forked from linkong/planet
862 lines
32 KiB
Python
862 lines
32 KiB
Python
"""Earth boundary PMTiles artifact service.
|
||
|
||
Sources are downloaded once per build into the persistent boundary data
|
||
directory, the China POV builder (``scripts/build_earth_boundary_pmtiles.py``)
|
||
produces a versioned PMTiles archive plus small hover assets, and the API
|
||
serves them with HTTP Range support. Web and desktop clients share the same
|
||
``/api/v1/earth/boundaries/...`` URLs.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import asyncio
|
||
import hashlib
|
||
import json
|
||
import os
|
||
import shutil
|
||
import sys
|
||
import tempfile
|
||
import zipfile
|
||
from datetime import UTC, datetime
|
||
from functools import lru_cache
|
||
from pathlib import Path
|
||
from typing import Any
|
||
from uuid import uuid4
|
||
|
||
import httpx
|
||
|
||
from app.core.logging import get_logger
|
||
|
||
|
||
logger = get_logger(__name__)
|
||
|
||
REPO_ROOT = Path(__file__).resolve().parents[3]
|
||
BOUNDARY_DATA_DIR = Path(
|
||
os.environ.get("PLANET_EARTH_BOUNDARY_DIR") or REPO_ROOT / "backend/data/earth-boundaries"
|
||
)
|
||
SOURCE_OUTPUT_DIR = BOUNDARY_DATA_DIR / "sources"
|
||
SOURCE_MANIFEST_PATH = SOURCE_OUTPUT_DIR / "manifest.json"
|
||
BUILD_RESULT_PATH = BOUNDARY_DATA_DIR / "build-result.json"
|
||
BUILD_JOB_PATH = BOUNDARY_DATA_DIR / "build-job.json"
|
||
BOUNDARY_OUTPUT_DIR = BOUNDARY_DATA_DIR / "artifacts"
|
||
BOUNDARY_MANIFEST_PATH = BOUNDARY_OUTPUT_DIR / "manifest.json"
|
||
POLICY_FALLBACK_PATH = (
|
||
REPO_ROOT / "frontend/public/earth/data/countries-admin0.china-pov-v1.geojson"
|
||
)
|
||
POV_POLICY_PATH = REPO_ROOT / "config/earth-boundary-pov-policy.china-v1.json"
|
||
POV_GEOMETRY_PATH = REPO_ROOT / "resources/earth/boundary-pov-geometry.china-v1.json"
|
||
LOCAL_CONFIG_PATH = REPO_ROOT / "config/earth-boundary-sources.local.json"
|
||
EXAMPLE_CONFIG_PATH = REPO_ROOT / "config/earth-boundary-sources.example.json"
|
||
BUILDER_PATH = REPO_ROOT / "scripts/build_earth_boundary_pmtiles.py"
|
||
BUILDER_MODULE_PATHS = (
|
||
BUILDER_PATH,
|
||
REPO_ROOT / "scripts/earth_boundary_geometry.py",
|
||
REPO_ROOT / "scripts/earth_boundary_policy.py",
|
||
)
|
||
MANIFEST_SCHEMA = "planet-earth-boundaries/v2"
|
||
REQUIRED_TOOLS = ("tippecanoe",)
|
||
REQUIRED_POLICY_RULES = {"china-taiwan-penghu", "china-hong-kong", "china-macao", "kosovo"}
|
||
DOWNLOAD_CHUNK_BYTES = 1024 * 1024
|
||
|
||
BOUNDARY_SOURCE_KINDS = {
|
||
"earth_admin0_boundaries": "admin0-boundaries",
|
||
"earth_coastline": "coastline",
|
||
"earth_disputed_lines": "disputed-lines",
|
||
"earth_claim_lines": "claim-lines",
|
||
"earth_admin1_lines": "admin1-lines",
|
||
"earth_populated_places": "populated-places",
|
||
}
|
||
|
||
_NE_GEOJSON = "https://raw.githubusercontent.com/nvkelso/natural-earth-vector/master/geojson"
|
||
DEFAULT_PUBLIC_BOUNDARY_SOURCES = {
|
||
"earth_admin0_boundaries": {
|
||
"displayName": "Natural Earth Admin-0 Countries",
|
||
"sourceKind": "admin0-boundaries",
|
||
"endpoint": f"{_NE_GEOJSON}/ne_10m_admin_0_countries.geojson",
|
||
"method": "GET",
|
||
"headers": {},
|
||
"auth_type": "none",
|
||
"license": "Natural Earth public domain",
|
||
},
|
||
"earth_coastline": {
|
||
"displayName": "OpenStreetMap Coastlines (osmdata.openstreetmap.de)",
|
||
"sourceKind": "coastline",
|
||
"endpoint": "https://osmdata.openstreetmap.de/download/coastlines-split-4326.zip",
|
||
"method": "GET",
|
||
"headers": {},
|
||
"auth_type": "none",
|
||
"timeout": 1800,
|
||
"license": "ODbL 1.0 © OpenStreetMap contributors",
|
||
},
|
||
"earth_disputed_lines": {
|
||
"displayName": "Natural Earth Disputed Boundaries",
|
||
"sourceKind": "disputed-lines",
|
||
"endpoint": f"{_NE_GEOJSON}/ne_10m_admin_0_boundary_lines_disputed_areas.geojson",
|
||
"method": "GET",
|
||
"headers": {},
|
||
"auth_type": "none",
|
||
"license": "Natural Earth public domain",
|
||
},
|
||
"earth_claim_lines": {
|
||
"displayName": "Natural Earth China POV Maritime Indicator",
|
||
"sourceKind": "claim-lines",
|
||
"endpoint": f"{_NE_GEOJSON}/ne_10m_admin_0_boundary_lines_maritime_indicator_chn.geojson",
|
||
"method": "GET",
|
||
"headers": {},
|
||
"auth_type": "none",
|
||
"license": "Natural Earth public domain",
|
||
},
|
||
"earth_admin1_lines": {
|
||
"displayName": "Natural Earth Admin-1 Lines",
|
||
"sourceKind": "admin1-lines",
|
||
"endpoint": f"{_NE_GEOJSON}/ne_10m_admin_1_states_provinces_lines.geojson",
|
||
"method": "GET",
|
||
"headers": {},
|
||
"auth_type": "none",
|
||
"license": "Natural Earth public domain",
|
||
},
|
||
"earth_populated_places": {
|
||
"displayName": "Natural Earth Populated Places",
|
||
"sourceKind": "populated-places",
|
||
"endpoint": f"{_NE_GEOJSON}/ne_10m_populated_places.geojson",
|
||
"method": "GET",
|
||
"headers": {},
|
||
"auth_type": "none",
|
||
"license": "Natural Earth public domain",
|
||
},
|
||
}
|
||
|
||
BUILD_CONFIG = {
|
||
"builder": "scripts/build_earth_boundary_pmtiles.py",
|
||
"schema": MANIFEST_SCHEMA,
|
||
"format": "pmtiles+mvt",
|
||
"minZoom": 0,
|
||
"maxZoom": 10,
|
||
"coastlineMaxZoom": 10,
|
||
}
|
||
|
||
|
||
class _NotModified(Exception):
|
||
"""Upstream answered 304 for a conditional source download."""
|
||
|
||
|
||
class EarthBoundaryBuildError(RuntimeError):
|
||
def __init__(self, message: str, *, code: str = "build_failed", details: Any = None) -> None:
|
||
super().__init__(message)
|
||
self.code = code
|
||
self.details = details
|
||
|
||
|
||
_build_job_lock = asyncio.Lock()
|
||
_build_task: asyncio.Task | None = None
|
||
_build_job_state: dict[str, Any] = {}
|
||
|
||
|
||
def _utc_now_iso() -> str:
|
||
return datetime.now(UTC).isoformat()
|
||
|
||
|
||
def _public_job_state() -> dict[str, Any]:
|
||
if _build_job_state:
|
||
return dict(_build_job_state)
|
||
return _read_json(BUILD_JOB_PATH)
|
||
|
||
|
||
def get_boundary_build_status() -> dict[str, Any]:
|
||
return {"job": _public_job_state()}
|
||
|
||
|
||
def _set_job_state(**updates: Any) -> dict[str, Any]:
|
||
global _build_job_state
|
||
current = dict(_build_job_state)
|
||
current.update(updates)
|
||
current["updated_at"] = _utc_now_iso()
|
||
_build_job_state = current
|
||
_write_json(BUILD_JOB_PATH, current)
|
||
return current
|
||
|
||
|
||
def _append_job_log(message: str) -> None:
|
||
logs = list(_build_job_state.get("logs") or [])
|
||
logs.append({"time": _utc_now_iso(), "message": message})
|
||
_set_job_state(logs=logs[-40:])
|
||
|
||
|
||
def _update_job_progress(progress: float, phase: str, message: str, **extra: Any) -> None:
|
||
bounded_progress = max(0, min(100, int(round(progress))))
|
||
_set_job_state(
|
||
status="running",
|
||
progress=bounded_progress,
|
||
phase=phase,
|
||
message=message,
|
||
**extra,
|
||
)
|
||
|
||
|
||
def _read_json(path: Path) -> dict[str, Any]:
|
||
if not path.exists():
|
||
return {}
|
||
with path.open("r", encoding="utf-8") as f:
|
||
payload = json.load(f)
|
||
return payload if isinstance(payload, dict) else {}
|
||
|
||
|
||
def _write_json(path: Path, payload: dict[str, Any]) -> None:
|
||
path.parent.mkdir(parents=True, exist_ok=True)
|
||
tmp = path.with_suffix(path.suffix + ".tmp")
|
||
with tmp.open("w", encoding="utf-8") as f:
|
||
json.dump(payload, f, ensure_ascii=False, indent=2)
|
||
f.write("\n")
|
||
tmp.replace(path)
|
||
|
||
|
||
def _stable_json_hash(payload: Any) -> str:
|
||
encoded = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
|
||
return hashlib.sha256(encoded.encode("utf-8")).hexdigest()
|
||
|
||
|
||
@lru_cache(maxsize=16)
|
||
def _read_versioned_asset_cached(
|
||
path: Path, mtime_ns: int, size_bytes: int
|
||
) -> tuple[dict[str, Any], str]:
|
||
payload = _read_json(path)
|
||
return payload, _stable_json_hash(payload)
|
||
|
||
|
||
def _versioned_asset(path: Path) -> tuple[dict[str, Any], str]:
|
||
if not path.exists():
|
||
return {}, ""
|
||
stat = path.stat()
|
||
return _read_versioned_asset_cached(path, stat.st_mtime_ns, stat.st_size)
|
||
|
||
|
||
def _display_path(path: Path) -> str:
|
||
try:
|
||
return str(path.relative_to(REPO_ROOT))
|
||
except ValueError:
|
||
return str(path)
|
||
|
||
|
||
def missing_build_tools() -> list[str]:
|
||
return [tool for tool in REQUIRED_TOOLS if shutil.which(tool) is None]
|
||
|
||
|
||
def load_boundary_config() -> tuple[dict[str, Any], str]:
|
||
if LOCAL_CONFIG_PATH.exists():
|
||
return _read_json(LOCAL_CONFIG_PATH), "local"
|
||
return _read_json(EXAMPLE_CONFIG_PATH), "example"
|
||
|
||
|
||
def save_boundary_config(payload: dict[str, Any]) -> dict[str, Any]:
|
||
if not isinstance(payload, dict):
|
||
raise EarthBoundaryBuildError("Earth boundary config must be a JSON object", code="invalid_config")
|
||
_write_json(LOCAL_CONFIG_PATH, payload)
|
||
return get_boundary_status()
|
||
|
||
|
||
def _source_configs(payload: dict[str, Any]) -> dict[str, Any]:
|
||
raw_sources = payload.get("collectorConfigs") or payload.get("sources") or {}
|
||
return raw_sources if isinstance(raw_sources, dict) else {}
|
||
|
||
|
||
def _is_placeholder_endpoint(endpoint: Any) -> bool:
|
||
value = str(endpoint or "").strip()
|
||
return not value or "example.com" in value
|
||
|
||
|
||
def _source_configs_with_defaults(payload: dict[str, Any]) -> dict[str, Any]:
|
||
raw_sources = _source_configs(payload)
|
||
merged: dict[str, Any] = {}
|
||
for source_key, default_config in DEFAULT_PUBLIC_BOUNDARY_SOURCES.items():
|
||
configured = raw_sources.get(source_key)
|
||
if not isinstance(configured, dict) or _is_placeholder_endpoint(configured.get("endpoint")):
|
||
merged[source_key] = dict(default_config)
|
||
else:
|
||
merged[source_key] = {**default_config, **configured}
|
||
for source_key, source_config in raw_sources.items():
|
||
if source_key not in merged:
|
||
merged[source_key] = source_config
|
||
return merged
|
||
|
||
|
||
def _build_input_hash(source_manifest: dict[str, Any]) -> str:
|
||
return _stable_json_hash(
|
||
{
|
||
"source_manifest_schema": source_manifest.get("schema"),
|
||
"sources": [
|
||
{
|
||
"id": source.get("id"),
|
||
"sha256": source.get("sha256"),
|
||
"kind": source.get("kind"),
|
||
}
|
||
for source in source_manifest.get("sources", [])
|
||
],
|
||
"pov_policy": source_manifest.get("povPolicy"),
|
||
"pov_geometry_sha256": _versioned_asset(POV_GEOMETRY_PATH)[1],
|
||
"build_config": BUILD_CONFIG,
|
||
"builder_sha256": {
|
||
path.name: _file_sha256(path) for path in BUILDER_MODULE_PATHS if path.exists()
|
||
},
|
||
}
|
||
)
|
||
|
||
|
||
def _file_sha256(path: Path) -> str:
|
||
digest = hashlib.sha256()
|
||
with path.open("rb") as f:
|
||
for chunk in iter(lambda: f.read(DOWNLOAD_CHUNK_BYTES), b""):
|
||
digest.update(chunk)
|
||
return digest.hexdigest()
|
||
|
||
|
||
def _policy_verified(manifest: dict[str, Any]) -> bool:
|
||
policy, policy_hash = _versioned_asset(POV_POLICY_PATH)
|
||
geometry, geometry_hash = _versioned_asset(POV_GEOMETRY_PATH)
|
||
coverage = manifest.get("povPolicy") or {}
|
||
return (
|
||
policy.get("profile") == "china-pov-v1"
|
||
and coverage.get("profile") == policy["profile"]
|
||
and coverage.get("sha256") == policy_hash
|
||
and coverage.get("reviewedGeometrySourceCommit") == geometry.get("sourceCommit")
|
||
and coverage.get("geometrySha256") == geometry_hash
|
||
and coverage.get("applied") is True
|
||
and REQUIRED_POLICY_RULES <= set(coverage.get("appliedRuleIds") or [])
|
||
)
|
||
|
||
|
||
def _manifest_artifact_names(manifest: dict[str, Any]) -> list[str]:
|
||
names = [
|
||
(manifest.get("pmtiles") or {}).get("path"),
|
||
manifest.get("hoverIndex"),
|
||
manifest.get("hoverBorders"),
|
||
manifest.get("geoLabels"),
|
||
]
|
||
return [name for name in names if isinstance(name, str) and name]
|
||
|
||
|
||
def _artifacts_exist(manifest: dict[str, Any]) -> bool:
|
||
names = _manifest_artifact_names(manifest)
|
||
required = [
|
||
(manifest.get("pmtiles") or {}).get("path"),
|
||
manifest.get("hoverIndex"),
|
||
manifest.get("hoverBorders"),
|
||
]
|
||
if not all(isinstance(name, str) and name for name in required):
|
||
return False
|
||
return all(Path(name).name == name and (BOUNDARY_OUTPUT_DIR / name).is_file() for name in names)
|
||
|
||
|
||
def _high_precision_ready(manifest: dict[str, Any]) -> bool:
|
||
return (
|
||
manifest.get("schema") == MANIFEST_SCHEMA
|
||
and manifest.get("tileProvider") == "pmtiles-mvt"
|
||
and _policy_verified(manifest)
|
||
and _artifacts_exist(manifest)
|
||
)
|
||
|
||
|
||
def _has_current_artifacts(boundary_manifest: dict[str, Any], build_input_hash: str) -> bool:
|
||
return (
|
||
boundary_manifest.get("buildInputHash") == build_input_hash
|
||
and _high_precision_ready(boundary_manifest)
|
||
)
|
||
|
||
|
||
def get_public_boundary_manifest() -> dict[str, Any] | None:
|
||
"""Manifest for Earth clients, or ``None`` when no verified artifact exists."""
|
||
manifest = _read_json(BOUNDARY_MANIFEST_PATH)
|
||
if not _high_precision_ready(manifest):
|
||
return None
|
||
return manifest
|
||
|
||
|
||
def resolve_boundary_artifact(name: str) -> Path | None:
|
||
"""Only files listed by the current verified manifest are served."""
|
||
if not name or Path(name).name != name:
|
||
return None
|
||
manifest = get_public_boundary_manifest()
|
||
if manifest is None or name not in _manifest_artifact_names(manifest):
|
||
return None
|
||
path = BOUNDARY_OUTPUT_DIR / name
|
||
return path if path.is_file() else None
|
||
|
||
|
||
def get_boundary_status() -> dict[str, Any]:
|
||
config_payload, config_source = load_boundary_config()
|
||
effective_source_configs = _source_configs_with_defaults(config_payload)
|
||
boundary_manifest = _read_json(BOUNDARY_MANIFEST_PATH)
|
||
manifest_exists = BOUNDARY_MANIFEST_PATH.exists()
|
||
high_precision_ready = manifest_exists and _high_precision_ready(boundary_manifest)
|
||
legacy_exists = POLICY_FALLBACK_PATH.exists() and _policy_verified(
|
||
_versioned_asset(POLICY_FALLBACK_PATH)[0]
|
||
)
|
||
provider = (
|
||
"pmtiles-mvt"
|
||
if high_precision_ready
|
||
else "policy-geojson-fallback" if legacy_exists else "missing"
|
||
)
|
||
pmtiles_info = boundary_manifest.get("pmtiles") or {}
|
||
missing_tools = missing_build_tools()
|
||
return {
|
||
"provider": provider,
|
||
"high_precision_ready": high_precision_ready,
|
||
"fallback_available": legacy_exists,
|
||
"policy_publishable": bool(
|
||
high_precision_ready and boundary_manifest.get("povPolicy", {}).get("publicationReady")
|
||
),
|
||
"build_tools_ready": not missing_tools,
|
||
"missing_tools": missing_tools,
|
||
"config_source": config_source,
|
||
"config_path": _display_path(LOCAL_CONFIG_PATH),
|
||
"config_exists": LOCAL_CONFIG_PATH.exists(),
|
||
"config": config_payload,
|
||
"effective_default_sources": [
|
||
source_key
|
||
for source_key, source_config in effective_source_configs.items()
|
||
if source_key in DEFAULT_PUBLIC_BOUNDARY_SOURCES
|
||
and source_config.get("endpoint") == DEFAULT_PUBLIC_BOUNDARY_SOURCES[source_key]["endpoint"]
|
||
],
|
||
"manifest": {
|
||
"path": _display_path(BOUNDARY_MANIFEST_PATH),
|
||
"exists": manifest_exists,
|
||
"schema": boundary_manifest.get("schema"),
|
||
"tileProvider": boundary_manifest.get("tileProvider"),
|
||
"buildInputHash": boundary_manifest.get("buildInputHash"),
|
||
"builtAt": boundary_manifest.get("builtAt"),
|
||
"povPolicy": boundary_manifest.get("povPolicy"),
|
||
"publicationReady": boundary_manifest.get("povPolicy", {}).get("publicationReady", False),
|
||
},
|
||
"pmtiles": {
|
||
"path": pmtiles_info.get("path"),
|
||
"exists": high_precision_ready,
|
||
"size_bytes": pmtiles_info.get("sizeBytes", 0) if high_precision_ready else 0,
|
||
},
|
||
"legacy": {
|
||
"path": _display_path(POLICY_FALLBACK_PATH),
|
||
"exists": legacy_exists,
|
||
"size_bytes": POLICY_FALLBACK_PATH.stat().st_size if legacy_exists else 0,
|
||
},
|
||
"source_manifest": {
|
||
"path": _display_path(SOURCE_MANIFEST_PATH),
|
||
"exists": SOURCE_MANIFEST_PATH.exists(),
|
||
},
|
||
"last_build": _read_json(BUILD_RESULT_PATH),
|
||
"current_job": _public_job_state(),
|
||
}
|
||
|
||
|
||
def _artifact_extension(endpoint: str, content_type: str, head: bytes) -> str:
|
||
suffix = Path(endpoint.split("?", 1)[0]).suffix.lower()
|
||
if suffix in {".json", ".geojson", ".zip"}:
|
||
return suffix
|
||
if head.startswith(b"PK\x03\x04"):
|
||
return ".zip"
|
||
if "geo+json" in content_type or b'"FeatureCollection"' in head:
|
||
return ".geojson"
|
||
if "json" in content_type:
|
||
return ".json"
|
||
return ".dat"
|
||
|
||
|
||
def _zip_shapefile_feature_count(path: Path) -> int:
|
||
"""Count shapefile records from the .shx index (100-byte header, 8 bytes per record)."""
|
||
try:
|
||
with zipfile.ZipFile(path) as archive:
|
||
for info in archive.infolist():
|
||
if info.filename.endswith("lines.shx"):
|
||
return max(0, (info.file_size - 100) // 8)
|
||
except zipfile.BadZipFile as exc:
|
||
raise EarthBoundaryBuildError(
|
||
f"{path.name} is not a valid zip archive", code="invalid_source"
|
||
) from exc
|
||
return 0
|
||
|
||
|
||
def _source_feature_count(path: Path, extension: str) -> int:
|
||
if extension == ".zip":
|
||
return _zip_shapefile_feature_count(path)
|
||
if extension in {".json", ".geojson"}:
|
||
with path.open("r", encoding="utf-8") as f:
|
||
payload = json.load(f)
|
||
if isinstance(payload, dict) and isinstance(payload.get("features"), list):
|
||
return len(payload["features"])
|
||
if isinstance(payload, list):
|
||
return len(payload)
|
||
return 1 if payload else 0
|
||
return 0
|
||
|
||
|
||
def _previous_source(source_key: str, endpoint: str) -> dict[str, Any] | None:
|
||
"""Last downloaded artifact for this endpoint, if it is still on disk."""
|
||
for source in _read_json(SOURCE_MANIFEST_PATH).get("sources") or []:
|
||
if source.get("id") != source_key or source.get("endpoint") != endpoint:
|
||
continue
|
||
path = Path(str(source.get("path") or ""))
|
||
if path.is_file() and source.get("sha256") and path.name.startswith(str(source["sha256"])):
|
||
return source
|
||
return None
|
||
|
||
|
||
def _conditional_headers(previous: dict[str, Any] | None) -> dict[str, str]:
|
||
if not previous:
|
||
return {}
|
||
headers = {}
|
||
if previous.get("etag"):
|
||
headers["If-None-Match"] = str(previous["etag"])
|
||
if previous.get("lastModified"):
|
||
headers["If-Modified-Since"] = str(previous["lastModified"])
|
||
return headers
|
||
|
||
|
||
async def _download_source(
|
||
source_key: str,
|
||
source_config: dict[str, Any],
|
||
progress_callback: Any = None,
|
||
) -> dict[str, Any]:
|
||
endpoint = str(source_config.get("endpoint") or "").strip()
|
||
if _is_placeholder_endpoint(endpoint):
|
||
raise EarthBoundaryBuildError(
|
||
f"{source_key} endpoint is not configured",
|
||
code="source_not_configured",
|
||
details={"source": source_key},
|
||
)
|
||
method = str(source_config.get("method") or "GET").upper()
|
||
if method not in {"GET", "POST"}:
|
||
raise EarthBoundaryBuildError(
|
||
f"{source_key} method must be GET or POST",
|
||
code="invalid_config",
|
||
details={"source": source_key, "method": method},
|
||
)
|
||
|
||
source_dir = SOURCE_OUTPUT_DIR / source_key
|
||
source_dir.mkdir(parents=True, exist_ok=True)
|
||
previous = _previous_source(source_key, endpoint)
|
||
digest = hashlib.sha256()
|
||
content_type = ""
|
||
head = b""
|
||
validators: dict[str, str] = {}
|
||
not_modified = False
|
||
with tempfile.NamedTemporaryFile(dir=source_dir, prefix=".download-", delete=False) as tmp:
|
||
tmp_path = Path(tmp.name)
|
||
try:
|
||
local_path = Path(endpoint.removeprefix("file://")).expanduser()
|
||
if endpoint.startswith("file://") or local_path.exists():
|
||
total = local_path.stat().st_size
|
||
with local_path.open("rb") as src:
|
||
while chunk := src.read(DOWNLOAD_CHUNK_BYTES):
|
||
head = head or chunk[:4096]
|
||
digest.update(chunk)
|
||
tmp.write(chunk)
|
||
if progress_callback:
|
||
progress_callback(1, total, total)
|
||
else:
|
||
timeout = float(source_config.get("timeout") or 120)
|
||
headers = source_config.get("headers") if isinstance(source_config.get("headers"), dict) else {}
|
||
# Re-use the stored artifact when the upstream file is unchanged
|
||
# (the OSM coastline archive alone is ~900 MB).
|
||
headers = {**headers, **_conditional_headers(previous)}
|
||
async with httpx.AsyncClient(timeout=timeout, follow_redirects=True) as client:
|
||
async with client.stream(method, endpoint, headers=headers) as response:
|
||
if response.status_code == 304 and previous:
|
||
not_modified = True
|
||
raise _NotModified
|
||
response.raise_for_status()
|
||
validators = {
|
||
key: value
|
||
for key, value in (
|
||
("etag", response.headers.get("etag")),
|
||
("lastModified", response.headers.get("last-modified")),
|
||
)
|
||
if value
|
||
}
|
||
content_type = response.headers.get("content-type", "")
|
||
# Content-Length counts encoded bytes; aiter_bytes yields decoded ones.
|
||
encoded = bool(response.headers.get("content-encoding"))
|
||
total = 0 if encoded else int(response.headers.get("content-length") or 0)
|
||
downloaded = 0
|
||
async for chunk in response.aiter_bytes(DOWNLOAD_CHUNK_BYTES):
|
||
if not chunk:
|
||
continue
|
||
head = head or chunk[:4096]
|
||
digest.update(chunk)
|
||
tmp.write(chunk)
|
||
downloaded += len(chunk)
|
||
if progress_callback:
|
||
progress_callback((downloaded / total) if total else None, downloaded, total)
|
||
except _NotModified:
|
||
pass
|
||
except BaseException:
|
||
tmp_path.unlink(missing_ok=True)
|
||
raise
|
||
|
||
if not_modified and previous:
|
||
tmp_path.unlink(missing_ok=True)
|
||
if progress_callback:
|
||
progress_callback(1, 0, 0)
|
||
logger.info("earth_boundary_source_not_modified", extra={"source": source_key})
|
||
return {**previous, "notModified": True}
|
||
|
||
sha256 = digest.hexdigest()
|
||
extension = _artifact_extension(endpoint, content_type, head)
|
||
artifact_path = source_dir / f"{sha256}{extension}"
|
||
tmp_path.replace(artifact_path)
|
||
for stale in source_dir.iterdir():
|
||
if stale.is_file() and stale != artifact_path:
|
||
stale.unlink()
|
||
feature_count = _source_feature_count(artifact_path, extension)
|
||
if feature_count <= 0:
|
||
raise EarthBoundaryBuildError(
|
||
f"{source_key} downloaded payload contains no features",
|
||
code="empty_source",
|
||
details={"source": source_key},
|
||
)
|
||
return {
|
||
"id": source_key,
|
||
"kind": source_config.get("sourceKind") or BOUNDARY_SOURCE_KINDS[source_key],
|
||
"endpoint": endpoint,
|
||
"path": str(artifact_path),
|
||
"sha256": sha256,
|
||
"featureCount": feature_count,
|
||
"license": source_config.get("license"),
|
||
**validators,
|
||
}
|
||
|
||
|
||
async def _run_builder(args: list[str]) -> dict[str, Any]:
|
||
command = [sys.executable, str(BUILDER_PATH), *args]
|
||
nice = shutil.which("nice")
|
||
if nice:
|
||
# Keep API latency stable while a production rebuild runs in the backend container.
|
||
command = [nice, "-n", "10", *command]
|
||
process = await asyncio.create_subprocess_exec(
|
||
*command,
|
||
cwd=REPO_ROOT,
|
||
stdout=asyncio.subprocess.PIPE,
|
||
stderr=asyncio.subprocess.PIPE,
|
||
)
|
||
stdout_bytes, stderr_bytes = await process.communicate()
|
||
stdout = stdout_bytes.decode("utf-8", errors="replace").strip()
|
||
stderr = stderr_bytes.decode("utf-8", errors="replace").strip()
|
||
payload: dict[str, Any] = {"returncode": process.returncode, "stderr_tail": stderr[-4000:]}
|
||
last_line = stdout.splitlines()[-1:] or []
|
||
if last_line:
|
||
try:
|
||
payload["result"] = json.loads(last_line[0])
|
||
except json.JSONDecodeError:
|
||
payload["result"] = last_line[0]
|
||
if process.returncode != 0:
|
||
raise EarthBoundaryBuildError(
|
||
(stderr.splitlines()[-1] if stderr else "") or "Earth boundary PMTiles build failed",
|
||
code="build_command_failed",
|
||
details=payload,
|
||
)
|
||
return payload
|
||
|
||
|
||
async def build_boundary_assets(progress_callback: Any = None) -> dict[str, Any]:
|
||
missing_tools = missing_build_tools()
|
||
if missing_tools:
|
||
raise EarthBoundaryBuildError(
|
||
f"PMTiles build tools missing: {', '.join(missing_tools)}",
|
||
code="missing_tools",
|
||
details={"missing_tools": missing_tools},
|
||
)
|
||
|
||
config_payload, _config_source = load_boundary_config()
|
||
source_configs = _source_configs_with_defaults(config_payload)
|
||
missing = [source for source in BOUNDARY_SOURCE_KINDS if source not in source_configs]
|
||
if missing:
|
||
raise EarthBoundaryBuildError(
|
||
f"Missing Earth boundary source configs: {', '.join(missing)}",
|
||
code="missing_sources",
|
||
details={"missing": missing},
|
||
)
|
||
|
||
sources = []
|
||
source_keys = list(BOUNDARY_SOURCE_KINDS)
|
||
span = 52 / len(source_keys)
|
||
for index, source_key in enumerate(source_keys):
|
||
source_config = source_configs[source_key]
|
||
if not isinstance(source_config, dict):
|
||
raise EarthBoundaryBuildError(
|
||
f"{source_key} config must be an object",
|
||
code="invalid_config",
|
||
details={"source": source_key},
|
||
)
|
||
source_start = 8 + index * span
|
||
source_end = source_start + span
|
||
if progress_callback:
|
||
progress_callback(source_start, "download", f"正在下载 {source_key}")
|
||
|
||
def report_download_progress(
|
||
ratio: float | None,
|
||
downloaded: int,
|
||
total: int,
|
||
_start: float = source_start,
|
||
_end: float = source_end,
|
||
_key: str = source_key,
|
||
) -> None:
|
||
if not progress_callback:
|
||
return
|
||
if ratio is None:
|
||
progress_callback(_start + span / 2, "download", f"{_key} 已下载 {downloaded} bytes")
|
||
return
|
||
progress_callback(
|
||
_start + (_end - _start) * ratio,
|
||
"download",
|
||
f"{_key} 下载 {int(ratio * 100)}%",
|
||
downloaded_bytes=downloaded,
|
||
total_bytes=total,
|
||
)
|
||
|
||
sources.append(await _download_source(source_key, source_config, report_download_progress))
|
||
|
||
source_manifest = {
|
||
"schema": "planet-earth-boundary-sources/v3",
|
||
"sources": sources,
|
||
"povPolicy": _read_json(POV_POLICY_PATH),
|
||
}
|
||
if progress_callback:
|
||
progress_callback(62, "manifest", "正在写入边界源 manifest")
|
||
_write_json(SOURCE_MANIFEST_PATH, source_manifest)
|
||
build_input_hash = _build_input_hash(source_manifest)
|
||
|
||
boundary_manifest = _read_json(BOUNDARY_MANIFEST_PATH)
|
||
build_skipped = _has_current_artifacts(boundary_manifest, build_input_hash)
|
||
if build_skipped:
|
||
if progress_callback:
|
||
progress_callback(96, "unchanged", "高精国界已是最新")
|
||
build_result: dict[str, Any] = {
|
||
"status": "unchanged",
|
||
"reason": "source manifest and build config hash unchanged",
|
||
"buildInputHash": build_input_hash,
|
||
}
|
||
else:
|
||
if progress_callback:
|
||
progress_callback(66, "build", "正在构建 PMTiles/MVT(海岸线 z0–z10)")
|
||
by_kind = {source["kind"]: source["path"] for source in sources}
|
||
builder_args = [
|
||
"--admin0-source", by_kind["admin0-boundaries"],
|
||
"--coastline-source", by_kind["coastline"],
|
||
"--disputed-source", by_kind["disputed-lines"],
|
||
"--claims-source", by_kind["claim-lines"],
|
||
"--admin1-source", by_kind["admin1-lines"],
|
||
"--output-dir", str(BOUNDARY_OUTPUT_DIR),
|
||
"--build-input-hash", build_input_hash,
|
||
"--pov-policy", str(POV_POLICY_PATH),
|
||
"--pov-geometry", str(POV_GEOMETRY_PATH),
|
||
"--min-zoom", str(BUILD_CONFIG["minZoom"]),
|
||
"--max-zoom", str(BUILD_CONFIG["maxZoom"]),
|
||
"--coastline-max-zoom", str(BUILD_CONFIG["coastlineMaxZoom"]),
|
||
"--temp-dir", str(BOUNDARY_DATA_DIR / "tmp"),
|
||
]
|
||
if "populated-places" in by_kind:
|
||
builder_args.extend(["--places-source", by_kind["populated-places"]])
|
||
build_result = await _run_builder(builder_args)
|
||
if progress_callback:
|
||
progress_callback(95, "finalize", "正在校验构建产物")
|
||
|
||
boundary_manifest = _read_json(BOUNDARY_MANIFEST_PATH)
|
||
if not _high_precision_ready(boundary_manifest):
|
||
raise EarthBoundaryBuildError(
|
||
"Earth boundary build finished without a verified China POV manifest",
|
||
code="unverified_artifact",
|
||
details={"manifest": _display_path(BOUNDARY_MANIFEST_PATH)},
|
||
)
|
||
result = {
|
||
"status": "unchanged" if build_skipped else "built",
|
||
"sources": sources,
|
||
"source_manifest": _display_path(SOURCE_MANIFEST_PATH),
|
||
"boundary_manifest": _display_path(BOUNDARY_MANIFEST_PATH),
|
||
"pmtiles": boundary_manifest.get("pmtiles"),
|
||
"manifest": boundary_manifest,
|
||
"build_result": build_result,
|
||
}
|
||
_write_json(BUILD_RESULT_PATH, result)
|
||
logger.info(
|
||
"earth_boundary_build_finished",
|
||
extra={"status": result["status"], "pmtiles_bytes": (boundary_manifest.get("pmtiles") or {}).get("sizeBytes")},
|
||
)
|
||
return {**get_boundary_status(), "build": result}
|
||
|
||
|
||
async def _run_boundary_build_job(job_id: str) -> None:
|
||
def report(progress: float, phase: str, message: str, **extra: Any) -> None:
|
||
if _build_job_state.get("id") != job_id:
|
||
return
|
||
_update_job_progress(progress, phase, message, **extra)
|
||
|
||
try:
|
||
report(3, "prepare", "正在准备高精国界构建")
|
||
result = await build_boundary_assets(report)
|
||
_set_job_state(
|
||
id=job_id,
|
||
status="succeeded",
|
||
progress=100,
|
||
phase="complete",
|
||
message="高精国界构建完成",
|
||
finished_at=_utc_now_iso(),
|
||
result={
|
||
"provider": result.get("provider"),
|
||
"high_precision_ready": result.get("high_precision_ready"),
|
||
"pmtiles": result.get("pmtiles"),
|
||
"manifest": result.get("manifest"),
|
||
},
|
||
)
|
||
_append_job_log("高精国界构建完成")
|
||
except EarthBoundaryBuildError as exc:
|
||
logger.warning("earth_boundary_build_failed", extra={"code": exc.code, "error": str(exc)})
|
||
_set_job_state(
|
||
id=job_id,
|
||
status="failed",
|
||
progress=_build_job_state.get("progress", 0),
|
||
phase="failed",
|
||
message=str(exc),
|
||
code=exc.code,
|
||
details=exc.details,
|
||
finished_at=_utc_now_iso(),
|
||
)
|
||
_append_job_log(str(exc))
|
||
except Exception as exc: # pragma: no cover - defensive guard for background task
|
||
logger.exception("earth_boundary_build_crashed")
|
||
_set_job_state(
|
||
id=job_id,
|
||
status="failed",
|
||
progress=_build_job_state.get("progress", 0),
|
||
phase="failed",
|
||
message=str(exc),
|
||
code="build_failed",
|
||
finished_at=_utc_now_iso(),
|
||
)
|
||
_append_job_log(str(exc))
|
||
|
||
|
||
async def start_boundary_build_job() -> dict[str, Any]:
|
||
global _build_task
|
||
async with _build_job_lock:
|
||
if _build_task and not _build_task.done():
|
||
return {"accepted": False, "job": _public_job_state()}
|
||
missing_tools = missing_build_tools()
|
||
if missing_tools:
|
||
raise EarthBoundaryBuildError(
|
||
f"PMTiles build tools missing: {', '.join(missing_tools)}",
|
||
code="missing_tools",
|
||
details={"missing_tools": missing_tools},
|
||
)
|
||
job_id = uuid4().hex
|
||
_set_job_state(
|
||
id=job_id,
|
||
status="queued",
|
||
progress=0,
|
||
phase="queued",
|
||
message="高精国界构建已加入队列",
|
||
logs=[],
|
||
started_at=_utc_now_iso(),
|
||
finished_at=None,
|
||
code=None,
|
||
details=None,
|
||
)
|
||
_append_job_log("高精国界构建已启动")
|
||
_build_task = asyncio.create_task(_run_boundary_build_job(job_id))
|
||
return {"accepted": True, "job": _public_job_state()}
|