release: bump version to 0.78.0
ci / backend (push) Waiting to run
ci / frontend (push) Waiting to run
release / images (push) Waiting to run
release / client_release (push) Waiting to run

This commit is contained in:
linkong committed 2026-11-23 22:40:11 +08:00
1 parent e6aa8c539b
commit 5fc698d738
96 files changed
+10214 -747

No files matched your search

+1
View File
@@ -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/
+2
View File
@@ -6,8 +6,10 @@
# 敏感文件
# ----------------------
.env
.env.deploy
.env.local
.env.*.local
backups/
config/earth-boundary-sources.local.json
*.pem
*.key
+1 -1
View File
@@ -1 +1 @@
0.77.0
0.78.0
+9 -8
View File
@@ -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
+6
View File
@@ -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
View File
@@ -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
View File
@@ -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
+1
View File
@@ -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
+157 -21
View File
@@ -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"}
+36 -13
View File
@@ -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(
+11 -1
View File
@@ -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
+7 -2
View File
@@ -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":
+40 -8
View File
@@ -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
View File
@@ -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)),
}
+12 -2
View File
@@ -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)
+125 -8
View File
@@ -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,48 @@ class Settings(BaseSettings):
AI_PROVIDER_RETRY_ATTEMPTS: int = 2
OBSERVABILITY_INGEST_TOKEN: str = ""
@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 +136,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()
+110
View File
@@ -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)
+197 -7
View File
@@ -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)},
)
+112 -20
View File
@@ -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]):
+162 -29
View File
@@ -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."""
+217
View File
@@ -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
View File
@@ -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
View File
@@ -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()}
+1
View File
@@ -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
+1
View File
@@ -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
+12 -12
View File
@@ -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:
+103 -5
View File
@@ -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,
File diff suppressed because it is too large. Load diff
+70 -15
View File
@@ -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(),
},
)
+36 -12
View File
@@ -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",
+89 -6
View File
@@ -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,
+203 -46
View File
@@ -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)
+11 -2
View File
@@ -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
+132 -2
View File
@@ -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:
+339
View File
@@ -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)
+523
View File
@@ -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
+258 -16
View File
@@ -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
+149
View File
@@ -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())
+8 -6
View File
@@ -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],
]
+424
View File
@@ -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()
+106 -1
View File
@@ -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()
+4 -4
View File
@@ -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
+329
View File
@@ -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()
+571
View File
@@ -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
+4
View File
@@ -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
View File
@@ -1,6 +1,6 @@
{
"name": "planet-client",
"version": "0.77.0",
"version": "0.78.0",
"description": "Intelligent Planet Program - Native Electron Earth Viewer",
"private": true,
"packageManager": "bun@1",
+3 -3
View File
@@ -45,9 +45,9 @@ export function normalizeSplashTheme(
return VALID_SPLASH_THEMES.has(normalized) ? normalized : fallback
}
const DEFAULT_ENDPOINTS: ServerEndpoints = {
backendUrl: 'http://127.0.0.1:8000',
adminUrl: 'http://127.0.0.1:3000',
export const DEFAULT_ENDPOINTS: Readonly<ServerEndpoints> = {
backendUrl: 'https://rclaw.top',
adminUrl: 'https://admin.rclaw.top',
motionWsUrl: 'ws://127.0.0.1:8765/ws/gestures',
}
+57
View File
@@ -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')
}
}
+22 -14
View File
@@ -4,6 +4,7 @@ import path from 'node:path'
import { app, BrowserWindow, ipcMain, Menu, session, shell } from 'electron'
import { DesktopConfigStore, normalizeSplashTheme, type ServerEndpoints } from './config'
import { DESKTOP_SCHEME, registerDesktopLink } from './desktop-link'
import { buildApplicationMenu } from './menu'
import { EARTH_ORIGIN, installEarthSessionHandlers, registerEarthScheme } from './protocol'
import { createMainWindow, dismissMenuBarOnPointerDown, toggleWindowOrientation } from './window'
@@ -63,24 +64,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') {
@@ -89,6 +94,9 @@ if (!singleInstanceLock) {
})
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')),
@@ -180,7 +188,7 @@ if (!singleInstanceLock) {
dismissMenuBarOnPointerDown(mainWindow)
})
const launchWindow = () => {
launchWindow = () => {
const preloadPath = resolvePreloadPath()
mainWindow = createMainWindow({
preloadPath,
@@ -321,7 +329,7 @@ if (!singleInstanceLock) {
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
launchWindow()
launchWindow?.()
}
})
})
+4 -4
View File
@@ -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 {
@@ -489,9 +489,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', () => {
+15
View File
@@ -22,6 +22,21 @@ afterAll(() => {
})
describe('splash theme configuration and landmask', () => {
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 validates allowed themes and falls back safely', () => {
expect(normalizeSplashTheme('singularity')).toBe('singularity')
expect(normalizeSplashTheme('CONSTELLATION')).toBe('constellation')
+37 -2
View File
@@ -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
+1 -2
View File
@@ -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
+53
View File
@@ -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 }}
+69 -7
View File
@@ -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
+118 -15
View File
@@ -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,17 @@ 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
- collector_cache:/root/.cache/planet/downloads
mem_limit: ${PLANET_BACKEND_MEM_LIMIT:-2g}
logging: *default-logging
depends_on:
postgres:
condition: service_healthy
@@ -72,10 +145,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 +185,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 +206,8 @@ services:
volumes:
postgres_data:
redis_data:
earth_brand_data:
collector_cache:
secrets:
planet_uv_config:
+14
View File
@@ -8,6 +8,20 @@ This project follows the repository versioning rule:
- `improvement` -> `+0.0.1`(bugfix + 小功能混合)
- `bugfix` -> `+0.0.1`
## [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
+116
View File
@@ -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
```
+2
View File
@@ -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 |
+2
View File
@@ -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.
+2
View File
@@ -6,6 +6,8 @@
## 入口总览
使用线上轻量控制台时,从「智能星球」进入桌面客户端页面。首次使用请下载 Planet Earth,放到常用位置并启动一次。之后在该页面点击「打开桌面客户端」即可进入本机地球视图。桌面客户端默认连接 [rclaw.top](https://rclaw.top)。
| 名称 | 地址 | 是否需要登录 | 说明 |
| --- | --- | --- | --- |
| 智能星球 | `http://<域名>/earth` | 否 | 公开 3D 态势页面 |
+2
View File
@@ -13,6 +13,8 @@
- 公开页:`/earth`(3D 态势)、`/docs`(公共文档)
- 登录后:`/admin`(控制台)、`/ai`(AI)、`/settings`(系统设置)、`/earth-content`(智能星球内容)、`/collection-management`(采集管理)
使用线上轻量控制台时,从「智能星球」进入桌面客户端页面。首次使用请下载 Planet Earth,放到常用位置并启动一次。之后在该页面点击「打开桌面客户端」即可进入本机地球视图。桌面客户端默认连接 [rclaw.top](https://rclaw.top)。
## 2. 注册账号
1. 打开 `/login`,点击表单下方"注册账户"。
+2 -1
View File
@@ -16,12 +16,13 @@
## Current Version
- `main` 当前主线历史推导到:`0.16.5`
- `dev` 当前开发分支历史推导到:`0.77.0`
- `dev` 当前开发分支历史推导到:`0.78.0`
## Timeline
| Version | Type | Branch | Commit | Summary |
| --- | --- | --- | --- | --- |
| `0.78.0` | feature | `dev` | `v0.78.0` | 全局单份采集策略、短期船舶航迹、精简生产部署和桌面协议注册 |
| `0.77.0` | feature | `dev` | `v0.77.0` | 新增原生 Electron Earth 桌面客户端(多方案 3D 启动页/横竖屏/离线协议/Gitea 自动发布)、轻量 Admin 独立容器、全球综合态势工作台与算力对比增强 |
| `0.76.20` | improvement | `dev` | `v0.76.20` | 统一 Earth 卡片布局仲裁与连接线,修复悬停展开和固定深度,并优化卫星分批查询与连接测试反馈 |
| `0.76.19` | improvement | `dev` | `v0.76.19` | 改善 Earth 卡片与移动交互、新闻后台刷新、图层缓存、BGP 前缀查询及 Outbox 维护 |
+29
View File
@@ -3,6 +3,11 @@ server {
server_name _;
root /usr/share/nginx/html;
index index.html;
client_max_body_size 25m;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
gzip on;
gzip_types text/plain text/css application/javascript application/json image/svg+xml;
@@ -20,9 +25,30 @@ server {
proxy_set_header X-Forwarded-Proto $scheme;
}
location = /api/health/live {
proxy_pass http://${PLANET_BACKEND_UPSTREAM}/health/live;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location = /api/health/ready {
proxy_pass http://${PLANET_BACKEND_UPSTREAM}/health/ready;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /api/ {
proxy_pass http://${PLANET_BACKEND_UPSTREAM}/api/;
proxy_http_version 1.1;
proxy_connect_timeout 10s;
proxy_send_timeout 180s;
proxy_read_timeout 180s;
proxy_buffering off;
proxy_request_buffering off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
@@ -32,6 +58,9 @@ server {
location /ws {
proxy_pass http://${PLANET_BACKEND_UPSTREAM}/ws;
proxy_http_version 1.1;
proxy_connect_timeout 10s;
proxy_send_timeout 3600s;
proxy_read_timeout 3600s;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "planet-frontend",
"version": "0.77.0",
"version": "0.78.0",
"private": true,
"packageManager": "bun@1",
"dependencies": {
+8
View File
@@ -377,6 +377,14 @@ const EXACT_TRANSLATIONS = {
"开启": "On",
"已显示": "Shown",
"已隐藏": "Hidden",
"打开全球综合态势工作台": "Open global situation workbench",
"全球综合态势工作台": "Global situation workbench",
"在工作台分析海缆": "Analyze cable in workbench",
"在工作台分析登陆站": "Analyze landing station in workbench",
"在工作台分析卫星": "Analyze satellite in workbench",
"在工作台分析船舶": "Analyze vessel in workbench",
"在工作台分析算力": "Analyze compute resource in workbench",
"算力对比浮层": "Compute comparison panel",
"折叠图层列表": "Collapse layer list",
"关闭图层面板": "Close layer panel",
"搜索图层...": "Search layers...",
+269 -6
View File
@@ -1,17 +1,21 @@
import type { ColumnDef } from '@tanstack/react-table'
import axios from 'axios'
import {
AlertTriangle,
ArrowLeft,
Bot,
BrushCleaning,
CheckCircle2,
CircleHelp,
Copy,
Database,
DatabaseZap,
Eye,
FileText,
Globe2,
History,
ImageUp,
Layers,
ListChecks,
Radio,
Redo2,
@@ -1021,6 +1025,7 @@ const fieldLabels: Record<string, string> = {
system_name: '系统名称',
refresh_interval: '刷新间隔(秒)',
data_retention_days: '数据保留天数',
snapshot_mode: '存储策略',
max_concurrent_tasks: '最大并发任务数',
auto_refresh: '自动刷新',
demo_mode: '演示模式',
@@ -1048,6 +1053,7 @@ const fieldLabels: Record<string, string> = {
const fieldHelp: Record<string, string> = {
demo_mode: '开启后访问智能星球会直接显示 OOBE 引导,不再要求首次采集条件,也会忽略本机“先浏览”临时跳过。',
data_retention_days: '与「采集管理 → 采集调度」中的历史保留天数保持同步;仅在开启自动清理时回收超期历史。',
}
function fieldLabel(key: string, locale?: SupportedLocale) {
@@ -1396,11 +1402,38 @@ function formatSnapshotTime(record: AnyRecord) {
})
}
const COLLECTOR_STORAGE_POLICY_KEYS = new Set([
'snapshot_mode',
'snapshot_overridden',
'supports_annual',
'high_volume_warning',
])
function snapshotModeLabel(mode: unknown) {
const normalized = text(mode, 'single').toLowerCase()
if (normalized === 'annual') return '年末对比'
if (normalized === 'history') return '历史快照'
return '单份增量'
}
function snapshotModeDescription(mode: unknown) {
const normalized = text(mode, 'single').toLowerCase()
if (normalized === 'annual') {
return '同自然年内原地增量更新;跨年首次采集自动固化上一年末里程碑快照,支撑算力跨年对比。'
}
if (normalized === 'history') {
return '每次采集均保留历史版本与时间胶囊对比,超期非当前快照受自动清理与保留天数约束。'
}
return '仅保留最新 1 份数据,按实体差异原地增量更新,未变化记录零写入,极省硬盘容量。'
}
function snapshotOptionLabel(record: AnyRecord) {
const current = record.is_current === true ? '当前 · ' : ''
const status = semanticLabel(snapshotStatus(record))
const count = typeof record.record_count === 'number' ? formatCountZh(record.record_count) : pick(record, ['record_count'], '0 条')
return `${current}${formatSnapshotTime(record)} · ${status} · ${count}`
const milestoneYear = isObjectRecord(record.summary) ? record.summary.milestone_year : null
const milestoneSuffix = milestoneYear ? ` · 年末里程碑 (${String(milestoneYear)})` : ''
return `${current}${formatSnapshotTime(record)} · ${status} · ${count}${milestoneSuffix}`
}
const emptyRows = () => []
@@ -2938,6 +2971,7 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
const [newsFilters, setNewsFilters] = useState({ status: 'all', sourceType: 'all', region: 'all', tag: 'all' })
const [collectionDraftGroup, setCollectionDraftGroup] = useState<HierarchyGroup | null>(null)
const [snapshotSelectionBySource, setSnapshotSelectionBySource] = useState<Record<string, string>>({})
const [retentionDaysDraft, setRetentionDaysDraft] = useState('30')
const [loading, setLoading] = useState(false)
const [actionLoading, setActionLoading] = useState(false)
const [rowActionLoading, setRowActionLoading] = useState<Record<string, boolean>>({})
@@ -4735,6 +4769,24 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
await requestAction(label, 'put', '/settings/integrations', buildExternalIntegrationPayload(overrides))
}
const collectorStoragePolicy = useMemo(() => {
if (config !== configs.collection) return null
const collectorsState = states.find((state) => state.section.key === 'collectors')
const rawPolicy = objectAt(collectorsState?.raw, 'storage_policy')
return Object.keys(rawPolicy).length ? rawPolicy : null
}, [config, states])
useEffect(() => {
const retention = collectorStoragePolicy?.history_retention_days
if (typeof retention === 'number' && Number.isFinite(retention)) {
setRetentionDaysDraft(String(retention))
}
}, [collectorStoragePolicy?.history_retention_days])
const updateStoragePolicy = async (payload: AnyRecord, label: string) => {
await requestAction(label, 'put', '/settings/storage-policy', payload)
}
const getActiveHierarchyGroup = (groups: HierarchyGroup[]) => {
const flat = groups.flatMap((group) => group.children?.length ? group.children : [group])
return flat.find((group) => group.key === activeGroupKey) || flat[0] || null
@@ -5300,7 +5352,9 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
let groups: HierarchyGroup[] = activeState.rows.map((row) => ({
key: row.__rowId,
label: recordTitle(row),
description: row.__module,
description: config === configs.collection && activeSection.key === 'collectors'
? `${row.__module} · ${snapshotModeLabel(row.snapshot_mode)}${row.snapshot_locked === true ? ' · 全局锁定' : row.snapshot_overridden === true ? ' · 覆盖' : ''}`
: row.__module,
status: normalizeStatusLabel(recordStatus(row)),
count: Object.keys(cleanRecord(row)).length,
record: { ...cleanRecord(row), __sourceEndpoint: row.__endpointKey, __sourceLabel: row.__endpointLabel },
@@ -5462,8 +5516,11 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
setActionLoading(false)
}
}
const hiddenCollectorStorageField = (key: string) => (
activeSection.key === 'collectors' && COLLECTOR_STORAGE_POLICY_KEYS.has(key)
)
const scalarFields = Object.entries(activeGroup?.record || {})
.filter(([key, value]) => !key.startsWith('__') && ['string', 'number', 'boolean'].includes(typeof value))
.filter(([key, value]) => !key.startsWith('__') && !hiddenCollectorStorageField(key) && ['string', 'number', 'boolean'].includes(typeof value))
.map(([key, value]): FieldConfig => ({
key,
label: fieldLabel(key),
@@ -5483,7 +5540,7 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
: undefined,
}))
const objectFields = Object.entries(activeGroup?.record || {})
.filter(([key, value]) => !key.startsWith('__') && !shouldHideDatasourceConfigObjectField(activeGroup?.record || {}, activeSourceEndpoint, key) && value !== null && typeof value === 'object')
.filter(([key, value]) => !key.startsWith('__') && !hiddenCollectorStorageField(key) && !shouldHideDatasourceConfigObjectField(activeGroup?.record || {}, activeSourceEndpoint, key) && value !== null && typeof value === 'object')
.map(([key]): FieldConfig => ({ key, label: fieldLabel(key), type: 'textarea', wide: true }))
const newsSourceFields: FieldConfig[] = config === configs.earthContent && activeSection.key === 'news_sources' ? [
{ key: 'id', label: '源 ID' },
@@ -5799,10 +5856,12 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
}
if (activeSection.key === 'collectors') {
const id = pick(activeGroup.record, ['id'], '')
const globalSingleLocked = Boolean(collectorStoragePolicy?.global_single_lock || activeGroup.record.snapshot_locked === true)
await saveHierarchySettings(`/settings/collectors/${encodeURIComponent(id)}`, {
is_active: Boolean(payload.is_active),
priority: text(payload.priority, 'P1'),
frequency_minutes: Number(payload.frequency_minutes || 60),
snapshot_mode: globalSingleLocked ? 'single' : text(payload.snapshot_mode, 'single'),
}, '保存采集器设置')
return
}
@@ -5947,10 +6006,12 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
return
}
if (activeSection.key === 'collectors' && id) {
const globalSingleLocked = Boolean(collectorStoragePolicy?.global_single_lock || activeGroup.record.snapshot_locked === true)
await saveHierarchySettings(`/settings/collectors/${encodeURIComponent(id)}`, {
is_active: Boolean(payload.is_active),
priority: text(payload.priority, 'P1'),
frequency_minutes: Number(payload.frequency_minutes || 60),
snapshot_mode: globalSingleLocked ? 'single' : text(payload.snapshot_mode, 'single'),
}, '保存采集调度')
return
}
@@ -6050,7 +6111,136 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
</TactileControlGroup>
) : null
const hierarchyHeader = config === configs.earthContent && activeSection.key === 'news_sources' ? (
const renderCollectorStorageHeader = () => {
if (!collectorStoragePolicy) return null
const masterState = text(collectorStoragePolicy.master_state, 'partial')
const totalSources = Number(collectorStoragePolicy.total_sources || groups.length || 0)
const snapshotEnabledCount = Number(collectorStoragePolicy.snapshot_enabled_count || 0)
const annualCount = Number(collectorStoragePolicy.annual_count || 0)
const historyCount = Number(collectorStoragePolicy.history_count || 0)
const currentRetentionDays = Number(collectorStoragePolicy.history_retention_days || 30)
const autoPruneEnabled = Boolean(collectorStoragePolicy.auto_prune_enabled)
const globalSingleLocked = Boolean(collectorStoragePolicy.global_single_lock)
const defaultMode = text(collectorStoragePolicy.default_mode, 'single')
const parsedRetention = Number(retentionDaysDraft)
const retentionChanged = Number.isFinite(parsedRetention)
&& parsedRetention >= 1
&& parsedRetention <= 3650
&& parsedRetention !== currentRetentionDays
const statusBadgeLabel = globalSingleLocked || masterState === 'off'
? `全部单份 (0/${totalSources})`
: masterState === 'all'
? `全部历史 (${totalSources}/${totalSources})`
: `部分开启 (${snapshotEnabledCount}/${totalSources})`
const statusToneClass = globalSingleLocked || masterState === 'off'
? 'an-badge an-badge--green'
: masterState === 'all'
? 'an-badge an-badge--amber'
: 'an-badge an-badge--cyan'
const StateIcon = globalSingleLocked || masterState === 'off' ? Database : masterState === 'all' ? History : Layers
const recommendedActive = !globalSingleLocked && defaultMode === 'single' && annualCount > 0 && historyCount === 0
const allSingleActive = globalSingleLocked || masterState === 'off'
const allHistoryActive = !globalSingleLocked && masterState === 'all' && historyCount === totalSources
return (
<div className="an-storage-policy-bar" aria-label={localizeAdminText('全局采集存储策略', locale)}>
<div className="an-storage-policy-bar__summary">
<span className={statusToneClass}>
<StateIcon size={13} aria-hidden="true" />
<span>{localizeAdminText(statusBadgeLabel, locale)}</span>
</span>
<span className="an-storage-policy-bar__meta">
{localizeAdminText(`默认${snapshotModeLabel(defaultMode)}${globalSingleLocked ? '(全局单份已锁定)' : ''} · 保留 ${currentRetentionDays} 天 · ${autoPruneEnabled ? '自动清理已开' : '自动清理已关(保留存量)'}`, locale)}
</span>
</div>
<div className="an-storage-policy-bar__controls">
<div className="an-segmented" role="group" aria-label={localizeAdminText('存储总控模式', locale)}>
<button
type="button"
className={allSingleActive ? 'is-active' : undefined}
disabled={actionLoading}
onClick={() => void updateStoragePolicy({ action: 'all_single' }, '切换为全部单份')}
>
{localizeAdminText('全部单份', locale)}
</button>
<button
type="button"
className={recommendedActive ? 'is-active' : undefined}
disabled={actionLoading}
onClick={() => void updateStoragePolicy({ action: 'recommended_default' }, '应用默认推荐策略')}
>
{localizeAdminText('默认推荐', locale)}
</button>
<button
type="button"
className={allHistoryActive ? 'is-active' : undefined}
disabled={actionLoading}
onClick={() => setConfirmAction({
title: localizeAdminText('确认开启全部历史快照', locale),
description: localizeAdminText('开启全部历史快照后,IP 前缀库(iptoasn / nro)与实时船舶 AIS 数据源将继续写入完整历史快照(估算约 66 GB/月),仅建议在需要全量审计时使用。', locale),
danger: true,
confirmLabel: localizeAdminText('确认全部开启', locale),
run: () => updateStoragePolicy({ action: 'all_history' }, '切换为全部历史快照'),
})}
>
{localizeAdminText('全部历史', locale)}
</button>
</div>
<div className="an-storage-policy-bar__retention">
<label className="an-inline-field">
<span>{localizeAdminText('保留天数', locale)}</span>
<input
className="an-input an-storage-policy-bar__days"
type="number"
min={1}
max={3650}
value={retentionDaysDraft}
onChange={(event) => setRetentionDaysDraft(event.target.value)}
/>
</label>
{retentionChanged ? (
<Button
size="sm"
variant="subtle"
loading={actionLoading}
onClick={() => void updateStoragePolicy({ history_retention_days: parsedRetention }, '更新保留天数')}
>
{localizeAdminText('应用', locale)}
</Button>
) : null}
<span className="an-storage-policy-bar__switch">
<span className="an-storage-policy-bar__switch-label">{localizeAdminText('自动清理', locale)}</span>
<AdminSwitch
checked={autoPruneEnabled}
label={localizeAdminText('自动清理', locale)}
disabled={actionLoading}
onCheckedChange={(next) => {
if (!next) {
void updateStoragePolicy({ auto_prune_enabled: false }, '关闭自动清理')
return
}
setConfirmAction({
title: localizeAdminText('确认开启超期自动清理', locale),
description: localizeAdminText(`开启后将按保留窗口(历史快照与日志 ${currentRetentionDays} 天、BGP 原始观测 7 天)分批清理过期历史,同时永久保留当前最新数据与算力年末里程碑。若这是包含历史资产的开发库,请确认不再需要 ${currentRetentionDays} 天前的旧快照。`, locale),
danger: true,
confirmLabel: localizeAdminText('确认开启', locale),
run: () => updateStoragePolicy({ auto_prune_enabled: true }, '开启自动清理'),
})
}}
/>
</span>
</div>
</div>
</div>
)
}
const hierarchyHeader = config === configs.collection && activeSection.key === 'collectors' ? (
renderCollectorStorageHeader()
) : config === configs.earthContent && activeSection.key === 'news_sources' ? (
<div className="an-news-source-filters">
<select className="an-input" value={newsFilters.status} onChange={(event) => setNewsFilters((current) => ({ ...current, status: event.target.value }))}>
<option value="all">全部状态</option>
@@ -6296,7 +6486,11 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
<section className="an-field-cluster">
<div className="an-field-cluster__heading">
<h3>Time Capsule</h3>
<p>{localizeAdminText(`${snapshotTimeline.length} 个历史快照,选择后查看该版本详情。`, locale)}</p>
<p>
{snapshotTimeline.length <= 1
? localizeAdminText(`${snapshotTimeline.length} 个快照。单份增量模式下只维护最新 1 份,可在「采集调度」按数据源开启年末对比或历史快照。`, locale)
: localizeAdminText(`${snapshotTimeline.length} 个历史快照,选择后查看该版本详情。`, locale)}
</p>
</div>
<div className="an-time-capsule__controls">
<label className="an-field an-field--wide">
@@ -6434,6 +6628,75 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
/>
</section>
</>
) : activeSection.key === 'collectors' ? (
(() => {
const globalSingleLocked = Boolean(collectorStoragePolicy?.global_single_lock || record.snapshot_locked === true)
const currentMode = globalSingleLocked ? 'single' : text(record.snapshot_mode, 'single')
return (
<>
<section className="an-field-cluster an-field-cluster--compact">
<div className="an-field-cluster__heading">
<h3>{localizeAdminText('存储与快照策略', locale)}</h3>
<p>
{localizeAdminText(
globalSingleLocked
? '已开启全局全部单份锁定,需切换为默认推荐后方可单独开启历史'
: record.snapshot_overridden === true
? '自定义覆盖(独立于全局默认)'
: '继承全局默认策略',
locale,
)}
</p>
</div>
<div className="an-storage-mode-row">
<div className="an-segmented" role="group" aria-label={localizeAdminText('单源存储策略', locale)}>
{(
[
{ value: 'single', label: '单份增量' },
...(record.supports_annual === true || currentMode === 'annual'
? [{ value: 'annual', label: '年末对比' }]
: []),
{ value: 'history', label: '历史快照' },
] as const
).map((option) => {
const optionDisabled = globalSingleLocked && option.value !== 'single'
return (
<button
key={option.value}
type="button"
disabled={optionDisabled}
title={optionDisabled ? localizeAdminText('已开启全局全部单份锁定,请先切换为默认推荐或全部历史', locale) : undefined}
className={currentMode === option.value ? 'is-active' : undefined}
onClick={() => {
if (!activeGroup || optionDisabled) return
setHierarchyDraft(setNestedDraftField(hierarchyDraft, activeGroup.record, 'snapshot_mode', option.value))
}}
>
{localizeAdminText(option.label, locale)}
</button>
)
})}
</div>
<span className="an-storage-policy-bar__meta">
{localizeAdminText(snapshotModeDescription(currentMode), locale)}
</span>
</div>
{isObjectRecord(record.high_volume_warning) && currentMode === 'history' ? (
<div className="an-storage-warning" role="alert">
<AlertTriangle size={15} aria-hidden="true" />
<span>
{localizeAdminText(
`高体积提醒(预计增量 ${text(record.high_volume_warning.estimated_monthly_growth, '')}):${text(record.high_volume_warning.note, '')}`,
locale,
)}
</span>
</div>
) : null}
</section>
<FieldGrid record={activeGroup.record} draft={hierarchyDraft} onDraftChange={setHierarchyDraft} fields={editableFields} searchGroupKey={activeGroup.key} />
</>
)
})()
) : (
<FieldGrid record={activeGroup.record} draft={hierarchyDraft} onDraftChange={setHierarchyDraft} fields={editableFields} searchGroupKey={activeGroup.key} />
)}
+86
View File
@@ -1951,10 +1951,91 @@ body:has(.admin-theme-root[data-theme='dark']) .an-toast {
overflow: hidden;
}
.an-storage-policy-bar {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 10px 14px;
padding: 10px 12px;
border: 1px solid var(--an-border);
border-radius: 7px;
background: var(--an-surface);
}
.an-storage-policy-bar__summary,
.an-storage-policy-bar__controls,
.an-storage-policy-bar__retention {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px 10px;
min-width: 0;
}
.an-storage-policy-bar__meta {
color: var(--an-muted);
font-size: 12px;
line-height: 1.4;
}
.an-storage-policy-bar__retention .an-inline-field {
height: 30px;
}
.an-storage-policy-bar__retention .an-storage-policy-bar__days {
width: 72px;
min-width: 64px;
height: 30px;
padding-inline: 8px;
}
.an-storage-policy-bar__switch {
display: inline-flex;
align-items: center;
gap: 7px;
height: 30px;
}
.an-storage-policy-bar__switch-label {
color: var(--an-muted);
font-size: 12px;
white-space: nowrap;
}
.an-storage-mode-row {
display: grid;
gap: 8px;
justify-items: start;
}
.an-storage-warning {
display: grid;
grid-template-columns: 16px minmax(0, 1fr);
align-items: start;
gap: 8px;
padding: 9px 10px;
border: 1px solid color-mix(in srgb, var(--an-warning) 55%, var(--an-border));
border-radius: 6px;
background: color-mix(in srgb, var(--an-warning) 10%, var(--an-surface));
color: var(--an-text);
font-size: 12px;
line-height: 1.45;
}
.an-storage-warning svg {
color: var(--an-warning);
margin-top: 1px;
}
@media (max-width: 900px) {
.an-news-source-filters {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.an-storage-policy-bar {
align-items: stretch;
}
}
@media (max-width: 560px) {
@@ -4311,6 +4392,11 @@ body[data-admin-theme='dark'] .an-connection-test-input > .tui-button:hover:not(
outline-offset: -2px;
}
.an-segmented button:disabled {
opacity: 0.45;
cursor: not-allowed;
}
.an-summary-kpis {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
+27
View File
@@ -861,6 +861,33 @@ export const legacyUiTextEnUS: Record<string, string> = {
'是': 'Yes',
'否': 'No',
'采集间隔(分钟)': 'Collection interval (minutes)',
'存储策略': 'Storage policy',
'单份增量': 'Single copy (incremental)',
'年末对比': 'Year-end comparison',
'历史快照': 'Historical snapshots',
'全局采集存储策略': 'Global collection storage policy',
'存储总控模式': 'Storage master control mode',
'全部单份': 'All single-copy',
'默认推荐': 'Recommended default',
'全部历史': 'All history',
'保留天数': 'Retention days',
'自动清理': 'Auto prune',
'应用': 'Apply',
'存储与快照策略': 'Storage & snapshot policy',
'单源存储策略': 'Collector storage mode',
'自定义覆盖(独立于全局默认)': 'Custom override (independent from global default)',
'继承全局默认策略': 'Inherits global default policy',
'切换为全部单份': 'Switch all to single copy',
'应用默认推荐策略': 'Apply recommended default policy',
'切换为全部历史快照': 'Switch all to historical snapshots',
'确认开启全部历史快照': 'Enable historical snapshots for all collectors?',
'确认全部开启': 'Confirm enable all',
'确认开启超期自动清理': 'Enable automatic expiration pruning?',
'确认开启': 'Confirm enable',
'关闭自动清理': 'Disable auto prune',
'开启自动清理': 'Enable auto prune',
'更新保留天数': 'Update retention days',
'与「采集管理 → 采集调度」中的历史保留天数保持同步;仅在开启自动清理时回收超期历史。': 'Synchronized with retention days in Collection Management → Schedule; expired history is pruned only when auto-prune is enabled.',
'无时间': 'No timestamp',
'自动刷新': 'Auto refresh',
'会话超时(分钟)': 'Session timeout (minutes)',
-13
View File
@@ -29,19 +29,6 @@
gap: 14px;
}
.earth-desktop-handoff__badge {
display: inline-flex;
align-items: center;
gap: 8px;
width: fit-content;
padding: 5px 10px;
border: 1px solid rgba(96, 165, 250, 0.32);
background: rgba(59, 130, 246, 0.14);
color: #93c5fd;
font-size: 12px;
font-weight: 600;
}
.earth-desktop-handoff__title {
font-size: 22px;
font-weight: 600;
@@ -1,4 +1,4 @@
import { ArrowLeft, ExternalLink, Globe2 } from 'lucide-react'
import { ArrowLeft, Download, ExternalLink } from 'lucide-react'
import { Link } from 'react-router-dom'
import { useLocale } from '../../i18n/locale'
@@ -11,17 +11,13 @@ export default function EarthDesktopRedirect() {
return (
<main className="earth-desktop-handoff">
<section className="earth-desktop-handoff__panel">
<div className="earth-desktop-handoff__badge">
<Globe2 size={14} aria-hidden="true" />
<span>{isEnglish ? 'Admin Container Mode' : '独立控制台容器模式'}</span>
</div>
<h1 className="earth-desktop-handoff__title">
{isEnglish ? 'Open Intelligent Planet Desktop' : '请在桌面客户端打开智能星球'}
{isEnglish ? 'Open Planet Earth' : '打开 Planet Earth'}
</h1>
<p className="earth-desktop-handoff__desc">
{isEnglish
? 'This container serves the Admin Console and Docs only. Launch the native Electron Planet Earth client for hardware-accelerated 3D rendering, or run ./planet.sh earth locally.'
: '当前容器仅承载运维控制台与系统文档服务。请启动原生 Planet Earth 桌面客户端观看硬件加速 3D 地球,或在本地运行 ./planet.sh earth。'}
? 'First visit? Download Planet Earth and start it once from the location where you plan to keep it. Then use the button below to open your globe.'
: '首次使用请下载客户端,放到常用位置并启动一次。之后点击下方按钮即可打开地球。'}
</p>
<div className="earth-desktop-handoff__actions">
<a
@@ -29,7 +25,11 @@ export default function EarthDesktopRedirect() {
href="planet-earth://open"
>
<ExternalLink size={15} aria-hidden="true" />
<span>{isEnglish ? 'Launch Planet Earth' : '唤起桌面端 Earth'}</span>
<span>{isEnglish ? 'Launch desktop app' : '打开桌面客户端'}</span>
</a>
<a className="earth-desktop-handoff__btn" href="https://rclaw.top/">
<Download size={15} aria-hidden="true" />
<span>{isEnglish ? 'Download latest version' : '下载最新版'}</span>
</a>
<Link className="earth-desktop-handoff__btn" to="/admin">
<ArrowLeft size={15} aria-hidden="true" />
+2 -2
View File
@@ -58,8 +58,8 @@ function Register() {
setFeedback(null)
try {
const response = await axios.post(`${API_URL}/auth/verify-email`, { email, code })
const { access_token, user } = response.data
useAuthStore.setState({ token: access_token, user })
const { access_token, refresh_token, user } = response.data
useAuthStore.setState({ token: access_token, refreshToken: refresh_token ?? null, user })
axios.defaults.headers.common.Authorization = `Bearer ${access_token}`
navigate('/admin', { replace: true })
} catch (error) {
@@ -37,8 +37,8 @@ function VerifyEmail() {
setFeedback(null)
try {
const response = await axios.post(`${API_URL}/auth/verify-email`, { email, code })
const { access_token, user } = response.data
useAuthStore.setState({ token: access_token, user })
const { access_token, refresh_token, user } = response.data
useAuthStore.setState({ token: access_token, refreshToken: refresh_token ?? null, user })
axios.defaults.headers.common.Authorization = `Bearer ${access_token}`
navigate('/admin', { replace: true })
} catch (error) {
+90 -8
View File
@@ -1,6 +1,6 @@
import axios, { AxiosError, type InternalAxiosRequestConfig } from 'axios'
import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
import axios from 'axios'
import { createJSONStorage, persist } from 'zustand/middleware'
interface User {
id: number
@@ -11,18 +11,25 @@ interface User {
interface AuthState {
token: string | null
refreshToken: string | null
user: User | null
login: (username: string, password: string) => Promise<void>
logout: () => void
clearAuth: () => void
}
interface RetryableRequestConfig extends InternalAxiosRequestConfig {
_authRetried?: boolean
}
const API_URL = import.meta.env.VITE_API_URL || '/api/v1'
let pendingRefresh: Promise<string | null> | null = null
export const useAuthStore = create<AuthState>()(
persist(
(set) => ({
(set, get) => ({
token: null,
refreshToken: null,
user: null,
async login(username: string, password: string) {
@@ -34,18 +41,30 @@ export const useAuthStore = create<AuthState>()(
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
})
const { access_token, user } = response.data
set({ token: access_token, user })
const { access_token, refresh_token, user } = response.data
set({ token: access_token, refreshToken: refresh_token ?? null, user })
axios.defaults.headers.common['Authorization'] = `Bearer ${access_token}`
},
logout() {
set({ token: null, user: null })
const { token, refreshToken } = get()
set({ token: null, refreshToken: null, user: null })
delete axios.defaults.headers.common['Authorization']
if (token || refreshToken) {
void axios
.post(
`${API_URL}/auth/logout`,
refreshToken ? { refresh_token: refreshToken } : {},
{
headers: token ? { Authorization: `Bearer ${token}` } : {},
}
)
.catch(() => undefined)
}
},
clearAuth() {
set({ token: null, user: null })
set({ token: null, refreshToken: null, user: null })
localStorage.removeItem('auth-storage')
delete axios.defaults.headers.common['Authorization']
},
@@ -59,8 +78,71 @@ export const useAuthStore = create<AuthState>()(
axios.interceptors.request.use((config) => {
const token = useAuthStore.getState().token
if (token) {
if (token && !config.headers.Authorization) {
config.headers.Authorization = `Bearer ${token}`
}
return config
})
async function refreshAccessToken(): Promise<string | null> {
const { refreshToken } = useAuthStore.getState()
if (!refreshToken) {
return null
}
if (!pendingRefresh) {
pendingRefresh = axios
.post(
`${API_URL}/auth/refresh`,
{},
{
headers: { Authorization: `Bearer ${refreshToken}` },
}
)
.then((response) => {
const { access_token, refresh_token, user } = response.data
useAuthStore.setState({
token: access_token,
refreshToken: refresh_token ?? refreshToken,
user,
})
axios.defaults.headers.common['Authorization'] = `Bearer ${access_token}`
return String(access_token)
})
.catch(() => {
useAuthStore.getState().clearAuth()
return null
})
.finally(() => {
pendingRefresh = null
})
}
return pendingRefresh
}
axios.interceptors.response.use(
(response) => response,
async (error: AxiosError) => {
const originalRequest = error.config as RetryableRequestConfig | undefined
const requestUrl = originalRequest?.url || ''
const isAuthLifecycleRequest =
requestUrl.includes('/auth/login') ||
requestUrl.includes('/auth/refresh') ||
requestUrl.includes('/auth/logout')
if (
error.response?.status === 401 &&
originalRequest &&
!originalRequest._authRetried &&
!isAuthLifecycleRequest &&
useAuthStore.getState().refreshToken
) {
originalRequest._authRetried = true
const nextToken = await refreshAccessToken()
if (nextToken) {
originalRequest.headers.Authorization = `Bearer ${nextToken}`
return axios(originalRequest)
}
}
return Promise.reject(error)
}
)
+93 -4
View File
@@ -247,6 +247,7 @@ source "$SCRIPT_DIR/scripts/lib/docker-bootstrap.zsh"
source "$SCRIPT_DIR/scripts/lib/docker-proxy.zsh"
source "$SCRIPT_DIR/scripts/lib/error-diagnostics.zsh"
source "$SCRIPT_DIR/scripts/lib/docker-mirror.zsh"
source "$SCRIPT_DIR/scripts/lib/deploy.zsh"
# Shell / Docker helpers
is_pid() {
@@ -2788,11 +2789,64 @@ cleanup_backend_processes() {
return 0
}
build_dev_cors_origins_json() {
local backend_port="${1:-$DEFAULT_BACKEND_PORT}"
local frontend_port="${2:-${FRONTEND_PORT:-$DEFAULT_FRONTEND_PORT}}"
local admin_port="${3:-${ADMIN_PORT:-$DEFAULT_ADMIN_PORT}}"
local -a origins=(
"http://localhost:${frontend_port}"
"https://localhost:${frontend_port}"
"http://127.0.0.1:${frontend_port}"
"https://127.0.0.1:${frontend_port}"
"http://localhost:${admin_port}"
"http://127.0.0.1:${admin_port}"
"http://localhost:${backend_port}"
"http://127.0.0.1:${backend_port}"
"planet://earth"
)
if [ "${FRONTEND_LAN_ENABLED:-0}" -eq 1 ] && (( $+functions[get_recommended_lan_ipv4] )); then
local lan_ip=""
if lan_ip="$(get_recommended_lan_ipv4 2>/dev/null || true)" && [ -n "$lan_ip" ]; then
origins+=(
"http://${lan_ip}:${frontend_port}"
"https://${lan_ip}:${frontend_port}"
"http://${lan_ip}:${admin_port}"
"http://${lan_ip}:${backend_port}"
)
fi
fi
local json="["
local first=1
local origin=""
local -A seen=()
for origin in "${origins[@]}"; do
[ -z "${seen[$origin]:-}" ] || continue
seen[$origin]=1
if [ "$first" -eq 0 ]; then
json="${json},"
fi
first=0
json="${json}\"${origin}\""
done
printf "%s]\n" "$json"
}
start_backend_with_retry() {
local backend_port="$1"
local retry=1
local backend_bind_host="0.0.0.0"
local readiness_status=0
local -a backend_cors_env=()
if [ -z "${CORS_ORIGINS:-}" ] && (( $+functions[build_dev_cors_origins_json] )); then
if [ "${FRONTEND_LAN_ENABLED:-0}" -eq 1 ] ||
[ "$backend_port" != "${DEFAULT_BACKEND_PORT:-8000}" ] ||
[ "${FRONTEND_PORT:-${DEFAULT_FRONTEND_PORT:-3000}}" != "${DEFAULT_FRONTEND_PORT:-3000}" ] ||
[ "${ADMIN_PORT:-${DEFAULT_ADMIN_PORT:-3000}}" != "${DEFAULT_ADMIN_PORT:-3000}" ]; then
backend_cors_env=("CORS_ORIGINS=$(build_dev_cors_origins_json "$backend_port")")
fi
fi
while [ "$retry" -le "$BACKEND_MAX_RETRIES" ]; do
if ! cleanup_backend_processes "$backend_port"; then
@@ -2804,6 +2858,7 @@ start_backend_with_retry() {
env PYTHONPATH="$SCRIPT_DIR/backend" \
PLANET_CACHE_DIR="$PLANET_CACHE_DIR" \
PLANET_DOWNLOAD_CACHE_DIR="${PLANET_DOWNLOAD_CACHE_DIR:-$PLANET_CACHE_DIR/downloads}" \
"${backend_cors_env[@]}" \
uv run --frozen --project "$SCRIPT_DIR" python -m uvicorn app.main:app \
--host "$backend_bind_host" --port "$backend_port" --reload)"
write_pid_file "$BACKEND_PID_FILE" "$BACKEND_PID"
@@ -2812,7 +2867,7 @@ start_backend_with_retry() {
fi
readiness_status=0
wait_for_http "http://localhost:${backend_port}/health" "$BACKEND_HEALTH_CHECK_ATTEMPTS" "$BACKEND_HEALTH_CHECK_INTERVAL" "后端" backend_startup_failed || readiness_status=$?
wait_for_http "http://localhost:${backend_port}/health/ready" "$BACKEND_HEALTH_CHECK_ATTEMPTS" "$BACKEND_HEALTH_CHECK_INTERVAL" "后端" backend_startup_failed || readiness_status=$?
if [ "$readiness_status" -eq 0 ]; then
return 0
fi
@@ -5072,7 +5127,8 @@ health() {
echo ""
echo -e "${DIM}·${NC} ${BLUE}view${NC} ${WHITE}服务状态${NC}"
print_http_health_status "后端" "http://localhost:${backend_port}/health"
print_http_health_status "后端存活" "http://localhost:${backend_port}/health/live"
print_http_health_status "后端就绪" "http://localhost:${backend_port}/health/ready"
print_http_health_status "AI Provider" "http://localhost:${ai_provider_port}/health"
print_frontend_health_status "$frontend_port"
print_admin_health_status "$admin_port"
@@ -5353,7 +5409,7 @@ bundle_command() {
print_usage() {
cat <<'EOF'
用法: ./planet.sh {init|start|stop|destroy|restart|createuser|health|log|admin|earth|bundle}
用法: ./planet.sh {init|start|stop|destroy|restart|createuser|health|log|admin|earth|bundle|deploy|backup|migrate}
全局参数: -v, --verbose 在状态提示之间增量输出命令日志
start / restart 可加 --no-build:仅使用本地已有镜像,缺少镜像时报错
@@ -5363,6 +5419,9 @@ start / restart 可加 --no-build:仅使用本地已有镜像,缺少镜像
admin 单独管理 Admin 轻量容器: ./planet.sh admin {start|stop|restart|health|log}
earth 启动 Electron Earth 桌面端 (WSL2 优先拉起原生 Windows 客户端,加 --linux 强制 Linux)
bundle 打包跨平台独立客户端: ./planet.sh bundle {--win|--linux|--mac|--dir|--all}
deploy 生产编排管理: ./planet.sh deploy {up|down|restart|status|logs|init-env} [--split] [--no-build] [--env-file <path>]
backup 执行 PostgreSQL 滚动压缩备份: ./planet.sh backup [--mode full|core] [--retention-days 14]
migrate 数据库版本迁移: ./planet.sh migrate {status|upgrade|stamp <version>} [--container [name]]
stop 停止所有服务(含 Admin 容器)
destroy 删除 Planet 容器、卷、镜像和本地编译状态,执行前需要输入 Y 确认
restart 重启服务(支持 --admin / --admin-only / --no-frontend 及原有端口参数)
@@ -5398,6 +5457,15 @@ case "$1" in
init|start|restart|stop|health|log|createuser|admin)
refresh_docker_group "${PLANET_COMMAND_ARGS[@]}" || exit 1
;;
deploy|backup)
case "${2:-}" in
-h|--help|help|init-env)
;;
*)
refresh_docker_group "${PLANET_COMMAND_ARGS[@]}" || exit 1
;;
esac
;;
esac
case "$1" in
@@ -5440,6 +5508,18 @@ case "$1" in
shift
bundle_command "$@"
;;
deploy)
shift
deploy_command "$@"
;;
backup)
shift
backup_command "$@"
;;
migrate)
shift
migrate_command "$@"
;;
-h|--help|help)
case "${2:-}" in
admin)
@@ -5451,6 +5531,15 @@ case "$1" in
bundle)
bundle_command --help
;;
deploy)
deploy_command --help
;;
backup)
backup_command --help
;;
migrate)
migrate_command --help
;;
*)
print_usage
;;
@@ -5458,7 +5547,7 @@ case "$1" in
exit 0
;;
*)
log_error "用法: ./planet.sh {init|start|stop|destroy|restart|createuser|health|log|admin|earth|bundle}"
log_error "用法: ./planet.sh {init|start|stop|destroy|restart|createuser|health|log|admin|earth|bundle|deploy|backup|migrate}"
print_usage >&2
exit 1
;;
+1 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "planet"
version = "0.77.0"
version = "0.78.0"
description = "智能星球计划 - 态势感知系统"
requires-python = ">=3.14"
dependencies = [
+138
View File
@@ -0,0 +1,138 @@
#!/usr/bin/env bash
set -euo pipefail
OUTPUT_DIR="${PLANET_BACKUP_DIR:-./backups/postgres}"
RETENTION_DAYS="${PLANET_BACKUP_RETENTION_DAYS:-14}"
MODE="full"
CONTAINER_NAME=""
VERIFY_GZIP=1
POSTGRES_USER_VALUE="${POSTGRES_USER:-postgres}"
POSTGRES_DB_VALUE="${POSTGRES_DB:-planet_db}"
usage() {
cat <<'EOF'
Usage: scripts/backup_db.sh [options]
Create a compressed PostgreSQL backup and prune expired archives after success.
Options:
--output-dir <path> Backup output directory (default: ./backups/postgres)
--retention-days <days> Delete .sql.gz files older than N days (default: 14)
--mode <full|core> full: complete DB dump (default)
core: schema + core config/users/assessment tables
(skips high-volume collected_data/logs/bgp_observations)
--container <name> Docker Postgres container name (auto-detects running container)
--no-verify Skip gzip integrity verification after dump
-h, --help Show this help message
EOF
}
while [[ $# -gt 0 ]]; do
case "$1" in
--output-dir)
OUTPUT_DIR="$2"
shift 2
;;
--retention-days)
RETENTION_DAYS="$2"
shift 2
;;
--mode)
MODE="$2"
shift 2
;;
--container)
CONTAINER_NAME="$2"
shift 2
;;
--no-verify)
VERIFY_GZIP=0
shift
;;
-h|--help)
usage
exit 0
;;
*)
printf 'Unknown option: %s\n' "$1" >&2
usage >&2
exit 2
;;
esac
done
if [[ "$MODE" != "full" && "$MODE" != "core" ]]; then
printf 'Invalid --mode: %s (expected full or core)\n' "$MODE" >&2
exit 2
fi
if ! [[ "$RETENTION_DAYS" =~ ^[0-9]+$ ]]; then
printf 'Invalid --retention-days: %s\n' "$RETENTION_DAYS" >&2
exit 2
fi
detect_container() {
if [[ -n "$CONTAINER_NAME" ]]; then
printf '%s\n' "$CONTAINER_NAME"
return 0
fi
if command -v docker >/dev/null 2>&1; then
local candidate
for candidate in planet_deploy_postgres planet_postgres; do
if docker ps --format '{{.Names}}' | grep -qx "$candidate"; then
printf '%s\n' "$candidate"
return 0
fi
done
fi
return 1
}
mkdir -p "$OUTPUT_DIR"
STAMP="$(date -u +%Y%m%dT%H%M%SZ)"
TARGET_FILE="${OUTPUT_DIR%/}/planet_${POSTGRES_DB_VALUE}_${MODE}_${STAMP}.sql.gz"
TMP_FILE="${TARGET_FILE}.tmp"
cleanup_tmp() {
rm -f "$TMP_FILE"
}
trap cleanup_tmp EXIT
PG_DUMP_ARGS=(--no-owner --no-privileges --format=plain)
if [[ "$MODE" == "core" ]]; then
PG_DUMP_ARGS+=(
--exclude-table-data=collected_data
--exclude-table-data=bgp_observations
--exclude-table-data=ais_raw_observations
--exclude-table-data=system_logs
--exclude-table-data=observability_events
--exclude-table-data=earth_data_change_events
)
fi
if ACTIVE_CONTAINER="$(detect_container)"; then
docker exec -e PGPASSWORD="${POSTGRES_PASSWORD:-}" "$ACTIVE_CONTAINER" \
pg_dump -U "$POSTGRES_USER_VALUE" -d "$POSTGRES_DB_VALUE" "${PG_DUMP_ARGS[@]}" \
| gzip -c > "$TMP_FILE"
else
DB_URL_RAW="${DATABASE_URL:-}"
if [[ -n "$DB_URL_RAW" ]]; then
DB_URL_NORM="${DB_URL_RAW/postgresql+asyncpg:\/\//postgresql:\/\/}"
pg_dump "$DB_URL_NORM" "${PG_DUMP_ARGS[@]}" | gzip -c > "$TMP_FILE"
else
pg_dump -U "$POSTGRES_USER_VALUE" -d "$POSTGRES_DB_VALUE" "${PG_DUMP_ARGS[@]}" \
| gzip -c > "$TMP_FILE"
fi
fi
if [[ "$VERIFY_GZIP" -eq 1 ]]; then
gzip -t "$TMP_FILE"
fi
mv "$TMP_FILE" "$TARGET_FILE"
printf 'Backup created: %s\n' "$TARGET_FILE"
if [[ "$RETENTION_DAYS" -gt 0 ]]; then
find "$OUTPUT_DIR" -maxdepth 1 -type f -name 'planet_*.sql.gz' -mtime +"$RETENTION_DAYS" -delete
fi
+52
View File
@@ -0,0 +1,52 @@
#!/usr/bin/env python3
"""Versioned database migration CLI for Planet."""
from __future__ import annotations
import argparse
import asyncio
import json
from pathlib import Path
import sys
REPO_ROOT = Path(__file__).resolve().parents[1]
BACKEND_DIR = REPO_ROOT / "backend"
if str(BACKEND_DIR) not in sys.path:
sys.path.insert(0, str(BACKEND_DIR))
from app.db.migrations import get_migration_status, run_migrations, stamp_migrations # noqa: E402
from app.db.session import engine # noqa: E402
async def _run_command(args: argparse.Namespace) -> int:
try:
if args.command == "status":
status = await get_migration_status(engine)
print(json.dumps(status, indent=2, ensure_ascii=False))
return 1 if status["mismatches"] else 0
if args.command == "upgrade":
applied = await run_migrations(engine)
print(json.dumps({"applied": applied}, ensure_ascii=False))
return 0
if args.command == "stamp":
stamped = await stamp_migrations(engine, args.version)
print(json.dumps({"stamped": stamped}, ensure_ascii=False))
return 0
return 2
finally:
await engine.dispose()
def main() -> int:
parser = argparse.ArgumentParser(description="Planet versioned schema migration helper")
subparsers = parser.add_subparsers(dest="command", required=True)
subparsers.add_parser("status", help="Show applied, pending, and checksum-mismatched migrations")
subparsers.add_parser("upgrade", help="Apply all pending migrations")
stamp_parser = subparsers.add_parser("stamp", help="Mark migrations up to VERSION as applied")
stamp_parser.add_argument("version", help="4-digit migration version (e.g. 0001)")
args = parser.parse_args()
return asyncio.run(_run_command(args))
if __name__ == "__main__":
raise SystemExit(main())
+1
View File
@@ -17,6 +17,7 @@ main() {
harness_run zsh -n scripts/lib/docker-proxy.zsh
harness_run zsh -n scripts/lib/docker-mirror.zsh
harness_run zsh -n scripts/lib/error-diagnostics.zsh
harness_run zsh -n scripts/lib/deploy.zsh
harness_run zsh -n scripts/windows/restart.zsh
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_docker_bootstrap.py
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_docker_command.py
+502
View File
@@ -0,0 +1,502 @@
#!/usr/bin/env zsh
# Production deployment, backup, and migration helpers sourced by planet.sh.
deploy_resolve_python() {
local venv_python="${SCRIPT_DIR:-.}/.venv/bin/python"
if [ -x "$venv_python" ]; then
printf "%s\n" "$venv_python"
return 0
fi
if command -v python3 >/dev/null 2>&1; then
command -v python3
return 0
fi
return 1
}
deploy_usage() {
cat <<'EOF'
用法: ./planet.sh deploy [up|down|restart|status|logs|init-env] [选项]
选项:
--split 启用 API + Worker 拆分高可用模式 (backend API-only + worker 调度实例)
--no-build 使用本地已有镜像启动,不重新构建
--env-file <path> 指定部署环境变量文件 (默认: ./.env.deploy)
--force 与 init-env 配合使用,允许覆盖已有环境文件
-h, --help 显示此帮助信息
EOF
}
backup_usage() {
"$SCRIPT_DIR/scripts/backup_db.sh" --help
}
migrate_usage() {
cat <<'EOF'
用法: ./planet.sh migrate {status|upgrade|stamp <version>} [--container [容器名]]
说明:
status 查看已应用、待应用与校验和异常的数据库迁移
upgrade 按顺序执行所有待应用迁移 (带 PostgreSQL Advisory Lock)
stamp <version> 将指定版本及之前迁移标记为已应用(不执行 SQL)
--container [name] 在运行中的后端容器内执行 (默认: planet_deploy_backend)
EOF
}
deploy_parse_env_file_value() {
local env_file="$1"
local target_key="$2"
local default_val="${3:-}"
local py_bin=""
py_bin="$(deploy_resolve_python || true)"
[ -n "$py_bin" ] && [ -f "$env_file" ] || {
printf "%s\n" "$default_val"
return 0
}
"$py_bin" - "$env_file" "$target_key" "$default_val" <<'PY'
from pathlib import Path
import sys
env_path, key, default_val = Path(sys.argv[1]), sys.argv[2], sys.argv[3]
found = default_val
for raw in env_path.read_text(encoding="utf-8", errors="ignore").splitlines():
line = raw.strip()
if not line or line.startswith("#") or "=" not in line:
continue
k, v = line.split("=", 1)
k = k.strip()
if k.startswith("export "):
k = k[len("export "):].strip()
if k == key:
v = v.strip()
if len(v) >= 2 and v[0] == v[-1] and v[0] in ("'", '"'):
v = v[1:-1]
found = v
print(found)
PY
}
deploy_init_env() {
local env_file="$1"
local force="${2:-0}"
local py_bin=""
if [ -f "$env_file" ] && [ "$force" -ne 1 ]; then
log_error "部署环境文件已存在: ${env_file}(如需覆盖请追加 --force)"
return 1
fi
py_bin="$(deploy_resolve_python || true)"
if [ -z "$py_bin" ]; then
log_error "未找到 Python 运行时,无法生成高强度随机密钥"
return 1
fi
local admin_user="${INITIAL_ADMIN_USERNAME:-}"
local admin_email="${INITIAL_ADMIN_EMAIL:-}"
local admin_password="${INITIAL_ADMIN_PASSWORD:-}"
local generated_password=0
if [ -z "$admin_user" ]; then
if [ -t 0 ]; then
printf "初始超级管理员用户名 [admin_prod]: " >&2
read -r admin_user || true
fi
admin_user="${admin_user:-admin_prod}"
fi
if [ -z "$admin_email" ]; then
local default_email="${admin_user}@planet.local"
if [ -t 0 ]; then
printf "初始超级管理员邮箱 [%s]: " "$default_email" >&2
read -r admin_email || true
fi
admin_email="${admin_email:-$default_email}"
fi
if [ -z "$admin_password" ]; then
if [ -t 0 ]; then
local password_confirm=""
while true; do
printf "初始超级管理员密码 (至少8位): " >&2
read -rs admin_password || true
printf "\n" >&2
if [ "${#admin_password}" -lt 8 ]; then
log_warn "密码长度不能少于 8 位,请重新输入"
continue
fi
printf "确认密码: " >&2
read -rs password_confirm || true
printf "\n" >&2
if [ "$admin_password" != "$password_confirm" ]; then
log_warn "两次输入密码不一致,请重新输入"
continue
fi
break
done
else
admin_password="$("$py_bin" -c 'import secrets; print(secrets.token_urlsafe(14))')"
generated_password=1
fi
fi
mkdir -p "$(dirname "$env_file")"
DEPLOY_ENV_TARGET="$env_file" \
DEPLOY_ADMIN_USER="$admin_user" \
DEPLOY_ADMIN_EMAIL="$admin_email" \
DEPLOY_ADMIN_PASSWORD="$admin_password" \
DEPLOY_CORS_ORIGINS="${CORS_ORIGINS:-[]}" \
DEPLOY_ADMIN_PORT="${PLANET_ADMIN_PORT:-3000}" \
DEPLOY_FRONTEND_TARGET="${PLANET_FRONTEND_TARGET:-full}" \
"$py_bin" - <<'PY'
import base64
import os
from pathlib import Path
import secrets
target = Path(os.environ["DEPLOY_ENV_TARGET"])
secret_key = secrets.token_urlsafe(40)
service_token = secrets.token_urlsafe(32)
encryption_key = base64.urlsafe_b64encode(secrets.token_bytes(32)).decode("ascii")
pg_password = secrets.token_urlsafe(20)
redis_password = secrets.token_urlsafe(20)
content = "\n".join(
[
"# Planet production deployment environment (generated by ./planet.sh deploy init-env)",
"APP_ENV=production",
"PLANET_ROLE=all",
f"PLANET_FRONTEND_TARGET={os.environ['DEPLOY_FRONTEND_TARGET']}",
f"PLANET_ADMIN_PORT={os.environ['DEPLOY_ADMIN_PORT']}",
f"CORS_ORIGINS={os.environ['DEPLOY_CORS_ORIGINS']}",
"",
"# Cryptographic keys and internal service tokens",
f"SECRET_KEY={secret_key}",
"ACCESS_TOKEN_EXPIRE_MINUTES=60",
"REFRESH_TOKEN_EXPIRE_DAYS=7",
f"AI_PROVIDER_SERVICE_TOKEN={service_token}",
f"SETTINGS_ENCRYPTION_KEY={encryption_key}",
"",
"# Database & Redis",
"POSTGRES_USER=postgres",
f"POSTGRES_PASSWORD={pg_password}",
"POSTGRES_DB=planet_db",
f"REDIS_PASSWORD={redis_password}",
"",
"# Initial super_admin (used when bootstrapping an empty/production DB)",
f"INITIAL_ADMIN_USERNAME={os.environ['DEPLOY_ADMIN_USER']}",
f"INITIAL_ADMIN_EMAIL={os.environ['DEPLOY_ADMIN_EMAIL']}",
f"INITIAL_ADMIN_PASSWORD={os.environ['DEPLOY_ADMIN_PASSWORD']}",
"",
"# Collector concurrency guardrails",
"COLLECTOR_MAX_CONCURRENCY=2",
"COLLECTOR_HEAVY_CONCURRENCY=1",
"",
]
)
target.write_text(content, encoding="utf-8")
os.chmod(target, 0o600)
PY
log_success "已生成生产部署环境文件: ${env_file} (权限 0600)"
if [ "$generated_password" -eq 1 ]; then
log_note "已为非交互环境自动生成初始超级管理员密码,请在 ${env_file} 中查看 INITIAL_ADMIN_PASSWORD"
fi
}
deploy_validate_env_file() {
local env_file="$1"
local py_bin=""
if [ ! -f "$env_file" ]; then
log_error "缺少部署环境文件: ${env_file}"
return 1
fi
py_bin="$(deploy_resolve_python || true)"
if [ -z "$py_bin" ]; then
log_error "未找到 Python 运行时,无法校验生产环境配置"
return 1
fi
"$py_bin" - "$env_file" <<'PY'
import json
from pathlib import Path
import sys
env_path = Path(sys.argv[1])
values: dict[str, str] = {}
for raw in env_path.read_text(encoding="utf-8", errors="ignore").splitlines():
line = raw.strip()
if not line or line.startswith("#") or "=" not in line:
continue
k, v = line.split("=", 1)
k = k.strip()
if k.startswith("export "):
k = k[len("export "):].strip()
v = v.strip()
if len(v) >= 2 and v[0] == v[-1] and v[0] in ("'", '"'):
v = v[1:-1]
values[k] = v
weak_secrets = {
"",
"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_tokens = {"", "change-me", "change_me", "replace-with-internal-token"}
errors: list[str] = []
app_env = values.get("APP_ENV", "production").strip().lower()
if app_env != "production":
errors.append(f"APP_ENV 应为 production(当前: {app_env!r})")
secret_key = values.get("SECRET_KEY", "").strip()
if secret_key in weak_secrets or len(secret_key) < 32:
errors.append("SECRET_KEY 必须为至少 32 字符的随机字符串且不能使用占位符")
try:
if int(values.get("ACCESS_TOKEN_EXPIRE_MINUTES", "60")) <= 0:
errors.append("ACCESS_TOKEN_EXPIRE_MINUTES 必须大于 0")
except ValueError:
errors.append("ACCESS_TOKEN_EXPIRE_MINUTES 必须为整数")
try:
if int(values.get("REFRESH_TOKEN_EXPIRE_DAYS", "7")) <= 0:
errors.append("REFRESH_TOKEN_EXPIRE_DAYS 必须大于 0")
except ValueError:
errors.append("REFRESH_TOKEN_EXPIRE_DAYS 必须为整数")
service_token = values.get("AI_PROVIDER_SERVICE_TOKEN", "").strip()
if service_token in weak_tokens:
errors.append("AI_PROVIDER_SERVICE_TOKEN 不能为空或占位符")
cors_raw = values.get("CORS_ORIGINS", "[]").strip()
try:
cors_list = json.loads(cors_raw) if cors_raw else []
if not isinstance(cors_list, list):
errors.append("CORS_ORIGINS 必须为 JSON 数组")
elif "*" in cors_list:
errors.append("生产环境 CORS_ORIGINS 禁止包含 '*'")
except json.JSONDecodeError:
errors.append("CORS_ORIGINS 必须为合法 JSON 数组(例如 [] 或 [\"https://planet.example.com\"])")
if errors:
for err in errors:
sys.stderr.write(f"配置校验失败: {err}\n")
raise SystemExit(1)
PY
}
deploy_compose_exec() {
local env_file="$1"
local split_mode="$2"
shift 2
local -a prefix=()
local -a profile_args=()
if [ "$split_mode" -eq 1 ]; then
prefix=(env PLANET_ROLE=api)
profile_args=(--profile split)
fi
if (( $+functions[compose_available] )) && compose_available; then
"${prefix[@]}" docker compose --env-file "$env_file" -f "$SCRIPT_DIR/docker-compose.deploy.yml" "${profile_args[@]}" "$@"
return $?
fi
if command -v docker-compose >/dev/null 2>&1; then
"${prefix[@]}" docker-compose --env-file "$env_file" -f "$SCRIPT_DIR/docker-compose.deploy.yml" "${profile_args[@]}" "$@"
return $?
fi
log_error "未找到 Docker Compose,请先安装或启动 Docker"
return 1
}
deploy_command() {
local action="up"
local split_mode=0
local no_build=0
local force_init=0
local env_file="$SCRIPT_DIR/.env.deploy"
local -a passthrough=()
if [ "$#" -gt 0 ]; then
case "$1" in
up|down|restart|status|logs|init-env)
action="$1"
shift
;;
-h|--help|help)
deploy_usage
return 0
;;
esac
fi
while [ "$#" -gt 0 ]; do
case "$1" in
--split)
split_mode=1
shift
;;
--no-build)
no_build=1
shift
;;
--force)
force_init=1
shift
;;
--env-file)
if [ "$#" -lt 2 ]; then
log_error "--env-file 需要提供路径参数"
return 1
fi
env_file="$2"
shift 2
;;
--env-file=*)
env_file="${1#--env-file=}"
shift
;;
-h|--help|help)
deploy_usage
return 0
;;
*)
passthrough+=("$1")
shift
;;
esac
done
case "$action" in
init-env)
deploy_init_env "$env_file" "$force_init"
return $?
;;
up)
if (( $+functions[ensure_docker_runtime] )); then
ensure_docker_runtime "${PLANET_COMMAND_ARGS[@]}" || return 1
fi
if [ ! -f "$env_file" ]; then
log_step "未发现 ${env_file},正在生成生产环境配置"
deploy_init_env "$env_file" 0 || return 1
fi
deploy_validate_env_file "$env_file" || return 1
local -a up_args=(up -d)
if [ "$no_build" -eq 0 ]; then
up_args+=(--build)
fi
[ "$split_mode" -eq 1 ] && log_step "启动生产环境 (API + Worker 拆分模式)" || log_step "启动生产环境 (单节点模式)"
deploy_compose_exec "$env_file" "$split_mode" "${up_args[@]}" "${passthrough[@]}" || return 1
local admin_port=""
admin_port="$(deploy_parse_env_file_value "$env_file" "PLANET_ADMIN_PORT" "3000")"
log_success "生产环境容器已启动: http://127.0.0.1:${admin_port}/"
if command -v curl >/dev/null 2>&1; then
if curl -fsS --max-time 3 "http://127.0.0.1:${admin_port}/api/health/ready" >/dev/null 2>&1; then
log_success "后端就绪探针 (/api/health/ready) 已通过"
else
log_note "服务仍在初始化,稍后可执行 ./planet.sh deploy status 查看就绪状态"
fi
fi
;;
down)
deploy_compose_exec "$env_file" "$split_mode" down "${passthrough[@]}"
;;
restart)
deploy_validate_env_file "$env_file" || return 1
deploy_compose_exec "$env_file" "$split_mode" restart "${passthrough[@]}"
;;
status)
deploy_compose_exec "$env_file" "$split_mode" ps
local admin_port=""
admin_port="$(deploy_parse_env_file_value "$env_file" "PLANET_ADMIN_PORT" "3000")"
if (( $+functions[print_http_health_status] )); then
print_http_health_status "生产入口存活" "http://127.0.0.1:${admin_port}/api/health/live"
print_http_health_status "生产入口就绪" "http://127.0.0.1:${admin_port}/api/health/ready"
fi
;;
logs)
if [ "${#passthrough[@]}" -gt 0 ]; then
deploy_compose_exec "$env_file" "$split_mode" logs -f "${passthrough[@]}"
else
deploy_compose_exec "$env_file" "$split_mode" logs --tail 80 -f
fi
;;
esac
}
backup_command() {
for arg in "$@"; do
case "$arg" in
-h|--help|help)
backup_usage
return 0
;;
esac
done
"$SCRIPT_DIR/scripts/backup_db.sh" "$@"
}
migrate_command() {
local use_container=0
local container_name="planet_deploy_backend"
local -a migrate_args=()
while [ "$#" -gt 0 ]; do
case "$1" in
-h|--help|help)
migrate_usage
return 0
;;
--container)
use_container=1
if [ "$#" -ge 2 ] && [[ "$2" != -* ]] && [ "$2" != "status" ] && [ "$2" != "upgrade" ] && [ "$2" != "stamp" ]; then
container_name="$2"
shift 2
else
shift
fi
;;
--container=*)
use_container=1
container_name="${1#--container=}"
shift
;;
*)
migrate_args+=("$1")
shift
;;
esac
done
if [ "${#migrate_args[@]}" -eq 0 ]; then
migrate_usage
return 2
fi
if [ "$use_container" -eq 1 ]; then
docker exec "$container_name" uv run --frozen --no-dev --project /app python /app/scripts/db_migrate.py "${migrate_args[@]}"
return $?
fi
local py_bin=""
py_bin="$(deploy_resolve_python || true)"
if command -v uv >/dev/null 2>&1; then
uv run --frozen --project "$SCRIPT_DIR" python "$SCRIPT_DIR/scripts/db_migrate.py" "${migrate_args[@]}"
elif [ -n "$py_bin" ]; then
PYTHONPATH="$SCRIPT_DIR/backend" "$py_bin" "$SCRIPT_DIR/scripts/db_migrate.py" "${migrate_args[@]}"
else
log_error "未找到 uv 或 Python 运行时"
return 1
fi
}
Generated
+1 -1
View File
@@ -757,7 +757,7 @@ wheels = [
[[package]]
name = "planet"
version = "0.77.0"
version = "0.78.0"
source = { virtual = "." }
dependencies = [
{ name = "aiofiles" },