diff --git a/VERSION b/VERSION index 89266660..de4de097 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.79.1 +0.79.2 diff --git a/backend/app/api/v1/visualization.py b/backend/app/api/v1/visualization.py index 133d85a0..010c713d 100644 --- a/backend/app/api/v1/visualization.py +++ b/backend/app/api/v1/visualization.py @@ -7,11 +7,12 @@ Returns GeoJSON format compatible with Three.js, CesiumJS, and Unreal Cesium. import asyncio import base64 from collections import OrderedDict +from contextlib import aclosing from datetime import UTC, datetime, timedelta import math import re import httpx -from fastapi import APIRouter, HTTPException, Depends, Query, Response +from fastapi import APIRouter, HTTPException, Depends, Query, Request, Response from pydantic import BaseModel, Field from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy import select, func @@ -63,6 +64,7 @@ from app.services.earth_layer_cache import ( earth_layer_cache, format_bbox_key, get_or_build_layer_payload, + get_or_build_layer_response, quantize_bbox, ) from app.core.logging import get_logger @@ -278,36 +280,43 @@ def convert_landing_point_to_geojson(records: List[CollectedData], city_to_cable return {"type": "FeatureCollection", "features": features} +def _extract_satellite_record(record: CollectedData) -> tuple[dict[str, Any], Any, Optional[str], Optional[str], Optional[str], str] | None: + metadata = record.extra_data or {} + norad_id = metadata.get("norad_cat_id") + if not norad_id: + return None + + tle_line1 = metadata.get("tle_line1") + tle_line2 = metadata.get("tle_line2") + if not tle_line1 or not tle_line2: + tle_line1, tle_line2 = build_tle_lines_from_elements( + norad_cat_id=norad_id, + epoch=metadata.get("epoch"), + inclination=metadata.get("inclination"), + raan=metadata.get("raan"), + eccentricity=metadata.get("eccentricity"), + arg_of_perigee=metadata.get("arg_of_perigee"), + mean_anomaly=metadata.get("mean_anomaly"), + mean_motion=metadata.get("mean_motion"), + ) + + constellation_group = _normalize_satellite_constellation_group( + metadata.get("constellation_group"), + record.name, + ) + footprint_policy = _get_satellite_footprint_policy(constellation_group) + return metadata, norad_id, tle_line1, tle_line2, constellation_group, footprint_policy + + def convert_satellite_to_geojson(records: List[CollectedData]) -> Dict[str, Any]: """Convert satellite TLE records to GeoJSON""" features = [] for record in records: - metadata = record.extra_data or {} - norad_id = metadata.get("norad_cat_id") - - if not norad_id: + extracted = _extract_satellite_record(record) + if extracted is None: continue - - tle_line1 = metadata.get("tle_line1") - tle_line2 = metadata.get("tle_line2") - if not tle_line1 or not tle_line2: - tle_line1, tle_line2 = build_tle_lines_from_elements( - norad_cat_id=norad_id, - epoch=metadata.get("epoch"), - inclination=metadata.get("inclination"), - raan=metadata.get("raan"), - eccentricity=metadata.get("eccentricity"), - arg_of_perigee=metadata.get("arg_of_perigee"), - mean_anomaly=metadata.get("mean_anomaly"), - mean_motion=metadata.get("mean_motion"), - ) - - constellation_group = _normalize_satellite_constellation_group( - metadata.get("constellation_group"), - record.name, - ) - footprint_policy = _get_satellite_footprint_policy(constellation_group) + metadata, norad_id, tle_line1, tle_line2, constellation_group, footprint_policy = extracted features.append( { @@ -340,6 +349,43 @@ def convert_satellite_to_geojson(records: List[CollectedData]) -> Dict[str, Any] return {"type": "FeatureCollection", "features": features} +def convert_satellite_to_compact_rows(records: List[CollectedData]) -> List[List[Any]]: + """Convert satellite TLE records into compact array rows while keeping full catalog fidelity.""" + rows: List[List[Any]] = [] + + for record in records: + extracted = _extract_satellite_record(record) + if extracted is None: + continue + metadata, norad_id, tle_line1, tle_line2, constellation_group, _footprint_policy = extracted + row: List[Any] = [ + record.id, + norad_id, + record.name, + constellation_group, + tle_line1, + tle_line2, + ] + if not tle_line1 or not tle_line2: + row.append( + [ + metadata.get("inclination"), + metadata.get("raan"), + metadata.get("eccentricity"), + metadata.get("arg_of_perigee"), + metadata.get("mean_anomaly"), + metadata.get("mean_motion"), + metadata.get("epoch"), + metadata.get("international_designator"), + metadata.get("classification_type"), + metadata.get("bstar"), + ] + ) + rows.append(row) + + return rows + + def _get_satellite_footprint_policy(constellation_group: Optional[str]) -> str: if constellation_group == "starlink": @@ -1836,32 +1882,55 @@ async def get_all_geojson(db: AsyncSession = Depends(get_db)): @router.get("/geo/satellites") async def get_satellites_geojson( + request: Request = None, limit: Optional[int] = Query( None, ge=1, description="Maximum number of satellites to return. Omit for no limit.", ), + format: Optional[str] = Query( + None, + pattern="^(geojson|compact)$", + description="Response payload format: default GeoJSON or compact full-catalog rows.", + ), db: AsyncSession = Depends(get_db), response: Response = None, ): - """获取卫星 TLE GeoJSON 数据""" + """获取卫星 TLE 数据(支持完整 GeoJSON 与全量紧凑数组格式)""" + compact = format == "compact" + cache_key = ( + earth_layer_cache.key("satellites", format="compact", limit=limit or "all") + if compact + else earth_layer_cache.key("satellites", limit=limit or "all") + ) + async def build_payload() -> dict[str, Any]: + if compact: + return await _build_satellites_compact(limit=limit, db=db) return await _build_satellites_geojson(limit=limit, db=db) - return await get_or_build_layer_payload( - key=earth_layer_cache.key("satellites", limit=limit or "all"), + if request is None: + return await get_or_build_layer_payload( + key=cache_key, + policy=SATELLITE_CACHE_POLICY, + builder=build_payload, + response=response, + ) + + return await get_or_build_layer_response( + key=cache_key, policy=SATELLITE_CACHE_POLICY, builder=build_payload, + request=request, response=response, ) -async def _build_satellites_geojson( +async def _stream_satellite_batches( *, limit: int | None, db: AsyncSession, -) -> dict[str, Any]: - features: list[dict[str, Any]] = [] +): source = "celestrak_tle" for current_only in (True, False): if current_only: @@ -1887,15 +1956,52 @@ async def _build_satellites_geojson( try: async for batch in records.partitions(SATELLITE_QUERY_BATCH_SIZE): found_records = True - features.extend(convert_satellite_to_geojson(batch)["features"]) + yield batch finally: await records.close() if found_records: break + +async def _build_satellites_geojson( + *, + limit: int | None, + db: AsyncSession, +) -> dict[str, Any]: + features: list[dict[str, Any]] = [] + async with aclosing(_stream_satellite_batches(limit=limit, db=db)) as batches: + async for batch in batches: + features.extend(convert_satellite_to_geojson(batch)["features"]) + return {"type": "FeatureCollection", "features": features, "count": len(features)} +async def _build_satellites_compact( + *, + limit: int | None, + db: AsyncSession, +) -> dict[str, Any]: + rows: list[list[Any]] = [] + async with aclosing(_stream_satellite_batches(limit=limit, db=db)) as batches: + async for batch in batches: + rows.extend(convert_satellite_to_compact_rows(batch)) + + return { + "format": "satellite_compact_v1", + "count": len(rows), + "fields": [ + "id", + "norad_cat_id", + "name", + "constellation_group", + "tle_line1", + "tle_line2", + "fallback_elements", + ], + "satellites": rows, + } + + @router.get("/geo/supercomputers") async def get_supercomputers_geojson( limit: int = 500, diff --git a/backend/app/main.py b/backend/app/main.py index 88772dab..c8434b12 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -5,6 +5,7 @@ from uuid import uuid4 from fastapi import Depends, FastAPI from fastapi.middleware.cors import CORSMiddleware +from fastapi.middleware.gzip import GZipMiddleware from fastapi.responses import JSONResponse from fastapi.staticfiles import StaticFiles from sqlalchemy import text @@ -185,6 +186,8 @@ app = FastAPI( openapi_url="/openapi.json", ) +app.add_middleware(GZipMiddleware, minimum_size=1024) + configured_origins = list(settings.CORS_ORIGINS or []) app.add_middleware( CORSMiddleware, diff --git a/backend/app/services/earth_layer_cache.py b/backend/app/services/earth_layer_cache.py index 3a1f3bde..72a2904c 100644 --- a/backend/app/services/earth_layer_cache.py +++ b/backend/app/services/earth_layer_cache.py @@ -1,16 +1,18 @@ from __future__ import annotations import asyncio +from collections import OrderedDict from collections.abc import Awaitable, Callable from contextlib import suppress from dataclasses import dataclass, replace +import gzip import hashlib import json import time from typing import Any from uuid import uuid4 -from fastapi import HTTPException, Response +from fastapi import HTTPException, Request, Response from app.core.cache import _RedisClient from app.core.config import settings @@ -27,6 +29,8 @@ DEFAULT_MAX_FEATURES = 5000 DEFAULT_MAX_BYTES = 5 * 1024 * 1024 DEFAULT_BBOX_PRECISION_DEGREES = 0.1 DEV_CACHE_KEY_HEADER = {"development", "dev", "test", "testing", "local"} +ENCODED_ARTIFACT_CACHE_MAX_ENTRIES = 8 +GZIP_COMPRESS_LEVEL = 5 @dataclass(frozen=True) @@ -49,6 +53,25 @@ class EarthLayerCacheResult: bytes: int +@dataclass(frozen=True) +class _EncodedLayerArtifact: + raw_bytes: bytes + gzip_bytes: bytes + etag: str + features: int + byte_length: int + + +@dataclass(frozen=True) +class EarthLayerEncodedResult: + artifact: _EncodedLayerArtifact + state: str + key: str + + +_ENCODED_ARTIFACT_CACHE: OrderedDict[tuple[str, str], _EncodedLayerArtifact] = OrderedDict() + + class EarthLayerCache: def __init__(self) -> None: self._client = None @@ -81,6 +104,16 @@ class EarthLayerCache: digest = hashlib.sha256(key.encode("utf-8")).hexdigest()[:32] return f"{EARTH_LAYER_LOCK_PREFIX}:{digest}" + def get_raw(self, key: str) -> bytes | None: + raw = self.client.get(key) + if not raw: + return None + if isinstance(raw, bytes): + return raw + if isinstance(raw, str): + return raw.encode("utf-8") + return None + def get_json(self, key: str) -> dict[str, Any] | None: raw = self.client.get(key) if not raw: @@ -191,15 +224,143 @@ def format_bbox_key(bbox: tuple[float, float, float, float]) -> str: return ",".join(f"{value:.1f}" for value in bbox) -def apply_cache_headers(response: Response | None, result: EarthLayerCacheResult) -> None: - if response is None: - return - response.headers["X-Planet-Cache"] = result.state - response.headers["X-Planet-Cache-Features"] = str(result.features) - response.headers["X-Planet-Cache-Bytes"] = str(result.bytes) +def _cache_headers( + result: EarthLayerCacheResult | EarthLayerEncodedResult, +) -> dict[str, str]: + if isinstance(result, EarthLayerEncodedResult): + features, byte_length = result.artifact.features, result.artifact.byte_length + else: + features, byte_length = result.features, result.bytes + headers = { + "X-Planet-Cache": result.state, + "X-Planet-Cache-Features": str(features), + "X-Planet-Cache-Bytes": str(byte_length), + } env_name = str(getattr(settings, "ENVIRONMENT", "") or "development").lower() if env_name in DEV_CACHE_KEY_HEADER: - response.headers["X-Planet-Cache-Key"] = result.key + headers["X-Planet-Cache-Key"] = result.key + return headers + + +def apply_cache_headers( + response: Response | None, + result: EarthLayerCacheResult | EarthLayerEncodedResult, +) -> None: + if response is not None: + response.headers.update(_cache_headers(result)) + + +def _etag_matches(if_none_match: str | None, etag: str) -> bool: + if not if_none_match: + return False + normalized_target = etag.strip() + if normalized_target.startswith("W/"): + normalized_target = normalized_target[2:].strip() + for candidate in if_none_match.split(","): + token = candidate.strip() + if token == "*": + return True + if token.startswith("W/"): + token = token[2:].strip() + if token == normalized_target: + return True + return False + + +def _encode_layer_bytes( + key: str, + raw_bytes: bytes, + *, + features: int | None = None, +) -> _EncodedLayerArtifact: + etag = f'"{hashlib.sha256(raw_bytes).hexdigest()[:24]}"' + cache_key = (key, etag) + cached = _ENCODED_ARTIFACT_CACHE.get(cache_key) + if cached is not None: + _ENCODED_ARTIFACT_CACHE.move_to_end(cache_key) + return cached + + resolved_features = features + if resolved_features is None: + parsed = json.loads(raw_bytes) + if not isinstance(parsed, dict): + raise ValueError("Earth layer cache payload must be a JSON object") + resolved_features = _feature_count(parsed) + + gzip_bytes = gzip.compress(raw_bytes, compresslevel=GZIP_COMPRESS_LEVEL) + artifact = _EncodedLayerArtifact( + raw_bytes=raw_bytes, + gzip_bytes=gzip_bytes, + etag=etag, + features=resolved_features, + byte_length=len(raw_bytes), + ) + _ENCODED_ARTIFACT_CACHE[cache_key] = artifact + while len(_ENCODED_ARTIFACT_CACHE) > ENCODED_ARTIFACT_CACHE_MAX_ENTRIES: + _ENCODED_ARTIFACT_CACHE.popitem(last=False) + return artifact + + +async def resolve_layer_encoded_payload( + *, + key: str, + policy: EarthLayerCachePolicy, + builder: Callable[[], Awaitable[dict[str, Any]]], +) -> EarthLayerEncodedResult: + flight_key = (asyncio.get_running_loop(), key) + if flight_key not in earth_layer_cache._inflight: + cached_raw = None + with suppress(Exception): + cached_raw = earth_layer_cache.get_raw(key) + if cached_raw is not None: + try: + artifact = _encode_layer_bytes(key, cached_raw) + return EarthLayerEncodedResult(artifact=artifact, state="hit", key=key) + except Exception as exc: + logger.warning_event( + "Invalid raw earth layer cache payload; falling back to standard resolver", + event="earth_layer_cache.raw_decode_failed", + context={"key": key, "error": str(exc)}, + ) + + result = await resolve_layer_payload(key=key, policy=policy, builder=builder) + raw_bytes = json.dumps(result.payload, ensure_ascii=False, default=str).encode("utf-8") + artifact = _encode_layer_bytes(key, raw_bytes, features=result.features) + return EarthLayerEncodedResult(artifact=artifact, state=result.state, key=result.key) + + +async def get_or_build_layer_response( + *, + key: str, + policy: EarthLayerCachePolicy, + builder: Callable[[], Awaitable[dict[str, Any]]], + request: Request, + response: Response | None = None, +) -> Response: + result = await resolve_layer_encoded_payload(key=key, policy=policy, builder=builder) + headers = _cache_headers(result) + if response is not None: + response.headers.update(headers) + headers.update({ + "ETag": result.artifact.etag, + "Cache-Control": "private, no-cache", + "Vary": "Accept-Encoding", + }) + if _etag_matches(request.headers.get("if-none-match"), result.artifact.etag): + return Response(status_code=304, headers=headers) + + accept_encoding = (request.headers.get("accept-encoding") or "").lower() + if "gzip" in accept_encoding: + return Response( + content=result.artifact.gzip_bytes, + media_type="application/json", + headers={**headers, "Content-Encoding": "gzip"}, + ) + return Response( + content=result.artifact.raw_bytes, + media_type="application/json", + headers=headers, + ) async def get_or_build_layer_payload( @@ -262,9 +423,11 @@ async def _resolve_layer_payload( try: async with asyncio.timeout(policy.build_wait_seconds): while True: - cached = earth_layer_cache.get_json(key) - if cached is not None: - return _result(cached, state="hit", key=key) + cached_raw = earth_layer_cache.get_raw(key) + if cached_raw is not None: + cached = json.loads(cached_raw) + if isinstance(cached, dict): + return _result(cached, state="hit", key=key, byte_length=len(cached_raw)) token = earth_layer_cache.acquire_lock(key, policy.lock_ttl_seconds) if token is not None: break @@ -454,13 +617,19 @@ def _with_budget_diagnostics( return {**payload, "diagnostics": diagnostics} -def _result(payload: dict[str, Any], *, state: str, key: str) -> EarthLayerCacheResult: +def _result( + payload: dict[str, Any], + *, + state: str, + key: str, + byte_length: int | None = None, +) -> EarthLayerCacheResult: return EarthLayerCacheResult( payload=payload, state=state, key=key, features=_feature_count(payload), - bytes=_payload_size(payload), + bytes=_payload_size(payload) if byte_length is None else byte_length, ) diff --git a/backend/tests/test_earth_layer_cache.py b/backend/tests/test_earth_layer_cache.py index d024be09..dd572cc1 100644 --- a/backend/tests/test_earth_layer_cache.py +++ b/backend/tests/test_earth_layer_cache.py @@ -1,6 +1,7 @@ from __future__ import annotations import asyncio +import gzip import json import httpx @@ -9,6 +10,7 @@ from fastapi import FastAPI, HTTPException, Response from app.api.v1 import visualization from app.services.earth_layer_cache import ( + _ENCODED_ARTIFACT_CACHE, EarthLayerCachePolicy, apply_payload_budget, earth_layer_cache, @@ -81,9 +83,11 @@ def fake_cache_client(): previous = earth_layer_cache._client fake = FakeRedis() earth_layer_cache._client = fake + _ENCODED_ARTIFACT_CACHE.clear() try: yield fake finally: + _ENCODED_ARTIFACT_CACHE.clear() earth_layer_cache._client = previous @@ -566,3 +570,99 @@ def test_invalidate_earth_layer_cache_for_source_degrades_gracefully_on_redis_fa assert invalidate_earth_layer_cache_for_source("ris_live_bgp") == 0 finally: earth_layer_cache._client = previous + + +@pytest.mark.asyncio +async def test_satellites_endpoint_supports_compact_gzip_and_etag_304( + fake_cache_client, + monkeypatch, +): + geojson_calls = 0 + compact_calls = 0 + + async def fake_build_satellites_geojson(*, limit, db): + nonlocal geojson_calls + geojson_calls += 1 + return { + "type": "FeatureCollection", + "features": [{"type": "Feature", "id": 25544, "properties": {"id": 1}}], + "count": 1, + } + + async def fake_build_satellites_compact(*, limit, db): + nonlocal compact_calls + compact_calls += 1 + return { + "format": "satellite_compact_v1", + "count": 1, + "fields": [ + "id", + "norad_cat_id", + "name", + "constellation_group", + "tle_line1", + "tle_line2", + "fallback_elements", + ], + "satellites": [[1, 25544, "ISS (ZARYA)", "leo", "1 25544U ...", "2 25544 ..."]], + } + + monkeypatch.setattr(visualization, "_build_satellites_geojson", fake_build_satellites_geojson) + monkeypatch.setattr(visualization, "_build_satellites_compact", fake_build_satellites_compact) + + app = FastAPI() + app.include_router(visualization.router, prefix="/api/v1/visualization") + app.dependency_overrides[visualization.get_db] = lambda: object() + + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), + base_url="http://test", + ) as client: + first_compact = await client.get( + "/api/v1/visualization/geo/satellites?format=compact", + headers={"Accept-Encoding": "gzip"}, + ) + assert first_compact.status_code == 200 + assert first_compact.headers["X-Planet-Cache"] == "refresh" + assert first_compact.headers["X-Planet-Cache-Features"] == "1" + assert first_compact.headers["Content-Encoding"] == "gzip" + etag = first_compact.headers["ETag"] + assert etag + assert first_compact.json()["format"] == "satellite_compact_v1" + assert first_compact.json()["satellites"][0][1] == 25544 + + second_compact = await client.get( + "/api/v1/visualization/geo/satellites?format=compact", + headers={"Accept-Encoding": "gzip"}, + ) + assert second_compact.status_code == 200 + assert second_compact.headers["X-Planet-Cache"] == "hit" + assert second_compact.headers["ETag"] == etag + assert second_compact.headers["Content-Encoding"] == "gzip" + + not_modified = await client.get( + "/api/v1/visualization/geo/satellites?format=compact", + headers={"If-None-Match": etag, "Accept-Encoding": "gzip"}, + ) + assert not_modified.status_code == 304 + assert not_modified.content == b"" + assert not_modified.headers["ETag"] == etag + + plain_geo = await client.get( + "/api/v1/visualization/geo/satellites", + headers={"Accept-Encoding": "identity"}, + ) + assert plain_geo.status_code == 200 + assert "content-encoding" not in {k.lower() for k in plain_geo.headers.keys()} + assert plain_geo.json()["type"] == "FeatureCollection" + assert geojson_calls == 1 + assert compact_calls == 1 + + # Verify raw bytes cached cleanly match uncompressed response and encoded artifact gzip round-trips + raw_cached = fake_cache_client.store[ + earth_layer_cache.key("satellites", format="compact", limit="all") + ] + assert json.loads(raw_cached)["count"] == 1 + assert second_compact.json()["count"] == 1 + artifact = next(iter(_ENCODED_ARTIFACT_CACHE.values())) + assert gzip.decompress(artifact.gzip_bytes) == artifact.raw_bytes diff --git a/backend/tests/test_visualization_satellite_streaming.py b/backend/tests/test_visualization_satellite_streaming.py index 0ae3bf84..3b19f243 100644 --- a/backend/tests/test_visualization_satellite_streaming.py +++ b/backend/tests/test_visualization_satellite_streaming.py @@ -154,3 +154,50 @@ async def test_satellite_cursor_closes_if_conversion_fails( await visualization._build_satellites_geojson(limit=None, db=satellite_db) assert satellite_db.streams[0].closed + + +@pytest.mark.asyncio +async def test_compact_satellite_builder_emits_compact_rows_and_fallback_elements( + satellite_db: SatelliteSession, +) -> None: + with_tle = satellite(10) + without_tle = CollectedData( + id=11, + source="celestrak_tle", + source_id="11", + data_type="satellite_tle", + name="NO-TLE-SAT", + is_current=True, + task_id=1, + collected_at=datetime(2026, 1, 1, tzinfo=UTC), + extra_data={ + "norad_cat_id": 51000, + "inclination": 53.2, + "raan": 120.5, + "eccentricity": 0.00012, + "arg_of_perigee": 90.0, + "mean_anomaly": 45.0, + "mean_motion": 15.1, + "international_designator": "24001A", + "classification_type": "U", + "bstar": 0.0001, + }, + ) + starlink = satellite(12, name="STARLINK-1234") + satellite_db.session.add_all([with_tle, without_tle, starlink]) + satellite_db.session.commit() + + payload = await visualization._build_satellites_compact(limit=None, db=satellite_db) + + assert payload["format"] == "satellite_compact_v1" + assert payload["count"] == 3 + rows_by_id = {row[0]: row for row in payload["satellites"]} + assert len(rows_by_id[10]) == 6 + assert rows_by_id[10][:4] == [10, 40010, "SAT-10", None] + assert rows_by_id[10][4:6] == ["line-1-10", "line-2-10"] + assert rows_by_id[12][:4] == [12, 40012, "STARLINK-1234", "starlink"] + assert len(rows_by_id[11]) == 7 + assert rows_by_id[11][4] is None + assert isinstance(rows_by_id[11][5], str) and rows_by_id[11][5].startswith("2 51000 ") + assert rows_by_id[11][6][:2] == [53.2, 120.5] + assert all(stream.closed for stream in satellite_db.streams) diff --git a/client/package.json b/client/package.json index a49c1fa2..5fdeec9e 100644 --- a/client/package.json +++ b/client/package.json @@ -1,6 +1,6 @@ { "name": "planet-client", - "version": "0.79.1", + "version": "0.79.2", "description": "Intelligent Planet Program - Native Electron Earth Viewer", "private": true, "packageManager": "bun@1", diff --git a/client/src/main/orientation.ts b/client/src/main/orientation.ts index 27b6073c..25f05a6e 100644 --- a/client/src/main/orientation.ts +++ b/client/src/main/orientation.ts @@ -101,3 +101,44 @@ export function computeLandscapeBounds(params: { const targetPos = pos ?? centerOnAnchor(anchorBounds, width, height) return clampBoundsToWorkArea({ x: targetPos.x, y: targetPos.y, width, height }, workArea) } + +export function resolveInitialWindowBounds(params: { + saved: { + x?: number + y?: number + width: number + height: number + isMaximized?: boolean + isFullScreen?: boolean + } + launchFullScreen: boolean + headlessSmoke: boolean + displayWorkArea: Rect + displayBounds: Rect +}): { + initialBounds: { x?: number; y?: number; width: number; height: number } + shouldRestoreNormalBoundsOnUnmaximize: boolean +} { + const { saved, launchFullScreen, headlessSmoke, displayWorkArea, displayBounds } = params + if (!headlessSmoke && (launchFullScreen || saved.isFullScreen)) { + return { + initialBounds: { ...displayBounds }, + shouldRestoreNormalBoundsOnUnmaximize: Boolean(saved.isMaximized), + } + } + if (!headlessSmoke && saved.isMaximized) { + return { + initialBounds: { ...displayWorkArea }, + shouldRestoreNormalBoundsOnUnmaximize: true, + } + } + return { + initialBounds: { + x: saved.x, + y: saved.y, + width: saved.width, + height: saved.height, + }, + shouldRestoreNormalBoundsOnUnmaximize: false, + } +} diff --git a/client/src/main/protocol-core.ts b/client/src/main/protocol-core.ts index cc6d4cc5..ff42a89e 100644 --- a/client/src/main/protocol-core.ts +++ b/client/src/main/protocol-core.ts @@ -173,6 +173,9 @@ export function createEarthProtocolHandler(options: { const forwardHeaders = new Headers(request.headers) forwardHeaders.delete('host') forwardHeaders.delete('content-length') + if (!forwardHeaders.has('accept-encoding')) { + forwardHeaders.set('accept-encoding', 'gzip, deflate, br') + } const method = request.method.toUpperCase() const hasBody = method !== 'GET' && method !== 'HEAD' @@ -181,6 +184,9 @@ export function createEarthProtocolHandler(options: { method, headers: forwardHeaders, } + if (request.signal) { + init.signal = request.signal + } if (hasBody && request.body) { init.body = request.body init.duplex = 'half' @@ -189,12 +195,16 @@ export function createEarthProtocolHandler(options: { const responseHeaders = new Headers(upstream.headers) responseHeaders.delete('content-encoding') responseHeaders.delete('content-length') - return new Response(upstream.body, { + const isNullBodyStatus = upstream.status === 204 || upstream.status === 205 || upstream.status === 304 + return new Response(isNullBodyStatus ? null : upstream.body, { status: upstream.status, statusText: upstream.statusText, headers: responseHeaders, }) } catch (error) { + if (request.signal?.aborted) { + throw error + } return Response.json( { detail: 'Backend service unavailable', diff --git a/client/src/main/window.ts b/client/src/main/window.ts index 0861fae6..838d1333 100644 --- a/client/src/main/window.ts +++ b/client/src/main/window.ts @@ -8,6 +8,7 @@ import { DEFAULT_ENDPOINTS, type DesktopConfigStore, type DesktopRuntimeConfig } import { resolveExternalTargetUrl } from './external-links' import { createWindowShowGate } from './show-gate' import { + clampBoundsToWorkArea, computeLandscapeBounds, computePortraitBounds, DEFAULT_LANDSCAPE_HEIGHT, @@ -15,6 +16,7 @@ import { detectWindowOrientation, MIN_WINDOW_HEIGHT, MIN_WINDOW_WIDTH, + resolveInitialWindowBounds, type Rect, type WindowOrientation, } from './orientation' @@ -22,6 +24,7 @@ import { EARTH_ENTRY_URL, EARTH_ORIGIN } from './protocol' const resetAltMenuTrackers = new WeakMap void>() const windowStateFlushers = new WeakMap void>() +const cancelInitialUnmaximizeRestore = new WeakMap void>() export function flushWindowState(win: BrowserWindow | null): void { if (!win || win.isDestroyed()) return @@ -74,6 +77,7 @@ export function toggleWindowOrientation(win: BrowserWindow): WindowOrientation { win.setFullScreen(false) } if (wasMaximized) { + cancelInitialUnmaximizeRestore.get(win)?.() win.unmaximize() } const portraitBounds = computePortraitBounds({ @@ -182,12 +186,23 @@ export function createMainWindow(options: { const statePath = path.join(options.userDataDir, 'window-state.json') const runtimeConfig: DesktopRuntimeConfig = options.configStore.get() const saved = loadWindowState(statePath, runtimeConfig.headlessSmoke) + const targetDisplay = + saved.x !== undefined && saved.y !== undefined + ? screen.getDisplayMatching({ x: saved.x, y: saved.y, width: saved.width, height: saved.height }) + : screen.getPrimaryDisplay() + const { initialBounds, shouldRestoreNormalBoundsOnUnmaximize } = resolveInitialWindowBounds({ + saved, + launchFullScreen: Boolean(runtimeConfig.fullscreen || runtimeConfig.kiosk), + headlessSmoke: runtimeConfig.headlessSmoke, + displayWorkArea: targetDisplay.workArea, + displayBounds: targetDisplay.bounds, + }) const win = new BrowserWindow({ - x: saved.x, - y: saved.y, - width: saved.width, - height: saved.height, + x: initialBounds.x, + y: initialBounds.y, + width: initialBounds.width, + height: initialBounds.height, minWidth: MIN_WINDOW_WIDTH, minHeight: MIN_WINDOW_HEIGHT, show: false, @@ -288,7 +303,17 @@ export function createMainWindow(options: { restoreFullScreenOnLandscape: Boolean(saved.isFullScreen), }) + let pendingInitialReveal = + !runtimeConfig.headlessSmoke && + Boolean(saved.isMaximized || saved.isFullScreen || runtimeConfig.fullscreen || runtimeConfig.kiosk) + let restoreNormalBoundsOnUnmaximize = shouldRestoreNormalBoundsOnUnmaximize + + cancelInitialUnmaximizeRestore.set(win, () => { + restoreNormalBoundsOnUnmaximize = false + }) + const captureNormalBounds = () => { + if (pendingInitialReveal) return if (!win.isDestroyed() && !win.isMaximized() && !win.isMinimized() && !win.isFullScreen()) { lastNormalBounds = win.getBounds() const orientState = windowOrientationStates.get(win) @@ -313,6 +338,18 @@ export function createMainWindow(options: { win.on('resize', captureNormalBounds) win.on('move', captureNormalBounds) win.on('close', flushCurrentWindowState) + win.on('unmaximize', () => { + if (!restoreNormalBoundsOnUnmaximize) return + restoreNormalBoundsOnUnmaximize = false + if (win.isDestroyed() || win.isFullScreen()) return + if ( + lastNormalBounds.width < targetDisplay.workArea.width || + lastNormalBounds.height < targetDisplay.workArea.height + ) { + const workArea = screen.getDisplayMatching(win.getBounds()).workArea + win.setBounds(clampBoundsToWorkArea(lastNormalBounds, workArea)) + } + }) win.on('minimize', () => { if (!win.isDestroyed()) { @@ -340,17 +377,21 @@ export function createMainWindow(options: { const revealMainWindow = () => { if (win.isDestroyed() || runtimeConfig.headlessSmoke) return - if (saved.isMaximized) { - win.maximize() - } - win.show() - if (runtimeConfig.kiosk) { - win.setKiosk(true) - } else if (runtimeConfig.fullscreen || saved.isFullScreen) { - win.setFullScreen(true) - } - if (runtimeConfig.devtools) { - win.webContents.openDevTools({ mode: 'detach' }) + try { + if (saved.isMaximized) { + win.maximize() + } + win.show() + if (runtimeConfig.kiosk) { + win.setKiosk(true) + } else if (runtimeConfig.fullscreen || saved.isFullScreen) { + win.setFullScreen(true) + } + if (runtimeConfig.devtools) { + win.webContents.openDevTools({ mode: 'detach' }) + } + } finally { + pendingInitialReveal = false } } @@ -372,6 +413,7 @@ export function createMainWindow(options: { win.once('closed', () => { windowStateFlushers.delete(win) + cancelInitialUnmaximizeRestore.delete(win) showGate.dispose() ipcMain.removeListener('planet:splash-first-paint', onSplashFirstPaint) }) diff --git a/client/src/preload/splash.ts b/client/src/preload/splash.ts index f8487be9..8f5063bf 100644 --- a/client/src/preload/splash.ts +++ b/client/src/preload/splash.ts @@ -265,6 +265,8 @@ const SPLASH_CSS = ` all: initial; position: fixed; inset: 0; + width: 100%; + height: 100%; z-index: 2147483000; display: block; pointer-events: auto; @@ -597,6 +599,7 @@ export function createDesktopSplashController(options: { let rafId = 0 let statusObserver: MutationObserver | null = null let keydownHandler: ((event: KeyboardEvent) => void) | null = null + let resizeHandler: (() => void) | null = null let startupProgressHandler: ((event: Event) => void) | null = null let startupReadyHandler: (() => void) | null = null let sessionMode: 'boot' | 'replay' = 'boot' @@ -655,6 +658,10 @@ export function createDesktopSplashController(options: { window.removeEventListener('keydown', keydownHandler, true) keydownHandler = null } + if (resizeHandler) { + window.removeEventListener('resize', resizeHandler) + resizeHandler = null + } if (hostEl && hostEl.parentNode) { hostEl.parentNode.removeChild(hostEl) } @@ -738,7 +745,7 @@ export function createDesktopSplashController(options: { hostEl = document.createElement('div') hostEl.id = SPLASH_HOST_ID - hostEl.style.cssText = 'position:fixed;inset:0;z-index:2147483647;pointer-events:auto;' + hostEl.style.cssText = 'position:fixed;inset:0;width:100%;height:100%;z-index:2147483647;pointer-events:auto;' hostEl.dataset.splashTheme = activeTheme shadow = hostEl.attachShadow({ mode: 'open' }) @@ -810,6 +817,18 @@ export function createDesktopSplashController(options: { window.addEventListener('keydown', keydownHandler, true) } + if (!resizeHandler) { + resizeHandler = () => { + if (!canvasEl || !rootEl) return + const now = performance.now() + const exitDuration = prefersReducedMotion() ? 300 : 940 + const clampedProgress = Math.max(0, Math.min(1, displayProgress)) + const exitRatio = exitStartTime > 0 ? Math.min(1, (now - exitStartTime) / exitDuration) : 0 + renderSceneFrame(now, clampedProgress, exitRatio) + } + window.addEventListener('resize', resizeHandler) + } + setActiveThemeVisual(activeTheme) } diff --git a/client/tests/orientation.test.ts b/client/tests/orientation.test.ts index 390fa8da..3c041a05 100644 --- a/client/tests/orientation.test.ts +++ b/client/tests/orientation.test.ts @@ -7,6 +7,7 @@ import { EARTH_MOBILE_MAX_WIDTH, MIN_WINDOW_HEIGHT, MIN_WINDOW_WIDTH, + resolveInitialWindowBounds, type Rect, } from '../src/main/orientation' @@ -67,4 +68,75 @@ describe('window orientation calculations', () => { }) expect(landscape).toEqual(savedLandscape) }) + + test('resolveInitialWindowBounds pre-sizes maximized and fullscreen windows to display work area or bounds', () => { + const displayWorkArea: Rect = { x: 0, y: 0, width: 1920, height: 1032 } + const displayBounds: Rect = { x: 0, y: 0, width: 1920, height: 1080 } + const savedNormal = { x: 160, y: 36, width: 1600, height: 960 } + + expect( + resolveInitialWindowBounds({ + saved: { ...savedNormal, isMaximized: true, isFullScreen: false }, + launchFullScreen: false, + headlessSmoke: false, + displayWorkArea, + displayBounds, + }), + ).toEqual({ + initialBounds: displayWorkArea, + shouldRestoreNormalBoundsOnUnmaximize: true, + }) + + expect( + resolveInitialWindowBounds({ + saved: { ...savedNormal, isMaximized: true, isFullScreen: true }, + launchFullScreen: false, + headlessSmoke: false, + displayWorkArea, + displayBounds, + }), + ).toEqual({ + initialBounds: displayBounds, + shouldRestoreNormalBoundsOnUnmaximize: true, + }) + + expect( + resolveInitialWindowBounds({ + saved: { ...savedNormal, isMaximized: false, isFullScreen: false }, + launchFullScreen: true, + headlessSmoke: false, + displayWorkArea, + displayBounds, + }), + ).toEqual({ + initialBounds: displayBounds, + shouldRestoreNormalBoundsOnUnmaximize: false, + }) + + expect( + resolveInitialWindowBounds({ + saved: { ...savedNormal, isMaximized: false, isFullScreen: false }, + launchFullScreen: false, + headlessSmoke: false, + displayWorkArea, + displayBounds, + }), + ).toEqual({ + initialBounds: savedNormal, + shouldRestoreNormalBoundsOnUnmaximize: false, + }) + + expect( + resolveInitialWindowBounds({ + saved: { ...savedNormal, isMaximized: true, isFullScreen: true }, + launchFullScreen: true, + headlessSmoke: true, + displayWorkArea, + displayBounds, + }), + ).toEqual({ + initialBounds: savedNormal, + shouldRestoreNormalBoundsOnUnmaximize: false, + }) + }) }) diff --git a/client/tests/protocol.test.ts b/client/tests/protocol.test.ts index 87668bc0..635315af 100644 --- a/client/tests/protocol.test.ts +++ b/client/tests/protocol.test.ts @@ -92,6 +92,60 @@ describe('protocol-core static and range handling', () => { const blocked = await handler(new Request('planet://other/earth/index.html')) expect(blocked.status).toBe(403) }) + + test('forwards Accept-Encoding, If-None-Match, and AbortSignal and preserves 304 null-body responses', async () => { + const capturedHeaders: Array = [] + let receivedSignal: AbortSignal | undefined + + const handler = createEarthProtocolHandler({ + earthBundleRoot: bundleRoot, + getBackendUrl: () => 'http://127.0.0.1:8000', + fetchImpl: (async (_input: RequestInfo | URL, init?: RequestInit) => { + capturedHeaders.push(new Headers(init?.headers)) + receivedSignal = init?.signal + return new Response(null, { + status: 304, + headers: { ETag: '"sat-v1"', 'Content-Length': '0' }, + }) + }) as typeof fetch, + }) + + const abortController = new AbortController() + const response = await handler( + new Request('planet://earth/api/v1/visualization/geo/satellites?format=compact', { + headers: { 'If-None-Match': '"sat-v1"' }, + signal: abortController.signal, + }), + ) + + expect(response.status).toBe(304) + expect(response.headers.get('ETag')).toBe('"sat-v1"') + expect(await response.text()).toBe('') + expect(capturedHeaders[0].get('accept-encoding')).toBe('gzip, deflate, br') + expect(capturedHeaders[0].get('if-none-match')).toBe('"sat-v1"') + expect(receivedSignal?.aborted).toBe(false) + + const abortedController = new AbortController() + abortedController.abort(new DOMException('Aborted', 'AbortError')) + const abortHandler = createEarthProtocolHandler({ + earthBundleRoot: bundleRoot, + getBackendUrl: () => 'http://127.0.0.1:8000', + fetchImpl: (async (_input: RequestInfo | URL, init?: RequestInit) => { + if (init?.signal?.aborted) { + throw init.signal.reason ?? new DOMException('Aborted', 'AbortError') + } + return Response.json({ ok: true }) + }) as typeof fetch, + }) + + await expect( + abortHandler( + new Request('planet://earth/api/v1/visualization/geo/satellites', { + signal: abortedController.signal, + }), + ), + ).rejects.toThrow() + }) }) describe('external links and runtime config', () => { diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 154c1383..3867a0b3 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -8,6 +8,18 @@ This project follows the repository versioning rule: - `improvement` -> `+0.0.1`(bugfix + 小功能混合) - `bugfix` -> `+0.0.1` +## [0.79.2] — 2026-11-25 + +Released: 2026-11-25 + +### Highlights + +- Earth can load the satellite catalog from a local cache while it checks the server for updates. The server offers a compact catalog with gzip compression and ETag validation, alongside the existing GeoJSON format. +- Turning off the satellite layer cancels pending requests. The desktop proxy forwards cancellation and handles an unchanged catalog without downloading it again. +- Electron restores a maximized or fullscreen window at the target display size on startup and preserves the normal window bounds for later use. + +--- + ## [0.79.1] — 2026-11-24 Released: 2026-11-24 diff --git a/docs/version-history.md b/docs/version-history.md index 042781a2..26fbf80c 100644 --- a/docs/version-history.md +++ b/docs/version-history.md @@ -16,12 +16,13 @@ ## Current Version - `main` 当前主线历史推导到:`0.16.5` -- `dev` 当前开发分支历史推导到:`0.79.1` +- `dev` 当前开发分支历史推导到:`0.79.2` ## Timeline | Version | Type | Branch | Commit | Summary | | --- | --- | --- | --- | --- | +| `0.79.2` | improvement | `dev` | `v0.79.2` | 卫星目录支持紧凑传输、本地缓存和后台校验,改进桌面客户端启动时的窗口尺寸恢复 | | `0.79.1` | improvement | `dev` | `v0.79.1` | Windows 根据显存与帧率自动切换显卡,保留 45 秒切换冷却与窗口状态,统一 IMI 英文名称 | | `0.79.0` | feature | `dev` | `v0.79.0` | 破晓-星核统一启动动效、Phase 1 L1 热更新体系与 Windows GPU/WebGL 恢复加固 | | `0.78.0` | feature | `dev` | `v0.78.0` | 全局单份采集策略、短期船舶航迹、精简生产部署和桌面协议注册 | diff --git a/frontend/nginx.conf.template b/frontend/nginx.conf.template index 5224a302..773ed322 100644 --- a/frontend/nginx.conf.template +++ b/frontend/nginx.conf.template @@ -10,6 +10,10 @@ server { add_header Referrer-Policy "strict-origin-when-cross-origin" always; gzip on; + gzip_proxied any; + gzip_vary on; + gzip_min_length 1024; + gzip_comp_level 5; gzip_types text/plain text/css application/javascript application/json image/svg+xml; location = /health { diff --git a/frontend/package.json b/frontend/package.json index b1aad506..ae695c59 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "planet-frontend", - "version": "0.79.1", + "version": "0.79.2", "private": true, "packageManager": "bun@1", "dependencies": { diff --git a/frontend/public/earth/js/layer-startup-tasks.js b/frontend/public/earth/js/layer-startup-tasks.js index d3ac8118..2c0214e6 100644 --- a/frontend/public/earth/js/layer-startup-tasks.js +++ b/frontend/public/earth/js/layer-startup-tasks.js @@ -167,10 +167,23 @@ function registerSatelliteStartupTask() { await context.yieldFrame(12); try { clearSatelliteData(); + const canApplyUpdate = () => !context.isCancelled() && context.isSatellitesEnabled(); const loadResult = await loadSatellites({ limit: context.getInitialSatelliteLoadLimit(), + shouldApplyBackgroundUpdate: canApplyUpdate, + onBackgroundUpdated: (nextResult) => { + if (!canApplyUpdate()) return; + context.updateSatelliteToggleUi(true, nextResult.count); + context.setLegendItems("satellites", getSatelliteLegendItems()); + context.refreshLegend(); + context.scheduleSatellitePositionWarmup(() => { + if (canApplyUpdate()) { + toggleSatellites(true); + } + }); + }, }); - if (!context.isCancelled() && context.isSatellitesEnabled()) { + if (canApplyUpdate()) { context.updateSatelliteToggleUi(true, loadResult.count); context.setLegendItems("satellites", getSatelliteLegendItems()); context.refreshLegend(); diff --git a/frontend/public/earth/js/main.js b/frontend/public/earth/js/main.js index be4e3cc5..6060da77 100644 --- a/frontend/public/earth/js/main.js +++ b/frontend/public/earth/js/main.js @@ -404,6 +404,7 @@ let isDataLoading = false; let currentLoadToken = 0; let cablesEnabled = true; let satellitesEnabled = false; +let satelliteLoadAbortController = null; let vesselsEnabled = false; let cableToggleToken = 0; let satelliteToggleToken = 0; @@ -4274,7 +4275,14 @@ function disableCables() { refreshLegend(); } -async function ensureSatellitesEnabled() { +function abortPendingSatelliteLoad() { + if (satelliteLoadAbortController) { + satelliteLoadAbortController.abort(); + satelliteLoadAbortController = null; + } +} + +async function ensureSatellitesEnabled(options = {}) { if (!scene || !camera || !renderer || destroyed) return 0; const earth = getEarth(); @@ -4282,16 +4290,47 @@ async function ensureSatellitesEnabled() { satellitesEnabled = true; const requestToken = ++satelliteToggleToken; + abortPendingSatelliteLoad(); + const loadController = new AbortController(); + satelliteLoadAbortController = loadController; if (!getSatellitePoints()) { createSatellites(scene, earth); } clearSatelliteData(); - const loadResult = await loadSatellites({ - limit: getInitialSatelliteLoadLimit(), - cacheBust: true, - }); + let loadResult; + try { + loadResult = await loadSatellites({ + limit: getInitialSatelliteLoadLimit(), + forceNetwork: Boolean(options.forceNetwork), + signal: loadController.signal, + shouldApplyBackgroundUpdate: () => + requestToken === satelliteToggleToken && + satellitesEnabled && + !destroyed, + onBackgroundUpdated: (nextResult) => { + reconcileSelectedSatellite(); + updateSatelliteToggleUi(true, nextResult.count); + setLegendItems("satellites", getSatelliteLegendItems()); + refreshLegend(); + scheduleSatellitePositionWarmup(); + }, + }); + } catch (error) { + if ( + requestToken !== satelliteToggleToken || + !satellitesEnabled || + destroyed + ) { + return 0; + } + throw error; + } finally { + if (satelliteLoadAbortController === loadController) { + satelliteLoadAbortController = null; + } + } if ( requestToken !== satelliteToggleToken || @@ -4361,6 +4400,7 @@ function disableSatellites() { satellitesEnabled = false; satelliteToggleToken += 1; satelliteHydrationToken += 1; + abortPendingSatelliteLoad(); toggleSatellites(false); resetSatelliteState(); updateSatelliteToggleUi(false, 0); @@ -5247,7 +5287,7 @@ const EARTH_DATA_LAYER_HANDLERS = { isVisible: () => satellitesEnabled || getShowSatellites(), localCount: () => getSatelliteCount(), clear: applySatelliteEmptyState, - refresh: ensureSatellitesEnabled, + refresh: () => ensureSatellitesEnabled({ forceNetwork: true }), refreshOnCountMismatch: true, }, vessels: { @@ -6042,6 +6082,9 @@ export async function setSatellitesEnabled( try { const satelliteCount = await ensureSatellitesEnabled(); + if (!satellitesEnabled || destroyed) { + return 0; + } if (!suppressStatus) { showStatusMessage(earthMessage("status.layerVisibility", { layer: "卫星", visible: true }), "info"); } @@ -7221,6 +7264,7 @@ export function destroy() { clearComputeCenterData(getEarth()); clearCountryBoundaryData(); clearEarthTexture(); + abortPendingSatelliteLoad(); resetSatelliteState(); clearUiState(); disposeCelestialLayer(); diff --git a/frontend/public/earth/js/satellite-cache.js b/frontend/public/earth/js/satellite-cache.js new file mode 100644 index 00000000..1421c15b --- /dev/null +++ b/frontend/public/earth/js/satellite-cache.js @@ -0,0 +1,111 @@ +const SATELLITE_CACHE_DB_NAME = "planet-earth-catalog-cache"; +const SATELLITE_CACHE_DB_VERSION = 1; +const SATELLITE_CACHE_STORE = "snapshots"; + +let dbPromise = null; + +function openSatelliteCacheDb() { + if (typeof indexedDB === "undefined") { + return Promise.resolve(null); + } + if (dbPromise) { + return dbPromise; + } + dbPromise = new Promise((resolve) => { + try { + const request = indexedDB.open(SATELLITE_CACHE_DB_NAME, SATELLITE_CACHE_DB_VERSION); + request.onupgradeneeded = () => { + const db = request.result; + if (!db.objectStoreNames.contains(SATELLITE_CACHE_STORE)) { + db.createObjectStore(SATELLITE_CACHE_STORE); + } + }; + request.onsuccess = () => resolve(request.result); + request.onerror = () => { + dbPromise = null; + resolve(null); + }; + } catch { + dbPromise = null; + resolve(null); + } + }); + return dbPromise; +} + +export async function resolveSatelliteCacheOrigin() { + if (typeof window === "undefined") return "local"; + try { + const getConfig = window.planetDesktop?.getConfig; + if (typeof getConfig === "function") { + const config = await getConfig(); + if (config?.backendUrl) { + return String(config.backendUrl).replace(/\/+$/, ""); + } + } + } catch { + // Fall back to window.location.origin when desktop config is unavailable. + } + return window.location.origin || "local"; +} + +export function buildSatelliteCacheKey({ origin = "local", apiPath = "", limit = null } = {}) { + const normalizedOrigin = String(origin || "local").replace(/\/+$/, ""); + const normalizedLimit = limit === null || limit === undefined ? "all" : String(limit); + return `satellites:v1:${normalizedOrigin}:${apiPath}:limit=${normalizedLimit}`; +} + +export async function readSatelliteSnapshot(cacheKey) { + if (!cacheKey) return null; + const db = await openSatelliteCacheDb(); + if (!db) return null; + + return new Promise((resolve) => { + try { + const tx = db.transaction(SATELLITE_CACHE_STORE, "readonly"); + const store = tx.objectStore(SATELLITE_CACHE_STORE); + const req = store.get(cacheKey); + req.onsuccess = () => { + const value = req.result; + if (value && typeof value === "object" && value.payload) { + resolve({ + etag: value.etag ?? null, + payload: value.payload, + savedAt: Number(value.savedAt) || 0, + }); + return; + } + resolve(null); + }; + req.onerror = () => resolve(null); + } catch { + resolve(null); + } + }); +} + +export async function writeSatelliteSnapshot(cacheKey, { etag = null, payload } = {}) { + if (!cacheKey || !payload) return; + const db = await openSatelliteCacheDb(); + if (!db) return; + + await new Promise((resolve) => { + try { + const tx = db.transaction(SATELLITE_CACHE_STORE, "readwrite"); + const store = tx.objectStore(SATELLITE_CACHE_STORE); + store.put( + { + etag: etag ?? null, + payload, + savedAt: Date.now(), + }, + cacheKey, + ); + tx.oncomplete = () => resolve(); + tx.onerror = () => resolve(); + tx.onabort = () => resolve(); + } catch { + resolve(); + } + }); +} diff --git a/frontend/public/earth/js/satellite-catalog.js b/frontend/public/earth/js/satellite-catalog.js new file mode 100644 index 00000000..db19d098 --- /dev/null +++ b/frontend/public/earth/js/satellite-catalog.js @@ -0,0 +1,129 @@ +export const SATELLITE_COMPACT_FORMAT = "satellite_compact_v1"; + +const MS_PER_DAY = 86400000; +const TLE_EPOCH_CENTURY_PIVOT = 57; + +function parseFiniteFloat(raw) { + if (typeof raw !== "string") return null; + const trimmed = raw.trim(); + if (!trimmed) return null; + const parsed = Number.parseFloat(trimmed); + return Number.isFinite(parsed) ? parsed : null; +} + +function parseTleEpochIso(line1) { + if (typeof line1 !== "string" || line1.length < 32) return null; + const raw = line1.slice(18, 32).trim(); + if (!/^\d{5}(?:\.\d+)?$/.test(raw)) return null; + const yy = Number.parseInt(raw.slice(0, 2), 10); + const dayOfYear = Number.parseFloat(raw.slice(2)); + if (!Number.isInteger(yy) || !Number.isFinite(dayOfYear) || dayOfYear < 1 || dayOfYear >= 367) { + return null; + } + const year = yy < TLE_EPOCH_CENTURY_PIVOT ? 2000 + yy : 1900 + yy; + const timestamp = Date.UTC(year, 0, 1) + (dayOfYear - 1) * MS_PER_DAY; + return Number.isFinite(timestamp) ? new Date(timestamp).toISOString() : null; +} + +function parseTleAssumedDecimalSci(rawField) { + if (typeof rawField !== "string") return null; + const trimmed = rawField.trim(); + if (!trimmed) return null; + const match = trimmed.match(/^([+-]?)\.?(\d{1,5})([+-]\d)$/); + if (!match) return null; + const [, signText, digits, expText] = match; + const mantissa = Number.parseFloat(`${signText || ""}0.${digits}`); + const exponent = Number.parseInt(expText, 10); + if (!Number.isFinite(mantissa) || !Number.isInteger(exponent)) return null; + const value = mantissa * (10 ** exponent); + return Number.isFinite(value) ? value : null; +} + +export function inferSatelliteFootprintPolicy(constellationGroup) { + const normalized = String(constellationGroup || "").trim().toLowerCase(); + if (normalized === "starlink") return "starlink_ground_footprint"; + if (normalized === "iridium-next") return "iridium_coverage_ring"; + return "none"; +} + +export function parseTleOrbitalElements(tleLine1, tleLine2) { + const validLine1 = typeof tleLine1 === "string" && tleLine1.length >= 63; + const validLine2 = typeof tleLine2 === "string" && tleLine2.length >= 63; + + const classificationRaw = validLine1 ? tleLine1.slice(7, 8).trim() : ""; + const intlRaw = validLine1 ? tleLine1.slice(9, 17).trim() : ""; + const eccDigits = validLine2 ? tleLine2.slice(26, 33).trim() : ""; + + return { + classification_type: classificationRaw || null, + international_designator: intlRaw || null, + epoch: validLine1 ? parseTleEpochIso(tleLine1) : null, + bstar: validLine1 ? parseTleAssumedDecimalSci(tleLine1.slice(53, 61)) : null, + inclination: validLine2 ? parseFiniteFloat(tleLine2.slice(8, 16)) : null, + raan: validLine2 ? parseFiniteFloat(tleLine2.slice(17, 25)) : null, + eccentricity: /^\d+$/.test(eccDigits) ? Number.parseFloat(`0.${eccDigits}`) : null, + arg_of_perigee: validLine2 ? parseFiniteFloat(tleLine2.slice(34, 42)) : null, + mean_anomaly: validLine2 ? parseFiniteFloat(tleLine2.slice(43, 51)) : null, + mean_motion: validLine2 ? parseFiniteFloat(tleLine2.slice(52, 63)) : null, + }; +} + +function normalizeCompactSatelliteRow(row) { + if (!Array.isArray(row) || row.length < 6) return null; + const [ + id, + noradCatId, + name, + constellationGroup, + tleLine1, + tleLine2, + fallbackElements, + ] = row; + if (noradCatId == null) return null; + + const parsed = parseTleOrbitalElements(tleLine1, tleLine2); + const fallback = Array.isArray(fallbackElements) ? fallbackElements : []; + + return { + type: "Feature", + id: noradCatId, + geometry: { type: "Point", coordinates: [0, 0, 0] }, + properties: { + id, + norad_cat_id: noradCatId, + name, + constellation_group: constellationGroup ?? null, + footprint_policy: inferSatelliteFootprintPolicy(constellationGroup), + international_designator: parsed.international_designator ?? fallback[7] ?? null, + epoch: parsed.epoch ?? fallback[6] ?? null, + inclination: parsed.inclination ?? fallback[0] ?? null, + raan: parsed.raan ?? fallback[1] ?? null, + eccentricity: parsed.eccentricity ?? fallback[2] ?? null, + arg_of_perigee: parsed.arg_of_perigee ?? fallback[3] ?? null, + mean_anomaly: parsed.mean_anomaly ?? fallback[4] ?? null, + mean_motion: parsed.mean_motion ?? fallback[5] ?? null, + bstar: parsed.bstar ?? fallback[9] ?? null, + classification_type: parsed.classification_type ?? fallback[8] ?? null, + tle_line1: tleLine1 ?? null, + tle_line2: tleLine2 ?? null, + data_type: "satellite_tle", + }, + }; +} + +export function decodeSatellitePayload(payload) { + if (payload?.format === SATELLITE_COMPACT_FORMAT && Array.isArray(payload.satellites)) { + const features = []; + for (const row of payload.satellites) { + const feature = normalizeCompactSatelliteRow(row); + if (feature) features.push(feature); + } + return features; + } + + if (Array.isArray(payload?.features)) { + return payload.features; + } + + return []; +} diff --git a/frontend/public/earth/js/satellites.js b/frontend/public/earth/js/satellites.js index 04f3551e..4c13dbef 100644 --- a/frontend/public/earth/js/satellites.js +++ b/frontend/public/earth/js/satellites.js @@ -4,6 +4,13 @@ import { createSatelliteLabels } from "./satellite-labels.js"; import { SATELLITE_CATEGORIES, satelliteCategory, satellitePixelSize } from "./satellite-display.js"; import { openOrbitSampleTimes, createOrbitFlowGeometry, createOrbitFlowMaterial } from "./satellite-orbit-visual.js"; import { createSatelliteMotion } from "./satellite-motion.js"; +import { decodeSatellitePayload } from "./satellite-catalog.js"; +import { + buildSatelliteCacheKey, + readSatelliteSnapshot, + resolveSatelliteCacheOrigin, + writeSatelliteSnapshot, +} from "./satellite-cache.js"; // satellites.js - Satellite visualization module with real SGP4 positions and animations import * as THREE from "three"; @@ -80,6 +87,11 @@ let satelliteWorkerPending = false; let satelliteWorkerDisabled = false; let pendingPositionSnapshot = null; let satelliteWorkerStartupTimer = null; +let activeSatelliteRevalidationController = null; + +const SATELLITE_FETCH_TIMEOUT_MS = 25000; +const SATELLITE_FETCH_RETRY_DELAY_MS = 800; +const SATELLITE_FETCH_MAX_ATTEMPTS = 2; const GROUND_FOOTPRINT_RENDER_ORDER = 3; @@ -778,25 +790,8 @@ function updateSatellitePointVisibilityAttributes(count = satelliteData.length) pointAlphaAttr.needsUpdate = true; } -export async function loadSatellites(options = {}) { - const limit = getRequestedSatelliteLimit(options.limit); - const url = new URL(SATELLITE_CONFIG.apiPath, window.location.origin); - if (limit !== null) { - url.searchParams.set("limit", String(limit)); - } - if (options.cacheBust) { - url.searchParams.set("_", String(Date.now())); - } - - const response = await fetch(url.toString(), { - cache: options.cache === "default" ? "default" : "no-store", - }); - if (!response.ok) { - throw new Error(`卫星接口返回 HTTP ${response.status}`); - } - - const data = await response.json(); - satelliteData = data.features || []; +function applyDecodedSatelliteFeatures(features) { + satelliteData = features; satelliteRules = satelliteData.map(satellite => satelliteCategory(satellite.properties)); satelliteCategoryCounts = new Map(); satelliteRules.forEach(rule => satelliteCategoryCounts.set(rule.key, (satelliteCategoryCounts.get(rule.key) || 0) + 1)); @@ -809,9 +804,248 @@ export async function loadSatellites(options = {}) { satelliteWorkerDisabled = false; startSatellitePositionWorker(); positionUpdateAccumulator = POSITION_UPDATE_INTERVAL_MS; +} + +function abortActiveSatelliteRevalidation() { + if (activeSatelliteRevalidationController) { + activeSatelliteRevalidationController.abort(); + activeSatelliteRevalidationController = null; + } +} + +function createAbortError(message = "Aborted") { + return typeof DOMException !== "undefined" + ? new DOMException(message, "AbortError") + : Object.assign(new Error(message), { name: "AbortError" }); +} + +function waitDelay(ms, signal) { + return new Promise((resolve, reject) => { + if (signal?.aborted) { + reject(createAbortError("Satellite retry aborted")); + return; + } + const timer = setTimeout(() => { + signal?.removeEventListener("abort", onAbort); + resolve(); + }, ms); + function onAbort() { + clearTimeout(timer); + reject(createAbortError("Satellite retry aborted")); + } + signal?.addEventListener("abort", onAbort, { once: true }); + }); +} + +async function fetchSatellitesOnce({ url, etag = null, timeoutMs = SATELLITE_FETCH_TIMEOUT_MS, signal } = {}) { + if (signal?.aborted) { + throw createAbortError("Satellite fetch aborted"); + } + const attemptController = new AbortController(); + let timedOut = false; + const onExternalAbort = () => attemptController.abort(signal.reason); + signal?.addEventListener("abort", onExternalAbort, { once: true }); + const timer = setTimeout(() => { + timedOut = true; + attemptController.abort(); + }, timeoutMs); + + const headers = {}; + if (etag) { + headers["If-None-Match"] = etag; + } + + try { + const response = await fetch(url, { + cache: "no-cache", + headers, + signal: attemptController.signal, + }); + if (response.status === 304) { + return { + notModified: true, + etag: response.headers?.get?.("etag") || etag, + }; + } + if (!response.ok) { + const error = new Error(`卫星接口返回 HTTP ${response.status}`); + error.httpStatus = response.status; + throw error; + } + const payload = await response.json(); + return { + notModified: false, + payload, + etag: response.headers?.get?.("etag") || null, + }; + } catch (error) { + if (signal?.aborted) { + throw createAbortError("Satellite fetch aborted"); + } + if (timedOut) { + const timeoutError = new Error("卫星数据加载超时,请重试"); + timeoutError.isTimeout = true; + throw timeoutError; + } + throw error; + } finally { + clearTimeout(timer); + signal?.removeEventListener("abort", onExternalAbort); + } +} + +async function fetchSatellitesWithRetry({ + url, + etag = null, + timeoutMs = SATELLITE_FETCH_TIMEOUT_MS, + maxAttempts = SATELLITE_FETCH_MAX_ATTEMPTS, + signal, +} = {}) { + let lastError = null; + for (let attempt = 1; attempt <= maxAttempts; attempt += 1) { + try { + return await fetchSatellitesOnce({ url, etag, timeoutMs, signal }); + } catch (error) { + lastError = error; + if (signal?.aborted || error?.name === "AbortError") { + throw error; + } + const status = Number(error?.httpStatus); + const retryable = !Number.isFinite(status) || status >= 500 || status === 429; + if (!retryable || attempt >= maxAttempts) { + throw error; + } + await waitDelay(SATELLITE_FETCH_RETRY_DELAY_MS, signal); + } + } + throw lastError || new Error("卫星数据加载失败"); +} + +function scheduleBackgroundSatelliteValidation({ + url, + cacheKey, + etag, + limit, + signal, + shouldApplyBackgroundUpdate, + onBackgroundUpdated, +}) { + abortActiveSatelliteRevalidation(); + const revalidationController = new AbortController(); + activeSatelliteRevalidationController = revalidationController; + const onExternalAbort = () => revalidationController.abort(signal?.reason); + signal?.addEventListener("abort", onExternalAbort, { once: true }); + + void (async () => { + try { + const result = await fetchSatellitesWithRetry({ + url, + etag, + timeoutMs: SATELLITE_FETCH_TIMEOUT_MS, + maxAttempts: 1, + signal: revalidationController.signal, + }); + if (result.notModified || !result.payload) return; + await writeSatelliteSnapshot(cacheKey, { + etag: result.etag, + payload: result.payload, + }); + if (revalidationController.signal.aborted) return; + if (typeof shouldApplyBackgroundUpdate === "function" && !shouldApplyBackgroundUpdate()) { + return; + } + const nextFeatures = decodeSatellitePayload(result.payload); + if (nextFeatures.length === 0) return; + applyDecodedSatelliteFeatures(nextFeatures); + onBackgroundUpdated?.({ + count: nextFeatures.length, + requestedLimit: limit, + fromCache: false, + }); + } catch { + // Cached full catalog is already displayed; silent conditional failure is non-fatal. + } finally { + signal?.removeEventListener("abort", onExternalAbort); + if (activeSatelliteRevalidationController === revalidationController) { + activeSatelliteRevalidationController = null; + } + } + })(); +} + +export async function loadSatellites(options = {}) { + abortActiveSatelliteRevalidation(); + const limit = getRequestedSatelliteLimit(options.limit); + const url = new URL(SATELLITE_CONFIG.apiPath, window.location.origin); + url.searchParams.set("format", "compact"); + if (limit !== null) { + url.searchParams.set("limit", String(limit)); + } + if (options.cacheBust) { + url.searchParams.set("_", String(Date.now())); + } + + const origin = await resolveSatelliteCacheOrigin(); + const cacheKey = options.cacheKey || buildSatelliteCacheKey({ + origin, + apiPath: `${SATELLITE_CONFIG.apiPath}?format=compact`, + limit, + }); + const cachedSnapshot = options.skipCache ? null : await readSatelliteSnapshot(cacheKey); + const cachedFeatures = cachedSnapshot?.payload + ? decodeSatellitePayload(cachedSnapshot.payload) + : []; + + if (!options.forceNetwork && cachedFeatures.length > 0) { + applyDecodedSatelliteFeatures(cachedFeatures); + scheduleBackgroundSatelliteValidation({ + url: url.toString(), + cacheKey, + etag: cachedSnapshot.etag, + limit, + signal: options.signal, + shouldApplyBackgroundUpdate: options.shouldApplyBackgroundUpdate, + onBackgroundUpdated: options.onBackgroundUpdated, + }); + return { + count: cachedFeatures.length, + requestedLimit: limit, + fromCache: true, + }; + } + + const networkResult = await fetchSatellitesWithRetry({ + url: url.toString(), + etag: options.forceNetwork ? null : cachedSnapshot?.etag || null, + timeoutMs: options.timeoutMs || SATELLITE_FETCH_TIMEOUT_MS, + maxAttempts: options.maxAttempts || SATELLITE_FETCH_MAX_ATTEMPTS, + signal: options.signal, + }); + + if (options.signal?.aborted) { + throw createAbortError("Satellite load aborted"); + } + + if (networkResult.notModified && cachedFeatures.length > 0) { + applyDecodedSatelliteFeatures(cachedFeatures); + return { + count: cachedFeatures.length, + requestedLimit: limit, + fromCache: true, + notModified: true, + }; + } + + const decodedFeatures = decodeSatellitePayload(networkResult.payload); + void writeSatelliteSnapshot(cacheKey, { + etag: networkResult.etag, + payload: networkResult.payload, + }); + applyDecodedSatelliteFeatures(decodedFeatures); return { - count: satelliteData.length, + count: decodedFeatures.length, requestedLimit: limit, + fromCache: false, }; } @@ -2218,6 +2452,7 @@ export function hidePredictedOrbit() { } export function clearSatelliteData() { + abortActiveSatelliteRevalidation(); satelliteLabels.dispose(); satelliteMotion.reset(); stopSatellitePositionWorker(); diff --git a/frontend/tests/satellite-catalog.test.ts b/frontend/tests/satellite-catalog.test.ts new file mode 100644 index 00000000..508f2c2e --- /dev/null +++ b/frontend/tests/satellite-catalog.test.ts @@ -0,0 +1,82 @@ +import { describe, expect, test } from "bun:test"; + +import { + decodeSatellitePayload, + inferSatelliteFootprintPolicy, + parseTleOrbitalElements, + SATELLITE_COMPACT_FORMAT, +} from "../public/earth/js/satellite-catalog.js"; + +const ISS_TLE_LINE1 = "1 25544U 98067A 26001.50000000 .00016717 00000-0 10270-3 0 9995"; +const ISS_TLE_LINE2 = "2 25544 51.6416 247.4627 0006703 130.5360 325.0288 15.72125391563537"; + +describe("satellite-catalog compact decoder & TLE parser", () => { + test("parses orbital elements accurately from standard TLE lines", () => { + const parsed = parseTleOrbitalElements(ISS_TLE_LINE1, ISS_TLE_LINE2); + + expect(parsed.classification_type).toBe("U"); + expect(parsed.international_designator).toBe("98067A"); + expect(parsed.epoch).toBe("2026-01-01T12:00:00.000Z"); + expect(parsed.bstar).toBeCloseTo(0.0001027, 8); + expect(parsed.inclination).toBeCloseTo(51.6416, 4); + expect(parsed.raan).toBeCloseTo(247.4627, 4); + expect(parsed.eccentricity).toBeCloseTo(0.0006703, 7); + expect(parsed.arg_of_perigee).toBeCloseTo(130.536, 4); + expect(parsed.mean_anomaly).toBeCloseTo(325.0288, 4); + expect(parsed.mean_motion).toBeCloseTo(15.72125391, 8); + }); + + test("maps footprint policy per constellation group", () => { + expect(inferSatelliteFootprintPolicy("starlink")).toBe("starlink_ground_footprint"); + expect(inferSatelliteFootprintPolicy("iridium-next")).toBe("iridium_coverage_ring"); + expect(inferSatelliteFootprintPolicy("leo")).toBe("none"); + }); + + test("decodes compact rows with TLE and fallback rows without TLE", () => { + const features = decodeSatellitePayload({ + format: SATELLITE_COMPACT_FORMAT, + count: 2, + satellites: [ + [101, 25544, "ISS (ZARYA)", "starlink", ISS_TLE_LINE1, ISS_TLE_LINE2], + [ + 102, + 55000, + "CUSTOM-SAT", + "iridium-next", + null, + null, + [86.4, 10.2, 0.001, 45.0, 90.0, 14.3, "2026-02-01T00:00:00Z", "24010A", "U", 0.0002], + ], + ], + }); + + expect(features).toHaveLength(2); + expect(features[0].id).toBe(25544); + expect(features[0].properties.norad_cat_id).toBe(25544); + expect(features[0].properties.footprint_policy).toBe("starlink_ground_footprint"); + expect(features[0].properties.inclination).toBeCloseTo(51.6416, 4); + expect(features[0].properties.tle_line1).toBe(ISS_TLE_LINE1); + expect(features[0].properties.data_type).toBe("satellite_tle"); + + expect(features[1].properties.footprint_policy).toBe("iridium_coverage_ring"); + expect(features[1].properties.inclination).toBe(86.4); + expect(features[1].properties.international_designator).toBe("24010A"); + expect(features[1].properties.bstar).toBe(0.0002); + }); + + test("passes through legacy GeoJSON FeatureCollection payloads unchanged", () => { + const legacyFeature = { + type: "Feature", + id: 25544, + geometry: { type: "Point", coordinates: [0, 0, 0] }, + properties: { norad_cat_id: 25544, name: "ISS (ZARYA)" }, + }; + + const features = decodeSatellitePayload({ + type: "FeatureCollection", + features: [legacyFeature], + }); + + expect(features).toEqual([legacyFeature]); + }); +}); diff --git a/pyproject.toml b/pyproject.toml index 3497cf3f..a56ca6ce 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "planet" -version = "0.79.1" +version = "0.79.2" description = "智能星球计划 - 态势感知系统" requires-python = ">=3.14" dependencies = [ diff --git a/uv.lock b/uv.lock index d4999799..4f529896 100644 --- a/uv.lock +++ b/uv.lock @@ -757,7 +757,7 @@ wheels = [ [[package]] name = "planet" -version = "0.79.1" +version = "0.79.2" source = { virtual = "." } dependencies = [ { name = "aiofiles" },