Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
352b34e7c6 | ||
|
|
1e9508f2f1 | ||
|
|
e53c3af355 | ||
|
|
5fc698d738 | ||
|
|
e6aa8c539b |
No files matched your search
@@ -176,7 +176,35 @@ Push to remote:
|
||||
```
|
||||
- If remote publication was not requested or remote access is restricted, report the commit and tag as complete and output the push commands for manual execution.
|
||||
|
||||
### Step 9 — Completion summary
|
||||
### Step 9 — Publish and verify the Gitea Release
|
||||
|
||||
When remote publication is requested, verify the remote tag points to the
|
||||
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.
|
||||
|
||||
```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
|
||||
python3 scripts/release_publish.py --tag vx.x.x --assets-dir client/release --use-git-credential
|
||||
```
|
||||
|
||||
Use `GITEA_TOKEN` instead of `--use-git-credential` when publishing with a
|
||||
configured token. The publish script uploads to a draft and checks the
|
||||
attachment names and sizes before publishing. Verify the published Release URL
|
||||
and expected attachments through Gitea before reporting success. If Gitea is
|
||||
unreachable, report the tag and package state and why publication is incomplete.
|
||||
|
||||
### Step 10 — Completion summary
|
||||
|
||||
```
|
||||
✓ Version bumped: 0.76.18 → 0.76.19
|
||||
@@ -187,6 +215,7 @@ Push to remote:
|
||||
✓ commit: release: bump version to 0.76.19
|
||||
✓ tag: v0.76.19
|
||||
✓ Pushed to origin/dev (or reported pending manual push)
|
||||
✓ Gitea Release and attachments verified (when publication was requested)
|
||||
```
|
||||
|
||||
## Notes
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
!scripts/
|
||||
!scripts/build_earth_boundary_china_pov_geojson.py
|
||||
!scripts/build_earth_boundary_pmtiles.py
|
||||
!scripts/db_migrate.py
|
||||
!scripts/earth_boundary_policy.py
|
||||
!resources/
|
||||
!resources/earth/
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -6,8 +6,10 @@
|
||||
# 敏感文件
|
||||
# ----------------------
|
||||
.env
|
||||
.env.deploy
|
||||
.env.local
|
||||
.env.*.local
|
||||
backups/
|
||||
config/earth-boundary-sources.local.json
|
||||
*.pem
|
||||
*.key
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
# Shared service settings
|
||||
SERVICE_NAME=planet-ai-provider
|
||||
SERVICE_VERSION=0.1.0
|
||||
APP_ENV=development
|
||||
AI_PROVIDER_SERVICE_TOKEN=change_me
|
||||
AI_TIMEOUT_SECONDS=60
|
||||
AI_HTTP_RETRY_ATTEMPTS=2
|
||||
@@ -28,18 +29,18 @@ AI_MODEL=MiniMax-M2.7
|
||||
|
||||
# MiniMax CN Anthropic-compatible example
|
||||
AI_BASE_URL=https://api.minimaxi.com/anthropic
|
||||
AI_API_KEY=sk-cp-change-me
|
||||
AI_API_KEY=replace-with-provider-key
|
||||
AI_MAX_TOKENS=1200
|
||||
AI_ANTHROPIC_VERSION=2023-06-01
|
||||
|
||||
# Optional provider-specific keys used by Settings fallback before AI_API_KEY
|
||||
# MINIMAX_API_KEY=sk-cp-change-me
|
||||
# OPENAI_API_KEY=sk-change-me
|
||||
# ANTHROPIC_API_KEY=sk-ant-change-me
|
||||
# DEEPSEEK_API_KEY=sk-change-me
|
||||
# DASHSCOPE_API_KEY=sk-change-me
|
||||
# MOONSHOT_API_KEY=sk-change-me
|
||||
# OPENROUTER_API_KEY=sk-or-change-me
|
||||
# MINIMAX_API_KEY=replace-with-minimax-key
|
||||
# OPENAI_API_KEY=replace-with-openai-key
|
||||
# ANTHROPIC_API_KEY=replace-with-anthropic-key
|
||||
# DEEPSEEK_API_KEY=replace-with-deepseek-key
|
||||
# DASHSCOPE_API_KEY=replace-with-dashscope-key
|
||||
# MOONSHOT_API_KEY=replace-with-moonshot-key
|
||||
# OPENROUTER_API_KEY=replace-with-openrouter-key
|
||||
|
||||
# OpenAI-compatible example (vLLM / LM Studio / One API / local gateway)
|
||||
# AI_PROVIDER=openai
|
||||
|
||||
@@ -7,6 +7,7 @@ from pydantic_settings import BaseSettings
|
||||
class Settings(BaseSettings):
|
||||
SERVICE_NAME: str = "planet-ai-provider"
|
||||
SERVICE_VERSION: str = "0.1.0"
|
||||
APP_ENV: str = "development"
|
||||
|
||||
AI_PROVIDER: str = "disabled"
|
||||
AI_PROVIDER_API: str = "auto"
|
||||
@@ -20,9 +21,14 @@ class Settings(BaseSettings):
|
||||
|
||||
AI_PROVIDER_SERVICE_TOKEN: str = ""
|
||||
|
||||
@property
|
||||
def is_production(self) -> bool:
|
||||
return str(self.APP_ENV or "").strip().lower() == "production"
|
||||
|
||||
class Config:
|
||||
env_file = Path(__file__).parent / ".env"
|
||||
case_sensitive = True
|
||||
extra = "ignore"
|
||||
|
||||
|
||||
@lru_cache()
|
||||
|
||||
+29
-2
@@ -1,3 +1,5 @@
|
||||
from contextlib import asynccontextmanager
|
||||
import hmac
|
||||
from uuid import uuid4
|
||||
|
||||
from fastapi import Depends, FastAPI, Header, HTTPException, Request, Response, status
|
||||
@@ -10,10 +12,30 @@ from aiprovider.schemas import (
|
||||
SituationalAnalysisResponse,
|
||||
)
|
||||
|
||||
WEAK_TOKEN_PLACEHOLDERS = frozenset({"", "change-me", "change_me", "replace-with-internal-token"})
|
||||
|
||||
|
||||
def validate_provider_security() -> None:
|
||||
if not settings.is_production:
|
||||
return
|
||||
token = str(settings.AI_PROVIDER_SERVICE_TOKEN or "").strip()
|
||||
if token in WEAK_TOKEN_PLACEHOLDERS:
|
||||
raise RuntimeError(
|
||||
"AI_PROVIDER_SERVICE_TOKEN must be configured (not empty or placeholder) when APP_ENV=production"
|
||||
)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI):
|
||||
validate_provider_security()
|
||||
yield
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title=settings.SERVICE_NAME,
|
||||
version=settings.SERVICE_VERSION,
|
||||
description="AI provider adapter service for Planet",
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
|
||||
@@ -27,10 +49,15 @@ async def request_id_middleware(request: Request, call_next):
|
||||
|
||||
|
||||
def verify_service_token(x_provider_token: str | None = Header(default=None)) -> None:
|
||||
expected = settings.AI_PROVIDER_SERVICE_TOKEN
|
||||
expected = str(settings.AI_PROVIDER_SERVICE_TOKEN or "")
|
||||
if not expected:
|
||||
if settings.is_production:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Provider service token not configured",
|
||||
)
|
||||
return
|
||||
if x_provider_token != expected:
|
||||
if not x_provider_token or not hmac.compare_digest(x_provider_token, expected):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid provider service token",
|
||||
|
||||
+21
-3
@@ -1,10 +1,24 @@
|
||||
PROJECT_NAME=Intelligent Planet Plan
|
||||
APP_VERSION=0.23.0
|
||||
APP_ENV=development
|
||||
PLANET_ROLE=all
|
||||
|
||||
SECRET_KEY=change_me_to_a_random_secret
|
||||
SECRET_KEY=change_me_to_a_random_32_plus_char_secret
|
||||
ALGORITHM=HS256
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES=0
|
||||
REFRESH_TOKEN_EXPIRE_DAYS=0
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES=60
|
||||
REFRESH_TOKEN_EXPIRE_DAYS=7
|
||||
CORS_ORIGINS=["http://localhost:3000","http://127.0.0.1:3000","http://localhost:8000","http://127.0.0.1:8000","planet://earth"]
|
||||
|
||||
# Optional bootstrap super_admin on fresh/production DB
|
||||
INITIAL_ADMIN_USERNAME=
|
||||
INITIAL_ADMIN_EMAIL=
|
||||
INITIAL_ADMIN_PASSWORD=
|
||||
|
||||
# Optional encryption key for persisted SMTP & integration API keys
|
||||
SETTINGS_ENCRYPTION_KEY=
|
||||
|
||||
LOGIN_RATE_LIMIT_MAX_ATTEMPTS=10
|
||||
LOGIN_RATE_LIMIT_WINDOW_SECONDS=300
|
||||
|
||||
POSTGRES_SERVER=localhost
|
||||
POSTGRES_USER=postgres
|
||||
@@ -15,8 +29,12 @@ DATABASE_URL=postgresql+asyncpg://postgres:postgres@localhost:5432/planet_db
|
||||
REDIS_SERVER=localhost
|
||||
REDIS_PORT=6379
|
||||
REDIS_DB=0
|
||||
REDIS_PASSWORD=
|
||||
REDIS_URL=redis://localhost:6379/0
|
||||
|
||||
COLLECTOR_MAX_CONCURRENCY=2
|
||||
COLLECTOR_HEAVY_CONCURRENCY=1
|
||||
|
||||
AI_PROVIDER_SERVICE_URL=http://localhost:8010
|
||||
AI_PROVIDER_SERVICE_TOKEN=change_me
|
||||
AI_PROVIDER_TIMEOUT_SECONDS=60
|
||||
|
||||
@@ -31,6 +31,7 @@ COPY backend /app/backend
|
||||
COPY config/earth-boundary-pov-policy.china-v1.json /app/config/earth-boundary-pov-policy.china-v1.json
|
||||
COPY scripts/build_earth_boundary_china_pov_geojson.py /app/scripts/build_earth_boundary_china_pov_geojson.py
|
||||
COPY scripts/build_earth_boundary_pmtiles.py /app/scripts/build_earth_boundary_pmtiles.py
|
||||
COPY scripts/db_migrate.py /app/scripts/db_migrate.py
|
||||
COPY scripts/earth_boundary_policy.py /app/scripts/earth_boundary_policy.py
|
||||
COPY resources/earth/boundary-pov-geometry.china-v1.json /app/resources/earth/boundary-pov-geometry.china-v1.json
|
||||
COPY frontend/public/earth/assets/cards/manifest.json /app/frontend/public/earth/assets/cards/manifest.json
|
||||
|
||||
@@ -8,6 +8,7 @@ from app.api.v1 import (
|
||||
datasources,
|
||||
docs,
|
||||
earth,
|
||||
client_updates,
|
||||
tasks,
|
||||
dashboard,
|
||||
alerts,
|
||||
@@ -40,6 +41,7 @@ api_router.include_router(datasources.router, prefix="/datasources", tags=["data
|
||||
api_router.include_router(collected_data.router, prefix="/collected", tags=["collected-data"])
|
||||
api_router.include_router(docs.router, prefix="/docs", tags=["docs"])
|
||||
api_router.include_router(earth.router, prefix="/earth", tags=["earth"])
|
||||
api_router.include_router(client_updates.router, prefix="/client", tags=["client-updates"])
|
||||
api_router.include_router(tasks.router, prefix="/tasks", tags=["tasks"])
|
||||
api_router.include_router(dashboard.router, prefix="/dashboard", tags=["dashboard"])
|
||||
api_router.include_router(alerts.router, prefix="/alerts", tags=["alerts"])
|
||||
|
||||
+157
-21
@@ -1,5 +1,12 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi.security import OAuth2PasswordRequestForm
|
||||
import asyncio
|
||||
from hashlib import sha256
|
||||
import ipaddress
|
||||
import time
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Body, Depends, HTTPException, Request, status
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer, OAuth2PasswordRequestForm
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import text
|
||||
|
||||
@@ -7,10 +14,13 @@ from app.core.config import settings
|
||||
from app.core.enums import OtpPurpose, UserRole
|
||||
from app.core.logging import get_logger
|
||||
from app.core.security import (
|
||||
_AsyncRedisClient,
|
||||
create_access_token,
|
||||
create_refresh_token,
|
||||
get_current_user,
|
||||
get_current_user_refresh,
|
||||
get_password_hash,
|
||||
revoke_token,
|
||||
verify_password,
|
||||
)
|
||||
from app.db.session import get_db
|
||||
@@ -34,6 +44,123 @@ from app.services.email import (
|
||||
logger = get_logger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
optional_bearer = HTTPBearer(auto_error=False)
|
||||
_LOCAL_LOGIN_FAILURES: dict[str, tuple[int, float]] = {}
|
||||
_LOCAL_LOGIN_FAILURES_MAX = 10_000
|
||||
|
||||
|
||||
class LogoutRequest(BaseModel):
|
||||
refresh_token: Optional[str] = None
|
||||
|
||||
|
||||
_TRUSTED_PROXY_NETWORKS = (
|
||||
ipaddress.ip_network("127.0.0.0/8"),
|
||||
ipaddress.ip_network("10.0.0.0/8"),
|
||||
ipaddress.ip_network("172.16.0.0/12"),
|
||||
ipaddress.ip_network("192.168.0.0/16"),
|
||||
ipaddress.ip_network("169.254.0.0/16"),
|
||||
ipaddress.ip_network("100.64.0.0/10"),
|
||||
ipaddress.ip_network("::1/128"),
|
||||
ipaddress.ip_network("fc00::/7"),
|
||||
ipaddress.ip_network("fe80::/10"),
|
||||
)
|
||||
|
||||
|
||||
def _is_trusted_proxy_peer(host: str) -> bool:
|
||||
cleaned = host.strip()
|
||||
if not cleaned:
|
||||
return False
|
||||
if cleaned in {"testclient", "localhost"}:
|
||||
return True
|
||||
try:
|
||||
parsed = ipaddress.ip_address(cleaned)
|
||||
except ValueError:
|
||||
return False
|
||||
if isinstance(parsed, ipaddress.IPv6Address) and parsed.ipv4_mapped is not None:
|
||||
parsed = parsed.ipv4_mapped
|
||||
return any(parsed in network for network in _TRUSTED_PROXY_NETWORKS)
|
||||
|
||||
|
||||
def _client_ip(request: Request) -> str:
|
||||
peer_host = request.client.host if (request.client and request.client.host) else ""
|
||||
if _is_trusted_proxy_peer(peer_host):
|
||||
real_ip = (request.headers.get("X-Real-IP") or "").strip()
|
||||
if real_ip:
|
||||
return real_ip
|
||||
forwarded = request.headers.get("X-Forwarded-For") or ""
|
||||
if forwarded:
|
||||
parts = [part.strip() for part in forwarded.split(",") if part.strip()]
|
||||
if parts:
|
||||
return parts[-1]
|
||||
if peer_host:
|
||||
return peer_host
|
||||
return "unknown"
|
||||
|
||||
|
||||
def _login_rate_key(client_ip: str, username: str) -> str:
|
||||
digest = sha256(f"{client_ip}:{username.strip().lower()}".encode("utf-8")).hexdigest()
|
||||
return f"auth:login_fail:{digest}"
|
||||
|
||||
|
||||
def _prune_local_login_failures(now: float) -> None:
|
||||
expired = [key for key, (_cnt, expires_at) in _LOCAL_LOGIN_FAILURES.items() if expires_at <= now]
|
||||
for key in expired:
|
||||
_LOCAL_LOGIN_FAILURES.pop(key, None)
|
||||
while len(_LOCAL_LOGIN_FAILURES) > _LOCAL_LOGIN_FAILURES_MAX:
|
||||
_LOCAL_LOGIN_FAILURES.pop(next(iter(_LOCAL_LOGIN_FAILURES)), None)
|
||||
|
||||
|
||||
async def check_login_rate_limit(client_ip: str, username: str) -> int:
|
||||
max_attempts = int(settings.LOGIN_RATE_LIMIT_MAX_ATTEMPTS)
|
||||
window_seconds = max(1, int(settings.LOGIN_RATE_LIMIT_WINDOW_SECONDS))
|
||||
if max_attempts <= 0:
|
||||
return 0
|
||||
key = _login_rate_key(client_ip, username)
|
||||
try:
|
||||
client = _AsyncRedisClient.get_client()
|
||||
raw = await asyncio.wait_for(client.get(key), timeout=1.5)
|
||||
if raw is not None and int(raw) >= max_attempts:
|
||||
ttl = await asyncio.wait_for(client.ttl(key), timeout=1.5)
|
||||
return max(1, int(ttl) if isinstance(ttl, int) and ttl > 0 else window_seconds)
|
||||
return 0
|
||||
except Exception:
|
||||
now = time.monotonic()
|
||||
_prune_local_login_failures(now)
|
||||
entry = _LOCAL_LOGIN_FAILURES.get(key)
|
||||
if entry and entry[1] > now and entry[0] >= max_attempts:
|
||||
return max(1, int(entry[1] - now))
|
||||
return 0
|
||||
|
||||
|
||||
async def record_login_failure(client_ip: str, username: str) -> None:
|
||||
max_attempts = int(settings.LOGIN_RATE_LIMIT_MAX_ATTEMPTS)
|
||||
window_seconds = max(1, int(settings.LOGIN_RATE_LIMIT_WINDOW_SECONDS))
|
||||
if max_attempts <= 0:
|
||||
return
|
||||
key = _login_rate_key(client_ip, username)
|
||||
try:
|
||||
client = _AsyncRedisClient.get_client()
|
||||
count = await asyncio.wait_for(client.incr(key), timeout=1.5)
|
||||
if int(count) == 1:
|
||||
await asyncio.wait_for(client.expire(key, window_seconds), timeout=1.5)
|
||||
except Exception:
|
||||
now = time.monotonic()
|
||||
_prune_local_login_failures(now)
|
||||
count, expires_at = _LOCAL_LOGIN_FAILURES.get(key, (0, now + window_seconds))
|
||||
if expires_at <= now:
|
||||
count = 0
|
||||
expires_at = now + window_seconds
|
||||
_LOCAL_LOGIN_FAILURES[key] = (count + 1, expires_at)
|
||||
|
||||
|
||||
async def clear_login_failures(client_ip: str, username: str) -> None:
|
||||
key = _login_rate_key(client_ip, username)
|
||||
_LOCAL_LOGIN_FAILURES.pop(key, None)
|
||||
try:
|
||||
client = _AsyncRedisClient.get_client()
|
||||
await asyncio.wait_for(client.delete(key), timeout=1.5)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _token_response(user: User) -> dict:
|
||||
@@ -83,9 +210,23 @@ async def _load_user_by_email(db: AsyncSession, email: str) -> User | None:
|
||||
|
||||
@router.post("/login", response_model=Token)
|
||||
async def login(
|
||||
request: Request,
|
||||
form_data: OAuth2PasswordRequestForm = Depends(),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
client_ip = _client_ip(request)
|
||||
retry_after = await check_login_rate_limit(client_ip, form_data.username)
|
||||
if retry_after > 0:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
headers={"Retry-After": str(retry_after)},
|
||||
detail={
|
||||
"code": "RATE_LIMITED",
|
||||
"message": "Too many failed login attempts",
|
||||
"retry_after_seconds": retry_after,
|
||||
},
|
||||
)
|
||||
|
||||
result = await db.execute(
|
||||
text(
|
||||
"SELECT id, username, email, password_hash, role, is_active, gatekeeper_groups, email_verified "
|
||||
@@ -95,6 +236,7 @@ async def login(
|
||||
)
|
||||
row = result.fetchone()
|
||||
if row is None:
|
||||
await record_login_failure(client_ip, form_data.username)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid credentials",
|
||||
@@ -111,11 +253,13 @@ async def login(
|
||||
user.email_verified = bool(row[7])
|
||||
|
||||
if not verify_password(form_data.password, user.password_hash):
|
||||
await record_login_failure(client_ip, form_data.username)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid credentials",
|
||||
)
|
||||
if not user.is_active:
|
||||
await record_login_failure(client_ip, form_data.username)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="User is inactive",
|
||||
@@ -126,34 +270,26 @@ async def login(
|
||||
detail={"code": "EMAIL_NOT_VERIFIED", "email": user.email},
|
||||
)
|
||||
|
||||
await clear_login_failures(client_ip, form_data.username)
|
||||
return _token_response(user)
|
||||
|
||||
|
||||
@router.post("/refresh", response_model=Token)
|
||||
async def refresh_token(
|
||||
current_user: User = Depends(get_current_user),
|
||||
current_user: User = Depends(get_current_user_refresh),
|
||||
):
|
||||
access_token = create_access_token(data={"sub": current_user.id})
|
||||
|
||||
expires_in = None
|
||||
if settings.ACCESS_TOKEN_EXPIRE_MINUTES > 0:
|
||||
expires_in = settings.ACCESS_TOKEN_EXPIRE_MINUTES * 60
|
||||
|
||||
return {
|
||||
"access_token": access_token,
|
||||
"token_type": "bearer",
|
||||
"expires_in": expires_in,
|
||||
"user": {
|
||||
"id": current_user.id,
|
||||
"username": current_user.username,
|
||||
"role": current_user.role,
|
||||
"gatekeeper_groups": current_user.gatekeeper_groups or [],
|
||||
},
|
||||
}
|
||||
return _token_response(current_user)
|
||||
|
||||
|
||||
@router.post("/logout")
|
||||
async def logout():
|
||||
async def logout(
|
||||
credentials: HTTPAuthorizationCredentials | None = Depends(optional_bearer),
|
||||
body: LogoutRequest | None = Body(default=None),
|
||||
):
|
||||
if credentials and credentials.credentials:
|
||||
await revoke_token(credentials.credentials)
|
||||
if body and body.refresh_token:
|
||||
await revoke_token(body.refresh_token)
|
||||
return {"message": "Successfully logged out"}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,317 @@
|
||||
"""Client L1 Earth hot-update manifest and bundle hosting endpoints."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import hmac
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import tarfile
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
from fastapi import APIRouter, Depends, File, Form, HTTPException, Request, UploadFile, status
|
||||
from fastapi.responses import FileResponse, JSONResponse
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.logging import get_logger
|
||||
from app.core.security import get_current_user
|
||||
from app.db.session import get_db
|
||||
|
||||
router = APIRouter()
|
||||
logger = get_logger(__name__, service="api")
|
||||
bearer_optional = HTTPBearer(auto_error=False)
|
||||
|
||||
DEFAULT_CLIENT_UPDATES_DIR = Path(__file__).resolve().parents[3] / "data" / "client-updates"
|
||||
MAX_HOTFIX_BUNDLE_BYTES = 32 * 1024 * 1024
|
||||
MAX_HOTFIX_FILES = 2000
|
||||
MAX_HOTFIX_UNCOMPRESSED_BYTES = 64 * 1024 * 1024
|
||||
SEMVER_PATTERN = re.compile(r"^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][0-9A-Za-z.-]+)?$")
|
||||
SAFE_BUNDLE_FILENAME_PATTERN = re.compile(r"^planet-earth-bundle-[0-9A-Za-z._-]+\.tar\.gz$")
|
||||
|
||||
|
||||
def get_client_updates_dir() -> Path:
|
||||
configured = str(settings.CLIENT_UPDATES_DIR or "").strip()
|
||||
if configured:
|
||||
return Path(configured)
|
||||
return DEFAULT_CLIENT_UPDATES_DIR
|
||||
|
||||
|
||||
def _manifest_path(updates_dir: Path) -> Path:
|
||||
return updates_dir / "manifest.json"
|
||||
|
||||
|
||||
def _atomic_write_bytes(target: Path, content: bytes) -> None:
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp_path = target.with_name(f".{target.name}.{os.getpid()}.{uuid4().hex}.tmp")
|
||||
try:
|
||||
tmp_path.write_bytes(content)
|
||||
os.replace(tmp_path, target)
|
||||
except Exception:
|
||||
tmp_path.unlink(missing_ok=True)
|
||||
raise
|
||||
|
||||
|
||||
def _validate_hotfix_tar_gz(content: bytes) -> dict[str, int]:
|
||||
if not content:
|
||||
raise HTTPException(status_code=400, detail="Hotfix bundle archive is empty")
|
||||
|
||||
file_count = 0
|
||||
total_size = 0
|
||||
has_index_html = False
|
||||
|
||||
try:
|
||||
with tarfile.open(fileobj=io.BytesIO(content), mode="r:gz") as archive:
|
||||
for member in archive.getmembers():
|
||||
raw_name = member.name or ""
|
||||
if "\\" in raw_name or "\0" in raw_name:
|
||||
raise HTTPException(status_code=400, detail=f"Unsafe archive entry path: {raw_name!r}")
|
||||
if member.issym() or member.islnk() or member.isdev() or member.ischr() or member.isblk() or member.isfifo():
|
||||
raise HTTPException(status_code=400, detail=f"Unsupported special archive entry: {raw_name!r}")
|
||||
|
||||
stripped = raw_name.lstrip("./") if raw_name.startswith("./") else raw_name
|
||||
while stripped.startswith("./"):
|
||||
stripped = stripped[2:]
|
||||
stripped = stripped.rstrip("/")
|
||||
|
||||
if raw_name.startswith("/"):
|
||||
raise HTTPException(status_code=400, detail=f"Absolute archive entry path is forbidden: {raw_name!r}")
|
||||
|
||||
if stripped in ("", "."):
|
||||
if member.isdir():
|
||||
continue
|
||||
raise HTTPException(status_code=400, detail="Empty archive file path")
|
||||
|
||||
segments = stripped.split("/")
|
||||
if any(seg in ("", ".", "..") for seg in segments):
|
||||
raise HTTPException(status_code=400, detail=f"Path traversal forbidden in archive: {raw_name!r}")
|
||||
|
||||
if member.isdir():
|
||||
continue
|
||||
if not member.isreg():
|
||||
raise HTTPException(status_code=400, detail=f"Unsupported archive entry type: {raw_name!r}")
|
||||
|
||||
file_count += 1
|
||||
if file_count > MAX_HOTFIX_FILES:
|
||||
raise HTTPException(status_code=400, detail="Archive exceeds maximum allowed file count")
|
||||
|
||||
total_size += max(0, int(member.size))
|
||||
if total_size > MAX_HOTFIX_UNCOMPRESSED_BYTES:
|
||||
raise HTTPException(status_code=400, detail="Archive exceeds maximum uncompressed size limit")
|
||||
|
||||
if stripped == "index.html":
|
||||
has_index_html = True
|
||||
except HTTPException:
|
||||
raise
|
||||
except (tarfile.TarError, EOFError, OSError, ValueError) as exc:
|
||||
raise HTTPException(status_code=400, detail=f"Invalid gzip tar archive: {exc}") from exc
|
||||
|
||||
if not has_index_html:
|
||||
raise HTTPException(status_code=400, detail="Hotfix bundle must include index.html at root")
|
||||
|
||||
return {"filesCount": file_count, "uncompressedBytes": total_size}
|
||||
|
||||
|
||||
def _default_manifest() -> dict[str, Any]:
|
||||
return {
|
||||
"shell": {
|
||||
"version": settings.VERSION,
|
||||
"minRequired": settings.CLIENT_MIN_SHELL_VERSION,
|
||||
"downloadUrl": settings.CLIENT_RELEASE_PAGE_URL,
|
||||
"releaseNotes": "",
|
||||
},
|
||||
"bundle": None,
|
||||
}
|
||||
|
||||
|
||||
def _read_manifest(updates_dir: Path) -> dict[str, Any]:
|
||||
manifest_file = _manifest_path(updates_dir)
|
||||
if not manifest_file.is_file():
|
||||
return _default_manifest()
|
||||
try:
|
||||
payload = json.loads(manifest_file.read_text(encoding="utf-8"))
|
||||
if not isinstance(payload, dict):
|
||||
return _default_manifest()
|
||||
return payload
|
||||
except (OSError, json.JSONDecodeError):
|
||||
return _default_manifest()
|
||||
|
||||
|
||||
async def _require_update_publisher(
|
||||
request: Request,
|
||||
credentials: HTTPAuthorizationCredentials | None = Depends(bearer_optional),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> str:
|
||||
publish_token = request.headers.get("X-Client-Update-Token")
|
||||
if publish_token is not None:
|
||||
expected = str(settings.CLIENT_UPDATE_PUBLISH_TOKEN or "").strip()
|
||||
if not expected or not hmac.compare_digest(publish_token.strip(), expected):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid client update publish token",
|
||||
)
|
||||
return "ci-token"
|
||||
|
||||
if credentials is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Not authenticated",
|
||||
)
|
||||
|
||||
user = await get_current_user(credentials=credentials, db=db)
|
||||
if getattr(user, "role", None) != "admin":
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Admin privileges required",
|
||||
)
|
||||
return f"admin:{user.username}"
|
||||
|
||||
|
||||
def _validate_semver(value: str, field_name: str) -> str:
|
||||
cleaned = str(value or "").strip().lstrip("vV")
|
||||
if not SEMVER_PATTERN.match(cleaned):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Invalid semantic version for {field_name}: {value!r}",
|
||||
)
|
||||
return cleaned
|
||||
|
||||
|
||||
@router.get("/update-manifest")
|
||||
async def get_client_update_manifest(
|
||||
platform: str = "",
|
||||
arch: str = "",
|
||||
shell: str = "",
|
||||
bundle: str = "",
|
||||
):
|
||||
updates_dir = get_client_updates_dir()
|
||||
manifest = _read_manifest(updates_dir)
|
||||
bundle_info = manifest.get("bundle")
|
||||
if isinstance(bundle_info, dict):
|
||||
filename = Path(str(bundle_info.get("url") or "")).name
|
||||
if not SAFE_BUNDLE_FILENAME_PATTERN.match(filename) or not (updates_dir / filename).is_file():
|
||||
manifest = {**manifest, "bundle": None}
|
||||
|
||||
logger.debug_event(
|
||||
"Served client update manifest",
|
||||
event="client_updates.manifest.read",
|
||||
context={
|
||||
"platform": platform or None,
|
||||
"arch": arch or None,
|
||||
"shell": shell or None,
|
||||
"bundle": bundle or None,
|
||||
"has_bundle": bool(manifest.get("bundle")),
|
||||
},
|
||||
)
|
||||
return JSONResponse(content=manifest, headers={"Cache-Control": "no-store"})
|
||||
|
||||
|
||||
@router.get("/updates/files/{filename}")
|
||||
async def download_client_hotfix_bundle(filename: str):
|
||||
if not SAFE_BUNDLE_FILENAME_PATTERN.match(filename):
|
||||
raise HTTPException(status_code=400, detail="Invalid client hotfix bundle filename")
|
||||
|
||||
updates_dir = get_client_updates_dir().resolve()
|
||||
target = (updates_dir / filename).resolve()
|
||||
if target.parent != updates_dir or not target.is_file():
|
||||
raise HTTPException(status_code=404, detail="Client hotfix bundle not found")
|
||||
|
||||
return FileResponse(
|
||||
path=target,
|
||||
media_type="application/gzip",
|
||||
filename=filename,
|
||||
headers={"Cache-Control": "public, max-age=31536000, immutable"},
|
||||
)
|
||||
|
||||
|
||||
@router.post("/updates/bundle")
|
||||
async def publish_client_hotfix_bundle(
|
||||
file: UploadFile = File(...),
|
||||
version: str = Form(...),
|
||||
min_shell_version: str = Form(""),
|
||||
release_notes: str = Form(""),
|
||||
shell_version: str = Form(""),
|
||||
shell_min_required: str = Form(""),
|
||||
shell_download_url: str = Form(""),
|
||||
publisher: str = Depends(_require_update_publisher),
|
||||
):
|
||||
normalized_version = _validate_semver(version, "version")
|
||||
normalized_min_shell = _validate_semver(
|
||||
min_shell_version or settings.CLIENT_MIN_SHELL_VERSION or normalized_version,
|
||||
"min_shell_version",
|
||||
)
|
||||
|
||||
content = await file.read(MAX_HOTFIX_BUNDLE_BYTES + 1)
|
||||
if len(content) > MAX_HOTFIX_BUNDLE_BYTES:
|
||||
raise HTTPException(status_code=400, detail="Hotfix bundle exceeds 32 MiB limit")
|
||||
|
||||
archive_meta = _validate_hotfix_tar_gz(content)
|
||||
sha256_hex = hashlib.sha256(content).hexdigest()
|
||||
bundle_filename = f"planet-earth-bundle-{normalized_version}.tar.gz"
|
||||
updates_dir = get_client_updates_dir()
|
||||
|
||||
_atomic_write_bytes(updates_dir / bundle_filename, content)
|
||||
|
||||
existing_manifest = _read_manifest(updates_dir)
|
||||
existing_shell = existing_manifest.get("shell") if isinstance(existing_manifest.get("shell"), dict) else {}
|
||||
|
||||
resolved_shell_version = (
|
||||
_validate_semver(shell_version, "shell_version")
|
||||
if str(shell_version or "").strip()
|
||||
else str(existing_shell.get("version") or settings.VERSION)
|
||||
)
|
||||
resolved_shell_min = (
|
||||
_validate_semver(shell_min_required, "shell_min_required")
|
||||
if str(shell_min_required or "").strip()
|
||||
else str(existing_shell.get("minRequired") or settings.CLIENT_MIN_SHELL_VERSION)
|
||||
)
|
||||
resolved_shell_url = str(shell_download_url or "").strip() or str(
|
||||
existing_shell.get("downloadUrl") or settings.CLIENT_RELEASE_PAGE_URL
|
||||
)
|
||||
if not resolved_shell_url.startswith(("https://", "http://")):
|
||||
raise HTTPException(status_code=400, detail="shell_download_url must start with http:// or https://")
|
||||
|
||||
cleaned_notes = str(release_notes or "").strip()[:4000]
|
||||
manifest: dict[str, Any] = {
|
||||
"shell": {
|
||||
"version": resolved_shell_version,
|
||||
"minRequired": resolved_shell_min,
|
||||
"downloadUrl": resolved_shell_url,
|
||||
"releaseNotes": cleaned_notes or str(existing_shell.get("releaseNotes") or ""),
|
||||
},
|
||||
"bundle": {
|
||||
"version": normalized_version,
|
||||
"minShellVersion": normalized_min_shell,
|
||||
"url": f"/api/v1/client/updates/files/{bundle_filename}",
|
||||
"sha256": sha256_hex,
|
||||
"size": len(content),
|
||||
"releaseNotes": cleaned_notes,
|
||||
"publishedAt": datetime.now(UTC).isoformat(),
|
||||
**archive_meta,
|
||||
},
|
||||
}
|
||||
|
||||
_atomic_write_bytes(
|
||||
_manifest_path(updates_dir),
|
||||
(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n").encode("utf-8"),
|
||||
)
|
||||
|
||||
logger.info_event(
|
||||
"Published client L1 hotfix bundle",
|
||||
event="client_updates.bundle_published",
|
||||
context={
|
||||
"publisher": publisher,
|
||||
"version": normalized_version,
|
||||
"min_shell_version": normalized_min_shell,
|
||||
"bytes": len(content),
|
||||
"sha256": sha256_hex,
|
||||
"files_count": archive_meta["filesCount"],
|
||||
},
|
||||
)
|
||||
return {"status": "published", "manifest": manifest}
|
||||
@@ -690,24 +690,47 @@ async def delete_config(
|
||||
deleted_records = {
|
||||
"collected_data": 0,
|
||||
"ais_raw_observations": 0,
|
||||
"vessel_current_state": 0,
|
||||
"ais_source_health": 0,
|
||||
}
|
||||
|
||||
if delete_source_data:
|
||||
collected_result = await db.execute(
|
||||
delete(CollectedData).where(CollectedData.source == config.name)
|
||||
from app.models.vessel import VesselCurrentState
|
||||
|
||||
sibling_result = await db.execute(
|
||||
select(DataSourceConfig.id)
|
||||
.where(DataSourceConfig.name == config.name, DataSourceConfig.id != config_id)
|
||||
.limit(1)
|
||||
)
|
||||
raw_result = await db.execute(
|
||||
delete(AISRawObservation).where(AISRawObservation.source == config.name)
|
||||
)
|
||||
health_result = await db.execute(
|
||||
delete(AISSourceHealth).where(AISSourceHealth.source == config.name)
|
||||
)
|
||||
deleted_records = {
|
||||
"collected_data": collected_result.rowcount or 0,
|
||||
"ais_raw_observations": raw_result.rowcount or 0,
|
||||
"ais_source_health": health_result.rowcount or 0,
|
||||
}
|
||||
has_same_name_sibling = sibling_result.scalar_one_or_none() is not None
|
||||
|
||||
if has_same_name_sibling:
|
||||
collected_result = await db.execute(
|
||||
delete(CollectedData).where(
|
||||
CollectedData.source == config.name,
|
||||
CollectedData.entity_key.like(f"datasource_config:{config_id}:%"),
|
||||
)
|
||||
)
|
||||
deleted_records["collected_data"] = collected_result.rowcount or 0
|
||||
else:
|
||||
collected_result = await db.execute(
|
||||
delete(CollectedData).where(CollectedData.source == config.name)
|
||||
)
|
||||
raw_result = await db.execute(
|
||||
delete(AISRawObservation).where(AISRawObservation.source == config.name)
|
||||
)
|
||||
current_vessel_result = await db.execute(
|
||||
delete(VesselCurrentState).where(VesselCurrentState.source == config.name)
|
||||
)
|
||||
health_result = await db.execute(
|
||||
delete(AISSourceHealth).where(AISSourceHealth.source == config.name)
|
||||
)
|
||||
deleted_records = {
|
||||
"collected_data": collected_result.rowcount or 0,
|
||||
"ais_raw_observations": raw_result.rowcount or 0,
|
||||
"vessel_current_state": current_vessel_result.rowcount or 0,
|
||||
"ais_source_health": health_result.rowcount or 0,
|
||||
}
|
||||
|
||||
if delete_mappings or delete_source_data:
|
||||
mapping_result = await db.execute(
|
||||
|
||||
@@ -19,7 +19,7 @@ from app.models.datasource import DataSource
|
||||
from app.models.datasource_config import DataSourceConfig
|
||||
from app.models.task import CollectionTask
|
||||
from app.models.user import User
|
||||
from app.models.vessel import AISRawObservation
|
||||
from app.models.vessel import AISRawObservation, VesselCurrentState
|
||||
from app.services.scheduler import (
|
||||
sync_datasource_job,
|
||||
)
|
||||
@@ -228,6 +228,16 @@ async def _load_collected_record_counts(
|
||||
if source in vessel_sources:
|
||||
counts[source] = max(counts.get(source, 0), int(round(total_rows * freq)))
|
||||
|
||||
missing_vessel_sources = [source for source in vessel_sources if counts.get(source, 0) == 0]
|
||||
if missing_vessel_sources:
|
||||
current_result = await db.execute(
|
||||
select(VesselCurrentState.source, func.count(VesselCurrentState.mmsi))
|
||||
.where(VesselCurrentState.source.in_(missing_vessel_sources))
|
||||
.group_by(VesselCurrentState.source)
|
||||
)
|
||||
for source, count in current_result.all():
|
||||
counts[source] = max(counts.get(source, 0), int(count or 0))
|
||||
|
||||
return counts
|
||||
|
||||
|
||||
|
||||
@@ -14,7 +14,12 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.config import settings as app_settings
|
||||
from app.core.logging import get_logger
|
||||
from app.core.security import decode_token, get_current_user, redis_client
|
||||
from app.core.security import (
|
||||
decode_token,
|
||||
get_current_user,
|
||||
is_token_blacklisted,
|
||||
redis_client,
|
||||
)
|
||||
from app.core.websocket.broadcaster import broadcaster
|
||||
from app.db.session import get_db
|
||||
from app.models.collected_data import CollectedData
|
||||
@@ -251,7 +256,7 @@ async def _get_optional_current_user(
|
||||
if credentials is None:
|
||||
return None
|
||||
token = credentials.credentials
|
||||
if redis_client.sismember("blacklisted_tokens", token):
|
||||
if await is_token_blacklisted(token, legacy_sync_client=redis_client):
|
||||
return None
|
||||
payload = decode_token(token)
|
||||
if payload is None or payload.get("type") != "access":
|
||||
|
||||
@@ -15,7 +15,8 @@ from app.db.session import get_db
|
||||
from app.models.datasource import DataSource
|
||||
from app.models.datasource_config import DataSourceConfig
|
||||
from app.models.user import User
|
||||
from app.models.vessel import AISRawObservation, AISSourceHealth
|
||||
from app.models.vessel import AISRawObservation, AISSourceHealth, VesselCurrentState
|
||||
from app.services.storage_policy import resolve_collector_storage_policy
|
||||
from app.services.custom_datasource_runtime import (
|
||||
get_custom_stream_status,
|
||||
start_custom_stream,
|
||||
@@ -77,14 +78,45 @@ async def _load_realtime_stats(db: AsyncSession, source: str) -> dict[str, Any]:
|
||||
.where(AISRawObservation.source == source)
|
||||
)
|
||||
row = result.mappings().one()
|
||||
mode, _ = await resolve_collector_storage_policy(db, source)
|
||||
total_obs = int(row["total_observations"] or 0)
|
||||
if total_obs > 0:
|
||||
return {
|
||||
"total_observations": total_obs,
|
||||
"observations_24h": int(row["observations_24h"] or 0),
|
||||
"observations_1h": int(row["observations_1h"] or 0),
|
||||
"unique_mmsi_total": int(row["unique_mmsi_total"] or 0),
|
||||
"unique_mmsi_24h": int(row["unique_mmsi_24h"] or 0),
|
||||
"latest_observed_at": to_iso8601_utc(row["latest_observed_at"]),
|
||||
"latest_collected_at": to_iso8601_utc(row["latest_collected_at"]),
|
||||
"storage_mode": mode,
|
||||
}
|
||||
|
||||
current_result = await db.execute(
|
||||
select(
|
||||
func.count(VesselCurrentState.mmsi).label("total_vessels"),
|
||||
func.count(VesselCurrentState.mmsi)
|
||||
.filter(VesselCurrentState.observed_at >= observed_24h)
|
||||
.label("vessels_24h"),
|
||||
func.count(VesselCurrentState.mmsi)
|
||||
.filter(VesselCurrentState.observed_at >= observed_1h)
|
||||
.label("vessels_1h"),
|
||||
func.max(VesselCurrentState.observed_at).label("latest_observed_at"),
|
||||
func.max(VesselCurrentState.updated_at).label("latest_collected_at"),
|
||||
).where(VesselCurrentState.source == source)
|
||||
)
|
||||
current_row = current_result.mappings().one()
|
||||
total_vessels = int(current_row["total_vessels"] or 0)
|
||||
vessels_24h = int(current_row["vessels_24h"] or 0)
|
||||
return {
|
||||
"total_observations": int(row["total_observations"] or 0),
|
||||
"observations_24h": int(row["observations_24h"] or 0),
|
||||
"observations_1h": int(row["observations_1h"] or 0),
|
||||
"unique_mmsi_total": int(row["unique_mmsi_total"] or 0),
|
||||
"unique_mmsi_24h": int(row["unique_mmsi_24h"] or 0),
|
||||
"latest_observed_at": to_iso8601_utc(row["latest_observed_at"]),
|
||||
"latest_collected_at": to_iso8601_utc(row["latest_collected_at"]),
|
||||
"total_observations": total_vessels,
|
||||
"observations_24h": vessels_24h,
|
||||
"observations_1h": int(current_row["vessels_1h"] or 0),
|
||||
"unique_mmsi_total": total_vessels,
|
||||
"unique_mmsi_24h": vessels_24h,
|
||||
"latest_observed_at": to_iso8601_utc(current_row["latest_observed_at"]),
|
||||
"latest_collected_at": to_iso8601_utc(current_row["latest_collected_at"]),
|
||||
"storage_mode": mode,
|
||||
}
|
||||
|
||||
|
||||
|
||||
+271
-20
@@ -2,7 +2,7 @@ from copy import deepcopy
|
||||
from datetime import UTC, datetime
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
from typing import Literal, Optional
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request, status
|
||||
@@ -12,6 +12,7 @@ from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.logging import get_logger
|
||||
from app.core.secret_crypto import decrypt_setting_payload, encrypt_setting_payload
|
||||
from app.core.enums import ProviderApi, TVSourceType, UserRole
|
||||
from app.core.security import get_current_user
|
||||
from app.core.time import to_iso8601_utc
|
||||
@@ -70,6 +71,20 @@ from app.services.scheduler import sync_datasource_job
|
||||
from app.services.tv_streams import DEFAULT_TV_SETTINGS, get_tv_settings_payload, normalize_tv_settings
|
||||
from app.services.persistent_logs import record_audit_log
|
||||
from app.services.business_logs import emit_business_log, exception_context
|
||||
from app.services.storage_policy import (
|
||||
ANNUAL_ELIGIBLE_SOURCES,
|
||||
HIGH_VOLUME_SOURCES,
|
||||
GlobalSnapshotAction,
|
||||
SnapshotMode,
|
||||
StoragePolicyLockedError,
|
||||
apply_global_snapshot_action,
|
||||
get_storage_policy,
|
||||
mutate_storage_policy,
|
||||
normalize_storage_policy,
|
||||
resolve_snapshot_mode,
|
||||
set_source_snapshot_mode,
|
||||
summarize_storage_policy,
|
||||
)
|
||||
|
||||
router = APIRouter()
|
||||
logger = get_logger(__name__, service="api")
|
||||
@@ -78,6 +93,14 @@ AI_CONNECTION_TEST_PROMPT_KEY = "ai.connection_test"
|
||||
SECRET_REVEAL_ROLES = {UserRole.ADMIN.value, UserRole.SUPER_ADMIN.value}
|
||||
LLM_PROVIDER_PRESET_CATEGORY_PREFIX = "llm_provider_preset:"
|
||||
|
||||
|
||||
def _require_admin(current_user: User, detail: str) -> None:
|
||||
if current_user.role not in SECRET_REVEAL_ROLES:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail=detail,
|
||||
)
|
||||
|
||||
DEFAULT_SETTINGS = {
|
||||
"system": {
|
||||
"system_name": "智能星球",
|
||||
@@ -231,6 +254,19 @@ class CollectorSettingsUpdate(BaseModel):
|
||||
is_active: bool
|
||||
priority: str = Field(default="P1")
|
||||
frequency_minutes: int = Field(default=60, ge=1, le=10080)
|
||||
snapshot_mode: Optional[SnapshotMode] = None
|
||||
|
||||
|
||||
class StoragePolicyUpdate(BaseModel):
|
||||
action: Optional[GlobalSnapshotAction] = None
|
||||
global_single_lock: Optional[bool] = None
|
||||
default_mode: Optional[SnapshotMode] = None
|
||||
overrides: Optional[dict[str, SnapshotMode]] = None
|
||||
source_mode: Optional[dict[str, SnapshotMode]] = None
|
||||
history_retention_days: Optional[int] = Field(default=None, ge=1, le=3650)
|
||||
bgp_observation_retention_days: Optional[int] = Field(default=None, ge=1, le=365)
|
||||
bgp_single_batch_max_rows: Optional[int] = Field(default=None, ge=50, le=5000)
|
||||
auto_prune_enabled: Optional[bool] = None
|
||||
|
||||
|
||||
class TVStreamSourceUpdate(BaseModel):
|
||||
@@ -355,12 +391,27 @@ def merge_with_defaults(category: str, payload: Optional[dict]) -> dict:
|
||||
defaults = DEFAULT_SETTINGS[category]
|
||||
merged = deepcopy(defaults)
|
||||
if payload:
|
||||
merged.update(payload)
|
||||
merged.update(decrypt_setting_payload(category, payload))
|
||||
return merged
|
||||
|
||||
|
||||
async def get_setting_record(db: AsyncSession, category: str) -> Optional[SystemSetting]:
|
||||
result = await db.execute(select(SystemSetting).where(SystemSetting.category == category))
|
||||
async def get_setting_record(
|
||||
db: AsyncSession,
|
||||
category: str,
|
||||
*,
|
||||
for_update: bool = False,
|
||||
) -> Optional[SystemSetting]:
|
||||
stmt = select(SystemSetting).where(SystemSetting.category == category)
|
||||
if hasattr(stmt, "execution_options"):
|
||||
stmt = stmt.execution_options(populate_existing=True)
|
||||
if for_update and hasattr(stmt, "with_for_update") and callable(getattr(db, "get_bind", None)):
|
||||
try:
|
||||
bind = db.get_bind()
|
||||
if getattr(getattr(bind, "dialect", None), "name", "") == "postgresql":
|
||||
stmt = stmt.with_for_update()
|
||||
except Exception:
|
||||
pass
|
||||
result = await db.execute(stmt)
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
|
||||
@@ -389,17 +440,27 @@ async def get_setting_payload(db: AsyncSession, category: str) -> dict:
|
||||
return merge_with_defaults(category, record.payload if record else None)
|
||||
|
||||
|
||||
async def save_setting_payload(db: AsyncSession, category: str, payload: dict) -> dict:
|
||||
async def save_setting_payload(
|
||||
db: AsyncSession,
|
||||
category: str,
|
||||
payload: dict,
|
||||
*,
|
||||
commit: bool = True,
|
||||
for_update: bool = False,
|
||||
) -> dict:
|
||||
merged = merge_with_defaults(category, payload)
|
||||
record = await get_setting_record(db, category)
|
||||
persisted_payload = encrypt_setting_payload(category, payload)
|
||||
record = await get_setting_record(db, category, for_update=for_update)
|
||||
if record is None:
|
||||
record = SystemSetting(category=category, payload=payload)
|
||||
record = SystemSetting(category=category, payload=persisted_payload)
|
||||
db.add(record)
|
||||
else:
|
||||
record.payload = payload
|
||||
record.payload = persisted_payload
|
||||
|
||||
await db.commit()
|
||||
await db.refresh(record)
|
||||
if commit:
|
||||
await db.commit()
|
||||
if hasattr(db, "refresh"):
|
||||
await db.refresh(record)
|
||||
return merged
|
||||
|
||||
|
||||
@@ -1223,8 +1284,14 @@ async def get_ais_source_health_by_source(db: AsyncSession) -> dict[str, dict]:
|
||||
return {item.source: item.to_dict() for item in result.scalars().all()}
|
||||
|
||||
|
||||
def serialize_collector(datasource: DataSource, ais_health_by_source: dict[str, dict] | None = None) -> dict:
|
||||
def serialize_collector(
|
||||
datasource: DataSource,
|
||||
ais_health_by_source: dict[str, dict] | None = None,
|
||||
storage_policy: dict | None = None,
|
||||
) -> dict:
|
||||
defaults = DEFAULT_DATASOURCES.get(datasource.source, {})
|
||||
effective_mode = resolve_snapshot_mode(storage_policy, datasource.source)
|
||||
overrides = (storage_policy or {}).get("overrides") or {}
|
||||
return {
|
||||
"id": datasource.id,
|
||||
"name": datasource.name,
|
||||
@@ -1243,6 +1310,11 @@ def serialize_collector(datasource: DataSource, ais_health_by_source: dict[str,
|
||||
"credential_provider": defaults.get("credential_provider"),
|
||||
"credential_status": defaults.get("credential_status", "none"),
|
||||
"ais_health": (ais_health_by_source or {}).get(datasource.source),
|
||||
"snapshot_mode": effective_mode,
|
||||
"snapshot_overridden": datasource.source in overrides,
|
||||
"snapshot_locked": bool((storage_policy or {}).get("global_single_lock", False)),
|
||||
"supports_annual": datasource.source in ANNUAL_ELIGIBLE_SOURCES,
|
||||
"high_volume_warning": HIGH_VOLUME_SOURCES.get(datasource.source),
|
||||
}
|
||||
|
||||
|
||||
@@ -1260,10 +1332,131 @@ async def update_system_settings(
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
payload = await save_setting_payload(db, "system", settings.model_dump())
|
||||
_require_admin(current_user, "Only administrators can change system settings")
|
||||
raw_system = settings.model_dump()
|
||||
# Canonical lock order: advisory lock -> collection_storage -> system, committed atomically.
|
||||
await mutate_storage_policy(
|
||||
db,
|
||||
lambda current_policy: {
|
||||
**current_policy,
|
||||
"history_retention_days": raw_system["data_retention_days"],
|
||||
},
|
||||
sync_system_retention=False,
|
||||
commit=False,
|
||||
)
|
||||
payload = await save_setting_payload(
|
||||
db,
|
||||
"system",
|
||||
raw_system,
|
||||
commit=True,
|
||||
for_update=True,
|
||||
)
|
||||
return {"status": "updated", "system": payload}
|
||||
|
||||
|
||||
async def _load_known_collector_sources(db: AsyncSession) -> list[str]:
|
||||
result = await db.execute(select(DataSource.source))
|
||||
return [str(source) for source in result.scalars().all() if source]
|
||||
|
||||
|
||||
@router.get("/storage-policy")
|
||||
async def get_storage_policy_settings(
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
policy = await get_storage_policy(db)
|
||||
sources = await _load_known_collector_sources(db)
|
||||
return {"storage_policy": summarize_storage_policy(policy, sources)}
|
||||
|
||||
|
||||
@router.put("/storage-policy")
|
||||
async def update_storage_policy_settings(
|
||||
update: StoragePolicyUpdate,
|
||||
request: Request,
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
_require_admin(current_user, "Only administrators can change storage policy settings")
|
||||
|
||||
def _apply_policy_update(current_policy: dict) -> dict:
|
||||
next_policy = dict(current_policy)
|
||||
if update.action is not None:
|
||||
next_policy = apply_global_snapshot_action(next_policy, update.action)
|
||||
if update.global_single_lock is not None:
|
||||
next_policy = normalize_storage_policy(
|
||||
{**next_policy, "global_single_lock": update.global_single_lock}
|
||||
)
|
||||
|
||||
if next_policy.get("global_single_lock"):
|
||||
requests_non_single_default = (
|
||||
update.default_mode is not None and update.default_mode != "single"
|
||||
)
|
||||
requests_non_single_override = any(
|
||||
mode != "single" for mode in (update.overrides or {}).values()
|
||||
)
|
||||
requests_non_single_source = any(
|
||||
mode != "single" for mode in (update.source_mode or {}).values()
|
||||
)
|
||||
if (
|
||||
requests_non_single_default
|
||||
or requests_non_single_override
|
||||
or requests_non_single_source
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="全局「全部单份」已开启,禁止单独开启历史或年末快照;请先切换为默认推荐或关闭全局单份锁定。",
|
||||
)
|
||||
|
||||
if update.default_mode is not None:
|
||||
next_policy = normalize_storage_policy({**next_policy, "default_mode": update.default_mode})
|
||||
if update.overrides is not None:
|
||||
next_policy = normalize_storage_policy({**next_policy, "overrides": update.overrides})
|
||||
if update.source_mode is not None:
|
||||
try:
|
||||
for source, mode in update.source_mode.items():
|
||||
next_policy = set_source_snapshot_mode(next_policy, source, mode)
|
||||
except StoragePolicyLockedError as exc:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="全局「全部单份」已开启,禁止单独开启历史或年末快照;请先切换为默认推荐或关闭全局单份锁定。",
|
||||
) from exc
|
||||
|
||||
patch: dict = {}
|
||||
if update.history_retention_days is not None:
|
||||
patch["history_retention_days"] = update.history_retention_days
|
||||
if update.bgp_observation_retention_days is not None:
|
||||
patch["bgp_observation_retention_days"] = update.bgp_observation_retention_days
|
||||
if update.bgp_single_batch_max_rows is not None:
|
||||
patch["bgp_single_batch_max_rows"] = update.bgp_single_batch_max_rows
|
||||
if update.auto_prune_enabled is not None:
|
||||
patch["auto_prune_enabled"] = update.auto_prune_enabled
|
||||
if patch:
|
||||
next_policy = normalize_storage_policy({**next_policy, **patch})
|
||||
return next_policy
|
||||
|
||||
saved = await mutate_storage_policy(db, _apply_policy_update, sync_system_retention=True)
|
||||
sources = await _load_known_collector_sources(db)
|
||||
summarized = summarize_storage_policy(saved, sources)
|
||||
await record_audit_log(
|
||||
action="settings.storage_policy.update",
|
||||
actor_id=getattr(current_user, "id", None),
|
||||
actor_name=_user_display_name(current_user),
|
||||
target_type="system_setting",
|
||||
target_id="collection_storage",
|
||||
result="success",
|
||||
ip=_request_client_ip(request),
|
||||
details={
|
||||
"default_mode": summarized["default_mode"],
|
||||
"global_single_lock": summarized["global_single_lock"],
|
||||
"overrides": summarized["overrides"],
|
||||
"history_retention_days": summarized["history_retention_days"],
|
||||
"auto_prune_enabled": summarized["auto_prune_enabled"],
|
||||
"master_state": summarized["master_state"],
|
||||
},
|
||||
)
|
||||
return {"status": "updated", "storage_policy": summarized}
|
||||
|
||||
|
||||
@router.get("/notifications")
|
||||
async def get_notification_settings(
|
||||
current_user: User = Depends(get_current_user),
|
||||
@@ -1278,6 +1471,7 @@ async def update_notification_settings(
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
_require_admin(current_user, "Only administrators can change notification settings")
|
||||
payload = await save_setting_payload(db, "notifications", settings.model_dump())
|
||||
return {"status": "updated", "notifications": payload}
|
||||
|
||||
@@ -1296,6 +1490,7 @@ async def update_security_settings(
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
_require_admin(current_user, "Only administrators can change security settings")
|
||||
payload = await save_setting_payload(db, "security", settings.model_dump())
|
||||
return {"status": "updated", "security": payload}
|
||||
|
||||
@@ -1405,6 +1600,7 @@ async def update_tv_settings(
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
_require_admin(current_user, "Only administrators can change TV settings")
|
||||
payload = normalize_tv_settings(settings.model_dump())
|
||||
saved = await save_setting_payload(db, "tv", payload)
|
||||
return {"status": "updated", "tv": normalize_tv_settings(saved)}
|
||||
@@ -2008,6 +2204,7 @@ async def update_external_integrations(
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
_require_admin(current_user, "Only administrators can change integration settings")
|
||||
saved = await save_external_integrations_payload(db, payload)
|
||||
return {"status": "updated", "integrations": saved}
|
||||
|
||||
@@ -2020,7 +2217,17 @@ async def get_collector_settings(
|
||||
result = await db.execute(select(DataSource).order_by(DataSource.module, DataSource.id))
|
||||
datasources = result.scalars().all()
|
||||
ais_health_by_source = await get_ais_source_health_by_source(db)
|
||||
return {"collectors": [serialize_collector(datasource, ais_health_by_source) for datasource in datasources]}
|
||||
storage_policy = await get_storage_policy(db)
|
||||
return {
|
||||
"collectors": [
|
||||
serialize_collector(datasource, ais_health_by_source, storage_policy)
|
||||
for datasource in datasources
|
||||
],
|
||||
"storage_policy": summarize_storage_policy(
|
||||
storage_policy,
|
||||
[datasource.source for datasource in datasources],
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
@router.put("/collectors/{datasource_id}")
|
||||
@@ -2030,18 +2237,54 @@ async def update_collector_settings(
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
_require_admin(current_user, "Only administrators can change collector settings")
|
||||
datasource = await db.get(DataSource, datasource_id)
|
||||
if not datasource:
|
||||
raise HTTPException(status_code=404, detail="Data source not found")
|
||||
|
||||
datasource.is_active = settings.is_active
|
||||
datasource.priority = settings.priority
|
||||
datasource.frequency_minutes = settings.frequency_minutes
|
||||
await db.commit()
|
||||
await db.refresh(datasource)
|
||||
if settings.snapshot_mode is not None:
|
||||
requested_mode = settings.snapshot_mode
|
||||
|
||||
def _apply_collector_snapshot_mode(current_policy: dict) -> dict:
|
||||
try:
|
||||
return set_source_snapshot_mode(
|
||||
current_policy,
|
||||
datasource.source,
|
||||
requested_mode,
|
||||
)
|
||||
except StoragePolicyLockedError as exc:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="全局「全部单份」已开启,无法单独开启该数据源的历史或年末快照。",
|
||||
) from exc
|
||||
|
||||
storage_policy = await mutate_storage_policy(
|
||||
db,
|
||||
_apply_collector_snapshot_mode,
|
||||
sync_system_retention=False,
|
||||
commit=False,
|
||||
)
|
||||
datasource.is_active = settings.is_active
|
||||
datasource.priority = settings.priority
|
||||
datasource.frequency_minutes = settings.frequency_minutes
|
||||
await db.commit()
|
||||
await db.refresh(datasource)
|
||||
else:
|
||||
datasource.is_active = settings.is_active
|
||||
datasource.priority = settings.priority
|
||||
datasource.frequency_minutes = settings.frequency_minutes
|
||||
await db.commit()
|
||||
await db.refresh(datasource)
|
||||
storage_policy = await get_storage_policy(db)
|
||||
|
||||
await sync_datasource_job(datasource.id)
|
||||
ais_health_by_source = await get_ais_source_health_by_source(db)
|
||||
return {"status": "updated", "collector": serialize_collector(datasource, ais_health_by_source)}
|
||||
sources = await _load_known_collector_sources(db)
|
||||
return {
|
||||
"status": "updated",
|
||||
"collector": serialize_collector(datasource, ais_health_by_source, storage_policy),
|
||||
"storage_policy": summarize_storage_policy(storage_policy, sources),
|
||||
}
|
||||
|
||||
|
||||
@router.get("")
|
||||
@@ -2056,12 +2299,20 @@ async def get_all_settings(
|
||||
["system", "notifications", "security"],
|
||||
)
|
||||
ais_health_by_source = await get_ais_source_health_by_source(db)
|
||||
storage_policy = await get_storage_policy(db)
|
||||
return {
|
||||
"system": setting_payloads["system"],
|
||||
"notifications": setting_payloads["notifications"],
|
||||
"security": setting_payloads["security"],
|
||||
"tv": await get_tv_settings_payload(db),
|
||||
"integrations": await serialize_external_integrations(db),
|
||||
"collectors": [serialize_collector(datasource, ais_health_by_source) for datasource in datasources],
|
||||
"collectors": [
|
||||
serialize_collector(datasource, ais_health_by_source, storage_policy)
|
||||
for datasource in datasources
|
||||
],
|
||||
"storage_policy": summarize_storage_policy(
|
||||
storage_policy,
|
||||
[datasource.source for datasource in datasources],
|
||||
),
|
||||
"generated_at": to_iso8601_utc(datetime.now(UTC)),
|
||||
}
|
||||
@@ -11,6 +11,7 @@ from sqlalchemy import text
|
||||
from app.core.config import settings
|
||||
from app.core.enums import UserRole
|
||||
from app.core.logging import get_logger
|
||||
from app.core.security import is_token_blacklisted
|
||||
from app.core.time import to_iso8601_utc
|
||||
from app.core.websocket.manager import manager
|
||||
from app.db.session import async_session_factory
|
||||
@@ -23,6 +24,12 @@ EARTH_UPDATES_CHANNEL = "earth_updates"
|
||||
|
||||
async def authenticate_token(token: str) -> Optional[dict]:
|
||||
"""Authenticate WebSocket connection via token"""
|
||||
if await is_token_blacklisted(token):
|
||||
logger.warning_event(
|
||||
"WebSocket auth failed: revoked token",
|
||||
event="auth.websocket.revoked_token",
|
||||
)
|
||||
return None
|
||||
try:
|
||||
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
|
||||
if payload.get("type") != "access":
|
||||
@@ -210,9 +217,12 @@ async def websocket_endpoint(
|
||||
await websocket.send_json({"type": "ack", "data": {"received": True}})
|
||||
|
||||
except asyncio.TimeoutError:
|
||||
await websocket.send_json({"type": "heartbeat", "data": {"action": "ping"}})
|
||||
try:
|
||||
await websocket.send_json({"type": "heartbeat", "data": {"action": "ping"}})
|
||||
except Exception:
|
||||
break
|
||||
|
||||
except WebSocketDisconnect:
|
||||
except (WebSocketDisconnect, RuntimeError):
|
||||
pass
|
||||
finally:
|
||||
await log_tail_manager.disconnect(websocket)
|
||||
|
||||
+130
-8
@@ -1,13 +1,34 @@
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
from typing import List
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import List, Optional
|
||||
from urllib.parse import quote, urlsplit, urlunsplit
|
||||
|
||||
from pydantic_settings import BaseSettings
|
||||
|
||||
|
||||
ROOT_DIR = Path(__file__).parent.parent.parent.parent
|
||||
VERSION_FILE = ROOT_DIR / "VERSION"
|
||||
WEAK_SECRET_PLACEHOLDERS = frozenset(
|
||||
{
|
||||
"",
|
||||
"change-me",
|
||||
"change_me",
|
||||
"change_me_to_a_random_secret",
|
||||
"change_me_to_a_random_32_plus_char_secret",
|
||||
"your-secret-key-change-in-production",
|
||||
"replace-with-strong-32-char-random-secret",
|
||||
}
|
||||
)
|
||||
WEAK_SERVICE_TOKEN_PLACEHOLDERS = frozenset(
|
||||
{
|
||||
"",
|
||||
"change-me",
|
||||
"change_me",
|
||||
"replace-with-internal-token",
|
||||
}
|
||||
)
|
||||
VALID_PLANET_ROLES = frozenset({"all", "api", "worker"})
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
@@ -16,23 +37,46 @@ class Settings(BaseSettings):
|
||||
os.getenv("APP_VERSION")
|
||||
or (VERSION_FILE.read_text(encoding="utf-8").strip() if VERSION_FILE.exists() else "0.19.0")
|
||||
)
|
||||
APP_ENV: str = "development"
|
||||
PLANET_ROLE: str = "all"
|
||||
ENABLE_SCHEDULER: Optional[bool] = None
|
||||
|
||||
API_V1_STR: str = "/api/v1"
|
||||
SECRET_KEY: str = "your-secret-key-change-in-production"
|
||||
ALGORITHM: str = "HS256"
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES: int = 0
|
||||
REFRESH_TOKEN_EXPIRE_DAYS: int = 0
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES: int = 60
|
||||
REFRESH_TOKEN_EXPIRE_DAYS: int = 7
|
||||
|
||||
SEED_DEFAULT_DEV_USERS: Optional[bool] = None
|
||||
INITIAL_ADMIN_USERNAME: str = ""
|
||||
INITIAL_ADMIN_EMAIL: str = ""
|
||||
INITIAL_ADMIN_PASSWORD: str = ""
|
||||
SETTINGS_ENCRYPTION_KEY: str = ""
|
||||
|
||||
LOGIN_RATE_LIMIT_MAX_ATTEMPTS: int = 10
|
||||
LOGIN_RATE_LIMIT_WINDOW_SECONDS: int = 300
|
||||
|
||||
POSTGRES_SERVER: str = "localhost"
|
||||
POSTGRES_USER: str = "postgres"
|
||||
POSTGRES_PASSWORD: str = "postgres"
|
||||
POSTGRES_DB: str = "planet_db"
|
||||
DATABASE_URL: str = f"postgresql+asyncpg://postgres:postgres@localhost:5432/planet_db"
|
||||
DATABASE_URL: str = "postgresql+asyncpg://postgres:postgres@localhost:5432/planet_db"
|
||||
|
||||
REDIS_SERVER: str = "localhost"
|
||||
REDIS_PORT: int = 6379
|
||||
REDIS_DB: int = 0
|
||||
REDIS_PASSWORD: str = ""
|
||||
|
||||
CORS_ORIGINS: List[str] = ["http://localhost:3000", "http://localhost:8000"]
|
||||
CORS_ORIGINS: List[str] = [
|
||||
"http://localhost:3000",
|
||||
"http://127.0.0.1:3000",
|
||||
"http://localhost:8000",
|
||||
"http://127.0.0.1:8000",
|
||||
"planet://earth",
|
||||
]
|
||||
|
||||
COLLECTOR_MAX_CONCURRENCY: int = 2
|
||||
COLLECTOR_HEAVY_CONCURRENCY: int = 1
|
||||
|
||||
SPACETRACK_USERNAME: str = ""
|
||||
SPACETRACK_PASSWORD: str = ""
|
||||
@@ -43,11 +87,53 @@ class Settings(BaseSettings):
|
||||
AI_PROVIDER_RETRY_ATTEMPTS: int = 2
|
||||
OBSERVABILITY_INGEST_TOKEN: str = ""
|
||||
|
||||
CLIENT_UPDATES_DIR: str = ""
|
||||
CLIENT_UPDATE_PUBLISH_TOKEN: str = ""
|
||||
CLIENT_MIN_SHELL_VERSION: str = "0.78.0"
|
||||
CLIENT_RELEASE_PAGE_URL: str = "https://gitea.rclaw.top/linkong/planet/releases"
|
||||
|
||||
@property
|
||||
def is_production(self) -> bool:
|
||||
return str(self.APP_ENV or "").strip().lower() == "production"
|
||||
|
||||
@property
|
||||
def normalized_role(self) -> str:
|
||||
role = str(self.PLANET_ROLE or "all").strip().lower()
|
||||
return role if role in VALID_PLANET_ROLES else "all"
|
||||
|
||||
@property
|
||||
def should_run_scheduler(self) -> bool:
|
||||
if self.ENABLE_SCHEDULER is not None:
|
||||
return bool(self.ENABLE_SCHEDULER)
|
||||
return self.normalized_role in {"all", "worker"}
|
||||
|
||||
@property
|
||||
def should_run_workers(self) -> bool:
|
||||
return self.normalized_role in {"all", "worker"}
|
||||
|
||||
@property
|
||||
def should_seed_default_dev_users(self) -> bool:
|
||||
if self.SEED_DEFAULT_DEV_USERS is not None:
|
||||
return bool(self.SEED_DEFAULT_DEV_USERS)
|
||||
return not self.is_production
|
||||
|
||||
@property
|
||||
def REDIS_URL(self) -> str:
|
||||
return os.getenv(
|
||||
"REDIS_URL", f"redis://{self.REDIS_SERVER}:{self.REDIS_PORT}/{self.REDIS_DB}"
|
||||
raw = os.getenv(
|
||||
"REDIS_URL",
|
||||
f"redis://{self.REDIS_SERVER}:{self.REDIS_PORT}/{self.REDIS_DB}",
|
||||
)
|
||||
password = str(self.REDIS_PASSWORD or "")
|
||||
if password:
|
||||
parsed = urlsplit(raw)
|
||||
if parsed.scheme in {"redis", "rediss"} and parsed.password is None and parsed.hostname:
|
||||
user_part = parsed.username or ""
|
||||
encoded_pw = quote(password, safe="")
|
||||
netloc = f"{user_part}:{encoded_pw}@{parsed.hostname}"
|
||||
if parsed.port:
|
||||
netloc = f"{netloc}:{parsed.port}"
|
||||
return urlunsplit((parsed.scheme, netloc, parsed.path, parsed.query, parsed.fragment))
|
||||
return raw
|
||||
|
||||
class Config:
|
||||
env_file = Path(__file__).parent.parent.parent / ".env"
|
||||
@@ -55,6 +141,42 @@ class Settings(BaseSettings):
|
||||
extra = "ignore"
|
||||
|
||||
|
||||
def validate_production_security(cfg: Settings) -> None:
|
||||
"""Fail fast on insecure defaults when APP_ENV=production."""
|
||||
raw_role = str(cfg.PLANET_ROLE or "all").strip().lower()
|
||||
if raw_role not in VALID_PLANET_ROLES:
|
||||
raise RuntimeError(
|
||||
f"Invalid PLANET_ROLE={cfg.PLANET_ROLE!r}; expected one of {sorted(VALID_PLANET_ROLES)}"
|
||||
)
|
||||
|
||||
if not cfg.is_production:
|
||||
return
|
||||
|
||||
errors: list[str] = []
|
||||
secret_key = str(cfg.SECRET_KEY or "").strip()
|
||||
if secret_key in WEAK_SECRET_PLACEHOLDERS or len(secret_key) < 32:
|
||||
errors.append("SECRET_KEY must be set to a random string of at least 32 characters")
|
||||
|
||||
if int(cfg.ACCESS_TOKEN_EXPIRE_MINUTES) <= 0:
|
||||
errors.append("ACCESS_TOKEN_EXPIRE_MINUTES must be > 0 in production")
|
||||
|
||||
if int(cfg.REFRESH_TOKEN_EXPIRE_DAYS) <= 0:
|
||||
errors.append("REFRESH_TOKEN_EXPIRE_DAYS must be > 0 in production")
|
||||
|
||||
if "*" in (cfg.CORS_ORIGINS or []):
|
||||
errors.append("CORS_ORIGINS must not contain '*' in production")
|
||||
|
||||
ai_url = str(cfg.AI_PROVIDER_SERVICE_URL or "").strip()
|
||||
ai_token = str(cfg.AI_PROVIDER_SERVICE_TOKEN or "").strip()
|
||||
if ai_url and ai_token in WEAK_SERVICE_TOKEN_PLACEHOLDERS:
|
||||
errors.append(
|
||||
"AI_PROVIDER_SERVICE_TOKEN must be configured (not empty or placeholder) in production"
|
||||
)
|
||||
|
||||
if errors:
|
||||
raise RuntimeError("Production security validation failed: " + "; ".join(errors))
|
||||
|
||||
|
||||
@lru_cache()
|
||||
def get_settings() -> Settings:
|
||||
return Settings()
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
"""Symmetric encryption helpers for persisted sensitive settings."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
from copy import deepcopy
|
||||
import hashlib
|
||||
from typing import Any
|
||||
|
||||
from cryptography.fernet import Fernet, InvalidToken
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.logging import get_logger
|
||||
|
||||
logger = get_logger(__name__, service="secret_crypto")
|
||||
|
||||
ENCRYPTED_PREFIX = "enc:v1:"
|
||||
ENCRYPTED_CATEGORIES = frozenset({"smtp", "external_integrations"})
|
||||
SECRET_FIELD_NAMES = frozenset(
|
||||
{
|
||||
"api_key",
|
||||
"service_token",
|
||||
"client_secret",
|
||||
"password",
|
||||
"token",
|
||||
"access_token",
|
||||
"bearer_token",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _derive_fernet_key(raw_key: str) -> bytes:
|
||||
cleaned = raw_key.strip()
|
||||
candidate = cleaned.encode("utf-8")
|
||||
try:
|
||||
Fernet(candidate)
|
||||
return candidate
|
||||
except Exception:
|
||||
digest = hashlib.sha256(candidate).digest()
|
||||
return base64.urlsafe_b64encode(digest)
|
||||
|
||||
|
||||
def _get_fernet() -> Fernet | None:
|
||||
raw_key = str(getattr(settings, "SETTINGS_ENCRYPTION_KEY", "") or "").strip()
|
||||
if not raw_key:
|
||||
return None
|
||||
return Fernet(_derive_fernet_key(raw_key))
|
||||
|
||||
|
||||
def encrypt_secret(value: str) -> str:
|
||||
"""Encrypt a secret string when SETTINGS_ENCRYPTION_KEY is configured."""
|
||||
if not value or value.startswith(ENCRYPTED_PREFIX):
|
||||
return value
|
||||
fernet = _get_fernet()
|
||||
if fernet is None:
|
||||
return value
|
||||
token = fernet.encrypt(value.encode("utf-8")).decode("ascii")
|
||||
return f"{ENCRYPTED_PREFIX}{token}"
|
||||
|
||||
|
||||
def decrypt_secret(value: str) -> str:
|
||||
"""Decrypt a secret string; transparently passes through legacy plaintext."""
|
||||
if not value or not value.startswith(ENCRYPTED_PREFIX):
|
||||
return value
|
||||
fernet = _get_fernet()
|
||||
if fernet is None:
|
||||
logger.warning_event(
|
||||
"Encrypted setting encountered without SETTINGS_ENCRYPTION_KEY configured",
|
||||
event="settings.secret.key_missing",
|
||||
)
|
||||
return ""
|
||||
ciphertext = value[len(ENCRYPTED_PREFIX) :].encode("ascii")
|
||||
try:
|
||||
return fernet.decrypt(ciphertext).decode("utf-8")
|
||||
except (InvalidToken, ValueError):
|
||||
logger.warning_event(
|
||||
"Failed to decrypt persisted setting secret",
|
||||
event="settings.secret.decrypt_failed",
|
||||
)
|
||||
return ""
|
||||
|
||||
|
||||
def _transform_payload(value: Any, *, encrypt: bool) -> Any:
|
||||
if isinstance(value, dict):
|
||||
transformed: dict[str, Any] = {}
|
||||
for key, item in value.items():
|
||||
if key in SECRET_FIELD_NAMES and isinstance(item, str):
|
||||
transformed[key] = encrypt_secret(item) if encrypt else decrypt_secret(item)
|
||||
else:
|
||||
transformed[key] = _transform_payload(item, encrypt=encrypt)
|
||||
return transformed
|
||||
if isinstance(value, list):
|
||||
return [_transform_payload(item, encrypt=encrypt) for item in value]
|
||||
return value
|
||||
|
||||
|
||||
def encrypt_setting_payload(category: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Return a deep copy of payload with sensitive fields encrypted if enabled."""
|
||||
copied = deepcopy(payload)
|
||||
if category not in ENCRYPTED_CATEGORIES:
|
||||
return copied
|
||||
return _transform_payload(copied, encrypt=True)
|
||||
|
||||
|
||||
def decrypt_setting_payload(category: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Return a deep copy of payload with encrypted sensitive fields decrypted."""
|
||||
copied = deepcopy(payload)
|
||||
if category not in ENCRYPTED_CATEGORIES:
|
||||
return copied
|
||||
return _transform_payload(copied, encrypt=False)
|
||||
@@ -1,20 +1,32 @@
|
||||
import asyncio
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import Optional
|
||||
import hashlib
|
||||
import time
|
||||
from typing import Any, Optional
|
||||
from uuid import uuid4
|
||||
|
||||
import bcrypt
|
||||
import redis
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
from jose import JWTError, jwt
|
||||
import redis
|
||||
import redis.asyncio as aioredis
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.logging import get_logger
|
||||
from app.db.session import get_db
|
||||
from app.models.user import User
|
||||
|
||||
logger = get_logger(__name__, service="security")
|
||||
oauth2_scheme = HTTPBearer()
|
||||
|
||||
REVOKED_KEY_PREFIX = "revoked_jwt:"
|
||||
LOCAL_REVOKED_MAX_ENTRIES = 10_000
|
||||
REDIS_OP_TIMEOUT_SECONDS = 1.5
|
||||
_LOCAL_REVOKED_TOKENS: dict[str, float] = {}
|
||||
|
||||
|
||||
class _RedisClient:
|
||||
_client = None
|
||||
@@ -23,7 +35,7 @@ class _RedisClient:
|
||||
def get_client(cls):
|
||||
if cls._client is None:
|
||||
redis_url = settings.REDIS_URL
|
||||
if redis_url.startswith("redis://"):
|
||||
if redis_url.startswith(("redis://", "rediss://")):
|
||||
cls._client = redis.from_url(
|
||||
redis_url,
|
||||
decode_responses=True,
|
||||
@@ -35,6 +47,7 @@ class _RedisClient:
|
||||
host=settings.REDIS_SERVER,
|
||||
port=settings.REDIS_PORT,
|
||||
db=settings.REDIS_DB,
|
||||
password=settings.REDIS_PASSWORD or None,
|
||||
decode_responses=True,
|
||||
socket_connect_timeout=2,
|
||||
socket_timeout=2,
|
||||
@@ -42,9 +55,95 @@ class _RedisClient:
|
||||
return cls._client
|
||||
|
||||
|
||||
class _AsyncRedisClient:
|
||||
_client: aioredis.Redis | None = None
|
||||
_loop: asyncio.AbstractEventLoop | None = None
|
||||
|
||||
@classmethod
|
||||
def get_client(cls) -> aioredis.Redis:
|
||||
loop = asyncio.get_running_loop()
|
||||
if cls._client is None or cls._loop is not loop:
|
||||
redis_url = settings.REDIS_URL
|
||||
if redis_url.startswith(("redis://", "rediss://")):
|
||||
cls._client = aioredis.from_url(
|
||||
redis_url,
|
||||
decode_responses=True,
|
||||
socket_connect_timeout=1.5,
|
||||
socket_timeout=1.5,
|
||||
)
|
||||
else:
|
||||
cls._client = aioredis.Redis(
|
||||
host=settings.REDIS_SERVER,
|
||||
port=settings.REDIS_PORT,
|
||||
db=settings.REDIS_DB,
|
||||
password=settings.REDIS_PASSWORD or None,
|
||||
decode_responses=True,
|
||||
socket_connect_timeout=1.5,
|
||||
socket_timeout=1.5,
|
||||
)
|
||||
cls._loop = loop
|
||||
return cls._client
|
||||
|
||||
|
||||
redis_client = _RedisClient.get_client()
|
||||
|
||||
|
||||
def _token_digest(token: str) -> str:
|
||||
return hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def _prune_local_revocations(now: float | None = None) -> None:
|
||||
current = now if now is not None else time.monotonic()
|
||||
expired = [key for key, deadline in _LOCAL_REVOKED_TOKENS.items() if deadline <= current]
|
||||
for key in expired:
|
||||
_LOCAL_REVOKED_TOKENS.pop(key, None)
|
||||
while len(_LOCAL_REVOKED_TOKENS) > LOCAL_REVOKED_MAX_ENTRIES:
|
||||
oldest_key = next(iter(_LOCAL_REVOKED_TOKENS))
|
||||
_LOCAL_REVOKED_TOKENS.pop(oldest_key, None)
|
||||
|
||||
|
||||
def _record_local_revocation(token_digest: str, ttl_seconds: int) -> None:
|
||||
now = time.monotonic()
|
||||
_prune_local_revocations(now)
|
||||
_LOCAL_REVOKED_TOKENS[token_digest] = now + max(60, ttl_seconds)
|
||||
|
||||
|
||||
def _is_locally_revoked(token_digest: str) -> bool:
|
||||
now = time.monotonic()
|
||||
deadline = _LOCAL_REVOKED_TOKENS.get(token_digest)
|
||||
if deadline is None:
|
||||
return False
|
||||
if deadline <= now:
|
||||
_LOCAL_REVOKED_TOKENS.pop(token_digest, None)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _is_monkeypatched_sync_redis(candidate: Any) -> bool:
|
||||
if candidate is None:
|
||||
return False
|
||||
if not isinstance(candidate, redis.Redis):
|
||||
return True
|
||||
return "sismember" in getattr(candidate, "__dict__", {})
|
||||
|
||||
|
||||
def _token_revocation_ttl_seconds(
|
||||
token: str,
|
||||
default_ttl: int | None = None,
|
||||
*,
|
||||
decoded_payload: dict[str, Any] | None = None,
|
||||
) -> int:
|
||||
fallback = default_ttl if default_ttl is not None else max(settings.REFRESH_TOKEN_EXPIRE_DAYS, 7) * 86400
|
||||
payload = decoded_payload if decoded_payload is not None else decode_token(token)
|
||||
if payload and payload.get("exp") is not None:
|
||||
try:
|
||||
remaining = int(float(payload["exp"]) - datetime.now(UTC).timestamp())
|
||||
return max(60, remaining)
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
return max(60, int(fallback))
|
||||
|
||||
|
||||
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
||||
return bcrypt.checkpw(plain_password.encode(), hashed_password.encode())
|
||||
|
||||
@@ -63,7 +162,7 @@ def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -
|
||||
expire = None
|
||||
if expire:
|
||||
to_encode.update({"exp": expire})
|
||||
to_encode.update({"type": "access"})
|
||||
to_encode.update({"type": "access", "jti": uuid4().hex})
|
||||
if "sub" in to_encode:
|
||||
to_encode["sub"] = str(to_encode["sub"])
|
||||
return jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
|
||||
@@ -74,7 +173,7 @@ def create_refresh_token(data: dict) -> str:
|
||||
if settings.REFRESH_TOKEN_EXPIRE_DAYS > 0:
|
||||
expire = datetime.now(UTC) + timedelta(days=settings.REFRESH_TOKEN_EXPIRE_DAYS)
|
||||
to_encode.update({"exp": expire})
|
||||
to_encode.update({"type": "refresh"})
|
||||
to_encode.update({"type": "refresh", "jti": uuid4().hex})
|
||||
if "sub" in to_encode:
|
||||
to_encode["sub"] = str(to_encode["sub"])
|
||||
return jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
|
||||
@@ -88,6 +187,76 @@ def decode_token(token: str) -> Optional[dict]:
|
||||
return None
|
||||
|
||||
|
||||
async def revoke_token(token: str, *, ttl_seconds: int | None = None) -> None:
|
||||
"""Revoke a verified, unexpired JWT in Redis with bounded TTL plus local fallback."""
|
||||
if not token:
|
||||
return
|
||||
payload = decode_token(token)
|
||||
if payload is None:
|
||||
return
|
||||
digest = _token_digest(token)
|
||||
ttl = _token_revocation_ttl_seconds(
|
||||
token,
|
||||
default_ttl=ttl_seconds,
|
||||
decoded_payload=payload,
|
||||
)
|
||||
_record_local_revocation(digest, ttl)
|
||||
try:
|
||||
client = _AsyncRedisClient.get_client()
|
||||
await asyncio.wait_for(
|
||||
client.set(f"{REVOKED_KEY_PREFIX}{digest}", "1", ex=ttl),
|
||||
timeout=REDIS_OP_TIMEOUT_SECONDS,
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed to persist revoked token to Redis; kept in local revocation cache",
|
||||
event="auth.redis_revoke.unavailable",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
|
||||
|
||||
async def is_token_blacklisted(token: str, *, legacy_sync_client: Any = None) -> bool:
|
||||
"""Check whether a JWT was revoked without blocking the event loop or failing 500 on Redis outage."""
|
||||
if not token:
|
||||
return False
|
||||
digest = _token_digest(token)
|
||||
if _is_locally_revoked(digest):
|
||||
return True
|
||||
|
||||
for candidate in (legacy_sync_client, redis_client):
|
||||
if _is_monkeypatched_sync_redis(candidate):
|
||||
try:
|
||||
return bool(candidate.sismember("blacklisted_tokens", token))
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Sync token blacklist check failed; degrading safely",
|
||||
event="auth.redis_blacklist.sync_unavailable",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
return False
|
||||
|
||||
try:
|
||||
client = _AsyncRedisClient.get_client()
|
||||
if await asyncio.wait_for(
|
||||
client.exists(f"{REVOKED_KEY_PREFIX}{digest}"),
|
||||
timeout=REDIS_OP_TIMEOUT_SECONDS,
|
||||
):
|
||||
return True
|
||||
return bool(
|
||||
await asyncio.wait_for(
|
||||
client.sismember("blacklisted_tokens", token),
|
||||
timeout=REDIS_OP_TIMEOUT_SECONDS,
|
||||
)
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Async token blacklist check failed; degrading safely",
|
||||
event="auth.redis_blacklist.unavailable",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
return False
|
||||
|
||||
|
||||
async def _load_active_user(user_id: str, db: AsyncSession) -> User:
|
||||
try:
|
||||
parsed_id = int(user_id)
|
||||
@@ -108,7 +277,7 @@ async def get_current_user(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> User:
|
||||
token = credentials.credentials
|
||||
if redis_client.sismember("blacklisted_tokens", token):
|
||||
if await is_token_blacklisted(token):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Token has been revoked",
|
||||
@@ -133,6 +302,11 @@ async def get_current_user_refresh(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> User:
|
||||
token = credentials.credentials
|
||||
if await is_token_blacklisted(token):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Token has been revoked",
|
||||
)
|
||||
payload = decode_token(token)
|
||||
if payload is None or payload.get("type") != "refresh":
|
||||
raise HTTPException(
|
||||
@@ -149,4 +323,20 @@ async def get_current_user_refresh(
|
||||
|
||||
|
||||
def blacklist_token(token: str) -> None:
|
||||
redis_client.sadd("blacklisted_tokens", token)
|
||||
"""Best-effort revocation helper for legacy synchronous callers."""
|
||||
if not token:
|
||||
return
|
||||
payload = decode_token(token)
|
||||
if payload is None:
|
||||
return
|
||||
digest = _token_digest(token)
|
||||
ttl = _token_revocation_ttl_seconds(token, decoded_payload=payload)
|
||||
_record_local_revocation(digest, ttl)
|
||||
try:
|
||||
redis_client.set(f"{REVOKED_KEY_PREFIX}{digest}", "1", ex=ttl)
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed to write sync token revocation to Redis",
|
||||
event="auth.redis_revoke.sync_unavailable",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
@@ -24,32 +24,124 @@ class DataBroadcaster:
|
||||
self._vessel_flush_interval = 1.0
|
||||
|
||||
async def get_dashboard_stats(self) -> Dict[str, Any]:
|
||||
"""Get dashboard statistics"""
|
||||
return {
|
||||
"total_datasources": 9,
|
||||
"active_datasources": 8,
|
||||
"tasks_today": 45,
|
||||
"success_rate": 97.8,
|
||||
"last_updated": to_iso8601_utc(datetime.now(UTC)),
|
||||
"alerts": {"critical": 0, "warning": 2, "info": 5},
|
||||
"""Get dashboard statistics from PostgreSQL."""
|
||||
from sqlalchemy import func, select
|
||||
|
||||
from app.core.enums import AlertSeverity, AlertStatus, JobStatus
|
||||
from app.db.session import async_session_factory
|
||||
from app.models.alert import Alert
|
||||
from app.models.datasource import DataSource
|
||||
from app.models.task import CollectionTask
|
||||
|
||||
alerts_summary = {
|
||||
AlertSeverity.CRITICAL.value: 0,
|
||||
AlertSeverity.WARNING.value: 0,
|
||||
AlertSeverity.INFO.value: 0,
|
||||
}
|
||||
now_utc = datetime.now(UTC)
|
||||
today_start = now_utc.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
|
||||
try:
|
||||
async with async_session_factory() as db:
|
||||
total_datasources = int(
|
||||
(await db.scalar(select(func.count(DataSource.id)))) or 0
|
||||
)
|
||||
active_datasources = int(
|
||||
(
|
||||
await db.scalar(
|
||||
select(func.count(DataSource.id)).where(DataSource.is_active.is_(True))
|
||||
)
|
||||
)
|
||||
or 0
|
||||
)
|
||||
tasks_today = int(
|
||||
(
|
||||
await db.scalar(
|
||||
select(func.count(CollectionTask.id)).where(
|
||||
CollectionTask.created_at >= today_start
|
||||
)
|
||||
)
|
||||
)
|
||||
or 0
|
||||
)
|
||||
finished_rows = (
|
||||
await db.execute(
|
||||
select(CollectionTask.status, func.count(CollectionTask.id))
|
||||
.where(
|
||||
CollectionTask.created_at >= today_start,
|
||||
CollectionTask.status.in_(
|
||||
[JobStatus.SUCCESS.value, JobStatus.FAILED.value]
|
||||
),
|
||||
)
|
||||
.group_by(CollectionTask.status)
|
||||
)
|
||||
).all()
|
||||
finished_counts = {str(status): int(count) for status, count in finished_rows}
|
||||
success_count = finished_counts.get(JobStatus.SUCCESS.value, 0)
|
||||
total_finished = success_count + finished_counts.get(JobStatus.FAILED.value, 0)
|
||||
success_rate = (
|
||||
round(success_count * 100.0 / total_finished, 1)
|
||||
if total_finished > 0
|
||||
else 100.0
|
||||
)
|
||||
|
||||
alert_rows = (
|
||||
await db.execute(
|
||||
select(Alert.severity, func.count(Alert.id))
|
||||
.where(Alert.status == AlertStatus.ACTIVE)
|
||||
.group_by(Alert.severity)
|
||||
)
|
||||
).all()
|
||||
for severity, count in alert_rows:
|
||||
key = severity.value if hasattr(severity, "value") else str(severity).lower()
|
||||
if key in alerts_summary:
|
||||
alerts_summary[key] = int(count)
|
||||
|
||||
return {
|
||||
"total_datasources": total_datasources,
|
||||
"active_datasources": active_datasources,
|
||||
"tasks_today": tasks_today,
|
||||
"success_rate": success_rate,
|
||||
"last_updated": to_iso8601_utc(now_utc),
|
||||
"alerts": alerts_summary,
|
||||
}
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed to query dashboard stats; returning empty fallback",
|
||||
event="dashboard.stats.query_failed",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
return {
|
||||
"total_datasources": 0,
|
||||
"active_datasources": 0,
|
||||
"tasks_today": 0,
|
||||
"success_rate": 100.0,
|
||||
"last_updated": to_iso8601_utc(now_utc),
|
||||
"alerts": alerts_summary,
|
||||
}
|
||||
|
||||
async def broadcast_stats(self, interval: int = 5):
|
||||
"""Broadcast dashboard stats periodically"""
|
||||
"""Broadcast dashboard stats periodically only when subscribers are attached."""
|
||||
while self.running:
|
||||
try:
|
||||
stats = await self.get_dashboard_stats()
|
||||
await manager.broadcast(
|
||||
{
|
||||
"type": "data_frame",
|
||||
"channel": "dashboard",
|
||||
"timestamp": to_iso8601_utc(datetime.now(UTC)),
|
||||
"payload": {"stats": stats},
|
||||
},
|
||||
channel="dashboard",
|
||||
if manager.channel_subscriptions.get("dashboard"):
|
||||
stats = await self.get_dashboard_stats()
|
||||
await manager.broadcast(
|
||||
{
|
||||
"type": "data_frame",
|
||||
"channel": "dashboard",
|
||||
"timestamp": to_iso8601_utc(datetime.now(UTC)),
|
||||
"payload": {"stats": stats},
|
||||
},
|
||||
channel="dashboard",
|
||||
publish=False,
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed to broadcast dashboard stats",
|
||||
event="dashboard.stats.broadcast_failed",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
await asyncio.sleep(interval)
|
||||
|
||||
async def broadcast_alert(self, alert: Dict[str, Any]):
|
||||
|
||||
@@ -1,26 +1,150 @@
|
||||
"""WebSocket Connection Manager"""
|
||||
"""WebSocket Connection Manager with optional cross-replica Redis Pub/Sub relay."""
|
||||
|
||||
import asyncio
|
||||
from contextlib import suppress
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any, Dict, Set, Optional
|
||||
import json
|
||||
from typing import Any, Dict, Optional, Set
|
||||
from uuid import uuid4
|
||||
|
||||
from fastapi import WebSocket
|
||||
import redis.asyncio as redis
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.logging import get_logger
|
||||
|
||||
logger = get_logger(__name__, service="websocket")
|
||||
|
||||
MAX_VESSEL_SUBSCRIPTION_LIMIT = 5000
|
||||
MAX_VESSEL_WS_MESSAGE_ITEMS = 1000
|
||||
MAX_VESSEL_BBOX_AREA = 2500.0
|
||||
PLANET_WS_PUBSUB_CHANNEL = "planet:ws:broadcast"
|
||||
|
||||
|
||||
def _create_async_redis_client(*, socket_timeout: float = 2.0) -> redis.Redis:
|
||||
redis_url = settings.REDIS_URL
|
||||
if redis_url.startswith(("redis://", "rediss://")):
|
||||
return redis.from_url(
|
||||
redis_url,
|
||||
decode_responses=True,
|
||||
socket_connect_timeout=2.0,
|
||||
socket_timeout=socket_timeout,
|
||||
)
|
||||
return redis.Redis(
|
||||
host=settings.REDIS_SERVER,
|
||||
port=settings.REDIS_PORT,
|
||||
db=settings.REDIS_DB,
|
||||
password=settings.REDIS_PASSWORD or None,
|
||||
decode_responses=True,
|
||||
socket_connect_timeout=2.0,
|
||||
socket_timeout=socket_timeout,
|
||||
)
|
||||
|
||||
|
||||
class ConnectionManager:
|
||||
"""Manages WebSocket connections"""
|
||||
"""Manages WebSocket connections and cross-replica Pub/Sub fanout."""
|
||||
|
||||
def __init__(self):
|
||||
self.active_connections: Dict[str, Set[WebSocket]] = {} # user_id -> connections
|
||||
self.active_connections: Dict[str, Set[WebSocket]] = {}
|
||||
self.channel_subscriptions: Dict[str, Set[WebSocket]] = {}
|
||||
self.websocket_channels: Dict[WebSocket, Set[str]] = {}
|
||||
self.vessel_subscriptions: Dict[WebSocket, dict[str, Any]] = {}
|
||||
self.redis_client: Optional[redis.Redis] = None
|
||||
self.instance_id: str = uuid4().hex[:12]
|
||||
self._pubsub_enabled: bool = False
|
||||
self._pubsub_publish_only: bool = False
|
||||
self._pubsub_task: Optional[asyncio.Task[Any]] = None
|
||||
self._pubsub_client: Optional[redis.Redis] = None
|
||||
|
||||
async def start_pubsub(self, *, publish_only: bool = False) -> None:
|
||||
self._pubsub_enabled = True
|
||||
self._pubsub_publish_only = publish_only
|
||||
if not publish_only and (self._pubsub_task is None or self._pubsub_task.done()):
|
||||
self._pubsub_task = asyncio.create_task(self._pubsub_loop())
|
||||
|
||||
async def stop_pubsub(self) -> None:
|
||||
self._pubsub_enabled = False
|
||||
task = self._pubsub_task
|
||||
self._pubsub_task = None
|
||||
if task is not None:
|
||||
task.cancel()
|
||||
with suppress(asyncio.CancelledError):
|
||||
await task
|
||||
if self._pubsub_client is not None:
|
||||
with suppress(Exception):
|
||||
await self._pubsub_client.aclose()
|
||||
self._pubsub_client = None
|
||||
|
||||
async def _publish_pubsub_envelope(self, envelope: dict[str, Any]) -> None:
|
||||
if not self._pubsub_enabled:
|
||||
return
|
||||
try:
|
||||
if self._pubsub_client is None:
|
||||
self._pubsub_client = _create_async_redis_client(socket_timeout=2.0)
|
||||
payload = json.dumps({"origin": self.instance_id, **envelope}, default=str)
|
||||
await self._pubsub_client.publish(PLANET_WS_PUBSUB_CHANNEL, payload)
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed to publish WebSocket broadcast to Redis Pub/Sub",
|
||||
event="websocket.pubsub.publish_failed",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
|
||||
async def handle_pubsub_payload(self, raw_payload: str | bytes) -> bool:
|
||||
text = raw_payload.decode("utf-8") if isinstance(raw_payload, bytes) else str(raw_payload)
|
||||
try:
|
||||
envelope = json.loads(text)
|
||||
except json.JSONDecodeError:
|
||||
return False
|
||||
if not isinstance(envelope, dict):
|
||||
return False
|
||||
if envelope.get("origin") == self.instance_id:
|
||||
return False
|
||||
|
||||
kind = envelope.get("kind")
|
||||
if kind == "channel" and isinstance(envelope.get("message"), dict):
|
||||
await self._deliver_local_broadcast(
|
||||
envelope["message"],
|
||||
channel=str(envelope.get("channel") or "all"),
|
||||
)
|
||||
return True
|
||||
if kind == "vessels" and isinstance(envelope.get("data"), dict):
|
||||
await self._deliver_local_vessels(envelope["data"])
|
||||
return True
|
||||
return False
|
||||
|
||||
async def _pubsub_loop(self) -> None:
|
||||
while self._pubsub_enabled and not self._pubsub_publish_only:
|
||||
client: Optional[redis.Redis] = None
|
||||
pubsub = None
|
||||
try:
|
||||
client = _create_async_redis_client(socket_timeout=5.0)
|
||||
pubsub = client.pubsub()
|
||||
await pubsub.subscribe(PLANET_WS_PUBSUB_CHANNEL)
|
||||
while self._pubsub_enabled and not self._pubsub_publish_only:
|
||||
message = await pubsub.get_message(
|
||||
ignore_subscribe_messages=True,
|
||||
timeout=1.0,
|
||||
)
|
||||
if message and message.get("data") is not None:
|
||||
await self.handle_pubsub_payload(message["data"])
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"WebSocket Redis Pub/Sub listener reconnecting after error",
|
||||
event="websocket.pubsub.listener_error",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
await asyncio.sleep(2.0)
|
||||
finally:
|
||||
if pubsub is not None:
|
||||
with suppress(Exception):
|
||||
await pubsub.unsubscribe(PLANET_WS_PUBSUB_CHANNEL)
|
||||
await pubsub.aclose()
|
||||
if client is not None:
|
||||
with suppress(Exception):
|
||||
await client.aclose()
|
||||
|
||||
async def connect(self, websocket: WebSocket, user_id: str):
|
||||
await websocket.accept()
|
||||
@@ -29,16 +153,7 @@ class ConnectionManager:
|
||||
self.active_connections[user_id].add(websocket)
|
||||
|
||||
if self.redis_client is None:
|
||||
redis_url = settings.REDIS_URL
|
||||
if redis_url.startswith("redis://"):
|
||||
self.redis_client = redis.from_url(redis_url, decode_responses=True)
|
||||
else:
|
||||
self.redis_client = redis.Redis(
|
||||
host=settings.REDIS_SERVER,
|
||||
port=settings.REDIS_PORT,
|
||||
db=settings.REDIS_DB,
|
||||
decode_responses=True,
|
||||
)
|
||||
self.redis_client = _create_async_redis_client(socket_timeout=2.0)
|
||||
|
||||
def disconnect(self, websocket: WebSocket, user_id: str):
|
||||
if user_id in self.active_connections:
|
||||
@@ -129,15 +244,15 @@ class ConnectionManager:
|
||||
|
||||
async def send_personal_message(self, message: dict, user_id: str):
|
||||
if user_id in self.active_connections:
|
||||
for connection in self.active_connections[user_id]:
|
||||
for connection in list(self.active_connections[user_id]):
|
||||
try:
|
||||
await connection.send_json(message)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
async def broadcast(self, message: dict, channel: str = "all"):
|
||||
async def _deliver_local_broadcast(self, message: dict, channel: str = "all") -> None:
|
||||
if channel == "all":
|
||||
for user_id in self.active_connections:
|
||||
for user_id in list(self.active_connections):
|
||||
await self.send_personal_message(message, user_id)
|
||||
else:
|
||||
for connection in list(self.channel_subscriptions.get(channel, set())):
|
||||
@@ -146,7 +261,14 @@ class ConnectionManager:
|
||||
except Exception:
|
||||
self.unsubscribe_all(connection)
|
||||
|
||||
async def broadcast_vessels(self, data: dict[str, Any]):
|
||||
async def broadcast(self, message: dict, channel: str = "all", *, publish: bool = True):
|
||||
await self._deliver_local_broadcast(message, channel=channel)
|
||||
if publish:
|
||||
await self._publish_pubsub_envelope(
|
||||
{"kind": "channel", "channel": channel, "message": message}
|
||||
)
|
||||
|
||||
async def _deliver_local_vessels(self, data: dict[str, Any]) -> None:
|
||||
vessels = data.get("vessels") if isinstance(data, dict) else None
|
||||
if not isinstance(vessels, list) or not vessels:
|
||||
return
|
||||
@@ -158,7 +280,7 @@ class ConnectionManager:
|
||||
if self._vessel_matches_subscription(vessel, subscription)
|
||||
]
|
||||
if subscription.get("scope") != "global":
|
||||
matched = matched[:subscription["limit"]]
|
||||
matched = matched[: subscription["limit"]]
|
||||
if not matched:
|
||||
continue
|
||||
subscription["last_sent_at"] = datetime.now(UTC)
|
||||
@@ -179,16 +301,25 @@ class ConnectionManager:
|
||||
}
|
||||
try:
|
||||
for offset in range(0, len(matched), MAX_VESSEL_WS_MESSAGE_ITEMS):
|
||||
await connection.send_json({
|
||||
**message,
|
||||
"payload": {
|
||||
**message["payload"],
|
||||
"vessels": matched[offset:offset + MAX_VESSEL_WS_MESSAGE_ITEMS],
|
||||
},
|
||||
})
|
||||
await connection.send_json(
|
||||
{
|
||||
**message,
|
||||
"payload": {
|
||||
**message["payload"],
|
||||
"vessels": matched[offset : offset + MAX_VESSEL_WS_MESSAGE_ITEMS],
|
||||
},
|
||||
}
|
||||
)
|
||||
except Exception:
|
||||
self.unsubscribe_all(connection)
|
||||
|
||||
async def broadcast_vessels(self, data: dict[str, Any]):
|
||||
vessels = data.get("vessels") if isinstance(data, dict) else None
|
||||
if not isinstance(vessels, list) or not vessels:
|
||||
return
|
||||
await self._deliver_local_vessels(data)
|
||||
await self._publish_pubsub_envelope({"kind": "vessels", "data": data})
|
||||
|
||||
def _vessel_matches_subscription(
|
||||
self,
|
||||
vessel: dict[str, Any],
|
||||
@@ -211,9 +342,11 @@ class ConnectionManager:
|
||||
return any(requested_type in type_name for requested_type in requested_types)
|
||||
|
||||
async def close_all(self):
|
||||
for user_id in self.active_connections:
|
||||
for connection in self.active_connections[user_id]:
|
||||
await connection.close()
|
||||
await self.stop_pubsub()
|
||||
for user_id in list(self.active_connections):
|
||||
for connection in list(self.active_connections[user_id]):
|
||||
with suppress(Exception):
|
||||
await connection.close()
|
||||
self.active_connections.clear()
|
||||
self.channel_subscriptions.clear()
|
||||
self.websocket_channels.clear()
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
"""Baseline schema migration matching Base.metadata and init_db DDL."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
VERSION = "0001"
|
||||
NAME = "baseline_schema"
|
||||
|
||||
|
||||
async def upgrade(conn) -> None:
|
||||
"""Create any missing SQLAlchemy baseline tables without altering existing rows."""
|
||||
from app.db.session import Base
|
||||
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
@@ -0,0 +1,18 @@
|
||||
"""Fix earth table update notify trigger so non-id tables (e.g. vessel_current_state) update cleanly."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
VERSION = "0002"
|
||||
NAME = "fix_earth_notify_trigger"
|
||||
|
||||
|
||||
async def upgrade(conn) -> None:
|
||||
"""Replace planet_notify_earth_table_changed_statement without USING (id) on transition tables."""
|
||||
if getattr(getattr(conn, "dialect", None), "name", "") != "postgresql":
|
||||
return
|
||||
|
||||
from app.db.session import PLANET_NOTIFY_EARTH_TABLE_CHANGED_FUNCTION_SQL
|
||||
|
||||
await conn.execute(text(PLANET_NOTIFY_EARTH_TABLE_CHANGED_FUNCTION_SQL))
|
||||
@@ -0,0 +1,23 @@
|
||||
"""Enforce deferred single-mode publish guard on data_snapshots at commit time."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
VERSION = "0003"
|
||||
NAME = "enforce_storage_policy_publish_guard"
|
||||
|
||||
|
||||
async def upgrade(conn) -> None:
|
||||
"""Install deferred storage-policy constraint trigger on PostgreSQL data_snapshots."""
|
||||
if getattr(getattr(conn, "dialect", None), "name", "") != "postgresql":
|
||||
return
|
||||
|
||||
from app.db.session import (
|
||||
PLANET_ENFORCE_STORAGE_POLICY_PUBLISH_FUNCTION_SQL,
|
||||
PLANET_ENFORCE_STORAGE_POLICY_PUBLISH_TRIGGER_STATEMENTS,
|
||||
)
|
||||
|
||||
await conn.execute(text(PLANET_ENFORCE_STORAGE_POLICY_PUBLISH_FUNCTION_SQL))
|
||||
for statement in PLANET_ENFORCE_STORAGE_POLICY_PUBLISH_TRIGGER_STATEMENTS:
|
||||
await conn.execute(text(statement))
|
||||
@@ -0,0 +1 @@
|
||||
"""Versioned database migration steps package."""
|
||||
@@ -0,0 +1,217 @@
|
||||
"""Versioned schema migration tracker and runner for PostgreSQL/SQLite."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, datetime
|
||||
import hashlib
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import re
|
||||
from typing import Any, Awaitable, Callable
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from app.core.logging import get_logger
|
||||
|
||||
logger = get_logger(__name__, service="migrations")
|
||||
|
||||
DEFAULT_STEPS_DIR = Path(__file__).resolve().parent / "migration_steps"
|
||||
MIGRATION_FILE_RE = re.compile(r"^(?P<version>\d{4})_(?P<slug>[a-z0-9_]+)\.py$")
|
||||
MIGRATION_LOCK_KEY = (17001613, 4)
|
||||
|
||||
CREATE_MIGRATIONS_TABLE_SQL = """
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version VARCHAR(64) PRIMARY KEY,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
checksum VARCHAR(64) NOT NULL,
|
||||
applied_at TIMESTAMP WITH TIME ZONE NOT NULL
|
||||
)
|
||||
"""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MigrationStep:
|
||||
version: str
|
||||
name: str
|
||||
checksum: str
|
||||
path: Path
|
||||
upgrade: Callable[[Any], Awaitable[None]]
|
||||
|
||||
|
||||
def discover_migrations(steps_dir: Path | None = None) -> list[MigrationStep]:
|
||||
"""Load ordered migration modules matching NNNN_name.py."""
|
||||
directory = steps_dir or DEFAULT_STEPS_DIR
|
||||
if not directory.exists():
|
||||
return []
|
||||
|
||||
steps: list[MigrationStep] = []
|
||||
for path in sorted(directory.glob("*.py")):
|
||||
match = MIGRATION_FILE_RE.match(path.name)
|
||||
if not match:
|
||||
continue
|
||||
raw_bytes = path.read_bytes()
|
||||
checksum = hashlib.sha256(raw_bytes).hexdigest()
|
||||
module_name = f"planet_migration_{match.group('version')}_{match.group('slug')}"
|
||||
spec = importlib.util.spec_from_file_location(module_name, path)
|
||||
if spec is None or spec.loader is None:
|
||||
raise RuntimeError(f"Could not load migration module: {path}")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
|
||||
version = str(getattr(module, "VERSION", match.group("version")))
|
||||
name = str(getattr(module, "NAME", match.group("slug")))
|
||||
upgrade_fn = getattr(module, "upgrade", None)
|
||||
if not callable(upgrade_fn):
|
||||
raise RuntimeError(f"Migration {path.name} does not define callable upgrade(conn)")
|
||||
steps.append(
|
||||
MigrationStep(
|
||||
version=version,
|
||||
name=name,
|
||||
checksum=checksum,
|
||||
path=path,
|
||||
upgrade=upgrade_fn,
|
||||
)
|
||||
)
|
||||
|
||||
steps.sort(key=lambda item: item.version)
|
||||
return steps
|
||||
|
||||
|
||||
async def ensure_migrations_table(conn: Any) -> None:
|
||||
await conn.execute(text(CREATE_MIGRATIONS_TABLE_SQL))
|
||||
|
||||
|
||||
async def _fetch_applied_map(conn: Any) -> dict[str, tuple[str, str]]:
|
||||
result = await conn.execute(
|
||||
text("SELECT version, name, checksum FROM schema_migrations ORDER BY version")
|
||||
)
|
||||
return {str(row[0]): (str(row[1]), str(row[2])) for row in result.fetchall()}
|
||||
|
||||
|
||||
async def _record_migration(conn: Any, step: MigrationStep) -> None:
|
||||
await conn.execute(
|
||||
text(
|
||||
"INSERT INTO schema_migrations (version, name, checksum, applied_at) "
|
||||
"VALUES (:version, :name, :checksum, :applied_at)"
|
||||
),
|
||||
{
|
||||
"version": step.version,
|
||||
"name": step.name,
|
||||
"checksum": step.checksum,
|
||||
"applied_at": datetime.now(UTC),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
async def ensure_baseline_stamped(conn: Any, steps_dir: Path | None = None) -> bool:
|
||||
"""Ensure schema_migrations exists and stamp baseline 0001 if no version is recorded."""
|
||||
await ensure_migrations_table(conn)
|
||||
applied = await _fetch_applied_map(conn)
|
||||
if applied:
|
||||
return False
|
||||
steps = discover_migrations(steps_dir)
|
||||
if not steps:
|
||||
return False
|
||||
baseline = steps[0]
|
||||
await _record_migration(conn, baseline)
|
||||
return True
|
||||
|
||||
|
||||
async def get_migration_status(engine: Any, steps_dir: Path | None = None) -> dict[str, Any]:
|
||||
"""Return applied versions, pending versions, and checksum mismatches."""
|
||||
steps = discover_migrations(steps_dir)
|
||||
async with engine.begin() as conn:
|
||||
await ensure_migrations_table(conn)
|
||||
applied_map = await _fetch_applied_map(conn)
|
||||
|
||||
mismatches: list[dict[str, str]] = []
|
||||
pending: list[str] = []
|
||||
for step in steps:
|
||||
recorded = applied_map.get(step.version)
|
||||
if recorded is None:
|
||||
pending.append(step.version)
|
||||
elif recorded[1] != step.checksum:
|
||||
mismatches.append(
|
||||
{
|
||||
"version": step.version,
|
||||
"expected": recorded[1],
|
||||
"actual": step.checksum,
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
"applied": sorted(applied_map.keys()),
|
||||
"pending": pending,
|
||||
"mismatches": mismatches,
|
||||
}
|
||||
|
||||
|
||||
async def run_migrations(
|
||||
engine: Any,
|
||||
steps_dir: Path | None = None,
|
||||
*,
|
||||
verify_checksums: bool = True,
|
||||
) -> list[str]:
|
||||
"""Run all pending migrations transactionally under a PostgreSQL advisory lock."""
|
||||
steps = discover_migrations(steps_dir)
|
||||
newly_applied: list[str] = []
|
||||
|
||||
async with engine.begin() as conn:
|
||||
if getattr(conn.dialect, "name", "") == "postgresql":
|
||||
await conn.execute(
|
||||
text("SELECT pg_advisory_xact_lock(:k1, :k2)"),
|
||||
{"k1": MIGRATION_LOCK_KEY[0], "k2": MIGRATION_LOCK_KEY[1]},
|
||||
)
|
||||
await ensure_migrations_table(conn)
|
||||
applied_map = await _fetch_applied_map(conn)
|
||||
|
||||
for step in steps:
|
||||
recorded = applied_map.get(step.version)
|
||||
if recorded is not None:
|
||||
if verify_checksums and recorded[1] != step.checksum:
|
||||
raise RuntimeError(
|
||||
f"Checksum mismatch for already-applied migration {step.version} ({step.name})"
|
||||
)
|
||||
continue
|
||||
|
||||
logger.info_event(
|
||||
"Applying database migration",
|
||||
event="db.migration.applying",
|
||||
context={"version": step.version, "name": step.name},
|
||||
)
|
||||
await step.upgrade(conn)
|
||||
await _record_migration(conn, step)
|
||||
newly_applied.append(step.version)
|
||||
logger.info_event(
|
||||
"Applied database migration",
|
||||
event="db.migration.applied",
|
||||
context={"version": step.version, "name": step.name},
|
||||
)
|
||||
|
||||
return newly_applied
|
||||
|
||||
|
||||
async def stamp_migrations(
|
||||
engine: Any,
|
||||
target_version: str,
|
||||
steps_dir: Path | None = None,
|
||||
) -> list[str]:
|
||||
"""Record migrations up to target_version as applied without executing SQL."""
|
||||
steps = discover_migrations(steps_dir)
|
||||
known_versions = {step.version for step in steps}
|
||||
if target_version not in known_versions:
|
||||
raise ValueError(f"Unknown migration version: {target_version}")
|
||||
|
||||
stamped: list[str] = []
|
||||
async with engine.begin() as conn:
|
||||
await ensure_migrations_table(conn)
|
||||
applied_map = await _fetch_applied_map(conn)
|
||||
for step in steps:
|
||||
if step.version > target_version:
|
||||
break
|
||||
if step.version in applied_map:
|
||||
continue
|
||||
await _record_migration(conn, step)
|
||||
stamped.append(step.version)
|
||||
return stamped
|
||||
+396
-155
@@ -1,3 +1,4 @@
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import AsyncGenerator
|
||||
|
||||
from sqlalchemy import bindparam, text
|
||||
@@ -28,6 +29,240 @@ async_session_factory = async_sessionmaker(engine, class_=AsyncSession, expire_o
|
||||
|
||||
Base = declarative_base()
|
||||
|
||||
PLANET_NOTIFY_EARTH_TABLE_CHANGED_FUNCTION_SQL = """
|
||||
CREATE OR REPLACE FUNCTION planet_notify_earth_table_changed_statement()
|
||||
RETURNS trigger AS $$
|
||||
DECLARE
|
||||
change_source TEXT;
|
||||
source_record_count INTEGER;
|
||||
source_entity_keys TEXT[];
|
||||
BEGIN
|
||||
IF TG_OP = 'INSERT' THEN
|
||||
FOR change_source IN
|
||||
SELECT DISTINCT COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME)
|
||||
FROM (SELECT to_jsonb(t) AS row_data FROM new_rows AS t) changed_rows
|
||||
LOOP
|
||||
SELECT
|
||||
COUNT(*),
|
||||
ARRAY(
|
||||
SELECT DISTINCT COALESCE(
|
||||
NULLIF(row_data->>'entity_key', ''),
|
||||
NULLIF(row_data->>'source_id', ''),
|
||||
NULLIF(row_data->>'incident_key', ''),
|
||||
NULLIF(row_data->>'id', ''),
|
||||
NULLIF(row_data->>'mmsi', '')
|
||||
)
|
||||
FROM (SELECT to_jsonb(t) AS row_data FROM new_rows AS t) rows_for_keys
|
||||
WHERE COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME) = change_source
|
||||
LIMIT 20
|
||||
)
|
||||
INTO source_record_count, source_entity_keys
|
||||
FROM (SELECT to_jsonb(t) AS row_data FROM new_rows AS t) rows_for_count
|
||||
WHERE COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME) = change_source;
|
||||
|
||||
PERFORM planet_emit_earth_data_changed_statement(
|
||||
TG_TABLE_NAME,
|
||||
TG_OP,
|
||||
change_source,
|
||||
source_record_count,
|
||||
source_entity_keys
|
||||
);
|
||||
END LOOP;
|
||||
ELSIF TG_OP = 'DELETE' THEN
|
||||
FOR change_source IN
|
||||
SELECT DISTINCT COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME)
|
||||
FROM (SELECT to_jsonb(t) AS row_data FROM old_rows AS t) changed_rows
|
||||
LOOP
|
||||
SELECT
|
||||
COUNT(*),
|
||||
ARRAY(
|
||||
SELECT DISTINCT COALESCE(
|
||||
NULLIF(row_data->>'entity_key', ''),
|
||||
NULLIF(row_data->>'source_id', ''),
|
||||
NULLIF(row_data->>'incident_key', ''),
|
||||
NULLIF(row_data->>'id', ''),
|
||||
NULLIF(row_data->>'mmsi', '')
|
||||
)
|
||||
FROM (SELECT to_jsonb(t) AS row_data FROM old_rows AS t) rows_for_keys
|
||||
WHERE COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME) = change_source
|
||||
LIMIT 20
|
||||
)
|
||||
INTO source_record_count, source_entity_keys
|
||||
FROM (SELECT to_jsonb(t) AS row_data FROM old_rows AS t) rows_for_count
|
||||
WHERE COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME) = change_source;
|
||||
|
||||
PERFORM planet_emit_earth_data_changed_statement(
|
||||
TG_TABLE_NAME,
|
||||
TG_OP,
|
||||
change_source,
|
||||
source_record_count,
|
||||
source_entity_keys
|
||||
);
|
||||
END LOOP;
|
||||
ELSIF TG_OP = 'UPDATE' THEN
|
||||
IF TG_TABLE_NAME = 'earth_news_items' THEN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM (SELECT to_jsonb(t) AS row_data FROM new_rows AS t) AS current_row
|
||||
FULL JOIN (SELECT to_jsonb(t) AS row_data FROM old_rows AS t) AS previous_row
|
||||
ON current_row.row_data->>'id' = previous_row.row_data->>'id'
|
||||
WHERE (current_row.row_data - 'last_seen_at' - 'updated_at')
|
||||
IS DISTINCT FROM
|
||||
(previous_row.row_data - 'last_seen_at' - 'updated_at')
|
||||
) THEN
|
||||
RETURN NULL;
|
||||
END IF;
|
||||
END IF;
|
||||
FOR change_source IN
|
||||
SELECT DISTINCT COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME)
|
||||
FROM (
|
||||
SELECT to_jsonb(t) AS row_data FROM new_rows AS t
|
||||
UNION ALL
|
||||
SELECT to_jsonb(t) AS row_data FROM old_rows AS t
|
||||
) changed_rows
|
||||
LOOP
|
||||
SELECT
|
||||
COUNT(*),
|
||||
ARRAY(
|
||||
SELECT DISTINCT COALESCE(
|
||||
NULLIF(row_data->>'entity_key', ''),
|
||||
NULLIF(row_data->>'source_id', ''),
|
||||
NULLIF(row_data->>'incident_key', ''),
|
||||
NULLIF(row_data->>'id', ''),
|
||||
NULLIF(row_data->>'mmsi', '')
|
||||
)
|
||||
FROM (
|
||||
SELECT to_jsonb(t) AS row_data FROM new_rows AS t
|
||||
UNION ALL
|
||||
SELECT to_jsonb(t) AS row_data FROM old_rows AS t
|
||||
) rows_for_keys
|
||||
WHERE COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME) = change_source
|
||||
LIMIT 20
|
||||
)
|
||||
INTO source_record_count, source_entity_keys
|
||||
FROM (
|
||||
SELECT to_jsonb(t) AS row_data FROM new_rows AS t
|
||||
UNION ALL
|
||||
SELECT to_jsonb(t) AS row_data FROM old_rows AS t
|
||||
) rows_for_count
|
||||
WHERE COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME) = change_source;
|
||||
|
||||
PERFORM planet_emit_earth_data_changed_statement(
|
||||
TG_TABLE_NAME,
|
||||
TG_OP,
|
||||
change_source,
|
||||
source_record_count,
|
||||
source_entity_keys
|
||||
);
|
||||
END LOOP;
|
||||
END IF;
|
||||
|
||||
RETURN NULL;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
"""
|
||||
|
||||
PLANET_ENFORCE_STORAGE_POLICY_PUBLISH_FUNCTION_SQL = """
|
||||
CREATE OR REPLACE FUNCTION planet_enforce_storage_policy_on_snapshot_publish()
|
||||
RETURNS trigger AS $$
|
||||
DECLARE
|
||||
is_new_publish BOOLEAN := FALSE;
|
||||
still_published BOOLEAN := FALSE;
|
||||
policy_payload JSONB;
|
||||
global_locked BOOLEAN := FALSE;
|
||||
default_mode TEXT := 'single';
|
||||
override_mode TEXT;
|
||||
effective_mode TEXT := 'single';
|
||||
has_other_success BOOLEAN := FALSE;
|
||||
BEGIN
|
||||
IF TG_OP = 'INSERT' THEN
|
||||
is_new_publish := COALESCE(NEW.is_current, FALSE) = TRUE OR NEW.status = 'success';
|
||||
ELSIF TG_OP = 'UPDATE' THEN
|
||||
is_new_publish := (COALESCE(NEW.is_current, FALSE) = TRUE OR NEW.status = 'success')
|
||||
AND COALESCE(OLD.is_current, FALSE) = FALSE
|
||||
AND COALESCE(OLD.status, '') <> 'success';
|
||||
END IF;
|
||||
|
||||
IF NOT is_new_publish THEN
|
||||
RETURN NULL;
|
||||
END IF;
|
||||
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM data_snapshots
|
||||
WHERE id = NEW.id
|
||||
AND (COALESCE(is_current, FALSE) = TRUE OR status = 'success')
|
||||
)
|
||||
INTO still_published;
|
||||
|
||||
IF NOT still_published THEN
|
||||
RETURN NULL;
|
||||
END IF;
|
||||
|
||||
PERFORM pg_advisory_xact_lock_shared(17001614, 2);
|
||||
|
||||
SELECT payload::jsonb
|
||||
INTO policy_payload
|
||||
FROM system_settings
|
||||
WHERE category = 'collection_storage'
|
||||
LIMIT 1
|
||||
FOR SHARE;
|
||||
|
||||
IF policy_payload IS NULL THEN
|
||||
RETURN NULL;
|
||||
END IF;
|
||||
|
||||
global_locked := LOWER(COALESCE(policy_payload->>'global_single_lock', 'false')) IN ('true', '1', 'yes', 'on');
|
||||
IF global_locked THEN
|
||||
effective_mode := 'single';
|
||||
ELSE
|
||||
default_mode := LOWER(COALESCE(NULLIF(policy_payload->>'default_mode', ''), 'single'));
|
||||
override_mode := LOWER(COALESCE(NULLIF((policy_payload->'overrides')->>NEW.source, ''), ''));
|
||||
IF override_mode <> '' THEN
|
||||
effective_mode := override_mode;
|
||||
ELSE
|
||||
effective_mode := default_mode;
|
||||
END IF;
|
||||
END IF;
|
||||
|
||||
IF effective_mode <> 'single' THEN
|
||||
RETURN NULL;
|
||||
END IF;
|
||||
|
||||
IF TG_OP = 'INSERT' AND NOT global_locked AND COALESCE(NEW.is_current, FALSE) <> TRUE THEN
|
||||
RETURN NULL;
|
||||
END IF;
|
||||
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM data_snapshots
|
||||
WHERE source = NEW.source
|
||||
AND id IS DISTINCT FROM NEW.id
|
||||
AND status = 'success'
|
||||
)
|
||||
INTO has_other_success;
|
||||
|
||||
IF has_other_success THEN
|
||||
RAISE EXCEPTION 'planet_storage_policy_single_violation: snapshot % for source % cannot be published while single storage mode is active', NEW.id, NEW.source
|
||||
USING ERRCODE = 'P0001';
|
||||
END IF;
|
||||
|
||||
RETURN NULL;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
"""
|
||||
|
||||
PLANET_ENFORCE_STORAGE_POLICY_PUBLISH_TRIGGER_STATEMENTS = (
|
||||
"DROP TRIGGER IF EXISTS tr_planet_enforce_storage_policy_publish ON data_snapshots",
|
||||
"""
|
||||
CREATE CONSTRAINT TRIGGER tr_planet_enforce_storage_policy_publish
|
||||
AFTER INSERT OR UPDATE ON data_snapshots
|
||||
DEFERRABLE INITIALLY DEFERRED
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION planet_enforce_storage_policy_on_snapshot_publish()
|
||||
""",
|
||||
)
|
||||
|
||||
|
||||
async def get_db() -> AsyncGenerator[AsyncSession, None]:
|
||||
async with async_session_factory() as session:
|
||||
@@ -39,19 +274,32 @@ async def get_db() -> AsyncGenerator[AsyncSession, None]:
|
||||
raise
|
||||
|
||||
|
||||
def _is_postgresql_session(session: AsyncSession | None) -> bool:
|
||||
if session is None or not callable(getattr(session, "get_bind", None)):
|
||||
return False
|
||||
try:
|
||||
bind = session.get_bind()
|
||||
return getattr(getattr(bind, "dialect", None), "name", "") == "postgresql"
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
async def seed_default_datasources(session: AsyncSession):
|
||||
from app.core.datasource_defaults import DEFAULT_DATASOURCES
|
||||
from app.models.datasource import DataSource
|
||||
|
||||
if _is_postgresql_session(session):
|
||||
await session.execute(text("SELECT pg_advisory_xact_lock(17001613, 6)"))
|
||||
|
||||
for source, info in DEFAULT_DATASOURCES.items():
|
||||
existing = await session.get(DataSource, info["id"])
|
||||
if existing:
|
||||
existing.name = info["name"]
|
||||
existing.source = source
|
||||
existing.module = info["module"]
|
||||
existing.priority = info["priority"]
|
||||
existing.frequency_minutes = info["frequency_minutes"]
|
||||
existing.collector_class = source
|
||||
if not existing.source:
|
||||
existing.source = source
|
||||
if not existing.module:
|
||||
existing.module = info["module"]
|
||||
if not existing.collector_class:
|
||||
existing.collector_class = source
|
||||
if existing.config is None:
|
||||
existing.config = "{}"
|
||||
continue
|
||||
@@ -161,24 +409,62 @@ async def ensure_default_admin_user(session: AsyncSession):
|
||||
from app.core.security import get_password_hash
|
||||
from app.models.user import User
|
||||
|
||||
for default_user in DEFAULT_LOGIN_USERS:
|
||||
result = await session.execute(
|
||||
text("SELECT id FROM users WHERE username = :username"),
|
||||
{"username": default_user["username"]},
|
||||
)
|
||||
if result.fetchone():
|
||||
continue
|
||||
if _is_postgresql_session(session):
|
||||
await session.execute(text("SELECT pg_advisory_xact_lock(17001613, 5)"))
|
||||
|
||||
session.add(
|
||||
User(
|
||||
username=default_user["username"],
|
||||
email=default_user["email"],
|
||||
password_hash=get_password_hash(default_user["password"]),
|
||||
role=default_user["role"],
|
||||
is_active=True,
|
||||
email_verified=True,
|
||||
custom_username = str(settings.INITIAL_ADMIN_USERNAME or "").strip()
|
||||
custom_password = str(settings.INITIAL_ADMIN_PASSWORD or "").strip()
|
||||
custom_email = str(settings.INITIAL_ADMIN_EMAIL or "").strip() or (
|
||||
f"{custom_username}@planet.local" if custom_username else ""
|
||||
)
|
||||
|
||||
if custom_username and custom_password:
|
||||
existing_custom = (
|
||||
await session.execute(
|
||||
text("SELECT id FROM users WHERE username = :username"),
|
||||
{"username": custom_username},
|
||||
)
|
||||
)
|
||||
).fetchone()
|
||||
if existing_custom is None:
|
||||
session.add(
|
||||
User(
|
||||
username=custom_username,
|
||||
email=custom_email,
|
||||
password_hash=get_password_hash(custom_password),
|
||||
role="super_admin",
|
||||
is_active=True,
|
||||
email_verified=True,
|
||||
)
|
||||
)
|
||||
await session.flush()
|
||||
|
||||
if settings.should_seed_default_dev_users:
|
||||
for default_user in DEFAULT_LOGIN_USERS:
|
||||
result = await session.execute(
|
||||
text("SELECT id FROM users WHERE username = :username"),
|
||||
{"username": default_user["username"]},
|
||||
)
|
||||
if result.fetchone():
|
||||
continue
|
||||
|
||||
session.add(
|
||||
User(
|
||||
username=default_user["username"],
|
||||
email=default_user["email"],
|
||||
password_hash=get_password_hash(default_user["password"]),
|
||||
role=default_user["role"],
|
||||
is_active=True,
|
||||
email_verified=True,
|
||||
)
|
||||
)
|
||||
else:
|
||||
user_count = (await session.execute(text("SELECT COUNT(*) FROM users"))).scalar() or 0
|
||||
if int(user_count) == 0:
|
||||
logger.warning_event(
|
||||
"No users exist and default dev accounts are disabled in production; configure INITIAL_ADMIN_USERNAME and INITIAL_ADMIN_PASSWORD",
|
||||
event="auth.bootstrap.no_users",
|
||||
)
|
||||
|
||||
await session.commit()
|
||||
|
||||
|
||||
@@ -219,6 +505,34 @@ async def init_db():
|
||||
},
|
||||
)
|
||||
|
||||
async with _init_db_advisory_lock():
|
||||
await _init_db_ddl_and_seed()
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def _init_db_advisory_lock():
|
||||
"""Serialize full DDL + seed startup across concurrent PostgreSQL replicas."""
|
||||
if getattr(getattr(engine, "dialect", None), "name", "") != "postgresql":
|
||||
yield
|
||||
return
|
||||
|
||||
async with engine.connect() as base_conn:
|
||||
lock_conn = await base_conn.execution_options(isolation_level="AUTOCOMMIT")
|
||||
await lock_conn.execute(text("SELECT pg_advisory_lock(17001613, 4)"))
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
try:
|
||||
await lock_conn.execute(text("SELECT pg_advisory_unlock(17001613, 4)"))
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed to release init_db advisory lock cleanly",
|
||||
event="database.init_db.unlock_failed",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
|
||||
|
||||
async def _init_db_ddl_and_seed():
|
||||
async with engine.begin() as conn:
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
await install_bgp_prefix_geo_functions(conn)
|
||||
@@ -258,6 +572,7 @@ async def init_db():
|
||||
ADD COLUMN IF NOT EXISTS previous_record_id INTEGER,
|
||||
ADD COLUMN IF NOT EXISTS change_type VARCHAR(20),
|
||||
ADD COLUMN IF NOT EXISTS change_summary JSONB DEFAULT '{}'::jsonb,
|
||||
ADD COLUMN IF NOT EXISTS content_hash VARCHAR(64),
|
||||
ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ
|
||||
"""
|
||||
)
|
||||
@@ -367,139 +682,7 @@ async def init_db():
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE OR REPLACE FUNCTION planet_notify_earth_table_changed_statement()
|
||||
RETURNS trigger AS $$
|
||||
DECLARE
|
||||
change_source TEXT;
|
||||
source_record_count INTEGER;
|
||||
source_entity_keys TEXT[];
|
||||
BEGIN
|
||||
IF TG_OP = 'INSERT' THEN
|
||||
FOR change_source IN
|
||||
SELECT DISTINCT COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME)
|
||||
FROM (SELECT to_jsonb(t) AS row_data FROM new_rows AS t) changed_rows
|
||||
LOOP
|
||||
SELECT
|
||||
COUNT(*),
|
||||
ARRAY(
|
||||
SELECT DISTINCT COALESCE(
|
||||
NULLIF(row_data->>'entity_key', ''),
|
||||
NULLIF(row_data->>'source_id', ''),
|
||||
NULLIF(row_data->>'incident_key', ''),
|
||||
NULLIF(row_data->>'id', ''),
|
||||
NULLIF(row_data->>'mmsi', '')
|
||||
)
|
||||
FROM (SELECT to_jsonb(t) AS row_data FROM new_rows AS t) rows_for_keys
|
||||
WHERE COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME) = change_source
|
||||
LIMIT 20
|
||||
)
|
||||
INTO source_record_count, source_entity_keys
|
||||
FROM (SELECT to_jsonb(t) AS row_data FROM new_rows AS t) rows_for_count
|
||||
WHERE COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME) = change_source;
|
||||
|
||||
PERFORM planet_emit_earth_data_changed_statement(
|
||||
TG_TABLE_NAME,
|
||||
TG_OP,
|
||||
change_source,
|
||||
source_record_count,
|
||||
source_entity_keys
|
||||
);
|
||||
END LOOP;
|
||||
ELSIF TG_OP = 'DELETE' THEN
|
||||
FOR change_source IN
|
||||
SELECT DISTINCT COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME)
|
||||
FROM (SELECT to_jsonb(t) AS row_data FROM old_rows AS t) changed_rows
|
||||
LOOP
|
||||
SELECT
|
||||
COUNT(*),
|
||||
ARRAY(
|
||||
SELECT DISTINCT COALESCE(
|
||||
NULLIF(row_data->>'entity_key', ''),
|
||||
NULLIF(row_data->>'source_id', ''),
|
||||
NULLIF(row_data->>'incident_key', ''),
|
||||
NULLIF(row_data->>'id', ''),
|
||||
NULLIF(row_data->>'mmsi', '')
|
||||
)
|
||||
FROM (SELECT to_jsonb(t) AS row_data FROM old_rows AS t) rows_for_keys
|
||||
WHERE COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME) = change_source
|
||||
LIMIT 20
|
||||
)
|
||||
INTO source_record_count, source_entity_keys
|
||||
FROM (SELECT to_jsonb(t) AS row_data FROM old_rows AS t) rows_for_count
|
||||
WHERE COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME) = change_source;
|
||||
|
||||
PERFORM planet_emit_earth_data_changed_statement(
|
||||
TG_TABLE_NAME,
|
||||
TG_OP,
|
||||
change_source,
|
||||
source_record_count,
|
||||
source_entity_keys
|
||||
);
|
||||
END LOOP;
|
||||
ELSIF TG_OP = 'UPDATE' THEN
|
||||
IF TG_TABLE_NAME = 'earth_news_items' AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM new_rows AS current_row
|
||||
FULL JOIN old_rows AS previous_row USING (id)
|
||||
WHERE (to_jsonb(current_row) - 'last_seen_at' - 'updated_at')
|
||||
IS DISTINCT FROM
|
||||
(to_jsonb(previous_row) - 'last_seen_at' - 'updated_at')
|
||||
) THEN
|
||||
RETURN NULL;
|
||||
END IF;
|
||||
FOR change_source IN
|
||||
SELECT DISTINCT COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME)
|
||||
FROM (
|
||||
SELECT to_jsonb(t) AS row_data FROM new_rows AS t
|
||||
UNION ALL
|
||||
SELECT to_jsonb(t) AS row_data FROM old_rows AS t
|
||||
) changed_rows
|
||||
LOOP
|
||||
SELECT
|
||||
COUNT(*),
|
||||
ARRAY(
|
||||
SELECT DISTINCT COALESCE(
|
||||
NULLIF(row_data->>'entity_key', ''),
|
||||
NULLIF(row_data->>'source_id', ''),
|
||||
NULLIF(row_data->>'incident_key', ''),
|
||||
NULLIF(row_data->>'id', ''),
|
||||
NULLIF(row_data->>'mmsi', '')
|
||||
)
|
||||
FROM (
|
||||
SELECT to_jsonb(t) AS row_data FROM new_rows AS t
|
||||
UNION ALL
|
||||
SELECT to_jsonb(t) AS row_data FROM old_rows AS t
|
||||
) rows_for_keys
|
||||
WHERE COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME) = change_source
|
||||
LIMIT 20
|
||||
)
|
||||
INTO source_record_count, source_entity_keys
|
||||
FROM (
|
||||
SELECT to_jsonb(t) AS row_data FROM new_rows AS t
|
||||
UNION ALL
|
||||
SELECT to_jsonb(t) AS row_data FROM old_rows AS t
|
||||
) rows_for_count
|
||||
WHERE COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME) = change_source;
|
||||
|
||||
PERFORM planet_emit_earth_data_changed_statement(
|
||||
TG_TABLE_NAME,
|
||||
TG_OP,
|
||||
change_source,
|
||||
source_record_count,
|
||||
source_entity_keys
|
||||
);
|
||||
END LOOP;
|
||||
END IF;
|
||||
|
||||
RETURN NULL;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(text(PLANET_NOTIFY_EARTH_TABLE_CHANGED_FUNCTION_SQL))
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
@@ -677,6 +860,10 @@ async def init_db():
|
||||
"DROP TRIGGER IF EXISTS tr_planet_situational_assessments_changed_delete ON situational_assessments",
|
||||
):
|
||||
await conn.execute(text(drop_stmt))
|
||||
if conn.dialect.name == "postgresql":
|
||||
await conn.execute(text(PLANET_ENFORCE_STORAGE_POLICY_PUBLISH_FUNCTION_SQL))
|
||||
for stmt in PLANET_ENFORCE_STORAGE_POLICY_PUBLISH_TRIGGER_STATEMENTS:
|
||||
await conn.execute(text(stmt))
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
@@ -866,6 +1053,58 @@ async def init_db():
|
||||
"""
|
||||
)
|
||||
)
|
||||
duplicate_current_exists = (
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
SELECT 1
|
||||
FROM collected_data
|
||||
WHERE COALESCE(is_current, TRUE) = TRUE
|
||||
AND deleted_at IS NULL
|
||||
AND entity_key IS NOT NULL
|
||||
GROUP BY source, entity_key
|
||||
HAVING COUNT(*) > 1
|
||||
LIMIT 1
|
||||
"""
|
||||
)
|
||||
)
|
||||
).fetchone() is not None
|
||||
if duplicate_current_exists:
|
||||
# Demote older duplicate is_current rows safely; never delete existing dev history.
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
WITH ranked AS (
|
||||
SELECT id,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY source, entity_key
|
||||
ORDER BY collected_at DESC NULLS LAST, id DESC
|
||||
) AS rn
|
||||
FROM collected_data
|
||||
WHERE COALESCE(is_current, TRUE) = TRUE
|
||||
AND deleted_at IS NULL
|
||||
AND entity_key IS NOT NULL
|
||||
)
|
||||
UPDATE collected_data
|
||||
SET is_current = FALSE
|
||||
WHERE id IN (SELECT id FROM ranked WHERE rn > 1)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_collected_data_current_entity
|
||||
ON collected_data (source, entity_key)
|
||||
WHERE COALESCE(is_current, TRUE) = TRUE
|
||||
AND deleted_at IS NULL
|
||||
AND entity_key IS NOT NULL
|
||||
"""
|
||||
)
|
||||
)
|
||||
from app.db.migrations import ensure_baseline_stamped
|
||||
|
||||
await ensure_baseline_stamped(conn)
|
||||
|
||||
async with async_session_factory() as session:
|
||||
from app.services.bgp_collector_locations import (
|
||||
@@ -874,9 +1113,11 @@ async def init_db():
|
||||
from app.services.compute_center_locations import (
|
||||
seed_compute_center_locations_from_source_coords,
|
||||
)
|
||||
from app.services.storage_policy import ensure_default_storage_policy
|
||||
|
||||
await seed_default_bgp_collector_locations(session)
|
||||
await seed_compute_center_locations_from_source_coords(session)
|
||||
await seed_default_datasources(session)
|
||||
await purge_legacy_earth_boundary_datasources(session)
|
||||
await ensure_default_admin_user(session)
|
||||
await ensure_default_storage_policy(session)
|
||||
+167
-32
@@ -1,44 +1,57 @@
|
||||
import asyncio
|
||||
from contextlib import asynccontextmanager
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi import Depends, FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import JSONResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from sqlalchemy import text
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
|
||||
from app.api.main import api_router
|
||||
from app.api.v1 import websocket
|
||||
from app.core.config import settings
|
||||
from app.core.logging import configure_logging
|
||||
from app.core.config import settings, validate_production_security
|
||||
from app.core.logging import configure_logging, get_logger
|
||||
from app.core.request_context import set_request_id
|
||||
from app.core.security import _AsyncRedisClient, get_current_user
|
||||
from app.core.websocket.broadcaster import broadcaster
|
||||
from app.db.session import init_db
|
||||
from app.services.scheduler import (
|
||||
cleanup_stale_running_tasks,
|
||||
start_scheduler,
|
||||
stop_scheduler,
|
||||
sync_scheduler_with_datasources,
|
||||
from app.core.websocket.manager import manager
|
||||
from app.db.session import async_session_factory, init_db
|
||||
from app.models.user import User
|
||||
from app.services.data_jobs import start_data_job_worker, stop_data_job_worker
|
||||
from app.services.earth_db_change_listener import (
|
||||
start_earth_db_change_listener,
|
||||
stop_earth_db_change_listener,
|
||||
)
|
||||
from app.services.earth_news_worker import (
|
||||
start_earth_news_target_worker,
|
||||
stop_earth_news_target_worker,
|
||||
)
|
||||
from app.services.earth_db_change_listener import (
|
||||
start_earth_db_change_listener,
|
||||
stop_earth_db_change_listener,
|
||||
from app.services.scheduler import (
|
||||
acquire_scheduler_leader_lock,
|
||||
cleanup_stale_running_tasks,
|
||||
release_scheduler_leader_lock,
|
||||
start_scheduler,
|
||||
stop_scheduler,
|
||||
sync_scheduler_with_datasources,
|
||||
)
|
||||
from app.services.data_jobs import start_data_job_worker, stop_data_job_worker
|
||||
|
||||
|
||||
configure_logging()
|
||||
logger = get_logger(__name__, service="main")
|
||||
|
||||
|
||||
class WebSocketCORSMiddleware(BaseHTTPMiddleware):
|
||||
async def dispatch(self, request, call_next):
|
||||
if request.url.path.startswith("/ws") and request.method == "GET":
|
||||
response = await call_next(request)
|
||||
response.headers["Access-Control-Allow-Origin"] = "*"
|
||||
allow_origins = settings.CORS_ORIGINS or []
|
||||
origin = request.headers.get("origin")
|
||||
if "*" in allow_origins:
|
||||
response.headers["Access-Control-Allow-Origin"] = "*"
|
||||
elif origin and origin in allow_origins:
|
||||
response.headers["Access-Control-Allow-Origin"] = origin
|
||||
response.headers["Access-Control-Allow-Methods"] = "GET, OPTIONS"
|
||||
response.headers["Access-Control-Allow-Headers"] = "*"
|
||||
return response
|
||||
@@ -59,20 +72,107 @@ class RequestContextMiddleware(BaseHTTPMiddleware):
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
validate_production_security(settings)
|
||||
await init_db()
|
||||
await cleanup_stale_running_tasks()
|
||||
start_scheduler()
|
||||
await sync_scheduler_with_datasources()
|
||||
broadcaster.start()
|
||||
start_data_job_worker()
|
||||
start_earth_db_change_listener()
|
||||
start_earth_news_target_worker()
|
||||
yield
|
||||
await stop_earth_news_target_worker()
|
||||
await stop_earth_db_change_listener()
|
||||
await stop_data_job_worker()
|
||||
broadcaster.stop()
|
||||
stop_scheduler()
|
||||
|
||||
pubsub_started = False
|
||||
leader_lock_acquired = False
|
||||
scheduler_started = False
|
||||
workers_started = False
|
||||
broadcaster_started = False
|
||||
listener_started = False
|
||||
|
||||
try:
|
||||
await manager.start_pubsub()
|
||||
pubsub_started = True
|
||||
|
||||
if settings.should_run_scheduler:
|
||||
if await acquire_scheduler_leader_lock():
|
||||
leader_lock_acquired = True
|
||||
await cleanup_stale_running_tasks()
|
||||
start_scheduler()
|
||||
scheduler_started = True
|
||||
await sync_scheduler_with_datasources()
|
||||
else:
|
||||
logger.warning_event(
|
||||
"Scheduler leader lock held by another instance; skipping scheduler startup",
|
||||
event="scheduler.leader_lock.skipped",
|
||||
context={"role": settings.normalized_role},
|
||||
)
|
||||
|
||||
if settings.should_run_workers:
|
||||
start_data_job_worker()
|
||||
start_earth_news_target_worker()
|
||||
workers_started = True
|
||||
|
||||
broadcaster.start()
|
||||
broadcaster_started = True
|
||||
start_earth_db_change_listener()
|
||||
listener_started = True
|
||||
yield
|
||||
finally:
|
||||
if listener_started:
|
||||
try:
|
||||
await stop_earth_db_change_listener()
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed stopping earth db change listener during shutdown",
|
||||
event="app.shutdown.listener_error",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
if broadcaster_started:
|
||||
try:
|
||||
broadcaster.stop()
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed stopping broadcaster during shutdown",
|
||||
event="app.shutdown.broadcaster_error",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
if workers_started:
|
||||
try:
|
||||
await stop_earth_news_target_worker()
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed stopping earth news worker during shutdown",
|
||||
event="app.shutdown.earth_news_error",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
try:
|
||||
await stop_data_job_worker()
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed stopping data job worker during shutdown",
|
||||
event="app.shutdown.data_job_error",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
if scheduler_started:
|
||||
try:
|
||||
stop_scheduler()
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed stopping scheduler during shutdown",
|
||||
event="app.shutdown.scheduler_error",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
if leader_lock_acquired:
|
||||
try:
|
||||
await release_scheduler_leader_lock()
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed releasing scheduler leader lock during shutdown",
|
||||
event="app.shutdown.leader_lock_error",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
if pubsub_started:
|
||||
try:
|
||||
await manager.stop_pubsub()
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed stopping pubsub during shutdown",
|
||||
event="app.shutdown.pubsub_error",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
@@ -85,10 +185,11 @@ app = FastAPI(
|
||||
openapi_url="/openapi.json",
|
||||
)
|
||||
|
||||
configured_origins = list(settings.CORS_ORIGINS or [])
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_origins=configured_origins,
|
||||
allow_credentials="*" not in configured_origins and bool(configured_origins),
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
@@ -113,6 +214,40 @@ async def health_check():
|
||||
return {"status": "healthy", "version": settings.VERSION}
|
||||
|
||||
|
||||
@app.get("/health/live")
|
||||
async def health_live():
|
||||
return {"status": "alive", "version": settings.VERSION, "role": settings.normalized_role}
|
||||
|
||||
|
||||
@app.get("/health/ready")
|
||||
async def health_ready():
|
||||
checks = {"database": "error", "redis": "error"}
|
||||
try:
|
||||
async with async_session_factory() as db:
|
||||
await asyncio.wait_for(db.execute(text("SELECT 1")), timeout=2.0)
|
||||
checks["database"] = "ok"
|
||||
except Exception:
|
||||
checks["database"] = "error"
|
||||
|
||||
try:
|
||||
client = _AsyncRedisClient.get_client()
|
||||
pong = await asyncio.wait_for(client.ping(), timeout=2.0)
|
||||
checks["redis"] = "ok" if pong else "error"
|
||||
except Exception:
|
||||
checks["redis"] = "error"
|
||||
|
||||
all_ok = all(value == "ok" for value in checks.values())
|
||||
payload = {
|
||||
"status": "ready" if all_ok else "degraded",
|
||||
"version": settings.VERSION,
|
||||
"role": settings.normalized_role,
|
||||
"checks": checks,
|
||||
}
|
||||
if not all_ok:
|
||||
return JSONResponse(status_code=503, content=payload)
|
||||
return payload
|
||||
|
||||
|
||||
@app.get("/")
|
||||
async def root():
|
||||
return {
|
||||
@@ -124,7 +259,7 @@ async def root():
|
||||
|
||||
|
||||
@app.get("/api/v1/scheduler/jobs")
|
||||
async def get_scheduler_jobs():
|
||||
async def get_scheduler_jobs(_current_user: User = Depends(get_current_user)):
|
||||
from app.services.scheduler import get_scheduler_jobs
|
||||
|
||||
return {"jobs": get_scheduler_jobs()}
|
||||
return {"jobs": get_scheduler_jobs()}
|
||||
@@ -43,6 +43,7 @@ class CollectedData(Base):
|
||||
previous_record_id = Column(Integer, ForeignKey("collected_data.id"), nullable=True, index=True)
|
||||
change_type = Column(String(20), nullable=True)
|
||||
change_summary = Column(JSON, default={})
|
||||
content_hash = Column(String(64), nullable=True)
|
||||
deleted_at = Column(DateTime(timezone=True), nullable=True)
|
||||
|
||||
# Indexes for common queries
|
||||
|
||||
@@ -8,6 +8,7 @@ class Token(BaseModel):
|
||||
access_token: str
|
||||
token_type: str = "bearer"
|
||||
expires_in: Optional[int] = None
|
||||
refresh_token: Optional[str] = None
|
||||
user: dict
|
||||
|
||||
|
||||
|
||||
@@ -19,7 +19,13 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.enums import UserRole
|
||||
from app.core.logging import get_logger
|
||||
from app.core.security import _load_active_user, decode_token, get_current_user, redis_client
|
||||
from app.core.security import (
|
||||
_load_active_user,
|
||||
decode_token,
|
||||
get_current_user,
|
||||
is_token_blacklisted,
|
||||
redis_client,
|
||||
)
|
||||
from app.db.session import get_db
|
||||
from app.models.situational_assessment import WorkflowRun
|
||||
from app.models.system_setting import SystemSetting
|
||||
@@ -130,17 +136,11 @@ async def _try_load_bearer_user(
|
||||
if credentials is None or not credentials.credentials:
|
||||
return None
|
||||
token = credentials.credentials
|
||||
try:
|
||||
if redis_client.sismember("blacklisted_tokens", token):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Token has been revoked",
|
||||
)
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception:
|
||||
# Redis offline in unit tests should not block valid JWT verification
|
||||
pass
|
||||
if await is_token_blacklisted(token, legacy_sync_client=redis_client):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Token has been revoked",
|
||||
)
|
||||
|
||||
payload = decode_token(token)
|
||||
if payload is None or payload.get("type") != "access" or payload.get("sub") is None:
|
||||
|
||||
@@ -4,6 +4,7 @@ from datetime import UTC, datetime
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import select
|
||||
@@ -14,10 +15,13 @@ from app.core.time import to_iso8601_utc
|
||||
from app.core.websocket.broadcaster import broadcaster
|
||||
from app.models.datasource_config import DataSourceConfig
|
||||
from app.models.task import CollectionTask
|
||||
from app.services.collectors.base import BaseCollector
|
||||
from app.models.vessel import VesselCurrentState
|
||||
from app.services.collectors.base import BaseCollector, _StoragePolicyDowngradedToSingle
|
||||
from app.services.storage_policy import is_storage_policy_single_violation
|
||||
from app.services.vessel_ais_aggregation import (
|
||||
AISSTREAM_DELIVERY_MODE,
|
||||
AISSTREAM_TRANSPORT,
|
||||
prune_expired_vessel_track_points,
|
||||
record_vessel_ais_observation,
|
||||
update_ais_source_health,
|
||||
)
|
||||
@@ -282,12 +286,98 @@ class AISStreamCollector(BaseCollector):
|
||||
records.append(record)
|
||||
return records
|
||||
|
||||
async def _has_existing_current_data(self, db: AsyncSession | None) -> bool:
|
||||
if db is None or not callable(getattr(db, "execute", None)):
|
||||
return False
|
||||
try:
|
||||
result = await db.execute(
|
||||
select(VesselCurrentState.mmsi)
|
||||
.where(VesselCurrentState.source == self.name)
|
||||
.limit(1)
|
||||
)
|
||||
except Exception:
|
||||
return False
|
||||
if result is None or not callable(getattr(result, "scalar_one_or_none", None)):
|
||||
return False
|
||||
return result.scalar_one_or_none() is not None
|
||||
|
||||
async def _should_persist_raw_ais(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
*,
|
||||
force_refresh: bool = False,
|
||||
) -> tuple[bool, str]:
|
||||
now_mono = time.monotonic()
|
||||
cached_at = float(getattr(self, "_stream_mode_checked_at", 0.0))
|
||||
if (
|
||||
not force_refresh
|
||||
and (now_mono - cached_at) < 2.0
|
||||
and self._snapshot_mode is not None
|
||||
):
|
||||
return self._snapshot_mode == "history", self._snapshot_mode
|
||||
if callable(getattr(db, "execute", None)):
|
||||
mode, _ = await self._resolve_storage_policy(db)
|
||||
self._stream_mode_checked_at = now_mono
|
||||
return mode == "history", mode
|
||||
mode = self._snapshot_mode or "single"
|
||||
return mode == "history", mode
|
||||
|
||||
async def _save_data(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
data: list[dict[str, Any]],
|
||||
task_id: int | None = None,
|
||||
snapshot_id: int | None = None,
|
||||
) -> int:
|
||||
persist_raw, mode = await self._should_persist_raw_ais(db, force_refresh=True)
|
||||
snapshot_id = await self._reconcile_snapshot_for_mode_switch(
|
||||
db,
|
||||
mode=mode,
|
||||
task_id=task_id,
|
||||
snapshot_id=snapshot_id,
|
||||
)
|
||||
try:
|
||||
records_added = await self._write_aisstream_batch(
|
||||
db,
|
||||
data,
|
||||
persist_raw=persist_raw,
|
||||
mode=mode,
|
||||
snapshot_id=snapshot_id,
|
||||
)
|
||||
if persist_raw:
|
||||
await self._assert_versioned_publish_allowed(db, snapshot_id=snapshot_id)
|
||||
await db.commit()
|
||||
except Exception as exc:
|
||||
if (
|
||||
(not isinstance(exc, _StoragePolicyDowngradedToSingle) and not is_storage_policy_single_violation(exc))
|
||||
or self._previous_current_snapshot_id is None
|
||||
):
|
||||
raise
|
||||
downgraded_snapshot_id = await self._downgrade_pending_snapshot_to_single(
|
||||
db,
|
||||
task_id=task_id,
|
||||
snapshot_id=snapshot_id,
|
||||
)
|
||||
records_added = await self._write_aisstream_batch(
|
||||
db,
|
||||
data,
|
||||
persist_raw=False,
|
||||
mode="single",
|
||||
snapshot_id=downgraded_snapshot_id,
|
||||
)
|
||||
await db.commit()
|
||||
|
||||
await self.update_progress(records_added, force=True)
|
||||
return records_added
|
||||
|
||||
async def _write_aisstream_batch(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
data: list[dict[str, Any]],
|
||||
*,
|
||||
persist_raw: bool,
|
||||
mode: str,
|
||||
snapshot_id: int | None,
|
||||
) -> int:
|
||||
now = datetime.now(UTC)
|
||||
records_added = 0
|
||||
@@ -305,13 +395,17 @@ class AISStreamCollector(BaseCollector):
|
||||
source_message_id=item.get("_source_message_id"),
|
||||
observed_at=observed_at,
|
||||
collected_at=now,
|
||||
persist_raw=persist_raw,
|
||||
)
|
||||
if observation is not None:
|
||||
records_added += 1
|
||||
if isinstance(observed_at, datetime) and observed_at > latest_observed_at:
|
||||
latest_observed_at = observed_at
|
||||
if (index + 1) % 1000 == 0:
|
||||
await self.update_progress(index + 1, commit=True)
|
||||
await self.update_progress(index + 1, commit=False)
|
||||
|
||||
if not persist_raw:
|
||||
await prune_expired_vessel_track_points(db, now=now)
|
||||
|
||||
await update_ais_source_health(
|
||||
db,
|
||||
@@ -327,6 +421,7 @@ class AISStreamCollector(BaseCollector):
|
||||
|
||||
snapshot = await db.get(DataSnapshot, snapshot_id)
|
||||
if snapshot:
|
||||
await self._promote_snapshot_to_current(db, snapshot)
|
||||
snapshot.record_count = records_added
|
||||
snapshot.status = "success"
|
||||
snapshot.completed_at = now
|
||||
@@ -335,13 +430,13 @@ class AISStreamCollector(BaseCollector):
|
||||
"updated": 0,
|
||||
"unchanged": 0,
|
||||
"deleted": 0,
|
||||
"storage": "ais_raw_observations",
|
||||
"storage": "ais_raw_observations" if persist_raw else "vessel_current_state_and_24h_track",
|
||||
"storage_mode": mode,
|
||||
}
|
||||
await db.commit()
|
||||
await self.update_progress(records_added, force=True)
|
||||
return records_added
|
||||
|
||||
async def _save_stream_record(self, db: AsyncSession, item: dict[str, Any]) -> bool:
|
||||
persist_raw, _mode = await self._should_persist_raw_ais(db)
|
||||
now = datetime.now(UTC)
|
||||
observed_at = item.get("received_at") or now
|
||||
observation = await record_vessel_ais_observation(
|
||||
@@ -355,7 +450,10 @@ class AISStreamCollector(BaseCollector):
|
||||
source_message_id=item.get("_source_message_id"),
|
||||
observed_at=observed_at,
|
||||
collected_at=now,
|
||||
persist_raw=persist_raw,
|
||||
)
|
||||
if not persist_raw:
|
||||
await prune_expired_vessel_track_points(db, now=now)
|
||||
await update_ais_source_health(
|
||||
db,
|
||||
source=self.name,
|
||||
|
||||
+1138
-161
File diff suppressed because it is too large.
Load diff
@@ -4,15 +4,14 @@ from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from collections import defaultdict
|
||||
from datetime import UTC, datetime
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy import or_, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.bgp_anomaly import BGPAnomaly
|
||||
from app.models.bgp_observation import BGPObservation
|
||||
from app.models.collected_data import CollectedData
|
||||
from app.services.bgp_collector_locations import (
|
||||
RIPE_RIS_COLLECTOR_COORDS,
|
||||
get_bgp_collector_location_dict,
|
||||
@@ -37,11 +36,49 @@ from app.services.bgp_enrichment import enrich_bgp_events_for_batch, extract_bgp
|
||||
__all__ = [
|
||||
"RIPE_RIS_COLLECTOR_COORDS",
|
||||
"normalize_bgp_event",
|
||||
"slim_bgp_events_for_collected_data",
|
||||
"compact_bgp_raw_payload",
|
||||
"save_bgp_observations_for_batch",
|
||||
"create_bgp_anomalies_for_batch",
|
||||
]
|
||||
|
||||
|
||||
def compact_bgp_raw_payload(metadata: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Build a compact BGP observation summary payload without raw verbose envelopes."""
|
||||
compact: dict[str, Any] = {}
|
||||
for key in (
|
||||
"event_type",
|
||||
"prefix",
|
||||
"origin_asn",
|
||||
"as_path",
|
||||
"collector",
|
||||
"peer_ip",
|
||||
"peer_asn",
|
||||
"next_hop",
|
||||
"communities",
|
||||
"timestamp",
|
||||
):
|
||||
value = metadata.get(key)
|
||||
if value not in (None, [], ""):
|
||||
compact[key] = value
|
||||
return compact
|
||||
|
||||
|
||||
def slim_bgp_events_for_collected_data(
|
||||
events: list[dict[str, Any]],
|
||||
*,
|
||||
max_rows: int = 500,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Strip heavyweight `raw_message` payloads and bound single-copy BGP batch size."""
|
||||
selected = events[-max_rows:] if max_rows > 0 and len(events) > max_rows else list(events)
|
||||
slimmed: list[dict[str, Any]] = []
|
||||
for event in selected:
|
||||
metadata = dict(event.get("metadata") or {})
|
||||
metadata.pop("raw_message", None)
|
||||
slimmed.append({**event, "metadata": metadata})
|
||||
return slimmed
|
||||
|
||||
|
||||
def _safe_int(value: Any) -> int | None:
|
||||
try:
|
||||
if value in (None, ""):
|
||||
@@ -184,6 +221,7 @@ async def save_bgp_observations_for_batch(
|
||||
snapshot_id: int | None,
|
||||
task_id: int | None,
|
||||
events: list[dict[str, Any]],
|
||||
compact_raw_payload: bool = False,
|
||||
) -> int:
|
||||
if not events:
|
||||
return 0
|
||||
@@ -197,6 +235,11 @@ async def save_bgp_observations_for_batch(
|
||||
observed_at = _parse_timestamp(
|
||||
metadata.get("timestamp") or event.get("reference_date")
|
||||
)
|
||||
raw_payload = (
|
||||
compact_bgp_raw_payload(metadata)
|
||||
if compact_raw_payload
|
||||
else (metadata.get("raw_message") or {})
|
||||
)
|
||||
|
||||
db.add(
|
||||
BGPObservation(
|
||||
@@ -216,7 +259,7 @@ async def save_bgp_observations_for_batch(
|
||||
communities=metadata.get("communities") or [],
|
||||
observed_at=observed_at,
|
||||
collector_geo=collector_location,
|
||||
raw_payload=metadata.get("raw_message") or {},
|
||||
raw_payload=raw_payload,
|
||||
note=event.get("description"),
|
||||
)
|
||||
)
|
||||
@@ -224,8 +267,8 @@ async def save_bgp_observations_for_batch(
|
||||
|
||||
if created:
|
||||
await db.commit()
|
||||
for source in {"ris_live_bgp", "bgpstream_bgp"}:
|
||||
invalidate_earth_layer_cache_for_source(source)
|
||||
for cache_source in {"ris_live_bgp", "bgpstream_bgp"}:
|
||||
invalidate_earth_layer_cache_for_source(cache_source)
|
||||
|
||||
return created
|
||||
|
||||
@@ -255,17 +298,29 @@ async def create_bgp_anomalies_for_batch(
|
||||
previous_origin_map: dict[str, set[int]] = defaultdict(set)
|
||||
|
||||
if prefixes:
|
||||
previous_query = await db.execute(
|
||||
select(CollectedData).where(
|
||||
CollectedData.source == source,
|
||||
CollectedData.snapshot_id != snapshot_id,
|
||||
CollectedData.extra_data["prefix"].as_string().in_(sorted(prefixes)),
|
||||
lookback_since = datetime.now(UTC) - timedelta(days=7)
|
||||
baseline_filters = [
|
||||
BGPObservation.source == source,
|
||||
BGPObservation.prefix.in_(sorted(prefixes)),
|
||||
BGPObservation.origin_asn.is_not(None),
|
||||
BGPObservation.observed_at >= lookback_since,
|
||||
]
|
||||
if task_id is not None:
|
||||
baseline_filters.append(
|
||||
or_(BGPObservation.task_id.is_(None), BGPObservation.task_id != task_id)
|
||||
)
|
||||
)
|
||||
elif snapshot_id is not None:
|
||||
baseline_filters.append(
|
||||
or_(BGPObservation.snapshot_id.is_(None), BGPObservation.snapshot_id != snapshot_id)
|
||||
)
|
||||
previous_query = await db.execute(select(BGPObservation).where(*baseline_filters))
|
||||
for record in previous_query.scalars().all():
|
||||
metadata = record.extra_data or {}
|
||||
prefix = metadata.get("prefix")
|
||||
origin = _safe_int(metadata.get("origin_asn"))
|
||||
prefix = getattr(record, "prefix", None)
|
||||
origin = _safe_int(getattr(record, "origin_asn", None))
|
||||
if (prefix is None or origin is None) and hasattr(record, "extra_data"):
|
||||
metadata = record.extra_data or {}
|
||||
prefix = prefix or metadata.get("prefix")
|
||||
origin = origin if origin is not None else _safe_int(metadata.get("origin_asn"))
|
||||
if prefix and origin is not None:
|
||||
previous_origin_map[prefix].add(origin)
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ from app.services.collectors.bgp_common import (
|
||||
create_bgp_anomalies_for_batch,
|
||||
normalize_bgp_event,
|
||||
save_bgp_observations_for_batch,
|
||||
slim_bgp_events_for_collected_data,
|
||||
)
|
||||
|
||||
|
||||
@@ -96,6 +97,29 @@ class BGPStreamBackfillCollector(BaseCollector):
|
||||
self._latest_transformed_batch = transformed
|
||||
return transformed
|
||||
|
||||
async def _save_data(
|
||||
self,
|
||||
db,
|
||||
data: list[dict[str, Any]],
|
||||
task_id: int | None = None,
|
||||
snapshot_id: int | None = None,
|
||||
) -> int:
|
||||
if callable(getattr(db, "execute", None)):
|
||||
mode, policy = await self._resolve_storage_policy(db)
|
||||
else:
|
||||
mode = self._snapshot_mode
|
||||
policy = self._storage_policy or {}
|
||||
prepared_data = data
|
||||
if (mode or "single") == "single":
|
||||
max_rows = int(policy.get("bgp_single_batch_max_rows", 500))
|
||||
prepared_data = slim_bgp_events_for_collected_data(data, max_rows=max_rows)
|
||||
return await super()._save_data(
|
||||
db,
|
||||
prepared_data,
|
||||
task_id=task_id,
|
||||
snapshot_id=snapshot_id,
|
||||
)
|
||||
|
||||
async def run(self, db):
|
||||
result = await super().run(db)
|
||||
if result.get("status") != "success":
|
||||
@@ -108,6 +132,7 @@ class BGPStreamBackfillCollector(BaseCollector):
|
||||
snapshot_id=snapshot_id,
|
||||
task_id=result.get("task_id"),
|
||||
events=getattr(self, "_latest_transformed_batch", []),
|
||||
compact_raw_payload=(self._snapshot_mode != "history"),
|
||||
)
|
||||
anomaly_count = await create_bgp_anomalies_for_batch(
|
||||
db,
|
||||
@@ -121,6 +146,10 @@ class BGPStreamBackfillCollector(BaseCollector):
|
||||
return result
|
||||
|
||||
async def _resolve_snapshot_id(self, db, task_id: int | None) -> int | None:
|
||||
if getattr(self, "_deduped_unchanged_snapshot_id", None) is not None:
|
||||
return self._deduped_unchanged_snapshot_id
|
||||
if getattr(self, "_reused_snapshot_id", None) is not None:
|
||||
return self._reused_snapshot_id
|
||||
if task_id is None:
|
||||
return None
|
||||
from sqlalchemy import select
|
||||
|
||||
@@ -98,7 +98,18 @@ class CelesTrakTLECollector(BaseCollector):
|
||||
progress_callback=self._report_download_progress,
|
||||
validate_existing=self._validate_json_file,
|
||||
)
|
||||
file_sha256 = self._downloader.get_file_sha256(url, ".json", body_path)
|
||||
if file_sha256:
|
||||
self._last_source_file_sha256 = file_sha256
|
||||
short_snap = await self._can_short_circuit_unchanged_file(
|
||||
self._db_session,
|
||||
file_sha256=file_sha256,
|
||||
)
|
||||
if short_snap is not None:
|
||||
self._short_circuited_snapshot_id = short_snap.id
|
||||
return []
|
||||
data = await self._load_downloaded_payload(body_path, url)
|
||||
self._mark_fetch_complete(True)
|
||||
await emit_business_log(
|
||||
logger,
|
||||
event="collector.celestrak.download.success",
|
||||
@@ -124,7 +135,18 @@ class CelesTrakTLECollector(BaseCollector):
|
||||
validate_existing=self._validate_json_file,
|
||||
)
|
||||
if cached_path is not None:
|
||||
file_sha256 = self._downloader.get_file_sha256(url, ".json", cached_path)
|
||||
if file_sha256:
|
||||
self._last_source_file_sha256 = file_sha256
|
||||
short_snap = await self._can_short_circuit_unchanged_file(
|
||||
self._db_session,
|
||||
file_sha256=file_sha256,
|
||||
)
|
||||
if short_snap is not None:
|
||||
self._short_circuited_snapshot_id = short_snap.id
|
||||
return []
|
||||
data = await self._load_downloaded_payload(cached_path, url)
|
||||
self._mark_fetch_complete(True)
|
||||
await emit_business_log(
|
||||
logger,
|
||||
event="collector.celestrak.download.cached_not_updated",
|
||||
@@ -295,6 +317,7 @@ class CelesTrakTLECollector(BaseCollector):
|
||||
if not records:
|
||||
raise RuntimeError("CelesTrak fallback group mode produced no satellite records")
|
||||
|
||||
self._mark_fetch_complete(False)
|
||||
await emit_business_log(
|
||||
logger,
|
||||
event="collector.celestrak.fallback_groups.success",
|
||||
@@ -465,6 +488,7 @@ class CelesTrakTLECollector(BaseCollector):
|
||||
return None
|
||||
|
||||
def _get_sample_data(self) -> List[Dict[str, Any]]:
|
||||
self._mark_sample_fallback("celestrak_tle_sample_fallback")
|
||||
return [
|
||||
{
|
||||
"name": "STARLINK-1000",
|
||||
|
||||
@@ -14,6 +14,7 @@ from app.services.collectors.base import BaseCollector
|
||||
class ComputeCollector(BaseCollector):
|
||||
fail_on_empty = True
|
||||
preserve_snapshot_on_failure = True
|
||||
full_snapshot_reconcile = True
|
||||
|
||||
async def _create_snapshot(
|
||||
self, db: AsyncSession, task_id: int, data: list[dict], started_at: datetime
|
||||
|
||||
@@ -16,6 +16,18 @@ ProgressCallback = Callable[[int, int | None], Awaitable[None]]
|
||||
ValidateCallback = Callable[[Path], bool]
|
||||
|
||||
|
||||
def compute_file_sha256(path: Path, *, chunk_size: int = 1024 * 1024) -> str:
|
||||
"""Compute SHA-256 hex digest of a local file without loading it all into memory."""
|
||||
hasher = hashlib.sha256()
|
||||
with path.open("rb") as f:
|
||||
while True:
|
||||
chunk = f.read(chunk_size)
|
||||
if not chunk:
|
||||
break
|
||||
hasher.update(chunk)
|
||||
return hasher.hexdigest()
|
||||
|
||||
|
||||
class DownloadHTTPStatusError(RuntimeError):
|
||||
"""HTTP status error that keeps the upstream response body for caller-specific handling."""
|
||||
|
||||
@@ -105,6 +117,47 @@ class ResumableFileDownloader:
|
||||
def _save_meta(meta_path: Path, payload: dict[str, Any]) -> None:
|
||||
meta_path.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
|
||||
|
||||
@staticmethod
|
||||
def compute_combined_sha256(digests: list[str]) -> str:
|
||||
"""Combine multiple file SHA-256 digests deterministically."""
|
||||
return hashlib.sha256("|".join(digests).encode("utf-8")).hexdigest()
|
||||
|
||||
def get_file_sha256(
|
||||
self,
|
||||
url: str,
|
||||
extension: str,
|
||||
path: Path | None = None,
|
||||
) -> str | None:
|
||||
"""Return cached or freshly computed SHA-256 digest for a downloaded dataset."""
|
||||
target_path = path or self.cached_file_path(url, extension)
|
||||
if not target_path.exists():
|
||||
return None
|
||||
_, _, meta_path = self._cache_paths(url, extension)
|
||||
stat = target_path.stat()
|
||||
meta = self._load_meta(meta_path)
|
||||
cached_digest = meta.get("sha256")
|
||||
if (
|
||||
isinstance(cached_digest, str)
|
||||
and cached_digest
|
||||
and meta.get("file_size") == stat.st_size
|
||||
and meta.get("file_mtime_ns") == stat.st_mtime_ns
|
||||
):
|
||||
return cached_digest
|
||||
|
||||
digest = compute_file_sha256(target_path)
|
||||
if meta_path.parent.exists():
|
||||
self._save_meta(
|
||||
meta_path,
|
||||
{
|
||||
**meta,
|
||||
"url": meta.get("url") or url,
|
||||
"sha256": digest,
|
||||
"file_size": stat.st_size,
|
||||
"file_mtime_ns": stat.st_mtime_ns,
|
||||
},
|
||||
)
|
||||
return digest
|
||||
|
||||
@staticmethod
|
||||
def _validators_match(meta: dict[str, Any], remote: dict[str, Any]) -> bool:
|
||||
etag = str(remote.get("etag") or "").strip()
|
||||
@@ -262,6 +315,8 @@ class ResumableFileDownloader:
|
||||
part_path.unlink(missing_ok=True)
|
||||
raise RuntimeError(f"Downloaded file validation failed for {url}")
|
||||
part_path.replace(final_path)
|
||||
stat = final_path.stat()
|
||||
file_sha256 = compute_file_sha256(final_path)
|
||||
self._save_meta(
|
||||
meta_path,
|
||||
{
|
||||
@@ -269,6 +324,9 @@ class ResumableFileDownloader:
|
||||
"etag": remote.get("etag"),
|
||||
"last_modified": remote.get("last_modified"),
|
||||
"content_length": expected_size,
|
||||
"sha256": file_sha256,
|
||||
"file_size": stat.st_size,
|
||||
"file_mtime_ns": stat.st_mtime_ns,
|
||||
"updated_at": datetime.now(UTC).isoformat(),
|
||||
},
|
||||
)
|
||||
|
||||
@@ -65,29 +65,40 @@ class IPtoASNPrefixGeoCollector(BaseCollector):
|
||||
raise RuntimeError(f"IPtoASN dataset parsed empty rows: {file_path.name}")
|
||||
return rows
|
||||
|
||||
async def _fetch_dataset_rows(
|
||||
async def _download_dataset_file(
|
||||
self,
|
||||
client: httpx.AsyncClient,
|
||||
url: str,
|
||||
*,
|
||||
progress_callback=None,
|
||||
) -> list[dict[str, Any]]:
|
||||
file_path = await self._downloader.download_file(
|
||||
) -> Path:
|
||||
return await self._downloader.download_file(
|
||||
client,
|
||||
url,
|
||||
extension=".tsv.gz",
|
||||
progress_callback=progress_callback,
|
||||
validate_existing=lambda p: self._validate_gzip_dataset(p),
|
||||
)
|
||||
return self._parse_rows_from_gzip_file(file_path)
|
||||
|
||||
def _validate_gzip_dataset(self, file_path: Path) -> bool:
|
||||
try:
|
||||
self._parse_rows_from_gzip_file(file_path)
|
||||
return True
|
||||
with gzip.open(file_path, "rt", encoding="utf-8", errors="replace") as f:
|
||||
for raw_line in f:
|
||||
line = raw_line.strip()
|
||||
if line and not line.startswith("#") and len(line.split("\t")) >= 5:
|
||||
for _ in f:
|
||||
pass
|
||||
return True
|
||||
return False
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def _parse_dataset_files(self, dataset_paths: list[Path]) -> list[dict[str, Any]]:
|
||||
rows: list[dict[str, Any]] = []
|
||||
for path in dataset_paths:
|
||||
rows.extend(self._parse_rows_from_gzip_file(path))
|
||||
return rows
|
||||
|
||||
async def fetch(self) -> list[dict[str, Any]]:
|
||||
if not self._resolved_url:
|
||||
raise RuntimeError("IPtoASN combined URL is not configured")
|
||||
@@ -149,9 +160,9 @@ class IPtoASNPrefixGeoCollector(BaseCollector):
|
||||
)
|
||||
await self.update_progress(current, commit=True)
|
||||
|
||||
batches = await asyncio.gather(
|
||||
dataset_paths = await asyncio.gather(
|
||||
*(
|
||||
self._fetch_dataset_rows(
|
||||
self._download_dataset_file(
|
||||
client,
|
||||
url,
|
||||
progress_callback=lambda downloaded, total, u=url: on_url_progress(u, downloaded, total),
|
||||
@@ -168,10 +179,23 @@ class IPtoASNPrefixGeoCollector(BaseCollector):
|
||||
)
|
||||
await self.update_progress(total_expected, commit=True, force=True)
|
||||
|
||||
rows: list[dict[str, Any]] = []
|
||||
for batch in batches:
|
||||
rows.extend(batch)
|
||||
return rows
|
||||
digests = [
|
||||
self._downloader.get_file_sha256(url, ".tsv.gz", path)
|
||||
for url, path in zip(dataset_urls, dataset_paths)
|
||||
]
|
||||
if digests and all(isinstance(d, str) and d for d in digests):
|
||||
combined_sha256 = self._downloader.compute_combined_sha256([str(d) for d in digests])
|
||||
self._last_source_file_sha256 = combined_sha256
|
||||
short_snap = await self._can_short_circuit_unchanged_file(
|
||||
self._db_session,
|
||||
file_sha256=combined_sha256,
|
||||
)
|
||||
if short_snap is not None:
|
||||
self._short_circuited_snapshot_id = short_snap.id
|
||||
return []
|
||||
|
||||
self._mark_fetch_complete(True)
|
||||
return await asyncio.to_thread(self._parse_dataset_files, dataset_paths)
|
||||
|
||||
def transform(self, raw_data: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
reference_date = datetime.now(UTC).isoformat()
|
||||
|
||||
@@ -6,8 +6,10 @@ allocation geography as prefix-centric fallback hints.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import ipaddress
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
@@ -64,42 +66,57 @@ class NRODelegatedPrefixGeoCollector(BaseCollector):
|
||||
extension=".txt",
|
||||
progress_callback=on_progress,
|
||||
)
|
||||
body = body_path.read_text(encoding="utf-8", errors="replace")
|
||||
file_sha256 = self._downloader.get_file_sha256(self._resolved_url, ".txt", body_path)
|
||||
if file_sha256:
|
||||
self._last_source_file_sha256 = file_sha256
|
||||
short_snap = await self._can_short_circuit_unchanged_file(
|
||||
self._db_session,
|
||||
file_sha256=file_sha256,
|
||||
)
|
||||
if short_snap is not None:
|
||||
self._short_circuited_snapshot_id = short_snap.id
|
||||
return []
|
||||
|
||||
self._mark_fetch_complete(True)
|
||||
return await asyncio.to_thread(self._parse_delegated_file, body_path)
|
||||
|
||||
def _parse_delegated_file(self, body_path: Path) -> list[dict[str, Any]]:
|
||||
"""Stream and parse NRO delegated stats line-by-line off the event loop."""
|
||||
rows: list[dict[str, Any]] = []
|
||||
for raw_line in body.splitlines():
|
||||
line = raw_line.strip()
|
||||
if not line or line.startswith("#"):
|
||||
continue
|
||||
with body_path.open("r", encoding="utf-8", errors="replace") as handle:
|
||||
for raw_line in handle:
|
||||
line = raw_line.strip()
|
||||
if not line or line.startswith("#"):
|
||||
continue
|
||||
|
||||
parts = line.split("|")
|
||||
if len(parts) < 7:
|
||||
continue
|
||||
parts = line.split("|")
|
||||
if len(parts) < 7:
|
||||
continue
|
||||
|
||||
rir = (parts[0] or "").strip().lower()
|
||||
country_code = (parts[1] or "").strip().upper()
|
||||
record_type = (parts[2] or "").strip().lower()
|
||||
start = (parts[3] or "").strip()
|
||||
value = (parts[4] or "").strip()
|
||||
allocated_date = (parts[5] or "").strip()
|
||||
status = (parts[6] or "").strip().lower()
|
||||
rir = (parts[0] or "").strip().lower()
|
||||
country_code = (parts[1] or "").strip().upper()
|
||||
record_type = (parts[2] or "").strip().lower()
|
||||
start = (parts[3] or "").strip()
|
||||
value = (parts[4] or "").strip()
|
||||
allocated_date = (parts[5] or "").strip()
|
||||
status = (parts[6] or "").strip().lower()
|
||||
|
||||
if record_type not in {"ipv4", "ipv6"}:
|
||||
continue
|
||||
if not start or not value:
|
||||
continue
|
||||
if record_type not in {"ipv4", "ipv6"}:
|
||||
continue
|
||||
if not start or not value:
|
||||
continue
|
||||
|
||||
rows.append(
|
||||
{
|
||||
"rir": rir,
|
||||
"country_code": country_code,
|
||||
"type": record_type,
|
||||
"start": start,
|
||||
"value": value,
|
||||
"allocated_date": allocated_date,
|
||||
"status": status,
|
||||
}
|
||||
)
|
||||
rows.append(
|
||||
{
|
||||
"rir": rir,
|
||||
"country_code": country_code,
|
||||
"type": record_type,
|
||||
"start": start,
|
||||
"value": value,
|
||||
"allocated_date": allocated_date,
|
||||
"status": status,
|
||||
}
|
||||
)
|
||||
|
||||
return rows
|
||||
|
||||
|
||||
@@ -65,6 +65,16 @@ class OpenGeoFeedPrefixGeoCollector(BaseCollector):
|
||||
extension=".csv",
|
||||
progress_callback=on_progress,
|
||||
)
|
||||
file_sha256 = self._downloader.get_file_sha256(self._resolved_url, ".csv", body_path)
|
||||
if file_sha256:
|
||||
self._last_source_file_sha256 = file_sha256
|
||||
short_snap = await self._can_short_circuit_unchanged_file(
|
||||
self._db_session,
|
||||
file_sha256=file_sha256,
|
||||
)
|
||||
if short_snap is not None:
|
||||
self._short_circuited_snapshot_id = short_snap.id
|
||||
return []
|
||||
body = body_path.read_text(encoding="utf-8", errors="replace")
|
||||
|
||||
rows: list[dict[str, Any]] = []
|
||||
|
||||
@@ -17,6 +17,7 @@ from app.services.collectors.bgp_common import (
|
||||
create_bgp_anomalies_for_batch,
|
||||
normalize_bgp_event,
|
||||
save_bgp_observations_for_batch,
|
||||
slim_bgp_events_for_collected_data,
|
||||
)
|
||||
|
||||
logger = get_logger(__name__, service="collector")
|
||||
@@ -177,6 +178,29 @@ class RISLiveCollector(BaseCollector):
|
||||
self._latest_transformed_batch = transformed
|
||||
return transformed
|
||||
|
||||
async def _save_data(
|
||||
self,
|
||||
db,
|
||||
data: list[dict[str, Any]],
|
||||
task_id: int | None = None,
|
||||
snapshot_id: int | None = None,
|
||||
) -> int:
|
||||
if callable(getattr(db, "execute", None)):
|
||||
mode, policy = await self._resolve_storage_policy(db)
|
||||
else:
|
||||
mode = self._snapshot_mode
|
||||
policy = self._storage_policy or {}
|
||||
prepared_data = data
|
||||
if (mode or "single") == "single":
|
||||
max_rows = int(policy.get("bgp_single_batch_max_rows", 500))
|
||||
prepared_data = slim_bgp_events_for_collected_data(data, max_rows=max_rows)
|
||||
return await super()._save_data(
|
||||
db,
|
||||
prepared_data,
|
||||
task_id=task_id,
|
||||
snapshot_id=snapshot_id,
|
||||
)
|
||||
|
||||
async def run(self, db):
|
||||
result = await super().run(db)
|
||||
if result.get("status") != "success":
|
||||
@@ -189,6 +213,7 @@ class RISLiveCollector(BaseCollector):
|
||||
snapshot_id=snapshot_id,
|
||||
task_id=result.get("task_id"),
|
||||
events=getattr(self, "_latest_transformed_batch", []),
|
||||
compact_raw_payload=(self._snapshot_mode != "history"),
|
||||
)
|
||||
anomaly_count = await create_bgp_anomalies_for_batch(
|
||||
db,
|
||||
@@ -202,6 +227,10 @@ class RISLiveCollector(BaseCollector):
|
||||
return result
|
||||
|
||||
async def _resolve_snapshot_id(self, db, task_id: int | None) -> int | None:
|
||||
if getattr(self, "_deduped_unchanged_snapshot_id", None) is not None:
|
||||
return self._deduped_unchanged_snapshot_id
|
||||
if getattr(self, "_reused_snapshot_id", None) is not None:
|
||||
return self._reused_snapshot_id
|
||||
if task_id is None:
|
||||
return None
|
||||
from sqlalchemy import select
|
||||
|
||||
@@ -213,6 +213,7 @@ class SpaceTrackTLECollector(BaseCollector):
|
||||
|
||||
def _get_sample_data(self) -> List[Dict[str, Any]]:
|
||||
"""Return sample TLE data for testing"""
|
||||
self._mark_sample_fallback("spacetrack_tle_sample_fallback")
|
||||
return [
|
||||
{
|
||||
"name": "ISS (ZARYA)",
|
||||
|
||||
@@ -119,6 +119,7 @@ class TeleGeographyCableCollector(BaseCollector):
|
||||
|
||||
def _get_sample_data(self) -> List[Dict[str, Any]]:
|
||||
"""Return sample submarine cable data"""
|
||||
self._mark_sample_fallback("telegeography_cables_sample_fallback")
|
||||
return [
|
||||
{
|
||||
"source_id": "telegeo_sample_1",
|
||||
@@ -235,6 +236,7 @@ class TeleGeographyLandingPointCollector(BaseCollector):
|
||||
|
||||
def _get_sample_data(self) -> List[Dict[str, Any]]:
|
||||
"""Return sample landing point data"""
|
||||
self._mark_sample_fallback("telegeography_landing_sample_fallback")
|
||||
return [
|
||||
{
|
||||
"source_id": "telegeo_lp_sample_1",
|
||||
@@ -306,6 +308,7 @@ class TeleGeographyCableSystemCollector(BaseCollector):
|
||||
|
||||
def _get_sample_data(self) -> List[Dict[str, Any]]:
|
||||
"""Return sample cable system data"""
|
||||
self._mark_sample_fallback("telegeography_systems_sample_fallback")
|
||||
return [
|
||||
{
|
||||
"source_id": "telegeo_sys_sample_1",
|
||||
|
||||
@@ -4,20 +4,24 @@ from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.enums import SnapshotStatus
|
||||
from app.core.time import to_iso8601_utc
|
||||
from app.core.websocket.broadcaster import broadcaster
|
||||
from app.models.vessel import VesselCurrentState
|
||||
from app.services.barentswatch import (
|
||||
BARENTSWATCH_LATEST_URL,
|
||||
fetch_barentswatch_access_token,
|
||||
resolve_barentswatch_config,
|
||||
)
|
||||
from app.services.collectors.base import BaseCollector
|
||||
from app.services.collectors.base import BaseCollector, _StoragePolicyDowngradedToSingle
|
||||
from app.services.storage_policy import is_storage_policy_single_violation
|
||||
from app.services.vessel_ais_aggregation import (
|
||||
BARENTSWATCH_DELIVERY_MODE,
|
||||
BARENTSWATCH_TRANSPORT,
|
||||
prune_expired_vessel_track_points,
|
||||
record_vessel_ais_observation,
|
||||
update_ais_source_health,
|
||||
)
|
||||
@@ -80,12 +84,87 @@ class VesselAISCollector(BaseCollector):
|
||||
transformed.append(record)
|
||||
return transformed
|
||||
|
||||
async def _has_existing_current_data(self, db: AsyncSession | None) -> bool:
|
||||
if db is None or not callable(getattr(db, "execute", None)):
|
||||
return False
|
||||
try:
|
||||
result = await db.execute(
|
||||
select(VesselCurrentState.mmsi)
|
||||
.where(VesselCurrentState.source == self.name)
|
||||
.limit(1)
|
||||
)
|
||||
except Exception:
|
||||
return False
|
||||
if result is None or not callable(getattr(result, "scalar_one_or_none", None)):
|
||||
return False
|
||||
return result.scalar_one_or_none() is not None
|
||||
|
||||
async def _save_data(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
data: list[dict[str, Any]],
|
||||
task_id: int | None = None,
|
||||
snapshot_id: int | None = None,
|
||||
) -> int:
|
||||
if callable(getattr(db, "execute", None)):
|
||||
mode, _ = await self._resolve_storage_policy(db)
|
||||
else:
|
||||
mode = self._snapshot_mode or "single"
|
||||
if self._fetch_is_sample_fallback and await self._has_existing_current_data(db):
|
||||
raise RuntimeError(
|
||||
f"Collector {self.name} refused to save sample fallback data over existing vessels"
|
||||
)
|
||||
persist_raw = mode == "history"
|
||||
snapshot_id = await self._reconcile_snapshot_for_mode_switch(
|
||||
db,
|
||||
mode=mode,
|
||||
task_id=task_id,
|
||||
snapshot_id=snapshot_id,
|
||||
)
|
||||
|
||||
try:
|
||||
records_added = await self._write_ais_batch(
|
||||
db,
|
||||
data,
|
||||
persist_raw=persist_raw,
|
||||
mode=mode,
|
||||
snapshot_id=snapshot_id,
|
||||
)
|
||||
if persist_raw:
|
||||
await self._assert_versioned_publish_allowed(db, snapshot_id=snapshot_id)
|
||||
await db.commit()
|
||||
except Exception as exc:
|
||||
if (
|
||||
(not isinstance(exc, _StoragePolicyDowngradedToSingle) and not is_storage_policy_single_violation(exc))
|
||||
or self._previous_current_snapshot_id is None
|
||||
):
|
||||
raise
|
||||
downgraded_snapshot_id = await self._downgrade_pending_snapshot_to_single(
|
||||
db,
|
||||
task_id=task_id,
|
||||
snapshot_id=snapshot_id,
|
||||
)
|
||||
records_added = await self._write_ais_batch(
|
||||
db,
|
||||
data,
|
||||
persist_raw=False,
|
||||
mode="single",
|
||||
snapshot_id=downgraded_snapshot_id,
|
||||
)
|
||||
await db.commit()
|
||||
|
||||
await self._broadcast_vessel_snapshot(data)
|
||||
await self.update_progress(records_added, force=True)
|
||||
return records_added
|
||||
|
||||
async def _write_ais_batch(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
data: list[dict[str, Any]],
|
||||
*,
|
||||
persist_raw: bool,
|
||||
mode: str,
|
||||
snapshot_id: int | None,
|
||||
) -> int:
|
||||
now = datetime.now(UTC)
|
||||
records_added = 0
|
||||
@@ -101,11 +180,15 @@ class VesselAISCollector(BaseCollector):
|
||||
transport=BARENTSWATCH_TRANSPORT,
|
||||
observed_at=observed_at,
|
||||
collected_at=now,
|
||||
persist_raw=persist_raw,
|
||||
)
|
||||
records_added += 1
|
||||
|
||||
if (index + 1) % 1000 == 0:
|
||||
await self.update_progress(index + 1, commit=True)
|
||||
await self.update_progress(index + 1, commit=False)
|
||||
|
||||
if not persist_raw:
|
||||
await prune_expired_vessel_track_points(db, now=now)
|
||||
|
||||
latest_observed_at = max(
|
||||
(item.get("received_at") for item in data if item.get("received_at")),
|
||||
@@ -125,6 +208,7 @@ class VesselAISCollector(BaseCollector):
|
||||
|
||||
snapshot = await db.get(DataSnapshot, snapshot_id)
|
||||
if snapshot:
|
||||
await self._promote_snapshot_to_current(db, snapshot)
|
||||
snapshot.record_count = records_added
|
||||
snapshot.status = SnapshotStatus.SUCCESS.value
|
||||
snapshot.completed_at = now
|
||||
@@ -133,11 +217,9 @@ class VesselAISCollector(BaseCollector):
|
||||
"updated": 0,
|
||||
"unchanged": 0,
|
||||
"deleted": 0,
|
||||
"storage": "ais_raw_observations",
|
||||
"storage": "ais_raw_observations" if persist_raw else "vessel_current_state_and_24h_track",
|
||||
"storage_mode": mode,
|
||||
}
|
||||
await db.commit()
|
||||
await self._broadcast_vessel_snapshot(data)
|
||||
await self.update_progress(records_added, force=True)
|
||||
return records_added
|
||||
|
||||
async def _broadcast_vessel_snapshot(self, data: list[dict[str, Any]]) -> None:
|
||||
@@ -219,6 +301,7 @@ class VesselAISCollector(BaseCollector):
|
||||
}
|
||||
|
||||
def _get_sample_data(self) -> list[dict[str, Any]]:
|
||||
self._mark_sample_fallback("barentswatch_vessels_sample_fallback")
|
||||
return [
|
||||
{
|
||||
"mmsi": 257123000,
|
||||
|
||||
@@ -299,47 +299,80 @@ async def persist_mapped_records(
|
||||
mapping_version: int,
|
||||
delivery_mode: str | None = None,
|
||||
transport: str | None = None,
|
||||
snapshot_mode: str | None = None,
|
||||
) -> int:
|
||||
"""Persist validated mapped records to the destination for a target schema."""
|
||||
from app.services.storage_policy import (
|
||||
acquire_storage_policy_publish_lock,
|
||||
compute_record_content_hash,
|
||||
resolve_collector_storage_policy,
|
||||
)
|
||||
|
||||
can_query_db = callable(getattr(db, "execute", None))
|
||||
if can_query_db:
|
||||
resolved_mode, policy = await resolve_collector_storage_policy(db, datasource_name)
|
||||
if policy.get("global_single_lock"):
|
||||
effective_mode = "single"
|
||||
elif snapshot_mode is not None:
|
||||
effective_mode = snapshot_mode
|
||||
else:
|
||||
effective_mode = resolved_mode
|
||||
else:
|
||||
effective_mode = snapshot_mode or "single"
|
||||
|
||||
if target_schema == "vessel_ais":
|
||||
from app.core.time import to_iso8601_utc
|
||||
from app.core.websocket.broadcaster import broadcaster
|
||||
from app.services.vessel_ais_aggregation import (
|
||||
prune_expired_vessel_track_points,
|
||||
record_vessel_ais_observation,
|
||||
update_ais_source_health,
|
||||
)
|
||||
|
||||
now = datetime.now(UTC)
|
||||
latest_observed_at = now
|
||||
written_count = 0
|
||||
for record in records:
|
||||
observed_at = _parse_datetime(record.get("received_at")) or now
|
||||
observation = await record_vessel_ais_observation(
|
||||
for attempt in range(2):
|
||||
now = datetime.now(UTC)
|
||||
latest_observed_at = now
|
||||
written_count = 0
|
||||
persist_raw = effective_mode == "history"
|
||||
for record in records:
|
||||
observed_at = _parse_datetime(record.get("received_at")) or now
|
||||
observation = await record_vessel_ais_observation(
|
||||
db,
|
||||
source=datasource_name,
|
||||
normalized_payload=record,
|
||||
raw_payload=record,
|
||||
delivery_mode=delivery_mode or "polling",
|
||||
transport=transport or "http",
|
||||
message_type="PositionReport",
|
||||
observed_at=observed_at,
|
||||
collected_at=now,
|
||||
persist_raw=persist_raw,
|
||||
)
|
||||
if observation is not None:
|
||||
written_count += 1
|
||||
if observed_at > latest_observed_at:
|
||||
latest_observed_at = observed_at
|
||||
|
||||
if not persist_raw:
|
||||
await prune_expired_vessel_track_points(db, now=now)
|
||||
|
||||
await update_ais_source_health(
|
||||
db,
|
||||
source=datasource_name,
|
||||
normalized_payload=record,
|
||||
raw_payload=record,
|
||||
delivery_mode=delivery_mode or "polling",
|
||||
transport=transport or "http",
|
||||
message_type="PositionReport",
|
||||
observed_at=observed_at,
|
||||
collected_at=now,
|
||||
connection_state="connected",
|
||||
observed_count=len(records),
|
||||
last_seen_at=latest_observed_at,
|
||||
last_success_at=now if records else None,
|
||||
lag_seconds=max((now - latest_observed_at).total_seconds(), 0),
|
||||
)
|
||||
if observation is not None:
|
||||
written_count += 1
|
||||
if observed_at > latest_observed_at:
|
||||
latest_observed_at = observed_at
|
||||
|
||||
await update_ais_source_health(
|
||||
db,
|
||||
source=datasource_name,
|
||||
connection_state="connected",
|
||||
observed_count=len(records),
|
||||
last_seen_at=latest_observed_at,
|
||||
last_success_at=now if records else None,
|
||||
lag_seconds=max((now - latest_observed_at).total_seconds(), 0),
|
||||
)
|
||||
await db.commit()
|
||||
if persist_raw and can_query_db and attempt == 0:
|
||||
latest_mode, _ = await acquire_storage_policy_publish_lock(db, datasource_name)
|
||||
if latest_mode == "single":
|
||||
await db.rollback()
|
||||
effective_mode = "single"
|
||||
continue
|
||||
await db.commit()
|
||||
break
|
||||
if records:
|
||||
await broadcaster.broadcast_custom(
|
||||
"vessels",
|
||||
@@ -369,9 +402,11 @@ async def persist_mapped_records(
|
||||
)
|
||||
return written_count
|
||||
|
||||
from sqlalchemy import select
|
||||
from app.models.collected_data import CollectedData
|
||||
|
||||
collected_at = datetime.now(UTC)
|
||||
prepared_by_key: dict[str, dict[str, Any]] = {}
|
||||
for index, record in enumerate(records):
|
||||
if target_schema == "geo_points":
|
||||
source_id = record.get("source_id") or f"{datasource_config_id}:{index}"
|
||||
@@ -383,6 +418,7 @@ async def persist_mapped_records(
|
||||
"mapping_version": mapping_version,
|
||||
"target_schema": target_schema,
|
||||
**(record.get("metadata") or {}),
|
||||
"datasource_config_id": datasource_config_id,
|
||||
}
|
||||
reference_date = _parse_datetime(record.get("observed_at"))
|
||||
else:
|
||||
@@ -392,26 +428,147 @@ async def persist_mapped_records(
|
||||
"data": record.get("data") or {},
|
||||
"mapping_version": mapping_version,
|
||||
"target_schema": target_schema,
|
||||
"datasource_config_id": datasource_config_id,
|
||||
}
|
||||
reference_date = _parse_datetime(record.get("observed_at"))
|
||||
|
||||
db.add(
|
||||
CollectedData(
|
||||
source=datasource_name,
|
||||
source_id=str(source_id),
|
||||
entity_key=f"{datasource_name}:{source_id}",
|
||||
data_type=target_schema,
|
||||
name=name,
|
||||
title=name,
|
||||
extra_data=metadata,
|
||||
collected_at=collected_at,
|
||||
reference_date=reference_date,
|
||||
is_valid=1,
|
||||
is_current=True,
|
||||
change_type="created",
|
||||
change_summary={},
|
||||
)
|
||||
source_id_str = str(source_id)
|
||||
# Scope entity identity by datasource_config_id so same-named configs stay isolated.
|
||||
entity_key = f"datasource_config:{datasource_config_id}:{source_id_str}"
|
||||
content_hash = compute_record_content_hash(
|
||||
{
|
||||
"name": name,
|
||||
"title": name,
|
||||
"metadata": metadata,
|
||||
"reference_date": reference_date.isoformat() if reference_date else None,
|
||||
}
|
||||
)
|
||||
prepared_by_key[entity_key] = {
|
||||
"source_id": source_id_str,
|
||||
"entity_key": entity_key,
|
||||
"name": name,
|
||||
"metadata": metadata,
|
||||
"reference_date": reference_date,
|
||||
"content_hash": content_hash,
|
||||
}
|
||||
|
||||
await db.commit()
|
||||
return len(records)
|
||||
if not prepared_by_key:
|
||||
return 0
|
||||
|
||||
if not can_query_db:
|
||||
for item in prepared_by_key.values():
|
||||
db.add(
|
||||
CollectedData(
|
||||
source=datasource_name,
|
||||
source_id=item["source_id"],
|
||||
entity_key=item["entity_key"],
|
||||
data_type=target_schema,
|
||||
name=item["name"],
|
||||
title=item["name"],
|
||||
extra_data=item["metadata"],
|
||||
collected_at=collected_at,
|
||||
reference_date=item["reference_date"],
|
||||
is_valid=1,
|
||||
is_current=True,
|
||||
change_type="created",
|
||||
change_summary={},
|
||||
content_hash=item["content_hash"],
|
||||
)
|
||||
)
|
||||
await db.commit()
|
||||
return len(prepared_by_key)
|
||||
|
||||
for attempt in range(2):
|
||||
existing_result = await db.execute(
|
||||
select(CollectedData)
|
||||
.where(
|
||||
CollectedData.source == datasource_name,
|
||||
CollectedData.entity_key.in_(list(prepared_by_key.keys())),
|
||||
CollectedData.is_current.is_(True),
|
||||
CollectedData.deleted_at.is_(None),
|
||||
)
|
||||
.order_by(CollectedData.id.desc())
|
||||
)
|
||||
existing_by_key: dict[str, CollectedData] = {}
|
||||
for row in existing_result.scalars().all():
|
||||
if row.entity_key not in existing_by_key:
|
||||
existing_by_key[row.entity_key] = row
|
||||
else:
|
||||
row.is_current = False
|
||||
|
||||
if effective_mode == "history":
|
||||
pending_inserts: list[tuple[str, dict[str, Any], CollectedData | None]] = []
|
||||
for entity_key, item in prepared_by_key.items():
|
||||
prev = existing_by_key.get(entity_key)
|
||||
if prev is not None and prev.content_hash == item["content_hash"]:
|
||||
continue
|
||||
if prev is not None:
|
||||
prev.is_current = False
|
||||
pending_inserts.append((entity_key, item, prev))
|
||||
if pending_inserts and hasattr(db, "flush"):
|
||||
await db.flush()
|
||||
for entity_key, item, prev in pending_inserts:
|
||||
db.add(
|
||||
CollectedData(
|
||||
source=datasource_name,
|
||||
source_id=item["source_id"],
|
||||
entity_key=entity_key,
|
||||
data_type=target_schema,
|
||||
name=item["name"],
|
||||
title=item["name"],
|
||||
extra_data=item["metadata"],
|
||||
collected_at=collected_at,
|
||||
reference_date=item["reference_date"],
|
||||
is_valid=1,
|
||||
is_current=True,
|
||||
previous_record_id=prev.id if prev is not None else None,
|
||||
change_type="created" if prev is None else "updated",
|
||||
change_summary={},
|
||||
content_hash=item["content_hash"],
|
||||
)
|
||||
)
|
||||
if attempt == 0:
|
||||
latest_mode, _ = await acquire_storage_policy_publish_lock(db, datasource_name)
|
||||
if latest_mode == "single":
|
||||
await db.rollback()
|
||||
effective_mode = "single"
|
||||
continue
|
||||
else:
|
||||
for entity_key, item in prepared_by_key.items():
|
||||
existing = existing_by_key.get(entity_key)
|
||||
if existing is None:
|
||||
db.add(
|
||||
CollectedData(
|
||||
source=datasource_name,
|
||||
source_id=item["source_id"],
|
||||
entity_key=entity_key,
|
||||
data_type=target_schema,
|
||||
name=item["name"],
|
||||
title=item["name"],
|
||||
extra_data=item["metadata"],
|
||||
collected_at=collected_at,
|
||||
reference_date=item["reference_date"],
|
||||
is_valid=1,
|
||||
is_current=True,
|
||||
previous_record_id=None,
|
||||
change_type="created",
|
||||
change_summary={},
|
||||
content_hash=item["content_hash"],
|
||||
)
|
||||
)
|
||||
elif existing.content_hash != item["content_hash"]:
|
||||
existing.source_id = item["source_id"]
|
||||
existing.data_type = target_schema
|
||||
existing.name = item["name"]
|
||||
existing.title = item["name"]
|
||||
existing.extra_data = item["metadata"]
|
||||
existing.collected_at = collected_at
|
||||
existing.reference_date = item["reference_date"]
|
||||
existing.is_current = True
|
||||
existing.previous_record_id = None
|
||||
existing.change_type = "updated"
|
||||
existing.content_hash = item["content_hash"]
|
||||
|
||||
await db.commit()
|
||||
break
|
||||
return len(prepared_by_key)
|
||||
@@ -172,18 +172,27 @@ async def clear_derived_datasource_data(db: AsyncSession, source: str) -> dict[s
|
||||
from app.models.bgp_anomaly import BGPAnomaly
|
||||
from app.models.bgp_incident import BGPIncident
|
||||
from app.models.bgp_observation import BGPObservation
|
||||
from app.models.vessel import AISConflictRecord, AISRawObservation, AISSourceHealth
|
||||
from app.models.vessel import (
|
||||
AISConflictRecord,
|
||||
AISRawObservation,
|
||||
AISSourceHealth,
|
||||
VesselCurrentState,
|
||||
)
|
||||
|
||||
model_by_key: dict[str, Any] = {
|
||||
"bgp_observations": BGPObservation,
|
||||
"bgp_anomalies": BGPAnomaly,
|
||||
"bgp_incidents": BGPIncident,
|
||||
"ais_raw_observations": AISRawObservation,
|
||||
"vessel_current_state": VesselCurrentState,
|
||||
"ais_conflict_records": AISConflictRecord,
|
||||
"ais_source_health": AISSourceHealth,
|
||||
}
|
||||
deleted_counts: dict[str, int] = {}
|
||||
for key in adapter.derived_models:
|
||||
keys_to_clear = list(adapter.derived_models)
|
||||
if "ais_raw_observations" in keys_to_clear and "vessel_current_state" not in keys_to_clear:
|
||||
keys_to_clear.append("vessel_current_state")
|
||||
for key in keys_to_clear:
|
||||
model = model_by_key.get(key)
|
||||
if model is None:
|
||||
continue
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
"""Task Scheduler for running collection jobs."""
|
||||
|
||||
import asyncio
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import UTC, datetime, timedelta
|
||||
import time
|
||||
from typing import Any, Dict, Optional
|
||||
import weakref
|
||||
|
||||
from apscheduler.schedulers.asyncio import AsyncIOScheduler
|
||||
from apscheduler.triggers.date import DateTrigger
|
||||
from apscheduler.triggers.interval import IntervalTrigger
|
||||
import asyncpg
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.enums import JobStatus
|
||||
from app.core.logging import get_logger
|
||||
from app.db.session import async_session_factory
|
||||
@@ -37,13 +41,27 @@ from app.services.earth_news_refresh import (
|
||||
REFRESH_STATUS_HEARTBEAT_SECONDS as EARTH_NEWS_STATUS_HEARTBEAT_SECONDS,
|
||||
)
|
||||
from app.services.earth_news import REGION_ANCHORS
|
||||
from app.services.storage_maintenance import run_storage_retention_maintenance
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
scheduler = AsyncIOScheduler()
|
||||
RUNNING_TASK_GUARD_TIMEOUT_MINUTES = 90
|
||||
RUNNING_COLLECTOR_TASKS: dict[str, asyncio.Task[Any]] = {}
|
||||
HEAVY_COLLECTOR_SOURCES: frozenset[str] = frozenset(
|
||||
{"iptoasn_prefix_geo", "nro_delegated_prefix_geo"}
|
||||
)
|
||||
_COLLECTOR_SEMAPHORES: weakref.WeakKeyDictionary[
|
||||
asyncio.AbstractEventLoop, tuple[int, asyncio.Semaphore]
|
||||
] = weakref.WeakKeyDictionary()
|
||||
_HEAVY_COLLECTOR_SEMAPHORES: weakref.WeakKeyDictionary[
|
||||
asyncio.AbstractEventLoop, tuple[int, asyncio.Semaphore]
|
||||
] = weakref.WeakKeyDictionary()
|
||||
EARTH_NEWS_REFRESH_JOB_ID = "earth_news_rss_refresh"
|
||||
STORAGE_RETENTION_JOB_ID = "storage_retention_maintenance"
|
||||
STORAGE_RETENTION_INTERVAL_HOURS = 6
|
||||
SCHEDULER_LEADER_LOCK_KEY = (17001613, 3)
|
||||
_leader_lock_conn: Optional[asyncpg.Connection] = None
|
||||
_pending_earth_news_refreshes: dict[str, dict[str, Any]] = {}
|
||||
_running_earth_news_refreshes: set[str] = set()
|
||||
_rerun_earth_news_refreshes: dict[str, dict[str, Any]] = {}
|
||||
@@ -56,6 +74,45 @@ EARTH_NEWS_REFRESH_PUBLIC_ERRORS = {
|
||||
}
|
||||
|
||||
|
||||
def _get_loop_semaphore(
|
||||
registry: weakref.WeakKeyDictionary[asyncio.AbstractEventLoop, tuple[int, asyncio.Semaphore]],
|
||||
limit: int,
|
||||
) -> asyncio.Semaphore:
|
||||
bounded_limit = max(1, int(limit))
|
||||
loop = asyncio.get_running_loop()
|
||||
existing = registry.get(loop)
|
||||
if existing is None or existing[0] != bounded_limit:
|
||||
semaphore = asyncio.Semaphore(bounded_limit)
|
||||
registry[loop] = (bounded_limit, semaphore)
|
||||
return semaphore
|
||||
return existing[1]
|
||||
|
||||
|
||||
def _get_collector_semaphore() -> asyncio.Semaphore:
|
||||
return _get_loop_semaphore(_COLLECTOR_SEMAPHORES, settings.COLLECTOR_MAX_CONCURRENCY)
|
||||
|
||||
|
||||
def _get_heavy_collector_semaphore() -> asyncio.Semaphore:
|
||||
return _get_loop_semaphore(
|
||||
_HEAVY_COLLECTOR_SEMAPHORES, settings.COLLECTOR_HEAVY_CONCURRENCY
|
||||
)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def _acquire_collector_slots(collector_name: str):
|
||||
"""Serialize heavy collectors first so lightweight collectors are not starved."""
|
||||
heavy_semaphore = (
|
||||
_get_heavy_collector_semaphore() if collector_name in HEAVY_COLLECTOR_SOURCES else None
|
||||
)
|
||||
if heavy_semaphore is not None:
|
||||
async with heavy_semaphore:
|
||||
async with _get_collector_semaphore():
|
||||
yield
|
||||
else:
|
||||
async with _get_collector_semaphore():
|
||||
yield
|
||||
|
||||
|
||||
def _collector_task_name(collector_name: str) -> str:
|
||||
return f"collector:{collector_name}"
|
||||
|
||||
@@ -108,6 +165,9 @@ async def _apply_datasource_schedule(datasource: DataSource, session) -> None:
|
||||
id=datasource.source,
|
||||
name=datasource.name,
|
||||
replace_existing=True,
|
||||
max_instances=1,
|
||||
coalesce=True,
|
||||
misfire_grace_time=300,
|
||||
kwargs={"collector_name": datasource.source},
|
||||
)
|
||||
logger.info_event(
|
||||
@@ -268,7 +328,9 @@ async def run_collector_task(collector_name: str):
|
||||
"status": "running",
|
||||
},
|
||||
)
|
||||
task_result = await collector.run(db)
|
||||
task_result = None
|
||||
async with _acquire_collector_slots(collector_name):
|
||||
task_result = await collector.run(db)
|
||||
datasource = await db.get(DataSource, datasource_id)
|
||||
if datasource is None:
|
||||
logger.error_event(
|
||||
@@ -415,6 +477,60 @@ async def cleanup_stale_running_tasks(max_age_hours: int = 2) -> int:
|
||||
return len(stale_tasks)
|
||||
|
||||
|
||||
async def acquire_scheduler_leader_lock() -> bool:
|
||||
"""Acquire a PostgreSQL session advisory lock so only one instance schedules jobs."""
|
||||
global _leader_lock_conn
|
||||
|
||||
dsn = str(settings.DATABASE_URL or "").replace("postgresql+asyncpg://", "postgresql://", 1)
|
||||
if not dsn.startswith(("postgresql://", "postgres://")):
|
||||
return True
|
||||
|
||||
if _leader_lock_conn is not None and not _leader_lock_conn.is_closed():
|
||||
return True
|
||||
|
||||
try:
|
||||
conn = await asyncpg.connect(dsn, timeout=5.0)
|
||||
acquired = bool(
|
||||
await conn.fetchval("SELECT pg_try_advisory_lock($1, $2)", *SCHEDULER_LEADER_LOCK_KEY)
|
||||
)
|
||||
if acquired:
|
||||
_leader_lock_conn = conn
|
||||
logger.info_event(
|
||||
"Acquired scheduler leader advisory lock",
|
||||
event="scheduler.leader_lock.acquired",
|
||||
)
|
||||
return True
|
||||
await conn.close()
|
||||
return False
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed to acquire scheduler leader lock",
|
||||
event="scheduler.leader_lock.error",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
return False
|
||||
|
||||
|
||||
async def release_scheduler_leader_lock() -> None:
|
||||
"""Release the PostgreSQL scheduler leader advisory lock if held."""
|
||||
global _leader_lock_conn
|
||||
|
||||
conn = _leader_lock_conn
|
||||
_leader_lock_conn = None
|
||||
if conn is None or conn.is_closed():
|
||||
return
|
||||
try:
|
||||
await conn.fetchval("SELECT pg_advisory_unlock($1, $2)", *SCHEDULER_LEADER_LOCK_KEY)
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed to unlock scheduler leader lock cleanly",
|
||||
event="scheduler.leader_lock.unlock_failed",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
finally:
|
||||
await conn.close()
|
||||
|
||||
|
||||
def start_scheduler() -> None:
|
||||
"""Start the scheduler."""
|
||||
if not scheduler.running:
|
||||
@@ -429,6 +545,16 @@ def start_scheduler() -> None:
|
||||
coalesce=True,
|
||||
misfire_grace_time=60,
|
||||
)
|
||||
scheduler.add_job(
|
||||
run_storage_retention_maintenance,
|
||||
trigger=IntervalTrigger(hours=STORAGE_RETENTION_INTERVAL_HOURS),
|
||||
id=STORAGE_RETENTION_JOB_ID,
|
||||
name="Collection storage retention maintenance",
|
||||
replace_existing=True,
|
||||
max_instances=1,
|
||||
coalesce=True,
|
||||
misfire_grace_time=300,
|
||||
)
|
||||
scheduler.start()
|
||||
logger.info_event("Scheduler started", event="scheduler.started")
|
||||
|
||||
@@ -650,7 +776,11 @@ async def sync_scheduler_with_datasources() -> None:
|
||||
is_earth_news_refresh = job.id == EARTH_NEWS_REFRESH_JOB_ID or job.id.startswith(
|
||||
f"{EARTH_NEWS_REFRESH_JOB_ID}:"
|
||||
)
|
||||
if job.id not in configured_sources and not is_earth_news_refresh:
|
||||
if (
|
||||
job.id not in configured_sources
|
||||
and not is_earth_news_refresh
|
||||
and job.id != STORAGE_RETENTION_JOB_ID
|
||||
):
|
||||
scheduler.remove_job(job.id)
|
||||
|
||||
for datasource in datasources:
|
||||
|
||||
@@ -0,0 +1,339 @@
|
||||
"""Opt-in batch storage retention maintenance service."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import delete, func, or_, select, text, update
|
||||
from sqlalchemy.ext.asyncio import AsyncConnection, AsyncEngine, AsyncSession
|
||||
|
||||
from app.core.logging import get_logger
|
||||
from app.db.session import async_session_factory
|
||||
from app.models.bgp_anomaly import BGPAnomaly
|
||||
from app.models.bgp_incident import BGPIncident
|
||||
from app.models.bgp_observation import BGPObservation
|
||||
from app.models.collected_data import CollectedData
|
||||
from app.models.data_snapshot import DataSnapshot
|
||||
from app.models.earth_news import EarthNewsItem
|
||||
from app.models.system_log import ObservabilityEvent, SystemLog
|
||||
from app.models.vessel import AISRawObservation, VesselPosition
|
||||
from app.services.storage_policy import get_storage_policy
|
||||
from app.services.vessel_ais_aggregation import VESSEL_TRACK_RETENTION_HOURS
|
||||
|
||||
logger = get_logger(__name__, service="storage_maintenance")
|
||||
|
||||
STORAGE_MAINTENANCE_LOCK_KEY = (17001614, 1)
|
||||
DEFAULT_BATCH_SIZE = 50_000
|
||||
MAX_BATCHES_PER_TABLE = 20
|
||||
|
||||
|
||||
def _is_postgresql(db: AsyncSession) -> bool:
|
||||
try:
|
||||
bind = db.get_bind()
|
||||
return getattr(getattr(bind, "dialect", None), "name", "") == "postgresql"
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _resolve_async_engine(db: AsyncSession) -> AsyncEngine | None:
|
||||
bound = getattr(db, "bind", None)
|
||||
if isinstance(bound, AsyncEngine):
|
||||
return bound
|
||||
if isinstance(bound, AsyncConnection):
|
||||
return AsyncEngine(bound.engine)
|
||||
return None
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def _storage_maintenance_advisory_lock(db: AsyncSession):
|
||||
"""Hold PostgreSQL session advisory lock on a dedicated connection outside pooled commits."""
|
||||
if not _is_postgresql(db):
|
||||
yield True
|
||||
return
|
||||
|
||||
target_engine = _resolve_async_engine(db)
|
||||
if target_engine is None:
|
||||
from app.db.session import engine as default_engine
|
||||
|
||||
target_engine = default_engine
|
||||
|
||||
async with target_engine.connect() as base_conn:
|
||||
lock_conn = await base_conn.execution_options(isolation_level="AUTOCOMMIT")
|
||||
acquired = False
|
||||
try:
|
||||
result = await lock_conn.execute(
|
||||
text("SELECT pg_try_advisory_lock(:key1, :key2)"),
|
||||
{
|
||||
"key1": STORAGE_MAINTENANCE_LOCK_KEY[0],
|
||||
"key2": STORAGE_MAINTENANCE_LOCK_KEY[1],
|
||||
},
|
||||
)
|
||||
acquired = bool(result.scalar())
|
||||
yield acquired
|
||||
finally:
|
||||
if acquired:
|
||||
try:
|
||||
await lock_conn.execute(
|
||||
text("SELECT pg_advisory_unlock(:key1, :key2)"),
|
||||
{
|
||||
"key1": STORAGE_MAINTENANCE_LOCK_KEY[0],
|
||||
"key2": STORAGE_MAINTENANCE_LOCK_KEY[1],
|
||||
},
|
||||
)
|
||||
except Exception:
|
||||
logger.warning_event(
|
||||
"Failed to release storage retention advisory lock",
|
||||
event="storage.retention.unlock_failed",
|
||||
)
|
||||
|
||||
|
||||
async def _prune_collected_data_for_snapshots(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
snapshot_ids: list[int],
|
||||
batch_size: int,
|
||||
) -> int:
|
||||
if not snapshot_ids:
|
||||
return 0
|
||||
|
||||
deleted_total = 0
|
||||
for _ in range(MAX_BATCHES_PER_TABLE):
|
||||
id_result = await db.execute(
|
||||
select(CollectedData.id)
|
||||
.where(
|
||||
CollectedData.snapshot_id.in_(snapshot_ids),
|
||||
or_(CollectedData.is_current.is_(False), CollectedData.is_current.is_(None)),
|
||||
)
|
||||
.order_by(CollectedData.id.asc())
|
||||
.limit(batch_size)
|
||||
)
|
||||
batch_ids = [int(row_id) for row_id in id_result.scalars().all()]
|
||||
if not batch_ids:
|
||||
break
|
||||
|
||||
await db.execute(
|
||||
update(CollectedData)
|
||||
.where(CollectedData.previous_record_id.in_(batch_ids))
|
||||
.values(previous_record_id=None)
|
||||
)
|
||||
delete_result = await db.execute(
|
||||
delete(CollectedData).where(
|
||||
CollectedData.id.in_(batch_ids),
|
||||
or_(CollectedData.is_current.is_(False), CollectedData.is_current.is_(None)),
|
||||
)
|
||||
)
|
||||
deleted_total += int(delete_result.rowcount or len(batch_ids))
|
||||
await db.commit()
|
||||
if len(batch_ids) < batch_size:
|
||||
break
|
||||
return deleted_total
|
||||
|
||||
|
||||
async def _prune_expired_snapshots(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
history_cutoff: datetime,
|
||||
batch_size: int,
|
||||
) -> tuple[int, int]:
|
||||
candidates_result = await db.execute(
|
||||
select(DataSnapshot)
|
||||
.where(
|
||||
DataSnapshot.is_current.is_(False),
|
||||
func.coalesce(DataSnapshot.completed_at, DataSnapshot.started_at) < history_cutoff,
|
||||
)
|
||||
.order_by(DataSnapshot.id.asc())
|
||||
.limit(1000)
|
||||
)
|
||||
expired_ids = [
|
||||
snapshot.id
|
||||
for snapshot in candidates_result.scalars().all()
|
||||
if not (isinstance(snapshot.summary, dict) and snapshot.summary.get("milestone_year") is not None)
|
||||
]
|
||||
if not expired_ids:
|
||||
return 0, 0
|
||||
|
||||
deleted_collected = await _prune_collected_data_for_snapshots(
|
||||
db,
|
||||
snapshot_ids=expired_ids,
|
||||
batch_size=batch_size,
|
||||
)
|
||||
|
||||
remaining_result = await db.execute(
|
||||
select(CollectedData.snapshot_id)
|
||||
.where(CollectedData.snapshot_id.in_(expired_ids))
|
||||
.distinct()
|
||||
)
|
||||
busy_snapshot_ids = {int(sid) for sid in remaining_result.scalars().all() if sid is not None}
|
||||
removable_snapshot_ids = [sid for sid in expired_ids if sid not in busy_snapshot_ids]
|
||||
if not removable_snapshot_ids:
|
||||
return deleted_collected, 0
|
||||
|
||||
for offset in range(0, len(removable_snapshot_ids), 500):
|
||||
chunk = removable_snapshot_ids[offset : offset + 500]
|
||||
await db.execute(
|
||||
update(DataSnapshot)
|
||||
.where(DataSnapshot.parent_snapshot_id.in_(chunk))
|
||||
.values(parent_snapshot_id=None)
|
||||
)
|
||||
await db.execute(
|
||||
update(BGPObservation)
|
||||
.where(BGPObservation.snapshot_id.in_(chunk))
|
||||
.values(snapshot_id=None)
|
||||
)
|
||||
await db.execute(
|
||||
update(BGPAnomaly)
|
||||
.where(BGPAnomaly.snapshot_id.in_(chunk))
|
||||
.values(snapshot_id=None)
|
||||
)
|
||||
await db.execute(
|
||||
update(BGPIncident)
|
||||
.where(BGPIncident.snapshot_id.in_(chunk))
|
||||
.values(snapshot_id=None)
|
||||
)
|
||||
await db.execute(
|
||||
delete(DataSnapshot).where(
|
||||
DataSnapshot.id.in_(chunk),
|
||||
DataSnapshot.is_current.is_(False),
|
||||
)
|
||||
)
|
||||
await db.commit()
|
||||
return deleted_collected, len(removable_snapshot_ids)
|
||||
|
||||
|
||||
async def _prune_model_by_id(
|
||||
db: AsyncSession,
|
||||
model: Any,
|
||||
*,
|
||||
where_clause: list[Any],
|
||||
batch_size: int,
|
||||
) -> int:
|
||||
deleted_total = 0
|
||||
for _ in range(MAX_BATCHES_PER_TABLE):
|
||||
ids_result = await db.execute(
|
||||
select(model.id)
|
||||
.where(*where_clause)
|
||||
.order_by(model.id.asc())
|
||||
.limit(batch_size)
|
||||
)
|
||||
batch_ids = [row_id for row_id in ids_result.scalars().all()]
|
||||
if not batch_ids:
|
||||
break
|
||||
result = await db.execute(delete(model).where(model.id.in_(batch_ids)))
|
||||
deleted_total += int(result.rowcount or len(batch_ids))
|
||||
await db.commit()
|
||||
if len(batch_ids) < batch_size:
|
||||
break
|
||||
return deleted_total
|
||||
|
||||
|
||||
async def _run_maintenance_with_session(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
batch_size: int,
|
||||
now: datetime | None,
|
||||
) -> dict[str, Any]:
|
||||
policy = await get_storage_policy(db)
|
||||
if not policy.get("auto_prune_enabled", False):
|
||||
logger.info_event(
|
||||
"Skipped storage retention maintenance because auto_prune_enabled is False",
|
||||
event="storage.retention.skipped",
|
||||
context={"reason": "auto_prune_disabled"},
|
||||
)
|
||||
return {"skipped": True, "reason": "auto_prune_disabled", "deleted": {}}
|
||||
|
||||
async with _storage_maintenance_advisory_lock(db) as acquired:
|
||||
if not acquired:
|
||||
logger.info_event(
|
||||
"Skipped storage retention maintenance because another worker holds the lock",
|
||||
event="storage.retention.skipped",
|
||||
context={"reason": "lock_busy"},
|
||||
)
|
||||
return {"skipped": True, "reason": "lock_busy", "deleted": {}}
|
||||
|
||||
ref_now = now or datetime.now(UTC)
|
||||
history_cutoff = ref_now - timedelta(days=int(policy.get("history_retention_days", 30)))
|
||||
bgp_cutoff = ref_now - timedelta(days=int(policy.get("bgp_observation_retention_days", 7)))
|
||||
vessel_track_cutoff = ref_now - timedelta(hours=VESSEL_TRACK_RETENTION_HOURS)
|
||||
|
||||
deleted_collected, deleted_snapshots = await _prune_expired_snapshots(
|
||||
db,
|
||||
history_cutoff=history_cutoff,
|
||||
batch_size=batch_size,
|
||||
)
|
||||
deleted_bgp_observations = await _prune_model_by_id(
|
||||
db,
|
||||
BGPObservation,
|
||||
where_clause=[BGPObservation.observed_at < bgp_cutoff],
|
||||
batch_size=batch_size,
|
||||
)
|
||||
deleted_ais_raw = await _prune_model_by_id(
|
||||
db,
|
||||
AISRawObservation,
|
||||
where_clause=[AISRawObservation.observed_at < history_cutoff],
|
||||
batch_size=batch_size,
|
||||
)
|
||||
deleted_vessel_positions = await _prune_model_by_id(
|
||||
db,
|
||||
VesselPosition,
|
||||
where_clause=[VesselPosition.received_at < vessel_track_cutoff],
|
||||
batch_size=batch_size,
|
||||
)
|
||||
deleted_news_items = await _prune_model_by_id(
|
||||
db,
|
||||
EarthNewsItem,
|
||||
where_clause=[
|
||||
~EarthNewsItem.id.like("manual:%"),
|
||||
func.coalesce(EarthNewsItem.published_at, EarthNewsItem.last_seen_at)
|
||||
< history_cutoff,
|
||||
],
|
||||
batch_size=batch_size,
|
||||
)
|
||||
deleted_system_logs = await _prune_model_by_id(
|
||||
db,
|
||||
SystemLog,
|
||||
where_clause=[SystemLog.occurred_at < history_cutoff],
|
||||
batch_size=batch_size,
|
||||
)
|
||||
deleted_observability_events = await _prune_model_by_id(
|
||||
db,
|
||||
ObservabilityEvent,
|
||||
where_clause=[ObservabilityEvent.occurred_at < history_cutoff],
|
||||
batch_size=batch_size,
|
||||
)
|
||||
|
||||
deleted_counts = {
|
||||
"collected_data": deleted_collected,
|
||||
"data_snapshots": deleted_snapshots,
|
||||
"bgp_observations": deleted_bgp_observations,
|
||||
"ais_raw_observations": deleted_ais_raw,
|
||||
"vessel_positions": deleted_vessel_positions,
|
||||
"earth_news_items": deleted_news_items,
|
||||
"system_logs": deleted_system_logs,
|
||||
"observability_events": deleted_observability_events,
|
||||
}
|
||||
logger.info_event(
|
||||
"Completed storage retention maintenance",
|
||||
event="storage.retention.completed",
|
||||
context={
|
||||
"history_retention_days": policy["history_retention_days"],
|
||||
"bgp_observation_retention_days": policy["bgp_observation_retention_days"],
|
||||
"deleted": deleted_counts,
|
||||
},
|
||||
)
|
||||
return {"skipped": False, "deleted": deleted_counts}
|
||||
|
||||
|
||||
async def run_storage_retention_maintenance(
|
||||
db: AsyncSession | None = None,
|
||||
*,
|
||||
batch_size: int = DEFAULT_BATCH_SIZE,
|
||||
now: datetime | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Run batch storage retention cleanup when `auto_prune_enabled` is enabled."""
|
||||
if db is not None:
|
||||
return await _run_maintenance_with_session(db, batch_size=batch_size, now=now)
|
||||
|
||||
async with async_session_factory() as session:
|
||||
return await _run_maintenance_with_session(session, batch_size=batch_size, now=now)
|
||||
@@ -0,0 +1,523 @@
|
||||
"""Unified collection storage & snapshot retention policy service."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from copy import deepcopy
|
||||
import hashlib
|
||||
import json
|
||||
from typing import Any, Callable, Iterable, Literal
|
||||
|
||||
from sqlalchemy import select, text
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.logging import get_logger
|
||||
from app.models.system_setting import SystemSetting
|
||||
|
||||
logger = get_logger(__name__, service="storage_policy")
|
||||
|
||||
SnapshotMode = Literal["single", "annual", "history"]
|
||||
GlobalSnapshotAction = Literal["all_single", "all_history", "recommended_default"]
|
||||
|
||||
|
||||
class StoragePolicyLockedError(ValueError):
|
||||
"""Raised when a per-source snapshot override violates global all-single lock."""
|
||||
|
||||
STORAGE_POLICY_CATEGORY = "collection_storage"
|
||||
STORAGE_POLICY_TX_LOCK_KEY = (17001614, 2)
|
||||
STORAGE_POLICY_SINGLE_VIOLATION_CODE = "planet_storage_policy_single_violation"
|
||||
VALID_SNAPSHOT_MODES: tuple[SnapshotMode, ...] = ("single", "annual", "history")
|
||||
ANNUAL_ELIGIBLE_SOURCES: frozenset[str] = frozenset({"top500", "epoch_ai_gpu"})
|
||||
|
||||
HIGH_VOLUME_SOURCES: dict[str, dict[str, str]] = {
|
||||
"iptoasn_prefix_geo": {
|
||||
"estimated_monthly_growth": "~14 GB / 月",
|
||||
"note": "全量 IPv4/IPv6 ASN 前缀约 72 万行,每 6 小时重采开启历史快照将快速膨胀",
|
||||
},
|
||||
"nro_delegated_prefix_geo": {
|
||||
"estimated_monthly_growth": "~12 GB / 月",
|
||||
"note": "五大 RIR IP 分配表约 65 万行,每 12 小时全量落盘对磁盘与触发器压力较大",
|
||||
},
|
||||
"barentswatch_vessels": {
|
||||
"estimated_monthly_growth": "~25 GB / 月",
|
||||
"note": "每 5 分钟拉取近实时 AIS 报文,开启历史快照将持续写入 ais_raw_observations",
|
||||
},
|
||||
"aisstream_vessels": {
|
||||
"estimated_monthly_growth": "~15 GB / 月",
|
||||
"note": "WebSocket 高频 AIS 报文流,开启历史快照将高频写入 ais_raw_observations",
|
||||
},
|
||||
}
|
||||
|
||||
DEFAULT_RECOMMENDED_OVERRIDES: dict[str, SnapshotMode] = {
|
||||
"top500": "annual",
|
||||
"epoch_ai_gpu": "annual",
|
||||
}
|
||||
|
||||
DEFAULT_STORAGE_POLICY: dict[str, Any] = {
|
||||
"default_mode": "single",
|
||||
"overrides": deepcopy(DEFAULT_RECOMMENDED_OVERRIDES),
|
||||
"global_single_lock": False,
|
||||
"history_retention_days": 30,
|
||||
"bgp_observation_retention_days": 7,
|
||||
"bgp_single_batch_max_rows": 500,
|
||||
"auto_prune_enabled": False,
|
||||
}
|
||||
|
||||
|
||||
def compute_record_content_hash(payload: dict[str, Any]) -> str:
|
||||
"""Return a deterministic SHA-256 hex digest for a comparable collector record payload."""
|
||||
canonical = json.dumps(
|
||||
payload,
|
||||
sort_keys=True,
|
||||
separators=(",", ":"),
|
||||
ensure_ascii=False,
|
||||
default=str,
|
||||
)
|
||||
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def _clamp_int(value: Any, default: int, *, minimum: int, maximum: int) -> int:
|
||||
try:
|
||||
parsed = int(value)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
return max(minimum, min(parsed, maximum))
|
||||
|
||||
|
||||
def _normalize_mode(value: Any, fallback: SnapshotMode = "single") -> SnapshotMode:
|
||||
if isinstance(value, str):
|
||||
candidate = value.strip().lower()
|
||||
if candidate in VALID_SNAPSHOT_MODES:
|
||||
return candidate # type: ignore[return-value]
|
||||
return fallback
|
||||
|
||||
|
||||
def normalize_storage_policy(
|
||||
raw: dict[str, Any] | None,
|
||||
*,
|
||||
fallback_auto_prune: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""Validate and normalize a raw storage policy dictionary, dropping redundant overrides."""
|
||||
data = raw if isinstance(raw, dict) else {}
|
||||
global_single_lock_raw = data.get("global_single_lock")
|
||||
if isinstance(global_single_lock_raw, bool):
|
||||
global_single_lock = global_single_lock_raw
|
||||
elif global_single_lock_raw is None:
|
||||
global_single_lock = False
|
||||
else:
|
||||
global_single_lock = str(global_single_lock_raw).strip().lower() in {
|
||||
"1",
|
||||
"true",
|
||||
"yes",
|
||||
"on",
|
||||
}
|
||||
|
||||
default_mode = "single" if global_single_lock else _normalize_mode(data.get("default_mode"), "single")
|
||||
|
||||
overrides_raw = data.get("overrides")
|
||||
if global_single_lock:
|
||||
cleaned_overrides: dict[str, SnapshotMode] = {}
|
||||
elif isinstance(overrides_raw, dict):
|
||||
cleaned_overrides = {}
|
||||
for source, mode_raw in overrides_raw.items():
|
||||
source_key = str(source or "").strip()
|
||||
if not source_key:
|
||||
continue
|
||||
mode = _normalize_mode(mode_raw, default_mode)
|
||||
if mode == "annual" and source_key not in ANNUAL_ELIGIBLE_SOURCES:
|
||||
mode = "history"
|
||||
if mode != default_mode:
|
||||
cleaned_overrides[source_key] = mode
|
||||
else:
|
||||
cleaned_overrides = {
|
||||
source: mode
|
||||
for source, mode in DEFAULT_RECOMMENDED_OVERRIDES.items()
|
||||
if mode != default_mode
|
||||
}
|
||||
|
||||
auto_prune_raw = data.get("auto_prune_enabled")
|
||||
if isinstance(auto_prune_raw, bool):
|
||||
auto_prune_enabled = auto_prune_raw
|
||||
elif auto_prune_raw is None:
|
||||
auto_prune_enabled = fallback_auto_prune
|
||||
else:
|
||||
auto_prune_enabled = str(auto_prune_raw).strip().lower() in {"1", "true", "yes", "on"}
|
||||
|
||||
return {
|
||||
"default_mode": default_mode,
|
||||
"overrides": cleaned_overrides,
|
||||
"global_single_lock": global_single_lock,
|
||||
"history_retention_days": _clamp_int(
|
||||
data.get("history_retention_days"),
|
||||
int(DEFAULT_STORAGE_POLICY["history_retention_days"]),
|
||||
minimum=1,
|
||||
maximum=3650,
|
||||
),
|
||||
"bgp_observation_retention_days": _clamp_int(
|
||||
data.get("bgp_observation_retention_days"),
|
||||
int(DEFAULT_STORAGE_POLICY["bgp_observation_retention_days"]),
|
||||
minimum=1,
|
||||
maximum=365,
|
||||
),
|
||||
"bgp_single_batch_max_rows": _clamp_int(
|
||||
data.get("bgp_single_batch_max_rows"),
|
||||
int(DEFAULT_STORAGE_POLICY["bgp_single_batch_max_rows"]),
|
||||
minimum=50,
|
||||
maximum=5000,
|
||||
),
|
||||
"auto_prune_enabled": auto_prune_enabled,
|
||||
}
|
||||
|
||||
|
||||
def resolve_snapshot_mode(policy: dict[str, Any] | None, source: str) -> SnapshotMode:
|
||||
"""Resolve effective snapshot mode for one datasource from a single unified policy."""
|
||||
normalized = normalize_storage_policy(policy)
|
||||
if normalized.get("global_single_lock"):
|
||||
return "single"
|
||||
overrides: dict[str, SnapshotMode] = normalized["overrides"]
|
||||
default_mode: SnapshotMode = normalized["default_mode"]
|
||||
mode = overrides.get(source, default_mode)
|
||||
if mode == "annual" and source not in ANNUAL_ELIGIBLE_SOURCES:
|
||||
return "history"
|
||||
return mode
|
||||
|
||||
|
||||
def set_source_snapshot_mode(
|
||||
policy: dict[str, Any] | None,
|
||||
source: str,
|
||||
mode: SnapshotMode,
|
||||
) -> dict[str, Any]:
|
||||
"""Update a single datasource override sparsely, deleting override when equal to default."""
|
||||
normalized = normalize_storage_policy(policy)
|
||||
target_mode = _normalize_mode(mode, normalized["default_mode"])
|
||||
if target_mode == "annual" and source not in ANNUAL_ELIGIBLE_SOURCES:
|
||||
target_mode = "history"
|
||||
|
||||
if normalized.get("global_single_lock") and target_mode != "single":
|
||||
raise StoragePolicyLockedError(
|
||||
"Global all-single lock is active; switch off all-single before enabling history or annual snapshots for a source."
|
||||
)
|
||||
|
||||
next_overrides = dict(normalized["overrides"])
|
||||
if target_mode == normalized["default_mode"]:
|
||||
next_overrides.pop(source, None)
|
||||
else:
|
||||
next_overrides[source] = target_mode
|
||||
|
||||
return normalize_storage_policy({**normalized, "overrides": next_overrides})
|
||||
|
||||
|
||||
def apply_global_snapshot_action(
|
||||
policy: dict[str, Any] | None,
|
||||
action: GlobalSnapshotAction,
|
||||
) -> dict[str, Any]:
|
||||
"""Apply tri-state master switch actions cleanly without leaving stale overrides."""
|
||||
normalized = normalize_storage_policy(policy)
|
||||
if action == "all_single":
|
||||
return normalize_storage_policy(
|
||||
{**normalized, "default_mode": "single", "overrides": {}, "global_single_lock": True}
|
||||
)
|
||||
if action == "all_history":
|
||||
return normalize_storage_policy(
|
||||
{**normalized, "default_mode": "history", "overrides": {}, "global_single_lock": False}
|
||||
)
|
||||
if action == "recommended_default":
|
||||
return normalize_storage_policy(
|
||||
{
|
||||
**normalized,
|
||||
"default_mode": "single",
|
||||
"overrides": deepcopy(DEFAULT_RECOMMENDED_OVERRIDES),
|
||||
"global_single_lock": False,
|
||||
}
|
||||
)
|
||||
return normalized
|
||||
|
||||
|
||||
def summarize_storage_policy(
|
||||
policy: dict[str, Any] | None,
|
||||
sources: Iterable[str],
|
||||
) -> dict[str, Any]:
|
||||
"""Compute effective per-source counts and tri-state master status (`off`/`partial`/`all`)."""
|
||||
normalized = normalize_storage_policy(policy)
|
||||
unique_sources = sorted({str(source).strip() for source in sources if str(source or "").strip()})
|
||||
|
||||
effective_modes: dict[str, SnapshotMode] = {}
|
||||
single_count = 0
|
||||
annual_count = 0
|
||||
history_count = 0
|
||||
|
||||
for source in unique_sources:
|
||||
mode = resolve_snapshot_mode(normalized, source)
|
||||
effective_modes[source] = mode
|
||||
if mode == "single":
|
||||
single_count += 1
|
||||
elif mode == "annual":
|
||||
annual_count += 1
|
||||
else:
|
||||
history_count += 1
|
||||
|
||||
total_sources = len(unique_sources)
|
||||
snapshot_enabled_count = annual_count + history_count
|
||||
if total_sources == 0 or snapshot_enabled_count == 0:
|
||||
master_state: Literal["off", "partial", "all"] = "off"
|
||||
elif snapshot_enabled_count == total_sources:
|
||||
master_state = "all"
|
||||
else:
|
||||
master_state = "partial"
|
||||
|
||||
return {
|
||||
**normalized,
|
||||
"total_sources": total_sources,
|
||||
"single_count": single_count,
|
||||
"annual_count": annual_count,
|
||||
"history_count": history_count,
|
||||
"snapshot_enabled_count": snapshot_enabled_count,
|
||||
"master_state": master_state,
|
||||
"annual_eligible_sources": sorted(ANNUAL_ELIGIBLE_SOURCES),
|
||||
"high_volume_sources": deepcopy(HIGH_VOLUME_SOURCES),
|
||||
"effective_modes": effective_modes,
|
||||
}
|
||||
|
||||
|
||||
def _is_postgresql_session(db: AsyncSession | None) -> bool:
|
||||
if db is None or not callable(getattr(db, "get_bind", None)):
|
||||
return False
|
||||
try:
|
||||
bind = db.get_bind()
|
||||
return getattr(getattr(bind, "dialect", None), "name", "") == "postgresql"
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def is_storage_policy_single_violation(exc: BaseException) -> bool:
|
||||
"""Return True if an exception (or wrapped DBAPI cause) came from the single-mode publish guard."""
|
||||
visited: set[int] = set()
|
||||
pending: list[BaseException | None] = [exc]
|
||||
while pending:
|
||||
current = pending.pop()
|
||||
if current is None or id(current) in visited:
|
||||
continue
|
||||
visited.add(id(current))
|
||||
if STORAGE_POLICY_SINGLE_VIOLATION_CODE in str(current):
|
||||
return True
|
||||
pending.append(getattr(current, "__cause__", None))
|
||||
pending.append(getattr(current, "__context__", None))
|
||||
pending.append(getattr(current, "orig", None))
|
||||
return False
|
||||
|
||||
|
||||
async def acquire_storage_policy_write_lock(db: AsyncSession | None) -> None:
|
||||
"""Take transaction-scoped exclusive lock serializing storage policy changes with snapshot publish."""
|
||||
if not _is_postgresql_session(db):
|
||||
return
|
||||
await db.execute( # type: ignore[union-attr]
|
||||
text("SELECT pg_advisory_xact_lock(:key1, :key2)"),
|
||||
{"key1": STORAGE_POLICY_TX_LOCK_KEY[0], "key2": STORAGE_POLICY_TX_LOCK_KEY[1]},
|
||||
)
|
||||
|
||||
|
||||
async def acquire_storage_policy_publish_lock(
|
||||
db: AsyncSession | None,
|
||||
source: str,
|
||||
) -> tuple[SnapshotMode, dict[str, Any]]:
|
||||
"""Take transaction-scoped shared lock and read the latest committed storage policy."""
|
||||
if db is None or not callable(getattr(db, "execute", None)):
|
||||
policy = normalize_storage_policy(None)
|
||||
return resolve_snapshot_mode(policy, source), policy
|
||||
|
||||
is_pg = _is_postgresql_session(db)
|
||||
if is_pg:
|
||||
await db.execute(
|
||||
text("SELECT pg_advisory_xact_lock_shared(:key1, :key2)"),
|
||||
{"key1": STORAGE_POLICY_TX_LOCK_KEY[0], "key2": STORAGE_POLICY_TX_LOCK_KEY[1]},
|
||||
)
|
||||
|
||||
stmt = (
|
||||
select(SystemSetting.payload)
|
||||
.where(SystemSetting.category == STORAGE_POLICY_CATEGORY)
|
||||
.limit(1)
|
||||
)
|
||||
if is_pg and hasattr(stmt, "with_for_update"):
|
||||
stmt = stmt.with_for_update(read=True)
|
||||
|
||||
try:
|
||||
result = await db.execute(stmt)
|
||||
except Exception:
|
||||
policy = normalize_storage_policy(None)
|
||||
return resolve_snapshot_mode(policy, source), policy
|
||||
|
||||
raw_payload = None
|
||||
if result is not None and callable(getattr(result, "scalar_one_or_none", None)):
|
||||
raw_payload = result.scalar_one_or_none()
|
||||
if isinstance(raw_payload, SystemSetting):
|
||||
raw_payload = raw_payload.payload
|
||||
policy = normalize_storage_policy(raw_payload if isinstance(raw_payload, dict) else None)
|
||||
return resolve_snapshot_mode(policy, source), policy
|
||||
|
||||
|
||||
async def _load_setting_row(
|
||||
db: AsyncSession,
|
||||
category: str,
|
||||
*,
|
||||
for_update: bool = False,
|
||||
) -> SystemSetting | None:
|
||||
try:
|
||||
stmt = select(SystemSetting).where(SystemSetting.category == category).limit(1)
|
||||
if hasattr(stmt, "execution_options"):
|
||||
stmt = stmt.execution_options(populate_existing=True)
|
||||
if for_update and _is_postgresql_session(db) and hasattr(stmt, "with_for_update"):
|
||||
stmt = stmt.with_for_update()
|
||||
result = await db.execute(stmt)
|
||||
except Exception:
|
||||
return None
|
||||
if result is None or not callable(getattr(result, "scalar_one_or_none", None)):
|
||||
return None
|
||||
record = result.scalar_one_or_none()
|
||||
if isinstance(record, SystemSetting):
|
||||
return record
|
||||
return None
|
||||
|
||||
|
||||
async def get_storage_policy(db: AsyncSession | None) -> dict[str, Any]:
|
||||
"""Load storage policy fresh from DB, safely falling back when called with fake/None sessions."""
|
||||
if db is None or not callable(getattr(db, "execute", None)):
|
||||
return normalize_storage_policy(None)
|
||||
|
||||
try:
|
||||
result = await db.execute(
|
||||
select(SystemSetting.payload)
|
||||
.where(SystemSetting.category == STORAGE_POLICY_CATEGORY)
|
||||
.limit(1)
|
||||
)
|
||||
except Exception:
|
||||
return normalize_storage_policy(None)
|
||||
|
||||
if result is not None and callable(getattr(result, "scalar_one_or_none", None)):
|
||||
raw_payload = result.scalar_one_or_none()
|
||||
if isinstance(raw_payload, SystemSetting):
|
||||
raw_payload = raw_payload.payload
|
||||
if isinstance(raw_payload, dict):
|
||||
return normalize_storage_policy(raw_payload)
|
||||
return normalize_storage_policy(None)
|
||||
|
||||
|
||||
async def resolve_collector_storage_policy(
|
||||
db: AsyncSession | None,
|
||||
source: str,
|
||||
) -> tuple[SnapshotMode, dict[str, Any]]:
|
||||
"""Return `(effective_mode, full_policy)` for a collector source."""
|
||||
policy = await get_storage_policy(db)
|
||||
return resolve_snapshot_mode(policy, source), policy
|
||||
|
||||
|
||||
async def mutate_storage_policy(
|
||||
db: AsyncSession,
|
||||
mutator: Callable[[dict[str, Any]], dict[str, Any]],
|
||||
*,
|
||||
sync_system_retention: bool = True,
|
||||
commit: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""Read, validate, merge, and persist storage policy inside one locked transaction."""
|
||||
await acquire_storage_policy_write_lock(db)
|
||||
record = await _load_setting_row(db, STORAGE_POLICY_CATEGORY, for_update=True)
|
||||
current_policy = normalize_storage_policy(
|
||||
record.payload if record is not None and isinstance(record.payload, dict) else None
|
||||
)
|
||||
normalized = normalize_storage_policy(mutator(deepcopy(current_policy)))
|
||||
|
||||
if record is None:
|
||||
record = SystemSetting(category=STORAGE_POLICY_CATEGORY, payload=normalized)
|
||||
db.add(record)
|
||||
else:
|
||||
record.payload = normalized
|
||||
|
||||
if sync_system_retention:
|
||||
# Canonical lock order: advisory lock -> collection_storage -> system.
|
||||
system_record = await _load_setting_row(db, "system", for_update=True)
|
||||
if system_record is not None and isinstance(system_record.payload, dict):
|
||||
next_system_payload = dict(system_record.payload)
|
||||
next_system_payload["data_retention_days"] = normalized["history_retention_days"]
|
||||
system_record.payload = next_system_payload
|
||||
|
||||
if commit:
|
||||
await db.commit()
|
||||
if hasattr(db, "refresh"):
|
||||
await db.refresh(record)
|
||||
return normalized
|
||||
|
||||
|
||||
async def save_storage_policy(
|
||||
db: AsyncSession,
|
||||
policy: dict[str, Any],
|
||||
*,
|
||||
sync_system_retention: bool = True,
|
||||
commit: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""Persist storage policy under an exclusive transaction lock blocking incompatible snapshot commits."""
|
||||
return await mutate_storage_policy(
|
||||
db,
|
||||
lambda _current: policy,
|
||||
sync_system_retention=sync_system_retention,
|
||||
commit=commit,
|
||||
)
|
||||
|
||||
|
||||
async def _detect_existing_collection_data(db: AsyncSession) -> bool:
|
||||
"""Return True if any historical collection or AIS raw table already holds data."""
|
||||
probes = (
|
||||
text("SELECT 1 FROM data_snapshots LIMIT 1"),
|
||||
text("SELECT 1 FROM collected_data LIMIT 1"),
|
||||
text("SELECT 1 FROM ais_raw_observations LIMIT 1"),
|
||||
)
|
||||
for probe in probes:
|
||||
try:
|
||||
result = await db.execute(probe)
|
||||
if result is not None and result.fetchone() is not None:
|
||||
return True
|
||||
except Exception:
|
||||
continue
|
||||
return False
|
||||
|
||||
|
||||
async def ensure_default_storage_policy(db: AsyncSession) -> dict[str, Any]:
|
||||
"""Seed `collection_storage` once under lock; protect existing DB history by setting auto_prune=False."""
|
||||
await acquire_storage_policy_write_lock(db)
|
||||
existing = await _load_setting_row(db, STORAGE_POLICY_CATEGORY, for_update=True)
|
||||
if existing is not None and isinstance(existing.payload, dict):
|
||||
return normalize_storage_policy(existing.payload)
|
||||
|
||||
has_existing_data = await _detect_existing_collection_data(db)
|
||||
history_retention_days = int(DEFAULT_STORAGE_POLICY["history_retention_days"])
|
||||
system_record = await _load_setting_row(db, "system")
|
||||
if system_record is not None and isinstance(system_record.payload, dict):
|
||||
history_retention_days = _clamp_int(
|
||||
system_record.payload.get("data_retention_days"),
|
||||
history_retention_days,
|
||||
minimum=1,
|
||||
maximum=3650,
|
||||
)
|
||||
|
||||
seed_policy = normalize_storage_policy(
|
||||
{
|
||||
**deepcopy(DEFAULT_STORAGE_POLICY),
|
||||
"history_retention_days": history_retention_days,
|
||||
"auto_prune_enabled": not has_existing_data,
|
||||
},
|
||||
fallback_auto_prune=not has_existing_data,
|
||||
)
|
||||
record = SystemSetting(category=STORAGE_POLICY_CATEGORY, payload=seed_policy)
|
||||
db.add(record)
|
||||
await db.commit()
|
||||
if hasattr(db, "refresh"):
|
||||
await db.refresh(record)
|
||||
logger.info_event(
|
||||
"Initialized default collection storage policy",
|
||||
event="storage_policy.seeded",
|
||||
context={
|
||||
"has_existing_data": has_existing_data,
|
||||
"default_mode": seed_policy["default_mode"],
|
||||
"overrides": seed_policy["overrides"],
|
||||
"auto_prune_enabled": seed_policy["auto_prune_enabled"],
|
||||
"history_retention_days": seed_policy["history_retention_days"],
|
||||
},
|
||||
)
|
||||
return seed_policy
|
||||
@@ -3,9 +3,10 @@
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from hashlib import sha256
|
||||
import json
|
||||
import time
|
||||
from typing import Any, Iterable
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy import delete, select
|
||||
from sqlalchemy import Float
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
@@ -14,6 +15,7 @@ from app.models.vessel import (
|
||||
AISRawObservation,
|
||||
AISSourceHealth,
|
||||
VesselCurrentState,
|
||||
VesselPosition,
|
||||
)
|
||||
from app.services.vessel_aggregation_strategy import (
|
||||
DEFAULT_STRATEGY,
|
||||
@@ -23,6 +25,9 @@ from app.services.vessel_types import normalize_vessel_type_name
|
||||
|
||||
VESSEL_AIS_SCHEMA = "vessel_ais"
|
||||
DEFAULT_AGGREGATION_WINDOW_HOURS = 24
|
||||
VESSEL_TRACK_RETENTION_HOURS = 24
|
||||
VESSEL_TRACK_PRUNE_INTERVAL_SECONDS = 1800.0
|
||||
_LAST_TRACK_PRUNE_MONO = 0.0
|
||||
DEFAULT_SNAPSHOT_WINDOW_MINUTES = 60
|
||||
MAX_SNAPSHOT_LIMIT = 5000
|
||||
MAX_SNAPSHOT_CANDIDATE_MULTIPLIER = 20
|
||||
@@ -449,6 +454,105 @@ def _group_observations(observations: Iterable[AISRawObservation]) -> dict[str,
|
||||
return grouped
|
||||
|
||||
|
||||
def _optional_float(value: Any) -> float | None:
|
||||
try:
|
||||
if value in (None, ""):
|
||||
return None
|
||||
return float(value)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _optional_small_int(value: Any) -> int | None:
|
||||
try:
|
||||
if value in (None, ""):
|
||||
return None
|
||||
parsed = int(float(value))
|
||||
return parsed if -32768 <= parsed <= 32767 else None
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
async def _record_vessel_track_point(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
normalized_payload: dict[str, Any],
|
||||
observed_at: datetime,
|
||||
) -> VesselPosition | None:
|
||||
"""Append a bounded 24-hour track point to `vessel_position` without duplicating exact replays."""
|
||||
if not _has_valid_position(normalized_payload):
|
||||
return None
|
||||
|
||||
mmsi = int(normalized_payload["mmsi"])
|
||||
lat = float(normalized_payload["lat"])
|
||||
lon = float(normalized_payload["lon"])
|
||||
observed_utc = _coerce_datetime(observed_at) or datetime.now(UTC)
|
||||
|
||||
if callable(getattr(db, "execute", None)):
|
||||
try:
|
||||
latest_result = await db.execute(
|
||||
select(VesselPosition)
|
||||
.where(VesselPosition.mmsi == mmsi)
|
||||
.order_by(VesselPosition.received_at.desc(), VesselPosition.id.desc())
|
||||
.limit(1)
|
||||
)
|
||||
if latest_result is not None and callable(
|
||||
getattr(latest_result, "scalar_one_or_none", None)
|
||||
):
|
||||
latest = latest_result.scalar_one_or_none()
|
||||
if latest is not None:
|
||||
latest_ts = _coerce_datetime(latest.received_at)
|
||||
if (
|
||||
latest_ts is not None
|
||||
and abs((latest_ts - observed_utc).total_seconds()) < 1e-6
|
||||
and round(float(latest.lat), 5) == round(lat, 5)
|
||||
and round(float(latest.lon), 5) == round(lon, 5)
|
||||
):
|
||||
return None
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
track_point = VesselPosition(
|
||||
mmsi=mmsi,
|
||||
lat=lat,
|
||||
lon=lon,
|
||||
sog=_optional_float(normalized_payload.get("sog")),
|
||||
cog=_optional_float(normalized_payload.get("cog")),
|
||||
heading=_optional_small_int(normalized_payload.get("heading")),
|
||||
nav_status=_optional_small_int(normalized_payload.get("nav_status")),
|
||||
received_at=observed_utc,
|
||||
)
|
||||
db.add(track_point)
|
||||
return track_point
|
||||
|
||||
|
||||
async def prune_expired_vessel_track_points(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
retention_hours: int = VESSEL_TRACK_RETENTION_HOURS,
|
||||
force: bool = False,
|
||||
) -> int:
|
||||
"""Prune `vessel_position` points older than the 24-hour track window."""
|
||||
global _LAST_TRACK_PRUNE_MONO
|
||||
|
||||
if db is None or not callable(getattr(db, "execute", None)):
|
||||
return 0
|
||||
now_mono = time.monotonic()
|
||||
if not force and (now_mono - _LAST_TRACK_PRUNE_MONO) < VESSEL_TRACK_PRUNE_INTERVAL_SECONDS:
|
||||
return 0
|
||||
|
||||
cutoff = (now or datetime.now(UTC)) - timedelta(hours=max(int(retention_hours), 1))
|
||||
try:
|
||||
result = await db.execute(
|
||||
delete(VesselPosition).where(VesselPosition.received_at < cutoff)
|
||||
)
|
||||
except Exception:
|
||||
return 0
|
||||
_LAST_TRACK_PRUNE_MONO = now_mono
|
||||
return int(getattr(result, "rowcount", 0) or 0)
|
||||
|
||||
|
||||
async def record_vessel_ais_observation(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
@@ -462,8 +566,9 @@ async def record_vessel_ais_observation(
|
||||
observed_at: datetime | None = None,
|
||||
collected_at: datetime | None = None,
|
||||
quality_flags: list[str] | None = None,
|
||||
) -> AISRawObservation | None:
|
||||
"""Insert one raw observation if the source-level fact has not already been stored."""
|
||||
persist_raw: bool = True,
|
||||
) -> AISRawObservation | VesselCurrentState | None:
|
||||
"""Persist vessel state; maintain 24h `vessel_position` track when `persist_raw` is False."""
|
||||
|
||||
entity_key = str(normalized_payload["mmsi"])
|
||||
collected_at = collected_at or datetime.now(UTC)
|
||||
@@ -473,6 +578,23 @@ async def record_vessel_ais_observation(
|
||||
or collected_at
|
||||
)
|
||||
normalized_json = _jsonable(normalized_payload)
|
||||
|
||||
if not persist_raw:
|
||||
current = await upsert_vessel_current_state(
|
||||
db,
|
||||
source=source,
|
||||
normalized_payload=normalized_json,
|
||||
observed_at=observed_at,
|
||||
quality_flags=quality_flags or [],
|
||||
)
|
||||
if _has_valid_position(normalized_json):
|
||||
await _record_vessel_track_point(
|
||||
db,
|
||||
normalized_payload=normalized_json,
|
||||
observed_at=observed_at,
|
||||
)
|
||||
return current
|
||||
|
||||
raw_json = _jsonable(raw_payload or {})
|
||||
|
||||
observation_hash = build_observation_hash(
|
||||
@@ -525,10 +647,43 @@ async def upsert_vessel_current_state(
|
||||
) -> VesselCurrentState | None:
|
||||
"""Keep one latest renderable row per MMSI while preserving useful static fields."""
|
||||
|
||||
if not _has_valid_position(normalized_payload):
|
||||
return None
|
||||
mmsi = int(normalized_payload["mmsi"])
|
||||
current = await db.get(VesselCurrentState, mmsi)
|
||||
has_position = _has_valid_position(normalized_payload)
|
||||
|
||||
if not has_position:
|
||||
if current is None:
|
||||
return None
|
||||
updated_fields: set[str] = set()
|
||||
field_sources = dict(current.field_sources or {})
|
||||
for field in CURRENT_STATE_STATIC_FIELDS:
|
||||
value = _payload_value(normalized_payload, field)
|
||||
if value is None:
|
||||
continue
|
||||
existing_source = field_sources.get(field)
|
||||
existing_value = getattr(current, field, None)
|
||||
if (
|
||||
existing_value in (None, "")
|
||||
or _strategy_source_rank(source, DEFAULT_STRATEGY)
|
||||
>= _strategy_source_rank(str(existing_source or ""), DEFAULT_STRATEGY)
|
||||
):
|
||||
setattr(current, field, value)
|
||||
updated_fields.add(field)
|
||||
if not updated_fields:
|
||||
return current
|
||||
current.vessel_type_name = current.vessel_type_name or normalize_vessel_type_name(
|
||||
current.vessel_type
|
||||
)
|
||||
selected_reasons = dict(current.selected_reasons or {})
|
||||
for field in updated_fields:
|
||||
field_sources[field] = source
|
||||
selected_reasons[field] = "source_priority"
|
||||
current.field_sources = field_sources
|
||||
current.selected_reasons = selected_reasons
|
||||
current.updated_at = datetime.now(UTC)
|
||||
current.quality_flags = sorted(set((current.quality_flags or []) + (quality_flags or [])))
|
||||
return current
|
||||
|
||||
if current is not None and current.observed_at is not None:
|
||||
current_observed_at = _coerce_datetime(current.observed_at)
|
||||
if current_observed_at is not None and observed_at < current_observed_at:
|
||||
@@ -689,6 +844,26 @@ async def get_aggregated_vessels(
|
||||
return []
|
||||
vessels = await aggregate_vessel_observations(db, result.scalars().all())
|
||||
|
||||
if not vessels:
|
||||
current_stmt = (
|
||||
select(VesselCurrentState)
|
||||
.where(VesselCurrentState.observed_at >= observed_since)
|
||||
.order_by(VesselCurrentState.observed_at.desc(), VesselCurrentState.mmsi.asc())
|
||||
)
|
||||
if bbox is not None:
|
||||
lon_min, lat_min, lon_max, lat_max = bbox
|
||||
current_stmt = current_stmt.where(
|
||||
VesselCurrentState.lon >= lon_min,
|
||||
VesselCurrentState.lon <= lon_max,
|
||||
VesselCurrentState.lat >= lat_min,
|
||||
VesselCurrentState.lat <= lat_max,
|
||||
)
|
||||
if limit and limit > 0:
|
||||
current_stmt = current_stmt.limit(limit)
|
||||
current_result = await db.execute(current_stmt)
|
||||
if hasattr(current_result, "scalars"):
|
||||
return [item.to_dict() for item in current_result.scalars().all()]
|
||||
|
||||
if bbox is not None:
|
||||
lon_min, lat_min, lon_max, lat_max = bbox
|
||||
vessels = [
|
||||
@@ -740,13 +915,26 @@ async def get_aggregated_vessels_snapshot(
|
||||
if not hasattr(result, "scalars"):
|
||||
return []
|
||||
vessels = await aggregate_vessel_observations(db, result.scalars().all())
|
||||
if not vessels:
|
||||
return await get_current_vessels_snapshot(
|
||||
db,
|
||||
bbox=bbox,
|
||||
limit=safe_limit,
|
||||
observed_since=observed_since,
|
||||
)
|
||||
return vessels[:safe_limit]
|
||||
|
||||
|
||||
async def get_aggregated_vessel(db: AsyncSession, mmsi: int) -> dict[str, Any] | None:
|
||||
observations = await get_vessel_raw_observations(db, mmsi, limit=1000)
|
||||
vessels = await aggregate_vessel_observations(db, observations)
|
||||
return vessels[0] if vessels else None
|
||||
if vessels:
|
||||
return vessels[0]
|
||||
if callable(getattr(db, "get", None)):
|
||||
current = await db.get(VesselCurrentState, mmsi)
|
||||
if current is not None:
|
||||
return current.to_dict()
|
||||
return None
|
||||
|
||||
|
||||
async def get_aggregated_vessel_track(
|
||||
@@ -766,32 +954,86 @@ async def get_aggregated_vessel_track(
|
||||
return []
|
||||
|
||||
points: list[dict[str, Any]] = []
|
||||
seen: set[tuple[str, float, float, str]] = set()
|
||||
seen_coords_at: set[tuple[str, float, float]] = set()
|
||||
for observation in result.scalars().all():
|
||||
payload = observation.normalized_payload or {}
|
||||
if not _has_valid_position(payload):
|
||||
continue
|
||||
observed_at = _coerce_datetime(observation.observed_at)
|
||||
if observed_at is None:
|
||||
continue
|
||||
lat = float(payload["lat"])
|
||||
lon = float(payload["lon"])
|
||||
key = (
|
||||
observation.observed_at.isoformat(),
|
||||
round(lat, 5),
|
||||
round(lon, 5),
|
||||
observation.source,
|
||||
)
|
||||
if key in seen:
|
||||
coord_key = (observed_at.isoformat(), round(lat, 5), round(lon, 5))
|
||||
if coord_key in seen_coords_at:
|
||||
continue
|
||||
seen.add(key)
|
||||
seen_coords_at.add(coord_key)
|
||||
points.append(
|
||||
{
|
||||
"lat": lat,
|
||||
"lon": lon,
|
||||
"observed_at": observation.observed_at,
|
||||
"observed_at": observed_at,
|
||||
"source": observation.source,
|
||||
"selected_reason": "track_timeline",
|
||||
"quality_flags": observation.quality_flags or [],
|
||||
}
|
||||
)
|
||||
|
||||
pos_result = await db.execute(
|
||||
select(VesselPosition)
|
||||
.where(VesselPosition.mmsi == mmsi)
|
||||
.where(VesselPosition.received_at >= cutoff)
|
||||
.order_by(VesselPosition.received_at.asc(), VesselPosition.id.asc())
|
||||
)
|
||||
if pos_result is not None and hasattr(pos_result, "scalars"):
|
||||
source_name = "vessel_ais"
|
||||
if callable(getattr(db, "get", None)):
|
||||
current_for_source = await db.get(VesselCurrentState, mmsi)
|
||||
if current_for_source is not None and getattr(current_for_source, "source", None):
|
||||
source_name = str(current_for_source.source)
|
||||
for position in pos_result.scalars().all():
|
||||
observed_at = _coerce_datetime(position.received_at)
|
||||
if observed_at is None:
|
||||
continue
|
||||
lat = float(position.lat)
|
||||
lon = float(position.lon)
|
||||
if not (-90 <= lat <= 90 and -180 <= lon <= 180):
|
||||
continue
|
||||
coord_key = (observed_at.isoformat(), round(lat, 5), round(lon, 5))
|
||||
if coord_key in seen_coords_at:
|
||||
continue
|
||||
seen_coords_at.add(coord_key)
|
||||
points.append(
|
||||
{
|
||||
"lat": lat,
|
||||
"lon": lon,
|
||||
"observed_at": observed_at,
|
||||
"source": source_name,
|
||||
"selected_reason": "track_24h",
|
||||
"quality_flags": [],
|
||||
}
|
||||
)
|
||||
|
||||
if points:
|
||||
points.sort(key=lambda point: point["observed_at"])
|
||||
return points
|
||||
|
||||
if callable(getattr(db, "get", None)):
|
||||
current = await db.get(VesselCurrentState, mmsi)
|
||||
if current is not None and current.lat is not None and current.lon is not None:
|
||||
observed_at = _coerce_datetime(current.observed_at)
|
||||
cutoff_dt = _coerce_datetime(cutoff)
|
||||
if observed_at is not None and (cutoff_dt is None or observed_at >= cutoff_dt):
|
||||
points.append(
|
||||
{
|
||||
"lat": float(current.lat),
|
||||
"lon": float(current.lon),
|
||||
"observed_at": observed_at,
|
||||
"source": current.source,
|
||||
"selected_reason": "current_state",
|
||||
"quality_flags": current.quality_flags or [],
|
||||
}
|
||||
)
|
||||
return points
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
"""Standalone background worker entrypoint for split API/worker deployments."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from contextlib import suppress
|
||||
import signal
|
||||
|
||||
from app.core.config import settings, validate_production_security
|
||||
from app.core.logging import configure_logging, get_logger
|
||||
from app.core.websocket.broadcaster import broadcaster
|
||||
from app.core.websocket.manager import manager
|
||||
from app.db.session import init_db
|
||||
from app.services.data_jobs import start_data_job_worker, stop_data_job_worker
|
||||
from app.services.earth_news_worker import (
|
||||
start_earth_news_target_worker,
|
||||
stop_earth_news_target_worker,
|
||||
)
|
||||
from app.services.scheduler import (
|
||||
acquire_scheduler_leader_lock,
|
||||
cleanup_stale_running_tasks,
|
||||
release_scheduler_leader_lock,
|
||||
start_scheduler,
|
||||
stop_scheduler,
|
||||
sync_scheduler_with_datasources,
|
||||
)
|
||||
|
||||
LEADER_RETRY_SECONDS = 5.0
|
||||
logger = get_logger(__name__, service="worker")
|
||||
|
||||
|
||||
async def run_worker(stop_event: asyncio.Event | None = None) -> None:
|
||||
"""Run scheduler and async queue workers with PostgreSQL leader election."""
|
||||
configure_logging()
|
||||
validate_production_security(settings)
|
||||
await init_db()
|
||||
|
||||
active_stop = stop_event or asyncio.Event()
|
||||
pubsub_started = False
|
||||
leader_lock_acquired = False
|
||||
scheduler_started = False
|
||||
workers_started = False
|
||||
broadcaster_started = False
|
||||
|
||||
try:
|
||||
await manager.start_pubsub(publish_only=True)
|
||||
pubsub_started = True
|
||||
|
||||
while not active_stop.is_set():
|
||||
if not settings.should_run_scheduler:
|
||||
break
|
||||
if await acquire_scheduler_leader_lock():
|
||||
leader_lock_acquired = True
|
||||
break
|
||||
logger.info_event(
|
||||
"Waiting for scheduler leader advisory lock",
|
||||
event="worker.leader_lock.waiting",
|
||||
)
|
||||
with suppress(TimeoutError):
|
||||
await asyncio.wait_for(active_stop.wait(), timeout=LEADER_RETRY_SECONDS)
|
||||
|
||||
if active_stop.is_set():
|
||||
return
|
||||
|
||||
if settings.should_run_scheduler:
|
||||
await cleanup_stale_running_tasks()
|
||||
start_scheduler()
|
||||
scheduler_started = True
|
||||
await sync_scheduler_with_datasources()
|
||||
|
||||
broadcaster.start()
|
||||
broadcaster_started = True
|
||||
start_data_job_worker()
|
||||
start_earth_news_target_worker()
|
||||
workers_started = True
|
||||
logger.info_event(
|
||||
"Background worker started",
|
||||
event="worker.started",
|
||||
context={"role": settings.normalized_role, "scheduler": scheduler_started},
|
||||
)
|
||||
await active_stop.wait()
|
||||
finally:
|
||||
if broadcaster_started:
|
||||
try:
|
||||
broadcaster.stop()
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed stopping broadcaster during worker shutdown",
|
||||
event="worker.shutdown.broadcaster_error",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
if workers_started:
|
||||
try:
|
||||
await stop_earth_news_target_worker()
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed stopping earth news worker during worker shutdown",
|
||||
event="worker.shutdown.earth_news_error",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
try:
|
||||
await stop_data_job_worker()
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed stopping data job worker during worker shutdown",
|
||||
event="worker.shutdown.data_job_error",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
if scheduler_started:
|
||||
try:
|
||||
stop_scheduler()
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed stopping scheduler during worker shutdown",
|
||||
event="worker.shutdown.scheduler_error",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
if leader_lock_acquired:
|
||||
try:
|
||||
await release_scheduler_leader_lock()
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed releasing scheduler leader lock during worker shutdown",
|
||||
event="worker.shutdown.leader_lock_error",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
if pubsub_started:
|
||||
try:
|
||||
await manager.stop_pubsub()
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed stopping pubsub during worker shutdown",
|
||||
event="worker.shutdown.pubsub_error",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
logger.info_event("Background worker stopped", event="worker.stopped")
|
||||
|
||||
|
||||
async def _main() -> None:
|
||||
stop_event = asyncio.Event()
|
||||
loop = asyncio.get_running_loop()
|
||||
for sig in (signal.SIGINT, signal.SIGTERM):
|
||||
with suppress(NotImplementedError):
|
||||
loop.add_signal_handler(sig, stop_event.set)
|
||||
await run_worker(stop_event)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(_main())
|
||||
@@ -1203,9 +1203,10 @@ async def test_save_bgp_observations_for_batch_adds_rows(monkeypatch):
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_bgp_anomalies_for_batch_calls_incident_aggregation():
|
||||
previous_record = CollectedData(
|
||||
previous_record = BGPObservation(
|
||||
source="ris_live_bgp",
|
||||
extra_data={"prefix": "203.0.113.0/24", "origin_asn": 64496},
|
||||
prefix="203.0.113.0/24",
|
||||
origin_asn=64496,
|
||||
)
|
||||
db = _StrictFakeAsyncSession(
|
||||
[
|
||||
@@ -1214,7 +1215,7 @@ async def test_create_bgp_anomalies_for_batch_calls_incident_aggregation():
|
||||
[], # IPtoASN prefix geography
|
||||
[], # NRO delegated prefix geography
|
||||
[], # PeeringDB ASN profiles
|
||||
[previous_record], # Prior collected snapshot for origin-change detection
|
||||
[previous_record], # Prior BGP observations for origin-change detection
|
||||
[], # Existing anomaly entity keys
|
||||
]
|
||||
)
|
||||
@@ -1262,9 +1263,10 @@ async def test_create_bgp_anomalies_for_batch_calls_incident_aggregation():
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_bgp_anomalies_for_batch_skips_existing_entity_keys():
|
||||
previous_record = CollectedData(
|
||||
previous_record = BGPObservation(
|
||||
source="ris_live_bgp",
|
||||
extra_data={"prefix": "203.0.113.0/24", "origin_asn": 64496},
|
||||
prefix="203.0.113.0/24",
|
||||
origin_asn=64496,
|
||||
)
|
||||
existing_key = ("origin_change:203.0.113.0/24:64497",)
|
||||
existing_anomaly = BGPAnomaly(
|
||||
@@ -1284,7 +1286,7 @@ async def test_create_bgp_anomalies_for_batch_skips_existing_entity_keys():
|
||||
[], # IPtoASN prefix geography
|
||||
[], # NRO delegated prefix geography
|
||||
[], # PeeringDB ASN profiles
|
||||
[previous_record], # Prior collected snapshot for origin-change detection
|
||||
[previous_record], # Prior BGP observations for origin-change detection
|
||||
[existing_key],
|
||||
[existing_anomaly],
|
||||
]
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
"""Tests for client L1 hot-update manifest and bundle hosting APIs."""
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import tarfile
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.security import create_access_token
|
||||
from app.db.session import get_db
|
||||
from app.main import app
|
||||
from app.models.user import User
|
||||
|
||||
|
||||
class _DummyDbSession:
|
||||
pass
|
||||
|
||||
|
||||
class _ScalarResult:
|
||||
def __init__(self, user: User):
|
||||
self._user = user
|
||||
|
||||
def scalar_one_or_none(self):
|
||||
return self._user
|
||||
|
||||
|
||||
class _UserLookupSession:
|
||||
def __init__(self, user: User):
|
||||
self._user = user
|
||||
|
||||
async def execute(self, _stmt):
|
||||
return _ScalarResult(self._user)
|
||||
|
||||
|
||||
def _make_tar_gz(entries: dict[str, bytes], *, prefix: str = "") -> bytes:
|
||||
buf = io.BytesIO()
|
||||
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
|
||||
for name, data in entries.items():
|
||||
info = tarfile.TarInfo(name=f"{prefix}{name}")
|
||||
info.size = len(data)
|
||||
tar.addfile(info, io.BytesIO(data))
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _isolate_client_updates_dir(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(settings, "CLIENT_UPDATES_DIR", str(tmp_path))
|
||||
monkeypatch.setattr(settings, "CLIENT_UPDATE_PUBLISH_TOKEN", "ci-publish-secret-token")
|
||||
monkeypatch.setattr("app.core.security.redis_client", type("NoRedis", (), {"sismember": staticmethod(lambda *_a, **_k: False)})())
|
||||
yield
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_default_manifest_before_any_hotfix_published():
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
res = await client.get("/api/v1/client/update-manifest?shell=0.78.0&bundle=0.78.0")
|
||||
assert res.status_code == 200
|
||||
assert res.headers["cache-control"] == "no-store"
|
||||
data = res.json()
|
||||
assert data["shell"]["version"] == settings.VERSION
|
||||
assert data["bundle"] is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_publish_bundle_auth_validation_and_download():
|
||||
valid_tar = _make_tar_gz(
|
||||
{
|
||||
"index.html": b"<!doctype html><html><body>updated</body></html>",
|
||||
"js/main.js": b"console.log('hotfix');",
|
||||
}
|
||||
)
|
||||
expected_sha = hashlib.sha256(valid_tar).hexdigest()
|
||||
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
# Unauthenticated rejected
|
||||
unauth = await client.post(
|
||||
"/api/v1/client/updates/bundle",
|
||||
data={"version": "0.78.1"},
|
||||
files={"file": ("bundle.tar.gz", valid_tar, "application/gzip")},
|
||||
)
|
||||
assert unauth.status_code == 401
|
||||
|
||||
# Wrong CI publish token rejected
|
||||
bad_token = await client.post(
|
||||
"/api/v1/client/updates/bundle",
|
||||
headers={"X-Client-Update-Token": "wrong-token"},
|
||||
data={"version": "0.78.1"},
|
||||
files={"file": ("bundle.tar.gz", valid_tar, "application/gzip")},
|
||||
)
|
||||
assert bad_token.status_code == 401
|
||||
|
||||
# Non-admin JWT rejected
|
||||
async def _non_admin_db():
|
||||
yield _UserLookupSession(User(id=2, username="viewer", email="v@example.com", role="viewer", is_active=True))
|
||||
|
||||
app.dependency_overrides[get_db] = _non_admin_db
|
||||
viewer_jwt = create_access_token({"sub": "2", "username": "viewer"})
|
||||
forbidden = await client.post(
|
||||
"/api/v1/client/updates/bundle",
|
||||
headers={"Authorization": f"Bearer {viewer_jwt}"},
|
||||
data={"version": "0.78.1"},
|
||||
files={"file": ("bundle.tar.gz", valid_tar, "application/gzip")},
|
||||
)
|
||||
assert forbidden.status_code == 403
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
# Malicious path traversal archive rejected
|
||||
evil_tar = _make_tar_gz({"../evil.js": b"alert(1)", "index.html": b"ok"})
|
||||
evil_res = await client.post(
|
||||
"/api/v1/client/updates/bundle",
|
||||
headers={"X-Client-Update-Token": "ci-publish-secret-token"},
|
||||
data={"version": "0.78.1"},
|
||||
files={"file": ("evil.tar.gz", evil_tar, "application/gzip")},
|
||||
)
|
||||
assert evil_res.status_code == 400
|
||||
|
||||
# Valid publish via CI token succeeds and updates manifest
|
||||
pub = await client.post(
|
||||
"/api/v1/client/updates/bundle",
|
||||
headers={"X-Client-Update-Token": "ci-publish-secret-token"},
|
||||
data={
|
||||
"version": "0.78.1",
|
||||
"min_shell_version": "0.78.0",
|
||||
"release_notes": "Fix WebGL recovery",
|
||||
"shell_version": "0.78.1",
|
||||
"shell_min_required": "0.78.0",
|
||||
"shell_download_url": "https://gitea.rclaw.top/linkong/planet/releases/tag/v0.78.1",
|
||||
},
|
||||
files={"file": ("planet-earth-bundle-0.78.1.tar.gz", valid_tar, "application/gzip")},
|
||||
)
|
||||
assert pub.status_code == 200
|
||||
pub_data = pub.json()
|
||||
assert pub_data["status"] == "published"
|
||||
assert pub_data["manifest"]["bundle"]["version"] == "0.78.1"
|
||||
assert pub_data["manifest"]["bundle"]["sha256"] == expected_sha
|
||||
assert pub_data["manifest"]["bundle"]["size"] == len(valid_tar)
|
||||
assert pub_data["manifest"]["bundle"]["filesCount"] == 2
|
||||
|
||||
# Manifest reflects published bundle
|
||||
manifest_res = await client.get("/api/v1/client/update-manifest")
|
||||
assert manifest_res.status_code == 200
|
||||
bundle = manifest_res.json()["bundle"]
|
||||
assert bundle["version"] == "0.78.1"
|
||||
assert bundle["url"] == "/api/v1/client/updates/files/planet-earth-bundle-0.78.1.tar.gz"
|
||||
|
||||
# Download serves exact archive bytes
|
||||
dl = await client.get(bundle["url"])
|
||||
assert dl.status_code == 200
|
||||
assert dl.content == valid_tar
|
||||
|
||||
# Admin JWT publish also works cleanly
|
||||
missing_index_tar = _make_tar_gz({"js/main.js": b"console.log(1)"})
|
||||
|
||||
async def _admin_db():
|
||||
yield _UserLookupSession(User(id=1, username="admin", email="a@example.com", role="admin", is_active=True))
|
||||
|
||||
app.dependency_overrides[get_db] = _admin_db
|
||||
admin_jwt = create_access_token({"sub": "1", "username": "admin"})
|
||||
no_idx = await client.post(
|
||||
"/api/v1/client/updates/bundle",
|
||||
headers={"Authorization": f"Bearer {admin_jwt}"},
|
||||
data={"version": "0.78.2"},
|
||||
files={"file": ("no-index.tar.gz", missing_index_tar, "application/gzip")},
|
||||
)
|
||||
assert no_idx.status_code == 400
|
||||
|
||||
# Invalid download filename rejected
|
||||
bad_dl = await client.get("/api/v1/client/updates/files/not-allowed.txt")
|
||||
assert bad_dl.status_code == 400
|
||||
@@ -0,0 +1,424 @@
|
||||
"""Tests for collector concurrency limits, thread-offloaded parsing/transform, Core bulk upsert, and dashboard stats."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from datetime import UTC, datetime, timedelta
|
||||
import gzip
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.enums import AlertSeverity, AlertStatus, JobStatus
|
||||
from app.core.websocket import broadcaster as broadcaster_module
|
||||
from app.core.websocket.broadcaster import DataBroadcaster
|
||||
from app.models.alert import Alert
|
||||
from app.models.collected_data import CollectedData
|
||||
from app.models.data_snapshot import DataSnapshot
|
||||
from app.models.datasource import DataSource
|
||||
from app.models.task import CollectionTask
|
||||
from app.services import scheduler
|
||||
from app.services.collectors.base import BaseCollector
|
||||
from app.services.collectors.iptoasn import IPtoASNPrefixGeoCollector
|
||||
from app.services.collectors.nro_delegated import NRODelegatedPrefixGeoCollector
|
||||
from app.services.collectors.registry import collector_registry
|
||||
|
||||
|
||||
class _AsyncSQLiteSession:
|
||||
def __init__(self, session: Session):
|
||||
self._session = session
|
||||
|
||||
def get_bind(self):
|
||||
return self._session.get_bind()
|
||||
|
||||
def add(self, instance) -> None:
|
||||
self._session.add(instance)
|
||||
|
||||
def add_all(self, instances) -> None:
|
||||
self._session.add_all(instances)
|
||||
|
||||
async def get(self, entity, ident):
|
||||
return self._session.get(entity, ident)
|
||||
|
||||
async def execute(self, statement, params=None):
|
||||
if params is not None:
|
||||
return self._session.execute(statement, params)
|
||||
return self._session.execute(statement)
|
||||
|
||||
async def scalar(self, statement):
|
||||
return self._session.scalar(statement)
|
||||
|
||||
async def scalars(self, statement):
|
||||
return self._session.scalars(statement)
|
||||
|
||||
async def flush(self) -> None:
|
||||
self._session.flush()
|
||||
|
||||
async def commit(self) -> None:
|
||||
self._session.commit()
|
||||
|
||||
async def rollback(self) -> None:
|
||||
self._session.rollback()
|
||||
|
||||
async def refresh(self, instance) -> None:
|
||||
self._session.refresh(instance)
|
||||
|
||||
|
||||
class _DummySessionCtx:
|
||||
def __init__(self, sync_session: Session):
|
||||
self._wrapper = _AsyncSQLiteSession(sync_session)
|
||||
|
||||
async def __aenter__(self):
|
||||
return self._wrapper
|
||||
|
||||
async def __aexit__(self, *_args):
|
||||
return False
|
||||
|
||||
|
||||
def _create_collector_db():
|
||||
engine = create_engine("sqlite://")
|
||||
for model in (DataSource, CollectionTask, DataSnapshot, CollectedData, Alert):
|
||||
model.__table__.create(engine)
|
||||
return engine
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_heavy_collectors_serialize_without_blocking_light_collectors(monkeypatch):
|
||||
scheduler._COLLECTOR_SEMAPHORES.clear()
|
||||
scheduler._HEAVY_COLLECTOR_SEMAPHORES.clear()
|
||||
monkeypatch.setattr(settings, "COLLECTOR_MAX_CONCURRENCY", 2)
|
||||
monkeypatch.setattr(settings, "COLLECTOR_HEAVY_CONCURRENCY", 1)
|
||||
|
||||
events: list[tuple[str, str]] = []
|
||||
heavy_active = 0
|
||||
max_heavy_active = 0
|
||||
|
||||
class FakeCollector:
|
||||
def __init__(self, source_name: str, *, heavy: bool):
|
||||
self.name = source_name
|
||||
self._heavy = heavy
|
||||
self._datasource_id = 1
|
||||
|
||||
async def run(self, _db):
|
||||
nonlocal heavy_active, max_heavy_active
|
||||
events.append(("start", self.name))
|
||||
if self._heavy:
|
||||
heavy_active += 1
|
||||
max_heavy_active = max(max_heavy_active, heavy_active)
|
||||
await asyncio.sleep(0.08 if self._heavy else 0.02)
|
||||
if self._heavy:
|
||||
heavy_active -= 1
|
||||
events.append(("end", self.name))
|
||||
return {"status": "success"}
|
||||
|
||||
fake_collectors = {
|
||||
"iptoasn_prefix_geo": FakeCollector("iptoasn_prefix_geo", heavy=True),
|
||||
"nro_delegated_prefix_geo": FakeCollector("nro_delegated_prefix_geo", heavy=True),
|
||||
"light_source": FakeCollector("light_source", heavy=False),
|
||||
}
|
||||
|
||||
engine = _create_collector_db()
|
||||
with Session(engine) as s:
|
||||
s.add_all(
|
||||
[
|
||||
DataSource(
|
||||
id=1,
|
||||
name="IPtoASN",
|
||||
source="iptoasn_prefix_geo",
|
||||
module="L3",
|
||||
priority="P1",
|
||||
frequency_minutes=360,
|
||||
collector_class="iptoasn_prefix_geo",
|
||||
is_active=True,
|
||||
),
|
||||
DataSource(
|
||||
id=2,
|
||||
name="NRO",
|
||||
source="nro_delegated_prefix_geo",
|
||||
module="L3",
|
||||
priority="P1",
|
||||
frequency_minutes=720,
|
||||
collector_class="nro_delegated_prefix_geo",
|
||||
is_active=True,
|
||||
),
|
||||
DataSource(
|
||||
id=3,
|
||||
name="Light",
|
||||
source="light_source",
|
||||
module="L1",
|
||||
priority="P0",
|
||||
frequency_minutes=60,
|
||||
collector_class="light_source",
|
||||
is_active=True,
|
||||
),
|
||||
]
|
||||
)
|
||||
s.commit()
|
||||
|
||||
def session_factory():
|
||||
return _DummySessionCtx(Session(engine))
|
||||
|
||||
monkeypatch.setattr(scheduler, "async_session_factory", session_factory)
|
||||
monkeypatch.setattr(collector_registry, "get", lambda name: fake_collectors.get(name))
|
||||
|
||||
async def noop(*_args, **_kwargs):
|
||||
return None
|
||||
|
||||
async def fake_candidate(*_args, **_kwargs):
|
||||
return {"endpoint": "", "auth_type": "none", "headers": {}, "config": {}}
|
||||
|
||||
async def fake_checksum(*_args, **_kwargs):
|
||||
return ("chk", {})
|
||||
|
||||
monkeypatch.setattr(scheduler, "emit_business_log", noop)
|
||||
monkeypatch.setattr(scheduler, "_update_next_run_at", noop)
|
||||
monkeypatch.setattr(scheduler, "get_builtin_effective_candidate", fake_candidate)
|
||||
monkeypatch.setattr(scheduler, "build_builtin_connectivity_checksum", fake_checksum)
|
||||
monkeypatch.setattr(scheduler, "save_connectivity_success", noop)
|
||||
|
||||
await asyncio.gather(
|
||||
scheduler.run_collector_task("iptoasn_prefix_geo"),
|
||||
scheduler.run_collector_task("nro_delegated_prefix_geo"),
|
||||
scheduler.run_collector_task("light_source"),
|
||||
)
|
||||
|
||||
assert max_heavy_active == 1
|
||||
first_heavy_end = next(
|
||||
idx for idx, item in enumerate(events) if item[0] == "end" and item[1] in scheduler.HEAVY_COLLECTOR_SOURCES
|
||||
)
|
||||
second_heavy_start = max(
|
||||
idx for idx, item in enumerate(events) if item[0] == "start" and item[1] in scheduler.HEAVY_COLLECTOR_SOURCES
|
||||
)
|
||||
assert second_heavy_start > first_heavy_end
|
||||
light_end = events.index(("end", "light_source"))
|
||||
assert light_end < second_heavy_start
|
||||
|
||||
scheduler._COLLECTOR_SEMAPHORES.clear()
|
||||
scheduler._HEAVY_COLLECTOR_SEMAPHORES.clear()
|
||||
engine.dispose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_large_collector_offloading_and_core_bulk_incremental_upsert(
|
||||
monkeypatch, tmp_path: Path
|
||||
):
|
||||
# Verify streaming NRO parser & gzip IPtoASN parser work cleanly on files.
|
||||
nro_file = tmp_path / "delegated.txt"
|
||||
nro_lines = [
|
||||
"# header",
|
||||
"apnic|CN|ipv4|1.0.1.0|256|20110414|allocated",
|
||||
"ripencc|DE|ipv6|2001:db8::|32|20200101|assigned",
|
||||
"arin|US|asn|15169|1|20000101|allocated",
|
||||
]
|
||||
nro_file.write_text("\n".join(nro_lines), encoding="utf-8")
|
||||
nro_collector = NRODelegatedPrefixGeoCollector()
|
||||
parsed_nro = await asyncio.to_thread(nro_collector._parse_delegated_file, nro_file)
|
||||
assert len(parsed_nro) == 2
|
||||
transformed_nro = nro_collector.transform(parsed_nro)
|
||||
assert len(transformed_nro) == 2
|
||||
|
||||
gz_file = tmp_path / "iptoasn.tsv.gz"
|
||||
with gzip.open(gz_file, "wt", encoding="utf-8") as fh:
|
||||
fh.write("1.0.0.0\t1.0.0.255\t13335\tAU\tCLOUDFLARENET\n")
|
||||
ip_collector = IPtoASNPrefixGeoCollector()
|
||||
parsed_ip = await asyncio.to_thread(ip_collector._parse_dataset_files, [gz_file])
|
||||
assert len(parsed_ip) == 1
|
||||
|
||||
# Verify >=1500 row offloaded transform/prepare + Core bulk insert + incremental update/unchanged/delete.
|
||||
engine = _create_collector_db()
|
||||
|
||||
class BulkTestCollector(BaseCollector):
|
||||
name = "bulk_test_source"
|
||||
data_type = "prefix_geography"
|
||||
full_snapshot_reconcile = True
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.rows: list[dict] = []
|
||||
|
||||
async def fetch(self):
|
||||
return list(self.rows)
|
||||
|
||||
def transform(self, raw_data):
|
||||
return [
|
||||
{
|
||||
"source_id": item["id"],
|
||||
"name": item["name"],
|
||||
"title": item["name"],
|
||||
"country": "CN",
|
||||
"metadata": {"seq": item["seq"]},
|
||||
"reference_date": "2026-11-23T00:00:00Z",
|
||||
}
|
||||
for item in raw_data
|
||||
]
|
||||
|
||||
monkeypatch.setattr(collector_registry, "is_active", lambda _name: True)
|
||||
collector = BulkTestCollector()
|
||||
collector.rows = [{"id": f"id-{i}", "name": f"Node {i}", "seq": i} for i in range(1500)]
|
||||
|
||||
ticks = 0
|
||||
keep_ticking = True
|
||||
|
||||
async def ticker():
|
||||
nonlocal ticks
|
||||
while keep_ticking:
|
||||
ticks += 1
|
||||
await asyncio.sleep(0.005)
|
||||
|
||||
with Session(engine) as sync_session:
|
||||
db = _AsyncSQLiteSession(sync_session)
|
||||
sync_session.add(
|
||||
DataSource(
|
||||
id=1,
|
||||
name="Bulk Test",
|
||||
source="bulk_test_source",
|
||||
module="L3",
|
||||
priority="P1",
|
||||
frequency_minutes=60,
|
||||
collector_class="bulk_test_source",
|
||||
is_active=True,
|
||||
)
|
||||
)
|
||||
sync_session.commit()
|
||||
|
||||
tick_task = asyncio.create_task(ticker())
|
||||
try:
|
||||
first_result = await collector.run(db)
|
||||
finally:
|
||||
keep_ticking = False
|
||||
await tick_task
|
||||
|
||||
assert first_result["status"] == "success"
|
||||
assert first_result["records_processed"] == 1500
|
||||
assert collector._last_save_summary == {
|
||||
"created": 1500,
|
||||
"updated": 0,
|
||||
"unchanged": 0,
|
||||
"deleted": 0,
|
||||
}
|
||||
assert ticks >= 1
|
||||
|
||||
# Verify Core bulk insert populated extra_data and content_hash without comparable_payload leak.
|
||||
sample = sync_session.execute(
|
||||
select(CollectedData).where(CollectedData.source_id == "id-42")
|
||||
).scalar_one()
|
||||
assert sample.extra_data["seq"] == 42
|
||||
assert sample.extra_data["country"] == "中国"
|
||||
assert sample.content_hash is not None
|
||||
|
||||
# Incremental update: update 1 row, vanish 1 row, leave 1498 unchanged, create 1 new row.
|
||||
collector.rows = [
|
||||
item for item in collector.rows if item["id"] != "id-0"
|
||||
]
|
||||
collector.rows[0] = {"id": "id-1", "name": "Node 1 Updated", "seq": 9999}
|
||||
collector.rows.append({"id": "id-new", "name": "Node New", "seq": 2000})
|
||||
|
||||
second_result = await collector.run(db)
|
||||
assert second_result["status"] == "success"
|
||||
assert second_result["records_processed"] == 1500
|
||||
assert collector._last_save_summary == {
|
||||
"created": 1,
|
||||
"updated": 1,
|
||||
"unchanged": 1498,
|
||||
"deleted": 1,
|
||||
}
|
||||
|
||||
engine.dispose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_dashboard_broadcaster_skips_when_unsubscribed_and_queries_real_stats(monkeypatch):
|
||||
engine = _create_collector_db()
|
||||
with Session(engine) as s:
|
||||
now = datetime.now(UTC)
|
||||
s.add_all(
|
||||
[
|
||||
DataSource(
|
||||
id=1,
|
||||
name="Active A",
|
||||
source="a",
|
||||
module="L1",
|
||||
priority="P0",
|
||||
frequency_minutes=60,
|
||||
collector_class="a",
|
||||
is_active=True,
|
||||
),
|
||||
DataSource(
|
||||
id=2,
|
||||
name="Paused B",
|
||||
source="b",
|
||||
module="L2",
|
||||
priority="P1",
|
||||
frequency_minutes=60,
|
||||
collector_class="b",
|
||||
is_active=False,
|
||||
),
|
||||
CollectionTask(
|
||||
datasource_id=1,
|
||||
source="a",
|
||||
status=JobStatus.SUCCESS.value,
|
||||
created_at=now,
|
||||
),
|
||||
CollectionTask(
|
||||
datasource_id=1,
|
||||
source="a",
|
||||
status=JobStatus.SUCCESS.value,
|
||||
created_at=now,
|
||||
),
|
||||
CollectionTask(
|
||||
datasource_id=2,
|
||||
source="b",
|
||||
status=JobStatus.FAILED.value,
|
||||
created_at=now,
|
||||
),
|
||||
CollectionTask(
|
||||
datasource_id=1,
|
||||
source="a",
|
||||
status=JobStatus.FAILED.value,
|
||||
created_at=now - timedelta(days=2),
|
||||
),
|
||||
Alert(severity=AlertSeverity.CRITICAL, status=AlertStatus.ACTIVE, message="crit"),
|
||||
Alert(severity=AlertSeverity.WARNING, status=AlertStatus.ACTIVE, message="warn"),
|
||||
Alert(severity=AlertSeverity.WARNING, status=AlertStatus.RESOLVED, message="old"),
|
||||
]
|
||||
)
|
||||
s.commit()
|
||||
|
||||
from app import db as db_pkg
|
||||
|
||||
monkeypatch.setattr(db_pkg.session, "async_session_factory", lambda: _DummySessionCtx(Session(engine)))
|
||||
|
||||
broadcaster = DataBroadcaster()
|
||||
stats = await broadcaster.get_dashboard_stats()
|
||||
assert stats["total_datasources"] == 2
|
||||
assert stats["active_datasources"] == 1
|
||||
assert stats["tasks_today"] == 3
|
||||
assert stats["success_rate"] == 66.7
|
||||
assert stats["alerts"] == {"critical": 1, "warning": 1, "info": 0}
|
||||
|
||||
import importlib
|
||||
|
||||
ws_broadcaster_mod = importlib.import_module("app.core.websocket.broadcaster")
|
||||
monkeypatch.setattr(ws_broadcaster_mod.manager, "channel_subscriptions", {})
|
||||
query_calls = 0
|
||||
|
||||
async def fail_if_called():
|
||||
nonlocal query_calls
|
||||
query_calls += 1
|
||||
broadcaster.running = False
|
||||
return stats
|
||||
|
||||
monkeypatch.setattr(broadcaster, "get_dashboard_stats", fail_if_called)
|
||||
|
||||
async def stop_sleep(_sec):
|
||||
broadcaster.running = False
|
||||
|
||||
monkeypatch.setattr(ws_broadcaster_mod.asyncio, "sleep", stop_sleep)
|
||||
broadcaster.running = True
|
||||
await broadcaster.broadcast_stats(interval=5)
|
||||
assert query_calls == 0
|
||||
|
||||
engine.dispose()
|
||||
@@ -3,17 +3,25 @@ from types import SimpleNamespace
|
||||
import pytest
|
||||
from unittest.mock import AsyncMock
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from sqlalchemy import create_engine, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.api.v1.datasource_config import get_ai_provider_client
|
||||
from app.core.websocket import broadcaster as broadcaster_module
|
||||
from app.core.security import get_current_user
|
||||
from app.core.target_schema_registry import get_target_schema, list_target_schemas
|
||||
from app.db.session import Base
|
||||
from app.main import app
|
||||
from app.models.user import User
|
||||
from app.models.collected_data import CollectedData
|
||||
from app.models.data_snapshot import DataSnapshot
|
||||
from app.models.datasource_config import DataSourceConfig
|
||||
from app.models.system_setting import SystemSetting
|
||||
from app.models.task import CollectionTask
|
||||
from app.models.user import User
|
||||
from app.services import custom_datasource_runtime
|
||||
from app.services.custom_datasource_runtime import run_mapped_websocket_config
|
||||
from app.services.datasource_mapping import execute_mapping, persist_mapped_records, redact_for_llm
|
||||
from app.services.storage_policy import save_storage_policy
|
||||
|
||||
|
||||
SAMPLE_AIS = {
|
||||
@@ -326,3 +334,100 @@ async def test_mapping_propose_api_redacts_sample_before_ai():
|
||||
payload = response.json()
|
||||
assert payload["mapping_json"]["meta"]["generated_by"] == "ai_provider"
|
||||
assert seen_context["sample_payload"]["data"][0]["api_token"] == "[REDACTED]"
|
||||
|
||||
|
||||
class _AsyncMappingSQLiteSession:
|
||||
def __init__(self, session: Session):
|
||||
self._session = session
|
||||
|
||||
def add(self, instance) -> None:
|
||||
self._session.add(instance)
|
||||
|
||||
async def execute(self, statement, params=None):
|
||||
if params is not None:
|
||||
return self._session.execute(statement, params)
|
||||
return self._session.execute(statement)
|
||||
|
||||
async def flush(self) -> None:
|
||||
self._session.flush()
|
||||
|
||||
async def commit(self) -> None:
|
||||
self._session.commit()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_persist_mapped_records_isolates_same_name_configs_and_enforces_lock():
|
||||
engine = create_engine("sqlite:///:memory:")
|
||||
Base.metadata.create_all(
|
||||
engine,
|
||||
tables=[
|
||||
SystemSetting.__table__,
|
||||
CollectionTask.__table__,
|
||||
DataSnapshot.__table__,
|
||||
CollectedData.__table__,
|
||||
],
|
||||
)
|
||||
try:
|
||||
with Session(engine) as sync_session:
|
||||
db = _AsyncMappingSQLiteSession(sync_session)
|
||||
await save_storage_policy(
|
||||
db,
|
||||
{
|
||||
"default_mode": "single",
|
||||
"global_single_lock": True,
|
||||
"overrides": {},
|
||||
},
|
||||
sync_system_retention=False,
|
||||
)
|
||||
|
||||
await persist_mapped_records(
|
||||
db,
|
||||
datasource_name="SharedDisplayName",
|
||||
datasource_config_id=101,
|
||||
target_schema="geo_points",
|
||||
records=[
|
||||
{
|
||||
"source_id": "biz-1",
|
||||
"name": "Alpha Point",
|
||||
"lat": 31.23,
|
||||
"lon": 121.47,
|
||||
"metadata": {"origin": "feed-a"},
|
||||
}
|
||||
],
|
||||
mapping_version=1,
|
||||
snapshot_mode="history",
|
||||
)
|
||||
await persist_mapped_records(
|
||||
db,
|
||||
datasource_name="SharedDisplayName",
|
||||
datasource_config_id=102,
|
||||
target_schema="geo_points",
|
||||
records=[
|
||||
{
|
||||
"source_id": "biz-1",
|
||||
"name": "Beta Point",
|
||||
"lat": 39.90,
|
||||
"lon": 116.40,
|
||||
"metadata": {"origin": "feed-b"},
|
||||
}
|
||||
],
|
||||
mapping_version=1,
|
||||
snapshot_mode="history",
|
||||
)
|
||||
|
||||
rows = list(
|
||||
sync_session.scalars(
|
||||
select(CollectedData)
|
||||
.where(
|
||||
CollectedData.source == "SharedDisplayName",
|
||||
CollectedData.is_current.is_(True),
|
||||
)
|
||||
.order_by(CollectedData.id.asc())
|
||||
).all()
|
||||
)
|
||||
assert len(rows) == 2
|
||||
assert {row.name for row in rows} == {"Alpha Point", "Beta Point"}
|
||||
assert {row.extra_data["datasource_config_id"] for row in rows} == {101, 102}
|
||||
assert len({row.entity_key for row in rows}) == 2
|
||||
finally:
|
||||
engine.dispose()
|
||||
@@ -446,10 +446,10 @@ async def test_earth_news_refresh_scheduler_job_survives_datasource_sync(monkeyp
|
||||
_earth_news_region_refresh_job_id("global")
|
||||
),
|
||||
}
|
||||
self.added: dict[str, object] = {}
|
||||
self.added_jobs: dict[str, dict[str, object]] = {}
|
||||
|
||||
def add_job(self, _func, **kwargs):
|
||||
self.added.update(kwargs)
|
||||
self.added_jobs[kwargs["id"]] = dict(kwargs)
|
||||
self.jobs[kwargs["id"]] = FakeJob(kwargs["id"])
|
||||
|
||||
def start(self) -> None:
|
||||
@@ -484,8 +484,8 @@ async def test_earth_news_refresh_scheduler_job_survives_datasource_sync(monkeyp
|
||||
start_scheduler()
|
||||
await sync_scheduler_with_datasources()
|
||||
|
||||
assert fake_scheduler.added["id"] == EARTH_NEWS_REFRESH_JOB_ID
|
||||
assert fake_scheduler.added["next_run_time"] <= datetime.now(UTC)
|
||||
assert EARTH_NEWS_REFRESH_JOB_ID in fake_scheduler.added_jobs
|
||||
assert fake_scheduler.added_jobs[EARTH_NEWS_REFRESH_JOB_ID]["next_run_time"] <= datetime.now(UTC)
|
||||
assert EARTH_NEWS_REFRESH_JOB_ID in fake_scheduler.jobs
|
||||
assert _earth_news_region_refresh_job_id("global") in fake_scheduler.jobs
|
||||
assert "obsolete" not in fake_scheduler.jobs
|
||||
|
||||
@@ -0,0 +1,329 @@
|
||||
"""Tests for role split, scheduler leader locking, Redis WS Pub/Sub, and DB migrations."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from contextlib import asynccontextmanager
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
from app import main as main_module
|
||||
from app import worker as worker_module
|
||||
from app.core.config import settings
|
||||
from app.core.websocket.manager import ConnectionManager
|
||||
from app.db.migrations import (
|
||||
ensure_baseline_stamped,
|
||||
get_migration_status,
|
||||
run_migrations,
|
||||
stamp_migrations,
|
||||
)
|
||||
|
||||
|
||||
class _AsyncSQLiteConnAdapter:
|
||||
def __init__(self, conn):
|
||||
self._conn = conn
|
||||
self.dialect = conn.dialect
|
||||
|
||||
async def execute(self, statement, params=None):
|
||||
if params is not None:
|
||||
return self._conn.execute(statement, params)
|
||||
return self._conn.execute(statement)
|
||||
|
||||
async def run_sync(self, fn):
|
||||
return fn(self._conn)
|
||||
|
||||
|
||||
class _AsyncSQLiteEngineAdapter:
|
||||
def __init__(self, sync_engine):
|
||||
self._engine = sync_engine
|
||||
|
||||
@asynccontextmanager
|
||||
async def begin(self):
|
||||
with self._engine.begin() as conn:
|
||||
yield _AsyncSQLiteConnAdapter(conn)
|
||||
|
||||
|
||||
class _FakeWebSocket:
|
||||
def __init__(self):
|
||||
self.accepted = False
|
||||
self.sent = []
|
||||
self.closed = False
|
||||
|
||||
async def accept(self):
|
||||
self.accepted = True
|
||||
|
||||
async def send_json(self, message):
|
||||
self.sent.append(message)
|
||||
|
||||
async def close(self):
|
||||
self.closed = True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_lifespan_respects_planet_role_and_leader_lock(monkeypatch):
|
||||
calls: list[str] = []
|
||||
|
||||
async def noop_async(*_args, **_kwargs):
|
||||
return None
|
||||
|
||||
async def true_lock():
|
||||
calls.append("acquire_lock")
|
||||
return True
|
||||
|
||||
async def false_lock():
|
||||
calls.append("acquire_lock_denied")
|
||||
return False
|
||||
|
||||
monkeypatch.setattr(main_module, "init_db", noop_async)
|
||||
monkeypatch.setattr(main_module, "cleanup_stale_running_tasks", lambda: noop_async())
|
||||
monkeypatch.setattr(main_module, "sync_scheduler_with_datasources", lambda: noop_async())
|
||||
monkeypatch.setattr(main_module, "release_scheduler_leader_lock", lambda: noop_async())
|
||||
monkeypatch.setattr(main_module, "start_scheduler", lambda: calls.append("start_scheduler"))
|
||||
monkeypatch.setattr(main_module, "stop_scheduler", lambda: calls.append("stop_scheduler"))
|
||||
monkeypatch.setattr(main_module, "start_data_job_worker", lambda: calls.append("start_jobs"))
|
||||
monkeypatch.setattr(main_module, "stop_data_job_worker", lambda: noop_async())
|
||||
monkeypatch.setattr(main_module, "start_earth_news_target_worker", lambda: calls.append("start_news"))
|
||||
monkeypatch.setattr(main_module, "stop_earth_news_target_worker", lambda: noop_async())
|
||||
monkeypatch.setattr(main_module, "start_earth_db_change_listener", lambda: calls.append("start_db_listener"))
|
||||
monkeypatch.setattr(main_module, "stop_earth_db_change_listener", lambda: noop_async())
|
||||
monkeypatch.setattr(main_module.broadcaster, "start", lambda: calls.append("start_broadcaster"))
|
||||
monkeypatch.setattr(main_module.broadcaster, "stop", lambda: calls.append("stop_broadcaster"))
|
||||
monkeypatch.setattr(main_module.manager, "start_pubsub", lambda **_kwargs: noop_async())
|
||||
monkeypatch.setattr(main_module.manager, "stop_pubsub", lambda: noop_async())
|
||||
|
||||
# Role=api must not start scheduler or background workers.
|
||||
monkeypatch.setattr(settings, "PLANET_ROLE", "api")
|
||||
monkeypatch.setattr(settings, "ENABLE_SCHEDULER", None)
|
||||
monkeypatch.setattr(main_module, "acquire_scheduler_leader_lock", true_lock)
|
||||
calls.clear()
|
||||
async with main_module.lifespan(FastAPI()):
|
||||
pass
|
||||
assert "start_scheduler" not in calls
|
||||
assert "start_jobs" not in calls
|
||||
assert "start_news" not in calls
|
||||
assert "start_broadcaster" in calls
|
||||
|
||||
# Role=all with leader lock denied skips scheduler start cleanly.
|
||||
monkeypatch.setattr(settings, "PLANET_ROLE", "all")
|
||||
monkeypatch.setattr(main_module, "acquire_scheduler_leader_lock", false_lock)
|
||||
calls.clear()
|
||||
async with main_module.lifespan(FastAPI()):
|
||||
pass
|
||||
assert "acquire_lock_denied" in calls
|
||||
assert "start_scheduler" not in calls
|
||||
assert "start_jobs" in calls
|
||||
|
||||
# Role=all with leader lock acquired starts scheduler and workers.
|
||||
monkeypatch.setattr(main_module, "acquire_scheduler_leader_lock", true_lock)
|
||||
calls.clear()
|
||||
async with main_module.lifespan(FastAPI()):
|
||||
pass
|
||||
assert "acquire_lock" in calls
|
||||
assert "start_scheduler" in calls
|
||||
assert "stop_scheduler" in calls
|
||||
assert "start_jobs" in calls
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_standalone_worker_starts_scheduler_workers_and_releases_lock(monkeypatch):
|
||||
events: list[str] = []
|
||||
|
||||
async def noop_async(*_args, **_kwargs):
|
||||
return None
|
||||
|
||||
async def acquire_lock():
|
||||
events.append("lock_acquired")
|
||||
return True
|
||||
|
||||
async def release_lock():
|
||||
events.append("lock_released")
|
||||
|
||||
async def fake_start_pubsub(*, publish_only: bool = False):
|
||||
events.append(f"pubsub:{publish_only}")
|
||||
|
||||
monkeypatch.setattr(worker_module, "init_db", noop_async)
|
||||
monkeypatch.setattr(worker_module, "cleanup_stale_running_tasks", noop_async)
|
||||
monkeypatch.setattr(worker_module, "sync_scheduler_with_datasources", noop_async)
|
||||
monkeypatch.setattr(worker_module, "acquire_scheduler_leader_lock", acquire_lock)
|
||||
monkeypatch.setattr(worker_module, "release_scheduler_leader_lock", release_lock)
|
||||
monkeypatch.setattr(worker_module, "start_scheduler", lambda: events.append("scheduler_started"))
|
||||
monkeypatch.setattr(worker_module, "stop_scheduler", lambda: events.append("scheduler_stopped"))
|
||||
monkeypatch.setattr(worker_module, "start_data_job_worker", lambda: events.append("jobs_started"))
|
||||
monkeypatch.setattr(worker_module, "stop_data_job_worker", noop_async)
|
||||
monkeypatch.setattr(worker_module, "start_earth_news_target_worker", lambda: events.append("news_started"))
|
||||
monkeypatch.setattr(worker_module, "stop_earth_news_target_worker", noop_async)
|
||||
monkeypatch.setattr(worker_module.broadcaster, "start", lambda: events.append("broadcaster_started"))
|
||||
monkeypatch.setattr(worker_module.broadcaster, "stop", lambda: events.append("broadcaster_stopped"))
|
||||
monkeypatch.setattr(worker_module.manager, "start_pubsub", fake_start_pubsub)
|
||||
monkeypatch.setattr(worker_module.manager, "stop_pubsub", noop_async)
|
||||
monkeypatch.setattr(settings, "PLANET_ROLE", "worker")
|
||||
monkeypatch.setattr(settings, "ENABLE_SCHEDULER", None)
|
||||
|
||||
stop_event = asyncio.Event()
|
||||
task = asyncio.create_task(worker_module.run_worker(stop_event))
|
||||
await asyncio.sleep(0.05)
|
||||
stop_event.set()
|
||||
await task
|
||||
|
||||
assert "pubsub:True" in events
|
||||
assert "lock_acquired" in events
|
||||
assert "scheduler_started" in events
|
||||
assert "jobs_started" in events
|
||||
assert "scheduler_stopped" in events
|
||||
assert "lock_released" in events
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_worker_releases_leader_lock_when_startup_fails(monkeypatch):
|
||||
events: list[str] = []
|
||||
|
||||
async def noop_async(*_args, **_kwargs):
|
||||
return None
|
||||
|
||||
async def acquire_lock():
|
||||
events.append("lock_acquired")
|
||||
return True
|
||||
|
||||
async def release_lock():
|
||||
events.append("lock_released")
|
||||
|
||||
async def failing_sync():
|
||||
raise RuntimeError("scheduler sync failed")
|
||||
|
||||
async def fake_stop_pubsub():
|
||||
events.append("pubsub_stopped")
|
||||
|
||||
monkeypatch.setattr(worker_module, "init_db", noop_async)
|
||||
monkeypatch.setattr(worker_module, "cleanup_stale_running_tasks", noop_async)
|
||||
monkeypatch.setattr(worker_module, "sync_scheduler_with_datasources", failing_sync)
|
||||
monkeypatch.setattr(worker_module, "acquire_scheduler_leader_lock", acquire_lock)
|
||||
monkeypatch.setattr(worker_module, "release_scheduler_leader_lock", release_lock)
|
||||
monkeypatch.setattr(worker_module, "start_scheduler", lambda: events.append("scheduler_started"))
|
||||
monkeypatch.setattr(worker_module, "stop_scheduler", lambda: events.append("scheduler_stopped"))
|
||||
monkeypatch.setattr(worker_module.manager, "start_pubsub", noop_async)
|
||||
monkeypatch.setattr(worker_module.manager, "stop_pubsub", fake_stop_pubsub)
|
||||
monkeypatch.setattr(settings, "PLANET_ROLE", "worker")
|
||||
monkeypatch.setattr(settings, "ENABLE_SCHEDULER", None)
|
||||
|
||||
with pytest.raises(RuntimeError, match="scheduler sync failed"):
|
||||
await worker_module.run_worker(asyncio.Event())
|
||||
|
||||
assert events == [
|
||||
"lock_acquired",
|
||||
"scheduler_started",
|
||||
"scheduler_stopped",
|
||||
"lock_released",
|
||||
"pubsub_stopped",
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_connection_manager_redis_pubsub_relay_and_self_echo_suppression():
|
||||
manager_a = ConnectionManager()
|
||||
manager_b = ConnectionManager()
|
||||
published: list[str] = []
|
||||
|
||||
class FakePubSubRedis:
|
||||
async def publish(self, _channel, payload):
|
||||
published.append(payload)
|
||||
|
||||
async def aclose(self):
|
||||
return None
|
||||
|
||||
manager_a._pubsub_enabled = True
|
||||
manager_a._pubsub_client = FakePubSubRedis()
|
||||
|
||||
sock_a = _FakeWebSocket()
|
||||
sock_b = _FakeWebSocket()
|
||||
sock_vessel_b = _FakeWebSocket()
|
||||
|
||||
await manager_a.connect(sock_a, "u-a")
|
||||
await manager_b.connect(sock_b, "u-b")
|
||||
await manager_b.connect(sock_vessel_b, "u-v")
|
||||
manager_a.subscribe(sock_a, ["earth_updates"])
|
||||
manager_b.subscribe(sock_b, ["earth_updates"])
|
||||
manager_b.subscribe_vessels(sock_vessel_b, {"scope": "global", "zoom": 4})
|
||||
|
||||
frame = {"type": "data_frame", "channel": "earth_updates", "payload": {"layers": ["cables"]}}
|
||||
await manager_a.broadcast(frame, channel="earth_updates")
|
||||
await manager_a.broadcast_vessels({"vessels": [{"mmsi": 999, "lat": 10.0, "lon": 20.0}]})
|
||||
|
||||
assert len(published) == 2
|
||||
assert len(sock_a.sent) == 1
|
||||
|
||||
# Self-origin replay must be ignored on manager_a, delivered cleanly on manager_b.
|
||||
for raw in published:
|
||||
assert await manager_a.handle_pubsub_payload(raw) is False
|
||||
assert await manager_b.handle_pubsub_payload(raw) is True
|
||||
|
||||
assert len(sock_a.sent) == 1
|
||||
assert sock_b.sent == [frame]
|
||||
assert sock_vessel_b.sent[0]["payload"]["vessels"] == [{"mmsi": 999, "lat": 10.0, "lon": 20.0}]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_versioned_migrations_upgrade_stamp_and_checksum_validation(tmp_path: Path):
|
||||
steps_dir = tmp_path / "steps"
|
||||
steps_dir.mkdir()
|
||||
m1 = steps_dir / "0001_initial_notes.py"
|
||||
m1.write_text(
|
||||
"from sqlalchemy import text\n"
|
||||
"VERSION = '0001'\n"
|
||||
"NAME = 'initial_notes'\n"
|
||||
"async def upgrade(conn):\n"
|
||||
" await conn.execute(text('CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY)'))\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
sync_engine = create_engine("sqlite://")
|
||||
adapter = _AsyncSQLiteEngineAdapter(sync_engine)
|
||||
|
||||
status_before = await get_migration_status(adapter, steps_dir)
|
||||
assert status_before["applied"] == []
|
||||
assert status_before["pending"] == ["0001"]
|
||||
|
||||
applied = await run_migrations(adapter, steps_dir)
|
||||
assert applied == ["0001"]
|
||||
with sync_engine.connect() as conn:
|
||||
assert conn.execute(text("SELECT COUNT(*) FROM notes")).scalar() == 0
|
||||
|
||||
m2 = steps_dir / "0002_add_body.py"
|
||||
m2.write_text(
|
||||
"from sqlalchemy import text\n"
|
||||
"VERSION = '0002'\n"
|
||||
"NAME = 'add_body'\n"
|
||||
"async def upgrade(conn):\n"
|
||||
" await conn.execute(text('ALTER TABLE notes ADD COLUMN body TEXT'))\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
status_mid = await get_migration_status(adapter, steps_dir)
|
||||
assert status_mid["pending"] == ["0002"]
|
||||
|
||||
applied_second = await run_migrations(adapter, steps_dir)
|
||||
assert applied_second == ["0002"]
|
||||
|
||||
# Mutating an applied migration file triggers checksum mismatch detection.
|
||||
m1.write_text(m1.read_text(encoding="utf-8") + "\n# tampered\n", encoding="utf-8")
|
||||
status_tampered = await get_migration_status(adapter, steps_dir)
|
||||
assert len(status_tampered["mismatches"]) == 1
|
||||
with pytest.raises(RuntimeError, match="Checksum mismatch"):
|
||||
await run_migrations(adapter, steps_dir)
|
||||
|
||||
# Verify ensure_baseline_stamped & stamp_migrations on a fresh DB.
|
||||
sync_engine2 = create_engine("sqlite://")
|
||||
adapter2 = _AsyncSQLiteEngineAdapter(sync_engine2)
|
||||
async with adapter2.begin() as conn:
|
||||
stamped_first = await ensure_baseline_stamped(conn, steps_dir)
|
||||
assert stamped_first is True
|
||||
stamped_rest = await stamp_migrations(adapter2, "0002", steps_dir)
|
||||
assert stamped_rest == ["0002"]
|
||||
final_status = await get_migration_status(adapter2, steps_dir)
|
||||
assert final_status["applied"] == ["0001", "0002"]
|
||||
assert final_status["pending"] == []
|
||||
|
||||
sync_engine.dispose()
|
||||
sync_engine2.dispose()
|
||||
@@ -0,0 +1,571 @@
|
||||
"""Tests for production deployment configs, security hardening, and health probes."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shlex
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
from cryptography.fernet import Fernet
|
||||
from fastapi import FastAPI
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, select
|
||||
from sqlalchemy.orm import Session
|
||||
import yaml
|
||||
|
||||
from app.api.v1 import settings as settings_api
|
||||
from app.api.v1.auth import _LOCAL_LOGIN_FAILURES, _client_ip, router as auth_router
|
||||
from app.core import secret_crypto, security
|
||||
from app.core.config import Settings, settings, validate_production_security
|
||||
from app.db.session import ensure_default_admin_user, get_db, seed_default_datasources
|
||||
from app.main import app as main_app
|
||||
from app.models.datasource import DataSource
|
||||
from app.models.system_setting import SystemSetting
|
||||
from app.models.user import User
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||
if str(REPO_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(REPO_ROOT))
|
||||
|
||||
|
||||
class _AsyncSQLiteSession:
|
||||
"""AsyncSession-compatible test adapter over an isolated in-memory SQLite Session."""
|
||||
|
||||
def __init__(self, session: Session):
|
||||
self._session = session
|
||||
|
||||
def get_bind(self):
|
||||
return self._session.get_bind()
|
||||
|
||||
def add(self, instance) -> None:
|
||||
self._session.add(instance)
|
||||
|
||||
def add_all(self, instances) -> None:
|
||||
self._session.add_all(instances)
|
||||
|
||||
async def get(self, entity, ident):
|
||||
return self._session.get(entity, ident)
|
||||
|
||||
async def execute(self, statement, params=None):
|
||||
if params is not None:
|
||||
return self._session.execute(statement, params)
|
||||
return self._session.execute(statement)
|
||||
|
||||
async def scalar(self, statement):
|
||||
return self._session.scalar(statement)
|
||||
|
||||
async def scalars(self, statement):
|
||||
return self._session.scalars(statement)
|
||||
|
||||
async def flush(self) -> None:
|
||||
self._session.flush()
|
||||
|
||||
async def commit(self) -> None:
|
||||
self._session.commit()
|
||||
|
||||
async def rollback(self) -> None:
|
||||
self._session.rollback()
|
||||
|
||||
async def refresh(self, instance) -> None:
|
||||
self._session.refresh(instance)
|
||||
|
||||
|
||||
def test_deploy_compose_fixes_ai_url_frontend_target_volumes_and_ports():
|
||||
compose = yaml.safe_load((REPO_ROOT / "docker-compose.deploy.yml").read_text(encoding="utf-8"))
|
||||
services = compose["services"]
|
||||
|
||||
backend = services["backend"]
|
||||
backend_env = backend["environment"]
|
||||
assert "AI_PROVIDER_SERVICE_URL" in backend_env
|
||||
assert "AI_PROVIDER_BASE_URL" not in backend_env
|
||||
assert "ports" not in backend
|
||||
assert "8000" in [str(item) for item in backend.get("expose", [])]
|
||||
assert "/health/ready" in " ".join(backend["healthcheck"]["test"])
|
||||
|
||||
volume_targets = {str(item).split(":", 1)[1] for item in backend.get("volumes", [])}
|
||||
assert "/app/backend/data/earth-brand" in volume_targets
|
||||
assert "/root/.cache/planet/downloads" in volume_targets
|
||||
|
||||
admin = services["admin"]
|
||||
assert "full" in str(admin["build"]["args"]["PLANET_FRONTEND_TARGET"])
|
||||
|
||||
worker = services["worker"]
|
||||
assert "split" in worker.get("profiles", [])
|
||||
assert worker["environment"]["PLANET_ROLE"] == "worker"
|
||||
|
||||
for name, service in services.items():
|
||||
assert service.get("logging", {}).get("driver") == "json-file", name
|
||||
assert "mem_limit" in service, name
|
||||
|
||||
|
||||
def test_helm_templates_and_values_fix_ai_provider_and_probes():
|
||||
configmap_text = (
|
||||
REPO_ROOT / "deploy/helm/planet/templates/configmap.yaml"
|
||||
).read_text(encoding="utf-8")
|
||||
assert "AI_PROVIDER_SERVICE_URL" in configmap_text
|
||||
assert "AI_BASE_URL:" not in configmap_text
|
||||
assert "AI_PROVIDER_API:" not in configmap_text
|
||||
|
||||
backend_yaml_text = (
|
||||
REPO_ROOT / "deploy/helm/planet/templates/backend.yaml"
|
||||
).read_text(encoding="utf-8")
|
||||
assert "/health/ready" in backend_yaml_text
|
||||
assert "/health/live" in backend_yaml_text
|
||||
assert "startupProbe:" in backend_yaml_text
|
||||
|
||||
worker_yaml_text = (
|
||||
REPO_ROOT / "deploy/helm/planet/templates/worker.yaml"
|
||||
).read_text(encoding="utf-8")
|
||||
assert ".Values.worker.enabled" in worker_yaml_text
|
||||
assert "app.worker" in worker_yaml_text
|
||||
|
||||
values = yaml.safe_load(
|
||||
(REPO_ROOT / "deploy/helm/planet/values.yaml").read_text(encoding="utf-8")
|
||||
)
|
||||
assert values["backend"]["env"]["APP_ENV"] == "production"
|
||||
assert "limits" in values["backend"]["resources"]
|
||||
assert "limits" in values["frontend"]["resources"]
|
||||
assert "limits" in values["aiprovider"]["resources"]
|
||||
|
||||
|
||||
def test_nginx_template_sets_timeouts_streaming_and_upload_limits():
|
||||
nginx_text = (REPO_ROOT / "frontend/nginx.conf.template").read_text(encoding="utf-8")
|
||||
assert "client_max_body_size 25m;" in nginx_text
|
||||
assert "proxy_read_timeout 180s;" in nginx_text
|
||||
assert "proxy_buffering off;" in nginx_text
|
||||
assert "proxy_read_timeout 3600s;" in nginx_text
|
||||
assert "/api/health/ready" in nginx_text
|
||||
assert "/api/health/live" in nginx_text
|
||||
assert "X-Content-Type-Options" in nginx_text
|
||||
|
||||
|
||||
def test_validate_production_security_enforces_strong_defaults(monkeypatch):
|
||||
weak_cfg = Settings(
|
||||
APP_ENV="production",
|
||||
SECRET_KEY="short-secret",
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES=0,
|
||||
REFRESH_TOKEN_EXPIRE_DAYS=0,
|
||||
CORS_ORIGINS=["*"],
|
||||
AI_PROVIDER_SERVICE_URL="http://aiprovider:8010",
|
||||
AI_PROVIDER_SERVICE_TOKEN="",
|
||||
)
|
||||
with pytest.raises(RuntimeError, match="Production security validation failed"):
|
||||
validate_production_security(weak_cfg)
|
||||
|
||||
strong_cfg = Settings(
|
||||
APP_ENV="production",
|
||||
SECRET_KEY="x" * 40,
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES=60,
|
||||
REFRESH_TOKEN_EXPIRE_DAYS=7,
|
||||
CORS_ORIGINS=["https://planet.example.com"],
|
||||
AI_PROVIDER_SERVICE_URL="http://aiprovider:8010",
|
||||
AI_PROVIDER_SERVICE_TOKEN="internal-token-123456",
|
||||
)
|
||||
validate_production_security(strong_cfg)
|
||||
|
||||
from aiprovider import main as aiprovider_main
|
||||
|
||||
monkeypatch.setattr(aiprovider_main.settings, "APP_ENV", "production")
|
||||
monkeypatch.setattr(aiprovider_main.settings, "AI_PROVIDER_SERVICE_TOKEN", "")
|
||||
with pytest.raises(RuntimeError, match="AI_PROVIDER_SERVICE_TOKEN"):
|
||||
aiprovider_main.validate_provider_security()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_secret_crypto_roundtrip_and_database_storage(monkeypatch):
|
||||
monkeypatch.setattr(settings, "SETTINGS_ENCRYPTION_KEY", "test-master-passphrase-2026")
|
||||
engine = create_engine("sqlite://")
|
||||
SystemSetting.__table__.create(engine)
|
||||
|
||||
with Session(engine) as sync_session:
|
||||
db = _AsyncSQLiteSession(sync_session)
|
||||
await settings_api.save_setting_payload(
|
||||
db,
|
||||
"smtp",
|
||||
{"host": "smtp.example.com", "port": 587, "password": "smtp-secret-value"},
|
||||
)
|
||||
raw_record = sync_session.execute(
|
||||
select(SystemSetting).where(SystemSetting.category == "smtp")
|
||||
).scalar_one()
|
||||
assert raw_record.payload["password"].startswith(secret_crypto.ENCRYPTED_PREFIX)
|
||||
|
||||
loaded = await settings_api.get_setting_payload(db, "smtp")
|
||||
assert loaded["password"] == "smtp-secret-value"
|
||||
|
||||
legacy_decrypted = secret_crypto.decrypt_setting_payload(
|
||||
"smtp", {"host": "smtp.example.com", "password": "legacy-plaintext"}
|
||||
)
|
||||
assert legacy_decrypted["password"] == "legacy-plaintext"
|
||||
|
||||
engine.dispose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_auth_refresh_logout_revocation_rate_limit_and_redis_fallback(monkeypatch):
|
||||
security._LOCAL_REVOKED_TOKENS.clear()
|
||||
_LOCAL_LOGIN_FAILURES.clear()
|
||||
|
||||
class BrokenRedis:
|
||||
async def exists(self, *_args):
|
||||
raise ConnectionError("redis down")
|
||||
|
||||
async def sismember(self, *_args):
|
||||
raise ConnectionError("redis down")
|
||||
|
||||
async def set(self, *_args, **_kwargs):
|
||||
raise ConnectionError("redis down")
|
||||
|
||||
async def get(self, *_args):
|
||||
raise ConnectionError("redis down")
|
||||
|
||||
async def incr(self, *_args):
|
||||
raise ConnectionError("redis down")
|
||||
|
||||
async def delete(self, *_args):
|
||||
raise ConnectionError("redis down")
|
||||
|
||||
monkeypatch.setattr(
|
||||
security._AsyncRedisClient, "get_client", classmethod(lambda cls: BrokenRedis())
|
||||
)
|
||||
monkeypatch.setattr(settings, "LOGIN_RATE_LIMIT_MAX_ATTEMPTS", 2)
|
||||
monkeypatch.setattr(settings, "LOGIN_RATE_LIMIT_WINDOW_SECONDS", 60)
|
||||
|
||||
engine = create_engine("sqlite://")
|
||||
User.__table__.create(engine)
|
||||
with Session(engine) as seed_session:
|
||||
seed_session.add(
|
||||
User(
|
||||
username="ops_user",
|
||||
email="ops@example.com",
|
||||
password_hash=security.get_password_hash("CorrectPass123!"),
|
||||
role="admin",
|
||||
is_active=True,
|
||||
email_verified=True,
|
||||
)
|
||||
)
|
||||
seed_session.commit()
|
||||
|
||||
test_app = FastAPI()
|
||||
test_app.include_router(auth_router, prefix="/auth")
|
||||
|
||||
async def override_db():
|
||||
with Session(engine) as sync_session:
|
||||
yield _AsyncSQLiteSession(sync_session)
|
||||
|
||||
test_app.dependency_overrides[get_db] = override_db
|
||||
|
||||
async with AsyncClient(transport=ASGITransport(app=test_app), base_url="http://test") as client:
|
||||
for _ in range(2):
|
||||
fail_resp = await client.post(
|
||||
"/auth/login", data={"username": "ops_user", "password": "wrong"}
|
||||
)
|
||||
assert fail_resp.status_code == 401
|
||||
blocked_resp = await client.post(
|
||||
"/auth/login", data={"username": "ops_user", "password": "CorrectPass123!"}
|
||||
)
|
||||
assert blocked_resp.status_code == 429
|
||||
assert int(blocked_resp.headers["Retry-After"]) >= 1
|
||||
|
||||
_LOCAL_LOGIN_FAILURES.clear()
|
||||
login_resp = await client.post(
|
||||
"/auth/login", data={"username": "ops_user", "password": "CorrectPass123!"}
|
||||
)
|
||||
assert login_resp.status_code == 200
|
||||
tokens = login_resp.json()
|
||||
access_token = tokens["access_token"]
|
||||
refresh_token = tokens["refresh_token"]
|
||||
|
||||
me_resp = await client.get("/auth/me", headers={"Authorization": f"Bearer {access_token}"})
|
||||
assert me_resp.status_code == 200
|
||||
|
||||
bad_refresh = await client.post(
|
||||
"/auth/refresh", headers={"Authorization": f"Bearer {access_token}"}
|
||||
)
|
||||
assert bad_refresh.status_code == 401
|
||||
|
||||
ok_refresh = await client.post(
|
||||
"/auth/refresh", headers={"Authorization": f"Bearer {refresh_token}"}
|
||||
)
|
||||
assert ok_refresh.status_code == 200
|
||||
new_access = ok_refresh.json()["access_token"]
|
||||
assert new_access != access_token
|
||||
|
||||
logout_resp = await client.post(
|
||||
"/auth/logout",
|
||||
headers={"Authorization": f"Bearer {new_access}"},
|
||||
json={"refresh_token": refresh_token},
|
||||
)
|
||||
assert logout_resp.status_code == 200
|
||||
|
||||
revoked_me = await client.get("/auth/me", headers={"Authorization": f"Bearer {new_access}"})
|
||||
assert revoked_me.status_code == 401
|
||||
|
||||
revoked_refresh = await client.post(
|
||||
"/auth/refresh", headers={"Authorization": f"Bearer {refresh_token}"}
|
||||
)
|
||||
assert revoked_refresh.status_code == 401
|
||||
|
||||
security._LOCAL_REVOKED_TOKENS.clear()
|
||||
_LOCAL_LOGIN_FAILURES.clear()
|
||||
engine.dispose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_seeding_preserves_custom_datasource_schedule_and_production_admin(monkeypatch):
|
||||
engine = create_engine("sqlite://")
|
||||
DataSource.__table__.create(engine)
|
||||
User.__table__.create(engine)
|
||||
|
||||
with Session(engine) as sync_session:
|
||||
db = _AsyncSQLiteSession(sync_session)
|
||||
await seed_default_datasources(db)
|
||||
first = sync_session.execute(select(DataSource).limit(1)).scalar_one()
|
||||
first.frequency_minutes = 777
|
||||
first.priority = "P9"
|
||||
first.is_active = False
|
||||
sync_session.commit()
|
||||
|
||||
await seed_default_datasources(db)
|
||||
reloaded = sync_session.get(DataSource, first.id)
|
||||
assert reloaded.frequency_minutes == 777
|
||||
assert reloaded.priority == "P9"
|
||||
assert reloaded.is_active is False
|
||||
|
||||
monkeypatch.setattr(settings, "APP_ENV", "production")
|
||||
monkeypatch.setattr(settings, "SEED_DEFAULT_DEV_USERS", None)
|
||||
monkeypatch.setattr(settings, "INITIAL_ADMIN_USERNAME", "prod_root")
|
||||
monkeypatch.setattr(settings, "INITIAL_ADMIN_PASSWORD", "ProdStrongPass!123")
|
||||
monkeypatch.setattr(settings, "INITIAL_ADMIN_EMAIL", "root@planet.example.com")
|
||||
|
||||
await ensure_default_admin_user(db)
|
||||
usernames = {row[0] for row in sync_session.execute(select(User.username)).all()}
|
||||
assert usernames == {"prod_root"}
|
||||
|
||||
engine.dispose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_scheduler_jobs_requires_auth_and_health_ready_checks_deps(monkeypatch):
|
||||
async with AsyncClient(transport=ASGITransport(app=main_app), base_url="http://test") as client:
|
||||
unauth_jobs = await client.get("/api/v1/scheduler/jobs")
|
||||
assert unauth_jobs.status_code in {401, 403}
|
||||
|
||||
live_resp = await client.get("/health/live")
|
||||
assert live_resp.status_code == 200
|
||||
assert live_resp.json()["status"] == "alive"
|
||||
|
||||
class HealthySession:
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *_args):
|
||||
return False
|
||||
|
||||
async def execute(self, *_args):
|
||||
return None
|
||||
|
||||
class HealthyRedis:
|
||||
async def ping(self):
|
||||
return True
|
||||
|
||||
monkeypatch.setattr("app.main.async_session_factory", HealthySession)
|
||||
monkeypatch.setattr(
|
||||
security._AsyncRedisClient, "get_client", classmethod(lambda cls: HealthyRedis())
|
||||
)
|
||||
|
||||
async with AsyncClient(transport=ASGITransport(app=main_app), base_url="http://test") as client:
|
||||
ready_ok = await client.get("/health/ready")
|
||||
assert ready_ok.status_code == 200
|
||||
assert ready_ok.json()["checks"] == {"database": "ok", "redis": "ok"}
|
||||
|
||||
class FailingRedis:
|
||||
async def ping(self):
|
||||
raise ConnectionError("down")
|
||||
|
||||
monkeypatch.setattr(
|
||||
security._AsyncRedisClient, "get_client", classmethod(lambda cls: FailingRedis())
|
||||
)
|
||||
async with AsyncClient(transport=ASGITransport(app=main_app), base_url="http://test") as client:
|
||||
ready_fail = await client.get("/health/ready")
|
||||
assert ready_fail.status_code == 503
|
||||
assert ready_fail.json()["checks"]["redis"] == "error"
|
||||
|
||||
|
||||
def test_backend_dockerfile_and_dockerignore_ship_db_migrate():
|
||||
dockerfile = (REPO_ROOT / "backend/Dockerfile").read_text(encoding="utf-8")
|
||||
dockerignore = (REPO_ROOT / ".dockerignore").read_text(encoding="utf-8")
|
||||
assert "COPY scripts/db_migrate.py /app/scripts/db_migrate.py" in dockerfile
|
||||
assert "!scripts/db_migrate.py" in dockerignore
|
||||
|
||||
|
||||
def test_planet_sh_deploy_backup_migrate_cli_and_env_generation(tmp_path: Path):
|
||||
if shutil.which("zsh") is None:
|
||||
pytest.skip("zsh not available")
|
||||
|
||||
for subcmd in ("deploy", "backup", "migrate"):
|
||||
res = subprocess.run(
|
||||
["zsh", str(REPO_ROOT / "planet.sh"), subcmd, "--help"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=15,
|
||||
check=False,
|
||||
)
|
||||
assert res.returncode == 0, res.stderr
|
||||
|
||||
env_path = tmp_path / ".env.deploy"
|
||||
zsh_script = "\n".join(
|
||||
[
|
||||
"set -e",
|
||||
f"SCRIPT_DIR={shlex.quote(str(REPO_ROOT))}",
|
||||
"log_step() { :; }",
|
||||
"log_warn() { :; }",
|
||||
"log_error() { echo \"$1\" >&2; }",
|
||||
"log_success() { :; }",
|
||||
"log_note() { :; }",
|
||||
f"source {shlex.quote(str(REPO_ROOT / 'scripts/lib/deploy.zsh'))}",
|
||||
f"deploy_init_env {shlex.quote(str(env_path))} 0 < /dev/null",
|
||||
f"deploy_validate_env_file {shlex.quote(str(env_path))}",
|
||||
]
|
||||
)
|
||||
gen = subprocess.run(
|
||||
["zsh", "-f"],
|
||||
input=zsh_script,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=15,
|
||||
check=False,
|
||||
env={**os.environ, "INITIAL_ADMIN_PASSWORD": "StrongProdPassword!1"},
|
||||
)
|
||||
assert gen.returncode == 0, gen.stderr
|
||||
assert env_path.exists()
|
||||
assert stat.S_IMODE(env_path.stat().st_mode) == 0o600
|
||||
|
||||
parsed = {}
|
||||
for line in env_path.read_text(encoding="utf-8").splitlines():
|
||||
if line and not line.startswith("#") and "=" in line:
|
||||
k, v = line.split("=", 1)
|
||||
parsed[k] = v
|
||||
|
||||
assert parsed["APP_ENV"] == "production"
|
||||
assert len(parsed["SECRET_KEY"]) >= 32
|
||||
assert parsed["INITIAL_ADMIN_PASSWORD"] == "StrongProdPassword!1"
|
||||
Fernet(parsed["SETTINGS_ENCRYPTION_KEY"].encode("ascii"))
|
||||
|
||||
# Generated file must pass Pydantic Settings + validate_production_security directly.
|
||||
loaded_cfg = Settings(_env_file=env_path)
|
||||
validate_production_security(loaded_cfg)
|
||||
|
||||
# Weak placeholder file must fail deploy_validate_env_file.
|
||||
weak_path = tmp_path / ".env.weak"
|
||||
weak_path.write_text(
|
||||
"APP_ENV=production\nSECRET_KEY=short\nAI_PROVIDER_SERVICE_TOKEN=change_me\nCORS_ORIGINS=[\"*\"]\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
weak_check = subprocess.run(
|
||||
["zsh", "-f"],
|
||||
input="\n".join(
|
||||
[
|
||||
f"SCRIPT_DIR={shlex.quote(str(REPO_ROOT))}",
|
||||
"log_error() { echo \"$1\" >&2; }",
|
||||
f"source {shlex.quote(str(REPO_ROOT / 'scripts/lib/deploy.zsh'))}",
|
||||
f"deploy_validate_env_file {shlex.quote(str(weak_path))}",
|
||||
]
|
||||
),
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=15,
|
||||
check=False,
|
||||
)
|
||||
assert weak_check.returncode != 0
|
||||
|
||||
|
||||
def test_planet_sh_dev_cors_builder_includes_electron_and_lan_origins():
|
||||
if shutil.which("zsh") is None:
|
||||
pytest.skip("zsh not available")
|
||||
|
||||
planet_text = (REPO_ROOT / "planet.sh").read_text(encoding="utf-8")
|
||||
start = planet_text.index("build_dev_cors_origins_json() {")
|
||||
end = planet_text.index("\nstart_backend_with_retry()", start)
|
||||
fn_code = planet_text[start:end]
|
||||
|
||||
res = subprocess.run(
|
||||
["zsh", "-f"],
|
||||
input="\n".join(
|
||||
[
|
||||
"set -e",
|
||||
fn_code,
|
||||
"FRONTEND_LAN_ENABLED=1",
|
||||
"get_recommended_lan_ipv4() { echo 192.168.10.25; }",
|
||||
"build_dev_cors_origins_json 8000 3000 3000",
|
||||
]
|
||||
),
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=10,
|
||||
check=False,
|
||||
)
|
||||
assert res.returncode == 0, res.stderr
|
||||
origins = json.loads(res.stdout.strip())
|
||||
assert "http://localhost:3000" in origins
|
||||
assert "http://127.0.0.1:3000" in origins
|
||||
assert "planet://earth" in origins
|
||||
assert "http://192.168.10.25:3000" in origins
|
||||
assert "http://192.168.10.25:8000" in origins
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_client_ip_trusts_only_private_proxy_rightmost_hop_and_forged_logout_ignored(
|
||||
monkeypatch,
|
||||
):
|
||||
from types import SimpleNamespace
|
||||
|
||||
# Trusted proxy peer uses X-Real-IP, or rightmost X-Forwarded-For entry appended by nginx.
|
||||
trusted_real_req = SimpleNamespace(
|
||||
client=SimpleNamespace(host="172.18.0.5"),
|
||||
headers={"X-Real-IP": "198.51.100.42", "X-Forwarded-For": "9.9.9.9, 198.51.100.42"},
|
||||
)
|
||||
assert _client_ip(trusted_real_req) == "198.51.100.42"
|
||||
|
||||
trusted_xff_req = SimpleNamespace(
|
||||
client=SimpleNamespace(host="127.0.0.1"),
|
||||
headers={"X-Forwarded-For": "9.9.9.9, 203.0.113.88"},
|
||||
)
|
||||
assert _client_ip(trusted_xff_req) == "203.0.113.88"
|
||||
|
||||
# Untrusted direct public peer cannot spoof rate-limit keys via headers.
|
||||
untrusted_req = SimpleNamespace(
|
||||
client=SimpleNamespace(host="203.0.113.55"),
|
||||
headers={"X-Real-IP": "1.1.1.1", "X-Forwarded-For": "8.8.8.8"},
|
||||
)
|
||||
assert _client_ip(untrusted_req) == "203.0.113.55"
|
||||
|
||||
# Forged / invalid JWT passed to revoke_token must not pollute local revocation cache or Redis.
|
||||
security._LOCAL_REVOKED_TOKENS.clear()
|
||||
redis_sets: list[str] = []
|
||||
|
||||
class RecordingRedis:
|
||||
async def set(self, key, *_args, **_kwargs):
|
||||
redis_sets.append(key)
|
||||
|
||||
monkeypatch.setattr(
|
||||
security._AsyncRedisClient, "get_client", classmethod(lambda cls: RecordingRedis())
|
||||
)
|
||||
await security.revoke_token("not-a-valid-jwt-token")
|
||||
security.blacklist_token("also-invalid-token")
|
||||
assert len(security._LOCAL_REVOKED_TOKENS) == 0
|
||||
assert redis_sets == []
|
||||
|
||||
|
||||
def test_helm_backend_deployment_sets_api_role_when_worker_enabled():
|
||||
backend_yaml_text = (
|
||||
REPO_ROOT / "deploy/helm/planet/templates/backend.yaml"
|
||||
).read_text(encoding="utf-8")
|
||||
assert "{{- if .Values.worker.enabled }}" in backend_yaml_text
|
||||
assert 'name: PLANET_ROLE' in backend_yaml_text
|
||||
assert 'value: "api"' in backend_yaml_text
|
||||
File diff suppressed because it is too large.
Load diff
@@ -3,6 +3,10 @@ productName: Planet Earth
|
||||
copyright: Copyright © 2026 Linkong Intelligent Media Lab
|
||||
npmRebuild: false
|
||||
asar: true
|
||||
protocols:
|
||||
- name: Open Planet Earth
|
||||
schemes:
|
||||
- planet-earth
|
||||
afterPack: ./scripts/after-pack.cjs
|
||||
|
||||
directories:
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "planet-client",
|
||||
"version": "0.77.0",
|
||||
"version": "0.79.1",
|
||||
"description": "Intelligent Planet Program - Native Electron Earth Viewer",
|
||||
"private": true,
|
||||
"packageManager": "bun@1",
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { cpSync, existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { createHash } from 'node:crypto'
|
||||
import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { createRequire } from 'node:module'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
import { compileEarthRuntime } from '../../frontend/scripts/compile-earth-runtime.mjs'
|
||||
import { createTarGz } from '../src/main/tar-gz.ts'
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url))
|
||||
const desktopRoot = join(__dirname, '..')
|
||||
@@ -100,3 +102,50 @@ if (existsSync(mediaPipeWasmDir)) {
|
||||
}
|
||||
|
||||
console.log(`Built offline Earth bundle at ${bundleEarthDir}`)
|
||||
|
||||
const clientPkg = JSON.parse(readFileSync(join(desktopRoot, 'package.json'), 'utf8'))
|
||||
const bundleVersion = String(clientPkg.version || '0.0.0').trim()
|
||||
const metaPayload = {
|
||||
version: bundleVersion,
|
||||
shellVersion: bundleVersion,
|
||||
builtAt: new Date().toISOString(),
|
||||
}
|
||||
writeFileSync(join(bundleEarthDir, 'bundle-meta.json'), `${JSON.stringify(metaPayload, null, 2)}\n`, 'utf8')
|
||||
|
||||
function collectHotfixEntries(rootDir) {
|
||||
const entries = []
|
||||
for (const topFile of ['index.html', 'bundle-meta.json']) {
|
||||
const filePath = join(rootDir, topFile)
|
||||
if (existsSync(filePath)) {
|
||||
entries.push({ path: topFile, data: readFileSync(filePath) })
|
||||
}
|
||||
}
|
||||
const walk = (relDir) => {
|
||||
const absDir = join(rootDir, relDir)
|
||||
if (!existsSync(absDir)) return
|
||||
for (const dirent of readdirSync(absDir, { withFileTypes: true })) {
|
||||
const relPath = `${relDir}/${dirent.name}`
|
||||
if (dirent.isDirectory()) {
|
||||
walk(relPath)
|
||||
} else if (dirent.isFile()) {
|
||||
entries.push({ path: relPath, data: readFileSync(join(rootDir, relPath)) })
|
||||
}
|
||||
}
|
||||
}
|
||||
walk('js')
|
||||
walk('css')
|
||||
return entries
|
||||
}
|
||||
|
||||
const hotfixEntries = collectHotfixEntries(bundleEarthDir)
|
||||
const hotfixArchive = createTarGz(hotfixEntries)
|
||||
const hotfixSha256 = createHash('sha256').update(hotfixArchive).digest('hex')
|
||||
const releaseOutDir = join(desktopRoot, 'release')
|
||||
mkdirSync(releaseOutDir, { recursive: true })
|
||||
const hotfixName = `planet-earth-bundle-${bundleVersion}.tar.gz`
|
||||
const hotfixPath = join(releaseOutDir, hotfixName)
|
||||
writeFileSync(hotfixPath, hotfixArchive)
|
||||
writeFileSync(join(releaseOutDir, `${hotfixName}.sha256`), `${hotfixSha256} ${hotfixName}\n`, 'utf8')
|
||||
console.log(
|
||||
`Built L1 hotfix bundle ${hotfixPath} (${(hotfixArchive.byteLength / 1024).toFixed(1)} KiB, sha256=${hotfixSha256})`,
|
||||
)
|
||||
+147
-20
@@ -1,7 +1,8 @@
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
|
||||
export type SplashTheme = 'singularity' | 'constellation' | 'horizon' | 'off'
|
||||
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,18 +40,23 @@ 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 VALID_SPLASH_THEMES: ReadonlySet<SplashTheme> = new Set([
|
||||
const LEGACY_ACTIVE_THEMES: ReadonlySet<string> = new Set([
|
||||
'singularity',
|
||||
'constellation',
|
||||
'horizon',
|
||||
'off',
|
||||
'on',
|
||||
'default',
|
||||
])
|
||||
|
||||
export function normalizeSplashTheme(
|
||||
@@ -41,13 +64,43 @@ export function normalizeSplashTheme(
|
||||
fallback: SplashTheme = 'singularity',
|
||||
): SplashTheme {
|
||||
if (typeof raw !== 'string') return fallback
|
||||
const normalized = raw.trim().toLowerCase() as SplashTheme
|
||||
return VALID_SPLASH_THEMES.has(normalized) ? normalized : fallback
|
||||
const normalized = raw.trim().toLowerCase()
|
||||
if (normalized === 'off') return 'off'
|
||||
return LEGACY_ACTIVE_THEMES.has(normalized) ? 'singularity' : fallback
|
||||
}
|
||||
|
||||
const DEFAULT_ENDPOINTS: ServerEndpoints = {
|
||||
backendUrl: 'http://127.0.0.1:8000',
|
||||
adminUrl: 'http://127.0.0.1:3000',
|
||||
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',
|
||||
motionWsUrl: 'ws://127.0.0.1:8765/ws/gestures',
|
||||
}
|
||||
|
||||
@@ -113,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) {
|
||||
@@ -134,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') {
|
||||
@@ -155,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[]
|
||||
@@ -170,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
|
||||
@@ -182,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,
|
||||
@@ -210,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,
|
||||
@@ -217,6 +333,7 @@ export class DesktopConfigStore {
|
||||
motionWsUrl,
|
||||
wsUrl: deriveBackendWsUrl(backendUrl),
|
||||
splashTheme,
|
||||
gpuMode,
|
||||
...this.launchFlags,
|
||||
}
|
||||
}
|
||||
@@ -258,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,57 @@
|
||||
import { execFile } from 'node:child_process'
|
||||
import { mkdir, writeFile } from 'node:fs/promises'
|
||||
import { homedir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { promisify } from 'node:util'
|
||||
|
||||
import { app } from 'electron'
|
||||
|
||||
const run = promisify(execFile)
|
||||
export const DESKTOP_SCHEME = 'planet-earth'
|
||||
|
||||
export async function registerDesktopLink(): Promise<void> {
|
||||
if (!app.isPackaged) return
|
||||
|
||||
if (process.platform === 'linux') {
|
||||
let desktopId = 'planet-client.desktop'
|
||||
if (process.env.APPIMAGE) {
|
||||
desktopId = 'planet-earth-appimage.desktop'
|
||||
const applications = path.join(
|
||||
process.env.XDG_DATA_HOME || path.join(homedir(), '.local', 'share'),
|
||||
'applications',
|
||||
)
|
||||
const executable = process.env.APPIMAGE
|
||||
if (!path.isAbsolute(executable) || /[\r\n]/.test(executable)) {
|
||||
throw new Error('Invalid AppImage path')
|
||||
}
|
||||
// Escape the Exec argument, then the backslashes in the desktop-entry value.
|
||||
const escaped = executable.replace(/%/g, '%%').replace(/["$\x60\\]/g, '\\$&').replace(/\\/g, '\\\\')
|
||||
await mkdir(applications, { recursive: true })
|
||||
await writeFile(path.join(applications, desktopId), [
|
||||
'[Desktop Entry]',
|
||||
'Type=Application',
|
||||
'Name=Planet Earth',
|
||||
'NoDisplay=true',
|
||||
'Exec="' + escaped + '" %u',
|
||||
'MimeType=x-scheme-handler/' + DESKTOP_SCHEME + ';',
|
||||
'',
|
||||
].join('\n'))
|
||||
}
|
||||
const mimeType = 'x-scheme-handler/' + DESKTOP_SCHEME
|
||||
try {
|
||||
await run('xdg-mime', ['default', desktopId, mimeType], { timeout: 8000 })
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
|
||||
await run('gio', ['mime', mimeType, desktopId], { timeout: 8000 })
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
const executable = process.platform === 'win32'
|
||||
? process.env.PORTABLE_EXECUTABLE_FILE || process.execPath
|
||||
: undefined
|
||||
if (!app.isDefaultProtocolClient(DESKTOP_SCHEME, executable)
|
||||
&& !app.setAsDefaultProtocolClient(DESKTOP_SCHEME, executable)) {
|
||||
throw new Error('Could not register the Planet Earth URL handler')
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
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
|
||||
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[] {
|
||||
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' },
|
||||
{ name: 'use-angle', value: 'swiftshader' },
|
||||
{ name: 'enable-unsafe-swiftshader' },
|
||||
]
|
||||
}
|
||||
|
||||
// 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[] = []
|
||||
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 {
|
||||
return Boolean(details && details.type === 'GPU' && details.reason !== 'clean-exit')
|
||||
}
|
||||
@@ -0,0 +1,504 @@
|
||||
import crypto from 'node:crypto'
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
|
||||
import { extractTarGzSafely } from './tar-gz'
|
||||
|
||||
export interface ClientShellUpdateInfo {
|
||||
version: string
|
||||
minRequired?: string | null
|
||||
downloadUrl: string
|
||||
releaseNotes?: string | null
|
||||
}
|
||||
|
||||
export interface ClientBundleUpdateInfo {
|
||||
version: string
|
||||
minShellVersion: string
|
||||
url: string
|
||||
sha256: string
|
||||
size?: number
|
||||
releaseNotes?: string | null
|
||||
}
|
||||
|
||||
export interface ClientUpdateManifest {
|
||||
shell?: ClientShellUpdateInfo | null
|
||||
bundle?: ClientBundleUpdateInfo | null
|
||||
}
|
||||
|
||||
export interface HotfixState {
|
||||
activeVersion: string | null
|
||||
previousVerifiedVersion: string | null
|
||||
status: 'verified' | 'pending'
|
||||
pendingAttempts: number
|
||||
blacklistedVersions: string[]
|
||||
installedAt?: string
|
||||
}
|
||||
|
||||
export interface ActiveOverlayResolution {
|
||||
overlayRoot: string | null
|
||||
activeBundleVersion: string
|
||||
pendingVerification: boolean
|
||||
rolledBackFrom: string | null
|
||||
}
|
||||
|
||||
export type UpdateDecision =
|
||||
| { kind: 'up-to-date' }
|
||||
| { kind: 'hotfix-update'; bundle: ClientBundleUpdateInfo }
|
||||
| { kind: 'shell-update'; shell: ClientShellUpdateInfo; mandatory: boolean }
|
||||
|
||||
const SEMVER_PATTERN = /^[vV]?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/
|
||||
const STRICT_VERSION_PATTERN = /^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][0-9A-Za-z.-]+)?$/
|
||||
const SHA256_PATTERN = /^[0-9a-f]{64}$/i
|
||||
const MAX_PENDING_ATTEMPTS = 2
|
||||
|
||||
interface ParsedSemver {
|
||||
major: number
|
||||
minor: number
|
||||
patch: number
|
||||
prerelease: string[]
|
||||
}
|
||||
|
||||
function parseSemver(raw: string): ParsedSemver | null {
|
||||
const match = SEMVER_PATTERN.exec(String(raw || '').trim())
|
||||
if (!match) return null
|
||||
return {
|
||||
major: Number(match[1] ?? 0),
|
||||
minor: Number(match[2] ?? 0),
|
||||
patch: Number(match[3] ?? 0),
|
||||
prerelease: match[4] ? match[4].split('.') : [],
|
||||
}
|
||||
}
|
||||
|
||||
export function compareSemver(a: string, b: string): number {
|
||||
const pa = parseSemver(a)
|
||||
const pb = parseSemver(b)
|
||||
if (!pa || !pb) {
|
||||
return String(a).localeCompare(String(b))
|
||||
}
|
||||
for (const [va, vb] of [
|
||||
[pa.major, pb.major],
|
||||
[pa.minor, pb.minor],
|
||||
[pa.patch, pb.patch],
|
||||
]) {
|
||||
if (va !== vb) return va > vb ? 1 : -1
|
||||
}
|
||||
if (pa.prerelease.length === 0 && pb.prerelease.length === 0) return 0
|
||||
if (pa.prerelease.length === 0) return 1
|
||||
if (pb.prerelease.length === 0) return -1
|
||||
|
||||
const maxLen = Math.max(pa.prerelease.length, pb.prerelease.length)
|
||||
for (let i = 0; i < maxLen; i += 1) {
|
||||
const ia = pa.prerelease[i]
|
||||
const ib = pb.prerelease[i]
|
||||
if (ia === undefined) return -1
|
||||
if (ib === undefined) return 1
|
||||
const na = /^\d+$/.test(ia) ? Number(ia) : null
|
||||
const nb = /^\d+$/.test(ib) ? Number(ib) : null
|
||||
if (na !== null && nb !== null) {
|
||||
if (na !== nb) return na > nb ? 1 : -1
|
||||
} else if (na !== null) {
|
||||
return -1
|
||||
} else if (nb !== null) {
|
||||
return 1
|
||||
} else if (ia !== ib) {
|
||||
return ia > ib ? 1 : -1
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
export function getHotfixRootDir(userDataDir: string): string {
|
||||
return path.join(userDataDir, 'earth-hotfix')
|
||||
}
|
||||
|
||||
export function getHotfixBundlesDir(userDataDir: string): string {
|
||||
return path.join(getHotfixRootDir(userDataDir), 'bundles')
|
||||
}
|
||||
|
||||
export function getHotfixBundleDir(userDataDir: string, version: string): string {
|
||||
return path.join(getHotfixBundlesDir(userDataDir), version)
|
||||
}
|
||||
|
||||
function getHotfixStatePath(userDataDir: string): string {
|
||||
return path.join(getHotfixRootDir(userDataDir), 'state.json')
|
||||
}
|
||||
|
||||
function defaultHotfixState(): HotfixState {
|
||||
return {
|
||||
activeVersion: null,
|
||||
previousVerifiedVersion: null,
|
||||
status: 'verified',
|
||||
pendingAttempts: 0,
|
||||
blacklistedVersions: [],
|
||||
}
|
||||
}
|
||||
|
||||
export function readHotfixState(userDataDir: string): HotfixState {
|
||||
const statePath = getHotfixStatePath(userDataDir)
|
||||
try {
|
||||
if (!fs.existsSync(statePath)) return defaultHotfixState()
|
||||
const raw = JSON.parse(fs.readFileSync(statePath, 'utf8')) as Partial<HotfixState>
|
||||
return {
|
||||
activeVersion: typeof raw.activeVersion === 'string' && STRICT_VERSION_PATTERN.test(raw.activeVersion)
|
||||
? raw.activeVersion
|
||||
: null,
|
||||
previousVerifiedVersion: typeof raw.previousVerifiedVersion === 'string' && STRICT_VERSION_PATTERN.test(raw.previousVerifiedVersion)
|
||||
? raw.previousVerifiedVersion
|
||||
: null,
|
||||
status: raw.status === 'pending' ? 'pending' : 'verified',
|
||||
pendingAttempts: Number.isInteger(raw.pendingAttempts) && Number(raw.pendingAttempts) >= 0
|
||||
? Number(raw.pendingAttempts)
|
||||
: 0,
|
||||
blacklistedVersions: Array.isArray(raw.blacklistedVersions)
|
||||
? raw.blacklistedVersions.filter((item): item is string => typeof item === 'string' && STRICT_VERSION_PATTERN.test(item))
|
||||
: [],
|
||||
installedAt: typeof raw.installedAt === 'string' ? raw.installedAt : undefined,
|
||||
}
|
||||
} catch {
|
||||
return defaultHotfixState()
|
||||
}
|
||||
}
|
||||
|
||||
export function writeHotfixStateAtomic(userDataDir: string, state: HotfixState): void {
|
||||
const rootDir = getHotfixRootDir(userDataDir)
|
||||
const statePath = getHotfixStatePath(userDataDir)
|
||||
const tmpPath = `${statePath}.${process.pid}.tmp`
|
||||
fs.mkdirSync(rootDir, { recursive: true })
|
||||
fs.writeFileSync(tmpPath, `${JSON.stringify(state, null, 2)}\n`, 'utf8')
|
||||
fs.renameSync(tmpPath, statePath)
|
||||
}
|
||||
|
||||
function hasValidBundleIndex(bundleDir: string): boolean {
|
||||
try {
|
||||
return fs.statSync(path.join(bundleDir, 'index.html')).isFile()
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function resolveFallbackVersion(state: HotfixState, shellVersion: string, userDataDir: string): string | null {
|
||||
const candidate = state.previousVerifiedVersion
|
||||
if (!candidate) return null
|
||||
if (candidate === state.activeVersion) return null
|
||||
if (state.blacklistedVersions.includes(candidate)) return null
|
||||
if (compareSemver(candidate, shellVersion) <= 0) return null
|
||||
if (!hasValidBundleIndex(getHotfixBundleDir(userDataDir, candidate))) return null
|
||||
return candidate
|
||||
}
|
||||
|
||||
function pruneObsoleteBundles(userDataDir: string, keepVersions: Set<string>): void {
|
||||
const bundlesDir = getHotfixBundlesDir(userDataDir)
|
||||
try {
|
||||
if (!fs.existsSync(bundlesDir)) return
|
||||
for (const entry of fs.readdirSync(bundlesDir, { withFileTypes: true })) {
|
||||
if (!entry.isDirectory()) continue
|
||||
if (keepVersions.has(entry.name)) continue
|
||||
fs.rmSync(path.join(bundlesDir, entry.name), { recursive: true, force: true })
|
||||
}
|
||||
} catch {
|
||||
// Non-fatal cleanup best-effort.
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveActiveEarthOverlay(options: {
|
||||
userDataDir: string
|
||||
shellVersion: string
|
||||
}): ActiveOverlayResolution {
|
||||
const { userDataDir, shellVersion } = options
|
||||
const state = readHotfixState(userDataDir)
|
||||
|
||||
if (!state.activeVersion || compareSemver(state.activeVersion, shellVersion) <= 0) {
|
||||
return {
|
||||
overlayRoot: null,
|
||||
activeBundleVersion: shellVersion,
|
||||
pendingVerification: false,
|
||||
rolledBackFrom: null,
|
||||
}
|
||||
}
|
||||
|
||||
const activeDir = getHotfixBundleDir(userDataDir, state.activeVersion)
|
||||
const activeUsable =
|
||||
!state.blacklistedVersions.includes(state.activeVersion) && hasValidBundleIndex(activeDir)
|
||||
|
||||
if (!activeUsable) {
|
||||
const badVersion = state.activeVersion
|
||||
const fallbackVer = resolveFallbackVersion(state, shellVersion, userDataDir)
|
||||
const nextState: HotfixState = {
|
||||
...state,
|
||||
activeVersion: fallbackVer,
|
||||
previousVerifiedVersion: fallbackVer,
|
||||
status: 'verified',
|
||||
pendingAttempts: 0,
|
||||
}
|
||||
writeHotfixStateAtomic(userDataDir, nextState)
|
||||
return {
|
||||
overlayRoot: fallbackVer ? getHotfixBundleDir(userDataDir, fallbackVer) : null,
|
||||
activeBundleVersion: fallbackVer ?? shellVersion,
|
||||
pendingVerification: false,
|
||||
rolledBackFrom: badVersion,
|
||||
}
|
||||
}
|
||||
|
||||
if (state.status === 'pending') {
|
||||
if (state.pendingAttempts >= MAX_PENDING_ATTEMPTS) {
|
||||
const rolledBackFrom = state.activeVersion
|
||||
const blacklist = state.blacklistedVersions.includes(rolledBackFrom)
|
||||
? state.blacklistedVersions
|
||||
: [...state.blacklistedVersions, rolledBackFrom]
|
||||
const fallbackVer = resolveFallbackVersion(
|
||||
{ ...state, blacklistedVersions: blacklist },
|
||||
shellVersion,
|
||||
userDataDir,
|
||||
)
|
||||
const nextState: HotfixState = {
|
||||
activeVersion: fallbackVer,
|
||||
previousVerifiedVersion: fallbackVer,
|
||||
status: 'verified',
|
||||
pendingAttempts: 0,
|
||||
blacklistedVersions: blacklist,
|
||||
}
|
||||
writeHotfixStateAtomic(userDataDir, nextState)
|
||||
fs.rmSync(activeDir, { recursive: true, force: true })
|
||||
return {
|
||||
overlayRoot: fallbackVer ? getHotfixBundleDir(userDataDir, fallbackVer) : null,
|
||||
activeBundleVersion: fallbackVer ?? shellVersion,
|
||||
pendingVerification: false,
|
||||
rolledBackFrom,
|
||||
}
|
||||
}
|
||||
|
||||
const nextState: HotfixState = {
|
||||
...state,
|
||||
pendingAttempts: state.pendingAttempts + 1,
|
||||
}
|
||||
writeHotfixStateAtomic(userDataDir, nextState)
|
||||
return {
|
||||
overlayRoot: activeDir,
|
||||
activeBundleVersion: state.activeVersion,
|
||||
pendingVerification: true,
|
||||
rolledBackFrom: null,
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
overlayRoot: activeDir,
|
||||
activeBundleVersion: state.activeVersion,
|
||||
pendingVerification: false,
|
||||
rolledBackFrom: null,
|
||||
}
|
||||
}
|
||||
|
||||
export function markHotfixVerified(userDataDir: string): HotfixState {
|
||||
const state = readHotfixState(userDataDir)
|
||||
if (!state.activeVersion) {
|
||||
return state
|
||||
}
|
||||
const nextState: HotfixState = {
|
||||
...state,
|
||||
previousVerifiedVersion: state.activeVersion,
|
||||
status: 'verified',
|
||||
pendingAttempts: 0,
|
||||
}
|
||||
writeHotfixStateAtomic(userDataDir, nextState)
|
||||
const keep = new Set<string>([state.activeVersion])
|
||||
if (nextState.previousVerifiedVersion) {
|
||||
keep.add(nextState.previousVerifiedVersion)
|
||||
}
|
||||
pruneObsoleteBundles(userDataDir, keep)
|
||||
return nextState
|
||||
}
|
||||
|
||||
export function rollbackPendingHotfix(userDataDir: string, shellVersion: string): {
|
||||
rolledBackFrom: string | null
|
||||
overlayRoot: string | null
|
||||
activeBundleVersion: string
|
||||
} {
|
||||
const state = readHotfixState(userDataDir)
|
||||
if (!state.activeVersion || state.status !== 'pending') {
|
||||
const activeDir = state.activeVersion ? getHotfixBundleDir(userDataDir, state.activeVersion) : null
|
||||
const valid = Boolean(
|
||||
activeDir &&
|
||||
state.activeVersion &&
|
||||
compareSemver(state.activeVersion, shellVersion) > 0 &&
|
||||
hasValidBundleIndex(activeDir),
|
||||
)
|
||||
return {
|
||||
rolledBackFrom: null,
|
||||
overlayRoot: valid ? activeDir : null,
|
||||
activeBundleVersion: valid && state.activeVersion ? state.activeVersion : shellVersion,
|
||||
}
|
||||
}
|
||||
|
||||
const rolledBackFrom = state.activeVersion
|
||||
const blacklist = state.blacklistedVersions.includes(rolledBackFrom)
|
||||
? state.blacklistedVersions
|
||||
: [...state.blacklistedVersions, rolledBackFrom]
|
||||
const fallbackVer = resolveFallbackVersion(
|
||||
{ ...state, blacklistedVersions: blacklist },
|
||||
shellVersion,
|
||||
userDataDir,
|
||||
)
|
||||
const nextState: HotfixState = {
|
||||
activeVersion: fallbackVer,
|
||||
previousVerifiedVersion: fallbackVer,
|
||||
status: 'verified',
|
||||
pendingAttempts: 0,
|
||||
blacklistedVersions: blacklist,
|
||||
}
|
||||
writeHotfixStateAtomic(userDataDir, nextState)
|
||||
fs.rmSync(getHotfixBundleDir(userDataDir, rolledBackFrom), { recursive: true, force: true })
|
||||
|
||||
return {
|
||||
rolledBackFrom,
|
||||
overlayRoot: fallbackVer ? getHotfixBundleDir(userDataDir, fallbackVer) : null,
|
||||
activeBundleVersion: fallbackVer ?? shellVersion,
|
||||
}
|
||||
}
|
||||
|
||||
export function evaluateUpdateDecision(input: {
|
||||
shellVersion: string
|
||||
activeBundleVersion: string
|
||||
blacklistedVersions: string[]
|
||||
manifest: ClientUpdateManifest | null | undefined
|
||||
}): UpdateDecision {
|
||||
const manifest = input.manifest
|
||||
if (!manifest || typeof manifest !== 'object') {
|
||||
return { kind: 'up-to-date' }
|
||||
}
|
||||
|
||||
const shell = manifest.shell
|
||||
const hasShellDownload = Boolean(shell?.downloadUrl && typeof shell.downloadUrl === 'string')
|
||||
const shellMandatory = Boolean(
|
||||
hasShellDownload && shell?.minRequired && compareSemver(shell.minRequired, input.shellVersion) > 0,
|
||||
)
|
||||
const shellNewer = Boolean(
|
||||
hasShellDownload && shell?.version && compareSemver(shell.version, input.shellVersion) > 0,
|
||||
)
|
||||
if (shell && shellMandatory) {
|
||||
return { kind: 'shell-update', shell, mandatory: true }
|
||||
}
|
||||
|
||||
const bundle = manifest.bundle
|
||||
if (
|
||||
bundle &&
|
||||
typeof bundle.version === 'string' &&
|
||||
STRICT_VERSION_PATTERN.test(bundle.version) &&
|
||||
typeof bundle.url === 'string' &&
|
||||
bundle.url.trim().length > 0 &&
|
||||
typeof bundle.sha256 === 'string' &&
|
||||
SHA256_PATTERN.test(bundle.sha256.trim()) &&
|
||||
compareSemver(bundle.version, input.activeBundleVersion) > 0 &&
|
||||
compareSemver(input.shellVersion, bundle.minShellVersion || '0.0.0') >= 0 &&
|
||||
!input.blacklistedVersions.includes(bundle.version)
|
||||
) {
|
||||
return { kind: 'hotfix-update', bundle }
|
||||
}
|
||||
|
||||
if (shell && shellNewer) {
|
||||
return { kind: 'shell-update', shell, mandatory: false }
|
||||
}
|
||||
|
||||
return { kind: 'up-to-date' }
|
||||
}
|
||||
|
||||
export const PERIODIC_UPDATE_CHECK_INTERVAL_MS = 12 * 60 * 60 * 1000
|
||||
|
||||
export function getUpdatePromptKey(decision: UpdateDecision): string | null {
|
||||
if (decision.kind === 'hotfix-update') {
|
||||
return `hotfix:${decision.bundle.version}`
|
||||
}
|
||||
if (decision.kind === 'shell-update') {
|
||||
return `shell:${decision.shell.version}`
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export function shouldSuppressUpdatePrompt(
|
||||
decision: UpdateDecision,
|
||||
options: { manual: boolean; dismissedKeys: ReadonlySet<string> },
|
||||
): boolean {
|
||||
if (options.manual || decision.kind === 'up-to-date') {
|
||||
return false
|
||||
}
|
||||
const key = getUpdatePromptKey(decision)
|
||||
return Boolean(key && options.dismissedKeys.has(key))
|
||||
}
|
||||
|
||||
export function resolveUpdateAssetUrl(rawUrl: string, backendUrl: string): string {
|
||||
const trimmed = String(rawUrl || '').trim()
|
||||
if (!trimmed) {
|
||||
throw new Error('Empty update asset URL')
|
||||
}
|
||||
if (trimmed.startsWith('/')) {
|
||||
const base = new URL(backendUrl)
|
||||
return new URL(trimmed, `${base.origin}`).toString()
|
||||
}
|
||||
const parsed = new URL(trimmed)
|
||||
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
||||
throw new Error(`Unsupported update asset URL protocol: ${parsed.protocol}`)
|
||||
}
|
||||
return parsed.toString()
|
||||
}
|
||||
|
||||
export function installHotfixArchive(input: {
|
||||
userDataDir: string
|
||||
version: string
|
||||
archiveBuffer: Buffer
|
||||
expectedSha256: string
|
||||
}): { overlayRoot: string; filesCount: number } {
|
||||
const version = String(input.version || '').trim()
|
||||
if (!STRICT_VERSION_PATTERN.test(version)) {
|
||||
throw new Error(`Invalid hotfix bundle version: ${version}`)
|
||||
}
|
||||
const expected = String(input.expectedSha256 || '').trim().toLowerCase()
|
||||
if (!SHA256_PATTERN.test(expected)) {
|
||||
throw new Error('Invalid expected SHA-256 checksum')
|
||||
}
|
||||
|
||||
const actual = crypto.createHash('sha256').update(input.archiveBuffer).digest('hex').toLowerCase()
|
||||
if (actual !== expected) {
|
||||
throw new Error(`Hotfix SHA-256 mismatch (expected ${expected}, got ${actual})`)
|
||||
}
|
||||
|
||||
const rootDir = getHotfixRootDir(input.userDataDir)
|
||||
const bundlesDir = getHotfixBundlesDir(input.userDataDir)
|
||||
const targetDir = getHotfixBundleDir(input.userDataDir, version)
|
||||
const stagingDir = path.join(rootDir, `staging-${version}-${Date.now()}`)
|
||||
|
||||
try {
|
||||
const extracted = extractTarGzSafely(input.archiveBuffer, stagingDir)
|
||||
if (!hasValidBundleIndex(stagingDir)) {
|
||||
throw new Error('Hotfix archive is missing required index.html entry')
|
||||
}
|
||||
|
||||
fs.mkdirSync(bundlesDir, { recursive: true })
|
||||
fs.rmSync(targetDir, { recursive: true, force: true })
|
||||
fs.renameSync(stagingDir, targetDir)
|
||||
|
||||
const previousState = readHotfixState(input.userDataDir)
|
||||
const preservedVerified =
|
||||
previousState.status === 'verified' && previousState.activeVersion && previousState.activeVersion !== version
|
||||
? previousState.activeVersion
|
||||
: previousState.previousVerifiedVersion && previousState.previousVerifiedVersion !== version
|
||||
? previousState.previousVerifiedVersion
|
||||
: null
|
||||
|
||||
const nextState: HotfixState = {
|
||||
activeVersion: version,
|
||||
previousVerifiedVersion: preservedVerified,
|
||||
status: 'pending',
|
||||
pendingAttempts: 0,
|
||||
blacklistedVersions: previousState.blacklistedVersions.filter((item) => item !== version),
|
||||
installedAt: new Date().toISOString(),
|
||||
}
|
||||
writeHotfixStateAtomic(input.userDataDir, nextState)
|
||||
|
||||
return {
|
||||
overlayRoot: targetDir,
|
||||
filesCount: extracted.files.length,
|
||||
}
|
||||
} catch (error) {
|
||||
fs.rmSync(stagingDir, { recursive: true, force: true })
|
||||
throw error
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
import { dialog, net, shell, type BrowserWindow, type MessageBoxOptions } from 'electron'
|
||||
|
||||
import {
|
||||
evaluateUpdateDecision,
|
||||
getUpdatePromptKey,
|
||||
installHotfixArchive,
|
||||
markHotfixVerified,
|
||||
readHotfixState,
|
||||
resolveActiveEarthOverlay,
|
||||
resolveUpdateAssetUrl,
|
||||
rollbackPendingHotfix,
|
||||
shouldSuppressUpdatePrompt,
|
||||
type ClientUpdateManifest,
|
||||
} from './hot-update-core'
|
||||
|
||||
export interface HotUpdateVersionInfo {
|
||||
shellVersion: string
|
||||
activeBundleVersion: string
|
||||
usingHotfix: boolean
|
||||
pendingVerification: boolean
|
||||
}
|
||||
|
||||
export interface HotUpdateController {
|
||||
getOverlayRoot(): string | null
|
||||
getVersionInfo(): HotUpdateVersionInfo
|
||||
markStartupReady(): void
|
||||
handleRendererCrash(): void
|
||||
startStartupWatchdog(): void
|
||||
stopStartupWatchdog(): void
|
||||
checkForUpdates(options?: { manual?: boolean }): Promise<void>
|
||||
}
|
||||
|
||||
const MANIFEST_TIMEOUT_MS = 10_000
|
||||
const DOWNLOAD_TIMEOUT_MS = 60_000
|
||||
const STARTUP_VERIFY_TIMEOUT_MS = 15_000
|
||||
|
||||
async function fetchWithTimeout(
|
||||
fetchImpl: typeof fetch,
|
||||
url: string,
|
||||
timeoutMs: number,
|
||||
init: RequestInit = {},
|
||||
): Promise<Response> {
|
||||
const controller = new AbortController()
|
||||
const timer = setTimeout(() => controller.abort(), timeoutMs)
|
||||
try {
|
||||
return await fetchImpl(url, { ...init, signal: controller.signal })
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
}
|
||||
}
|
||||
|
||||
export function createHotUpdateController(options: {
|
||||
userDataDir: string
|
||||
shellVersion: string
|
||||
getBackendUrl: () => string
|
||||
getMainWindow: () => BrowserWindow | null
|
||||
onOverlayChanged: (nextOverlayRoot: string | null, nextBundleVersion: string) => void
|
||||
fetchImpl?: typeof fetch
|
||||
}): HotUpdateController {
|
||||
const fetchImpl = options.fetchImpl ?? ((input, init) => net.fetch(input as string, init))
|
||||
|
||||
const initial = resolveActiveEarthOverlay({
|
||||
userDataDir: options.userDataDir,
|
||||
shellVersion: options.shellVersion,
|
||||
})
|
||||
if (initial.rolledBackFrom) {
|
||||
console.warn(
|
||||
`[planet-client] Rolled back unverified hotfix v${initial.rolledBackFrom} -> v${initial.activeBundleVersion}`,
|
||||
)
|
||||
}
|
||||
|
||||
let overlayRoot = initial.overlayRoot
|
||||
let activeBundleVersion = initial.activeBundleVersion
|
||||
let pendingVerification = initial.pendingVerification
|
||||
let watchdogTimer: ReturnType<typeof setTimeout> | null = null
|
||||
let inFlightCheck: Promise<void> | null = null
|
||||
const dismissedPromptKeys = new Set<string>()
|
||||
|
||||
const notifyStatus = (message: string, type: 'info' | 'success' | 'error' = 'info') => {
|
||||
const win = options.getMainWindow()
|
||||
if (win && !win.isDestroyed() && !win.webContents.isDestroyed()) {
|
||||
win.webContents.send('planet:update-status', { message, type })
|
||||
}
|
||||
}
|
||||
|
||||
const showBox = (boxOptions: MessageBoxOptions) => {
|
||||
const win = options.getMainWindow()
|
||||
if (win && !win.isDestroyed()) {
|
||||
return dialog.showMessageBox(win, boxOptions)
|
||||
}
|
||||
return dialog.showMessageBox(boxOptions)
|
||||
}
|
||||
|
||||
const stopStartupWatchdog = () => {
|
||||
if (watchdogTimer) {
|
||||
clearTimeout(watchdogTimer)
|
||||
watchdogTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
const performRollbackAndReload = (reason: string) => {
|
||||
stopStartupWatchdog()
|
||||
const result = rollbackPendingHotfix(options.userDataDir, options.shellVersion)
|
||||
if (!result.rolledBackFrom) return
|
||||
console.warn(`[planet-client] ${reason}; rolled back v${result.rolledBackFrom} -> v${result.activeBundleVersion}`)
|
||||
overlayRoot = result.overlayRoot
|
||||
activeBundleVersion = result.activeBundleVersion
|
||||
pendingVerification = false
|
||||
options.onOverlayChanged(overlayRoot, activeBundleVersion)
|
||||
const win = options.getMainWindow()
|
||||
if (win && !win.isDestroyed() && !win.webContents.isDestroyed()) {
|
||||
win.webContents.reloadIgnoringCache()
|
||||
}
|
||||
}
|
||||
|
||||
const startStartupWatchdog = () => {
|
||||
stopStartupWatchdog()
|
||||
if (!pendingVerification) return
|
||||
watchdogTimer = setTimeout(() => {
|
||||
watchdogTimer = null
|
||||
if (!pendingVerification) return
|
||||
performRollbackAndReload('Hotfix startup verification timed out')
|
||||
}, STARTUP_VERIFY_TIMEOUT_MS)
|
||||
}
|
||||
|
||||
const markStartupReady = () => {
|
||||
stopStartupWatchdog()
|
||||
if (!pendingVerification) return
|
||||
pendingVerification = false
|
||||
markHotfixVerified(options.userDataDir)
|
||||
options.onOverlayChanged(overlayRoot, activeBundleVersion)
|
||||
notifyStatus(`热更新已生效 / Hotfix v${activeBundleVersion} active`, 'success')
|
||||
}
|
||||
|
||||
const handleRendererCrash = () => {
|
||||
if (!pendingVerification) return
|
||||
performRendererCrashRecovery()
|
||||
}
|
||||
|
||||
const performRendererCrashRecovery = () => {
|
||||
performRendererSafeRollback()
|
||||
}
|
||||
|
||||
const performRendererSafeRollback = () => {
|
||||
performRollbackAndReload('Renderer exited unexpectedly under pending hotfix')
|
||||
}
|
||||
|
||||
const applyHotfixBundle = async (bundleUrl: string, version: string, expectedSha256: string) => {
|
||||
notifyStatus(`正在下载热更新 v${version}… / Downloading hotfix v${version}…`, 'info')
|
||||
const response = await fetchWithTimeout(fetchImpl, bundleUrl, DOWNLOAD_TIMEOUT_MS, {
|
||||
cache: 'no-store',
|
||||
})
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}`)
|
||||
}
|
||||
const arrayBuf = await response.arrayBuffer()
|
||||
const archiveBuffer = Buffer.from(arrayBuf)
|
||||
|
||||
const installed = installHotfixArchive({
|
||||
userDataDir: options.userDataDir,
|
||||
version,
|
||||
archiveBuffer,
|
||||
expectedSha256,
|
||||
})
|
||||
|
||||
overlayRoot = installed.overlayRoot
|
||||
activeBundleVersion = version
|
||||
pendingVerification = true
|
||||
options.onOverlayChanged(overlayRoot, activeBundleVersion)
|
||||
startStartupWatchdog()
|
||||
|
||||
const win = options.getMainWindow()
|
||||
if (win && !win.isDestroyed() && !win.webContents.isDestroyed()) {
|
||||
win.webContents.reloadIgnoringCache()
|
||||
}
|
||||
}
|
||||
|
||||
const runCheck = async (manual: boolean): Promise<void> => {
|
||||
const backendUrl = options.getBackendUrl().replace(/\/+$/, '')
|
||||
const manifestUrl = new URL(`${backendUrl}/api/v1/client/update-manifest`)
|
||||
manifestUrl.searchParams.set('platform', process.platform)
|
||||
manifestUrl.searchParams.set('arch', process.arch)
|
||||
manifestUrl.searchParams.set('shell', options.shellVersion)
|
||||
manifestUrl.searchParams.set('bundle', activeBundleVersion)
|
||||
|
||||
let manifest: ClientUpdateManifest
|
||||
try {
|
||||
const response = await fetchWithTimeout(fetchImpl, manifestUrl.toString(), MANIFEST_TIMEOUT_MS, {
|
||||
cache: 'no-store',
|
||||
headers: { Accept: 'application/json' },
|
||||
})
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}`)
|
||||
}
|
||||
manifest = (await response.json()) as ClientUpdateManifest
|
||||
} catch (error) {
|
||||
const detail = error instanceof Error ? error.message : String(error)
|
||||
if (manual) {
|
||||
await showBox({
|
||||
type: 'warning',
|
||||
title: '检查更新失败 / Update Check Failed',
|
||||
message: '无法获取版本清单,请确认服务端连接正常。',
|
||||
detail,
|
||||
buttons: ['确定 / OK'],
|
||||
})
|
||||
} else {
|
||||
console.warn('[planet-client] Startup update check skipped:', detail)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
const state = readHotfixState(options.userDataDir)
|
||||
const decision = evaluateUpdateDecision({
|
||||
shellVersion: options.shellVersion,
|
||||
activeBundleVersion,
|
||||
blacklistedVersions: state.blacklistedVersions,
|
||||
manifest,
|
||||
})
|
||||
|
||||
if (decision.kind === 'up-to-date') {
|
||||
if (manual) {
|
||||
await showBox({
|
||||
type: 'info',
|
||||
title: '当前已是最新版本 / Up to Date',
|
||||
message: 'Planet Earth 客户端已是最新版本。',
|
||||
detail: `外壳版本 / Shell: v${options.shellVersion}\n地球业务包 / Earth Bundle: v${activeBundleVersion}`,
|
||||
buttons: ['确定 / OK'],
|
||||
})
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (shouldSuppressUpdatePrompt(decision, { manual, dismissedKeys: dismissedPromptKeys })) {
|
||||
return
|
||||
}
|
||||
|
||||
const promptKey = getUpdatePromptKey(decision)
|
||||
|
||||
if (decision.kind === 'hotfix-update') {
|
||||
const { bundle } = decision
|
||||
const notes = bundle.releaseNotes?.trim() ? `\n\n更新内容:\n${bundle.releaseNotes.trim()}` : ''
|
||||
const { response } = await showBox({
|
||||
type: 'info',
|
||||
title: '发现新版本 / Update Available',
|
||||
message: `发现 Planet Earth 增量热更新 v${bundle.version}`,
|
||||
detail: `当前地球版本 v${activeBundleVersion} → 最新版本 v${bundle.version}\n更新方式:轻量热更新(无需重新安装,应用后自动生效)${notes}`,
|
||||
buttons: ['立即更新 / Update Now', '稍后提醒 / Later'],
|
||||
defaultId: 0,
|
||||
cancelId: 1,
|
||||
})
|
||||
if (response !== 0) {
|
||||
if (promptKey) dismissedPromptKeys.add(promptKey)
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const assetUrl = resolveUpdateAssetUrl(bundle.url, backendUrl)
|
||||
await applyHotfixBundle(assetUrl, bundle.version, bundle.sha256)
|
||||
} catch (error) {
|
||||
const detail = error instanceof Error ? error.message : String(error)
|
||||
console.error('[planet-client] Hotfix installation failed:', detail)
|
||||
await showBox({
|
||||
type: 'error',
|
||||
title: '热更新失败 / Hotfix Failed',
|
||||
message: `热更新包 v${bundle.version} 下载或校验失败,已保留当前版本运行。`,
|
||||
detail,
|
||||
buttons: ['确定 / OK'],
|
||||
})
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
const { shell: shellInfo, mandatory } = decision
|
||||
const notes = shellInfo.releaseNotes?.trim() ? `\n\n更新说明:\n${shellInfo.releaseNotes.trim()}` : ''
|
||||
const { response } = await showBox({
|
||||
type: mandatory ? 'warning' : 'info',
|
||||
title: '发现客户端大版本更新 / Major Client Update',
|
||||
message: mandatory
|
||||
? `当前客户端版本 v${options.shellVersion} 过低,需升级至 v${shellInfo.version}`
|
||||
: `发现客户端新版本 v${shellInfo.version}`,
|
||||
detail: `当前客户端外壳:v${options.shellVersion}\n最新版本:v${shellInfo.version}\n该版本包含底层架构或原生壳变更,需下载安装包覆盖更新。${notes}`,
|
||||
buttons: ['前往下载 / Download', '稍后提醒 / Later'],
|
||||
defaultId: 0,
|
||||
cancelId: 1,
|
||||
})
|
||||
if (response === 0) {
|
||||
await shell.openExternal(shellInfo.downloadUrl)
|
||||
} else if (promptKey) {
|
||||
dismissedPromptKeys.add(promptKey)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
getOverlayRoot: () => overlayRoot,
|
||||
getVersionInfo: () => ({
|
||||
shellVersion: options.shellVersion,
|
||||
activeBundleVersion,
|
||||
usingHotfix: Boolean(overlayRoot),
|
||||
pendingVerification,
|
||||
}),
|
||||
markStartupReady,
|
||||
handleRendererCrash,
|
||||
startStartupWatchdog,
|
||||
stopStartupWatchdog,
|
||||
checkForUpdates(checkOpts = {}) {
|
||||
if (inFlightCheck) return inFlightCheck
|
||||
inFlightCheck = runCheck(Boolean(checkOpts.manual)).finally(() => {
|
||||
inFlightCheck = null
|
||||
})
|
||||
return inFlightCheck
|
||||
},
|
||||
}
|
||||
}
|
||||
+251
-40
@@ -1,29 +1,73 @@
|
||||
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 { 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')
|
||||
if (isHeadlessSmoke) {
|
||||
app.commandLine.appendSwitch('disable-gpu')
|
||||
app.commandLine.appendSwitch('use-gl', 'angle')
|
||||
app.commandLine.appendSwitch('use-angle', 'swiftshader')
|
||||
app.commandLine.appendSwitch('enable-unsafe-swiftshader')
|
||||
} else {
|
||||
// Prioritize discrete/high-performance GPU and avoid throttling visible secondary-screen renders.
|
||||
app.commandLine.appendSwitch('force_high_performance_gpu')
|
||||
app.commandLine.appendSwitch('enable-gpu-rasterization')
|
||||
app.commandLine.appendSwitch('enable-zero-copy')
|
||||
app.commandLine.appendSwitch('disable-renderer-backgrounding')
|
||||
if (process.platform === 'linux') {
|
||||
app.commandLine.appendSwitch('ozone-platform-hint', 'auto')
|
||||
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,
|
||||
target: startupGpuDecision.target,
|
||||
})) {
|
||||
if (sw.value !== undefined) {
|
||||
app.commandLine.appendSwitch(sw.name, sw.value)
|
||||
} else {
|
||||
app.commandLine.appendSwitch(sw.name)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,24 +107,28 @@ function resolvePreloadPath(): string {
|
||||
}
|
||||
|
||||
let mainWindow: BrowserWindow | null = null
|
||||
let launchWindow: (() => void) | undefined
|
||||
|
||||
function showEarthWindow() {
|
||||
if (!mainWindow || mainWindow.isDestroyed()) {
|
||||
launchWindow?.()
|
||||
return
|
||||
}
|
||||
if (mainWindow.isMinimized()) mainWindow.restore()
|
||||
mainWindow.show()
|
||||
mainWindow.focus()
|
||||
}
|
||||
|
||||
const singleInstanceLock = isHeadlessSmoke ? true : app.requestSingleInstanceLock()
|
||||
if (!singleInstanceLock) {
|
||||
app.quit()
|
||||
} else {
|
||||
if (!isHeadlessSmoke && typeof app.setAsDefaultProtocolClient === 'function') {
|
||||
try {
|
||||
app.setAsDefaultProtocolClient('planet-earth')
|
||||
} catch {
|
||||
// Non-fatal in unpackaged dev sessions.
|
||||
}
|
||||
}
|
||||
|
||||
app.on('second-instance', () => {
|
||||
if (!mainWindow || mainWindow.isDestroyed()) return
|
||||
if (mainWindow.isMinimized()) mainWindow.restore()
|
||||
mainWindow.focus()
|
||||
app.on('open-url', (event, url) => {
|
||||
if (url !== `${DESKTOP_SCHEME}://open` && url !== `${DESKTOP_SCHEME}://open/`) return
|
||||
event.preventDefault()
|
||||
showEarthWindow()
|
||||
})
|
||||
app.on('second-instance', showEarthWindow)
|
||||
|
||||
app.on('window-all-closed', () => {
|
||||
if (process.platform !== 'darwin') {
|
||||
@@ -88,7 +136,24 @@ if (!singleInstanceLock) {
|
||||
}
|
||||
})
|
||||
|
||||
app.on('child-process-gone', (_event, details) => {
|
||||
if (!isGpuProcessCrash(details)) return
|
||||
console.warn('[planet-client] GPU process exited unexpectedly', {
|
||||
reason: details.reason,
|
||||
exitCode: details.exitCode,
|
||||
})
|
||||
if (mainWindow && !mainWindow.isDestroyed() && !mainWindow.webContents.isDestroyed()) {
|
||||
mainWindow.webContents.send('planet:gpu-process-gone', {
|
||||
reason: details.reason,
|
||||
exitCode: details.exitCode,
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
void app.whenReady().then(async () => {
|
||||
if (!isHeadlessSmoke) {
|
||||
void registerDesktopLink().catch(error => console.warn('Planet Earth protocol registration failed', error))
|
||||
}
|
||||
const configStore = new DesktopConfigStore({
|
||||
userDataDir: app.getPath('userData'),
|
||||
exeDir: path.dirname(app.getPath('exe')),
|
||||
@@ -97,11 +162,120 @@ 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(),
|
||||
getBackendUrl: () => configStore.get().backendUrl,
|
||||
getMainWindow: () => mainWindow,
|
||||
onOverlayChanged: () => {
|
||||
refreshApplicationMenu()
|
||||
},
|
||||
})
|
||||
|
||||
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(
|
||||
buildApplicationMenu({
|
||||
mainWindow,
|
||||
configStore,
|
||||
getVersionInfo: () => hotUpdater.getVersionInfo(),
|
||||
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 })
|
||||
}
|
||||
},
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
installEarthSessionHandlers(session.defaultSession, {
|
||||
earthBundleRoot,
|
||||
getEarthOverlayRoot: () => hotUpdater.getOverlayRoot(),
|
||||
getBackendUrl: () => configStore.get().backendUrl,
|
||||
})
|
||||
|
||||
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 })
|
||||
})
|
||||
|
||||
ipcMain.handle('planet:get-version-info', () => hotUpdater.getVersionInfo())
|
||||
|
||||
ipcMain.on('planet:get-runtime-config', (event) => {
|
||||
const cfg = configStore.get()
|
||||
event.returnValue = {
|
||||
@@ -111,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,
|
||||
@@ -170,9 +347,7 @@ if (!singleInstanceLock) {
|
||||
|
||||
ipcMain.handle('planet:set-splash-theme', (_event, rawTheme: unknown) => {
|
||||
const next = configStore.updateSplashTheme(normalizeSplashTheme(rawTheme, configStore.get().splashTheme))
|
||||
if (mainWindow && !mainWindow.isDestroyed()) {
|
||||
Menu.setApplicationMenu(buildApplicationMenu({ mainWindow, configStore }))
|
||||
}
|
||||
refreshApplicationMenu()
|
||||
return next.splashTheme
|
||||
})
|
||||
|
||||
@@ -180,7 +355,7 @@ if (!singleInstanceLock) {
|
||||
dismissMenuBarOnPointerDown(mainWindow)
|
||||
})
|
||||
|
||||
const launchWindow = () => {
|
||||
launchWindow = () => {
|
||||
const preloadPath = resolvePreloadPath()
|
||||
mainWindow = createMainWindow({
|
||||
preloadPath,
|
||||
@@ -189,11 +364,48 @@ if (!singleInstanceLock) {
|
||||
configStore,
|
||||
})
|
||||
|
||||
Menu.setApplicationMenu(buildApplicationMenu({ mainWindow, configStore }))
|
||||
refreshApplicationMenu()
|
||||
if (process.platform !== 'darwin') {
|
||||
mainWindow.setMenuBarVisibility(false)
|
||||
}
|
||||
|
||||
if (!isHeadlessSmoke) {
|
||||
let autoUpdateTimer: ReturnType<typeof setTimeout> | null = null
|
||||
let periodicUpdateTimer: ReturnType<typeof setInterval> | null = null
|
||||
mainWindow.webContents.on('render-process-gone', () => {
|
||||
hotUpdater.handleRendererCrash()
|
||||
})
|
||||
hotUpdater.startStartupWatchdog()
|
||||
mainWindow.webContents.once('did-finish-load', () => {
|
||||
gpuMonitor.start()
|
||||
autoUpdateTimer = setTimeout(() => {
|
||||
autoUpdateTimer = null
|
||||
if (mainWindow && !mainWindow.isDestroyed()) {
|
||||
void hotUpdater.checkForUpdates({ manual: false })
|
||||
}
|
||||
}, 4000)
|
||||
if (!periodicUpdateTimer) {
|
||||
periodicUpdateTimer = setInterval(() => {
|
||||
if (mainWindow && !mainWindow.isDestroyed() && !mainWindow.isMinimized()) {
|
||||
void hotUpdater.checkForUpdates({ manual: false })
|
||||
}
|
||||
}, PERIODIC_UPDATE_CHECK_INTERVAL_MS)
|
||||
}
|
||||
})
|
||||
mainWindow.once('closed', () => {
|
||||
gpuMonitor.stop()
|
||||
if (autoUpdateTimer) {
|
||||
clearTimeout(autoUpdateTimer)
|
||||
autoUpdateTimer = null
|
||||
}
|
||||
if (periodicUpdateTimer) {
|
||||
clearInterval(periodicUpdateTimer)
|
||||
periodicUpdateTimer = null
|
||||
}
|
||||
hotUpdater.stopStartupWatchdog()
|
||||
})
|
||||
}
|
||||
|
||||
if (isHeadlessSmoke) {
|
||||
const smokeTimeout = setTimeout(() => {
|
||||
app.exit(1)
|
||||
@@ -259,19 +471,18 @@ if (!singleInstanceLock) {
|
||||
const img = sr?.querySelector('.splash-zju-emblem');
|
||||
const copy = sr?.querySelector('.splash-presenter-copy')?.textContent || '';
|
||||
const finishCheck = () => {
|
||||
window.planetDesktop.replaySplash('constellation');
|
||||
const firstSwitch = host?.dataset.splashTheme || '';
|
||||
window.planetDesktop.replaySplash('horizon');
|
||||
const secondSwitch = host?.dataset.splashTheme || '';
|
||||
const activeTheme = host?.dataset.splashTheme || '';
|
||||
const hasNoThemeSwitcher = !sr?.querySelector('.splash-switcher');
|
||||
window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
|
||||
resolve({
|
||||
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,
|
||||
switchedThemes: [firstSwitch, secondSwitch],
|
||||
activeTheme,
|
||||
hasNoThemeSwitcher,
|
||||
});
|
||||
};
|
||||
if (!img || img.complete) {
|
||||
@@ -321,7 +532,7 @@ if (!singleInstanceLock) {
|
||||
|
||||
app.on('activate', () => {
|
||||
if (BrowserWindow.getAllWindows().length === 0) {
|
||||
launchWindow()
|
||||
launchWindow?.()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
+93
-24
@@ -1,11 +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'
|
||||
|
||||
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()) {
|
||||
@@ -19,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)
|
||||
@@ -72,31 +96,13 @@ export function buildApplicationMenu(options: {
|
||||
},
|
||||
},
|
||||
{
|
||||
label: '启动画面方案 / Splash Screen',
|
||||
label: '启动画面 / Splash Screen',
|
||||
submenu: [
|
||||
{
|
||||
label: '方案 1:星核奇点展开 / Singularity Burst',
|
||||
type: 'radio',
|
||||
checked: currentSplashTheme === 'singularity',
|
||||
click: () => selectSplashTheme('singularity'),
|
||||
},
|
||||
{
|
||||
label: '方案 2:轨道星座校准 / Orbital Astrolabe',
|
||||
type: 'radio',
|
||||
checked: currentSplashTheme === 'constellation',
|
||||
click: () => selectSplashTheme('constellation'),
|
||||
},
|
||||
{
|
||||
label: '方案 3:晨昏日冕破晓 / Eclipse Horizon',
|
||||
type: 'radio',
|
||||
checked: currentSplashTheme === 'horizon',
|
||||
click: () => selectSplashTheme('horizon'),
|
||||
},
|
||||
{
|
||||
label: '关闭启动画面 / Off',
|
||||
type: 'radio',
|
||||
checked: currentSplashTheme === 'off',
|
||||
click: () => selectSplashTheme('off'),
|
||||
label: '启用启动画面 / Enable Splash Screen',
|
||||
type: 'checkbox',
|
||||
checked: currentSplashTheme !== 'off',
|
||||
click: () => selectSplashTheme(currentSplashTheme === 'off' ? 'singularity' : 'off'),
|
||||
},
|
||||
{ type: 'separator' },
|
||||
{
|
||||
@@ -106,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',
|
||||
@@ -116,6 +168,23 @@ export function buildApplicationMenu(options: {
|
||||
click: () => openAdminPath('/docs/manual'),
|
||||
},
|
||||
{ type: 'separator' },
|
||||
{
|
||||
label: '检查更新 / Check for Updates...',
|
||||
click: () => options.onCheckForUpdates?.(),
|
||||
},
|
||||
...(options.getVersionInfo
|
||||
? [
|
||||
(() => {
|
||||
const info = options.getVersionInfo!()
|
||||
const suffix = info.usingHotfix ? ' (热更 / Hotfix)' : ''
|
||||
return {
|
||||
label: `当前版本: Shell v${info.shellVersion} · Earth v${info.activeBundleVersion}${suffix}`,
|
||||
enabled: false,
|
||||
}
|
||||
})(),
|
||||
]
|
||||
: []),
|
||||
{ type: 'separator' },
|
||||
{ role: 'quit', label: '退出 / Quit' },
|
||||
],
|
||||
},
|
||||
|
||||
@@ -156,6 +156,7 @@ export function createStaticFileResponse(filePath: string, requestHeaders: Heade
|
||||
|
||||
export function createEarthProtocolHandler(options: {
|
||||
earthBundleRoot: string
|
||||
getEarthOverlayRoot?: () => string | null
|
||||
getBackendUrl: () => string
|
||||
fetchImpl?: typeof fetch
|
||||
}): (request: Request) => Promise<Response> {
|
||||
@@ -209,6 +210,21 @@ export function createEarthProtocolHandler(options: {
|
||||
if (!staticPath) {
|
||||
return new Response('Forbidden', { status: 403 })
|
||||
}
|
||||
|
||||
const overlayRoot = options.getEarthOverlayRoot?.()
|
||||
if (overlayRoot) {
|
||||
const overlayPath = resolveEarthStaticPath(overlayRoot, parsedUrl.pathname)
|
||||
if (overlayPath) {
|
||||
try {
|
||||
if (fs.statSync(overlayPath).isFile()) {
|
||||
return createStaticFileResponse(overlayPath, request.headers)
|
||||
}
|
||||
} catch {
|
||||
// Fall back to the built-in shell bundle for non-overlaid static assets.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return createStaticFileResponse(staticPath, request.headers)
|
||||
}
|
||||
}
|
||||
@@ -25,11 +25,13 @@ export function installEarthSessionHandlers(
|
||||
targetSession: Session,
|
||||
options: {
|
||||
earthBundleRoot: string
|
||||
getEarthOverlayRoot?: () => string | null
|
||||
getBackendUrl: () => string
|
||||
},
|
||||
): void {
|
||||
const handler = createEarthProtocolHandler({
|
||||
earthBundleRoot: options.earthBundleRoot,
|
||||
getEarthOverlayRoot: options.getEarthOverlayRoot,
|
||||
getBackendUrl: options.getBackendUrl,
|
||||
fetchImpl: (input, init) => net.fetch(input as string, init),
|
||||
})
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import zlib from 'node:zlib'
|
||||
|
||||
export interface TarEntryInput {
|
||||
path: string
|
||||
data: Uint8Array
|
||||
}
|
||||
|
||||
export interface ExtractTarGzOptions {
|
||||
maxFiles?: number
|
||||
maxTotalBytes?: number
|
||||
}
|
||||
|
||||
export interface ExtractTarGzResult {
|
||||
files: string[]
|
||||
totalBytes: number
|
||||
}
|
||||
|
||||
const TAR_BLOCK_SIZE = 512
|
||||
const DEFAULT_MAX_FILES = 2000
|
||||
const DEFAULT_MAX_TOTAL_BYTES = 64 * 1024 * 1024
|
||||
|
||||
export function normalizeArchiveEntryPath(rawPath: string): string {
|
||||
if (!rawPath || rawPath.includes('\0') || rawPath.includes('\\')) {
|
||||
throw new Error(`Invalid archive entry path: ${JSON.stringify(rawPath)}`)
|
||||
}
|
||||
let stripped = rawPath.replace(/^(?:\.\/)+/, '').replace(/\/+$/, '')
|
||||
if (!stripped || stripped.startsWith('/')) {
|
||||
throw new Error(`Unsafe archive entry path: ${JSON.stringify(rawPath)}`)
|
||||
}
|
||||
const segments = stripped.split('/')
|
||||
if (segments.some((seg) => !seg || seg === '.' || seg === '..')) {
|
||||
throw new Error(`Path traversal not allowed in archive entry: ${JSON.stringify(rawPath)}`)
|
||||
}
|
||||
stripped = segments.join('/')
|
||||
if (/^[A-Za-z]:/.test(stripped)) {
|
||||
throw new Error(`Drive-prefixed archive entry path not allowed: ${JSON.stringify(rawPath)}`)
|
||||
}
|
||||
return stripped
|
||||
}
|
||||
|
||||
function splitUstarPath(entryPath: string): { name: string; prefix: string } {
|
||||
const bytesLen = Buffer.byteLength(entryPath, 'utf8')
|
||||
if (bytesLen <= 100) {
|
||||
return { name: entryPath, prefix: '' }
|
||||
}
|
||||
if (bytesLen > 256) {
|
||||
throw new Error(`Archive entry path exceeds POSIX USTAR 256-byte limit: ${entryPath}`)
|
||||
}
|
||||
for (let idx = entryPath.indexOf('/', Math.max(0, entryPath.length - 101)); idx !== -1; idx = entryPath.indexOf('/', idx + 1)) {
|
||||
const prefix = entryPath.slice(0, idx)
|
||||
const name = entryPath.slice(idx + 1)
|
||||
if (name && Buffer.byteLength(name, 'utf8') <= 100 && Buffer.byteLength(prefix, 'utf8') <= 155) {
|
||||
return { name, prefix }
|
||||
}
|
||||
}
|
||||
throw new Error(`Cannot split archive entry path into USTAR prefix/name: ${entryPath}`)
|
||||
}
|
||||
|
||||
function writeOctalField(buf: Buffer, offset: number, length: number, value: number): void {
|
||||
const digits = length - 1
|
||||
const octal = Math.max(0, Math.floor(value)).toString(8)
|
||||
if (octal.length > digits) {
|
||||
throw new Error(`Tar numeric value overflows ${digits}-digit octal field: ${value}`)
|
||||
}
|
||||
buf.write(`${octal.padStart(digits, '0')}\0`, offset, length, 'ascii')
|
||||
}
|
||||
|
||||
export function createTarGz(entries: TarEntryInput[]): Buffer {
|
||||
const normalizedEntries = [...entries]
|
||||
.map((entry) => ({
|
||||
path: normalizeArchiveEntryPath(entry.path),
|
||||
data: entry.data instanceof Buffer ? entry.data : Buffer.from(entry.data),
|
||||
}))
|
||||
.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))
|
||||
|
||||
const chunks: Buffer[] = []
|
||||
for (const entry of normalizedEntries) {
|
||||
const { name, prefix } = splitUstarPath(entry.path)
|
||||
const header = Buffer.alloc(TAR_BLOCK_SIZE, 0)
|
||||
header.write(name, 0, 100, 'utf8')
|
||||
writeOctalField(header, 100, 8, 0o644)
|
||||
writeOctalField(header, 108, 8, 0)
|
||||
writeOctalField(header, 116, 8, 0)
|
||||
writeOctalField(header, 124, 12, entry.data.byteLength)
|
||||
writeOctalField(header, 136, 12, 0)
|
||||
header.fill(0x20, 148, 156)
|
||||
header.write('0', 156, 1, 'ascii')
|
||||
header.write('ustar\0', 257, 6, 'ascii')
|
||||
header.write('00', 263, 2, 'ascii')
|
||||
if (prefix) {
|
||||
header.write(prefix, 345, 155, 'utf8')
|
||||
}
|
||||
|
||||
let checksum = 0
|
||||
for (let i = 0; i < TAR_BLOCK_SIZE; i += 1) {
|
||||
checksum += header[i]
|
||||
}
|
||||
const chksumStr = `${checksum.toString(8).padStart(6, '0')}\0 `
|
||||
header.write(chksumStr, 148, 8, 'ascii')
|
||||
|
||||
chunks.push(header)
|
||||
if (entry.data.byteLength > 0) {
|
||||
chunks.push(entry.data)
|
||||
const remainder = entry.data.byteLength % TAR_BLOCK_SIZE
|
||||
if (remainder !== 0) {
|
||||
chunks.push(Buffer.alloc(TAR_BLOCK_SIZE - remainder, 0))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
chunks.push(Buffer.alloc(TAR_BLOCK_SIZE * 2, 0))
|
||||
const tarBuffer = Buffer.concat(chunks)
|
||||
return zlib.gzipSync(tarBuffer, { level: 9 })
|
||||
}
|
||||
|
||||
function readCString(buf: Buffer, start: number, length: number): string {
|
||||
const slice = buf.subarray(start, start + length)
|
||||
const nulIdx = slice.indexOf(0)
|
||||
return slice.subarray(0, nulIdx === -1 ? length : nulIdx).toString('utf8')
|
||||
}
|
||||
|
||||
function parseOctalField(buf: Buffer, start: number, length: number): number {
|
||||
const raw = readCString(buf, start, length).trim()
|
||||
if (!raw) return 0
|
||||
if (!/^[0-7]+$/.test(raw)) {
|
||||
throw new Error(`Invalid tar octal field: ${JSON.stringify(raw)}`)
|
||||
}
|
||||
return Number.parseInt(raw, 8)
|
||||
}
|
||||
|
||||
function isZeroBlock(block: Buffer): boolean {
|
||||
for (let i = 0; i < block.length; i += 1) {
|
||||
if (block[i] !== 0) return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
function verifyHeaderChecksum(header: Buffer): void {
|
||||
const stored = parseOctalField(header, 148, 8)
|
||||
let unsignedSum = 0
|
||||
for (let i = 0; i < TAR_BLOCK_SIZE; i += 1) {
|
||||
unsignedSum += i >= 148 && i < 156 ? 0x20 : header[i]
|
||||
}
|
||||
if (stored !== unsignedSum) {
|
||||
throw new Error(`Invalid tar header checksum (expected ${unsignedSum}, got ${stored})`)
|
||||
}
|
||||
}
|
||||
|
||||
export function extractTarGzSafely(
|
||||
archiveBuffer: Buffer,
|
||||
destDir: string,
|
||||
options: ExtractTarGzOptions = {},
|
||||
): ExtractTarGzResult {
|
||||
const maxFiles = options.maxFiles ?? DEFAULT_MAX_FILES
|
||||
const maxTotalBytes = options.maxTotalBytes ?? DEFAULT_MAX_TOTAL_BYTES
|
||||
const tarBuffer = zlib.gunzipSync(archiveBuffer, {
|
||||
maxOutputLength: maxTotalBytes + 2 * 1024 * 1024,
|
||||
})
|
||||
if (tarBuffer.byteLength % TAR_BLOCK_SIZE !== 0) {
|
||||
throw new Error('Corrupt tar archive: unaligned block length')
|
||||
}
|
||||
|
||||
const resolvedDest = path.resolve(destDir)
|
||||
fs.mkdirSync(resolvedDest, { recursive: true })
|
||||
|
||||
const extractedFiles: string[] = []
|
||||
let totalBytes = 0
|
||||
let offset = 0
|
||||
|
||||
while (offset + TAR_BLOCK_SIZE <= tarBuffer.byteLength) {
|
||||
const header = tarBuffer.subarray(offset, offset + TAR_BLOCK_SIZE)
|
||||
offset += TAR_BLOCK_SIZE
|
||||
if (isZeroBlock(header)) {
|
||||
break
|
||||
}
|
||||
|
||||
verifyHeaderChecksum(header)
|
||||
const rawName = readCString(header, 0, 100)
|
||||
const rawPrefix = readCString(header, 345, 155)
|
||||
const fullRawPath = rawPrefix ? `${rawPrefix}/${rawName}` : rawName
|
||||
const size = parseOctalField(header, 124, 12)
|
||||
const typeFlagByte = header[156]
|
||||
const typeFlag = typeFlagByte === 0 ? '0' : String.fromCharCode(typeFlagByte)
|
||||
|
||||
if (offset + size > tarBuffer.byteLength) {
|
||||
throw new Error(`Truncated tar entry data for ${fullRawPath}`)
|
||||
}
|
||||
const data = tarBuffer.subarray(offset, offset + size)
|
||||
const paddedSize = Math.ceil(size / TAR_BLOCK_SIZE) * TAR_BLOCK_SIZE
|
||||
offset += paddedSize
|
||||
|
||||
if (typeFlag === '5') {
|
||||
const normalizedDir = fullRawPath.replace(/^(?:\.\/)+/, '').replace(/\/+$/, '')
|
||||
if (normalizedDir && normalizedDir !== '.') {
|
||||
const safeDir = normalizeArchiveEntryPath(normalizedDir)
|
||||
const targetDir = path.resolve(resolvedDest, safeDir)
|
||||
if (targetDir !== resolvedDest && !targetDir.startsWith(`${resolvedDest}${path.sep}`)) {
|
||||
throw new Error(`Directory escapes extraction root: ${safeDir}`)
|
||||
}
|
||||
fs.mkdirSync(targetDir, { recursive: true })
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if (typeFlag !== '0') {
|
||||
throw new Error(`Unsupported or unsafe tar entry type ${JSON.stringify(typeFlag)} for ${fullRawPath}`)
|
||||
}
|
||||
|
||||
const safeRelPath = normalizeArchiveEntryPath(fullRawPath)
|
||||
if (extractedFiles.length + 1 > maxFiles) {
|
||||
throw new Error(`Archive exceeds maximum file count limit (${maxFiles})`)
|
||||
}
|
||||
totalBytes += size
|
||||
if (totalBytes > maxTotalBytes) {
|
||||
throw new Error(`Archive exceeds maximum uncompressed byte limit (${maxTotalBytes})`)
|
||||
}
|
||||
|
||||
const targetPath = path.resolve(resolvedDest, safeRelPath)
|
||||
if (!targetPath.startsWith(`${resolvedDest}${path.sep}`)) {
|
||||
throw new Error(`File escapes extraction root: ${safeRelPath}`)
|
||||
}
|
||||
fs.mkdirSync(path.dirname(targetPath), { recursive: true })
|
||||
fs.writeFileSync(targetPath, data)
|
||||
extractedFiles.push(safeRelPath)
|
||||
}
|
||||
|
||||
return {
|
||||
files: extractedFiles,
|
||||
totalBytes,
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import path from 'node:path'
|
||||
import { BrowserWindow, ipcMain, nativeTheme, screen, shell, type Display } from 'electron'
|
||||
|
||||
import { createSoloAltMenuTracker } from './alt-menu'
|
||||
import type { DesktopConfigStore, DesktopRuntimeConfig } from './config'
|
||||
import { DEFAULT_ENDPOINTS, type DesktopConfigStore, type DesktopRuntimeConfig } from './config'
|
||||
import { resolveExternalTargetUrl } from './external-links'
|
||||
import { createWindowShowGate } from './show-gate'
|
||||
import {
|
||||
@@ -21,6 +21,12 @@ import {
|
||||
import { EARTH_ENTRY_URL, EARTH_ORIGIN } from './protocol'
|
||||
|
||||
const resetAltMenuTrackers = new WeakMap<BrowserWindow, () => void>()
|
||||
const windowStateFlushers = new WeakMap<BrowserWindow, () => void>()
|
||||
|
||||
export function flushWindowState(win: BrowserWindow | null): void {
|
||||
if (!win || win.isDestroyed()) return
|
||||
windowStateFlushers.get(win)?.()
|
||||
}
|
||||
|
||||
interface OrientationWindowState {
|
||||
lastLandscapeBounds: Rect | null
|
||||
@@ -296,14 +302,17 @@ 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('minimize', () => {
|
||||
if (!win.isDestroyed()) {
|
||||
@@ -346,7 +355,10 @@ export function createMainWindow(options: {
|
||||
}
|
||||
|
||||
const showGate = createWindowShowGate({
|
||||
requireSplashFirstPaint: !runtimeConfig.headlessSmoke && runtimeConfig.splashTheme !== 'off',
|
||||
requireSplashFirstPaint:
|
||||
!runtimeConfig.headlessSmoke &&
|
||||
!runtimeConfig.gpuHandoff &&
|
||||
runtimeConfig.splashTheme !== 'off',
|
||||
fallbackDelayMs: 1500,
|
||||
onReveal: revealMainWindow,
|
||||
})
|
||||
@@ -359,6 +371,7 @@ export function createMainWindow(options: {
|
||||
ipcMain.on('planet:splash-first-paint', onSplashFirstPaint)
|
||||
|
||||
win.once('closed', () => {
|
||||
windowStateFlushers.delete(win)
|
||||
showGate.dispose()
|
||||
ipcMain.removeListener('planet:splash-first-paint', onSplashFirstPaint)
|
||||
})
|
||||
@@ -489,9 +502,9 @@ export function openServerSettingsDialog(
|
||||
}
|
||||
};
|
||||
document.getElementById('defaults').addEventListener('click', () => {
|
||||
form.elements.backendUrl.value = 'http://127.0.0.1:8000';
|
||||
form.elements.adminUrl.value = 'http://127.0.0.1:3000';
|
||||
form.elements.motionWsUrl.value = 'ws://127.0.0.1:8765/ws/gestures';
|
||||
form.elements.backendUrl.value = ${JSON.stringify(DEFAULT_ENDPOINTS.backendUrl)};
|
||||
form.elements.adminUrl.value = ${JSON.stringify(DEFAULT_ENDPOINTS.adminUrl)};
|
||||
form.elements.motionWsUrl.value = ${JSON.stringify(DEFAULT_ENDPOINTS.motionWsUrl)};
|
||||
errEl.textContent = '';
|
||||
});
|
||||
document.getElementById('cancel').addEventListener('click', () => {
|
||||
|
||||
@@ -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', {
|
||||
@@ -75,6 +92,8 @@ contextBridge.exposeInMainWorld('planetDesktop', {
|
||||
replaySplash: (theme?: SplashTheme) => {
|
||||
splashController.replay(theme)
|
||||
},
|
||||
checkForUpdates: () => ipcRenderer.invoke('planet:check-for-updates') as Promise<void>,
|
||||
getVersionInfo: () => ipcRenderer.invoke('planet:get-version-info'),
|
||||
})
|
||||
|
||||
ipcRenderer.on('planet:visibility', (_event, detail) => {
|
||||
@@ -93,6 +112,25 @@ ipcRenderer.on('planet:replay-splash', (_event, detail?: { theme?: SplashTheme }
|
||||
splashController.replay(detail?.theme)
|
||||
})
|
||||
|
||||
ipcRenderer.on('planet:gpu-process-gone', (_event, detail) => {
|
||||
window.dispatchEvent(new CustomEvent('planet-desktop:gpu-process-gone', { detail }))
|
||||
})
|
||||
|
||||
ipcRenderer.on('planet:update-status', (_event, detail) => {
|
||||
window.dispatchEvent(new CustomEvent('earth:status', { detail }))
|
||||
})
|
||||
|
||||
if (document.documentElement?.dataset?.earthStartupReady === '1') {
|
||||
ipcRenderer.send('planet:earth-startup-ready')
|
||||
}
|
||||
window.addEventListener(
|
||||
'earth:startup-ready',
|
||||
() => {
|
||||
ipcRenderer.send('planet:earth-startup-ready')
|
||||
},
|
||||
{ once: true },
|
||||
)
|
||||
|
||||
window.addEventListener(
|
||||
'pointerdown',
|
||||
() => {
|
||||
|
||||
+200
-364
@@ -1,7 +1,7 @@
|
||||
import { LANDMASK_HEIGHT, LANDMASK_WIDTH, unpackEarthLandMask } from './earth-landmask'
|
||||
|
||||
export type SplashTheme = 'singularity' | 'constellation' | 'horizon' | 'off'
|
||||
export type ActiveSplashTheme = Exclude<SplashTheme, 'off'>
|
||||
export type SplashTheme = 'singularity' | 'off'
|
||||
export type ActiveSplashTheme = 'singularity'
|
||||
|
||||
interface GlobePoint {
|
||||
lat: number
|
||||
@@ -32,10 +32,70 @@ interface ArcDef {
|
||||
|
||||
const SPLASH_HOST_ID = 'planet-desktop-splash-host'
|
||||
const DEFAULT_HOST_THEME: ActiveSplashTheme = 'singularity'
|
||||
const REPLAY_DURATION_MS = 2600
|
||||
const MIN_BOOT_SHOWCASE_MS = 1800
|
||||
const REPLAY_DURATION_MS = 3200
|
||||
const MIN_BOOT_SHOWCASE_MS = 2200
|
||||
const MAX_BOOT_CAP_MS = 20000
|
||||
|
||||
export interface SplashCanvasSize {
|
||||
dpr: number
|
||||
width: number
|
||||
height: number
|
||||
}
|
||||
|
||||
export function computeSplashCanvasSize(
|
||||
width: number,
|
||||
height: number,
|
||||
devicePixelRatio: number,
|
||||
maxPixels = 1920 * 1080,
|
||||
maxDpr = 1.5,
|
||||
): SplashCanvasSize {
|
||||
const safeW = Math.max(1, Number(width) || 1)
|
||||
const safeH = Math.max(1, Number(height) || 1)
|
||||
const rawDpr = Math.min(Math.max(Number(devicePixelRatio) || 1, 0.5), maxDpr)
|
||||
const totalPixels = safeW * safeH * rawDpr * rawDpr
|
||||
const dpr =
|
||||
totalPixels > maxPixels
|
||||
? Math.min(rawDpr, Math.max(0.75, Math.floor(Math.sqrt(maxPixels / (safeW * safeH)) * 100) / 100))
|
||||
: rawDpr
|
||||
return {
|
||||
dpr,
|
||||
width: Math.max(1, Math.round(safeW * dpr)),
|
||||
height: Math.max(1, Math.round(safeH * dpr)),
|
||||
}
|
||||
}
|
||||
|
||||
export interface SplashMorphPhases {
|
||||
dawnIntensity: number
|
||||
coreReveal: number
|
||||
orbitReveal: number
|
||||
arcReveal: number
|
||||
burst: number
|
||||
fade: number
|
||||
}
|
||||
|
||||
function clamp01(value: number): number {
|
||||
return Math.max(0, Math.min(1, value))
|
||||
}
|
||||
|
||||
function smoothstep(edge0: number, edge1: number, x: number): number {
|
||||
if (edge1 <= edge0) return x >= edge1 ? 1 : 0
|
||||
const t = clamp01((x - edge0) / (edge1 - edge0))
|
||||
return t * t * (3 - 2 * t)
|
||||
}
|
||||
|
||||
export function computeSplashMorphPhases(progress: number, exitRatio: number): SplashMorphPhases {
|
||||
const p = clamp01(Number.isFinite(progress) ? progress : 0)
|
||||
const e = clamp01(Number.isFinite(exitRatio) ? exitRatio : 0)
|
||||
return {
|
||||
dawnIntensity: (1 - smoothstep(0.36, 0.78, p)) * (1 - smoothstep(0, 0.35, e)),
|
||||
coreReveal: smoothstep(0.18, 0.68, p),
|
||||
orbitReveal: smoothstep(0.38, 0.82, p),
|
||||
arcReveal: smoothstep(0.56, 0.9, p),
|
||||
burst: e > 0 ? Math.pow(e, 1.38) : 0,
|
||||
fade: 1 - Math.pow(e, 2.2),
|
||||
}
|
||||
}
|
||||
|
||||
export interface BootSplashStateInput {
|
||||
elapsedMs: number
|
||||
minDurationMs: number
|
||||
@@ -84,7 +144,7 @@ const ARC_DEFINITIONS: readonly ArcDef[] = [
|
||||
]
|
||||
|
||||
function isActiveTheme(value: string | undefined | null): value is ActiveSplashTheme {
|
||||
return value === 'singularity' || value === 'constellation' || value === 'horizon'
|
||||
return value === 'singularity'
|
||||
}
|
||||
|
||||
function getLocaleIsEn(): boolean {
|
||||
@@ -225,14 +285,6 @@ const SPLASH_CSS = `
|
||||
transition: opacity 380ms cubic-bezier(0.22, 1, 0.36, 1);
|
||||
}
|
||||
|
||||
.splash-root[data-theme="horizon"] {
|
||||
background: radial-gradient(circle at 50% 41%, #091322 0%, #030710 56%, #010308 100%);
|
||||
}
|
||||
|
||||
.splash-root[data-theme="constellation"] {
|
||||
background: radial-gradient(circle at 50% 41%, #06182c 0%, #030916 55%, #02040a 100%);
|
||||
}
|
||||
|
||||
.splash-root.is-exiting {
|
||||
pointer-events: none;
|
||||
}
|
||||
@@ -309,48 +361,24 @@ const SPLASH_CSS = `
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.splash-switcher {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding: 3px;
|
||||
border: 1px solid rgba(173, 210, 255, 0.16);
|
||||
background: rgba(8, 19, 36, 0.62);
|
||||
backdrop-filter: blur(10px);
|
||||
}
|
||||
|
||||
.splash-pill,
|
||||
.splash-skip {
|
||||
appearance: none;
|
||||
border: 1px solid transparent;
|
||||
background: transparent;
|
||||
color: rgba(190, 216, 245, 0.72);
|
||||
border: 1px solid rgba(173, 210, 255, 0.16);
|
||||
background: rgba(8, 19, 36, 0.55);
|
||||
backdrop-filter: blur(10px);
|
||||
color: rgba(190, 216, 245, 0.78);
|
||||
font-family: inherit;
|
||||
font-size: 11px;
|
||||
font-weight: 500;
|
||||
letter-spacing: 0.04em;
|
||||
padding: 4px 9px;
|
||||
padding: 5px 10px;
|
||||
cursor: pointer;
|
||||
transition: color 160ms ease, background-color 160ms ease, border-color 160ms ease;
|
||||
}
|
||||
|
||||
.splash-pill:hover,
|
||||
.splash-skip:hover {
|
||||
color: #f3f9ff;
|
||||
background: rgba(132, 192, 255, 0.12);
|
||||
}
|
||||
|
||||
.splash-pill.is-active {
|
||||
color: #f5faff;
|
||||
background: rgba(82, 168, 255, 0.24);
|
||||
border-color: rgba(136, 206, 255, 0.42);
|
||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.16);
|
||||
}
|
||||
|
||||
.splash-skip {
|
||||
border-color: rgba(173, 210, 255, 0.16);
|
||||
background: rgba(8, 19, 36, 0.55);
|
||||
padding: 5px 10px;
|
||||
background: rgba(132, 192, 255, 0.14);
|
||||
}
|
||||
|
||||
.splash-footer {
|
||||
@@ -438,21 +466,6 @@ const SPLASH_CSS = `
|
||||
border: 1px solid rgba(173, 214, 255, 0.12);
|
||||
}
|
||||
|
||||
.splash-root[data-theme="horizon"] .splash-progress-track {
|
||||
height: 2px;
|
||||
border: none;
|
||||
background: rgba(210, 232, 255, 0.14);
|
||||
}
|
||||
|
||||
.splash-root[data-theme="constellation"] .splash-progress-track {
|
||||
height: 6px;
|
||||
background: repeating-linear-gradient(
|
||||
90deg,
|
||||
rgba(135, 188, 242, 0.18) 0 12px,
|
||||
rgba(6, 15, 30, 0.7) 12px 16px
|
||||
);
|
||||
}
|
||||
|
||||
.splash-progress-fill {
|
||||
position: relative;
|
||||
height: 100%;
|
||||
@@ -461,20 +474,6 @@ const SPLASH_CSS = `
|
||||
box-shadow: 0 0 14px rgba(105, 198, 255, 0.55);
|
||||
}
|
||||
|
||||
.splash-root[data-theme="constellation"] .splash-progress-fill {
|
||||
background: repeating-linear-gradient(
|
||||
90deg,
|
||||
#77cfff 0 12px,
|
||||
transparent 12px 16px
|
||||
);
|
||||
box-shadow: 0 0 12px rgba(105, 206, 255, 0.45);
|
||||
}
|
||||
|
||||
.splash-root[data-theme="horizon"] .splash-progress-fill {
|
||||
background: linear-gradient(90deg, rgba(84, 165, 255, 0.55) 0%, #c4e4ff 70%, #ffffff 100%);
|
||||
box-shadow: 0 0 16px rgba(196, 228, 255, 0.72);
|
||||
}
|
||||
|
||||
.splash-progress-fill::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
@@ -594,7 +593,6 @@ export function createDesktopSplashController(options: {
|
||||
let progressFillEl: HTMLDivElement | null = null
|
||||
let stageEl: HTMLSpanElement | null = null
|
||||
let percentEl: HTMLSpanElement | null = null
|
||||
let switcherButtons: HTMLButtonElement[] = []
|
||||
|
||||
let rafId = 0
|
||||
let statusObserver: MutationObserver | null = null
|
||||
@@ -667,7 +665,6 @@ export function createDesktopSplashController(options: {
|
||||
progressFillEl = null
|
||||
stageEl = null
|
||||
percentEl = null
|
||||
switcherButtons = []
|
||||
exitStartTime = 0
|
||||
}
|
||||
|
||||
@@ -685,11 +682,6 @@ export function createDesktopSplashController(options: {
|
||||
if (hostEl) {
|
||||
hostEl.dataset.splashTheme = nextTheme
|
||||
}
|
||||
for (const btn of switcherButtons) {
|
||||
const match = btn.dataset.splashSwitch === nextTheme
|
||||
btn.classList.toggle('is-active', match)
|
||||
btn.setAttribute('aria-pressed', String(match))
|
||||
}
|
||||
}
|
||||
|
||||
const notifyFirstPaintOnce = () => {
|
||||
@@ -764,11 +756,6 @@ export function createDesktopSplashController(options: {
|
||||
<span>PLANET EARTH // HOLOGRAPHIC PERCEPTION KERNEL</span>
|
||||
</div>
|
||||
<div class="splash-controls">
|
||||
<div class="splash-switcher" role="group" aria-label="启动画面方案">
|
||||
<button type="button" class="splash-pill" data-splash-switch="singularity">01 星核</button>
|
||||
<button type="button" class="splash-pill" data-splash-switch="constellation">02 星轨</button>
|
||||
<button type="button" class="splash-pill" data-splash-switch="horizon">03 破晓</button>
|
||||
</div>
|
||||
<button type="button" class="splash-skip" data-splash-skip title="跳过启动动画 (Esc)">ESC 跳过</button>
|
||||
</div>
|
||||
</header>
|
||||
@@ -792,7 +779,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>
|
||||
@@ -807,23 +794,6 @@ export function createDesktopSplashController(options: {
|
||||
progressFillEl = root.querySelector('[data-splash-fill]')
|
||||
stageEl = root.querySelector('[data-splash-stage]')
|
||||
percentEl = root.querySelector('[data-splash-percent]')
|
||||
switcherButtons = Array.from(root.querySelectorAll('[data-splash-switch]'))
|
||||
|
||||
for (const btn of switcherButtons) {
|
||||
btn.addEventListener('click', (event) => {
|
||||
event.stopPropagation()
|
||||
const picked = btn.dataset.splashSwitch
|
||||
if (isActiveTheme(picked)) {
|
||||
preferredTheme = picked
|
||||
options.onSelectTheme(picked)
|
||||
if (sessionMode === 'boot' && !startupReady) {
|
||||
setActiveThemeVisual(picked)
|
||||
} else {
|
||||
startSplashSession(picked, 'replay')
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const skipBtn = root.querySelector('[data-splash-skip]')
|
||||
skipBtn?.addEventListener('click', (event) => {
|
||||
@@ -932,7 +902,7 @@ export function createDesktopSplashController(options: {
|
||||
cx: number,
|
||||
cy: number,
|
||||
) => {
|
||||
const warp = exitRatio > 0 && activeTheme === 'singularity' ? exitRatio * exitRatio : 0
|
||||
const warp = exitRatio > 0 ? exitRatio * exitRatio : 0
|
||||
for (const star of stars) {
|
||||
const sx = star.x * w
|
||||
const sy = star.y * h
|
||||
@@ -960,7 +930,7 @@ export function createDesktopSplashController(options: {
|
||||
}
|
||||
}
|
||||
|
||||
const drawSingularityScene = (
|
||||
const drawDawnToSingularityScene = (
|
||||
ctx: CanvasRenderingContext2D,
|
||||
w: number,
|
||||
h: number,
|
||||
@@ -971,57 +941,115 @@ export function createDesktopSplashController(options: {
|
||||
progress: number,
|
||||
exitRatio: number,
|
||||
) => {
|
||||
const burst = exitRatio > 0 ? Math.pow(exitRatio, 1.4) : 0
|
||||
const fade = 1 - Math.pow(exitRatio, 2.2)
|
||||
const { dawnIntensity, coreReveal, orbitReveal, arcReveal, burst, fade } =
|
||||
computeSplashMorphPhases(progress, exitRatio)
|
||||
|
||||
// Deep holographic ambient halo
|
||||
const glow = ctx.createRadialGradient(cx, cy, radius * 0.12, cx, cy, radius * (1.75 + burst * 1.4))
|
||||
glow.addColorStop(0, `rgba(66, 152, 255, ${(0.28 * fade).toFixed(3)})`)
|
||||
glow.addColorStop(0.52, `rgba(48, 128, 228, ${(0.11 * fade).toFixed(3)})`)
|
||||
glow.addColorStop(1, 'rgba(2, 4, 10, 0)')
|
||||
ctx.fillStyle = glow
|
||||
ctx.beginPath()
|
||||
ctx.arc(cx, cy, radius * (1.85 + burst * 1.4), 0, Math.PI * 2)
|
||||
ctx.fill()
|
||||
const perspD = 3.6
|
||||
const perspK = 3.25
|
||||
const tiltX = -0.25
|
||||
const rollZ = -0.11
|
||||
const yaw = (108 * Math.PI) / 180 + elapsed * (0.26 + coreReveal * 0.42 + burst * 2.1)
|
||||
const eclipseR = radius * 0.955
|
||||
const coronaOffsetAngle = -Math.PI * 0.68 + progress * Math.PI * 0.45
|
||||
|
||||
// Tilted orbital rings accelerating cleanly toward phase lock
|
||||
const yaw = (108 * Math.PI) / 180 + elapsed * (0.42 + progress * 0.48 + burst * 2.2)
|
||||
const ringConfigs = [
|
||||
{ rx: radius * (1.36 + burst * 1.6), ry: radius * (0.4 + burst * 0.5), rot: -0.34, color: '116, 206, 255' },
|
||||
{ rx: radius * (1.56 + burst * 2.0), ry: radius * (0.5 + burst * 0.6), rot: 0.42, color: '146, 184, 255' },
|
||||
{ rx: radius * (1.18 + burst * 1.3), ry: radius * (0.34 + burst * 0.4), rot: 0.08, color: '214, 240, 255' },
|
||||
]
|
||||
for (let i = 0; i < ringConfigs.length; i += 1) {
|
||||
const ring = ringConfigs[i]
|
||||
ctx.save()
|
||||
ctx.translate(cx, cy)
|
||||
ctx.rotate(ring.rot + elapsed * 0.08 * (i % 2 === 0 ? 1 : -1))
|
||||
ctx.strokeStyle = `rgba(${ring.color}, ${(0.28 * fade).toFixed(3)})`
|
||||
ctx.lineWidth = 1.15
|
||||
// Act 1 -> Act 2: Eclipse atmospheric corona cross-dissolves into deep holographic halo
|
||||
if (dawnIntensity > 0.01) {
|
||||
const lx = cx + Math.cos(coronaOffsetAngle) * eclipseR * 0.72
|
||||
const ly = cy + Math.sin(coronaOffsetAngle) * eclipseR * 0.72
|
||||
const coronaAlpha = dawnIntensity * fade
|
||||
const corona = ctx.createRadialGradient(lx, ly, eclipseR * 0.15, cx, cy, eclipseR * (1.9 + burst * 1.4))
|
||||
corona.addColorStop(0, `rgba(238, 249, 255, ${(0.9 * coronaAlpha).toFixed(3)})`)
|
||||
corona.addColorStop(0.28, `rgba(136, 208, 255, ${(0.5 * coronaAlpha).toFixed(3)})`)
|
||||
corona.addColorStop(0.62, `rgba(48, 118, 212, ${(0.15 * coronaAlpha).toFixed(3)})`)
|
||||
corona.addColorStop(1, 'rgba(1, 3, 8, 0)')
|
||||
ctx.fillStyle = corona
|
||||
ctx.beginPath()
|
||||
ctx.ellipse(0, 0, ring.rx, ring.ry, 0, 0, Math.PI * 2)
|
||||
ctx.stroke()
|
||||
|
||||
// Moving orbital shard beacon along ellipse
|
||||
const a = elapsed * (1.2 + i * 0.45) + i * 2.1
|
||||
const sx = Math.cos(a) * ring.rx
|
||||
const sy = Math.sin(a) * ring.ry
|
||||
ctx.fillStyle = `rgba(225, 247, 255, ${(0.92 * fade).toFixed(3)})`
|
||||
ctx.beginPath()
|
||||
ctx.arc(sx, sy, 2.6 + burst * 1.5, 0, Math.PI * 2)
|
||||
ctx.arc(cx, cy, eclipseR * (1.95 + burst * 1.4), 0, Math.PI * 2)
|
||||
ctx.fill()
|
||||
ctx.restore()
|
||||
}
|
||||
|
||||
// 3D Holographic Earth point cloud + burst explosion streaks
|
||||
const tiltX = -0.26
|
||||
const rollZ = -0.14
|
||||
const perspD = 3.1
|
||||
if (coreReveal > 0.01) {
|
||||
const haloAlpha = coreReveal * fade
|
||||
const glow = ctx.createRadialGradient(cx, cy, radius * 0.12, cx, cy, radius * (1.75 + burst * 1.4))
|
||||
glow.addColorStop(0, `rgba(66, 152, 255, ${(0.28 * haloAlpha).toFixed(3)})`)
|
||||
glow.addColorStop(0.52, `rgba(48, 128, 228, ${(0.11 * haloAlpha).toFixed(3)})`)
|
||||
glow.addColorStop(1, 'rgba(2, 4, 10, 0)')
|
||||
ctx.fillStyle = glow
|
||||
ctx.beginPath()
|
||||
ctx.arc(cx, cy, radius * (1.85 + burst * 1.4), 0, Math.PI * 2)
|
||||
ctx.fill()
|
||||
}
|
||||
|
||||
// Act 1 silhouette & luminous dawn limb hugging the sphere edge cleanly without shadowBlur
|
||||
if (dawnIntensity > 0.01) {
|
||||
const lx = cx + Math.cos(coronaOffsetAngle) * eclipseR * 0.72
|
||||
const ly = cy + Math.sin(coronaOffsetAngle) * eclipseR * 0.72
|
||||
const discAlpha = dawnIntensity * fade
|
||||
const discGrad = ctx.createRadialGradient(lx, ly, eclipseR * 0.55, cx, cy, eclipseR)
|
||||
discGrad.addColorStop(0, `rgba(8, 22, 42, ${(0.94 * discAlpha).toFixed(3)})`)
|
||||
discGrad.addColorStop(1, `rgba(2, 6, 14, ${(0.98 * discAlpha).toFixed(3)})`)
|
||||
ctx.fillStyle = discGrad
|
||||
ctx.beginPath()
|
||||
ctx.arc(cx, cy, eclipseR * 0.99, 0, Math.PI * 2)
|
||||
ctx.fill()
|
||||
|
||||
const arcStart = coronaOffsetAngle - 0.88
|
||||
const arcEnd = coronaOffsetAngle + 0.88
|
||||
ctx.strokeStyle = `rgba(148, 214, 255, ${(0.24 * discAlpha).toFixed(3)})`
|
||||
ctx.lineWidth = 7
|
||||
ctx.beginPath()
|
||||
ctx.arc(cx, cy, eclipseR, arcStart, arcEnd)
|
||||
ctx.stroke()
|
||||
|
||||
ctx.strokeStyle = `rgba(226, 246, 255, ${(0.92 * discAlpha).toFixed(3)})`
|
||||
ctx.lineWidth = 2.3
|
||||
ctx.beginPath()
|
||||
ctx.arc(cx, cy, eclipseR, arcStart, arcEnd)
|
||||
ctx.stroke()
|
||||
}
|
||||
|
||||
// Act 2: Three tilted orbital rings drawing into full orbits, expanding on Act 3 burst
|
||||
if (orbitReveal > 0.01) {
|
||||
const ringConfigs = [
|
||||
{ rx: radius * (1.36 + burst * 1.6), ry: radius * (0.4 + burst * 0.5), rot: -0.34, color: '116, 206, 255' },
|
||||
{ rx: radius * (1.56 + burst * 2.0), ry: radius * (0.5 + burst * 0.6), rot: 0.42, color: '146, 184, 255' },
|
||||
{ rx: radius * (1.18 + burst * 1.3), ry: radius * (0.34 + burst * 0.4), rot: 0.08, color: '214, 240, 255' },
|
||||
]
|
||||
for (let i = 0; i < ringConfigs.length; i += 1) {
|
||||
const ringReveal = clamp01((orbitReveal - i * 0.1) / 0.8)
|
||||
if (ringReveal <= 0.005) continue
|
||||
const ring = ringConfigs[i]
|
||||
const a = elapsed * (1.2 + i * 0.45) + i * 2.1
|
||||
|
||||
ctx.save()
|
||||
ctx.translate(cx, cy)
|
||||
ctx.rotate(ring.rot + elapsed * 0.08 * (i % 2 === 0 ? 1 : -1))
|
||||
ctx.strokeStyle = `rgba(${ring.color}, ${(0.28 * ringReveal * fade).toFixed(3)})`
|
||||
ctx.lineWidth = 1.15
|
||||
ctx.beginPath()
|
||||
if (ringReveal >= 0.995) {
|
||||
ctx.ellipse(0, 0, ring.rx, ring.ry, 0, 0, Math.PI * 2)
|
||||
} else {
|
||||
ctx.ellipse(0, 0, ring.rx, ring.ry, 0, a - ringReveal * Math.PI * 2, a)
|
||||
}
|
||||
ctx.stroke()
|
||||
|
||||
const sx = Math.cos(a) * ring.rx
|
||||
const sy = Math.sin(a) * ring.ry
|
||||
ctx.fillStyle = `rgba(225, 247, 255, ${(0.92 * ringReveal * fade).toFixed(3)})`
|
||||
ctx.beginPath()
|
||||
ctx.arc(sx, sy, 2.6 + burst * 1.5, 0, Math.PI * 2)
|
||||
ctx.fill()
|
||||
ctx.restore()
|
||||
}
|
||||
}
|
||||
|
||||
// Shared 3D globe point cloud: Dawn coastline lights -> full holographic sphere -> radial scatter
|
||||
const oceanReveal = clamp01((coreReveal - 0.25) / 0.75)
|
||||
for (const pt of globePoints) {
|
||||
const p = projectSpherePoint(pt.lat, pt.lon, yaw, tiltX, rollZ)
|
||||
if (burst === 0 && p.nz < -0.22) continue
|
||||
|
||||
// On explosion, scatter outward radially & toward camera
|
||||
const radialBoost = 1 + burst * (1.6 + pt.shardSpeed * 2.8)
|
||||
const jitterX = Math.cos(pt.shardAngle) * burst * 0.28
|
||||
const jitterY = Math.sin(pt.shardAngle) * burst * 0.28
|
||||
@@ -1030,7 +1058,7 @@ export function createDesktopSplashController(options: {
|
||||
const pz = p.nz + burst * pt.shardSpeed * 1.1
|
||||
|
||||
const depth = Math.max(0.25, perspD - pz)
|
||||
const screenScale = (radius * (perspD - 0.6)) / depth
|
||||
const screenScale = (radius * perspK) / depth
|
||||
const sx = cx + px * screenScale
|
||||
const sy = cy + py * screenScale
|
||||
if (sx < -60 || sx > w + 60 || sy < -60 || sy > h + 60) continue
|
||||
@@ -1038,23 +1066,29 @@ export function createDesktopSplashController(options: {
|
||||
const depthFade = p.nz >= 0 ? 1 : Math.max(0.14, 1 + p.nz * 2.2)
|
||||
const polarFade = Math.abs(pt.lat) > 1.14 ? 0.36 : 1
|
||||
let color = '84, 146, 232'
|
||||
let baseAlpha = 0.28
|
||||
let pointGain = 0
|
||||
let dotR = 1.1
|
||||
if (pt.kind === 2) {
|
||||
color = '196, 240, 255'
|
||||
baseAlpha = 0.94
|
||||
dotR = 1.75
|
||||
const dawnShimmer = 0.45 + 0.55 * Math.sin(elapsed * 1.8 + pt.phase)
|
||||
const dawnWeight = p.nz > 0.06 ? dawnIntensity * 0.58 * p.nz * dawnShimmer : 0
|
||||
const coreWeight = coreReveal * 0.94 * depthFade
|
||||
pointGain = Math.max(dawnWeight, coreWeight)
|
||||
dotR = 1.45 + coreReveal * 0.3
|
||||
} else if (pt.kind === 1) {
|
||||
color = '106, 188, 255'
|
||||
baseAlpha = 0.56
|
||||
pointGain = coreReveal * 0.56 * depthFade
|
||||
dotR = 1.3
|
||||
} else {
|
||||
pointGain = oceanReveal * 0.28 * depthFade
|
||||
}
|
||||
const alpha = baseAlpha * depthFade * polarFade * fade
|
||||
|
||||
const alpha = pointGain * polarFade * fade
|
||||
if (alpha <= 0.015) continue
|
||||
|
||||
if (burst > 0.03) {
|
||||
const prevBoost = Math.max(1, radialBoost - 0.36 * pt.shardSpeed * burst)
|
||||
const prevScale = (radius * (perspD - 0.6)) / Math.max(0.3, perspD - p.nz)
|
||||
const prevScale = (radius * perspK) / Math.max(0.3, perspD - p.nz)
|
||||
const ox = cx + p.nx * prevBoost * prevScale
|
||||
const oy = cy + p.ny * prevBoost * prevScale
|
||||
ctx.strokeStyle = `rgba(${color}, ${Math.min(1, alpha * 1.15).toFixed(3)})`
|
||||
@@ -1071,8 +1105,9 @@ export function createDesktopSplashController(options: {
|
||||
}
|
||||
}
|
||||
|
||||
// Great-circle telemetry arcs across front hemisphere
|
||||
if (burst < 0.55) {
|
||||
// Intercontinental telemetry arcs across front hemisphere
|
||||
if (arcReveal > 0.01 && burst < 0.55) {
|
||||
const arcAlpha = arcReveal * fade * Math.max(0, 1 - burst * 1.6)
|
||||
for (const arc of ARC_DEFINITIONS) {
|
||||
const p1 = projectSpherePoint((arc.lat1 * Math.PI) / 180, (arc.lon1 * Math.PI) / 180, yaw, tiltX, rollZ)
|
||||
const p2 = projectSpherePoint((arc.lat2 * Math.PI) / 180, (arc.lon2 * Math.PI) / 180, yaw, tiltX, rollZ)
|
||||
@@ -1088,7 +1123,7 @@ export function createDesktopSplashController(options: {
|
||||
const cpx = cx + mx * radius * lift
|
||||
const cpy = cy + my * radius * lift
|
||||
|
||||
ctx.strokeStyle = `rgba(128, 214, 255, ${(0.34 * fade).toFixed(3)})`
|
||||
ctx.strokeStyle = `rgba(128, 214, 255, ${(0.34 * arcAlpha).toFixed(3)})`
|
||||
ctx.lineWidth = 1.25
|
||||
ctx.beginPath()
|
||||
ctx.moveTo(x1, y1)
|
||||
@@ -1099,14 +1134,14 @@ export function createDesktopSplashController(options: {
|
||||
const inv = 1 - u
|
||||
const px = inv * inv * x1 + 2 * inv * u * cpx + u * u * x2
|
||||
const py = inv * inv * y1 + 2 * inv * u * cpy + u * u * y2
|
||||
ctx.fillStyle = `rgba(235, 250, 255, ${(0.95 * fade).toFixed(3)})`
|
||||
ctx.fillStyle = `rgba(235, 250, 255, ${(0.95 * arcAlpha).toFixed(3)})`
|
||||
ctx.beginPath()
|
||||
ctx.arc(px, py, 2.2, 0, Math.PI * 2)
|
||||
ctx.fill()
|
||||
}
|
||||
}
|
||||
|
||||
// Shockwave ring on climax burst
|
||||
// Act 3: Climax shockwave ring on scatter burst
|
||||
if (burst > 0.005) {
|
||||
const shockR = radius * (0.88 + exitRatio * 5.2)
|
||||
ctx.strokeStyle = `rgba(168, 228, 255, ${(0.72 * (1 - exitRatio)).toFixed(3)})`
|
||||
@@ -1117,203 +1152,16 @@ export function createDesktopSplashController(options: {
|
||||
}
|
||||
}
|
||||
|
||||
const drawConstellationScene = (
|
||||
ctx: CanvasRenderingContext2D,
|
||||
_w: number,
|
||||
_h: number,
|
||||
cx: number,
|
||||
cy: number,
|
||||
radius: number,
|
||||
elapsed: number,
|
||||
progress: number,
|
||||
exitRatio: number,
|
||||
) => {
|
||||
const irisScale = 1 + Math.pow(exitRatio, 1.55) * 2.1
|
||||
const fade = 1 - Math.pow(exitRatio, 1.8)
|
||||
const yaw = (108 * Math.PI) / 180 + elapsed * 0.34
|
||||
|
||||
// Outer calibrated compass reticle rings
|
||||
ctx.save()
|
||||
ctx.translate(cx, cy)
|
||||
ctx.scale(irisScale, irisScale)
|
||||
|
||||
const outerR = radius * 1.42
|
||||
const midR = radius * 1.2
|
||||
ctx.strokeStyle = `rgba(130, 198, 255, ${(0.22 * fade).toFixed(3)})`
|
||||
ctx.lineWidth = 1
|
||||
ctx.beginPath()
|
||||
ctx.arc(0, 0, outerR, 0, Math.PI * 2)
|
||||
ctx.stroke()
|
||||
|
||||
ctx.strokeStyle = `rgba(154, 214, 255, ${(0.36 * fade).toFixed(3)})`
|
||||
ctx.setLineDash([4, 6])
|
||||
ctx.beginPath()
|
||||
ctx.arc(0, 0, midR, -elapsed * 0.25, -elapsed * 0.25 + Math.PI * 1.65)
|
||||
ctx.stroke()
|
||||
ctx.setLineDash([])
|
||||
|
||||
// Progress calibration arc
|
||||
const sweepAngle = Math.max(0.08, progress * Math.PI * 2)
|
||||
ctx.strokeStyle = `rgba(126, 222, 255, ${(0.88 * fade).toFixed(3)})`
|
||||
ctx.lineWidth = 2.1
|
||||
ctx.beginPath()
|
||||
ctx.arc(0, 0, radius * 1.29, -Math.PI / 2, -Math.PI / 2 + sweepAngle)
|
||||
ctx.stroke()
|
||||
|
||||
// 72 degree graduation ticks
|
||||
for (let deg = 0; deg < 360; deg += 5) {
|
||||
const rad = (deg * Math.PI) / 180 + elapsed * 0.05
|
||||
const major = deg % 30 === 0
|
||||
const len = major ? 9 : 4
|
||||
ctx.strokeStyle = `rgba(170, 216, 255, ${((major ? 0.55 : 0.22) * fade).toFixed(3)})`
|
||||
ctx.lineWidth = major ? 1.3 : 0.85
|
||||
ctx.beginPath()
|
||||
ctx.moveTo(Math.cos(rad) * (outerR - len), Math.sin(rad) * (outerR - len))
|
||||
ctx.lineTo(Math.cos(rad) * outerR, Math.sin(rad) * outerR)
|
||||
ctx.stroke()
|
||||
}
|
||||
|
||||
// Precision meridian & equator CAD wireframe + continental points
|
||||
ctx.strokeStyle = `rgba(104, 178, 245, ${(0.22 * fade).toFixed(3)})`
|
||||
ctx.lineWidth = 0.9
|
||||
ctx.beginPath()
|
||||
ctx.arc(0, 0, radius, 0, Math.PI * 2)
|
||||
ctx.stroke()
|
||||
for (const tilt of [-0.55, 0, 0.55]) {
|
||||
ctx.beginPath()
|
||||
ctx.ellipse(0, 0, radius * Math.abs(Math.cos(tilt)), radius, 0, 0, Math.PI * 2)
|
||||
ctx.stroke()
|
||||
}
|
||||
|
||||
for (const pt of globePoints) {
|
||||
if (pt.kind === 0) continue
|
||||
const p = projectSpherePoint(pt.lat, pt.lon, yaw, -0.24, 0)
|
||||
if (p.nz < 0) continue
|
||||
const sx = p.nx * radius
|
||||
const sy = p.ny * radius
|
||||
const isCoast = pt.kind === 2
|
||||
const polarFade = Math.abs(pt.lat) > 1.14 ? 0.35 : 1
|
||||
ctx.fillStyle = isCoast
|
||||
? `rgba(216, 246, 255, ${(0.92 * polarFade * fade).toFixed(3)})`
|
||||
: `rgba(106, 186, 255, ${(0.42 * polarFade * fade).toFixed(3)})`
|
||||
ctx.fillRect(sx - (isCoast ? 1 : 0.7), sy - (isCoast ? 1 : 0.7), isCoast ? 2 : 1.4, isCoast ? 2 : 1.4)
|
||||
}
|
||||
|
||||
// Hangzhou target crosshair lock when front-facing
|
||||
const hz = projectSpherePoint((30.27 * Math.PI) / 180, (120.15 * Math.PI) / 180, yaw, -0.24, 0)
|
||||
if (hz.nz > 0.1) {
|
||||
const hx = hz.nx * radius
|
||||
const hy = hz.ny * radius
|
||||
ctx.strokeStyle = `rgba(255, 255, 255, ${(0.88 * fade).toFixed(3)})`
|
||||
ctx.lineWidth = 1.2
|
||||
ctx.strokeRect(hx - 6, hy - 6, 12, 12)
|
||||
ctx.beginPath()
|
||||
ctx.moveTo(hx - 12, hy)
|
||||
ctx.lineTo(hx + 12, hy)
|
||||
ctx.moveTo(hx, hy - 12)
|
||||
ctx.lineTo(hx, hy + 12)
|
||||
ctx.stroke()
|
||||
}
|
||||
|
||||
// Keplerian satellites
|
||||
for (let i = 0; i < 3; i += 1) {
|
||||
ctx.save()
|
||||
ctx.rotate(-0.5 + i * 0.55)
|
||||
const rx = radius * 1.48
|
||||
const ry = radius * 0.42
|
||||
ctx.strokeStyle = `rgba(136, 206, 255, ${(0.24 * fade).toFixed(3)})`
|
||||
ctx.lineWidth = 0.9
|
||||
ctx.beginPath()
|
||||
ctx.ellipse(0, 0, rx, ry, 0, 0, Math.PI * 2)
|
||||
ctx.stroke()
|
||||
|
||||
const theta = elapsed * (0.9 + i * 0.35) + i * 1.9
|
||||
const sx = Math.cos(theta) * rx
|
||||
const sy = Math.sin(theta) * ry
|
||||
ctx.fillStyle = `rgba(232, 249, 255, ${(0.95 * fade).toFixed(3)})`
|
||||
ctx.beginPath()
|
||||
ctx.arc(sx, sy, 3, 0, Math.PI * 2)
|
||||
ctx.fill()
|
||||
ctx.restore()
|
||||
}
|
||||
|
||||
ctx.restore()
|
||||
}
|
||||
|
||||
const drawHorizonScene = (
|
||||
ctx: CanvasRenderingContext2D,
|
||||
_w: number,
|
||||
_h: number,
|
||||
cx: number,
|
||||
cy: number,
|
||||
radius: number,
|
||||
elapsed: number,
|
||||
progress: number,
|
||||
exitRatio: number,
|
||||
) => {
|
||||
const fade = 1 - Math.pow(exitRatio, 2.0)
|
||||
const bloom = 1 + exitRatio * 0.55
|
||||
const yaw = (108 * Math.PI) / 180 + elapsed * 0.24
|
||||
const r = radius * 1.06 * bloom
|
||||
|
||||
// Volumetric atmospheric crescent corona behind dark planet
|
||||
const coronaOffsetAngle = -Math.PI * 0.65 + progress * Math.PI * 0.38
|
||||
const lx = cx + Math.cos(coronaOffsetAngle) * r * 0.72
|
||||
const ly = cy + Math.sin(coronaOffsetAngle) * r * 0.72
|
||||
const corona = ctx.createRadialGradient(lx, ly, r * 0.15, cx, cy, r * (1.85 + exitRatio * 1.4))
|
||||
corona.addColorStop(0, `rgba(238, 249, 255, ${(0.92 * fade).toFixed(3)})`)
|
||||
corona.addColorStop(0.28, `rgba(136, 208, 255, ${(0.52 * fade).toFixed(3)})`)
|
||||
corona.addColorStop(0.62, `rgba(48, 118, 212, ${(0.16 * fade).toFixed(3)})`)
|
||||
corona.addColorStop(1, 'rgba(1, 3, 8, 0)')
|
||||
ctx.fillStyle = corona
|
||||
ctx.beginPath()
|
||||
ctx.arc(cx, cy, r * (1.9 + exitRatio * 1.4), 0, Math.PI * 2)
|
||||
ctx.fill()
|
||||
|
||||
// Planetary shadow disc eclipsing the sun
|
||||
const discGrad = ctx.createRadialGradient(lx, ly, r * 0.55, cx, cy, r)
|
||||
discGrad.addColorStop(0, `rgba(8, 22, 42, ${(0.94 * fade).toFixed(3)})`)
|
||||
discGrad.addColorStop(1, `rgba(2, 6, 14, ${(0.98 * fade).toFixed(3)})`)
|
||||
ctx.fillStyle = discGrad
|
||||
ctx.beginPath()
|
||||
ctx.arc(cx, cy, r * 0.99, 0, Math.PI * 2)
|
||||
ctx.fill()
|
||||
|
||||
// Crisp luminous terminator limb sweep following progress
|
||||
ctx.save()
|
||||
ctx.strokeStyle = `rgba(222, 245, 255, ${(0.92 * fade).toFixed(3)})`
|
||||
ctx.lineWidth = 2.4
|
||||
ctx.shadowColor = 'rgba(148, 214, 255, 0.95)'
|
||||
ctx.shadowBlur = 18
|
||||
ctx.beginPath()
|
||||
ctx.arc(cx, cy, r, coronaOffsetAngle - 0.85, coronaOffsetAngle + 0.85)
|
||||
ctx.stroke()
|
||||
ctx.restore()
|
||||
|
||||
// Subtle night-side coastline lights glimmering across the shadowed face
|
||||
for (const pt of globePoints) {
|
||||
if (pt.kind !== 2) continue
|
||||
const p = projectSpherePoint(pt.lat, pt.lon, yaw, -0.24, -0.08)
|
||||
if (p.nz < 0.08) continue
|
||||
const shimmer = 0.45 + 0.55 * Math.sin(elapsed * 1.8 + pt.phase)
|
||||
const polarFade = Math.abs(pt.lat) > 1.14 ? 0.35 : 1
|
||||
const alpha = 0.56 * p.nz * shimmer * polarFade * fade
|
||||
if (alpha <= 0.02) continue
|
||||
ctx.fillStyle = `rgba(176, 224, 255, ${alpha.toFixed(3)})`
|
||||
ctx.beginPath()
|
||||
ctx.arc(cx + p.nx * r * 0.96, cy + p.ny * r * 0.96, 1.4, 0, Math.PI * 2)
|
||||
ctx.fill()
|
||||
}
|
||||
}
|
||||
|
||||
const renderSceneFrame = (now: number, clampedProgress: number, exitRatio: number) => {
|
||||
if (!canvasEl || !rootEl) return
|
||||
|
||||
const dpr = Math.min(window.devicePixelRatio || 1, 2)
|
||||
const width = window.innerWidth || 1280
|
||||
const height = window.innerHeight || 800
|
||||
const targetCanvasW = Math.max(1, Math.round(width * dpr))
|
||||
const targetCanvasH = Math.max(1, Math.round(height * dpr))
|
||||
const { dpr, width: targetCanvasW, height: targetCanvasH } = computeSplashCanvasSize(
|
||||
width,
|
||||
height,
|
||||
window.devicePixelRatio || 1,
|
||||
)
|
||||
if (canvasEl.width !== targetCanvasW || canvasEl.height !== targetCanvasH) {
|
||||
canvasEl.width = targetCanvasW
|
||||
canvasEl.height = targetCanvasH
|
||||
@@ -1347,7 +1195,7 @@ export function createDesktopSplashController(options: {
|
||||
const radius = Math.max(82, Math.min(width * 0.24, height * 0.21, 196))
|
||||
|
||||
if (exitRatio > 0) {
|
||||
if (reducedMotion || activeTheme === 'horizon') {
|
||||
if (reducedMotion) {
|
||||
rootEl.style.opacity = `${Math.max(0, 1 - Math.pow(exitRatio, 1.35)).toFixed(3)}`
|
||||
} else {
|
||||
// Portal cutout expands from center while particle bursts continue radiating over edges
|
||||
@@ -1365,13 +1213,7 @@ export function createDesktopSplashController(options: {
|
||||
ctx.setTransform(dpr, 0, 0, dpr, 0, 0)
|
||||
ctx.clearRect(0, 0, width, height)
|
||||
drawStars(ctx, width, height, elapsedSec, exitRatio, cx, cy)
|
||||
if (activeTheme === 'singularity') {
|
||||
drawSingularityScene(ctx, width, height, cx, cy, radius, elapsedSec, clampedProgress, exitRatio)
|
||||
} else if (activeTheme === 'constellation') {
|
||||
drawConstellationScene(ctx, width, height, cx, cy, radius, elapsedSec, clampedProgress, exitRatio)
|
||||
} else {
|
||||
drawHorizonScene(ctx, width, height, cx, cy, radius, elapsedSec, clampedProgress, exitRatio)
|
||||
}
|
||||
drawDawnToSingularityScene(ctx, width, height, cx, cy, radius, elapsedSec, clampedProgress, exitRatio)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1463,13 +1305,7 @@ export function createDesktopSplashController(options: {
|
||||
}
|
||||
|
||||
const clampedProgress = Math.max(0, Math.min(1, displayProgress))
|
||||
const exitDuration = reducedMotion
|
||||
? 300
|
||||
: activeTheme === 'singularity'
|
||||
? 920
|
||||
: activeTheme === 'constellation'
|
||||
? 860
|
||||
: 900
|
||||
const exitDuration = reducedMotion ? 300 : 940
|
||||
const exitRatio = exitStartTime > 0 ? Math.min(1, (now - exitStartTime) / exitDuration) : 0
|
||||
|
||||
renderSceneFrame(now, clampedProgress, exitRatio)
|
||||
|
||||
@@ -0,0 +1,468 @@
|
||||
import { mkdtempSync, rmSync } from 'node:fs'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
|
||||
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 by default', () => {
|
||||
const switches = resolveChromiumGpuSwitches({
|
||||
platform: 'win32',
|
||||
headlessSmoke: false,
|
||||
softwareGl: false,
|
||||
})
|
||||
const names = switches.map((entry) => entry.name)
|
||||
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',
|
||||
headlessSmoke: false,
|
||||
softwareGl: false,
|
||||
})
|
||||
expect(switches).toEqual([
|
||||
{ name: 'disable-renderer-backgrounding' },
|
||||
{ name: 'ozone-platform-hint', value: 'auto' },
|
||||
])
|
||||
})
|
||||
|
||||
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([
|
||||
{ name: 'disable-gpu' },
|
||||
{ name: 'use-gl', value: 'angle' },
|
||||
{ name: 'use-angle', value: 'swiftshader' },
|
||||
{ name: 'enable-unsafe-swiftshader' },
|
||||
])
|
||||
}
|
||||
})
|
||||
|
||||
test('isGpuProcessCrash detects unexpected GPU exits and ignores clean exits', () => {
|
||||
expect(isGpuProcessCrash({ type: 'GPU', reason: 'crashed' })).toBe(true)
|
||||
expect(isGpuProcessCrash({ type: 'GPU', reason: 'killed' })).toBe(true)
|
||||
expect(isGpuProcessCrash({ type: 'GPU', reason: 'clean-exit' })).toBe(false)
|
||||
expect(isGpuProcessCrash({ type: 'Utility', reason: 'crashed' })).toBe(false)
|
||||
expect(isGpuProcessCrash(null)).toBe(false)
|
||||
})
|
||||
|
||||
test('computeSplashCanvasSize preserves 1080p clarity while capping 4K splash buffers', () => {
|
||||
expect(computeSplashCanvasSize(1920, 1080, 1)).toEqual({
|
||||
dpr: 1,
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
})
|
||||
|
||||
const qhdScaled4k = computeSplashCanvasSize(2560, 1440, 1.5)
|
||||
expect(qhdScaled4k.dpr).toBeLessThan(1.5)
|
||||
expect(qhdScaled4k.width * qhdScaled4k.height).toBeLessThanOrEqual(1920 * 1080)
|
||||
|
||||
const native4k = computeSplashCanvasSize(3840, 2160, 1)
|
||||
expect(native4k.dpr).toBe(0.75)
|
||||
expect(native4k.width).toBe(2880)
|
||||
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'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,303 @@
|
||||
import crypto from 'node:crypto'
|
||||
import fs from 'node:fs'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import zlib from 'node:zlib'
|
||||
|
||||
import { afterEach, describe, expect, test } from 'bun:test'
|
||||
|
||||
import {
|
||||
PERIODIC_UPDATE_CHECK_INTERVAL_MS,
|
||||
compareSemver,
|
||||
evaluateUpdateDecision,
|
||||
getUpdatePromptKey,
|
||||
installHotfixArchive,
|
||||
markHotfixVerified,
|
||||
readHotfixState,
|
||||
resolveActiveEarthOverlay,
|
||||
resolveUpdateAssetUrl,
|
||||
rollbackPendingHotfix,
|
||||
shouldSuppressUpdatePrompt,
|
||||
} from '../src/main/hot-update-core'
|
||||
import { createEarthProtocolHandler } from '../src/main/protocol-core'
|
||||
import { createTarGz, extractTarGzSafely } from '../src/main/tar-gz'
|
||||
|
||||
const tempRoots: string[] = []
|
||||
|
||||
function makeTempDir(prefix: string): string {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix))
|
||||
tempRoots.push(dir)
|
||||
return dir
|
||||
}
|
||||
|
||||
function buildMaliciousTarGz(entryName: string, typeFlag = '0'): Buffer {
|
||||
const header = Buffer.alloc(512, 0)
|
||||
header.write(entryName, 0, 100, 'utf8')
|
||||
header.write('0000644\0', 100, 8, 'ascii')
|
||||
header.write('0000000\0', 108, 8, 'ascii')
|
||||
header.write('0000000\0', 116, 8, 'ascii')
|
||||
header.write('00000000000\0', 124, 12, 'ascii')
|
||||
header.write('00000000000\0', 136, 12, 'ascii')
|
||||
header.fill(0x20, 148, 156)
|
||||
header.write(typeFlag, 156, 1, 'ascii')
|
||||
header.write('ustar\0', 257, 6, 'ascii')
|
||||
header.write('00', 263, 2, 'ascii')
|
||||
let checksum = 0
|
||||
for (let i = 0; i < 512; i += 1) checksum += header[i]
|
||||
header.write(`${checksum.toString(8).padStart(6, '0')}\0 `, 148, 8, 'ascii')
|
||||
return zlib.gzipSync(Buffer.concat([header, Buffer.alloc(1024, 0)]))
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
while (tempRoots.length > 0) {
|
||||
const dir = tempRoots.pop()!
|
||||
fs.rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
describe('tar-gz archive creation and safe extraction', () => {
|
||||
test('round-trips files including nested js/css directories and long USTAR paths', () => {
|
||||
const outDir = makeTempDir('planet-tar-ok-')
|
||||
const longPath =
|
||||
'js/submodules/deeply/nested/component/folder/structure/extra-segment/another-segment/runtime-earth-worker-module-bundle.js'
|
||||
const archive = createTarGz([
|
||||
{ path: 'index.html', data: Buffer.from('<!doctype html><html><body>ok</body></html>') },
|
||||
{ path: 'css/theme.css', data: Buffer.from('body { color: #fff; }') },
|
||||
{ path: longPath, data: Buffer.from('export const ok = true;') },
|
||||
])
|
||||
|
||||
const result = extractTarGzSafely(archive, outDir)
|
||||
expect(result.files).toEqual(['css/theme.css', 'index.html', longPath])
|
||||
expect(fs.readFileSync(path.join(outDir, 'index.html'), 'utf8')).toContain('<body>ok</body>')
|
||||
expect(fs.readFileSync(path.join(outDir, longPath), 'utf8')).toBe('export const ok = true;')
|
||||
})
|
||||
|
||||
test('rejects path traversal, absolute paths, and symlink entries', () => {
|
||||
const outDir = makeTempDir('planet-tar-bad-')
|
||||
expect(() => createTarGz([{ path: '../escape.js', data: Buffer.from('x') }])).toThrow()
|
||||
expect(() => createTarGz([{ path: '/etc/passwd', data: Buffer.from('x') }])).toThrow()
|
||||
|
||||
expect(() => extractTarGzSafely(buildMaliciousTarGz('../escape.js', '0'), outDir)).toThrow()
|
||||
expect(() => extractTarGzSafely(buildMaliciousTarGz('/abs/path.js', '0'), outDir)).toThrow()
|
||||
expect(() => extractTarGzSafely(buildMaliciousTarGz('js/link.js', '2'), outDir)).toThrow()
|
||||
})
|
||||
})
|
||||
|
||||
describe('hot-update decision matrix, verification, rollback, and overlay protocol', () => {
|
||||
test('compareSemver and evaluateUpdateDecision select the exact right update tier', () => {
|
||||
expect(compareSemver('0.78.0', '0.78.0')).toBe(0)
|
||||
expect(compareSemver('0.78.1', '0.78.0')).toBe(1)
|
||||
expect(compareSemver('0.79.0', '0.78.9')).toBe(1)
|
||||
expect(compareSemver('v0.79.0', '0.79.0-beta.1')).toBe(1)
|
||||
|
||||
const validSha = 'a'.repeat(64)
|
||||
|
||||
expect(
|
||||
evaluateUpdateDecision({
|
||||
shellVersion: '0.78.0',
|
||||
activeBundleVersion: '0.78.0',
|
||||
blacklistedVersions: [],
|
||||
manifest: {
|
||||
shell: { version: '0.78.0', minRequired: '0.78.0', downloadUrl: 'https://gitea.rclaw.top/r' },
|
||||
bundle: null,
|
||||
},
|
||||
}),
|
||||
).toEqual({ kind: 'up-to-date' })
|
||||
|
||||
expect(
|
||||
evaluateUpdateDecision({
|
||||
shellVersion: '0.78.0',
|
||||
activeBundleVersion: '0.78.0',
|
||||
blacklistedVersions: [],
|
||||
manifest: {
|
||||
shell: { version: '0.78.0', minRequired: '0.78.0', downloadUrl: 'https://gitea.rclaw.top/r' },
|
||||
bundle: { version: '0.78.2', minShellVersion: '0.78.0', url: '/api/v1/client/updates/files/b.tar.gz', sha256: validSha },
|
||||
},
|
||||
}),
|
||||
).toMatchObject({ kind: 'hotfix-update', bundle: { version: '0.78.2' } })
|
||||
|
||||
expect(
|
||||
evaluateUpdateDecision({
|
||||
shellVersion: '0.78.0',
|
||||
activeBundleVersion: '0.78.2',
|
||||
blacklistedVersions: ['0.78.3'],
|
||||
manifest: {
|
||||
shell: { version: '0.79.0', minRequired: '0.79.0', downloadUrl: 'https://gitea.rclaw.top/r' },
|
||||
bundle: { version: '0.78.3', minShellVersion: '0.78.0', url: '/b.tar.gz', sha256: validSha },
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
kind: 'shell-update',
|
||||
mandatory: true,
|
||||
shell: { version: '0.79.0', minRequired: '0.79.0', downloadUrl: 'https://gitea.rclaw.top/r' },
|
||||
})
|
||||
|
||||
expect(
|
||||
evaluateUpdateDecision({
|
||||
shellVersion: '0.78.0',
|
||||
activeBundleVersion: '0.78.0',
|
||||
blacklistedVersions: [],
|
||||
manifest: {
|
||||
shell: { version: '0.79.0', minRequired: '0.78.0', downloadUrl: 'https://gitea.rclaw.top/r' },
|
||||
bundle: { version: '0.79.1', minShellVersion: '0.79.0', url: '/b.tar.gz', sha256: validSha },
|
||||
},
|
||||
}),
|
||||
).toMatchObject({ kind: 'shell-update', mandatory: false })
|
||||
|
||||
expect(resolveUpdateAssetUrl('/api/v1/client/updates/files/a.tar.gz', 'https://rclaw.top/sub')).toBe(
|
||||
'https://rclaw.top/api/v1/client/updates/files/a.tar.gz',
|
||||
)
|
||||
})
|
||||
|
||||
test('verifies SHA-256 on install, marks verified on ready, and auto-rolls back failing pending bundles', () => {
|
||||
const userDataDir = makeTempDir('planet-hotfix-state-')
|
||||
|
||||
const goodV1Archive = createTarGz([
|
||||
{ path: 'index.html', data: Buffer.from('<html>v1</html>') },
|
||||
{ path: 'js/app.js', data: Buffer.from('console.log("v1")') },
|
||||
])
|
||||
const goodV1Sha = crypto.createHash('sha256').update(goodV1Archive).digest('hex')
|
||||
|
||||
expect(() =>
|
||||
installHotfixArchive({
|
||||
userDataDir,
|
||||
version: '0.78.1',
|
||||
archiveBuffer: goodV1Archive,
|
||||
expectedSha256: '0'.repeat(64),
|
||||
}),
|
||||
).toThrow(/SHA-256 mismatch/)
|
||||
|
||||
installHotfixArchive({
|
||||
userDataDir,
|
||||
version: '0.78.1',
|
||||
archiveBuffer: goodV1Archive,
|
||||
expectedSha256: goodV1Sha,
|
||||
})
|
||||
|
||||
const boot1 = resolveActiveEarthOverlay({ userDataDir, shellVersion: '0.78.0' })
|
||||
expect(boot1.activeBundleVersion).toBe('0.78.1')
|
||||
expect(boot1.pendingVerification).toBe(true)
|
||||
expect(boot1.overlayRoot).toBeTruthy()
|
||||
|
||||
const verifiedState = markHotfixVerified(userDataDir)
|
||||
expect(verifiedState.status).toBe('verified')
|
||||
expect(verifiedState.previousVerifiedVersion).toBe('0.78.1')
|
||||
|
||||
// Install a bad pending v0.78.2 that fails to mark ready across 2 launch attempts.
|
||||
const badV2Archive = createTarGz([
|
||||
{ path: 'index.html', data: Buffer.from('<html>broken v2</html>') },
|
||||
])
|
||||
const badV2Sha = crypto.createHash('sha256').update(badV2Archive).digest('hex')
|
||||
installHotfixArchive({
|
||||
userDataDir,
|
||||
version: '0.78.2',
|
||||
archiveBuffer: badV2Archive,
|
||||
expectedSha256: badV2Sha,
|
||||
})
|
||||
|
||||
const failBoot1 = resolveActiveEarthOverlay({ userDataDir, shellVersion: '0.78.0' })
|
||||
expect(failBoot1.activeBundleVersion).toBe('0.78.2')
|
||||
expect(failBoot1.pendingVerification).toBe(true)
|
||||
|
||||
const failBoot2 = resolveActiveEarthOverlay({ userDataDir, shellVersion: '0.78.0' })
|
||||
expect(failBoot2.activeBundleVersion).toBe('0.78.2')
|
||||
expect(failBoot2.pendingVerification).toBe(true)
|
||||
|
||||
// 3rd attempt sees 2 failed unverified boots -> automatically rolls back to verified v0.78.1
|
||||
const rolledBack = resolveActiveEarthOverlay({ userDataDir, shellVersion: '0.78.0' })
|
||||
expect(rolledBack.rolledBackFrom).toBe('0.78.2')
|
||||
expect(rolledBack.activeBundleVersion).toBe('0.78.1')
|
||||
expect(rolledBack.pendingVerification).toBe(false)
|
||||
expect(readHotfixState(userDataDir).blacklistedVersions).toContain('0.78.2')
|
||||
|
||||
// Immediate crash rollback also blacklists pending version right away.
|
||||
installHotfixArchive({
|
||||
userDataDir,
|
||||
version: '0.78.3',
|
||||
archiveBuffer: badV2Archive,
|
||||
expectedSha256: badV2Sha,
|
||||
})
|
||||
const immediateRollback = rollbackPendingHotfix(userDataDir, '0.78.0')
|
||||
expect(immediateRollback.rolledBackFrom).toBe('0.78.3')
|
||||
expect(immediateRollback.activeBundleVersion).toBe('0.78.1')
|
||||
|
||||
// Installing a newer shell (0.79.0) automatically retires older hotfixes (0.78.1).
|
||||
const afterShellUpgrade = resolveActiveEarthOverlay({ userDataDir, shellVersion: '0.79.0' })
|
||||
expect(afterShellUpgrade.overlayRoot).toBeNull()
|
||||
expect(afterShellUpgrade.activeBundleVersion).toBe('0.79.0')
|
||||
})
|
||||
|
||||
test('createEarthProtocolHandler serves overlay files first and falls back to shell assets', async () => {
|
||||
const shellRoot = makeTempDir('planet-proto-shell-')
|
||||
const overlayRoot = makeTempDir('planet-proto-overlay-')
|
||||
|
||||
fs.mkdirSync(path.join(shellRoot, 'js'), { recursive: true })
|
||||
fs.mkdirSync(path.join(shellRoot, 'assets'), { recursive: true })
|
||||
fs.writeFileSync(path.join(shellRoot, 'index.html'), '<html>shell</html>')
|
||||
fs.writeFileSync(path.join(shellRoot, 'js', 'main.js'), 'shell-js')
|
||||
fs.writeFileSync(path.join(shellRoot, 'assets', '8k_earth_daymap.jpg'), 'heavy-texture-bytes')
|
||||
|
||||
fs.mkdirSync(path.join(overlayRoot, 'js'), { recursive: true })
|
||||
fs.writeFileSync(path.join(overlayRoot, 'index.html'), '<html>hotfix</html>')
|
||||
fs.writeFileSync(path.join(overlayRoot, 'js', 'main.js'), 'hotfix-js')
|
||||
|
||||
let activeOverlay: string | null = overlayRoot
|
||||
const handler = createEarthProtocolHandler({
|
||||
earthBundleRoot: shellRoot,
|
||||
getEarthOverlayRoot: () => activeOverlay,
|
||||
getBackendUrl: () => 'https://rclaw.top',
|
||||
})
|
||||
|
||||
const htmlRes = await handler(new Request('planet://earth/earth/index.html'))
|
||||
expect(await htmlRes.text()).toBe('<html>hotfix</html>')
|
||||
|
||||
const jsRes = await handler(new Request('planet://earth/earth/js/main.js'))
|
||||
expect(await jsRes.text()).toBe('hotfix-js')
|
||||
|
||||
const assetRes = await handler(new Request('planet://earth/earth/assets/8k_earth_daymap.jpg'))
|
||||
expect(await assetRes.text()).toBe('heavy-texture-bytes')
|
||||
|
||||
const traversalRes = await handler(new Request('planet://earth/earth/..%2f..%2fsecret.txt'))
|
||||
expect(traversalRes.status).toBe(403)
|
||||
|
||||
activeOverlay = null
|
||||
const restoredHtmlRes = await handler(new Request('planet://earth/earth/index.html'))
|
||||
expect(await restoredHtmlRes.text()).toBe('<html>shell</html>')
|
||||
})
|
||||
|
||||
test('periodic 12h polling interval and per-session dismissal guard behave cleanly', () => {
|
||||
expect(PERIODIC_UPDATE_CHECK_INTERVAL_MS).toBe(12 * 60 * 60 * 1000)
|
||||
|
||||
const validSha = 'b'.repeat(64)
|
||||
const hotfixDecision = evaluateUpdateDecision({
|
||||
shellVersion: '0.78.0',
|
||||
activeBundleVersion: '0.78.0',
|
||||
blacklistedVersions: [],
|
||||
manifest: {
|
||||
shell: { version: '0.78.0', minRequired: '0.78.0', downloadUrl: 'https://gitea.rclaw.top/r' },
|
||||
bundle: { version: '0.78.1', minShellVersion: '0.78.0', url: '/b.tar.gz', sha256: validSha },
|
||||
},
|
||||
})
|
||||
const key = getUpdatePromptKey(hotfixDecision)
|
||||
expect(key).toBe('hotfix:0.78.1')
|
||||
|
||||
const dismissed = new Set<string>()
|
||||
expect(shouldSuppressUpdatePrompt(hotfixDecision, { manual: false, dismissedKeys: dismissed })).toBe(false)
|
||||
|
||||
dismissed.add(key!)
|
||||
expect(shouldSuppressUpdatePrompt(hotfixDecision, { manual: false, dismissedKeys: dismissed })).toBe(true)
|
||||
expect(shouldSuppressUpdatePrompt(hotfixDecision, { manual: true, dismissedKeys: dismissed })).toBe(false)
|
||||
|
||||
const newerDecision = evaluateUpdateDecision({
|
||||
shellVersion: '0.78.0',
|
||||
activeBundleVersion: '0.78.0',
|
||||
blacklistedVersions: [],
|
||||
manifest: {
|
||||
shell: { version: '0.78.0', minRequired: '0.78.0', downloadUrl: 'https://gitea.rclaw.top/r' },
|
||||
bundle: { version: '0.78.2', minShellVersion: '0.78.0', url: '/b.tar.gz', sha256: validSha },
|
||||
},
|
||||
})
|
||||
expect(shouldSuppressUpdatePrompt(newerDecision, { manual: false, dismissedKeys: dismissed })).toBe(false)
|
||||
expect(getUpdatePromptKey({ kind: 'up-to-date' })).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -7,7 +7,7 @@ import { afterAll, beforeAll, describe, expect, test } from 'bun:test'
|
||||
import { DesktopConfigStore, normalizeSplashTheme, parseLaunchArgs } from '../src/main/config'
|
||||
import { createWindowShowGate } from '../src/main/show-gate'
|
||||
import { LANDMASK_HEIGHT, LANDMASK_WIDTH, unpackEarthLandMask } from '../src/preload/earth-landmask'
|
||||
import { evaluateBootSplashState } from '../src/preload/splash'
|
||||
import { computeSplashMorphPhases, evaluateBootSplashState } from '../src/preload/splash'
|
||||
|
||||
let tempRoot = ''
|
||||
|
||||
@@ -22,18 +22,33 @@ afterAll(() => {
|
||||
})
|
||||
|
||||
describe('splash theme configuration and landmask', () => {
|
||||
test('normalizeSplashTheme validates allowed themes and falls back safely', () => {
|
||||
test('a clean desktop launch from the Admin handoff uses the public service', () => {
|
||||
const store = new DesktopConfigStore({
|
||||
userDataDir: tempRoot,
|
||||
exeDir: tempRoot,
|
||||
argv: ['Planet Earth', 'planet-earth://open'],
|
||||
env: {},
|
||||
})
|
||||
expect(store.get()).toMatchObject({
|
||||
backendUrl: 'https://rclaw.top',
|
||||
adminUrl: 'https://admin.rclaw.top',
|
||||
wsUrl: 'wss://rclaw.top/ws',
|
||||
deepLinkUrl: 'planet-earth://open',
|
||||
})
|
||||
})
|
||||
|
||||
test('normalizeSplashTheme normalizes unified singularity theme, legacy names, and off', () => {
|
||||
expect(normalizeSplashTheme('singularity')).toBe('singularity')
|
||||
expect(normalizeSplashTheme('CONSTELLATION')).toBe('constellation')
|
||||
expect(normalizeSplashTheme('horizon')).toBe('horizon')
|
||||
expect(normalizeSplashTheme('HORIZON')).toBe('singularity')
|
||||
expect(normalizeSplashTheme('constellation')).toBe('singularity')
|
||||
expect(normalizeSplashTheme('off')).toBe('off')
|
||||
expect(normalizeSplashTheme('invalid', 'singularity')).toBe('singularity')
|
||||
expect(normalizeSplashTheme(undefined)).toBe('singularity')
|
||||
})
|
||||
|
||||
test('parses --splash-theme CLI flag and persists splashTheme without clobbering endpoints', () => {
|
||||
const parsed = parseLaunchArgs(['--splash-theme=constellation'])
|
||||
expect(parsed.flags.splashThemeOverride).toBe('constellation')
|
||||
const parsed = parseLaunchArgs(['--splash-theme=off'])
|
||||
expect(parsed.flags.splashThemeOverride).toBe('off')
|
||||
|
||||
const userDataDir = path.join(tempRoot, 'user-data')
|
||||
const exeDir = path.join(tempRoot, 'exe-dir')
|
||||
@@ -41,18 +56,48 @@ describe('splash theme configuration and landmask', () => {
|
||||
|
||||
expect(store.get().splashTheme).toBe('singularity')
|
||||
store.updateEndpoints({ backendUrl: 'https://api.planet.test:8443' })
|
||||
store.updateSplashTheme('horizon')
|
||||
store.updateSplashTheme('off')
|
||||
|
||||
const reloaded = new DesktopConfigStore({ userDataDir, exeDir, argv: [], env: {} })
|
||||
expect(reloaded.get().backendUrl).toBe('https://api.planet.test:8443')
|
||||
expect(reloaded.get().splashTheme).toBe('horizon')
|
||||
expect(reloaded.get().splashTheme).toBe('off')
|
||||
|
||||
reloaded.updateSplashTheme('singularity')
|
||||
reloaded.updateEndpoints({ adminUrl: 'https://admin.planet.test:8443' })
|
||||
const reloadedAgain = new DesktopConfigStore({ userDataDir, exeDir, argv: [], env: {} })
|
||||
expect(reloadedAgain.get().splashTheme).toBe('horizon')
|
||||
expect(reloadedAgain.get().splashTheme).toBe('singularity')
|
||||
expect(reloadedAgain.get().adminUrl).toBe('https://admin.planet.test:8443')
|
||||
})
|
||||
|
||||
test('computeSplashMorphPhases choreographs dawn to singularity reveal and climax burst', () => {
|
||||
const start = computeSplashMorphPhases(0, 0)
|
||||
expect(start.dawnIntensity).toBe(1)
|
||||
expect(start.coreReveal).toBe(0)
|
||||
expect(start.orbitReveal).toBe(0)
|
||||
expect(start.arcReveal).toBe(0)
|
||||
expect(start.burst).toBe(0)
|
||||
expect(start.fade).toBe(1)
|
||||
|
||||
const midpoint = computeSplashMorphPhases(0.5, 0)
|
||||
expect(midpoint.dawnIntensity).toBeGreaterThan(0.5)
|
||||
expect(midpoint.dawnIntensity).toBeLessThan(1)
|
||||
expect(midpoint.coreReveal).toBeGreaterThan(0.5)
|
||||
expect(midpoint.orbitReveal).toBeGreaterThan(0)
|
||||
expect(midpoint.orbitReveal).toBeLessThan(0.5)
|
||||
|
||||
const awakened = computeSplashMorphPhases(0.95, 0)
|
||||
expect(awakened.dawnIntensity).toBe(0)
|
||||
expect(awakened.coreReveal).toBe(1)
|
||||
expect(awakened.orbitReveal).toBe(1)
|
||||
expect(awakened.arcReveal).toBe(1)
|
||||
|
||||
const exitScatter = computeSplashMorphPhases(1, 0.6)
|
||||
expect(exitScatter.dawnIntensity).toBe(0)
|
||||
expect(exitScatter.burst).toBeGreaterThan(0.45)
|
||||
expect(exitScatter.fade).toBeLessThan(0.8)
|
||||
expect(exitScatter.fade).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
test('unpackEarthLandMask reconstructs accurate continental and coastal pixels', () => {
|
||||
const grid = unpackEarthLandMask()
|
||||
expect(grid.length).toBe(LANDMASK_WIDTH * LANDMASK_HEIGHT)
|
||||
|
||||
@@ -33,20 +33,55 @@ spec:
|
||||
name: {{ include "planet.fullname" . }}-config
|
||||
- secretRef:
|
||||
name: {{ include "planet.fullname" . }}-secrets
|
||||
{{- if .Values.worker.enabled }}
|
||||
env:
|
||||
- name: PLANET_ROLE
|
||||
value: "api"
|
||||
{{- end }}
|
||||
startupProbe:
|
||||
httpGet:
|
||||
path: /health/live
|
||||
port: http
|
||||
periodSeconds: 5
|
||||
failureThreshold: 30
|
||||
readinessProbe:
|
||||
httpGet:
|
||||
path: /health
|
||||
path: /health/ready
|
||||
port: http
|
||||
initialDelaySeconds: 10
|
||||
periodSeconds: 10
|
||||
livenessProbe:
|
||||
httpGet:
|
||||
path: /health
|
||||
path: /health/live
|
||||
port: http
|
||||
initialDelaySeconds: 30
|
||||
periodSeconds: 20
|
||||
volumeMounts:
|
||||
- name: earth-brand-data
|
||||
mountPath: /app/backend/data/earth-brand
|
||||
{{- if not .Values.worker.enabled }}
|
||||
- name: collector-cache
|
||||
mountPath: /root/.cache/planet/downloads
|
||||
{{- end }}
|
||||
resources:
|
||||
{{- toYaml .Values.backend.resources | nindent 12 }}
|
||||
volumes:
|
||||
- name: earth-brand-data
|
||||
{{- if .Values.backend.persistence.earthBrand.existingClaim }}
|
||||
persistentVolumeClaim:
|
||||
claimName: {{ .Values.backend.persistence.earthBrand.existingClaim | quote }}
|
||||
{{- else }}
|
||||
emptyDir: {}
|
||||
{{- end }}
|
||||
{{- if not .Values.worker.enabled }}
|
||||
- name: collector-cache
|
||||
{{- if .Values.backend.persistence.collectorCache.existingClaim }}
|
||||
persistentVolumeClaim:
|
||||
claimName: {{ .Values.backend.persistence.collectorCache.existingClaim | quote }}
|
||||
{{- else }}
|
||||
emptyDir: {}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
|
||||
@@ -17,8 +17,7 @@ data:
|
||||
REDIS_SERVER: {{ $redisHost | quote }}
|
||||
REDIS_PORT: {{ .Values.redis.external.port | quote }}
|
||||
REDIS_DB: {{ .Values.redis.external.db | quote }}
|
||||
AI_BASE_URL: "http://{{ include "planet.fullname" . }}-aiprovider:{{ .Values.aiprovider.service.port }}"
|
||||
AI_PROVIDER_API: "http://{{ include "planet.fullname" . }}-aiprovider:{{ .Values.aiprovider.service.port }}"
|
||||
AI_PROVIDER_SERVICE_URL: "http://{{ include "planet.fullname" . }}-aiprovider:{{ .Values.aiprovider.service.port }}"
|
||||
{{- range $key, $value := .Values.backend.env }}
|
||||
{{ $key }}: {{ $value | quote }}
|
||||
{{- end }}
|
||||
|
||||
@@ -37,6 +37,8 @@ spec:
|
||||
command: ["pg_isready", "-U", {{ .Values.postgresql.external.username | quote }}]
|
||||
initialDelaySeconds: 5
|
||||
periodSeconds: 10
|
||||
resources:
|
||||
{{- toYaml .Values.postgresql.internal.resources | nindent 12 }}
|
||||
volumeMounts:
|
||||
- name: data
|
||||
mountPath: /var/lib/postgresql/data
|
||||
@@ -47,7 +49,7 @@ spec:
|
||||
accessModes: ["ReadWriteOnce"]
|
||||
resources:
|
||||
requests:
|
||||
storage: 8Gi
|
||||
storage: 15Gi
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
@@ -89,6 +91,13 @@ spec:
|
||||
containers:
|
||||
- name: redis
|
||||
image: redis:7-alpine
|
||||
args:
|
||||
- --appendonly
|
||||
- "yes"
|
||||
- --maxmemory
|
||||
- 256mb
|
||||
- --maxmemory-policy
|
||||
- allkeys-lru
|
||||
ports:
|
||||
- name: redis
|
||||
containerPort: 6379
|
||||
@@ -97,6 +106,8 @@ spec:
|
||||
command: ["redis-cli", "ping"]
|
||||
initialDelaySeconds: 5
|
||||
periodSeconds: 10
|
||||
resources:
|
||||
{{- toYaml .Values.redis.internal.resources | nindent 12 }}
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
{{- if .Values.worker.enabled }}
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: {{ include "planet.fullname" . }}-worker
|
||||
labels:
|
||||
{{- include "planet.labels" . | nindent 4 }}
|
||||
app.kubernetes.io/component: worker
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy:
|
||||
type: Recreate
|
||||
selector:
|
||||
matchLabels:
|
||||
{{- include "planet.selectorLabels" . | nindent 6 }}
|
||||
app.kubernetes.io/component: worker
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
{{- include "planet.selectorLabels" . | nindent 8 }}
|
||||
app.kubernetes.io/component: worker
|
||||
spec:
|
||||
{{- with .Values.global.imagePullSecrets }}
|
||||
imagePullSecrets:
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
containers:
|
||||
- name: worker
|
||||
image: {{ include "planet.image" (dict "root" . "repository" .Values.backend.image.repository) | quote }}
|
||||
imagePullPolicy: {{ .Values.image.pullPolicy }}
|
||||
command: ["uv", "run", "--frozen", "--no-dev", "--project", "/app", "python", "-m", "app.worker"]
|
||||
envFrom:
|
||||
- configMapRef:
|
||||
name: {{ include "planet.fullname" . }}-config
|
||||
- secretRef:
|
||||
name: {{ include "planet.fullname" . }}-secrets
|
||||
env:
|
||||
- name: PLANET_ROLE
|
||||
value: "worker"
|
||||
volumeMounts:
|
||||
- name: collector-cache
|
||||
mountPath: /root/.cache/planet/downloads
|
||||
resources:
|
||||
{{- toYaml .Values.worker.resources | nindent 12 }}
|
||||
volumes:
|
||||
- name: collector-cache
|
||||
{{- if .Values.backend.persistence.collectorCache.existingClaim }}
|
||||
persistentVolumeClaim:
|
||||
claimName: {{ .Values.backend.persistence.collectorCache.existingClaim | quote }}
|
||||
{{- else }}
|
||||
emptyDir: {}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
@@ -19,9 +19,18 @@ frontend:
|
||||
enabled: true
|
||||
className: nginx
|
||||
host: planet.example.com
|
||||
annotations: {}
|
||||
annotations:
|
||||
nginx.ingress.kubernetes.io/proxy-read-timeout: "180"
|
||||
nginx.ingress.kubernetes.io/proxy-send-timeout: "180"
|
||||
nginx.ingress.kubernetes.io/proxy-body-size: "25m"
|
||||
tls: []
|
||||
resources: {}
|
||||
resources:
|
||||
requests:
|
||||
cpu: 50m
|
||||
memory: 64Mi
|
||||
limits:
|
||||
cpu: 500m
|
||||
memory: 256Mi
|
||||
|
||||
backend:
|
||||
replicaCount: 1
|
||||
@@ -30,11 +39,43 @@ backend:
|
||||
service:
|
||||
port: 8000
|
||||
env:
|
||||
APP_ENV: production
|
||||
PLANET_ROLE: all
|
||||
PROJECT_NAME: Planet
|
||||
CORS_ORIGINS: '["*"]'
|
||||
CORS_ORIGINS: '[]'
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES: "60"
|
||||
REFRESH_TOKEN_EXPIRE_DAYS: "7"
|
||||
COLLECTOR_MAX_CONCURRENCY: "2"
|
||||
COLLECTOR_HEAVY_CONCURRENCY: "1"
|
||||
secretEnv:
|
||||
SECRET_KEY: change-me
|
||||
resources: {}
|
||||
SECRET_KEY: replace-with-strong-32-char-random-secret
|
||||
AI_PROVIDER_SERVICE_TOKEN: replace-with-internal-token
|
||||
SETTINGS_ENCRYPTION_KEY: ""
|
||||
INITIAL_ADMIN_USERNAME: ""
|
||||
INITIAL_ADMIN_EMAIL: ""
|
||||
INITIAL_ADMIN_PASSWORD: ""
|
||||
persistence:
|
||||
earthBrand:
|
||||
existingClaim: ""
|
||||
collectorCache:
|
||||
existingClaim: ""
|
||||
resources:
|
||||
requests:
|
||||
cpu: 250m
|
||||
memory: 512Mi
|
||||
limits:
|
||||
cpu: "2"
|
||||
memory: 2Gi
|
||||
|
||||
worker:
|
||||
enabled: false
|
||||
resources:
|
||||
requests:
|
||||
cpu: 250m
|
||||
memory: 512Mi
|
||||
limits:
|
||||
cpu: "2"
|
||||
memory: 2Gi
|
||||
|
||||
aiprovider:
|
||||
replicaCount: 1
|
||||
@@ -43,15 +84,29 @@ aiprovider:
|
||||
service:
|
||||
port: 8010
|
||||
env:
|
||||
APP_ENV: production
|
||||
AI_PROVIDER: openai
|
||||
AI_MODEL: gpt-4o-mini
|
||||
secretEnv:
|
||||
AI_API_KEY: ""
|
||||
resources: {}
|
||||
resources:
|
||||
requests:
|
||||
cpu: 100m
|
||||
memory: 128Mi
|
||||
limits:
|
||||
cpu: "1"
|
||||
memory: 512Mi
|
||||
|
||||
postgresql:
|
||||
internal:
|
||||
enabled: false
|
||||
resources:
|
||||
requests:
|
||||
cpu: 250m
|
||||
memory: 512Mi
|
||||
limits:
|
||||
cpu: "2"
|
||||
memory: 2Gi
|
||||
external:
|
||||
host: postgres.example.com
|
||||
port: 5432
|
||||
@@ -62,6 +117,13 @@ postgresql:
|
||||
redis:
|
||||
internal:
|
||||
enabled: false
|
||||
resources:
|
||||
requests:
|
||||
cpu: 100m
|
||||
memory: 128Mi
|
||||
limits:
|
||||
cpu: 500m
|
||||
memory: 512Mi
|
||||
external:
|
||||
host: redis.example.com
|
||||
port: 6379
|
||||
@@ -69,5 +131,5 @@ redis:
|
||||
|
||||
smoke:
|
||||
frontendPath: /
|
||||
backendHealthPath: /health
|
||||
backendHealthPath: /health/ready
|
||||
aiProviderHealthPath: /health
|
||||
@@ -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
|
||||
+120
-15
@@ -1,27 +1,88 @@
|
||||
x-logging: &default-logging
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "50m"
|
||||
max-file: "5"
|
||||
|
||||
x-backend-env: &backend-env
|
||||
APP_ENV: ${APP_ENV:-production}
|
||||
PLANET_ROLE: ${PLANET_ROLE:-all}
|
||||
DATABASE_URL: ${DATABASE_URL:-postgresql+asyncpg://${POSTGRES_USER:-postgres}:${POSTGRES_PASSWORD:-postgres}@postgres:5432/${POSTGRES_DB:-planet_db}}
|
||||
REDIS_URL: ${REDIS_URL:-redis://redis:6379/0}
|
||||
REDIS_PASSWORD:
|
||||
AI_PROVIDER_SERVICE_URL: ${AI_PROVIDER_SERVICE_URL:-http://aiprovider:8010}
|
||||
AI_PROVIDER_SERVICE_TOKEN:
|
||||
SECRET_KEY:
|
||||
CORS_ORIGINS: ${CORS_ORIGINS:-[]}
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES: ${ACCESS_TOKEN_EXPIRE_MINUTES:-60}
|
||||
REFRESH_TOKEN_EXPIRE_DAYS: ${REFRESH_TOKEN_EXPIRE_DAYS:-7}
|
||||
INITIAL_ADMIN_USERNAME:
|
||||
INITIAL_ADMIN_EMAIL:
|
||||
INITIAL_ADMIN_PASSWORD:
|
||||
SETTINGS_ENCRYPTION_KEY:
|
||||
COLLECTOR_MAX_CONCURRENCY: ${COLLECTOR_MAX_CONCURRENCY:-2}
|
||||
COLLECTOR_HEAVY_CONCURRENCY: ${COLLECTOR_HEAVY_CONCURRENCY:-1}
|
||||
HTTP_PROXY: ${HTTP_PROXY:-}
|
||||
HTTPS_PROXY: ${HTTPS_PROXY:-}
|
||||
NO_PROXY: ${NO_PROXY:-localhost,127.0.0.1,postgres,redis,backend,aiprovider,admin}
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:15
|
||||
image: ${POSTGRES_IMAGE:-postgres:15}
|
||||
container_name: planet_deploy_postgres
|
||||
command:
|
||||
- postgres
|
||||
- -c
|
||||
- shared_buffers=${POSTGRES_SHARED_BUFFERS:-256MB}
|
||||
- -c
|
||||
- work_mem=${POSTGRES_WORK_MEM:-16MB}
|
||||
- -c
|
||||
- maintenance_work_mem=${POSTGRES_MAINTENANCE_WORK_MEM:-128MB}
|
||||
- -c
|
||||
- max_connections=${POSTGRES_MAX_CONNECTIONS:-150}
|
||||
- -c
|
||||
- autovacuum_vacuum_scale_factor=0.1
|
||||
- -c
|
||||
- log_min_duration_statement=1000
|
||||
environment:
|
||||
POSTGRES_USER: ${POSTGRES_USER:-postgres}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-postgres}
|
||||
POSTGRES_DB: ${POSTGRES_DB:-planet_db}
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
mem_limit: ${PLANET_POSTGRES_MEM_LIMIT:-2g}
|
||||
logging: *default-logging
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-postgres}"]
|
||||
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-postgres} -d ${POSTGRES_DB:-planet_db}"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
restart: unless-stopped
|
||||
|
||||
redis:
|
||||
image: redis:7-alpine
|
||||
image: ${REDIS_IMAGE:-redis:7-alpine}
|
||||
container_name: planet_deploy_redis
|
||||
command:
|
||||
- sh
|
||||
- -c
|
||||
- |
|
||||
if [ -n "$$REDIS_PASSWORD" ]; then
|
||||
exec redis-server --appendonly yes --maxmemory 256mb --maxmemory-policy allkeys-lru --requirepass "$$REDIS_PASSWORD"
|
||||
else
|
||||
exec redis-server --appendonly yes --maxmemory 256mb --maxmemory-policy allkeys-lru
|
||||
fi
|
||||
environment:
|
||||
REDIS_PASSWORD: ${REDIS_PASSWORD:-}
|
||||
volumes:
|
||||
- redis_data:/data
|
||||
mem_limit: ${PLANET_REDIS_MEM_LIMIT:-512m}
|
||||
logging: *default-logging
|
||||
healthcheck:
|
||||
test: ["CMD", "redis-cli", "ping"]
|
||||
test:
|
||||
[
|
||||
"CMD-SHELL",
|
||||
"if [ -n \"$$REDIS_PASSWORD\" ]; then redis-cli -a \"$$REDIS_PASSWORD\" ping; else redis-cli ping; fi",
|
||||
]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
@@ -36,8 +97,17 @@ services:
|
||||
PYTHON_IMAGE: ${PYTHON_IMAGE:-python:3.14-slim}
|
||||
UV_IMAGE: ${UV_IMAGE:-ghcr.io/astral-sh/uv:latest}
|
||||
env_file:
|
||||
- ./aiprovider/.env
|
||||
- path: ./aiprovider/.env
|
||||
required: false
|
||||
environment:
|
||||
APP_ENV: ${APP_ENV:-production}
|
||||
AI_PROVIDER_SERVICE_TOKEN:
|
||||
HTTP_PROXY: ${HTTP_PROXY:-}
|
||||
HTTPS_PROXY: ${HTTPS_PROXY:-}
|
||||
NO_PROXY: ${NO_PROXY:-localhost,127.0.0.1,postgres,redis,backend,aiprovider,admin}
|
||||
container_name: planet_deploy_aiprovider
|
||||
mem_limit: ${PLANET_AIPROVIDER_MEM_LIMIT:-512m}
|
||||
logging: *default-logging
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "-fsS", "http://127.0.0.1:8010/health"]
|
||||
interval: 10s
|
||||
@@ -56,14 +126,18 @@ services:
|
||||
secrets:
|
||||
- planet_uv_config
|
||||
env_file:
|
||||
- ./backend/.env
|
||||
- path: ./backend/.env
|
||||
required: false
|
||||
container_name: planet_deploy_backend
|
||||
environment:
|
||||
DATABASE_URL: ${DATABASE_URL:-postgresql+asyncpg://postgres:postgres@postgres:5432/planet_db}
|
||||
REDIS_URL: ${REDIS_URL:-redis://redis:6379/0}
|
||||
AI_PROVIDER_BASE_URL: ${AI_PROVIDER_BASE_URL:-http://aiprovider:8010}
|
||||
ports:
|
||||
- "${PLANET_BACKEND_PORT:-8000}:8000"
|
||||
environment: *backend-env
|
||||
expose:
|
||||
- "8000"
|
||||
volumes:
|
||||
- earth_brand_data:/app/backend/data/earth-brand
|
||||
- client_updates_data:/app/backend/data/client-updates
|
||||
- collector_cache:/root/.cache/planet/downloads
|
||||
mem_limit: ${PLANET_BACKEND_MEM_LIMIT:-2g}
|
||||
logging: *default-logging
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
@@ -72,10 +146,36 @@ services:
|
||||
aiprovider:
|
||||
condition: service_healthy
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "-fsS", "http://127.0.0.1:8000/health"]
|
||||
test: ["CMD", "curl", "-fsS", "http://127.0.0.1:8000/health/ready"]
|
||||
interval: 15s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 30s
|
||||
restart: unless-stopped
|
||||
|
||||
worker:
|
||||
profiles:
|
||||
- split
|
||||
image: ${BACKEND_IMAGE_NAME:-planet-backend:latest}
|
||||
container_name: planet_deploy_worker
|
||||
command: ["uv", "run", "--frozen", "--no-dev", "--project", "/app", "python", "-m", "app.worker"]
|
||||
env_file:
|
||||
- path: ./backend/.env
|
||||
required: false
|
||||
environment:
|
||||
<<: *backend-env
|
||||
PLANET_ROLE: worker
|
||||
volumes:
|
||||
- collector_cache:/root/.cache/planet/downloads
|
||||
mem_limit: ${PLANET_WORKER_MEM_LIMIT:-2g}
|
||||
logging: *default-logging
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
redis:
|
||||
condition: service_healthy
|
||||
aiprovider:
|
||||
condition: service_healthy
|
||||
restart: unless-stopped
|
||||
|
||||
admin:
|
||||
@@ -86,12 +186,14 @@ services:
|
||||
args:
|
||||
BUN_IMAGE: ${BUN_IMAGE:-oven/bun:1-alpine}
|
||||
NGINX_IMAGE: ${NGINX_IMAGE:-nginx:1.27-alpine}
|
||||
PLANET_FRONTEND_TARGET: admin
|
||||
PLANET_FRONTEND_TARGET: ${PLANET_FRONTEND_TARGET:-full}
|
||||
container_name: planet_deploy_admin
|
||||
environment:
|
||||
PLANET_BACKEND_UPSTREAM: backend:8000
|
||||
ports:
|
||||
- "${PLANET_ADMIN_PORT:-3000}:3000"
|
||||
- "${PLANET_ADMIN_BIND_HOST:-0.0.0.0}:${PLANET_ADMIN_PORT:-3000}:3000"
|
||||
mem_limit: ${PLANET_ADMIN_MEM_LIMIT:-256m}
|
||||
logging: *default-logging
|
||||
depends_on:
|
||||
backend:
|
||||
condition: service_healthy
|
||||
@@ -105,6 +207,9 @@ services:
|
||||
volumes:
|
||||
postgres_data:
|
||||
redis_data:
|
||||
earth_brand_data:
|
||||
client_updates_data:
|
||||
collector_cache:
|
||||
|
||||
secrets:
|
||||
planet_uv_config:
|
||||
|
||||
@@ -8,6 +8,53 @@ This project follows the repository versioning rule:
|
||||
- `improvement` -> `+0.0.1`(bugfix + 小功能混合)
|
||||
- `bugfix` -> `+0.0.1`
|
||||
|
||||
## [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
|
||||
|
||||
### Highlights
|
||||
|
||||
- **Unified 3-Act Splash Screen**: Merged horizon and singularity splash animations into a unified Dawn -> Singularity -> Burst sequence, retired the constellation switcher UI, and capped splash canvas pixel budgets on high-DPI displays.
|
||||
- **Phase 1 L1 Earth Business Hot-Update System**: Added self-hosted update manifest and `.tar.gz` bundle endpoints (`GET /api/v1/client/update-manifest`, `GET /api/v1/client/updates/files/{filename}`, `POST /api/v1/client/updates/bundle`), pure USTAR `.tar.gz` overlay extraction with SHA-256 verification and 2-attempt crash auto-rollback, overlay-first `planet://earth/` resolution, prominent native update dialogs, startup + 12-hour polling, and Alt-menu update checks.
|
||||
- **Windows Electron GPU/TDR Stability & WebGL Recovery**: Hardened Chromium GPU switches with `--software-gl` fallback and crash forwarding, capped 4K startup DPR and starfield VRAM usage, added `webglcontextlost` / `webglcontextrestored` auto-recovery, and added brand image retry on GPU restarts.
|
||||
|
||||
### Added
|
||||
|
||||
- Client hot-update modules (`tar-gz.ts`, `hot-update-core.ts`, `hot-updater.ts`) and lightweight `planet-earth-bundle` `.tar.gz` packaging in `build-earth-bundle.mjs` and `scripts/release_publish.py`.
|
||||
- Backend client updates API (`backend/app/api/v1/client_updates.py`) and `client_updates_data` volume configuration in `docker-compose.deploy.yml`.
|
||||
|
||||
### Fixed & Improved
|
||||
|
||||
- Removed unstable Windows Chromium GPU switches (`enable-zero-copy`, `enable-gpu-rasterization`, `force_high_performance_gpu`) and prevented duplicate "Later" update prompts within the same session.
|
||||
|
||||
---
|
||||
|
||||
## [0.78.0] — 2026-11-23
|
||||
|
||||
Released: 2026-11-23
|
||||
|
||||
### Highlights
|
||||
|
||||
- 采集历史支持全局单份、增量更新和独立保留规则,发布与设置更新在 PostgreSQL 中保持一致。
|
||||
- 单份模式保留 24 小时轻量船舶航迹,同名自定义数据源按配置区分。
|
||||
- 增加生产配置、备份、数据库迁移及 API 和采集 Worker 分离部署。
|
||||
- Electron 首次启动默认连接 rclaw.top,轻量 Admin 提供桌面唤起页和客户端下载入口。
|
||||
- Windows、macOS 和 Linux 发行包支持 planet-earth 协议以及已运行窗口的唤起。
|
||||
|
||||
---
|
||||
|
||||
## [0.77.0] — 2026-11-20
|
||||
|
||||
Released: 2026-11-20
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
# 生产环境部署与运维指南
|
||||
|
||||
本文档总结了 Planet 在生产服务器上的标准化部署架构、必需安全配置、高可用(API + Worker)拆分方式、备份策略与健康检查说明。
|
||||
|
||||
---
|
||||
|
||||
## 一、资源与存储规划
|
||||
|
||||
按最新默认存储策略(`default_mode="single"`、`top500` / `epoch_ai_gpu` 按年度保留里程碑、新库默认 `auto_prune_enabled=True`、BGP 观测保留 7 天、新闻与日志保留 30 天、AIS 不写原始流水表):
|
||||
|
||||
| 部署形态 | 初始纯数据 | 长期稳态数据 | 推荐磁盘与内存 |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| **全开 26 个采集器(含 IPtoASN + NRO)** | ~2.0 ~ 2.3 GB | ~2.6 ~ 4.0 GB | 磁盘 >= 15 GB,内存 >= 4 GB(推荐 8 GB) |
|
||||
| **关闭 2 个 IP 前缀库(其余全开)** | ~180 ~ 260 MB | ~0.5 ~ 1.2 GB | 磁盘 >= 10 GB,内存 >= 4 GB |
|
||||
|
||||
> 部署脚本与编排文件已内置 `iptoasn` / `nro` 重任务并发互斥(`COLLECTOR_HEAVY_CONCURRENCY=1`)、全局采集并发限制(`COLLECTOR_MAX_CONCURRENCY=2`)、线程池 CPU 卸载与 500 行批量 Core 写入,防止大表采集阻塞事件循环或引发 OOM。
|
||||
|
||||
---
|
||||
|
||||
## 一点五、`./planet.sh` 一键运维命令
|
||||
|
||||
可直接使用根目录脚本管理生产编排、备份与迁移:
|
||||
|
||||
```bash
|
||||
# 首次部署:自动生成高强度随机 .env.deploy(权限 0600),校验配置并构建启动
|
||||
./planet.sh deploy up
|
||||
|
||||
# 启用 API + Worker 拆分高可用模式
|
||||
./planet.sh deploy up --split
|
||||
|
||||
# 查看生产容器状态与 /api/health/{live,ready} 探针
|
||||
./planet.sh deploy status
|
||||
|
||||
# 滚动备份与数据库迁移(支持容器内执行)
|
||||
./planet.sh backup --mode full --retention-days 14
|
||||
./planet.sh migrate status --container
|
||||
./planet.sh migrate upgrade --container
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 二、单机 Docker Compose 生产部署
|
||||
|
||||
使用 [docker-compose.deploy.yml](../docker-compose.deploy.yml) 启动:
|
||||
|
||||
1. **准备环境变量**(可放在宿主机 `.env` 或 `./backend/.env`、`./aiprovider/.env`,参考 `backend/.env.example` 与 `aiprovider/.env.example`):
|
||||
|
||||
| 变量名 | 必填(`APP_ENV=production`) | 说明 |
|
||||
| :--- | :--- | :--- |
|
||||
| `SECRET_KEY` | 是(>= 32 字符随机串) | JWT 签名密钥,禁止使用默认占位串 |
|
||||
| `ACCESS_TOKEN_EXPIRE_MINUTES` | 建议 `60` | 生产禁止 `<= 0`(永不过期) |
|
||||
| `REFRESH_TOKEN_EXPIRE_DAYS` | 建议 `7` | 生产禁止 `<= 0` |
|
||||
| `CORS_ORIGINS` | 建议 `[]` 或精确域名 JSON | 同域走 Nginx 时设 `[]`;生产禁止包含 `*` |
|
||||
| `AI_PROVIDER_SERVICE_URL` | 是 | 默认容器内网 `http://aiprovider:8010` |
|
||||
| `AI_PROVIDER_SERVICE_TOKEN` | 是 | `backend` 与 `aiprovider` 间鉴权 Token,两端需一致 |
|
||||
| `INITIAL_ADMIN_USERNAME` / `PASSWORD` | 首次部署必填 | 生产环境禁止自动生成 `admin/admin123` 等默认开发账号 |
|
||||
| `SETTINGS_ENCRYPTION_KEY` | 强烈建议设置 | 对数据库中保存的 SMTP / 集成 API Key 做 Fernet 对称加密 |
|
||||
| `REDIS_PASSWORD` | 建议设置 | 启用 Redis `requirepass` 访问认证 |
|
||||
| `PLANET_FRONTEND_TARGET` | 默认 `full` | 保留完整 `/earth/` 3D 地球与 `/admin` 管理端 |
|
||||
|
||||
2. **启动服务**:
|
||||
|
||||
```bash
|
||||
docker compose -f docker-compose.deploy.yml up -d --build
|
||||
```
|
||||
|
||||
3. **对外入口与 HTTPS/TLS 终结**:
|
||||
- `backend` 仅通过内部网络暴露 `8000` 端口,`aiprovider` 不对外暴露,所有外部流量统一经由 `admin`(Nginx `3000` 端口)进入。
|
||||
- 公网部署时,务必在 `3000` 端口前置 TLS 终结网关(Caddy / 云负载均衡 / K8s Nginx Ingress),确保 HTTPS 与 `wss://` 加密传输,并配置 `CORS_ORIGINS` 为实际 HTTPS 域名(如 `["https://planet.example.com"]`)。
|
||||
|
||||
---
|
||||
|
||||
## 三、API 与 Worker 高可用拆分(多副本)
|
||||
|
||||
单实例部署使用 `PLANET_ROLE=all`。如需扩容多台 API 实例,应将后台采集与调度拆分为唯一 Worker,避免重复采集与本地 WebSocket 孤岛:
|
||||
|
||||
1. **Docker Compose 拆分模式**:
|
||||
- API 服务配置 `PLANET_ROLE=api`(支持多实例扩展,不运行定时调度与队列 Worker)。
|
||||
- 启动 `split` Profile 唯一 Worker 容器:
|
||||
|
||||
```bash
|
||||
PLANET_ROLE=api docker compose -f docker-compose.deploy.yml --profile split up -d
|
||||
```
|
||||
|
||||
2. **Kubernetes / Helm 部署**:
|
||||
- 在 [values.yaml](../deploy/helm/planet/values.yaml) 中设置 `worker.enabled: true`、`backend.env.PLANET_ROLE: api` 并按需提高 `backend.replicaCount`。
|
||||
- 跨实例 WebSocket 广播通过 Redis Pub/Sub(频道 `planet:ws:broadcast`)自动同步;调度器通过 PostgreSQL 会话级 Advisory Lock(键 `(17001613, 3)`)确保同时仅有一个主调度器生效。
|
||||
|
||||
---
|
||||
|
||||
## 四、健康检查、备份与数据库迁移
|
||||
|
||||
### 1. 健康探针
|
||||
- `GET /health/live`:进程存活探针(Liveness)。
|
||||
- `GET /health/ready`:真实依赖就绪探针(Readiness),2 秒超时探测 PostgreSQL `SELECT 1` 与 Redis `PING`,任一失败返回 HTTP `503`。
|
||||
- `GET /health`:向后兼容探针。
|
||||
|
||||
### 2. 自动滚动备份
|
||||
使用 [scripts/backup_db.sh](../scripts/backup_db.sh)(建议接入宿主机 `cron` 每日执行):
|
||||
|
||||
```bash
|
||||
# 全量压缩备份并校验证书完整性,保留近 14 天
|
||||
scripts/backup_db.sh --mode full --retention-days 14 --output-dir /var/backups/planet
|
||||
|
||||
# 轻量核心备份(仅表结构 + 用户/配置/研判业务表,跳过巨型 IP 前缀库与日志流)
|
||||
scripts/backup_db.sh --mode core --retention-days 30 --output-dir /var/backups/planet
|
||||
```
|
||||
|
||||
### 3. 版本化数据库迁移
|
||||
- 应用启动初始化(`init_db()`)会在事务型 PostgreSQL Advisory Lock(`(17001613, 4)`)保护下自动初始化并记录 `schema_migrations` 基线版本(`0001`)。
|
||||
- 后续变更可使用 [scripts/db_migrate.py](../scripts/db_migrate.py) 检查与执行升级:
|
||||
|
||||
```bash
|
||||
uv run --project . python scripts/db_migrate.py status
|
||||
uv run --project . python scripts/db_migrate.py upgrade
|
||||
```
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -6,6 +6,8 @@ If you are responsible for deployment or on-call duty, read the [Intelligent Pla
|
||||
|
||||
## Entry Overview
|
||||
|
||||
In the hosted Admin Console, select Earth to open the desktop launch page. On your first visit, download Planet Earth, place it where you intend to keep it, and start it once. Then choose **Launch desktop app** on the page. The desktop client connects to [rclaw.top](https://rclaw.top) by default.
|
||||
|
||||
| Name | URL | Login Required | Description |
|
||||
| --- | --- | --- | --- |
|
||||
| Earth | `http://<host>/earth` | No | Public 3D situational awareness page |
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -13,6 +13,8 @@ Entry points are split in two:
|
||||
- Public: `/earth` (3D situational view), `/docs` (public documentation)
|
||||
- Login required: `/admin` (console), `/ai` (AI), `/settings` (system settings), `/earth-content` (Earth content), `/collection-management` (collection management)
|
||||
|
||||
In the hosted Admin Console, select Earth to open the desktop launch page. On your first visit, download Planet Earth, place it where you intend to keep it, and start it once. Then choose **Launch desktop app** on the page. The desktop client connects to [rclaw.top](https://rclaw.top) by default.
|
||||
|
||||
## 2. Register
|
||||
|
||||
1. Open `/login` and click "Register" under the form.
|
||||
|
||||
@@ -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 与桌面端。
|
||||
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
|
||||
## 入口总览
|
||||
|
||||
使用线上轻量控制台时,从「智能星球」进入桌面客户端页面。首次使用请下载 Planet Earth,放到常用位置并启动一次。之后在该页面点击「打开桌面客户端」即可进入本机地球视图。桌面客户端默认连接 [rclaw.top](https://rclaw.top)。
|
||||
|
||||
| 名称 | 地址 | 是否需要登录 | 说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| 智能星球 | `http://<域名>/earth` | 否 | 公开 3D 态势页面 |
|
||||
|
||||
Loaded 100 of 133 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user