release: bump version to 0.84.0
This commit is contained in:
1 parent
3b1b9ef68c
commit
e1cc27f13d
241 files changed
+42779
-6027
No files matched your search
@@ -1,142 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build a usable high-precision China-POV Earth boundary GeoJSON artifact."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from earth_boundary_policy import apply_admin0_policy, load_policy
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--admin0-source", type=Path, required=True)
|
||||
parser.add_argument("--coastline-source", type=Path, required=True)
|
||||
parser.add_argument("--claims-source", type=Path, required=True)
|
||||
parser.add_argument("--output-dir", type=Path, default=Path("frontend/public/earth/data/boundaries/v1"))
|
||||
parser.add_argument("--build-input-hash", required=True)
|
||||
parser.add_argument("--pov-policy", type=Path, required=True)
|
||||
parser.add_argument("--pov-geometry", type=Path, required=True)
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def load_geojson(path: Path) -> dict[str, Any]:
|
||||
with path.open("r", encoding="utf-8") as f:
|
||||
payload = json.load(f)
|
||||
if payload.get("type") == "Feature":
|
||||
payload = {"type": "FeatureCollection", "features": [payload]}
|
||||
if payload.get("type") != "FeatureCollection":
|
||||
raise ValueError(f"{path} must be a GeoJSON FeatureCollection or Feature")
|
||||
return payload
|
||||
|
||||
|
||||
def feature_collection(features: list[dict[str, Any]], **extra: Any) -> dict[str, Any]:
|
||||
return {"type": "FeatureCollection", **extra, "features": features}
|
||||
|
||||
|
||||
def sha256_file(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as f:
|
||||
for chunk in iter(lambda: f.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def split_line_features(claims: dict[str, Any]) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
|
||||
disputed, maritime = [], []
|
||||
for feature in claims.get("features") or []:
|
||||
if not feature.get("geometry"):
|
||||
continue
|
||||
props = dict(feature.get("properties") or {})
|
||||
is_claim = props.get("PLANET_LAYER") == "claim_line"
|
||||
props["PLANET_LAYER"] = "claim_line" if is_claim else "disputed_internal"
|
||||
(maritime if is_claim else disputed).append({**feature, "properties": props})
|
||||
return disputed, maritime
|
||||
|
||||
|
||||
def main() -> None:
|
||||
args = parse_args()
|
||||
args.output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
admin0 = load_geojson(args.admin0_source)
|
||||
coastline = load_geojson(args.coastline_source)
|
||||
claims = load_geojson(args.claims_source)
|
||||
|
||||
policy = load_policy(args.pov_policy)
|
||||
geometry_package = json.loads(args.pov_geometry.read_text(encoding="utf-8"))
|
||||
admin0, coverage = apply_admin0_policy(admin0, policy, geometry_package=geometry_package)
|
||||
admin_features = admin0["features"]
|
||||
coastline_features = [
|
||||
{**feature, "properties": {**(feature.get("properties") or {}), "PLANET_LAYER": "coastline"}}
|
||||
for feature in coastline.get("features") or []
|
||||
if feature.get("geometry")
|
||||
]
|
||||
disputed_features, claim_features = split_line_features(claims)
|
||||
|
||||
asset_version = f"{args.build_input_hash[:12]}-{coverage['geometrySha256'][:12]}"
|
||||
hover_path = args.output_dir / f"hover-index.{asset_version}.geojson"
|
||||
base_path = args.output_dir / f"base.{asset_version}.geojson"
|
||||
claim_path = args.output_dir / f"china-claims.{asset_version}.geojson"
|
||||
manifest_path = args.output_dir / "manifest.json"
|
||||
|
||||
hover = feature_collection(admin_features, name="earth-boundaries-china-pov-hover")
|
||||
base = feature_collection(
|
||||
[*admin_features, *coastline_features, *disputed_features],
|
||||
name="earth-boundaries-china-pov-base",
|
||||
)
|
||||
claim_fc = feature_collection(claim_features, name="earth-boundaries-china-pov-claims")
|
||||
|
||||
for path, payload in ((hover_path, hover), (base_path, base), (claim_path, claim_fc)):
|
||||
with path.open("w", encoding="utf-8") as f:
|
||||
json.dump(payload, f, ensure_ascii=False, separators=(",", ":"))
|
||||
f.write("\n")
|
||||
|
||||
manifest = {
|
||||
"version": coverage["profile"],
|
||||
"builtAt": dt.datetime.now(dt.UTC).replace(microsecond=0).isoformat(),
|
||||
"tileProvider": "geojson-high-precision",
|
||||
"format": "geojson",
|
||||
"buildInputHash": args.build_input_hash,
|
||||
"base": base_path.name,
|
||||
"hoverIndex": hover_path.name,
|
||||
"claimLine": claim_path.name,
|
||||
"sourceFeatureCount": len(admin_features),
|
||||
"coastlineFeatureCount": len(coastline_features),
|
||||
"disputedFeatureCount": len(disputed_features),
|
||||
"claimFeatureCount": len(claim_features),
|
||||
"tiles": {"minZoom": 0, "maxZoom": 0},
|
||||
"chinaClaims": {"available": bool(claim_features), "path": claim_path.name},
|
||||
"sha256": {
|
||||
"base": sha256_file(base_path),
|
||||
"hoverIndex": sha256_file(hover_path),
|
||||
"claimLine": sha256_file(claim_path),
|
||||
},
|
||||
"povPolicy": coverage,
|
||||
}
|
||||
with manifest_path.open("w", encoding="utf-8") as f:
|
||||
json.dump(manifest, f, ensure_ascii=False, indent=2)
|
||||
f.write("\n")
|
||||
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"status": "success",
|
||||
"provider": "geojson-high-precision",
|
||||
"manifest": str(manifest_path),
|
||||
"admin0_features": len(admin_features),
|
||||
"coastline_features": len(coastline_features),
|
||||
"claim_features": len(claim_features),
|
||||
},
|
||||
ensure_ascii=False,
|
||||
sort_keys=True,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,37 +1,113 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build the production Earth boundary PMTiles artifact from collected sources."""
|
||||
"""Build the China POV Earth boundary PMTiles artifact.
|
||||
|
||||
Layers (all lines, Web Mercator MVT tiles):
|
||||
- ``coastline`` OSM coastline (osmdata.openstreetmap.de, ODbL)
|
||||
- ``boundary_admin0`` shared land edges of the policy-applied admin-0 polygons
|
||||
- ``boundary_disputed_internal`` Natural Earth disputed lines outside China
|
||||
- ``boundary_admin1`` Natural Earth admin-1 lines (China POV filtered), z4+
|
||||
- ``claim_line`` Natural Earth China POV nine-dash maritime line
|
||||
|
||||
Coastal ends of admin-0 / admin-1 lines are trimmed or extended onto the OSM
|
||||
coastline so borders meet the shore that the satellite imagery shows.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import ctypes
|
||||
import datetime as dt
|
||||
import gc
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import resource
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from earth_boundary_policy import apply_admin0_policy, load_policy
|
||||
from shapely import STRtree
|
||||
from shapely.geometry import Point, shape
|
||||
|
||||
from earth_boundary_geometry import (
|
||||
CoastlineCountryAssigner,
|
||||
admin1_lines,
|
||||
build_geo_labels,
|
||||
china_clip_geometry,
|
||||
collect_coast_near,
|
||||
country_geometries,
|
||||
derive_land_borders,
|
||||
disputed_lines,
|
||||
free_endpoints,
|
||||
geojson_feature,
|
||||
hover_borders,
|
||||
hover_index,
|
||||
iter_shapefile_lines,
|
||||
resolve_coastline_shapefile,
|
||||
rounded_mapping,
|
||||
snap_coastal_ends,
|
||||
)
|
||||
from earth_boundary_policy import apply_admin0_policy, load_policy, policy_digest
|
||||
|
||||
|
||||
ARTIFACT_PREFIX = "earth-boundaries"
|
||||
CLAIM_RULE_ID = "china-maritime-claim-line"
|
||||
MIN_CLAIM_DASHES = 9
|
||||
HOVER_INDEX_TOLERANCE = 0.02
|
||||
TIPPECANOE_DEFAULT_THREADS = "2"
|
||||
HOVER_BORDER_TOLERANCE = 0.002
|
||||
ADMIN1_BORDER_CLEARANCE = 0.02
|
||||
BORDER_LAYER_MAX_ZOOM = 6
|
||||
ATTRIBUTION = ["© OpenStreetMap contributors (ODbL)", "Natural Earth (public domain)"]
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--admin0-source", type=Path, required=True)
|
||||
parser.add_argument("--coastline-source", type=Path, required=True)
|
||||
parser.add_argument("--disputed-source", type=Path, required=True)
|
||||
parser.add_argument("--claims-source", type=Path, required=True)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
parser.add_argument("--manifest", type=Path, required=True)
|
||||
parser.add_argument("--admin1-source", type=Path, required=True)
|
||||
parser.add_argument("--places-source", type=Path, default=None)
|
||||
parser.add_argument("--output-dir", type=Path, required=True)
|
||||
parser.add_argument("--build-input-hash", required=True)
|
||||
parser.add_argument("--pov-policy", type=Path, required=True)
|
||||
parser.add_argument("--pov-geometry", type=Path, required=True)
|
||||
parser.add_argument("--min-zoom", type=int, default=0)
|
||||
parser.add_argument("--max-zoom", type=int, default=10)
|
||||
parser.add_argument("--coastline-max-zoom", type=int, default=None)
|
||||
parser.add_argument("--simplification", type=float, default=4.0)
|
||||
parser.add_argument("--temp-dir", type=Path, default=None)
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def log(message: str, **fields: Any) -> None:
|
||||
# Progress goes to stderr; stdout carries the final JSON result only.
|
||||
payload = {"event": message, **fields}
|
||||
print(json.dumps(payload, ensure_ascii=False, sort_keys=True), file=sys.stderr, flush=True)
|
||||
|
||||
|
||||
def current_rss_mb() -> float:
|
||||
try:
|
||||
pages = int(Path("/proc/self/statm").read_text().split()[1])
|
||||
except (OSError, ValueError, IndexError):
|
||||
return 0.0
|
||||
return round(pages * os.sysconf("SC_PAGE_SIZE") / 1024 / 1024, 1)
|
||||
|
||||
|
||||
def release_heap() -> None:
|
||||
"""Return freed geometry memory to the OS before the tippecanoe child starts."""
|
||||
try:
|
||||
ctypes.CDLL("libc.so.6").malloc_trim(0)
|
||||
except (OSError, AttributeError):
|
||||
pass
|
||||
|
||||
|
||||
def require_tool(name: str) -> str:
|
||||
path = shutil.which(name)
|
||||
if not path:
|
||||
@@ -47,30 +123,6 @@ def load_geojson(path: Path) -> dict[str, Any]:
|
||||
return payload
|
||||
|
||||
|
||||
def iter_layer_features(payload: dict[str, Any], layer: str) -> list[dict[str, Any]]:
|
||||
out = []
|
||||
for feature in payload.get("features") or []:
|
||||
if not feature.get("geometry"):
|
||||
continue
|
||||
props = dict(feature.get("properties") or {})
|
||||
props["tippecanoe"] = {"layer": layer}
|
||||
out.append(
|
||||
{
|
||||
"type": "Feature",
|
||||
"geometry": feature["geometry"],
|
||||
"properties": props,
|
||||
}
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def write_ndjson(path: Path, features: list[dict[str, Any]]) -> None:
|
||||
with path.open("w", encoding="utf-8") as f:
|
||||
for feature in features:
|
||||
f.write(json.dumps(feature, ensure_ascii=False, separators=(",", ":")))
|
||||
f.write("\n")
|
||||
|
||||
|
||||
def sha256_file(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as f:
|
||||
@@ -79,95 +131,314 @@ def sha256_file(path: Path) -> str:
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def write_json(path: Path, payload: Any, *, indent: int | None = None) -> None:
|
||||
tmp = path.with_suffix(path.suffix + ".tmp")
|
||||
with tmp.open("w", encoding="utf-8") as f:
|
||||
if indent:
|
||||
json.dump(payload, f, ensure_ascii=False, indent=indent)
|
||||
else:
|
||||
json.dump(payload, f, ensure_ascii=False, separators=(",", ":"))
|
||||
f.write("\n")
|
||||
tmp.replace(path)
|
||||
|
||||
|
||||
def claim_features(collection: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""Accept only the Natural Earth China POV dashed maritime line."""
|
||||
features = []
|
||||
for feature in collection.get("features") or []:
|
||||
props = feature.get("properties") or {}
|
||||
if not feature.get("geometry"):
|
||||
continue
|
||||
if "9 dash" not in str(props.get("COMMENT") or ""):
|
||||
continue
|
||||
if not str(props.get("FCLASS_CN") or "").startswith("International boundary"):
|
||||
continue
|
||||
features.append(
|
||||
{
|
||||
"type": "Feature",
|
||||
"geometry": shape(feature["geometry"]),
|
||||
"properties": {"name": "九段线", "name_en": "Nine-dash line"},
|
||||
}
|
||||
)
|
||||
return features
|
||||
|
||||
|
||||
def admin1_coastal_endpoints(
|
||||
features: list[dict[str, Any]], borders: list[dict[str, Any]]
|
||||
) -> set[tuple[float, float]]:
|
||||
"""Admin-1 free ends that do not sit on a national border are coastal."""
|
||||
free = free_endpoints(features)
|
||||
if not borders:
|
||||
return free
|
||||
border_tree = STRtree([feature["geometry"] for feature in borders])
|
||||
coastal = set()
|
||||
for lon, lat in free:
|
||||
point = Point(lon, lat)
|
||||
nearby = border_tree.query(point.buffer(ADMIN1_BORDER_CLEARANCE))
|
||||
if not any(
|
||||
borders[int(i)]["geometry"].distance(point) <= ADMIN1_BORDER_CLEARANCE for i in nearby
|
||||
):
|
||||
coastal.add((lon, lat))
|
||||
return coastal
|
||||
|
||||
|
||||
def apply_claim_coverage(coverage: dict[str, Any], claims: list[dict[str, Any]]) -> None:
|
||||
applied = set(coverage.get("appliedRuleIds") or [])
|
||||
unresolved = set(coverage.get("unresolvedRuleIds") or [])
|
||||
reasons = dict(coverage.get("unresolvedReasons") or {})
|
||||
if len(claims) >= MIN_CLAIM_DASHES:
|
||||
applied.add(CLAIM_RULE_ID)
|
||||
unresolved.discard(CLAIM_RULE_ID)
|
||||
reasons.pop(CLAIM_RULE_ID, None)
|
||||
coverage["appliedRuleIds"] = sorted(applied)
|
||||
coverage["unresolvedRuleIds"] = sorted(unresolved)
|
||||
coverage["unresolvedReasons"] = reasons
|
||||
coverage["coverage"] = "partial" if unresolved else "complete"
|
||||
coverage["claimLine"] = {
|
||||
"source": "Natural Earth ne_10m_admin_0_boundary_lines_maritime_indicator_chn",
|
||||
"featureCount": len(claims),
|
||||
}
|
||||
|
||||
|
||||
def remove_stale_artifacts(output_dir: Path, keep: set[str]) -> list[str]:
|
||||
removed = []
|
||||
for path in output_dir.iterdir():
|
||||
if not path.is_file() or path.name in keep or path.name == "manifest.json":
|
||||
continue
|
||||
if path.name.startswith((ARTIFACT_PREFIX, "hover-index", "hover-borders", "geo-labels")):
|
||||
path.unlink()
|
||||
removed.append(path.name)
|
||||
return removed
|
||||
|
||||
|
||||
def main() -> None:
|
||||
args = parse_args()
|
||||
started = time.monotonic()
|
||||
tippecanoe = require_tool("tippecanoe")
|
||||
pmtiles = require_tool("pmtiles")
|
||||
coast_max_zoom = args.coastline_max_zoom if args.coastline_max_zoom is not None else args.max_zoom
|
||||
|
||||
policy = load_policy(args.pov_policy)
|
||||
geometry_package = json.loads(args.pov_geometry.read_text(encoding="utf-8"))
|
||||
admin0, coverage = apply_admin0_policy(
|
||||
load_geojson(args.admin0_source), policy, geometry_package=geometry_package
|
||||
)
|
||||
coastline = load_geojson(args.coastline_source)
|
||||
claims = load_geojson(args.claims_source)
|
||||
maritime = [f for f in claims["features"] if (f.get("properties") or {}).get("PLANET_LAYER") == "claim_line"]
|
||||
disputed = [f for f in claims["features"] if f not in maritime]
|
||||
features = [
|
||||
*iter_layer_features(admin0, "boundary_admin0"),
|
||||
*iter_layer_features(coastline, "coastline"),
|
||||
*iter_layer_features(disputed, "boundary_disputed_internal"),
|
||||
*iter_layer_features({"features": maritime}, "claim_line"),
|
||||
]
|
||||
if not features:
|
||||
raise RuntimeError("no features available for PMTiles build")
|
||||
countries = country_geometries(admin0)
|
||||
coast_assigner = CoastlineCountryAssigner(countries)
|
||||
china_clip = china_clip_geometry(countries)
|
||||
border_max_zoom = min(BORDER_LAYER_MAX_ZOOM, args.max_zoom)
|
||||
log("policy_applied", countries=len(countries))
|
||||
|
||||
args.output.parent.mkdir(parents=True, exist_ok=True)
|
||||
args.manifest.parent.mkdir(parents=True, exist_ok=True)
|
||||
hover_path = args.manifest.parent / "hover-index.geojson"
|
||||
with tempfile.TemporaryDirectory(prefix="planet-earth-boundaries-") as tmp:
|
||||
borders = derive_land_borders(countries)
|
||||
admin1 = admin1_lines(load_geojson(args.admin1_source), china_clip)
|
||||
disputed = disputed_lines(load_geojson(args.disputed_source), china_clip)
|
||||
claims = claim_features(load_geojson(args.claims_source))
|
||||
if len(claims) < MIN_CLAIM_DASHES:
|
||||
raise RuntimeError(
|
||||
f"China POV claim line source must contain {MIN_CLAIM_DASHES} audited dashes, found {len(claims)}"
|
||||
)
|
||||
apply_claim_coverage(coverage, claims)
|
||||
border_free = free_endpoints(borders)
|
||||
admin1_free = admin1_coastal_endpoints(admin1, borders)
|
||||
log(
|
||||
"lines_derived",
|
||||
borders=len(borders), admin1=len(admin1), disputed=len(disputed), claims=len(claims),
|
||||
border_coastal_ends=len(border_free), admin1_coastal_ends=len(admin1_free),
|
||||
)
|
||||
|
||||
args.output_dir.mkdir(parents=True, exist_ok=True)
|
||||
temp_parent = args.temp_dir or args.output_dir.parent
|
||||
temp_parent.mkdir(parents=True, exist_ok=True)
|
||||
asset_version = f"{args.build_input_hash[:12]}-{coverage['geometrySha256'][:12]}"
|
||||
pmtiles_name = f"{ARTIFACT_PREFIX}.{asset_version}.pmtiles"
|
||||
hover_name = f"hover-index.{asset_version}.json"
|
||||
hover_borders_name = f"hover-borders.{asset_version}.json"
|
||||
geo_labels_name = f"geo-labels.{asset_version}.json"
|
||||
geo_labels_payload: dict[str, Any] | None = None
|
||||
if args.places_source and args.places_source.is_file():
|
||||
geo_labels_payload = build_geo_labels(
|
||||
load_geojson(args.places_source),
|
||||
policy=policy,
|
||||
china_clip=china_clip,
|
||||
)
|
||||
log("geo_labels_built", **(geo_labels_payload.get("counts") or {}))
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix="planet-earth-boundaries-", dir=temp_parent) as tmp:
|
||||
tmp_dir = Path(tmp)
|
||||
ndjson_path = tmp_dir / "earth-boundaries.ndjson"
|
||||
mbtiles_path = tmp_dir / "earth-boundaries.mbtiles"
|
||||
write_ndjson(ndjson_path, features)
|
||||
coast_shp = resolve_coastline_shapefile(args.coastline_source, tmp_dir)
|
||||
if coast_shp is None:
|
||||
raise RuntimeError(f"coastline source has no lines.shp: {args.coastline_source}")
|
||||
|
||||
ndjson_path = tmp_dir / "earth-boundaries.ndjson"
|
||||
endpoints = border_free | admin1_free
|
||||
coast_count = 0
|
||||
coast_tagged = 0
|
||||
with ndjson_path.open("w", encoding="utf-8") as out:
|
||||
near: list[Any] = []
|
||||
|
||||
def stream_coast():
|
||||
nonlocal coast_count, coast_tagged
|
||||
for line in iter_shapefile_lines(coast_shp):
|
||||
for tagged_line, adm0_a3 in coast_assigner.assign(line):
|
||||
coast_count += 1
|
||||
if adm0_a3:
|
||||
coast_tagged += 1
|
||||
out.write(json.dumps(
|
||||
{
|
||||
"type": "Feature",
|
||||
"tippecanoe": {"layer": "coastline", "minzoom": args.min_zoom, "maxzoom": coast_max_zoom},
|
||||
"properties": {"ADM0_A3": adm0_a3} if adm0_a3 else {},
|
||||
"geometry": rounded_mapping(tagged_line, 7),
|
||||
},
|
||||
separators=(",", ":"),
|
||||
))
|
||||
out.write("\n")
|
||||
yield line
|
||||
|
||||
near = collect_coast_near(stream_coast(), endpoints)
|
||||
log("coastline_streamed", features=coast_count, tagged=coast_tagged, near_endpoints=len(near))
|
||||
|
||||
snap_stats = {
|
||||
"boundary_admin0": dict(snap_coastal_ends(borders, near, border_free)),
|
||||
"boundary_admin1": dict(snap_coastal_ends(admin1, near, admin1_free)),
|
||||
}
|
||||
log("coastal_ends_snapped", **snap_stats)
|
||||
|
||||
layer_counts: Counter[str] = Counter({"coastline": coast_count})
|
||||
for layer, features, min_zoom in (
|
||||
("boundary_admin0", borders, args.min_zoom),
|
||||
("boundary_disputed_internal", disputed, args.min_zoom),
|
||||
("claim_line", claims, args.min_zoom),
|
||||
):
|
||||
for feature in features:
|
||||
out.write(
|
||||
json.dumps(
|
||||
geojson_feature(feature, layer, min_zoom, border_max_zoom),
|
||||
ensure_ascii=False,
|
||||
separators=(",", ":"),
|
||||
)
|
||||
)
|
||||
out.write("\n")
|
||||
layer_counts[layer] += 1
|
||||
for feature in admin1:
|
||||
out.write(json.dumps(
|
||||
geojson_feature(feature, "boundary_admin1", feature["properties"]["minzoom"], border_max_zoom),
|
||||
ensure_ascii=False, separators=(",", ":"),
|
||||
))
|
||||
out.write("\n")
|
||||
layer_counts["boundary_admin1"] += 1
|
||||
|
||||
hover = hover_index(admin0, countries, HOVER_INDEX_TOLERANCE)
|
||||
hover_border_fc = hover_borders(borders, HOVER_BORDER_TOLERANCE)
|
||||
write_json(tmp_dir / hover_name, hover)
|
||||
write_json(tmp_dir / hover_borders_name, hover_border_fc)
|
||||
move_names = [pmtiles_name, hover_name, hover_borders_name]
|
||||
if geo_labels_payload is not None:
|
||||
write_json(tmp_dir / geo_labels_name, geo_labels_payload)
|
||||
move_names.append(geo_labels_name)
|
||||
# Release geometry before tippecanoe so the backend container keeps headroom.
|
||||
del near, borders, admin1, disputed, hover, hover_border_fc, countries, china_clip, coast_assigner
|
||||
gc.collect()
|
||||
release_heap()
|
||||
log("python_rss_before_tiles", rss_mb=current_rss_mb())
|
||||
|
||||
tmp_pmtiles = tmp_dir / pmtiles_name
|
||||
tippecanoe_started = time.monotonic()
|
||||
tippecanoe_env = {
|
||||
**os.environ,
|
||||
"TIPPECANOE_MAX_THREADS": os.environ.get("TIPPECANOE_MAX_THREADS", TIPPECANOE_DEFAULT_THREADS),
|
||||
}
|
||||
subprocess.run(
|
||||
[
|
||||
tippecanoe,
|
||||
"--force",
|
||||
"--quiet",
|
||||
"--read-parallel",
|
||||
"--minimum-zoom",
|
||||
str(args.min_zoom),
|
||||
"--maximum-zoom",
|
||||
str(args.max_zoom),
|
||||
"--no-tile-compression",
|
||||
"--output",
|
||||
str(mbtiles_path),
|
||||
"--minimum-zoom", str(args.min_zoom),
|
||||
"--maximum-zoom", str(args.max_zoom),
|
||||
"--no-feature-limit",
|
||||
"--no-tile-size-limit",
|
||||
"--simplification", str(args.simplification),
|
||||
"--temporary-directory", str(tmp_dir),
|
||||
"--name", "Planet Earth boundaries (china-pov-v1)",
|
||||
"--attribution", " | ".join(ATTRIBUTION),
|
||||
"--output", str(tmp_pmtiles),
|
||||
str(ndjson_path),
|
||||
],
|
||||
check=True,
|
||||
env=tippecanoe_env,
|
||||
)
|
||||
subprocess.run([pmtiles, "convert", str(mbtiles_path), str(args.output)], check=True)
|
||||
tippecanoe_seconds = round(time.monotonic() - tippecanoe_started, 1)
|
||||
log("tiles_built", seconds=tippecanoe_seconds, bytes=tmp_pmtiles.stat().st_size)
|
||||
|
||||
with hover_path.open("w", encoding="utf-8") as output:
|
||||
json.dump(admin0, output, ensure_ascii=False, separators=(",", ":"))
|
||||
output.write("\n")
|
||||
for name in move_names:
|
||||
shutil.move(str(tmp_dir / name), args.output_dir / name)
|
||||
|
||||
pmtiles_path = args.output_dir / pmtiles_name
|
||||
keep_names = {pmtiles_name, hover_name, hover_borders_name}
|
||||
geo_labels_manifest: dict[str, Any] = {}
|
||||
if geo_labels_payload is not None and (args.output_dir / geo_labels_name).is_file():
|
||||
keep_names.add(geo_labels_name)
|
||||
geo_labels_manifest = {
|
||||
"geoLabels": geo_labels_name,
|
||||
"geoLabelsSha256": sha256_file(args.output_dir / geo_labels_name),
|
||||
"geoLabelsCounts": geo_labels_payload.get("counts"),
|
||||
}
|
||||
manifest = {
|
||||
"schema": "planet-earth-boundaries/v2",
|
||||
"version": coverage["profile"],
|
||||
"assetVersion": asset_version,
|
||||
"builtAt": dt.datetime.now(dt.UTC).replace(microsecond=0).isoformat(),
|
||||
"tileProvider": "pmtiles-mvt",
|
||||
"format": "pmtiles+mvt",
|
||||
"buildInputHash": args.build_input_hash,
|
||||
"pmtiles": {
|
||||
"path": os.path.relpath(args.output, args.manifest.parent),
|
||||
"sha256": sha256_file(args.output),
|
||||
"path": pmtiles_name,
|
||||
"sha256": sha256_file(pmtiles_path),
|
||||
"sizeBytes": pmtiles_path.stat().st_size,
|
||||
},
|
||||
"tiles": {
|
||||
"minZoom": args.min_zoom,
|
||||
"maxZoom": args.max_zoom,
|
||||
"layerZoom": {
|
||||
"coastline": [args.min_zoom, coast_max_zoom],
|
||||
"boundary_admin0": [args.min_zoom, border_max_zoom],
|
||||
"boundary_disputed_internal": [args.min_zoom, border_max_zoom],
|
||||
"boundary_admin1": [4, border_max_zoom],
|
||||
"claim_line": [args.min_zoom, border_max_zoom],
|
||||
},
|
||||
},
|
||||
"layers": [
|
||||
"boundary_admin0", "boundary_disputed_internal", "coastline",
|
||||
*(["claim_line"] if maritime else []),
|
||||
],
|
||||
"layers": ["coastline", "boundary_admin0", "boundary_disputed_internal", "boundary_admin1", "claim_line"],
|
||||
"layerFeatureCounts": dict(layer_counts),
|
||||
"snap": snap_stats,
|
||||
"povPolicy": coverage,
|
||||
"chinaClaims": {"available": bool(maritime)},
|
||||
"chinaClaims": {"available": True, "featureCount": len(claims)},
|
||||
"base": None,
|
||||
"hoverIndex": hover_path.name,
|
||||
"hoverIndexSha256": sha256_file(hover_path),
|
||||
"hoverIndex": hover_name,
|
||||
"hoverIndexSha256": sha256_file(args.output_dir / hover_name),
|
||||
"hoverBorders": hover_borders_name,
|
||||
"hoverBordersSha256": sha256_file(args.output_dir / hover_borders_name),
|
||||
**geo_labels_manifest,
|
||||
"policySha256": policy_digest(policy),
|
||||
"attribution": ATTRIBUTION,
|
||||
}
|
||||
with args.manifest.open("w", encoding="utf-8") as f:
|
||||
json.dump(manifest, f, ensure_ascii=False, indent=2)
|
||||
f.write("\n")
|
||||
|
||||
write_json(args.output_dir / "manifest.json", manifest, indent=2)
|
||||
removed = remove_stale_artifacts(args.output_dir, keep_names)
|
||||
peak_rss_mb = round(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024, 1)
|
||||
child_peak_rss_mb = round(resource.getrusage(resource.RUSAGE_CHILDREN).ru_maxrss / 1024, 1)
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"status": "success",
|
||||
"output": str(args.output),
|
||||
"features": len(features),
|
||||
"format": "pmtiles+mvt",
|
||||
"output": str(pmtiles_path),
|
||||
"sizeBytes": manifest["pmtiles"]["sizeBytes"],
|
||||
"layerFeatureCounts": manifest["layerFeatureCounts"],
|
||||
"snap": snap_stats,
|
||||
"seconds": round(time.monotonic() - started, 1),
|
||||
"tippecanoeSeconds": tippecanoe_seconds,
|
||||
"peakRssMb": peak_rss_mb,
|
||||
"tippecanoePeakRssMb": child_peak_rss_mb,
|
||||
"removedStaleArtifacts": removed,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
sort_keys=True,
|
||||
|
||||
@@ -16,7 +16,7 @@ from typing import Any
|
||||
|
||||
|
||||
DEFAULT_CONFIG = Path("config/earth-boundary-sources.example.json")
|
||||
DEFAULT_ARTIFACT = Path("frontend/public/earth/data/boundaries/earth-boundaries-china-pov-v1.pmtiles")
|
||||
DEFAULT_ARTIFACT = Path("backend/data/earth-boundaries/artifacts/manifest.json")
|
||||
|
||||
|
||||
def load_json(path: Path) -> dict[str, Any]:
|
||||
@@ -43,7 +43,7 @@ def main() -> int:
|
||||
failures.append("policy.productionTileFormat must be pmtiles+mvt")
|
||||
if not policy.get("povPolicyPath"):
|
||||
failures.append("policy.povPolicyPath is required")
|
||||
required_kinds = {"admin0-boundaries", "coastline", "claim-lines"}
|
||||
required_kinds = {"admin0-boundaries", "coastline", "disputed-lines", "claim-lines", "admin1-lines"}
|
||||
configured_kinds = {str(source.get("sourceKind")) for source in collector_configs.values()}
|
||||
missing_kinds = sorted(required_kinds - configured_kinds)
|
||||
if missing_kinds:
|
||||
@@ -53,12 +53,12 @@ def main() -> int:
|
||||
if not endpoint or endpoint.startswith("https://example.com/"):
|
||||
failures.append(f"{collector_name} endpoint must be configured to an audited production source")
|
||||
|
||||
for tool in ("tippecanoe", "pmtiles"):
|
||||
for tool in ("tippecanoe",):
|
||||
if shutil.which(tool) is None:
|
||||
failures.append(f"external tool not found in PATH: {tool}")
|
||||
|
||||
if not args.artifact.exists():
|
||||
warnings.append(f"PMTiles artifact does not exist yet: {args.artifact}")
|
||||
warnings.append(f"PMTiles manifest does not exist yet: {args.artifact}")
|
||||
|
||||
result = {
|
||||
"ready": not failures,
|
||||
|
||||
@@ -0,0 +1,615 @@
|
||||
"""Geometry helpers for the China POV Earth boundary PMTiles build.
|
||||
|
||||
The display policy decides country ownership on admin-0 polygons
|
||||
(``earth_boundary_policy``). This module turns those polygons into the line
|
||||
layers the globe renders, aligns their coastal ends with the high precision
|
||||
OSM coastline and prepares the light-weight hover / label assets.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import zipfile
|
||||
from collections import Counter
|
||||
from collections.abc import Iterable, Iterator
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import shapefile
|
||||
from shapely import STRtree, get_coordinates, prepare
|
||||
from shapely.geometry import LineString, MultiLineString, Point, Polygon, box, mapping, shape
|
||||
from shapely.geometry.base import BaseGeometry
|
||||
from shapely.ops import linemerge, nearest_points, substring, unary_union
|
||||
|
||||
|
||||
SNAP_MAX_DEGREES = 0.05 # ~5 km; larger gaps stay visible and are logged.
|
||||
ENDPOINT_KEY_DIGITS = 7
|
||||
CHINA_CLIP_BUFFER_DEGREES = 0.01
|
||||
CHINA_ADMIN0_CODE = "CHN"
|
||||
ABSORBED_ADMIN1_CODES = {"TWN", "HKG", "MAC"}
|
||||
|
||||
|
||||
def country_code(properties: dict[str, Any]) -> str:
|
||||
code = properties.get("ADM0_A3") or properties.get("ISO_A3") or ""
|
||||
return str(code).upper()
|
||||
|
||||
|
||||
def _line_parts(geometry: BaseGeometry | None) -> list[LineString]:
|
||||
if geometry is None or geometry.is_empty:
|
||||
return []
|
||||
if isinstance(geometry, LineString):
|
||||
return [geometry] if geometry.length > 0 else []
|
||||
if isinstance(geometry, MultiLineString):
|
||||
return [part for part in geometry.geoms if part.length > 0]
|
||||
parts: list[LineString] = []
|
||||
for part in getattr(geometry, "geoms", []):
|
||||
parts.extend(_line_parts(part))
|
||||
return parts
|
||||
|
||||
|
||||
def _merged_lines(geometry: BaseGeometry | None) -> list[LineString]:
|
||||
parts = _line_parts(geometry)
|
||||
if not parts:
|
||||
return []
|
||||
merged = linemerge(MultiLineString(parts)) if len(parts) > 1 else parts[0]
|
||||
return _line_parts(merged)
|
||||
|
||||
|
||||
def country_geometries(admin0: dict[str, Any]) -> dict[str, BaseGeometry]:
|
||||
"""Dissolve policy-applied admin-0 features into one geometry per country."""
|
||||
grouped: dict[str, list[BaseGeometry]] = {}
|
||||
for feature in admin0.get("features") or []:
|
||||
geometry = feature.get("geometry")
|
||||
if not geometry:
|
||||
continue
|
||||
code = country_code(feature.get("properties") or {})
|
||||
if not code:
|
||||
continue
|
||||
geom = shape(geometry)
|
||||
if not geom.is_valid:
|
||||
geom = geom.buffer(0)
|
||||
grouped.setdefault(code, []).append(geom)
|
||||
return {
|
||||
code: parts[0] if len(parts) == 1 else unary_union(parts)
|
||||
for code, parts in grouped.items()
|
||||
}
|
||||
|
||||
|
||||
def derive_land_borders(countries: dict[str, BaseGeometry]) -> list[dict[str, Any]]:
|
||||
"""Return shared admin-0 edges only, so coasts never double the coastline layer."""
|
||||
codes = sorted(countries)
|
||||
geoms = [countries[code] for code in codes]
|
||||
boundaries = [geom.boundary for geom in geoms]
|
||||
tree = STRtree(geoms)
|
||||
features: list[dict[str, Any]] = []
|
||||
for left_index, left_code in enumerate(codes):
|
||||
for right_index in tree.query(geoms[left_index]):
|
||||
right_index = int(right_index)
|
||||
if right_index <= left_index:
|
||||
continue
|
||||
shared = boundaries[left_index].intersection(boundaries[right_index])
|
||||
for line in _merged_lines(shared):
|
||||
features.append(
|
||||
{
|
||||
"type": "Feature",
|
||||
"geometry": line,
|
||||
"properties": {"ADM0_L": left_code, "ADM0_R": codes[right_index]},
|
||||
}
|
||||
)
|
||||
return features
|
||||
|
||||
|
||||
def _endpoint_key(coord: Iterable[float]) -> tuple[float, float]:
|
||||
lon, lat = list(coord)[:2]
|
||||
return (round(lon, ENDPOINT_KEY_DIGITS), round(lat, ENDPOINT_KEY_DIGITS))
|
||||
|
||||
|
||||
def free_endpoints(features: list[dict[str, Any]]) -> set[tuple[float, float]]:
|
||||
"""Endpoints touched by a single line: coastal ends of a border network."""
|
||||
counts: Counter[tuple[float, float]] = Counter()
|
||||
for feature in features:
|
||||
line: LineString = feature["geometry"]
|
||||
coords = line.coords
|
||||
counts[_endpoint_key(coords[0])] += 1
|
||||
counts[_endpoint_key(coords[-1])] += 1
|
||||
return {key for key, count in counts.items() if count == 1}
|
||||
|
||||
|
||||
def iter_shapefile_lines(path: Path) -> Iterator[LineString]:
|
||||
with shapefile.Reader(str(path)) as reader:
|
||||
for shp in reader.iterShapes():
|
||||
if not shp.points or len(shp.points) < 2:
|
||||
continue
|
||||
parts = list(shp.parts) + [len(shp.points)]
|
||||
for start, end in zip(parts[:-1], parts[1:], strict=False):
|
||||
points = shp.points[start:end]
|
||||
if len(points) >= 2:
|
||||
yield LineString(points)
|
||||
|
||||
|
||||
def resolve_coastline_shapefile(source: Path, work_dir: Path) -> Path | None:
|
||||
"""Accept an OSM coastline zip, an extracted directory or a .shp file."""
|
||||
if source.suffix.lower() == ".shp":
|
||||
return source
|
||||
if source.is_dir():
|
||||
matches = sorted(source.rglob("lines.shp"))
|
||||
return matches[0] if matches else None
|
||||
if source.suffix.lower() == ".zip":
|
||||
target = work_dir / "coastline"
|
||||
target.mkdir(parents=True, exist_ok=True)
|
||||
with zipfile.ZipFile(source) as archive:
|
||||
for member in archive.namelist():
|
||||
name = Path(member).name
|
||||
if name.startswith("lines."):
|
||||
with archive.open(member) as src, (target / name).open("wb") as dst:
|
||||
while chunk := src.read(1024 * 1024):
|
||||
dst.write(chunk)
|
||||
shp = target / "lines.shp"
|
||||
return shp if shp.exists() else None
|
||||
return None
|
||||
|
||||
|
||||
def collect_coast_near(
|
||||
coast_lines: Iterable[LineString],
|
||||
endpoints: Iterable[tuple[float, float]],
|
||||
radius: float = SNAP_MAX_DEGREES,
|
||||
) -> list[LineString]:
|
||||
points = [Point(lon, lat).buffer(radius, quad_segs=2) for lon, lat in endpoints]
|
||||
if not points:
|
||||
return []
|
||||
endpoint_tree = STRtree(points)
|
||||
near: list[LineString] = []
|
||||
for line in coast_lines:
|
||||
if len(endpoint_tree.query(line)):
|
||||
near.append(line)
|
||||
return near
|
||||
|
||||
|
||||
def _cut_or_extend(
|
||||
line: LineString,
|
||||
at_start: bool,
|
||||
coast_tree: STRtree,
|
||||
coast: list[LineString],
|
||||
max_distance: float,
|
||||
) -> tuple[LineString, str]:
|
||||
coords = list(line.coords)
|
||||
end = Point(coords[0] if at_start else coords[-1])
|
||||
candidates = [coast[int(i)] for i in coast_tree.query(end.buffer(max_distance))]
|
||||
if not candidates:
|
||||
return line, "no_coast"
|
||||
nearby = unary_union(candidates)
|
||||
window = min(line.length, max_distance)
|
||||
tail = (
|
||||
substring(line, 0, window) if at_start else substring(line, line.length - window, line.length)
|
||||
)
|
||||
crossing = tail.intersection(nearby)
|
||||
crossing_points = [Point(c) for c in get_coordinates(crossing)] if not crossing.is_empty else []
|
||||
if crossing_points:
|
||||
# Keep the land part: cut at the crossing closest to the line end.
|
||||
distances = [line.project(point) for point in crossing_points]
|
||||
cut = min(distances) if at_start else max(distances)
|
||||
if at_start:
|
||||
trimmed = substring(line, cut, line.length)
|
||||
else:
|
||||
trimmed = substring(line, 0, cut)
|
||||
if isinstance(trimmed, LineString) and trimmed.length > 0:
|
||||
return trimmed, "trimmed"
|
||||
return line, "unchanged"
|
||||
target = nearest_points(end, nearby)[1]
|
||||
gap = end.distance(target)
|
||||
if gap == 0:
|
||||
return line, "unchanged"
|
||||
if gap > max_distance:
|
||||
return line, "gap_too_large"
|
||||
if at_start:
|
||||
return LineString([target.coords[0], *coords]), "extended"
|
||||
return LineString([*coords, target.coords[0]]), "extended"
|
||||
|
||||
|
||||
def snap_coastal_ends(
|
||||
features: list[dict[str, Any]],
|
||||
coast: list[LineString],
|
||||
free: set[tuple[float, float]],
|
||||
max_distance: float = SNAP_MAX_DEGREES,
|
||||
) -> Counter[str]:
|
||||
"""Trim or extend coastal border ends onto the OSM coastline in place."""
|
||||
stats: Counter[str] = Counter()
|
||||
if not coast:
|
||||
stats["no_coast_data"] = len(free)
|
||||
return stats
|
||||
coast_tree = STRtree(coast)
|
||||
for feature in features:
|
||||
line: LineString = feature["geometry"]
|
||||
for at_start in (True, False):
|
||||
coord = line.coords[0] if at_start else line.coords[-1]
|
||||
if _endpoint_key(coord) not in free:
|
||||
continue
|
||||
line, outcome = _cut_or_extend(line, at_start, coast_tree, coast, max_distance)
|
||||
stats[outcome] += 1
|
||||
feature["geometry"] = line
|
||||
return stats
|
||||
|
||||
|
||||
def china_clip_geometry(countries: dict[str, BaseGeometry]) -> BaseGeometry | None:
|
||||
china = countries.get(CHINA_ADMIN0_CODE)
|
||||
if china is None:
|
||||
return None
|
||||
# Shrink slightly so lines on the shared border survive the clip.
|
||||
return china.buffer(-CHINA_CLIP_BUFFER_DEGREES)
|
||||
|
||||
|
||||
def _clip_outside(geometry: BaseGeometry, clip: BaseGeometry | None) -> list[LineString]:
|
||||
if clip is None or not geometry.intersects(clip):
|
||||
return _line_parts(geometry)
|
||||
return _line_parts(geometry.difference(clip))
|
||||
|
||||
|
||||
def admin1_lines(collection: dict[str, Any], china_clip: BaseGeometry | None) -> list[dict[str, Any]]:
|
||||
"""China POV admin-1 lines: no unrecognized lines and no foreign lines inside China."""
|
||||
features: list[dict[str, Any]] = []
|
||||
for feature in collection.get("features") or []:
|
||||
geometry = feature.get("geometry")
|
||||
if not geometry:
|
||||
continue
|
||||
props = feature.get("properties") or {}
|
||||
code = country_code(props)
|
||||
if code in ABSORBED_ADMIN1_CODES:
|
||||
continue
|
||||
if str(props.get("FCLASS_CN") or "").startswith("Unrecognized"):
|
||||
continue
|
||||
geom = shape(geometry)
|
||||
parts = _line_parts(geom) if code == CHINA_ADMIN0_CODE else _clip_outside(geom, china_clip)
|
||||
for part in parts:
|
||||
features.append(
|
||||
{
|
||||
"type": "Feature",
|
||||
"geometry": part,
|
||||
"properties": {"ADM0_A3": code, "minzoom": 4},
|
||||
}
|
||||
)
|
||||
return features
|
||||
|
||||
|
||||
def disputed_lines(collection: dict[str, Any], china_clip: BaseGeometry | None) -> list[dict[str, Any]]:
|
||||
"""Keep disputed lines outside China; China POV has no internal disputed lines."""
|
||||
features: list[dict[str, Any]] = []
|
||||
for feature in collection.get("features") or []:
|
||||
geometry = feature.get("geometry")
|
||||
if not geometry:
|
||||
continue
|
||||
props = feature.get("properties") or {}
|
||||
if props.get("PLANET_LAYER") == "claim_line":
|
||||
continue
|
||||
for part in _clip_outside(shape(geometry), china_clip):
|
||||
features.append(
|
||||
{
|
||||
"type": "Feature",
|
||||
"geometry": part,
|
||||
"properties": {"FEATURECLA": props.get("FEATURECLA"), "NAME": props.get("NAME")},
|
||||
}
|
||||
)
|
||||
return features
|
||||
|
||||
|
||||
def hover_index(
|
||||
admin0: dict[str, Any],
|
||||
countries: dict[str, BaseGeometry],
|
||||
tolerance: float,
|
||||
) -> dict[str, Any]:
|
||||
"""One dissolved, simplified polygon per country for picking and hover fill."""
|
||||
properties_by_code: dict[str, dict[str, Any]] = {}
|
||||
rules_by_code: dict[str, set[str]] = {}
|
||||
for feature in admin0.get("features") or []:
|
||||
props = feature.get("properties") or {}
|
||||
code = country_code(props)
|
||||
if not code:
|
||||
continue
|
||||
if props.get("PLANET_POLICY_RULE"):
|
||||
rules_by_code.setdefault(code, set()).add(str(props["PLANET_POLICY_RULE"]))
|
||||
# Prefer the source feature that is not a policy-absorbed region.
|
||||
current = properties_by_code.get(code)
|
||||
if current is None or (current.get("PLANET_POLICY_RULE") and not props.get("PLANET_POLICY_RULE")):
|
||||
properties_by_code[code] = props
|
||||
keep = (
|
||||
"ISO_A3", "ADM0_A3", "ISO_A2", "NAME", "NAME_EN", "NAME_ZH", "ADMIN", "CONTINENT",
|
||||
)
|
||||
features = []
|
||||
for code in sorted(countries):
|
||||
simplified = countries[code].simplify(tolerance, preserve_topology=True)
|
||||
if simplified.is_empty:
|
||||
continue
|
||||
source = properties_by_code.get(code, {})
|
||||
props = {key: source[key] for key in keep if source.get(key) not in (None, "")}
|
||||
if code in rules_by_code:
|
||||
# Dissolved polygons keep the list of display-policy rules they absorbed.
|
||||
props["PLANET_POLICY_RULES"] = sorted(rules_by_code[code])
|
||||
features.append({"type": "Feature", "properties": props, "geometry": rounded_mapping(simplified, 4)})
|
||||
return {"type": "FeatureCollection", "features": features}
|
||||
|
||||
|
||||
def hover_borders(borders: list[dict[str, Any]], tolerance: float) -> dict[str, Any]:
|
||||
features = []
|
||||
for feature in borders:
|
||||
simplified = feature["geometry"].simplify(tolerance, preserve_topology=False)
|
||||
if simplified.is_empty or simplified.length == 0:
|
||||
continue
|
||||
features.append(
|
||||
{
|
||||
"type": "Feature",
|
||||
"properties": dict(feature["properties"]),
|
||||
"geometry": rounded_mapping(simplified, 4),
|
||||
}
|
||||
)
|
||||
return {"type": "FeatureCollection", "features": features}
|
||||
|
||||
|
||||
def _round_coords(value: Any, digits: int) -> Any:
|
||||
if isinstance(value, (list, tuple)):
|
||||
if value and isinstance(value[0], (int, float)):
|
||||
return [round(float(v), digits) for v in value[:2]]
|
||||
return [_round_coords(item, digits) for item in value]
|
||||
return value
|
||||
|
||||
|
||||
def rounded_mapping(geometry: BaseGeometry, digits: int = 5) -> dict[str, Any]:
|
||||
geojson = mapping(geometry)
|
||||
return {"type": geojson["type"], "coordinates": _round_coords(geojson["coordinates"], digits)}
|
||||
|
||||
|
||||
def _polygon_parts(geometry: BaseGeometry | None) -> list[Polygon]:
|
||||
if geometry is None or geometry.is_empty:
|
||||
return []
|
||||
if isinstance(geometry, Polygon):
|
||||
return [geometry] if geometry.area > 0 else []
|
||||
parts: list[Polygon] = []
|
||||
for geom in getattr(geometry, "geoms", []):
|
||||
parts.extend(_polygon_parts(geom))
|
||||
return parts
|
||||
|
||||
|
||||
class CoastlineCountryAssigner:
|
||||
"""Assign policy-normalized `ADM0_A3` codes to OSM coastline segments."""
|
||||
|
||||
SEARCH_RADIUS_DEGREES = 0.08
|
||||
FALLBACK_RADIUS_DEGREES = 0.25
|
||||
MIN_SPLIT_LENGTH = 0.05
|
||||
MAX_SPLIT_DEPTH = 5
|
||||
|
||||
def __init__(self, countries: dict[str, BaseGeometry], tolerance: float = 0.005) -> None:
|
||||
self.polys: list[Polygon] = []
|
||||
self.codes: list[str] = []
|
||||
for code in sorted(countries):
|
||||
for poly in _polygon_parts(countries[code]):
|
||||
simplified = poly.simplify(tolerance, preserve_topology=False) if tolerance > 0 else poly
|
||||
candidate = simplified if isinstance(simplified, Polygon) and not simplified.is_empty else poly
|
||||
if not candidate.is_valid:
|
||||
candidate = candidate.buffer(0)
|
||||
for clean in _polygon_parts(candidate):
|
||||
prepare(clean)
|
||||
self.polys.append(clean)
|
||||
self.codes.append(code)
|
||||
self.tree = STRtree(self.polys) if self.polys else None
|
||||
|
||||
def _nearest_code(self, point: Point, candidate_indices: Iterable[int]) -> str | None:
|
||||
for raw_idx in candidate_indices:
|
||||
idx = int(raw_idx)
|
||||
if self.polys[idx].contains(point):
|
||||
return self.codes[idx]
|
||||
best_code: str | None = None
|
||||
best_dist = math.inf
|
||||
for raw_idx in candidate_indices:
|
||||
idx = int(raw_idx)
|
||||
dist = self.polys[idx].distance(point)
|
||||
if dist < best_dist:
|
||||
best_dist = dist
|
||||
best_code = self.codes[idx]
|
||||
return best_code
|
||||
|
||||
def _assign_segment(
|
||||
self,
|
||||
line: LineString,
|
||||
candidate_indices: list[int],
|
||||
depth: int,
|
||||
) -> list[tuple[LineString, str | None]]:
|
||||
coords = line.coords
|
||||
if len(coords) < 2 or line.length <= 0:
|
||||
return []
|
||||
start_code = self._nearest_code(Point(coords[0]), candidate_indices)
|
||||
mid_code = self._nearest_code(line.interpolate(0.5, normalized=True), candidate_indices)
|
||||
end_code = self._nearest_code(Point(coords[-1]), candidate_indices)
|
||||
if start_code == mid_code == end_code:
|
||||
return [(line, mid_code)]
|
||||
if depth < self.MAX_SPLIT_DEPTH and line.length > self.MIN_SPLIT_LENGTH:
|
||||
half = line.length * 0.5
|
||||
left = substring(line, 0.0, half)
|
||||
right = substring(line, half, line.length)
|
||||
out: list[tuple[LineString, str | None]] = []
|
||||
for part in (*_line_parts(left), *_line_parts(right)):
|
||||
out.extend(self._assign_segment(part, candidate_indices, depth + 1))
|
||||
return out
|
||||
return [(line, mid_code or start_code or end_code)]
|
||||
|
||||
def assign(self, line: LineString) -> list[tuple[LineString, str | None]]:
|
||||
if self.tree is None or line.is_empty or line.length <= 0:
|
||||
return [(line, None)] if not line.is_empty else []
|
||||
minx, miny, maxx, maxy = line.bounds
|
||||
pad = self.SEARCH_RADIUS_DEGREES
|
||||
candidates = self.tree.query(box(minx - pad, miny - pad, maxx + pad, maxy + pad))
|
||||
if len(candidates) == 0:
|
||||
pad = self.FALLBACK_RADIUS_DEGREES
|
||||
candidates = self.tree.query(box(minx - pad, miny - pad, maxx + pad, maxy + pad))
|
||||
if len(candidates) == 0:
|
||||
return [(line, None)]
|
||||
cand_list = [int(i) for i in candidates]
|
||||
distinct_codes = {self.codes[idx] for idx in cand_list}
|
||||
if len(distinct_codes) == 1:
|
||||
return [(line, next(iter(distinct_codes)))]
|
||||
|
||||
raw_segments = self._assign_segment(line, cand_list, 0)
|
||||
if len(raw_segments) <= 1:
|
||||
return raw_segments
|
||||
|
||||
merged: list[tuple[LineString, str | None]] = []
|
||||
for seg, code in raw_segments:
|
||||
if (
|
||||
merged
|
||||
and merged[-1][1] == code
|
||||
and merged[-1][0].coords[-1] == seg.coords[0]
|
||||
):
|
||||
merged[-1] = (LineString([*merged[-1][0].coords, *seg.coords[1:]]), code)
|
||||
else:
|
||||
merged.append((seg, code))
|
||||
return merged
|
||||
|
||||
|
||||
def geojson_feature(
|
||||
feature: dict[str, Any],
|
||||
layer: str,
|
||||
min_zoom: int | None = None,
|
||||
max_zoom: int | None = None,
|
||||
) -> dict[str, Any]:
|
||||
geometry = feature["geometry"]
|
||||
if isinstance(geometry, BaseGeometry):
|
||||
geometry = rounded_mapping(geometry, 7)
|
||||
props = {k: v for k, v in (feature.get("properties") or {}).items() if k != "minzoom" and v is not None}
|
||||
tippecanoe: dict[str, Any] = {"layer": layer}
|
||||
if min_zoom is not None:
|
||||
tippecanoe["minzoom"] = min_zoom
|
||||
if max_zoom is not None:
|
||||
tippecanoe["maxzoom"] = max_zoom
|
||||
return {"type": "Feature", "tippecanoe": tippecanoe, "properties": props, "geometry": geometry}
|
||||
|
||||
|
||||
_SKIP_SETTLEMENT_CLASSES = {
|
||||
"Scientific station",
|
||||
"Historic place",
|
||||
"Meteorological Station",
|
||||
}
|
||||
_ADMIN1_SETTLEMENT_CLASSES = {
|
||||
"Admin-1 capital",
|
||||
"Admin-1 region capital",
|
||||
"Admin-0 region capital",
|
||||
}
|
||||
|
||||
|
||||
def _clean_label_text(value: Any) -> str:
|
||||
if value is None:
|
||||
return ""
|
||||
return " ".join(str(value).split())
|
||||
|
||||
|
||||
def build_geo_labels(
|
||||
places_geojson: dict[str, Any],
|
||||
*,
|
||||
policy: dict[str, Any] | None = None,
|
||||
china_clip: BaseGeometry | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Build China-POV filtered, 3-tier global city labels payload."""
|
||||
prepared_clip = china_clip
|
||||
if prepared_clip is not None and not prepared_clip.is_empty:
|
||||
prepare(prepared_clip)
|
||||
|
||||
dedup: dict[tuple[str, str, float, float], dict[str, Any]] = {}
|
||||
for feature in places_geojson.get("features") or []:
|
||||
geometry = feature.get("geometry") or {}
|
||||
if geometry.get("type") != "Point":
|
||||
continue
|
||||
coords = geometry.get("coordinates") or []
|
||||
if len(coords) < 2:
|
||||
continue
|
||||
lon = float(coords[0])
|
||||
lat = float(coords[1])
|
||||
if not (-180.0 <= lon <= 180.0 and -90.0 <= lat <= 90.0):
|
||||
continue
|
||||
|
||||
props = feature.get("properties") or {}
|
||||
fclass = _clean_label_text(props.get("FCLASS_CN") or props.get("FEATURECLA") or "")
|
||||
if fclass in _SKIP_SETTLEMENT_CLASSES:
|
||||
continue
|
||||
|
||||
raw_adm0 = str(props.get("ADM0_A3") or "").strip().upper()
|
||||
raw_sov = str(props.get("SOV_A3") or "").strip().upper()
|
||||
raw_iso = str(props.get("ISO_A3") or "").strip().upper()
|
||||
iso = raw_adm0 or raw_sov or raw_iso or ""
|
||||
|
||||
demoted_from_admin0 = False
|
||||
if iso in ABSORBED_ADMIN1_CODES:
|
||||
iso = CHINA_ADMIN0_CODE
|
||||
demoted_from_admin0 = True
|
||||
elif iso in {"KOS", "XKS"}:
|
||||
iso = "SRB"
|
||||
demoted_from_admin0 = True
|
||||
elif iso == "SOL":
|
||||
iso = "SOM"
|
||||
demoted_from_admin0 = True
|
||||
|
||||
was_admin0 = fclass in {"Admin-0 capital", "Admin-0 capital alt"}
|
||||
if demoted_from_admin0 and was_admin0:
|
||||
fclass = "Admin-1 capital"
|
||||
|
||||
if (
|
||||
prepared_clip is not None
|
||||
and not prepared_clip.is_empty
|
||||
and iso != CHINA_ADMIN0_CODE
|
||||
and prepared_clip.contains(Point(lon, lat))
|
||||
):
|
||||
continue
|
||||
|
||||
sr = int(props.get("SCALERANK") if props.get("SCALERANK") is not None else 10)
|
||||
pop = int(props.get("POP_MAX") or 0)
|
||||
wc = int(props.get("WORLDCITY") or 0)
|
||||
|
||||
if fclass == "Admin-0 capital":
|
||||
tier = 1
|
||||
kind = "capital"
|
||||
elif sr <= 1 or (wc == 1 and pop >= 3_500_000):
|
||||
tier = 1
|
||||
kind = "admin1" if demoted_from_admin0 else "megacity"
|
||||
elif sr <= 4 or pop >= 1_000_000 or fclass in {"Admin-0 region capital", "Admin-0 capital alt"} or (demoted_from_admin0 and was_admin0):
|
||||
tier = 2
|
||||
kind = "admin1" if (demoted_from_admin0 or fclass in _ADMIN1_SETTLEMENT_CLASSES) else "major"
|
||||
elif fclass in {"Admin-1 capital", "Admin-1 region capital"} and (sr <= 7 or pop >= 100_000):
|
||||
tier = 3
|
||||
kind = "admin1"
|
||||
else:
|
||||
continue
|
||||
|
||||
en = _clean_label_text(props.get("NAME_EN") or props.get("NAME") or props.get("NAMEASCII"))
|
||||
zh = _clean_label_text(props.get("NAME_ZH") or props.get("NAME_ZHT") or en)
|
||||
if not en and not zh:
|
||||
continue
|
||||
|
||||
item = {
|
||||
"zh": zh or en,
|
||||
"en": en or zh,
|
||||
"lat": round(lat, 4),
|
||||
"lon": round(lon, 4),
|
||||
"t": tier,
|
||||
"k": kind,
|
||||
"iso": iso,
|
||||
"sr": sr,
|
||||
"pop": pop,
|
||||
}
|
||||
dedup_key = (iso, (en or zh).lower(), round(lat, 2), round(lon, 2))
|
||||
prev = dedup.get(dedup_key)
|
||||
if prev is None or (item["t"], item["sr"], -item["pop"]) < (prev["t"], prev["sr"], -prev["pop"]):
|
||||
dedup[dedup_key] = item
|
||||
|
||||
kind_rank = {"capital": 0, "megacity": 1, "major": 2, "admin1": 3}
|
||||
places = sorted(
|
||||
dedup.values(),
|
||||
key=lambda item: (item["t"], kind_rank.get(item["k"], 4), item["sr"], -item["pop"], item["en"]),
|
||||
)
|
||||
tier_counts = Counter(item["t"] for item in places)
|
||||
profile = (policy or {}).get("profile") or "china-pov-v1"
|
||||
return {
|
||||
"schema": "planet-earth-geo-labels/v1",
|
||||
"version": profile,
|
||||
"counts": {
|
||||
"total": len(places),
|
||||
"tier1": tier_counts[1],
|
||||
"tier2": tier_counts[2],
|
||||
"tier3": tier_counts[3],
|
||||
},
|
||||
"places": places,
|
||||
}
|
||||
@@ -12,6 +12,11 @@ main() {
|
||||
|
||||
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python - <<'PY'
|
||||
import ast
|
||||
import importlib
|
||||
import inspect
|
||||
import os
|
||||
import pkgutil
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
root = Path.cwd()
|
||||
@@ -48,6 +53,70 @@ for path in sorted((root / "backend/app").rglob("*.py")):
|
||||
continue
|
||||
BackendDebugCallVisitor(rel).visit(tree)
|
||||
|
||||
if not failures:
|
||||
# Verify ASGI app and every collector can be imported and instantiated offline.
|
||||
os.environ["DATABASE_URL"] = "postgresql+asyncpg://check:check@127.0.0.1:1/check"
|
||||
os.environ["REDIS_URL"] = "redis://127.0.0.1:1/0"
|
||||
backend_dir = str(root / "backend")
|
||||
if backend_dir not in sys.path:
|
||||
sys.path.insert(0, backend_dir)
|
||||
|
||||
try:
|
||||
import app.main # noqa: F401
|
||||
import app.services.collectors as collectors_pkg
|
||||
from app.services.collectors import (
|
||||
BaseCollector,
|
||||
HTTPCollector,
|
||||
IntervalCollector,
|
||||
collector_registry,
|
||||
)
|
||||
from app.services.collectors.compute_base import ComputeCollector
|
||||
except Exception as exc:
|
||||
fail(f"backend/app/main.py: failed offline ASGI import: {type(exc).__name__}: {exc}")
|
||||
else:
|
||||
abstract_bases = (BaseCollector, HTTPCollector, IntervalCollector, ComputeCollector)
|
||||
for mod in pkgutil.iter_modules(collectors_pkg.__path__, collectors_pkg.__name__ + "."):
|
||||
try:
|
||||
module = importlib.import_module(mod.name)
|
||||
except Exception as exc:
|
||||
fail(f"{mod.name}: failed to import collector module: {type(exc).__name__}: {exc}")
|
||||
continue
|
||||
for attr_name, obj in inspect.getmembers(module, inspect.isclass):
|
||||
if obj.__module__ != mod.name or not issubclass(obj, BaseCollector):
|
||||
continue
|
||||
if obj in abstract_bases or attr_name.startswith("_"):
|
||||
continue
|
||||
if inspect.isabstract(obj):
|
||||
fail(
|
||||
f"{mod.name}.{attr_name}: abstract methods unimplemented: "
|
||||
f"{sorted(obj.__abstractmethods__)}"
|
||||
)
|
||||
continue
|
||||
try:
|
||||
inst = obj()
|
||||
except Exception as exc:
|
||||
fail(f"{mod.name}.{attr_name}: zero-arg init failed: {type(exc).__name__}: {exc}")
|
||||
continue
|
||||
if not str(getattr(inst, "name", "") or "").strip():
|
||||
fail(f"{mod.name}.{attr_name}: collector name must be non-empty")
|
||||
if not callable(getattr(inst, "fetch", None)):
|
||||
fail(f"{mod.name}.{attr_name}: collector missing callable fetch()")
|
||||
run_fn = getattr(inst, "run", None)
|
||||
if not callable(run_fn) or "db" not in inspect.signature(run_fn).parameters:
|
||||
fail(f"{mod.name}.{attr_name}: collector run() must accept 'db'")
|
||||
|
||||
for key, col in sorted(collector_registry.all().items()):
|
||||
if not isinstance(col, BaseCollector):
|
||||
fail(f"collector_registry[{key!r}]: not a BaseCollector instance")
|
||||
continue
|
||||
if col.name != key:
|
||||
fail(f"collector_registry[{key!r}]: registered key != collector.name ({col.name!r})")
|
||||
if not callable(getattr(col, "fetch", None)):
|
||||
fail(f"collector_registry[{key!r}]: missing callable fetch()")
|
||||
run_fn = getattr(col, "run", None)
|
||||
if not callable(run_fn) or "db" not in inspect.signature(run_fn).parameters:
|
||||
fail(f"collector_registry[{key!r}]: run() must accept 'db'")
|
||||
|
||||
if failures:
|
||||
for message in failures:
|
||||
print(f"fail: {message}")
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env bun
|
||||
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'
|
||||
import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { dirname, join, resolve } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
@@ -86,7 +86,14 @@ function checkAdminBuildSeparation() {
|
||||
assert(existsSync(join(adminOutDir, 'favicon.ico')), 'admin build output missing favicon.ico')
|
||||
assert(existsSync(join(adminOutDir, 'favicon.png')), 'admin build output missing favicon.png')
|
||||
assert(!existsSync(join(adminOutDir, 'earth')), 'admin build output must exclude public/earth assets')
|
||||
console.log('ok: frontend admin target excludes public/earth assets and includes favicons')
|
||||
const assetFiles = readdirSync(join(adminOutDir, 'assets'))
|
||||
for (const prefix of ['earth-logo-', 'title-zh-', 'title-en-', 'lim-logo-', 'earth_clouds_2048-']) {
|
||||
assert(
|
||||
assetFiles.some((file) => file.startsWith(prefix) && file.endsWith('.png')),
|
||||
`admin build output missing bundled preview asset ${prefix}*.png in assets/`,
|
||||
)
|
||||
}
|
||||
console.log('ok: frontend admin target excludes public/earth assets and bundles admin preview assets')
|
||||
} finally {
|
||||
rmSync(adminOutDir, { recursive: true, force: true })
|
||||
}
|
||||
@@ -159,10 +166,9 @@ function checkElectronHeadlessSmoke() {
|
||||
)
|
||||
assert(report.splashCheck?.mounted === true, 'expected desktop splash Shadow DOM host to mount on replay')
|
||||
assert(
|
||||
report.splashCheck?.hasPresenterZh === true &&
|
||||
report.splashCheck?.hasPresenterEn === true &&
|
||||
report.splashCheck?.hasPresentedBy === true,
|
||||
`expected presenter lockup texts on splash, got ${JSON.stringify(report.splashCheck)}`,
|
||||
report.splashCheck?.hasPresentedBy === true &&
|
||||
(report.splashCheck?.hasPresenterZh === true || report.splashCheck?.hasPresenterEn === true),
|
||||
`expected localized presenter lockup texts on splash, got ${JSON.stringify(report.splashCheck)}`,
|
||||
)
|
||||
assert(
|
||||
report.splashCheck?.emblemLoaded === true && report.splashCheck?.emblemWidth === 283,
|
||||
|
||||
@@ -96,6 +96,8 @@ main() {
|
||||
|
||||
check_optional_cmd docker "needed for local stack and optional image smoke builds"
|
||||
check_optional_cmd helm "needed for optional Helm delivery smoke checks"
|
||||
check_optional_cmd tippecanoe "needed for local Earth boundary PMTiles rebuilds (run scripts/harness/install-earth-boundary-tools.sh)"
|
||||
check_optional_cmd pmtiles "optional PMTiles CLI for inspecting built boundary archives"
|
||||
|
||||
check_absent frontend/package-lock.json "frontend package management is Bun-only"
|
||||
check_absent frontend/pnpm-lock.yaml "frontend package management is Bun-only"
|
||||
|
||||
@@ -764,6 +764,21 @@ def check_admin_control_design_contract() -> None:
|
||||
"for column-level alignment rules"
|
||||
)
|
||||
|
||||
table_action_block = css_block_for_selector(
|
||||
admin_css,
|
||||
".an-table-actions .tui-button--icon.tui-button--tactile",
|
||||
)
|
||||
if (
|
||||
table_action_block is None
|
||||
or not css_has_declaration(table_action_block[1], "width", r"(?:var\(--an-control-xs\)|28px)")
|
||||
or not css_has_declaration(table_action_block[1], "height", r"(?:var\(--an-control-xs\)|28px)")
|
||||
or not css_has_declaration(table_action_block[1], "box-shadow", r"none")
|
||||
):
|
||||
fail(
|
||||
"frontend/src/admin/styles.css: .an-table-actions .tui-button--icon.tui-button--tactile must lock "
|
||||
"width/height to var(--an-control-xs) and box-shadow: none so table row actions stay uniform"
|
||||
)
|
||||
|
||||
|
||||
def check_uiux_static_warnings() -> None:
|
||||
viewport_font_pattern = re.compile(r"\b(?:font-size|fontSize)\s*[:=]\s*[^;\n}]*(?:vw|vmin|vmax|cqw|cqi)")
|
||||
|
||||
@@ -69,6 +69,7 @@ const interactionChecks = [
|
||||
'logs raw tab',
|
||||
'users add dialog',
|
||||
'data distribution toggle',
|
||||
'data ledger compute',
|
||||
'earth i18n settings',
|
||||
'earth card limit controls independent',
|
||||
'earth manual news refresh lifecycle',
|
||||
@@ -1014,10 +1015,102 @@ function apiPayloadFor(requestUrl, method) {
|
||||
}
|
||||
|
||||
if (path === '/collected') return jsonResponse({ data: [], total: 0 })
|
||||
if (path === '/collected/summary') return jsonResponse({ total: 0, source_totals: [], type_totals: [], country_totals: [] })
|
||||
if (path === '/collected/summary') return jsonResponse({ total: 0, overall_total_records: 0, by_source: {}, source_totals: [{ source: 'open_bgp', source_name: 'Open BGP', count: 12 }], type_totals: [{ data_type: 'bgp_event', count: 12 }] })
|
||||
if (path === '/collected/sources') return jsonResponse({ sources: [{ source: 'open_bgp', source_name: 'Open BGP' }] })
|
||||
if (path === '/collected/types') return jsonResponse({ data_types: ['bgp_event'] })
|
||||
if (path === '/collected/countries') return jsonResponse({ countries: ['CN'] })
|
||||
if (path === '/data-ledger/layers') {
|
||||
return jsonResponse({
|
||||
layers: [
|
||||
{ id: 'compute', name: '算力', count: 2, kinds: [] },
|
||||
{ id: 'satellites', name: '卫星', count: 1, kinds: [] },
|
||||
{ id: 'cables', name: '海底光缆', count: 1, kinds: [{ id: 'submarine_cable', label: '海缆系统' }] },
|
||||
{ id: 'vessels', name: '船只', count: 1, kinds: [] },
|
||||
{ id: 'bgp', name: 'BGP', count: 1, kinds: [{ id: 'collectors', label: '观测站' }, { id: 'incidents', label: 'BGP 事件' }] },
|
||||
{ id: 'news', name: '新闻与直播', count: 1, kinds: [{ id: 'items', label: '新闻条目' }, { id: 'live_streams', label: 'Live 直播源' }] },
|
||||
{ id: 'weather', name: '气象', count: 1, kinds: [] },
|
||||
{ id: 'geo', name: '地理/底图', count: 1, kinds: [] },
|
||||
{ id: 'raw', name: '原始采集记录', count: 12, kinds: [] },
|
||||
],
|
||||
})
|
||||
}
|
||||
if (path === '/data-ledger/compute-centers') {
|
||||
const requestedType = url.searchParams.get('site_type') || ''
|
||||
const allItems = [
|
||||
{
|
||||
id: 101,
|
||||
source: 'top500',
|
||||
source_id: 'top500_frontier',
|
||||
name: 'Frontier',
|
||||
site_type: 'supercomputer',
|
||||
operator: 'ORNL',
|
||||
country: '美国',
|
||||
city: 'Oak Ridge',
|
||||
latitude: 35.93,
|
||||
longitude: -84.31,
|
||||
precision: 'site',
|
||||
confidence: 0.95,
|
||||
verification_status: 'verified',
|
||||
status_bucket: 'located',
|
||||
terminal_status: null,
|
||||
location_source: 'official_facility_registry',
|
||||
source_url: 'https://ornl.gov',
|
||||
source_note: '橡树岭国家实验室官方地址确认。',
|
||||
workflow_run_id: null,
|
||||
updated_at: '2026-12-03T12:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 102,
|
||||
source: 'epoch_ai_gpu',
|
||||
source_id: 'epoch_ibm_dyeus',
|
||||
name: 'IBM DYEUS',
|
||||
site_type: 'gpu_cluster',
|
||||
operator: 'IBM',
|
||||
country: '美国',
|
||||
city: null,
|
||||
latitude: null,
|
||||
longitude: null,
|
||||
precision: 'unknown',
|
||||
confidence: 0.0,
|
||||
verification_status: 'undisclosed',
|
||||
status_bucket: 'terminal',
|
||||
terminal_status: 'undisclosed',
|
||||
location_source: 'agent_terminal_undisclosed',
|
||||
source_url: null,
|
||||
source_note: '官方材料未披露物理 部署城市。',
|
||||
workflow_run_id: 'run_smoke_dyeus',
|
||||
updated_at: '2026-12-03T12:00:00Z',
|
||||
},
|
||||
]
|
||||
const items = requestedType ? allItems.filter((item) => item.site_type === requestedType) : allItems
|
||||
return jsonResponse({
|
||||
items,
|
||||
total: items.length,
|
||||
page: 1,
|
||||
page_size: 20,
|
||||
counts: {
|
||||
total: allItems.length,
|
||||
by_site_type: { supercomputer: 1, gpu_cluster: 1, data_center: 0, cloud_center: 0, edge_node: 0 },
|
||||
by_status: { located: 1, needs_confirmation: 0, terminal: 1, pending: 0 },
|
||||
},
|
||||
countries: ['美国'],
|
||||
})
|
||||
}
|
||||
if (/^\/data-ledger\/[^/]+\/items$/.test(path)) {
|
||||
return jsonResponse({
|
||||
layer: 'vessels',
|
||||
kind: 'all',
|
||||
kinds: [],
|
||||
columns: [
|
||||
{ key: 'name', label: '船名' },
|
||||
{ key: 'mmsi', label: 'MMSI' },
|
||||
],
|
||||
rows: [{ id: '1', name: 'Smoke Vessel', mmsi: '413000001' }],
|
||||
total: 1,
|
||||
page: 1,
|
||||
page_size: 20,
|
||||
})
|
||||
}
|
||||
|
||||
const datasourceToggle = method === 'POST' ? path.match(/^\/datasources\/(\d+)\/(enable|disable)$/) : null
|
||||
if (datasourceToggle) {
|
||||
@@ -1034,9 +1127,84 @@ function apiPayloadFor(requestUrl, method) {
|
||||
if (method === 'POST' && path === '/datasources/batch-status') {
|
||||
return jsonResponse({ is_active: true, updated: [], unchanged: [], not_found: [], sync_failed: [], counts: datasourceCounts })
|
||||
}
|
||||
if (path === '/datasources') return jsonResponse({ total: 2, data: [datasource, disabledDatasource], counts: datasourceCounts })
|
||||
if (path === '/datasources') {
|
||||
if (url.searchParams.get('product') === 'geo') {
|
||||
return jsonResponse({
|
||||
total: 1,
|
||||
data: [
|
||||
{
|
||||
...datasource,
|
||||
id: 36,
|
||||
source_id: 'earth_imagery_sentinel2',
|
||||
name: 'earth_imagery_sentinel2',
|
||||
display_name: 'Sentinel-2 无云高分底图',
|
||||
module: 'L1',
|
||||
source: 'earth_imagery_sentinel2',
|
||||
product: 'geo',
|
||||
},
|
||||
],
|
||||
counts: { all: 1, active: 1, inactive: 0 },
|
||||
})
|
||||
}
|
||||
return jsonResponse({ total: 2, data: [datasource, disabledDatasource], counts: datasourceCounts })
|
||||
}
|
||||
if (path === '/datasources/configs') return jsonResponse([datasource])
|
||||
if (path === '/datasources/configs/all') return jsonResponse([datasource])
|
||||
if (path === '/datasources/configs/all') return jsonResponse([
|
||||
{ ...datasource, product: 'bgp' },
|
||||
{
|
||||
...datasource,
|
||||
id: 34,
|
||||
name: 'global_cloud_map',
|
||||
display_name: '全球卫星红外云图',
|
||||
source: 'global_cloud_map',
|
||||
product: 'weather',
|
||||
source_type: 'http',
|
||||
endpoint: 'https://gibs.earthdata.nasa.gov/wms/epsg4326/best/wms.cgi',
|
||||
config: { primary_source: 'multi_sat_ir', resolution: '2048x1024' },
|
||||
},
|
||||
{
|
||||
...datasource,
|
||||
id: 36,
|
||||
name: 'earth_imagery_sentinel2',
|
||||
display_name: 'Sentinel-2 无云高分底图',
|
||||
source: 'earth_imagery_sentinel2',
|
||||
product: 'geo',
|
||||
source_type: 'http',
|
||||
endpoint: 'https://tiles.maps.eox.at/wmts/1.0.0/s2cloudless-2024_3857/default/GoogleMapsCompatible/{z}/{y}/{x}.jpg',
|
||||
config: { warmup_max_zoom: 3, max_zoom: 10 },
|
||||
},
|
||||
])
|
||||
const productStatusMatch = path.match(/^\/data-products\/([a-z_]+)\/status$/)
|
||||
if (productStatusMatch) {
|
||||
const productId = productStatusMatch[1]
|
||||
return jsonResponse({
|
||||
product_id: productId,
|
||||
name: productId,
|
||||
total_count: 1,
|
||||
has_data: true,
|
||||
total_collector_count: productId === 'weather' ? 3 : 1,
|
||||
active_collector_count: productId === 'weather' ? 3 : 1,
|
||||
running_collector_count: 0,
|
||||
datasources_url: `/datasources?product=${productId}`,
|
||||
stats: productId === 'weather' ? { wind_available_flag: 1 } : {},
|
||||
build_state: 'ready',
|
||||
})
|
||||
}
|
||||
if (path === '/data-products') {
|
||||
return jsonResponse({
|
||||
generated_at: now,
|
||||
data: ['vessels', 'cables', 'satellites', 'bgp', 'compute', 'weather', 'geo'].map((productId) => ({
|
||||
product_id: productId,
|
||||
name: productId,
|
||||
total_count: 1,
|
||||
has_data: true,
|
||||
total_collector_count: productId === 'weather' ? 3 : 1,
|
||||
active_collector_count: productId === 'weather' ? 3 : 1,
|
||||
running_collector_count: 0,
|
||||
datasources_url: `/datasources?product=${productId}`,
|
||||
})),
|
||||
})
|
||||
}
|
||||
if (path === '/datasources/mappings') return jsonResponse({ mappings: [{ id: 1, name: 'Default Mapping', target_schema: 'collected_data', validation_status: 'valid' }] })
|
||||
if (path === '/datasources/target-schemas') return jsonResponse({ schemas: [{ id: 'collected_data', name: 'collected_data', status: 'active' }] })
|
||||
if (path === '/datasources/snapshots') return jsonResponse({ data: [{ id: 1, source: 'open_bgp', status: 'completed', record_count: 12, is_current: true, completed_at: now }] })
|
||||
@@ -1179,7 +1347,233 @@ function apiPayloadFor(requestUrl, method) {
|
||||
return jsonResponse({ id: 'run_smoke_1', workflow_id: 'default.general', status: 'completed', actor_key: 'admin', question: 'Smoke run question', tool_trace: ['intake', 'default_advisor'], started_at: now })
|
||||
}
|
||||
|
||||
if (path === '/earth/brand') return jsonResponse({ brand: { title: '智能星球', subtitle: 'Smoke', logo_alt: 'Planet' } })
|
||||
if (path === '/earth/brand') return jsonResponse({
|
||||
brand: {
|
||||
logo_src: '/earth/assets/brand/earth-logo.png',
|
||||
title_src: '/earth/assets/brand/title-zh.png',
|
||||
title_text: '智能星球计划',
|
||||
subtitle: 'Smoke',
|
||||
description: '卫星 · 海底光缆 · 算力基础设施',
|
||||
aria_label: '智能星球计划品牌标识',
|
||||
title_alt: '智能星球计划',
|
||||
},
|
||||
})
|
||||
if (path === '/earth/clouds/meta') return jsonResponse({
|
||||
enabled: true,
|
||||
mode: 'realtime',
|
||||
degraded: false,
|
||||
source: 'multi_sat_ir',
|
||||
satellites: ['himawari', 'goes_east', 'goes_west', 'meteosat_0deg', 'meteosat_iodc'],
|
||||
captured_at: now,
|
||||
version: '20261203T113000Z',
|
||||
image_url: '/api/v1/earth/clouds/frames/20261203T113000Z',
|
||||
default_opacity: 0.9,
|
||||
timelapse_enabled: true,
|
||||
show_convective_markers: true,
|
||||
convective_threshold: 0.78,
|
||||
frames: [
|
||||
{
|
||||
version: '20261203T113000Z',
|
||||
captured_at: now,
|
||||
source: 'multi_sat_ir',
|
||||
satellites: ['himawari', 'goes_east', 'goes_west', 'meteosat_0deg', 'meteosat_iodc'],
|
||||
degraded: false,
|
||||
resolution: '2048x1024',
|
||||
file_size_bytes: 184320,
|
||||
image_url: '/api/v1/earth/clouds/frames/20261203T113000Z',
|
||||
global_summary: {
|
||||
global_cloud_cover_pct: 61.4,
|
||||
global_overcast_pct: 32.8,
|
||||
global_convective_pct: 4.6,
|
||||
convective_cluster_count: 2,
|
||||
min_brightness_temp_c: -68.2,
|
||||
},
|
||||
},
|
||||
],
|
||||
summary: {
|
||||
global_cloud_cover_pct: 61.4,
|
||||
global_overcast_pct: 32.8,
|
||||
global_convective_pct: 4.6,
|
||||
northern_hemisphere_pct: 58.1,
|
||||
southern_hemisphere_pct: 64.7,
|
||||
tropics_pct: 52.3,
|
||||
delta_pct: 1.2,
|
||||
convective_cluster_count: 2,
|
||||
min_brightness_temp_c: -68.2,
|
||||
},
|
||||
regions: [
|
||||
{
|
||||
key: 'east_asia_west_pac',
|
||||
name: '东亚与西太平洋',
|
||||
name_en: 'East Asia & West Pacific',
|
||||
center_lat: 27.5,
|
||||
center_lon: 122.5,
|
||||
cloud_cover_pct: 59.2,
|
||||
overcast_coverage_pct: 34.1,
|
||||
convective_coverage_pct: 5.4,
|
||||
min_brightness_temp_c: -64.5,
|
||||
delta_pct: 0.8,
|
||||
},
|
||||
],
|
||||
convective_clusters: [
|
||||
{
|
||||
cluster_id: 'cc_smoke_1',
|
||||
latitude: 14.5,
|
||||
longitude: 131.2,
|
||||
area_km2: 86400,
|
||||
peak_intensity: 0.91,
|
||||
min_brightness_temp_c: -68.2,
|
||||
region: '东亚与西太平洋',
|
||||
region_en: 'East Asia & West Pacific',
|
||||
bbox: { lon_min: 128, lon_max: 134, lat_max: 17, lat_min: 12 },
|
||||
},
|
||||
],
|
||||
storage_stats: { file_count: 3, total_bytes: 262144, total_mb: 0.25 },
|
||||
})
|
||||
if (path === '/earth/clouds/configuration' || path === '/earth/clouds/configuration/reset') return jsonResponse({
|
||||
config: {
|
||||
enabled: true,
|
||||
primary_source: 'multi_sat_ir',
|
||||
fallback_source: 'matteason_live',
|
||||
resolution: '2048x1024',
|
||||
ir_threshold: 0.12,
|
||||
contrast_gamma: 0.85,
|
||||
convective_threshold: 0.78,
|
||||
min_cluster_area_km2: 12000,
|
||||
polar_feather_enabled: true,
|
||||
max_history_frames: 12,
|
||||
timelapse_enabled: true,
|
||||
show_convective_markers: true,
|
||||
default_opacity: 0.9,
|
||||
request_timeout_seconds: 25,
|
||||
},
|
||||
revision: 'smoke-cloud-rev-1',
|
||||
is_default: true,
|
||||
meta: {
|
||||
enabled: true,
|
||||
mode: 'realtime',
|
||||
degraded: false,
|
||||
source: 'multi_sat_ir',
|
||||
satellites: ['himawari', 'goes_east', 'goes_west', 'meteosat_0deg', 'meteosat_iodc'],
|
||||
captured_at: now,
|
||||
version: '20261203T113000Z',
|
||||
image_url: '/api/v1/earth/clouds/frames/20261203T113000Z',
|
||||
default_opacity: 0.9,
|
||||
timelapse_enabled: true,
|
||||
show_convective_markers: true,
|
||||
convective_threshold: 0.78,
|
||||
frames: [],
|
||||
summary: { global_cloud_cover_pct: 61.4, convective_cluster_count: 2 },
|
||||
regions: [],
|
||||
convective_clusters: [],
|
||||
storage_stats: { file_count: 3, total_bytes: 262144, total_mb: 0.25 },
|
||||
},
|
||||
datasource: {
|
||||
id: 34,
|
||||
source: 'global_cloud_map',
|
||||
name: '全球气象云图采集',
|
||||
is_active: true,
|
||||
frequency_minutes: 30,
|
||||
last_run_at: now,
|
||||
next_run_at: now,
|
||||
last_status: 'success',
|
||||
},
|
||||
})
|
||||
if (method === 'POST' && path === '/earth/clouds/test') return jsonResponse({
|
||||
source_id: 'multi_sat_ir',
|
||||
ok: true,
|
||||
latency_ms: 48,
|
||||
reachable_count: 5,
|
||||
total_count: 5,
|
||||
satellites: [
|
||||
{ id: 'himawari', label: 'Himawari-9', ok: true, latency_ms: 48 },
|
||||
],
|
||||
})
|
||||
if (method === 'DELETE' && path === '/earth/clouds/cache') return jsonResponse({ deleted_files: 3, freed_bytes: 262144 })
|
||||
if (method === 'GET' && path.startsWith('/earth/clouds/frames/')) {
|
||||
return {
|
||||
status: 200,
|
||||
contentType: 'image/png',
|
||||
body: Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+X2S8AAAAASUVORK5CYII=', 'base64'),
|
||||
}
|
||||
}
|
||||
if (method === 'GET' && path.startsWith('/earth/clouds/flows/')) {
|
||||
return {
|
||||
status: 200,
|
||||
contentType: 'image/png',
|
||||
body: Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+X2S8AAAAASUVORK5CYII=', 'base64'),
|
||||
}
|
||||
}
|
||||
if (path === '/earth/basemap/meta' || path === '/earth/basemap/configuration' || path === '/earth/basemap/configuration/reset') {
|
||||
return jsonResponse({
|
||||
config: {
|
||||
active_source: 'earth_imagery_sentinel2',
|
||||
hd_tiles_enabled: true,
|
||||
cloud_hd_tiles_enabled: true,
|
||||
lod_switch_altitude: 2.3,
|
||||
max_zoom: 7,
|
||||
warmup_max_zoom: 3,
|
||||
max_cache_mb: 1024,
|
||||
request_timeout_seconds: 15,
|
||||
},
|
||||
revision: 'smoke-basemap-rev-1',
|
||||
is_default: true,
|
||||
meta: {
|
||||
active_source: 'earth_imagery_sentinel2',
|
||||
hd_tiles_enabled: true,
|
||||
cloud_hd_tiles_enabled: true,
|
||||
hd_tiles_ready: true,
|
||||
cloud_hd_tiles_ready: true,
|
||||
lod_switch_altitude: 2.3,
|
||||
max_zoom: 7,
|
||||
warmup_max_zoom: 3,
|
||||
max_cache_mb: 1024,
|
||||
tile_url_template: '/api/v1/earth/tiles/earth_imagery_sentinel2/{z}/{x}/{y}.webp',
|
||||
cloud_tile_url_template: '/api/v1/earth/tiles/cloud_hd_tiles/{z}/{x}/{y}.webp',
|
||||
sources: [
|
||||
{ source: 'earth_imagery_sentinel2', display_name: 'Sentinel-2 无云高分底图', is_active: true, has_data: true, cached_tiles: 21, cache_mb: 1.2, zoom_levels: [0, 1, 2], max_zoom: 10, warmup_max_zoom: 3, max_cache_mb: 1024, tile_url_template: '/api/v1/earth/tiles/earth_imagery_sentinel2/{z}/{x}/{y}.webp', upstream_template: '' },
|
||||
],
|
||||
},
|
||||
})
|
||||
}
|
||||
if (method === 'GET' && path.startsWith('/earth/tiles/')) {
|
||||
return {
|
||||
status: 200,
|
||||
contentType: 'image/webp',
|
||||
body: Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+X2S8AAAAASUVORK5CYII=', 'base64'),
|
||||
}
|
||||
}
|
||||
if (method === 'DELETE' && /^\/earth\/tiles\/[a-z0-9_]+\/cache$/.test(path)) {
|
||||
return jsonResponse({ removed_files: 5 })
|
||||
}
|
||||
if (path === '/earth/wind/meta') {
|
||||
return jsonResponse({
|
||||
available: true,
|
||||
is_active: true,
|
||||
has_data: true,
|
||||
version: '20261203T120000Z',
|
||||
captured_at: now,
|
||||
forecast_time: now,
|
||||
grid_url: '/api/v1/earth/wind/grid/20261203T120000Z',
|
||||
global_summary: { mean_speed_ms: 8.4, max_speed_ms: 24.5, storm_core_count: 2 },
|
||||
regions: [],
|
||||
storm_cores: [],
|
||||
})
|
||||
}
|
||||
if (path.startsWith('/earth/wind/grid/')) {
|
||||
return jsonResponse({
|
||||
version: '20261203T120000Z',
|
||||
width: 4,
|
||||
height: 2,
|
||||
lat_min: -45,
|
||||
lat_max: 45,
|
||||
lon_min: -180,
|
||||
lon_max: 90,
|
||||
max_speed_ms: 12.0,
|
||||
u: [5, 6, 7, 8, 5, 6, 7, 8],
|
||||
v: [1, 2, 1, 2, -1, -2, -1, -2],
|
||||
})
|
||||
}
|
||||
if (path === '/data-products/compute/configuration') return jsonResponse({
|
||||
config: JSON.parse(readRepoText('backend/app/services/compute_history_defaults.json')),
|
||||
revision: 'compute-configuration-smoke',
|
||||
@@ -1769,9 +2163,25 @@ async function runAdminInteractionChecks(browser, failures, consoleErrors) {
|
||||
await clickFirstVisible(page.getByRole('button', { name: /添加用户/ }), 'users add dialog button')
|
||||
await expectVisibleText(page, '添加用户', 'users add dialog')
|
||||
|
||||
await page.goto(urlFor('/data'), { waitUntil: 'domcontentloaded' })
|
||||
await page.goto(urlFor('/admin'), { waitUntil: 'domcontentloaded' })
|
||||
await clickFirstVisible(page.getByRole('button', { name: '按类型' }), 'data distribution toggle')
|
||||
await expectVisibleText(page, '按类型', 'data distribution toggle')
|
||||
await clickFirstVisible(page.getByRole('button', { name: '图层占比' }), 'runtime layer donut toggle')
|
||||
await expectVisibleText(page, '算力中心地理定位进度', 'runtime layer donut toggle')
|
||||
|
||||
smokeProgress('data ledger compute')
|
||||
await page.goto(urlFor('/data?layer=compute'), { waitUntil: 'domcontentloaded' })
|
||||
await expectVisibleText(page, 'Frontier', 'data ledger compute row')
|
||||
await expectVisibleText(page, 'IBM DYEUS', 'data ledger compute terminal row')
|
||||
const actionHeader = page.locator("th[data-column-id='actions']").first()
|
||||
await actionHeader.waitFor({ state: 'visible', timeout: SMOKE_RENDER_TIMEOUT_MS })
|
||||
assert.equal((await actionHeader.innerText()).trim(), '操作', 'compute ledger actions header must be 操作')
|
||||
const actionButton = page.locator('.an-table-actions .an-table-action').first()
|
||||
await actionButton.waitFor({ state: 'visible', timeout: SMOKE_RENDER_TIMEOUT_MS })
|
||||
const actionBox = await actionButton.boundingBox()
|
||||
assert.ok(actionBox && Math.round(actionBox.height) === 28 && Math.round(actionBox.width) === 28, `expected 28px TableActionButton, got ${JSON.stringify(actionBox)}`)
|
||||
await clickFirstVisible(page.getByRole('button', { name: /超算/ }), 'data ledger site_type filter')
|
||||
await expectVisibleText(page, 'Frontier', 'data ledger compute filtered row')
|
||||
|
||||
smokeProgress('earth news source test')
|
||||
await page.goto(urlFor('/earth-content?section=news_sources'), { waitUntil: 'domcontentloaded' })
|
||||
@@ -1801,6 +2211,73 @@ async function runAdminInteractionChecks(browser, failures, consoleErrors) {
|
||||
await clickFirstVisible(page.getByRole('button', { name: '导入配置草稿' }), 'compute candidate import')
|
||||
await expectVisibleText(page, '已将审核通过的候选观测导入草稿', 'compute candidate import toast')
|
||||
|
||||
smokeProgress('earth brand preview bundled assets')
|
||||
await page.goto(urlFor('/earth-content?section=brand'), { waitUntil: 'domcontentloaded' })
|
||||
await page.locator('.an-earth-brand-preview img.earth-brand__logo').waitFor({ state: 'visible', timeout: 8000 })
|
||||
const brandImageCheck = await page.evaluate(async () => {
|
||||
const imgs = Array.from(document.querySelectorAll('.an-earth-brand-preview img'))
|
||||
await Promise.all(
|
||||
imgs.map((img) => {
|
||||
if (img.complete) return Promise.resolve()
|
||||
return new Promise((resolve) => {
|
||||
img.addEventListener('load', resolve, { once: true })
|
||||
img.addEventListener('error', resolve, { once: true })
|
||||
setTimeout(resolve, 4000)
|
||||
})
|
||||
}),
|
||||
)
|
||||
return imgs.map((img) => ({
|
||||
className: img.className,
|
||||
src: img.getAttribute('src') || '',
|
||||
complete: img.complete,
|
||||
naturalWidth: img.naturalWidth,
|
||||
}))
|
||||
})
|
||||
assert(
|
||||
brandImageCheck.length >= 2 &&
|
||||
brandImageCheck.every((img) => img.complete && img.naturalWidth > 0 && img.src.startsWith('/assets/')),
|
||||
`brand preview images must load from bundled /assets/: ${JSON.stringify(brandImageCheck)}`,
|
||||
)
|
||||
|
||||
smokeProgress('cloud map workbench')
|
||||
await page.goto(urlFor('/earth-content?section=cloud_map'), { waitUntil: 'domcontentloaded' })
|
||||
await expectVisibleText(page, '全球实时红外云图', 'cloud map workbench title')
|
||||
await checkAdminShellOneScreen(page, 'cloud map workbench one-screen', { expectAccountVisible: true })
|
||||
const cloudImageCheck = await page.evaluate(async () => {
|
||||
const img = document.querySelector('.an-cloud-canvas__img')
|
||||
if (!img) return null
|
||||
if (!img.complete) {
|
||||
await new Promise((resolve) => {
|
||||
img.addEventListener('load', resolve, { once: true })
|
||||
img.addEventListener('error', resolve, { once: true })
|
||||
setTimeout(resolve, 4000)
|
||||
})
|
||||
}
|
||||
return {
|
||||
src: img.getAttribute('src') || '',
|
||||
complete: img.complete,
|
||||
naturalWidth: img.naturalWidth,
|
||||
}
|
||||
})
|
||||
assert(
|
||||
cloudImageCheck && cloudImageCheck.complete && cloudImageCheck.naturalWidth > 0,
|
||||
`cloud map preview image failed to load: ${JSON.stringify(cloudImageCheck)}`,
|
||||
)
|
||||
|
||||
smokeProgress('basemap workbench')
|
||||
await page.goto(urlFor('/earth-content?section=basemap'), { waitUntil: 'domcontentloaded' })
|
||||
await expectVisibleText(page, '地球高清底图与瓦片金字塔', 'basemap workbench title')
|
||||
await checkAdminShellOneScreen(page, 'basemap workbench one-screen', { expectAccountVisible: true })
|
||||
|
||||
smokeProgress('geo datasources filter')
|
||||
await page.goto(urlFor('/datasources?product=geo'), { waitUntil: 'domcontentloaded' })
|
||||
await expectVisibleText(page, 'earth_imagery_sentinel2', 'geo datasource item')
|
||||
|
||||
smokeProgress('collection-management product labels')
|
||||
await page.goto(urlFor('/collection-management'), { waitUntil: 'domcontentloaded' })
|
||||
await expectVisibleText(page, 'global_cloud_map', 'collection-management cloud collector item')
|
||||
await expectVisibleText(page, '气象', 'collection-management weather domain subtitle')
|
||||
|
||||
await page.goto(urlFor('/definitely-not-a-real-admin-route'), { waitUntil: 'domcontentloaded' })
|
||||
await expectUrl(page, 'authenticated unknown route fallback', (location) => location.pathname === '/admin')
|
||||
await expectVisibleText(page, '仪表盘', 'authenticated unknown route fallback')
|
||||
@@ -1845,6 +2322,12 @@ async function runAdminInteractionChecks(browser, failures, consoleErrors) {
|
||||
await checkNoFrameworkOverlay(mobilePage, label)
|
||||
await checkNoGlobalHorizontalOverflow(mobilePage, label)
|
||||
}
|
||||
|
||||
smokeProgress('mobile cloud map workbench')
|
||||
await mobilePage.goto(urlFor('/earth-content?section=cloud_map'), { waitUntil: 'domcontentloaded' })
|
||||
await expectVisibleText(mobilePage, '全球实时红外云图', 'mobile cloud map workbench title')
|
||||
await checkNoFrameworkOverlay(mobilePage, 'mobile cloud map workbench')
|
||||
await checkNoGlobalHorizontalOverflow(mobilePage, 'mobile cloud map workbench')
|
||||
} catch (error) {
|
||||
failures.push(formatSmokeError(error))
|
||||
} finally {
|
||||
@@ -1969,15 +2452,15 @@ async function runDatasourceSchedulingChecks(browser, failures, consoleErrors) {
|
||||
const alignment = await page.evaluate(() => {
|
||||
const cb = document.querySelector('thead th.an-data-table__selection-cell input')?.getBoundingClientRect()
|
||||
const cell = document.querySelector('thead th.an-data-table__selection-cell')?.getBoundingClientRect()
|
||||
const schedTh = document.querySelector('thead th[data-column-id="schedule"]')?.getBoundingClientRect()
|
||||
const schedLabel = document.querySelector('thead th[data-column-id="schedule"] .an-data-table__header-label')?.getBoundingClientRect()
|
||||
const schedSwitch = document.querySelector('tbody td[data-column-id="schedule"] [role="switch"]')?.getBoundingClientRect()
|
||||
return {
|
||||
checkboxDelta: cb && cell ? Math.abs((cb.left - cell.left) - (cell.right - cb.right)) : null,
|
||||
scheduleDelta: schedTh && schedSwitch ? Math.abs(((schedTh.left + schedTh.right) / 2) - ((schedSwitch.left + schedSwitch.right) / 2)) : null,
|
||||
scheduleDelta: schedLabel && schedSwitch ? Math.abs(schedLabel.left - schedSwitch.left) : null,
|
||||
}
|
||||
})
|
||||
assert.ok(alignment.checkboxDelta !== null && alignment.checkboxDelta <= 1.5, `selection checkbox must be centered, got delta=${alignment.checkboxDelta}`)
|
||||
assert.ok(alignment.scheduleDelta !== null && alignment.scheduleDelta <= 1.5, `schedule switch must align with header center, got delta=${alignment.scheduleDelta}`)
|
||||
assert.ok(alignment.scheduleDelta !== null && alignment.scheduleDelta <= 1.5, `schedule switch must align with header left edge, got delta=${alignment.scheduleDelta}`)
|
||||
const listRequestsBeforeToggle = listRequests
|
||||
await enableSwitch.first().click()
|
||||
await page.locator('.an-toast--success').first().waitFor({ state: 'visible' })
|
||||
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
#!/usr/bin/env bash
|
||||
# Install the Earth boundary PMTiles toolchain (tippecanoe + pmtiles) into a
|
||||
# user prefix without sudo. Production images build the same tools in
|
||||
# backend/Dockerfile; this script is only for local WSL/Linux development.
|
||||
set -euo pipefail
|
||||
|
||||
PREFIX="${PLANET_TOOLS_PREFIX:-$HOME/.local}"
|
||||
TIPPECANOE_REF="${TIPPECANOE_REF:-2.79.0}"
|
||||
PMTILES_VERSION="${PMTILES_VERSION:-1.31.2}"
|
||||
SQLITE_AMALGAMATION="${SQLITE_AMALGAMATION:-sqlite-amalgamation-3500400}"
|
||||
SQLITE_YEAR="${SQLITE_YEAR:-2025}"
|
||||
|
||||
mkdir -p "$PREFIX/bin"
|
||||
work="$(mktemp -d "${TMPDIR:-/tmp}/planet-earth-tools.XXXXXX")"
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
|
||||
have() { command -v "$1" >/dev/null 2>&1; }
|
||||
|
||||
if have tippecanoe && [ "${FORCE:-0}" != "1" ]; then
|
||||
echo "ok: tippecanoe already installed ($(command -v tippecanoe))"
|
||||
else
|
||||
sqlite_flags=(PLANET_TOOLS_BUILD=1)
|
||||
if [ ! -f /usr/include/sqlite3.h ]; then
|
||||
echo "info: sqlite3 headers missing; building static sqlite amalgamation"
|
||||
curl -fsSL "https://www.sqlite.org/${SQLITE_YEAR}/${SQLITE_AMALGAMATION}.zip" -o "$work/sqlite.zip"
|
||||
(cd "$work" && python3 -m zipfile -e sqlite.zip .)
|
||||
sqlite_dir="$work/$SQLITE_AMALGAMATION"
|
||||
mkdir -p "$work/sqlite/include" "$work/sqlite/lib"
|
||||
cp "$sqlite_dir/sqlite3.h" "$work/sqlite/include/"
|
||||
cc -O2 -DSQLITE_THREADSAFE=1 -c "$sqlite_dir/sqlite3.c" -o "$work/sqlite/sqlite3.o"
|
||||
ar rcs "$work/sqlite/lib/libsqlite3.a" "$work/sqlite/sqlite3.o"
|
||||
# The tippecanoe Makefile appends to CFLAGS/CXXFLAGS/LDFLAGS inherited from env.
|
||||
sqlite_flags=(
|
||||
"CFLAGS=-I$work/sqlite/include"
|
||||
"CXXFLAGS=-I$work/sqlite/include"
|
||||
"LDFLAGS=-L$work/sqlite/lib -ldl"
|
||||
)
|
||||
fi
|
||||
git clone --depth 1 --branch "$TIPPECANOE_REF" https://github.com/felt/tippecanoe.git "$work/tippecanoe"
|
||||
env "${sqlite_flags[@]}" make -C "$work/tippecanoe" -j"$(nproc)" tippecanoe tile-join
|
||||
install -m 0755 "$work/tippecanoe/tippecanoe" "$work/tippecanoe/tile-join" "$PREFIX/bin/"
|
||||
echo "ok: installed tippecanoe into $PREFIX/bin"
|
||||
fi
|
||||
|
||||
if have pmtiles && [ "${FORCE:-0}" != "1" ]; then
|
||||
echo "ok: pmtiles already installed ($(command -v pmtiles))"
|
||||
else
|
||||
arch="$(uname -m)"
|
||||
case "$arch" in
|
||||
x86_64) arch="x86_64" ;;
|
||||
aarch64|arm64) arch="arm64" ;;
|
||||
*) echo "error: unsupported arch $arch" >&2; exit 1 ;;
|
||||
esac
|
||||
url="https://github.com/protomaps/go-pmtiles/releases/download/v${PMTILES_VERSION}/go-pmtiles_${PMTILES_VERSION}_Linux_${arch}.tar.gz"
|
||||
curl -fsSL "$url" -o "$work/pmtiles.tar.gz"
|
||||
tar -xzf "$work/pmtiles.tar.gz" -C "$work" pmtiles
|
||||
install -m 0755 "$work/pmtiles" "$PREFIX/bin/pmtiles"
|
||||
echo "ok: installed pmtiles into $PREFIX/bin"
|
||||
fi
|
||||
|
||||
"$PREFIX/bin/tippecanoe" --version 2>&1 | head -1 || true
|
||||
"$PREFIX/bin/pmtiles" version 2>&1 | head -1 || true
|
||||
@@ -42,7 +42,7 @@ class BackendRuntimeAssetsTests(unittest.TestCase):
|
||||
self.assertFalse((exported / "app/backend/.env").exists())
|
||||
self.assertFalse((exported / "app/config/earth-boundary-sources.local.json").exists())
|
||||
self.assertTrue((exported / "app/resources/earth/boundary-pov-geometry.china-v1.json").is_file())
|
||||
for builder in ("build_earth_boundary_china_pov_geojson.py", "build_earth_boundary_pmtiles.py"):
|
||||
for builder in ("build_earth_boundary_pmtiles.py",):
|
||||
probe = subprocess.run(
|
||||
[sys.executable, str(exported / "app/scripts" / builder), "--help"],
|
||||
capture_output=True, text=True, timeout=10,
|
||||
|
||||
@@ -343,7 +343,13 @@ class DatabaseLifecycleTests(unittest.TestCase):
|
||||
def test_backend_worker_import_failure_is_distinct_from_optional_collector_errors(self) -> None:
|
||||
for contents, expected_status in (
|
||||
("Process SpawnProcess-1:\nModuleNotFoundError: missing_app\n", 0),
|
||||
(
|
||||
"Process SpawnProcess-19:\n"
|
||||
"TypeError: Can't instantiate abstract class CloudHDTilesCollector without an implementation for abstract method 'fetch'\n",
|
||||
0,
|
||||
),
|
||||
("Collector unavailable\nImportError: optional_dependency\n", 1),
|
||||
("Collector warning\nTypeError: transient parse error\n", 1),
|
||||
):
|
||||
with self.subTest(contents=contents), tempfile.TemporaryDirectory() as directory:
|
||||
log_file = Path(directory) / "backend.log"
|
||||
|
||||
@@ -51,8 +51,8 @@ BACKEND_RUNTIME_FILES = frozenset(
|
||||
"uv.lock",
|
||||
"config/earth-boundary-pov-policy.china-v1.json",
|
||||
"resources/earth/boundary-pov-geometry.china-v1.json",
|
||||
"scripts/build_earth_boundary_china_pov_geojson.py",
|
||||
"scripts/build_earth_boundary_pmtiles.py",
|
||||
"scripts/earth_boundary_geometry.py",
|
||||
"scripts/db_migrate.py",
|
||||
"scripts/earth_boundary_policy.py",
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user