Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b7772f664c | ||
|
|
352b34e7c6 | ||
|
|
1e9508f2f1 |
No files matched your search
@@ -179,12 +179,19 @@ Push to remote:
|
||||
### Step 9 — Publish and verify the Gitea Release
|
||||
|
||||
When remote publication is requested, verify the remote tag points to the
|
||||
release commit. Check the tag's Gitea Actions run and its release job. A queued
|
||||
run without an online runner does not publish anything.
|
||||
release commit. For `gitea.rclaw.top/linkong/planet`, publish from the workstation
|
||||
using the command below. The publisher builds the three production images and
|
||||
the desktop packages from the tag. A published stable release triggers the
|
||||
server's two-minute Compose deployment check. The workstation can go offline
|
||||
after publication. Check the live update manifest and the running image digests
|
||||
before reporting production deployment complete.
|
||||
|
||||
If the job cannot start or finish, use the packaged client artifacts for the
|
||||
exact tag. Reuse verified artifacts when available, or build with Bun from the
|
||||
tag in a clean checkout. Use an asset directory that contains only this release.
|
||||
```bash
|
||||
python3 scripts/release_publish.py --tag vx.x.x --use-git-credential
|
||||
```
|
||||
|
||||
When verified desktop artifacts for the exact tag already exist, pass their
|
||||
directory explicitly. A queued Gitea Actions run does not block local publication.
|
||||
|
||||
```bash
|
||||
python3 scripts/release_publish.py --tag vx.x.x --assets-dir client/release --dry-run
|
||||
|
||||
@@ -4,8 +4,7 @@ on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
tags:
|
||||
- "v*"
|
||||
# Tagged production releases are published on demand from the workstation.
|
||||
workflow_dispatch:
|
||||
|
||||
env:
|
||||
@@ -17,18 +16,18 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Resolve image tags
|
||||
id: meta
|
||||
run: |
|
||||
echo "sha_tag=${GITHUB_SHA}" >> "$GITHUB_OUTPUT"
|
||||
if printf "%s" "${GITHUB_REF}" | grep -q '^refs/tags/v'; then
|
||||
echo "release_tag=${GITHUB_REF_NAME}" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "release_tag=" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
- name: Login to registry
|
||||
run: echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login "$REGISTRY" -u "${{ secrets.REGISTRY_USER }}" --password-stdin
|
||||
- name: Build and push images
|
||||
env:
|
||||
REGISTRY_USER: ${{ secrets.REGISTRY_USER }}
|
||||
REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }}
|
||||
run: printf '%s' "$REGISTRY_PASSWORD" | docker login "$REGISTRY" -u "$REGISTRY_USER" --password-stdin
|
||||
- name: Publish immutable production images
|
||||
if: startsWith(github.ref, 'refs/tags/v')
|
||||
run: |
|
||||
export PLANET_RELEASE_DOCKER_CONFIG="${DOCKER_CONFIG:-$HOME/.docker}"
|
||||
python3 scripts/production_release.py "$GITHUB_REF_NAME"
|
||||
- name: Build and push staging images
|
||||
if: "!startsWith(github.ref, 'refs/tags/v')"
|
||||
run: |
|
||||
for service in frontend admin backend aiprovider; do
|
||||
extra_build_args=""
|
||||
@@ -52,18 +51,13 @@ jobs:
|
||||
;;
|
||||
esac
|
||||
|
||||
image="$REGISTRY/$IMAGE_NAMESPACE/$service:${{ steps.meta.outputs.sha_tag }}"
|
||||
image="$REGISTRY/$IMAGE_NAMESPACE/$service:$GITHUB_SHA"
|
||||
docker build $extra_build_args -t "$image" -f "$dockerfile" "$context"
|
||||
docker push "$image"
|
||||
|
||||
if [ -n "${{ steps.meta.outputs.release_tag }}" ]; then
|
||||
release_image="$REGISTRY/$IMAGE_NAMESPACE/$service:${{ steps.meta.outputs.release_tag }}"
|
||||
docker tag "$image" "$release_image"
|
||||
docker push "$release_image"
|
||||
fi
|
||||
done
|
||||
|
||||
client_release:
|
||||
needs: images
|
||||
if: startsWith(github.ref, 'refs/tags/v')
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
@@ -82,12 +76,8 @@ jobs:
|
||||
- name: Publish Gitea Release with client packages
|
||||
env:
|
||||
GITEA_TOKEN: ${{ secrets.RELEASE_TOKEN || github.token }}
|
||||
CLIENT_UPDATE_PUBLISH_URL: ${{ secrets.CLIENT_UPDATE_PUBLISH_URL }}
|
||||
CLIENT_UPDATE_PUBLISH_TOKEN: ${{ secrets.CLIENT_UPDATE_PUBLISH_TOKEN }}
|
||||
run: |
|
||||
python3 scripts/release_publish.py \
|
||||
--tag "${GITHUB_REF_NAME}" \
|
||||
--assets-dir client/release \
|
||||
--changelog docs/CHANGELOG.md \
|
||||
--hotfix-publish-url "${CLIENT_UPDATE_PUBLISH_URL}" \
|
||||
--hotfix-publish-token "${CLIENT_UPDATE_PUBLISH_TOKEN}"
|
||||
--changelog docs/CHANGELOG.md
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -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)
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "planet-client",
|
||||
"version": "0.79.0",
|
||||
"version": "0.79.2",
|
||||
"description": "Intelligent Planet Program - Native Electron Earth Viewer",
|
||||
"private": true,
|
||||
"packageManager": "bun@1",
|
||||
|
||||
+137
-12
@@ -2,6 +2,7 @@ import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
|
||||
export type SplashTheme = 'singularity' | 'off'
|
||||
export type GpuRenderMode = 'auto' | 'high-performance' | 'low-power' | 'software'
|
||||
|
||||
export interface ServerEndpoints {
|
||||
backendUrl: string
|
||||
@@ -11,6 +12,23 @@ export interface ServerEndpoints {
|
||||
|
||||
export interface PersistedUserConfig extends Partial<ServerEndpoints> {
|
||||
splashTheme?: SplashTheme
|
||||
gpuMode?: GpuRenderMode
|
||||
}
|
||||
|
||||
export type GpuHandoffTarget = 'default' | 'high-performance' | 'low-power' | 'software'
|
||||
|
||||
export function normalizeGpuHandoffTarget(raw: unknown): GpuHandoffTarget | undefined {
|
||||
if (typeof raw !== 'string') return undefined
|
||||
const normalized = raw.trim().toLowerCase()
|
||||
if (
|
||||
normalized === 'default' ||
|
||||
normalized === 'high-performance' ||
|
||||
normalized === 'low-power' ||
|
||||
normalized === 'software'
|
||||
) {
|
||||
return normalized
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
export interface DesktopLaunchFlags {
|
||||
@@ -22,11 +40,15 @@ export interface DesktopLaunchFlags {
|
||||
smokeOutputPath: string | null
|
||||
deepLinkUrl: string | null
|
||||
splashThemeOverride?: SplashTheme
|
||||
gpuModeOverride?: GpuRenderMode
|
||||
gpuHandoff: boolean
|
||||
gpuHandoffTarget?: GpuHandoffTarget
|
||||
}
|
||||
|
||||
export interface DesktopRuntimeConfig extends ServerEndpoints, DesktopLaunchFlags {
|
||||
wsUrl: string
|
||||
splashTheme: SplashTheme
|
||||
gpuMode: GpuRenderMode
|
||||
}
|
||||
|
||||
const LEGACY_ACTIVE_THEMES: ReadonlySet<string> = new Set([
|
||||
@@ -47,6 +69,35 @@ export function normalizeSplashTheme(
|
||||
return LEGACY_ACTIVE_THEMES.has(normalized) ? 'singularity' : fallback
|
||||
}
|
||||
|
||||
export function normalizeGpuMode(
|
||||
raw: unknown,
|
||||
fallback: GpuRenderMode = 'auto',
|
||||
): GpuRenderMode {
|
||||
if (typeof raw !== 'string') return fallback
|
||||
const normalized = raw.trim().toLowerCase()
|
||||
if (normalized === 'auto') return 'auto'
|
||||
if (
|
||||
normalized === 'high-performance' ||
|
||||
normalized === 'high' ||
|
||||
normalized === 'discrete' ||
|
||||
normalized === 'dgpu'
|
||||
) {
|
||||
return 'high-performance'
|
||||
}
|
||||
if (
|
||||
normalized === 'low-power' ||
|
||||
normalized === 'low' ||
|
||||
normalized === 'integrated' ||
|
||||
normalized === 'igpu'
|
||||
) {
|
||||
return 'low-power'
|
||||
}
|
||||
if (normalized === 'software' || normalized === 'cpu' || normalized === 'swiftshader') {
|
||||
return 'software'
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
export const DEFAULT_ENDPOINTS: Readonly<ServerEndpoints> = {
|
||||
backendUrl: 'https://rclaw.top',
|
||||
adminUrl: 'https://admin.rclaw.top',
|
||||
@@ -115,6 +166,7 @@ export function parseLaunchArgs(argv: string[]): {
|
||||
headlessSmoke: false,
|
||||
smokeOutputPath: null,
|
||||
deepLinkUrl: null,
|
||||
gpuHandoff: false,
|
||||
}
|
||||
|
||||
for (let i = 0; i < argv.length; i += 1) {
|
||||
@@ -136,6 +188,22 @@ export function parseLaunchArgs(argv: string[]): {
|
||||
flags.splashThemeOverride = normalizeSplashTheme(arg.slice('--splash-theme='.length))
|
||||
} else if (arg === '--splash-theme' && argv[i + 1]) {
|
||||
flags.splashThemeOverride = normalizeSplashTheme(argv[++i])
|
||||
} else if (arg.startsWith('--gpu-mode=')) {
|
||||
flags.gpuModeOverride = normalizeGpuMode(arg.slice('--gpu-mode='.length))
|
||||
} else if (arg === '--gpu-mode' && argv[i + 1]) {
|
||||
flags.gpuModeOverride = normalizeGpuMode(argv[++i])
|
||||
} else if (arg === '--software-gl') {
|
||||
flags.gpuModeOverride = 'software'
|
||||
} else if (arg === '--low-power-gpu') {
|
||||
flags.gpuModeOverride = 'low-power'
|
||||
} else if (arg === '--high-performance-gpu') {
|
||||
flags.gpuModeOverride = 'high-performance'
|
||||
} else if (arg === '--gpu-handoff') {
|
||||
flags.gpuHandoff = true
|
||||
} else if (arg.startsWith('--gpu-handoff-target=')) {
|
||||
flags.gpuHandoffTarget = normalizeGpuHandoffTarget(arg.slice('--gpu-handoff-target='.length))
|
||||
} else if (arg === '--gpu-handoff-target' && argv[i + 1]) {
|
||||
flags.gpuHandoffTarget = normalizeGpuHandoffTarget(argv[++i])
|
||||
} else if (arg === '--fullscreen') {
|
||||
flags.fullscreen = true
|
||||
} else if (arg === '--kiosk') {
|
||||
@@ -157,6 +225,55 @@ export function parseLaunchArgs(argv: string[]): {
|
||||
return { endpoints, flags }
|
||||
}
|
||||
|
||||
function getPortableConfigPaths(exeDir: string, resourcesDir?: string): string[] {
|
||||
const candidates: string[] = []
|
||||
if (exeDir) {
|
||||
candidates.push(path.join(exeDir, 'planet-earth.json'))
|
||||
}
|
||||
if (resourcesDir) {
|
||||
candidates.push(path.join(resourcesDir, 'planet-earth.json'))
|
||||
}
|
||||
return candidates
|
||||
}
|
||||
|
||||
function readFirstPortableConfig(paths: string[]): PersistedUserConfig {
|
||||
for (const candidate of paths) {
|
||||
const data = readJsonFileSafe(candidate)
|
||||
if (Object.keys(data).length > 0) {
|
||||
return data
|
||||
}
|
||||
}
|
||||
return {}
|
||||
}
|
||||
|
||||
export function readPreReadyGpuMode(options: {
|
||||
userDataDir: string
|
||||
exeDir: string
|
||||
resourcesDir?: string
|
||||
argv: string[]
|
||||
env?: NodeJS.ProcessEnv
|
||||
}): GpuRenderMode {
|
||||
const env = options.env ?? process.env
|
||||
const { flags } = parseLaunchArgs(options.argv)
|
||||
const portable = readFirstPortableConfig(getPortableConfigPaths(options.exeDir, options.resourcesDir))
|
||||
const userSaved = options.userDataDir ? readJsonFileSafe(path.join(options.userDataDir, 'config.json')) : {}
|
||||
return normalizeGpuMode(
|
||||
flags.gpuModeOverride ?? env.PLANET_GPU_MODE ?? portable.gpuMode ?? userSaved.gpuMode,
|
||||
'auto',
|
||||
)
|
||||
}
|
||||
|
||||
export function readPreReadyGpuHandoff(argv: string[]): {
|
||||
gpuHandoff: boolean
|
||||
gpuHandoffTarget?: GpuHandoffTarget
|
||||
} {
|
||||
const { flags } = parseLaunchArgs(argv)
|
||||
return {
|
||||
gpuHandoff: flags.gpuHandoff,
|
||||
gpuHandoffTarget: flags.gpuHandoffTarget,
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopConfigStore {
|
||||
private readonly userConfigPath: string
|
||||
private readonly portableConfigPaths: string[]
|
||||
@@ -172,10 +289,7 @@ export class DesktopConfigStore {
|
||||
env?: NodeJS.ProcessEnv
|
||||
}) {
|
||||
this.userConfigPath = path.join(options.userDataDir, 'config.json')
|
||||
this.portableConfigPaths = [
|
||||
path.join(options.exeDir, 'planet-earth.json'),
|
||||
...(options.resourcesDir ? [path.join(options.resourcesDir, 'planet-earth.json')] : []),
|
||||
]
|
||||
this.portableConfigPaths = getPortableConfigPaths(options.exeDir, options.resourcesDir)
|
||||
const parsed = parseLaunchArgs(options.argv)
|
||||
this.cliEndpoints = parsed.endpoints
|
||||
this.launchFlags = parsed.flags
|
||||
@@ -184,14 +298,7 @@ export class DesktopConfigStore {
|
||||
|
||||
private resolve(env: NodeJS.ProcessEnv): DesktopRuntimeConfig {
|
||||
const userSaved = readJsonFileSafe(this.userConfigPath)
|
||||
let portable: PersistedUserConfig = {}
|
||||
for (const candidate of this.portableConfigPaths) {
|
||||
const data = readJsonFileSafe(candidate)
|
||||
if (Object.keys(data).length > 0) {
|
||||
portable = data
|
||||
break
|
||||
}
|
||||
}
|
||||
const portable = readFirstPortableConfig(this.portableConfigPaths)
|
||||
|
||||
const backendUrl = normalizeHttpUrl(
|
||||
this.cliEndpoints.backendUrl ?? env.PLANET_BACKEND_URL ?? portable.backendUrl ?? userSaved.backendUrl,
|
||||
@@ -212,6 +319,13 @@ export class DesktopConfigStore {
|
||||
userSaved.splashTheme,
|
||||
'singularity',
|
||||
)
|
||||
const gpuMode = normalizeGpuMode(
|
||||
this.launchFlags.gpuModeOverride ??
|
||||
env.PLANET_GPU_MODE ??
|
||||
portable.gpuMode ??
|
||||
userSaved.gpuMode,
|
||||
'auto',
|
||||
)
|
||||
|
||||
return {
|
||||
backendUrl,
|
||||
@@ -219,6 +333,7 @@ export class DesktopConfigStore {
|
||||
motionWsUrl,
|
||||
wsUrl: deriveBackendWsUrl(backendUrl),
|
||||
splashTheme,
|
||||
gpuMode,
|
||||
...this.launchFlags,
|
||||
}
|
||||
}
|
||||
@@ -260,4 +375,14 @@ export class DesktopConfigStore {
|
||||
}
|
||||
return this.get()
|
||||
}
|
||||
|
||||
updateGpuMode(rawMode: unknown): DesktopRuntimeConfig {
|
||||
const nextMode = normalizeGpuMode(rawMode, this.current.gpuMode)
|
||||
this.writeUserConfig({ gpuMode: nextMode })
|
||||
this.current = {
|
||||
...this.current,
|
||||
gpuMode: nextMode,
|
||||
}
|
||||
return this.get()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
import { execFile, execFileSync } from 'node:child_process'
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { promisify } from 'node:util'
|
||||
|
||||
import type { BrowserWindow } from 'electron'
|
||||
|
||||
import type { GpuRenderMode } from './config'
|
||||
import {
|
||||
canAutoSwitchGpu,
|
||||
createVramHysteresisTracker,
|
||||
detectIntegratedGpuFromRegistryOutput,
|
||||
parseNvidiaSmiCsv,
|
||||
VRAM_LOW_THRESHOLD_MIB,
|
||||
VRAM_MONITOR_INTERVAL_MS,
|
||||
type DiscreteVramSample,
|
||||
type ResolvedGpuTarget,
|
||||
type StartupGpuDecision,
|
||||
type StartupGpuDecisionReason,
|
||||
} from './gpu-policy'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
const HANDOFF_RECORD_MAX_AGE_MS = 30_000
|
||||
const HANDOFF_RECORD_FILE = 'gpu-handoff.json'
|
||||
|
||||
const NVIDIA_SMI_ARGS = [
|
||||
'--query-gpu=name,memory.used,memory.free,memory.total',
|
||||
'--format=csv,noheader,nounits',
|
||||
]
|
||||
|
||||
const DISPLAY_CLASS_REG_ARGS = [
|
||||
'query',
|
||||
'HKLM\\SYSTEM\\CurrentControlSet\\Control\\Class\\{4d36e968-e325-11ce-bfc1-08002be10318}',
|
||||
'/s',
|
||||
'/v',
|
||||
'DriverDesc',
|
||||
]
|
||||
|
||||
export interface GpuHandoffRecord {
|
||||
lastSwitchAt: number
|
||||
target: ResolvedGpuTarget
|
||||
reason: 'low-fps-low-vram' | 'vram-recovered' | 'manual'
|
||||
freeMiB?: number
|
||||
avgFps?: number
|
||||
}
|
||||
|
||||
export interface GpuRuntimeSummary {
|
||||
requestedMode: GpuRenderMode
|
||||
activeTarget: ResolvedGpuTarget
|
||||
reason: StartupGpuDecisionReason
|
||||
hasIntegratedGpu: boolean
|
||||
latestVramSample: DiscreteVramSample | null
|
||||
}
|
||||
|
||||
export interface AdaptiveGpuMonitor {
|
||||
start(): void
|
||||
stop(): void
|
||||
handleLowFpsReport(report: { avgFps: number; sustainedMs: number }): Promise<void>
|
||||
consumePendingHandoffToast(): { message: string; type: 'info' | 'success' } | null
|
||||
getRuntimeSummary(): GpuRuntimeSummary
|
||||
}
|
||||
|
||||
export function readGpuHandoffRecord(userDataDir: string): GpuHandoffRecord | null {
|
||||
if (!userDataDir) return null
|
||||
try {
|
||||
const filePath = path.join(userDataDir, HANDOFF_RECORD_FILE)
|
||||
if (!fs.existsSync(filePath)) return null
|
||||
const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8')) as Partial<GpuHandoffRecord>
|
||||
if (
|
||||
!parsed ||
|
||||
typeof parsed.lastSwitchAt !== 'number' ||
|
||||
!Number.isFinite(parsed.lastSwitchAt) ||
|
||||
typeof parsed.target !== 'string' ||
|
||||
typeof parsed.reason !== 'string'
|
||||
) {
|
||||
return null
|
||||
}
|
||||
return parsed as GpuHandoffRecord
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export function writeGpuHandoffRecord(userDataDir: string, record: GpuHandoffRecord): void {
|
||||
if (!userDataDir) return
|
||||
try {
|
||||
const filePath = path.join(userDataDir, HANDOFF_RECORD_FILE)
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true })
|
||||
fs.writeFileSync(filePath, `${JSON.stringify(record, null, 2)}\n`, 'utf8')
|
||||
} catch {
|
||||
// Ignore non-critical handoff state write failures.
|
||||
}
|
||||
}
|
||||
|
||||
export function probeWindowsGpuEnvironmentSync(): {
|
||||
vramSample: DiscreteVramSample | null
|
||||
hasIntegratedGpu: boolean
|
||||
} {
|
||||
if (process.platform !== 'win32') {
|
||||
return { vramSample: null, hasIntegratedGpu: false }
|
||||
}
|
||||
|
||||
let vramSample: DiscreteVramSample | null = null
|
||||
try {
|
||||
const out = execFileSync('nvidia-smi', NVIDIA_SMI_ARGS, {
|
||||
encoding: 'utf8',
|
||||
timeout: 800,
|
||||
windowsHide: true,
|
||||
stdio: ['ignore', 'pipe', 'ignore'],
|
||||
})
|
||||
vramSample = parseNvidiaSmiCsv(out)
|
||||
} catch {
|
||||
vramSample = null
|
||||
}
|
||||
|
||||
let hasIntegratedGpu = false
|
||||
try {
|
||||
const out = execFileSync('reg.exe', DISPLAY_CLASS_REG_ARGS, {
|
||||
encoding: 'utf8',
|
||||
timeout: 800,
|
||||
windowsHide: true,
|
||||
stdio: ['ignore', 'pipe', 'ignore'],
|
||||
})
|
||||
hasIntegratedGpu = detectIntegratedGpuFromRegistryOutput(out)
|
||||
} catch {
|
||||
hasIntegratedGpu = false
|
||||
}
|
||||
|
||||
return { vramSample, hasIntegratedGpu }
|
||||
}
|
||||
|
||||
export async function probeDiscreteVramAsync(): Promise<DiscreteVramSample | null> {
|
||||
if (process.platform !== 'win32') {
|
||||
return null
|
||||
}
|
||||
try {
|
||||
const { stdout } = await execFileAsync('nvidia-smi', NVIDIA_SMI_ARGS, {
|
||||
encoding: 'utf8',
|
||||
timeout: 2000,
|
||||
windowsHide: true,
|
||||
})
|
||||
return parseNvidiaSmiCsv(stdout)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export async function probeIntegratedGpuAsync(): Promise<boolean> {
|
||||
if (process.platform !== 'win32') {
|
||||
return false
|
||||
}
|
||||
try {
|
||||
const { stdout } = await execFileAsync('reg.exe', DISPLAY_CLASS_REG_ARGS, {
|
||||
encoding: 'utf8',
|
||||
timeout: 2000,
|
||||
windowsHide: true,
|
||||
})
|
||||
return detectIntegratedGpuFromRegistryOutput(stdout)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export function createAdaptiveGpuMonitor(options: {
|
||||
userDataDir: string
|
||||
startupDecision: StartupGpuDecision
|
||||
getConfiguredMode: () => GpuRenderMode
|
||||
getMainWindow: () => BrowserWindow | null
|
||||
onAutoSwitch: (target: ResolvedGpuTarget, record: GpuHandoffRecord) => void
|
||||
onStatusUpdated?: () => void
|
||||
}): AdaptiveGpuMonitor {
|
||||
let latestVramSample: DiscreteVramSample | null = options.startupDecision.vramSample
|
||||
let switching = false
|
||||
let toastConsumed = false
|
||||
let intervalTimer: ReturnType<typeof setInterval> | null = null
|
||||
const lastSwitchAt = readGpuHandoffRecord(options.userDataDir)?.lastSwitchAt ?? null
|
||||
|
||||
const activeTarget = options.startupDecision.target
|
||||
const isDiscrete = activeTarget === 'default' || activeTarget === 'high-performance'
|
||||
const isOffloaded = activeTarget === 'low-power' || activeTarget === 'software'
|
||||
|
||||
const tracker = createVramHysteresisTracker({
|
||||
activeTarget,
|
||||
hasIntegratedGpu: options.startupDecision.hasIntegratedGpu,
|
||||
})
|
||||
|
||||
const triggerAutoSwitch = (target: ResolvedGpuTarget, record: GpuHandoffRecord) => {
|
||||
if (switching) return
|
||||
switching = true
|
||||
if (intervalTimer) {
|
||||
clearInterval(intervalTimer)
|
||||
intervalTimer = null
|
||||
}
|
||||
writeGpuHandoffRecord(options.userDataDir, record)
|
||||
options.onAutoSwitch(target, record)
|
||||
}
|
||||
|
||||
const tickOffloadedRecovery = async () => {
|
||||
if (switching || !isOffloaded || options.getConfiguredMode() !== 'auto') return
|
||||
if (!canAutoSwitchGpu(lastSwitchAt, Date.now())) return
|
||||
const win = options.getMainWindow()
|
||||
if (!win || win.isDestroyed() || win.isMinimized()) return
|
||||
|
||||
const sample = await probeDiscreteVramAsync()
|
||||
latestVramSample = sample
|
||||
options.onStatusUpdated?.()
|
||||
|
||||
if (switching || options.getConfiguredMode() !== 'auto') return
|
||||
const action = tracker.observe(sample)
|
||||
if (!action || action.kind !== 'switch-to-discrete') return
|
||||
|
||||
const now = Date.now()
|
||||
if (!canAutoSwitchGpu(lastSwitchAt, now)) return
|
||||
console.info(
|
||||
`[planet-client] Discrete GPU VRAM recovered (freeMiB=${action.sample.freeMiB}); auto-switching back to discrete GPU`,
|
||||
)
|
||||
triggerAutoSwitch('default', {
|
||||
lastSwitchAt: now,
|
||||
target: 'default',
|
||||
reason: 'vram-recovered',
|
||||
freeMiB: action.sample.freeMiB,
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
start() {
|
||||
if (process.platform !== 'win32' || options.startupDecision.reason === 'headless-smoke') {
|
||||
return
|
||||
}
|
||||
if (!isOffloaded || intervalTimer) return
|
||||
intervalTimer = setInterval(() => {
|
||||
void tickOffloadedRecovery()
|
||||
}, VRAM_MONITOR_INTERVAL_MS)
|
||||
},
|
||||
|
||||
stop() {
|
||||
if (intervalTimer) {
|
||||
clearInterval(intervalTimer)
|
||||
intervalTimer = null
|
||||
}
|
||||
},
|
||||
|
||||
async handleLowFpsReport(report: { avgFps: number; sustainedMs: number }): Promise<void> {
|
||||
if (
|
||||
process.platform !== 'win32' ||
|
||||
options.startupDecision.reason === 'headless-smoke' ||
|
||||
switching ||
|
||||
!isDiscrete ||
|
||||
options.getConfiguredMode() !== 'auto'
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
const now = Date.now()
|
||||
if (!canAutoSwitchGpu(lastSwitchAt, now)) return
|
||||
|
||||
const sample = await probeDiscreteVramAsync()
|
||||
latestVramSample = sample
|
||||
options.onStatusUpdated?.()
|
||||
|
||||
if (
|
||||
switching ||
|
||||
options.getConfiguredMode() !== 'auto' ||
|
||||
!sample ||
|
||||
sample.freeMiB >= VRAM_LOW_THRESHOLD_MIB
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
const hasIgpu = options.startupDecision.hasIntegratedGpu || (await probeIntegratedGpuAsync())
|
||||
const nextTarget: ResolvedGpuTarget = hasIgpu ? 'low-power' : 'software'
|
||||
const switchNow = Date.now()
|
||||
if (!canAutoSwitchGpu(lastSwitchAt, switchNow)) return
|
||||
|
||||
console.info(
|
||||
`[planet-client] Sustained low FPS (${report.avgFps} fps for ${report.sustainedMs}ms) with low discrete VRAM (freeMiB=${sample.freeMiB}); auto-switching to ${nextTarget}`,
|
||||
)
|
||||
triggerAutoSwitch(nextTarget, {
|
||||
lastSwitchAt: switchNow,
|
||||
target: nextTarget,
|
||||
reason: 'low-fps-low-vram',
|
||||
freeMiB: sample.freeMiB,
|
||||
avgFps: report.avgFps,
|
||||
})
|
||||
},
|
||||
|
||||
consumePendingHandoffToast(): { message: string; type: 'info' | 'success' } | null {
|
||||
if (toastConsumed || options.startupDecision.reason !== 'gpu-handoff') {
|
||||
return null
|
||||
}
|
||||
toastConsumed = true
|
||||
const record = readGpuHandoffRecord(options.userDataDir)
|
||||
if (!record || Date.now() - record.lastSwitchAt >= HANDOFF_RECORD_MAX_AGE_MS) {
|
||||
return null
|
||||
}
|
||||
if (record.reason === 'low-fps-low-vram') {
|
||||
return record.target === 'software'
|
||||
? { message: '独显显存不足且帧率偏低,已自动切换至 CPU 软渲染', type: 'info' }
|
||||
: {
|
||||
message: '独显显存不足且帧率偏低,已自动切换至集成核显渲染(保留全部特效)',
|
||||
type: 'info',
|
||||
}
|
||||
}
|
||||
if (record.reason === 'vram-recovered') {
|
||||
return { message: '独显显存已充足,已自动切回独立显卡渲染', type: 'success' }
|
||||
}
|
||||
return null
|
||||
},
|
||||
|
||||
getRuntimeSummary(): GpuRuntimeSummary {
|
||||
return {
|
||||
requestedMode: options.getConfiguredMode(),
|
||||
activeTarget: options.startupDecision.target,
|
||||
reason: options.startupDecision.reason,
|
||||
hasIntegratedGpu: options.startupDecision.hasIntegratedGpu,
|
||||
latestVramSample,
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,168 @@
|
||||
import type { GpuRenderMode } from './config'
|
||||
|
||||
export const VRAM_LOW_THRESHOLD_MIB = 2048
|
||||
export const VRAM_RECOVER_THRESHOLD_MIB = 3584
|
||||
export const VRAM_MONITOR_INTERVAL_MS = 5_000
|
||||
export const VRAM_SWITCH_CONSECUTIVE_REQUIRED = 2
|
||||
export const LOW_FPS_THRESHOLD = 20
|
||||
export const LOW_FPS_SUSTAINED_MS = 5_000
|
||||
export const FPS_STARTUP_WARMUP_MS = 6_000
|
||||
export const FPS_REPORT_COOLDOWN_MS = 15_000
|
||||
export const AUTO_SWITCH_COOLDOWN_MS = 45_000
|
||||
|
||||
export interface ChromiumSwitch {
|
||||
name: string
|
||||
value?: string
|
||||
}
|
||||
|
||||
export type ResolvedGpuTarget = 'default' | 'high-performance' | 'low-power' | 'software'
|
||||
|
||||
export interface DiscreteVramSample {
|
||||
gpuName: string
|
||||
usedMiB: number
|
||||
freeMiB: number
|
||||
totalMiB: number
|
||||
}
|
||||
|
||||
export type StartupGpuDecisionReason =
|
||||
| 'headless-smoke'
|
||||
| 'gpu-handoff'
|
||||
| 'user-software'
|
||||
| 'user-low-power'
|
||||
| 'user-high-performance'
|
||||
| 'low-vram-igpu'
|
||||
| 'low-vram-software'
|
||||
| 'normal-gpu'
|
||||
|
||||
export interface StartupGpuDecision {
|
||||
target: ResolvedGpuTarget
|
||||
requestedMode: GpuRenderMode
|
||||
reason: StartupGpuDecisionReason
|
||||
vramSample: DiscreteVramSample | null
|
||||
hasIntegratedGpu: boolean
|
||||
}
|
||||
|
||||
export interface VramMonitorAction {
|
||||
kind: 'switch-to-discrete' | 'switch-to-low-power' | 'switch-to-software'
|
||||
sample: DiscreteVramSample
|
||||
}
|
||||
|
||||
export interface GpuPolicyInput {
|
||||
platform: NodeJS.Platform
|
||||
headlessSmoke: boolean
|
||||
softwareGl: boolean
|
||||
softwareGl?: boolean
|
||||
target?: ResolvedGpuTarget
|
||||
}
|
||||
|
||||
const VIRTUAL_DISPLAY_ADAPTER_RE = /microsoft basic|remote display|parsec|virtual|indirect|mirage/i
|
||||
const INTEL_ADAPTER_RE = /\bintel\b/i
|
||||
const INTEL_DISCRETE_ARC_RE = /\barc\b.*\b[ab]\d{3}\b/i
|
||||
const AMD_INTEGRATED_RE = /\bamd\s+radeon(?:\(tm\))?\s+(?:graphics|\d+m\b|vega\s+\d+\s+graphics)/i
|
||||
|
||||
function parseMiBField(raw: string | undefined): number | null {
|
||||
if (!raw) return null
|
||||
const trimmed = raw.trim()
|
||||
if (!trimmed || /n\/a/i.test(trimmed)) return null
|
||||
const cleaned = trimmed.replace(/\s*mib$/i, '')
|
||||
if (!/^\d+(?:\.\d+)?$/.test(cleaned)) return null
|
||||
const num = Number(cleaned)
|
||||
return Number.isFinite(num) ? num : null
|
||||
}
|
||||
|
||||
export function parseNvidiaSmiCsv(stdout: string): DiscreteVramSample | null {
|
||||
if (!stdout) return null
|
||||
for (const rawLine of stdout.split(/\r?\n/)) {
|
||||
const line = rawLine.trim()
|
||||
if (!line) continue
|
||||
const parts = line.split(',')
|
||||
if (parts.length < 4) continue
|
||||
const gpuName = parts.slice(0, -3).join(',').trim()
|
||||
const usedMiB = parseMiBField(parts[parts.length - 3])
|
||||
const freeMiB = parseMiBField(parts[parts.length - 2])
|
||||
const totalMiB = parseMiBField(parts[parts.length - 1])
|
||||
if (
|
||||
!gpuName ||
|
||||
usedMiB === null ||
|
||||
freeMiB === null ||
|
||||
totalMiB === null ||
|
||||
usedMiB < 0 ||
|
||||
freeMiB < 0 ||
|
||||
totalMiB <= 0
|
||||
) {
|
||||
continue
|
||||
}
|
||||
return { gpuName, usedMiB, freeMiB, totalMiB }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export function detectIntegratedGpuFromRegistryOutput(stdout: string): boolean {
|
||||
if (!stdout) return false
|
||||
for (const rawLine of stdout.split(/\r?\n/)) {
|
||||
const match = /^\s*DriverDesc\s+REG_SZ\s+(.+?)\s*$/i.exec(rawLine)
|
||||
if (!match) continue
|
||||
const desc = match[1].trim()
|
||||
if (!desc || VIRTUAL_DISPLAY_ADAPTER_RE.test(desc)) continue
|
||||
if (INTEL_ADAPTER_RE.test(desc) && !INTEL_DISCRETE_ARC_RE.test(desc)) {
|
||||
return true
|
||||
}
|
||||
if (AMD_INTEGRATED_RE.test(desc)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
export function chooseStartupGpuTarget(input: {
|
||||
platform: NodeJS.Platform
|
||||
headlessSmoke: boolean
|
||||
requestedMode: GpuRenderMode
|
||||
handoffTarget?: ResolvedGpuTarget
|
||||
vramSample: DiscreteVramSample | null
|
||||
hasIntegratedGpu: boolean
|
||||
}): StartupGpuDecision {
|
||||
const base = {
|
||||
requestedMode: input.requestedMode,
|
||||
vramSample: input.vramSample,
|
||||
hasIntegratedGpu: input.hasIntegratedGpu,
|
||||
}
|
||||
|
||||
if (input.headlessSmoke) {
|
||||
return { ...base, target: 'software', reason: 'headless-smoke' }
|
||||
}
|
||||
if (input.requestedMode === 'software') {
|
||||
return { ...base, target: 'software', reason: 'user-software' }
|
||||
}
|
||||
if (input.requestedMode === 'low-power') {
|
||||
return { ...base, target: 'low-power', reason: 'user-low-power' }
|
||||
}
|
||||
if (input.requestedMode === 'high-performance') {
|
||||
return { ...base, target: 'high-performance', reason: 'user-high-performance' }
|
||||
}
|
||||
if (input.handoffTarget) {
|
||||
return { ...base, target: input.handoffTarget, reason: 'gpu-handoff' }
|
||||
}
|
||||
|
||||
if (
|
||||
input.platform === 'win32' &&
|
||||
input.vramSample &&
|
||||
input.vramSample.freeMiB < VRAM_LOW_THRESHOLD_MIB
|
||||
) {
|
||||
return input.hasIntegratedGpu
|
||||
? { ...base, target: 'low-power', reason: 'low-vram-igpu' }
|
||||
: { ...base, target: 'software', reason: 'low-vram-software' }
|
||||
}
|
||||
|
||||
return { ...base, target: 'default', reason: 'normal-gpu' }
|
||||
}
|
||||
|
||||
export function resolveChromiumGpuSwitches(input: GpuPolicyInput): ChromiumSwitch[] {
|
||||
if (input.headlessSmoke || input.softwareGl) {
|
||||
const effectiveTarget: ResolvedGpuTarget =
|
||||
input.headlessSmoke || input.softwareGl || input.target === 'software'
|
||||
? 'software'
|
||||
: (input.target ?? 'default')
|
||||
|
||||
if (effectiveTarget === 'software') {
|
||||
return [
|
||||
{ name: 'disable-gpu' },
|
||||
{ name: 'use-gl', value: 'angle' },
|
||||
@@ -19,15 +171,175 @@ export function resolveChromiumGpuSwitches(input: GpuPolicyInput): ChromiumSwitc
|
||||
]
|
||||
}
|
||||
|
||||
// Avoid forcing enable-zero-copy / enable-gpu-rasterization / force_high_performance_gpu:
|
||||
// Avoid forcing enable-zero-copy / enable-gpu-rasterization:
|
||||
// on Windows dual-GPU setups with high baseline VRAM usage they can provoke driver TDRs.
|
||||
const switches: ChromiumSwitch[] = [{ name: 'disable-renderer-backgrounding' }]
|
||||
const switches: ChromiumSwitch[] = []
|
||||
if (effectiveTarget === 'low-power') {
|
||||
switches.push({ name: 'force_low_power_gpu' })
|
||||
} else if (effectiveTarget === 'high-performance') {
|
||||
switches.push({ name: 'force_high_performance_gpu' })
|
||||
}
|
||||
switches.push({ name: 'disable-renderer-backgrounding' })
|
||||
if (input.platform === 'linux') {
|
||||
switches.push({ name: 'ozone-platform-hint', value: 'auto' })
|
||||
}
|
||||
return switches
|
||||
}
|
||||
|
||||
export function createVramHysteresisTracker(options: {
|
||||
activeTarget: ResolvedGpuTarget
|
||||
hasIntegratedGpu: boolean
|
||||
lowThresholdMiB?: number
|
||||
recoverThresholdMiB?: number
|
||||
requiredConsecutive?: number
|
||||
}) {
|
||||
const lowThresholdMiB = options.lowThresholdMiB ?? VRAM_LOW_THRESHOLD_MIB
|
||||
const recoverThresholdMiB = options.recoverThresholdMiB ?? VRAM_RECOVER_THRESHOLD_MIB
|
||||
const requiredConsecutive = Math.max(1, options.requiredConsecutive ?? VRAM_SWITCH_CONSECUTIVE_REQUIRED)
|
||||
let streak = 0
|
||||
|
||||
return {
|
||||
observe(sample: DiscreteVramSample | null): VramMonitorAction | null {
|
||||
if (!sample) {
|
||||
streak = 0
|
||||
return null
|
||||
}
|
||||
|
||||
if (options.activeTarget === 'low-power' || options.activeTarget === 'software') {
|
||||
if (sample.freeMiB >= recoverThresholdMiB) {
|
||||
streak += 1
|
||||
if (streak >= requiredConsecutive) {
|
||||
return { kind: 'switch-to-discrete', sample }
|
||||
}
|
||||
} else {
|
||||
streak = 0
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
if (sample.freeMiB < lowThresholdMiB) {
|
||||
streak += 1
|
||||
if (streak >= requiredConsecutive) {
|
||||
return {
|
||||
kind: options.hasIntegratedGpu ? 'switch-to-low-power' : 'switch-to-software',
|
||||
sample,
|
||||
}
|
||||
}
|
||||
} else {
|
||||
streak = 0
|
||||
}
|
||||
return null
|
||||
},
|
||||
reset(): void {
|
||||
streak = 0
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export function createSustainedLowFpsTracker(
|
||||
options: {
|
||||
thresholdFps?: number
|
||||
sustainedMs?: number
|
||||
sampleWindowMs?: number
|
||||
reportCooldownMs?: number
|
||||
} = {},
|
||||
) {
|
||||
const thresholdFps = options.thresholdFps ?? LOW_FPS_THRESHOLD
|
||||
const sustainedMs = options.sustainedMs ?? LOW_FPS_SUSTAINED_MS
|
||||
const sampleWindowMs = options.sampleWindowMs ?? 1000
|
||||
const reportCooldownMs = options.reportCooldownMs ?? FPS_REPORT_COOLDOWN_MS
|
||||
|
||||
let bucketStartMs: number | null = null
|
||||
let bucketFrames = 0
|
||||
let lowDurationMs = 0
|
||||
let lowFrames = 0
|
||||
let lastReportedAt = -Infinity
|
||||
|
||||
return {
|
||||
onFrame(nowMs: number): { avgFps: number; sustainedMs: number } | null {
|
||||
if (!Number.isFinite(nowMs)) return null
|
||||
if (bucketStartMs === null) {
|
||||
bucketStartMs = nowMs
|
||||
bucketFrames = 0
|
||||
return null
|
||||
}
|
||||
bucketFrames += 1
|
||||
const elapsedMs = nowMs - bucketStartMs
|
||||
if (elapsedMs < sampleWindowMs) {
|
||||
return null
|
||||
}
|
||||
|
||||
const fps = (bucketFrames * 1000) / elapsedMs
|
||||
bucketStartMs = nowMs
|
||||
|
||||
if (fps < thresholdFps) {
|
||||
lowDurationMs += elapsedMs
|
||||
lowFrames += bucketFrames
|
||||
bucketFrames = 0
|
||||
if (lowDurationMs >= sustainedMs && nowMs - lastReportedAt >= reportCooldownMs) {
|
||||
const avgFps = Math.round(((lowFrames * 1000) / lowDurationMs) * 10) / 10
|
||||
const reportedDuration = Math.round(lowDurationMs)
|
||||
lastReportedAt = nowMs
|
||||
lowDurationMs = 0
|
||||
lowFrames = 0
|
||||
return { avgFps, sustainedMs: reportedDuration }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
bucketFrames = 0
|
||||
lowDurationMs = 0
|
||||
lowFrames = 0
|
||||
return null
|
||||
},
|
||||
reset(): void {
|
||||
bucketStartMs = null
|
||||
bucketFrames = 0
|
||||
lowDurationMs = 0
|
||||
lowFrames = 0
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export function canAutoSwitchGpu(
|
||||
lastSwitchAt: number | null | undefined,
|
||||
nowMs: number,
|
||||
cooldownMs = AUTO_SWITCH_COOLDOWN_MS,
|
||||
): boolean {
|
||||
return !lastSwitchAt || !Number.isFinite(lastSwitchAt) || nowMs - lastSwitchAt >= cooldownMs
|
||||
}
|
||||
|
||||
export function stripGpuOverrideArgs(argv: string[]): string[] {
|
||||
const stripped: string[] = []
|
||||
for (let i = 0; i < argv.length; i += 1) {
|
||||
const arg = argv[i]
|
||||
if (
|
||||
arg === '--software-gl' ||
|
||||
arg === '--low-power-gpu' ||
|
||||
arg === '--high-performance-gpu' ||
|
||||
arg === '--gpu-handoff' ||
|
||||
arg.startsWith('--gpu-mode=') ||
|
||||
arg.startsWith('--gpu-handoff-target=')
|
||||
) {
|
||||
continue
|
||||
}
|
||||
if (arg === '--gpu-mode' || arg === '--gpu-handoff-target') {
|
||||
i += 1
|
||||
continue
|
||||
}
|
||||
stripped.push(arg)
|
||||
}
|
||||
return stripped
|
||||
}
|
||||
|
||||
export function buildGpuHandoffArgs(argv: string[], target?: ResolvedGpuTarget): string[] {
|
||||
return [
|
||||
...stripGpuOverrideArgs(argv),
|
||||
'--gpu-handoff',
|
||||
...(target ? [`--gpu-handoff-target=${target}`] : []),
|
||||
]
|
||||
}
|
||||
|
||||
export function isGpuProcessCrash(
|
||||
details: { type?: string; reason?: string } | null | undefined,
|
||||
): boolean {
|
||||
|
||||
+127
-7
@@ -1,25 +1,68 @@
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
|
||||
import { app, BrowserWindow, ipcMain, Menu, session, shell } from 'electron'
|
||||
import { app, BrowserWindow, dialog, ipcMain, Menu, session, shell } from 'electron'
|
||||
|
||||
import { DesktopConfigStore, normalizeSplashTheme, type ServerEndpoints } from './config'
|
||||
import { DesktopConfigStore, normalizeSplashTheme, readPreReadyGpuHandoff, readPreReadyGpuMode, type GpuRenderMode, type ServerEndpoints } from './config'
|
||||
import { DESKTOP_SCHEME, registerDesktopLink } from './desktop-link'
|
||||
import { isGpuProcessCrash, resolveChromiumGpuSwitches } from './gpu-policy'
|
||||
import { createAdaptiveGpuMonitor, probeWindowsGpuEnvironmentSync } from './gpu-monitor'
|
||||
import { buildGpuHandoffArgs, chooseStartupGpuTarget, isGpuProcessCrash, resolveChromiumGpuSwitches, stripGpuOverrideArgs, type ResolvedGpuTarget } from './gpu-policy'
|
||||
import { PERIODIC_UPDATE_CHECK_INTERVAL_MS } from './hot-update-core'
|
||||
import { createHotUpdateController } from './hot-updater'
|
||||
import { buildApplicationMenu } from './menu'
|
||||
import { EARTH_ORIGIN, installEarthSessionHandlers, registerEarthScheme } from './protocol'
|
||||
import { createMainWindow, dismissMenuBarOnPointerDown, toggleWindowOrientation } from './window'
|
||||
import { createMainWindow, dismissMenuBarOnPointerDown, flushWindowState, toggleWindowOrientation } from './window'
|
||||
|
||||
registerEarthScheme()
|
||||
|
||||
const isHeadlessSmoke = process.argv.includes('--headless-smoke')
|
||||
const isSoftwareGl = process.argv.includes('--software-gl')
|
||||
let preReadyUserDataDir = ''
|
||||
let preReadyExeDir = process.cwd()
|
||||
try {
|
||||
preReadyUserDataDir = app.getPath('userData')
|
||||
} catch {
|
||||
preReadyUserDataDir = ''
|
||||
}
|
||||
try {
|
||||
preReadyExeDir = path.dirname(app.getPath('exe'))
|
||||
} catch {
|
||||
preReadyExeDir = process.cwd()
|
||||
}
|
||||
|
||||
const requestedGpuMode = readPreReadyGpuMode({
|
||||
userDataDir: preReadyUserDataDir,
|
||||
exeDir: preReadyExeDir,
|
||||
resourcesDir: process.resourcesPath,
|
||||
argv: process.argv,
|
||||
})
|
||||
const preReadyHandoff = readPreReadyGpuHandoff(process.argv)
|
||||
const preReadyGpuEnv =
|
||||
!isHeadlessSmoke &&
|
||||
!preReadyHandoff.gpuHandoffTarget &&
|
||||
requestedGpuMode === 'auto' &&
|
||||
process.platform === 'win32'
|
||||
? probeWindowsGpuEnvironmentSync()
|
||||
: { vramSample: null, hasIntegratedGpu: false }
|
||||
|
||||
const startupGpuDecision = chooseStartupGpuTarget({
|
||||
platform: process.platform,
|
||||
headlessSmoke: isHeadlessSmoke,
|
||||
requestedMode: requestedGpuMode,
|
||||
handoffTarget: preReadyHandoff.gpuHandoffTarget,
|
||||
vramSample: preReadyGpuEnv.vramSample,
|
||||
hasIntegratedGpu: preReadyGpuEnv.hasIntegratedGpu,
|
||||
})
|
||||
|
||||
if (startupGpuDecision.reason === 'low-vram-igpu' || startupGpuDecision.reason === 'low-vram-software') {
|
||||
console.info(
|
||||
`[planet-client] Adaptive GPU selected ${startupGpuDecision.target} (reason=${startupGpuDecision.reason}, freeMiB=${startupGpuDecision.vramSample?.freeMiB ?? 'unknown'})`,
|
||||
)
|
||||
}
|
||||
|
||||
for (const sw of resolveChromiumGpuSwitches({
|
||||
platform: process.platform,
|
||||
headlessSmoke: isHeadlessSmoke,
|
||||
softwareGl: isSoftwareGl,
|
||||
target: startupGpuDecision.target,
|
||||
})) {
|
||||
if (sw.value !== undefined) {
|
||||
app.commandLine.appendSwitch(sw.name, sw.value)
|
||||
@@ -119,6 +162,22 @@ if (!singleInstanceLock) {
|
||||
})
|
||||
|
||||
const earthBundleRoot = resolveEarthBundleRoot()
|
||||
const relaunchDesktopApp = (relaunchOptions?: {
|
||||
gpuHandoff?: boolean
|
||||
gpuHandoffTarget?: ResolvedGpuTarget
|
||||
}) => {
|
||||
flushWindowState(mainWindow)
|
||||
if (singleInstanceLock) {
|
||||
app.releaseSingleInstanceLock()
|
||||
}
|
||||
const rawArgs = process.argv.slice(1)
|
||||
const args = relaunchOptions?.gpuHandoff
|
||||
? buildGpuHandoffArgs(rawArgs, relaunchOptions.gpuHandoffTarget)
|
||||
: stripGpuOverrideArgs(rawArgs)
|
||||
app.relaunch({ args })
|
||||
app.exit(0)
|
||||
}
|
||||
|
||||
const hotUpdater = createHotUpdateController({
|
||||
userDataDir: app.getPath('userData'),
|
||||
shellVersion: app.getVersion(),
|
||||
@@ -129,6 +188,29 @@ if (!singleInstanceLock) {
|
||||
},
|
||||
})
|
||||
|
||||
const gpuMonitor = createAdaptiveGpuMonitor({
|
||||
userDataDir: app.getPath('userData'),
|
||||
startupDecision: startupGpuDecision,
|
||||
getConfiguredMode: () => configStore.get().gpuMode,
|
||||
getMainWindow: () => mainWindow,
|
||||
onAutoSwitch: (nextTarget) => {
|
||||
relaunchDesktopApp({ gpuHandoff: true, gpuHandoffTarget: nextTarget })
|
||||
},
|
||||
onStatusUpdated: () => {
|
||||
refreshApplicationMenu()
|
||||
},
|
||||
})
|
||||
|
||||
const sendPendingHandoffToast = () => {
|
||||
if (isHeadlessSmoke || !mainWindow || mainWindow.isDestroyed() || mainWindow.webContents.isDestroyed()) {
|
||||
return
|
||||
}
|
||||
const toast = gpuMonitor.consumePendingHandoffToast()
|
||||
if (toast) {
|
||||
mainWindow.webContents.send('planet:update-status', toast)
|
||||
}
|
||||
}
|
||||
|
||||
const refreshApplicationMenu = () => {
|
||||
if (!mainWindow || mainWindow.isDestroyed()) return
|
||||
Menu.setApplicationMenu(
|
||||
@@ -139,6 +221,27 @@ if (!singleInstanceLock) {
|
||||
onCheckForUpdates: () => {
|
||||
void hotUpdater.checkForUpdates({ manual: true })
|
||||
},
|
||||
getGpuStatus: () => gpuMonitor.getRuntimeSummary(),
|
||||
onSelectGpuMode: async (nextMode: GpuRenderMode) => {
|
||||
configStore.updateGpuMode(nextMode)
|
||||
refreshApplicationMenu()
|
||||
const targetWin = mainWindow && !mainWindow.isDestroyed() ? mainWindow : undefined
|
||||
const boxOptions = {
|
||||
type: 'info' as const,
|
||||
title: '渲染设备设置 / GPU Mode',
|
||||
message: '渲染设备模式已更新,需重启客户端生效',
|
||||
detail: '是否立即重启 Planet Earth?(重启约需 1-2 秒,将保留全部视觉特效)',
|
||||
buttons: ['立即重启 / Restart Now', '稍后手动重启 / Later'],
|
||||
defaultId: 0,
|
||||
cancelId: 1,
|
||||
}
|
||||
const { response } = targetWin
|
||||
? await dialog.showMessageBox(targetWin, boxOptions)
|
||||
: await dialog.showMessageBox(boxOptions)
|
||||
if (response === 0) {
|
||||
relaunchDesktopApp({ gpuHandoff: true })
|
||||
}
|
||||
},
|
||||
}),
|
||||
)
|
||||
}
|
||||
@@ -152,9 +255,21 @@ if (!singleInstanceLock) {
|
||||
ipcMain.on('planet:earth-startup-ready', () => {
|
||||
if (!isHeadlessSmoke) {
|
||||
hotUpdater.markStartupReady()
|
||||
sendPendingHandoffToast()
|
||||
}
|
||||
})
|
||||
|
||||
ipcMain.on('planet:low-fps-report', (_event, payload: unknown) => {
|
||||
if (isHeadlessSmoke || !payload || typeof payload !== 'object') return
|
||||
const candidate = payload as { avgFps?: unknown; sustainedMs?: unknown }
|
||||
const avgFps = Number(candidate.avgFps)
|
||||
const sustainedMs = Number(candidate.sustainedMs)
|
||||
if (!Number.isFinite(avgFps) || avgFps <= 0 || !Number.isFinite(sustainedMs) || sustainedMs <= 0) {
|
||||
return
|
||||
}
|
||||
void gpuMonitor.handleLowFpsReport({ avgFps, sustainedMs })
|
||||
})
|
||||
|
||||
ipcMain.handle('planet:check-for-updates', async () => {
|
||||
await hotUpdater.checkForUpdates({ manual: true })
|
||||
})
|
||||
@@ -170,6 +285,9 @@ if (!singleInstanceLock) {
|
||||
wsUrl: cfg.wsUrl,
|
||||
forceShowFps: cfg.forceShowFps,
|
||||
splashTheme: cfg.splashTheme,
|
||||
gpuMode: cfg.gpuMode,
|
||||
gpuTarget: startupGpuDecision.target,
|
||||
gpuHandoff: cfg.gpuHandoff,
|
||||
headlessSmoke: cfg.headlessSmoke,
|
||||
isElectron: true,
|
||||
platform: process.platform,
|
||||
@@ -259,6 +377,7 @@ if (!singleInstanceLock) {
|
||||
})
|
||||
hotUpdater.startStartupWatchdog()
|
||||
mainWindow.webContents.once('did-finish-load', () => {
|
||||
gpuMonitor.start()
|
||||
autoUpdateTimer = setTimeout(() => {
|
||||
autoUpdateTimer = null
|
||||
if (mainWindow && !mainWindow.isDestroyed()) {
|
||||
@@ -274,6 +393,7 @@ if (!singleInstanceLock) {
|
||||
}
|
||||
})
|
||||
mainWindow.once('closed', () => {
|
||||
gpuMonitor.stop()
|
||||
if (autoUpdateTimer) {
|
||||
clearTimeout(autoUpdateTimer)
|
||||
autoUpdateTimer = null
|
||||
@@ -358,7 +478,7 @@ if (!singleInstanceLock) {
|
||||
mounted: Boolean(host && sr),
|
||||
hasPresentedBy: copy.includes('PRESENTED BY'),
|
||||
hasPresenterZh: copy.includes('临空智能媒体研究院'),
|
||||
hasPresenterEn: copy.includes('Institute of Intelligent Media'),
|
||||
hasPresenterEn: copy.includes('Intelligent Media Institute'),
|
||||
emblemLoaded: Boolean(img && img.complete && img.naturalWidth > 0),
|
||||
emblemWidth: img ? img.naturalWidth : 0,
|
||||
activeTheme,
|
||||
|
||||
+68
-2
@@ -1,15 +1,33 @@
|
||||
import { app, Menu, shell, type BrowserWindow, type MenuItemConstructorOptions } from 'electron'
|
||||
|
||||
import type { DesktopConfigStore, SplashTheme } from './config'
|
||||
import type { DesktopConfigStore, GpuRenderMode, SplashTheme } from './config'
|
||||
import type { GpuRuntimeSummary } from './gpu-monitor'
|
||||
import type { HotUpdateVersionInfo } from './hot-updater'
|
||||
import { openServerSettingsDialog, toggleWindowOrientation } from './window'
|
||||
|
||||
import type { HotUpdateVersionInfo } from './hot-updater'
|
||||
function formatGpuSummaryLabel(summary: GpuRuntimeSummary): string {
|
||||
const targetLabel =
|
||||
summary.activeTarget === 'low-power'
|
||||
? '集成核显'
|
||||
: summary.activeTarget === 'software'
|
||||
? 'CPU 软渲染'
|
||||
: summary.activeTarget === 'high-performance' || summary.latestVramSample
|
||||
? '独立显卡'
|
||||
: '硬件 GPU'
|
||||
const modeTag = summary.requestedMode === 'auto' ? '自动' : '手动'
|
||||
const vramTag = summary.latestVramSample
|
||||
? ` · 独显空闲 ${(summary.latestVramSample.freeMiB / 1024).toFixed(1)} GB`
|
||||
: ''
|
||||
return `当前生效: ${targetLabel} (${modeTag}${vramTag})`
|
||||
}
|
||||
|
||||
export function buildApplicationMenu(options: {
|
||||
mainWindow: BrowserWindow
|
||||
configStore: DesktopConfigStore
|
||||
getVersionInfo?: () => HotUpdateVersionInfo
|
||||
onCheckForUpdates?: () => void
|
||||
getGpuStatus?: () => GpuRuntimeSummary
|
||||
onSelectGpuMode?: (mode: GpuRenderMode) => void | Promise<void>
|
||||
}): Menu {
|
||||
const sendAction = (action: string) => {
|
||||
if (!options.mainWindow.isDestroyed()) {
|
||||
@@ -23,6 +41,8 @@ export function buildApplicationMenu(options: {
|
||||
}
|
||||
|
||||
const currentSplashTheme = options.configStore.get().splashTheme
|
||||
const currentGpuMode = options.configStore.get().gpuMode
|
||||
const gpuSummary = options.getGpuStatus?.()
|
||||
|
||||
const selectSplashTheme = (theme: SplashTheme) => {
|
||||
options.configStore.updateSplashTheme(theme)
|
||||
@@ -92,6 +112,52 @@ export function buildApplicationMenu(options: {
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
label: '渲染设备 / GPU Mode',
|
||||
submenu: [
|
||||
...(gpuSummary
|
||||
? [
|
||||
{
|
||||
label: formatGpuSummaryLabel(gpuSummary),
|
||||
enabled: false,
|
||||
},
|
||||
{ type: 'separator' as const },
|
||||
]
|
||||
: []),
|
||||
{
|
||||
label: '自动(卡顿缺显存切核显,显存空出自动回独显) / Auto',
|
||||
type: 'radio',
|
||||
checked: currentGpuMode === 'auto',
|
||||
click: () => {
|
||||
void options.onSelectGpuMode?.('auto')
|
||||
},
|
||||
},
|
||||
{
|
||||
label: '独立显卡(高性能) / Discrete GPU',
|
||||
type: 'radio',
|
||||
checked: currentGpuMode === 'high-performance',
|
||||
click: () => {
|
||||
void options.onSelectGpuMode?.('high-performance')
|
||||
},
|
||||
},
|
||||
{
|
||||
label: '集成核显(不占独显显存) / Integrated GPU',
|
||||
type: 'radio',
|
||||
checked: currentGpuMode === 'low-power',
|
||||
click: () => {
|
||||
void options.onSelectGpuMode?.('low-power')
|
||||
},
|
||||
},
|
||||
{
|
||||
label: '纯 CPU 软渲染 / Software GL',
|
||||
type: 'radio',
|
||||
checked: currentGpuMode === 'software',
|
||||
click: () => {
|
||||
void options.onSelectGpuMode?.('software')
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{ type: 'separator' },
|
||||
{
|
||||
label: '打开运维控制台 / Open Admin Console',
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
@@ -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',
|
||||
|
||||
+74
-19
@@ -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,12 +16,20 @@ import {
|
||||
detectWindowOrientation,
|
||||
MIN_WINDOW_HEIGHT,
|
||||
MIN_WINDOW_WIDTH,
|
||||
resolveInitialWindowBounds,
|
||||
type Rect,
|
||||
type WindowOrientation,
|
||||
} from './orientation'
|
||||
import { EARTH_ENTRY_URL, EARTH_ORIGIN } from './protocol'
|
||||
|
||||
const resetAltMenuTrackers = new WeakMap<BrowserWindow, () => void>()
|
||||
const windowStateFlushers = new WeakMap<BrowserWindow, () => void>()
|
||||
const cancelInitialUnmaximizeRestore = new WeakMap<BrowserWindow, () => void>()
|
||||
|
||||
export function flushWindowState(win: BrowserWindow | null): void {
|
||||
if (!win || win.isDestroyed()) return
|
||||
windowStateFlushers.get(win)?.()
|
||||
}
|
||||
|
||||
interface OrientationWindowState {
|
||||
lastLandscapeBounds: Rect | null
|
||||
@@ -68,6 +77,7 @@ export function toggleWindowOrientation(win: BrowserWindow): WindowOrientation {
|
||||
win.setFullScreen(false)
|
||||
}
|
||||
if (wasMaximized) {
|
||||
cancelInitialUnmaximizeRestore.get(win)?.()
|
||||
win.unmaximize()
|
||||
}
|
||||
const portraitBounds = computePortraitBounds({
|
||||
@@ -176,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,
|
||||
@@ -282,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)
|
||||
@@ -296,13 +327,28 @@ export function createMainWindow(options: {
|
||||
}
|
||||
}
|
||||
|
||||
win.on('resize', captureNormalBounds)
|
||||
win.on('move', captureNormalBounds)
|
||||
win.on('close', () => {
|
||||
const flushCurrentWindowState = () => {
|
||||
captureNormalBounds()
|
||||
if (!runtimeConfig.headlessSmoke) {
|
||||
saveWindowState(statePath, win, lastNormalBounds)
|
||||
}
|
||||
}
|
||||
windowStateFlushers.set(win, flushCurrentWindowState)
|
||||
|
||||
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', () => {
|
||||
@@ -331,22 +377,29 @@ 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
|
||||
}
|
||||
}
|
||||
|
||||
const showGate = createWindowShowGate({
|
||||
requireSplashFirstPaint: !runtimeConfig.headlessSmoke && runtimeConfig.splashTheme !== 'off',
|
||||
requireSplashFirstPaint:
|
||||
!runtimeConfig.headlessSmoke &&
|
||||
!runtimeConfig.gpuHandoff &&
|
||||
runtimeConfig.splashTheme !== 'off',
|
||||
fallbackDelayMs: 1500,
|
||||
onReveal: revealMainWindow,
|
||||
})
|
||||
@@ -359,6 +412,8 @@ export function createMainWindow(options: {
|
||||
ipcMain.on('planet:splash-first-paint', onSplashFirstPaint)
|
||||
|
||||
win.once('closed', () => {
|
||||
windowStateFlushers.delete(win)
|
||||
cancelInitialUnmaximizeRestore.delete(win)
|
||||
showGate.dispose()
|
||||
ipcMain.removeListener('planet:splash-first-paint', onSplashFirstPaint)
|
||||
})
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import {
|
||||
createSustainedLowFpsTracker,
|
||||
FPS_STARTUP_WARMUP_MS,
|
||||
} from '../main/gpu-policy'
|
||||
|
||||
export function startDesktopLowFpsWatcher(options: {
|
||||
onLowFps: (report: { avgFps: number; sustainedMs: number }) => void
|
||||
}): () => void {
|
||||
const tracker = createSustainedLowFpsTracker()
|
||||
let disposed = false
|
||||
let rafId = 0
|
||||
let warmupTimer: ReturnType<typeof setTimeout> | null = null
|
||||
let startupReady = document.documentElement?.dataset?.earthStartupReady === '1'
|
||||
let warmupDone = false
|
||||
let desktopMinimized = false
|
||||
|
||||
const isActive = () =>
|
||||
!disposed && startupReady && warmupDone && !desktopMinimized && !document.hidden
|
||||
|
||||
const stopLoop = () => {
|
||||
if (rafId) {
|
||||
cancelAnimationFrame(rafId)
|
||||
rafId = 0
|
||||
}
|
||||
tracker.reset()
|
||||
}
|
||||
|
||||
const tick = (now: number) => {
|
||||
if (!isActive()) {
|
||||
rafId = 0
|
||||
tracker.reset()
|
||||
return
|
||||
}
|
||||
const report = tracker.onFrame(now)
|
||||
if (report) {
|
||||
options.onLowFps(report)
|
||||
}
|
||||
rafId = requestAnimationFrame(tick)
|
||||
}
|
||||
|
||||
const syncLoop = () => {
|
||||
if (!isActive()) {
|
||||
stopLoop()
|
||||
return
|
||||
}
|
||||
if (!rafId) {
|
||||
rafId = requestAnimationFrame(tick)
|
||||
}
|
||||
}
|
||||
|
||||
const beginWarmup = () => {
|
||||
if (disposed || warmupDone || warmupTimer) return
|
||||
warmupTimer = setTimeout(() => {
|
||||
warmupTimer = null
|
||||
warmupDone = true
|
||||
syncLoop()
|
||||
}, FPS_STARTUP_WARMUP_MS)
|
||||
}
|
||||
|
||||
const onStartupReady = () => {
|
||||
startupReady = true
|
||||
beginWarmup()
|
||||
}
|
||||
|
||||
const onVisibilityChange = () => {
|
||||
syncLoop()
|
||||
}
|
||||
|
||||
const onDesktopVisibility = (event: Event) => {
|
||||
const detail = (event as CustomEvent<{ minimized?: boolean }>).detail
|
||||
desktopMinimized = Boolean(detail?.minimized)
|
||||
syncLoop()
|
||||
}
|
||||
|
||||
if (startupReady) {
|
||||
beginWarmup()
|
||||
} else {
|
||||
window.addEventListener('earth:startup-ready', onStartupReady, { once: true })
|
||||
}
|
||||
document.addEventListener('visibilitychange', onVisibilityChange)
|
||||
window.addEventListener('planet-desktop:visibility', onDesktopVisibility)
|
||||
|
||||
return () => {
|
||||
disposed = true
|
||||
stopLoop()
|
||||
if (warmupTimer) {
|
||||
clearTimeout(warmupTimer)
|
||||
warmupTimer = null
|
||||
}
|
||||
window.removeEventListener('earth:startup-ready', onStartupReady)
|
||||
document.removeEventListener('visibilitychange', onVisibilityChange)
|
||||
window.removeEventListener('planet-desktop:visibility', onDesktopVisibility)
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { contextBridge, ipcRenderer } from 'electron'
|
||||
|
||||
import { startDesktopLowFpsWatcher } from './fps-watcher'
|
||||
import { createDesktopSplashController, type SplashTheme } from './splash'
|
||||
|
||||
interface PreloadRuntimeConfig {
|
||||
@@ -9,6 +10,9 @@ interface PreloadRuntimeConfig {
|
||||
wsUrl: string
|
||||
forceShowFps: boolean
|
||||
splashTheme: SplashTheme
|
||||
gpuMode?: string
|
||||
gpuTarget?: string
|
||||
gpuHandoff?: boolean
|
||||
headlessSmoke: boolean
|
||||
isElectron: true
|
||||
platform: string
|
||||
@@ -27,7 +31,7 @@ const splashController = createDesktopSplashController({
|
||||
},
|
||||
})
|
||||
|
||||
if (!runtimeConfig.headlessSmoke && runtimeConfig.splashTheme !== 'off') {
|
||||
if (!runtimeConfig.headlessSmoke && !runtimeConfig.gpuHandoff && runtimeConfig.splashTheme !== 'off') {
|
||||
let bootStarted = false
|
||||
const tryStartBoot = () => {
|
||||
if (bootStarted || !document.documentElement) return false
|
||||
@@ -54,6 +58,19 @@ if (!runtimeConfig.headlessSmoke && runtimeConfig.splashTheme !== 'off') {
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
!runtimeConfig.headlessSmoke &&
|
||||
runtimeConfig.platform === 'win32' &&
|
||||
runtimeConfig.gpuMode === 'auto' &&
|
||||
(runtimeConfig.gpuTarget === 'default' || runtimeConfig.gpuTarget === 'high-performance')
|
||||
) {
|
||||
startDesktopLowFpsWatcher({
|
||||
onLowFps: (report) => {
|
||||
ipcRenderer.send('planet:low-fps-report', report)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
contextBridge.exposeInMainWorld('__PLANET_RUNTIME_CONFIG__', runtimeConfig)
|
||||
|
||||
contextBridge.exposeInMainWorld('planetDesktop', {
|
||||
|
||||
@@ -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' })
|
||||
|
||||
@@ -779,7 +786,7 @@ export function createDesktopSplashController(options: {
|
||||
<div class="splash-presenter-copy">
|
||||
<span class="splash-presenter-kicker">PRESENTED BY</span>
|
||||
<span class="splash-presenter-zh">临空智能媒体研究院</span>
|
||||
<span class="splash-presenter-en">Institute of Intelligent Media</span>
|
||||
<span class="splash-presenter-en">Intelligent Media Institute</span>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,46 @@
|
||||
import { describe, expect, test } from 'bun:test'
|
||||
import { mkdtempSync, rmSync } from 'node:fs'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
|
||||
import { isGpuProcessCrash, resolveChromiumGpuSwitches } from '../src/main/gpu-policy'
|
||||
import { afterAll, beforeAll, describe, expect, test } from 'bun:test'
|
||||
|
||||
import {
|
||||
DesktopConfigStore,
|
||||
normalizeGpuMode,
|
||||
parseLaunchArgs,
|
||||
readPreReadyGpuHandoff,
|
||||
readPreReadyGpuMode,
|
||||
} from '../src/main/config'
|
||||
import {
|
||||
buildGpuHandoffArgs,
|
||||
canAutoSwitchGpu,
|
||||
chooseStartupGpuTarget,
|
||||
createSustainedLowFpsTracker,
|
||||
createVramHysteresisTracker,
|
||||
detectIntegratedGpuFromRegistryOutput,
|
||||
isGpuProcessCrash,
|
||||
parseNvidiaSmiCsv,
|
||||
resolveChromiumGpuSwitches,
|
||||
stripGpuOverrideArgs,
|
||||
VRAM_LOW_THRESHOLD_MIB,
|
||||
VRAM_RECOVER_THRESHOLD_MIB,
|
||||
} from '../src/main/gpu-policy'
|
||||
import { computeSplashCanvasSize } from '../src/preload/splash'
|
||||
|
||||
let tempRoot = ''
|
||||
|
||||
beforeAll(() => {
|
||||
tempRoot = mkdtempSync(path.join(os.tmpdir(), 'planet-gpu-policy-test-'))
|
||||
})
|
||||
|
||||
afterAll(() => {
|
||||
if (tempRoot) {
|
||||
rmSync(tempRoot, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
describe('chromium GPU switch policy and splash pixel budget', () => {
|
||||
test('win32 hardware mode avoids risky zero-copy and forced GPU switches', () => {
|
||||
test('win32 hardware mode avoids risky zero-copy and forced GPU switches by default', () => {
|
||||
const switches = resolveChromiumGpuSwitches({
|
||||
platform: 'win32',
|
||||
headlessSmoke: false,
|
||||
@@ -14,10 +50,33 @@ describe('chromium GPU switch policy and splash pixel budget', () => {
|
||||
expect(names).not.toContain('enable-zero-copy')
|
||||
expect(names).not.toContain('enable-gpu-rasterization')
|
||||
expect(names).not.toContain('force_high_performance_gpu')
|
||||
expect(names).not.toContain('force_low_power_gpu')
|
||||
expect(names).toContain('disable-renderer-backgrounding')
|
||||
expect(names).not.toContain('ozone-platform-hint')
|
||||
})
|
||||
|
||||
test('low-power and high-performance targets emit matching Chromium GPU preference switches without enable-zero-copy', () => {
|
||||
const igpuSwitches = resolveChromiumGpuSwitches({
|
||||
platform: 'win32',
|
||||
headlessSmoke: false,
|
||||
target: 'low-power',
|
||||
})
|
||||
expect(igpuSwitches).toEqual([
|
||||
{ name: 'force_low_power_gpu' },
|
||||
{ name: 'disable-renderer-backgrounding' },
|
||||
])
|
||||
|
||||
const dgpuSwitches = resolveChromiumGpuSwitches({
|
||||
platform: 'win32',
|
||||
headlessSmoke: false,
|
||||
target: 'high-performance',
|
||||
})
|
||||
expect(dgpuSwitches).toEqual([
|
||||
{ name: 'force_high_performance_gpu' },
|
||||
{ name: 'disable-renderer-backgrounding' },
|
||||
])
|
||||
})
|
||||
|
||||
test('linux hardware mode adds ozone auto hint without enable-zero-copy', () => {
|
||||
const switches = resolveChromiumGpuSwitches({
|
||||
platform: 'linux',
|
||||
@@ -30,10 +89,11 @@ describe('chromium GPU switch policy and splash pixel budget', () => {
|
||||
])
|
||||
})
|
||||
|
||||
test('headless smoke and explicit software-gl select SwiftShader safely', () => {
|
||||
test('headless smoke, explicit software-gl, and target=software select SwiftShader safely', () => {
|
||||
for (const flags of [
|
||||
{ headlessSmoke: true, softwareGl: false },
|
||||
{ headlessSmoke: false, softwareGl: true },
|
||||
{ headlessSmoke: false, target: 'software' as const },
|
||||
]) {
|
||||
const switches = resolveChromiumGpuSwitches({ platform: 'win32', ...flags })
|
||||
expect(switches).toEqual([
|
||||
@@ -70,3 +130,339 @@ describe('chromium GPU switch policy and splash pixel budget', () => {
|
||||
expect(native4k.height).toBe(1620)
|
||||
})
|
||||
})
|
||||
|
||||
describe('adaptive VRAM probing, GPU decision, and hysteresis', () => {
|
||||
test('parseNvidiaSmiCsv parses single and multi-line CSV while skipping invalid rows', () => {
|
||||
expect(
|
||||
parseNvidiaSmiCsv('NVIDIA GeForce RTX 5070 Ti, 14651, 1345, 16303\n'),
|
||||
).toEqual({
|
||||
gpuName: 'NVIDIA GeForce RTX 5070 Ti',
|
||||
usedMiB: 14651,
|
||||
freeMiB: 1345,
|
||||
totalMiB: 16303,
|
||||
})
|
||||
|
||||
expect(
|
||||
parseNvidiaSmiCsv(
|
||||
'\n[N/A], [N/A], [N/A], [N/A]\nNVIDIA GeForce RTX 4090, 4096 MiB, 20480 MiB, 24576 MiB\n',
|
||||
),
|
||||
).toEqual({
|
||||
gpuName: 'NVIDIA GeForce RTX 4090',
|
||||
usedMiB: 4096,
|
||||
freeMiB: 20480,
|
||||
totalMiB: 24576,
|
||||
})
|
||||
|
||||
expect(parseNvidiaSmiCsv('')).toBeNull()
|
||||
expect(parseNvidiaSmiCsv('Failed to initialize NVML')).toBeNull()
|
||||
})
|
||||
|
||||
test('detectIntegratedGpuFromRegistryOutput distinguishes iGPU from single-GPU and virtual adapters', () => {
|
||||
expect(
|
||||
detectIntegratedGpuFromRegistryOutput(`
|
||||
HKEY_LOCAL_MACHINE\\...\\0000
|
||||
DriverDesc REG_SZ Intel(R) Graphics
|
||||
|
||||
HKEY_LOCAL_MACHINE\\...\\0001
|
||||
DriverDesc REG_SZ NVIDIA GeForce RTX 5070 Ti
|
||||
`),
|
||||
).toBe(true)
|
||||
|
||||
expect(
|
||||
detectIntegratedGpuFromRegistryOutput(`
|
||||
DriverDesc REG_SZ AMD Radeon(TM) Graphics
|
||||
DriverDesc REG_SZ NVIDIA GeForce RTX 4060 Laptop GPU
|
||||
`),
|
||||
).toBe(true)
|
||||
|
||||
expect(
|
||||
detectIntegratedGpuFromRegistryOutput(`
|
||||
DriverDesc REG_SZ NVIDIA GeForce RTX 5070 Ti
|
||||
DriverDesc REG_SZ Microsoft Basic Display Adapter
|
||||
DriverDesc REG_SZ Parsec Virtual Display Adapter
|
||||
`),
|
||||
).toBe(false)
|
||||
|
||||
expect(
|
||||
detectIntegratedGpuFromRegistryOutput(`
|
||||
DriverDesc REG_SZ Intel(R) Arc(TM) A770 Graphics
|
||||
DriverDesc REG_SZ NVIDIA GeForce RTX 5070 Ti
|
||||
`),
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
test('chooseStartupGpuTarget handles low VRAM auto offload, recovery, explicit modes, and smoke', () => {
|
||||
const lowVramSample = {
|
||||
gpuName: 'NVIDIA GeForce RTX 5070 Ti',
|
||||
usedMiB: 14651,
|
||||
freeMiB: 1345,
|
||||
totalMiB: 16303,
|
||||
}
|
||||
const healthyVramSample = {
|
||||
gpuName: 'NVIDIA GeForce RTX 5070 Ti',
|
||||
usedMiB: 4000,
|
||||
freeMiB: 8000,
|
||||
totalMiB: 16303,
|
||||
}
|
||||
|
||||
expect(
|
||||
chooseStartupGpuTarget({
|
||||
platform: 'win32',
|
||||
headlessSmoke: false,
|
||||
requestedMode: 'auto',
|
||||
vramSample: lowVramSample,
|
||||
hasIntegratedGpu: true,
|
||||
}),
|
||||
).toEqual({
|
||||
target: 'low-power',
|
||||
requestedMode: 'auto',
|
||||
reason: 'low-vram-igpu',
|
||||
vramSample: lowVramSample,
|
||||
hasIntegratedGpu: true,
|
||||
})
|
||||
|
||||
expect(
|
||||
chooseStartupGpuTarget({
|
||||
platform: 'win32',
|
||||
headlessSmoke: false,
|
||||
requestedMode: 'auto',
|
||||
vramSample: lowVramSample,
|
||||
hasIntegratedGpu: false,
|
||||
}),
|
||||
).toEqual({
|
||||
target: 'software',
|
||||
requestedMode: 'auto',
|
||||
reason: 'low-vram-software',
|
||||
vramSample: lowVramSample,
|
||||
hasIntegratedGpu: false,
|
||||
})
|
||||
|
||||
expect(
|
||||
chooseStartupGpuTarget({
|
||||
platform: 'win32',
|
||||
headlessSmoke: false,
|
||||
requestedMode: 'auto',
|
||||
vramSample: healthyVramSample,
|
||||
hasIntegratedGpu: true,
|
||||
}),
|
||||
).toEqual({
|
||||
target: 'default',
|
||||
requestedMode: 'auto',
|
||||
reason: 'normal-gpu',
|
||||
vramSample: healthyVramSample,
|
||||
hasIntegratedGpu: true,
|
||||
})
|
||||
|
||||
expect(
|
||||
chooseStartupGpuTarget({
|
||||
platform: 'win32',
|
||||
headlessSmoke: false,
|
||||
requestedMode: 'high-performance',
|
||||
vramSample: lowVramSample,
|
||||
hasIntegratedGpu: true,
|
||||
}).reason,
|
||||
).toBe('user-high-performance')
|
||||
|
||||
expect(
|
||||
chooseStartupGpuTarget({
|
||||
platform: 'win32',
|
||||
headlessSmoke: false,
|
||||
requestedMode: 'low-power',
|
||||
vramSample: healthyVramSample,
|
||||
hasIntegratedGpu: true,
|
||||
}).target,
|
||||
).toBe('low-power')
|
||||
|
||||
expect(
|
||||
chooseStartupGpuTarget({
|
||||
platform: 'win32',
|
||||
headlessSmoke: true,
|
||||
requestedMode: 'high-performance',
|
||||
vramSample: healthyVramSample,
|
||||
hasIntegratedGpu: true,
|
||||
}),
|
||||
).toMatchObject({ target: 'software', reason: 'headless-smoke' })
|
||||
})
|
||||
|
||||
test('createVramHysteresisTracker enforces consecutive readings and deadband', () => {
|
||||
const lowSample = { gpuName: 'RTX 5070 Ti', usedMiB: 14500, freeMiB: 1500, totalMiB: 16303 }
|
||||
const midSample = { gpuName: 'RTX 5070 Ti', usedMiB: 13000, freeMiB: 3000, totalMiB: 16303 }
|
||||
const highSample = { gpuName: 'RTX 5070 Ti', usedMiB: 11000, freeMiB: VRAM_RECOVER_THRESHOLD_MIB, totalMiB: 16303 }
|
||||
|
||||
const igpuTracker = createVramHysteresisTracker({
|
||||
activeTarget: 'low-power',
|
||||
hasIntegratedGpu: true,
|
||||
})
|
||||
expect(igpuTracker.observe(midSample)).toBeNull()
|
||||
expect(igpuTracker.observe(highSample)).toBeNull()
|
||||
expect(igpuTracker.observe(midSample)).toBeNull() // streak reset
|
||||
expect(igpuTracker.observe(highSample)).toBeNull()
|
||||
expect(igpuTracker.observe(highSample)).toEqual({
|
||||
kind: 'switch-to-discrete',
|
||||
sample: highSample,
|
||||
})
|
||||
|
||||
const dgpuWithIgpu = createVramHysteresisTracker({
|
||||
activeTarget: 'default',
|
||||
hasIntegratedGpu: true,
|
||||
})
|
||||
expect(dgpuWithIgpu.observe(midSample)).toBeNull()
|
||||
expect(dgpuWithIgpu.observe({ ...lowSample, freeMiB: VRAM_LOW_THRESHOLD_MIB - 1 })).toBeNull()
|
||||
expect(dgpuWithIgpu.observe(null)).toBeNull() // missing reading resets streak
|
||||
expect(dgpuWithIgpu.observe(lowSample)).toBeNull()
|
||||
expect(dgpuWithIgpu.observe(lowSample)).toEqual({
|
||||
kind: 'switch-to-low-power',
|
||||
sample: lowSample,
|
||||
})
|
||||
|
||||
const dgpuNoIgpu = createVramHysteresisTracker({
|
||||
activeTarget: 'high-performance',
|
||||
hasIntegratedGpu: false,
|
||||
})
|
||||
expect(dgpuNoIgpu.observe(lowSample)).toBeNull()
|
||||
expect(dgpuNoIgpu.observe(lowSample)).toEqual({
|
||||
kind: 'switch-to-software',
|
||||
sample: lowSample,
|
||||
})
|
||||
})
|
||||
|
||||
test('stripGpuOverrideArgs removes CLI GPU override flags cleanly', () => {
|
||||
expect(
|
||||
stripGpuOverrideArgs([
|
||||
'--fullscreen',
|
||||
'--software-gl',
|
||||
'--gpu-mode=low-power',
|
||||
'--gpu-mode',
|
||||
'high-performance',
|
||||
'--low-power-gpu',
|
||||
'--high-performance-gpu',
|
||||
'planet-earth://open',
|
||||
]),
|
||||
).toEqual(['--fullscreen', 'planet-earth://open'])
|
||||
})
|
||||
|
||||
test('gpuMode config normalization, CLI flags, persistence, and readPreReadyGpuMode precedence work', () => {
|
||||
expect(normalizeGpuMode('AUTO')).toBe('auto')
|
||||
expect(normalizeGpuMode('igpu')).toBe('low-power')
|
||||
expect(normalizeGpuMode('discrete')).toBe('high-performance')
|
||||
expect(normalizeGpuMode('cpu')).toBe('software')
|
||||
expect(normalizeGpuMode('unknown', 'low-power')).toBe('low-power')
|
||||
|
||||
expect(parseLaunchArgs(['--low-power-gpu']).flags.gpuModeOverride).toBe('low-power')
|
||||
expect(parseLaunchArgs(['--high-performance-gpu']).flags.gpuModeOverride).toBe('high-performance')
|
||||
expect(parseLaunchArgs(['--software-gl']).flags.gpuModeOverride).toBe('software')
|
||||
expect(parseLaunchArgs(['--gpu-mode', 'igpu']).flags.gpuModeOverride).toBe('low-power')
|
||||
|
||||
const userDataDir = path.join(tempRoot, 'gpu-user-data')
|
||||
const exeDir = path.join(tempRoot, 'gpu-exe-dir')
|
||||
const store = new DesktopConfigStore({ userDataDir, exeDir, argv: [], env: {} })
|
||||
expect(store.get().gpuMode).toBe('auto')
|
||||
store.updateEndpoints({ backendUrl: 'https://rclaw.test' })
|
||||
store.updateGpuMode('low-power')
|
||||
|
||||
expect(
|
||||
readPreReadyGpuMode({ userDataDir, exeDir, argv: [], env: {} }),
|
||||
).toBe('low-power')
|
||||
expect(
|
||||
readPreReadyGpuMode({ userDataDir, exeDir, argv: [], env: { PLANET_GPU_MODE: 'high-performance' } }),
|
||||
).toBe('high-performance')
|
||||
expect(
|
||||
readPreReadyGpuMode({
|
||||
userDataDir,
|
||||
exeDir,
|
||||
argv: ['--software-gl'],
|
||||
env: { PLANET_GPU_MODE: 'high-performance' },
|
||||
}),
|
||||
).toBe('software')
|
||||
|
||||
const reloaded = new DesktopConfigStore({ userDataDir, exeDir, argv: [], env: {} })
|
||||
expect(reloaded.get().gpuMode).toBe('low-power')
|
||||
expect(reloaded.get().backendUrl).toBe('https://rclaw.test')
|
||||
})
|
||||
|
||||
test('createSustainedLowFpsTracker ignores brief dips and triggers after 5s below 20 FPS with cooldown', () => {
|
||||
const tracker = createSustainedLowFpsTracker()
|
||||
let now = 0
|
||||
expect(tracker.onFrame(now)).toBeNull()
|
||||
|
||||
// Simulate 10 FPS (100ms frame delta) for 4 seconds -> not yet 5s sustained
|
||||
for (let sec = 0; sec < 4; sec += 1) {
|
||||
for (let f = 0; f < 10; f += 1) {
|
||||
now += 100
|
||||
expect(tracker.onFrame(now)).toBeNull()
|
||||
}
|
||||
}
|
||||
|
||||
// Recover above 20 FPS -> resets low streak
|
||||
for (let f = 0; f < 30; f += 1) {
|
||||
now += 35
|
||||
expect(tracker.onFrame(now)).toBeNull()
|
||||
}
|
||||
|
||||
// Now sustain 10 FPS for 5 full seconds -> triggers on 5th second
|
||||
let trigger: { avgFps: number; sustainedMs: number } | null = null
|
||||
for (let sec = 0; sec < 5; sec += 1) {
|
||||
for (let f = 0; f < 10; f += 1) {
|
||||
now += 100
|
||||
const res = tracker.onFrame(now)
|
||||
if (res) trigger = res
|
||||
}
|
||||
}
|
||||
expect(trigger).not.toBeNull()
|
||||
expect(trigger!.avgFps).toBeGreaterThanOrEqual(9.5)
|
||||
expect(trigger!.avgFps).toBeLessThan(11)
|
||||
expect(trigger!.sustainedMs).toBeGreaterThanOrEqual(5000)
|
||||
|
||||
// Within 15s report cooldown -> suppressed even if slow again
|
||||
for (let sec = 0; sec < 5; sec += 1) {
|
||||
for (let f = 0; f < 10; f += 1) {
|
||||
now += 100
|
||||
expect(tracker.onFrame(now)).toBeNull()
|
||||
}
|
||||
}
|
||||
|
||||
// Reset clears accumulated low duration cleanly
|
||||
tracker.reset()
|
||||
now += 20_000
|
||||
expect(tracker.onFrame(now)).toBeNull()
|
||||
for (let sec = 0; sec < 4; sec += 1) {
|
||||
for (let f = 0; f < 10; f += 1) {
|
||||
now += 100
|
||||
expect(tracker.onFrame(now)).toBeNull()
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
test('canAutoSwitchGpu, handoff target decision, and handoff CLI args preserve state across relaunch', () => {
|
||||
expect(canAutoSwitchGpu(null, 10_000)).toBe(true)
|
||||
expect(canAutoSwitchGpu(10_000, 40_000)).toBe(false)
|
||||
expect(canAutoSwitchGpu(10_000, 55_000)).toBe(true)
|
||||
|
||||
expect(
|
||||
chooseStartupGpuTarget({
|
||||
platform: 'win32',
|
||||
headlessSmoke: false,
|
||||
requestedMode: 'auto',
|
||||
handoffTarget: 'low-power',
|
||||
vramSample: null,
|
||||
hasIntegratedGpu: true,
|
||||
}),
|
||||
).toMatchObject({ target: 'low-power', reason: 'gpu-handoff' })
|
||||
|
||||
const args = buildGpuHandoffArgs(
|
||||
['--fullscreen', '--gpu-handoff', '--gpu-handoff-target=low-power', 'planet-earth://open'],
|
||||
'default',
|
||||
)
|
||||
expect(args).toEqual([
|
||||
'--fullscreen',
|
||||
'planet-earth://open',
|
||||
'--gpu-handoff',
|
||||
'--gpu-handoff-target=default',
|
||||
])
|
||||
expect(readPreReadyGpuHandoff(args)).toEqual({
|
||||
gpuHandoff: true,
|
||||
gpuHandoffTarget: 'default',
|
||||
})
|
||||
expect(stripGpuOverrideArgs(args)).toEqual(['--fullscreen', 'planet-earth://open'])
|
||||
})
|
||||
})
|
||||
@@ -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,
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -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<Headers> = []
|
||||
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', () => {
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
[Unit]
|
||||
Description=Deploy the latest published Planet release
|
||||
After=network-online.target docker.service
|
||||
Wants=network-online.target
|
||||
Requires=docker.service
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
UMask=0077
|
||||
Nice=10
|
||||
StateDirectory=planet-release-deploy
|
||||
StateDirectoryMode=0700
|
||||
TimeoutStartSec=45min
|
||||
ExecStart=/usr/bin/python3 /usr/local/lib/planet-release/production_deploy.py
|
||||
@@ -0,0 +1,11 @@
|
||||
[Unit]
|
||||
Description=Check Gitea for published Planet releases
|
||||
|
||||
[Timer]
|
||||
OnCalendar=*:0/2
|
||||
Persistent=true
|
||||
AccuracySec=5s
|
||||
Unit=planet-release-deploy.service
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
@@ -8,6 +8,30 @@ 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
|
||||
|
||||
### Highlights
|
||||
|
||||
- On Windows, automatic GPU selection checks free discrete GPU memory at startup. Below 2 GiB it requests integrated graphics when available and falls back to software rendering otherwise.
|
||||
- During use, five seconds below 20 FPS prompts a second memory check before switching away from the discrete GPU. An automatic switch starts a 45-second cooldown. Once it expires, the client checks every five seconds and switches back after two consecutive readings of at least 3.5 GiB free. Automatic relaunches skip the splash and restore the window state.
|
||||
- The splash screen and Earth interface now use **Intelligent Media Institute** as the English name of 临空智能媒体研究院 (IMI).
|
||||
|
||||
---
|
||||
|
||||
## [0.79.0] — 2026-11-24
|
||||
|
||||
Released: 2026-11-24
|
||||
|
||||
@@ -44,7 +44,7 @@ Earth now supports both a **Web browser entry** and a **native Electron desktop
|
||||
- **Runtime endpoint injection**: Preload injects synchronous `window.__PLANET_RUNTIME_CONFIG__` (`backendUrl`, `adminUrl`, `wsUrl`, `motionWsUrl`, `localMediaPipeBaseUrl`, `isElectron`) and `window.planetDesktop`. `realtime.js`, `motion-control.js`, and `motion-browser-provider.js` consume those endpoints and load bundled MediaPipe assets locally first.
|
||||
- **Cross-process live synchronization**: Because Electron Earth runs outside the Admin origin, backend API mutations for compute comparison settings, brand config, and about info push `earth_updates` reload hints (`compute_configuration`, `earth_brand`, `earth_about`) over `/ws` alongside same-origin `BroadcastChannel` notices.
|
||||
- **Native window controls and frame pacing**: Desktop uses a native dark OS frame so window buttons never overlap `#media-panel`, lowers minimum window dimensions to `360×480` so manual narrowing enters Earth's mobile layout (`<= 820px`), and adds one-click **View → Toggle Portrait & Landscape** (`CmdOrCtrl+Shift+M`) in the native `Alt` menu bar alongside saved portrait/landscape bounds; it also locks Chromium page zoom (`setVisualZoomLevelLimits(1, 1)`) while forwarding pinch (`wheel + ctrlKey`) and `CmdOrCtrl + =/-/0` to 3D globe zoom, and stabilizes frame pacing by coalescing HUD glow pointer moves and globe hover raycasting into `requestAnimationFrame`, caching `DOMRect` via `ResizeObserver`, clamping `deltaTime` (`<= 50 ms`), and pausing renders on minimize via `planet-desktop:visibility`.
|
||||
- **Switchable desktop splash screen and zero-flash readiness gate**: [Desktop splash controller](/home/ray/dev/linkong/planet/client/src/preload/splash.ts) mounts via a `document` `MutationObserver` in preload the instant `<html>` is created and synchronously paints frame 1, while [Window show gate](/home/ray/dev/linkong/planet/client/src/main/show-gate.ts) waits for both `ready-to-show` and `planet:splash-first-paint` before showing the OS window so raw HTML never flashes; meanwhile `frontend/public/earth/js/main.js` and `controls.js` emit non-visual `earth:startup-progress` and `earth:startup-ready` lifecycle events (with zero Web UI/DOM impact) only after startup layers, `applyDeferredLayerVisibilitySettings` user-preference layers, stats/media readiness, and rendered 3D GPU frames settle before revealing the Earth viewport. It provides three real-coastline 3D Canvas themes (`singularity`, `constellation`, `horizon`, plus `off`), displays the transparent ZJU seal (`zju-emblem.png`) and `PRESENTED BY 临空智能媒体研究院 / Institute of Intelligent Media` lockup, and is controllable via splash pills, `Planet Earth → Splash Screen`, `CmdOrCtrl+Shift+S`, or `--splash-theme`.
|
||||
- **Switchable desktop splash screen and zero-flash readiness gate**: [Desktop splash controller](/home/ray/dev/linkong/planet/client/src/preload/splash.ts) mounts via a `document` `MutationObserver` in preload the instant `<html>` is created and synchronously paints frame 1, while [Window show gate](/home/ray/dev/linkong/planet/client/src/main/show-gate.ts) waits for both `ready-to-show` and `planet:splash-first-paint` before showing the OS window so raw HTML never flashes; meanwhile `frontend/public/earth/js/main.js` and `controls.js` emit non-visual `earth:startup-progress` and `earth:startup-ready` lifecycle events (with zero Web UI/DOM impact) only after startup layers, `applyDeferredLayerVisibilitySettings` user-preference layers, stats/media readiness, and rendered 3D GPU frames settle before revealing the Earth viewport. It provides three real-coastline 3D Canvas themes (`singularity`, `constellation`, `horizon`, plus `off`), displays the transparent ZJU seal (`zju-emblem.png`) and `PRESENTED BY 临空智能媒体研究院 / Intelligent Media Institute` lockup, and is controllable via splash pills, `Planet Earth → Splash Screen`, `CmdOrCtrl+Shift+S`, or `--splash-theme`.
|
||||
|
||||
Earth frontend is essentially a single shared visualization core under `public/earth` powering both Web and Desktop.
|
||||
|
||||
|
||||
@@ -473,6 +473,44 @@ uv run pytest backend/tests/test_otp_service.py
|
||||
5. After deployment, open Earth, enable "Border Lines", and inspect China's southeast coast, Taiwan, Hainan, the South China Sea, Zangnan, Kosovo, and Gaza for hover behavior and boundary policy.
|
||||
6. If no high-precision manifest/PMTiles exists locally, Earth uses the bundled `frontend/public/earth/data/countries-admin0.min.geojson` fallback. If high-precision assets exist but tile requests fail, troubleshoot PMTiles range requests, manifest provider, Nginx `.pmtiles` static serving, and sha256 consistency.
|
||||
|
||||
## Publish locally and deploy production releases automatically
|
||||
|
||||
Push the stable version tag to Gitea. On a new publishing workstation, sign in to the dedicated Docker configuration with a Gitea token scoped to `write:package`. Git release credentials and the package writer credential are stored separately.
|
||||
|
||||
```bash
|
||||
docker --config "${XDG_CONFIG_HOME:-$HOME/.config}/planet/registry" login gitea.rclaw.top --username linkong
|
||||
```
|
||||
|
||||
Run the following command from the tagged commit.
|
||||
|
||||
```bash
|
||||
python3 scripts/release_publish.py --tag "$(git describe --tags --exact-match)" --use-git-credential
|
||||
```
|
||||
|
||||
The publisher builds Linux amd64 images for `admin`, `backend`, and `aiprovider` from the tag, then verifies their revisions and digests in Gitea. Admin uses the lightweight build target. Desktop packages are built from the same commit by default. Pass `--assets-dir client/release` to reuse complete packages and a hotfix built for that tag. Repeat the same command after an interrupted upload to reuse the original build and verified attachments. The workstation can go offline once publication succeeds.
|
||||
|
||||
The production host checks the latest stable Gitea Release approximately every two minutes using `planet-release-deploy.timer`. Once all three images and the hotfix checksum are available, it pulls the images by digest, backs up PostgreSQL, updates AI Provider, backend, and Admin in order, verifies their endpoints, publishes the Earth hotfix, and downloads it to verify its checksum. The host retains its Compose configuration, memory limits, and data volumes. Apply the release-specific infrastructure migration first when a release requires new mounts, services, or incompatible database changes.
|
||||
|
||||
A failed rollout restores the previous application images and hotfix manifest while preserving database writes. An interrupted rollout resumes recovery on the next check. A failed version waits for an explicit retry or a newer release. The most recent pre-change database backups and version records are under `/var/lib/planet-release-deploy/last-success/` and `last-failed/`. Retry after resolving the underlying error.
|
||||
|
||||
```bash
|
||||
systemctl list-timers planet-release-deploy.timer
|
||||
journalctl -u planet-release-deploy.service -n 40
|
||||
sudo python3 /usr/local/lib/planet-release/production_deploy.py --check
|
||||
sudo python3 /usr/local/lib/planet-release/production_deploy.py --retry
|
||||
```
|
||||
|
||||
To provision a replacement host, restore `/etc/planet/deploy.env`, `/opt/planet/current`, and the production volumes. Install the controller from a trusted checkout and verify the current deployment before enabling its timer.
|
||||
|
||||
```bash
|
||||
sudo install -d /usr/local/lib/planet-release
|
||||
sudo install -m 0644 scripts/{production_deploy,production_registry,release_publish}.py /usr/local/lib/planet-release/
|
||||
sudo install -m 0644 deploy/systemd/planet-release-deploy.{service,timer} /etc/systemd/system/
|
||||
sudo systemctl daemon-reload
|
||||
sudo python3 /usr/local/lib/planet-release/production_deploy.py --check
|
||||
sudo systemctl enable --now planet-release-deploy.timer
|
||||
```
|
||||
|
||||
## Related Docs
|
||||
|
||||
- [planet.sh Startup Mechanism](/home/ray/dev/linkong/planet/docs/technical/en/ops-planet-sh-startup.md)
|
||||
|
||||
@@ -42,7 +42,7 @@ Earth 现同时支持**Web 浏览入口**与**原生 Electron 桌面客户端入
|
||||
- **运行时端点注入**:桌面预加载脚本暴露同步 `window.__PLANET_RUNTIME_CONFIG__`(`backendUrl`、`adminUrl`、`wsUrl`、`motionWsUrl`、`localMediaPipeBaseUrl`、`isElectron`)及受控 `window.planetDesktop` 桥接,`realtime.js`、`motion-control.js` 与 `motion-browser-provider.js` 自动读取该配置并优先加载本地 MediaPipe WASM。
|
||||
- **跨进程实时同步**:由于 Electron 桌面端与 `planet_admin` 容器不在同一浏览器源,后台对算力配置、Earth 品牌信息及关于信息的修改除广播 `BroadcastChannel` 外,同时经后端 WebSocket 推送 `earth_updates`(`compute_configuration` / `earth_brand` / `earth_about`),使桌面端与浏览器端同步刷新。
|
||||
- **原生窗口与帧率稳定**:桌面端使用原生暗色标题栏避免遮挡右上角 `#media-panel`,窗口最小尺寸放宽至 `360×480` 以支持手动拖窄进入移动端布局(`<= 820px`),并可通过 `Alt` 菜单栏 **视图 / View → 切换横竖屏 / Toggle Portrait & Landscape**(或 `CmdOrCtrl+Shift+M`)一键切换横竖屏比例;同时禁用 Chromium 页面缩放并将触控板捏合(`wheel + ctrlKey`)及 `CmdOrCtrl + =/-/0` 映射至 3D 视角缩放;`controls.js` 对液态玻璃光斑响应、`frame-stats.js` 布局刷新与 `main.js` 地球悬停拾取采用 `ResizeObserver` + `requestAnimationFrame` 合帧并限制 `deltaTime` 尖峰,窗口最小化时通过 `planet-desktop:visibility` 暂停空转渲染。
|
||||
- **多方案桌面端启动画面与无闪烁就绪门控**:[桌面端启动画面控制器](/home/ray/dev/linkong/planet/client/src/preload/splash.ts) 通过预加载脚本里的 `document` `MutationObserver` 在解析出 `<html>` 的第一时间挂载隔离 Shadow DOM 蒙层并同步绘制首帧,[窗口展示门控](/home/ray/dev/linkong/planet/client/src/main/show-gate.ts) 同时等待 `ready-to-show` 与 `planet:splash-first-paint` 后才显示窗口,彻底消除启动瞬间的原始网页闪屏;同时 `frontend/public/earth/js/main.js` 与 `controls.js` 在保持 Web 端视觉与交互完全一致的前提下,通过非可视化的 `earth:startup-progress` / `earth:startup-ready` 生命周期事件在完成 `applyDeferredLayerVisibilitySettings` 用户偏好图层恢复、统计/新闻直播初始化及首帧 3D GPU 渲染后再触发星核/星轨/破晓退场;内置三套 3D Canvas 动态启动方案(`singularity` / `constellation` / `horizon`),展示透明浙大校徽与 `PRESENTED BY 临空智能媒体研究院 / Institute of Intelligent Media` 署名,可通过启动页切换按钮、`Alt → Planet Earth → 启动画面方案`、`CmdOrCtrl+Shift+S` 重播及 `--splash-theme` 切换。
|
||||
- **多方案桌面端启动画面与无闪烁就绪门控**:[桌面端启动画面控制器](/home/ray/dev/linkong/planet/client/src/preload/splash.ts) 通过预加载脚本里的 `document` `MutationObserver` 在解析出 `<html>` 的第一时间挂载隔离 Shadow DOM 蒙层并同步绘制首帧,[窗口展示门控](/home/ray/dev/linkong/planet/client/src/main/show-gate.ts) 同时等待 `ready-to-show` 与 `planet:splash-first-paint` 后才显示窗口,彻底消除启动瞬间的原始网页闪屏;同时 `frontend/public/earth/js/main.js` 与 `controls.js` 在保持 Web 端视觉与交互完全一致的前提下,通过非可视化的 `earth:startup-progress` / `earth:startup-ready` 生命周期事件在完成 `applyDeferredLayerVisibilitySettings` 用户偏好图层恢复、统计/新闻直播初始化及首帧 3D GPU 渲染后再触发星核/星轨/破晓退场;内置三套 3D Canvas 动态启动方案(`singularity` / `constellation` / `horizon`),展示透明浙大校徽与 `PRESENTED BY 临空智能媒体研究院 / Intelligent Media Institute` 署名,可通过启动页切换按钮、`Alt → Planet Earth → 启动画面方案`、`CmdOrCtrl+Shift+S` 重播及 `--splash-theme` 切换。
|
||||
|
||||
所以 Earth 前端本质上是 `public/earth` 下的一套独立可视化内核,同时服务 Web 与桌面端。
|
||||
|
||||
|
||||
@@ -473,6 +473,44 @@ uv run pytest backend/tests/test_otp_service.py
|
||||
5. 部署后打开智能星球,开启“国界线”,放大中国东南海岸、台湾、海南、南海、藏南、科索沃、加沙等区域验证 hover 和边界口径。
|
||||
6. 如果本地没有高精 manifest/PMTiles,Earth 会使用 `frontend/public/earth/data/countries-admin0.min.geojson` 低精度 fallback;如果高精产物存在但瓦片请求失败,按 PMTiles range 请求、manifest provider、Nginx `.pmtiles` 静态返回和 sha256 一致性排查。
|
||||
|
||||
## 在本机发版,生产机自动部署
|
||||
|
||||
把正式版本标签推送到 Gitea 后,在发版机的 Planet 仓库执行以下命令。首次配置发版机时,使用具有 `write:package` 权限的 Gitea 令牌登录专用 Docker 配置目录。Git 发布凭据与镜像推送凭据分别保存。
|
||||
|
||||
```bash
|
||||
docker --config "${XDG_CONFIG_HOME:-$HOME/.config}/planet/registry" login gitea.rclaw.top --username linkong
|
||||
```
|
||||
|
||||
日常发版时在已打标签的提交上执行以下命令。
|
||||
|
||||
```bash
|
||||
python3 scripts/release_publish.py --tag "$(git describe --tags --exact-match)" --use-git-credential
|
||||
```
|
||||
|
||||
发布器从标签提交构建 Linux amd64 的 `admin`、`backend`、`aiprovider` 镜像,并核验仓库中的提交标签与摘要。Admin 使用轻量构建目标。默认从同一提交打包桌面客户端。已经备好该标签的各平台安装包和热更新包时可加 `--assets-dir client/release`。上传中断后重复同一命令即可复用已构建的镜像和已校验的附件。发布命令成功后可以关闭本机。
|
||||
|
||||
生产机的 `planet-release-deploy.timer` 约每两分钟读取 Gitea 最新正式 Release。新版本的三个镜像和热更新校验文件齐全后,服务按不可变摘要拉取镜像,备份 PostgreSQL,依次更新 AI Provider、后端和 Admin,再验证接口、发布并回读 Earth 热更新包。主机沿用当前生产 Compose、内存限制和数据卷。需要新增挂载、服务或数据库不兼容变更时,先按该版本的迁移方案调整主机配置。
|
||||
|
||||
上线失败时,服务恢复上一版的镜像摘要和热更新清单,保留数据库里的业务写入。事务记录在重启后仍可恢复。失败的版本会暂停自动重试,较新的正式版仍可上线。`/var/lib/planet-release-deploy/last-success/` 和 `last-failed/` 分别保留最近一次成功或失败切换前的数据库备份和版本信息。确认故障已排除后可以单独重试该版本。
|
||||
|
||||
```bash
|
||||
systemctl list-timers planet-release-deploy.timer
|
||||
journalctl -u planet-release-deploy.service -n 40
|
||||
sudo python3 /usr/local/lib/planet-release/production_deploy.py --check
|
||||
sudo python3 /usr/local/lib/planet-release/production_deploy.py --retry
|
||||
```
|
||||
|
||||
替换部署主机时,从受信任的运维检出中安装控制程序和定时器。先恢复 `/etc/planet/deploy.env`、`/opt/planet/current` 及当前生产数据卷,再校验当前版本并启用定时器。
|
||||
|
||||
```bash
|
||||
sudo install -d /usr/local/lib/planet-release
|
||||
sudo install -m 0644 scripts/{production_deploy,production_registry,release_publish}.py /usr/local/lib/planet-release/
|
||||
sudo install -m 0644 deploy/systemd/planet-release-deploy.{service,timer} /etc/systemd/system/
|
||||
sudo systemctl daemon-reload
|
||||
sudo python3 /usr/local/lib/planet-release/production_deploy.py --check
|
||||
sudo systemctl enable --now planet-release-deploy.timer
|
||||
```
|
||||
|
||||
## 相关文档
|
||||
|
||||
- [planet.sh 启动机制](/home/ray/dev/linkong/planet/docs/technical/zh/ops-planet-sh-startup.md)
|
||||
|
||||
@@ -16,12 +16,14 @@
|
||||
## Current Version
|
||||
|
||||
- `main` 当前主线历史推导到:`0.16.5`
|
||||
- `dev` 当前开发分支历史推导到:`0.79.0`
|
||||
- `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` | 全局单份采集策略、短期船舶航迹、精简生产部署和桌面协议注册 |
|
||||
| `0.77.0` | feature | `dev` | `v0.77.0` | 新增原生 Electron Earth 桌面客户端(多方案 3D 启动页/横竖屏/离线协议/Gitea 自动发布)、轻量 Admin 独立容器、全球综合态势工作台与算力对比增强 |
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "planet-frontend",
|
||||
"version": "0.79.0",
|
||||
"version": "0.79.2",
|
||||
"private": true,
|
||||
"packageManager": "bun@1",
|
||||
"dependencies": {
|
||||
|
||||
@@ -871,7 +871,7 @@ const EXACT_TRANSLATIONS = {
|
||||
"出品方": "Producer",
|
||||
"策划人": "Planners",
|
||||
"产品兼开发者": "Product & Development",
|
||||
"浙江大学临空智能媒体研究院": "Zhejiang University Linkong Institute of Intelligent Media",
|
||||
"浙江大学临空智能媒体研究院": "Zhejiang University Linkong Intelligent Media Institute",
|
||||
"方兴东、黄柳青": "Fang Xingdong, Huang Liuqing",
|
||||
"钱坤、张鸽、齐鹏": "Qian Kun, Zhang Ge, Qi Peng",
|
||||
"面向临空场景下的智能媒体研究、全球态势感知与多源开放数据巡航,提供可视化观测、事件聚合与交互式探索能力。": "For intelligent media research, global situational awareness, and multi-source open-data cruise in linkong scenarios, providing visual observation, event aggregation, and interactive exploration.",
|
||||
@@ -981,7 +981,7 @@ const EXACT_TRANSLATIONS = {
|
||||
"搜索结果": "Search results",
|
||||
"调整地球默认大小": "Adjust default Earth size",
|
||||
"调整地形透明度": "Adjust terrain opacity",
|
||||
"浙江大学临空智能媒体研究院 Logo": "Zhejiang University Linkong Institute of Intelligent Media Logo",
|
||||
"浙江大学临空智能媒体研究院 Logo": "Zhejiang University Linkong Intelligent Media Institute Logo",
|
||||
"Earth 页面发生未捕获错误": "Earth page uncaught error",
|
||||
"Earth 页面发生未处理 Promise 错误": "Earth page unhandled Promise error",
|
||||
"等待动捕数据": "Waiting for motion data",
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -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 [];
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -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]);
|
||||
});
|
||||
});
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "planet"
|
||||
version = "0.79.0"
|
||||
version = "0.79.2"
|
||||
description = "智能星球计划 - 态势感知系统"
|
||||
requires-python = ">=3.14"
|
||||
dependencies = [
|
||||
|
||||
@@ -24,6 +24,7 @@ main() {
|
||||
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_docker_proxy.py
|
||||
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_docker_mirror.py
|
||||
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_database_startup.py
|
||||
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_production_release.py
|
||||
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_windows_restart.py
|
||||
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_error_diagnostics.py
|
||||
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_tool_resolution.py
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import unittest
|
||||
from contextlib import ExitStack
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
import production_deploy as deploy
|
||||
import production_registry as registry
|
||||
import production_release as publisher
|
||||
|
||||
|
||||
def hotfix(tag):
|
||||
buf = io.BytesIO()
|
||||
with tarfile.open(fileobj=buf, mode="w:gz") as archive:
|
||||
for name, data in {
|
||||
"bundle-meta.json": json.dumps({"version": tag[1:], "shellVersion": tag[1:]}).encode(),
|
||||
"index.html": b"<html>release test</html>",
|
||||
}.items():
|
||||
member = tarfile.TarInfo(name)
|
||||
member.size = len(data)
|
||||
archive.addfile(member, io.BytesIO(data))
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
class TransactionTests(unittest.TestCase):
|
||||
old, tag = "v1.0.0", "v1.1.0"
|
||||
|
||||
def setUp(self):
|
||||
self.stack = ExitStack()
|
||||
self.addCleanup(self.stack.close)
|
||||
base = Path(self.stack.enter_context(tempfile.TemporaryDirectory()))
|
||||
self.host = deploy.Host(base / "host", base / "settings", base / "state")
|
||||
self.host.state.mkdir()
|
||||
folder = self.host.directory(self.old)
|
||||
folder.mkdir(parents=True)
|
||||
for name in deploy.HOST_FILES:
|
||||
(folder / name).write_text("host-managed")
|
||||
deploy.point_current(self.host, self.old)
|
||||
self.old_refs = {key: "previous-" + key for key in registry.SERVICES}
|
||||
self.new_refs = {key: "candidate-" + key for key in registry.SERVICES}
|
||||
lines = [f"{key}={self.old_refs[name]}" for name, key in registry.SERVICES.items()]
|
||||
self.host.env.write_text(
|
||||
"\n".join(lines + ["LIMIT=500m", "CLIENT_UPDATE_PUBLISH_TOKEN=fixture"]) + "\n"
|
||||
)
|
||||
self.running = self.old_refs.copy()
|
||||
self.manifest = base / "manifest.json"
|
||||
self.original = b'{"bundle":{"version":"1.0.0","sha256":"previous"}}'
|
||||
self.manifest.write_bytes(self.original)
|
||||
self.calls = []
|
||||
self.data = hotfix(self.tag)
|
||||
self.sha = hashlib.sha256(self.data).hexdigest()
|
||||
self.release = {"tag_name": self.tag, "draft": False, "prerelease": False}
|
||||
self.mock("read_url", return_value=json.dumps(self.release).encode())
|
||||
self.mock("tag_commit", return_value="f" * 40)
|
||||
self.images = self.mock("resolved_images", return_value=self.new_refs)
|
||||
self.mock("release_bundle", return_value=("bundle.tar.gz", self.data, self.sha))
|
||||
self.mock("inspect", side_effect=lambda name: {"Config": {"Image": self.running[name]}})
|
||||
self.mock("data_containers", return_value={"postgres": "same-db", "redis": "same-redis"})
|
||||
self.mock("live_manifest_path", return_value=self.manifest)
|
||||
self.mock("docker", side_effect=lambda *args: self.calls.append(args[0]))
|
||||
self.mock("backup_database", side_effect=lambda p: p.write_bytes(b"verified backup"))
|
||||
self.mock("check_routes", side_effect=lambda: self.calls.append("health"))
|
||||
self.service = self.mock("rollout_services", side_effect=self.roll)
|
||||
self.publish = self.mock("publish_hotfix_bundle", side_effect=self.publish_data)
|
||||
self.verify = self.mock("check_hotfix", side_effect=self.verify_data)
|
||||
|
||||
def mock(self, name, **kwargs):
|
||||
return self.stack.enter_context(patch.object(deploy, name, **kwargs))
|
||||
|
||||
def roll(self, host, tag, refs):
|
||||
self.calls.append(tag)
|
||||
self.running.update(refs)
|
||||
|
||||
def publish_data(self, **kwargs):
|
||||
self.calls.append("hotfix")
|
||||
archive, digest = kwargs["assets"][0]
|
||||
self.assertEqual(hashlib.sha256(archive.read_bytes()).hexdigest(), digest)
|
||||
self.manifest.write_text(
|
||||
json.dumps({"bundle": {"version": kwargs["tag"][1:], "sha256": digest}})
|
||||
)
|
||||
|
||||
def verify_data(self, tag, digest, shell_version=None):
|
||||
self.assertEqual(
|
||||
json.loads(self.manifest.read_bytes())["bundle"], {"version": tag[1:], "sha256": digest}
|
||||
)
|
||||
|
||||
def test_new_release_and_duplicate_tick(self):
|
||||
deploy.reconcile(self.host)
|
||||
self.assertEqual(self.calls, ["pull"] * 3 + [self.tag, "health", "hotfix"])
|
||||
self.assertEqual(self.host.current(), self.tag)
|
||||
self.assertEqual(self.running, self.new_refs)
|
||||
self.assertIn("LIMIT=500m\n", self.host.env.read_text())
|
||||
self.assertTrue((self.host.state / "last-success/database.dump").is_file())
|
||||
deploy.reconcile(self.host)
|
||||
self.assertEqual(self.service.call_count, 1)
|
||||
|
||||
def test_manifest_failure_restores_previous_release_and_parks_it(self):
|
||||
def verify(tag, sha, shell_version=None):
|
||||
if tag == self.tag:
|
||||
raise RuntimeError("independent public download failed")
|
||||
self.verify_data(tag, sha)
|
||||
|
||||
self.verify.side_effect = verify
|
||||
with self.assertRaisesRegex(RuntimeError, "download failed"):
|
||||
deploy.reconcile(self.host)
|
||||
self.assertEqual(self.host.current(), self.old)
|
||||
self.assertEqual(self.running, self.old_refs)
|
||||
self.assertEqual(self.manifest.read_bytes(), self.original)
|
||||
self.assertTrue((self.host.state / "last-failed/database.dump").is_file())
|
||||
deploy.reconcile(self.host)
|
||||
self.assertEqual(self.service.call_count, 2)
|
||||
self.verify.side_effect = self.verify_data
|
||||
deploy.reconcile(self.host, retry=True)
|
||||
self.assertEqual(self.host.current(), self.tag)
|
||||
|
||||
def test_interrupted_rollout_recovers_before_processing_latest(self):
|
||||
self.service.side_effect = KeyboardInterrupt()
|
||||
with self.assertRaises(KeyboardInterrupt):
|
||||
deploy.reconcile(self.host)
|
||||
self.assertTrue((self.host.state / "pending/release.json").is_file())
|
||||
self.service.side_effect = self.roll
|
||||
deploy.reconcile(self.host)
|
||||
self.assertFalse((self.host.state / "pending").exists())
|
||||
self.assertEqual(self.host.current(), self.old)
|
||||
self.assertEqual(self.running, self.old_refs)
|
||||
self.assertEqual(self.calls.count(self.old), 1)
|
||||
self.publish.assert_not_called()
|
||||
|
||||
def test_incomplete_publication_does_not_change_production(self):
|
||||
self.images.side_effect = RuntimeError("image is missing")
|
||||
env = self.host.env.read_bytes()
|
||||
with self.assertRaisesRegex(RuntimeError, "image is missing"):
|
||||
deploy.reconcile(self.host)
|
||||
self.assertEqual(self.host.env.read_bytes(), env)
|
||||
self.assertFalse((self.host.state / "pending").exists())
|
||||
self.service.assert_not_called()
|
||||
|
||||
def test_drafts_prereleases_and_older_versions_never_roll_out(self):
|
||||
for tag, draft, pre in [
|
||||
(self.tag, True, False),
|
||||
(self.tag, False, True),
|
||||
("v0.9.9", False, False),
|
||||
]:
|
||||
data = json.dumps({"tag_name": tag, "draft": draft, "prerelease": pre}).encode()
|
||||
with patch.object(deploy, "read_url", return_value=data):
|
||||
deploy.reconcile(self.host)
|
||||
self.images.assert_not_called()
|
||||
|
||||
|
||||
class ImageTests(unittest.TestCase):
|
||||
def test_interrupted_upload_reuses_identical_local_artifacts(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
root = Path(temp)
|
||||
supplied = root / "supplied"
|
||||
supplied.mkdir()
|
||||
cache = root / "cache"
|
||||
tag = "v1.2.3"
|
||||
for name in (
|
||||
"Planet Earth-1.2.3-win.zip",
|
||||
"Planet Earth-1.2.3-mac.zip",
|
||||
"planet_1.2.3.deb",
|
||||
):
|
||||
(supplied / name).write_bytes(b"original")
|
||||
(supplied / "planet-earth-bundle-1.2.3.tar.gz").write_bytes(hotfix(tag))
|
||||
suffixes = (".zip", ".deb", ".tar.gz")
|
||||
publisher.cached_packages(root, supplied, cache, tag, suffixes)
|
||||
original = "Planet Earth-1.2.3-win.zip"
|
||||
(supplied / original).write_bytes(b"later build")
|
||||
publisher.cached_packages(root, supplied, cache, tag, suffixes)
|
||||
self.assertEqual((cache / original).read_bytes(), b"original")
|
||||
(cache / original).write_bytes(b"corrupt cache")
|
||||
with self.assertRaisesRegex(ValueError, "differ"):
|
||||
publisher.cached_packages(root, supplied, cache, tag, suffixes)
|
||||
|
||||
def test_builds_only_missing_service_from_tag_and_verifies_after_push(self):
|
||||
with (
|
||||
tempfile.TemporaryDirectory() as temp,
|
||||
patch.object(publisher, "resolve_image") as resolve,
|
||||
patch.object(publisher.subprocess, "run") as run,
|
||||
):
|
||||
resolve.side_effect = ["provider-pin", "backend-pin", None, "admin-pin"]
|
||||
publisher.ensure_images(Path(temp), "v1.2.3", "a" * 40)
|
||||
args = run.call_args.args[0]
|
||||
self.assertIn("linux/amd64", args)
|
||||
self.assertIn("PLANET_FRONTEND_TARGET=admin", args)
|
||||
self.assertIn("org.opencontainers.image.revision=" + "a" * 40, args)
|
||||
self.assertTrue(any("push=true" in x and "admin:v1.2.3" in x for x in args))
|
||||
run.assert_called_once()
|
||||
|
||||
def test_registry_verifies_actual_config_and_commit_before_accepting_digest(self):
|
||||
commit = "a" * 40
|
||||
cfg = json.dumps(
|
||||
{
|
||||
"os": "linux",
|
||||
"architecture": "amd64",
|
||||
"config": {
|
||||
"Labels": {
|
||||
"org.opencontainers.image.revision": commit,
|
||||
"planet.frontend.target": "admin",
|
||||
}
|
||||
},
|
||||
}
|
||||
).encode()
|
||||
raw = json.dumps({"config": {"digest": registry.digest(cfg)}}).encode()
|
||||
with patch.object(registry, "read_url", side_effect=[b'{"token":"read"}', raw, cfg]):
|
||||
pin = registry.resolve_image("admin", "v1.2.3", commit)
|
||||
self.assertTrue(pin.endswith("@" + registry.digest(raw)))
|
||||
for bad_commit, bad_cfg in [("b" * 40, cfg), (commit, cfg + b" ")]:
|
||||
with (
|
||||
patch.object(registry, "read_url", side_effect=[b'{"token":"read"}', raw, bad_cfg]),
|
||||
self.assertRaises(ValueError),
|
||||
):
|
||||
registry.resolve_image("admin", "v1.2.3", bad_commit)
|
||||
|
||||
def test_corrupt_bundle_and_duplicate_checksum_are_rejected(self):
|
||||
tag = "v1.2.3"
|
||||
name = "planet-earth-bundle-1.2.3.tar.gz"
|
||||
data = hotfix(tag)
|
||||
expected = f"{hashlib.sha256(data).hexdigest()} {name}\n".encode()
|
||||
release = {
|
||||
"tag_name": tag,
|
||||
"assets": [{"name": name, "size": len(data)}, {"name": "SHA256SUMS.txt", "size": 99}],
|
||||
}
|
||||
for sums, content in [(expected + expected, data), (expected, b"x" * len(data))]:
|
||||
with (
|
||||
patch.object(registry, "read_url", side_effect=[sums, content]),
|
||||
self.assertRaises(ValueError),
|
||||
):
|
||||
registry.release_bundle(release, tag)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,479 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Reconcile published Planet releases with the existing lightweight production Compose stack."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import fcntl
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
if __package__:
|
||||
from .production_registry import (
|
||||
API,
|
||||
REPO,
|
||||
SERVER,
|
||||
SERVICES,
|
||||
read_url,
|
||||
release_bundle,
|
||||
resolve_image,
|
||||
tag_commit,
|
||||
version,
|
||||
)
|
||||
from .release_publish import publish_hotfix_bundle
|
||||
else:
|
||||
from production_registry import (
|
||||
API,
|
||||
REPO,
|
||||
SERVER,
|
||||
SERVICES,
|
||||
read_url,
|
||||
release_bundle,
|
||||
resolve_image,
|
||||
tag_commit,
|
||||
version,
|
||||
)
|
||||
from release_publish import publish_hotfix_bundle
|
||||
|
||||
PUBLIC = "https://rclaw.top"
|
||||
ADMIN = "https://admin.rclaw.top"
|
||||
PROJECT = "planet-production"
|
||||
HOST_FILES = (
|
||||
"compose.yaml",
|
||||
"compose.pilot.yaml",
|
||||
"planet-https.conf",
|
||||
"planet-api-locations.conf",
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Host:
|
||||
root: Path = Path("/opt/planet")
|
||||
env: Path = Path("/etc/planet/deploy.env")
|
||||
state: Path = Path("/var/lib/planet-release-deploy")
|
||||
|
||||
def directory(self, tag):
|
||||
version(tag)
|
||||
path = self.root / "releases" / tag
|
||||
if path.is_symlink():
|
||||
raise ValueError("Release directories must not be symbolic links")
|
||||
return path
|
||||
|
||||
def current(self):
|
||||
path = (self.root / "current").resolve(strict=True)
|
||||
if path != self.directory(path.name):
|
||||
raise ValueError("Unexpected active release directory")
|
||||
return path.name
|
||||
|
||||
|
||||
def sync_directory(path):
|
||||
fd = os.open(path, os.O_DIRECTORY | os.O_RDONLY)
|
||||
try:
|
||||
os.fsync(fd)
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
def atomic_file(path, data, mode=0o600):
|
||||
fd, name = tempfile.mkstemp(prefix="." + path.name, dir=path.parent)
|
||||
try:
|
||||
with os.fdopen(fd, "wb") as out:
|
||||
os.fchmod(out.fileno(), mode)
|
||||
out.write(data)
|
||||
out.flush()
|
||||
os.fsync(out.fileno())
|
||||
os.replace(name, path)
|
||||
sync_directory(path.parent)
|
||||
finally:
|
||||
Path(name).unlink(missing_ok=True)
|
||||
|
||||
|
||||
def point_current(host, tag):
|
||||
link = host.root / "current"
|
||||
with tempfile.TemporaryDirectory(dir=host.root) as temp:
|
||||
candidate = Path(temp) / "current"
|
||||
candidate.symlink_to(host.directory(tag))
|
||||
os.replace(candidate, link)
|
||||
sync_directory(host.root)
|
||||
|
||||
|
||||
def env_settings(host):
|
||||
return dict(
|
||||
line.split("=", 1)
|
||||
for line in host.env.read_text().splitlines()
|
||||
if "=" in line and not line.lstrip().startswith("#")
|
||||
)
|
||||
|
||||
|
||||
def set_images(host, images):
|
||||
values = {SERVICES[service]: images[service] for service in SERVICES}
|
||||
found = set()
|
||||
lines = host.env.read_text().splitlines(keepends=True)
|
||||
for index, line in enumerate(lines):
|
||||
key = line.partition("=")[0]
|
||||
if key in values:
|
||||
found.add(key)
|
||||
lines[index] = f"{key}={values[key]}\n"
|
||||
if missing := values.keys() - found:
|
||||
raise ValueError("Missing production image settings: " + ", ".join(sorted(missing)))
|
||||
atomic_file(host.env, "".join(lines).encode())
|
||||
|
||||
|
||||
def docker(*args):
|
||||
return subprocess.check_output(["docker", *map(str, args)], text=True).strip()
|
||||
|
||||
|
||||
def container_name(service):
|
||||
return "planet_deploy_" + service
|
||||
|
||||
|
||||
def inspect(service):
|
||||
return json.loads(docker("inspect", container_name(service)))[0]
|
||||
|
||||
|
||||
def data_containers():
|
||||
return {name: inspect(name)["Id"] for name in ("postgres", "redis")}
|
||||
|
||||
|
||||
def live_manifest_path():
|
||||
mounts = inspect("backend")["Mounts"]
|
||||
[mount] = [m for m in mounts if m["Destination"] == "/app/backend/data/client-updates"]
|
||||
if mount.get("Name") != PROJECT + "_client_updates_data" or mount["Type"] != "volume":
|
||||
raise RuntimeError("Expected the persistent production client update volume")
|
||||
return Path(mount["Source"]) / "manifest.json"
|
||||
|
||||
|
||||
def stage_config(host, previous, tag):
|
||||
source, target = host.directory(previous), host.directory(tag)
|
||||
target.mkdir(exist_ok=True)
|
||||
sync_directory(target.parent)
|
||||
for name in HOST_FILES:
|
||||
original, dest = source / name, target / name
|
||||
if dest.exists():
|
||||
if dest.is_symlink() or dest.read_bytes() != original.read_bytes():
|
||||
raise RuntimeError(f"Existing host configuration differs: {dest}")
|
||||
else:
|
||||
atomic_file(dest, original.read_bytes(), original.stat().st_mode & 0o777)
|
||||
return target
|
||||
|
||||
|
||||
def rollout_services(host, tag, images):
|
||||
directory = host.directory(tag)
|
||||
for name in SERVICES:
|
||||
print(f"Starting {name} from {images[name]}", flush=True)
|
||||
docker(
|
||||
"compose",
|
||||
"--project-name",
|
||||
PROJECT,
|
||||
"--env-file",
|
||||
host.env,
|
||||
"-f",
|
||||
directory / "compose.yaml",
|
||||
"-f",
|
||||
directory / "compose.pilot.yaml",
|
||||
"up",
|
||||
"-d",
|
||||
"--no-deps",
|
||||
"--no-build",
|
||||
"--pull",
|
||||
"never",
|
||||
name,
|
||||
)
|
||||
deadline = time.monotonic() + 100
|
||||
while True:
|
||||
container = inspect(name)
|
||||
state = container["State"]
|
||||
if (
|
||||
container["Config"]["Image"] == images[name]
|
||||
and state["Status"] == "running"
|
||||
and state.get("Health", {}).get("Status") == "healthy"
|
||||
):
|
||||
break
|
||||
if (
|
||||
state["Status"] in ("exited", "dead")
|
||||
or state.get("OOMKilled")
|
||||
or time.monotonic() >= deadline
|
||||
):
|
||||
raise RuntimeError(f"{name} did not become healthy")
|
||||
time.sleep(2)
|
||||
|
||||
|
||||
def check_routes():
|
||||
for url in (PUBLIC + "/health/ready", PUBLIC + "/api/v1/visualization/geo/summary"):
|
||||
if not isinstance(json.loads(read_url(url)), dict):
|
||||
raise RuntimeError(f"Unexpected response from {url}")
|
||||
if b"<html" not in read_url(ADMIN + "/earth").lower():
|
||||
raise RuntimeError("Admin Earth entry did not return HTML")
|
||||
|
||||
|
||||
def check_hotfix(tag, sha, shell_version=None):
|
||||
manifest = json.loads(read_url(PUBLIC + "/api/v1/client/update-manifest"))
|
||||
bundle = manifest.get("bundle") or {}
|
||||
path = f"/api/v1/client/updates/files/planet-earth-bundle-{tag[1:]}.tar.gz"
|
||||
if (
|
||||
manifest.get("shell", {}).get("version") != (shell_version or tag[1:])
|
||||
or bundle.get("version") != tag[1:]
|
||||
or bundle.get("sha256") != sha
|
||||
or bundle.get("url") != path
|
||||
):
|
||||
raise RuntimeError("Live hotfix manifest does not match the release")
|
||||
if hashlib.sha256(read_url(PUBLIC + path, limit=32 * 1024 * 1024)).hexdigest() != sha:
|
||||
raise RuntimeError("Live hotfix download failed SHA-256 verification")
|
||||
|
||||
|
||||
def minimum_shell(data, tag):
|
||||
with tarfile.open(fileobj=io.BytesIO(data), mode="r:gz") as archive:
|
||||
member = archive.getmember("bundle-meta.json")
|
||||
if not member.isfile() or member.size > 8192:
|
||||
raise ValueError("Invalid hotfix metadata")
|
||||
meta = json.load(archive.extractfile(member))
|
||||
if meta.get("version") != tag[1:]:
|
||||
raise ValueError("Hotfix metadata version differs from the release")
|
||||
minimum = meta.get("minShellVersion") or meta["shellVersion"]
|
||||
if version("v" + minimum) > version(tag):
|
||||
raise ValueError("Hotfix requires a newer shell than the release")
|
||||
return minimum
|
||||
|
||||
|
||||
def backup_database(target):
|
||||
with target.open("xb") as out:
|
||||
subprocess.run(
|
||||
[
|
||||
"docker",
|
||||
"exec",
|
||||
container_name("postgres"),
|
||||
"sh",
|
||||
"-ec",
|
||||
'exec pg_dump -Fc -Z 1 -U "$POSTGRES_USER" "$POSTGRES_DB"',
|
||||
],
|
||||
stdout=out,
|
||||
check=True,
|
||||
)
|
||||
os.fsync(out.fileno())
|
||||
with target.open("rb") as source:
|
||||
catalog = subprocess.check_output(
|
||||
["docker", "exec", "-i", container_name("postgres"), "pg_restore", "-l"], stdin=source
|
||||
)
|
||||
if b"TABLE DATA" not in catalog:
|
||||
raise RuntimeError("Pre-deployment database backup failed verification")
|
||||
|
||||
|
||||
def save_journal(host, journal, manifest):
|
||||
with tempfile.TemporaryDirectory(dir=host.state) as scratch:
|
||||
directory = Path(scratch) / "transaction"
|
||||
directory.mkdir()
|
||||
atomic_file(directory / "release.json", json.dumps(journal).encode())
|
||||
if manifest.exists():
|
||||
atomic_file(directory / "previous-manifest.json", manifest.read_bytes())
|
||||
backup_database(directory / "database.dump")
|
||||
sync_directory(directory)
|
||||
os.rename(directory, host.state / "pending")
|
||||
sync_directory(host.state)
|
||||
|
||||
|
||||
def finish_journal(host, name):
|
||||
previous = host.state / name
|
||||
if previous.exists():
|
||||
shutil.rmtree(previous)
|
||||
os.rename(host.state / "pending", previous)
|
||||
sync_directory(host.state)
|
||||
|
||||
|
||||
def rollback(host):
|
||||
pending = host.state / "pending"
|
||||
journal = json.loads((pending / "release.json").read_text())
|
||||
previous = journal["previous"]
|
||||
print(f"Restoring {previous} after interrupted or unsuccessful {journal['tag']}", flush=True)
|
||||
manifest = Path(journal["manifest"])
|
||||
old = pending / "previous-manifest.json"
|
||||
before = old.read_bytes() if old.exists() else None
|
||||
current = manifest.read_bytes() if manifest.exists() else None
|
||||
if current != before:
|
||||
bundle = json.loads(current or b"{}").get("bundle") or {}
|
||||
if bundle.get("version") != journal["tag"][1:] or bundle.get("sha256") != journal["sha"]:
|
||||
raise RuntimeError(
|
||||
"Hotfix manifest changed independently; preserved the transaction for review"
|
||||
)
|
||||
if before is None:
|
||||
manifest.unlink()
|
||||
sync_directory(manifest.parent)
|
||||
else:
|
||||
atomic_file(manifest, before, 0o644)
|
||||
set_images(host, journal["old_images"])
|
||||
rollout_services(host, previous, journal["old_images"])
|
||||
point_current(host, previous)
|
||||
check_routes()
|
||||
if before:
|
||||
old_manifest = json.loads(before)
|
||||
bundle = old_manifest.get("bundle")
|
||||
if bundle:
|
||||
check_hotfix(
|
||||
"v" + bundle["version"],
|
||||
bundle["sha256"],
|
||||
old_manifest.get("shell", {}).get("version"),
|
||||
)
|
||||
finish_journal(host, "last-failed")
|
||||
print(f"Rollback to {previous} verified", flush=True)
|
||||
|
||||
|
||||
def resolved_images(tag, commit):
|
||||
images = {}
|
||||
for service in SERVICES:
|
||||
ref = resolve_image(service, tag, commit)
|
||||
if not ref:
|
||||
raise RuntimeError(f"Waiting for the published {service}:{tag} image")
|
||||
images[service] = ref
|
||||
return images
|
||||
|
||||
|
||||
def deploy(host, release, previous, tag, images, commit):
|
||||
name, data, sha = release_bundle(release, tag)
|
||||
minimum = minimum_shell(data, tag)
|
||||
settings = env_settings(host)
|
||||
token = settings.get("CLIENT_UPDATE_PUBLISH_TOKEN", "").strip("'\u0022")
|
||||
if not token:
|
||||
raise RuntimeError("Production hotfix publisher credential is missing")
|
||||
old_images = {n: settings[k].strip("'\u0022") for n, k in SERVICES.items()}
|
||||
for service, ref in images.items():
|
||||
docker("pull", "--platform", "linux/amd64", ref)
|
||||
if inspect(service)["Config"]["Image"] != old_images[service]:
|
||||
raise RuntimeError("Running image differs from the host configuration: " + service)
|
||||
stage_config(host, previous, tag)
|
||||
manifest = live_manifest_path()
|
||||
bundle_path = manifest.parent / name
|
||||
if bundle_path.exists() and hashlib.sha256(bundle_path.read_bytes()).hexdigest() != sha:
|
||||
raise RuntimeError("Existing versioned hotfix file has different contents")
|
||||
original_stores = data_containers()
|
||||
save_journal(
|
||||
host,
|
||||
dict(
|
||||
tag=tag,
|
||||
previous=previous,
|
||||
old_images=old_images,
|
||||
manifest=str(manifest),
|
||||
sha=sha,
|
||||
commit=commit,
|
||||
),
|
||||
manifest,
|
||||
)
|
||||
try:
|
||||
set_images(host, images)
|
||||
rollout_services(host, tag, images)
|
||||
check_routes()
|
||||
if data_containers() != original_stores:
|
||||
raise RuntimeError("PostgreSQL or Redis container identity changed")
|
||||
with tempfile.TemporaryDirectory(dir=host.state) as tmp:
|
||||
archive = Path(tmp) / name
|
||||
archive.write_bytes(data)
|
||||
publish_hotfix_bundle(
|
||||
publish_url=PUBLIC,
|
||||
publish_token=token,
|
||||
tag=tag,
|
||||
notes=release.get("body") or "",
|
||||
release_html_url=f"{SERVER}/{REPO}/releases/tag/{tag}",
|
||||
assets=[(archive, sha)],
|
||||
min_shell_version=minimum,
|
||||
)
|
||||
check_hotfix(tag, sha)
|
||||
point_current(host, tag)
|
||||
finish_journal(host, "last-success")
|
||||
except Exception as exc:
|
||||
print(f"Deploying {tag} failed: {exc}", file=sys.stderr, flush=True)
|
||||
rollback(host)
|
||||
raise
|
||||
print(f"Deployed {tag} at {commit}", flush=True)
|
||||
|
||||
|
||||
def reconcile(host, *, check=False, retry=False):
|
||||
if (host.state / "pending").exists():
|
||||
if check:
|
||||
raise RuntimeError("A previous rollout is pending recovery")
|
||||
rollback(host)
|
||||
previous = host.current()
|
||||
release = json.loads(read_url(API + "/releases/latest"))
|
||||
tag = release["tag_name"]
|
||||
if release.get("draft") or release.get("prerelease"):
|
||||
return
|
||||
try:
|
||||
candidate_version = version(tag)
|
||||
except ValueError:
|
||||
print(f"Ignoring release with a non-production tag: {tag!r}")
|
||||
return
|
||||
if candidate_version < version(previous):
|
||||
return
|
||||
if tag == previous and not check:
|
||||
print(f"{tag} is already active")
|
||||
return
|
||||
commit = tag_commit(tag)
|
||||
failed = host.state / "last-failed/release.json"
|
||||
if (
|
||||
tag != previous
|
||||
and failed.is_file()
|
||||
and json.loads(failed.read_text())["tag"] == tag
|
||||
and not retry
|
||||
):
|
||||
print(f"{tag} previously rolled back; waiting for a new release or --retry", flush=True)
|
||||
return
|
||||
images = resolved_images(tag, commit)
|
||||
if check:
|
||||
_, data, sha = release_bundle(release, tag)
|
||||
minimum_shell(data, tag)
|
||||
if tag == previous:
|
||||
for name, ref in images.items():
|
||||
container = inspect(name)
|
||||
if (
|
||||
container["Config"]["Image"] != ref
|
||||
or container["State"]["Health"]["Status"] != "healthy"
|
||||
):
|
||||
raise RuntimeError("Active service differs from the release: " + name)
|
||||
check_routes()
|
||||
check_hotfix(tag, sha)
|
||||
print(f"Verified {tag} at {commit}; active release {previous}", flush=True)
|
||||
return
|
||||
deploy(host, release, previous, tag, images, commit)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
group = parser.add_mutually_exclusive_group()
|
||||
group.add_argument(
|
||||
"--check", action="store_true", help="Verify the release without switching production"
|
||||
)
|
||||
group.add_argument(
|
||||
"--retry", action="store_true", help="Retry the latest release after a verified rollback"
|
||||
)
|
||||
args = parser.parse_args()
|
||||
os.umask(0o077)
|
||||
host = Host()
|
||||
host.state.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
with (host.state / "lock").open("a") as lock:
|
||||
try:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError:
|
||||
print("Another production release check is running")
|
||||
return
|
||||
reconcile(host, check=args.check, retry=args.retry)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except (
|
||||
RuntimeError,
|
||||
ValueError,
|
||||
KeyError,
|
||||
OSError,
|
||||
tarfile.TarError,
|
||||
subprocess.SubprocessError,
|
||||
) as exc:
|
||||
sys.exit(f"Production release check failed: {exc}")
|
||||
@@ -0,0 +1,155 @@
|
||||
"""Read the public Planet release and immutable linux/amd64 images from Gitea."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
SERVER = "https://gitea.rclaw.top"
|
||||
REPO = "linkong/planet"
|
||||
REGISTRY = urllib.parse.urlsplit(SERVER).netloc
|
||||
API = f"{SERVER}/api/v1/repos/{REPO}"
|
||||
SERVICES = {
|
||||
"aiprovider": "AI_PROVIDER_IMAGE_NAME",
|
||||
"backend": "BACKEND_IMAGE_NAME",
|
||||
"admin": "ADMIN_IMAGE_NAME",
|
||||
}
|
||||
MANIFEST_TYPES = ", ".join(
|
||||
(
|
||||
"application/vnd.oci.image.index.v1+json",
|
||||
"application/vnd.oci.image.manifest.v1+json",
|
||||
"application/vnd.docker.distribution.manifest.list.v2+json",
|
||||
"application/vnd.docker.distribution.manifest.v2+json",
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, *args):
|
||||
return None
|
||||
|
||||
|
||||
def read_url(url, *, headers=None, limit=2 * 1024 * 1024):
|
||||
"""Bound a release download and keep authorization on its original HTTPS endpoint."""
|
||||
request = urllib.request.Request(url, headers=headers or {})
|
||||
for attempt in range(3):
|
||||
try:
|
||||
with urllib.request.build_opener(NoRedirect()).open(request, timeout=30) as response:
|
||||
data = response.read(limit + 1)
|
||||
if len(data) > limit:
|
||||
raise ValueError(f"Release response exceeds {limit} bytes")
|
||||
return data
|
||||
except urllib.error.HTTPError as exc:
|
||||
if exc.code not in (502, 503, 504) or attempt == 2:
|
||||
raise
|
||||
except (urllib.error.URLError, TimeoutError, ConnectionError) as exc:
|
||||
if attempt == 2:
|
||||
raise RuntimeError(f"Could not read release metadata from {url}") from exc
|
||||
time.sleep(1 + attempt)
|
||||
|
||||
|
||||
def version(tag):
|
||||
if not isinstance(tag, str) or not re.fullmatch(
|
||||
r"v(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)", tag
|
||||
):
|
||||
raise ValueError(f"Expected a stable version tag, got {tag!r}")
|
||||
return tuple(int(part) for part in tag[1:].split("."))
|
||||
|
||||
|
||||
def tag_commit(tag):
|
||||
version(tag)
|
||||
commit = json.loads(read_url(f"{API}/tags/{tag}"))["commit"]["sha"]
|
||||
if not re.fullmatch("[0-9a-f]{40,64}", commit):
|
||||
raise ValueError("Invalid Gitea commit ID")
|
||||
return commit
|
||||
|
||||
|
||||
def release_bundle(release, tag):
|
||||
"""Read the published hotfix and check it against the release checksum file."""
|
||||
version(tag)
|
||||
if release.get("tag_name") != tag or release.get("draft") or release.get("prerelease"):
|
||||
raise ValueError("Expected the selected stable, published release")
|
||||
assets = release.get("assets") or []
|
||||
sizes = {entry["name"]: entry["size"] for entry in assets}
|
||||
if len(assets) != len(sizes):
|
||||
raise ValueError("Duplicate release attachment names")
|
||||
name = f"planet-earth-bundle-{tag[1:]}.tar.gz"
|
||||
base = f"{SERVER}/{REPO}/releases/download/{tag}"
|
||||
if not 0 < sizes.get(name, 0) <= 32 * 1024 * 1024 or "SHA256SUMS.txt" not in sizes:
|
||||
raise ValueError("Release has no complete Earth bundle and checksum list")
|
||||
sums = read_url(f"{base}/SHA256SUMS.txt", limit=128 * 1024).decode().splitlines()
|
||||
hashes = [line.split(" ", 1)[0] for line in sums if line.endswith(" " + name)]
|
||||
data = read_url(f"{base}/{name}", limit=sizes[name])
|
||||
sha = hashlib.sha256(data).hexdigest()
|
||||
if hashes != [sha] or len(data) != sizes[name]:
|
||||
raise ValueError("Earth bundle failed release SHA-256 or size verification")
|
||||
return name, data, sha
|
||||
|
||||
|
||||
def image_name(service):
|
||||
if service not in SERVICES:
|
||||
raise ValueError(f"Unexpected production service: {service}")
|
||||
return f"{REGISTRY}/{REPO}/{service}"
|
||||
|
||||
|
||||
def digest(data):
|
||||
return "sha256:" + hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def descriptor_digest(desc):
|
||||
value = desc["digest"]
|
||||
if not re.fullmatch(r"sha256:[a-f0-9]{64}", value):
|
||||
raise ValueError("Registry returned an invalid digest")
|
||||
return value
|
||||
|
||||
|
||||
def resolve_image(service, tag, commit):
|
||||
"""Return the immutable platform image; only an absent tag returns None."""
|
||||
version(tag)
|
||||
name = image_name(service)
|
||||
repository = f"{REPO}/{service}"
|
||||
query = urllib.parse.urlencode(
|
||||
{"service": "container_registry", "scope": f"repository:{repository}:pull"}
|
||||
)
|
||||
token = json.loads(read_url(f"{SERVER}/v2/token?{query}"))["token"]
|
||||
headers = {"Authorization": "Bearer " + token, "Accept": MANIFEST_TYPES}
|
||||
base = f"{SERVER}/v2/{repository}"
|
||||
try:
|
||||
raw = read_url(f"{base}/manifests/{tag}", headers=headers)
|
||||
except urllib.error.HTTPError as exc:
|
||||
if exc.code == 404:
|
||||
return None
|
||||
raise
|
||||
manifest = json.loads(raw)
|
||||
if "manifests" in manifest:
|
||||
candidates = [
|
||||
entry
|
||||
for entry in manifest["manifests"]
|
||||
if entry.get("platform", {}).get("os") == "linux"
|
||||
and entry["platform"].get("architecture") == "amd64"
|
||||
]
|
||||
if len(candidates) != 1:
|
||||
raise ValueError(f"{name}:{tag} must contain one linux/amd64 image")
|
||||
selected = descriptor_digest(candidates[0])
|
||||
raw = read_url(f"{base}/manifests/{selected}", headers=headers)
|
||||
if digest(raw) != selected:
|
||||
raise ValueError("Registry platform manifest failed digest verification")
|
||||
manifest = json.loads(raw)
|
||||
config_digest = descriptor_digest(manifest["config"])
|
||||
config_raw = read_url(f"{base}/blobs/{config_digest}", headers=headers)
|
||||
if digest(config_raw) != config_digest:
|
||||
raise ValueError("Registry image configuration failed digest verification")
|
||||
config = json.loads(config_raw)
|
||||
labels = config.get("config", {}).get("Labels") or {}
|
||||
if (config.get("os"), config.get("architecture")) != ("linux", "amd64"):
|
||||
raise ValueError(f"{name}:{tag} is not a linux/amd64 image")
|
||||
if labels.get("org.opencontainers.image.revision") != commit:
|
||||
raise ValueError(f"{name}:{tag} belongs to a different commit")
|
||||
if service == "admin" and labels.get("planet.frontend.target") != "admin":
|
||||
raise ValueError("The production Admin image must be built with the admin-only target")
|
||||
return f"{name}:{tag}@{digest(raw)}"
|
||||
@@ -0,0 +1,223 @@
|
||||
"""Prepare a tagged Planet release on the publishing workstation."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
|
||||
if __package__:
|
||||
from .production_registry import (
|
||||
REPO,
|
||||
SERVER,
|
||||
SERVICES,
|
||||
image_name,
|
||||
resolve_image,
|
||||
tag_commit,
|
||||
version,
|
||||
)
|
||||
else:
|
||||
from production_registry import (
|
||||
REPO,
|
||||
SERVER,
|
||||
SERVICES,
|
||||
image_name,
|
||||
resolve_image,
|
||||
tag_commit,
|
||||
version,
|
||||
)
|
||||
|
||||
|
||||
def git(*args, cwd=None):
|
||||
return subprocess.check_output(["git", *args], cwd=cwd, text=True).strip()
|
||||
|
||||
|
||||
def verified_tag(tag):
|
||||
commit = tag_commit(tag)
|
||||
if git("rev-parse", "--verify", f"{commit}^{{commit}}") != commit:
|
||||
raise RuntimeError("The remote release commit is not available locally")
|
||||
if git("show", f"{commit}:VERSION") != tag[1:]:
|
||||
raise ValueError("Tagged VERSION differs from the published tag")
|
||||
return commit
|
||||
|
||||
|
||||
def docker_config():
|
||||
config = os.environ.get("PLANET_RELEASE_DOCKER_CONFIG")
|
||||
if config:
|
||||
return Path(config).expanduser()
|
||||
return (
|
||||
Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "planet" / "registry"
|
||||
)
|
||||
|
||||
|
||||
def ensure_images(source, tag, commit):
|
||||
for service in SERVICES:
|
||||
pin = resolve_image(service, tag, commit)
|
||||
if not pin:
|
||||
context = source / "frontend" if service == "admin" else source
|
||||
dockerfile = (
|
||||
context / "Dockerfile" if service == "admin" else source / service / "Dockerfile"
|
||||
)
|
||||
cmd = [
|
||||
"docker",
|
||||
"--config",
|
||||
str(docker_config()),
|
||||
"buildx",
|
||||
"build",
|
||||
"--platform",
|
||||
"linux/amd64",
|
||||
"--provenance=false",
|
||||
"--file",
|
||||
str(dockerfile),
|
||||
"--label",
|
||||
f"org.opencontainers.image.revision={commit}",
|
||||
"--label",
|
||||
f"org.opencontainers.image.version={tag[1:]}",
|
||||
"--label",
|
||||
f"org.opencontainers.image.source={SERVER}/{REPO}",
|
||||
]
|
||||
if service == "admin":
|
||||
cmd += [
|
||||
"--build-arg",
|
||||
"PLANET_FRONTEND_TARGET=admin",
|
||||
"--label",
|
||||
"planet.frontend.target=admin",
|
||||
]
|
||||
uv_config = Path.home() / ".config/uv/uv.toml"
|
||||
if service != "admin" and uv_config.is_file():
|
||||
cmd += ["--secret", f"id=planet_uv_config,src={uv_config}"]
|
||||
cmd += [
|
||||
"--output",
|
||||
f"type=image,name={image_name(service)}:{tag},push=true,compression=gzip,force-compression=true",
|
||||
str(context),
|
||||
]
|
||||
subprocess.run(cmd, check=True)
|
||||
pin = resolve_image(service, tag, commit)
|
||||
if not pin:
|
||||
raise RuntimeError(f"Pushed image is not visible: {service}:{tag}")
|
||||
print(f"Verified {pin}", flush=True)
|
||||
|
||||
|
||||
def select_packages(directory, tag, suffixes):
|
||||
number = re.compile(rf"(?<![\d.]){re.escape(tag[1:])}(?!\d|\.\d)")
|
||||
paths = (
|
||||
[
|
||||
p
|
||||
for p in directory.iterdir()
|
||||
if p.is_file() and number.search(p.name) and p.name.lower().endswith(suffixes)
|
||||
]
|
||||
if directory.is_dir()
|
||||
else []
|
||||
)
|
||||
names = [p.name.lower() for p in paths]
|
||||
if not (
|
||||
any(n.endswith(".exe") or n.endswith("-win.zip") for n in names)
|
||||
and any(n.endswith(".dmg") or "mac" in n and n.endswith(".zip") for n in names)
|
||||
and any(n.endswith((".appimage", ".deb")) for n in names)
|
||||
and f"planet-earth-bundle-{tag[1:]}.tar.gz" in names
|
||||
):
|
||||
return []
|
||||
bundle = directory / f"planet-earth-bundle-{tag[1:]}.tar.gz"
|
||||
with tarfile.open(bundle, "r:gz") as archive:
|
||||
member = archive.getmember("bundle-meta.json")
|
||||
if not member.isfile() or member.size > 8192:
|
||||
raise ValueError("Invalid hotfix package metadata")
|
||||
if json.load(archive.extractfile(member)).get("version") != tag[1:]:
|
||||
raise ValueError("Hotfix contents do not match the release tag")
|
||||
return paths
|
||||
|
||||
|
||||
@contextmanager
|
||||
def local_release_lock(path):
|
||||
with path.open("a+b") as lock:
|
||||
if os.name == "nt":
|
||||
import msvcrt
|
||||
|
||||
lock.seek(0)
|
||||
msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1)
|
||||
else:
|
||||
import fcntl
|
||||
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
yield
|
||||
|
||||
|
||||
def package_hash(path):
|
||||
with path.open("rb") as stream:
|
||||
return hashlib.file_digest(stream, "sha256").hexdigest()
|
||||
|
||||
|
||||
def cached_packages(source, supplied, cache, tag, suffixes):
|
||||
if not cache.exists():
|
||||
if supplied is None:
|
||||
subprocess.run(["./planet.sh", "bundle", "--all"], cwd=source, check=True)
|
||||
supplied = source / "client/release"
|
||||
packages = select_packages(supplied, tag, suffixes)
|
||||
if not packages:
|
||||
raise RuntimeError(f"Missing tagged desktop clients or Earth hotfix in {supplied}")
|
||||
with tempfile.TemporaryDirectory(dir=cache.parent) as tmp:
|
||||
stage = Path(tmp) / "assets"
|
||||
stage.mkdir()
|
||||
for package in packages:
|
||||
shutil.copy2(package, stage / package.name)
|
||||
sums = {p.name: package_hash(p) for p in stage.iterdir()}
|
||||
(stage / "checksums.json").write_text(json.dumps(sums))
|
||||
os.rename(stage, cache)
|
||||
packages = select_packages(cache, tag, suffixes)
|
||||
expected = json.loads((cache / "checksums.json").read_text())
|
||||
if not packages or {p.name: package_hash(p) for p in packages} != expected:
|
||||
raise ValueError("The saved release artifacts differ from the original build")
|
||||
return packages
|
||||
|
||||
|
||||
@contextmanager
|
||||
def prepare(tag, assets_dir, suffixes, *, already_published=False):
|
||||
version(tag)
|
||||
commit = verified_tag(tag)
|
||||
state = Path(os.environ.get("XDG_STATE_HOME") or Path.home() / ".local/state")
|
||||
state = state / "planet-releases" / tag / "publisher"
|
||||
state.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
cache = state / commit
|
||||
with (
|
||||
local_release_lock(state / "lock"),
|
||||
tempfile.TemporaryDirectory(prefix="planet-publish-") as tmp,
|
||||
):
|
||||
worktree = Path(tmp) / "src"
|
||||
subprocess.run(
|
||||
["git", "worktree", "add", "--quiet", "--detach", str(worktree), commit], check=True
|
||||
)
|
||||
try:
|
||||
ensure_images(worktree, tag, commit)
|
||||
stage = Path(tmp) / "assets"
|
||||
stage.mkdir()
|
||||
if not already_published:
|
||||
for package in cached_packages(worktree, assets_dir, cache, tag, suffixes):
|
||||
try:
|
||||
os.link(package, stage / package.name)
|
||||
except OSError:
|
||||
shutil.copy2(package, stage / package.name)
|
||||
yield stage, worktree / "docs/CHANGELOG.md"
|
||||
# The verified public release now holds these bytes. Keep the cache on upload failure.
|
||||
if cache.exists():
|
||||
shutil.rmtree(cache)
|
||||
finally:
|
||||
# This detached checkout and its generated build files are private to this invocation.
|
||||
subprocess.run(["git", "worktree", "remove", "--force", str(worktree)], check=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) != 2:
|
||||
sys.exit("Usage: production_release.py vX.Y.Z")
|
||||
release_tag = sys.argv[1]
|
||||
revision = verified_tag(release_tag)
|
||||
if git("rev-parse", "HEAD") != revision or git("status", "--porcelain", "--untracked-files=no"):
|
||||
sys.exit("Image-only CI jobs require a clean checkout at the tagged commit")
|
||||
ensure_images(Path.cwd(), release_tag, revision)
|
||||
+71
-21
@@ -11,6 +11,8 @@ import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
@@ -24,6 +26,10 @@ class RejectRedirects(urllib.request.HTTPRedirectHandler):
|
||||
return None
|
||||
|
||||
|
||||
class RetryableUploadError(RuntimeError):
|
||||
"""The server may already have received the attachment."""
|
||||
|
||||
|
||||
API_OPENER = urllib.request.build_opener(RejectRedirects())
|
||||
|
||||
|
||||
@@ -226,7 +232,8 @@ def upload_asset_with_curl(
|
||||
capture_output=True,
|
||||
)
|
||||
if proc.returncode != 0:
|
||||
raise RuntimeError(
|
||||
error = RetryableUploadError if proc.returncode in (6, 7, 18, 28, 52, 55, 56, 92) else RuntimeError
|
||||
raise error(
|
||||
f"curl upload failed for {file_path.name} (exit={proc.returncode}): {proc.stderr.strip()}"
|
||||
)
|
||||
|
||||
@@ -243,7 +250,8 @@ def upload_asset_with_curl(
|
||||
"Check Gitea app.ini [attachment] MAX_SIZE and Nginx/Ingress client_max_body_size (>= 300M)."
|
||||
)
|
||||
if status_code != 201:
|
||||
raise RuntimeError(f"Upload failed for {file_path.name} (HTTP {status_code})")
|
||||
error = RetryableUploadError if status_code in (408, 409, 429, 502, 503, 504) else RuntimeError
|
||||
raise error(f"Upload failed for {file_path.name} (HTTP {status_code})")
|
||||
|
||||
|
||||
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
|
||||
@@ -251,7 +259,7 @@ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
|
||||
parser.add_argument("--tag", required=True, help="Git release tag, e.g. v0.77.0")
|
||||
parser.add_argument(
|
||||
"--assets-dir",
|
||||
default="client/release",
|
||||
default=None,
|
||||
help="Directory containing packaged client binaries (default: client/release)",
|
||||
)
|
||||
parser.add_argument(
|
||||
@@ -387,17 +395,30 @@ def publish_release(
|
||||
if path.name in existing:
|
||||
verify_existing_asset(existing[path.name], path, sha, server, authorization)
|
||||
print(f"verified existing {path.name}", flush=True)
|
||||
for path, _sha in assets:
|
||||
for path, sha in assets:
|
||||
if path.name in existing:
|
||||
continue
|
||||
name = urllib.parse.quote(path.name, safe="")
|
||||
print(f"uploading {path.name}...", flush=True)
|
||||
upload_asset_with_curl(f"{release_url}/assets?name={name}", authorization, path)
|
||||
for attempt in range(3):
|
||||
try:
|
||||
upload_asset_with_curl(f"{release_url}/assets?name={name}", authorization, path)
|
||||
break
|
||||
except RetryableUploadError:
|
||||
received = list_assets(release_url, authorization).get(path.name)
|
||||
if received:
|
||||
verify_existing_asset(received, path, sha, server, authorization)
|
||||
break
|
||||
if attempt == 2:
|
||||
raise
|
||||
time.sleep(2 ** attempt)
|
||||
|
||||
uploaded = list_assets(release_url, authorization)
|
||||
for path, _sha in assets:
|
||||
for path, sha in assets:
|
||||
if uploaded.get(path.name, {}).get("size") != path.stat().st_size:
|
||||
raise RuntimeError(f"Missing or incomplete attachment: {path.name}")
|
||||
if path.name not in existing or uploaded[path.name].get("id") != existing[path.name].get("id"):
|
||||
verify_existing_asset(uploaded[path.name], path, sha, server, authorization)
|
||||
|
||||
status, published = api_request(
|
||||
"PATCH", release_url, authorization, {"name": tag, "body": notes, "draft": False}
|
||||
@@ -416,6 +437,7 @@ def publish_hotfix_bundle(
|
||||
notes: str,
|
||||
release_html_url: str,
|
||||
assets: list[tuple[Path, str]],
|
||||
min_shell_version: str | None = None,
|
||||
) -> None:
|
||||
hotfix_tar = next(
|
||||
(
|
||||
@@ -448,15 +470,15 @@ def publish_hotfix_bundle(
|
||||
"@-",
|
||||
"-F",
|
||||
f"file=@{hotfix_tar}",
|
||||
"-F",
|
||||
"--form-string",
|
||||
f"version={version}",
|
||||
"-F",
|
||||
f"min_shell_version={version}",
|
||||
"-F",
|
||||
"--form-string",
|
||||
f"min_shell_version={min_shell_version or version}",
|
||||
"--form-string",
|
||||
f"shell_version={version}",
|
||||
"-F",
|
||||
"--form-string",
|
||||
f"shell_download_url={release_html_url}",
|
||||
"-F",
|
||||
"--form-string",
|
||||
f"release_notes={notes[:2000]}",
|
||||
endpoint,
|
||||
],
|
||||
@@ -495,14 +517,14 @@ def main(argv: list[str] | None = None) -> int:
|
||||
print("error: unable to resolve Gitea server URL or owner/repo slug", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
notes = extract_release_notes(Path(args.changelog), args.tag)
|
||||
assets_dir = Path(args.assets_dir)
|
||||
assets = collect_release_assets(assets_dir)
|
||||
if not assets:
|
||||
print(f"error: no distributable assets found in {assets_dir}", file=sys.stderr)
|
||||
return 1
|
||||
assets_dir = Path(args.assets_dir or "client/release")
|
||||
|
||||
if args.dry_run:
|
||||
notes = extract_release_notes(Path(args.changelog), args.tag)
|
||||
assets = collect_release_assets(assets_dir)
|
||||
if not assets:
|
||||
print(f"error: no distributable assets found in {assets_dir}", file=sys.stderr)
|
||||
return 1
|
||||
print(f"server: {server}")
|
||||
print(f"repo: {repo}")
|
||||
print(f"tag: {args.tag}")
|
||||
@@ -514,13 +536,41 @@ def main(argv: list[str] | None = None) -> int:
|
||||
return 0
|
||||
|
||||
try:
|
||||
if args.use_git_credential:
|
||||
if __package__:
|
||||
from .production_registry import API, REPO, SERVER, release_bundle
|
||||
from .production_release import prepare
|
||||
else:
|
||||
from production_registry import API, REPO, SERVER, release_bundle
|
||||
from production_release import prepare
|
||||
|
||||
production = (server, repo) == (SERVER, REPO) and re.fullmatch(r"v\d+\.\d+\.\d+", args.tag)
|
||||
token = os.environ.get("GITEA_TOKEN")
|
||||
if not token and (not production or os.environ.get("GITHUB_SERVER_URL", "").rstrip("/") == server):
|
||||
token = os.environ.get("GITHUB_TOKEN")
|
||||
if args.use_git_credential or (production and not token):
|
||||
authorization = git_credential_authorization(origin, server, repo)
|
||||
else:
|
||||
token = os.environ.get("GITEA_TOKEN") or os.environ.get("GITHUB_TOKEN")
|
||||
if not token:
|
||||
raise RuntimeError("Set GITEA_TOKEN or use the saved HTTPS Git credential")
|
||||
authorization = f"token {token}"
|
||||
if production:
|
||||
status, public = api_request("GET", f"{API}/releases/tags/{args.tag}", authorization)
|
||||
if status not in (200, 404):
|
||||
raise RuntimeError(f"Cannot inspect the release (HTTP {status})")
|
||||
published = status == 200 and isinstance(public, dict) and public.get("draft") is False
|
||||
supplied = assets_dir if args.assets_dir else None
|
||||
with prepare(args.tag, supplied, ASSET_SUFFIXES, already_published=published) as (stage, changelog):
|
||||
if published:
|
||||
release_bundle(public, args.tag)
|
||||
print(f"Verified published release {args.tag}; production follows stable releases")
|
||||
else:
|
||||
notes = extract_release_notes(changelog, args.tag)
|
||||
publish_release(server, repo, args.tag, notes, collect_release_assets(stage), authorization)
|
||||
return 0
|
||||
notes = extract_release_notes(Path(args.changelog), args.tag)
|
||||
assets = collect_release_assets(assets_dir)
|
||||
if not assets:
|
||||
raise RuntimeError(f"No distributable assets found in {assets_dir}")
|
||||
release_html_url = publish_release(server, repo, args.tag, notes, assets, authorization)
|
||||
hotfix_url = str(args.hotfix_publish_url or "").strip()
|
||||
hotfix_token = str(args.hotfix_publish_token or "").strip()
|
||||
@@ -533,7 +583,7 @@ def main(argv: list[str] | None = None) -> int:
|
||||
release_html_url=release_html_url,
|
||||
assets=assets,
|
||||
)
|
||||
except (RuntimeError, urllib.error.URLError, TimeoutError) as exc:
|
||||
except (RuntimeError, ValueError, KeyError, OSError, subprocess.SubprocessError, tarfile.TarError) as exc:
|
||||
print(f"error: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
Reference in new issue
Block a user