Files
planet/backend/app/services/earth_tiles.py
T

996 lines
34 KiB
Python

"""Managed Web-Mercator tile pyramid proxy, warmup collection, LRU cache, and basemap settings."""
from __future__ import annotations
import asyncio
import hashlib
import io
import math
import os
import time
import weakref
from datetime import UTC, datetime
from pathlib import Path
from typing import Any
from uuid import uuid4
import cv2
import httpx
import numpy as np
from PIL import Image
from pydantic import BaseModel, Field, field_validator
from sqlalchemy import select
from sqlalchemy.dialects.postgresql import insert as pg_insert
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.data_sources import get_data_sources_config
from app.core.datasource_defaults import DEFAULT_DATASOURCES
from app.core.logging import get_logger
from app.core.request_context import get_request_id
from app.models.datasource import DataSource
from app.models.datasource_config import DataSourceConfig
from app.models.system_log import AuditLog
from app.models.system_setting import SystemSetting
from app.models.user import User
from app.services.earth_clouds import (
EUMETVIEW_WMS_URL,
decode_eumetview_ir_to_temp_and_valid,
decode_gibs_band13_to_temp_and_valid,
temperature_to_density,
)
ORIGIN_SHIFT_3857 = 20037508.342789244
logger = get_logger(__name__, service="earth_tiles")
REPO_ROOT = Path(__file__).resolve().parents[3]
TILES_DATA_DIR = REPO_ROOT / "data" / "earth-tiles"
BASEMAP_CONFIG_CATEGORY = "earth_basemap"
CLOUD_HD_TILE_TTL_SECONDS = 1800
TILE_SOURCES: tuple[str, ...] = (
"cloud_hd_tiles",
"earth_imagery_sentinel2",
"earth_imagery_viirs_daily",
)
BASEMAP_TILE_SOURCES: tuple[str, ...] = (
"earth_imagery_sentinel2",
"earth_imagery_viirs_daily",
)
# A contended semaphore holds its event loop, so the cache also keeps values weakly.
_TILE_ENCODE_SEMAPHORES: weakref.WeakKeyDictionary[
asyncio.AbstractEventLoop, weakref.ReferenceType[asyncio.Semaphore]
] = weakref.WeakKeyDictionary()
_INFLIGHT_TILE_FETCHES: weakref.WeakKeyDictionary[
asyncio.AbstractEventLoop, dict[tuple[str, int, int, int], asyncio.Task[bytes | None]]
] = weakref.WeakKeyDictionary()
def _tile_encode_concurrency() -> int:
raw = str(os.environ.get("PLANET_TILE_ENCODE_CONCURRENCY") or "2").strip()
try:
return max(1, min(8, int(raw)))
except ValueError:
return 2
def _get_tile_encode_semaphore() -> asyncio.Semaphore:
loop = asyncio.get_running_loop()
semaphore_ref = _TILE_ENCODE_SEMAPHORES.get(loop)
semaphore = semaphore_ref() if semaphore_ref is not None else None
if semaphore is None:
semaphore = asyncio.Semaphore(_tile_encode_concurrency())
_TILE_ENCODE_SEMAPHORES[loop] = weakref.ref(semaphore)
return semaphore
def _get_inflight_tile_fetches() -> dict[tuple[str, int, int, int], asyncio.Task[bytes | None]]:
loop = asyncio.get_running_loop()
inflight = _INFLIGHT_TILE_FETCHES.get(loop)
if inflight is None:
inflight = {}
_INFLIGHT_TILE_FETCHES[loop] = inflight
return inflight
DEFAULT_TILE_TEMPLATES: dict[str, str] = {
"cloud_hd_tiles": (
"https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/"
"GOES-East_ABI_GeoColor/default/default/"
"GoogleMapsCompatible_Level7/{z}/{y}/{x}.png"
),
"earth_imagery_sentinel2": (
"https://tiles.maps.eox.at/wmts/1.0.0/s2cloudless-2024_3857/default/"
"GoogleMapsCompatible/{z}/{y}/{x}.jpg"
),
"earth_imagery_viirs_daily": (
"https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/"
"VIIRS_SNPP_CorrectedReflectance_TrueColor/default/default/"
"GoogleMapsCompatible_Level9/{z}/{y}/{x}.jpg"
),
}
class BasemapRevisionConflictError(RuntimeError):
"""Raised when saving basemap configuration with a stale revision."""
class BasemapConfig(BaseModel):
active_source: str = Field(default="earth_imagery_sentinel2")
hd_tiles_enabled: bool = True
cloud_hd_tiles_enabled: bool = False
lod_switch_altitude: float = Field(default=1.85, ge=1.2, le=5.0)
max_zoom: int = Field(default=7, ge=2, le=10)
warmup_max_zoom: int = Field(default=3, ge=1, le=4)
max_cache_mb: int = Field(default=1024, ge=128, le=8192)
request_timeout_seconds: int = Field(default=15, ge=5, le=45)
@field_validator("active_source")
@classmethod
def validate_active_source(cls, value: str) -> str:
normalized = str(value or "earth_imagery_sentinel2").strip()
if normalized not in {"static", *BASEMAP_TILE_SOURCES}:
raise ValueError(
"active_source must be 'static', 'earth_imagery_sentinel2', or 'earth_imagery_viirs_daily'"
)
return normalized
DEFAULT_BASEMAP_CONFIG = BasemapConfig()
DEFAULT_BASEMAP_REVISION = hashlib.sha256(
DEFAULT_BASEMAP_CONFIG.model_dump_json().encode("utf-8")
).hexdigest()[:16]
def _default_basemap_envelope() -> dict[str, Any]:
return {
"config": DEFAULT_BASEMAP_CONFIG.model_dump(mode="json"),
"revision": DEFAULT_BASEMAP_REVISION,
"is_default": True,
}
def _tiles_root() -> Path:
return TILES_DATA_DIR
def _source_dir(source_key: str) -> Path:
if source_key not in TILE_SOURCES:
raise ValueError(f"Unsupported tile source: {source_key}")
return _tiles_root() / source_key
def _tile_path(source_key: str, z: int, x: int, y: int) -> Path:
return _source_dir(source_key) / str(int(z)) / str(int(x)) / f"{int(y)}.webp"
def _atomic_write_bytes(path: Path, content: bytes) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
tmp_path = path.with_name(f".{path.name}.{uuid4().hex[:8]}.tmp")
try:
tmp_path.write_bytes(content)
os.replace(tmp_path, path)
finally:
if tmp_path.exists():
try:
tmp_path.unlink()
except OSError:
pass
def validate_tile_coords(source_key: str, z: int, x: int, y: int, max_zoom: int = 10) -> None:
if source_key not in TILE_SOURCES:
raise ValueError("Unsupported tile source")
if z < 0 or z > max_zoom:
raise ValueError("Zoom level out of range")
limit = 1 << z
if x < 0 or x >= limit or y < 0 or y >= limit:
raise ValueError("Tile coordinates out of range")
def _tile_center_lon(z: int, x: int) -> float:
n = float(1 << max(0, z))
return ((float(x) + 0.5) / n) * 360.0 - 180.0
def _tile_center_lat(z: int, y: int) -> float:
n = float(1 << max(0, z))
merc_y = math.pi * (1.0 - 2.0 * ((float(y) + 0.5) / n))
return math.degrees(math.atan(math.sinh(merc_y)))
def _tile_solar_cosine(z: int, x: int, y: int, now_utc: datetime | None = None) -> float:
utc = now_utc or datetime.now(UTC)
utc = utc.astimezone(UTC) if utc.tzinfo else utc.replace(tzinfo=UTC)
doy = utc.timetuple().tm_yday
decl = math.radians(-23.44 * math.cos(2.0 * math.pi * (doy + 10) / 365.0))
utc_hour = utc.hour + utc.minute / 60.0 + utc.second / 3600.0
subsolar_lon = (12.0 - utc_hour) * 15.0
lat_rad = math.radians(_tile_center_lat(z, y))
ha_rad = math.radians(_tile_center_lon(z, x) - subsolar_lon)
return (
math.sin(lat_rad) * math.sin(decl)
+ math.cos(lat_rad) * math.cos(decl) * math.cos(ha_rad)
)
def _tile_to_3857_bbox(z: int, x: int, y: int) -> str:
n = 1 << max(0, int(z))
tile_span = (2.0 * ORIGIN_SHIFT_3857) / float(n)
minx = -ORIGIN_SHIFT_3857 + float(x) * tile_span
maxx = minx + tile_span
maxy = ORIGIN_SHIFT_3857 - float(y) * tile_span
miny = maxy - tile_span
return f"{minx:.3f},{miny:.3f},{maxx:.3f},{maxy:.3f}"
def _resolve_cloud_hd_ir_fallback(
z: int,
x: int,
y: int,
) -> tuple[str, dict[str, str] | None, str, int]:
"""Return `(url, query_params, provider, src_zoom)` for 5-satellite Band13/IR10.8 cloud tiles."""
lon = _tile_center_lon(z, x)
if 23.0 <= lon < 93.0 or -37.5 <= lon < 23.0:
wms_layer = "msg_fes:ir108" if lon < 23.0 else "msg_iodc:ir108"
params = {
"SERVICE": "WMS",
"REQUEST": "GetMap",
"VERSION": "1.1.1",
"LAYERS": wms_layer,
"STYLES": "",
"FORMAT": "image/png",
"TRANSPARENT": "true",
"SRS": "EPSG:3857",
"BBOX": _tile_to_3857_bbox(z, x, y),
"WIDTH": "256",
"HEIGHT": "256",
}
return EUMETVIEW_WMS_URL, params, "eumetview", int(z)
if lon < -106.0:
layer = "GOES-West_ABI_Band13_Clean_Infrared"
elif lon < -37.5:
layer = "GOES-East_ABI_Band13_Clean_Infrared"
else:
layer = "Himawari_AHI_Band13_Clean_Infrared"
ir_z = min(int(z), 6)
shift = max(0, int(z) - ir_z)
ir_x = int(x) >> shift
ir_y = int(y) >> shift
wmts_url = (
f"https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/"
f"{layer}/default/default/GoogleMapsCompatible_Level6/{ir_z}/{ir_y}/{ir_x}.png"
)
return wmts_url, None, "gibs", ir_z
def _resolve_cloud_hd_request(
default_template: str,
z: int,
x: int,
y: int,
*,
now_utc: datetime | None = None,
daytime: bool | None = None,
) -> tuple[str, dict[str, str] | None, str]:
"""Route HD cloud tiles across 5 geostationary satellites using daytime 1km/2km visible or nighttime IR."""
if "GOES-East_ABI_GeoColor" not in default_template and "GOES-East_ABI_Band13" not in default_template:
url = (
default_template.replace("{z}", str(int(z)))
.replace("{y}", str(int(y)))
.replace("{x}", str(int(x)))
)
return url, None, "gibs"
is_daytime = (
daytime
if daytime is not None
else (_tile_solar_cosine(z, x, y, now_utc) > 0.14)
)
if not is_daytime:
ir_url, ir_params, ir_provider, _ = _resolve_cloud_hd_ir_fallback(z, x, y)
return ir_url, ir_params, ir_provider
lon = _tile_center_lon(z, x)
if lon < -106.0:
layer = "GOES-West_ABI_GeoColor"
provider = "gibs_geocolor"
elif lon < -37.5:
layer = "GOES-East_ABI_GeoColor"
provider = "gibs_geocolor"
elif lon < 93.0:
wms_layer = "msg_fes:rgb_naturalenhncd" if lon < 23.0 else "msg_iodc:rgb_naturalenhncd"
params = {
"SERVICE": "WMS",
"REQUEST": "GetMap",
"VERSION": "1.1.1",
"LAYERS": wms_layer,
"STYLES": "",
"FORMAT": "image/png",
"TRANSPARENT": "true",
"SRS": "EPSG:3857",
"BBOX": _tile_to_3857_bbox(z, x, y),
"WIDTH": "256",
"HEIGHT": "256",
}
return EUMETVIEW_WMS_URL, params, "eumetview_visible"
else:
layer = "Himawari_AHI_Band3_Red_Visible_1km"
provider = "gibs_visible"
wmts_z = min(int(z), 7)
shift = max(0, int(z) - wmts_z)
wmts_x = int(x) >> shift
wmts_y = int(y) >> shift
wmts_url = (
f"https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/"
f"{layer}/default/default/GoogleMapsCompatible_Level7/{wmts_z}/{wmts_y}/{wmts_x}.png"
)
return wmts_url, None, provider
def _crop_subtile_rgba(
raw_bytes: bytes,
z_target: int,
x_target: int,
y_target: int,
z_src: int,
) -> np.ndarray:
with Image.open(io.BytesIO(raw_bytes)) as img:
rgba = np.asarray(img.convert("RGBA"), dtype=np.uint8)
shift = int(z_target) - int(z_src)
if shift <= 0 or rgba.shape[0] < (1 << shift) or rgba.shape[1] < (1 << shift):
if rgba.shape[:2] != (256, 256):
return cv2.resize(rgba, (256, 256), interpolation=cv2.INTER_LINEAR)
return rgba
mask = (1 << shift) - 1
sub_x = int(x_target) & mask
sub_y = int(y_target) & mask
cell_h = max(1, rgba.shape[0] >> shift)
cell_w = max(1, rgba.shape[1] >> shift)
crop = rgba[sub_y * cell_h:(sub_y + 1) * cell_h, sub_x * cell_w:(sub_x + 1) * cell_w]
return cv2.resize(crop, (256, 256), interpolation=cv2.INTER_LINEAR)
def _decode_ir_density_and_temp(
ir_rgba: np.ndarray,
ir_provider: str,
) -> tuple[np.ndarray, np.ndarray]:
if ir_provider == "eumetview":
temp, valid = decode_eumetview_ir_to_temp_and_valid(ir_rgba)
else:
temp, valid = decode_gibs_band13_to_temp_and_valid(ir_rgba)
density = temperature_to_density(temp, ir_threshold=22, contrast_gamma=0.88)
density_u8 = np.where(valid, density, 0).astype(np.uint8)
return density_u8, temp
def _encode_tile_webp(
source_key: str,
raw_bytes: bytes,
*,
provider: str = "gibs",
ir_bytes: bytes | None = None,
ir_provider: str = "gibs",
cos_sza: float = 1.0,
z: int = 0,
x: int = 0,
y: int = 0,
ir_z_src: int | None = None,
) -> bytes:
if source_key == "cloud_hd_tiles":
src_z = min(int(z), 6) if provider == "gibs" else int(z)
rgba = _crop_subtile_rgba(raw_bytes, z, x, y, src_z)
if provider in ("gibs_geocolor", "gibs_visible", "eumetview_visible"):
rgb = rgba[:, :, :3].astype(np.float32)
alpha = rgba[:, :, 3].astype(np.float32)
luma = 0.299 * rgb[:, :, 0] + 0.587 * rgb[:, :, 1] + 0.114 * rgb[:, :, 2]
ir_density = np.zeros(rgba.shape[:2], dtype=np.uint8)
safe_temp = np.full(rgba.shape[:2], 15.0, dtype=np.float32)
cool_gate = np.ones(rgba.shape[:2], dtype=np.float32)
if ir_bytes:
try:
ir_rgba = _crop_subtile_rgba(
ir_bytes, z, x, y, ir_z_src if ir_z_src is not None else min(int(z), 6)
)
ir_density, temp = _decode_ir_density_and_temp(ir_rgba, ir_provider)
safe_temp = np.where(np.isfinite(temp), temp, 15.0).astype(np.float32)
# Band-pass warm low-cloud gate: peaks on -2C..+16C stratocumulus and suppresses freezing snow (<-8C) and hot deserts (>+24C).
cool_gate = (
np.clip((24.0 - safe_temp) / 12.0, 0.0, 1.0)
* np.clip((safe_temp + 8.0) / 10.0, 0.0, 1.0)
).astype(np.float32)
except Exception:
pass
not_clipped = ~(
(rgb[:, :, 0] >= 254.0)
& (rgb[:, :, 1] >= 254.0)
& (rgb[:, :, 2] >= 254.0)
& (safe_temp > -10.0)
)
valid = (alpha > 12.0) & (luma > 8.0) & not_clipped
cos_safe = max(0.30, float(cos_sza))
if provider == "gibs_visible":
albedo = luma / cos_safe
vis = np.clip((albedo - 88.0) / 132.0, 0.0, 1.0) * cool_gate
else:
chroma = (np.max(rgb, axis=2) - np.min(rgb, axis=2)) / 255.0
whiteness = np.clip(1.0 - chroma / 0.36, 0.0, 1.0)
min_rgb = np.min(rgb, axis=2)
albedo = min_rgb / cos_safe
vis = np.clip((albedo - 85.0) / 135.0, 0.0, 1.0) * whiteness * cool_gate
vis_u8 = np.where(valid, np.clip(np.round(vis * 255.0), 0, 255), 0).astype(np.uint8)
density = np.maximum(ir_density, vis_u8)
else:
density, _ = _decode_ir_density_and_temp(rgba, provider)
density = cv2.GaussianBlur(density, (3, 3), 0.5)
out = np.empty_like(rgba)
out[:, :, 0] = density
out[:, :, 1] = density
out[:, :, 2] = density
out[:, :, 3] = density
out_img = Image.fromarray(out, mode="RGBA")
else:
with Image.open(io.BytesIO(raw_bytes)) as img:
out_img = img.convert("RGB")
buf = io.BytesIO()
out_img.save(buf, format="WEBP", quality=84, method=1)
return buf.getvalue()
def summarize_tile_source_cache(source_key: str) -> dict[str, Any]:
root = _source_dir(source_key)
if not root.exists():
return {"tile_count": 0, "total_bytes": 0, "total_mb": 0.0, "zoom_levels": []}
tile_count = 0
total_bytes = 0
zooms: set[int] = set()
for path in root.rglob("*.webp"):
if path.name.startswith(".") or not path.is_file():
continue
tile_count += 1
try:
total_bytes += path.stat().st_size
zoom_dir = path.relative_to(root).parts[0]
if zoom_dir.isdigit():
zooms.add(int(zoom_dir))
except (OSError, IndexError, ValueError):
pass
return {
"tile_count": tile_count,
"total_bytes": total_bytes,
"total_mb": round(total_bytes / (1024 * 1024), 2),
"zoom_levels": sorted(zooms),
}
def prune_tile_source_cache(source_key: str, max_cache_mb: int) -> int:
root = _source_dir(source_key)
if not root.exists():
return 0
limit_bytes = max(16, int(max_cache_mb)) * 1024 * 1024
files: list[tuple[float, int, Path]] = []
total_bytes = 0
for path in root.rglob("*.webp"):
if path.name.startswith(".") or not path.is_file():
continue
try:
st = path.stat()
except OSError:
continue
total_bytes += st.st_size
files.append((st.st_mtime, st.st_size, path))
if total_bytes <= limit_bytes:
return 0
files.sort(key=lambda item: item[0])
removed = 0
for _mtime, size, path in files:
if total_bytes <= limit_bytes:
break
try:
path.unlink()
total_bytes -= size
removed += 1
except OSError:
pass
return removed
def clear_tile_source_cache(source_key: str) -> int:
root = _source_dir(source_key)
if not root.exists():
return 0
removed = 0
for path in root.rglob("*"):
if path.is_file():
try:
path.unlink()
removed += 1
except OSError:
pass
for directory in sorted((p for p in root.rglob("*") if p.is_dir()), reverse=True):
try:
directory.rmdir()
except OSError:
pass
return removed
async def _get_source_runtime_settings(
db: AsyncSession | None,
source_key: str,
) -> tuple[bool, str, dict[str, Any]]:
default_template = DEFAULT_TILE_TEMPLATES[source_key]
ds_active = True
endpoint = default_template
cfg: dict[str, Any] = {
"warmup_max_zoom": 2 if source_key == "cloud_hd_tiles" else 3,
"max_zoom": 7 if source_key == "cloud_hd_tiles" else (10 if source_key == "earth_imagery_sentinel2" else 9),
"max_cache_mb": 512 if source_key == "cloud_hd_tiles" else 1024,
"request_timeout_seconds": 15,
}
if db is None or not hasattr(db, "execute"):
return ds_active, endpoint, cfg
try:
ds_row = (
await db.execute(select(DataSource).where(DataSource.source == source_key))
).scalar_one_or_none()
if ds_row is not None:
ds_active = bool(ds_row.is_active)
except Exception:
pass
try:
cfg_row = (
await db.execute(select(DataSourceConfig).where(DataSourceConfig.name == source_key))
).scalar_one_or_none()
if cfg_row is not None:
if cfg_row.endpoint:
endpoint = str(cfg_row.endpoint).strip()
if isinstance(cfg_row.config, dict):
for key, val in cfg_row.config.items():
if val is not None:
cfg[key] = val
except Exception:
pass
try:
yaml_url = await get_data_sources_config().get_url(source_key, db)
if yaml_url:
endpoint = yaml_url
except Exception:
pass
return ds_active, endpoint, cfg
def _is_cloud_tile_fresh(target: Path) -> bool:
try:
return (time.time() - target.stat().st_mtime) < CLOUD_HD_TILE_TTL_SECONDS
except OSError:
return False
def _is_valid_image_response(resp: Any) -> bool:
if not isinstance(resp, httpx.Response) or resp.status_code != 200:
return False
ctype = str(resp.headers.get("content-type") or "").lower()
return ctype.startswith("image/")
async def _safe_get(
client: httpx.AsyncClient,
url: str,
params: dict[str, str] | None = None,
) -> httpx.Response | Exception:
try:
return await client.get(url, params=params)
except Exception as exc:
return exc
async def _fetch_and_encode_tile(
client: httpx.AsyncClient,
source_key: str,
template: str,
z: int,
x: int,
y: int,
*,
raise_on_error: bool = True,
) -> bytes | None:
if source_key == "cloud_hd_tiles":
cos_sza = _tile_solar_cosine(z, x, y)
is_daytime = cos_sza > 0.14
url, query_params, provider = _resolve_cloud_hd_request(
template, z, x, y, daytime=is_daytime
)
if provider in ("gibs_geocolor", "gibs_visible", "eumetview_visible"):
ir_url, ir_params, ir_provider, ir_z_src = _resolve_cloud_hd_ir_fallback(z, x, y)
primary_res, ir_res = await asyncio.gather(
_safe_get(client, url, query_params),
_safe_get(client, ir_url, ir_params),
)
ir_bytes = ir_res.content if _is_valid_image_response(ir_res) else None
if _is_valid_image_response(primary_res):
async with _get_tile_encode_semaphore():
return await asyncio.to_thread(
_encode_tile_webp,
source_key,
primary_res.content,
provider=provider,
ir_bytes=ir_bytes,
ir_provider=ir_provider,
cos_sza=cos_sza,
z=z,
x=x,
y=y,
ir_z_src=ir_z_src,
)
if ir_bytes is not None:
async with _get_tile_encode_semaphore():
return await asyncio.to_thread(
_encode_tile_webp,
source_key,
ir_bytes,
provider=ir_provider,
z=z,
x=x,
y=y,
)
if isinstance(primary_res, Exception) and raise_on_error:
raise primary_res
if isinstance(primary_res, httpx.Response) and primary_res.status_code not in (200, 404) and raise_on_error:
primary_res.raise_for_status()
return None
else:
url = (
template.replace("{z}", str(int(z)))
.replace("{y}", str(int(y)))
.replace("{x}", str(int(x)))
)
query_params = None
provider = "gibs"
response = await client.get(url, params=query_params)
if response.status_code == 404:
return None
response.raise_for_status()
if not _is_valid_image_response(response):
return None
async with _get_tile_encode_semaphore():
return await asyncio.to_thread(
_encode_tile_webp,
source_key,
response.content,
provider=provider,
z=z,
x=x,
y=y,
)
async def get_or_fetch_tile(
source_key: str,
z: int,
x: int,
y: int,
*,
db: AsyncSession | None = None,
) -> tuple[bytes | None, bool]:
"""Return `(webp_bytes, is_allowed)` enforcing `DataSource.is_active` and caching as WebP."""
ds_active, template, cfg = await _get_source_runtime_settings(db, source_key)
max_zoom = int(cfg.get("max_zoom") or 8)
validate_tile_coords(source_key, z, x, y, max_zoom=max_zoom)
if not ds_active:
return None, False
target = _tile_path(source_key, z, x, y)
if target.exists() and (source_key != "cloud_hd_tiles" or _is_cloud_tile_fresh(target)):
try:
os.utime(target, None)
except OSError:
pass
return target.read_bytes(), True
tile_key = (source_key, int(z), int(x), int(y))
inflight = _get_inflight_tile_fetches()
existing_task = inflight.get(tile_key)
if existing_task is None or existing_task.done():
timeout = httpx.Timeout(float(cfg.get("request_timeout_seconds") or 15))
headers = {"User-Agent": "Planet-Intelligence-System/1.0 (EarthTileProxy)"}
async def _load_and_persist() -> bytes | None:
async with httpx.AsyncClient(
timeout=timeout,
follow_redirects=True,
headers=headers,
) as client:
loaded = await _fetch_and_encode_tile(
client, source_key, template, z, x, y
)
if loaded is not None:
await asyncio.to_thread(_atomic_write_bytes, target, loaded)
return loaded
existing_task = asyncio.create_task(_load_and_persist())
inflight[tile_key] = existing_task
existing_task.add_done_callback(
lambda done_task: (
inflight.pop(tile_key, None)
if inflight.get(tile_key) is done_task
else None
)
)
webp_bytes = await asyncio.shield(existing_task)
if webp_bytes is None:
return None, True
return webp_bytes, True
async def warmup_tile_source(
source_key: str,
*,
db: AsyncSession | None = None,
max_zoom_override: int | None = None,
) -> dict[str, Any]:
"""Pre-warm z=0..warmup_max_zoom tile pyramid into managed local WebP storage."""
if source_key not in TILE_SOURCES:
raise ValueError(f"Unsupported tile source: {source_key}")
_ds_active, template, cfg = await _get_source_runtime_settings(db, source_key)
warmup_max = int(
max_zoom_override
if max_zoom_override is not None
else cfg.get("warmup_max_zoom") or (2 if source_key == "cloud_hd_tiles" else 3)
)
warmup_max = max(0, min(4, warmup_max))
max_cache_mb = int(cfg.get("max_cache_mb") or 1024)
timeout = httpx.Timeout(float(cfg.get("request_timeout_seconds") or 15))
headers = {"User-Agent": "Planet-Intelligence-System/1.0 (EarthTileWarmup)"}
coords: list[tuple[int, int, int]] = []
for z in range(0, warmup_max + 1):
dim = 1 << z
for x in range(dim):
for y in range(dim):
coords.append((z, x, y))
fetched = 0
cached_hits = 0
failed = 0
total_bytes = 0
semaphore = asyncio.Semaphore(8)
async with httpx.AsyncClient(timeout=timeout, follow_redirects=True, headers=headers) as client:
async def _worker(z: int, x: int, y: int) -> None:
nonlocal fetched, cached_hits, failed, total_bytes
target = _tile_path(source_key, z, x, y)
if target.exists() and (source_key != "cloud_hd_tiles" or _is_cloud_tile_fresh(target)):
cached_hits += 1
try:
total_bytes += target.stat().st_size
except OSError:
pass
return
async with semaphore:
try:
webp_bytes = await _fetch_and_encode_tile(
client, source_key, template, z, x, y, raise_on_error=True
)
if webp_bytes is None:
failed += 1
return
await asyncio.to_thread(_atomic_write_bytes, target, webp_bytes)
fetched += 1
total_bytes += len(webp_bytes)
except Exception as exc:
failed += 1
logger.warning_event(
"Tile warmup request failed",
event="earth.tiles.warmup_failed",
context={"source": source_key, "z": z, "x": x, "y": y, "error": str(exc)},
)
await asyncio.gather(*(_worker(z, x, y) for z, x, y in coords))
pruned = await asyncio.to_thread(prune_tile_source_cache, source_key, max_cache_mb)
cache_stats = await asyncio.to_thread(summarize_tile_source_cache, source_key)
return {
"source": source_key,
"warmup_max_zoom": warmup_max,
"total_targets": len(coords),
"fetched": fetched,
"cached_hits": cached_hits,
"failed": failed,
"pruned": pruned,
"written_bytes": total_bytes,
"cache_stats": cache_stats,
}
async def prune_all_tile_caches(db: AsyncSession | None = None) -> int:
removed = 0
for source_key in TILE_SOURCES:
_, _, cfg = await _get_source_runtime_settings(db, source_key)
max_mb = int(cfg.get("max_cache_mb") or 1024)
removed += await asyncio.to_thread(prune_tile_source_cache, source_key, max_mb)
return removed
async def read_basemap_configuration(db: AsyncSession | None) -> dict[str, Any]:
if db is None or not callable(getattr(db, "execute", None)):
return _default_basemap_envelope()
result = await db.execute(
select(SystemSetting).where(SystemSetting.category == BASEMAP_CONFIG_CATEGORY)
)
record = result.scalar_one_or_none()
if not record or not isinstance(record.payload, dict):
return _default_basemap_envelope()
payload = dict(record.payload)
try:
validated = BasemapConfig.model_validate(payload.get("config") or {})
except Exception:
validated = DEFAULT_BASEMAP_CONFIG
return {
"config": validated.model_dump(mode="json"),
"revision": str(payload.get("revision") or DEFAULT_BASEMAP_REVISION),
"is_default": bool(payload.get("is_default", False)),
}
async def save_basemap_configuration(
db: AsyncSession,
*,
revision: str,
config: BasemapConfig,
actor: User,
reset: bool = False,
) -> dict[str, Any]:
dialect_name = ""
try:
bind = db.get_bind()
dialect_name = str(getattr(getattr(bind, "dialect", None), "name", "") or "").lower()
except Exception:
dialect_name = ""
if dialect_name == "postgresql":
await db.execute(
pg_insert(SystemSetting)
.values(category=BASEMAP_CONFIG_CATEGORY, payload=_default_basemap_envelope())
.on_conflict_do_nothing(index_elements=[SystemSetting.category])
)
record = (
await db.execute(
select(SystemSetting)
.where(SystemSetting.category == BASEMAP_CONFIG_CATEGORY)
.with_for_update()
)
).scalar_one()
else:
record = (
await db.execute(
select(SystemSetting).where(SystemSetting.category == BASEMAP_CONFIG_CATEGORY)
)
).scalar_one_or_none()
if record is None:
record = SystemSetting(
category=BASEMAP_CONFIG_CATEGORY,
payload=_default_basemap_envelope(),
)
db.add(record)
current_revision = str((record.payload or {}).get("revision") or DEFAULT_BASEMAP_REVISION)
if current_revision != revision:
await db.rollback()
raise BasemapRevisionConflictError(
"Configuration changed by another editor. Reload and retry."
)
envelope = (
_default_basemap_envelope()
if reset
else {
"config": config.model_dump(mode="json"),
"revision": uuid4().hex[:16],
"is_default": False,
}
)
before = dict(record.payload or {})
if reset:
if getattr(record, "id", None) is not None:
await db.delete(record)
else:
record.payload = envelope
db.add(
AuditLog(
actor_id=actor.id,
actor_name=actor.username,
action="earth_basemap.reset" if reset else "earth_basemap.update",
target_type="system_setting",
target_id=BASEMAP_CONFIG_CATEGORY,
result="success",
request_id=get_request_id(),
details={"before": before, "after": envelope},
)
)
await db.commit()
return envelope
async def get_basemap_runtime_meta(db: AsyncSession | None = None) -> dict[str, Any]:
envelope = await read_basemap_configuration(db)
config = BasemapConfig.model_validate(envelope["config"])
source_items: list[dict[str, Any]] = []
active_map: dict[str, bool] = {}
for source_key in TILE_SOURCES:
is_active, template, cfg = await _get_source_runtime_settings(db, source_key)
cache_stats = await asyncio.to_thread(summarize_tile_source_cache, source_key)
meta_defaults = DEFAULT_DATASOURCES.get(source_key, {})
active_map[source_key] = is_active
source_items.append(
{
"source": source_key,
"display_name": meta_defaults.get("display_name") or source_key,
"is_active": is_active,
"has_data": cache_stats["tile_count"] > 0,
"cached_tiles": cache_stats["tile_count"],
"cache_mb": cache_stats["total_mb"],
"zoom_levels": cache_stats["zoom_levels"],
"max_zoom": int(cfg.get("max_zoom") or config.max_zoom),
"warmup_max_zoom": int(cfg.get("warmup_max_zoom") or config.warmup_max_zoom),
"max_cache_mb": int(cfg.get("max_cache_mb") or config.max_cache_mb),
"tile_url_template": f"/api/v1/earth/tiles/{source_key}/{{z}}/{{x}}/{{y}}.webp",
"upstream_template": template,
}
)
active_source = config.active_source
hd_ready = bool(
config.hd_tiles_enabled
and active_source in BASEMAP_TILE_SOURCES
and active_map.get(active_source, False)
)
cloud_hd_ready = bool(
config.cloud_hd_tiles_enabled and active_map.get("cloud_hd_tiles", False)
)
return {
"active_source": active_source,
"hd_tiles_enabled": config.hd_tiles_enabled,
"cloud_hd_tiles_enabled": config.cloud_hd_tiles_enabled,
"hd_tiles_ready": hd_ready,
"cloud_hd_tiles_ready": cloud_hd_ready,
"lod_switch_altitude": config.lod_switch_altitude,
"max_zoom": config.max_zoom,
"warmup_max_zoom": config.warmup_max_zoom,
"max_cache_mb": config.max_cache_mb,
"tile_url_template": (
f"/api/v1/earth/tiles/{active_source}/{{z}}/{{x}}/{{y}}.webp"
if hd_ready
else None
),
"cloud_tile_url_template": (
"/api/v1/earth/tiles/cloud_hd_tiles/{z}/{x}/{y}.webp"
if cloud_hd_ready
else None
),
"sources": source_items,
}