Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4b2004b7d8 | ||
|
|
41059ca42a | ||
|
|
b7772f664c | ||
|
|
352b34e7c6 | ||
|
|
1e9508f2f1 | ||
|
|
e53c3af355 | ||
|
|
5fc698d738 | ||
|
|
e6aa8c539b |
No files matched your search
@@ -176,7 +176,35 @@ Push to remote:
|
||||
```
|
||||
- If remote publication was not requested or remote access is restricted, report the commit and tag as complete and output the push commands for manual execution.
|
||||
|
||||
### Step 9 — Completion summary
|
||||
### Step 9 — Publish and verify the Gitea Release
|
||||
|
||||
When remote publication is requested, verify the remote tag points to the
|
||||
release commit. For `gitea.rclaw.top/linkong/planet`, publish from the workstation
|
||||
using the command below. The publisher builds the three production images and
|
||||
the desktop packages from the tag. A published stable release triggers the
|
||||
server's two-minute Compose deployment check. The workstation can go offline
|
||||
after publication. Check the live update manifest and the running image digests
|
||||
before reporting production deployment complete.
|
||||
|
||||
```bash
|
||||
python3 scripts/release_publish.py --tag vx.x.x --use-git-credential
|
||||
```
|
||||
|
||||
When verified desktop artifacts for the exact tag already exist, pass their
|
||||
directory explicitly. A queued Gitea Actions run does not block local publication.
|
||||
|
||||
```bash
|
||||
python3 scripts/release_publish.py --tag vx.x.x --assets-dir client/release --dry-run
|
||||
python3 scripts/release_publish.py --tag vx.x.x --assets-dir client/release --use-git-credential
|
||||
```
|
||||
|
||||
Use `GITEA_TOKEN` instead of `--use-git-credential` when publishing with a
|
||||
configured token. The publish script uploads to a draft and checks the
|
||||
attachment names and sizes before publishing. Verify the published Release URL
|
||||
and expected attachments through Gitea before reporting success. If Gitea is
|
||||
unreachable, report the tag and package state and why publication is incomplete.
|
||||
|
||||
### Step 10 — Completion summary
|
||||
|
||||
```
|
||||
✓ Version bumped: 0.76.18 → 0.76.19
|
||||
@@ -187,6 +215,7 @@ Push to remote:
|
||||
✓ commit: release: bump version to 0.76.19
|
||||
✓ tag: v0.76.19
|
||||
✓ Pushed to origin/dev (or reported pending manual push)
|
||||
✓ Gitea Release and attachments verified (when publication was requested)
|
||||
```
|
||||
|
||||
## Notes
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
!scripts/
|
||||
!scripts/build_earth_boundary_china_pov_geojson.py
|
||||
!scripts/build_earth_boundary_pmtiles.py
|
||||
!scripts/db_migrate.py
|
||||
!scripts/earth_boundary_policy.py
|
||||
!resources/
|
||||
!resources/earth/
|
||||
|
||||
@@ -4,8 +4,7 @@ on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
tags:
|
||||
- "v*"
|
||||
# Tagged production releases are published on demand from the workstation.
|
||||
workflow_dispatch:
|
||||
|
||||
env:
|
||||
@@ -17,18 +16,18 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Resolve image tags
|
||||
id: meta
|
||||
run: |
|
||||
echo "sha_tag=${GITHUB_SHA}" >> "$GITHUB_OUTPUT"
|
||||
if printf "%s" "${GITHUB_REF}" | grep -q '^refs/tags/v'; then
|
||||
echo "release_tag=${GITHUB_REF_NAME}" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "release_tag=" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
- name: Login to registry
|
||||
run: echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login "$REGISTRY" -u "${{ secrets.REGISTRY_USER }}" --password-stdin
|
||||
- name: Build and push images
|
||||
env:
|
||||
REGISTRY_USER: ${{ secrets.REGISTRY_USER }}
|
||||
REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }}
|
||||
run: printf '%s' "$REGISTRY_PASSWORD" | docker login "$REGISTRY" -u "$REGISTRY_USER" --password-stdin
|
||||
- name: Publish immutable production images
|
||||
if: startsWith(github.ref, 'refs/tags/v')
|
||||
run: |
|
||||
export PLANET_RELEASE_DOCKER_CONFIG="${DOCKER_CONFIG:-$HOME/.docker}"
|
||||
python3 scripts/production_release.py "$GITHUB_REF_NAME"
|
||||
- name: Build and push staging images
|
||||
if: "!startsWith(github.ref, 'refs/tags/v')"
|
||||
run: |
|
||||
for service in frontend admin backend aiprovider; do
|
||||
extra_build_args=""
|
||||
@@ -52,18 +51,13 @@ jobs:
|
||||
;;
|
||||
esac
|
||||
|
||||
image="$REGISTRY/$IMAGE_NAMESPACE/$service:${{ steps.meta.outputs.sha_tag }}"
|
||||
image="$REGISTRY/$IMAGE_NAMESPACE/$service:$GITHUB_SHA"
|
||||
docker build $extra_build_args -t "$image" -f "$dockerfile" "$context"
|
||||
docker push "$image"
|
||||
|
||||
if [ -n "${{ steps.meta.outputs.release_tag }}" ]; then
|
||||
release_image="$REGISTRY/$IMAGE_NAMESPACE/$service:${{ steps.meta.outputs.release_tag }}"
|
||||
docker tag "$image" "$release_image"
|
||||
docker push "$release_image"
|
||||
fi
|
||||
done
|
||||
|
||||
client_release:
|
||||
needs: images
|
||||
if: startsWith(github.ref, 'refs/tags/v')
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
|
||||
@@ -6,8 +6,10 @@
|
||||
# 敏感文件
|
||||
# ----------------------
|
||||
.env
|
||||
.env.deploy
|
||||
.env.local
|
||||
.env.*.local
|
||||
backups/
|
||||
config/earth-boundary-sources.local.json
|
||||
*.pem
|
||||
*.key
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
# Shared service settings
|
||||
SERVICE_NAME=planet-ai-provider
|
||||
SERVICE_VERSION=0.1.0
|
||||
APP_ENV=development
|
||||
AI_PROVIDER_SERVICE_TOKEN=change_me
|
||||
AI_TIMEOUT_SECONDS=60
|
||||
AI_HTTP_RETRY_ATTEMPTS=2
|
||||
@@ -28,18 +29,18 @@ AI_MODEL=MiniMax-M2.7
|
||||
|
||||
# MiniMax CN Anthropic-compatible example
|
||||
AI_BASE_URL=https://api.minimaxi.com/anthropic
|
||||
AI_API_KEY=sk-cp-change-me
|
||||
AI_API_KEY=replace-with-provider-key
|
||||
AI_MAX_TOKENS=1200
|
||||
AI_ANTHROPIC_VERSION=2023-06-01
|
||||
|
||||
# Optional provider-specific keys used by Settings fallback before AI_API_KEY
|
||||
# MINIMAX_API_KEY=sk-cp-change-me
|
||||
# OPENAI_API_KEY=sk-change-me
|
||||
# ANTHROPIC_API_KEY=sk-ant-change-me
|
||||
# DEEPSEEK_API_KEY=sk-change-me
|
||||
# DASHSCOPE_API_KEY=sk-change-me
|
||||
# MOONSHOT_API_KEY=sk-change-me
|
||||
# OPENROUTER_API_KEY=sk-or-change-me
|
||||
# MINIMAX_API_KEY=replace-with-minimax-key
|
||||
# OPENAI_API_KEY=replace-with-openai-key
|
||||
# ANTHROPIC_API_KEY=replace-with-anthropic-key
|
||||
# DEEPSEEK_API_KEY=replace-with-deepseek-key
|
||||
# DASHSCOPE_API_KEY=replace-with-dashscope-key
|
||||
# MOONSHOT_API_KEY=replace-with-moonshot-key
|
||||
# OPENROUTER_API_KEY=replace-with-openrouter-key
|
||||
|
||||
# OpenAI-compatible example (vLLM / LM Studio / One API / local gateway)
|
||||
# AI_PROVIDER=openai
|
||||
|
||||
@@ -7,6 +7,7 @@ from pydantic_settings import BaseSettings
|
||||
class Settings(BaseSettings):
|
||||
SERVICE_NAME: str = "planet-ai-provider"
|
||||
SERVICE_VERSION: str = "0.1.0"
|
||||
APP_ENV: str = "development"
|
||||
|
||||
AI_PROVIDER: str = "disabled"
|
||||
AI_PROVIDER_API: str = "auto"
|
||||
@@ -20,9 +21,14 @@ class Settings(BaseSettings):
|
||||
|
||||
AI_PROVIDER_SERVICE_TOKEN: str = ""
|
||||
|
||||
@property
|
||||
def is_production(self) -> bool:
|
||||
return str(self.APP_ENV or "").strip().lower() == "production"
|
||||
|
||||
class Config:
|
||||
env_file = Path(__file__).parent / ".env"
|
||||
case_sensitive = True
|
||||
extra = "ignore"
|
||||
|
||||
|
||||
@lru_cache()
|
||||
|
||||
+63
-2
@@ -1,6 +1,10 @@
|
||||
from contextlib import asynccontextmanager
|
||||
import hmac
|
||||
import json
|
||||
from uuid import uuid4
|
||||
|
||||
from fastapi import Depends, FastAPI, Header, HTTPException, Request, Response, status
|
||||
from fastapi.responses import StreamingResponse
|
||||
|
||||
from aiprovider.config import settings
|
||||
from aiprovider.provider_service import ProviderService
|
||||
@@ -10,10 +14,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 +51,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",
|
||||
@@ -97,3 +126,35 @@ async def analyze(
|
||||
):
|
||||
response.headers["X-Request-ID"] = request.state.request_id
|
||||
return await provider_service.analyze(payload)
|
||||
|
||||
|
||||
@app.post(
|
||||
"/v1/analyze/stream",
|
||||
dependencies=[Depends(verify_service_token)],
|
||||
)
|
||||
async def analyze_stream(
|
||||
payload: SituationalAnalysisRequest,
|
||||
request: Request,
|
||||
provider_service: ProviderService = Depends(get_provider_service),
|
||||
):
|
||||
request_id = request.state.request_id
|
||||
|
||||
async def event_generator():
|
||||
try:
|
||||
async for item in provider_service.stream_analyze(payload):
|
||||
event_name = str(item.get("event") or "message")
|
||||
yield f"event: {event_name}\ndata: {json.dumps(item, ensure_ascii=False)}\n\n"
|
||||
except Exception as exc:
|
||||
detail = exc.detail if isinstance(exc, HTTPException) else exc
|
||||
err_payload = {"event": "error", "detail": str(detail)}
|
||||
yield f"event: error\ndata: {json.dumps(err_payload, ensure_ascii=False)}\n\n"
|
||||
|
||||
return StreamingResponse(
|
||||
event_generator(),
|
||||
media_type="text/event-stream",
|
||||
headers={
|
||||
"Cache-Control": "no-cache",
|
||||
"X-Accel-Buffering": "no",
|
||||
"X-Request-ID": request_id,
|
||||
},
|
||||
)
|
||||
+472
-41
@@ -1,6 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections.abc import AsyncIterator
|
||||
import json
|
||||
from typing import Any
|
||||
from uuid import NAMESPACE_URL, uuid4, uuid5
|
||||
@@ -97,17 +98,22 @@ class ProviderService:
|
||||
)
|
||||
|
||||
prompt = self._build_prompt(payload)
|
||||
conversation_messages = self._build_conversation_messages(payload, prompt)
|
||||
if payload.context.get("session_id") is not None:
|
||||
self.session_id = str(uuid5(NAMESPACE_URL, f"planet:{payload.context['session_id']}"))
|
||||
|
||||
provider_api = self._resolve_model_provider_api(model)
|
||||
|
||||
if provider_api == "openai-completions":
|
||||
data = await self._request_openai_compatible(model, prompt, payload.system_prompt)
|
||||
data = await self._request_openai_compatible(
|
||||
model, prompt, payload.system_prompt, conversation_messages=conversation_messages
|
||||
)
|
||||
content = self._extract_openai_content(data)
|
||||
content_blocks = self._extract_openai_blocks(data)
|
||||
elif provider_api == "openai-responses":
|
||||
data = await self._request_openai_responses(model, prompt, payload.system_prompt)
|
||||
data = await self._request_openai_responses(
|
||||
model, prompt, payload.system_prompt, conversation_messages=conversation_messages
|
||||
)
|
||||
content_blocks = self._extract_responses_blocks(data)
|
||||
content = "".join(block.text for block in content_blocks if block.text)
|
||||
elif provider_api == "anthropic-messages":
|
||||
@@ -116,11 +122,14 @@ class ProviderService:
|
||||
prompt,
|
||||
payload.thinking,
|
||||
payload.system_prompt,
|
||||
conversation_messages=conversation_messages,
|
||||
)
|
||||
content = self._extract_anthropic_content(data)
|
||||
content_blocks = self._extract_anthropic_blocks(data)
|
||||
elif provider_api == "ollama-generate":
|
||||
data = await self._request_ollama(model, prompt, payload.system_prompt)
|
||||
data = await self._request_ollama(
|
||||
model, prompt, payload.system_prompt, conversation_messages=conversation_messages
|
||||
)
|
||||
content = self._extract_ollama_content(data)
|
||||
content_blocks = self._extract_ollama_blocks(data)
|
||||
else:
|
||||
@@ -142,6 +151,394 @@ class ProviderService:
|
||||
raw_response=data,
|
||||
)
|
||||
|
||||
async def stream_analyze(
|
||||
self,
|
||||
payload: SituationalAnalysisRequest,
|
||||
) -> AsyncIterator[dict[str, Any]]:
|
||||
if self.provider == "disabled":
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="AI provider is disabled. Configure AI_PROVIDER in .env to enable analysis.",
|
||||
)
|
||||
|
||||
model = payload.preferred_model or self.default_model
|
||||
has_credentials = bool(self.api_key) if self._requires_api_key() else True
|
||||
if not self.base_url or not has_credentials or not model:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="AI provider is not fully configured. Check AI_BASE_URL, AI_API_KEY, and AI_MODEL.",
|
||||
)
|
||||
|
||||
prompt = self._build_prompt(payload)
|
||||
conversation_messages = self._build_conversation_messages(payload, prompt)
|
||||
if payload.context.get("session_id") is not None:
|
||||
self.session_id = str(uuid5(NAMESPACE_URL, f"planet:{payload.context['session_id']}"))
|
||||
|
||||
provider_api = self._resolve_model_provider_api(model)
|
||||
yield {"event": "start", "provider": self.provider, "model": model}
|
||||
|
||||
if provider_api == "anthropic-messages":
|
||||
async for item in self._stream_anthropic_messages(
|
||||
model,
|
||||
prompt,
|
||||
payload.thinking,
|
||||
payload.system_prompt,
|
||||
conversation_messages=conversation_messages,
|
||||
):
|
||||
yield item
|
||||
return
|
||||
if provider_api == "openai-completions":
|
||||
async for item in self._stream_openai_compatible(
|
||||
model, prompt, payload.system_prompt, conversation_messages=conversation_messages
|
||||
):
|
||||
yield item
|
||||
return
|
||||
if provider_api == "openai-responses":
|
||||
async for item in self._stream_openai_responses(
|
||||
model, prompt, payload.system_prompt, conversation_messages=conversation_messages
|
||||
):
|
||||
yield item
|
||||
return
|
||||
if provider_api == "ollama-generate":
|
||||
async for item in self._stream_ollama(
|
||||
model, prompt, payload.system_prompt, conversation_messages=conversation_messages
|
||||
):
|
||||
yield item
|
||||
return
|
||||
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f"Unsupported AI provider API: {self.provider_api}",
|
||||
)
|
||||
|
||||
def _outbound_headers(self, headers: dict[str, str]) -> dict[str, str]:
|
||||
merged = {"User-Agent": "Planet/1.0", **headers}
|
||||
if self.provider == "opencode-go":
|
||||
merged["x-opencode-session"] = self.session_id
|
||||
return merged
|
||||
|
||||
async def _iter_sse_events(
|
||||
self,
|
||||
response: httpx.Response,
|
||||
) -> AsyncIterator[tuple[str, str]]:
|
||||
event_name = ""
|
||||
data_lines: list[str] = []
|
||||
async for raw_line in response.aiter_lines():
|
||||
line = raw_line.rstrip("\r")
|
||||
if line == "":
|
||||
if data_lines:
|
||||
yield event_name, "\n".join(data_lines)
|
||||
event_name = ""
|
||||
data_lines = []
|
||||
continue
|
||||
if line.startswith(":"):
|
||||
continue
|
||||
if line.startswith("event:"):
|
||||
event_name = line[6:].strip()
|
||||
elif line.startswith("data:"):
|
||||
data_lines.append(line[5:].lstrip())
|
||||
if data_lines:
|
||||
yield event_name, "\n".join(data_lines)
|
||||
|
||||
def _build_anthropic_request(
|
||||
self,
|
||||
model: str,
|
||||
prompt: str,
|
||||
thinking: dict[str, Any] | None = None,
|
||||
system_prompt: str | None = None,
|
||||
*,
|
||||
stream: bool = False,
|
||||
conversation_messages: list[dict[str, str]] | None = None,
|
||||
) -> tuple[str, dict[str, str], dict[str, Any]]:
|
||||
if conversation_messages and len(conversation_messages) > 1:
|
||||
anthropic_messages = [
|
||||
{"role": m["role"], "content": [{"type": "text", "text": m["content"]}]}
|
||||
for m in conversation_messages
|
||||
]
|
||||
else:
|
||||
anthropic_messages = [{"role": "user", "content": [{"type": "text", "text": prompt}]}]
|
||||
resolved_thinking, resolved_output_config = self._resolve_anthropic_thinking(thinking, model)
|
||||
thinking_active = bool(
|
||||
resolved_thinking
|
||||
and str(resolved_thinking.get("type") or "").lower() in {"enabled", "adaptive"}
|
||||
)
|
||||
max_tokens = self.max_tokens
|
||||
if resolved_thinking and isinstance(resolved_thinking.get("budget_tokens"), (int, float)):
|
||||
budget_tokens = int(resolved_thinking["budget_tokens"])
|
||||
if budget_tokens >= max_tokens:
|
||||
max_tokens = budget_tokens + 1024
|
||||
|
||||
request_body: dict[str, Any] = {
|
||||
"model": model,
|
||||
"messages": anthropic_messages,
|
||||
"max_tokens": max_tokens,
|
||||
}
|
||||
if not thinking_active:
|
||||
request_body["temperature"] = 0.2
|
||||
if stream:
|
||||
request_body["stream"] = True
|
||||
resolved_system_prompt = self._resolve_system_prompt(system_prompt)
|
||||
if resolved_system_prompt:
|
||||
request_body["system"] = resolved_system_prompt
|
||||
if resolved_thinking:
|
||||
request_body["thinking"] = resolved_thinking
|
||||
if resolved_output_config:
|
||||
request_body["output_config"] = resolved_output_config
|
||||
path = "/v1/messages" if self.provider == "minimax" and self.base_url.endswith("/anthropic") else "/messages"
|
||||
headers = {
|
||||
"x-api-key": self.api_key,
|
||||
"anthropic-version": self.anthropic_version,
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
return path, headers, request_body
|
||||
|
||||
async def _stream_anthropic_messages(
|
||||
self,
|
||||
model: str,
|
||||
prompt: str,
|
||||
thinking: dict[str, Any] | None = None,
|
||||
system_prompt: str | None = None,
|
||||
*,
|
||||
conversation_messages: list[dict[str, str]] | None = None,
|
||||
) -> AsyncIterator[dict[str, Any]]:
|
||||
path, headers, request_body = self._build_anthropic_request(
|
||||
model,
|
||||
prompt,
|
||||
thinking,
|
||||
system_prompt,
|
||||
stream=True,
|
||||
conversation_messages=conversation_messages,
|
||||
)
|
||||
resolved_model = model
|
||||
usage: dict[str, Any] = {}
|
||||
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
||||
async with client.stream(
|
||||
"POST",
|
||||
f"{self.base_url}{path}",
|
||||
headers=self._outbound_headers(headers),
|
||||
json=request_body,
|
||||
) as response:
|
||||
if response.status_code >= 400:
|
||||
detail = (await response.aread()).decode("utf-8", errors="replace")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail=f"AI provider request failed: {detail or response.status_code}",
|
||||
)
|
||||
async for event_name, data_str in self._iter_sse_events(response):
|
||||
if data_str == "[DONE]":
|
||||
continue
|
||||
try:
|
||||
chunk = json.loads(data_str)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
if not isinstance(chunk, dict):
|
||||
continue
|
||||
msg_type = str(chunk.get("type") or event_name or "")
|
||||
if msg_type == "error":
|
||||
err = chunk.get("error") if isinstance(chunk.get("error"), dict) else {}
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail=str(err.get("message") or chunk.get("message") or "Upstream stream error"),
|
||||
)
|
||||
if msg_type == "message_start":
|
||||
message = chunk.get("message") if isinstance(chunk.get("message"), dict) else {}
|
||||
if isinstance(message.get("model"), str) and message["model"]:
|
||||
resolved_model = message["model"]
|
||||
if isinstance(message.get("usage"), dict):
|
||||
usage.update(message["usage"])
|
||||
elif msg_type == "message_delta":
|
||||
if isinstance(chunk.get("usage"), dict):
|
||||
usage.update(chunk["usage"])
|
||||
elif msg_type == "content_block_start":
|
||||
block = chunk.get("content_block") if isinstance(chunk.get("content_block"), dict) else {}
|
||||
if block.get("type") == "thinking" and isinstance(block.get("thinking"), str) and block["thinking"]:
|
||||
yield {"event": "reasoning", "delta": block["thinking"]}
|
||||
elif block.get("type") == "text" and isinstance(block.get("text"), str) and block["text"]:
|
||||
yield {"event": "text", "delta": block["text"]}
|
||||
elif msg_type == "content_block_delta":
|
||||
delta = chunk.get("delta") if isinstance(chunk.get("delta"), dict) else {}
|
||||
delta_type = str(delta.get("type") or "")
|
||||
if delta_type == "thinking_delta" and isinstance(delta.get("thinking"), str) and delta["thinking"]:
|
||||
yield {"event": "reasoning", "delta": delta["thinking"]}
|
||||
elif delta_type == "text_delta" and isinstance(delta.get("text"), str) and delta["text"]:
|
||||
yield {"event": "text", "delta": delta["text"]}
|
||||
yield {"event": "done", "provider": self.provider, "model": resolved_model, "usage": usage}
|
||||
|
||||
async def _stream_openai_compatible(
|
||||
self,
|
||||
model: str,
|
||||
prompt: str,
|
||||
system_prompt: str | None = None,
|
||||
*,
|
||||
conversation_messages: list[dict[str, str]] | None = None,
|
||||
) -> AsyncIterator[dict[str, Any]]:
|
||||
messages = []
|
||||
resolved_system_prompt = self._resolve_system_prompt(system_prompt)
|
||||
if resolved_system_prompt:
|
||||
messages.append({"role": "system", "content": resolved_system_prompt})
|
||||
if conversation_messages and len(conversation_messages) > 1:
|
||||
messages.extend(conversation_messages)
|
||||
else:
|
||||
messages.append({"role": "user", "content": prompt})
|
||||
request_body = {
|
||||
"model": model,
|
||||
"messages": messages,
|
||||
"temperature": 0.2,
|
||||
"max_tokens": self.max_tokens,
|
||||
"stream": True,
|
||||
"stream_options": {"include_usage": True},
|
||||
}
|
||||
resolved_model = model
|
||||
usage: dict[str, Any] = {}
|
||||
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
||||
async with client.stream(
|
||||
"POST",
|
||||
f"{self.base_url}/chat/completions",
|
||||
headers=self._outbound_headers(
|
||||
{"Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json"}
|
||||
),
|
||||
json=request_body,
|
||||
) as response:
|
||||
if response.status_code >= 400:
|
||||
detail = (await response.aread()).decode("utf-8", errors="replace")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail=f"AI provider request failed: {detail or response.status_code}",
|
||||
)
|
||||
async for _, data_str in self._iter_sse_events(response):
|
||||
if data_str == "[DONE]":
|
||||
break
|
||||
try:
|
||||
chunk = json.loads(data_str)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
if not isinstance(chunk, dict):
|
||||
continue
|
||||
if isinstance(chunk.get("model"), str) and chunk["model"]:
|
||||
resolved_model = chunk["model"]
|
||||
if isinstance(chunk.get("usage"), dict):
|
||||
usage.update(chunk["usage"])
|
||||
choices = chunk.get("choices") or []
|
||||
if not choices or not isinstance(choices[0], dict):
|
||||
continue
|
||||
delta = choices[0].get("delta") if isinstance(choices[0].get("delta"), dict) else {}
|
||||
for r_key in ("reasoning_content", "reasoning", "thinking"):
|
||||
r_val = delta.get(r_key)
|
||||
if isinstance(r_val, str) and r_val:
|
||||
yield {"event": "reasoning", "delta": r_val}
|
||||
break
|
||||
text_val = delta.get("content")
|
||||
if isinstance(text_val, str) and text_val:
|
||||
yield {"event": "text", "delta": text_val}
|
||||
yield {"event": "done", "provider": self.provider, "model": resolved_model, "usage": usage}
|
||||
|
||||
async def _stream_openai_responses(
|
||||
self,
|
||||
model: str,
|
||||
prompt: str,
|
||||
system_prompt: str | None = None,
|
||||
*,
|
||||
conversation_messages: list[dict[str, str]] | None = None,
|
||||
) -> AsyncIterator[dict[str, Any]]:
|
||||
responses_input: Any = (
|
||||
[{"role": m["role"], "content": m["content"]} for m in conversation_messages]
|
||||
if (conversation_messages and len(conversation_messages) > 1)
|
||||
else prompt
|
||||
)
|
||||
request_body: dict[str, Any] = {
|
||||
"model": model,
|
||||
"input": responses_input,
|
||||
"max_output_tokens": self.max_tokens,
|
||||
"store": False,
|
||||
"stream": True,
|
||||
}
|
||||
resolved_system_prompt = self._resolve_system_prompt(system_prompt)
|
||||
if resolved_system_prompt:
|
||||
request_body["instructions"] = resolved_system_prompt
|
||||
resolved_model = model
|
||||
usage: dict[str, Any] = {}
|
||||
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
||||
async with client.stream(
|
||||
"POST",
|
||||
f"{self.base_url}/responses",
|
||||
headers=self._outbound_headers(
|
||||
{"Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json"}
|
||||
),
|
||||
json=request_body,
|
||||
) as response:
|
||||
if response.status_code >= 400:
|
||||
detail = (await response.aread()).decode("utf-8", errors="replace")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail=f"AI provider request failed: {detail or response.status_code}",
|
||||
)
|
||||
async for event_name, data_str in self._iter_sse_events(response):
|
||||
if data_str == "[DONE]":
|
||||
break
|
||||
try:
|
||||
chunk = json.loads(data_str)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
if not isinstance(chunk, dict):
|
||||
continue
|
||||
ev_type = str(chunk.get("type") or event_name or "")
|
||||
if ev_type == "response.output_text.delta" and isinstance(chunk.get("delta"), str) and chunk["delta"]:
|
||||
yield {"event": "text", "delta": chunk["delta"]}
|
||||
elif ("reasoning" in ev_type or "thinking" in ev_type) and isinstance(chunk.get("delta"), str) and chunk["delta"]:
|
||||
yield {"event": "reasoning", "delta": chunk["delta"]}
|
||||
elif ev_type == "response.completed":
|
||||
resp_obj = chunk.get("response") if isinstance(chunk.get("response"), dict) else {}
|
||||
if isinstance(resp_obj.get("model"), str) and resp_obj["model"]:
|
||||
resolved_model = resp_obj["model"]
|
||||
if isinstance(resp_obj.get("usage"), dict):
|
||||
usage.update(resp_obj["usage"])
|
||||
yield {"event": "done", "provider": self.provider, "model": resolved_model, "usage": usage}
|
||||
|
||||
async def _stream_ollama(
|
||||
self,
|
||||
model: str,
|
||||
prompt: str,
|
||||
system_prompt: str | None = None,
|
||||
*,
|
||||
conversation_messages: list[dict[str, str]] | None = None,
|
||||
) -> AsyncIterator[dict[str, Any]]:
|
||||
ollama_prompt = self._format_ollama_prompt(prompt, conversation_messages)
|
||||
request_body: dict[str, Any] = {
|
||||
"model": model,
|
||||
"stream": True,
|
||||
"prompt": ollama_prompt,
|
||||
"options": {"temperature": 0.2, "num_predict": self.max_tokens},
|
||||
}
|
||||
resolved_system_prompt = self._resolve_system_prompt(system_prompt)
|
||||
if resolved_system_prompt:
|
||||
request_body["system"] = resolved_system_prompt
|
||||
usage: dict[str, Any] = {}
|
||||
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
||||
async with client.stream(
|
||||
"POST",
|
||||
f"{self.base_url}/api/generate",
|
||||
headers=self._outbound_headers({"Content-Type": "application/json"}),
|
||||
json=request_body,
|
||||
) as response:
|
||||
if response.status_code >= 400:
|
||||
detail = (await response.aread()).decode("utf-8", errors="replace")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail=f"AI provider request failed: {detail or response.status_code}",
|
||||
)
|
||||
async for line in response.aiter_lines():
|
||||
if not line.strip():
|
||||
continue
|
||||
try:
|
||||
chunk = json.loads(line)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
if isinstance(chunk.get("thinking"), str) and chunk["thinking"]:
|
||||
yield {"event": "reasoning", "delta": chunk["thinking"]}
|
||||
if isinstance(chunk.get("response"), str) and chunk["response"]:
|
||||
yield {"event": "text", "delta": chunk["response"]}
|
||||
yield {"event": "done", "provider": self.provider, "model": model, "usage": usage}
|
||||
|
||||
def _requires_api_key(self) -> bool:
|
||||
return self.provider_api != "ollama-generate"
|
||||
|
||||
@@ -165,6 +562,44 @@ class ProviderService:
|
||||
if model and provider_api
|
||||
}
|
||||
|
||||
def _build_conversation_messages(
|
||||
self,
|
||||
payload: SituationalAnalysisRequest,
|
||||
final_prompt: str,
|
||||
) -> list[dict[str, str]]:
|
||||
"""Normalize multi-turn history + current prompt into alternating user/assistant messages."""
|
||||
normalized: list[dict[str, str]] = []
|
||||
for item in getattr(payload, "messages", None) or []:
|
||||
role = str(getattr(item, "role", None) or (item.get("role") if isinstance(item, dict) else "")).strip().lower()
|
||||
content = str(getattr(item, "content", None) or (item.get("content") if isinstance(item, dict) else "")).strip()
|
||||
if role not in {"user", "assistant"} or not content:
|
||||
continue
|
||||
if not normalized and role == "assistant":
|
||||
continue
|
||||
if normalized and normalized[-1]["role"] == role:
|
||||
normalized[-1]["content"] = f"{normalized[-1]['content']}\n\n{content}"
|
||||
else:
|
||||
normalized.append({"role": role, "content": content})
|
||||
|
||||
if normalized and normalized[-1]["role"] == "user":
|
||||
normalized[-1]["content"] = f"{normalized[-1]['content']}\n\n{final_prompt}"
|
||||
else:
|
||||
normalized.append({"role": "user", "content": final_prompt})
|
||||
return normalized
|
||||
|
||||
@staticmethod
|
||||
def _format_ollama_prompt(
|
||||
prompt: str,
|
||||
conversation_messages: list[dict[str, str]] | None,
|
||||
) -> str:
|
||||
if not conversation_messages or len(conversation_messages) <= 1:
|
||||
return prompt
|
||||
history_lines = []
|
||||
for m in conversation_messages[:-1]:
|
||||
prefix = "用户" if m["role"] == "user" else "助手"
|
||||
history_lines.append(f"{prefix}: {m['content']}")
|
||||
return "历史对话:\n" + "\n".join(history_lines) + f"\n\n当前任务:\n{conversation_messages[-1]['content']}"
|
||||
|
||||
def _build_prompt(self, payload: SituationalAnalysisRequest) -> str:
|
||||
sections = [
|
||||
f"任务标题:\n{payload.title}",
|
||||
@@ -187,12 +622,17 @@ class ProviderService:
|
||||
model: str,
|
||||
prompt: str,
|
||||
system_prompt: str | None = None,
|
||||
*,
|
||||
conversation_messages: list[dict[str, str]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
messages = []
|
||||
resolved_system_prompt = self._resolve_system_prompt(system_prompt)
|
||||
if resolved_system_prompt:
|
||||
messages.append({"role": "system", "content": resolved_system_prompt})
|
||||
messages.append({"role": "user", "content": prompt})
|
||||
if conversation_messages and len(conversation_messages) > 1:
|
||||
messages.extend(conversation_messages)
|
||||
else:
|
||||
messages.append({"role": "user", "content": prompt})
|
||||
request_body = {
|
||||
"model": model,
|
||||
"messages": messages,
|
||||
@@ -209,10 +649,23 @@ class ProviderService:
|
||||
)
|
||||
|
||||
async def _request_openai_responses(
|
||||
self, model: str, prompt: str, system_prompt: str | None = None,
|
||||
self,
|
||||
model: str,
|
||||
prompt: str,
|
||||
system_prompt: str | None = None,
|
||||
*,
|
||||
conversation_messages: list[dict[str, str]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
responses_input: Any = (
|
||||
[{"role": m["role"], "content": m["content"]} for m in conversation_messages]
|
||||
if (conversation_messages and len(conversation_messages) > 1)
|
||||
else prompt
|
||||
)
|
||||
request_body: dict[str, Any] = {
|
||||
"model": model, "input": prompt, "max_output_tokens": self.max_tokens, "store": False,
|
||||
"model": model,
|
||||
"input": responses_input,
|
||||
"max_output_tokens": self.max_tokens,
|
||||
"store": False,
|
||||
}
|
||||
resolved_system_prompt = self._resolve_system_prompt(system_prompt)
|
||||
if resolved_system_prompt:
|
||||
@@ -247,44 +700,20 @@ class ProviderService:
|
||||
prompt: str,
|
||||
thinking: dict[str, Any] | None = None,
|
||||
system_prompt: str | None = None,
|
||||
*,
|
||||
conversation_messages: list[dict[str, str]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
request_body = {
|
||||
"model": model,
|
||||
"messages": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": prompt,
|
||||
}
|
||||
],
|
||||
}
|
||||
],
|
||||
"max_tokens": self.max_tokens,
|
||||
"temperature": 0.2,
|
||||
}
|
||||
resolved_system_prompt = self._resolve_system_prompt(system_prompt)
|
||||
if resolved_system_prompt:
|
||||
request_body["system"] = resolved_system_prompt
|
||||
resolved_thinking, resolved_output_config = self._resolve_anthropic_thinking(
|
||||
thinking, model
|
||||
path, headers, request_body = self._build_anthropic_request(
|
||||
model,
|
||||
prompt,
|
||||
thinking,
|
||||
system_prompt,
|
||||
stream=False,
|
||||
conversation_messages=conversation_messages,
|
||||
)
|
||||
if resolved_thinking:
|
||||
request_body["thinking"] = resolved_thinking
|
||||
if resolved_output_config:
|
||||
request_body["output_config"] = resolved_output_config
|
||||
if self.provider == "minimax" and self.base_url.endswith("/anthropic"):
|
||||
path = "/v1/messages"
|
||||
else:
|
||||
path = "/messages"
|
||||
return await self._post(
|
||||
path=path,
|
||||
headers={
|
||||
"x-api-key": self.api_key,
|
||||
"anthropic-version": self.anthropic_version,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
headers=headers,
|
||||
request_body=request_body,
|
||||
)
|
||||
|
||||
@@ -332,11 +761,13 @@ class ProviderService:
|
||||
model: str,
|
||||
prompt: str,
|
||||
system_prompt: str | None = None,
|
||||
*,
|
||||
conversation_messages: list[dict[str, str]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
request_body = {
|
||||
"model": model,
|
||||
"stream": False,
|
||||
"prompt": prompt,
|
||||
"prompt": self._format_ollama_prompt(prompt, conversation_messages),
|
||||
"options": {
|
||||
"temperature": 0.2,
|
||||
"num_predict": self.max_tokens,
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
from typing import Any
|
||||
from typing import Any, Literal
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class ChatMessage(BaseModel):
|
||||
role: Literal["user", "assistant"]
|
||||
content: str = Field(..., min_length=1, max_length=12000)
|
||||
|
||||
|
||||
class AIContentBlock(BaseModel):
|
||||
type: str
|
||||
text: str | None = None
|
||||
@@ -20,6 +25,7 @@ class SituationalAnalysisRequest(BaseModel):
|
||||
system_prompt: str | None = Field(default=None, max_length=8000)
|
||||
preferred_model: str | None = Field(default=None, max_length=200)
|
||||
thinking: dict[str, Any] | None = None
|
||||
messages: list[ChatMessage] = Field(default_factory=list, max_length=32)
|
||||
|
||||
|
||||
class SituationalAnalysisResponse(BaseModel):
|
||||
|
||||
+21
-3
@@ -1,10 +1,24 @@
|
||||
PROJECT_NAME=Intelligent Planet Plan
|
||||
APP_VERSION=0.23.0
|
||||
APP_ENV=development
|
||||
PLANET_ROLE=all
|
||||
|
||||
SECRET_KEY=change_me_to_a_random_secret
|
||||
SECRET_KEY=change_me_to_a_random_32_plus_char_secret
|
||||
ALGORITHM=HS256
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES=0
|
||||
REFRESH_TOKEN_EXPIRE_DAYS=0
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES=60
|
||||
REFRESH_TOKEN_EXPIRE_DAYS=7
|
||||
CORS_ORIGINS=["http://localhost:3000","http://127.0.0.1:3000","http://localhost:8000","http://127.0.0.1:8000","planet://earth"]
|
||||
|
||||
# Optional bootstrap super_admin on fresh/production DB
|
||||
INITIAL_ADMIN_USERNAME=
|
||||
INITIAL_ADMIN_EMAIL=
|
||||
INITIAL_ADMIN_PASSWORD=
|
||||
|
||||
# Optional encryption key for persisted SMTP & integration API keys
|
||||
SETTINGS_ENCRYPTION_KEY=
|
||||
|
||||
LOGIN_RATE_LIMIT_MAX_ATTEMPTS=10
|
||||
LOGIN_RATE_LIMIT_WINDOW_SECONDS=300
|
||||
|
||||
POSTGRES_SERVER=localhost
|
||||
POSTGRES_USER=postgres
|
||||
@@ -15,8 +29,12 @@ DATABASE_URL=postgresql+asyncpg://postgres:postgres@localhost:5432/planet_db
|
||||
REDIS_SERVER=localhost
|
||||
REDIS_PORT=6379
|
||||
REDIS_DB=0
|
||||
REDIS_PASSWORD=
|
||||
REDIS_URL=redis://localhost:6379/0
|
||||
|
||||
COLLECTOR_MAX_CONCURRENCY=2
|
||||
COLLECTOR_HEAVY_CONCURRENCY=1
|
||||
|
||||
AI_PROVIDER_SERVICE_URL=http://localhost:8010
|
||||
AI_PROVIDER_SERVICE_TOKEN=change_me
|
||||
AI_PROVIDER_TIMEOUT_SECONDS=60
|
||||
|
||||
@@ -31,6 +31,7 @@ COPY backend /app/backend
|
||||
COPY config/earth-boundary-pov-policy.china-v1.json /app/config/earth-boundary-pov-policy.china-v1.json
|
||||
COPY scripts/build_earth_boundary_china_pov_geojson.py /app/scripts/build_earth_boundary_china_pov_geojson.py
|
||||
COPY scripts/build_earth_boundary_pmtiles.py /app/scripts/build_earth_boundary_pmtiles.py
|
||||
COPY scripts/db_migrate.py /app/scripts/db_migrate.py
|
||||
COPY scripts/earth_boundary_policy.py /app/scripts/earth_boundary_policy.py
|
||||
COPY resources/earth/boundary-pov-geometry.china-v1.json /app/resources/earth/boundary-pov-geometry.china-v1.json
|
||||
COPY frontend/public/earth/assets/cards/manifest.json /app/frontend/public/earth/assets/cards/manifest.json
|
||||
|
||||
@@ -8,6 +8,7 @@ from app.api.v1 import (
|
||||
datasources,
|
||||
docs,
|
||||
earth,
|
||||
client_updates,
|
||||
tasks,
|
||||
dashboard,
|
||||
alerts,
|
||||
@@ -40,6 +41,7 @@ api_router.include_router(datasources.router, prefix="/datasources", tags=["data
|
||||
api_router.include_router(collected_data.router, prefix="/collected", tags=["collected-data"])
|
||||
api_router.include_router(docs.router, prefix="/docs", tags=["docs"])
|
||||
api_router.include_router(earth.router, prefix="/earth", tags=["earth"])
|
||||
api_router.include_router(client_updates.router, prefix="/client", tags=["client-updates"])
|
||||
api_router.include_router(tasks.router, prefix="/tasks", tags=["tasks"])
|
||||
api_router.include_router(dashboard.router, prefix="/dashboard", tags=["dashboard"])
|
||||
api_router.include_router(alerts.router, prefix="/alerts", tags=["alerts"])
|
||||
|
||||
+157
-21
@@ -1,5 +1,12 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi.security import OAuth2PasswordRequestForm
|
||||
import asyncio
|
||||
from hashlib import sha256
|
||||
import ipaddress
|
||||
import time
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Body, Depends, HTTPException, Request, status
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer, OAuth2PasswordRequestForm
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import text
|
||||
|
||||
@@ -7,10 +14,13 @@ from app.core.config import settings
|
||||
from app.core.enums import OtpPurpose, UserRole
|
||||
from app.core.logging import get_logger
|
||||
from app.core.security import (
|
||||
_AsyncRedisClient,
|
||||
create_access_token,
|
||||
create_refresh_token,
|
||||
get_current_user,
|
||||
get_current_user_refresh,
|
||||
get_password_hash,
|
||||
revoke_token,
|
||||
verify_password,
|
||||
)
|
||||
from app.db.session import get_db
|
||||
@@ -34,6 +44,123 @@ from app.services.email import (
|
||||
logger = get_logger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
optional_bearer = HTTPBearer(auto_error=False)
|
||||
_LOCAL_LOGIN_FAILURES: dict[str, tuple[int, float]] = {}
|
||||
_LOCAL_LOGIN_FAILURES_MAX = 10_000
|
||||
|
||||
|
||||
class LogoutRequest(BaseModel):
|
||||
refresh_token: Optional[str] = None
|
||||
|
||||
|
||||
_TRUSTED_PROXY_NETWORKS = (
|
||||
ipaddress.ip_network("127.0.0.0/8"),
|
||||
ipaddress.ip_network("10.0.0.0/8"),
|
||||
ipaddress.ip_network("172.16.0.0/12"),
|
||||
ipaddress.ip_network("192.168.0.0/16"),
|
||||
ipaddress.ip_network("169.254.0.0/16"),
|
||||
ipaddress.ip_network("100.64.0.0/10"),
|
||||
ipaddress.ip_network("::1/128"),
|
||||
ipaddress.ip_network("fc00::/7"),
|
||||
ipaddress.ip_network("fe80::/10"),
|
||||
)
|
||||
|
||||
|
||||
def _is_trusted_proxy_peer(host: str) -> bool:
|
||||
cleaned = host.strip()
|
||||
if not cleaned:
|
||||
return False
|
||||
if cleaned in {"testclient", "localhost"}:
|
||||
return True
|
||||
try:
|
||||
parsed = ipaddress.ip_address(cleaned)
|
||||
except ValueError:
|
||||
return False
|
||||
if isinstance(parsed, ipaddress.IPv6Address) and parsed.ipv4_mapped is not None:
|
||||
parsed = parsed.ipv4_mapped
|
||||
return any(parsed in network for network in _TRUSTED_PROXY_NETWORKS)
|
||||
|
||||
|
||||
def _client_ip(request: Request) -> str:
|
||||
peer_host = request.client.host if (request.client and request.client.host) else ""
|
||||
if _is_trusted_proxy_peer(peer_host):
|
||||
real_ip = (request.headers.get("X-Real-IP") or "").strip()
|
||||
if real_ip:
|
||||
return real_ip
|
||||
forwarded = request.headers.get("X-Forwarded-For") or ""
|
||||
if forwarded:
|
||||
parts = [part.strip() for part in forwarded.split(",") if part.strip()]
|
||||
if parts:
|
||||
return parts[-1]
|
||||
if peer_host:
|
||||
return peer_host
|
||||
return "unknown"
|
||||
|
||||
|
||||
def _login_rate_key(client_ip: str, username: str) -> str:
|
||||
digest = sha256(f"{client_ip}:{username.strip().lower()}".encode("utf-8")).hexdigest()
|
||||
return f"auth:login_fail:{digest}"
|
||||
|
||||
|
||||
def _prune_local_login_failures(now: float) -> None:
|
||||
expired = [key for key, (_cnt, expires_at) in _LOCAL_LOGIN_FAILURES.items() if expires_at <= now]
|
||||
for key in expired:
|
||||
_LOCAL_LOGIN_FAILURES.pop(key, None)
|
||||
while len(_LOCAL_LOGIN_FAILURES) > _LOCAL_LOGIN_FAILURES_MAX:
|
||||
_LOCAL_LOGIN_FAILURES.pop(next(iter(_LOCAL_LOGIN_FAILURES)), None)
|
||||
|
||||
|
||||
async def check_login_rate_limit(client_ip: str, username: str) -> int:
|
||||
max_attempts = int(settings.LOGIN_RATE_LIMIT_MAX_ATTEMPTS)
|
||||
window_seconds = max(1, int(settings.LOGIN_RATE_LIMIT_WINDOW_SECONDS))
|
||||
if max_attempts <= 0:
|
||||
return 0
|
||||
key = _login_rate_key(client_ip, username)
|
||||
try:
|
||||
client = _AsyncRedisClient.get_client()
|
||||
raw = await asyncio.wait_for(client.get(key), timeout=1.5)
|
||||
if raw is not None and int(raw) >= max_attempts:
|
||||
ttl = await asyncio.wait_for(client.ttl(key), timeout=1.5)
|
||||
return max(1, int(ttl) if isinstance(ttl, int) and ttl > 0 else window_seconds)
|
||||
return 0
|
||||
except Exception:
|
||||
now = time.monotonic()
|
||||
_prune_local_login_failures(now)
|
||||
entry = _LOCAL_LOGIN_FAILURES.get(key)
|
||||
if entry and entry[1] > now and entry[0] >= max_attempts:
|
||||
return max(1, int(entry[1] - now))
|
||||
return 0
|
||||
|
||||
|
||||
async def record_login_failure(client_ip: str, username: str) -> None:
|
||||
max_attempts = int(settings.LOGIN_RATE_LIMIT_MAX_ATTEMPTS)
|
||||
window_seconds = max(1, int(settings.LOGIN_RATE_LIMIT_WINDOW_SECONDS))
|
||||
if max_attempts <= 0:
|
||||
return
|
||||
key = _login_rate_key(client_ip, username)
|
||||
try:
|
||||
client = _AsyncRedisClient.get_client()
|
||||
count = await asyncio.wait_for(client.incr(key), timeout=1.5)
|
||||
if int(count) == 1:
|
||||
await asyncio.wait_for(client.expire(key, window_seconds), timeout=1.5)
|
||||
except Exception:
|
||||
now = time.monotonic()
|
||||
_prune_local_login_failures(now)
|
||||
count, expires_at = _LOCAL_LOGIN_FAILURES.get(key, (0, now + window_seconds))
|
||||
if expires_at <= now:
|
||||
count = 0
|
||||
expires_at = now + window_seconds
|
||||
_LOCAL_LOGIN_FAILURES[key] = (count + 1, expires_at)
|
||||
|
||||
|
||||
async def clear_login_failures(client_ip: str, username: str) -> None:
|
||||
key = _login_rate_key(client_ip, username)
|
||||
_LOCAL_LOGIN_FAILURES.pop(key, None)
|
||||
try:
|
||||
client = _AsyncRedisClient.get_client()
|
||||
await asyncio.wait_for(client.delete(key), timeout=1.5)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _token_response(user: User) -> dict:
|
||||
@@ -83,9 +210,23 @@ async def _load_user_by_email(db: AsyncSession, email: str) -> User | None:
|
||||
|
||||
@router.post("/login", response_model=Token)
|
||||
async def login(
|
||||
request: Request,
|
||||
form_data: OAuth2PasswordRequestForm = Depends(),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
client_ip = _client_ip(request)
|
||||
retry_after = await check_login_rate_limit(client_ip, form_data.username)
|
||||
if retry_after > 0:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
headers={"Retry-After": str(retry_after)},
|
||||
detail={
|
||||
"code": "RATE_LIMITED",
|
||||
"message": "Too many failed login attempts",
|
||||
"retry_after_seconds": retry_after,
|
||||
},
|
||||
)
|
||||
|
||||
result = await db.execute(
|
||||
text(
|
||||
"SELECT id, username, email, password_hash, role, is_active, gatekeeper_groups, email_verified "
|
||||
@@ -95,6 +236,7 @@ async def login(
|
||||
)
|
||||
row = result.fetchone()
|
||||
if row is None:
|
||||
await record_login_failure(client_ip, form_data.username)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid credentials",
|
||||
@@ -111,11 +253,13 @@ async def login(
|
||||
user.email_verified = bool(row[7])
|
||||
|
||||
if not verify_password(form_data.password, user.password_hash):
|
||||
await record_login_failure(client_ip, form_data.username)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid credentials",
|
||||
)
|
||||
if not user.is_active:
|
||||
await record_login_failure(client_ip, form_data.username)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="User is inactive",
|
||||
@@ -126,34 +270,26 @@ async def login(
|
||||
detail={"code": "EMAIL_NOT_VERIFIED", "email": user.email},
|
||||
)
|
||||
|
||||
await clear_login_failures(client_ip, form_data.username)
|
||||
return _token_response(user)
|
||||
|
||||
|
||||
@router.post("/refresh", response_model=Token)
|
||||
async def refresh_token(
|
||||
current_user: User = Depends(get_current_user),
|
||||
current_user: User = Depends(get_current_user_refresh),
|
||||
):
|
||||
access_token = create_access_token(data={"sub": current_user.id})
|
||||
|
||||
expires_in = None
|
||||
if settings.ACCESS_TOKEN_EXPIRE_MINUTES > 0:
|
||||
expires_in = settings.ACCESS_TOKEN_EXPIRE_MINUTES * 60
|
||||
|
||||
return {
|
||||
"access_token": access_token,
|
||||
"token_type": "bearer",
|
||||
"expires_in": expires_in,
|
||||
"user": {
|
||||
"id": current_user.id,
|
||||
"username": current_user.username,
|
||||
"role": current_user.role,
|
||||
"gatekeeper_groups": current_user.gatekeeper_groups or [],
|
||||
},
|
||||
}
|
||||
return _token_response(current_user)
|
||||
|
||||
|
||||
@router.post("/logout")
|
||||
async def logout():
|
||||
async def logout(
|
||||
credentials: HTTPAuthorizationCredentials | None = Depends(optional_bearer),
|
||||
body: LogoutRequest | None = Body(default=None),
|
||||
):
|
||||
if credentials and credentials.credentials:
|
||||
await revoke_token(credentials.credentials)
|
||||
if body and body.refresh_token:
|
||||
await revoke_token(body.refresh_token)
|
||||
return {"message": "Successfully logged out"}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,317 @@
|
||||
"""Client L1 Earth hot-update manifest and bundle hosting endpoints."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import hmac
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import tarfile
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
from fastapi import APIRouter, Depends, File, Form, HTTPException, Request, UploadFile, status
|
||||
from fastapi.responses import FileResponse, JSONResponse
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.logging import get_logger
|
||||
from app.core.security import get_current_user
|
||||
from app.db.session import get_db
|
||||
|
||||
router = APIRouter()
|
||||
logger = get_logger(__name__, service="api")
|
||||
bearer_optional = HTTPBearer(auto_error=False)
|
||||
|
||||
DEFAULT_CLIENT_UPDATES_DIR = Path(__file__).resolve().parents[3] / "data" / "client-updates"
|
||||
MAX_HOTFIX_BUNDLE_BYTES = 32 * 1024 * 1024
|
||||
MAX_HOTFIX_FILES = 2000
|
||||
MAX_HOTFIX_UNCOMPRESSED_BYTES = 64 * 1024 * 1024
|
||||
SEMVER_PATTERN = re.compile(r"^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][0-9A-Za-z.-]+)?$")
|
||||
SAFE_BUNDLE_FILENAME_PATTERN = re.compile(r"^planet-earth-bundle-[0-9A-Za-z._-]+\.tar\.gz$")
|
||||
|
||||
|
||||
def get_client_updates_dir() -> Path:
|
||||
configured = str(settings.CLIENT_UPDATES_DIR or "").strip()
|
||||
if configured:
|
||||
return Path(configured)
|
||||
return DEFAULT_CLIENT_UPDATES_DIR
|
||||
|
||||
|
||||
def _manifest_path(updates_dir: Path) -> Path:
|
||||
return updates_dir / "manifest.json"
|
||||
|
||||
|
||||
def _atomic_write_bytes(target: Path, content: bytes) -> None:
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp_path = target.with_name(f".{target.name}.{os.getpid()}.{uuid4().hex}.tmp")
|
||||
try:
|
||||
tmp_path.write_bytes(content)
|
||||
os.replace(tmp_path, target)
|
||||
except Exception:
|
||||
tmp_path.unlink(missing_ok=True)
|
||||
raise
|
||||
|
||||
|
||||
def _validate_hotfix_tar_gz(content: bytes) -> dict[str, int]:
|
||||
if not content:
|
||||
raise HTTPException(status_code=400, detail="Hotfix bundle archive is empty")
|
||||
|
||||
file_count = 0
|
||||
total_size = 0
|
||||
has_index_html = False
|
||||
|
||||
try:
|
||||
with tarfile.open(fileobj=io.BytesIO(content), mode="r:gz") as archive:
|
||||
for member in archive.getmembers():
|
||||
raw_name = member.name or ""
|
||||
if "\\" in raw_name or "\0" in raw_name:
|
||||
raise HTTPException(status_code=400, detail=f"Unsafe archive entry path: {raw_name!r}")
|
||||
if member.issym() or member.islnk() or member.isdev() or member.ischr() or member.isblk() or member.isfifo():
|
||||
raise HTTPException(status_code=400, detail=f"Unsupported special archive entry: {raw_name!r}")
|
||||
|
||||
stripped = raw_name.lstrip("./") if raw_name.startswith("./") else raw_name
|
||||
while stripped.startswith("./"):
|
||||
stripped = stripped[2:]
|
||||
stripped = stripped.rstrip("/")
|
||||
|
||||
if raw_name.startswith("/"):
|
||||
raise HTTPException(status_code=400, detail=f"Absolute archive entry path is forbidden: {raw_name!r}")
|
||||
|
||||
if stripped in ("", "."):
|
||||
if member.isdir():
|
||||
continue
|
||||
raise HTTPException(status_code=400, detail="Empty archive file path")
|
||||
|
||||
segments = stripped.split("/")
|
||||
if any(seg in ("", ".", "..") for seg in segments):
|
||||
raise HTTPException(status_code=400, detail=f"Path traversal forbidden in archive: {raw_name!r}")
|
||||
|
||||
if member.isdir():
|
||||
continue
|
||||
if not member.isreg():
|
||||
raise HTTPException(status_code=400, detail=f"Unsupported archive entry type: {raw_name!r}")
|
||||
|
||||
file_count += 1
|
||||
if file_count > MAX_HOTFIX_FILES:
|
||||
raise HTTPException(status_code=400, detail="Archive exceeds maximum allowed file count")
|
||||
|
||||
total_size += max(0, int(member.size))
|
||||
if total_size > MAX_HOTFIX_UNCOMPRESSED_BYTES:
|
||||
raise HTTPException(status_code=400, detail="Archive exceeds maximum uncompressed size limit")
|
||||
|
||||
if stripped == "index.html":
|
||||
has_index_html = True
|
||||
except HTTPException:
|
||||
raise
|
||||
except (tarfile.TarError, EOFError, OSError, ValueError) as exc:
|
||||
raise HTTPException(status_code=400, detail=f"Invalid gzip tar archive: {exc}") from exc
|
||||
|
||||
if not has_index_html:
|
||||
raise HTTPException(status_code=400, detail="Hotfix bundle must include index.html at root")
|
||||
|
||||
return {"filesCount": file_count, "uncompressedBytes": total_size}
|
||||
|
||||
|
||||
def _default_manifest() -> dict[str, Any]:
|
||||
return {
|
||||
"shell": {
|
||||
"version": settings.VERSION,
|
||||
"minRequired": settings.CLIENT_MIN_SHELL_VERSION,
|
||||
"downloadUrl": settings.CLIENT_RELEASE_PAGE_URL,
|
||||
"releaseNotes": "",
|
||||
},
|
||||
"bundle": None,
|
||||
}
|
||||
|
||||
|
||||
def _read_manifest(updates_dir: Path) -> dict[str, Any]:
|
||||
manifest_file = _manifest_path(updates_dir)
|
||||
if not manifest_file.is_file():
|
||||
return _default_manifest()
|
||||
try:
|
||||
payload = json.loads(manifest_file.read_text(encoding="utf-8"))
|
||||
if not isinstance(payload, dict):
|
||||
return _default_manifest()
|
||||
return payload
|
||||
except (OSError, json.JSONDecodeError):
|
||||
return _default_manifest()
|
||||
|
||||
|
||||
async def _require_update_publisher(
|
||||
request: Request,
|
||||
credentials: HTTPAuthorizationCredentials | None = Depends(bearer_optional),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> str:
|
||||
publish_token = request.headers.get("X-Client-Update-Token")
|
||||
if publish_token is not None:
|
||||
expected = str(settings.CLIENT_UPDATE_PUBLISH_TOKEN or "").strip()
|
||||
if not expected or not hmac.compare_digest(publish_token.strip(), expected):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid client update publish token",
|
||||
)
|
||||
return "ci-token"
|
||||
|
||||
if credentials is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Not authenticated",
|
||||
)
|
||||
|
||||
user = await get_current_user(credentials=credentials, db=db)
|
||||
if getattr(user, "role", None) != "admin":
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Admin privileges required",
|
||||
)
|
||||
return f"admin:{user.username}"
|
||||
|
||||
|
||||
def _validate_semver(value: str, field_name: str) -> str:
|
||||
cleaned = str(value or "").strip().lstrip("vV")
|
||||
if not SEMVER_PATTERN.match(cleaned):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Invalid semantic version for {field_name}: {value!r}",
|
||||
)
|
||||
return cleaned
|
||||
|
||||
|
||||
@router.get("/update-manifest")
|
||||
async def get_client_update_manifest(
|
||||
platform: str = "",
|
||||
arch: str = "",
|
||||
shell: str = "",
|
||||
bundle: str = "",
|
||||
):
|
||||
updates_dir = get_client_updates_dir()
|
||||
manifest = _read_manifest(updates_dir)
|
||||
bundle_info = manifest.get("bundle")
|
||||
if isinstance(bundle_info, dict):
|
||||
filename = Path(str(bundle_info.get("url") or "")).name
|
||||
if not SAFE_BUNDLE_FILENAME_PATTERN.match(filename) or not (updates_dir / filename).is_file():
|
||||
manifest = {**manifest, "bundle": None}
|
||||
|
||||
logger.debug_event(
|
||||
"Served client update manifest",
|
||||
event="client_updates.manifest.read",
|
||||
context={
|
||||
"platform": platform or None,
|
||||
"arch": arch or None,
|
||||
"shell": shell or None,
|
||||
"bundle": bundle or None,
|
||||
"has_bundle": bool(manifest.get("bundle")),
|
||||
},
|
||||
)
|
||||
return JSONResponse(content=manifest, headers={"Cache-Control": "no-store"})
|
||||
|
||||
|
||||
@router.get("/updates/files/{filename}")
|
||||
async def download_client_hotfix_bundle(filename: str):
|
||||
if not SAFE_BUNDLE_FILENAME_PATTERN.match(filename):
|
||||
raise HTTPException(status_code=400, detail="Invalid client hotfix bundle filename")
|
||||
|
||||
updates_dir = get_client_updates_dir().resolve()
|
||||
target = (updates_dir / filename).resolve()
|
||||
if target.parent != updates_dir or not target.is_file():
|
||||
raise HTTPException(status_code=404, detail="Client hotfix bundle not found")
|
||||
|
||||
return FileResponse(
|
||||
path=target,
|
||||
media_type="application/gzip",
|
||||
filename=filename,
|
||||
headers={"Cache-Control": "public, max-age=31536000, immutable"},
|
||||
)
|
||||
|
||||
|
||||
@router.post("/updates/bundle")
|
||||
async def publish_client_hotfix_bundle(
|
||||
file: UploadFile = File(...),
|
||||
version: str = Form(...),
|
||||
min_shell_version: str = Form(""),
|
||||
release_notes: str = Form(""),
|
||||
shell_version: str = Form(""),
|
||||
shell_min_required: str = Form(""),
|
||||
shell_download_url: str = Form(""),
|
||||
publisher: str = Depends(_require_update_publisher),
|
||||
):
|
||||
normalized_version = _validate_semver(version, "version")
|
||||
normalized_min_shell = _validate_semver(
|
||||
min_shell_version or settings.CLIENT_MIN_SHELL_VERSION or normalized_version,
|
||||
"min_shell_version",
|
||||
)
|
||||
|
||||
content = await file.read(MAX_HOTFIX_BUNDLE_BYTES + 1)
|
||||
if len(content) > MAX_HOTFIX_BUNDLE_BYTES:
|
||||
raise HTTPException(status_code=400, detail="Hotfix bundle exceeds 32 MiB limit")
|
||||
|
||||
archive_meta = _validate_hotfix_tar_gz(content)
|
||||
sha256_hex = hashlib.sha256(content).hexdigest()
|
||||
bundle_filename = f"planet-earth-bundle-{normalized_version}.tar.gz"
|
||||
updates_dir = get_client_updates_dir()
|
||||
|
||||
_atomic_write_bytes(updates_dir / bundle_filename, content)
|
||||
|
||||
existing_manifest = _read_manifest(updates_dir)
|
||||
existing_shell = existing_manifest.get("shell") if isinstance(existing_manifest.get("shell"), dict) else {}
|
||||
|
||||
resolved_shell_version = (
|
||||
_validate_semver(shell_version, "shell_version")
|
||||
if str(shell_version or "").strip()
|
||||
else str(existing_shell.get("version") or settings.VERSION)
|
||||
)
|
||||
resolved_shell_min = (
|
||||
_validate_semver(shell_min_required, "shell_min_required")
|
||||
if str(shell_min_required or "").strip()
|
||||
else str(existing_shell.get("minRequired") or settings.CLIENT_MIN_SHELL_VERSION)
|
||||
)
|
||||
resolved_shell_url = str(shell_download_url or "").strip() or str(
|
||||
existing_shell.get("downloadUrl") or settings.CLIENT_RELEASE_PAGE_URL
|
||||
)
|
||||
if not resolved_shell_url.startswith(("https://", "http://")):
|
||||
raise HTTPException(status_code=400, detail="shell_download_url must start with http:// or https://")
|
||||
|
||||
cleaned_notes = str(release_notes or "").strip()[:4000]
|
||||
manifest: dict[str, Any] = {
|
||||
"shell": {
|
||||
"version": resolved_shell_version,
|
||||
"minRequired": resolved_shell_min,
|
||||
"downloadUrl": resolved_shell_url,
|
||||
"releaseNotes": cleaned_notes or str(existing_shell.get("releaseNotes") or ""),
|
||||
},
|
||||
"bundle": {
|
||||
"version": normalized_version,
|
||||
"minShellVersion": normalized_min_shell,
|
||||
"url": f"/api/v1/client/updates/files/{bundle_filename}",
|
||||
"sha256": sha256_hex,
|
||||
"size": len(content),
|
||||
"releaseNotes": cleaned_notes,
|
||||
"publishedAt": datetime.now(UTC).isoformat(),
|
||||
**archive_meta,
|
||||
},
|
||||
}
|
||||
|
||||
_atomic_write_bytes(
|
||||
_manifest_path(updates_dir),
|
||||
(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n").encode("utf-8"),
|
||||
)
|
||||
|
||||
logger.info_event(
|
||||
"Published client L1 hotfix bundle",
|
||||
event="client_updates.bundle_published",
|
||||
context={
|
||||
"publisher": publisher,
|
||||
"version": normalized_version,
|
||||
"min_shell_version": normalized_min_shell,
|
||||
"bytes": len(content),
|
||||
"sha256": sha256_hex,
|
||||
"files_count": archive_meta["filesCount"],
|
||||
},
|
||||
)
|
||||
return {"status": "published", "manifest": manifest}
|
||||
@@ -690,24 +690,47 @@ async def delete_config(
|
||||
deleted_records = {
|
||||
"collected_data": 0,
|
||||
"ais_raw_observations": 0,
|
||||
"vessel_current_state": 0,
|
||||
"ais_source_health": 0,
|
||||
}
|
||||
|
||||
if delete_source_data:
|
||||
collected_result = await db.execute(
|
||||
delete(CollectedData).where(CollectedData.source == config.name)
|
||||
from app.models.vessel import VesselCurrentState
|
||||
|
||||
sibling_result = await db.execute(
|
||||
select(DataSourceConfig.id)
|
||||
.where(DataSourceConfig.name == config.name, DataSourceConfig.id != config_id)
|
||||
.limit(1)
|
||||
)
|
||||
raw_result = await db.execute(
|
||||
delete(AISRawObservation).where(AISRawObservation.source == config.name)
|
||||
)
|
||||
health_result = await db.execute(
|
||||
delete(AISSourceHealth).where(AISSourceHealth.source == config.name)
|
||||
)
|
||||
deleted_records = {
|
||||
"collected_data": collected_result.rowcount or 0,
|
||||
"ais_raw_observations": raw_result.rowcount or 0,
|
||||
"ais_source_health": health_result.rowcount or 0,
|
||||
}
|
||||
has_same_name_sibling = sibling_result.scalar_one_or_none() is not None
|
||||
|
||||
if has_same_name_sibling:
|
||||
collected_result = await db.execute(
|
||||
delete(CollectedData).where(
|
||||
CollectedData.source == config.name,
|
||||
CollectedData.entity_key.like(f"datasource_config:{config_id}:%"),
|
||||
)
|
||||
)
|
||||
deleted_records["collected_data"] = collected_result.rowcount or 0
|
||||
else:
|
||||
collected_result = await db.execute(
|
||||
delete(CollectedData).where(CollectedData.source == config.name)
|
||||
)
|
||||
raw_result = await db.execute(
|
||||
delete(AISRawObservation).where(AISRawObservation.source == config.name)
|
||||
)
|
||||
current_vessel_result = await db.execute(
|
||||
delete(VesselCurrentState).where(VesselCurrentState.source == config.name)
|
||||
)
|
||||
health_result = await db.execute(
|
||||
delete(AISSourceHealth).where(AISSourceHealth.source == config.name)
|
||||
)
|
||||
deleted_records = {
|
||||
"collected_data": collected_result.rowcount or 0,
|
||||
"ais_raw_observations": raw_result.rowcount or 0,
|
||||
"vessel_current_state": current_vessel_result.rowcount or 0,
|
||||
"ais_source_health": health_result.rowcount or 0,
|
||||
}
|
||||
|
||||
if delete_mappings or delete_source_data:
|
||||
mapping_result = await db.execute(
|
||||
|
||||
@@ -7,7 +7,7 @@ from sqlalchemy import func, or_, select, text
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.logging import get_logger
|
||||
from app.core.enums import JobStatus, SnapshotStatus
|
||||
from app.core.enums import JobStatus, SnapshotStatus, UserRole
|
||||
from app.core.time import to_iso8601_utc
|
||||
from app.core.security import get_current_user
|
||||
from app.core.data_sources import get_data_sources_config
|
||||
@@ -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,
|
||||
)
|
||||
@@ -39,6 +39,7 @@ from app.services.business_logs import emit_business_log
|
||||
router = APIRouter()
|
||||
logger = get_logger(__name__, service="api")
|
||||
STALE_RUNNING_TASK_TIMEOUT_MINUTES = 90
|
||||
DATASOURCE_ADMIN_ROLES = {UserRole.ADMIN.value, UserRole.SUPER_ADMIN.value}
|
||||
|
||||
|
||||
PRODUCT_SOURCE_KEYWORDS: tuple[tuple[str, tuple[str, ...]], ...] = (
|
||||
@@ -65,6 +66,20 @@ class DatasourceBatchTriggerRequest(BaseModel):
|
||||
q: Optional[str] = None
|
||||
|
||||
|
||||
class DatasourceBatchStatusRequest(BaseModel):
|
||||
source_ids: list[int] = Field(min_length=1, max_length=500)
|
||||
is_active: bool
|
||||
|
||||
|
||||
def _require_datasource_admin(current_user: User) -> None:
|
||||
role = getattr(current_user.role, "value", current_user.role)
|
||||
if role not in DATASOURCE_ADMIN_ROLES:
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Only administrators can change datasource scheduling",
|
||||
)
|
||||
|
||||
|
||||
def format_frequency_label(minutes: int) -> str:
|
||||
if minutes % 1440 == 0:
|
||||
return f"{minutes // 1440}d"
|
||||
@@ -228,6 +243,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
|
||||
|
||||
|
||||
@@ -343,6 +368,78 @@ def serialize_datasource_row(
|
||||
return row
|
||||
|
||||
|
||||
async def _serialize_datasource_rows(
|
||||
db: AsyncSession,
|
||||
datasources: list[DataSource],
|
||||
) -> list[dict]:
|
||||
if not datasources:
|
||||
return []
|
||||
config = get_data_sources_config()
|
||||
running_tasks, latest_tasks, endpoint_overrides = await _load_datasource_list_context(
|
||||
db,
|
||||
datasources,
|
||||
include_endpoint=False,
|
||||
)
|
||||
record_counts = await _load_collected_record_counts(
|
||||
db, [datasource.source for datasource in datasources]
|
||||
)
|
||||
return [
|
||||
serialize_datasource_row(
|
||||
datasource,
|
||||
running_tasks=running_tasks,
|
||||
latest_tasks=latest_tasks,
|
||||
record_counts=record_counts,
|
||||
endpoint_overrides=endpoint_overrides,
|
||||
config=config,
|
||||
include_endpoint=False,
|
||||
)
|
||||
for datasource in datasources
|
||||
]
|
||||
|
||||
|
||||
async def _load_datasource_status_counts(db: AsyncSession) -> dict[str, int]:
|
||||
result = await db.execute(
|
||||
select(DataSource.is_active, func.count(DataSource.id)).group_by(DataSource.is_active)
|
||||
)
|
||||
active = 0
|
||||
inactive = 0
|
||||
for is_active, count in result.all():
|
||||
if is_active:
|
||||
active += int(count or 0)
|
||||
else:
|
||||
inactive += int(count or 0)
|
||||
return {"all": active + inactive, "active": active, "inactive": inactive}
|
||||
|
||||
|
||||
async def _apply_datasource_activation(
|
||||
db: AsyncSession,
|
||||
datasources: list[DataSource],
|
||||
is_active: bool,
|
||||
) -> tuple[list[DataSource], list[int]]:
|
||||
"""Persist scheduling state, then reconcile scheduler jobs for changed rows only."""
|
||||
changed = [datasource for datasource in datasources if bool(datasource.is_active) != is_active]
|
||||
for datasource in changed:
|
||||
datasource.is_active = is_active
|
||||
if changed:
|
||||
await db.commit()
|
||||
sync_failed: list[int] = []
|
||||
for datasource in changed:
|
||||
try:
|
||||
await sync_datasource_job(datasource.id)
|
||||
except Exception as exc:
|
||||
sync_failed.append(datasource.id)
|
||||
logger.warning_event(
|
||||
"Datasource scheduler sync failed",
|
||||
event="collector.schedule.sync_failed",
|
||||
context={
|
||||
"datasource_id": datasource.id,
|
||||
"source": datasource.source,
|
||||
"error_type": type(exc).__name__,
|
||||
},
|
||||
)
|
||||
return changed, sync_failed
|
||||
|
||||
|
||||
def _apply_datasource_query_filters(
|
||||
query,
|
||||
*,
|
||||
@@ -807,7 +904,55 @@ async def list_datasources(
|
||||
)
|
||||
)
|
||||
|
||||
return {"total": len(collector_list), "data": collector_list}
|
||||
return {
|
||||
"total": len(collector_list),
|
||||
"data": collector_list,
|
||||
"counts": await _load_datasource_status_counts(db),
|
||||
}
|
||||
|
||||
|
||||
@router.post("/batch-status")
|
||||
async def update_datasource_batch_status(
|
||||
payload: DatasourceBatchStatusRequest,
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
_require_datasource_admin(current_user)
|
||||
requested_ids = list(dict.fromkeys(payload.source_ids))
|
||||
result = await db.execute(
|
||||
select(DataSource)
|
||||
.where(DataSource.id.in_(requested_ids))
|
||||
.order_by(DataSource.module, DataSource.id)
|
||||
)
|
||||
datasources = list(result.scalars().all())
|
||||
found_ids = {datasource.id for datasource in datasources}
|
||||
changed, sync_failed = await _apply_datasource_activation(db, datasources, payload.is_active)
|
||||
changed_ids = {datasource.id for datasource in changed}
|
||||
await emit_business_log(
|
||||
logger,
|
||||
event="collector.schedule.batch_status",
|
||||
message="Datasource scheduling batch update completed",
|
||||
category="collector",
|
||||
service="api",
|
||||
module=__name__,
|
||||
user_id=current_user.id,
|
||||
context={
|
||||
"is_active": payload.is_active,
|
||||
"requested_count": len(requested_ids),
|
||||
"updated_count": len(changed),
|
||||
"sync_failed_count": len(sync_failed),
|
||||
},
|
||||
)
|
||||
return {
|
||||
"is_active": payload.is_active,
|
||||
"updated": await _serialize_datasource_rows(db, changed),
|
||||
"unchanged": [
|
||||
datasource.id for datasource in datasources if datasource.id not in changed_ids
|
||||
],
|
||||
"not_found": [source_id for source_id in requested_ids if source_id not in found_ids],
|
||||
"sync_failed": sync_failed,
|
||||
"counts": await _load_datasource_status_counts(db),
|
||||
}
|
||||
|
||||
|
||||
@router.post("/trigger-all")
|
||||
@@ -977,20 +1122,35 @@ async def get_datasource_row(
|
||||
}
|
||||
|
||||
|
||||
async def _set_single_datasource_active(
|
||||
db: AsyncSession,
|
||||
source_id: str,
|
||||
current_user: User,
|
||||
is_active: bool,
|
||||
) -> dict:
|
||||
_require_datasource_admin(current_user)
|
||||
datasource = await get_datasource_record(db, source_id)
|
||||
if not datasource:
|
||||
raise HTTPException(status_code=404, detail="Data source not found")
|
||||
|
||||
_changed, sync_failed = await _apply_datasource_activation(db, [datasource], is_active)
|
||||
rows = await _serialize_datasource_rows(db, [datasource])
|
||||
return {
|
||||
"status": "enabled" if is_active else "disabled",
|
||||
"source_id": datasource.id,
|
||||
"data": rows[0] if rows else None,
|
||||
"sync_failed": bool(sync_failed),
|
||||
"counts": await _load_datasource_status_counts(db),
|
||||
}
|
||||
|
||||
|
||||
@router.post("/{source_id}/enable")
|
||||
async def enable_datasource(
|
||||
source_id: str,
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
datasource = await get_datasource_record(db, source_id)
|
||||
if not datasource:
|
||||
raise HTTPException(status_code=404, detail="Data source not found")
|
||||
|
||||
datasource.is_active = True
|
||||
await db.commit()
|
||||
await sync_datasource_job(datasource.id)
|
||||
return {"status": "enabled", "source_id": datasource.id}
|
||||
return await _set_single_datasource_active(db, source_id, current_user, True)
|
||||
|
||||
|
||||
@router.post("/{source_id}/disable")
|
||||
@@ -999,14 +1159,7 @@ async def disable_datasource(
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
datasource = await get_datasource_record(db, source_id)
|
||||
if not datasource:
|
||||
raise HTTPException(status_code=404, detail="Data source not found")
|
||||
|
||||
datasource.is_active = False
|
||||
await db.commit()
|
||||
await sync_datasource_job(datasource.id)
|
||||
return {"status": "disabled", "source_id": datasource.id}
|
||||
return await _set_single_datasource_active(db, source_id, current_user, False)
|
||||
|
||||
|
||||
@router.get("/{source_id}/stats")
|
||||
|
||||
@@ -14,7 +14,12 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.config import settings as app_settings
|
||||
from app.core.logging import get_logger
|
||||
from app.core.security import decode_token, get_current_user, redis_client
|
||||
from app.core.security import (
|
||||
decode_token,
|
||||
get_current_user,
|
||||
is_token_blacklisted,
|
||||
redis_client,
|
||||
)
|
||||
from app.core.websocket.broadcaster import broadcaster
|
||||
from app.db.session import get_db
|
||||
from app.models.collected_data import CollectedData
|
||||
@@ -251,7 +256,7 @@ async def _get_optional_current_user(
|
||||
if credentials is None:
|
||||
return None
|
||||
token = credentials.credentials
|
||||
if redis_client.sismember("blacklisted_tokens", token):
|
||||
if await is_token_blacklisted(token, legacy_sync_client=redis_client):
|
||||
return None
|
||||
payload = decode_token(token)
|
||||
if payload is None or payload.get("type") != "access":
|
||||
|
||||
@@ -15,7 +15,8 @@ from app.db.session import get_db
|
||||
from app.models.datasource import DataSource
|
||||
from app.models.datasource_config import DataSourceConfig
|
||||
from app.models.user import User
|
||||
from app.models.vessel import AISRawObservation, AISSourceHealth
|
||||
from app.models.vessel import AISRawObservation, AISSourceHealth, VesselCurrentState
|
||||
from app.services.storage_policy import resolve_collector_storage_policy
|
||||
from app.services.custom_datasource_runtime import (
|
||||
get_custom_stream_status,
|
||||
start_custom_stream,
|
||||
@@ -77,14 +78,45 @@ async def _load_realtime_stats(db: AsyncSession, source: str) -> dict[str, Any]:
|
||||
.where(AISRawObservation.source == source)
|
||||
)
|
||||
row = result.mappings().one()
|
||||
mode, _ = await resolve_collector_storage_policy(db, source)
|
||||
total_obs = int(row["total_observations"] or 0)
|
||||
if total_obs > 0:
|
||||
return {
|
||||
"total_observations": total_obs,
|
||||
"observations_24h": int(row["observations_24h"] or 0),
|
||||
"observations_1h": int(row["observations_1h"] or 0),
|
||||
"unique_mmsi_total": int(row["unique_mmsi_total"] or 0),
|
||||
"unique_mmsi_24h": int(row["unique_mmsi_24h"] or 0),
|
||||
"latest_observed_at": to_iso8601_utc(row["latest_observed_at"]),
|
||||
"latest_collected_at": to_iso8601_utc(row["latest_collected_at"]),
|
||||
"storage_mode": mode,
|
||||
}
|
||||
|
||||
current_result = await db.execute(
|
||||
select(
|
||||
func.count(VesselCurrentState.mmsi).label("total_vessels"),
|
||||
func.count(VesselCurrentState.mmsi)
|
||||
.filter(VesselCurrentState.observed_at >= observed_24h)
|
||||
.label("vessels_24h"),
|
||||
func.count(VesselCurrentState.mmsi)
|
||||
.filter(VesselCurrentState.observed_at >= observed_1h)
|
||||
.label("vessels_1h"),
|
||||
func.max(VesselCurrentState.observed_at).label("latest_observed_at"),
|
||||
func.max(VesselCurrentState.updated_at).label("latest_collected_at"),
|
||||
).where(VesselCurrentState.source == source)
|
||||
)
|
||||
current_row = current_result.mappings().one()
|
||||
total_vessels = int(current_row["total_vessels"] or 0)
|
||||
vessels_24h = int(current_row["vessels_24h"] or 0)
|
||||
return {
|
||||
"total_observations": int(row["total_observations"] or 0),
|
||||
"observations_24h": int(row["observations_24h"] or 0),
|
||||
"observations_1h": int(row["observations_1h"] or 0),
|
||||
"unique_mmsi_total": int(row["unique_mmsi_total"] or 0),
|
||||
"unique_mmsi_24h": int(row["unique_mmsi_24h"] or 0),
|
||||
"latest_observed_at": to_iso8601_utc(row["latest_observed_at"]),
|
||||
"latest_collected_at": to_iso8601_utc(row["latest_collected_at"]),
|
||||
"total_observations": total_vessels,
|
||||
"observations_24h": vessels_24h,
|
||||
"observations_1h": int(current_row["vessels_1h"] or 0),
|
||||
"unique_mmsi_total": total_vessels,
|
||||
"unique_mmsi_24h": vessels_24h,
|
||||
"latest_observed_at": to_iso8601_utc(current_row["latest_observed_at"]),
|
||||
"latest_collected_at": to_iso8601_utc(current_row["latest_collected_at"]),
|
||||
"storage_mode": mode,
|
||||
}
|
||||
|
||||
|
||||
|
||||
+357
-26
@@ -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
|
||||
@@ -65,11 +66,30 @@ from app.services.llm_provider_catalog import (
|
||||
list_fallback_llm_provider_presets,
|
||||
refresh_llm_provider_preset,
|
||||
)
|
||||
from app.services.llm_model_catalog import catalog_error_message, fetch_model_catalog
|
||||
from app.services.llm_model_catalog import (
|
||||
LLMProviderCatalogConfigError,
|
||||
catalog_error_message,
|
||||
catalog_requires_api_key,
|
||||
fetch_model_catalog,
|
||||
)
|
||||
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 +98,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 +259,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 +396,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 +445,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
|
||||
|
||||
|
||||
@@ -779,7 +845,7 @@ async def _check_ai_provider_lightweight(llm_config: dict, timeout_seconds: int)
|
||||
}
|
||||
if not base_url or not model:
|
||||
return {**result, "message": "当前 provider/base_url/model 未完整配置。"}
|
||||
if provider_api != ProviderApi.OLLAMA_GENERATE.value and not api_key:
|
||||
if provider != "ollama" and provider_api != ProviderApi.OLLAMA_GENERATE.value and not api_key:
|
||||
return {**result, "message": "当前 provider 未配置 API Key。"}
|
||||
try:
|
||||
catalog = await fetch_model_catalog(
|
||||
@@ -1223,8 +1289,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 +1315,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 +1337,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 +1476,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 +1495,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 +1605,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)}
|
||||
@@ -1949,6 +2150,74 @@ async def get_ai_provider_presets(
|
||||
}
|
||||
|
||||
|
||||
async def refresh_public_llm_provider_presets(db: AsyncSession) -> dict:
|
||||
current_payload = await get_setting_payload(db, "external_integrations")
|
||||
ai_payload = _normalize_ai_provider_payload(current_payload.get("ai_provider") or {})
|
||||
results: list[dict] = []
|
||||
for preset in list_fallback_llm_provider_presets():
|
||||
provider_id = preset["provider"]
|
||||
provider_config = ai_payload["providers"].get(provider_id) or _provider_defaults(provider_id)
|
||||
base_url = str(provider_config.get("base_url") or preset["base_url"] or "")
|
||||
provider_api = str(provider_config.get("provider_api") or preset["provider_api"] or "")
|
||||
if catalog_requires_api_key(provider_id, base_url, provider_api):
|
||||
continue
|
||||
try:
|
||||
refreshed = await refresh_llm_provider_preset(
|
||||
provider_id,
|
||||
api_key="",
|
||||
base_url=base_url,
|
||||
provider_api=provider_api,
|
||||
anthropic_version=provider_config.get("anthropic_version") or "2023-06-01",
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning(
|
||||
"LLM provider catalog refresh failed",
|
||||
extra={
|
||||
"event": "settings.ai_provider.catalog.failed",
|
||||
"context": {
|
||||
"provider": provider_id,
|
||||
"error_type": type(exc).__name__,
|
||||
},
|
||||
},
|
||||
)
|
||||
results.append(
|
||||
{
|
||||
"provider": provider_id,
|
||||
"status": "failed",
|
||||
"error": f"{catalog_error_message(exc)} 已保留上次模型列表。",
|
||||
}
|
||||
)
|
||||
continue
|
||||
|
||||
refreshed["refreshed_at"] = to_iso8601_utc(datetime.now(UTC))
|
||||
await save_setting_payload(
|
||||
db, f"{LLM_PROVIDER_PRESET_CATEGORY_PREFIX}{provider_id}", refreshed
|
||||
)
|
||||
results.append(
|
||||
{
|
||||
"provider": provider_id,
|
||||
"status": "refreshed",
|
||||
"models_count": len(refreshed["models"]),
|
||||
"refreshed_at": refreshed["refreshed_at"],
|
||||
"source": refreshed["source"],
|
||||
}
|
||||
)
|
||||
return {
|
||||
"data": results,
|
||||
"refreshed": [item["provider"] for item in results if item["status"] == "refreshed"],
|
||||
"failed": [item["provider"] for item in results if item["status"] == "failed"],
|
||||
}
|
||||
|
||||
|
||||
@router.post("/integrations/ai-provider/presets/refresh-public")
|
||||
async def refresh_public_ai_provider_presets(
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
_require_admin(current_user, "Only administrators can refresh AI provider presets")
|
||||
return await refresh_public_llm_provider_presets(db)
|
||||
|
||||
|
||||
@router.post("/integrations/ai-provider/presets/{provider}/refresh")
|
||||
async def refresh_ai_provider_preset(
|
||||
provider: str,
|
||||
@@ -1956,9 +2225,10 @@ async def refresh_ai_provider_preset(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
payload: AIProviderIntegrationUpdate | None = None,
|
||||
):
|
||||
_require_admin(current_user, "Only administrators can refresh AI provider presets")
|
||||
try:
|
||||
provider_id = _normalize_provider_id(provider)
|
||||
get_fallback_llm_provider_preset(provider_id)
|
||||
fallback = get_fallback_llm_provider_preset(provider_id)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=404, detail=str(exc)) from exc
|
||||
|
||||
@@ -1970,17 +2240,23 @@ async def refresh_ai_provider_preset(
|
||||
else:
|
||||
ai_payload = _normalize_ai_provider_payload(current_payload.get("ai_provider") or {})
|
||||
provider_config = ai_payload["providers"].get(provider_id) or _provider_defaults(provider_id)
|
||||
resolved_base_url = str(provider_config.get("base_url") or fallback["base_url"] or "")
|
||||
resolved_api = str(provider_config.get("provider_api") or fallback["provider_api"] or "")
|
||||
api_key, _api_key_source = _resolve_provider_api_key(provider_id, provider_config)
|
||||
if not api_key and provider_id not in {"ollama", "opencode-go", "openrouter"}:
|
||||
if not api_key and catalog_requires_api_key(provider_id, resolved_base_url, resolved_api):
|
||||
raise HTTPException(
|
||||
status_code=400, detail="请先配置当前供应商的 API Key,再刷新模型列表。",
|
||||
)
|
||||
try:
|
||||
refreshed = await refresh_llm_provider_preset(
|
||||
provider_id, api_key=api_key, base_url=provider_config.get("base_url"),
|
||||
provider_api=provider_config.get("provider_api"),
|
||||
provider_id,
|
||||
api_key=api_key,
|
||||
base_url=resolved_base_url,
|
||||
provider_api=resolved_api,
|
||||
anthropic_version=provider_config.get("anthropic_version") or "2023-06-01",
|
||||
)
|
||||
except LLMProviderCatalogConfigError as exc:
|
||||
raise HTTPException(status_code=400, detail=catalog_error_message(exc)) from exc
|
||||
except Exception as exc:
|
||||
logger.warning(
|
||||
"LLM provider catalog refresh failed",
|
||||
@@ -2008,6 +2284,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 +2297,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 +2317,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 +2379,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)),
|
||||
}
|
||||
@@ -7,7 +7,8 @@ from datetime import UTC, datetime
|
||||
import uuid
|
||||
from typing import Any, Literal
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Response
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response
|
||||
from fastapi.responses import StreamingResponse
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
from sqlalchemy import desc, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
@@ -53,6 +54,7 @@ from app.services.ai.workflow_runtime import (
|
||||
get_active_run_handle,
|
||||
read_frozen_result_revision,
|
||||
)
|
||||
from app.services.ai.stream_turn import stream_session_turn
|
||||
from app.services.ai_client import AIProviderClient, get_ai_provider_client
|
||||
from app.services.compute_history import ComputeSeriesMode
|
||||
|
||||
@@ -79,6 +81,13 @@ class SessionPinUpdateRequest(BaseModel):
|
||||
pinned_items: list[dict[str, Any]] = Field(default_factory=list, max_length=12)
|
||||
|
||||
|
||||
class HistoryMessageItem(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
||||
|
||||
role: Literal["user", "assistant"]
|
||||
content: str = Field(min_length=1, max_length=6000)
|
||||
|
||||
|
||||
class SessionTurnRequest(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
||||
|
||||
@@ -95,6 +104,11 @@ class SessionTurnRequest(BaseModel):
|
||||
preset: ViewPreset | None = None
|
||||
prefer_llm: bool | Literal["auto"] = False
|
||||
external_urls: list[str] = Field(default_factory=list, max_length=3)
|
||||
news_context: dict[str, Any] | None = None
|
||||
history: list[HistoryMessageItem] = Field(default_factory=list, max_length=40)
|
||||
conversation_summary: str | None = Field(default=None, max_length=2400)
|
||||
memory_notes: list[str] = Field(default_factory=list, max_length=12)
|
||||
pinned_summaries: list[str] = Field(default_factory=list, max_length=8)
|
||||
run_id: str | None = Field(default=None, min_length=4, max_length=64, pattern=r"^[A-Za-z0-9_-]+$")
|
||||
|
||||
|
||||
@@ -340,6 +354,68 @@ async def create_session_turn(
|
||||
return turn_result
|
||||
|
||||
|
||||
@router.post("/sessions/{session_id}/turns/stream")
|
||||
async def stream_investigation_session_turn(
|
||||
session_id: str,
|
||||
payload: SessionTurnRequest,
|
||||
request: Request,
|
||||
response: Response,
|
||||
access: AccessContext = Depends(resolve_access_context),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
ai_client: AIProviderClient = Depends(get_ai_provider_client),
|
||||
) -> StreamingResponse:
|
||||
"""Adaptive SSE endpoint streaming LLM reasoning & answer when configured, else grounded baseline."""
|
||||
session_row: InvestigationSession | None = None
|
||||
effective_access = access
|
||||
issued_token: str | None = None
|
||||
if session_id == "stateless":
|
||||
owner_key, issued_token = ensure_session_owner_identity(access, response)
|
||||
effective_access = replace(access, actor_key=owner_key, has_session_credential=True)
|
||||
else:
|
||||
session_row = await _load_owned_session_or_fail(session_id, access, db)
|
||||
|
||||
codes = (
|
||||
selected_countries(",".join(payload.selected_codes))
|
||||
if payload.selected_codes
|
||||
else None
|
||||
)
|
||||
overrides = {
|
||||
"domain": payload.domain,
|
||||
"selected_codes": codes,
|
||||
"mode": payload.mode,
|
||||
"focus_year": payload.focus_year,
|
||||
"entity_id": payload.entity_id,
|
||||
"visible_layers": payload.visible_layers,
|
||||
"time_basis": payload.time_basis,
|
||||
"cutoff_at": payload.cutoff_at,
|
||||
"include_drill": payload.include_drill,
|
||||
}
|
||||
headers = {
|
||||
"Cache-Control": "no-cache",
|
||||
"X-Accel-Buffering": "no",
|
||||
}
|
||||
return StreamingResponse(
|
||||
stream_session_turn(
|
||||
db,
|
||||
request=request,
|
||||
session=session_row,
|
||||
question=payload.question,
|
||||
context_override=overrides,
|
||||
news_context=payload.news_context,
|
||||
history=[item.model_dump() for item in payload.history],
|
||||
conversation_summary=payload.conversation_summary,
|
||||
memory_notes=payload.memory_notes,
|
||||
pinned_summaries=payload.pinned_summaries,
|
||||
access=effective_access,
|
||||
ai_client=ai_client,
|
||||
client_run_id=payload.run_id,
|
||||
issued_session_token=issued_token,
|
||||
),
|
||||
media_type="text/event-stream",
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Group 3: WorkflowRun Inspection & Explicit Cancellation
|
||||
# ============================================================================
|
||||
|
||||
@@ -7,11 +7,12 @@ Returns GeoJSON format compatible with Three.js, CesiumJS, and Unreal Cesium.
|
||||
import asyncio
|
||||
import base64
|
||||
from collections import OrderedDict
|
||||
from contextlib import aclosing
|
||||
from datetime import UTC, datetime, timedelta
|
||||
import math
|
||||
import re
|
||||
import httpx
|
||||
from fastapi import APIRouter, HTTPException, Depends, Query, Response
|
||||
from fastapi import APIRouter, HTTPException, Depends, Query, Request, Response
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select, func
|
||||
@@ -63,6 +64,7 @@ from app.services.earth_layer_cache import (
|
||||
earth_layer_cache,
|
||||
format_bbox_key,
|
||||
get_or_build_layer_payload,
|
||||
get_or_build_layer_response,
|
||||
quantize_bbox,
|
||||
)
|
||||
from app.core.logging import get_logger
|
||||
@@ -278,36 +280,43 @@ def convert_landing_point_to_geojson(records: List[CollectedData], city_to_cable
|
||||
return {"type": "FeatureCollection", "features": features}
|
||||
|
||||
|
||||
def _extract_satellite_record(record: CollectedData) -> tuple[dict[str, Any], Any, Optional[str], Optional[str], Optional[str], str] | None:
|
||||
metadata = record.extra_data or {}
|
||||
norad_id = metadata.get("norad_cat_id")
|
||||
if not norad_id:
|
||||
return None
|
||||
|
||||
tle_line1 = metadata.get("tle_line1")
|
||||
tle_line2 = metadata.get("tle_line2")
|
||||
if not tle_line1 or not tle_line2:
|
||||
tle_line1, tle_line2 = build_tle_lines_from_elements(
|
||||
norad_cat_id=norad_id,
|
||||
epoch=metadata.get("epoch"),
|
||||
inclination=metadata.get("inclination"),
|
||||
raan=metadata.get("raan"),
|
||||
eccentricity=metadata.get("eccentricity"),
|
||||
arg_of_perigee=metadata.get("arg_of_perigee"),
|
||||
mean_anomaly=metadata.get("mean_anomaly"),
|
||||
mean_motion=metadata.get("mean_motion"),
|
||||
)
|
||||
|
||||
constellation_group = _normalize_satellite_constellation_group(
|
||||
metadata.get("constellation_group"),
|
||||
record.name,
|
||||
)
|
||||
footprint_policy = _get_satellite_footprint_policy(constellation_group)
|
||||
return metadata, norad_id, tle_line1, tle_line2, constellation_group, footprint_policy
|
||||
|
||||
|
||||
def convert_satellite_to_geojson(records: List[CollectedData]) -> Dict[str, Any]:
|
||||
"""Convert satellite TLE records to GeoJSON"""
|
||||
features = []
|
||||
|
||||
for record in records:
|
||||
metadata = record.extra_data or {}
|
||||
norad_id = metadata.get("norad_cat_id")
|
||||
|
||||
if not norad_id:
|
||||
extracted = _extract_satellite_record(record)
|
||||
if extracted is None:
|
||||
continue
|
||||
|
||||
tle_line1 = metadata.get("tle_line1")
|
||||
tle_line2 = metadata.get("tle_line2")
|
||||
if not tle_line1 or not tle_line2:
|
||||
tle_line1, tle_line2 = build_tle_lines_from_elements(
|
||||
norad_cat_id=norad_id,
|
||||
epoch=metadata.get("epoch"),
|
||||
inclination=metadata.get("inclination"),
|
||||
raan=metadata.get("raan"),
|
||||
eccentricity=metadata.get("eccentricity"),
|
||||
arg_of_perigee=metadata.get("arg_of_perigee"),
|
||||
mean_anomaly=metadata.get("mean_anomaly"),
|
||||
mean_motion=metadata.get("mean_motion"),
|
||||
)
|
||||
|
||||
constellation_group = _normalize_satellite_constellation_group(
|
||||
metadata.get("constellation_group"),
|
||||
record.name,
|
||||
)
|
||||
footprint_policy = _get_satellite_footprint_policy(constellation_group)
|
||||
metadata, norad_id, tle_line1, tle_line2, constellation_group, footprint_policy = extracted
|
||||
|
||||
features.append(
|
||||
{
|
||||
@@ -340,6 +349,43 @@ def convert_satellite_to_geojson(records: List[CollectedData]) -> Dict[str, Any]
|
||||
return {"type": "FeatureCollection", "features": features}
|
||||
|
||||
|
||||
def convert_satellite_to_compact_rows(records: List[CollectedData]) -> List[List[Any]]:
|
||||
"""Convert satellite TLE records into compact array rows while keeping full catalog fidelity."""
|
||||
rows: List[List[Any]] = []
|
||||
|
||||
for record in records:
|
||||
extracted = _extract_satellite_record(record)
|
||||
if extracted is None:
|
||||
continue
|
||||
metadata, norad_id, tle_line1, tle_line2, constellation_group, _footprint_policy = extracted
|
||||
row: List[Any] = [
|
||||
record.id,
|
||||
norad_id,
|
||||
record.name,
|
||||
constellation_group,
|
||||
tle_line1,
|
||||
tle_line2,
|
||||
]
|
||||
if not tle_line1 or not tle_line2:
|
||||
row.append(
|
||||
[
|
||||
metadata.get("inclination"),
|
||||
metadata.get("raan"),
|
||||
metadata.get("eccentricity"),
|
||||
metadata.get("arg_of_perigee"),
|
||||
metadata.get("mean_anomaly"),
|
||||
metadata.get("mean_motion"),
|
||||
metadata.get("epoch"),
|
||||
metadata.get("international_designator"),
|
||||
metadata.get("classification_type"),
|
||||
metadata.get("bstar"),
|
||||
]
|
||||
)
|
||||
rows.append(row)
|
||||
|
||||
return rows
|
||||
|
||||
|
||||
|
||||
def _get_satellite_footprint_policy(constellation_group: Optional[str]) -> str:
|
||||
if constellation_group == "starlink":
|
||||
@@ -1836,32 +1882,55 @@ async def get_all_geojson(db: AsyncSession = Depends(get_db)):
|
||||
|
||||
@router.get("/geo/satellites")
|
||||
async def get_satellites_geojson(
|
||||
request: Request = None,
|
||||
limit: Optional[int] = Query(
|
||||
None,
|
||||
ge=1,
|
||||
description="Maximum number of satellites to return. Omit for no limit.",
|
||||
),
|
||||
format: Optional[str] = Query(
|
||||
None,
|
||||
pattern="^(geojson|compact)$",
|
||||
description="Response payload format: default GeoJSON or compact full-catalog rows.",
|
||||
),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
response: Response = None,
|
||||
):
|
||||
"""获取卫星 TLE GeoJSON 数据"""
|
||||
"""获取卫星 TLE 数据(支持完整 GeoJSON 与全量紧凑数组格式)"""
|
||||
compact = format == "compact"
|
||||
cache_key = (
|
||||
earth_layer_cache.key("satellites", format="compact", limit=limit or "all")
|
||||
if compact
|
||||
else earth_layer_cache.key("satellites", limit=limit or "all")
|
||||
)
|
||||
|
||||
async def build_payload() -> dict[str, Any]:
|
||||
if compact:
|
||||
return await _build_satellites_compact(limit=limit, db=db)
|
||||
return await _build_satellites_geojson(limit=limit, db=db)
|
||||
|
||||
return await get_or_build_layer_payload(
|
||||
key=earth_layer_cache.key("satellites", limit=limit or "all"),
|
||||
if request is None:
|
||||
return await get_or_build_layer_payload(
|
||||
key=cache_key,
|
||||
policy=SATELLITE_CACHE_POLICY,
|
||||
builder=build_payload,
|
||||
response=response,
|
||||
)
|
||||
|
||||
return await get_or_build_layer_response(
|
||||
key=cache_key,
|
||||
policy=SATELLITE_CACHE_POLICY,
|
||||
builder=build_payload,
|
||||
request=request,
|
||||
response=response,
|
||||
)
|
||||
|
||||
|
||||
async def _build_satellites_geojson(
|
||||
async def _stream_satellite_batches(
|
||||
*,
|
||||
limit: int | None,
|
||||
db: AsyncSession,
|
||||
) -> dict[str, Any]:
|
||||
features: list[dict[str, Any]] = []
|
||||
):
|
||||
source = "celestrak_tle"
|
||||
for current_only in (True, False):
|
||||
if current_only:
|
||||
@@ -1887,15 +1956,52 @@ async def _build_satellites_geojson(
|
||||
try:
|
||||
async for batch in records.partitions(SATELLITE_QUERY_BATCH_SIZE):
|
||||
found_records = True
|
||||
features.extend(convert_satellite_to_geojson(batch)["features"])
|
||||
yield batch
|
||||
finally:
|
||||
await records.close()
|
||||
if found_records:
|
||||
break
|
||||
|
||||
|
||||
async def _build_satellites_geojson(
|
||||
*,
|
||||
limit: int | None,
|
||||
db: AsyncSession,
|
||||
) -> dict[str, Any]:
|
||||
features: list[dict[str, Any]] = []
|
||||
async with aclosing(_stream_satellite_batches(limit=limit, db=db)) as batches:
|
||||
async for batch in batches:
|
||||
features.extend(convert_satellite_to_geojson(batch)["features"])
|
||||
|
||||
return {"type": "FeatureCollection", "features": features, "count": len(features)}
|
||||
|
||||
|
||||
async def _build_satellites_compact(
|
||||
*,
|
||||
limit: int | None,
|
||||
db: AsyncSession,
|
||||
) -> dict[str, Any]:
|
||||
rows: list[list[Any]] = []
|
||||
async with aclosing(_stream_satellite_batches(limit=limit, db=db)) as batches:
|
||||
async for batch in batches:
|
||||
rows.extend(convert_satellite_to_compact_rows(batch))
|
||||
|
||||
return {
|
||||
"format": "satellite_compact_v1",
|
||||
"count": len(rows),
|
||||
"fields": [
|
||||
"id",
|
||||
"norad_cat_id",
|
||||
"name",
|
||||
"constellation_group",
|
||||
"tle_line1",
|
||||
"tle_line2",
|
||||
"fallback_elements",
|
||||
],
|
||||
"satellites": rows,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/geo/supercomputers")
|
||||
async def get_supercomputers_geojson(
|
||||
limit: int = 500,
|
||||
|
||||
@@ -11,6 +11,7 @@ from sqlalchemy import text
|
||||
from app.core.config import settings
|
||||
from app.core.enums import UserRole
|
||||
from app.core.logging import get_logger
|
||||
from app.core.security import is_token_blacklisted
|
||||
from app.core.time import to_iso8601_utc
|
||||
from app.core.websocket.manager import manager
|
||||
from app.db.session import async_session_factory
|
||||
@@ -23,6 +24,12 @@ EARTH_UPDATES_CHANNEL = "earth_updates"
|
||||
|
||||
async def authenticate_token(token: str) -> Optional[dict]:
|
||||
"""Authenticate WebSocket connection via token"""
|
||||
if await is_token_blacklisted(token):
|
||||
logger.warning_event(
|
||||
"WebSocket auth failed: revoked token",
|
||||
event="auth.websocket.revoked_token",
|
||||
)
|
||||
return None
|
||||
try:
|
||||
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
|
||||
if payload.get("type") != "access":
|
||||
@@ -210,9 +217,12 @@ async def websocket_endpoint(
|
||||
await websocket.send_json({"type": "ack", "data": {"received": True}})
|
||||
|
||||
except asyncio.TimeoutError:
|
||||
await websocket.send_json({"type": "heartbeat", "data": {"action": "ping"}})
|
||||
try:
|
||||
await websocket.send_json({"type": "heartbeat", "data": {"action": "ping"}})
|
||||
except Exception:
|
||||
break
|
||||
|
||||
except WebSocketDisconnect:
|
||||
except (WebSocketDisconnect, RuntimeError):
|
||||
pass
|
||||
finally:
|
||||
await log_tail_manager.disconnect(websocket)
|
||||
|
||||
+130
-8
@@ -1,13 +1,34 @@
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
from typing import List
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import List, Optional
|
||||
from urllib.parse import quote, urlsplit, urlunsplit
|
||||
|
||||
from pydantic_settings import BaseSettings
|
||||
|
||||
|
||||
ROOT_DIR = Path(__file__).parent.parent.parent.parent
|
||||
VERSION_FILE = ROOT_DIR / "VERSION"
|
||||
WEAK_SECRET_PLACEHOLDERS = frozenset(
|
||||
{
|
||||
"",
|
||||
"change-me",
|
||||
"change_me",
|
||||
"change_me_to_a_random_secret",
|
||||
"change_me_to_a_random_32_plus_char_secret",
|
||||
"your-secret-key-change-in-production",
|
||||
"replace-with-strong-32-char-random-secret",
|
||||
}
|
||||
)
|
||||
WEAK_SERVICE_TOKEN_PLACEHOLDERS = frozenset(
|
||||
{
|
||||
"",
|
||||
"change-me",
|
||||
"change_me",
|
||||
"replace-with-internal-token",
|
||||
}
|
||||
)
|
||||
VALID_PLANET_ROLES = frozenset({"all", "api", "worker"})
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
@@ -16,23 +37,46 @@ class Settings(BaseSettings):
|
||||
os.getenv("APP_VERSION")
|
||||
or (VERSION_FILE.read_text(encoding="utf-8").strip() if VERSION_FILE.exists() else "0.19.0")
|
||||
)
|
||||
APP_ENV: str = "development"
|
||||
PLANET_ROLE: str = "all"
|
||||
ENABLE_SCHEDULER: Optional[bool] = None
|
||||
|
||||
API_V1_STR: str = "/api/v1"
|
||||
SECRET_KEY: str = "your-secret-key-change-in-production"
|
||||
ALGORITHM: str = "HS256"
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES: int = 0
|
||||
REFRESH_TOKEN_EXPIRE_DAYS: int = 0
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES: int = 60
|
||||
REFRESH_TOKEN_EXPIRE_DAYS: int = 7
|
||||
|
||||
SEED_DEFAULT_DEV_USERS: Optional[bool] = None
|
||||
INITIAL_ADMIN_USERNAME: str = ""
|
||||
INITIAL_ADMIN_EMAIL: str = ""
|
||||
INITIAL_ADMIN_PASSWORD: str = ""
|
||||
SETTINGS_ENCRYPTION_KEY: str = ""
|
||||
|
||||
LOGIN_RATE_LIMIT_MAX_ATTEMPTS: int = 10
|
||||
LOGIN_RATE_LIMIT_WINDOW_SECONDS: int = 300
|
||||
|
||||
POSTGRES_SERVER: str = "localhost"
|
||||
POSTGRES_USER: str = "postgres"
|
||||
POSTGRES_PASSWORD: str = "postgres"
|
||||
POSTGRES_DB: str = "planet_db"
|
||||
DATABASE_URL: str = f"postgresql+asyncpg://postgres:postgres@localhost:5432/planet_db"
|
||||
DATABASE_URL: str = "postgresql+asyncpg://postgres:postgres@localhost:5432/planet_db"
|
||||
|
||||
REDIS_SERVER: str = "localhost"
|
||||
REDIS_PORT: int = 6379
|
||||
REDIS_DB: int = 0
|
||||
REDIS_PASSWORD: str = ""
|
||||
|
||||
CORS_ORIGINS: List[str] = ["http://localhost:3000", "http://localhost:8000"]
|
||||
CORS_ORIGINS: List[str] = [
|
||||
"http://localhost:3000",
|
||||
"http://127.0.0.1:3000",
|
||||
"http://localhost:8000",
|
||||
"http://127.0.0.1:8000",
|
||||
"planet://earth",
|
||||
]
|
||||
|
||||
COLLECTOR_MAX_CONCURRENCY: int = 2
|
||||
COLLECTOR_HEAVY_CONCURRENCY: int = 1
|
||||
|
||||
SPACETRACK_USERNAME: str = ""
|
||||
SPACETRACK_PASSWORD: str = ""
|
||||
@@ -43,11 +87,53 @@ class Settings(BaseSettings):
|
||||
AI_PROVIDER_RETRY_ATTEMPTS: int = 2
|
||||
OBSERVABILITY_INGEST_TOKEN: str = ""
|
||||
|
||||
CLIENT_UPDATES_DIR: str = ""
|
||||
CLIENT_UPDATE_PUBLISH_TOKEN: str = ""
|
||||
CLIENT_MIN_SHELL_VERSION: str = "0.78.0"
|
||||
CLIENT_RELEASE_PAGE_URL: str = "https://gitea.rclaw.top/linkong/planet/releases"
|
||||
|
||||
@property
|
||||
def is_production(self) -> bool:
|
||||
return str(self.APP_ENV or "").strip().lower() == "production"
|
||||
|
||||
@property
|
||||
def normalized_role(self) -> str:
|
||||
role = str(self.PLANET_ROLE or "all").strip().lower()
|
||||
return role if role in VALID_PLANET_ROLES else "all"
|
||||
|
||||
@property
|
||||
def should_run_scheduler(self) -> bool:
|
||||
if self.ENABLE_SCHEDULER is not None:
|
||||
return bool(self.ENABLE_SCHEDULER)
|
||||
return self.normalized_role in {"all", "worker"}
|
||||
|
||||
@property
|
||||
def should_run_workers(self) -> bool:
|
||||
return self.normalized_role in {"all", "worker"}
|
||||
|
||||
@property
|
||||
def should_seed_default_dev_users(self) -> bool:
|
||||
if self.SEED_DEFAULT_DEV_USERS is not None:
|
||||
return bool(self.SEED_DEFAULT_DEV_USERS)
|
||||
return not self.is_production
|
||||
|
||||
@property
|
||||
def REDIS_URL(self) -> str:
|
||||
return os.getenv(
|
||||
"REDIS_URL", f"redis://{self.REDIS_SERVER}:{self.REDIS_PORT}/{self.REDIS_DB}"
|
||||
raw = os.getenv(
|
||||
"REDIS_URL",
|
||||
f"redis://{self.REDIS_SERVER}:{self.REDIS_PORT}/{self.REDIS_DB}",
|
||||
)
|
||||
password = str(self.REDIS_PASSWORD or "")
|
||||
if password:
|
||||
parsed = urlsplit(raw)
|
||||
if parsed.scheme in {"redis", "rediss"} and parsed.password is None and parsed.hostname:
|
||||
user_part = parsed.username or ""
|
||||
encoded_pw = quote(password, safe="")
|
||||
netloc = f"{user_part}:{encoded_pw}@{parsed.hostname}"
|
||||
if parsed.port:
|
||||
netloc = f"{netloc}:{parsed.port}"
|
||||
return urlunsplit((parsed.scheme, netloc, parsed.path, parsed.query, parsed.fragment))
|
||||
return raw
|
||||
|
||||
class Config:
|
||||
env_file = Path(__file__).parent.parent.parent / ".env"
|
||||
@@ -55,6 +141,42 @@ class Settings(BaseSettings):
|
||||
extra = "ignore"
|
||||
|
||||
|
||||
def validate_production_security(cfg: Settings) -> None:
|
||||
"""Fail fast on insecure defaults when APP_ENV=production."""
|
||||
raw_role = str(cfg.PLANET_ROLE or "all").strip().lower()
|
||||
if raw_role not in VALID_PLANET_ROLES:
|
||||
raise RuntimeError(
|
||||
f"Invalid PLANET_ROLE={cfg.PLANET_ROLE!r}; expected one of {sorted(VALID_PLANET_ROLES)}"
|
||||
)
|
||||
|
||||
if not cfg.is_production:
|
||||
return
|
||||
|
||||
errors: list[str] = []
|
||||
secret_key = str(cfg.SECRET_KEY or "").strip()
|
||||
if secret_key in WEAK_SECRET_PLACEHOLDERS or len(secret_key) < 32:
|
||||
errors.append("SECRET_KEY must be set to a random string of at least 32 characters")
|
||||
|
||||
if int(cfg.ACCESS_TOKEN_EXPIRE_MINUTES) <= 0:
|
||||
errors.append("ACCESS_TOKEN_EXPIRE_MINUTES must be > 0 in production")
|
||||
|
||||
if int(cfg.REFRESH_TOKEN_EXPIRE_DAYS) <= 0:
|
||||
errors.append("REFRESH_TOKEN_EXPIRE_DAYS must be > 0 in production")
|
||||
|
||||
if "*" in (cfg.CORS_ORIGINS or []):
|
||||
errors.append("CORS_ORIGINS must not contain '*' in production")
|
||||
|
||||
ai_url = str(cfg.AI_PROVIDER_SERVICE_URL or "").strip()
|
||||
ai_token = str(cfg.AI_PROVIDER_SERVICE_TOKEN or "").strip()
|
||||
if ai_url and ai_token in WEAK_SERVICE_TOKEN_PLACEHOLDERS:
|
||||
errors.append(
|
||||
"AI_PROVIDER_SERVICE_TOKEN must be configured (not empty or placeholder) in production"
|
||||
)
|
||||
|
||||
if errors:
|
||||
raise RuntimeError("Production security validation failed: " + "; ".join(errors))
|
||||
|
||||
|
||||
@lru_cache()
|
||||
def get_settings() -> Settings:
|
||||
return Settings()
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
"""Symmetric encryption helpers for persisted sensitive settings."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
from copy import deepcopy
|
||||
import hashlib
|
||||
from typing import Any
|
||||
|
||||
from cryptography.fernet import Fernet, InvalidToken
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.logging import get_logger
|
||||
|
||||
logger = get_logger(__name__, service="secret_crypto")
|
||||
|
||||
ENCRYPTED_PREFIX = "enc:v1:"
|
||||
ENCRYPTED_CATEGORIES = frozenset({"smtp", "external_integrations"})
|
||||
SECRET_FIELD_NAMES = frozenset(
|
||||
{
|
||||
"api_key",
|
||||
"service_token",
|
||||
"client_secret",
|
||||
"password",
|
||||
"token",
|
||||
"access_token",
|
||||
"bearer_token",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _derive_fernet_key(raw_key: str) -> bytes:
|
||||
cleaned = raw_key.strip()
|
||||
candidate = cleaned.encode("utf-8")
|
||||
try:
|
||||
Fernet(candidate)
|
||||
return candidate
|
||||
except Exception:
|
||||
digest = hashlib.sha256(candidate).digest()
|
||||
return base64.urlsafe_b64encode(digest)
|
||||
|
||||
|
||||
def _get_fernet() -> Fernet | None:
|
||||
raw_key = str(getattr(settings, "SETTINGS_ENCRYPTION_KEY", "") or "").strip()
|
||||
if not raw_key:
|
||||
return None
|
||||
return Fernet(_derive_fernet_key(raw_key))
|
||||
|
||||
|
||||
def encrypt_secret(value: str) -> str:
|
||||
"""Encrypt a secret string when SETTINGS_ENCRYPTION_KEY is configured."""
|
||||
if not value or value.startswith(ENCRYPTED_PREFIX):
|
||||
return value
|
||||
fernet = _get_fernet()
|
||||
if fernet is None:
|
||||
return value
|
||||
token = fernet.encrypt(value.encode("utf-8")).decode("ascii")
|
||||
return f"{ENCRYPTED_PREFIX}{token}"
|
||||
|
||||
|
||||
def decrypt_secret(value: str) -> str:
|
||||
"""Decrypt a secret string; transparently passes through legacy plaintext."""
|
||||
if not value or not value.startswith(ENCRYPTED_PREFIX):
|
||||
return value
|
||||
fernet = _get_fernet()
|
||||
if fernet is None:
|
||||
logger.warning_event(
|
||||
"Encrypted setting encountered without SETTINGS_ENCRYPTION_KEY configured",
|
||||
event="settings.secret.key_missing",
|
||||
)
|
||||
return ""
|
||||
ciphertext = value[len(ENCRYPTED_PREFIX) :].encode("ascii")
|
||||
try:
|
||||
return fernet.decrypt(ciphertext).decode("utf-8")
|
||||
except (InvalidToken, ValueError):
|
||||
logger.warning_event(
|
||||
"Failed to decrypt persisted setting secret",
|
||||
event="settings.secret.decrypt_failed",
|
||||
)
|
||||
return ""
|
||||
|
||||
|
||||
def _transform_payload(value: Any, *, encrypt: bool) -> Any:
|
||||
if isinstance(value, dict):
|
||||
transformed: dict[str, Any] = {}
|
||||
for key, item in value.items():
|
||||
if key in SECRET_FIELD_NAMES and isinstance(item, str):
|
||||
transformed[key] = encrypt_secret(item) if encrypt else decrypt_secret(item)
|
||||
else:
|
||||
transformed[key] = _transform_payload(item, encrypt=encrypt)
|
||||
return transformed
|
||||
if isinstance(value, list):
|
||||
return [_transform_payload(item, encrypt=encrypt) for item in value]
|
||||
return value
|
||||
|
||||
|
||||
def encrypt_setting_payload(category: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Return a deep copy of payload with sensitive fields encrypted if enabled."""
|
||||
copied = deepcopy(payload)
|
||||
if category not in ENCRYPTED_CATEGORIES:
|
||||
return copied
|
||||
return _transform_payload(copied, encrypt=True)
|
||||
|
||||
|
||||
def decrypt_setting_payload(category: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Return a deep copy of payload with encrypted sensitive fields decrypted."""
|
||||
copied = deepcopy(payload)
|
||||
if category not in ENCRYPTED_CATEGORIES:
|
||||
return copied
|
||||
return _transform_payload(copied, encrypt=False)
|
||||
@@ -1,20 +1,32 @@
|
||||
import asyncio
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import Optional
|
||||
import hashlib
|
||||
import time
|
||||
from typing import Any, Optional
|
||||
from uuid import uuid4
|
||||
|
||||
import bcrypt
|
||||
import redis
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
from jose import JWTError, jwt
|
||||
import redis
|
||||
import redis.asyncio as aioredis
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.logging import get_logger
|
||||
from app.db.session import get_db
|
||||
from app.models.user import User
|
||||
|
||||
logger = get_logger(__name__, service="security")
|
||||
oauth2_scheme = HTTPBearer()
|
||||
|
||||
REVOKED_KEY_PREFIX = "revoked_jwt:"
|
||||
LOCAL_REVOKED_MAX_ENTRIES = 10_000
|
||||
REDIS_OP_TIMEOUT_SECONDS = 1.5
|
||||
_LOCAL_REVOKED_TOKENS: dict[str, float] = {}
|
||||
|
||||
|
||||
class _RedisClient:
|
||||
_client = None
|
||||
@@ -23,7 +35,7 @@ class _RedisClient:
|
||||
def get_client(cls):
|
||||
if cls._client is None:
|
||||
redis_url = settings.REDIS_URL
|
||||
if redis_url.startswith("redis://"):
|
||||
if redis_url.startswith(("redis://", "rediss://")):
|
||||
cls._client = redis.from_url(
|
||||
redis_url,
|
||||
decode_responses=True,
|
||||
@@ -35,6 +47,7 @@ class _RedisClient:
|
||||
host=settings.REDIS_SERVER,
|
||||
port=settings.REDIS_PORT,
|
||||
db=settings.REDIS_DB,
|
||||
password=settings.REDIS_PASSWORD or None,
|
||||
decode_responses=True,
|
||||
socket_connect_timeout=2,
|
||||
socket_timeout=2,
|
||||
@@ -42,9 +55,95 @@ class _RedisClient:
|
||||
return cls._client
|
||||
|
||||
|
||||
class _AsyncRedisClient:
|
||||
_client: aioredis.Redis | None = None
|
||||
_loop: asyncio.AbstractEventLoop | None = None
|
||||
|
||||
@classmethod
|
||||
def get_client(cls) -> aioredis.Redis:
|
||||
loop = asyncio.get_running_loop()
|
||||
if cls._client is None or cls._loop is not loop:
|
||||
redis_url = settings.REDIS_URL
|
||||
if redis_url.startswith(("redis://", "rediss://")):
|
||||
cls._client = aioredis.from_url(
|
||||
redis_url,
|
||||
decode_responses=True,
|
||||
socket_connect_timeout=1.5,
|
||||
socket_timeout=1.5,
|
||||
)
|
||||
else:
|
||||
cls._client = aioredis.Redis(
|
||||
host=settings.REDIS_SERVER,
|
||||
port=settings.REDIS_PORT,
|
||||
db=settings.REDIS_DB,
|
||||
password=settings.REDIS_PASSWORD or None,
|
||||
decode_responses=True,
|
||||
socket_connect_timeout=1.5,
|
||||
socket_timeout=1.5,
|
||||
)
|
||||
cls._loop = loop
|
||||
return cls._client
|
||||
|
||||
|
||||
redis_client = _RedisClient.get_client()
|
||||
|
||||
|
||||
def _token_digest(token: str) -> str:
|
||||
return hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def _prune_local_revocations(now: float | None = None) -> None:
|
||||
current = now if now is not None else time.monotonic()
|
||||
expired = [key for key, deadline in _LOCAL_REVOKED_TOKENS.items() if deadline <= current]
|
||||
for key in expired:
|
||||
_LOCAL_REVOKED_TOKENS.pop(key, None)
|
||||
while len(_LOCAL_REVOKED_TOKENS) > LOCAL_REVOKED_MAX_ENTRIES:
|
||||
oldest_key = next(iter(_LOCAL_REVOKED_TOKENS))
|
||||
_LOCAL_REVOKED_TOKENS.pop(oldest_key, None)
|
||||
|
||||
|
||||
def _record_local_revocation(token_digest: str, ttl_seconds: int) -> None:
|
||||
now = time.monotonic()
|
||||
_prune_local_revocations(now)
|
||||
_LOCAL_REVOKED_TOKENS[token_digest] = now + max(60, ttl_seconds)
|
||||
|
||||
|
||||
def _is_locally_revoked(token_digest: str) -> bool:
|
||||
now = time.monotonic()
|
||||
deadline = _LOCAL_REVOKED_TOKENS.get(token_digest)
|
||||
if deadline is None:
|
||||
return False
|
||||
if deadline <= now:
|
||||
_LOCAL_REVOKED_TOKENS.pop(token_digest, None)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _is_monkeypatched_sync_redis(candidate: Any) -> bool:
|
||||
if candidate is None:
|
||||
return False
|
||||
if not isinstance(candidate, redis.Redis):
|
||||
return True
|
||||
return "sismember" in getattr(candidate, "__dict__", {})
|
||||
|
||||
|
||||
def _token_revocation_ttl_seconds(
|
||||
token: str,
|
||||
default_ttl: int | None = None,
|
||||
*,
|
||||
decoded_payload: dict[str, Any] | None = None,
|
||||
) -> int:
|
||||
fallback = default_ttl if default_ttl is not None else max(settings.REFRESH_TOKEN_EXPIRE_DAYS, 7) * 86400
|
||||
payload = decoded_payload if decoded_payload is not None else decode_token(token)
|
||||
if payload and payload.get("exp") is not None:
|
||||
try:
|
||||
remaining = int(float(payload["exp"]) - datetime.now(UTC).timestamp())
|
||||
return max(60, remaining)
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
return max(60, int(fallback))
|
||||
|
||||
|
||||
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
||||
return bcrypt.checkpw(plain_password.encode(), hashed_password.encode())
|
||||
|
||||
@@ -63,7 +162,7 @@ def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -
|
||||
expire = None
|
||||
if expire:
|
||||
to_encode.update({"exp": expire})
|
||||
to_encode.update({"type": "access"})
|
||||
to_encode.update({"type": "access", "jti": uuid4().hex})
|
||||
if "sub" in to_encode:
|
||||
to_encode["sub"] = str(to_encode["sub"])
|
||||
return jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
|
||||
@@ -74,7 +173,7 @@ def create_refresh_token(data: dict) -> str:
|
||||
if settings.REFRESH_TOKEN_EXPIRE_DAYS > 0:
|
||||
expire = datetime.now(UTC) + timedelta(days=settings.REFRESH_TOKEN_EXPIRE_DAYS)
|
||||
to_encode.update({"exp": expire})
|
||||
to_encode.update({"type": "refresh"})
|
||||
to_encode.update({"type": "refresh", "jti": uuid4().hex})
|
||||
if "sub" in to_encode:
|
||||
to_encode["sub"] = str(to_encode["sub"])
|
||||
return jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
|
||||
@@ -88,6 +187,76 @@ def decode_token(token: str) -> Optional[dict]:
|
||||
return None
|
||||
|
||||
|
||||
async def revoke_token(token: str, *, ttl_seconds: int | None = None) -> None:
|
||||
"""Revoke a verified, unexpired JWT in Redis with bounded TTL plus local fallback."""
|
||||
if not token:
|
||||
return
|
||||
payload = decode_token(token)
|
||||
if payload is None:
|
||||
return
|
||||
digest = _token_digest(token)
|
||||
ttl = _token_revocation_ttl_seconds(
|
||||
token,
|
||||
default_ttl=ttl_seconds,
|
||||
decoded_payload=payload,
|
||||
)
|
||||
_record_local_revocation(digest, ttl)
|
||||
try:
|
||||
client = _AsyncRedisClient.get_client()
|
||||
await asyncio.wait_for(
|
||||
client.set(f"{REVOKED_KEY_PREFIX}{digest}", "1", ex=ttl),
|
||||
timeout=REDIS_OP_TIMEOUT_SECONDS,
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed to persist revoked token to Redis; kept in local revocation cache",
|
||||
event="auth.redis_revoke.unavailable",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
|
||||
|
||||
async def is_token_blacklisted(token: str, *, legacy_sync_client: Any = None) -> bool:
|
||||
"""Check whether a JWT was revoked without blocking the event loop or failing 500 on Redis outage."""
|
||||
if not token:
|
||||
return False
|
||||
digest = _token_digest(token)
|
||||
if _is_locally_revoked(digest):
|
||||
return True
|
||||
|
||||
for candidate in (legacy_sync_client, redis_client):
|
||||
if _is_monkeypatched_sync_redis(candidate):
|
||||
try:
|
||||
return bool(candidate.sismember("blacklisted_tokens", token))
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Sync token blacklist check failed; degrading safely",
|
||||
event="auth.redis_blacklist.sync_unavailable",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
return False
|
||||
|
||||
try:
|
||||
client = _AsyncRedisClient.get_client()
|
||||
if await asyncio.wait_for(
|
||||
client.exists(f"{REVOKED_KEY_PREFIX}{digest}"),
|
||||
timeout=REDIS_OP_TIMEOUT_SECONDS,
|
||||
):
|
||||
return True
|
||||
return bool(
|
||||
await asyncio.wait_for(
|
||||
client.sismember("blacklisted_tokens", token),
|
||||
timeout=REDIS_OP_TIMEOUT_SECONDS,
|
||||
)
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Async token blacklist check failed; degrading safely",
|
||||
event="auth.redis_blacklist.unavailable",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
return False
|
||||
|
||||
|
||||
async def _load_active_user(user_id: str, db: AsyncSession) -> User:
|
||||
try:
|
||||
parsed_id = int(user_id)
|
||||
@@ -108,7 +277,7 @@ async def get_current_user(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> User:
|
||||
token = credentials.credentials
|
||||
if redis_client.sismember("blacklisted_tokens", token):
|
||||
if await is_token_blacklisted(token):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Token has been revoked",
|
||||
@@ -133,6 +302,11 @@ async def get_current_user_refresh(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> User:
|
||||
token = credentials.credentials
|
||||
if await is_token_blacklisted(token):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Token has been revoked",
|
||||
)
|
||||
payload = decode_token(token)
|
||||
if payload is None or payload.get("type") != "refresh":
|
||||
raise HTTPException(
|
||||
@@ -149,4 +323,20 @@ async def get_current_user_refresh(
|
||||
|
||||
|
||||
def blacklist_token(token: str) -> None:
|
||||
redis_client.sadd("blacklisted_tokens", token)
|
||||
"""Best-effort revocation helper for legacy synchronous callers."""
|
||||
if not token:
|
||||
return
|
||||
payload = decode_token(token)
|
||||
if payload is None:
|
||||
return
|
||||
digest = _token_digest(token)
|
||||
ttl = _token_revocation_ttl_seconds(token, decoded_payload=payload)
|
||||
_record_local_revocation(digest, ttl)
|
||||
try:
|
||||
redis_client.set(f"{REVOKED_KEY_PREFIX}{digest}", "1", ex=ttl)
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed to write sync token revocation to Redis",
|
||||
event="auth.redis_revoke.sync_unavailable",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
@@ -24,32 +24,124 @@ class DataBroadcaster:
|
||||
self._vessel_flush_interval = 1.0
|
||||
|
||||
async def get_dashboard_stats(self) -> Dict[str, Any]:
|
||||
"""Get dashboard statistics"""
|
||||
return {
|
||||
"total_datasources": 9,
|
||||
"active_datasources": 8,
|
||||
"tasks_today": 45,
|
||||
"success_rate": 97.8,
|
||||
"last_updated": to_iso8601_utc(datetime.now(UTC)),
|
||||
"alerts": {"critical": 0, "warning": 2, "info": 5},
|
||||
"""Get dashboard statistics from PostgreSQL."""
|
||||
from sqlalchemy import func, select
|
||||
|
||||
from app.core.enums import AlertSeverity, AlertStatus, JobStatus
|
||||
from app.db.session import async_session_factory
|
||||
from app.models.alert import Alert
|
||||
from app.models.datasource import DataSource
|
||||
from app.models.task import CollectionTask
|
||||
|
||||
alerts_summary = {
|
||||
AlertSeverity.CRITICAL.value: 0,
|
||||
AlertSeverity.WARNING.value: 0,
|
||||
AlertSeverity.INFO.value: 0,
|
||||
}
|
||||
now_utc = datetime.now(UTC)
|
||||
today_start = now_utc.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
|
||||
try:
|
||||
async with async_session_factory() as db:
|
||||
total_datasources = int(
|
||||
(await db.scalar(select(func.count(DataSource.id)))) or 0
|
||||
)
|
||||
active_datasources = int(
|
||||
(
|
||||
await db.scalar(
|
||||
select(func.count(DataSource.id)).where(DataSource.is_active.is_(True))
|
||||
)
|
||||
)
|
||||
or 0
|
||||
)
|
||||
tasks_today = int(
|
||||
(
|
||||
await db.scalar(
|
||||
select(func.count(CollectionTask.id)).where(
|
||||
CollectionTask.created_at >= today_start
|
||||
)
|
||||
)
|
||||
)
|
||||
or 0
|
||||
)
|
||||
finished_rows = (
|
||||
await db.execute(
|
||||
select(CollectionTask.status, func.count(CollectionTask.id))
|
||||
.where(
|
||||
CollectionTask.created_at >= today_start,
|
||||
CollectionTask.status.in_(
|
||||
[JobStatus.SUCCESS.value, JobStatus.FAILED.value]
|
||||
),
|
||||
)
|
||||
.group_by(CollectionTask.status)
|
||||
)
|
||||
).all()
|
||||
finished_counts = {str(status): int(count) for status, count in finished_rows}
|
||||
success_count = finished_counts.get(JobStatus.SUCCESS.value, 0)
|
||||
total_finished = success_count + finished_counts.get(JobStatus.FAILED.value, 0)
|
||||
success_rate = (
|
||||
round(success_count * 100.0 / total_finished, 1)
|
||||
if total_finished > 0
|
||||
else 100.0
|
||||
)
|
||||
|
||||
alert_rows = (
|
||||
await db.execute(
|
||||
select(Alert.severity, func.count(Alert.id))
|
||||
.where(Alert.status == AlertStatus.ACTIVE)
|
||||
.group_by(Alert.severity)
|
||||
)
|
||||
).all()
|
||||
for severity, count in alert_rows:
|
||||
key = severity.value if hasattr(severity, "value") else str(severity).lower()
|
||||
if key in alerts_summary:
|
||||
alerts_summary[key] = int(count)
|
||||
|
||||
return {
|
||||
"total_datasources": total_datasources,
|
||||
"active_datasources": active_datasources,
|
||||
"tasks_today": tasks_today,
|
||||
"success_rate": success_rate,
|
||||
"last_updated": to_iso8601_utc(now_utc),
|
||||
"alerts": alerts_summary,
|
||||
}
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed to query dashboard stats; returning empty fallback",
|
||||
event="dashboard.stats.query_failed",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
return {
|
||||
"total_datasources": 0,
|
||||
"active_datasources": 0,
|
||||
"tasks_today": 0,
|
||||
"success_rate": 100.0,
|
||||
"last_updated": to_iso8601_utc(now_utc),
|
||||
"alerts": alerts_summary,
|
||||
}
|
||||
|
||||
async def broadcast_stats(self, interval: int = 5):
|
||||
"""Broadcast dashboard stats periodically"""
|
||||
"""Broadcast dashboard stats periodically only when subscribers are attached."""
|
||||
while self.running:
|
||||
try:
|
||||
stats = await self.get_dashboard_stats()
|
||||
await manager.broadcast(
|
||||
{
|
||||
"type": "data_frame",
|
||||
"channel": "dashboard",
|
||||
"timestamp": to_iso8601_utc(datetime.now(UTC)),
|
||||
"payload": {"stats": stats},
|
||||
},
|
||||
channel="dashboard",
|
||||
if manager.channel_subscriptions.get("dashboard"):
|
||||
stats = await self.get_dashboard_stats()
|
||||
await manager.broadcast(
|
||||
{
|
||||
"type": "data_frame",
|
||||
"channel": "dashboard",
|
||||
"timestamp": to_iso8601_utc(datetime.now(UTC)),
|
||||
"payload": {"stats": stats},
|
||||
},
|
||||
channel="dashboard",
|
||||
publish=False,
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed to broadcast dashboard stats",
|
||||
event="dashboard.stats.broadcast_failed",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
await asyncio.sleep(interval)
|
||||
|
||||
async def broadcast_alert(self, alert: Dict[str, Any]):
|
||||
|
||||
@@ -1,26 +1,150 @@
|
||||
"""WebSocket Connection Manager"""
|
||||
"""WebSocket Connection Manager with optional cross-replica Redis Pub/Sub relay."""
|
||||
|
||||
import asyncio
|
||||
from contextlib import suppress
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any, Dict, Set, Optional
|
||||
import json
|
||||
from typing import Any, Dict, Optional, Set
|
||||
from uuid import uuid4
|
||||
|
||||
from fastapi import WebSocket
|
||||
import redis.asyncio as redis
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.logging import get_logger
|
||||
|
||||
logger = get_logger(__name__, service="websocket")
|
||||
|
||||
MAX_VESSEL_SUBSCRIPTION_LIMIT = 5000
|
||||
MAX_VESSEL_WS_MESSAGE_ITEMS = 1000
|
||||
MAX_VESSEL_BBOX_AREA = 2500.0
|
||||
PLANET_WS_PUBSUB_CHANNEL = "planet:ws:broadcast"
|
||||
|
||||
|
||||
def _create_async_redis_client(*, socket_timeout: float = 2.0) -> redis.Redis:
|
||||
redis_url = settings.REDIS_URL
|
||||
if redis_url.startswith(("redis://", "rediss://")):
|
||||
return redis.from_url(
|
||||
redis_url,
|
||||
decode_responses=True,
|
||||
socket_connect_timeout=2.0,
|
||||
socket_timeout=socket_timeout,
|
||||
)
|
||||
return redis.Redis(
|
||||
host=settings.REDIS_SERVER,
|
||||
port=settings.REDIS_PORT,
|
||||
db=settings.REDIS_DB,
|
||||
password=settings.REDIS_PASSWORD or None,
|
||||
decode_responses=True,
|
||||
socket_connect_timeout=2.0,
|
||||
socket_timeout=socket_timeout,
|
||||
)
|
||||
|
||||
|
||||
class ConnectionManager:
|
||||
"""Manages WebSocket connections"""
|
||||
"""Manages WebSocket connections and cross-replica Pub/Sub fanout."""
|
||||
|
||||
def __init__(self):
|
||||
self.active_connections: Dict[str, Set[WebSocket]] = {} # user_id -> connections
|
||||
self.active_connections: Dict[str, Set[WebSocket]] = {}
|
||||
self.channel_subscriptions: Dict[str, Set[WebSocket]] = {}
|
||||
self.websocket_channels: Dict[WebSocket, Set[str]] = {}
|
||||
self.vessel_subscriptions: Dict[WebSocket, dict[str, Any]] = {}
|
||||
self.redis_client: Optional[redis.Redis] = None
|
||||
self.instance_id: str = uuid4().hex[:12]
|
||||
self._pubsub_enabled: bool = False
|
||||
self._pubsub_publish_only: bool = False
|
||||
self._pubsub_task: Optional[asyncio.Task[Any]] = None
|
||||
self._pubsub_client: Optional[redis.Redis] = None
|
||||
|
||||
async def start_pubsub(self, *, publish_only: bool = False) -> None:
|
||||
self._pubsub_enabled = True
|
||||
self._pubsub_publish_only = publish_only
|
||||
if not publish_only and (self._pubsub_task is None or self._pubsub_task.done()):
|
||||
self._pubsub_task = asyncio.create_task(self._pubsub_loop())
|
||||
|
||||
async def stop_pubsub(self) -> None:
|
||||
self._pubsub_enabled = False
|
||||
task = self._pubsub_task
|
||||
self._pubsub_task = None
|
||||
if task is not None:
|
||||
task.cancel()
|
||||
with suppress(asyncio.CancelledError):
|
||||
await task
|
||||
if self._pubsub_client is not None:
|
||||
with suppress(Exception):
|
||||
await self._pubsub_client.aclose()
|
||||
self._pubsub_client = None
|
||||
|
||||
async def _publish_pubsub_envelope(self, envelope: dict[str, Any]) -> None:
|
||||
if not self._pubsub_enabled:
|
||||
return
|
||||
try:
|
||||
if self._pubsub_client is None:
|
||||
self._pubsub_client = _create_async_redis_client(socket_timeout=2.0)
|
||||
payload = json.dumps({"origin": self.instance_id, **envelope}, default=str)
|
||||
await self._pubsub_client.publish(PLANET_WS_PUBSUB_CHANNEL, payload)
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed to publish WebSocket broadcast to Redis Pub/Sub",
|
||||
event="websocket.pubsub.publish_failed",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
|
||||
async def handle_pubsub_payload(self, raw_payload: str | bytes) -> bool:
|
||||
text = raw_payload.decode("utf-8") if isinstance(raw_payload, bytes) else str(raw_payload)
|
||||
try:
|
||||
envelope = json.loads(text)
|
||||
except json.JSONDecodeError:
|
||||
return False
|
||||
if not isinstance(envelope, dict):
|
||||
return False
|
||||
if envelope.get("origin") == self.instance_id:
|
||||
return False
|
||||
|
||||
kind = envelope.get("kind")
|
||||
if kind == "channel" and isinstance(envelope.get("message"), dict):
|
||||
await self._deliver_local_broadcast(
|
||||
envelope["message"],
|
||||
channel=str(envelope.get("channel") or "all"),
|
||||
)
|
||||
return True
|
||||
if kind == "vessels" and isinstance(envelope.get("data"), dict):
|
||||
await self._deliver_local_vessels(envelope["data"])
|
||||
return True
|
||||
return False
|
||||
|
||||
async def _pubsub_loop(self) -> None:
|
||||
while self._pubsub_enabled and not self._pubsub_publish_only:
|
||||
client: Optional[redis.Redis] = None
|
||||
pubsub = None
|
||||
try:
|
||||
client = _create_async_redis_client(socket_timeout=5.0)
|
||||
pubsub = client.pubsub()
|
||||
await pubsub.subscribe(PLANET_WS_PUBSUB_CHANNEL)
|
||||
while self._pubsub_enabled and not self._pubsub_publish_only:
|
||||
message = await pubsub.get_message(
|
||||
ignore_subscribe_messages=True,
|
||||
timeout=1.0,
|
||||
)
|
||||
if message and message.get("data") is not None:
|
||||
await self.handle_pubsub_payload(message["data"])
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"WebSocket Redis Pub/Sub listener reconnecting after error",
|
||||
event="websocket.pubsub.listener_error",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
await asyncio.sleep(2.0)
|
||||
finally:
|
||||
if pubsub is not None:
|
||||
with suppress(Exception):
|
||||
await pubsub.unsubscribe(PLANET_WS_PUBSUB_CHANNEL)
|
||||
await pubsub.aclose()
|
||||
if client is not None:
|
||||
with suppress(Exception):
|
||||
await client.aclose()
|
||||
|
||||
async def connect(self, websocket: WebSocket, user_id: str):
|
||||
await websocket.accept()
|
||||
@@ -29,16 +153,7 @@ class ConnectionManager:
|
||||
self.active_connections[user_id].add(websocket)
|
||||
|
||||
if self.redis_client is None:
|
||||
redis_url = settings.REDIS_URL
|
||||
if redis_url.startswith("redis://"):
|
||||
self.redis_client = redis.from_url(redis_url, decode_responses=True)
|
||||
else:
|
||||
self.redis_client = redis.Redis(
|
||||
host=settings.REDIS_SERVER,
|
||||
port=settings.REDIS_PORT,
|
||||
db=settings.REDIS_DB,
|
||||
decode_responses=True,
|
||||
)
|
||||
self.redis_client = _create_async_redis_client(socket_timeout=2.0)
|
||||
|
||||
def disconnect(self, websocket: WebSocket, user_id: str):
|
||||
if user_id in self.active_connections:
|
||||
@@ -129,15 +244,15 @@ class ConnectionManager:
|
||||
|
||||
async def send_personal_message(self, message: dict, user_id: str):
|
||||
if user_id in self.active_connections:
|
||||
for connection in self.active_connections[user_id]:
|
||||
for connection in list(self.active_connections[user_id]):
|
||||
try:
|
||||
await connection.send_json(message)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
async def broadcast(self, message: dict, channel: str = "all"):
|
||||
async def _deliver_local_broadcast(self, message: dict, channel: str = "all") -> None:
|
||||
if channel == "all":
|
||||
for user_id in self.active_connections:
|
||||
for user_id in list(self.active_connections):
|
||||
await self.send_personal_message(message, user_id)
|
||||
else:
|
||||
for connection in list(self.channel_subscriptions.get(channel, set())):
|
||||
@@ -146,7 +261,14 @@ class ConnectionManager:
|
||||
except Exception:
|
||||
self.unsubscribe_all(connection)
|
||||
|
||||
async def broadcast_vessels(self, data: dict[str, Any]):
|
||||
async def broadcast(self, message: dict, channel: str = "all", *, publish: bool = True):
|
||||
await self._deliver_local_broadcast(message, channel=channel)
|
||||
if publish:
|
||||
await self._publish_pubsub_envelope(
|
||||
{"kind": "channel", "channel": channel, "message": message}
|
||||
)
|
||||
|
||||
async def _deliver_local_vessels(self, data: dict[str, Any]) -> None:
|
||||
vessels = data.get("vessels") if isinstance(data, dict) else None
|
||||
if not isinstance(vessels, list) or not vessels:
|
||||
return
|
||||
@@ -158,7 +280,7 @@ class ConnectionManager:
|
||||
if self._vessel_matches_subscription(vessel, subscription)
|
||||
]
|
||||
if subscription.get("scope") != "global":
|
||||
matched = matched[:subscription["limit"]]
|
||||
matched = matched[: subscription["limit"]]
|
||||
if not matched:
|
||||
continue
|
||||
subscription["last_sent_at"] = datetime.now(UTC)
|
||||
@@ -179,16 +301,25 @@ class ConnectionManager:
|
||||
}
|
||||
try:
|
||||
for offset in range(0, len(matched), MAX_VESSEL_WS_MESSAGE_ITEMS):
|
||||
await connection.send_json({
|
||||
**message,
|
||||
"payload": {
|
||||
**message["payload"],
|
||||
"vessels": matched[offset:offset + MAX_VESSEL_WS_MESSAGE_ITEMS],
|
||||
},
|
||||
})
|
||||
await connection.send_json(
|
||||
{
|
||||
**message,
|
||||
"payload": {
|
||||
**message["payload"],
|
||||
"vessels": matched[offset : offset + MAX_VESSEL_WS_MESSAGE_ITEMS],
|
||||
},
|
||||
}
|
||||
)
|
||||
except Exception:
|
||||
self.unsubscribe_all(connection)
|
||||
|
||||
async def broadcast_vessels(self, data: dict[str, Any]):
|
||||
vessels = data.get("vessels") if isinstance(data, dict) else None
|
||||
if not isinstance(vessels, list) or not vessels:
|
||||
return
|
||||
await self._deliver_local_vessels(data)
|
||||
await self._publish_pubsub_envelope({"kind": "vessels", "data": data})
|
||||
|
||||
def _vessel_matches_subscription(
|
||||
self,
|
||||
vessel: dict[str, Any],
|
||||
@@ -211,9 +342,11 @@ class ConnectionManager:
|
||||
return any(requested_type in type_name for requested_type in requested_types)
|
||||
|
||||
async def close_all(self):
|
||||
for user_id in self.active_connections:
|
||||
for connection in self.active_connections[user_id]:
|
||||
await connection.close()
|
||||
await self.stop_pubsub()
|
||||
for user_id in list(self.active_connections):
|
||||
for connection in list(self.active_connections[user_id]):
|
||||
with suppress(Exception):
|
||||
await connection.close()
|
||||
self.active_connections.clear()
|
||||
self.channel_subscriptions.clear()
|
||||
self.websocket_channels.clear()
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
"""Baseline schema migration matching Base.metadata and init_db DDL."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
VERSION = "0001"
|
||||
NAME = "baseline_schema"
|
||||
|
||||
|
||||
async def upgrade(conn) -> None:
|
||||
"""Create any missing SQLAlchemy baseline tables without altering existing rows."""
|
||||
from app.db.session import Base
|
||||
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
@@ -0,0 +1,18 @@
|
||||
"""Fix earth table update notify trigger so non-id tables (e.g. vessel_current_state) update cleanly."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
VERSION = "0002"
|
||||
NAME = "fix_earth_notify_trigger"
|
||||
|
||||
|
||||
async def upgrade(conn) -> None:
|
||||
"""Replace planet_notify_earth_table_changed_statement without USING (id) on transition tables."""
|
||||
if getattr(getattr(conn, "dialect", None), "name", "") != "postgresql":
|
||||
return
|
||||
|
||||
from app.db.session import PLANET_NOTIFY_EARTH_TABLE_CHANGED_FUNCTION_SQL
|
||||
|
||||
await conn.execute(text(PLANET_NOTIFY_EARTH_TABLE_CHANGED_FUNCTION_SQL))
|
||||
@@ -0,0 +1,23 @@
|
||||
"""Enforce deferred single-mode publish guard on data_snapshots at commit time."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
VERSION = "0003"
|
||||
NAME = "enforce_storage_policy_publish_guard"
|
||||
|
||||
|
||||
async def upgrade(conn) -> None:
|
||||
"""Install deferred storage-policy constraint trigger on PostgreSQL data_snapshots."""
|
||||
if getattr(getattr(conn, "dialect", None), "name", "") != "postgresql":
|
||||
return
|
||||
|
||||
from app.db.session import (
|
||||
PLANET_ENFORCE_STORAGE_POLICY_PUBLISH_FUNCTION_SQL,
|
||||
PLANET_ENFORCE_STORAGE_POLICY_PUBLISH_TRIGGER_STATEMENTS,
|
||||
)
|
||||
|
||||
await conn.execute(text(PLANET_ENFORCE_STORAGE_POLICY_PUBLISH_FUNCTION_SQL))
|
||||
for statement in PLANET_ENFORCE_STORAGE_POLICY_PUBLISH_TRIGGER_STATEMENTS:
|
||||
await conn.execute(text(statement))
|
||||
@@ -0,0 +1 @@
|
||||
"""Versioned database migration steps package."""
|
||||
@@ -0,0 +1,217 @@
|
||||
"""Versioned schema migration tracker and runner for PostgreSQL/SQLite."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, datetime
|
||||
import hashlib
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import re
|
||||
from typing import Any, Awaitable, Callable
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from app.core.logging import get_logger
|
||||
|
||||
logger = get_logger(__name__, service="migrations")
|
||||
|
||||
DEFAULT_STEPS_DIR = Path(__file__).resolve().parent / "migration_steps"
|
||||
MIGRATION_FILE_RE = re.compile(r"^(?P<version>\d{4})_(?P<slug>[a-z0-9_]+)\.py$")
|
||||
MIGRATION_LOCK_KEY = (17001613, 4)
|
||||
|
||||
CREATE_MIGRATIONS_TABLE_SQL = """
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version VARCHAR(64) PRIMARY KEY,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
checksum VARCHAR(64) NOT NULL,
|
||||
applied_at TIMESTAMP WITH TIME ZONE NOT NULL
|
||||
)
|
||||
"""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MigrationStep:
|
||||
version: str
|
||||
name: str
|
||||
checksum: str
|
||||
path: Path
|
||||
upgrade: Callable[[Any], Awaitable[None]]
|
||||
|
||||
|
||||
def discover_migrations(steps_dir: Path | None = None) -> list[MigrationStep]:
|
||||
"""Load ordered migration modules matching NNNN_name.py."""
|
||||
directory = steps_dir or DEFAULT_STEPS_DIR
|
||||
if not directory.exists():
|
||||
return []
|
||||
|
||||
steps: list[MigrationStep] = []
|
||||
for path in sorted(directory.glob("*.py")):
|
||||
match = MIGRATION_FILE_RE.match(path.name)
|
||||
if not match:
|
||||
continue
|
||||
raw_bytes = path.read_bytes()
|
||||
checksum = hashlib.sha256(raw_bytes).hexdigest()
|
||||
module_name = f"planet_migration_{match.group('version')}_{match.group('slug')}"
|
||||
spec = importlib.util.spec_from_file_location(module_name, path)
|
||||
if spec is None or spec.loader is None:
|
||||
raise RuntimeError(f"Could not load migration module: {path}")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
|
||||
version = str(getattr(module, "VERSION", match.group("version")))
|
||||
name = str(getattr(module, "NAME", match.group("slug")))
|
||||
upgrade_fn = getattr(module, "upgrade", None)
|
||||
if not callable(upgrade_fn):
|
||||
raise RuntimeError(f"Migration {path.name} does not define callable upgrade(conn)")
|
||||
steps.append(
|
||||
MigrationStep(
|
||||
version=version,
|
||||
name=name,
|
||||
checksum=checksum,
|
||||
path=path,
|
||||
upgrade=upgrade_fn,
|
||||
)
|
||||
)
|
||||
|
||||
steps.sort(key=lambda item: item.version)
|
||||
return steps
|
||||
|
||||
|
||||
async def ensure_migrations_table(conn: Any) -> None:
|
||||
await conn.execute(text(CREATE_MIGRATIONS_TABLE_SQL))
|
||||
|
||||
|
||||
async def _fetch_applied_map(conn: Any) -> dict[str, tuple[str, str]]:
|
||||
result = await conn.execute(
|
||||
text("SELECT version, name, checksum FROM schema_migrations ORDER BY version")
|
||||
)
|
||||
return {str(row[0]): (str(row[1]), str(row[2])) for row in result.fetchall()}
|
||||
|
||||
|
||||
async def _record_migration(conn: Any, step: MigrationStep) -> None:
|
||||
await conn.execute(
|
||||
text(
|
||||
"INSERT INTO schema_migrations (version, name, checksum, applied_at) "
|
||||
"VALUES (:version, :name, :checksum, :applied_at)"
|
||||
),
|
||||
{
|
||||
"version": step.version,
|
||||
"name": step.name,
|
||||
"checksum": step.checksum,
|
||||
"applied_at": datetime.now(UTC),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
async def ensure_baseline_stamped(conn: Any, steps_dir: Path | None = None) -> bool:
|
||||
"""Ensure schema_migrations exists and stamp baseline 0001 if no version is recorded."""
|
||||
await ensure_migrations_table(conn)
|
||||
applied = await _fetch_applied_map(conn)
|
||||
if applied:
|
||||
return False
|
||||
steps = discover_migrations(steps_dir)
|
||||
if not steps:
|
||||
return False
|
||||
baseline = steps[0]
|
||||
await _record_migration(conn, baseline)
|
||||
return True
|
||||
|
||||
|
||||
async def get_migration_status(engine: Any, steps_dir: Path | None = None) -> dict[str, Any]:
|
||||
"""Return applied versions, pending versions, and checksum mismatches."""
|
||||
steps = discover_migrations(steps_dir)
|
||||
async with engine.begin() as conn:
|
||||
await ensure_migrations_table(conn)
|
||||
applied_map = await _fetch_applied_map(conn)
|
||||
|
||||
mismatches: list[dict[str, str]] = []
|
||||
pending: list[str] = []
|
||||
for step in steps:
|
||||
recorded = applied_map.get(step.version)
|
||||
if recorded is None:
|
||||
pending.append(step.version)
|
||||
elif recorded[1] != step.checksum:
|
||||
mismatches.append(
|
||||
{
|
||||
"version": step.version,
|
||||
"expected": recorded[1],
|
||||
"actual": step.checksum,
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
"applied": sorted(applied_map.keys()),
|
||||
"pending": pending,
|
||||
"mismatches": mismatches,
|
||||
}
|
||||
|
||||
|
||||
async def run_migrations(
|
||||
engine: Any,
|
||||
steps_dir: Path | None = None,
|
||||
*,
|
||||
verify_checksums: bool = True,
|
||||
) -> list[str]:
|
||||
"""Run all pending migrations transactionally under a PostgreSQL advisory lock."""
|
||||
steps = discover_migrations(steps_dir)
|
||||
newly_applied: list[str] = []
|
||||
|
||||
async with engine.begin() as conn:
|
||||
if getattr(conn.dialect, "name", "") == "postgresql":
|
||||
await conn.execute(
|
||||
text("SELECT pg_advisory_xact_lock(:k1, :k2)"),
|
||||
{"k1": MIGRATION_LOCK_KEY[0], "k2": MIGRATION_LOCK_KEY[1]},
|
||||
)
|
||||
await ensure_migrations_table(conn)
|
||||
applied_map = await _fetch_applied_map(conn)
|
||||
|
||||
for step in steps:
|
||||
recorded = applied_map.get(step.version)
|
||||
if recorded is not None:
|
||||
if verify_checksums and recorded[1] != step.checksum:
|
||||
raise RuntimeError(
|
||||
f"Checksum mismatch for already-applied migration {step.version} ({step.name})"
|
||||
)
|
||||
continue
|
||||
|
||||
logger.info_event(
|
||||
"Applying database migration",
|
||||
event="db.migration.applying",
|
||||
context={"version": step.version, "name": step.name},
|
||||
)
|
||||
await step.upgrade(conn)
|
||||
await _record_migration(conn, step)
|
||||
newly_applied.append(step.version)
|
||||
logger.info_event(
|
||||
"Applied database migration",
|
||||
event="db.migration.applied",
|
||||
context={"version": step.version, "name": step.name},
|
||||
)
|
||||
|
||||
return newly_applied
|
||||
|
||||
|
||||
async def stamp_migrations(
|
||||
engine: Any,
|
||||
target_version: str,
|
||||
steps_dir: Path | None = None,
|
||||
) -> list[str]:
|
||||
"""Record migrations up to target_version as applied without executing SQL."""
|
||||
steps = discover_migrations(steps_dir)
|
||||
known_versions = {step.version for step in steps}
|
||||
if target_version not in known_versions:
|
||||
raise ValueError(f"Unknown migration version: {target_version}")
|
||||
|
||||
stamped: list[str] = []
|
||||
async with engine.begin() as conn:
|
||||
await ensure_migrations_table(conn)
|
||||
applied_map = await _fetch_applied_map(conn)
|
||||
for step in steps:
|
||||
if step.version > target_version:
|
||||
break
|
||||
if step.version in applied_map:
|
||||
continue
|
||||
await _record_migration(conn, step)
|
||||
stamped.append(step.version)
|
||||
return stamped
|
||||
+396
-155
@@ -1,3 +1,4 @@
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import AsyncGenerator
|
||||
|
||||
from sqlalchemy import bindparam, text
|
||||
@@ -28,6 +29,240 @@ async_session_factory = async_sessionmaker(engine, class_=AsyncSession, expire_o
|
||||
|
||||
Base = declarative_base()
|
||||
|
||||
PLANET_NOTIFY_EARTH_TABLE_CHANGED_FUNCTION_SQL = """
|
||||
CREATE OR REPLACE FUNCTION planet_notify_earth_table_changed_statement()
|
||||
RETURNS trigger AS $$
|
||||
DECLARE
|
||||
change_source TEXT;
|
||||
source_record_count INTEGER;
|
||||
source_entity_keys TEXT[];
|
||||
BEGIN
|
||||
IF TG_OP = 'INSERT' THEN
|
||||
FOR change_source IN
|
||||
SELECT DISTINCT COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME)
|
||||
FROM (SELECT to_jsonb(t) AS row_data FROM new_rows AS t) changed_rows
|
||||
LOOP
|
||||
SELECT
|
||||
COUNT(*),
|
||||
ARRAY(
|
||||
SELECT DISTINCT COALESCE(
|
||||
NULLIF(row_data->>'entity_key', ''),
|
||||
NULLIF(row_data->>'source_id', ''),
|
||||
NULLIF(row_data->>'incident_key', ''),
|
||||
NULLIF(row_data->>'id', ''),
|
||||
NULLIF(row_data->>'mmsi', '')
|
||||
)
|
||||
FROM (SELECT to_jsonb(t) AS row_data FROM new_rows AS t) rows_for_keys
|
||||
WHERE COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME) = change_source
|
||||
LIMIT 20
|
||||
)
|
||||
INTO source_record_count, source_entity_keys
|
||||
FROM (SELECT to_jsonb(t) AS row_data FROM new_rows AS t) rows_for_count
|
||||
WHERE COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME) = change_source;
|
||||
|
||||
PERFORM planet_emit_earth_data_changed_statement(
|
||||
TG_TABLE_NAME,
|
||||
TG_OP,
|
||||
change_source,
|
||||
source_record_count,
|
||||
source_entity_keys
|
||||
);
|
||||
END LOOP;
|
||||
ELSIF TG_OP = 'DELETE' THEN
|
||||
FOR change_source IN
|
||||
SELECT DISTINCT COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME)
|
||||
FROM (SELECT to_jsonb(t) AS row_data FROM old_rows AS t) changed_rows
|
||||
LOOP
|
||||
SELECT
|
||||
COUNT(*),
|
||||
ARRAY(
|
||||
SELECT DISTINCT COALESCE(
|
||||
NULLIF(row_data->>'entity_key', ''),
|
||||
NULLIF(row_data->>'source_id', ''),
|
||||
NULLIF(row_data->>'incident_key', ''),
|
||||
NULLIF(row_data->>'id', ''),
|
||||
NULLIF(row_data->>'mmsi', '')
|
||||
)
|
||||
FROM (SELECT to_jsonb(t) AS row_data FROM old_rows AS t) rows_for_keys
|
||||
WHERE COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME) = change_source
|
||||
LIMIT 20
|
||||
)
|
||||
INTO source_record_count, source_entity_keys
|
||||
FROM (SELECT to_jsonb(t) AS row_data FROM old_rows AS t) rows_for_count
|
||||
WHERE COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME) = change_source;
|
||||
|
||||
PERFORM planet_emit_earth_data_changed_statement(
|
||||
TG_TABLE_NAME,
|
||||
TG_OP,
|
||||
change_source,
|
||||
source_record_count,
|
||||
source_entity_keys
|
||||
);
|
||||
END LOOP;
|
||||
ELSIF TG_OP = 'UPDATE' THEN
|
||||
IF TG_TABLE_NAME = 'earth_news_items' THEN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM (SELECT to_jsonb(t) AS row_data FROM new_rows AS t) AS current_row
|
||||
FULL JOIN (SELECT to_jsonb(t) AS row_data FROM old_rows AS t) AS previous_row
|
||||
ON current_row.row_data->>'id' = previous_row.row_data->>'id'
|
||||
WHERE (current_row.row_data - 'last_seen_at' - 'updated_at')
|
||||
IS DISTINCT FROM
|
||||
(previous_row.row_data - 'last_seen_at' - 'updated_at')
|
||||
) THEN
|
||||
RETURN NULL;
|
||||
END IF;
|
||||
END IF;
|
||||
FOR change_source IN
|
||||
SELECT DISTINCT COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME)
|
||||
FROM (
|
||||
SELECT to_jsonb(t) AS row_data FROM new_rows AS t
|
||||
UNION ALL
|
||||
SELECT to_jsonb(t) AS row_data FROM old_rows AS t
|
||||
) changed_rows
|
||||
LOOP
|
||||
SELECT
|
||||
COUNT(*),
|
||||
ARRAY(
|
||||
SELECT DISTINCT COALESCE(
|
||||
NULLIF(row_data->>'entity_key', ''),
|
||||
NULLIF(row_data->>'source_id', ''),
|
||||
NULLIF(row_data->>'incident_key', ''),
|
||||
NULLIF(row_data->>'id', ''),
|
||||
NULLIF(row_data->>'mmsi', '')
|
||||
)
|
||||
FROM (
|
||||
SELECT to_jsonb(t) AS row_data FROM new_rows AS t
|
||||
UNION ALL
|
||||
SELECT to_jsonb(t) AS row_data FROM old_rows AS t
|
||||
) rows_for_keys
|
||||
WHERE COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME) = change_source
|
||||
LIMIT 20
|
||||
)
|
||||
INTO source_record_count, source_entity_keys
|
||||
FROM (
|
||||
SELECT to_jsonb(t) AS row_data FROM new_rows AS t
|
||||
UNION ALL
|
||||
SELECT to_jsonb(t) AS row_data FROM old_rows AS t
|
||||
) rows_for_count
|
||||
WHERE COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME) = change_source;
|
||||
|
||||
PERFORM planet_emit_earth_data_changed_statement(
|
||||
TG_TABLE_NAME,
|
||||
TG_OP,
|
||||
change_source,
|
||||
source_record_count,
|
||||
source_entity_keys
|
||||
);
|
||||
END LOOP;
|
||||
END IF;
|
||||
|
||||
RETURN NULL;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
"""
|
||||
|
||||
PLANET_ENFORCE_STORAGE_POLICY_PUBLISH_FUNCTION_SQL = """
|
||||
CREATE OR REPLACE FUNCTION planet_enforce_storage_policy_on_snapshot_publish()
|
||||
RETURNS trigger AS $$
|
||||
DECLARE
|
||||
is_new_publish BOOLEAN := FALSE;
|
||||
still_published BOOLEAN := FALSE;
|
||||
policy_payload JSONB;
|
||||
global_locked BOOLEAN := FALSE;
|
||||
default_mode TEXT := 'single';
|
||||
override_mode TEXT;
|
||||
effective_mode TEXT := 'single';
|
||||
has_other_success BOOLEAN := FALSE;
|
||||
BEGIN
|
||||
IF TG_OP = 'INSERT' THEN
|
||||
is_new_publish := COALESCE(NEW.is_current, FALSE) = TRUE OR NEW.status = 'success';
|
||||
ELSIF TG_OP = 'UPDATE' THEN
|
||||
is_new_publish := (COALESCE(NEW.is_current, FALSE) = TRUE OR NEW.status = 'success')
|
||||
AND COALESCE(OLD.is_current, FALSE) = FALSE
|
||||
AND COALESCE(OLD.status, '') <> 'success';
|
||||
END IF;
|
||||
|
||||
IF NOT is_new_publish THEN
|
||||
RETURN NULL;
|
||||
END IF;
|
||||
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM data_snapshots
|
||||
WHERE id = NEW.id
|
||||
AND (COALESCE(is_current, FALSE) = TRUE OR status = 'success')
|
||||
)
|
||||
INTO still_published;
|
||||
|
||||
IF NOT still_published THEN
|
||||
RETURN NULL;
|
||||
END IF;
|
||||
|
||||
PERFORM pg_advisory_xact_lock_shared(17001614, 2);
|
||||
|
||||
SELECT payload::jsonb
|
||||
INTO policy_payload
|
||||
FROM system_settings
|
||||
WHERE category = 'collection_storage'
|
||||
LIMIT 1
|
||||
FOR SHARE;
|
||||
|
||||
IF policy_payload IS NULL THEN
|
||||
RETURN NULL;
|
||||
END IF;
|
||||
|
||||
global_locked := LOWER(COALESCE(policy_payload->>'global_single_lock', 'false')) IN ('true', '1', 'yes', 'on');
|
||||
IF global_locked THEN
|
||||
effective_mode := 'single';
|
||||
ELSE
|
||||
default_mode := LOWER(COALESCE(NULLIF(policy_payload->>'default_mode', ''), 'single'));
|
||||
override_mode := LOWER(COALESCE(NULLIF((policy_payload->'overrides')->>NEW.source, ''), ''));
|
||||
IF override_mode <> '' THEN
|
||||
effective_mode := override_mode;
|
||||
ELSE
|
||||
effective_mode := default_mode;
|
||||
END IF;
|
||||
END IF;
|
||||
|
||||
IF effective_mode <> 'single' THEN
|
||||
RETURN NULL;
|
||||
END IF;
|
||||
|
||||
IF TG_OP = 'INSERT' AND NOT global_locked AND COALESCE(NEW.is_current, FALSE) <> TRUE THEN
|
||||
RETURN NULL;
|
||||
END IF;
|
||||
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM data_snapshots
|
||||
WHERE source = NEW.source
|
||||
AND id IS DISTINCT FROM NEW.id
|
||||
AND status = 'success'
|
||||
)
|
||||
INTO has_other_success;
|
||||
|
||||
IF has_other_success THEN
|
||||
RAISE EXCEPTION 'planet_storage_policy_single_violation: snapshot % for source % cannot be published while single storage mode is active', NEW.id, NEW.source
|
||||
USING ERRCODE = 'P0001';
|
||||
END IF;
|
||||
|
||||
RETURN NULL;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
"""
|
||||
|
||||
PLANET_ENFORCE_STORAGE_POLICY_PUBLISH_TRIGGER_STATEMENTS = (
|
||||
"DROP TRIGGER IF EXISTS tr_planet_enforce_storage_policy_publish ON data_snapshots",
|
||||
"""
|
||||
CREATE CONSTRAINT TRIGGER tr_planet_enforce_storage_policy_publish
|
||||
AFTER INSERT OR UPDATE ON data_snapshots
|
||||
DEFERRABLE INITIALLY DEFERRED
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION planet_enforce_storage_policy_on_snapshot_publish()
|
||||
""",
|
||||
)
|
||||
|
||||
|
||||
async def get_db() -> AsyncGenerator[AsyncSession, None]:
|
||||
async with async_session_factory() as session:
|
||||
@@ -39,19 +274,32 @@ async def get_db() -> AsyncGenerator[AsyncSession, None]:
|
||||
raise
|
||||
|
||||
|
||||
def _is_postgresql_session(session: AsyncSession | None) -> bool:
|
||||
if session is None or not callable(getattr(session, "get_bind", None)):
|
||||
return False
|
||||
try:
|
||||
bind = session.get_bind()
|
||||
return getattr(getattr(bind, "dialect", None), "name", "") == "postgresql"
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
async def seed_default_datasources(session: AsyncSession):
|
||||
from app.core.datasource_defaults import DEFAULT_DATASOURCES
|
||||
from app.models.datasource import DataSource
|
||||
|
||||
if _is_postgresql_session(session):
|
||||
await session.execute(text("SELECT pg_advisory_xact_lock(17001613, 6)"))
|
||||
|
||||
for source, info in DEFAULT_DATASOURCES.items():
|
||||
existing = await session.get(DataSource, info["id"])
|
||||
if existing:
|
||||
existing.name = info["name"]
|
||||
existing.source = source
|
||||
existing.module = info["module"]
|
||||
existing.priority = info["priority"]
|
||||
existing.frequency_minutes = info["frequency_minutes"]
|
||||
existing.collector_class = source
|
||||
if not existing.source:
|
||||
existing.source = source
|
||||
if not existing.module:
|
||||
existing.module = info["module"]
|
||||
if not existing.collector_class:
|
||||
existing.collector_class = source
|
||||
if existing.config is None:
|
||||
existing.config = "{}"
|
||||
continue
|
||||
@@ -161,24 +409,62 @@ async def ensure_default_admin_user(session: AsyncSession):
|
||||
from app.core.security import get_password_hash
|
||||
from app.models.user import User
|
||||
|
||||
for default_user in DEFAULT_LOGIN_USERS:
|
||||
result = await session.execute(
|
||||
text("SELECT id FROM users WHERE username = :username"),
|
||||
{"username": default_user["username"]},
|
||||
)
|
||||
if result.fetchone():
|
||||
continue
|
||||
if _is_postgresql_session(session):
|
||||
await session.execute(text("SELECT pg_advisory_xact_lock(17001613, 5)"))
|
||||
|
||||
session.add(
|
||||
User(
|
||||
username=default_user["username"],
|
||||
email=default_user["email"],
|
||||
password_hash=get_password_hash(default_user["password"]),
|
||||
role=default_user["role"],
|
||||
is_active=True,
|
||||
email_verified=True,
|
||||
custom_username = str(settings.INITIAL_ADMIN_USERNAME or "").strip()
|
||||
custom_password = str(settings.INITIAL_ADMIN_PASSWORD or "").strip()
|
||||
custom_email = str(settings.INITIAL_ADMIN_EMAIL or "").strip() or (
|
||||
f"{custom_username}@planet.local" if custom_username else ""
|
||||
)
|
||||
|
||||
if custom_username and custom_password:
|
||||
existing_custom = (
|
||||
await session.execute(
|
||||
text("SELECT id FROM users WHERE username = :username"),
|
||||
{"username": custom_username},
|
||||
)
|
||||
)
|
||||
).fetchone()
|
||||
if existing_custom is None:
|
||||
session.add(
|
||||
User(
|
||||
username=custom_username,
|
||||
email=custom_email,
|
||||
password_hash=get_password_hash(custom_password),
|
||||
role="super_admin",
|
||||
is_active=True,
|
||||
email_verified=True,
|
||||
)
|
||||
)
|
||||
await session.flush()
|
||||
|
||||
if settings.should_seed_default_dev_users:
|
||||
for default_user in DEFAULT_LOGIN_USERS:
|
||||
result = await session.execute(
|
||||
text("SELECT id FROM users WHERE username = :username"),
|
||||
{"username": default_user["username"]},
|
||||
)
|
||||
if result.fetchone():
|
||||
continue
|
||||
|
||||
session.add(
|
||||
User(
|
||||
username=default_user["username"],
|
||||
email=default_user["email"],
|
||||
password_hash=get_password_hash(default_user["password"]),
|
||||
role=default_user["role"],
|
||||
is_active=True,
|
||||
email_verified=True,
|
||||
)
|
||||
)
|
||||
else:
|
||||
user_count = (await session.execute(text("SELECT COUNT(*) FROM users"))).scalar() or 0
|
||||
if int(user_count) == 0:
|
||||
logger.warning_event(
|
||||
"No users exist and default dev accounts are disabled in production; configure INITIAL_ADMIN_USERNAME and INITIAL_ADMIN_PASSWORD",
|
||||
event="auth.bootstrap.no_users",
|
||||
)
|
||||
|
||||
await session.commit()
|
||||
|
||||
|
||||
@@ -219,6 +505,34 @@ async def init_db():
|
||||
},
|
||||
)
|
||||
|
||||
async with _init_db_advisory_lock():
|
||||
await _init_db_ddl_and_seed()
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def _init_db_advisory_lock():
|
||||
"""Serialize full DDL + seed startup across concurrent PostgreSQL replicas."""
|
||||
if getattr(getattr(engine, "dialect", None), "name", "") != "postgresql":
|
||||
yield
|
||||
return
|
||||
|
||||
async with engine.connect() as base_conn:
|
||||
lock_conn = await base_conn.execution_options(isolation_level="AUTOCOMMIT")
|
||||
await lock_conn.execute(text("SELECT pg_advisory_lock(17001613, 4)"))
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
try:
|
||||
await lock_conn.execute(text("SELECT pg_advisory_unlock(17001613, 4)"))
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed to release init_db advisory lock cleanly",
|
||||
event="database.init_db.unlock_failed",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
|
||||
|
||||
async def _init_db_ddl_and_seed():
|
||||
async with engine.begin() as conn:
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
await install_bgp_prefix_geo_functions(conn)
|
||||
@@ -258,6 +572,7 @@ async def init_db():
|
||||
ADD COLUMN IF NOT EXISTS previous_record_id INTEGER,
|
||||
ADD COLUMN IF NOT EXISTS change_type VARCHAR(20),
|
||||
ADD COLUMN IF NOT EXISTS change_summary JSONB DEFAULT '{}'::jsonb,
|
||||
ADD COLUMN IF NOT EXISTS content_hash VARCHAR(64),
|
||||
ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ
|
||||
"""
|
||||
)
|
||||
@@ -367,139 +682,7 @@ async def init_db():
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE OR REPLACE FUNCTION planet_notify_earth_table_changed_statement()
|
||||
RETURNS trigger AS $$
|
||||
DECLARE
|
||||
change_source TEXT;
|
||||
source_record_count INTEGER;
|
||||
source_entity_keys TEXT[];
|
||||
BEGIN
|
||||
IF TG_OP = 'INSERT' THEN
|
||||
FOR change_source IN
|
||||
SELECT DISTINCT COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME)
|
||||
FROM (SELECT to_jsonb(t) AS row_data FROM new_rows AS t) changed_rows
|
||||
LOOP
|
||||
SELECT
|
||||
COUNT(*),
|
||||
ARRAY(
|
||||
SELECT DISTINCT COALESCE(
|
||||
NULLIF(row_data->>'entity_key', ''),
|
||||
NULLIF(row_data->>'source_id', ''),
|
||||
NULLIF(row_data->>'incident_key', ''),
|
||||
NULLIF(row_data->>'id', ''),
|
||||
NULLIF(row_data->>'mmsi', '')
|
||||
)
|
||||
FROM (SELECT to_jsonb(t) AS row_data FROM new_rows AS t) rows_for_keys
|
||||
WHERE COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME) = change_source
|
||||
LIMIT 20
|
||||
)
|
||||
INTO source_record_count, source_entity_keys
|
||||
FROM (SELECT to_jsonb(t) AS row_data FROM new_rows AS t) rows_for_count
|
||||
WHERE COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME) = change_source;
|
||||
|
||||
PERFORM planet_emit_earth_data_changed_statement(
|
||||
TG_TABLE_NAME,
|
||||
TG_OP,
|
||||
change_source,
|
||||
source_record_count,
|
||||
source_entity_keys
|
||||
);
|
||||
END LOOP;
|
||||
ELSIF TG_OP = 'DELETE' THEN
|
||||
FOR change_source IN
|
||||
SELECT DISTINCT COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME)
|
||||
FROM (SELECT to_jsonb(t) AS row_data FROM old_rows AS t) changed_rows
|
||||
LOOP
|
||||
SELECT
|
||||
COUNT(*),
|
||||
ARRAY(
|
||||
SELECT DISTINCT COALESCE(
|
||||
NULLIF(row_data->>'entity_key', ''),
|
||||
NULLIF(row_data->>'source_id', ''),
|
||||
NULLIF(row_data->>'incident_key', ''),
|
||||
NULLIF(row_data->>'id', ''),
|
||||
NULLIF(row_data->>'mmsi', '')
|
||||
)
|
||||
FROM (SELECT to_jsonb(t) AS row_data FROM old_rows AS t) rows_for_keys
|
||||
WHERE COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME) = change_source
|
||||
LIMIT 20
|
||||
)
|
||||
INTO source_record_count, source_entity_keys
|
||||
FROM (SELECT to_jsonb(t) AS row_data FROM old_rows AS t) rows_for_count
|
||||
WHERE COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME) = change_source;
|
||||
|
||||
PERFORM planet_emit_earth_data_changed_statement(
|
||||
TG_TABLE_NAME,
|
||||
TG_OP,
|
||||
change_source,
|
||||
source_record_count,
|
||||
source_entity_keys
|
||||
);
|
||||
END LOOP;
|
||||
ELSIF TG_OP = 'UPDATE' THEN
|
||||
IF TG_TABLE_NAME = 'earth_news_items' AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM new_rows AS current_row
|
||||
FULL JOIN old_rows AS previous_row USING (id)
|
||||
WHERE (to_jsonb(current_row) - 'last_seen_at' - 'updated_at')
|
||||
IS DISTINCT FROM
|
||||
(to_jsonb(previous_row) - 'last_seen_at' - 'updated_at')
|
||||
) THEN
|
||||
RETURN NULL;
|
||||
END IF;
|
||||
FOR change_source IN
|
||||
SELECT DISTINCT COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME)
|
||||
FROM (
|
||||
SELECT to_jsonb(t) AS row_data FROM new_rows AS t
|
||||
UNION ALL
|
||||
SELECT to_jsonb(t) AS row_data FROM old_rows AS t
|
||||
) changed_rows
|
||||
LOOP
|
||||
SELECT
|
||||
COUNT(*),
|
||||
ARRAY(
|
||||
SELECT DISTINCT COALESCE(
|
||||
NULLIF(row_data->>'entity_key', ''),
|
||||
NULLIF(row_data->>'source_id', ''),
|
||||
NULLIF(row_data->>'incident_key', ''),
|
||||
NULLIF(row_data->>'id', ''),
|
||||
NULLIF(row_data->>'mmsi', '')
|
||||
)
|
||||
FROM (
|
||||
SELECT to_jsonb(t) AS row_data FROM new_rows AS t
|
||||
UNION ALL
|
||||
SELECT to_jsonb(t) AS row_data FROM old_rows AS t
|
||||
) rows_for_keys
|
||||
WHERE COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME) = change_source
|
||||
LIMIT 20
|
||||
)
|
||||
INTO source_record_count, source_entity_keys
|
||||
FROM (
|
||||
SELECT to_jsonb(t) AS row_data FROM new_rows AS t
|
||||
UNION ALL
|
||||
SELECT to_jsonb(t) AS row_data FROM old_rows AS t
|
||||
) rows_for_count
|
||||
WHERE COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME) = change_source;
|
||||
|
||||
PERFORM planet_emit_earth_data_changed_statement(
|
||||
TG_TABLE_NAME,
|
||||
TG_OP,
|
||||
change_source,
|
||||
source_record_count,
|
||||
source_entity_keys
|
||||
);
|
||||
END LOOP;
|
||||
END IF;
|
||||
|
||||
RETURN NULL;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(text(PLANET_NOTIFY_EARTH_TABLE_CHANGED_FUNCTION_SQL))
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
@@ -677,6 +860,10 @@ async def init_db():
|
||||
"DROP TRIGGER IF EXISTS tr_planet_situational_assessments_changed_delete ON situational_assessments",
|
||||
):
|
||||
await conn.execute(text(drop_stmt))
|
||||
if conn.dialect.name == "postgresql":
|
||||
await conn.execute(text(PLANET_ENFORCE_STORAGE_POLICY_PUBLISH_FUNCTION_SQL))
|
||||
for stmt in PLANET_ENFORCE_STORAGE_POLICY_PUBLISH_TRIGGER_STATEMENTS:
|
||||
await conn.execute(text(stmt))
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
@@ -866,6 +1053,58 @@ async def init_db():
|
||||
"""
|
||||
)
|
||||
)
|
||||
duplicate_current_exists = (
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
SELECT 1
|
||||
FROM collected_data
|
||||
WHERE COALESCE(is_current, TRUE) = TRUE
|
||||
AND deleted_at IS NULL
|
||||
AND entity_key IS NOT NULL
|
||||
GROUP BY source, entity_key
|
||||
HAVING COUNT(*) > 1
|
||||
LIMIT 1
|
||||
"""
|
||||
)
|
||||
)
|
||||
).fetchone() is not None
|
||||
if duplicate_current_exists:
|
||||
# Demote older duplicate is_current rows safely; never delete existing dev history.
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
WITH ranked AS (
|
||||
SELECT id,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY source, entity_key
|
||||
ORDER BY collected_at DESC NULLS LAST, id DESC
|
||||
) AS rn
|
||||
FROM collected_data
|
||||
WHERE COALESCE(is_current, TRUE) = TRUE
|
||||
AND deleted_at IS NULL
|
||||
AND entity_key IS NOT NULL
|
||||
)
|
||||
UPDATE collected_data
|
||||
SET is_current = FALSE
|
||||
WHERE id IN (SELECT id FROM ranked WHERE rn > 1)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_collected_data_current_entity
|
||||
ON collected_data (source, entity_key)
|
||||
WHERE COALESCE(is_current, TRUE) = TRUE
|
||||
AND deleted_at IS NULL
|
||||
AND entity_key IS NOT NULL
|
||||
"""
|
||||
)
|
||||
)
|
||||
from app.db.migrations import ensure_baseline_stamped
|
||||
|
||||
await ensure_baseline_stamped(conn)
|
||||
|
||||
async with async_session_factory() as session:
|
||||
from app.services.bgp_collector_locations import (
|
||||
@@ -874,9 +1113,11 @@ async def init_db():
|
||||
from app.services.compute_center_locations import (
|
||||
seed_compute_center_locations_from_source_coords,
|
||||
)
|
||||
from app.services.storage_policy import ensure_default_storage_policy
|
||||
|
||||
await seed_default_bgp_collector_locations(session)
|
||||
await seed_compute_center_locations_from_source_coords(session)
|
||||
await seed_default_datasources(session)
|
||||
await purge_legacy_earth_boundary_datasources(session)
|
||||
await ensure_default_admin_user(session)
|
||||
await ensure_default_storage_policy(session)
|
||||
+188
-32
@@ -1,44 +1,58 @@
|
||||
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.middleware.gzip import GZipMiddleware
|
||||
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 +73,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 +186,31 @@ app = FastAPI(
|
||||
openapi_url="/openapi.json",
|
||||
)
|
||||
|
||||
class NonStreamingGZipMiddleware:
|
||||
"""Apply GZip compression while skipping SSE streaming responses so events flush immediately."""
|
||||
|
||||
def __init__(self, app, minimum_size: int = 1024) -> None:
|
||||
self.app = app
|
||||
self.gzip_app = GZipMiddleware(app, minimum_size=minimum_size)
|
||||
|
||||
async def __call__(self, scope, receive, send) -> None:
|
||||
if scope.get("type") == "http":
|
||||
path = str(scope.get("path") or "")
|
||||
headers = dict(scope.get("headers") or [])
|
||||
accept = headers.get(b"accept", b"").lower()
|
||||
if path.endswith("/stream") or b"text/event-stream" in accept:
|
||||
await self.app(scope, receive, send)
|
||||
return
|
||||
await self.gzip_app(scope, receive, send)
|
||||
|
||||
|
||||
app.add_middleware(NonStreamingGZipMiddleware, minimum_size=1024)
|
||||
|
||||
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 +235,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 +280,7 @@ async def root():
|
||||
|
||||
|
||||
@app.get("/api/v1/scheduler/jobs")
|
||||
async def get_scheduler_jobs():
|
||||
async def get_scheduler_jobs(_current_user: User = Depends(get_current_user)):
|
||||
from app.services.scheduler import get_scheduler_jobs
|
||||
|
||||
return {"jobs": get_scheduler_jobs()}
|
||||
return {"jobs": get_scheduler_jobs()}
|
||||
@@ -43,6 +43,7 @@ class CollectedData(Base):
|
||||
previous_record_id = Column(Integer, ForeignKey("collected_data.id"), nullable=True, index=True)
|
||||
change_type = Column(String(20), nullable=True)
|
||||
change_summary = Column(JSON, default={})
|
||||
content_hash = Column(String(64), nullable=True)
|
||||
deleted_at = Column(DateTime(timezone=True), nullable=True)
|
||||
|
||||
# Indexes for common queries
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
from typing import Any
|
||||
from typing import Any, Literal
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.core.enums import PlaygroundMessageKind, PlaygroundMessageRole, PlaygroundMessageStatus
|
||||
|
||||
|
||||
class ChatMessage(BaseModel):
|
||||
role: Literal["user", "assistant"]
|
||||
content: str = Field(..., min_length=1, max_length=12000)
|
||||
|
||||
|
||||
class AIContentBlock(BaseModel):
|
||||
type: str
|
||||
text: str | None = None
|
||||
@@ -21,6 +27,7 @@ class SituationalAnalysisRequest(BaseModel):
|
||||
system_prompt: str | None = Field(default=None, max_length=8000)
|
||||
preferred_model: str | None = Field(default=None, max_length=200)
|
||||
thinking: dict[str, Any] | None = None
|
||||
messages: list[ChatMessage] = Field(default_factory=list, max_length=32)
|
||||
|
||||
|
||||
class BGPBriefRequest(BaseModel):
|
||||
|
||||
@@ -8,6 +8,7 @@ class Token(BaseModel):
|
||||
access_token: str
|
||||
token_type: str = "bearer"
|
||||
expires_in: Optional[int] = None
|
||||
refresh_token: Optional[str] = None
|
||||
user: dict
|
||||
|
||||
|
||||
|
||||
@@ -19,7 +19,13 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.enums import UserRole
|
||||
from app.core.logging import get_logger
|
||||
from app.core.security import _load_active_user, decode_token, get_current_user, redis_client
|
||||
from app.core.security import (
|
||||
_load_active_user,
|
||||
decode_token,
|
||||
get_current_user,
|
||||
is_token_blacklisted,
|
||||
redis_client,
|
||||
)
|
||||
from app.db.session import get_db
|
||||
from app.models.situational_assessment import WorkflowRun
|
||||
from app.models.system_setting import SystemSetting
|
||||
@@ -130,17 +136,11 @@ async def _try_load_bearer_user(
|
||||
if credentials is None or not credentials.credentials:
|
||||
return None
|
||||
token = credentials.credentials
|
||||
try:
|
||||
if redis_client.sismember("blacklisted_tokens", token):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Token has been revoked",
|
||||
)
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception:
|
||||
# Redis offline in unit tests should not block valid JWT verification
|
||||
pass
|
||||
if await is_token_blacklisted(token, legacy_sync_client=redis_client):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Token has been revoked",
|
||||
)
|
||||
|
||||
payload = decode_token(token)
|
||||
if payload is None or payload.get("type") != "access" or payload.get("sub") is None:
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
"""Multi-turn conversation sanitization, rolling compaction, and lightweight memory formatting."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from typing import Any
|
||||
|
||||
from app.core.logging import get_logger
|
||||
from app.schemas.ai import SituationalAnalysisRequest
|
||||
from app.services.ai.thinking_sanitizer import prepare_situational_ai_call, strip_thinking_text
|
||||
from app.services.ai_client import AIProviderClient
|
||||
|
||||
logger = get_logger(__name__, service="ai_memory")
|
||||
|
||||
RECENT_WINDOW_TURNS = 4
|
||||
COMPACT_TRIGGER_CHARS = 7500
|
||||
MAX_MESSAGE_CHARS = 1800
|
||||
MAX_SUMMARY_CHARS = 1600
|
||||
MAX_MEMORY_NOTES = 12
|
||||
MAX_PINNED_SUMMARIES = 8
|
||||
|
||||
|
||||
def _truncate_text(text: str, limit: int) -> str:
|
||||
cleaned = str(text or "").strip()
|
||||
if len(cleaned) <= limit:
|
||||
return cleaned
|
||||
return f"{cleaned[: max(0, limit - 1)].rstrip()}…"
|
||||
|
||||
|
||||
def sanitize_history_messages(raw_messages: list[Any] | None) -> list[dict[str, str]]:
|
||||
"""Strip inline thinking blocks, truncate extremes, and normalize alternating user/assistant turns."""
|
||||
normalized: list[dict[str, str]] = []
|
||||
for item in raw_messages or []:
|
||||
if isinstance(item, dict):
|
||||
role = str(item.get("role") or "").strip().lower()
|
||||
raw_content = item.get("content")
|
||||
else:
|
||||
role = str(getattr(item, "role", "") or "").strip().lower()
|
||||
raw_content = getattr(item, "content", "")
|
||||
if role not in {"user", "assistant"}:
|
||||
continue
|
||||
content = str(raw_content or "").strip()
|
||||
if not content:
|
||||
continue
|
||||
if role == "assistant":
|
||||
clean_content, _ = strip_thinking_text(content)
|
||||
content = clean_content or content
|
||||
content = _truncate_text(content, MAX_MESSAGE_CHARS)
|
||||
if not content:
|
||||
continue
|
||||
if not normalized and role == "assistant":
|
||||
continue
|
||||
if normalized and normalized[-1]["role"] == role:
|
||||
merged = f"{normalized[-1]['content']}\n\n{content}"
|
||||
normalized[-1]["content"] = _truncate_text(merged, MAX_MESSAGE_CHARS)
|
||||
else:
|
||||
normalized.append({"role": role, "content": content})
|
||||
return normalized
|
||||
|
||||
|
||||
def _sanitize_short_list(items: list[Any] | None, *, max_items: int, max_chars: int = 200) -> list[str]:
|
||||
result: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for raw in items or []:
|
||||
text = _truncate_text(str(raw or "").replace("\r", " ").replace("\n", " "), max_chars)
|
||||
if not text or text in seen:
|
||||
continue
|
||||
seen.add(text)
|
||||
result.append(text)
|
||||
if len(result) >= max_items:
|
||||
break
|
||||
return result
|
||||
|
||||
|
||||
def sanitize_memory_notes(notes: list[Any] | None) -> list[str]:
|
||||
"""Return deduplicated short user memory notes within configured cap."""
|
||||
return _sanitize_short_list(notes, max_items=MAX_MEMORY_NOTES)
|
||||
|
||||
|
||||
def sanitize_pinned_summaries(items: list[Any] | None) -> list[str]:
|
||||
"""Return deduplicated short pinned comparison summaries within configured cap."""
|
||||
return _sanitize_short_list(items, max_items=MAX_PINNED_SUMMARIES)
|
||||
|
||||
|
||||
def build_deterministic_compaction_summary(
|
||||
existing_summary: str,
|
||||
dropped_messages: list[dict[str, str]],
|
||||
) -> str:
|
||||
"""Build a bounded structured summary when older turns overflow the active window."""
|
||||
lines: list[str] = []
|
||||
prior = str(existing_summary or "").strip()
|
||||
if prior:
|
||||
lines.append(prior)
|
||||
|
||||
pair_lines: list[str] = []
|
||||
idx = 0
|
||||
while idx < len(dropped_messages):
|
||||
msg = dropped_messages[idx]
|
||||
if msg["role"] == "user":
|
||||
q = _truncate_text(msg["content"].replace("\n", " "), 120)
|
||||
a = ""
|
||||
if idx + 1 < len(dropped_messages) and dropped_messages[idx + 1]["role"] == "assistant":
|
||||
a = _truncate_text(dropped_messages[idx + 1]["content"].replace("\n", " "), 180)
|
||||
idx += 2
|
||||
else:
|
||||
idx += 1
|
||||
pair_lines.append(f"- 问:{q}" + (f" → 结:{a}" if a else ""))
|
||||
else:
|
||||
a = _truncate_text(msg["content"].replace("\n", " "), 160)
|
||||
pair_lines.append(f"- 历史结论:{a}")
|
||||
idx += 1
|
||||
|
||||
if pair_lines:
|
||||
block = "\n".join(pair_lines)
|
||||
if prior and not prior.startswith("### 前序对话摘要"):
|
||||
lines = [f"### 前序对话摘要\n{prior}", block]
|
||||
elif prior:
|
||||
lines = [prior, block]
|
||||
else:
|
||||
lines = [f"### 前序对话摘要\n{block}"]
|
||||
|
||||
combined = "\n".join(lines).strip()
|
||||
if len(combined) > MAX_SUMMARY_CHARS:
|
||||
head = "### 前序对话摘要\n"
|
||||
tail_budget = MAX_SUMMARY_CHARS - len(head) - 2
|
||||
combined = f"{head}…{combined[-tail_budget:].lstrip()}"
|
||||
return combined
|
||||
|
||||
|
||||
async def compact_conversation_history(
|
||||
raw_messages: list[Any] | None,
|
||||
existing_summary: str = "",
|
||||
*,
|
||||
ai_client: AIProviderClient | None = None,
|
||||
ai_ready: bool = False,
|
||||
recent_window_turns: int = RECENT_WINDOW_TURNS,
|
||||
char_budget: int = COMPACT_TRIGGER_CHARS,
|
||||
) -> dict[str, Any]:
|
||||
"""Keep recent window verbatim and compact overflow turns into a rolling summary."""
|
||||
sanitized = sanitize_history_messages(raw_messages)
|
||||
summary = _truncate_text(existing_summary or "", MAX_SUMMARY_CHARS)
|
||||
|
||||
keep_limit = max(2, recent_window_turns * 2)
|
||||
split_idx = max(0, len(sanitized) - keep_limit)
|
||||
if split_idx < len(sanitized) and sanitized[split_idx]["role"] == "assistant":
|
||||
split_idx += 1
|
||||
|
||||
older = sanitized[:split_idx]
|
||||
recent = sanitized[split_idx:]
|
||||
|
||||
total_chars = len(summary) + sum(len(m["content"]) for m in recent)
|
||||
while not older and total_chars > char_budget and len(recent) > 2:
|
||||
move_count = 2 if (len(recent) >= 4 and recent[0]["role"] == "user" and recent[1]["role"] == "assistant") else 1
|
||||
older.extend(recent[:move_count])
|
||||
recent = recent[move_count:]
|
||||
total_chars = len(summary) + sum(len(m["content"]) for m in recent)
|
||||
|
||||
if not older:
|
||||
return {
|
||||
"summary": summary,
|
||||
"recent_messages": recent,
|
||||
"compacted": False,
|
||||
"compacted_count": 0,
|
||||
}
|
||||
|
||||
next_summary = ""
|
||||
if ai_ready and ai_client is not None:
|
||||
try:
|
||||
effective_client = ai_client
|
||||
if type(ai_client) is AIProviderClient and ai_client.llm_config:
|
||||
effective_client, _ = prepare_situational_ai_call(ai_client, min_max_tokens=900)
|
||||
transcript = "\n".join(
|
||||
f"{'用户' if m['role'] == 'user' else 'AI 参谋'}: {m['content']}" for m in older
|
||||
)
|
||||
compact_req = SituationalAnalysisRequest(
|
||||
title="Planet 多轮对话上下文压缩摘要",
|
||||
objective=(
|
||||
"请将以下较早的多轮对话与既有摘要压缩为简明中文备忘(不超过 280 字),"
|
||||
"保留:1) 用户聚焦的图层/国家/新闻实体与口径边界;2) 已核验关键数据结论;"
|
||||
"3) 尚未完结的追问线索。严禁保留客套或编造数值。"
|
||||
),
|
||||
system_prompt="你是精准的对话上下文压缩器,只输出精炼中文要点摘要。",
|
||||
context={
|
||||
"existing_summary": summary or None,
|
||||
"archived_dialogue": transcript,
|
||||
},
|
||||
thinking=None,
|
||||
)
|
||||
resp = await asyncio.wait_for(effective_client.analyze(compact_req), timeout=12.0)
|
||||
clean_resp, _ = strip_thinking_text(str(getattr(resp, "content", "") or ""))
|
||||
next_summary = _truncate_text(clean_resp, MAX_SUMMARY_CHARS)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"LLM conversation compaction fell back to deterministic summary",
|
||||
event="ai_memory.compaction.fallback",
|
||||
context={"error": str(exc), "older_count": len(older)},
|
||||
)
|
||||
|
||||
if not next_summary:
|
||||
next_summary = build_deterministic_compaction_summary(summary, older)
|
||||
|
||||
return {
|
||||
"summary": next_summary,
|
||||
"recent_messages": recent,
|
||||
"compacted": True,
|
||||
"compacted_count": len(older),
|
||||
}
|
||||
@@ -4,7 +4,7 @@ from __future__ import annotations
|
||||
|
||||
from typing import Literal
|
||||
|
||||
WorkbenchDomain = Literal["global", "compute", "bgp", "cable", "satellite", "vessel"]
|
||||
WorkbenchDomain = Literal["global", "compute", "bgp", "cable", "satellite", "vessel", "news"]
|
||||
SpatialDomain = Literal["global", "cable", "satellite", "vessel"]
|
||||
ReportSubjectType = Literal[
|
||||
"global_posture",
|
||||
@@ -13,11 +13,12 @@ ReportSubjectType = Literal[
|
||||
"cable_posture",
|
||||
"satellite_posture",
|
||||
"vessel_posture",
|
||||
"news_brief",
|
||||
]
|
||||
|
||||
SPATIAL_POSTURE_DOMAINS: frozenset[str] = frozenset({"global", "cable", "satellite", "vessel"})
|
||||
SUPPORTED_WORKBENCH_DOMAINS: frozenset[str] = frozenset(
|
||||
{"global", "compute", "bgp", "cable", "satellite", "vessel"}
|
||||
{"global", "compute", "bgp", "cable", "satellite", "vessel", "news"}
|
||||
)
|
||||
|
||||
DOMAIN_TO_SUBJECT_TYPE: dict[str, ReportSubjectType] = {
|
||||
@@ -27,6 +28,7 @@ DOMAIN_TO_SUBJECT_TYPE: dict[str, ReportSubjectType] = {
|
||||
"cable": "cable_posture",
|
||||
"satellite": "satellite_posture",
|
||||
"vessel": "vessel_posture",
|
||||
"news": "news_brief",
|
||||
}
|
||||
|
||||
SUBJECT_TYPE_TO_DOMAIN: dict[str, WorkbenchDomain] = {
|
||||
@@ -36,6 +38,7 @@ SUBJECT_TYPE_TO_DOMAIN: dict[str, WorkbenchDomain] = {
|
||||
"cable_posture": "cable",
|
||||
"satellite_posture": "satellite",
|
||||
"vessel_posture": "vessel",
|
||||
"news_brief": "news",
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -520,7 +520,7 @@ async def investigate_spatial_domain(
|
||||
timeout=35.0,
|
||||
)
|
||||
_raise_if_cancelled(cancel_event)
|
||||
raw_text = (llm_resp.answer or "").strip()
|
||||
raw_text = (llm_resp.content or "").strip()
|
||||
assert_no_thinking_leak(raw_text)
|
||||
parsed = extract_json_object(raw_text)
|
||||
if not isinstance(parsed, dict):
|
||||
|
||||
@@ -0,0 +1,613 @@
|
||||
"""Adaptive SSE streaming turn orchestrator with thinking process, model attribution, and news context."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections import defaultdict, deque
|
||||
from collections.abc import AsyncIterator
|
||||
from datetime import UTC, datetime, timedelta
|
||||
import json
|
||||
import os
|
||||
from typing import Any
|
||||
import uuid
|
||||
|
||||
from fastapi import HTTPException, Request, status
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.logging import get_logger
|
||||
from app.models.situational_assessment import InvestigationSession
|
||||
from app.schemas.ai import ChatMessage, SituationalAnalysisRequest
|
||||
from app.services.ai.access_policy import AccessContext
|
||||
from app.services.ai.conversation_memory import (
|
||||
compact_conversation_history,
|
||||
sanitize_memory_notes,
|
||||
sanitize_pinned_summaries,
|
||||
)
|
||||
from app.services.ai.thinking_sanitizer import prepare_situational_ai_call, strip_thinking_text
|
||||
from app.services.ai.tool_registry import (
|
||||
TimeBasis,
|
||||
query_global_situational_tool,
|
||||
query_recent_earth_news_tool,
|
||||
)
|
||||
from app.services.ai.workflow_runtime import classify_turn_intent, execute_session_turn
|
||||
from app.services.ai_client import AIProviderClient
|
||||
|
||||
logger = get_logger(__name__, service="ai_stream")
|
||||
|
||||
_STREAM_QUOTA_WINDOW: dict[str, deque[datetime]] = defaultdict(deque)
|
||||
_GEOPOLITICAL_OR_NEWS_KEYWORDS = (
|
||||
"国际局势",
|
||||
"全球局势",
|
||||
"地缘",
|
||||
"新闻",
|
||||
"报道",
|
||||
"外交",
|
||||
"冲突",
|
||||
"制裁",
|
||||
"关税",
|
||||
"战争",
|
||||
"和平",
|
||||
"热点",
|
||||
"geopolit",
|
||||
"headline",
|
||||
"news",
|
||||
"international situation",
|
||||
"world situation",
|
||||
)
|
||||
|
||||
|
||||
def reset_stream_quota_ledger() -> None:
|
||||
"""Reset in-memory public stream rate limiter state (for deterministic tests)."""
|
||||
_STREAM_QUOTA_WINDOW.clear()
|
||||
|
||||
|
||||
def check_stream_quota(access: AccessContext) -> None:
|
||||
"""Enforce bounded hourly quota on adaptive streaming AI turns across all access tiers."""
|
||||
default_public_cap = int(os.getenv("PLANET_PUBLIC_AI_STREAM_HOURLY_QUOTA", "60"))
|
||||
limit = access.hourly_paid_quota if access.hourly_paid_quota > 0 else default_public_cap
|
||||
if limit <= 0:
|
||||
return
|
||||
|
||||
now = datetime.now(UTC)
|
||||
window_start = now - timedelta(hours=1)
|
||||
dq = _STREAM_QUOTA_WINDOW[access.actor_key]
|
||||
while dq and dq[0] < window_start:
|
||||
dq.popleft()
|
||||
if len(dq) >= limit:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
detail=f"Hourly AI stream quota ({limit}) exceeded.",
|
||||
)
|
||||
dq.append(now)
|
||||
|
||||
|
||||
def build_streaming_thinking_config(ai_client: AIProviderClient) -> dict[str, Any] | None:
|
||||
"""Enable streamed reasoning tokens for MiniMax/Anthropic providers when streaming turns."""
|
||||
llm_cfg = getattr(ai_client, "llm_config", None) or {}
|
||||
provider = str(llm_cfg.get("provider") or "").strip().lower()
|
||||
provider_api = str(llm_cfg.get("provider_api") or "").strip().lower()
|
||||
model = str(llm_cfg.get("model") or "").strip().lower()
|
||||
|
||||
if "minimax-m3" in model:
|
||||
return {"type": "adaptive", "effort": "medium"}
|
||||
if provider == "minimax" or provider_api == "anthropic-messages" or "anthropic" in provider or "claude" in model:
|
||||
return {"type": "enabled", "budget_tokens": 2048}
|
||||
return None
|
||||
|
||||
|
||||
def _is_geopolitical_or_news_question(
|
||||
question: str,
|
||||
*,
|
||||
domain: str,
|
||||
news_context: dict[str, Any] | None,
|
||||
) -> bool:
|
||||
if domain == "news" or news_context:
|
||||
return True
|
||||
q = (question or "").strip().lower()
|
||||
return any(kw in q for kw in _GEOPOLITICAL_OR_NEWS_KEYWORDS)
|
||||
|
||||
|
||||
def _format_sse(event: str, payload: dict[str, Any]) -> str:
|
||||
return f"event: {event}\ndata: {json.dumps(payload, ensure_ascii=False, default=str)}\n\n"
|
||||
|
||||
|
||||
def _build_news_fallback_markdown(
|
||||
*,
|
||||
question: str,
|
||||
news_context: dict[str, Any] | None,
|
||||
recent_news: dict[str, Any],
|
||||
ai_configured: bool,
|
||||
fallback_reason: str | None = None,
|
||||
) -> str:
|
||||
lines: list[str] = []
|
||||
if news_context:
|
||||
title = str(news_context.get("title") or "新闻速递").strip()
|
||||
source = str(news_context.get("source") or "").strip()
|
||||
region = str(news_context.get("region") or news_context.get("region_key") or "").strip()
|
||||
published_at = str(news_context.get("published_at") or "").strip()
|
||||
summary = str(news_context.get("summary") or "").strip()
|
||||
lines.append(f"### 新闻焦点:{title}")
|
||||
meta_parts = [p for p in (source, region, published_at) if p]
|
||||
if meta_parts:
|
||||
lines.append(f"- **来源与时间**:{' · '.join(meta_parts)}")
|
||||
if summary:
|
||||
lines.append(f"- **报道摘要**:{summary}")
|
||||
else:
|
||||
lines.append("### 全球局势与新闻态势速览")
|
||||
if question:
|
||||
lines.append(f"- **当前问题**:{question}")
|
||||
|
||||
items = list(recent_news.get("items") or [])
|
||||
if items:
|
||||
lines.append("")
|
||||
lines.append("#### 近期关联动态")
|
||||
for item in items[:5]:
|
||||
item_title = str(item.get("title") or "").strip()
|
||||
item_src = str(item.get("source") or "").strip()
|
||||
item_reg = str(item.get("region") or "").strip()
|
||||
if item_title:
|
||||
meta = f"({item_src}{' · ' + item_reg if item_reg else ''})" if item_src else ""
|
||||
lines.append(f"- {item_title}{meta}")
|
||||
|
||||
if not ai_configured:
|
||||
lines.append("")
|
||||
lines.append("> 当前后台尚未接入可用 AI 大模型,以上为内置新闻与遥测结构化汇总。")
|
||||
elif fallback_reason:
|
||||
lines.append("")
|
||||
lines.append(f"> AI 流式生成暂时不可用({fallback_reason}),已自动回退为内置结构化汇总。")
|
||||
return "\n".join(lines).strip()
|
||||
|
||||
|
||||
def _build_news_analysis_request(
|
||||
*,
|
||||
question: str,
|
||||
news_context: dict[str, Any] | None,
|
||||
recent_news: dict[str, Any],
|
||||
global_snapshot: dict[str, Any],
|
||||
thinking_cfg: dict[str, Any] | None,
|
||||
conversation_messages: list[ChatMessage] | None = None,
|
||||
conversation_summary: str = "",
|
||||
memory_notes: list[str] | None = None,
|
||||
pinned_summaries: list[str] | None = None,
|
||||
) -> SituationalAnalysisRequest:
|
||||
context: dict[str, Any] = {
|
||||
"focused_news": news_context or None,
|
||||
"recent_news_headlines": (recent_news.get("items") or [])[:10],
|
||||
"global_infrastructure_summary": global_snapshot.get("domain_summaries") or [],
|
||||
}
|
||||
if conversation_summary:
|
||||
context["conversation_summary"] = conversation_summary
|
||||
if memory_notes:
|
||||
context["user_memory_notes"] = memory_notes
|
||||
if pinned_summaries:
|
||||
context["pinned_comparisons"] = pinned_summaries
|
||||
return SituationalAnalysisRequest(
|
||||
title="Planet 全球新闻与国际局势研判",
|
||||
objective=(
|
||||
f"用户提问:{question}\n\n"
|
||||
"请结合多轮对话延续性与记忆备忘,直接使用中文(若用户用英文提问则用英文)输出结构清晰的 Markdown 深度分析,包括:\n"
|
||||
"1. **核心事实与背景脉络**(紧扣聚焦新闻或近期头条);\n"
|
||||
"2. **地缘、产业与基础设施影响**(可结合海缆/算力/航运/卫星/BGP 背景若相关,无直接关联则勿强行牵连);\n"
|
||||
"3. **后续重点观察信号与不确定边界**。\n"
|
||||
"请直接输出面向用户的 Markdown 正文,不要包在 JSON 里。"
|
||||
),
|
||||
system_prompt=(
|
||||
"你是 Planet(智能星球计划)的全球新闻与国际局势分析参谋。"
|
||||
"如有前序对话与用户备忘录,请保持指代与口径延续。"
|
||||
"请严谨区分已报道事实与推演研判,禁止虚构具体伤亡、断缆或未经报道的内部消息。"
|
||||
),
|
||||
context=context,
|
||||
constraints=[
|
||||
"Output clean user-facing Markdown directly (not JSON).",
|
||||
"Distinguish reported facts from analytical outlook.",
|
||||
],
|
||||
thinking=thinking_cfg,
|
||||
messages=conversation_messages or [],
|
||||
)
|
||||
|
||||
|
||||
def _build_telemetry_stream_request(
|
||||
*,
|
||||
domain: str,
|
||||
question: str,
|
||||
base_answer_md: str,
|
||||
evidence: dict[str, Any],
|
||||
view_spec: dict[str, Any] | None,
|
||||
recent_news: dict[str, Any] | None,
|
||||
thinking_cfg: dict[str, Any] | None,
|
||||
conversation_messages: list[ChatMessage] | None = None,
|
||||
conversation_summary: str = "",
|
||||
memory_notes: list[str] | None = None,
|
||||
pinned_summaries: list[str] | None = None,
|
||||
) -> SituationalAnalysisRequest:
|
||||
context: dict[str, Any] = {
|
||||
"domain": domain,
|
||||
"verified_baseline_summary": base_answer_md,
|
||||
"evidence": evidence,
|
||||
"view_headline": (view_spec or {}).get("headline"),
|
||||
}
|
||||
if recent_news and recent_news.get("items"):
|
||||
context["recent_news_headlines"] = (recent_news.get("items") or [])[:10]
|
||||
if conversation_summary:
|
||||
context["conversation_summary"] = conversation_summary
|
||||
if memory_notes:
|
||||
context["user_memory_notes"] = memory_notes
|
||||
if pinned_summaries:
|
||||
context["pinned_comparisons"] = pinned_summaries
|
||||
return SituationalAnalysisRequest(
|
||||
title=f"Planet 态势参谋分析({domain})",
|
||||
objective=(
|
||||
f"用户问题:{question}\n\n"
|
||||
"请严格基于 context 中的已核验内置遥测结论、证据源、前序对话摘要/记忆备忘与关联新闻头条,"
|
||||
"使用清晰自然的 Markdown 直接回答用户问题,给出结构化洞察与口径边界,不要输出 JSON 对象。"
|
||||
),
|
||||
system_prompt=(
|
||||
"你是 Planet 空间与网络基础设施态势参谋。如有前序对话与用户记忆备忘,请延续语境与偏好;"
|
||||
"所有具体数值必须与 context 一致,不得编造未给出的实时数值或故障原因;直接输出高质量 Markdown 分析正文。"
|
||||
),
|
||||
context=context,
|
||||
constraints=[
|
||||
"Output clean Markdown directly (not JSON).",
|
||||
"Do not invent telemetry counts or unverified outages outside context.",
|
||||
],
|
||||
thinking=thinking_cfg,
|
||||
messages=conversation_messages or [],
|
||||
)
|
||||
|
||||
|
||||
async def stream_session_turn(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
request: Request | None,
|
||||
session: InvestigationSession | None,
|
||||
question: str,
|
||||
context_override: dict[str, Any] | None,
|
||||
news_context: dict[str, Any] | None,
|
||||
access: AccessContext,
|
||||
ai_client: AIProviderClient | None,
|
||||
client_run_id: str | None = None,
|
||||
issued_session_token: str | None = None,
|
||||
history: list[dict[str, Any]] | None = None,
|
||||
conversation_summary: str | None = None,
|
||||
memory_notes: list[str] | None = None,
|
||||
pinned_summaries: list[str] | None = None,
|
||||
) -> AsyncIterator[str]:
|
||||
"""Adaptive SSE generator: streams real LLM + thinking when AI is configured, else grounded baseline."""
|
||||
check_stream_quota(access)
|
||||
|
||||
session_id_val = str(session.id) if session is not None else "stateless"
|
||||
run_id = client_run_id or f"run-{uuid.uuid4().hex[:12]}"
|
||||
|
||||
merged_ctx: dict[str, Any] = {}
|
||||
if session is not None and isinstance(session.context_state, dict):
|
||||
merged_ctx.update(session.context_state)
|
||||
if context_override:
|
||||
for k, v in context_override.items():
|
||||
if v is not None:
|
||||
merged_ctx[k] = v
|
||||
|
||||
raw_history = history if history else merged_ctx.get("recent_messages")
|
||||
existing_summary = str(
|
||||
conversation_summary
|
||||
if conversation_summary is not None
|
||||
else merged_ctx.get("conversation_summary") or ""
|
||||
)
|
||||
clean_memory_notes = sanitize_memory_notes(memory_notes)
|
||||
clean_pinned_summaries = sanitize_pinned_summaries(
|
||||
pinned_summaries
|
||||
if pinned_summaries is not None
|
||||
else [
|
||||
f"{p.get('pin_id', 'PIN')}: {p.get('title', '')}"
|
||||
for p in ((getattr(session, "pinned_items", None) or []) if session is not None else [])
|
||||
if isinstance(p, dict) and p.get("title")
|
||||
]
|
||||
)
|
||||
|
||||
routed = classify_turn_intent(question, merged_ctx)
|
||||
explicit_domain = str((context_override or {}).get("domain") or "").strip().lower()
|
||||
domain = "news" if news_context or explicit_domain == "news" else str(routed.get("domain") or "global")
|
||||
is_pure_view = bool(routed.get("is_pure_projection") or routed.get("auto_play_presentation"))
|
||||
geo_or_news_query = _is_geopolitical_or_news_question(
|
||||
question,
|
||||
domain=domain,
|
||||
news_context=news_context,
|
||||
)
|
||||
|
||||
time_basis: TimeBasis = (context_override or {}).get("time_basis") or merged_ctx.get("time_basis") or "retrospective"
|
||||
cutoff_at: str | None = (context_override or {}).get("cutoff_at") or merged_ctx.get("cutoff_at")
|
||||
codes = list((context_override or {}).get("selected_codes") or merged_ctx.get("selected_codes") or ["CN", "US"])
|
||||
visible_layers = dict((context_override or {}).get("visible_layers") or merged_ctx.get("visible_layers") or {})
|
||||
|
||||
ai_ready = False
|
||||
provider_name = ""
|
||||
model_name = ""
|
||||
if ai_client is not None:
|
||||
ai_ready, provider_name, model_name = await ai_client.is_ready()
|
||||
|
||||
compaction = await compact_conversation_history(
|
||||
raw_history,
|
||||
existing_summary,
|
||||
ai_client=ai_client,
|
||||
ai_ready=ai_ready,
|
||||
)
|
||||
compacted_summary = str(compaction.get("summary") or "")
|
||||
recent_history = list(compaction.get("recent_messages") or [])
|
||||
compacted_flag = bool(compaction.get("compacted"))
|
||||
memory_used_flag = bool(compacted_summary or recent_history or clean_memory_notes or clean_pinned_summaries)
|
||||
|
||||
view_spec: dict[str, Any] | None = None
|
||||
scene_spec: dict[str, Any] | None = None
|
||||
evidence: dict[str, Any] = {}
|
||||
subject_key = "global"
|
||||
revision = 1
|
||||
base_answer_md = ""
|
||||
context_state: dict[str, Any] = {**merged_ctx, "domain": domain}
|
||||
recent_news: dict[str, Any] = {"items": [], "evidence": {}}
|
||||
|
||||
if news_context or domain == "news":
|
||||
news_region = str((news_context or {}).get("region_key") or "").strip() or None
|
||||
recent_news = await query_recent_earth_news_tool(db, region=news_region, limit=10)
|
||||
global_snap = await query_global_situational_tool(
|
||||
db,
|
||||
selected_codes=codes,
|
||||
visible_layers=visible_layers,
|
||||
time_basis=time_basis,
|
||||
cutoff_at=cutoff_at,
|
||||
)
|
||||
evidence = {**(recent_news.get("evidence") or {}), **(global_snap.get("evidence") or {})}
|
||||
if news_context and news_context.get("url"):
|
||||
evidence["ev-news-focus"] = {
|
||||
"id": "ev-news-focus",
|
||||
"title": str(news_context.get("title") or "聚焦新闻"),
|
||||
"publisher": str(news_context.get("source") or "Planet News"),
|
||||
"url": str(news_context.get("url") or ""),
|
||||
"published_at": str(news_context.get("published_at") or ""),
|
||||
"locator": str(news_context.get("region") or news_context.get("region_key") or "news"),
|
||||
}
|
||||
subject_key = f"news:{(news_context or {}).get('id') or news_region or 'global'}"
|
||||
base_answer_md = _build_news_fallback_markdown(
|
||||
question=question,
|
||||
news_context=news_context,
|
||||
recent_news=recent_news,
|
||||
ai_configured=ai_ready,
|
||||
)
|
||||
else:
|
||||
base_turn = await execute_session_turn(
|
||||
db,
|
||||
session=session,
|
||||
question=question,
|
||||
context_override=context_override,
|
||||
prefer_llm=False,
|
||||
access=access,
|
||||
ai_client=None,
|
||||
client_run_id=None,
|
||||
)
|
||||
view_spec = base_turn.get("view_spec")
|
||||
scene_spec = base_turn.get("scene_spec")
|
||||
evidence = base_turn.get("evidence") or {}
|
||||
subject_key = str(base_turn.get("subject_key") or domain)
|
||||
revision = int(base_turn.get("revision") or 1)
|
||||
base_answer_md = str((base_turn.get("reply") or {}).get("answer_markdown") or "")
|
||||
if isinstance(base_turn.get("context_state"), dict):
|
||||
context_state = base_turn["context_state"]
|
||||
if domain == "global" and (geo_or_news_query or ai_ready):
|
||||
recent_news = await query_recent_earth_news_tool(db, limit=10)
|
||||
evidence = {**evidence, **(recent_news.get("evidence") or {})}
|
||||
if geo_or_news_query and not is_pure_view:
|
||||
# Conversational international/news questions should focus on the narrative, not a static bar chart.
|
||||
view_spec = None
|
||||
scene_spec = None
|
||||
if not ai_ready:
|
||||
base_answer_md = _build_news_fallback_markdown(
|
||||
question=question,
|
||||
news_context=None,
|
||||
recent_news=recent_news,
|
||||
ai_configured=False,
|
||||
)
|
||||
|
||||
meta_payload: dict[str, Any] = {
|
||||
"session_id": session_id_val,
|
||||
"run_id": run_id,
|
||||
"domain": domain,
|
||||
"subject_key": subject_key,
|
||||
"revision": revision,
|
||||
"ai_enabled": ai_ready and not is_pure_view,
|
||||
"provider": provider_name if (ai_ready and not is_pure_view) else None,
|
||||
"model": model_name if (ai_ready and not is_pure_view) else None,
|
||||
"compacted": compacted_flag,
|
||||
"conversation_summary": compacted_summary,
|
||||
"memory_used": memory_used_flag,
|
||||
"view_spec": view_spec,
|
||||
"scene_spec": scene_spec,
|
||||
"evidence": evidence,
|
||||
"context_state": context_state,
|
||||
}
|
||||
if issued_session_token:
|
||||
meta_payload["session_token"] = issued_session_token
|
||||
yield _format_sse("meta", meta_payload)
|
||||
|
||||
def _persist_session_memory(answer_text: str) -> None:
|
||||
if session is None or not isinstance(session.context_state, dict):
|
||||
return
|
||||
updated_recent = [*recent_history, {"role": "user", "content": question}]
|
||||
if answer_text:
|
||||
updated_recent.append({"role": "assistant", "content": answer_text[:1800]})
|
||||
session.context_state = {
|
||||
**session.context_state,
|
||||
"conversation_summary": compacted_summary,
|
||||
"recent_messages": updated_recent[-8:],
|
||||
}
|
||||
|
||||
if not ai_ready or is_pure_view or ai_client is None:
|
||||
_persist_session_memory(base_answer_md)
|
||||
if base_answer_md:
|
||||
yield _format_sse("text", {"delta": base_answer_md})
|
||||
yield _format_sse(
|
||||
"done",
|
||||
{
|
||||
"status": "completed",
|
||||
"generation_mode": "deterministic_baseline",
|
||||
"zero_token": True,
|
||||
"provider": None,
|
||||
"model": None,
|
||||
"usage": {},
|
||||
"compacted": compacted_flag,
|
||||
"conversation_summary": compacted_summary,
|
||||
"memory_used": memory_used_flag,
|
||||
"answer_markdown": base_answer_md,
|
||||
"reasoning_markdown": "",
|
||||
},
|
||||
)
|
||||
return
|
||||
|
||||
conversation_messages = [
|
||||
ChatMessage(role=m["role"], content=m["content"]) for m in recent_history
|
||||
]
|
||||
thinking_cfg = build_streaming_thinking_config(ai_client)
|
||||
effective_client = ai_client
|
||||
current_max = int((getattr(ai_client, "llm_config", None) or {}).get("max_tokens") or 0)
|
||||
if type(ai_client) is AIProviderClient and ai_client.llm_config and current_max < 3200:
|
||||
effective_client, _ = prepare_situational_ai_call(ai_client, min_max_tokens=3200)
|
||||
analysis_req = (
|
||||
_build_news_analysis_request(
|
||||
question=question,
|
||||
news_context=news_context,
|
||||
recent_news=recent_news,
|
||||
global_snapshot=await query_global_situational_tool(
|
||||
db,
|
||||
selected_codes=codes,
|
||||
visible_layers=visible_layers,
|
||||
time_basis=time_basis,
|
||||
cutoff_at=cutoff_at,
|
||||
),
|
||||
thinking_cfg=thinking_cfg,
|
||||
conversation_messages=conversation_messages,
|
||||
conversation_summary=compacted_summary,
|
||||
memory_notes=clean_memory_notes,
|
||||
pinned_summaries=clean_pinned_summaries,
|
||||
)
|
||||
if (news_context or domain == "news")
|
||||
else _build_telemetry_stream_request(
|
||||
domain=domain,
|
||||
question=question,
|
||||
base_answer_md=base_answer_md,
|
||||
evidence=evidence,
|
||||
view_spec=view_spec,
|
||||
recent_news=recent_news if domain == "global" else None,
|
||||
thinking_cfg=thinking_cfg,
|
||||
conversation_messages=conversation_messages,
|
||||
conversation_summary=compacted_summary,
|
||||
memory_notes=clean_memory_notes,
|
||||
pinned_summaries=clean_pinned_summaries,
|
||||
)
|
||||
)
|
||||
|
||||
text_chunks: list[str] = []
|
||||
reasoning_chunks: list[str] = []
|
||||
resolved_provider = provider_name
|
||||
resolved_model = model_name
|
||||
final_usage: dict[str, Any] = {}
|
||||
|
||||
try:
|
||||
async for ev in effective_client.stream_analyze(analysis_req, request_id=run_id):
|
||||
if request is not None and await request.is_disconnected():
|
||||
return
|
||||
ev_type = str(ev.get("event") or "")
|
||||
if ev_type == "start":
|
||||
if isinstance(ev.get("provider"), str) and ev["provider"]:
|
||||
resolved_provider = ev["provider"]
|
||||
if isinstance(ev.get("model"), str) and ev["model"]:
|
||||
resolved_model = ev["model"]
|
||||
elif ev_type == "reasoning":
|
||||
delta = ev.get("delta")
|
||||
if isinstance(delta, str) and delta:
|
||||
reasoning_chunks.append(delta)
|
||||
yield _format_sse("reasoning", {"delta": delta})
|
||||
elif ev_type == "text":
|
||||
delta = ev.get("delta")
|
||||
if isinstance(delta, str) and delta:
|
||||
text_chunks.append(delta)
|
||||
yield _format_sse("text", {"delta": delta})
|
||||
elif ev_type == "done":
|
||||
if isinstance(ev.get("provider"), str) and ev["provider"]:
|
||||
resolved_provider = ev["provider"]
|
||||
if isinstance(ev.get("model"), str) and ev["model"]:
|
||||
resolved_model = ev["model"]
|
||||
if isinstance(ev.get("usage"), dict):
|
||||
final_usage = ev["usage"]
|
||||
elif ev_type == "error":
|
||||
raise RuntimeError(str(ev.get("detail") or "AI stream error"))
|
||||
|
||||
combined_text = "".join(text_chunks).strip()
|
||||
if not combined_text:
|
||||
raise RuntimeError("AI provider stream returned empty response")
|
||||
|
||||
clean_text, inline_thoughts = strip_thinking_text(combined_text)
|
||||
combined_reasoning = "".join(reasoning_chunks).strip()
|
||||
if inline_thoughts:
|
||||
extra_thought = "\n\n".join(inline_thoughts)
|
||||
combined_reasoning = f"{combined_reasoning}\n\n{extra_thought}".strip() if combined_reasoning else extra_thought
|
||||
|
||||
final_answer_md = clean_text or combined_text
|
||||
_persist_session_memory(final_answer_md)
|
||||
if hasattr(db, "commit"):
|
||||
try:
|
||||
await db.commit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
yield _format_sse(
|
||||
"done",
|
||||
{
|
||||
"status": "completed",
|
||||
"generation_mode": "llm_verified",
|
||||
"zero_token": False,
|
||||
"provider": resolved_provider,
|
||||
"model": resolved_model,
|
||||
"usage": final_usage,
|
||||
"compacted": compacted_flag,
|
||||
"conversation_summary": compacted_summary,
|
||||
"memory_used": memory_used_flag,
|
||||
"answer_markdown": final_answer_md,
|
||||
"reasoning_markdown": combined_reasoning,
|
||||
},
|
||||
)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"AI stream turn failed",
|
||||
event="ai_stream.llm.fallback",
|
||||
context={"domain": domain, "emitted_text": bool(text_chunks), "error": str(exc)},
|
||||
)
|
||||
if text_chunks:
|
||||
yield _format_sse("error", {"detail": str(exc), "partial": True})
|
||||
return
|
||||
|
||||
fallback_md = (
|
||||
_build_news_fallback_markdown(
|
||||
question=question,
|
||||
news_context=news_context,
|
||||
recent_news=recent_news,
|
||||
ai_configured=True,
|
||||
fallback_reason=str(exc),
|
||||
)
|
||||
if (news_context or domain == "news" or geo_or_news_query)
|
||||
else f"{base_answer_md}\n\n> AI 流式研判暂时回退:{exc}".strip()
|
||||
)
|
||||
if fallback_md:
|
||||
yield _format_sse("text", {"delta": fallback_md})
|
||||
yield _format_sse(
|
||||
"done",
|
||||
{
|
||||
"status": "completed",
|
||||
"generation_mode": "deterministic_fallback",
|
||||
"zero_token": True,
|
||||
"provider": None,
|
||||
"model": None,
|
||||
"usage": {},
|
||||
"answer_markdown": fallback_md,
|
||||
"reasoning_markdown": "".join(reasoning_chunks).strip(),
|
||||
"fallback_reason": str(exc),
|
||||
},
|
||||
)
|
||||
@@ -11,11 +11,13 @@ from urllib.parse import urljoin, urlparse
|
||||
|
||||
import httpx
|
||||
from bs4 import BeautifulSoup
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy import desc, func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.logging import get_logger
|
||||
from app.models.bgp_incident import BGPIncident
|
||||
from app.models.collected_data import CollectedData
|
||||
from app.models.earth_news import EarthNewsItem
|
||||
from app.schemas.compute_configuration import ComputeConfiguration
|
||||
from app.services.ai_tools.schemas import FetchedEvidence
|
||||
from app.services.compute_configuration import read_configuration
|
||||
@@ -610,7 +612,20 @@ async def query_satellite_posture_tool(
|
||||
|
||||
safe_limit = max(50, min(int(limit or 1200), 3000))
|
||||
features: list[dict[str, Any]] = []
|
||||
catalog_total: int | None = None
|
||||
limitations: list[str] = []
|
||||
try:
|
||||
count_stmt = select(func.count(CollectedData.id)).where(
|
||||
CollectedData.source == "celestrak_tle",
|
||||
CollectedData.is_current.is_(True),
|
||||
CollectedData.name != "Unknown",
|
||||
)
|
||||
counted = (await db.execute(count_stmt)).scalar_one_or_none()
|
||||
if isinstance(counted, int) and counted > 0:
|
||||
catalog_total = counted
|
||||
except Exception:
|
||||
catalog_total = None
|
||||
|
||||
try:
|
||||
sat_fc = await _build_satellites_geojson(limit=safe_limit, db=db)
|
||||
features = list(sat_fc.get("features") or [])
|
||||
@@ -622,6 +637,8 @@ async def query_satellite_posture_tool(
|
||||
)
|
||||
limitations.append("内置卫星 TLE 查询受限")
|
||||
|
||||
effective_total = catalog_total if catalog_total is not None and catalog_total >= len(features) else len(features)
|
||||
|
||||
by_constellation: dict[str, int] = {}
|
||||
by_orbit_regime: dict[str, int] = {}
|
||||
sample_satellites: list[dict[str, Any]] = []
|
||||
@@ -657,15 +674,18 @@ async def query_satellite_posture_tool(
|
||||
sorted_constellations = dict(
|
||||
sorted(by_constellation.items(), key=lambda kv: kv[1], reverse=True)[:10]
|
||||
)
|
||||
if len(features) >= safe_limit:
|
||||
limitations.append(f"本次卫星样本按性能上限截取前 {safe_limit} 颗轨道目标,不代表全库总编目。")
|
||||
if effective_total > len(features):
|
||||
limitations.append(
|
||||
f"在轨卫星全库共 {effective_total} 颗;星座/轨道分布基于最新 {len(features)} 颗样本统计。"
|
||||
)
|
||||
if time_basis == "as_known_then":
|
||||
limitations.append("在轨星历基于最新同步批次(celestrak_tle),未按历史截点回卷旧 TLE。")
|
||||
|
||||
return {
|
||||
"domain": "satellite",
|
||||
"available": len(features) > 0,
|
||||
"satellites_total": len(features),
|
||||
"available": effective_total > 0,
|
||||
"satellites_total": effective_total,
|
||||
"sampled_count": len(features),
|
||||
"sample_limit": safe_limit,
|
||||
"by_constellation": sorted_constellations,
|
||||
"by_orbit_regime": by_orbit_regime,
|
||||
@@ -678,6 +698,74 @@ async def query_satellite_posture_tool(
|
||||
}
|
||||
|
||||
|
||||
async def query_recent_earth_news_tool(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
region: str | None = None,
|
||||
limit: int = 12,
|
||||
) -> dict[str, Any]:
|
||||
"""Read-only built-in snapshot of recent global/regional Earth news items for geopolitical & news copilot turns."""
|
||||
base_ev_id = "ev-news-1"
|
||||
evidence = {
|
||||
base_ev_id: {
|
||||
"id": base_ev_id,
|
||||
"title": "Planet 全球态势新闻聚合快照(earth_news_items)",
|
||||
"publisher": "Planet Global News Monitor",
|
||||
"url": "/api/v1/earth/news",
|
||||
"published_at": datetime.now(UTC).date().isoformat(),
|
||||
"locator": f"builtin:earth_news:{region or 'global'}:limit={limit}",
|
||||
}
|
||||
}
|
||||
if not hasattr(db, "execute"):
|
||||
return {"domain": "news", "available": False, "items": [], "evidence": evidence}
|
||||
|
||||
safe_limit = max(1, min(int(limit or 12), 25))
|
||||
items: list[dict[str, Any]] = []
|
||||
try:
|
||||
stmt = (
|
||||
select(EarthNewsItem)
|
||||
.where(EarthNewsItem.resolved_at.is_(None))
|
||||
.order_by(desc(EarthNewsItem.published_at), desc(EarthNewsItem.last_seen_at))
|
||||
.limit(safe_limit)
|
||||
)
|
||||
if region:
|
||||
stmt = stmt.where(EarthNewsItem.region == region)
|
||||
rows = (await db.execute(stmt)).scalars().all()
|
||||
for row in rows:
|
||||
loc_meta = dict(row.location_meta or {})
|
||||
news_meta = loc_meta.get("news_meta") if isinstance(loc_meta.get("news_meta"), dict) else {}
|
||||
localizations = row.localizations if isinstance(row.localizations, dict) else {}
|
||||
zh_loc = localizations.get("zh-CN") if isinstance(localizations.get("zh-CN"), dict) else {}
|
||||
items.append(
|
||||
{
|
||||
"id": row.id,
|
||||
"title": zh_loc.get("title") or row.title,
|
||||
"summary": (zh_loc.get("summary") or row.summary or "")[:400],
|
||||
"source": row.source or row.feed_name,
|
||||
"region": row.region,
|
||||
"location_label": row.location_label,
|
||||
"category": news_meta.get("category") or "other",
|
||||
"breaking_level": news_meta.get("breaking_level") or "none",
|
||||
"published_at": row.published_at.isoformat() if row.published_at else None,
|
||||
"url": row.url,
|
||||
}
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Recent earth news query degraded",
|
||||
event="ai_tool.earth_news.degraded",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
|
||||
return {
|
||||
"domain": "news",
|
||||
"available": len(items) > 0,
|
||||
"count": len(items),
|
||||
"items": items,
|
||||
"evidence": evidence,
|
||||
}
|
||||
|
||||
|
||||
async def query_vessel_posture_tool(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections.abc import AsyncIterator
|
||||
import json
|
||||
from time import perf_counter
|
||||
|
||||
@@ -45,6 +46,82 @@ class AIProviderClient:
|
||||
)
|
||||
self.llm_config = llm_config or {}
|
||||
|
||||
async def is_ready(self) -> tuple[bool, str, str]:
|
||||
"""Return `(configured_and_enabled, provider, model)` without calling LLM inference."""
|
||||
if not self.service_url:
|
||||
return False, "unconfigured", ""
|
||||
if isinstance(self.llm_config, dict) and self.llm_config:
|
||||
provider = str(self.llm_config.get("provider") or "").strip().lower()
|
||||
provider_api = str(self.llm_config.get("provider_api") or "").strip().lower()
|
||||
base_url = str(self.llm_config.get("base_url") or "").strip()
|
||||
model = str(self.llm_config.get("model") or "").strip()
|
||||
api_key = str(self.llm_config.get("api_key") or "").strip()
|
||||
if not provider or provider == "disabled":
|
||||
return False, provider or "disabled", model
|
||||
needs_key = provider != "ollama" and provider_api != "ollama-generate"
|
||||
configured = bool(base_url and model and (api_key or not needs_key))
|
||||
return configured, provider, model
|
||||
try:
|
||||
status_resp = await self.get_status()
|
||||
return (
|
||||
bool(status_resp.enabled and status_resp.configured),
|
||||
str(status_resp.provider or ""),
|
||||
str(status_resp.model or ""),
|
||||
)
|
||||
except Exception:
|
||||
return False, "unavailable", ""
|
||||
|
||||
async def stream_analyze(
|
||||
self,
|
||||
payload: SituationalAnalysisRequest,
|
||||
request_id: str | None = None,
|
||||
) -> AsyncIterator[dict]:
|
||||
"""Stream structured SSE events (`start`, `reasoning`, `text`, `done`, `error`) from aiprovider."""
|
||||
if not self.service_url:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="AI provider service URL is not configured.",
|
||||
)
|
||||
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
||||
async with client.stream(
|
||||
"POST",
|
||||
f"{self.service_url}/v1/analyze/stream",
|
||||
headers=self._headers(request_id),
|
||||
json=payload.model_dump(),
|
||||
) as response:
|
||||
if response.status_code >= 400:
|
||||
detail = (await response.aread()).decode("utf-8", errors="replace")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail=f"AI provider service request failed: {detail or response.status_code}",
|
||||
)
|
||||
event_name = ""
|
||||
data_lines: list[str] = []
|
||||
async for raw_line in response.aiter_lines():
|
||||
line = raw_line.rstrip("\r")
|
||||
if line == "":
|
||||
if data_lines:
|
||||
raw_json = "\n".join(data_lines)
|
||||
event_name_cur = event_name
|
||||
event_name = ""
|
||||
data_lines = []
|
||||
parsed = json.loads(raw_json)
|
||||
if isinstance(parsed, dict):
|
||||
parsed.setdefault("event", event_name_cur or "message")
|
||||
yield parsed
|
||||
continue
|
||||
if line.startswith(":"):
|
||||
continue
|
||||
if line.startswith("event:"):
|
||||
event_name = line[6:].strip()
|
||||
elif line.startswith("data:"):
|
||||
data_lines.append(line[5:].lstrip())
|
||||
if data_lines:
|
||||
parsed = json.loads("\n".join(data_lines))
|
||||
if isinstance(parsed, dict):
|
||||
parsed.setdefault("event", event_name or "message")
|
||||
yield parsed
|
||||
|
||||
def _headers(self, request_id: str | None = None) -> dict[str, str]:
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if self.service_token:
|
||||
|
||||
@@ -4,6 +4,7 @@ from datetime import UTC, datetime
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import select
|
||||
@@ -14,10 +15,13 @@ from app.core.time import to_iso8601_utc
|
||||
from app.core.websocket.broadcaster import broadcaster
|
||||
from app.models.datasource_config import DataSourceConfig
|
||||
from app.models.task import CollectionTask
|
||||
from app.services.collectors.base import BaseCollector
|
||||
from app.models.vessel import VesselCurrentState
|
||||
from app.services.collectors.base import BaseCollector, _StoragePolicyDowngradedToSingle
|
||||
from app.services.storage_policy import is_storage_policy_single_violation
|
||||
from app.services.vessel_ais_aggregation import (
|
||||
AISSTREAM_DELIVERY_MODE,
|
||||
AISSTREAM_TRANSPORT,
|
||||
prune_expired_vessel_track_points,
|
||||
record_vessel_ais_observation,
|
||||
update_ais_source_health,
|
||||
)
|
||||
@@ -282,12 +286,98 @@ class AISStreamCollector(BaseCollector):
|
||||
records.append(record)
|
||||
return records
|
||||
|
||||
async def _has_existing_current_data(self, db: AsyncSession | None) -> bool:
|
||||
if db is None or not callable(getattr(db, "execute", None)):
|
||||
return False
|
||||
try:
|
||||
result = await db.execute(
|
||||
select(VesselCurrentState.mmsi)
|
||||
.where(VesselCurrentState.source == self.name)
|
||||
.limit(1)
|
||||
)
|
||||
except Exception:
|
||||
return False
|
||||
if result is None or not callable(getattr(result, "scalar_one_or_none", None)):
|
||||
return False
|
||||
return result.scalar_one_or_none() is not None
|
||||
|
||||
async def _should_persist_raw_ais(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
*,
|
||||
force_refresh: bool = False,
|
||||
) -> tuple[bool, str]:
|
||||
now_mono = time.monotonic()
|
||||
cached_at = float(getattr(self, "_stream_mode_checked_at", 0.0))
|
||||
if (
|
||||
not force_refresh
|
||||
and (now_mono - cached_at) < 2.0
|
||||
and self._snapshot_mode is not None
|
||||
):
|
||||
return self._snapshot_mode == "history", self._snapshot_mode
|
||||
if callable(getattr(db, "execute", None)):
|
||||
mode, _ = await self._resolve_storage_policy(db)
|
||||
self._stream_mode_checked_at = now_mono
|
||||
return mode == "history", mode
|
||||
mode = self._snapshot_mode or "single"
|
||||
return mode == "history", mode
|
||||
|
||||
async def _save_data(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
data: list[dict[str, Any]],
|
||||
task_id: int | None = None,
|
||||
snapshot_id: int | None = None,
|
||||
) -> int:
|
||||
persist_raw, mode = await self._should_persist_raw_ais(db, force_refresh=True)
|
||||
snapshot_id = await self._reconcile_snapshot_for_mode_switch(
|
||||
db,
|
||||
mode=mode,
|
||||
task_id=task_id,
|
||||
snapshot_id=snapshot_id,
|
||||
)
|
||||
try:
|
||||
records_added = await self._write_aisstream_batch(
|
||||
db,
|
||||
data,
|
||||
persist_raw=persist_raw,
|
||||
mode=mode,
|
||||
snapshot_id=snapshot_id,
|
||||
)
|
||||
if persist_raw:
|
||||
await self._assert_versioned_publish_allowed(db, snapshot_id=snapshot_id)
|
||||
await db.commit()
|
||||
except Exception as exc:
|
||||
if (
|
||||
(not isinstance(exc, _StoragePolicyDowngradedToSingle) and not is_storage_policy_single_violation(exc))
|
||||
or self._previous_current_snapshot_id is None
|
||||
):
|
||||
raise
|
||||
downgraded_snapshot_id = await self._downgrade_pending_snapshot_to_single(
|
||||
db,
|
||||
task_id=task_id,
|
||||
snapshot_id=snapshot_id,
|
||||
)
|
||||
records_added = await self._write_aisstream_batch(
|
||||
db,
|
||||
data,
|
||||
persist_raw=False,
|
||||
mode="single",
|
||||
snapshot_id=downgraded_snapshot_id,
|
||||
)
|
||||
await db.commit()
|
||||
|
||||
await self.update_progress(records_added, force=True)
|
||||
return records_added
|
||||
|
||||
async def _write_aisstream_batch(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
data: list[dict[str, Any]],
|
||||
*,
|
||||
persist_raw: bool,
|
||||
mode: str,
|
||||
snapshot_id: int | None,
|
||||
) -> int:
|
||||
now = datetime.now(UTC)
|
||||
records_added = 0
|
||||
@@ -305,13 +395,17 @@ class AISStreamCollector(BaseCollector):
|
||||
source_message_id=item.get("_source_message_id"),
|
||||
observed_at=observed_at,
|
||||
collected_at=now,
|
||||
persist_raw=persist_raw,
|
||||
)
|
||||
if observation is not None:
|
||||
records_added += 1
|
||||
if isinstance(observed_at, datetime) and observed_at > latest_observed_at:
|
||||
latest_observed_at = observed_at
|
||||
if (index + 1) % 1000 == 0:
|
||||
await self.update_progress(index + 1, commit=True)
|
||||
await self.update_progress(index + 1, commit=False)
|
||||
|
||||
if not persist_raw:
|
||||
await prune_expired_vessel_track_points(db, now=now)
|
||||
|
||||
await update_ais_source_health(
|
||||
db,
|
||||
@@ -327,6 +421,7 @@ class AISStreamCollector(BaseCollector):
|
||||
|
||||
snapshot = await db.get(DataSnapshot, snapshot_id)
|
||||
if snapshot:
|
||||
await self._promote_snapshot_to_current(db, snapshot)
|
||||
snapshot.record_count = records_added
|
||||
snapshot.status = "success"
|
||||
snapshot.completed_at = now
|
||||
@@ -335,13 +430,13 @@ class AISStreamCollector(BaseCollector):
|
||||
"updated": 0,
|
||||
"unchanged": 0,
|
||||
"deleted": 0,
|
||||
"storage": "ais_raw_observations",
|
||||
"storage": "ais_raw_observations" if persist_raw else "vessel_current_state_and_24h_track",
|
||||
"storage_mode": mode,
|
||||
}
|
||||
await db.commit()
|
||||
await self.update_progress(records_added, force=True)
|
||||
return records_added
|
||||
|
||||
async def _save_stream_record(self, db: AsyncSession, item: dict[str, Any]) -> bool:
|
||||
persist_raw, _mode = await self._should_persist_raw_ais(db)
|
||||
now = datetime.now(UTC)
|
||||
observed_at = item.get("received_at") or now
|
||||
observation = await record_vessel_ais_observation(
|
||||
@@ -355,7 +450,10 @@ class AISStreamCollector(BaseCollector):
|
||||
source_message_id=item.get("_source_message_id"),
|
||||
observed_at=observed_at,
|
||||
collected_at=now,
|
||||
persist_raw=persist_raw,
|
||||
)
|
||||
if not persist_raw:
|
||||
await prune_expired_vessel_track_points(db, now=now)
|
||||
await update_ais_source_health(
|
||||
db,
|
||||
source=self.name,
|
||||
|
||||
+1138
-161
File diff suppressed because it is too large.
Load diff
@@ -4,15 +4,14 @@ from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from collections import defaultdict
|
||||
from datetime import UTC, datetime
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy import or_, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.bgp_anomaly import BGPAnomaly
|
||||
from app.models.bgp_observation import BGPObservation
|
||||
from app.models.collected_data import CollectedData
|
||||
from app.services.bgp_collector_locations import (
|
||||
RIPE_RIS_COLLECTOR_COORDS,
|
||||
get_bgp_collector_location_dict,
|
||||
@@ -37,11 +36,49 @@ from app.services.bgp_enrichment import enrich_bgp_events_for_batch, extract_bgp
|
||||
__all__ = [
|
||||
"RIPE_RIS_COLLECTOR_COORDS",
|
||||
"normalize_bgp_event",
|
||||
"slim_bgp_events_for_collected_data",
|
||||
"compact_bgp_raw_payload",
|
||||
"save_bgp_observations_for_batch",
|
||||
"create_bgp_anomalies_for_batch",
|
||||
]
|
||||
|
||||
|
||||
def compact_bgp_raw_payload(metadata: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Build a compact BGP observation summary payload without raw verbose envelopes."""
|
||||
compact: dict[str, Any] = {}
|
||||
for key in (
|
||||
"event_type",
|
||||
"prefix",
|
||||
"origin_asn",
|
||||
"as_path",
|
||||
"collector",
|
||||
"peer_ip",
|
||||
"peer_asn",
|
||||
"next_hop",
|
||||
"communities",
|
||||
"timestamp",
|
||||
):
|
||||
value = metadata.get(key)
|
||||
if value not in (None, [], ""):
|
||||
compact[key] = value
|
||||
return compact
|
||||
|
||||
|
||||
def slim_bgp_events_for_collected_data(
|
||||
events: list[dict[str, Any]],
|
||||
*,
|
||||
max_rows: int = 500,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Strip heavyweight `raw_message` payloads and bound single-copy BGP batch size."""
|
||||
selected = events[-max_rows:] if max_rows > 0 and len(events) > max_rows else list(events)
|
||||
slimmed: list[dict[str, Any]] = []
|
||||
for event in selected:
|
||||
metadata = dict(event.get("metadata") or {})
|
||||
metadata.pop("raw_message", None)
|
||||
slimmed.append({**event, "metadata": metadata})
|
||||
return slimmed
|
||||
|
||||
|
||||
def _safe_int(value: Any) -> int | None:
|
||||
try:
|
||||
if value in (None, ""):
|
||||
@@ -184,6 +221,7 @@ async def save_bgp_observations_for_batch(
|
||||
snapshot_id: int | None,
|
||||
task_id: int | None,
|
||||
events: list[dict[str, Any]],
|
||||
compact_raw_payload: bool = False,
|
||||
) -> int:
|
||||
if not events:
|
||||
return 0
|
||||
@@ -197,6 +235,11 @@ async def save_bgp_observations_for_batch(
|
||||
observed_at = _parse_timestamp(
|
||||
metadata.get("timestamp") or event.get("reference_date")
|
||||
)
|
||||
raw_payload = (
|
||||
compact_bgp_raw_payload(metadata)
|
||||
if compact_raw_payload
|
||||
else (metadata.get("raw_message") or {})
|
||||
)
|
||||
|
||||
db.add(
|
||||
BGPObservation(
|
||||
@@ -216,7 +259,7 @@ async def save_bgp_observations_for_batch(
|
||||
communities=metadata.get("communities") or [],
|
||||
observed_at=observed_at,
|
||||
collector_geo=collector_location,
|
||||
raw_payload=metadata.get("raw_message") or {},
|
||||
raw_payload=raw_payload,
|
||||
note=event.get("description"),
|
||||
)
|
||||
)
|
||||
@@ -224,8 +267,8 @@ async def save_bgp_observations_for_batch(
|
||||
|
||||
if created:
|
||||
await db.commit()
|
||||
for source in {"ris_live_bgp", "bgpstream_bgp"}:
|
||||
invalidate_earth_layer_cache_for_source(source)
|
||||
for cache_source in {"ris_live_bgp", "bgpstream_bgp"}:
|
||||
invalidate_earth_layer_cache_for_source(cache_source)
|
||||
|
||||
return created
|
||||
|
||||
@@ -255,17 +298,29 @@ async def create_bgp_anomalies_for_batch(
|
||||
previous_origin_map: dict[str, set[int]] = defaultdict(set)
|
||||
|
||||
if prefixes:
|
||||
previous_query = await db.execute(
|
||||
select(CollectedData).where(
|
||||
CollectedData.source == source,
|
||||
CollectedData.snapshot_id != snapshot_id,
|
||||
CollectedData.extra_data["prefix"].as_string().in_(sorted(prefixes)),
|
||||
lookback_since = datetime.now(UTC) - timedelta(days=7)
|
||||
baseline_filters = [
|
||||
BGPObservation.source == source,
|
||||
BGPObservation.prefix.in_(sorted(prefixes)),
|
||||
BGPObservation.origin_asn.is_not(None),
|
||||
BGPObservation.observed_at >= lookback_since,
|
||||
]
|
||||
if task_id is not None:
|
||||
baseline_filters.append(
|
||||
or_(BGPObservation.task_id.is_(None), BGPObservation.task_id != task_id)
|
||||
)
|
||||
)
|
||||
elif snapshot_id is not None:
|
||||
baseline_filters.append(
|
||||
or_(BGPObservation.snapshot_id.is_(None), BGPObservation.snapshot_id != snapshot_id)
|
||||
)
|
||||
previous_query = await db.execute(select(BGPObservation).where(*baseline_filters))
|
||||
for record in previous_query.scalars().all():
|
||||
metadata = record.extra_data or {}
|
||||
prefix = metadata.get("prefix")
|
||||
origin = _safe_int(metadata.get("origin_asn"))
|
||||
prefix = getattr(record, "prefix", None)
|
||||
origin = _safe_int(getattr(record, "origin_asn", None))
|
||||
if (prefix is None or origin is None) and hasattr(record, "extra_data"):
|
||||
metadata = record.extra_data or {}
|
||||
prefix = prefix or metadata.get("prefix")
|
||||
origin = origin if origin is not None else _safe_int(metadata.get("origin_asn"))
|
||||
if prefix and origin is not None:
|
||||
previous_origin_map[prefix].add(origin)
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ from app.services.collectors.bgp_common import (
|
||||
create_bgp_anomalies_for_batch,
|
||||
normalize_bgp_event,
|
||||
save_bgp_observations_for_batch,
|
||||
slim_bgp_events_for_collected_data,
|
||||
)
|
||||
|
||||
|
||||
@@ -96,6 +97,29 @@ class BGPStreamBackfillCollector(BaseCollector):
|
||||
self._latest_transformed_batch = transformed
|
||||
return transformed
|
||||
|
||||
async def _save_data(
|
||||
self,
|
||||
db,
|
||||
data: list[dict[str, Any]],
|
||||
task_id: int | None = None,
|
||||
snapshot_id: int | None = None,
|
||||
) -> int:
|
||||
if callable(getattr(db, "execute", None)):
|
||||
mode, policy = await self._resolve_storage_policy(db)
|
||||
else:
|
||||
mode = self._snapshot_mode
|
||||
policy = self._storage_policy or {}
|
||||
prepared_data = data
|
||||
if (mode or "single") == "single":
|
||||
max_rows = int(policy.get("bgp_single_batch_max_rows", 500))
|
||||
prepared_data = slim_bgp_events_for_collected_data(data, max_rows=max_rows)
|
||||
return await super()._save_data(
|
||||
db,
|
||||
prepared_data,
|
||||
task_id=task_id,
|
||||
snapshot_id=snapshot_id,
|
||||
)
|
||||
|
||||
async def run(self, db):
|
||||
result = await super().run(db)
|
||||
if result.get("status") != "success":
|
||||
@@ -108,6 +132,7 @@ class BGPStreamBackfillCollector(BaseCollector):
|
||||
snapshot_id=snapshot_id,
|
||||
task_id=result.get("task_id"),
|
||||
events=getattr(self, "_latest_transformed_batch", []),
|
||||
compact_raw_payload=(self._snapshot_mode != "history"),
|
||||
)
|
||||
anomaly_count = await create_bgp_anomalies_for_batch(
|
||||
db,
|
||||
@@ -121,6 +146,10 @@ class BGPStreamBackfillCollector(BaseCollector):
|
||||
return result
|
||||
|
||||
async def _resolve_snapshot_id(self, db, task_id: int | None) -> int | None:
|
||||
if getattr(self, "_deduped_unchanged_snapshot_id", None) is not None:
|
||||
return self._deduped_unchanged_snapshot_id
|
||||
if getattr(self, "_reused_snapshot_id", None) is not None:
|
||||
return self._reused_snapshot_id
|
||||
if task_id is None:
|
||||
return None
|
||||
from sqlalchemy import select
|
||||
|
||||
@@ -98,7 +98,18 @@ class CelesTrakTLECollector(BaseCollector):
|
||||
progress_callback=self._report_download_progress,
|
||||
validate_existing=self._validate_json_file,
|
||||
)
|
||||
file_sha256 = self._downloader.get_file_sha256(url, ".json", body_path)
|
||||
if file_sha256:
|
||||
self._last_source_file_sha256 = file_sha256
|
||||
short_snap = await self._can_short_circuit_unchanged_file(
|
||||
self._db_session,
|
||||
file_sha256=file_sha256,
|
||||
)
|
||||
if short_snap is not None:
|
||||
self._short_circuited_snapshot_id = short_snap.id
|
||||
return []
|
||||
data = await self._load_downloaded_payload(body_path, url)
|
||||
self._mark_fetch_complete(True)
|
||||
await emit_business_log(
|
||||
logger,
|
||||
event="collector.celestrak.download.success",
|
||||
@@ -124,7 +135,18 @@ class CelesTrakTLECollector(BaseCollector):
|
||||
validate_existing=self._validate_json_file,
|
||||
)
|
||||
if cached_path is not None:
|
||||
file_sha256 = self._downloader.get_file_sha256(url, ".json", cached_path)
|
||||
if file_sha256:
|
||||
self._last_source_file_sha256 = file_sha256
|
||||
short_snap = await self._can_short_circuit_unchanged_file(
|
||||
self._db_session,
|
||||
file_sha256=file_sha256,
|
||||
)
|
||||
if short_snap is not None:
|
||||
self._short_circuited_snapshot_id = short_snap.id
|
||||
return []
|
||||
data = await self._load_downloaded_payload(cached_path, url)
|
||||
self._mark_fetch_complete(True)
|
||||
await emit_business_log(
|
||||
logger,
|
||||
event="collector.celestrak.download.cached_not_updated",
|
||||
@@ -295,6 +317,7 @@ class CelesTrakTLECollector(BaseCollector):
|
||||
if not records:
|
||||
raise RuntimeError("CelesTrak fallback group mode produced no satellite records")
|
||||
|
||||
self._mark_fetch_complete(False)
|
||||
await emit_business_log(
|
||||
logger,
|
||||
event="collector.celestrak.fallback_groups.success",
|
||||
@@ -465,6 +488,7 @@ class CelesTrakTLECollector(BaseCollector):
|
||||
return None
|
||||
|
||||
def _get_sample_data(self) -> List[Dict[str, Any]]:
|
||||
self._mark_sample_fallback("celestrak_tle_sample_fallback")
|
||||
return [
|
||||
{
|
||||
"name": "STARLINK-1000",
|
||||
|
||||
@@ -14,6 +14,7 @@ from app.services.collectors.base import BaseCollector
|
||||
class ComputeCollector(BaseCollector):
|
||||
fail_on_empty = True
|
||||
preserve_snapshot_on_failure = True
|
||||
full_snapshot_reconcile = True
|
||||
|
||||
async def _create_snapshot(
|
||||
self, db: AsyncSession, task_id: int, data: list[dict], started_at: datetime
|
||||
|
||||
@@ -16,6 +16,18 @@ ProgressCallback = Callable[[int, int | None], Awaitable[None]]
|
||||
ValidateCallback = Callable[[Path], bool]
|
||||
|
||||
|
||||
def compute_file_sha256(path: Path, *, chunk_size: int = 1024 * 1024) -> str:
|
||||
"""Compute SHA-256 hex digest of a local file without loading it all into memory."""
|
||||
hasher = hashlib.sha256()
|
||||
with path.open("rb") as f:
|
||||
while True:
|
||||
chunk = f.read(chunk_size)
|
||||
if not chunk:
|
||||
break
|
||||
hasher.update(chunk)
|
||||
return hasher.hexdigest()
|
||||
|
||||
|
||||
class DownloadHTTPStatusError(RuntimeError):
|
||||
"""HTTP status error that keeps the upstream response body for caller-specific handling."""
|
||||
|
||||
@@ -105,6 +117,47 @@ class ResumableFileDownloader:
|
||||
def _save_meta(meta_path: Path, payload: dict[str, Any]) -> None:
|
||||
meta_path.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
|
||||
|
||||
@staticmethod
|
||||
def compute_combined_sha256(digests: list[str]) -> str:
|
||||
"""Combine multiple file SHA-256 digests deterministically."""
|
||||
return hashlib.sha256("|".join(digests).encode("utf-8")).hexdigest()
|
||||
|
||||
def get_file_sha256(
|
||||
self,
|
||||
url: str,
|
||||
extension: str,
|
||||
path: Path | None = None,
|
||||
) -> str | None:
|
||||
"""Return cached or freshly computed SHA-256 digest for a downloaded dataset."""
|
||||
target_path = path or self.cached_file_path(url, extension)
|
||||
if not target_path.exists():
|
||||
return None
|
||||
_, _, meta_path = self._cache_paths(url, extension)
|
||||
stat = target_path.stat()
|
||||
meta = self._load_meta(meta_path)
|
||||
cached_digest = meta.get("sha256")
|
||||
if (
|
||||
isinstance(cached_digest, str)
|
||||
and cached_digest
|
||||
and meta.get("file_size") == stat.st_size
|
||||
and meta.get("file_mtime_ns") == stat.st_mtime_ns
|
||||
):
|
||||
return cached_digest
|
||||
|
||||
digest = compute_file_sha256(target_path)
|
||||
if meta_path.parent.exists():
|
||||
self._save_meta(
|
||||
meta_path,
|
||||
{
|
||||
**meta,
|
||||
"url": meta.get("url") or url,
|
||||
"sha256": digest,
|
||||
"file_size": stat.st_size,
|
||||
"file_mtime_ns": stat.st_mtime_ns,
|
||||
},
|
||||
)
|
||||
return digest
|
||||
|
||||
@staticmethod
|
||||
def _validators_match(meta: dict[str, Any], remote: dict[str, Any]) -> bool:
|
||||
etag = str(remote.get("etag") or "").strip()
|
||||
@@ -262,6 +315,8 @@ class ResumableFileDownloader:
|
||||
part_path.unlink(missing_ok=True)
|
||||
raise RuntimeError(f"Downloaded file validation failed for {url}")
|
||||
part_path.replace(final_path)
|
||||
stat = final_path.stat()
|
||||
file_sha256 = compute_file_sha256(final_path)
|
||||
self._save_meta(
|
||||
meta_path,
|
||||
{
|
||||
@@ -269,6 +324,9 @@ class ResumableFileDownloader:
|
||||
"etag": remote.get("etag"),
|
||||
"last_modified": remote.get("last_modified"),
|
||||
"content_length": expected_size,
|
||||
"sha256": file_sha256,
|
||||
"file_size": stat.st_size,
|
||||
"file_mtime_ns": stat.st_mtime_ns,
|
||||
"updated_at": datetime.now(UTC).isoformat(),
|
||||
},
|
||||
)
|
||||
|
||||
@@ -65,29 +65,40 @@ class IPtoASNPrefixGeoCollector(BaseCollector):
|
||||
raise RuntimeError(f"IPtoASN dataset parsed empty rows: {file_path.name}")
|
||||
return rows
|
||||
|
||||
async def _fetch_dataset_rows(
|
||||
async def _download_dataset_file(
|
||||
self,
|
||||
client: httpx.AsyncClient,
|
||||
url: str,
|
||||
*,
|
||||
progress_callback=None,
|
||||
) -> list[dict[str, Any]]:
|
||||
file_path = await self._downloader.download_file(
|
||||
) -> Path:
|
||||
return await self._downloader.download_file(
|
||||
client,
|
||||
url,
|
||||
extension=".tsv.gz",
|
||||
progress_callback=progress_callback,
|
||||
validate_existing=lambda p: self._validate_gzip_dataset(p),
|
||||
)
|
||||
return self._parse_rows_from_gzip_file(file_path)
|
||||
|
||||
def _validate_gzip_dataset(self, file_path: Path) -> bool:
|
||||
try:
|
||||
self._parse_rows_from_gzip_file(file_path)
|
||||
return True
|
||||
with gzip.open(file_path, "rt", encoding="utf-8", errors="replace") as f:
|
||||
for raw_line in f:
|
||||
line = raw_line.strip()
|
||||
if line and not line.startswith("#") and len(line.split("\t")) >= 5:
|
||||
for _ in f:
|
||||
pass
|
||||
return True
|
||||
return False
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def _parse_dataset_files(self, dataset_paths: list[Path]) -> list[dict[str, Any]]:
|
||||
rows: list[dict[str, Any]] = []
|
||||
for path in dataset_paths:
|
||||
rows.extend(self._parse_rows_from_gzip_file(path))
|
||||
return rows
|
||||
|
||||
async def fetch(self) -> list[dict[str, Any]]:
|
||||
if not self._resolved_url:
|
||||
raise RuntimeError("IPtoASN combined URL is not configured")
|
||||
@@ -149,9 +160,9 @@ class IPtoASNPrefixGeoCollector(BaseCollector):
|
||||
)
|
||||
await self.update_progress(current, commit=True)
|
||||
|
||||
batches = await asyncio.gather(
|
||||
dataset_paths = await asyncio.gather(
|
||||
*(
|
||||
self._fetch_dataset_rows(
|
||||
self._download_dataset_file(
|
||||
client,
|
||||
url,
|
||||
progress_callback=lambda downloaded, total, u=url: on_url_progress(u, downloaded, total),
|
||||
@@ -168,10 +179,23 @@ class IPtoASNPrefixGeoCollector(BaseCollector):
|
||||
)
|
||||
await self.update_progress(total_expected, commit=True, force=True)
|
||||
|
||||
rows: list[dict[str, Any]] = []
|
||||
for batch in batches:
|
||||
rows.extend(batch)
|
||||
return rows
|
||||
digests = [
|
||||
self._downloader.get_file_sha256(url, ".tsv.gz", path)
|
||||
for url, path in zip(dataset_urls, dataset_paths)
|
||||
]
|
||||
if digests and all(isinstance(d, str) and d for d in digests):
|
||||
combined_sha256 = self._downloader.compute_combined_sha256([str(d) for d in digests])
|
||||
self._last_source_file_sha256 = combined_sha256
|
||||
short_snap = await self._can_short_circuit_unchanged_file(
|
||||
self._db_session,
|
||||
file_sha256=combined_sha256,
|
||||
)
|
||||
if short_snap is not None:
|
||||
self._short_circuited_snapshot_id = short_snap.id
|
||||
return []
|
||||
|
||||
self._mark_fetch_complete(True)
|
||||
return await asyncio.to_thread(self._parse_dataset_files, dataset_paths)
|
||||
|
||||
def transform(self, raw_data: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
reference_date = datetime.now(UTC).isoformat()
|
||||
|
||||
@@ -6,8 +6,10 @@ allocation geography as prefix-centric fallback hints.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import ipaddress
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
@@ -64,42 +66,57 @@ class NRODelegatedPrefixGeoCollector(BaseCollector):
|
||||
extension=".txt",
|
||||
progress_callback=on_progress,
|
||||
)
|
||||
body = body_path.read_text(encoding="utf-8", errors="replace")
|
||||
file_sha256 = self._downloader.get_file_sha256(self._resolved_url, ".txt", body_path)
|
||||
if file_sha256:
|
||||
self._last_source_file_sha256 = file_sha256
|
||||
short_snap = await self._can_short_circuit_unchanged_file(
|
||||
self._db_session,
|
||||
file_sha256=file_sha256,
|
||||
)
|
||||
if short_snap is not None:
|
||||
self._short_circuited_snapshot_id = short_snap.id
|
||||
return []
|
||||
|
||||
self._mark_fetch_complete(True)
|
||||
return await asyncio.to_thread(self._parse_delegated_file, body_path)
|
||||
|
||||
def _parse_delegated_file(self, body_path: Path) -> list[dict[str, Any]]:
|
||||
"""Stream and parse NRO delegated stats line-by-line off the event loop."""
|
||||
rows: list[dict[str, Any]] = []
|
||||
for raw_line in body.splitlines():
|
||||
line = raw_line.strip()
|
||||
if not line or line.startswith("#"):
|
||||
continue
|
||||
with body_path.open("r", encoding="utf-8", errors="replace") as handle:
|
||||
for raw_line in handle:
|
||||
line = raw_line.strip()
|
||||
if not line or line.startswith("#"):
|
||||
continue
|
||||
|
||||
parts = line.split("|")
|
||||
if len(parts) < 7:
|
||||
continue
|
||||
parts = line.split("|")
|
||||
if len(parts) < 7:
|
||||
continue
|
||||
|
||||
rir = (parts[0] or "").strip().lower()
|
||||
country_code = (parts[1] or "").strip().upper()
|
||||
record_type = (parts[2] or "").strip().lower()
|
||||
start = (parts[3] or "").strip()
|
||||
value = (parts[4] or "").strip()
|
||||
allocated_date = (parts[5] or "").strip()
|
||||
status = (parts[6] or "").strip().lower()
|
||||
rir = (parts[0] or "").strip().lower()
|
||||
country_code = (parts[1] or "").strip().upper()
|
||||
record_type = (parts[2] or "").strip().lower()
|
||||
start = (parts[3] or "").strip()
|
||||
value = (parts[4] or "").strip()
|
||||
allocated_date = (parts[5] or "").strip()
|
||||
status = (parts[6] or "").strip().lower()
|
||||
|
||||
if record_type not in {"ipv4", "ipv6"}:
|
||||
continue
|
||||
if not start or not value:
|
||||
continue
|
||||
if record_type not in {"ipv4", "ipv6"}:
|
||||
continue
|
||||
if not start or not value:
|
||||
continue
|
||||
|
||||
rows.append(
|
||||
{
|
||||
"rir": rir,
|
||||
"country_code": country_code,
|
||||
"type": record_type,
|
||||
"start": start,
|
||||
"value": value,
|
||||
"allocated_date": allocated_date,
|
||||
"status": status,
|
||||
}
|
||||
)
|
||||
rows.append(
|
||||
{
|
||||
"rir": rir,
|
||||
"country_code": country_code,
|
||||
"type": record_type,
|
||||
"start": start,
|
||||
"value": value,
|
||||
"allocated_date": allocated_date,
|
||||
"status": status,
|
||||
}
|
||||
)
|
||||
|
||||
return rows
|
||||
|
||||
|
||||
@@ -65,6 +65,16 @@ class OpenGeoFeedPrefixGeoCollector(BaseCollector):
|
||||
extension=".csv",
|
||||
progress_callback=on_progress,
|
||||
)
|
||||
file_sha256 = self._downloader.get_file_sha256(self._resolved_url, ".csv", body_path)
|
||||
if file_sha256:
|
||||
self._last_source_file_sha256 = file_sha256
|
||||
short_snap = await self._can_short_circuit_unchanged_file(
|
||||
self._db_session,
|
||||
file_sha256=file_sha256,
|
||||
)
|
||||
if short_snap is not None:
|
||||
self._short_circuited_snapshot_id = short_snap.id
|
||||
return []
|
||||
body = body_path.read_text(encoding="utf-8", errors="replace")
|
||||
|
||||
rows: list[dict[str, Any]] = []
|
||||
|
||||
@@ -17,6 +17,7 @@ from app.services.collectors.bgp_common import (
|
||||
create_bgp_anomalies_for_batch,
|
||||
normalize_bgp_event,
|
||||
save_bgp_observations_for_batch,
|
||||
slim_bgp_events_for_collected_data,
|
||||
)
|
||||
|
||||
logger = get_logger(__name__, service="collector")
|
||||
@@ -177,6 +178,29 @@ class RISLiveCollector(BaseCollector):
|
||||
self._latest_transformed_batch = transformed
|
||||
return transformed
|
||||
|
||||
async def _save_data(
|
||||
self,
|
||||
db,
|
||||
data: list[dict[str, Any]],
|
||||
task_id: int | None = None,
|
||||
snapshot_id: int | None = None,
|
||||
) -> int:
|
||||
if callable(getattr(db, "execute", None)):
|
||||
mode, policy = await self._resolve_storage_policy(db)
|
||||
else:
|
||||
mode = self._snapshot_mode
|
||||
policy = self._storage_policy or {}
|
||||
prepared_data = data
|
||||
if (mode or "single") == "single":
|
||||
max_rows = int(policy.get("bgp_single_batch_max_rows", 500))
|
||||
prepared_data = slim_bgp_events_for_collected_data(data, max_rows=max_rows)
|
||||
return await super()._save_data(
|
||||
db,
|
||||
prepared_data,
|
||||
task_id=task_id,
|
||||
snapshot_id=snapshot_id,
|
||||
)
|
||||
|
||||
async def run(self, db):
|
||||
result = await super().run(db)
|
||||
if result.get("status") != "success":
|
||||
@@ -189,6 +213,7 @@ class RISLiveCollector(BaseCollector):
|
||||
snapshot_id=snapshot_id,
|
||||
task_id=result.get("task_id"),
|
||||
events=getattr(self, "_latest_transformed_batch", []),
|
||||
compact_raw_payload=(self._snapshot_mode != "history"),
|
||||
)
|
||||
anomaly_count = await create_bgp_anomalies_for_batch(
|
||||
db,
|
||||
@@ -202,6 +227,10 @@ class RISLiveCollector(BaseCollector):
|
||||
return result
|
||||
|
||||
async def _resolve_snapshot_id(self, db, task_id: int | None) -> int | None:
|
||||
if getattr(self, "_deduped_unchanged_snapshot_id", None) is not None:
|
||||
return self._deduped_unchanged_snapshot_id
|
||||
if getattr(self, "_reused_snapshot_id", None) is not None:
|
||||
return self._reused_snapshot_id
|
||||
if task_id is None:
|
||||
return None
|
||||
from sqlalchemy import select
|
||||
|
||||
@@ -213,6 +213,7 @@ class SpaceTrackTLECollector(BaseCollector):
|
||||
|
||||
def _get_sample_data(self) -> List[Dict[str, Any]]:
|
||||
"""Return sample TLE data for testing"""
|
||||
self._mark_sample_fallback("spacetrack_tle_sample_fallback")
|
||||
return [
|
||||
{
|
||||
"name": "ISS (ZARYA)",
|
||||
|
||||
@@ -119,6 +119,7 @@ class TeleGeographyCableCollector(BaseCollector):
|
||||
|
||||
def _get_sample_data(self) -> List[Dict[str, Any]]:
|
||||
"""Return sample submarine cable data"""
|
||||
self._mark_sample_fallback("telegeography_cables_sample_fallback")
|
||||
return [
|
||||
{
|
||||
"source_id": "telegeo_sample_1",
|
||||
@@ -235,6 +236,7 @@ class TeleGeographyLandingPointCollector(BaseCollector):
|
||||
|
||||
def _get_sample_data(self) -> List[Dict[str, Any]]:
|
||||
"""Return sample landing point data"""
|
||||
self._mark_sample_fallback("telegeography_landing_sample_fallback")
|
||||
return [
|
||||
{
|
||||
"source_id": "telegeo_lp_sample_1",
|
||||
@@ -306,6 +308,7 @@ class TeleGeographyCableSystemCollector(BaseCollector):
|
||||
|
||||
def _get_sample_data(self) -> List[Dict[str, Any]]:
|
||||
"""Return sample cable system data"""
|
||||
self._mark_sample_fallback("telegeography_systems_sample_fallback")
|
||||
return [
|
||||
{
|
||||
"source_id": "telegeo_sys_sample_1",
|
||||
|
||||
@@ -4,20 +4,24 @@ from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.enums import SnapshotStatus
|
||||
from app.core.time import to_iso8601_utc
|
||||
from app.core.websocket.broadcaster import broadcaster
|
||||
from app.models.vessel import VesselCurrentState
|
||||
from app.services.barentswatch import (
|
||||
BARENTSWATCH_LATEST_URL,
|
||||
fetch_barentswatch_access_token,
|
||||
resolve_barentswatch_config,
|
||||
)
|
||||
from app.services.collectors.base import BaseCollector
|
||||
from app.services.collectors.base import BaseCollector, _StoragePolicyDowngradedToSingle
|
||||
from app.services.storage_policy import is_storage_policy_single_violation
|
||||
from app.services.vessel_ais_aggregation import (
|
||||
BARENTSWATCH_DELIVERY_MODE,
|
||||
BARENTSWATCH_TRANSPORT,
|
||||
prune_expired_vessel_track_points,
|
||||
record_vessel_ais_observation,
|
||||
update_ais_source_health,
|
||||
)
|
||||
@@ -80,12 +84,87 @@ class VesselAISCollector(BaseCollector):
|
||||
transformed.append(record)
|
||||
return transformed
|
||||
|
||||
async def _has_existing_current_data(self, db: AsyncSession | None) -> bool:
|
||||
if db is None or not callable(getattr(db, "execute", None)):
|
||||
return False
|
||||
try:
|
||||
result = await db.execute(
|
||||
select(VesselCurrentState.mmsi)
|
||||
.where(VesselCurrentState.source == self.name)
|
||||
.limit(1)
|
||||
)
|
||||
except Exception:
|
||||
return False
|
||||
if result is None or not callable(getattr(result, "scalar_one_or_none", None)):
|
||||
return False
|
||||
return result.scalar_one_or_none() is not None
|
||||
|
||||
async def _save_data(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
data: list[dict[str, Any]],
|
||||
task_id: int | None = None,
|
||||
snapshot_id: int | None = None,
|
||||
) -> int:
|
||||
if callable(getattr(db, "execute", None)):
|
||||
mode, _ = await self._resolve_storage_policy(db)
|
||||
else:
|
||||
mode = self._snapshot_mode or "single"
|
||||
if self._fetch_is_sample_fallback and await self._has_existing_current_data(db):
|
||||
raise RuntimeError(
|
||||
f"Collector {self.name} refused to save sample fallback data over existing vessels"
|
||||
)
|
||||
persist_raw = mode == "history"
|
||||
snapshot_id = await self._reconcile_snapshot_for_mode_switch(
|
||||
db,
|
||||
mode=mode,
|
||||
task_id=task_id,
|
||||
snapshot_id=snapshot_id,
|
||||
)
|
||||
|
||||
try:
|
||||
records_added = await self._write_ais_batch(
|
||||
db,
|
||||
data,
|
||||
persist_raw=persist_raw,
|
||||
mode=mode,
|
||||
snapshot_id=snapshot_id,
|
||||
)
|
||||
if persist_raw:
|
||||
await self._assert_versioned_publish_allowed(db, snapshot_id=snapshot_id)
|
||||
await db.commit()
|
||||
except Exception as exc:
|
||||
if (
|
||||
(not isinstance(exc, _StoragePolicyDowngradedToSingle) and not is_storage_policy_single_violation(exc))
|
||||
or self._previous_current_snapshot_id is None
|
||||
):
|
||||
raise
|
||||
downgraded_snapshot_id = await self._downgrade_pending_snapshot_to_single(
|
||||
db,
|
||||
task_id=task_id,
|
||||
snapshot_id=snapshot_id,
|
||||
)
|
||||
records_added = await self._write_ais_batch(
|
||||
db,
|
||||
data,
|
||||
persist_raw=False,
|
||||
mode="single",
|
||||
snapshot_id=downgraded_snapshot_id,
|
||||
)
|
||||
await db.commit()
|
||||
|
||||
await self._broadcast_vessel_snapshot(data)
|
||||
await self.update_progress(records_added, force=True)
|
||||
return records_added
|
||||
|
||||
async def _write_ais_batch(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
data: list[dict[str, Any]],
|
||||
*,
|
||||
persist_raw: bool,
|
||||
mode: str,
|
||||
snapshot_id: int | None,
|
||||
) -> int:
|
||||
now = datetime.now(UTC)
|
||||
records_added = 0
|
||||
@@ -101,11 +180,15 @@ class VesselAISCollector(BaseCollector):
|
||||
transport=BARENTSWATCH_TRANSPORT,
|
||||
observed_at=observed_at,
|
||||
collected_at=now,
|
||||
persist_raw=persist_raw,
|
||||
)
|
||||
records_added += 1
|
||||
|
||||
if (index + 1) % 1000 == 0:
|
||||
await self.update_progress(index + 1, commit=True)
|
||||
await self.update_progress(index + 1, commit=False)
|
||||
|
||||
if not persist_raw:
|
||||
await prune_expired_vessel_track_points(db, now=now)
|
||||
|
||||
latest_observed_at = max(
|
||||
(item.get("received_at") for item in data if item.get("received_at")),
|
||||
@@ -125,6 +208,7 @@ class VesselAISCollector(BaseCollector):
|
||||
|
||||
snapshot = await db.get(DataSnapshot, snapshot_id)
|
||||
if snapshot:
|
||||
await self._promote_snapshot_to_current(db, snapshot)
|
||||
snapshot.record_count = records_added
|
||||
snapshot.status = SnapshotStatus.SUCCESS.value
|
||||
snapshot.completed_at = now
|
||||
@@ -133,11 +217,9 @@ class VesselAISCollector(BaseCollector):
|
||||
"updated": 0,
|
||||
"unchanged": 0,
|
||||
"deleted": 0,
|
||||
"storage": "ais_raw_observations",
|
||||
"storage": "ais_raw_observations" if persist_raw else "vessel_current_state_and_24h_track",
|
||||
"storage_mode": mode,
|
||||
}
|
||||
await db.commit()
|
||||
await self._broadcast_vessel_snapshot(data)
|
||||
await self.update_progress(records_added, force=True)
|
||||
return records_added
|
||||
|
||||
async def _broadcast_vessel_snapshot(self, data: list[dict[str, Any]]) -> None:
|
||||
@@ -219,6 +301,7 @@ class VesselAISCollector(BaseCollector):
|
||||
}
|
||||
|
||||
def _get_sample_data(self) -> list[dict[str, Any]]:
|
||||
self._mark_sample_fallback("barentswatch_vessels_sample_fallback")
|
||||
return [
|
||||
{
|
||||
"mmsi": 257123000,
|
||||
|
||||
@@ -299,47 +299,80 @@ async def persist_mapped_records(
|
||||
mapping_version: int,
|
||||
delivery_mode: str | None = None,
|
||||
transport: str | None = None,
|
||||
snapshot_mode: str | None = None,
|
||||
) -> int:
|
||||
"""Persist validated mapped records to the destination for a target schema."""
|
||||
from app.services.storage_policy import (
|
||||
acquire_storage_policy_publish_lock,
|
||||
compute_record_content_hash,
|
||||
resolve_collector_storage_policy,
|
||||
)
|
||||
|
||||
can_query_db = callable(getattr(db, "execute", None))
|
||||
if can_query_db:
|
||||
resolved_mode, policy = await resolve_collector_storage_policy(db, datasource_name)
|
||||
if policy.get("global_single_lock"):
|
||||
effective_mode = "single"
|
||||
elif snapshot_mode is not None:
|
||||
effective_mode = snapshot_mode
|
||||
else:
|
||||
effective_mode = resolved_mode
|
||||
else:
|
||||
effective_mode = snapshot_mode or "single"
|
||||
|
||||
if target_schema == "vessel_ais":
|
||||
from app.core.time import to_iso8601_utc
|
||||
from app.core.websocket.broadcaster import broadcaster
|
||||
from app.services.vessel_ais_aggregation import (
|
||||
prune_expired_vessel_track_points,
|
||||
record_vessel_ais_observation,
|
||||
update_ais_source_health,
|
||||
)
|
||||
|
||||
now = datetime.now(UTC)
|
||||
latest_observed_at = now
|
||||
written_count = 0
|
||||
for record in records:
|
||||
observed_at = _parse_datetime(record.get("received_at")) or now
|
||||
observation = await record_vessel_ais_observation(
|
||||
for attempt in range(2):
|
||||
now = datetime.now(UTC)
|
||||
latest_observed_at = now
|
||||
written_count = 0
|
||||
persist_raw = effective_mode == "history"
|
||||
for record in records:
|
||||
observed_at = _parse_datetime(record.get("received_at")) or now
|
||||
observation = await record_vessel_ais_observation(
|
||||
db,
|
||||
source=datasource_name,
|
||||
normalized_payload=record,
|
||||
raw_payload=record,
|
||||
delivery_mode=delivery_mode or "polling",
|
||||
transport=transport or "http",
|
||||
message_type="PositionReport",
|
||||
observed_at=observed_at,
|
||||
collected_at=now,
|
||||
persist_raw=persist_raw,
|
||||
)
|
||||
if observation is not None:
|
||||
written_count += 1
|
||||
if observed_at > latest_observed_at:
|
||||
latest_observed_at = observed_at
|
||||
|
||||
if not persist_raw:
|
||||
await prune_expired_vessel_track_points(db, now=now)
|
||||
|
||||
await update_ais_source_health(
|
||||
db,
|
||||
source=datasource_name,
|
||||
normalized_payload=record,
|
||||
raw_payload=record,
|
||||
delivery_mode=delivery_mode or "polling",
|
||||
transport=transport or "http",
|
||||
message_type="PositionReport",
|
||||
observed_at=observed_at,
|
||||
collected_at=now,
|
||||
connection_state="connected",
|
||||
observed_count=len(records),
|
||||
last_seen_at=latest_observed_at,
|
||||
last_success_at=now if records else None,
|
||||
lag_seconds=max((now - latest_observed_at).total_seconds(), 0),
|
||||
)
|
||||
if observation is not None:
|
||||
written_count += 1
|
||||
if observed_at > latest_observed_at:
|
||||
latest_observed_at = observed_at
|
||||
|
||||
await update_ais_source_health(
|
||||
db,
|
||||
source=datasource_name,
|
||||
connection_state="connected",
|
||||
observed_count=len(records),
|
||||
last_seen_at=latest_observed_at,
|
||||
last_success_at=now if records else None,
|
||||
lag_seconds=max((now - latest_observed_at).total_seconds(), 0),
|
||||
)
|
||||
await db.commit()
|
||||
if persist_raw and can_query_db and attempt == 0:
|
||||
latest_mode, _ = await acquire_storage_policy_publish_lock(db, datasource_name)
|
||||
if latest_mode == "single":
|
||||
await db.rollback()
|
||||
effective_mode = "single"
|
||||
continue
|
||||
await db.commit()
|
||||
break
|
||||
if records:
|
||||
await broadcaster.broadcast_custom(
|
||||
"vessels",
|
||||
@@ -369,9 +402,11 @@ async def persist_mapped_records(
|
||||
)
|
||||
return written_count
|
||||
|
||||
from sqlalchemy import select
|
||||
from app.models.collected_data import CollectedData
|
||||
|
||||
collected_at = datetime.now(UTC)
|
||||
prepared_by_key: dict[str, dict[str, Any]] = {}
|
||||
for index, record in enumerate(records):
|
||||
if target_schema == "geo_points":
|
||||
source_id = record.get("source_id") or f"{datasource_config_id}:{index}"
|
||||
@@ -383,6 +418,7 @@ async def persist_mapped_records(
|
||||
"mapping_version": mapping_version,
|
||||
"target_schema": target_schema,
|
||||
**(record.get("metadata") or {}),
|
||||
"datasource_config_id": datasource_config_id,
|
||||
}
|
||||
reference_date = _parse_datetime(record.get("observed_at"))
|
||||
else:
|
||||
@@ -392,26 +428,147 @@ async def persist_mapped_records(
|
||||
"data": record.get("data") or {},
|
||||
"mapping_version": mapping_version,
|
||||
"target_schema": target_schema,
|
||||
"datasource_config_id": datasource_config_id,
|
||||
}
|
||||
reference_date = _parse_datetime(record.get("observed_at"))
|
||||
|
||||
db.add(
|
||||
CollectedData(
|
||||
source=datasource_name,
|
||||
source_id=str(source_id),
|
||||
entity_key=f"{datasource_name}:{source_id}",
|
||||
data_type=target_schema,
|
||||
name=name,
|
||||
title=name,
|
||||
extra_data=metadata,
|
||||
collected_at=collected_at,
|
||||
reference_date=reference_date,
|
||||
is_valid=1,
|
||||
is_current=True,
|
||||
change_type="created",
|
||||
change_summary={},
|
||||
)
|
||||
source_id_str = str(source_id)
|
||||
# Scope entity identity by datasource_config_id so same-named configs stay isolated.
|
||||
entity_key = f"datasource_config:{datasource_config_id}:{source_id_str}"
|
||||
content_hash = compute_record_content_hash(
|
||||
{
|
||||
"name": name,
|
||||
"title": name,
|
||||
"metadata": metadata,
|
||||
"reference_date": reference_date.isoformat() if reference_date else None,
|
||||
}
|
||||
)
|
||||
prepared_by_key[entity_key] = {
|
||||
"source_id": source_id_str,
|
||||
"entity_key": entity_key,
|
||||
"name": name,
|
||||
"metadata": metadata,
|
||||
"reference_date": reference_date,
|
||||
"content_hash": content_hash,
|
||||
}
|
||||
|
||||
await db.commit()
|
||||
return len(records)
|
||||
if not prepared_by_key:
|
||||
return 0
|
||||
|
||||
if not can_query_db:
|
||||
for item in prepared_by_key.values():
|
||||
db.add(
|
||||
CollectedData(
|
||||
source=datasource_name,
|
||||
source_id=item["source_id"],
|
||||
entity_key=item["entity_key"],
|
||||
data_type=target_schema,
|
||||
name=item["name"],
|
||||
title=item["name"],
|
||||
extra_data=item["metadata"],
|
||||
collected_at=collected_at,
|
||||
reference_date=item["reference_date"],
|
||||
is_valid=1,
|
||||
is_current=True,
|
||||
change_type="created",
|
||||
change_summary={},
|
||||
content_hash=item["content_hash"],
|
||||
)
|
||||
)
|
||||
await db.commit()
|
||||
return len(prepared_by_key)
|
||||
|
||||
for attempt in range(2):
|
||||
existing_result = await db.execute(
|
||||
select(CollectedData)
|
||||
.where(
|
||||
CollectedData.source == datasource_name,
|
||||
CollectedData.entity_key.in_(list(prepared_by_key.keys())),
|
||||
CollectedData.is_current.is_(True),
|
||||
CollectedData.deleted_at.is_(None),
|
||||
)
|
||||
.order_by(CollectedData.id.desc())
|
||||
)
|
||||
existing_by_key: dict[str, CollectedData] = {}
|
||||
for row in existing_result.scalars().all():
|
||||
if row.entity_key not in existing_by_key:
|
||||
existing_by_key[row.entity_key] = row
|
||||
else:
|
||||
row.is_current = False
|
||||
|
||||
if effective_mode == "history":
|
||||
pending_inserts: list[tuple[str, dict[str, Any], CollectedData | None]] = []
|
||||
for entity_key, item in prepared_by_key.items():
|
||||
prev = existing_by_key.get(entity_key)
|
||||
if prev is not None and prev.content_hash == item["content_hash"]:
|
||||
continue
|
||||
if prev is not None:
|
||||
prev.is_current = False
|
||||
pending_inserts.append((entity_key, item, prev))
|
||||
if pending_inserts and hasattr(db, "flush"):
|
||||
await db.flush()
|
||||
for entity_key, item, prev in pending_inserts:
|
||||
db.add(
|
||||
CollectedData(
|
||||
source=datasource_name,
|
||||
source_id=item["source_id"],
|
||||
entity_key=entity_key,
|
||||
data_type=target_schema,
|
||||
name=item["name"],
|
||||
title=item["name"],
|
||||
extra_data=item["metadata"],
|
||||
collected_at=collected_at,
|
||||
reference_date=item["reference_date"],
|
||||
is_valid=1,
|
||||
is_current=True,
|
||||
previous_record_id=prev.id if prev is not None else None,
|
||||
change_type="created" if prev is None else "updated",
|
||||
change_summary={},
|
||||
content_hash=item["content_hash"],
|
||||
)
|
||||
)
|
||||
if attempt == 0:
|
||||
latest_mode, _ = await acquire_storage_policy_publish_lock(db, datasource_name)
|
||||
if latest_mode == "single":
|
||||
await db.rollback()
|
||||
effective_mode = "single"
|
||||
continue
|
||||
else:
|
||||
for entity_key, item in prepared_by_key.items():
|
||||
existing = existing_by_key.get(entity_key)
|
||||
if existing is None:
|
||||
db.add(
|
||||
CollectedData(
|
||||
source=datasource_name,
|
||||
source_id=item["source_id"],
|
||||
entity_key=entity_key,
|
||||
data_type=target_schema,
|
||||
name=item["name"],
|
||||
title=item["name"],
|
||||
extra_data=item["metadata"],
|
||||
collected_at=collected_at,
|
||||
reference_date=item["reference_date"],
|
||||
is_valid=1,
|
||||
is_current=True,
|
||||
previous_record_id=None,
|
||||
change_type="created",
|
||||
change_summary={},
|
||||
content_hash=item["content_hash"],
|
||||
)
|
||||
)
|
||||
elif existing.content_hash != item["content_hash"]:
|
||||
existing.source_id = item["source_id"]
|
||||
existing.data_type = target_schema
|
||||
existing.name = item["name"]
|
||||
existing.title = item["name"]
|
||||
existing.extra_data = item["metadata"]
|
||||
existing.collected_at = collected_at
|
||||
existing.reference_date = item["reference_date"]
|
||||
existing.is_current = True
|
||||
existing.previous_record_id = None
|
||||
existing.change_type = "updated"
|
||||
existing.content_hash = item["content_hash"]
|
||||
|
||||
await db.commit()
|
||||
break
|
||||
return len(prepared_by_key)
|
||||
@@ -172,18 +172,27 @@ async def clear_derived_datasource_data(db: AsyncSession, source: str) -> dict[s
|
||||
from app.models.bgp_anomaly import BGPAnomaly
|
||||
from app.models.bgp_incident import BGPIncident
|
||||
from app.models.bgp_observation import BGPObservation
|
||||
from app.models.vessel import AISConflictRecord, AISRawObservation, AISSourceHealth
|
||||
from app.models.vessel import (
|
||||
AISConflictRecord,
|
||||
AISRawObservation,
|
||||
AISSourceHealth,
|
||||
VesselCurrentState,
|
||||
)
|
||||
|
||||
model_by_key: dict[str, Any] = {
|
||||
"bgp_observations": BGPObservation,
|
||||
"bgp_anomalies": BGPAnomaly,
|
||||
"bgp_incidents": BGPIncident,
|
||||
"ais_raw_observations": AISRawObservation,
|
||||
"vessel_current_state": VesselCurrentState,
|
||||
"ais_conflict_records": AISConflictRecord,
|
||||
"ais_source_health": AISSourceHealth,
|
||||
}
|
||||
deleted_counts: dict[str, int] = {}
|
||||
for key in adapter.derived_models:
|
||||
keys_to_clear = list(adapter.derived_models)
|
||||
if "ais_raw_observations" in keys_to_clear and "vessel_current_state" not in keys_to_clear:
|
||||
keys_to_clear.append("vessel_current_state")
|
||||
for key in keys_to_clear:
|
||||
model = model_by_key.get(key)
|
||||
if model is None:
|
||||
continue
|
||||
|
||||
@@ -1,16 +1,18 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections import OrderedDict
|
||||
from collections.abc import Awaitable, Callable
|
||||
from contextlib import suppress
|
||||
from dataclasses import dataclass, replace
|
||||
import gzip
|
||||
import hashlib
|
||||
import json
|
||||
import time
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
from fastapi import HTTPException, Response
|
||||
from fastapi import HTTPException, Request, Response
|
||||
|
||||
from app.core.cache import _RedisClient
|
||||
from app.core.config import settings
|
||||
@@ -27,6 +29,8 @@ DEFAULT_MAX_FEATURES = 5000
|
||||
DEFAULT_MAX_BYTES = 5 * 1024 * 1024
|
||||
DEFAULT_BBOX_PRECISION_DEGREES = 0.1
|
||||
DEV_CACHE_KEY_HEADER = {"development", "dev", "test", "testing", "local"}
|
||||
ENCODED_ARTIFACT_CACHE_MAX_ENTRIES = 8
|
||||
GZIP_COMPRESS_LEVEL = 5
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -49,6 +53,25 @@ class EarthLayerCacheResult:
|
||||
bytes: int
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _EncodedLayerArtifact:
|
||||
raw_bytes: bytes
|
||||
gzip_bytes: bytes
|
||||
etag: str
|
||||
features: int
|
||||
byte_length: int
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EarthLayerEncodedResult:
|
||||
artifact: _EncodedLayerArtifact
|
||||
state: str
|
||||
key: str
|
||||
|
||||
|
||||
_ENCODED_ARTIFACT_CACHE: OrderedDict[tuple[str, str], _EncodedLayerArtifact] = OrderedDict()
|
||||
|
||||
|
||||
class EarthLayerCache:
|
||||
def __init__(self) -> None:
|
||||
self._client = None
|
||||
@@ -81,6 +104,16 @@ class EarthLayerCache:
|
||||
digest = hashlib.sha256(key.encode("utf-8")).hexdigest()[:32]
|
||||
return f"{EARTH_LAYER_LOCK_PREFIX}:{digest}"
|
||||
|
||||
def get_raw(self, key: str) -> bytes | None:
|
||||
raw = self.client.get(key)
|
||||
if not raw:
|
||||
return None
|
||||
if isinstance(raw, bytes):
|
||||
return raw
|
||||
if isinstance(raw, str):
|
||||
return raw.encode("utf-8")
|
||||
return None
|
||||
|
||||
def get_json(self, key: str) -> dict[str, Any] | None:
|
||||
raw = self.client.get(key)
|
||||
if not raw:
|
||||
@@ -191,15 +224,143 @@ def format_bbox_key(bbox: tuple[float, float, float, float]) -> str:
|
||||
return ",".join(f"{value:.1f}" for value in bbox)
|
||||
|
||||
|
||||
def apply_cache_headers(response: Response | None, result: EarthLayerCacheResult) -> None:
|
||||
if response is None:
|
||||
return
|
||||
response.headers["X-Planet-Cache"] = result.state
|
||||
response.headers["X-Planet-Cache-Features"] = str(result.features)
|
||||
response.headers["X-Planet-Cache-Bytes"] = str(result.bytes)
|
||||
def _cache_headers(
|
||||
result: EarthLayerCacheResult | EarthLayerEncodedResult,
|
||||
) -> dict[str, str]:
|
||||
if isinstance(result, EarthLayerEncodedResult):
|
||||
features, byte_length = result.artifact.features, result.artifact.byte_length
|
||||
else:
|
||||
features, byte_length = result.features, result.bytes
|
||||
headers = {
|
||||
"X-Planet-Cache": result.state,
|
||||
"X-Planet-Cache-Features": str(features),
|
||||
"X-Planet-Cache-Bytes": str(byte_length),
|
||||
}
|
||||
env_name = str(getattr(settings, "ENVIRONMENT", "") or "development").lower()
|
||||
if env_name in DEV_CACHE_KEY_HEADER:
|
||||
response.headers["X-Planet-Cache-Key"] = result.key
|
||||
headers["X-Planet-Cache-Key"] = result.key
|
||||
return headers
|
||||
|
||||
|
||||
def apply_cache_headers(
|
||||
response: Response | None,
|
||||
result: EarthLayerCacheResult | EarthLayerEncodedResult,
|
||||
) -> None:
|
||||
if response is not None:
|
||||
response.headers.update(_cache_headers(result))
|
||||
|
||||
|
||||
def _etag_matches(if_none_match: str | None, etag: str) -> bool:
|
||||
if not if_none_match:
|
||||
return False
|
||||
normalized_target = etag.strip()
|
||||
if normalized_target.startswith("W/"):
|
||||
normalized_target = normalized_target[2:].strip()
|
||||
for candidate in if_none_match.split(","):
|
||||
token = candidate.strip()
|
||||
if token == "*":
|
||||
return True
|
||||
if token.startswith("W/"):
|
||||
token = token[2:].strip()
|
||||
if token == normalized_target:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _encode_layer_bytes(
|
||||
key: str,
|
||||
raw_bytes: bytes,
|
||||
*,
|
||||
features: int | None = None,
|
||||
) -> _EncodedLayerArtifact:
|
||||
etag = f'"{hashlib.sha256(raw_bytes).hexdigest()[:24]}"'
|
||||
cache_key = (key, etag)
|
||||
cached = _ENCODED_ARTIFACT_CACHE.get(cache_key)
|
||||
if cached is not None:
|
||||
_ENCODED_ARTIFACT_CACHE.move_to_end(cache_key)
|
||||
return cached
|
||||
|
||||
resolved_features = features
|
||||
if resolved_features is None:
|
||||
parsed = json.loads(raw_bytes)
|
||||
if not isinstance(parsed, dict):
|
||||
raise ValueError("Earth layer cache payload must be a JSON object")
|
||||
resolved_features = _feature_count(parsed)
|
||||
|
||||
gzip_bytes = gzip.compress(raw_bytes, compresslevel=GZIP_COMPRESS_LEVEL)
|
||||
artifact = _EncodedLayerArtifact(
|
||||
raw_bytes=raw_bytes,
|
||||
gzip_bytes=gzip_bytes,
|
||||
etag=etag,
|
||||
features=resolved_features,
|
||||
byte_length=len(raw_bytes),
|
||||
)
|
||||
_ENCODED_ARTIFACT_CACHE[cache_key] = artifact
|
||||
while len(_ENCODED_ARTIFACT_CACHE) > ENCODED_ARTIFACT_CACHE_MAX_ENTRIES:
|
||||
_ENCODED_ARTIFACT_CACHE.popitem(last=False)
|
||||
return artifact
|
||||
|
||||
|
||||
async def resolve_layer_encoded_payload(
|
||||
*,
|
||||
key: str,
|
||||
policy: EarthLayerCachePolicy,
|
||||
builder: Callable[[], Awaitable[dict[str, Any]]],
|
||||
) -> EarthLayerEncodedResult:
|
||||
flight_key = (asyncio.get_running_loop(), key)
|
||||
if flight_key not in earth_layer_cache._inflight:
|
||||
cached_raw = None
|
||||
with suppress(Exception):
|
||||
cached_raw = earth_layer_cache.get_raw(key)
|
||||
if cached_raw is not None:
|
||||
try:
|
||||
artifact = _encode_layer_bytes(key, cached_raw)
|
||||
return EarthLayerEncodedResult(artifact=artifact, state="hit", key=key)
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Invalid raw earth layer cache payload; falling back to standard resolver",
|
||||
event="earth_layer_cache.raw_decode_failed",
|
||||
context={"key": key, "error": str(exc)},
|
||||
)
|
||||
|
||||
result = await resolve_layer_payload(key=key, policy=policy, builder=builder)
|
||||
raw_bytes = json.dumps(result.payload, ensure_ascii=False, default=str).encode("utf-8")
|
||||
artifact = _encode_layer_bytes(key, raw_bytes, features=result.features)
|
||||
return EarthLayerEncodedResult(artifact=artifact, state=result.state, key=result.key)
|
||||
|
||||
|
||||
async def get_or_build_layer_response(
|
||||
*,
|
||||
key: str,
|
||||
policy: EarthLayerCachePolicy,
|
||||
builder: Callable[[], Awaitable[dict[str, Any]]],
|
||||
request: Request,
|
||||
response: Response | None = None,
|
||||
) -> Response:
|
||||
result = await resolve_layer_encoded_payload(key=key, policy=policy, builder=builder)
|
||||
headers = _cache_headers(result)
|
||||
if response is not None:
|
||||
response.headers.update(headers)
|
||||
headers.update({
|
||||
"ETag": result.artifact.etag,
|
||||
"Cache-Control": "private, no-cache",
|
||||
"Vary": "Accept-Encoding",
|
||||
})
|
||||
if _etag_matches(request.headers.get("if-none-match"), result.artifact.etag):
|
||||
return Response(status_code=304, headers=headers)
|
||||
|
||||
accept_encoding = (request.headers.get("accept-encoding") or "").lower()
|
||||
if "gzip" in accept_encoding:
|
||||
return Response(
|
||||
content=result.artifact.gzip_bytes,
|
||||
media_type="application/json",
|
||||
headers={**headers, "Content-Encoding": "gzip"},
|
||||
)
|
||||
return Response(
|
||||
content=result.artifact.raw_bytes,
|
||||
media_type="application/json",
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
|
||||
async def get_or_build_layer_payload(
|
||||
@@ -262,9 +423,11 @@ async def _resolve_layer_payload(
|
||||
try:
|
||||
async with asyncio.timeout(policy.build_wait_seconds):
|
||||
while True:
|
||||
cached = earth_layer_cache.get_json(key)
|
||||
if cached is not None:
|
||||
return _result(cached, state="hit", key=key)
|
||||
cached_raw = earth_layer_cache.get_raw(key)
|
||||
if cached_raw is not None:
|
||||
cached = json.loads(cached_raw)
|
||||
if isinstance(cached, dict):
|
||||
return _result(cached, state="hit", key=key, byte_length=len(cached_raw))
|
||||
token = earth_layer_cache.acquire_lock(key, policy.lock_ttl_seconds)
|
||||
if token is not None:
|
||||
break
|
||||
@@ -454,13 +617,19 @@ def _with_budget_diagnostics(
|
||||
return {**payload, "diagnostics": diagnostics}
|
||||
|
||||
|
||||
def _result(payload: dict[str, Any], *, state: str, key: str) -> EarthLayerCacheResult:
|
||||
def _result(
|
||||
payload: dict[str, Any],
|
||||
*,
|
||||
state: str,
|
||||
key: str,
|
||||
byte_length: int | None = None,
|
||||
) -> EarthLayerCacheResult:
|
||||
return EarthLayerCacheResult(
|
||||
payload=payload,
|
||||
state=state,
|
||||
key=key,
|
||||
features=_feature_count(payload),
|
||||
bytes=_payload_size(payload),
|
||||
bytes=_payload_size(payload) if byte_length is None else byte_length,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -20,26 +20,47 @@ SUPPORTED_PROVIDER_APIS = {
|
||||
"anthropic-messages",
|
||||
"ollama-generate",
|
||||
}
|
||||
OFFICIAL_PUBLIC_CATALOG_HOSTS: dict[str, frozenset[str]] = {
|
||||
"openrouter": frozenset({"openrouter.ai"}),
|
||||
"opencode-go": frozenset({"opencode.ai"}),
|
||||
}
|
||||
|
||||
|
||||
class LLMProviderCatalogError(RuntimeError):
|
||||
"""A safe, user-facing catalog failure with no upstream response or credentials."""
|
||||
|
||||
|
||||
class LLMProviderCatalogConfigError(LLMProviderCatalogError):
|
||||
"""Invalid local catalog configuration or missing required credentials."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ModelCatalog:
|
||||
url: str
|
||||
models: list[str]
|
||||
|
||||
|
||||
def is_official_public_catalog(provider: str, base_url: str) -> bool:
|
||||
provider_key = provider.strip().lower()
|
||||
host = (urlsplit(base_url.strip()).hostname or "").lower()
|
||||
return host in OFFICIAL_PUBLIC_CATALOG_HOSTS.get(provider_key, frozenset())
|
||||
|
||||
|
||||
def catalog_requires_api_key(provider: str, base_url: str, provider_api: str) -> bool:
|
||||
provider_key = provider.strip().lower()
|
||||
if provider_key == "ollama" or provider_api == "ollama-generate":
|
||||
return False
|
||||
return not is_official_public_catalog(provider_key, base_url)
|
||||
|
||||
|
||||
def model_catalog_url(provider: str, base_url: str, provider_api: str) -> str:
|
||||
parts = urlsplit(base_url.strip())
|
||||
if parts.scheme not in {"http", "https"} or not parts.hostname:
|
||||
raise LLMProviderCatalogError("请填写有效的 HTTP(S) 模型基础地址。")
|
||||
raise LLMProviderCatalogConfigError("请填写有效的 HTTP(S) 模型基础地址。")
|
||||
if parts.username or parts.password or parts.query or parts.fragment:
|
||||
raise LLMProviderCatalogError("模型基础地址不能包含账号、密码、查询参数或片段。")
|
||||
raise LLMProviderCatalogConfigError("模型基础地址不能包含账号、密码、查询参数或片段。")
|
||||
if provider_api not in SUPPORTED_PROVIDER_APIS:
|
||||
raise LLMProviderCatalogError("当前接口协议不支持模型目录查询。")
|
||||
raise LLMProviderCatalogConfigError("当前接口协议不支持模型目录查询。")
|
||||
path = parts.path.rstrip("/")
|
||||
if provider_api == "ollama-generate":
|
||||
path = path.removesuffix("/api").removesuffix("/v1") + "/api/tags"
|
||||
@@ -132,21 +153,23 @@ async def fetch_model_catalog(
|
||||
api_key: str = "",
|
||||
anthropic_version: str = "2023-06-01",
|
||||
timeout_seconds: int = CATALOG_TIMEOUT_SECONDS,
|
||||
*,
|
||||
include_auth: bool = True,
|
||||
) -> ModelCatalog:
|
||||
url = model_catalog_url(provider, base_url, provider_api)
|
||||
public_catalog = provider in {"opencode-go", "openrouter"}
|
||||
if not api_key and provider_api != "ollama-generate" and not public_catalog:
|
||||
raise LLMProviderCatalogError("请先配置当前供应商的 API Key,再刷新模型列表。")
|
||||
if not api_key and catalog_requires_api_key(provider, base_url, provider_api):
|
||||
raise LLMProviderCatalogConfigError("请先配置当前供应商的 API Key,再刷新模型列表。")
|
||||
headers = {"User-Agent": "Planet/1.0", "Accept": "application/json"}
|
||||
if provider_api == "anthropic-messages" and provider not in {
|
||||
"opencode-go",
|
||||
"openrouter",
|
||||
"alibaba",
|
||||
"moonshotai",
|
||||
}:
|
||||
headers.update({"x-api-key": api_key, "anthropic-version": anthropic_version})
|
||||
elif api_key:
|
||||
headers["Authorization"] = f"Bearer {api_key}"
|
||||
if include_auth and api_key:
|
||||
if provider_api == "anthropic-messages" and provider not in {
|
||||
"opencode-go",
|
||||
"openrouter",
|
||||
"alibaba",
|
||||
"moonshotai",
|
||||
}:
|
||||
headers.update({"x-api-key": api_key, "anthropic-version": anthropic_version})
|
||||
else:
|
||||
headers["Authorization"] = f"Bearer {api_key}"
|
||||
native_dashscope = provider == "alibaba" and urlsplit(url).hostname.endswith(".aliyuncs.com")
|
||||
params: dict[str, str | int] = {}
|
||||
if native_dashscope:
|
||||
@@ -179,8 +202,8 @@ async def fetch_model_catalog(
|
||||
)
|
||||
# An empty Ollama catalog is valid: no models have been installed yet.
|
||||
if not models and provider_api != "ollama-generate":
|
||||
raise LLMProviderCatalogError("供应商返回了空模型目录,已保留上次模型列表。")
|
||||
raise LLMProviderCatalogError("供应商返回了空模型目录。")
|
||||
return ModelCatalog(url=url, models=models)
|
||||
if len(rows_by_id) == previous_count:
|
||||
raise LLMProviderCatalogError("供应商模型目录分页没有进展,已保留上次模型列表。")
|
||||
raise LLMProviderCatalogError("供应商模型目录分页超过限制,已保留上次模型列表。")
|
||||
raise LLMProviderCatalogError("供应商模型目录分页没有进展。")
|
||||
raise LLMProviderCatalogError("供应商模型目录分页超过限制。")
|
||||
@@ -5,7 +5,7 @@ from __future__ import annotations
|
||||
from typing import Any
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from app.services.llm_model_catalog import fetch_model_catalog
|
||||
from app.services.llm_model_catalog import fetch_model_catalog, is_official_public_catalog
|
||||
|
||||
OPENCODE_GO_MODEL_PROVIDER_APIS = {
|
||||
"minimax-m3": "anthropic-messages",
|
||||
@@ -22,23 +22,31 @@ OPENCODE_GO_MODEL_PROVIDER_APIS = {
|
||||
"minimax-m2.5": "anthropic-messages",
|
||||
}
|
||||
OPENCODE_GO_FALLBACK_MODELS = [
|
||||
"minimax-m3",
|
||||
"kimi-k3",
|
||||
"glm-5.3",
|
||||
"qwen3.8-max",
|
||||
"gpt-5.6-luna",
|
||||
"minimax-m2.7",
|
||||
"minimax-m2.5",
|
||||
"kimi-k2.6",
|
||||
"kimi-k2.5",
|
||||
"glm-5.1",
|
||||
"glm-5",
|
||||
"glm-5.3-flash",
|
||||
"deepseek-v4.1-flash",
|
||||
"deepseek-v4-pro",
|
||||
"deepseek-v4-flash",
|
||||
"qwen3.6-plus",
|
||||
"qwen3.5-plus",
|
||||
"mimo-v2.5-pro",
|
||||
"mimo-v2.5",
|
||||
"kimi-k3.1-pro",
|
||||
"kimi-k3",
|
||||
"kimi-k2.7-code",
|
||||
"minimax-m3",
|
||||
"minimax-m3.1-flash",
|
||||
"qwen4-max",
|
||||
"qwen3.8-max",
|
||||
"qwen3.8-flash",
|
||||
"qwen3.7-plus",
|
||||
"gpt-6-luna",
|
||||
"gpt-5.6-luna",
|
||||
"grok-4.7",
|
||||
"claude-haiku-5-5",
|
||||
"gemini-4-argon",
|
||||
"mimo-v2.6-pro",
|
||||
"mimo-v2.6-flash",
|
||||
"hy4",
|
||||
"hy4-flash-free",
|
||||
"step-5-preview",
|
||||
"muse-spark-1.3-contributor",
|
||||
"muse-spark-1.2-contributor",
|
||||
]
|
||||
|
||||
|
||||
@@ -131,8 +139,14 @@ FALLBACK_LLM_PROVIDER_PRESETS: dict[str, dict[str, Any]] = {
|
||||
"label": "OpenRouter",
|
||||
"provider_api": "openai-completions",
|
||||
"base_url": "https://openrouter.ai/api/v1",
|
||||
"model": "openai/gpt-5.1",
|
||||
"models": ["openai/gpt-5.1", "anthropic/claude-sonnet-4.5", "qwen/qwen3-max"],
|
||||
"model": "openai/gpt-6.2-astra",
|
||||
"models": [
|
||||
"openai/gpt-6.2-astra",
|
||||
"openai/gpt-6.2-sol",
|
||||
"google/gemini-4-neon",
|
||||
"qwen/qwen4-max",
|
||||
"anthropic/claude-sonnet-4.5",
|
||||
],
|
||||
"api_key_env": "OPENROUTER_API_KEY",
|
||||
"source": "fallback",
|
||||
},
|
||||
@@ -141,7 +155,7 @@ FALLBACK_LLM_PROVIDER_PRESETS: dict[str, dict[str, Any]] = {
|
||||
"label": "OpenCode Go",
|
||||
"provider_api": "openai-completions",
|
||||
"base_url": "https://opencode.ai/zen/go/v1",
|
||||
"model": "glm-5.1",
|
||||
"model": "glm-5.3",
|
||||
"models": OPENCODE_GO_FALLBACK_MODELS,
|
||||
"model_provider_apis": OPENCODE_GO_MODEL_PROVIDER_APIS,
|
||||
"api_key_env": "OPENCODE_GO_API_KEY",
|
||||
@@ -195,6 +209,7 @@ async def refresh_llm_provider_preset(
|
||||
resolved_api,
|
||||
api_key or "",
|
||||
anthropic_version,
|
||||
include_auth=not is_official_public_catalog(fallback["provider"], resolved_base_url),
|
||||
)
|
||||
model_provider_apis = (
|
||||
_opencode_go_model_provider_apis(catalog.models)
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
"""Task Scheduler for running collection jobs."""
|
||||
|
||||
import asyncio
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import UTC, datetime, timedelta
|
||||
import time
|
||||
from typing import Any, Dict, Optional
|
||||
import weakref
|
||||
|
||||
from apscheduler.schedulers.asyncio import AsyncIOScheduler
|
||||
from apscheduler.triggers.date import DateTrigger
|
||||
from apscheduler.triggers.interval import IntervalTrigger
|
||||
import asyncpg
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.enums import JobStatus
|
||||
from app.core.logging import get_logger
|
||||
from app.db.session import async_session_factory
|
||||
@@ -37,13 +41,27 @@ from app.services.earth_news_refresh import (
|
||||
REFRESH_STATUS_HEARTBEAT_SECONDS as EARTH_NEWS_STATUS_HEARTBEAT_SECONDS,
|
||||
)
|
||||
from app.services.earth_news import REGION_ANCHORS
|
||||
from app.services.storage_maintenance import run_storage_retention_maintenance
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
scheduler = AsyncIOScheduler()
|
||||
RUNNING_TASK_GUARD_TIMEOUT_MINUTES = 90
|
||||
RUNNING_COLLECTOR_TASKS: dict[str, asyncio.Task[Any]] = {}
|
||||
HEAVY_COLLECTOR_SOURCES: frozenset[str] = frozenset(
|
||||
{"iptoasn_prefix_geo", "nro_delegated_prefix_geo"}
|
||||
)
|
||||
_COLLECTOR_SEMAPHORES: weakref.WeakKeyDictionary[
|
||||
asyncio.AbstractEventLoop, tuple[int, asyncio.Semaphore]
|
||||
] = weakref.WeakKeyDictionary()
|
||||
_HEAVY_COLLECTOR_SEMAPHORES: weakref.WeakKeyDictionary[
|
||||
asyncio.AbstractEventLoop, tuple[int, asyncio.Semaphore]
|
||||
] = weakref.WeakKeyDictionary()
|
||||
EARTH_NEWS_REFRESH_JOB_ID = "earth_news_rss_refresh"
|
||||
STORAGE_RETENTION_JOB_ID = "storage_retention_maintenance"
|
||||
STORAGE_RETENTION_INTERVAL_HOURS = 6
|
||||
SCHEDULER_LEADER_LOCK_KEY = (17001613, 3)
|
||||
_leader_lock_conn: Optional[asyncpg.Connection] = None
|
||||
_pending_earth_news_refreshes: dict[str, dict[str, Any]] = {}
|
||||
_running_earth_news_refreshes: set[str] = set()
|
||||
_rerun_earth_news_refreshes: dict[str, dict[str, Any]] = {}
|
||||
@@ -56,6 +74,45 @@ EARTH_NEWS_REFRESH_PUBLIC_ERRORS = {
|
||||
}
|
||||
|
||||
|
||||
def _get_loop_semaphore(
|
||||
registry: weakref.WeakKeyDictionary[asyncio.AbstractEventLoop, tuple[int, asyncio.Semaphore]],
|
||||
limit: int,
|
||||
) -> asyncio.Semaphore:
|
||||
bounded_limit = max(1, int(limit))
|
||||
loop = asyncio.get_running_loop()
|
||||
existing = registry.get(loop)
|
||||
if existing is None or existing[0] != bounded_limit:
|
||||
semaphore = asyncio.Semaphore(bounded_limit)
|
||||
registry[loop] = (bounded_limit, semaphore)
|
||||
return semaphore
|
||||
return existing[1]
|
||||
|
||||
|
||||
def _get_collector_semaphore() -> asyncio.Semaphore:
|
||||
return _get_loop_semaphore(_COLLECTOR_SEMAPHORES, settings.COLLECTOR_MAX_CONCURRENCY)
|
||||
|
||||
|
||||
def _get_heavy_collector_semaphore() -> asyncio.Semaphore:
|
||||
return _get_loop_semaphore(
|
||||
_HEAVY_COLLECTOR_SEMAPHORES, settings.COLLECTOR_HEAVY_CONCURRENCY
|
||||
)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def _acquire_collector_slots(collector_name: str):
|
||||
"""Serialize heavy collectors first so lightweight collectors are not starved."""
|
||||
heavy_semaphore = (
|
||||
_get_heavy_collector_semaphore() if collector_name in HEAVY_COLLECTOR_SOURCES else None
|
||||
)
|
||||
if heavy_semaphore is not None:
|
||||
async with heavy_semaphore:
|
||||
async with _get_collector_semaphore():
|
||||
yield
|
||||
else:
|
||||
async with _get_collector_semaphore():
|
||||
yield
|
||||
|
||||
|
||||
def _collector_task_name(collector_name: str) -> str:
|
||||
return f"collector:{collector_name}"
|
||||
|
||||
@@ -108,6 +165,9 @@ async def _apply_datasource_schedule(datasource: DataSource, session) -> None:
|
||||
id=datasource.source,
|
||||
name=datasource.name,
|
||||
replace_existing=True,
|
||||
max_instances=1,
|
||||
coalesce=True,
|
||||
misfire_grace_time=300,
|
||||
kwargs={"collector_name": datasource.source},
|
||||
)
|
||||
logger.info_event(
|
||||
@@ -268,7 +328,9 @@ async def run_collector_task(collector_name: str):
|
||||
"status": "running",
|
||||
},
|
||||
)
|
||||
task_result = await collector.run(db)
|
||||
task_result = None
|
||||
async with _acquire_collector_slots(collector_name):
|
||||
task_result = await collector.run(db)
|
||||
datasource = await db.get(DataSource, datasource_id)
|
||||
if datasource is None:
|
||||
logger.error_event(
|
||||
@@ -415,6 +477,60 @@ async def cleanup_stale_running_tasks(max_age_hours: int = 2) -> int:
|
||||
return len(stale_tasks)
|
||||
|
||||
|
||||
async def acquire_scheduler_leader_lock() -> bool:
|
||||
"""Acquire a PostgreSQL session advisory lock so only one instance schedules jobs."""
|
||||
global _leader_lock_conn
|
||||
|
||||
dsn = str(settings.DATABASE_URL or "").replace("postgresql+asyncpg://", "postgresql://", 1)
|
||||
if not dsn.startswith(("postgresql://", "postgres://")):
|
||||
return True
|
||||
|
||||
if _leader_lock_conn is not None and not _leader_lock_conn.is_closed():
|
||||
return True
|
||||
|
||||
try:
|
||||
conn = await asyncpg.connect(dsn, timeout=5.0)
|
||||
acquired = bool(
|
||||
await conn.fetchval("SELECT pg_try_advisory_lock($1, $2)", *SCHEDULER_LEADER_LOCK_KEY)
|
||||
)
|
||||
if acquired:
|
||||
_leader_lock_conn = conn
|
||||
logger.info_event(
|
||||
"Acquired scheduler leader advisory lock",
|
||||
event="scheduler.leader_lock.acquired",
|
||||
)
|
||||
return True
|
||||
await conn.close()
|
||||
return False
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed to acquire scheduler leader lock",
|
||||
event="scheduler.leader_lock.error",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
return False
|
||||
|
||||
|
||||
async def release_scheduler_leader_lock() -> None:
|
||||
"""Release the PostgreSQL scheduler leader advisory lock if held."""
|
||||
global _leader_lock_conn
|
||||
|
||||
conn = _leader_lock_conn
|
||||
_leader_lock_conn = None
|
||||
if conn is None or conn.is_closed():
|
||||
return
|
||||
try:
|
||||
await conn.fetchval("SELECT pg_advisory_unlock($1, $2)", *SCHEDULER_LEADER_LOCK_KEY)
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed to unlock scheduler leader lock cleanly",
|
||||
event="scheduler.leader_lock.unlock_failed",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
finally:
|
||||
await conn.close()
|
||||
|
||||
|
||||
def start_scheduler() -> None:
|
||||
"""Start the scheduler."""
|
||||
if not scheduler.running:
|
||||
@@ -429,6 +545,16 @@ def start_scheduler() -> None:
|
||||
coalesce=True,
|
||||
misfire_grace_time=60,
|
||||
)
|
||||
scheduler.add_job(
|
||||
run_storage_retention_maintenance,
|
||||
trigger=IntervalTrigger(hours=STORAGE_RETENTION_INTERVAL_HOURS),
|
||||
id=STORAGE_RETENTION_JOB_ID,
|
||||
name="Collection storage retention maintenance",
|
||||
replace_existing=True,
|
||||
max_instances=1,
|
||||
coalesce=True,
|
||||
misfire_grace_time=300,
|
||||
)
|
||||
scheduler.start()
|
||||
logger.info_event("Scheduler started", event="scheduler.started")
|
||||
|
||||
@@ -650,7 +776,11 @@ async def sync_scheduler_with_datasources() -> None:
|
||||
is_earth_news_refresh = job.id == EARTH_NEWS_REFRESH_JOB_ID or job.id.startswith(
|
||||
f"{EARTH_NEWS_REFRESH_JOB_ID}:"
|
||||
)
|
||||
if job.id not in configured_sources and not is_earth_news_refresh:
|
||||
if (
|
||||
job.id not in configured_sources
|
||||
and not is_earth_news_refresh
|
||||
and job.id != STORAGE_RETENTION_JOB_ID
|
||||
):
|
||||
scheduler.remove_job(job.id)
|
||||
|
||||
for datasource in datasources:
|
||||
|
||||
@@ -0,0 +1,339 @@
|
||||
"""Opt-in batch storage retention maintenance service."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import delete, func, or_, select, text, update
|
||||
from sqlalchemy.ext.asyncio import AsyncConnection, AsyncEngine, AsyncSession
|
||||
|
||||
from app.core.logging import get_logger
|
||||
from app.db.session import async_session_factory
|
||||
from app.models.bgp_anomaly import BGPAnomaly
|
||||
from app.models.bgp_incident import BGPIncident
|
||||
from app.models.bgp_observation import BGPObservation
|
||||
from app.models.collected_data import CollectedData
|
||||
from app.models.data_snapshot import DataSnapshot
|
||||
from app.models.earth_news import EarthNewsItem
|
||||
from app.models.system_log import ObservabilityEvent, SystemLog
|
||||
from app.models.vessel import AISRawObservation, VesselPosition
|
||||
from app.services.storage_policy import get_storage_policy
|
||||
from app.services.vessel_ais_aggregation import VESSEL_TRACK_RETENTION_HOURS
|
||||
|
||||
logger = get_logger(__name__, service="storage_maintenance")
|
||||
|
||||
STORAGE_MAINTENANCE_LOCK_KEY = (17001614, 1)
|
||||
DEFAULT_BATCH_SIZE = 50_000
|
||||
MAX_BATCHES_PER_TABLE = 20
|
||||
|
||||
|
||||
def _is_postgresql(db: AsyncSession) -> bool:
|
||||
try:
|
||||
bind = db.get_bind()
|
||||
return getattr(getattr(bind, "dialect", None), "name", "") == "postgresql"
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _resolve_async_engine(db: AsyncSession) -> AsyncEngine | None:
|
||||
bound = getattr(db, "bind", None)
|
||||
if isinstance(bound, AsyncEngine):
|
||||
return bound
|
||||
if isinstance(bound, AsyncConnection):
|
||||
return AsyncEngine(bound.engine)
|
||||
return None
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def _storage_maintenance_advisory_lock(db: AsyncSession):
|
||||
"""Hold PostgreSQL session advisory lock on a dedicated connection outside pooled commits."""
|
||||
if not _is_postgresql(db):
|
||||
yield True
|
||||
return
|
||||
|
||||
target_engine = _resolve_async_engine(db)
|
||||
if target_engine is None:
|
||||
from app.db.session import engine as default_engine
|
||||
|
||||
target_engine = default_engine
|
||||
|
||||
async with target_engine.connect() as base_conn:
|
||||
lock_conn = await base_conn.execution_options(isolation_level="AUTOCOMMIT")
|
||||
acquired = False
|
||||
try:
|
||||
result = await lock_conn.execute(
|
||||
text("SELECT pg_try_advisory_lock(:key1, :key2)"),
|
||||
{
|
||||
"key1": STORAGE_MAINTENANCE_LOCK_KEY[0],
|
||||
"key2": STORAGE_MAINTENANCE_LOCK_KEY[1],
|
||||
},
|
||||
)
|
||||
acquired = bool(result.scalar())
|
||||
yield acquired
|
||||
finally:
|
||||
if acquired:
|
||||
try:
|
||||
await lock_conn.execute(
|
||||
text("SELECT pg_advisory_unlock(:key1, :key2)"),
|
||||
{
|
||||
"key1": STORAGE_MAINTENANCE_LOCK_KEY[0],
|
||||
"key2": STORAGE_MAINTENANCE_LOCK_KEY[1],
|
||||
},
|
||||
)
|
||||
except Exception:
|
||||
logger.warning_event(
|
||||
"Failed to release storage retention advisory lock",
|
||||
event="storage.retention.unlock_failed",
|
||||
)
|
||||
|
||||
|
||||
async def _prune_collected_data_for_snapshots(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
snapshot_ids: list[int],
|
||||
batch_size: int,
|
||||
) -> int:
|
||||
if not snapshot_ids:
|
||||
return 0
|
||||
|
||||
deleted_total = 0
|
||||
for _ in range(MAX_BATCHES_PER_TABLE):
|
||||
id_result = await db.execute(
|
||||
select(CollectedData.id)
|
||||
.where(
|
||||
CollectedData.snapshot_id.in_(snapshot_ids),
|
||||
or_(CollectedData.is_current.is_(False), CollectedData.is_current.is_(None)),
|
||||
)
|
||||
.order_by(CollectedData.id.asc())
|
||||
.limit(batch_size)
|
||||
)
|
||||
batch_ids = [int(row_id) for row_id in id_result.scalars().all()]
|
||||
if not batch_ids:
|
||||
break
|
||||
|
||||
await db.execute(
|
||||
update(CollectedData)
|
||||
.where(CollectedData.previous_record_id.in_(batch_ids))
|
||||
.values(previous_record_id=None)
|
||||
)
|
||||
delete_result = await db.execute(
|
||||
delete(CollectedData).where(
|
||||
CollectedData.id.in_(batch_ids),
|
||||
or_(CollectedData.is_current.is_(False), CollectedData.is_current.is_(None)),
|
||||
)
|
||||
)
|
||||
deleted_total += int(delete_result.rowcount or len(batch_ids))
|
||||
await db.commit()
|
||||
if len(batch_ids) < batch_size:
|
||||
break
|
||||
return deleted_total
|
||||
|
||||
|
||||
async def _prune_expired_snapshots(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
history_cutoff: datetime,
|
||||
batch_size: int,
|
||||
) -> tuple[int, int]:
|
||||
candidates_result = await db.execute(
|
||||
select(DataSnapshot)
|
||||
.where(
|
||||
DataSnapshot.is_current.is_(False),
|
||||
func.coalesce(DataSnapshot.completed_at, DataSnapshot.started_at) < history_cutoff,
|
||||
)
|
||||
.order_by(DataSnapshot.id.asc())
|
||||
.limit(1000)
|
||||
)
|
||||
expired_ids = [
|
||||
snapshot.id
|
||||
for snapshot in candidates_result.scalars().all()
|
||||
if not (isinstance(snapshot.summary, dict) and snapshot.summary.get("milestone_year") is not None)
|
||||
]
|
||||
if not expired_ids:
|
||||
return 0, 0
|
||||
|
||||
deleted_collected = await _prune_collected_data_for_snapshots(
|
||||
db,
|
||||
snapshot_ids=expired_ids,
|
||||
batch_size=batch_size,
|
||||
)
|
||||
|
||||
remaining_result = await db.execute(
|
||||
select(CollectedData.snapshot_id)
|
||||
.where(CollectedData.snapshot_id.in_(expired_ids))
|
||||
.distinct()
|
||||
)
|
||||
busy_snapshot_ids = {int(sid) for sid in remaining_result.scalars().all() if sid is not None}
|
||||
removable_snapshot_ids = [sid for sid in expired_ids if sid not in busy_snapshot_ids]
|
||||
if not removable_snapshot_ids:
|
||||
return deleted_collected, 0
|
||||
|
||||
for offset in range(0, len(removable_snapshot_ids), 500):
|
||||
chunk = removable_snapshot_ids[offset : offset + 500]
|
||||
await db.execute(
|
||||
update(DataSnapshot)
|
||||
.where(DataSnapshot.parent_snapshot_id.in_(chunk))
|
||||
.values(parent_snapshot_id=None)
|
||||
)
|
||||
await db.execute(
|
||||
update(BGPObservation)
|
||||
.where(BGPObservation.snapshot_id.in_(chunk))
|
||||
.values(snapshot_id=None)
|
||||
)
|
||||
await db.execute(
|
||||
update(BGPAnomaly)
|
||||
.where(BGPAnomaly.snapshot_id.in_(chunk))
|
||||
.values(snapshot_id=None)
|
||||
)
|
||||
await db.execute(
|
||||
update(BGPIncident)
|
||||
.where(BGPIncident.snapshot_id.in_(chunk))
|
||||
.values(snapshot_id=None)
|
||||
)
|
||||
await db.execute(
|
||||
delete(DataSnapshot).where(
|
||||
DataSnapshot.id.in_(chunk),
|
||||
DataSnapshot.is_current.is_(False),
|
||||
)
|
||||
)
|
||||
await db.commit()
|
||||
return deleted_collected, len(removable_snapshot_ids)
|
||||
|
||||
|
||||
async def _prune_model_by_id(
|
||||
db: AsyncSession,
|
||||
model: Any,
|
||||
*,
|
||||
where_clause: list[Any],
|
||||
batch_size: int,
|
||||
) -> int:
|
||||
deleted_total = 0
|
||||
for _ in range(MAX_BATCHES_PER_TABLE):
|
||||
ids_result = await db.execute(
|
||||
select(model.id)
|
||||
.where(*where_clause)
|
||||
.order_by(model.id.asc())
|
||||
.limit(batch_size)
|
||||
)
|
||||
batch_ids = [row_id for row_id in ids_result.scalars().all()]
|
||||
if not batch_ids:
|
||||
break
|
||||
result = await db.execute(delete(model).where(model.id.in_(batch_ids)))
|
||||
deleted_total += int(result.rowcount or len(batch_ids))
|
||||
await db.commit()
|
||||
if len(batch_ids) < batch_size:
|
||||
break
|
||||
return deleted_total
|
||||
|
||||
|
||||
async def _run_maintenance_with_session(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
batch_size: int,
|
||||
now: datetime | None,
|
||||
) -> dict[str, Any]:
|
||||
policy = await get_storage_policy(db)
|
||||
if not policy.get("auto_prune_enabled", False):
|
||||
logger.info_event(
|
||||
"Skipped storage retention maintenance because auto_prune_enabled is False",
|
||||
event="storage.retention.skipped",
|
||||
context={"reason": "auto_prune_disabled"},
|
||||
)
|
||||
return {"skipped": True, "reason": "auto_prune_disabled", "deleted": {}}
|
||||
|
||||
async with _storage_maintenance_advisory_lock(db) as acquired:
|
||||
if not acquired:
|
||||
logger.info_event(
|
||||
"Skipped storage retention maintenance because another worker holds the lock",
|
||||
event="storage.retention.skipped",
|
||||
context={"reason": "lock_busy"},
|
||||
)
|
||||
return {"skipped": True, "reason": "lock_busy", "deleted": {}}
|
||||
|
||||
ref_now = now or datetime.now(UTC)
|
||||
history_cutoff = ref_now - timedelta(days=int(policy.get("history_retention_days", 30)))
|
||||
bgp_cutoff = ref_now - timedelta(days=int(policy.get("bgp_observation_retention_days", 7)))
|
||||
vessel_track_cutoff = ref_now - timedelta(hours=VESSEL_TRACK_RETENTION_HOURS)
|
||||
|
||||
deleted_collected, deleted_snapshots = await _prune_expired_snapshots(
|
||||
db,
|
||||
history_cutoff=history_cutoff,
|
||||
batch_size=batch_size,
|
||||
)
|
||||
deleted_bgp_observations = await _prune_model_by_id(
|
||||
db,
|
||||
BGPObservation,
|
||||
where_clause=[BGPObservation.observed_at < bgp_cutoff],
|
||||
batch_size=batch_size,
|
||||
)
|
||||
deleted_ais_raw = await _prune_model_by_id(
|
||||
db,
|
||||
AISRawObservation,
|
||||
where_clause=[AISRawObservation.observed_at < history_cutoff],
|
||||
batch_size=batch_size,
|
||||
)
|
||||
deleted_vessel_positions = await _prune_model_by_id(
|
||||
db,
|
||||
VesselPosition,
|
||||
where_clause=[VesselPosition.received_at < vessel_track_cutoff],
|
||||
batch_size=batch_size,
|
||||
)
|
||||
deleted_news_items = await _prune_model_by_id(
|
||||
db,
|
||||
EarthNewsItem,
|
||||
where_clause=[
|
||||
~EarthNewsItem.id.like("manual:%"),
|
||||
func.coalesce(EarthNewsItem.published_at, EarthNewsItem.last_seen_at)
|
||||
< history_cutoff,
|
||||
],
|
||||
batch_size=batch_size,
|
||||
)
|
||||
deleted_system_logs = await _prune_model_by_id(
|
||||
db,
|
||||
SystemLog,
|
||||
where_clause=[SystemLog.occurred_at < history_cutoff],
|
||||
batch_size=batch_size,
|
||||
)
|
||||
deleted_observability_events = await _prune_model_by_id(
|
||||
db,
|
||||
ObservabilityEvent,
|
||||
where_clause=[ObservabilityEvent.occurred_at < history_cutoff],
|
||||
batch_size=batch_size,
|
||||
)
|
||||
|
||||
deleted_counts = {
|
||||
"collected_data": deleted_collected,
|
||||
"data_snapshots": deleted_snapshots,
|
||||
"bgp_observations": deleted_bgp_observations,
|
||||
"ais_raw_observations": deleted_ais_raw,
|
||||
"vessel_positions": deleted_vessel_positions,
|
||||
"earth_news_items": deleted_news_items,
|
||||
"system_logs": deleted_system_logs,
|
||||
"observability_events": deleted_observability_events,
|
||||
}
|
||||
logger.info_event(
|
||||
"Completed storage retention maintenance",
|
||||
event="storage.retention.completed",
|
||||
context={
|
||||
"history_retention_days": policy["history_retention_days"],
|
||||
"bgp_observation_retention_days": policy["bgp_observation_retention_days"],
|
||||
"deleted": deleted_counts,
|
||||
},
|
||||
)
|
||||
return {"skipped": False, "deleted": deleted_counts}
|
||||
|
||||
|
||||
async def run_storage_retention_maintenance(
|
||||
db: AsyncSession | None = None,
|
||||
*,
|
||||
batch_size: int = DEFAULT_BATCH_SIZE,
|
||||
now: datetime | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Run batch storage retention cleanup when `auto_prune_enabled` is enabled."""
|
||||
if db is not None:
|
||||
return await _run_maintenance_with_session(db, batch_size=batch_size, now=now)
|
||||
|
||||
async with async_session_factory() as session:
|
||||
return await _run_maintenance_with_session(session, batch_size=batch_size, now=now)
|
||||
@@ -0,0 +1,523 @@
|
||||
"""Unified collection storage & snapshot retention policy service."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from copy import deepcopy
|
||||
import hashlib
|
||||
import json
|
||||
from typing import Any, Callable, Iterable, Literal
|
||||
|
||||
from sqlalchemy import select, text
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.logging import get_logger
|
||||
from app.models.system_setting import SystemSetting
|
||||
|
||||
logger = get_logger(__name__, service="storage_policy")
|
||||
|
||||
SnapshotMode = Literal["single", "annual", "history"]
|
||||
GlobalSnapshotAction = Literal["all_single", "all_history", "recommended_default"]
|
||||
|
||||
|
||||
class StoragePolicyLockedError(ValueError):
|
||||
"""Raised when a per-source snapshot override violates global all-single lock."""
|
||||
|
||||
STORAGE_POLICY_CATEGORY = "collection_storage"
|
||||
STORAGE_POLICY_TX_LOCK_KEY = (17001614, 2)
|
||||
STORAGE_POLICY_SINGLE_VIOLATION_CODE = "planet_storage_policy_single_violation"
|
||||
VALID_SNAPSHOT_MODES: tuple[SnapshotMode, ...] = ("single", "annual", "history")
|
||||
ANNUAL_ELIGIBLE_SOURCES: frozenset[str] = frozenset({"top500", "epoch_ai_gpu"})
|
||||
|
||||
HIGH_VOLUME_SOURCES: dict[str, dict[str, str]] = {
|
||||
"iptoasn_prefix_geo": {
|
||||
"estimated_monthly_growth": "~14 GB / 月",
|
||||
"note": "全量 IPv4/IPv6 ASN 前缀约 72 万行,每 6 小时重采开启历史快照将快速膨胀",
|
||||
},
|
||||
"nro_delegated_prefix_geo": {
|
||||
"estimated_monthly_growth": "~12 GB / 月",
|
||||
"note": "五大 RIR IP 分配表约 65 万行,每 12 小时全量落盘对磁盘与触发器压力较大",
|
||||
},
|
||||
"barentswatch_vessels": {
|
||||
"estimated_monthly_growth": "~25 GB / 月",
|
||||
"note": "每 5 分钟拉取近实时 AIS 报文,开启历史快照将持续写入 ais_raw_observations",
|
||||
},
|
||||
"aisstream_vessels": {
|
||||
"estimated_monthly_growth": "~15 GB / 月",
|
||||
"note": "WebSocket 高频 AIS 报文流,开启历史快照将高频写入 ais_raw_observations",
|
||||
},
|
||||
}
|
||||
|
||||
DEFAULT_RECOMMENDED_OVERRIDES: dict[str, SnapshotMode] = {
|
||||
"top500": "annual",
|
||||
"epoch_ai_gpu": "annual",
|
||||
}
|
||||
|
||||
DEFAULT_STORAGE_POLICY: dict[str, Any] = {
|
||||
"default_mode": "single",
|
||||
"overrides": deepcopy(DEFAULT_RECOMMENDED_OVERRIDES),
|
||||
"global_single_lock": False,
|
||||
"history_retention_days": 30,
|
||||
"bgp_observation_retention_days": 7,
|
||||
"bgp_single_batch_max_rows": 500,
|
||||
"auto_prune_enabled": False,
|
||||
}
|
||||
|
||||
|
||||
def compute_record_content_hash(payload: dict[str, Any]) -> str:
|
||||
"""Return a deterministic SHA-256 hex digest for a comparable collector record payload."""
|
||||
canonical = json.dumps(
|
||||
payload,
|
||||
sort_keys=True,
|
||||
separators=(",", ":"),
|
||||
ensure_ascii=False,
|
||||
default=str,
|
||||
)
|
||||
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def _clamp_int(value: Any, default: int, *, minimum: int, maximum: int) -> int:
|
||||
try:
|
||||
parsed = int(value)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
return max(minimum, min(parsed, maximum))
|
||||
|
||||
|
||||
def _normalize_mode(value: Any, fallback: SnapshotMode = "single") -> SnapshotMode:
|
||||
if isinstance(value, str):
|
||||
candidate = value.strip().lower()
|
||||
if candidate in VALID_SNAPSHOT_MODES:
|
||||
return candidate # type: ignore[return-value]
|
||||
return fallback
|
||||
|
||||
|
||||
def normalize_storage_policy(
|
||||
raw: dict[str, Any] | None,
|
||||
*,
|
||||
fallback_auto_prune: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""Validate and normalize a raw storage policy dictionary, dropping redundant overrides."""
|
||||
data = raw if isinstance(raw, dict) else {}
|
||||
global_single_lock_raw = data.get("global_single_lock")
|
||||
if isinstance(global_single_lock_raw, bool):
|
||||
global_single_lock = global_single_lock_raw
|
||||
elif global_single_lock_raw is None:
|
||||
global_single_lock = False
|
||||
else:
|
||||
global_single_lock = str(global_single_lock_raw).strip().lower() in {
|
||||
"1",
|
||||
"true",
|
||||
"yes",
|
||||
"on",
|
||||
}
|
||||
|
||||
default_mode = "single" if global_single_lock else _normalize_mode(data.get("default_mode"), "single")
|
||||
|
||||
overrides_raw = data.get("overrides")
|
||||
if global_single_lock:
|
||||
cleaned_overrides: dict[str, SnapshotMode] = {}
|
||||
elif isinstance(overrides_raw, dict):
|
||||
cleaned_overrides = {}
|
||||
for source, mode_raw in overrides_raw.items():
|
||||
source_key = str(source or "").strip()
|
||||
if not source_key:
|
||||
continue
|
||||
mode = _normalize_mode(mode_raw, default_mode)
|
||||
if mode == "annual" and source_key not in ANNUAL_ELIGIBLE_SOURCES:
|
||||
mode = "history"
|
||||
if mode != default_mode:
|
||||
cleaned_overrides[source_key] = mode
|
||||
else:
|
||||
cleaned_overrides = {
|
||||
source: mode
|
||||
for source, mode in DEFAULT_RECOMMENDED_OVERRIDES.items()
|
||||
if mode != default_mode
|
||||
}
|
||||
|
||||
auto_prune_raw = data.get("auto_prune_enabled")
|
||||
if isinstance(auto_prune_raw, bool):
|
||||
auto_prune_enabled = auto_prune_raw
|
||||
elif auto_prune_raw is None:
|
||||
auto_prune_enabled = fallback_auto_prune
|
||||
else:
|
||||
auto_prune_enabled = str(auto_prune_raw).strip().lower() in {"1", "true", "yes", "on"}
|
||||
|
||||
return {
|
||||
"default_mode": default_mode,
|
||||
"overrides": cleaned_overrides,
|
||||
"global_single_lock": global_single_lock,
|
||||
"history_retention_days": _clamp_int(
|
||||
data.get("history_retention_days"),
|
||||
int(DEFAULT_STORAGE_POLICY["history_retention_days"]),
|
||||
minimum=1,
|
||||
maximum=3650,
|
||||
),
|
||||
"bgp_observation_retention_days": _clamp_int(
|
||||
data.get("bgp_observation_retention_days"),
|
||||
int(DEFAULT_STORAGE_POLICY["bgp_observation_retention_days"]),
|
||||
minimum=1,
|
||||
maximum=365,
|
||||
),
|
||||
"bgp_single_batch_max_rows": _clamp_int(
|
||||
data.get("bgp_single_batch_max_rows"),
|
||||
int(DEFAULT_STORAGE_POLICY["bgp_single_batch_max_rows"]),
|
||||
minimum=50,
|
||||
maximum=5000,
|
||||
),
|
||||
"auto_prune_enabled": auto_prune_enabled,
|
||||
}
|
||||
|
||||
|
||||
def resolve_snapshot_mode(policy: dict[str, Any] | None, source: str) -> SnapshotMode:
|
||||
"""Resolve effective snapshot mode for one datasource from a single unified policy."""
|
||||
normalized = normalize_storage_policy(policy)
|
||||
if normalized.get("global_single_lock"):
|
||||
return "single"
|
||||
overrides: dict[str, SnapshotMode] = normalized["overrides"]
|
||||
default_mode: SnapshotMode = normalized["default_mode"]
|
||||
mode = overrides.get(source, default_mode)
|
||||
if mode == "annual" and source not in ANNUAL_ELIGIBLE_SOURCES:
|
||||
return "history"
|
||||
return mode
|
||||
|
||||
|
||||
def set_source_snapshot_mode(
|
||||
policy: dict[str, Any] | None,
|
||||
source: str,
|
||||
mode: SnapshotMode,
|
||||
) -> dict[str, Any]:
|
||||
"""Update a single datasource override sparsely, deleting override when equal to default."""
|
||||
normalized = normalize_storage_policy(policy)
|
||||
target_mode = _normalize_mode(mode, normalized["default_mode"])
|
||||
if target_mode == "annual" and source not in ANNUAL_ELIGIBLE_SOURCES:
|
||||
target_mode = "history"
|
||||
|
||||
if normalized.get("global_single_lock") and target_mode != "single":
|
||||
raise StoragePolicyLockedError(
|
||||
"Global all-single lock is active; switch off all-single before enabling history or annual snapshots for a source."
|
||||
)
|
||||
|
||||
next_overrides = dict(normalized["overrides"])
|
||||
if target_mode == normalized["default_mode"]:
|
||||
next_overrides.pop(source, None)
|
||||
else:
|
||||
next_overrides[source] = target_mode
|
||||
|
||||
return normalize_storage_policy({**normalized, "overrides": next_overrides})
|
||||
|
||||
|
||||
def apply_global_snapshot_action(
|
||||
policy: dict[str, Any] | None,
|
||||
action: GlobalSnapshotAction,
|
||||
) -> dict[str, Any]:
|
||||
"""Apply tri-state master switch actions cleanly without leaving stale overrides."""
|
||||
normalized = normalize_storage_policy(policy)
|
||||
if action == "all_single":
|
||||
return normalize_storage_policy(
|
||||
{**normalized, "default_mode": "single", "overrides": {}, "global_single_lock": True}
|
||||
)
|
||||
if action == "all_history":
|
||||
return normalize_storage_policy(
|
||||
{**normalized, "default_mode": "history", "overrides": {}, "global_single_lock": False}
|
||||
)
|
||||
if action == "recommended_default":
|
||||
return normalize_storage_policy(
|
||||
{
|
||||
**normalized,
|
||||
"default_mode": "single",
|
||||
"overrides": deepcopy(DEFAULT_RECOMMENDED_OVERRIDES),
|
||||
"global_single_lock": False,
|
||||
}
|
||||
)
|
||||
return normalized
|
||||
|
||||
|
||||
def summarize_storage_policy(
|
||||
policy: dict[str, Any] | None,
|
||||
sources: Iterable[str],
|
||||
) -> dict[str, Any]:
|
||||
"""Compute effective per-source counts and tri-state master status (`off`/`partial`/`all`)."""
|
||||
normalized = normalize_storage_policy(policy)
|
||||
unique_sources = sorted({str(source).strip() for source in sources if str(source or "").strip()})
|
||||
|
||||
effective_modes: dict[str, SnapshotMode] = {}
|
||||
single_count = 0
|
||||
annual_count = 0
|
||||
history_count = 0
|
||||
|
||||
for source in unique_sources:
|
||||
mode = resolve_snapshot_mode(normalized, source)
|
||||
effective_modes[source] = mode
|
||||
if mode == "single":
|
||||
single_count += 1
|
||||
elif mode == "annual":
|
||||
annual_count += 1
|
||||
else:
|
||||
history_count += 1
|
||||
|
||||
total_sources = len(unique_sources)
|
||||
snapshot_enabled_count = annual_count + history_count
|
||||
if total_sources == 0 or snapshot_enabled_count == 0:
|
||||
master_state: Literal["off", "partial", "all"] = "off"
|
||||
elif snapshot_enabled_count == total_sources:
|
||||
master_state = "all"
|
||||
else:
|
||||
master_state = "partial"
|
||||
|
||||
return {
|
||||
**normalized,
|
||||
"total_sources": total_sources,
|
||||
"single_count": single_count,
|
||||
"annual_count": annual_count,
|
||||
"history_count": history_count,
|
||||
"snapshot_enabled_count": snapshot_enabled_count,
|
||||
"master_state": master_state,
|
||||
"annual_eligible_sources": sorted(ANNUAL_ELIGIBLE_SOURCES),
|
||||
"high_volume_sources": deepcopy(HIGH_VOLUME_SOURCES),
|
||||
"effective_modes": effective_modes,
|
||||
}
|
||||
|
||||
|
||||
def _is_postgresql_session(db: AsyncSession | None) -> bool:
|
||||
if db is None or not callable(getattr(db, "get_bind", None)):
|
||||
return False
|
||||
try:
|
||||
bind = db.get_bind()
|
||||
return getattr(getattr(bind, "dialect", None), "name", "") == "postgresql"
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def is_storage_policy_single_violation(exc: BaseException) -> bool:
|
||||
"""Return True if an exception (or wrapped DBAPI cause) came from the single-mode publish guard."""
|
||||
visited: set[int] = set()
|
||||
pending: list[BaseException | None] = [exc]
|
||||
while pending:
|
||||
current = pending.pop()
|
||||
if current is None or id(current) in visited:
|
||||
continue
|
||||
visited.add(id(current))
|
||||
if STORAGE_POLICY_SINGLE_VIOLATION_CODE in str(current):
|
||||
return True
|
||||
pending.append(getattr(current, "__cause__", None))
|
||||
pending.append(getattr(current, "__context__", None))
|
||||
pending.append(getattr(current, "orig", None))
|
||||
return False
|
||||
|
||||
|
||||
async def acquire_storage_policy_write_lock(db: AsyncSession | None) -> None:
|
||||
"""Take transaction-scoped exclusive lock serializing storage policy changes with snapshot publish."""
|
||||
if not _is_postgresql_session(db):
|
||||
return
|
||||
await db.execute( # type: ignore[union-attr]
|
||||
text("SELECT pg_advisory_xact_lock(:key1, :key2)"),
|
||||
{"key1": STORAGE_POLICY_TX_LOCK_KEY[0], "key2": STORAGE_POLICY_TX_LOCK_KEY[1]},
|
||||
)
|
||||
|
||||
|
||||
async def acquire_storage_policy_publish_lock(
|
||||
db: AsyncSession | None,
|
||||
source: str,
|
||||
) -> tuple[SnapshotMode, dict[str, Any]]:
|
||||
"""Take transaction-scoped shared lock and read the latest committed storage policy."""
|
||||
if db is None or not callable(getattr(db, "execute", None)):
|
||||
policy = normalize_storage_policy(None)
|
||||
return resolve_snapshot_mode(policy, source), policy
|
||||
|
||||
is_pg = _is_postgresql_session(db)
|
||||
if is_pg:
|
||||
await db.execute(
|
||||
text("SELECT pg_advisory_xact_lock_shared(:key1, :key2)"),
|
||||
{"key1": STORAGE_POLICY_TX_LOCK_KEY[0], "key2": STORAGE_POLICY_TX_LOCK_KEY[1]},
|
||||
)
|
||||
|
||||
stmt = (
|
||||
select(SystemSetting.payload)
|
||||
.where(SystemSetting.category == STORAGE_POLICY_CATEGORY)
|
||||
.limit(1)
|
||||
)
|
||||
if is_pg and hasattr(stmt, "with_for_update"):
|
||||
stmt = stmt.with_for_update(read=True)
|
||||
|
||||
try:
|
||||
result = await db.execute(stmt)
|
||||
except Exception:
|
||||
policy = normalize_storage_policy(None)
|
||||
return resolve_snapshot_mode(policy, source), policy
|
||||
|
||||
raw_payload = None
|
||||
if result is not None and callable(getattr(result, "scalar_one_or_none", None)):
|
||||
raw_payload = result.scalar_one_or_none()
|
||||
if isinstance(raw_payload, SystemSetting):
|
||||
raw_payload = raw_payload.payload
|
||||
policy = normalize_storage_policy(raw_payload if isinstance(raw_payload, dict) else None)
|
||||
return resolve_snapshot_mode(policy, source), policy
|
||||
|
||||
|
||||
async def _load_setting_row(
|
||||
db: AsyncSession,
|
||||
category: str,
|
||||
*,
|
||||
for_update: bool = False,
|
||||
) -> SystemSetting | None:
|
||||
try:
|
||||
stmt = select(SystemSetting).where(SystemSetting.category == category).limit(1)
|
||||
if hasattr(stmt, "execution_options"):
|
||||
stmt = stmt.execution_options(populate_existing=True)
|
||||
if for_update and _is_postgresql_session(db) and hasattr(stmt, "with_for_update"):
|
||||
stmt = stmt.with_for_update()
|
||||
result = await db.execute(stmt)
|
||||
except Exception:
|
||||
return None
|
||||
if result is None or not callable(getattr(result, "scalar_one_or_none", None)):
|
||||
return None
|
||||
record = result.scalar_one_or_none()
|
||||
if isinstance(record, SystemSetting):
|
||||
return record
|
||||
return None
|
||||
|
||||
|
||||
async def get_storage_policy(db: AsyncSession | None) -> dict[str, Any]:
|
||||
"""Load storage policy fresh from DB, safely falling back when called with fake/None sessions."""
|
||||
if db is None or not callable(getattr(db, "execute", None)):
|
||||
return normalize_storage_policy(None)
|
||||
|
||||
try:
|
||||
result = await db.execute(
|
||||
select(SystemSetting.payload)
|
||||
.where(SystemSetting.category == STORAGE_POLICY_CATEGORY)
|
||||
.limit(1)
|
||||
)
|
||||
except Exception:
|
||||
return normalize_storage_policy(None)
|
||||
|
||||
if result is not None and callable(getattr(result, "scalar_one_or_none", None)):
|
||||
raw_payload = result.scalar_one_or_none()
|
||||
if isinstance(raw_payload, SystemSetting):
|
||||
raw_payload = raw_payload.payload
|
||||
if isinstance(raw_payload, dict):
|
||||
return normalize_storage_policy(raw_payload)
|
||||
return normalize_storage_policy(None)
|
||||
|
||||
|
||||
async def resolve_collector_storage_policy(
|
||||
db: AsyncSession | None,
|
||||
source: str,
|
||||
) -> tuple[SnapshotMode, dict[str, Any]]:
|
||||
"""Return `(effective_mode, full_policy)` for a collector source."""
|
||||
policy = await get_storage_policy(db)
|
||||
return resolve_snapshot_mode(policy, source), policy
|
||||
|
||||
|
||||
async def mutate_storage_policy(
|
||||
db: AsyncSession,
|
||||
mutator: Callable[[dict[str, Any]], dict[str, Any]],
|
||||
*,
|
||||
sync_system_retention: bool = True,
|
||||
commit: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""Read, validate, merge, and persist storage policy inside one locked transaction."""
|
||||
await acquire_storage_policy_write_lock(db)
|
||||
record = await _load_setting_row(db, STORAGE_POLICY_CATEGORY, for_update=True)
|
||||
current_policy = normalize_storage_policy(
|
||||
record.payload if record is not None and isinstance(record.payload, dict) else None
|
||||
)
|
||||
normalized = normalize_storage_policy(mutator(deepcopy(current_policy)))
|
||||
|
||||
if record is None:
|
||||
record = SystemSetting(category=STORAGE_POLICY_CATEGORY, payload=normalized)
|
||||
db.add(record)
|
||||
else:
|
||||
record.payload = normalized
|
||||
|
||||
if sync_system_retention:
|
||||
# Canonical lock order: advisory lock -> collection_storage -> system.
|
||||
system_record = await _load_setting_row(db, "system", for_update=True)
|
||||
if system_record is not None and isinstance(system_record.payload, dict):
|
||||
next_system_payload = dict(system_record.payload)
|
||||
next_system_payload["data_retention_days"] = normalized["history_retention_days"]
|
||||
system_record.payload = next_system_payload
|
||||
|
||||
if commit:
|
||||
await db.commit()
|
||||
if hasattr(db, "refresh"):
|
||||
await db.refresh(record)
|
||||
return normalized
|
||||
|
||||
|
||||
async def save_storage_policy(
|
||||
db: AsyncSession,
|
||||
policy: dict[str, Any],
|
||||
*,
|
||||
sync_system_retention: bool = True,
|
||||
commit: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""Persist storage policy under an exclusive transaction lock blocking incompatible snapshot commits."""
|
||||
return await mutate_storage_policy(
|
||||
db,
|
||||
lambda _current: policy,
|
||||
sync_system_retention=sync_system_retention,
|
||||
commit=commit,
|
||||
)
|
||||
|
||||
|
||||
async def _detect_existing_collection_data(db: AsyncSession) -> bool:
|
||||
"""Return True if any historical collection or AIS raw table already holds data."""
|
||||
probes = (
|
||||
text("SELECT 1 FROM data_snapshots LIMIT 1"),
|
||||
text("SELECT 1 FROM collected_data LIMIT 1"),
|
||||
text("SELECT 1 FROM ais_raw_observations LIMIT 1"),
|
||||
)
|
||||
for probe in probes:
|
||||
try:
|
||||
result = await db.execute(probe)
|
||||
if result is not None and result.fetchone() is not None:
|
||||
return True
|
||||
except Exception:
|
||||
continue
|
||||
return False
|
||||
|
||||
|
||||
async def ensure_default_storage_policy(db: AsyncSession) -> dict[str, Any]:
|
||||
"""Seed `collection_storage` once under lock; protect existing DB history by setting auto_prune=False."""
|
||||
await acquire_storage_policy_write_lock(db)
|
||||
existing = await _load_setting_row(db, STORAGE_POLICY_CATEGORY, for_update=True)
|
||||
if existing is not None and isinstance(existing.payload, dict):
|
||||
return normalize_storage_policy(existing.payload)
|
||||
|
||||
has_existing_data = await _detect_existing_collection_data(db)
|
||||
history_retention_days = int(DEFAULT_STORAGE_POLICY["history_retention_days"])
|
||||
system_record = await _load_setting_row(db, "system")
|
||||
if system_record is not None and isinstance(system_record.payload, dict):
|
||||
history_retention_days = _clamp_int(
|
||||
system_record.payload.get("data_retention_days"),
|
||||
history_retention_days,
|
||||
minimum=1,
|
||||
maximum=3650,
|
||||
)
|
||||
|
||||
seed_policy = normalize_storage_policy(
|
||||
{
|
||||
**deepcopy(DEFAULT_STORAGE_POLICY),
|
||||
"history_retention_days": history_retention_days,
|
||||
"auto_prune_enabled": not has_existing_data,
|
||||
},
|
||||
fallback_auto_prune=not has_existing_data,
|
||||
)
|
||||
record = SystemSetting(category=STORAGE_POLICY_CATEGORY, payload=seed_policy)
|
||||
db.add(record)
|
||||
await db.commit()
|
||||
if hasattr(db, "refresh"):
|
||||
await db.refresh(record)
|
||||
logger.info_event(
|
||||
"Initialized default collection storage policy",
|
||||
event="storage_policy.seeded",
|
||||
context={
|
||||
"has_existing_data": has_existing_data,
|
||||
"default_mode": seed_policy["default_mode"],
|
||||
"overrides": seed_policy["overrides"],
|
||||
"auto_prune_enabled": seed_policy["auto_prune_enabled"],
|
||||
"history_retention_days": seed_policy["history_retention_days"],
|
||||
},
|
||||
)
|
||||
return seed_policy
|
||||
@@ -3,9 +3,10 @@
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from hashlib import sha256
|
||||
import json
|
||||
import time
|
||||
from typing import Any, Iterable
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy import delete, select
|
||||
from sqlalchemy import Float
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
@@ -14,6 +15,7 @@ from app.models.vessel import (
|
||||
AISRawObservation,
|
||||
AISSourceHealth,
|
||||
VesselCurrentState,
|
||||
VesselPosition,
|
||||
)
|
||||
from app.services.vessel_aggregation_strategy import (
|
||||
DEFAULT_STRATEGY,
|
||||
@@ -23,6 +25,9 @@ from app.services.vessel_types import normalize_vessel_type_name
|
||||
|
||||
VESSEL_AIS_SCHEMA = "vessel_ais"
|
||||
DEFAULT_AGGREGATION_WINDOW_HOURS = 24
|
||||
VESSEL_TRACK_RETENTION_HOURS = 24
|
||||
VESSEL_TRACK_PRUNE_INTERVAL_SECONDS = 1800.0
|
||||
_LAST_TRACK_PRUNE_MONO = 0.0
|
||||
DEFAULT_SNAPSHOT_WINDOW_MINUTES = 60
|
||||
MAX_SNAPSHOT_LIMIT = 5000
|
||||
MAX_SNAPSHOT_CANDIDATE_MULTIPLIER = 20
|
||||
@@ -449,6 +454,105 @@ def _group_observations(observations: Iterable[AISRawObservation]) -> dict[str,
|
||||
return grouped
|
||||
|
||||
|
||||
def _optional_float(value: Any) -> float | None:
|
||||
try:
|
||||
if value in (None, ""):
|
||||
return None
|
||||
return float(value)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _optional_small_int(value: Any) -> int | None:
|
||||
try:
|
||||
if value in (None, ""):
|
||||
return None
|
||||
parsed = int(float(value))
|
||||
return parsed if -32768 <= parsed <= 32767 else None
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
async def _record_vessel_track_point(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
normalized_payload: dict[str, Any],
|
||||
observed_at: datetime,
|
||||
) -> VesselPosition | None:
|
||||
"""Append a bounded 24-hour track point to `vessel_position` without duplicating exact replays."""
|
||||
if not _has_valid_position(normalized_payload):
|
||||
return None
|
||||
|
||||
mmsi = int(normalized_payload["mmsi"])
|
||||
lat = float(normalized_payload["lat"])
|
||||
lon = float(normalized_payload["lon"])
|
||||
observed_utc = _coerce_datetime(observed_at) or datetime.now(UTC)
|
||||
|
||||
if callable(getattr(db, "execute", None)):
|
||||
try:
|
||||
latest_result = await db.execute(
|
||||
select(VesselPosition)
|
||||
.where(VesselPosition.mmsi == mmsi)
|
||||
.order_by(VesselPosition.received_at.desc(), VesselPosition.id.desc())
|
||||
.limit(1)
|
||||
)
|
||||
if latest_result is not None and callable(
|
||||
getattr(latest_result, "scalar_one_or_none", None)
|
||||
):
|
||||
latest = latest_result.scalar_one_or_none()
|
||||
if latest is not None:
|
||||
latest_ts = _coerce_datetime(latest.received_at)
|
||||
if (
|
||||
latest_ts is not None
|
||||
and abs((latest_ts - observed_utc).total_seconds()) < 1e-6
|
||||
and round(float(latest.lat), 5) == round(lat, 5)
|
||||
and round(float(latest.lon), 5) == round(lon, 5)
|
||||
):
|
||||
return None
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
track_point = VesselPosition(
|
||||
mmsi=mmsi,
|
||||
lat=lat,
|
||||
lon=lon,
|
||||
sog=_optional_float(normalized_payload.get("sog")),
|
||||
cog=_optional_float(normalized_payload.get("cog")),
|
||||
heading=_optional_small_int(normalized_payload.get("heading")),
|
||||
nav_status=_optional_small_int(normalized_payload.get("nav_status")),
|
||||
received_at=observed_utc,
|
||||
)
|
||||
db.add(track_point)
|
||||
return track_point
|
||||
|
||||
|
||||
async def prune_expired_vessel_track_points(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
retention_hours: int = VESSEL_TRACK_RETENTION_HOURS,
|
||||
force: bool = False,
|
||||
) -> int:
|
||||
"""Prune `vessel_position` points older than the 24-hour track window."""
|
||||
global _LAST_TRACK_PRUNE_MONO
|
||||
|
||||
if db is None or not callable(getattr(db, "execute", None)):
|
||||
return 0
|
||||
now_mono = time.monotonic()
|
||||
if not force and (now_mono - _LAST_TRACK_PRUNE_MONO) < VESSEL_TRACK_PRUNE_INTERVAL_SECONDS:
|
||||
return 0
|
||||
|
||||
cutoff = (now or datetime.now(UTC)) - timedelta(hours=max(int(retention_hours), 1))
|
||||
try:
|
||||
result = await db.execute(
|
||||
delete(VesselPosition).where(VesselPosition.received_at < cutoff)
|
||||
)
|
||||
except Exception:
|
||||
return 0
|
||||
_LAST_TRACK_PRUNE_MONO = now_mono
|
||||
return int(getattr(result, "rowcount", 0) or 0)
|
||||
|
||||
|
||||
async def record_vessel_ais_observation(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
@@ -462,8 +566,9 @@ async def record_vessel_ais_observation(
|
||||
observed_at: datetime | None = None,
|
||||
collected_at: datetime | None = None,
|
||||
quality_flags: list[str] | None = None,
|
||||
) -> AISRawObservation | None:
|
||||
"""Insert one raw observation if the source-level fact has not already been stored."""
|
||||
persist_raw: bool = True,
|
||||
) -> AISRawObservation | VesselCurrentState | None:
|
||||
"""Persist vessel state; maintain 24h `vessel_position` track when `persist_raw` is False."""
|
||||
|
||||
entity_key = str(normalized_payload["mmsi"])
|
||||
collected_at = collected_at or datetime.now(UTC)
|
||||
@@ -473,6 +578,23 @@ async def record_vessel_ais_observation(
|
||||
or collected_at
|
||||
)
|
||||
normalized_json = _jsonable(normalized_payload)
|
||||
|
||||
if not persist_raw:
|
||||
current = await upsert_vessel_current_state(
|
||||
db,
|
||||
source=source,
|
||||
normalized_payload=normalized_json,
|
||||
observed_at=observed_at,
|
||||
quality_flags=quality_flags or [],
|
||||
)
|
||||
if _has_valid_position(normalized_json):
|
||||
await _record_vessel_track_point(
|
||||
db,
|
||||
normalized_payload=normalized_json,
|
||||
observed_at=observed_at,
|
||||
)
|
||||
return current
|
||||
|
||||
raw_json = _jsonable(raw_payload or {})
|
||||
|
||||
observation_hash = build_observation_hash(
|
||||
@@ -525,10 +647,43 @@ async def upsert_vessel_current_state(
|
||||
) -> VesselCurrentState | None:
|
||||
"""Keep one latest renderable row per MMSI while preserving useful static fields."""
|
||||
|
||||
if not _has_valid_position(normalized_payload):
|
||||
return None
|
||||
mmsi = int(normalized_payload["mmsi"])
|
||||
current = await db.get(VesselCurrentState, mmsi)
|
||||
has_position = _has_valid_position(normalized_payload)
|
||||
|
||||
if not has_position:
|
||||
if current is None:
|
||||
return None
|
||||
updated_fields: set[str] = set()
|
||||
field_sources = dict(current.field_sources or {})
|
||||
for field in CURRENT_STATE_STATIC_FIELDS:
|
||||
value = _payload_value(normalized_payload, field)
|
||||
if value is None:
|
||||
continue
|
||||
existing_source = field_sources.get(field)
|
||||
existing_value = getattr(current, field, None)
|
||||
if (
|
||||
existing_value in (None, "")
|
||||
or _strategy_source_rank(source, DEFAULT_STRATEGY)
|
||||
>= _strategy_source_rank(str(existing_source or ""), DEFAULT_STRATEGY)
|
||||
):
|
||||
setattr(current, field, value)
|
||||
updated_fields.add(field)
|
||||
if not updated_fields:
|
||||
return current
|
||||
current.vessel_type_name = current.vessel_type_name or normalize_vessel_type_name(
|
||||
current.vessel_type
|
||||
)
|
||||
selected_reasons = dict(current.selected_reasons or {})
|
||||
for field in updated_fields:
|
||||
field_sources[field] = source
|
||||
selected_reasons[field] = "source_priority"
|
||||
current.field_sources = field_sources
|
||||
current.selected_reasons = selected_reasons
|
||||
current.updated_at = datetime.now(UTC)
|
||||
current.quality_flags = sorted(set((current.quality_flags or []) + (quality_flags or [])))
|
||||
return current
|
||||
|
||||
if current is not None and current.observed_at is not None:
|
||||
current_observed_at = _coerce_datetime(current.observed_at)
|
||||
if current_observed_at is not None and observed_at < current_observed_at:
|
||||
@@ -689,6 +844,26 @@ async def get_aggregated_vessels(
|
||||
return []
|
||||
vessels = await aggregate_vessel_observations(db, result.scalars().all())
|
||||
|
||||
if not vessels:
|
||||
current_stmt = (
|
||||
select(VesselCurrentState)
|
||||
.where(VesselCurrentState.observed_at >= observed_since)
|
||||
.order_by(VesselCurrentState.observed_at.desc(), VesselCurrentState.mmsi.asc())
|
||||
)
|
||||
if bbox is not None:
|
||||
lon_min, lat_min, lon_max, lat_max = bbox
|
||||
current_stmt = current_stmt.where(
|
||||
VesselCurrentState.lon >= lon_min,
|
||||
VesselCurrentState.lon <= lon_max,
|
||||
VesselCurrentState.lat >= lat_min,
|
||||
VesselCurrentState.lat <= lat_max,
|
||||
)
|
||||
if limit and limit > 0:
|
||||
current_stmt = current_stmt.limit(limit)
|
||||
current_result = await db.execute(current_stmt)
|
||||
if hasattr(current_result, "scalars"):
|
||||
return [item.to_dict() for item in current_result.scalars().all()]
|
||||
|
||||
if bbox is not None:
|
||||
lon_min, lat_min, lon_max, lat_max = bbox
|
||||
vessels = [
|
||||
@@ -740,13 +915,26 @@ async def get_aggregated_vessels_snapshot(
|
||||
if not hasattr(result, "scalars"):
|
||||
return []
|
||||
vessels = await aggregate_vessel_observations(db, result.scalars().all())
|
||||
if not vessels:
|
||||
return await get_current_vessels_snapshot(
|
||||
db,
|
||||
bbox=bbox,
|
||||
limit=safe_limit,
|
||||
observed_since=observed_since,
|
||||
)
|
||||
return vessels[:safe_limit]
|
||||
|
||||
|
||||
async def get_aggregated_vessel(db: AsyncSession, mmsi: int) -> dict[str, Any] | None:
|
||||
observations = await get_vessel_raw_observations(db, mmsi, limit=1000)
|
||||
vessels = await aggregate_vessel_observations(db, observations)
|
||||
return vessels[0] if vessels else None
|
||||
if vessels:
|
||||
return vessels[0]
|
||||
if callable(getattr(db, "get", None)):
|
||||
current = await db.get(VesselCurrentState, mmsi)
|
||||
if current is not None:
|
||||
return current.to_dict()
|
||||
return None
|
||||
|
||||
|
||||
async def get_aggregated_vessel_track(
|
||||
@@ -766,32 +954,86 @@ async def get_aggregated_vessel_track(
|
||||
return []
|
||||
|
||||
points: list[dict[str, Any]] = []
|
||||
seen: set[tuple[str, float, float, str]] = set()
|
||||
seen_coords_at: set[tuple[str, float, float]] = set()
|
||||
for observation in result.scalars().all():
|
||||
payload = observation.normalized_payload or {}
|
||||
if not _has_valid_position(payload):
|
||||
continue
|
||||
observed_at = _coerce_datetime(observation.observed_at)
|
||||
if observed_at is None:
|
||||
continue
|
||||
lat = float(payload["lat"])
|
||||
lon = float(payload["lon"])
|
||||
key = (
|
||||
observation.observed_at.isoformat(),
|
||||
round(lat, 5),
|
||||
round(lon, 5),
|
||||
observation.source,
|
||||
)
|
||||
if key in seen:
|
||||
coord_key = (observed_at.isoformat(), round(lat, 5), round(lon, 5))
|
||||
if coord_key in seen_coords_at:
|
||||
continue
|
||||
seen.add(key)
|
||||
seen_coords_at.add(coord_key)
|
||||
points.append(
|
||||
{
|
||||
"lat": lat,
|
||||
"lon": lon,
|
||||
"observed_at": observation.observed_at,
|
||||
"observed_at": observed_at,
|
||||
"source": observation.source,
|
||||
"selected_reason": "track_timeline",
|
||||
"quality_flags": observation.quality_flags or [],
|
||||
}
|
||||
)
|
||||
|
||||
pos_result = await db.execute(
|
||||
select(VesselPosition)
|
||||
.where(VesselPosition.mmsi == mmsi)
|
||||
.where(VesselPosition.received_at >= cutoff)
|
||||
.order_by(VesselPosition.received_at.asc(), VesselPosition.id.asc())
|
||||
)
|
||||
if pos_result is not None and hasattr(pos_result, "scalars"):
|
||||
source_name = "vessel_ais"
|
||||
if callable(getattr(db, "get", None)):
|
||||
current_for_source = await db.get(VesselCurrentState, mmsi)
|
||||
if current_for_source is not None and getattr(current_for_source, "source", None):
|
||||
source_name = str(current_for_source.source)
|
||||
for position in pos_result.scalars().all():
|
||||
observed_at = _coerce_datetime(position.received_at)
|
||||
if observed_at is None:
|
||||
continue
|
||||
lat = float(position.lat)
|
||||
lon = float(position.lon)
|
||||
if not (-90 <= lat <= 90 and -180 <= lon <= 180):
|
||||
continue
|
||||
coord_key = (observed_at.isoformat(), round(lat, 5), round(lon, 5))
|
||||
if coord_key in seen_coords_at:
|
||||
continue
|
||||
seen_coords_at.add(coord_key)
|
||||
points.append(
|
||||
{
|
||||
"lat": lat,
|
||||
"lon": lon,
|
||||
"observed_at": observed_at,
|
||||
"source": source_name,
|
||||
"selected_reason": "track_24h",
|
||||
"quality_flags": [],
|
||||
}
|
||||
)
|
||||
|
||||
if points:
|
||||
points.sort(key=lambda point: point["observed_at"])
|
||||
return points
|
||||
|
||||
if callable(getattr(db, "get", None)):
|
||||
current = await db.get(VesselCurrentState, mmsi)
|
||||
if current is not None and current.lat is not None and current.lon is not None:
|
||||
observed_at = _coerce_datetime(current.observed_at)
|
||||
cutoff_dt = _coerce_datetime(cutoff)
|
||||
if observed_at is not None and (cutoff_dt is None or observed_at >= cutoff_dt):
|
||||
points.append(
|
||||
{
|
||||
"lat": float(current.lat),
|
||||
"lon": float(current.lon),
|
||||
"observed_at": observed_at,
|
||||
"source": current.source,
|
||||
"selected_reason": "current_state",
|
||||
"quality_flags": current.quality_flags or [],
|
||||
}
|
||||
)
|
||||
return points
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
"""Standalone background worker entrypoint for split API/worker deployments."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from contextlib import suppress
|
||||
import signal
|
||||
|
||||
from app.core.config import settings, validate_production_security
|
||||
from app.core.logging import configure_logging, get_logger
|
||||
from app.core.websocket.broadcaster import broadcaster
|
||||
from app.core.websocket.manager import manager
|
||||
from app.db.session import init_db
|
||||
from app.services.data_jobs import start_data_job_worker, stop_data_job_worker
|
||||
from app.services.earth_news_worker import (
|
||||
start_earth_news_target_worker,
|
||||
stop_earth_news_target_worker,
|
||||
)
|
||||
from app.services.scheduler import (
|
||||
acquire_scheduler_leader_lock,
|
||||
cleanup_stale_running_tasks,
|
||||
release_scheduler_leader_lock,
|
||||
start_scheduler,
|
||||
stop_scheduler,
|
||||
sync_scheduler_with_datasources,
|
||||
)
|
||||
|
||||
LEADER_RETRY_SECONDS = 5.0
|
||||
logger = get_logger(__name__, service="worker")
|
||||
|
||||
|
||||
async def run_worker(stop_event: asyncio.Event | None = None) -> None:
|
||||
"""Run scheduler and async queue workers with PostgreSQL leader election."""
|
||||
configure_logging()
|
||||
validate_production_security(settings)
|
||||
await init_db()
|
||||
|
||||
active_stop = stop_event or asyncio.Event()
|
||||
pubsub_started = False
|
||||
leader_lock_acquired = False
|
||||
scheduler_started = False
|
||||
workers_started = False
|
||||
broadcaster_started = False
|
||||
|
||||
try:
|
||||
await manager.start_pubsub(publish_only=True)
|
||||
pubsub_started = True
|
||||
|
||||
while not active_stop.is_set():
|
||||
if not settings.should_run_scheduler:
|
||||
break
|
||||
if await acquire_scheduler_leader_lock():
|
||||
leader_lock_acquired = True
|
||||
break
|
||||
logger.info_event(
|
||||
"Waiting for scheduler leader advisory lock",
|
||||
event="worker.leader_lock.waiting",
|
||||
)
|
||||
with suppress(TimeoutError):
|
||||
await asyncio.wait_for(active_stop.wait(), timeout=LEADER_RETRY_SECONDS)
|
||||
|
||||
if active_stop.is_set():
|
||||
return
|
||||
|
||||
if settings.should_run_scheduler:
|
||||
await cleanup_stale_running_tasks()
|
||||
start_scheduler()
|
||||
scheduler_started = True
|
||||
await sync_scheduler_with_datasources()
|
||||
|
||||
broadcaster.start()
|
||||
broadcaster_started = True
|
||||
start_data_job_worker()
|
||||
start_earth_news_target_worker()
|
||||
workers_started = True
|
||||
logger.info_event(
|
||||
"Background worker started",
|
||||
event="worker.started",
|
||||
context={"role": settings.normalized_role, "scheduler": scheduler_started},
|
||||
)
|
||||
await active_stop.wait()
|
||||
finally:
|
||||
if broadcaster_started:
|
||||
try:
|
||||
broadcaster.stop()
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed stopping broadcaster during worker shutdown",
|
||||
event="worker.shutdown.broadcaster_error",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
if workers_started:
|
||||
try:
|
||||
await stop_earth_news_target_worker()
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed stopping earth news worker during worker shutdown",
|
||||
event="worker.shutdown.earth_news_error",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
try:
|
||||
await stop_data_job_worker()
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed stopping data job worker during worker shutdown",
|
||||
event="worker.shutdown.data_job_error",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
if scheduler_started:
|
||||
try:
|
||||
stop_scheduler()
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed stopping scheduler during worker shutdown",
|
||||
event="worker.shutdown.scheduler_error",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
if leader_lock_acquired:
|
||||
try:
|
||||
await release_scheduler_leader_lock()
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed releasing scheduler leader lock during worker shutdown",
|
||||
event="worker.shutdown.leader_lock_error",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
if pubsub_started:
|
||||
try:
|
||||
await manager.stop_pubsub()
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed stopping pubsub during worker shutdown",
|
||||
event="worker.shutdown.pubsub_error",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
logger.info_event("Background worker stopped", event="worker.stopped")
|
||||
|
||||
|
||||
async def _main() -> None:
|
||||
stop_event = asyncio.Event()
|
||||
loop = asyncio.get_running_loop()
|
||||
for sig in (signal.SIGINT, signal.SIGTERM):
|
||||
with suppress(NotImplementedError):
|
||||
loop.add_signal_handler(sig, stop_event.set)
|
||||
await run_worker(stop_event)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(_main())
|
||||
@@ -0,0 +1,279 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
|
||||
from app.api.v1 import situational_awareness
|
||||
from app.schemas.ai import SituationalAnalysisResponse
|
||||
from app.services.ai import spatial_domain_agent
|
||||
from app.services.ai.stream_turn import reset_stream_quota_ledger
|
||||
from app.services.ai_client import AIProviderClient, get_ai_provider_client
|
||||
|
||||
|
||||
def _parse_sse_text(raw: str) -> list[tuple[str, dict]]:
|
||||
events: list[tuple[str, dict]] = []
|
||||
for block in raw.replace("\r\n", "\n").split("\n\n"):
|
||||
if not block.strip():
|
||||
continue
|
||||
ev_name = "message"
|
||||
data_lines: list[str] = []
|
||||
for line in block.split("\n"):
|
||||
if line.startswith("event:"):
|
||||
ev_name = line[6:].strip()
|
||||
elif line.startswith("data:"):
|
||||
data_lines.append(line[5:].lstrip())
|
||||
if data_lines:
|
||||
events.append((ev_name, json.loads("\n".join(data_lines))))
|
||||
return events
|
||||
|
||||
|
||||
class _StubDb:
|
||||
pass
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_spatial_domain_agent_reads_content_attribute(monkeypatch):
|
||||
class _FakeClient:
|
||||
service_url = "http://aiprovider.test"
|
||||
llm_config = {"provider": "minimax", "model": "MiniMax-M2.7"}
|
||||
|
||||
async def analyze(self, _req):
|
||||
return SituationalAnalysisResponse(
|
||||
provider="minimax",
|
||||
model="MiniMax-M2.7",
|
||||
content=json.dumps(
|
||||
{
|
||||
"domain": "global",
|
||||
"subject_key": "global:test",
|
||||
"title": "全球多图层态势",
|
||||
"executive_assertion": "已成功读取大模型合成内容。",
|
||||
"confirmed_facts": [{"statement": "全网多图层数据在线。", "evidence_ids": ["ev-global-1"]}],
|
||||
"analytical_notes": [{"statement": "LLM 输出字段匹配成功。", "evidence_ids": ["ev-global-1"]}],
|
||||
"open_gaps": ["示例口径边界。"],
|
||||
"evidence_ids": ["ev-global-1"],
|
||||
},
|
||||
ensure_ascii=False,
|
||||
),
|
||||
)
|
||||
|
||||
async def fake_global_tool(*_args, **_kwargs):
|
||||
return {
|
||||
"domain": "global",
|
||||
"available": True,
|
||||
"domain_summaries": [],
|
||||
"bgp_summary": {"active_count": 0},
|
||||
"evidence": {"ev-global-1": {"id": "ev-global-1", "title": "Global Snapshot"}},
|
||||
"limitations": [],
|
||||
}
|
||||
|
||||
monkeypatch.setattr(spatial_domain_agent, "query_global_situational_tool", fake_global_tool)
|
||||
|
||||
result = await spatial_domain_agent.investigate_spatial_domain(
|
||||
_StubDb(),
|
||||
domain="global",
|
||||
question="分析全球态势",
|
||||
persist=False,
|
||||
ai_client=_FakeClient(),
|
||||
)
|
||||
|
||||
assert result["generation_mode"] == "llm_verified"
|
||||
assert result["payload"]["executive_assertion"] == "已成功读取大模型合成内容。"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stream_turn_adapts_between_configured_minimax_and_disabled_ai(monkeypatch):
|
||||
reset_stream_quota_ledger()
|
||||
|
||||
async def fake_recent_news(*_args, **_kwargs):
|
||||
return {
|
||||
"domain": "news",
|
||||
"available": True,
|
||||
"count": 1,
|
||||
"items": [{"id": "n1", "title": "全球海缆路由测试头条", "source": "Reuters", "region": "global"}],
|
||||
"evidence": {"ev-news-1": {"id": "ev-news-1", "title": "Planet News"}},
|
||||
}
|
||||
|
||||
async def fake_global_tool(*_args, **_kwargs):
|
||||
return {
|
||||
"domain": "global",
|
||||
"domain_summaries": [{"domain": "cable", "label": "海底光缆", "metric_text": "343 条"}],
|
||||
"evidence": {"ev-global-1": {"id": "ev-global-1", "title": "Global Telemetry"}},
|
||||
}
|
||||
|
||||
monkeypatch.setattr("app.services.ai.stream_turn.query_recent_earth_news_tool", fake_recent_news)
|
||||
monkeypatch.setattr("app.services.ai.stream_turn.query_global_situational_tool", fake_global_tool)
|
||||
|
||||
class _ConfiguredClient(AIProviderClient):
|
||||
def __init__(self):
|
||||
super().__init__(
|
||||
service_url="http://aiprovider.test",
|
||||
llm_config={
|
||||
"provider": "minimax",
|
||||
"provider_api": "anthropic-messages",
|
||||
"base_url": "https://api.minimaxi.com/anthropic",
|
||||
"api_key": "secret-key",
|
||||
"model": "MiniMax-M2.7",
|
||||
},
|
||||
)
|
||||
|
||||
async def stream_analyze(self, payload, request_id=None):
|
||||
assert payload.thinking == {"type": "enabled", "budget_tokens": 2048}
|
||||
yield {"event": "start", "provider": "minimax", "model": "MiniMax-M2.7"}
|
||||
yield {"event": "reasoning", "delta": "先梳理新闻核心矛盾。"}
|
||||
yield {"event": "text", "delta": "### 新闻深度分析\n\n- **要点**:供应链与光缆关注升温。"}
|
||||
yield {"event": "done", "provider": "minimax", "model": "MiniMax-M2.7", "usage": {"total_tokens": 42}}
|
||||
|
||||
class _DisabledClient(AIProviderClient):
|
||||
def __init__(self):
|
||||
super().__init__(
|
||||
service_url="http://aiprovider.test",
|
||||
llm_config={"provider": "disabled"},
|
||||
)
|
||||
|
||||
app = FastAPI()
|
||||
app.include_router(situational_awareness.router, prefix="/api/v1/situational-awareness")
|
||||
app.dependency_overrides[situational_awareness.get_db] = lambda: _StubDb()
|
||||
app.dependency_overrides[get_ai_provider_client] = lambda: _ConfiguredClient()
|
||||
|
||||
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:
|
||||
# 1. Anonymous Earth/desktop caller uses MiniMax automatically when configured
|
||||
res_ai = await client.post(
|
||||
"/api/v1/situational-awareness/sessions/stateless/turns/stream",
|
||||
json={
|
||||
"question": "请深度分析这条新闻:「全球海缆路由测试头条」",
|
||||
"domain": "news",
|
||||
"news_context": {
|
||||
"id": "n1",
|
||||
"title": "全球海缆路由测试头条",
|
||||
"summary": "测试新闻摘要",
|
||||
"source": "Reuters",
|
||||
"region": "全球",
|
||||
},
|
||||
},
|
||||
)
|
||||
assert res_ai.status_code == 200
|
||||
assert "text/event-stream" in res_ai.headers["content-type"]
|
||||
ai_events = _parse_sse_text(res_ai.text)
|
||||
ai_names = [name for name, _ in ai_events]
|
||||
assert ai_names == ["meta", "reasoning", "text", "done"]
|
||||
assert ai_events[0][1]["ai_enabled"] is True
|
||||
assert ai_events[0][1]["model"] == "MiniMax-M2.7"
|
||||
assert ai_events[1][1]["delta"] == "先梳理新闻核心矛盾。"
|
||||
assert "新闻深度分析" in ai_events[2][1]["delta"]
|
||||
assert ai_events[3][1]["zero_token"] is False
|
||||
assert ai_events[3][1]["generation_mode"] == "llm_verified"
|
||||
assert ai_events[3][1]["model"] == "MiniMax-M2.7"
|
||||
|
||||
# 2. Switching provider to disabled adapts seamlessly back to deterministic baseline
|
||||
app.dependency_overrides[get_ai_provider_client] = lambda: _DisabledClient()
|
||||
res_no_ai = await client.post(
|
||||
"/api/v1/situational-awareness/sessions/stateless/turns/stream",
|
||||
json={
|
||||
"question": "请深度分析这条新闻:「全球海缆路由测试头条」",
|
||||
"domain": "news",
|
||||
"news_context": {"id": "n1", "title": "全球海缆路由测试头条", "summary": "测试新闻摘要"},
|
||||
},
|
||||
)
|
||||
assert res_no_ai.status_code == 200
|
||||
no_ai_events = _parse_sse_text(res_no_ai.text)
|
||||
assert no_ai_events[0][1]["ai_enabled"] is False
|
||||
assert no_ai_events[0][1]["model"] is None
|
||||
assert no_ai_events[-1][0] == "done"
|
||||
assert no_ai_events[-1][1]["zero_token"] is True
|
||||
assert no_ai_events[-1][1]["model"] is None
|
||||
assert no_ai_events[-1][1]["generation_mode"] == "deterministic_baseline"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stream_turn_forwards_history_compaction_and_memory(monkeypatch):
|
||||
reset_stream_quota_ledger()
|
||||
|
||||
async def fake_global_tool(*_args, **_kwargs):
|
||||
return {
|
||||
"domain": "global",
|
||||
"domain_summaries": [{"domain": "cable", "label": "海底光缆", "metric_text": "343 条"}],
|
||||
"evidence": {"ev-global-1": {"id": "ev-global-1", "title": "Global Telemetry"}},
|
||||
}
|
||||
|
||||
async def fake_recent_news(*_args, **_kwargs):
|
||||
return {"domain": "news", "available": True, "count": 0, "items": [], "evidence": {}}
|
||||
|
||||
monkeypatch.setattr("app.services.ai.stream_turn.query_global_situational_tool", fake_global_tool)
|
||||
monkeypatch.setattr("app.services.ai.stream_turn.query_recent_earth_news_tool", fake_recent_news)
|
||||
|
||||
captured_analyze_reqs = []
|
||||
captured_stream_reqs = []
|
||||
|
||||
class _CompactingClient(AIProviderClient):
|
||||
def __init__(self):
|
||||
super().__init__(
|
||||
service_url="http://aiprovider.test",
|
||||
llm_config={
|
||||
"provider": "minimax",
|
||||
"provider_api": "anthropic-messages",
|
||||
"base_url": "https://api.minimaxi.com/anthropic",
|
||||
"api_key": "secret-key",
|
||||
"model": "MiniMax-M2.7",
|
||||
},
|
||||
)
|
||||
|
||||
async def analyze(self, payload, request_id=None):
|
||||
captured_analyze_reqs.append(payload)
|
||||
return SituationalAnalysisResponse(
|
||||
provider="minimax",
|
||||
model="MiniMax-M2.7",
|
||||
content="<think>internal</think>前序关注中美算力与亚太海缆冗余,已核验 343 条骨干海缆。",
|
||||
)
|
||||
|
||||
async def stream_analyze(self, payload, request_id=None):
|
||||
captured_stream_reqs.append(payload)
|
||||
yield {"event": "start", "provider": "minimax", "model": "MiniMax-M2.7"}
|
||||
yield {"event": "text", "delta": "结合前文 343 条海缆与您的亚太聚焦偏好,补充说明如下。"}
|
||||
yield {"event": "done", "provider": "minimax", "model": "MiniMax-M2.7", "usage": {"total_tokens": 55}}
|
||||
|
||||
app = FastAPI()
|
||||
app.include_router(situational_awareness.router, prefix="/api/v1/situational-awareness")
|
||||
app.dependency_overrides[situational_awareness.get_db] = lambda: _StubDb()
|
||||
app.dependency_overrides[get_ai_provider_client] = lambda: _CompactingClient()
|
||||
|
||||
long_history = []
|
||||
for idx in range(1, 7):
|
||||
long_history.append({"role": "user", "content": f"第 {idx} 轮提问"})
|
||||
long_history.append({"role": "assistant", "content": f"<think>thought-{idx}</think>第 {idx} 轮结论"})
|
||||
|
||||
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:
|
||||
res = await client.post(
|
||||
"/api/v1/situational-awareness/sessions/stateless/turns/stream",
|
||||
json={
|
||||
"question": "基于前面总结继续追问亚太海缆脆弱点",
|
||||
"domain": "global",
|
||||
"history": long_history,
|
||||
"memory_notes": ["优先给出亚太海缆冗余与算力口径边界"],
|
||||
"pinned_summaries": ["GLOBAL · Rev.1: 全球综合态势"],
|
||||
},
|
||||
)
|
||||
assert res.status_code == 200
|
||||
events = _parse_sse_text(res.text)
|
||||
meta_ev = events[0][1]
|
||||
done_ev = events[-1][1]
|
||||
|
||||
assert meta_ev["compacted"] is True
|
||||
assert "343 条骨干海缆" in meta_ev["conversation_summary"]
|
||||
assert "<think>" not in meta_ev["conversation_summary"]
|
||||
assert meta_ev["memory_used"] is True
|
||||
assert done_ev["compacted"] is True
|
||||
assert done_ev["conversation_summary"] == meta_ev["conversation_summary"]
|
||||
|
||||
assert len(captured_analyze_reqs) == 1
|
||||
assert len(captured_stream_reqs) == 1
|
||||
sent_payload = captured_stream_reqs[0]
|
||||
# Recent window preserves latest 4 turns (8 messages), with <think> stripped
|
||||
assert len(sent_payload.messages) == 8
|
||||
assert sent_payload.messages[0].content == "第 3 轮提问"
|
||||
assert sent_payload.messages[1].content == "第 3 轮结论"
|
||||
assert sent_payload.context["conversation_summary"] == meta_ev["conversation_summary"]
|
||||
assert sent_payload.context["user_memory_notes"] == ["优先给出亚太海缆冗余与算力口径边界"]
|
||||
assert sent_payload.context["pinned_comparisons"] == ["GLOBAL · Rev.1: 全球综合态势"]
|
||||
@@ -1203,9 +1203,10 @@ async def test_save_bgp_observations_for_batch_adds_rows(monkeypatch):
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_bgp_anomalies_for_batch_calls_incident_aggregation():
|
||||
previous_record = CollectedData(
|
||||
previous_record = BGPObservation(
|
||||
source="ris_live_bgp",
|
||||
extra_data={"prefix": "203.0.113.0/24", "origin_asn": 64496},
|
||||
prefix="203.0.113.0/24",
|
||||
origin_asn=64496,
|
||||
)
|
||||
db = _StrictFakeAsyncSession(
|
||||
[
|
||||
@@ -1214,7 +1215,7 @@ async def test_create_bgp_anomalies_for_batch_calls_incident_aggregation():
|
||||
[], # IPtoASN prefix geography
|
||||
[], # NRO delegated prefix geography
|
||||
[], # PeeringDB ASN profiles
|
||||
[previous_record], # Prior collected snapshot for origin-change detection
|
||||
[previous_record], # Prior BGP observations for origin-change detection
|
||||
[], # Existing anomaly entity keys
|
||||
]
|
||||
)
|
||||
@@ -1262,9 +1263,10 @@ async def test_create_bgp_anomalies_for_batch_calls_incident_aggregation():
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_bgp_anomalies_for_batch_skips_existing_entity_keys():
|
||||
previous_record = CollectedData(
|
||||
previous_record = BGPObservation(
|
||||
source="ris_live_bgp",
|
||||
extra_data={"prefix": "203.0.113.0/24", "origin_asn": 64496},
|
||||
prefix="203.0.113.0/24",
|
||||
origin_asn=64496,
|
||||
)
|
||||
existing_key = ("origin_change:203.0.113.0/24:64497",)
|
||||
existing_anomaly = BGPAnomaly(
|
||||
@@ -1284,7 +1286,7 @@ async def test_create_bgp_anomalies_for_batch_skips_existing_entity_keys():
|
||||
[], # IPtoASN prefix geography
|
||||
[], # NRO delegated prefix geography
|
||||
[], # PeeringDB ASN profiles
|
||||
[previous_record], # Prior collected snapshot for origin-change detection
|
||||
[previous_record], # Prior BGP observations for origin-change detection
|
||||
[existing_key],
|
||||
[existing_anomaly],
|
||||
]
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
"""Tests for client L1 hot-update manifest and bundle hosting APIs."""
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import tarfile
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.security import create_access_token
|
||||
from app.db.session import get_db
|
||||
from app.main import app
|
||||
from app.models.user import User
|
||||
|
||||
|
||||
class _DummyDbSession:
|
||||
pass
|
||||
|
||||
|
||||
class _ScalarResult:
|
||||
def __init__(self, user: User):
|
||||
self._user = user
|
||||
|
||||
def scalar_one_or_none(self):
|
||||
return self._user
|
||||
|
||||
|
||||
class _UserLookupSession:
|
||||
def __init__(self, user: User):
|
||||
self._user = user
|
||||
|
||||
async def execute(self, _stmt):
|
||||
return _ScalarResult(self._user)
|
||||
|
||||
|
||||
def _make_tar_gz(entries: dict[str, bytes], *, prefix: str = "") -> bytes:
|
||||
buf = io.BytesIO()
|
||||
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
|
||||
for name, data in entries.items():
|
||||
info = tarfile.TarInfo(name=f"{prefix}{name}")
|
||||
info.size = len(data)
|
||||
tar.addfile(info, io.BytesIO(data))
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _isolate_client_updates_dir(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(settings, "CLIENT_UPDATES_DIR", str(tmp_path))
|
||||
monkeypatch.setattr(settings, "CLIENT_UPDATE_PUBLISH_TOKEN", "ci-publish-secret-token")
|
||||
monkeypatch.setattr("app.core.security.redis_client", type("NoRedis", (), {"sismember": staticmethod(lambda *_a, **_k: False)})())
|
||||
yield
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_default_manifest_before_any_hotfix_published():
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
res = await client.get("/api/v1/client/update-manifest?shell=0.78.0&bundle=0.78.0")
|
||||
assert res.status_code == 200
|
||||
assert res.headers["cache-control"] == "no-store"
|
||||
data = res.json()
|
||||
assert data["shell"]["version"] == settings.VERSION
|
||||
assert data["bundle"] is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_publish_bundle_auth_validation_and_download():
|
||||
valid_tar = _make_tar_gz(
|
||||
{
|
||||
"index.html": b"<!doctype html><html><body>updated</body></html>",
|
||||
"js/main.js": b"console.log('hotfix');",
|
||||
}
|
||||
)
|
||||
expected_sha = hashlib.sha256(valid_tar).hexdigest()
|
||||
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
# Unauthenticated rejected
|
||||
unauth = await client.post(
|
||||
"/api/v1/client/updates/bundle",
|
||||
data={"version": "0.78.1"},
|
||||
files={"file": ("bundle.tar.gz", valid_tar, "application/gzip")},
|
||||
)
|
||||
assert unauth.status_code == 401
|
||||
|
||||
# Wrong CI publish token rejected
|
||||
bad_token = await client.post(
|
||||
"/api/v1/client/updates/bundle",
|
||||
headers={"X-Client-Update-Token": "wrong-token"},
|
||||
data={"version": "0.78.1"},
|
||||
files={"file": ("bundle.tar.gz", valid_tar, "application/gzip")},
|
||||
)
|
||||
assert bad_token.status_code == 401
|
||||
|
||||
# Non-admin JWT rejected
|
||||
async def _non_admin_db():
|
||||
yield _UserLookupSession(User(id=2, username="viewer", email="v@example.com", role="viewer", is_active=True))
|
||||
|
||||
app.dependency_overrides[get_db] = _non_admin_db
|
||||
viewer_jwt = create_access_token({"sub": "2", "username": "viewer"})
|
||||
forbidden = await client.post(
|
||||
"/api/v1/client/updates/bundle",
|
||||
headers={"Authorization": f"Bearer {viewer_jwt}"},
|
||||
data={"version": "0.78.1"},
|
||||
files={"file": ("bundle.tar.gz", valid_tar, "application/gzip")},
|
||||
)
|
||||
assert forbidden.status_code == 403
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
# Malicious path traversal archive rejected
|
||||
evil_tar = _make_tar_gz({"../evil.js": b"alert(1)", "index.html": b"ok"})
|
||||
evil_res = await client.post(
|
||||
"/api/v1/client/updates/bundle",
|
||||
headers={"X-Client-Update-Token": "ci-publish-secret-token"},
|
||||
data={"version": "0.78.1"},
|
||||
files={"file": ("evil.tar.gz", evil_tar, "application/gzip")},
|
||||
)
|
||||
assert evil_res.status_code == 400
|
||||
|
||||
# Valid publish via CI token succeeds and updates manifest
|
||||
pub = await client.post(
|
||||
"/api/v1/client/updates/bundle",
|
||||
headers={"X-Client-Update-Token": "ci-publish-secret-token"},
|
||||
data={
|
||||
"version": "0.78.1",
|
||||
"min_shell_version": "0.78.0",
|
||||
"release_notes": "Fix WebGL recovery",
|
||||
"shell_version": "0.78.1",
|
||||
"shell_min_required": "0.78.0",
|
||||
"shell_download_url": "https://gitea.rclaw.top/linkong/planet/releases/tag/v0.78.1",
|
||||
},
|
||||
files={"file": ("planet-earth-bundle-0.78.1.tar.gz", valid_tar, "application/gzip")},
|
||||
)
|
||||
assert pub.status_code == 200
|
||||
pub_data = pub.json()
|
||||
assert pub_data["status"] == "published"
|
||||
assert pub_data["manifest"]["bundle"]["version"] == "0.78.1"
|
||||
assert pub_data["manifest"]["bundle"]["sha256"] == expected_sha
|
||||
assert pub_data["manifest"]["bundle"]["size"] == len(valid_tar)
|
||||
assert pub_data["manifest"]["bundle"]["filesCount"] == 2
|
||||
|
||||
# Manifest reflects published bundle
|
||||
manifest_res = await client.get("/api/v1/client/update-manifest")
|
||||
assert manifest_res.status_code == 200
|
||||
bundle = manifest_res.json()["bundle"]
|
||||
assert bundle["version"] == "0.78.1"
|
||||
assert bundle["url"] == "/api/v1/client/updates/files/planet-earth-bundle-0.78.1.tar.gz"
|
||||
|
||||
# Download serves exact archive bytes
|
||||
dl = await client.get(bundle["url"])
|
||||
assert dl.status_code == 200
|
||||
assert dl.content == valid_tar
|
||||
|
||||
# Admin JWT publish also works cleanly
|
||||
missing_index_tar = _make_tar_gz({"js/main.js": b"console.log(1)"})
|
||||
|
||||
async def _admin_db():
|
||||
yield _UserLookupSession(User(id=1, username="admin", email="a@example.com", role="admin", is_active=True))
|
||||
|
||||
app.dependency_overrides[get_db] = _admin_db
|
||||
admin_jwt = create_access_token({"sub": "1", "username": "admin"})
|
||||
no_idx = await client.post(
|
||||
"/api/v1/client/updates/bundle",
|
||||
headers={"Authorization": f"Bearer {admin_jwt}"},
|
||||
data={"version": "0.78.2"},
|
||||
files={"file": ("no-index.tar.gz", missing_index_tar, "application/gzip")},
|
||||
)
|
||||
assert no_idx.status_code == 400
|
||||
|
||||
# Invalid download filename rejected
|
||||
bad_dl = await client.get("/api/v1/client/updates/files/not-allowed.txt")
|
||||
assert bad_dl.status_code == 400
|
||||
@@ -0,0 +1,424 @@
|
||||
"""Tests for collector concurrency limits, thread-offloaded parsing/transform, Core bulk upsert, and dashboard stats."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from datetime import UTC, datetime, timedelta
|
||||
import gzip
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.enums import AlertSeverity, AlertStatus, JobStatus
|
||||
from app.core.websocket import broadcaster as broadcaster_module
|
||||
from app.core.websocket.broadcaster import DataBroadcaster
|
||||
from app.models.alert import Alert
|
||||
from app.models.collected_data import CollectedData
|
||||
from app.models.data_snapshot import DataSnapshot
|
||||
from app.models.datasource import DataSource
|
||||
from app.models.task import CollectionTask
|
||||
from app.services import scheduler
|
||||
from app.services.collectors.base import BaseCollector
|
||||
from app.services.collectors.iptoasn import IPtoASNPrefixGeoCollector
|
||||
from app.services.collectors.nro_delegated import NRODelegatedPrefixGeoCollector
|
||||
from app.services.collectors.registry import collector_registry
|
||||
|
||||
|
||||
class _AsyncSQLiteSession:
|
||||
def __init__(self, session: Session):
|
||||
self._session = session
|
||||
|
||||
def get_bind(self):
|
||||
return self._session.get_bind()
|
||||
|
||||
def add(self, instance) -> None:
|
||||
self._session.add(instance)
|
||||
|
||||
def add_all(self, instances) -> None:
|
||||
self._session.add_all(instances)
|
||||
|
||||
async def get(self, entity, ident):
|
||||
return self._session.get(entity, ident)
|
||||
|
||||
async def execute(self, statement, params=None):
|
||||
if params is not None:
|
||||
return self._session.execute(statement, params)
|
||||
return self._session.execute(statement)
|
||||
|
||||
async def scalar(self, statement):
|
||||
return self._session.scalar(statement)
|
||||
|
||||
async def scalars(self, statement):
|
||||
return self._session.scalars(statement)
|
||||
|
||||
async def flush(self) -> None:
|
||||
self._session.flush()
|
||||
|
||||
async def commit(self) -> None:
|
||||
self._session.commit()
|
||||
|
||||
async def rollback(self) -> None:
|
||||
self._session.rollback()
|
||||
|
||||
async def refresh(self, instance) -> None:
|
||||
self._session.refresh(instance)
|
||||
|
||||
|
||||
class _DummySessionCtx:
|
||||
def __init__(self, sync_session: Session):
|
||||
self._wrapper = _AsyncSQLiteSession(sync_session)
|
||||
|
||||
async def __aenter__(self):
|
||||
return self._wrapper
|
||||
|
||||
async def __aexit__(self, *_args):
|
||||
return False
|
||||
|
||||
|
||||
def _create_collector_db():
|
||||
engine = create_engine("sqlite://")
|
||||
for model in (DataSource, CollectionTask, DataSnapshot, CollectedData, Alert):
|
||||
model.__table__.create(engine)
|
||||
return engine
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_heavy_collectors_serialize_without_blocking_light_collectors(monkeypatch):
|
||||
scheduler._COLLECTOR_SEMAPHORES.clear()
|
||||
scheduler._HEAVY_COLLECTOR_SEMAPHORES.clear()
|
||||
monkeypatch.setattr(settings, "COLLECTOR_MAX_CONCURRENCY", 2)
|
||||
monkeypatch.setattr(settings, "COLLECTOR_HEAVY_CONCURRENCY", 1)
|
||||
|
||||
events: list[tuple[str, str]] = []
|
||||
heavy_active = 0
|
||||
max_heavy_active = 0
|
||||
|
||||
class FakeCollector:
|
||||
def __init__(self, source_name: str, *, heavy: bool):
|
||||
self.name = source_name
|
||||
self._heavy = heavy
|
||||
self._datasource_id = 1
|
||||
|
||||
async def run(self, _db):
|
||||
nonlocal heavy_active, max_heavy_active
|
||||
events.append(("start", self.name))
|
||||
if self._heavy:
|
||||
heavy_active += 1
|
||||
max_heavy_active = max(max_heavy_active, heavy_active)
|
||||
await asyncio.sleep(0.08 if self._heavy else 0.02)
|
||||
if self._heavy:
|
||||
heavy_active -= 1
|
||||
events.append(("end", self.name))
|
||||
return {"status": "success"}
|
||||
|
||||
fake_collectors = {
|
||||
"iptoasn_prefix_geo": FakeCollector("iptoasn_prefix_geo", heavy=True),
|
||||
"nro_delegated_prefix_geo": FakeCollector("nro_delegated_prefix_geo", heavy=True),
|
||||
"light_source": FakeCollector("light_source", heavy=False),
|
||||
}
|
||||
|
||||
engine = _create_collector_db()
|
||||
with Session(engine) as s:
|
||||
s.add_all(
|
||||
[
|
||||
DataSource(
|
||||
id=1,
|
||||
name="IPtoASN",
|
||||
source="iptoasn_prefix_geo",
|
||||
module="L3",
|
||||
priority="P1",
|
||||
frequency_minutes=360,
|
||||
collector_class="iptoasn_prefix_geo",
|
||||
is_active=True,
|
||||
),
|
||||
DataSource(
|
||||
id=2,
|
||||
name="NRO",
|
||||
source="nro_delegated_prefix_geo",
|
||||
module="L3",
|
||||
priority="P1",
|
||||
frequency_minutes=720,
|
||||
collector_class="nro_delegated_prefix_geo",
|
||||
is_active=True,
|
||||
),
|
||||
DataSource(
|
||||
id=3,
|
||||
name="Light",
|
||||
source="light_source",
|
||||
module="L1",
|
||||
priority="P0",
|
||||
frequency_minutes=60,
|
||||
collector_class="light_source",
|
||||
is_active=True,
|
||||
),
|
||||
]
|
||||
)
|
||||
s.commit()
|
||||
|
||||
def session_factory():
|
||||
return _DummySessionCtx(Session(engine))
|
||||
|
||||
monkeypatch.setattr(scheduler, "async_session_factory", session_factory)
|
||||
monkeypatch.setattr(collector_registry, "get", lambda name: fake_collectors.get(name))
|
||||
|
||||
async def noop(*_args, **_kwargs):
|
||||
return None
|
||||
|
||||
async def fake_candidate(*_args, **_kwargs):
|
||||
return {"endpoint": "", "auth_type": "none", "headers": {}, "config": {}}
|
||||
|
||||
async def fake_checksum(*_args, **_kwargs):
|
||||
return ("chk", {})
|
||||
|
||||
monkeypatch.setattr(scheduler, "emit_business_log", noop)
|
||||
monkeypatch.setattr(scheduler, "_update_next_run_at", noop)
|
||||
monkeypatch.setattr(scheduler, "get_builtin_effective_candidate", fake_candidate)
|
||||
monkeypatch.setattr(scheduler, "build_builtin_connectivity_checksum", fake_checksum)
|
||||
monkeypatch.setattr(scheduler, "save_connectivity_success", noop)
|
||||
|
||||
await asyncio.gather(
|
||||
scheduler.run_collector_task("iptoasn_prefix_geo"),
|
||||
scheduler.run_collector_task("nro_delegated_prefix_geo"),
|
||||
scheduler.run_collector_task("light_source"),
|
||||
)
|
||||
|
||||
assert max_heavy_active == 1
|
||||
first_heavy_end = next(
|
||||
idx for idx, item in enumerate(events) if item[0] == "end" and item[1] in scheduler.HEAVY_COLLECTOR_SOURCES
|
||||
)
|
||||
second_heavy_start = max(
|
||||
idx for idx, item in enumerate(events) if item[0] == "start" and item[1] in scheduler.HEAVY_COLLECTOR_SOURCES
|
||||
)
|
||||
assert second_heavy_start > first_heavy_end
|
||||
light_end = events.index(("end", "light_source"))
|
||||
assert light_end < second_heavy_start
|
||||
|
||||
scheduler._COLLECTOR_SEMAPHORES.clear()
|
||||
scheduler._HEAVY_COLLECTOR_SEMAPHORES.clear()
|
||||
engine.dispose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_large_collector_offloading_and_core_bulk_incremental_upsert(
|
||||
monkeypatch, tmp_path: Path
|
||||
):
|
||||
# Verify streaming NRO parser & gzip IPtoASN parser work cleanly on files.
|
||||
nro_file = tmp_path / "delegated.txt"
|
||||
nro_lines = [
|
||||
"# header",
|
||||
"apnic|CN|ipv4|1.0.1.0|256|20110414|allocated",
|
||||
"ripencc|DE|ipv6|2001:db8::|32|20200101|assigned",
|
||||
"arin|US|asn|15169|1|20000101|allocated",
|
||||
]
|
||||
nro_file.write_text("\n".join(nro_lines), encoding="utf-8")
|
||||
nro_collector = NRODelegatedPrefixGeoCollector()
|
||||
parsed_nro = await asyncio.to_thread(nro_collector._parse_delegated_file, nro_file)
|
||||
assert len(parsed_nro) == 2
|
||||
transformed_nro = nro_collector.transform(parsed_nro)
|
||||
assert len(transformed_nro) == 2
|
||||
|
||||
gz_file = tmp_path / "iptoasn.tsv.gz"
|
||||
with gzip.open(gz_file, "wt", encoding="utf-8") as fh:
|
||||
fh.write("1.0.0.0\t1.0.0.255\t13335\tAU\tCLOUDFLARENET\n")
|
||||
ip_collector = IPtoASNPrefixGeoCollector()
|
||||
parsed_ip = await asyncio.to_thread(ip_collector._parse_dataset_files, [gz_file])
|
||||
assert len(parsed_ip) == 1
|
||||
|
||||
# Verify >=1500 row offloaded transform/prepare + Core bulk insert + incremental update/unchanged/delete.
|
||||
engine = _create_collector_db()
|
||||
|
||||
class BulkTestCollector(BaseCollector):
|
||||
name = "bulk_test_source"
|
||||
data_type = "prefix_geography"
|
||||
full_snapshot_reconcile = True
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.rows: list[dict] = []
|
||||
|
||||
async def fetch(self):
|
||||
return list(self.rows)
|
||||
|
||||
def transform(self, raw_data):
|
||||
return [
|
||||
{
|
||||
"source_id": item["id"],
|
||||
"name": item["name"],
|
||||
"title": item["name"],
|
||||
"country": "CN",
|
||||
"metadata": {"seq": item["seq"]},
|
||||
"reference_date": "2026-11-23T00:00:00Z",
|
||||
}
|
||||
for item in raw_data
|
||||
]
|
||||
|
||||
monkeypatch.setattr(collector_registry, "is_active", lambda _name: True)
|
||||
collector = BulkTestCollector()
|
||||
collector.rows = [{"id": f"id-{i}", "name": f"Node {i}", "seq": i} for i in range(1500)]
|
||||
|
||||
ticks = 0
|
||||
keep_ticking = True
|
||||
|
||||
async def ticker():
|
||||
nonlocal ticks
|
||||
while keep_ticking:
|
||||
ticks += 1
|
||||
await asyncio.sleep(0.005)
|
||||
|
||||
with Session(engine) as sync_session:
|
||||
db = _AsyncSQLiteSession(sync_session)
|
||||
sync_session.add(
|
||||
DataSource(
|
||||
id=1,
|
||||
name="Bulk Test",
|
||||
source="bulk_test_source",
|
||||
module="L3",
|
||||
priority="P1",
|
||||
frequency_minutes=60,
|
||||
collector_class="bulk_test_source",
|
||||
is_active=True,
|
||||
)
|
||||
)
|
||||
sync_session.commit()
|
||||
|
||||
tick_task = asyncio.create_task(ticker())
|
||||
try:
|
||||
first_result = await collector.run(db)
|
||||
finally:
|
||||
keep_ticking = False
|
||||
await tick_task
|
||||
|
||||
assert first_result["status"] == "success"
|
||||
assert first_result["records_processed"] == 1500
|
||||
assert collector._last_save_summary == {
|
||||
"created": 1500,
|
||||
"updated": 0,
|
||||
"unchanged": 0,
|
||||
"deleted": 0,
|
||||
}
|
||||
assert ticks >= 1
|
||||
|
||||
# Verify Core bulk insert populated extra_data and content_hash without comparable_payload leak.
|
||||
sample = sync_session.execute(
|
||||
select(CollectedData).where(CollectedData.source_id == "id-42")
|
||||
).scalar_one()
|
||||
assert sample.extra_data["seq"] == 42
|
||||
assert sample.extra_data["country"] == "中国"
|
||||
assert sample.content_hash is not None
|
||||
|
||||
# Incremental update: update 1 row, vanish 1 row, leave 1498 unchanged, create 1 new row.
|
||||
collector.rows = [
|
||||
item for item in collector.rows if item["id"] != "id-0"
|
||||
]
|
||||
collector.rows[0] = {"id": "id-1", "name": "Node 1 Updated", "seq": 9999}
|
||||
collector.rows.append({"id": "id-new", "name": "Node New", "seq": 2000})
|
||||
|
||||
second_result = await collector.run(db)
|
||||
assert second_result["status"] == "success"
|
||||
assert second_result["records_processed"] == 1500
|
||||
assert collector._last_save_summary == {
|
||||
"created": 1,
|
||||
"updated": 1,
|
||||
"unchanged": 1498,
|
||||
"deleted": 1,
|
||||
}
|
||||
|
||||
engine.dispose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_dashboard_broadcaster_skips_when_unsubscribed_and_queries_real_stats(monkeypatch):
|
||||
engine = _create_collector_db()
|
||||
with Session(engine) as s:
|
||||
now = datetime.now(UTC)
|
||||
s.add_all(
|
||||
[
|
||||
DataSource(
|
||||
id=1,
|
||||
name="Active A",
|
||||
source="a",
|
||||
module="L1",
|
||||
priority="P0",
|
||||
frequency_minutes=60,
|
||||
collector_class="a",
|
||||
is_active=True,
|
||||
),
|
||||
DataSource(
|
||||
id=2,
|
||||
name="Paused B",
|
||||
source="b",
|
||||
module="L2",
|
||||
priority="P1",
|
||||
frequency_minutes=60,
|
||||
collector_class="b",
|
||||
is_active=False,
|
||||
),
|
||||
CollectionTask(
|
||||
datasource_id=1,
|
||||
source="a",
|
||||
status=JobStatus.SUCCESS.value,
|
||||
created_at=now,
|
||||
),
|
||||
CollectionTask(
|
||||
datasource_id=1,
|
||||
source="a",
|
||||
status=JobStatus.SUCCESS.value,
|
||||
created_at=now,
|
||||
),
|
||||
CollectionTask(
|
||||
datasource_id=2,
|
||||
source="b",
|
||||
status=JobStatus.FAILED.value,
|
||||
created_at=now,
|
||||
),
|
||||
CollectionTask(
|
||||
datasource_id=1,
|
||||
source="a",
|
||||
status=JobStatus.FAILED.value,
|
||||
created_at=now - timedelta(days=2),
|
||||
),
|
||||
Alert(severity=AlertSeverity.CRITICAL, status=AlertStatus.ACTIVE, message="crit"),
|
||||
Alert(severity=AlertSeverity.WARNING, status=AlertStatus.ACTIVE, message="warn"),
|
||||
Alert(severity=AlertSeverity.WARNING, status=AlertStatus.RESOLVED, message="old"),
|
||||
]
|
||||
)
|
||||
s.commit()
|
||||
|
||||
from app import db as db_pkg
|
||||
|
||||
monkeypatch.setattr(db_pkg.session, "async_session_factory", lambda: _DummySessionCtx(Session(engine)))
|
||||
|
||||
broadcaster = DataBroadcaster()
|
||||
stats = await broadcaster.get_dashboard_stats()
|
||||
assert stats["total_datasources"] == 2
|
||||
assert stats["active_datasources"] == 1
|
||||
assert stats["tasks_today"] == 3
|
||||
assert stats["success_rate"] == 66.7
|
||||
assert stats["alerts"] == {"critical": 1, "warning": 1, "info": 0}
|
||||
|
||||
import importlib
|
||||
|
||||
ws_broadcaster_mod = importlib.import_module("app.core.websocket.broadcaster")
|
||||
monkeypatch.setattr(ws_broadcaster_mod.manager, "channel_subscriptions", {})
|
||||
query_calls = 0
|
||||
|
||||
async def fail_if_called():
|
||||
nonlocal query_calls
|
||||
query_calls += 1
|
||||
broadcaster.running = False
|
||||
return stats
|
||||
|
||||
monkeypatch.setattr(broadcaster, "get_dashboard_stats", fail_if_called)
|
||||
|
||||
async def stop_sleep(_sec):
|
||||
broadcaster.running = False
|
||||
|
||||
monkeypatch.setattr(ws_broadcaster_mod.asyncio, "sleep", stop_sleep)
|
||||
broadcaster.running = True
|
||||
await broadcaster.broadcast_stats(interval=5)
|
||||
assert query_calls == 0
|
||||
|
||||
engine.dispose()
|
||||
@@ -3,17 +3,25 @@ from types import SimpleNamespace
|
||||
import pytest
|
||||
from unittest.mock import AsyncMock
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from sqlalchemy import create_engine, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.api.v1.datasource_config import get_ai_provider_client
|
||||
from app.core.websocket import broadcaster as broadcaster_module
|
||||
from app.core.security import get_current_user
|
||||
from app.core.target_schema_registry import get_target_schema, list_target_schemas
|
||||
from app.db.session import Base
|
||||
from app.main import app
|
||||
from app.models.user import User
|
||||
from app.models.collected_data import CollectedData
|
||||
from app.models.data_snapshot import DataSnapshot
|
||||
from app.models.datasource_config import DataSourceConfig
|
||||
from app.models.system_setting import SystemSetting
|
||||
from app.models.task import CollectionTask
|
||||
from app.models.user import User
|
||||
from app.services import custom_datasource_runtime
|
||||
from app.services.custom_datasource_runtime import run_mapped_websocket_config
|
||||
from app.services.datasource_mapping import execute_mapping, persist_mapped_records, redact_for_llm
|
||||
from app.services.storage_policy import save_storage_policy
|
||||
|
||||
|
||||
SAMPLE_AIS = {
|
||||
@@ -326,3 +334,100 @@ async def test_mapping_propose_api_redacts_sample_before_ai():
|
||||
payload = response.json()
|
||||
assert payload["mapping_json"]["meta"]["generated_by"] == "ai_provider"
|
||||
assert seen_context["sample_payload"]["data"][0]["api_token"] == "[REDACTED]"
|
||||
|
||||
|
||||
class _AsyncMappingSQLiteSession:
|
||||
def __init__(self, session: Session):
|
||||
self._session = session
|
||||
|
||||
def add(self, instance) -> None:
|
||||
self._session.add(instance)
|
||||
|
||||
async def execute(self, statement, params=None):
|
||||
if params is not None:
|
||||
return self._session.execute(statement, params)
|
||||
return self._session.execute(statement)
|
||||
|
||||
async def flush(self) -> None:
|
||||
self._session.flush()
|
||||
|
||||
async def commit(self) -> None:
|
||||
self._session.commit()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_persist_mapped_records_isolates_same_name_configs_and_enforces_lock():
|
||||
engine = create_engine("sqlite:///:memory:")
|
||||
Base.metadata.create_all(
|
||||
engine,
|
||||
tables=[
|
||||
SystemSetting.__table__,
|
||||
CollectionTask.__table__,
|
||||
DataSnapshot.__table__,
|
||||
CollectedData.__table__,
|
||||
],
|
||||
)
|
||||
try:
|
||||
with Session(engine) as sync_session:
|
||||
db = _AsyncMappingSQLiteSession(sync_session)
|
||||
await save_storage_policy(
|
||||
db,
|
||||
{
|
||||
"default_mode": "single",
|
||||
"global_single_lock": True,
|
||||
"overrides": {},
|
||||
},
|
||||
sync_system_retention=False,
|
||||
)
|
||||
|
||||
await persist_mapped_records(
|
||||
db,
|
||||
datasource_name="SharedDisplayName",
|
||||
datasource_config_id=101,
|
||||
target_schema="geo_points",
|
||||
records=[
|
||||
{
|
||||
"source_id": "biz-1",
|
||||
"name": "Alpha Point",
|
||||
"lat": 31.23,
|
||||
"lon": 121.47,
|
||||
"metadata": {"origin": "feed-a"},
|
||||
}
|
||||
],
|
||||
mapping_version=1,
|
||||
snapshot_mode="history",
|
||||
)
|
||||
await persist_mapped_records(
|
||||
db,
|
||||
datasource_name="SharedDisplayName",
|
||||
datasource_config_id=102,
|
||||
target_schema="geo_points",
|
||||
records=[
|
||||
{
|
||||
"source_id": "biz-1",
|
||||
"name": "Beta Point",
|
||||
"lat": 39.90,
|
||||
"lon": 116.40,
|
||||
"metadata": {"origin": "feed-b"},
|
||||
}
|
||||
],
|
||||
mapping_version=1,
|
||||
snapshot_mode="history",
|
||||
)
|
||||
|
||||
rows = list(
|
||||
sync_session.scalars(
|
||||
select(CollectedData)
|
||||
.where(
|
||||
CollectedData.source == "SharedDisplayName",
|
||||
CollectedData.is_current.is_(True),
|
||||
)
|
||||
.order_by(CollectedData.id.asc())
|
||||
).all()
|
||||
)
|
||||
assert len(rows) == 2
|
||||
assert {row.name for row in rows} == {"Alpha Point", "Beta Point"}
|
||||
assert {row.extra_data["datasource_config_id"] for row in rows} == {101, 102}
|
||||
assert len({row.entity_key for row in rows}) == 2
|
||||
finally:
|
||||
engine.dispose()
|
||||
@@ -1,6 +1,10 @@
|
||||
import asyncio
|
||||
import inspect
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
|
||||
from app.api.v1 import datasources as datasources_api
|
||||
from app.models.datasource import DataSource
|
||||
@@ -219,3 +223,128 @@ def test_trigger_datasource_batch_skips_disabled_and_frequency_window(monkeypatc
|
||||
assert queued_sources == ["ris_live_bgp"]
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
class _CommitDb:
|
||||
def __init__(self, datasources=None):
|
||||
self.commits = 0
|
||||
self.datasources = list(datasources or [])
|
||||
|
||||
async def commit(self):
|
||||
self.commits += 1
|
||||
|
||||
async def execute(self, _query):
|
||||
datasources = self.datasources
|
||||
|
||||
class _Result:
|
||||
def scalars(self):
|
||||
return self
|
||||
|
||||
def all(self):
|
||||
return datasources
|
||||
|
||||
return _Result()
|
||||
|
||||
|
||||
def _patch_row_helpers(monkeypatch, synced: list[int]):
|
||||
async def fake_sync(datasource_id):
|
||||
synced.append(datasource_id)
|
||||
|
||||
async def fake_rows(_db, datasources):
|
||||
return [{"id": item.id, "source": item.source, "is_active": item.is_active} for item in datasources]
|
||||
|
||||
async def fake_counts(_db):
|
||||
return {"all": 3, "active": 2, "inactive": 1}
|
||||
|
||||
monkeypatch.setattr(datasources_api, "sync_datasource_job", fake_sync)
|
||||
monkeypatch.setattr(datasources_api, "_serialize_datasource_rows", fake_rows)
|
||||
monkeypatch.setattr(datasources_api, "_load_datasource_status_counts", fake_counts)
|
||||
|
||||
|
||||
def test_activation_only_commits_and_syncs_changed_sources(monkeypatch):
|
||||
async def run():
|
||||
synced: list[int] = []
|
||||
_patch_row_helpers(monkeypatch, synced)
|
||||
db = _CommitDb()
|
||||
enabled = make_datasource(1, "arcgis_cables", is_active=True)
|
||||
disabled = make_datasource(2, "ris_live_bgp", is_active=False)
|
||||
|
||||
changed, failed = await datasources_api._apply_datasource_activation(db, [enabled, disabled], True)
|
||||
|
||||
assert [item.id for item in changed] == [2]
|
||||
assert disabled.is_active is True
|
||||
assert failed == []
|
||||
assert synced == [2]
|
||||
assert db.commits == 1
|
||||
|
||||
unchanged, _ = await datasources_api._apply_datasource_activation(db, [enabled], True)
|
||||
assert unchanged == []
|
||||
assert db.commits == 1
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_batch_status_reports_updated_unchanged_and_missing(monkeypatch):
|
||||
async def run():
|
||||
synced: list[int] = []
|
||||
_patch_row_helpers(monkeypatch, synced)
|
||||
already = make_datasource(1, "arcgis_cables", is_active=True)
|
||||
target = make_datasource(2, "ris_live_bgp", is_active=False)
|
||||
db = _CommitDb([already, target])
|
||||
admin = SimpleNamespace(id=9, role="admin")
|
||||
|
||||
result = await datasources_api.update_datasource_batch_status(
|
||||
datasources_api.DatasourceBatchStatusRequest(source_ids=[1, 2, 2, 99], is_active=True),
|
||||
current_user=admin,
|
||||
db=db,
|
||||
)
|
||||
|
||||
assert [row["id"] for row in result["updated"]] == [2]
|
||||
assert result["updated"][0]["is_active"] is True
|
||||
assert result["unchanged"] == [1]
|
||||
assert result["not_found"] == [99]
|
||||
assert result["sync_failed"] == []
|
||||
assert result["counts"] == {"all": 3, "active": 2, "inactive": 1}
|
||||
assert synced == [2]
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_scheduling_changes_require_admin(monkeypatch):
|
||||
async def run():
|
||||
_patch_row_helpers(monkeypatch, [])
|
||||
viewer = SimpleNamespace(id=5, role="viewer")
|
||||
with pytest.raises(HTTPException) as batch_error:
|
||||
await datasources_api.update_datasource_batch_status(
|
||||
datasources_api.DatasourceBatchStatusRequest(source_ids=[1], is_active=False),
|
||||
current_user=viewer,
|
||||
db=_CommitDb(),
|
||||
)
|
||||
with pytest.raises(HTTPException) as single_error:
|
||||
await datasources_api.enable_datasource("1", current_user=viewer, db=_CommitDb())
|
||||
assert batch_error.value.status_code == 403
|
||||
assert single_error.value.status_code == 403
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_single_toggle_returns_row_and_counts(monkeypatch):
|
||||
async def run():
|
||||
synced: list[int] = []
|
||||
_patch_row_helpers(monkeypatch, synced)
|
||||
datasource = make_datasource(4, "ris_live_bgp", is_active=False)
|
||||
|
||||
async def fake_record(_db, _source_id):
|
||||
return datasource
|
||||
|
||||
monkeypatch.setattr(datasources_api, "get_datasource_record", fake_record)
|
||||
result = await datasources_api.enable_datasource(
|
||||
"4", current_user=SimpleNamespace(id=1, role="super_admin"), db=_CommitDb()
|
||||
)
|
||||
|
||||
assert result["status"] == "enabled"
|
||||
assert result["data"] == {"id": 4, "source": "ris_live_bgp", "is_active": True}
|
||||
assert result["counts"]["active"] == 2
|
||||
assert synced == [4]
|
||||
|
||||
asyncio.run(run())
|
||||
@@ -1,6 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import gzip
|
||||
import json
|
||||
|
||||
import httpx
|
||||
@@ -9,6 +10,7 @@ from fastapi import FastAPI, HTTPException, Response
|
||||
|
||||
from app.api.v1 import visualization
|
||||
from app.services.earth_layer_cache import (
|
||||
_ENCODED_ARTIFACT_CACHE,
|
||||
EarthLayerCachePolicy,
|
||||
apply_payload_budget,
|
||||
earth_layer_cache,
|
||||
@@ -81,9 +83,11 @@ def fake_cache_client():
|
||||
previous = earth_layer_cache._client
|
||||
fake = FakeRedis()
|
||||
earth_layer_cache._client = fake
|
||||
_ENCODED_ARTIFACT_CACHE.clear()
|
||||
try:
|
||||
yield fake
|
||||
finally:
|
||||
_ENCODED_ARTIFACT_CACHE.clear()
|
||||
earth_layer_cache._client = previous
|
||||
|
||||
|
||||
@@ -566,3 +570,99 @@ def test_invalidate_earth_layer_cache_for_source_degrades_gracefully_on_redis_fa
|
||||
assert invalidate_earth_layer_cache_for_source("ris_live_bgp") == 0
|
||||
finally:
|
||||
earth_layer_cache._client = previous
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_satellites_endpoint_supports_compact_gzip_and_etag_304(
|
||||
fake_cache_client,
|
||||
monkeypatch,
|
||||
):
|
||||
geojson_calls = 0
|
||||
compact_calls = 0
|
||||
|
||||
async def fake_build_satellites_geojson(*, limit, db):
|
||||
nonlocal geojson_calls
|
||||
geojson_calls += 1
|
||||
return {
|
||||
"type": "FeatureCollection",
|
||||
"features": [{"type": "Feature", "id": 25544, "properties": {"id": 1}}],
|
||||
"count": 1,
|
||||
}
|
||||
|
||||
async def fake_build_satellites_compact(*, limit, db):
|
||||
nonlocal compact_calls
|
||||
compact_calls += 1
|
||||
return {
|
||||
"format": "satellite_compact_v1",
|
||||
"count": 1,
|
||||
"fields": [
|
||||
"id",
|
||||
"norad_cat_id",
|
||||
"name",
|
||||
"constellation_group",
|
||||
"tle_line1",
|
||||
"tle_line2",
|
||||
"fallback_elements",
|
||||
],
|
||||
"satellites": [[1, 25544, "ISS (ZARYA)", "leo", "1 25544U ...", "2 25544 ..."]],
|
||||
}
|
||||
|
||||
monkeypatch.setattr(visualization, "_build_satellites_geojson", fake_build_satellites_geojson)
|
||||
monkeypatch.setattr(visualization, "_build_satellites_compact", fake_build_satellites_compact)
|
||||
|
||||
app = FastAPI()
|
||||
app.include_router(visualization.router, prefix="/api/v1/visualization")
|
||||
app.dependency_overrides[visualization.get_db] = lambda: object()
|
||||
|
||||
async with httpx.AsyncClient(
|
||||
transport=httpx.ASGITransport(app=app),
|
||||
base_url="http://test",
|
||||
) as client:
|
||||
first_compact = await client.get(
|
||||
"/api/v1/visualization/geo/satellites?format=compact",
|
||||
headers={"Accept-Encoding": "gzip"},
|
||||
)
|
||||
assert first_compact.status_code == 200
|
||||
assert first_compact.headers["X-Planet-Cache"] == "refresh"
|
||||
assert first_compact.headers["X-Planet-Cache-Features"] == "1"
|
||||
assert first_compact.headers["Content-Encoding"] == "gzip"
|
||||
etag = first_compact.headers["ETag"]
|
||||
assert etag
|
||||
assert first_compact.json()["format"] == "satellite_compact_v1"
|
||||
assert first_compact.json()["satellites"][0][1] == 25544
|
||||
|
||||
second_compact = await client.get(
|
||||
"/api/v1/visualization/geo/satellites?format=compact",
|
||||
headers={"Accept-Encoding": "gzip"},
|
||||
)
|
||||
assert second_compact.status_code == 200
|
||||
assert second_compact.headers["X-Planet-Cache"] == "hit"
|
||||
assert second_compact.headers["ETag"] == etag
|
||||
assert second_compact.headers["Content-Encoding"] == "gzip"
|
||||
|
||||
not_modified = await client.get(
|
||||
"/api/v1/visualization/geo/satellites?format=compact",
|
||||
headers={"If-None-Match": etag, "Accept-Encoding": "gzip"},
|
||||
)
|
||||
assert not_modified.status_code == 304
|
||||
assert not_modified.content == b""
|
||||
assert not_modified.headers["ETag"] == etag
|
||||
|
||||
plain_geo = await client.get(
|
||||
"/api/v1/visualization/geo/satellites",
|
||||
headers={"Accept-Encoding": "identity"},
|
||||
)
|
||||
assert plain_geo.status_code == 200
|
||||
assert "content-encoding" not in {k.lower() for k in plain_geo.headers.keys()}
|
||||
assert plain_geo.json()["type"] == "FeatureCollection"
|
||||
assert geojson_calls == 1
|
||||
assert compact_calls == 1
|
||||
|
||||
# Verify raw bytes cached cleanly match uncompressed response and encoded artifact gzip round-trips
|
||||
raw_cached = fake_cache_client.store[
|
||||
earth_layer_cache.key("satellites", format="compact", limit="all")
|
||||
]
|
||||
assert json.loads(raw_cached)["count"] == 1
|
||||
assert second_compact.json()["count"] == 1
|
||||
artifact = next(iter(_ENCODED_ARTIFACT_CACHE.values()))
|
||||
assert gzip.decompress(artifact.gzip_bytes) == artifact.raw_bytes
|
||||
@@ -446,10 +446,10 @@ async def test_earth_news_refresh_scheduler_job_survives_datasource_sync(monkeyp
|
||||
_earth_news_region_refresh_job_id("global")
|
||||
),
|
||||
}
|
||||
self.added: dict[str, object] = {}
|
||||
self.added_jobs: dict[str, dict[str, object]] = {}
|
||||
|
||||
def add_job(self, _func, **kwargs):
|
||||
self.added.update(kwargs)
|
||||
self.added_jobs[kwargs["id"]] = dict(kwargs)
|
||||
self.jobs[kwargs["id"]] = FakeJob(kwargs["id"])
|
||||
|
||||
def start(self) -> None:
|
||||
@@ -484,8 +484,8 @@ async def test_earth_news_refresh_scheduler_job_survives_datasource_sync(monkeyp
|
||||
start_scheduler()
|
||||
await sync_scheduler_with_datasources()
|
||||
|
||||
assert fake_scheduler.added["id"] == EARTH_NEWS_REFRESH_JOB_ID
|
||||
assert fake_scheduler.added["next_run_time"] <= datetime.now(UTC)
|
||||
assert EARTH_NEWS_REFRESH_JOB_ID in fake_scheduler.added_jobs
|
||||
assert fake_scheduler.added_jobs[EARTH_NEWS_REFRESH_JOB_ID]["next_run_time"] <= datetime.now(UTC)
|
||||
assert EARTH_NEWS_REFRESH_JOB_ID in fake_scheduler.jobs
|
||||
assert _earth_news_region_refresh_job_id("global") in fake_scheduler.jobs
|
||||
assert "obsolete" not in fake_scheduler.jobs
|
||||
|
||||
@@ -0,0 +1,329 @@
|
||||
"""Tests for role split, scheduler leader locking, Redis WS Pub/Sub, and DB migrations."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from contextlib import asynccontextmanager
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
from app import main as main_module
|
||||
from app import worker as worker_module
|
||||
from app.core.config import settings
|
||||
from app.core.websocket.manager import ConnectionManager
|
||||
from app.db.migrations import (
|
||||
ensure_baseline_stamped,
|
||||
get_migration_status,
|
||||
run_migrations,
|
||||
stamp_migrations,
|
||||
)
|
||||
|
||||
|
||||
class _AsyncSQLiteConnAdapter:
|
||||
def __init__(self, conn):
|
||||
self._conn = conn
|
||||
self.dialect = conn.dialect
|
||||
|
||||
async def execute(self, statement, params=None):
|
||||
if params is not None:
|
||||
return self._conn.execute(statement, params)
|
||||
return self._conn.execute(statement)
|
||||
|
||||
async def run_sync(self, fn):
|
||||
return fn(self._conn)
|
||||
|
||||
|
||||
class _AsyncSQLiteEngineAdapter:
|
||||
def __init__(self, sync_engine):
|
||||
self._engine = sync_engine
|
||||
|
||||
@asynccontextmanager
|
||||
async def begin(self):
|
||||
with self._engine.begin() as conn:
|
||||
yield _AsyncSQLiteConnAdapter(conn)
|
||||
|
||||
|
||||
class _FakeWebSocket:
|
||||
def __init__(self):
|
||||
self.accepted = False
|
||||
self.sent = []
|
||||
self.closed = False
|
||||
|
||||
async def accept(self):
|
||||
self.accepted = True
|
||||
|
||||
async def send_json(self, message):
|
||||
self.sent.append(message)
|
||||
|
||||
async def close(self):
|
||||
self.closed = True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_lifespan_respects_planet_role_and_leader_lock(monkeypatch):
|
||||
calls: list[str] = []
|
||||
|
||||
async def noop_async(*_args, **_kwargs):
|
||||
return None
|
||||
|
||||
async def true_lock():
|
||||
calls.append("acquire_lock")
|
||||
return True
|
||||
|
||||
async def false_lock():
|
||||
calls.append("acquire_lock_denied")
|
||||
return False
|
||||
|
||||
monkeypatch.setattr(main_module, "init_db", noop_async)
|
||||
monkeypatch.setattr(main_module, "cleanup_stale_running_tasks", lambda: noop_async())
|
||||
monkeypatch.setattr(main_module, "sync_scheduler_with_datasources", lambda: noop_async())
|
||||
monkeypatch.setattr(main_module, "release_scheduler_leader_lock", lambda: noop_async())
|
||||
monkeypatch.setattr(main_module, "start_scheduler", lambda: calls.append("start_scheduler"))
|
||||
monkeypatch.setattr(main_module, "stop_scheduler", lambda: calls.append("stop_scheduler"))
|
||||
monkeypatch.setattr(main_module, "start_data_job_worker", lambda: calls.append("start_jobs"))
|
||||
monkeypatch.setattr(main_module, "stop_data_job_worker", lambda: noop_async())
|
||||
monkeypatch.setattr(main_module, "start_earth_news_target_worker", lambda: calls.append("start_news"))
|
||||
monkeypatch.setattr(main_module, "stop_earth_news_target_worker", lambda: noop_async())
|
||||
monkeypatch.setattr(main_module, "start_earth_db_change_listener", lambda: calls.append("start_db_listener"))
|
||||
monkeypatch.setattr(main_module, "stop_earth_db_change_listener", lambda: noop_async())
|
||||
monkeypatch.setattr(main_module.broadcaster, "start", lambda: calls.append("start_broadcaster"))
|
||||
monkeypatch.setattr(main_module.broadcaster, "stop", lambda: calls.append("stop_broadcaster"))
|
||||
monkeypatch.setattr(main_module.manager, "start_pubsub", lambda **_kwargs: noop_async())
|
||||
monkeypatch.setattr(main_module.manager, "stop_pubsub", lambda: noop_async())
|
||||
|
||||
# Role=api must not start scheduler or background workers.
|
||||
monkeypatch.setattr(settings, "PLANET_ROLE", "api")
|
||||
monkeypatch.setattr(settings, "ENABLE_SCHEDULER", None)
|
||||
monkeypatch.setattr(main_module, "acquire_scheduler_leader_lock", true_lock)
|
||||
calls.clear()
|
||||
async with main_module.lifespan(FastAPI()):
|
||||
pass
|
||||
assert "start_scheduler" not in calls
|
||||
assert "start_jobs" not in calls
|
||||
assert "start_news" not in calls
|
||||
assert "start_broadcaster" in calls
|
||||
|
||||
# Role=all with leader lock denied skips scheduler start cleanly.
|
||||
monkeypatch.setattr(settings, "PLANET_ROLE", "all")
|
||||
monkeypatch.setattr(main_module, "acquire_scheduler_leader_lock", false_lock)
|
||||
calls.clear()
|
||||
async with main_module.lifespan(FastAPI()):
|
||||
pass
|
||||
assert "acquire_lock_denied" in calls
|
||||
assert "start_scheduler" not in calls
|
||||
assert "start_jobs" in calls
|
||||
|
||||
# Role=all with leader lock acquired starts scheduler and workers.
|
||||
monkeypatch.setattr(main_module, "acquire_scheduler_leader_lock", true_lock)
|
||||
calls.clear()
|
||||
async with main_module.lifespan(FastAPI()):
|
||||
pass
|
||||
assert "acquire_lock" in calls
|
||||
assert "start_scheduler" in calls
|
||||
assert "stop_scheduler" in calls
|
||||
assert "start_jobs" in calls
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_standalone_worker_starts_scheduler_workers_and_releases_lock(monkeypatch):
|
||||
events: list[str] = []
|
||||
|
||||
async def noop_async(*_args, **_kwargs):
|
||||
return None
|
||||
|
||||
async def acquire_lock():
|
||||
events.append("lock_acquired")
|
||||
return True
|
||||
|
||||
async def release_lock():
|
||||
events.append("lock_released")
|
||||
|
||||
async def fake_start_pubsub(*, publish_only: bool = False):
|
||||
events.append(f"pubsub:{publish_only}")
|
||||
|
||||
monkeypatch.setattr(worker_module, "init_db", noop_async)
|
||||
monkeypatch.setattr(worker_module, "cleanup_stale_running_tasks", noop_async)
|
||||
monkeypatch.setattr(worker_module, "sync_scheduler_with_datasources", noop_async)
|
||||
monkeypatch.setattr(worker_module, "acquire_scheduler_leader_lock", acquire_lock)
|
||||
monkeypatch.setattr(worker_module, "release_scheduler_leader_lock", release_lock)
|
||||
monkeypatch.setattr(worker_module, "start_scheduler", lambda: events.append("scheduler_started"))
|
||||
monkeypatch.setattr(worker_module, "stop_scheduler", lambda: events.append("scheduler_stopped"))
|
||||
monkeypatch.setattr(worker_module, "start_data_job_worker", lambda: events.append("jobs_started"))
|
||||
monkeypatch.setattr(worker_module, "stop_data_job_worker", noop_async)
|
||||
monkeypatch.setattr(worker_module, "start_earth_news_target_worker", lambda: events.append("news_started"))
|
||||
monkeypatch.setattr(worker_module, "stop_earth_news_target_worker", noop_async)
|
||||
monkeypatch.setattr(worker_module.broadcaster, "start", lambda: events.append("broadcaster_started"))
|
||||
monkeypatch.setattr(worker_module.broadcaster, "stop", lambda: events.append("broadcaster_stopped"))
|
||||
monkeypatch.setattr(worker_module.manager, "start_pubsub", fake_start_pubsub)
|
||||
monkeypatch.setattr(worker_module.manager, "stop_pubsub", noop_async)
|
||||
monkeypatch.setattr(settings, "PLANET_ROLE", "worker")
|
||||
monkeypatch.setattr(settings, "ENABLE_SCHEDULER", None)
|
||||
|
||||
stop_event = asyncio.Event()
|
||||
task = asyncio.create_task(worker_module.run_worker(stop_event))
|
||||
await asyncio.sleep(0.05)
|
||||
stop_event.set()
|
||||
await task
|
||||
|
||||
assert "pubsub:True" in events
|
||||
assert "lock_acquired" in events
|
||||
assert "scheduler_started" in events
|
||||
assert "jobs_started" in events
|
||||
assert "scheduler_stopped" in events
|
||||
assert "lock_released" in events
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_worker_releases_leader_lock_when_startup_fails(monkeypatch):
|
||||
events: list[str] = []
|
||||
|
||||
async def noop_async(*_args, **_kwargs):
|
||||
return None
|
||||
|
||||
async def acquire_lock():
|
||||
events.append("lock_acquired")
|
||||
return True
|
||||
|
||||
async def release_lock():
|
||||
events.append("lock_released")
|
||||
|
||||
async def failing_sync():
|
||||
raise RuntimeError("scheduler sync failed")
|
||||
|
||||
async def fake_stop_pubsub():
|
||||
events.append("pubsub_stopped")
|
||||
|
||||
monkeypatch.setattr(worker_module, "init_db", noop_async)
|
||||
monkeypatch.setattr(worker_module, "cleanup_stale_running_tasks", noop_async)
|
||||
monkeypatch.setattr(worker_module, "sync_scheduler_with_datasources", failing_sync)
|
||||
monkeypatch.setattr(worker_module, "acquire_scheduler_leader_lock", acquire_lock)
|
||||
monkeypatch.setattr(worker_module, "release_scheduler_leader_lock", release_lock)
|
||||
monkeypatch.setattr(worker_module, "start_scheduler", lambda: events.append("scheduler_started"))
|
||||
monkeypatch.setattr(worker_module, "stop_scheduler", lambda: events.append("scheduler_stopped"))
|
||||
monkeypatch.setattr(worker_module.manager, "start_pubsub", noop_async)
|
||||
monkeypatch.setattr(worker_module.manager, "stop_pubsub", fake_stop_pubsub)
|
||||
monkeypatch.setattr(settings, "PLANET_ROLE", "worker")
|
||||
monkeypatch.setattr(settings, "ENABLE_SCHEDULER", None)
|
||||
|
||||
with pytest.raises(RuntimeError, match="scheduler sync failed"):
|
||||
await worker_module.run_worker(asyncio.Event())
|
||||
|
||||
assert events == [
|
||||
"lock_acquired",
|
||||
"scheduler_started",
|
||||
"scheduler_stopped",
|
||||
"lock_released",
|
||||
"pubsub_stopped",
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_connection_manager_redis_pubsub_relay_and_self_echo_suppression():
|
||||
manager_a = ConnectionManager()
|
||||
manager_b = ConnectionManager()
|
||||
published: list[str] = []
|
||||
|
||||
class FakePubSubRedis:
|
||||
async def publish(self, _channel, payload):
|
||||
published.append(payload)
|
||||
|
||||
async def aclose(self):
|
||||
return None
|
||||
|
||||
manager_a._pubsub_enabled = True
|
||||
manager_a._pubsub_client = FakePubSubRedis()
|
||||
|
||||
sock_a = _FakeWebSocket()
|
||||
sock_b = _FakeWebSocket()
|
||||
sock_vessel_b = _FakeWebSocket()
|
||||
|
||||
await manager_a.connect(sock_a, "u-a")
|
||||
await manager_b.connect(sock_b, "u-b")
|
||||
await manager_b.connect(sock_vessel_b, "u-v")
|
||||
manager_a.subscribe(sock_a, ["earth_updates"])
|
||||
manager_b.subscribe(sock_b, ["earth_updates"])
|
||||
manager_b.subscribe_vessels(sock_vessel_b, {"scope": "global", "zoom": 4})
|
||||
|
||||
frame = {"type": "data_frame", "channel": "earth_updates", "payload": {"layers": ["cables"]}}
|
||||
await manager_a.broadcast(frame, channel="earth_updates")
|
||||
await manager_a.broadcast_vessels({"vessels": [{"mmsi": 999, "lat": 10.0, "lon": 20.0}]})
|
||||
|
||||
assert len(published) == 2
|
||||
assert len(sock_a.sent) == 1
|
||||
|
||||
# Self-origin replay must be ignored on manager_a, delivered cleanly on manager_b.
|
||||
for raw in published:
|
||||
assert await manager_a.handle_pubsub_payload(raw) is False
|
||||
assert await manager_b.handle_pubsub_payload(raw) is True
|
||||
|
||||
assert len(sock_a.sent) == 1
|
||||
assert sock_b.sent == [frame]
|
||||
assert sock_vessel_b.sent[0]["payload"]["vessels"] == [{"mmsi": 999, "lat": 10.0, "lon": 20.0}]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_versioned_migrations_upgrade_stamp_and_checksum_validation(tmp_path: Path):
|
||||
steps_dir = tmp_path / "steps"
|
||||
steps_dir.mkdir()
|
||||
m1 = steps_dir / "0001_initial_notes.py"
|
||||
m1.write_text(
|
||||
"from sqlalchemy import text\n"
|
||||
"VERSION = '0001'\n"
|
||||
"NAME = 'initial_notes'\n"
|
||||
"async def upgrade(conn):\n"
|
||||
" await conn.execute(text('CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY)'))\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
sync_engine = create_engine("sqlite://")
|
||||
adapter = _AsyncSQLiteEngineAdapter(sync_engine)
|
||||
|
||||
status_before = await get_migration_status(adapter, steps_dir)
|
||||
assert status_before["applied"] == []
|
||||
assert status_before["pending"] == ["0001"]
|
||||
|
||||
applied = await run_migrations(adapter, steps_dir)
|
||||
assert applied == ["0001"]
|
||||
with sync_engine.connect() as conn:
|
||||
assert conn.execute(text("SELECT COUNT(*) FROM notes")).scalar() == 0
|
||||
|
||||
m2 = steps_dir / "0002_add_body.py"
|
||||
m2.write_text(
|
||||
"from sqlalchemy import text\n"
|
||||
"VERSION = '0002'\n"
|
||||
"NAME = 'add_body'\n"
|
||||
"async def upgrade(conn):\n"
|
||||
" await conn.execute(text('ALTER TABLE notes ADD COLUMN body TEXT'))\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
status_mid = await get_migration_status(adapter, steps_dir)
|
||||
assert status_mid["pending"] == ["0002"]
|
||||
|
||||
applied_second = await run_migrations(adapter, steps_dir)
|
||||
assert applied_second == ["0002"]
|
||||
|
||||
# Mutating an applied migration file triggers checksum mismatch detection.
|
||||
m1.write_text(m1.read_text(encoding="utf-8") + "\n# tampered\n", encoding="utf-8")
|
||||
status_tampered = await get_migration_status(adapter, steps_dir)
|
||||
assert len(status_tampered["mismatches"]) == 1
|
||||
with pytest.raises(RuntimeError, match="Checksum mismatch"):
|
||||
await run_migrations(adapter, steps_dir)
|
||||
|
||||
# Verify ensure_baseline_stamped & stamp_migrations on a fresh DB.
|
||||
sync_engine2 = create_engine("sqlite://")
|
||||
adapter2 = _AsyncSQLiteEngineAdapter(sync_engine2)
|
||||
async with adapter2.begin() as conn:
|
||||
stamped_first = await ensure_baseline_stamped(conn, steps_dir)
|
||||
assert stamped_first is True
|
||||
stamped_rest = await stamp_migrations(adapter2, "0002", steps_dir)
|
||||
assert stamped_rest == ["0002"]
|
||||
final_status = await get_migration_status(adapter2, steps_dir)
|
||||
assert final_status["applied"] == ["0001", "0002"]
|
||||
assert final_status["pending"] == []
|
||||
|
||||
sync_engine.dispose()
|
||||
sync_engine2.dispose()
|
||||
@@ -26,8 +26,8 @@ def mock_http(monkeypatch, handler):
|
||||
("deepseek", "/v1/models", "authorization"),
|
||||
("alibaba", "/api/v1/models", "authorization"),
|
||||
("moonshotai", "/v1/models", "authorization"),
|
||||
("openrouter", "/api/v1/models", "authorization"),
|
||||
("opencode-go", "/zen/go/v1/models", "authorization"),
|
||||
("openrouter", "/api/v1/models", None),
|
||||
("opencode-go", "/zen/go/v1/models", None),
|
||||
("ollama", "/api/tags", "authorization"),
|
||||
],
|
||||
)
|
||||
@@ -37,7 +37,13 @@ async def test_official_catalog_requests(monkeypatch, provider, path, auth):
|
||||
def handle(request):
|
||||
assert request.url.path == path
|
||||
assert request.url.host == httpx.URL(preset["base_url"]).host
|
||||
assert request.headers[auth] == ("test-key" if auth == "x-api-key" else "Bearer test-key")
|
||||
if auth is None:
|
||||
assert "authorization" not in request.headers
|
||||
assert "x-api-key" not in request.headers
|
||||
else:
|
||||
assert request.headers[auth] == (
|
||||
"test-key" if auth == "x-api-key" else "Bearer test-key"
|
||||
)
|
||||
if provider == "alibaba":
|
||||
assert request.url.params["capabilities"] == "TG"
|
||||
return httpx.Response(
|
||||
@@ -217,3 +223,74 @@ async def test_retry_transient_error_only(monkeypatch):
|
||||
await catalog.refresh_llm_provider_preset("minimax", "test-key")
|
||||
assert len(calls) == 1
|
||||
assert "secret-upstream-text" not in discovery.catalog_error_message(error.value)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"provider,custom_base",
|
||||
[
|
||||
("openrouter", "https://proxy.test/api/v1"),
|
||||
("opencode-go", "https://proxy.test/zen/go/v1"),
|
||||
],
|
||||
)
|
||||
async def test_custom_gateway_for_public_provider_requires_and_sends_key(
|
||||
monkeypatch, provider, custom_base
|
||||
):
|
||||
with pytest.raises(discovery.LLMProviderCatalogConfigError):
|
||||
await catalog.refresh_llm_provider_preset(provider, base_url=custom_base)
|
||||
|
||||
def handle(request):
|
||||
assert request.url.host == "proxy.test"
|
||||
assert request.headers["authorization"] == "Bearer custom-key"
|
||||
return httpx.Response(200, json={"data": [{"id": "proxy-model"}]})
|
||||
|
||||
mock_http(monkeypatch, handle)
|
||||
result = await catalog.refresh_llm_provider_preset(
|
||||
provider, api_key="custom-key", base_url=custom_base
|
||||
)
|
||||
assert result["models"] == ["proxy-model"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fetch_model_catalog_include_auth_for_connectivity_check(monkeypatch):
|
||||
def handle(request):
|
||||
assert request.headers["authorization"] == "Bearer check-key"
|
||||
return httpx.Response(200, json={"data": [{"id": "glm-5.3"}]})
|
||||
|
||||
mock_http(monkeypatch, handle)
|
||||
result = await discovery.fetch_model_catalog(
|
||||
"opencode-go",
|
||||
"https://opencode.ai/zen/go/v1",
|
||||
"openai-completions",
|
||||
api_key="check-key",
|
||||
include_auth=True,
|
||||
)
|
||||
assert result.models == ["glm-5.3"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_ollama_openai_completions_refreshes_without_key(monkeypatch):
|
||||
def handle(request):
|
||||
assert request.url.path == "/v1/models"
|
||||
assert "authorization" not in request.headers
|
||||
return httpx.Response(200, json={"data": [{"id": "qwen2.5:7b"}]})
|
||||
|
||||
mock_http(monkeypatch, handle)
|
||||
result = await catalog.refresh_llm_provider_preset(
|
||||
"ollama", provider_api="openai-completions"
|
||||
)
|
||||
assert result["models"] == ["qwen2.5:7b"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_config_error_type_and_clean_upstream_error_messages(monkeypatch):
|
||||
with pytest.raises(discovery.LLMProviderCatalogConfigError):
|
||||
discovery.model_catalog_url("openai", "not-a-url", "openai-responses")
|
||||
with pytest.raises(discovery.LLMProviderCatalogConfigError):
|
||||
discovery.model_catalog_url("openai", "https://api.openai.com/v1", "unsupported-api")
|
||||
|
||||
mock_http(monkeypatch, lambda request: httpx.Response(200, json={"data": []}))
|
||||
with pytest.raises(discovery.LLMProviderCatalogError) as exc:
|
||||
await catalog.refresh_llm_provider_preset("openai", "test-key")
|
||||
assert not isinstance(exc.value, discovery.LLMProviderCatalogConfigError)
|
||||
assert "已保留上次模型列表" not in str(exc.value)
|
||||
@@ -13,6 +13,8 @@ from app.services import llm_model_catalog as discovery
|
||||
from app.services.llm_provider_catalog import list_fallback_llm_provider_presets
|
||||
|
||||
REAL_CLIENT = httpx.AsyncClient
|
||||
ADMIN_USER = SimpleNamespace(role="admin")
|
||||
VIEWER_USER = SimpleNamespace(role="viewer")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -82,7 +84,7 @@ async def test_refresh_commits_reloads_and_preserves_runtime_and_draft(settings_
|
||||
api_key="draft-secret",
|
||||
service_token="unsaved-service-token",
|
||||
)
|
||||
refreshed = await api.refresh_ai_provider_preset("minimax", None, settings_db, draft)
|
||||
refreshed = await api.refresh_ai_provider_preset("minimax", ADMIN_USER, settings_db, draft)
|
||||
result = await api.get_ai_provider_presets(None, settings_db)
|
||||
preset = next(row for row in result["data"] if row["provider"] == "minimax")
|
||||
assert len(seen) == 1
|
||||
@@ -108,7 +110,7 @@ async def test_failed_refresh_preserves_stored_catalog_and_sanitizes_errors(
|
||||
use_upstream(monkeypatch, lambda request: httpx.Response(401, text="private-upstream-secret"))
|
||||
commits = settings_db.commit.await_count
|
||||
with pytest.raises(api.HTTPException) as error:
|
||||
await api.refresh_ai_provider_preset("openrouter", None, settings_db)
|
||||
await api.refresh_ai_provider_preset("openrouter", ADMIN_USER, settings_db)
|
||||
assert error.value.status_code == 502
|
||||
assert "private-upstream-secret" not in error.value.detail
|
||||
assert settings_db.commit.await_count == commits
|
||||
@@ -124,11 +126,170 @@ async def test_missing_key_is_actionable_and_does_not_request_upstream(settings_
|
||||
|
||||
use_upstream(monkeypatch, fail_request)
|
||||
with pytest.raises(api.HTTPException) as error:
|
||||
await api.refresh_ai_provider_preset("minimax", None, settings_db)
|
||||
await api.refresh_ai_provider_preset("minimax", ADMIN_USER, settings_db)
|
||||
assert error.value.status_code == 400
|
||||
assert "API Key" in error.value.detail
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_refresh_requires_admin_role(settings_db):
|
||||
with pytest.raises(api.HTTPException) as single_err:
|
||||
await api.refresh_ai_provider_preset("openrouter", VIEWER_USER, settings_db)
|
||||
assert single_err.value.status_code == 403
|
||||
|
||||
with pytest.raises(api.HTTPException) as bulk_err:
|
||||
await api.refresh_public_ai_provider_presets(VIEWER_USER, settings_db)
|
||||
assert bulk_err.value.status_code == 403
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_opencode_go_refreshes_ignoring_invalid_saved_and_draft_keys(
|
||||
settings_db, monkeypatch
|
||||
):
|
||||
await api.save_setting_payload(
|
||||
settings_db,
|
||||
"external_integrations",
|
||||
{
|
||||
"ai_provider": {
|
||||
"default_provider": "opencode-go",
|
||||
"providers": {
|
||||
"opencode-go": {
|
||||
"base_url": "https://opencode.ai/zen/go/v1",
|
||||
"model": "glm-5.3",
|
||||
"api_key": "stale-invalid-key",
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
def handle(request):
|
||||
assert "authorization" not in request.headers
|
||||
assert "x-api-key" not in request.headers
|
||||
return httpx.Response(200, json={"data": [{"id": "glm-5.3"}, {"id": "deepseek-v4.1-flash"}]})
|
||||
|
||||
use_upstream(monkeypatch, handle)
|
||||
draft = api.AIProviderIntegrationUpdate(
|
||||
provider="opencode-go",
|
||||
base_url="https://opencode.ai/zen/go/v1",
|
||||
model="glm-5.3",
|
||||
api_key="bad-draft-key",
|
||||
)
|
||||
refreshed = await api.refresh_ai_provider_preset("opencode-go", ADMIN_USER, settings_db, draft)
|
||||
assert refreshed["data"]["models"] == ["glm-5.3", "deepseek-v4.1-flash"]
|
||||
stored = await api.get_setting_payload(settings_db, "llm_provider_preset:opencode-go")
|
||||
assert stored["models"] == ["glm-5.3", "deepseek-v4.1-flash"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_ollama_openai_completions_works_without_key(settings_db, monkeypatch):
|
||||
def handle(request):
|
||||
assert request.url.path == "/v1/models"
|
||||
assert "authorization" not in request.headers
|
||||
return httpx.Response(200, json={"data": [{"id": "qwen2.5:7b"}]})
|
||||
|
||||
use_upstream(monkeypatch, handle)
|
||||
draft = api.AIProviderIntegrationUpdate(
|
||||
provider="ollama",
|
||||
provider_api="openai-completions",
|
||||
base_url="http://127.0.0.1:11434/v1",
|
||||
model="qwen2.5:7b",
|
||||
)
|
||||
refreshed = await api.refresh_ai_provider_preset("ollama", ADMIN_USER, settings_db, draft)
|
||||
assert refreshed["data"]["models"] == ["qwen2.5:7b"]
|
||||
|
||||
check = await api._check_ai_provider_lightweight(
|
||||
{
|
||||
"provider": "ollama",
|
||||
"provider_api": "openai-completions",
|
||||
"base_url": "http://127.0.0.1:11434/v1",
|
||||
"model": "qwen2.5:7b",
|
||||
"api_key": "",
|
||||
},
|
||||
5,
|
||||
)
|
||||
assert check["success"] is True
|
||||
assert check["connected"] is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_invalid_draft_base_url_returns_400_without_calling_upstream(
|
||||
settings_db, monkeypatch
|
||||
):
|
||||
use_upstream(
|
||||
monkeypatch,
|
||||
lambda request: pytest.fail("must not query upstream when draft base_url is invalid"),
|
||||
)
|
||||
draft = api.AIProviderIntegrationUpdate(
|
||||
provider="openrouter",
|
||||
base_url="not-a-valid-url",
|
||||
model="openai/gpt-6.2-astra",
|
||||
)
|
||||
with pytest.raises(api.HTTPException) as error:
|
||||
await api.refresh_ai_provider_preset("openrouter", ADMIN_USER, settings_db, draft)
|
||||
assert error.value.status_code == 400
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_empty_catalog_error_does_not_duplicate_retention_suffix(settings_db, monkeypatch):
|
||||
use_upstream(monkeypatch, lambda request: httpx.Response(200, json={"data": []}))
|
||||
with pytest.raises(api.HTTPException) as error:
|
||||
await api.refresh_ai_provider_preset("openrouter", ADMIN_USER, settings_db)
|
||||
assert error.value.status_code == 502
|
||||
assert error.value.detail.count("已保留上次模型列表") == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_refresh_public_presets_updates_credential_free_and_isolates_failures(
|
||||
settings_db, monkeypatch
|
||||
):
|
||||
await api.save_setting_payload(
|
||||
settings_db,
|
||||
"external_integrations",
|
||||
{
|
||||
"ai_provider": {
|
||||
"default_provider": "openrouter",
|
||||
"providers": {
|
||||
"openrouter": {
|
||||
"base_url": "https://proxy.test/api/v1",
|
||||
"model": "custom-model",
|
||||
"api_key": "",
|
||||
},
|
||||
"opencode-go": {
|
||||
"base_url": "https://opencode.ai/zen/go/v1",
|
||||
"model": "glm-5.3",
|
||||
"api_key": "stale-key",
|
||||
},
|
||||
},
|
||||
}
|
||||
},
|
||||
)
|
||||
await api.save_setting_payload(
|
||||
settings_db, "llm_provider_preset:ollama", {"models": ["kept-local-model"]}
|
||||
)
|
||||
|
||||
seen_hosts = []
|
||||
|
||||
def handle(request):
|
||||
seen_hosts.append(request.url.host)
|
||||
assert "authorization" not in request.headers
|
||||
if request.url.host == "opencode.ai":
|
||||
return httpx.Response(200, json={"data": [{"id": "glm-5.3"}, {"id": "qwen4-max"}]})
|
||||
raise httpx.ConnectError("local ollama offline", request=request)
|
||||
|
||||
use_upstream(monkeypatch, handle)
|
||||
summary = await api.refresh_public_ai_provider_presets(ADMIN_USER, settings_db)
|
||||
assert seen_hosts == ["opencode.ai", "127.0.0.1", "127.0.0.1"]
|
||||
assert summary["refreshed"] == ["opencode-go"]
|
||||
assert summary["failed"] == ["ollama"]
|
||||
assert (await api.get_setting_payload(settings_db, "llm_provider_preset:opencode-go"))[
|
||||
"models"
|
||||
] == ["glm-5.3", "qwen4-max"]
|
||||
assert (await api.get_setting_payload(settings_db, "llm_provider_preset:ollama"))[
|
||||
"models"
|
||||
] == ["kept-local-model"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"preset", list_fallback_llm_provider_presets(), ids=lambda p: p["provider"]
|
||||
|
||||
@@ -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
|
||||
@@ -1,3 +1,4 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from unittest.mock import patch
|
||||
@@ -175,3 +176,173 @@ async def test_minimax_m31_flash_forces_adaptive_thinking_and_effort(monkeypatch
|
||||
assert payloads[0]["output_config"] == {"effort": "low"}
|
||||
assert payloads[1]["thinking"] == {"type": "adaptive"}
|
||||
assert payloads[1]["output_config"] == {"effort": "medium"}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stream_analyze_anthropic_emits_thinking_text_and_done(monkeypatch):
|
||||
client_type = httpx.AsyncClient
|
||||
sse_bytes = (
|
||||
b'event: message_start\n'
|
||||
b'data: {"type":"message_start","message":{"model":"MiniMax-M2.7","usage":{"input_tokens":12}}}\n\n'
|
||||
b'event: content_block_delta\n'
|
||||
b'data: {"type":"content_block_delta","delta":{"type":"thinking_delta","thinking":"step-1 "}}\n\n'
|
||||
b'event: content_block_delta\n'
|
||||
b'data: {"type":"content_block_delta","delta":{"type":"text_delta","text":"hello "}}\n\n'
|
||||
b'event: message_delta\n'
|
||||
b'data: {"type":"message_delta","usage":{"output_tokens":7}}\n\n'
|
||||
b'event: message_stop\n'
|
||||
b'data: {"type":"message_stop"}\n\n'
|
||||
)
|
||||
|
||||
def handle(_request):
|
||||
return httpx.Response(200, content=sse_bytes, headers={"content-type": "text/event-stream"})
|
||||
|
||||
transport = httpx.MockTransport(handle)
|
||||
monkeypatch.setattr(httpx, "AsyncClient", lambda **kw: client_type(transport=transport, **kw))
|
||||
service = ProviderService(
|
||||
{
|
||||
"provider": "minimax",
|
||||
"provider_api": "anthropic-messages",
|
||||
"base_url": "https://api.minimaxi.com/anthropic",
|
||||
"api_key": "test-key",
|
||||
"model": "MiniMax-M2.7",
|
||||
}
|
||||
)
|
||||
|
||||
events = []
|
||||
async for ev in service.stream_analyze(
|
||||
SituationalAnalysisRequest(title="news", objective="analyze", thinking={"type": "enabled", "budget_tokens": 1024})
|
||||
):
|
||||
events.append(ev)
|
||||
|
||||
assert events[0] == {"event": "start", "provider": "minimax", "model": "MiniMax-M2.7"}
|
||||
assert {"event": "reasoning", "delta": "step-1 "} in events
|
||||
assert {"event": "text", "delta": "hello "} in events
|
||||
assert events[-1]["event"] == "done"
|
||||
assert events[-1]["model"] == "MiniMax-M2.7"
|
||||
assert events[-1]["usage"]["output_tokens"] == 7
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stream_analyze_openai_emits_reasoning_and_text(monkeypatch):
|
||||
client_type = httpx.AsyncClient
|
||||
sse_bytes = (
|
||||
b'data: {"model":"gpt-5.6","choices":[{"delta":{"reasoning_content":"check cables"}}]}\n\n'
|
||||
b'data: {"model":"gpt-5.6","choices":[{"delta":{"content":"summary ok"}}],"usage":{"total_tokens":20}}\n\n'
|
||||
b'data: [DONE]\n\n'
|
||||
)
|
||||
|
||||
def handle(_request):
|
||||
return httpx.Response(200, content=sse_bytes, headers={"content-type": "text/event-stream"})
|
||||
|
||||
transport = httpx.MockTransport(handle)
|
||||
monkeypatch.setattr(httpx, "AsyncClient", lambda **kw: client_type(transport=transport, **kw))
|
||||
service = ProviderService(
|
||||
{
|
||||
"provider": "openai",
|
||||
"provider_api": "openai-completions",
|
||||
"base_url": "https://api.openai.test/v1",
|
||||
"api_key": "test-key",
|
||||
"model": "gpt-5.6",
|
||||
}
|
||||
)
|
||||
|
||||
events = []
|
||||
async for ev in service.stream_analyze(SituationalAnalysisRequest(title="global", objective="analyze")):
|
||||
events.append(ev)
|
||||
|
||||
assert {"event": "reasoning", "delta": "check cables"} in events
|
||||
assert {"event": "text", "delta": "summary ok"} in events
|
||||
assert events[-1]["event"] == "done"
|
||||
assert events[-1]["usage"]["total_tokens"] == 20
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stream_analyze_forwards_normalized_multi_turn_messages(monkeypatch):
|
||||
client_type = httpx.AsyncClient
|
||||
captured_bodies = []
|
||||
|
||||
def handle(request):
|
||||
captured_bodies.append(json.loads(request.content.decode("utf-8")))
|
||||
sse = (
|
||||
b'event: content_block_delta\n'
|
||||
b'data: {"type":"content_block_delta","delta":{"type":"text_delta","text":"multi-turn ok"}}\n\n'
|
||||
b'event: message_stop\n'
|
||||
b'data: {"type":"message_stop"}\n\n'
|
||||
)
|
||||
return httpx.Response(200, content=sse, headers={"content-type": "text/event-stream"})
|
||||
|
||||
transport = httpx.MockTransport(handle)
|
||||
monkeypatch.setattr(httpx, "AsyncClient", lambda **kw: client_type(transport=transport, **kw))
|
||||
service = ProviderService(
|
||||
{
|
||||
"provider": "minimax",
|
||||
"provider_api": "anthropic-messages",
|
||||
"base_url": "https://api.minimaxi.com/anthropic",
|
||||
"api_key": "test-key",
|
||||
"model": "MiniMax-M2.7",
|
||||
}
|
||||
)
|
||||
|
||||
events = []
|
||||
async for ev in service.stream_analyze(
|
||||
SituationalAnalysisRequest(
|
||||
title="follow-up",
|
||||
objective="继续追问第二点",
|
||||
messages=[
|
||||
{"role": "assistant", "content": "leading assistant ignored"},
|
||||
{"role": "user", "content": "第一轮问题"},
|
||||
{"role": "assistant", "content": "第一轮回答"},
|
||||
],
|
||||
)
|
||||
):
|
||||
events.append(ev)
|
||||
|
||||
assert len(captured_bodies) == 1
|
||||
sent_msgs = captured_bodies[0]["messages"]
|
||||
assert [m["role"] for m in sent_msgs] == ["user", "assistant", "user"]
|
||||
assert sent_msgs[0]["content"][0]["text"] == "第一轮问题"
|
||||
assert sent_msgs[1]["content"][0]["text"] == "第一轮回答"
|
||||
assert "继续追问第二点" in sent_msgs[2]["content"][0]["text"]
|
||||
assert {"event": "text", "delta": "multi-turn ok"} in events
|
||||
|
||||
|
||||
def test_anthropic_request_omits_temperature_and_bumps_max_tokens_when_thinking_enabled():
|
||||
service = ProviderService(
|
||||
{
|
||||
"provider": "minimax",
|
||||
"provider_api": "anthropic-messages",
|
||||
"base_url": "https://api.minimaxi.com/anthropic",
|
||||
"api_key": "test-key",
|
||||
"model": "MiniMax-M2.7",
|
||||
"max_tokens": 1200,
|
||||
}
|
||||
)
|
||||
|
||||
_, _, enabled_body = service._build_anthropic_request(
|
||||
"MiniMax-M2.7",
|
||||
"analyze",
|
||||
thinking={"type": "enabled", "budget_tokens": 2048},
|
||||
stream=True,
|
||||
)
|
||||
assert "temperature" not in enabled_body
|
||||
assert enabled_body["max_tokens"] == 3072
|
||||
assert enabled_body["thinking"] == {"type": "enabled", "budget_tokens": 2048}
|
||||
|
||||
_, _, adaptive_body = service._build_anthropic_request(
|
||||
"MiniMax-M3.1",
|
||||
"analyze",
|
||||
thinking=None,
|
||||
stream=True,
|
||||
)
|
||||
assert "temperature" not in adaptive_body
|
||||
assert adaptive_body["thinking"] == {"type": "adaptive"}
|
||||
|
||||
_, _, disabled_body = service._build_anthropic_request(
|
||||
"MiniMax-M2.7",
|
||||
"analyze",
|
||||
thinking=None,
|
||||
stream=False,
|
||||
)
|
||||
assert disabled_body["temperature"] == 0.2
|
||||
assert disabled_body["thinking"] == {"type": "disabled"}
|
||||
@@ -108,9 +108,9 @@ def test_opencode_go_provider_preset_is_openai_compatible():
|
||||
assert preset["label"] == "OpenCode Go"
|
||||
assert preset["provider_api"] == "openai-completions"
|
||||
assert preset["base_url"] == "https://opencode.ai/zen/go/v1"
|
||||
assert preset["model"] == "glm-5.1"
|
||||
assert "glm-5.1" in preset["models"]
|
||||
assert "deepseek-v4-flash" in preset["models"]
|
||||
assert preset["model"] == "glm-5.3"
|
||||
assert "glm-5.3" in preset["models"]
|
||||
assert "deepseek-v4.1-flash" in preset["models"]
|
||||
assert preset["model_provider_apis"]["minimax-m2.7"] == "anthropic-messages"
|
||||
assert preset["api_key_env"] == "OPENCODE_GO_API_KEY"
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -154,3 +154,50 @@ async def test_satellite_cursor_closes_if_conversion_fails(
|
||||
await visualization._build_satellites_geojson(limit=None, db=satellite_db)
|
||||
|
||||
assert satellite_db.streams[0].closed
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_compact_satellite_builder_emits_compact_rows_and_fallback_elements(
|
||||
satellite_db: SatelliteSession,
|
||||
) -> None:
|
||||
with_tle = satellite(10)
|
||||
without_tle = CollectedData(
|
||||
id=11,
|
||||
source="celestrak_tle",
|
||||
source_id="11",
|
||||
data_type="satellite_tle",
|
||||
name="NO-TLE-SAT",
|
||||
is_current=True,
|
||||
task_id=1,
|
||||
collected_at=datetime(2026, 1, 1, tzinfo=UTC),
|
||||
extra_data={
|
||||
"norad_cat_id": 51000,
|
||||
"inclination": 53.2,
|
||||
"raan": 120.5,
|
||||
"eccentricity": 0.00012,
|
||||
"arg_of_perigee": 90.0,
|
||||
"mean_anomaly": 45.0,
|
||||
"mean_motion": 15.1,
|
||||
"international_designator": "24001A",
|
||||
"classification_type": "U",
|
||||
"bstar": 0.0001,
|
||||
},
|
||||
)
|
||||
starlink = satellite(12, name="STARLINK-1234")
|
||||
satellite_db.session.add_all([with_tle, without_tle, starlink])
|
||||
satellite_db.session.commit()
|
||||
|
||||
payload = await visualization._build_satellites_compact(limit=None, db=satellite_db)
|
||||
|
||||
assert payload["format"] == "satellite_compact_v1"
|
||||
assert payload["count"] == 3
|
||||
rows_by_id = {row[0]: row for row in payload["satellites"]}
|
||||
assert len(rows_by_id[10]) == 6
|
||||
assert rows_by_id[10][:4] == [10, 40010, "SAT-10", None]
|
||||
assert rows_by_id[10][4:6] == ["line-1-10", "line-2-10"]
|
||||
assert rows_by_id[12][:4] == [12, 40012, "STARLINK-1234", "starlink"]
|
||||
assert len(rows_by_id[11]) == 7
|
||||
assert rows_by_id[11][4] is None
|
||||
assert isinstance(rows_by_id[11][5], str) and rows_by_id[11][5].startswith("2 51000 ")
|
||||
assert rows_by_id[11][6][:2] == [53.2, 120.5]
|
||||
assert all(stream.closed for stream in satellite_db.streams)
|
||||
@@ -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:
|
||||
@@ -52,6 +56,8 @@ linux:
|
||||
mac:
|
||||
icon: resources/icon.png
|
||||
category: public.app-category.utilities
|
||||
extendInfo:
|
||||
NSCameraUsageDescription: Planet Earth uses your camera locally for motion gesture control.
|
||||
target:
|
||||
- target: dmg
|
||||
arch:
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "planet-client",
|
||||
"version": "0.77.0",
|
||||
"version": "0.80.1",
|
||||
"description": "Intelligent Planet Program - Native Electron Earth Viewer",
|
||||
"private": true,
|
||||
"packageManager": "bun@1",
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { cpSync, existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { createHash } from 'node:crypto'
|
||||
import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { createRequire } from 'node:module'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
import { compileEarthRuntime } from '../../frontend/scripts/compile-earth-runtime.mjs'
|
||||
import { createTarGz } from '../src/main/tar-gz.ts'
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url))
|
||||
const desktopRoot = join(__dirname, '..')
|
||||
@@ -88,15 +90,65 @@ if (existsSync(zjuEmblemSrc)) {
|
||||
const mediaPipePkgDir = dirname(require.resolve('@mediapipe/tasks-vision/package.json'))
|
||||
const mediaPipeOutDir = join(bundleEarthDir, 'vendor/mediapipe')
|
||||
mkdirSync(mediaPipeOutDir, { recursive: true })
|
||||
for (const candidate of ['vision_bundle.mjs', 'vision_bundle.cjs']) {
|
||||
const srcFile = join(mediaPipePkgDir, candidate)
|
||||
if (existsSync(srcFile)) {
|
||||
cpSync(srcFile, join(mediaPipeOutDir, candidate))
|
||||
}
|
||||
const mediaPipeBundleSrc = join(mediaPipePkgDir, 'vision_bundle.mjs')
|
||||
if (existsSync(mediaPipeBundleSrc)) {
|
||||
cpSync(mediaPipeBundleSrc, join(mediaPipeOutDir, 'vision_bundle.mjs'))
|
||||
}
|
||||
const mediaPipeWasmDir = join(mediaPipePkgDir, 'wasm')
|
||||
if (existsSync(mediaPipeWasmDir)) {
|
||||
cpSync(mediaPipeWasmDir, join(mediaPipeOutDir, 'wasm'), { recursive: true })
|
||||
}
|
||||
const poseModelSrc = join(earthSourceDir, 'vendor/mediapipe/pose_landmarker_lite.task')
|
||||
if (!existsSync(poseModelSrc)) {
|
||||
throw new Error(`Missing bundled MediaPipe pose model: ${poseModelSrc}`)
|
||||
}
|
||||
cpSync(poseModelSrc, join(mediaPipeOutDir, 'pose_landmarker_lite.task'))
|
||||
|
||||
console.log(`Built offline Earth bundle at ${bundleEarthDir}`)
|
||||
|
||||
const clientPkg = JSON.parse(readFileSync(join(desktopRoot, 'package.json'), 'utf8'))
|
||||
const bundleVersion = String(clientPkg.version || '0.0.0').trim()
|
||||
const metaPayload = {
|
||||
version: bundleVersion,
|
||||
shellVersion: bundleVersion,
|
||||
builtAt: new Date().toISOString(),
|
||||
}
|
||||
writeFileSync(join(bundleEarthDir, 'bundle-meta.json'), `${JSON.stringify(metaPayload, null, 2)}\n`, 'utf8')
|
||||
|
||||
function collectHotfixEntries(rootDir) {
|
||||
const entries = []
|
||||
for (const topFile of ['index.html', 'bundle-meta.json']) {
|
||||
const filePath = join(rootDir, topFile)
|
||||
if (existsSync(filePath)) {
|
||||
entries.push({ path: topFile, data: readFileSync(filePath) })
|
||||
}
|
||||
}
|
||||
const walk = (relDir) => {
|
||||
const absDir = join(rootDir, relDir)
|
||||
if (!existsSync(absDir)) return
|
||||
for (const dirent of readdirSync(absDir, { withFileTypes: true })) {
|
||||
const relPath = `${relDir}/${dirent.name}`
|
||||
if (dirent.isDirectory()) {
|
||||
walk(relPath)
|
||||
} else if (dirent.isFile()) {
|
||||
entries.push({ path: relPath, data: readFileSync(join(rootDir, relPath)) })
|
||||
}
|
||||
}
|
||||
}
|
||||
walk('js')
|
||||
walk('css')
|
||||
return entries
|
||||
}
|
||||
|
||||
const hotfixEntries = collectHotfixEntries(bundleEarthDir)
|
||||
const hotfixArchive = createTarGz(hotfixEntries)
|
||||
const hotfixSha256 = createHash('sha256').update(hotfixArchive).digest('hex')
|
||||
const releaseOutDir = join(desktopRoot, 'release')
|
||||
mkdirSync(releaseOutDir, { recursive: true })
|
||||
const hotfixName = `planet-earth-bundle-${bundleVersion}.tar.gz`
|
||||
const hotfixPath = join(releaseOutDir, hotfixName)
|
||||
writeFileSync(hotfixPath, hotfixArchive)
|
||||
writeFileSync(join(releaseOutDir, `${hotfixName}.sha256`), `${hotfixSha256} ${hotfixName}\n`, 'utf8')
|
||||
console.log(
|
||||
`Built L1 hotfix bundle ${hotfixPath} (${(hotfixArchive.byteLength / 1024).toFixed(1)} KiB, sha256=${hotfixSha256})`,
|
||||
)
|
||||
+147
-20
@@ -1,7 +1,8 @@
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
|
||||
export type SplashTheme = 'singularity' | 'constellation' | 'horizon' | 'off'
|
||||
export type SplashTheme = 'singularity' | 'off'
|
||||
export type GpuRenderMode = 'auto' | 'high-performance' | 'low-power' | 'software'
|
||||
|
||||
export interface ServerEndpoints {
|
||||
backendUrl: string
|
||||
@@ -11,6 +12,23 @@ export interface ServerEndpoints {
|
||||
|
||||
export interface PersistedUserConfig extends Partial<ServerEndpoints> {
|
||||
splashTheme?: SplashTheme
|
||||
gpuMode?: GpuRenderMode
|
||||
}
|
||||
|
||||
export type GpuHandoffTarget = 'default' | 'high-performance' | 'low-power' | 'software'
|
||||
|
||||
export function normalizeGpuHandoffTarget(raw: unknown): GpuHandoffTarget | undefined {
|
||||
if (typeof raw !== 'string') return undefined
|
||||
const normalized = raw.trim().toLowerCase()
|
||||
if (
|
||||
normalized === 'default' ||
|
||||
normalized === 'high-performance' ||
|
||||
normalized === 'low-power' ||
|
||||
normalized === 'software'
|
||||
) {
|
||||
return normalized
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
export interface DesktopLaunchFlags {
|
||||
@@ -22,18 +40,23 @@ export interface DesktopLaunchFlags {
|
||||
smokeOutputPath: string | null
|
||||
deepLinkUrl: string | null
|
||||
splashThemeOverride?: SplashTheme
|
||||
gpuModeOverride?: GpuRenderMode
|
||||
gpuHandoff: boolean
|
||||
gpuHandoffTarget?: GpuHandoffTarget
|
||||
}
|
||||
|
||||
export interface DesktopRuntimeConfig extends ServerEndpoints, DesktopLaunchFlags {
|
||||
wsUrl: string
|
||||
splashTheme: SplashTheme
|
||||
gpuMode: GpuRenderMode
|
||||
}
|
||||
|
||||
const VALID_SPLASH_THEMES: ReadonlySet<SplashTheme> = new Set([
|
||||
const LEGACY_ACTIVE_THEMES: ReadonlySet<string> = new Set([
|
||||
'singularity',
|
||||
'constellation',
|
||||
'horizon',
|
||||
'off',
|
||||
'on',
|
||||
'default',
|
||||
])
|
||||
|
||||
export function normalizeSplashTheme(
|
||||
@@ -41,13 +64,43 @@ export function normalizeSplashTheme(
|
||||
fallback: SplashTheme = 'singularity',
|
||||
): SplashTheme {
|
||||
if (typeof raw !== 'string') return fallback
|
||||
const normalized = raw.trim().toLowerCase() as SplashTheme
|
||||
return VALID_SPLASH_THEMES.has(normalized) ? normalized : fallback
|
||||
const normalized = raw.trim().toLowerCase()
|
||||
if (normalized === 'off') return 'off'
|
||||
return LEGACY_ACTIVE_THEMES.has(normalized) ? 'singularity' : fallback
|
||||
}
|
||||
|
||||
const DEFAULT_ENDPOINTS: ServerEndpoints = {
|
||||
backendUrl: 'http://127.0.0.1:8000',
|
||||
adminUrl: 'http://127.0.0.1:3000',
|
||||
export function normalizeGpuMode(
|
||||
raw: unknown,
|
||||
fallback: GpuRenderMode = 'auto',
|
||||
): GpuRenderMode {
|
||||
if (typeof raw !== 'string') return fallback
|
||||
const normalized = raw.trim().toLowerCase()
|
||||
if (normalized === 'auto') return 'auto'
|
||||
if (
|
||||
normalized === 'high-performance' ||
|
||||
normalized === 'high' ||
|
||||
normalized === 'discrete' ||
|
||||
normalized === 'dgpu'
|
||||
) {
|
||||
return 'high-performance'
|
||||
}
|
||||
if (
|
||||
normalized === 'low-power' ||
|
||||
normalized === 'low' ||
|
||||
normalized === 'integrated' ||
|
||||
normalized === 'igpu'
|
||||
) {
|
||||
return 'low-power'
|
||||
}
|
||||
if (normalized === 'software' || normalized === 'cpu' || normalized === 'swiftshader') {
|
||||
return 'software'
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
export const DEFAULT_ENDPOINTS: Readonly<ServerEndpoints> = {
|
||||
backendUrl: 'https://rclaw.top',
|
||||
adminUrl: 'https://admin.rclaw.top',
|
||||
motionWsUrl: 'ws://127.0.0.1:8765/ws/gestures',
|
||||
}
|
||||
|
||||
@@ -113,6 +166,7 @@ export function parseLaunchArgs(argv: string[]): {
|
||||
headlessSmoke: false,
|
||||
smokeOutputPath: null,
|
||||
deepLinkUrl: null,
|
||||
gpuHandoff: false,
|
||||
}
|
||||
|
||||
for (let i = 0; i < argv.length; i += 1) {
|
||||
@@ -134,6 +188,22 @@ export function parseLaunchArgs(argv: string[]): {
|
||||
flags.splashThemeOverride = normalizeSplashTheme(arg.slice('--splash-theme='.length))
|
||||
} else if (arg === '--splash-theme' && argv[i + 1]) {
|
||||
flags.splashThemeOverride = normalizeSplashTheme(argv[++i])
|
||||
} else if (arg.startsWith('--gpu-mode=')) {
|
||||
flags.gpuModeOverride = normalizeGpuMode(arg.slice('--gpu-mode='.length))
|
||||
} else if (arg === '--gpu-mode' && argv[i + 1]) {
|
||||
flags.gpuModeOverride = normalizeGpuMode(argv[++i])
|
||||
} else if (arg === '--software-gl') {
|
||||
flags.gpuModeOverride = 'software'
|
||||
} else if (arg === '--low-power-gpu') {
|
||||
flags.gpuModeOverride = 'low-power'
|
||||
} else if (arg === '--high-performance-gpu') {
|
||||
flags.gpuModeOverride = 'high-performance'
|
||||
} else if (arg === '--gpu-handoff') {
|
||||
flags.gpuHandoff = true
|
||||
} else if (arg.startsWith('--gpu-handoff-target=')) {
|
||||
flags.gpuHandoffTarget = normalizeGpuHandoffTarget(arg.slice('--gpu-handoff-target='.length))
|
||||
} else if (arg === '--gpu-handoff-target' && argv[i + 1]) {
|
||||
flags.gpuHandoffTarget = normalizeGpuHandoffTarget(argv[++i])
|
||||
} else if (arg === '--fullscreen') {
|
||||
flags.fullscreen = true
|
||||
} else if (arg === '--kiosk') {
|
||||
@@ -155,6 +225,55 @@ export function parseLaunchArgs(argv: string[]): {
|
||||
return { endpoints, flags }
|
||||
}
|
||||
|
||||
function getPortableConfigPaths(exeDir: string, resourcesDir?: string): string[] {
|
||||
const candidates: string[] = []
|
||||
if (exeDir) {
|
||||
candidates.push(path.join(exeDir, 'planet-earth.json'))
|
||||
}
|
||||
if (resourcesDir) {
|
||||
candidates.push(path.join(resourcesDir, 'planet-earth.json'))
|
||||
}
|
||||
return candidates
|
||||
}
|
||||
|
||||
function readFirstPortableConfig(paths: string[]): PersistedUserConfig {
|
||||
for (const candidate of paths) {
|
||||
const data = readJsonFileSafe(candidate)
|
||||
if (Object.keys(data).length > 0) {
|
||||
return data
|
||||
}
|
||||
}
|
||||
return {}
|
||||
}
|
||||
|
||||
export function readPreReadyGpuMode(options: {
|
||||
userDataDir: string
|
||||
exeDir: string
|
||||
resourcesDir?: string
|
||||
argv: string[]
|
||||
env?: NodeJS.ProcessEnv
|
||||
}): GpuRenderMode {
|
||||
const env = options.env ?? process.env
|
||||
const { flags } = parseLaunchArgs(options.argv)
|
||||
const portable = readFirstPortableConfig(getPortableConfigPaths(options.exeDir, options.resourcesDir))
|
||||
const userSaved = options.userDataDir ? readJsonFileSafe(path.join(options.userDataDir, 'config.json')) : {}
|
||||
return normalizeGpuMode(
|
||||
flags.gpuModeOverride ?? env.PLANET_GPU_MODE ?? portable.gpuMode ?? userSaved.gpuMode,
|
||||
'auto',
|
||||
)
|
||||
}
|
||||
|
||||
export function readPreReadyGpuHandoff(argv: string[]): {
|
||||
gpuHandoff: boolean
|
||||
gpuHandoffTarget?: GpuHandoffTarget
|
||||
} {
|
||||
const { flags } = parseLaunchArgs(argv)
|
||||
return {
|
||||
gpuHandoff: flags.gpuHandoff,
|
||||
gpuHandoffTarget: flags.gpuHandoffTarget,
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopConfigStore {
|
||||
private readonly userConfigPath: string
|
||||
private readonly portableConfigPaths: string[]
|
||||
@@ -170,10 +289,7 @@ export class DesktopConfigStore {
|
||||
env?: NodeJS.ProcessEnv
|
||||
}) {
|
||||
this.userConfigPath = path.join(options.userDataDir, 'config.json')
|
||||
this.portableConfigPaths = [
|
||||
path.join(options.exeDir, 'planet-earth.json'),
|
||||
...(options.resourcesDir ? [path.join(options.resourcesDir, 'planet-earth.json')] : []),
|
||||
]
|
||||
this.portableConfigPaths = getPortableConfigPaths(options.exeDir, options.resourcesDir)
|
||||
const parsed = parseLaunchArgs(options.argv)
|
||||
this.cliEndpoints = parsed.endpoints
|
||||
this.launchFlags = parsed.flags
|
||||
@@ -182,14 +298,7 @@ export class DesktopConfigStore {
|
||||
|
||||
private resolve(env: NodeJS.ProcessEnv): DesktopRuntimeConfig {
|
||||
const userSaved = readJsonFileSafe(this.userConfigPath)
|
||||
let portable: PersistedUserConfig = {}
|
||||
for (const candidate of this.portableConfigPaths) {
|
||||
const data = readJsonFileSafe(candidate)
|
||||
if (Object.keys(data).length > 0) {
|
||||
portable = data
|
||||
break
|
||||
}
|
||||
}
|
||||
const portable = readFirstPortableConfig(this.portableConfigPaths)
|
||||
|
||||
const backendUrl = normalizeHttpUrl(
|
||||
this.cliEndpoints.backendUrl ?? env.PLANET_BACKEND_URL ?? portable.backendUrl ?? userSaved.backendUrl,
|
||||
@@ -210,6 +319,13 @@ export class DesktopConfigStore {
|
||||
userSaved.splashTheme,
|
||||
'singularity',
|
||||
)
|
||||
const gpuMode = normalizeGpuMode(
|
||||
this.launchFlags.gpuModeOverride ??
|
||||
env.PLANET_GPU_MODE ??
|
||||
portable.gpuMode ??
|
||||
userSaved.gpuMode,
|
||||
'auto',
|
||||
)
|
||||
|
||||
return {
|
||||
backendUrl,
|
||||
@@ -217,6 +333,7 @@ export class DesktopConfigStore {
|
||||
motionWsUrl,
|
||||
wsUrl: deriveBackendWsUrl(backendUrl),
|
||||
splashTheme,
|
||||
gpuMode,
|
||||
...this.launchFlags,
|
||||
}
|
||||
}
|
||||
@@ -258,4 +375,14 @@ export class DesktopConfigStore {
|
||||
}
|
||||
return this.get()
|
||||
}
|
||||
|
||||
updateGpuMode(rawMode: unknown): DesktopRuntimeConfig {
|
||||
const nextMode = normalizeGpuMode(rawMode, this.current.gpuMode)
|
||||
this.writeUserConfig({ gpuMode: nextMode })
|
||||
this.current = {
|
||||
...this.current,
|
||||
gpuMode: nextMode,
|
||||
}
|
||||
return this.get()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { execFile } from 'node:child_process'
|
||||
import { mkdir, writeFile } from 'node:fs/promises'
|
||||
import { homedir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { promisify } from 'node:util'
|
||||
|
||||
import { app } from 'electron'
|
||||
|
||||
const run = promisify(execFile)
|
||||
export const DESKTOP_SCHEME = 'planet-earth'
|
||||
|
||||
export async function registerDesktopLink(): Promise<void> {
|
||||
if (!app.isPackaged) return
|
||||
|
||||
if (process.platform === 'linux') {
|
||||
let desktopId = 'planet-client.desktop'
|
||||
if (process.env.APPIMAGE) {
|
||||
desktopId = 'planet-earth-appimage.desktop'
|
||||
const applications = path.join(
|
||||
process.env.XDG_DATA_HOME || path.join(homedir(), '.local', 'share'),
|
||||
'applications',
|
||||
)
|
||||
const executable = process.env.APPIMAGE
|
||||
if (!path.isAbsolute(executable) || /[\r\n]/.test(executable)) {
|
||||
throw new Error('Invalid AppImage path')
|
||||
}
|
||||
// Escape the Exec argument, then the backslashes in the desktop-entry value.
|
||||
const escaped = executable.replace(/%/g, '%%').replace(/["$\x60\\]/g, '\\$&').replace(/\\/g, '\\\\')
|
||||
await mkdir(applications, { recursive: true })
|
||||
await writeFile(path.join(applications, desktopId), [
|
||||
'[Desktop Entry]',
|
||||
'Type=Application',
|
||||
'Name=Planet Earth',
|
||||
'NoDisplay=true',
|
||||
'Exec="' + escaped + '" %u',
|
||||
'MimeType=x-scheme-handler/' + DESKTOP_SCHEME + ';',
|
||||
'',
|
||||
].join('\n'))
|
||||
}
|
||||
const mimeType = 'x-scheme-handler/' + DESKTOP_SCHEME
|
||||
try {
|
||||
await run('xdg-mime', ['default', desktopId, mimeType], { timeout: 8000 })
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
|
||||
await run('gio', ['mime', mimeType, desktopId], { timeout: 8000 })
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
const executable = process.platform === 'win32'
|
||||
? process.env.PORTABLE_EXECUTABLE_FILE || process.execPath
|
||||
: undefined
|
||||
if (!app.isDefaultProtocolClient(DESKTOP_SCHEME, executable)
|
||||
&& !app.setAsDefaultProtocolClient(DESKTOP_SCHEME, executable)) {
|
||||
throw new Error('Could not register the Planet Earth URL handler')
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
import { execFile, execFileSync } from 'node:child_process'
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { promisify } from 'node:util'
|
||||
|
||||
import type { BrowserWindow } from 'electron'
|
||||
|
||||
import type { GpuRenderMode } from './config'
|
||||
import {
|
||||
canAutoSwitchGpu,
|
||||
createVramHysteresisTracker,
|
||||
detectIntegratedGpuFromRegistryOutput,
|
||||
parseNvidiaSmiCsv,
|
||||
VRAM_LOW_THRESHOLD_MIB,
|
||||
VRAM_MONITOR_INTERVAL_MS,
|
||||
type DiscreteVramSample,
|
||||
type ResolvedGpuTarget,
|
||||
type StartupGpuDecision,
|
||||
type StartupGpuDecisionReason,
|
||||
} from './gpu-policy'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
const HANDOFF_RECORD_MAX_AGE_MS = 30_000
|
||||
const HANDOFF_RECORD_FILE = 'gpu-handoff.json'
|
||||
|
||||
const NVIDIA_SMI_ARGS = [
|
||||
'--query-gpu=name,memory.used,memory.free,memory.total',
|
||||
'--format=csv,noheader,nounits',
|
||||
]
|
||||
|
||||
const DISPLAY_CLASS_REG_ARGS = [
|
||||
'query',
|
||||
'HKLM\\SYSTEM\\CurrentControlSet\\Control\\Class\\{4d36e968-e325-11ce-bfc1-08002be10318}',
|
||||
'/s',
|
||||
'/v',
|
||||
'DriverDesc',
|
||||
]
|
||||
|
||||
export interface GpuHandoffRecord {
|
||||
lastSwitchAt: number
|
||||
target: ResolvedGpuTarget
|
||||
reason: 'low-fps-low-vram' | 'vram-recovered' | 'manual'
|
||||
freeMiB?: number
|
||||
avgFps?: number
|
||||
}
|
||||
|
||||
export interface GpuRuntimeSummary {
|
||||
requestedMode: GpuRenderMode
|
||||
activeTarget: ResolvedGpuTarget
|
||||
reason: StartupGpuDecisionReason
|
||||
hasIntegratedGpu: boolean
|
||||
latestVramSample: DiscreteVramSample | null
|
||||
}
|
||||
|
||||
export interface AdaptiveGpuMonitor {
|
||||
start(): void
|
||||
stop(): void
|
||||
handleLowFpsReport(report: { avgFps: number; sustainedMs: number }): Promise<void>
|
||||
consumePendingHandoffToast(): { message: string; type: 'info' | 'success' } | null
|
||||
getRuntimeSummary(): GpuRuntimeSummary
|
||||
}
|
||||
|
||||
export function readGpuHandoffRecord(userDataDir: string): GpuHandoffRecord | null {
|
||||
if (!userDataDir) return null
|
||||
try {
|
||||
const filePath = path.join(userDataDir, HANDOFF_RECORD_FILE)
|
||||
if (!fs.existsSync(filePath)) return null
|
||||
const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8')) as Partial<GpuHandoffRecord>
|
||||
if (
|
||||
!parsed ||
|
||||
typeof parsed.lastSwitchAt !== 'number' ||
|
||||
!Number.isFinite(parsed.lastSwitchAt) ||
|
||||
typeof parsed.target !== 'string' ||
|
||||
typeof parsed.reason !== 'string'
|
||||
) {
|
||||
return null
|
||||
}
|
||||
return parsed as GpuHandoffRecord
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export function writeGpuHandoffRecord(userDataDir: string, record: GpuHandoffRecord): void {
|
||||
if (!userDataDir) return
|
||||
try {
|
||||
const filePath = path.join(userDataDir, HANDOFF_RECORD_FILE)
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true })
|
||||
fs.writeFileSync(filePath, `${JSON.stringify(record, null, 2)}\n`, 'utf8')
|
||||
} catch {
|
||||
// Ignore non-critical handoff state write failures.
|
||||
}
|
||||
}
|
||||
|
||||
export function probeWindowsGpuEnvironmentSync(): {
|
||||
vramSample: DiscreteVramSample | null
|
||||
hasIntegratedGpu: boolean
|
||||
} {
|
||||
if (process.platform !== 'win32') {
|
||||
return { vramSample: null, hasIntegratedGpu: false }
|
||||
}
|
||||
|
||||
let vramSample: DiscreteVramSample | null = null
|
||||
try {
|
||||
const out = execFileSync('nvidia-smi', NVIDIA_SMI_ARGS, {
|
||||
encoding: 'utf8',
|
||||
timeout: 800,
|
||||
windowsHide: true,
|
||||
stdio: ['ignore', 'pipe', 'ignore'],
|
||||
})
|
||||
vramSample = parseNvidiaSmiCsv(out)
|
||||
} catch {
|
||||
vramSample = null
|
||||
}
|
||||
|
||||
let hasIntegratedGpu = false
|
||||
try {
|
||||
const out = execFileSync('reg.exe', DISPLAY_CLASS_REG_ARGS, {
|
||||
encoding: 'utf8',
|
||||
timeout: 800,
|
||||
windowsHide: true,
|
||||
stdio: ['ignore', 'pipe', 'ignore'],
|
||||
})
|
||||
hasIntegratedGpu = detectIntegratedGpuFromRegistryOutput(out)
|
||||
} catch {
|
||||
hasIntegratedGpu = false
|
||||
}
|
||||
|
||||
return { vramSample, hasIntegratedGpu }
|
||||
}
|
||||
|
||||
export async function probeDiscreteVramAsync(): Promise<DiscreteVramSample | null> {
|
||||
if (process.platform !== 'win32') {
|
||||
return null
|
||||
}
|
||||
try {
|
||||
const { stdout } = await execFileAsync('nvidia-smi', NVIDIA_SMI_ARGS, {
|
||||
encoding: 'utf8',
|
||||
timeout: 2000,
|
||||
windowsHide: true,
|
||||
})
|
||||
return parseNvidiaSmiCsv(stdout)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export async function probeIntegratedGpuAsync(): Promise<boolean> {
|
||||
if (process.platform !== 'win32') {
|
||||
return false
|
||||
}
|
||||
try {
|
||||
const { stdout } = await execFileAsync('reg.exe', DISPLAY_CLASS_REG_ARGS, {
|
||||
encoding: 'utf8',
|
||||
timeout: 2000,
|
||||
windowsHide: true,
|
||||
})
|
||||
return detectIntegratedGpuFromRegistryOutput(stdout)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export function createAdaptiveGpuMonitor(options: {
|
||||
userDataDir: string
|
||||
startupDecision: StartupGpuDecision
|
||||
getConfiguredMode: () => GpuRenderMode
|
||||
getMainWindow: () => BrowserWindow | null
|
||||
onAutoSwitch: (target: ResolvedGpuTarget, record: GpuHandoffRecord) => void
|
||||
onStatusUpdated?: () => void
|
||||
}): AdaptiveGpuMonitor {
|
||||
let latestVramSample: DiscreteVramSample | null = options.startupDecision.vramSample
|
||||
let switching = false
|
||||
let toastConsumed = false
|
||||
let intervalTimer: ReturnType<typeof setInterval> | null = null
|
||||
const lastSwitchAt = readGpuHandoffRecord(options.userDataDir)?.lastSwitchAt ?? null
|
||||
|
||||
const activeTarget = options.startupDecision.target
|
||||
const isDiscrete = activeTarget === 'default' || activeTarget === 'high-performance'
|
||||
const isOffloaded = activeTarget === 'low-power' || activeTarget === 'software'
|
||||
|
||||
const tracker = createVramHysteresisTracker({
|
||||
activeTarget,
|
||||
hasIntegratedGpu: options.startupDecision.hasIntegratedGpu,
|
||||
})
|
||||
|
||||
const triggerAutoSwitch = (target: ResolvedGpuTarget, record: GpuHandoffRecord) => {
|
||||
if (switching) return
|
||||
switching = true
|
||||
if (intervalTimer) {
|
||||
clearInterval(intervalTimer)
|
||||
intervalTimer = null
|
||||
}
|
||||
writeGpuHandoffRecord(options.userDataDir, record)
|
||||
options.onAutoSwitch(target, record)
|
||||
}
|
||||
|
||||
const tickOffloadedRecovery = async () => {
|
||||
if (switching || !isOffloaded || options.getConfiguredMode() !== 'auto') return
|
||||
if (!canAutoSwitchGpu(lastSwitchAt, Date.now())) return
|
||||
const win = options.getMainWindow()
|
||||
if (!win || win.isDestroyed() || win.isMinimized()) return
|
||||
|
||||
const sample = await probeDiscreteVramAsync()
|
||||
latestVramSample = sample
|
||||
options.onStatusUpdated?.()
|
||||
|
||||
if (switching || options.getConfiguredMode() !== 'auto') return
|
||||
const action = tracker.observe(sample)
|
||||
if (!action || action.kind !== 'switch-to-discrete') return
|
||||
|
||||
const now = Date.now()
|
||||
if (!canAutoSwitchGpu(lastSwitchAt, now)) return
|
||||
console.info(
|
||||
`[planet-client] Discrete GPU VRAM recovered (freeMiB=${action.sample.freeMiB}); auto-switching back to discrete GPU`,
|
||||
)
|
||||
triggerAutoSwitch('default', {
|
||||
lastSwitchAt: now,
|
||||
target: 'default',
|
||||
reason: 'vram-recovered',
|
||||
freeMiB: action.sample.freeMiB,
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
start() {
|
||||
if (process.platform !== 'win32' || options.startupDecision.reason === 'headless-smoke') {
|
||||
return
|
||||
}
|
||||
if (!isOffloaded || intervalTimer) return
|
||||
intervalTimer = setInterval(() => {
|
||||
void tickOffloadedRecovery()
|
||||
}, VRAM_MONITOR_INTERVAL_MS)
|
||||
},
|
||||
|
||||
stop() {
|
||||
if (intervalTimer) {
|
||||
clearInterval(intervalTimer)
|
||||
intervalTimer = null
|
||||
}
|
||||
},
|
||||
|
||||
async handleLowFpsReport(report: { avgFps: number; sustainedMs: number }): Promise<void> {
|
||||
if (
|
||||
process.platform !== 'win32' ||
|
||||
options.startupDecision.reason === 'headless-smoke' ||
|
||||
switching ||
|
||||
!isDiscrete ||
|
||||
options.getConfiguredMode() !== 'auto'
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
const now = Date.now()
|
||||
if (!canAutoSwitchGpu(lastSwitchAt, now)) return
|
||||
|
||||
const sample = await probeDiscreteVramAsync()
|
||||
latestVramSample = sample
|
||||
options.onStatusUpdated?.()
|
||||
|
||||
if (
|
||||
switching ||
|
||||
options.getConfiguredMode() !== 'auto' ||
|
||||
!sample ||
|
||||
sample.freeMiB >= VRAM_LOW_THRESHOLD_MIB
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
const hasIgpu = options.startupDecision.hasIntegratedGpu || (await probeIntegratedGpuAsync())
|
||||
const nextTarget: ResolvedGpuTarget = hasIgpu ? 'low-power' : 'software'
|
||||
const switchNow = Date.now()
|
||||
if (!canAutoSwitchGpu(lastSwitchAt, switchNow)) return
|
||||
|
||||
console.info(
|
||||
`[planet-client] Sustained low FPS (${report.avgFps} fps for ${report.sustainedMs}ms) with low discrete VRAM (freeMiB=${sample.freeMiB}); auto-switching to ${nextTarget}`,
|
||||
)
|
||||
triggerAutoSwitch(nextTarget, {
|
||||
lastSwitchAt: switchNow,
|
||||
target: nextTarget,
|
||||
reason: 'low-fps-low-vram',
|
||||
freeMiB: sample.freeMiB,
|
||||
avgFps: report.avgFps,
|
||||
})
|
||||
},
|
||||
|
||||
consumePendingHandoffToast(): { message: string; type: 'info' | 'success' } | null {
|
||||
if (toastConsumed || options.startupDecision.reason !== 'gpu-handoff') {
|
||||
return null
|
||||
}
|
||||
toastConsumed = true
|
||||
const record = readGpuHandoffRecord(options.userDataDir)
|
||||
if (!record || Date.now() - record.lastSwitchAt >= HANDOFF_RECORD_MAX_AGE_MS) {
|
||||
return null
|
||||
}
|
||||
if (record.reason === 'low-fps-low-vram') {
|
||||
return record.target === 'software'
|
||||
? { message: '独显显存不足且帧率偏低,已自动切换至 CPU 软渲染', type: 'info' }
|
||||
: {
|
||||
message: '独显显存不足且帧率偏低,已自动切换至集成核显渲染(保留全部特效)',
|
||||
type: 'info',
|
||||
}
|
||||
}
|
||||
if (record.reason === 'vram-recovered') {
|
||||
return { message: '独显显存已充足,已自动切回独立显卡渲染', type: 'success' }
|
||||
}
|
||||
return null
|
||||
},
|
||||
|
||||
getRuntimeSummary(): GpuRuntimeSummary {
|
||||
return {
|
||||
requestedMode: options.getConfiguredMode(),
|
||||
activeTarget: options.startupDecision.target,
|
||||
reason: options.startupDecision.reason,
|
||||
hasIntegratedGpu: options.startupDecision.hasIntegratedGpu,
|
||||
latestVramSample,
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
import type { GpuRenderMode } from './config'
|
||||
|
||||
export const VRAM_LOW_THRESHOLD_MIB = 2048
|
||||
export const VRAM_RECOVER_THRESHOLD_MIB = 3584
|
||||
export const VRAM_MONITOR_INTERVAL_MS = 5_000
|
||||
export const VRAM_SWITCH_CONSECUTIVE_REQUIRED = 2
|
||||
export const LOW_FPS_THRESHOLD = 20
|
||||
export const LOW_FPS_SUSTAINED_MS = 5_000
|
||||
export const FPS_STARTUP_WARMUP_MS = 6_000
|
||||
export const FPS_REPORT_COOLDOWN_MS = 15_000
|
||||
export const AUTO_SWITCH_COOLDOWN_MS = 45_000
|
||||
|
||||
export interface ChromiumSwitch {
|
||||
name: string
|
||||
value?: string
|
||||
}
|
||||
|
||||
export type ResolvedGpuTarget = 'default' | 'high-performance' | 'low-power' | 'software'
|
||||
|
||||
export interface DiscreteVramSample {
|
||||
gpuName: string
|
||||
usedMiB: number
|
||||
freeMiB: number
|
||||
totalMiB: number
|
||||
}
|
||||
|
||||
export type StartupGpuDecisionReason =
|
||||
| 'headless-smoke'
|
||||
| 'gpu-handoff'
|
||||
| 'user-software'
|
||||
| 'user-low-power'
|
||||
| 'user-high-performance'
|
||||
| 'low-vram-igpu'
|
||||
| 'low-vram-software'
|
||||
| 'normal-gpu'
|
||||
|
||||
export interface StartupGpuDecision {
|
||||
target: ResolvedGpuTarget
|
||||
requestedMode: GpuRenderMode
|
||||
reason: StartupGpuDecisionReason
|
||||
vramSample: DiscreteVramSample | null
|
||||
hasIntegratedGpu: boolean
|
||||
}
|
||||
|
||||
export interface VramMonitorAction {
|
||||
kind: 'switch-to-discrete' | 'switch-to-low-power' | 'switch-to-software'
|
||||
sample: DiscreteVramSample
|
||||
}
|
||||
|
||||
export interface GpuPolicyInput {
|
||||
platform: NodeJS.Platform
|
||||
headlessSmoke: boolean
|
||||
softwareGl?: boolean
|
||||
target?: ResolvedGpuTarget
|
||||
}
|
||||
|
||||
const VIRTUAL_DISPLAY_ADAPTER_RE = /microsoft basic|remote display|parsec|virtual|indirect|mirage/i
|
||||
const INTEL_ADAPTER_RE = /\bintel\b/i
|
||||
const INTEL_DISCRETE_ARC_RE = /\barc\b.*\b[ab]\d{3}\b/i
|
||||
const AMD_INTEGRATED_RE = /\bamd\s+radeon(?:\(tm\))?\s+(?:graphics|\d+m\b|vega\s+\d+\s+graphics)/i
|
||||
|
||||
function parseMiBField(raw: string | undefined): number | null {
|
||||
if (!raw) return null
|
||||
const trimmed = raw.trim()
|
||||
if (!trimmed || /n\/a/i.test(trimmed)) return null
|
||||
const cleaned = trimmed.replace(/\s*mib$/i, '')
|
||||
if (!/^\d+(?:\.\d+)?$/.test(cleaned)) return null
|
||||
const num = Number(cleaned)
|
||||
return Number.isFinite(num) ? num : null
|
||||
}
|
||||
|
||||
export function parseNvidiaSmiCsv(stdout: string): DiscreteVramSample | null {
|
||||
if (!stdout) return null
|
||||
for (const rawLine of stdout.split(/\r?\n/)) {
|
||||
const line = rawLine.trim()
|
||||
if (!line) continue
|
||||
const parts = line.split(',')
|
||||
if (parts.length < 4) continue
|
||||
const gpuName = parts.slice(0, -3).join(',').trim()
|
||||
const usedMiB = parseMiBField(parts[parts.length - 3])
|
||||
const freeMiB = parseMiBField(parts[parts.length - 2])
|
||||
const totalMiB = parseMiBField(parts[parts.length - 1])
|
||||
if (
|
||||
!gpuName ||
|
||||
usedMiB === null ||
|
||||
freeMiB === null ||
|
||||
totalMiB === null ||
|
||||
usedMiB < 0 ||
|
||||
freeMiB < 0 ||
|
||||
totalMiB <= 0
|
||||
) {
|
||||
continue
|
||||
}
|
||||
return { gpuName, usedMiB, freeMiB, totalMiB }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export function detectIntegratedGpuFromRegistryOutput(stdout: string): boolean {
|
||||
if (!stdout) return false
|
||||
for (const rawLine of stdout.split(/\r?\n/)) {
|
||||
const match = /^\s*DriverDesc\s+REG_SZ\s+(.+?)\s*$/i.exec(rawLine)
|
||||
if (!match) continue
|
||||
const desc = match[1].trim()
|
||||
if (!desc || VIRTUAL_DISPLAY_ADAPTER_RE.test(desc)) continue
|
||||
if (INTEL_ADAPTER_RE.test(desc) && !INTEL_DISCRETE_ARC_RE.test(desc)) {
|
||||
return true
|
||||
}
|
||||
if (AMD_INTEGRATED_RE.test(desc)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
export function chooseStartupGpuTarget(input: {
|
||||
platform: NodeJS.Platform
|
||||
headlessSmoke: boolean
|
||||
requestedMode: GpuRenderMode
|
||||
handoffTarget?: ResolvedGpuTarget
|
||||
vramSample: DiscreteVramSample | null
|
||||
hasIntegratedGpu: boolean
|
||||
}): StartupGpuDecision {
|
||||
const base = {
|
||||
requestedMode: input.requestedMode,
|
||||
vramSample: input.vramSample,
|
||||
hasIntegratedGpu: input.hasIntegratedGpu,
|
||||
}
|
||||
|
||||
if (input.headlessSmoke) {
|
||||
return { ...base, target: 'software', reason: 'headless-smoke' }
|
||||
}
|
||||
if (input.requestedMode === 'software') {
|
||||
return { ...base, target: 'software', reason: 'user-software' }
|
||||
}
|
||||
if (input.requestedMode === 'low-power') {
|
||||
return { ...base, target: 'low-power', reason: 'user-low-power' }
|
||||
}
|
||||
if (input.requestedMode === 'high-performance') {
|
||||
return { ...base, target: 'high-performance', reason: 'user-high-performance' }
|
||||
}
|
||||
if (input.handoffTarget) {
|
||||
return { ...base, target: input.handoffTarget, reason: 'gpu-handoff' }
|
||||
}
|
||||
|
||||
if (
|
||||
input.platform === 'win32' &&
|
||||
input.vramSample &&
|
||||
input.vramSample.freeMiB < VRAM_LOW_THRESHOLD_MIB
|
||||
) {
|
||||
return input.hasIntegratedGpu
|
||||
? { ...base, target: 'low-power', reason: 'low-vram-igpu' }
|
||||
: { ...base, target: 'software', reason: 'low-vram-software' }
|
||||
}
|
||||
|
||||
return { ...base, target: 'default', reason: 'normal-gpu' }
|
||||
}
|
||||
|
||||
export function resolveChromiumGpuSwitches(input: GpuPolicyInput): ChromiumSwitch[] {
|
||||
const effectiveTarget: ResolvedGpuTarget =
|
||||
input.headlessSmoke || input.softwareGl || input.target === 'software'
|
||||
? 'software'
|
||||
: (input.target ?? 'default')
|
||||
|
||||
if (effectiveTarget === 'software') {
|
||||
return [
|
||||
{ name: 'disable-gpu' },
|
||||
{ name: 'use-gl', value: 'angle' },
|
||||
{ name: 'use-angle', value: 'swiftshader' },
|
||||
{ name: 'enable-unsafe-swiftshader' },
|
||||
]
|
||||
}
|
||||
|
||||
// Avoid forcing enable-zero-copy / enable-gpu-rasterization:
|
||||
// on Windows dual-GPU setups with high baseline VRAM usage they can provoke driver TDRs.
|
||||
const switches: ChromiumSwitch[] = []
|
||||
if (effectiveTarget === 'low-power') {
|
||||
switches.push({ name: 'force_low_power_gpu' })
|
||||
} else if (effectiveTarget === 'high-performance') {
|
||||
switches.push({ name: 'force_high_performance_gpu' })
|
||||
}
|
||||
switches.push({ name: 'disable-renderer-backgrounding' })
|
||||
if (input.platform === 'linux') {
|
||||
switches.push({ name: 'ozone-platform-hint', value: 'auto' })
|
||||
}
|
||||
return switches
|
||||
}
|
||||
|
||||
export function createVramHysteresisTracker(options: {
|
||||
activeTarget: ResolvedGpuTarget
|
||||
hasIntegratedGpu: boolean
|
||||
lowThresholdMiB?: number
|
||||
recoverThresholdMiB?: number
|
||||
requiredConsecutive?: number
|
||||
}) {
|
||||
const lowThresholdMiB = options.lowThresholdMiB ?? VRAM_LOW_THRESHOLD_MIB
|
||||
const recoverThresholdMiB = options.recoverThresholdMiB ?? VRAM_RECOVER_THRESHOLD_MIB
|
||||
const requiredConsecutive = Math.max(1, options.requiredConsecutive ?? VRAM_SWITCH_CONSECUTIVE_REQUIRED)
|
||||
let streak = 0
|
||||
|
||||
return {
|
||||
observe(sample: DiscreteVramSample | null): VramMonitorAction | null {
|
||||
if (!sample) {
|
||||
streak = 0
|
||||
return null
|
||||
}
|
||||
|
||||
if (options.activeTarget === 'low-power' || options.activeTarget === 'software') {
|
||||
if (sample.freeMiB >= recoverThresholdMiB) {
|
||||
streak += 1
|
||||
if (streak >= requiredConsecutive) {
|
||||
return { kind: 'switch-to-discrete', sample }
|
||||
}
|
||||
} else {
|
||||
streak = 0
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
if (sample.freeMiB < lowThresholdMiB) {
|
||||
streak += 1
|
||||
if (streak >= requiredConsecutive) {
|
||||
return {
|
||||
kind: options.hasIntegratedGpu ? 'switch-to-low-power' : 'switch-to-software',
|
||||
sample,
|
||||
}
|
||||
}
|
||||
} else {
|
||||
streak = 0
|
||||
}
|
||||
return null
|
||||
},
|
||||
reset(): void {
|
||||
streak = 0
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export function createSustainedLowFpsTracker(
|
||||
options: {
|
||||
thresholdFps?: number
|
||||
sustainedMs?: number
|
||||
sampleWindowMs?: number
|
||||
reportCooldownMs?: number
|
||||
} = {},
|
||||
) {
|
||||
const thresholdFps = options.thresholdFps ?? LOW_FPS_THRESHOLD
|
||||
const sustainedMs = options.sustainedMs ?? LOW_FPS_SUSTAINED_MS
|
||||
const sampleWindowMs = options.sampleWindowMs ?? 1000
|
||||
const reportCooldownMs = options.reportCooldownMs ?? FPS_REPORT_COOLDOWN_MS
|
||||
|
||||
let bucketStartMs: number | null = null
|
||||
let bucketFrames = 0
|
||||
let lowDurationMs = 0
|
||||
let lowFrames = 0
|
||||
let lastReportedAt = -Infinity
|
||||
|
||||
return {
|
||||
onFrame(nowMs: number): { avgFps: number; sustainedMs: number } | null {
|
||||
if (!Number.isFinite(nowMs)) return null
|
||||
if (bucketStartMs === null) {
|
||||
bucketStartMs = nowMs
|
||||
bucketFrames = 0
|
||||
return null
|
||||
}
|
||||
bucketFrames += 1
|
||||
const elapsedMs = nowMs - bucketStartMs
|
||||
if (elapsedMs < sampleWindowMs) {
|
||||
return null
|
||||
}
|
||||
|
||||
const fps = (bucketFrames * 1000) / elapsedMs
|
||||
bucketStartMs = nowMs
|
||||
|
||||
if (fps < thresholdFps) {
|
||||
lowDurationMs += elapsedMs
|
||||
lowFrames += bucketFrames
|
||||
bucketFrames = 0
|
||||
if (lowDurationMs >= sustainedMs && nowMs - lastReportedAt >= reportCooldownMs) {
|
||||
const avgFps = Math.round(((lowFrames * 1000) / lowDurationMs) * 10) / 10
|
||||
const reportedDuration = Math.round(lowDurationMs)
|
||||
lastReportedAt = nowMs
|
||||
lowDurationMs = 0
|
||||
lowFrames = 0
|
||||
return { avgFps, sustainedMs: reportedDuration }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
bucketFrames = 0
|
||||
lowDurationMs = 0
|
||||
lowFrames = 0
|
||||
return null
|
||||
},
|
||||
reset(): void {
|
||||
bucketStartMs = null
|
||||
bucketFrames = 0
|
||||
lowDurationMs = 0
|
||||
lowFrames = 0
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export function canAutoSwitchGpu(
|
||||
lastSwitchAt: number | null | undefined,
|
||||
nowMs: number,
|
||||
cooldownMs = AUTO_SWITCH_COOLDOWN_MS,
|
||||
): boolean {
|
||||
return !lastSwitchAt || !Number.isFinite(lastSwitchAt) || nowMs - lastSwitchAt >= cooldownMs
|
||||
}
|
||||
|
||||
export function stripGpuOverrideArgs(argv: string[]): string[] {
|
||||
const stripped: string[] = []
|
||||
for (let i = 0; i < argv.length; i += 1) {
|
||||
const arg = argv[i]
|
||||
if (
|
||||
arg === '--software-gl' ||
|
||||
arg === '--low-power-gpu' ||
|
||||
arg === '--high-performance-gpu' ||
|
||||
arg === '--gpu-handoff' ||
|
||||
arg.startsWith('--gpu-mode=') ||
|
||||
arg.startsWith('--gpu-handoff-target=')
|
||||
) {
|
||||
continue
|
||||
}
|
||||
if (arg === '--gpu-mode' || arg === '--gpu-handoff-target') {
|
||||
i += 1
|
||||
continue
|
||||
}
|
||||
stripped.push(arg)
|
||||
}
|
||||
return stripped
|
||||
}
|
||||
|
||||
export function buildGpuHandoffArgs(argv: string[], target?: ResolvedGpuTarget): string[] {
|
||||
return [
|
||||
...stripGpuOverrideArgs(argv),
|
||||
'--gpu-handoff',
|
||||
...(target ? [`--gpu-handoff-target=${target}`] : []),
|
||||
]
|
||||
}
|
||||
|
||||
export function isGpuProcessCrash(
|
||||
details: { type?: string; reason?: string } | null | undefined,
|
||||
): boolean {
|
||||
return Boolean(details && details.type === 'GPU' && details.reason !== 'clean-exit')
|
||||
}
|
||||
@@ -0,0 +1,504 @@
|
||||
import crypto from 'node:crypto'
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
|
||||
import { extractTarGzSafely } from './tar-gz'
|
||||
|
||||
export interface ClientShellUpdateInfo {
|
||||
version: string
|
||||
minRequired?: string | null
|
||||
downloadUrl: string
|
||||
releaseNotes?: string | null
|
||||
}
|
||||
|
||||
export interface ClientBundleUpdateInfo {
|
||||
version: string
|
||||
minShellVersion: string
|
||||
url: string
|
||||
sha256: string
|
||||
size?: number
|
||||
releaseNotes?: string | null
|
||||
}
|
||||
|
||||
export interface ClientUpdateManifest {
|
||||
shell?: ClientShellUpdateInfo | null
|
||||
bundle?: ClientBundleUpdateInfo | null
|
||||
}
|
||||
|
||||
export interface HotfixState {
|
||||
activeVersion: string | null
|
||||
previousVerifiedVersion: string | null
|
||||
status: 'verified' | 'pending'
|
||||
pendingAttempts: number
|
||||
blacklistedVersions: string[]
|
||||
installedAt?: string
|
||||
}
|
||||
|
||||
export interface ActiveOverlayResolution {
|
||||
overlayRoot: string | null
|
||||
activeBundleVersion: string
|
||||
pendingVerification: boolean
|
||||
rolledBackFrom: string | null
|
||||
}
|
||||
|
||||
export type UpdateDecision =
|
||||
| { kind: 'up-to-date' }
|
||||
| { kind: 'hotfix-update'; bundle: ClientBundleUpdateInfo }
|
||||
| { kind: 'shell-update'; shell: ClientShellUpdateInfo; mandatory: boolean }
|
||||
|
||||
const SEMVER_PATTERN = /^[vV]?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/
|
||||
const STRICT_VERSION_PATTERN = /^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][0-9A-Za-z.-]+)?$/
|
||||
const SHA256_PATTERN = /^[0-9a-f]{64}$/i
|
||||
const MAX_PENDING_ATTEMPTS = 2
|
||||
|
||||
interface ParsedSemver {
|
||||
major: number
|
||||
minor: number
|
||||
patch: number
|
||||
prerelease: string[]
|
||||
}
|
||||
|
||||
function parseSemver(raw: string): ParsedSemver | null {
|
||||
const match = SEMVER_PATTERN.exec(String(raw || '').trim())
|
||||
if (!match) return null
|
||||
return {
|
||||
major: Number(match[1] ?? 0),
|
||||
minor: Number(match[2] ?? 0),
|
||||
patch: Number(match[3] ?? 0),
|
||||
prerelease: match[4] ? match[4].split('.') : [],
|
||||
}
|
||||
}
|
||||
|
||||
export function compareSemver(a: string, b: string): number {
|
||||
const pa = parseSemver(a)
|
||||
const pb = parseSemver(b)
|
||||
if (!pa || !pb) {
|
||||
return String(a).localeCompare(String(b))
|
||||
}
|
||||
for (const [va, vb] of [
|
||||
[pa.major, pb.major],
|
||||
[pa.minor, pb.minor],
|
||||
[pa.patch, pb.patch],
|
||||
]) {
|
||||
if (va !== vb) return va > vb ? 1 : -1
|
||||
}
|
||||
if (pa.prerelease.length === 0 && pb.prerelease.length === 0) return 0
|
||||
if (pa.prerelease.length === 0) return 1
|
||||
if (pb.prerelease.length === 0) return -1
|
||||
|
||||
const maxLen = Math.max(pa.prerelease.length, pb.prerelease.length)
|
||||
for (let i = 0; i < maxLen; i += 1) {
|
||||
const ia = pa.prerelease[i]
|
||||
const ib = pb.prerelease[i]
|
||||
if (ia === undefined) return -1
|
||||
if (ib === undefined) return 1
|
||||
const na = /^\d+$/.test(ia) ? Number(ia) : null
|
||||
const nb = /^\d+$/.test(ib) ? Number(ib) : null
|
||||
if (na !== null && nb !== null) {
|
||||
if (na !== nb) return na > nb ? 1 : -1
|
||||
} else if (na !== null) {
|
||||
return -1
|
||||
} else if (nb !== null) {
|
||||
return 1
|
||||
} else if (ia !== ib) {
|
||||
return ia > ib ? 1 : -1
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
export function getHotfixRootDir(userDataDir: string): string {
|
||||
return path.join(userDataDir, 'earth-hotfix')
|
||||
}
|
||||
|
||||
export function getHotfixBundlesDir(userDataDir: string): string {
|
||||
return path.join(getHotfixRootDir(userDataDir), 'bundles')
|
||||
}
|
||||
|
||||
export function getHotfixBundleDir(userDataDir: string, version: string): string {
|
||||
return path.join(getHotfixBundlesDir(userDataDir), version)
|
||||
}
|
||||
|
||||
function getHotfixStatePath(userDataDir: string): string {
|
||||
return path.join(getHotfixRootDir(userDataDir), 'state.json')
|
||||
}
|
||||
|
||||
function defaultHotfixState(): HotfixState {
|
||||
return {
|
||||
activeVersion: null,
|
||||
previousVerifiedVersion: null,
|
||||
status: 'verified',
|
||||
pendingAttempts: 0,
|
||||
blacklistedVersions: [],
|
||||
}
|
||||
}
|
||||
|
||||
export function readHotfixState(userDataDir: string): HotfixState {
|
||||
const statePath = getHotfixStatePath(userDataDir)
|
||||
try {
|
||||
if (!fs.existsSync(statePath)) return defaultHotfixState()
|
||||
const raw = JSON.parse(fs.readFileSync(statePath, 'utf8')) as Partial<HotfixState>
|
||||
return {
|
||||
activeVersion: typeof raw.activeVersion === 'string' && STRICT_VERSION_PATTERN.test(raw.activeVersion)
|
||||
? raw.activeVersion
|
||||
: null,
|
||||
previousVerifiedVersion: typeof raw.previousVerifiedVersion === 'string' && STRICT_VERSION_PATTERN.test(raw.previousVerifiedVersion)
|
||||
? raw.previousVerifiedVersion
|
||||
: null,
|
||||
status: raw.status === 'pending' ? 'pending' : 'verified',
|
||||
pendingAttempts: Number.isInteger(raw.pendingAttempts) && Number(raw.pendingAttempts) >= 0
|
||||
? Number(raw.pendingAttempts)
|
||||
: 0,
|
||||
blacklistedVersions: Array.isArray(raw.blacklistedVersions)
|
||||
? raw.blacklistedVersions.filter((item): item is string => typeof item === 'string' && STRICT_VERSION_PATTERN.test(item))
|
||||
: [],
|
||||
installedAt: typeof raw.installedAt === 'string' ? raw.installedAt : undefined,
|
||||
}
|
||||
} catch {
|
||||
return defaultHotfixState()
|
||||
}
|
||||
}
|
||||
|
||||
export function writeHotfixStateAtomic(userDataDir: string, state: HotfixState): void {
|
||||
const rootDir = getHotfixRootDir(userDataDir)
|
||||
const statePath = getHotfixStatePath(userDataDir)
|
||||
const tmpPath = `${statePath}.${process.pid}.tmp`
|
||||
fs.mkdirSync(rootDir, { recursive: true })
|
||||
fs.writeFileSync(tmpPath, `${JSON.stringify(state, null, 2)}\n`, 'utf8')
|
||||
fs.renameSync(tmpPath, statePath)
|
||||
}
|
||||
|
||||
function hasValidBundleIndex(bundleDir: string): boolean {
|
||||
try {
|
||||
return fs.statSync(path.join(bundleDir, 'index.html')).isFile()
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function resolveFallbackVersion(state: HotfixState, shellVersion: string, userDataDir: string): string | null {
|
||||
const candidate = state.previousVerifiedVersion
|
||||
if (!candidate) return null
|
||||
if (candidate === state.activeVersion) return null
|
||||
if (state.blacklistedVersions.includes(candidate)) return null
|
||||
if (compareSemver(candidate, shellVersion) <= 0) return null
|
||||
if (!hasValidBundleIndex(getHotfixBundleDir(userDataDir, candidate))) return null
|
||||
return candidate
|
||||
}
|
||||
|
||||
function pruneObsoleteBundles(userDataDir: string, keepVersions: Set<string>): void {
|
||||
const bundlesDir = getHotfixBundlesDir(userDataDir)
|
||||
try {
|
||||
if (!fs.existsSync(bundlesDir)) return
|
||||
for (const entry of fs.readdirSync(bundlesDir, { withFileTypes: true })) {
|
||||
if (!entry.isDirectory()) continue
|
||||
if (keepVersions.has(entry.name)) continue
|
||||
fs.rmSync(path.join(bundlesDir, entry.name), { recursive: true, force: true })
|
||||
}
|
||||
} catch {
|
||||
// Non-fatal cleanup best-effort.
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveActiveEarthOverlay(options: {
|
||||
userDataDir: string
|
||||
shellVersion: string
|
||||
}): ActiveOverlayResolution {
|
||||
const { userDataDir, shellVersion } = options
|
||||
const state = readHotfixState(userDataDir)
|
||||
|
||||
if (!state.activeVersion || compareSemver(state.activeVersion, shellVersion) <= 0) {
|
||||
return {
|
||||
overlayRoot: null,
|
||||
activeBundleVersion: shellVersion,
|
||||
pendingVerification: false,
|
||||
rolledBackFrom: null,
|
||||
}
|
||||
}
|
||||
|
||||
const activeDir = getHotfixBundleDir(userDataDir, state.activeVersion)
|
||||
const activeUsable =
|
||||
!state.blacklistedVersions.includes(state.activeVersion) && hasValidBundleIndex(activeDir)
|
||||
|
||||
if (!activeUsable) {
|
||||
const badVersion = state.activeVersion
|
||||
const fallbackVer = resolveFallbackVersion(state, shellVersion, userDataDir)
|
||||
const nextState: HotfixState = {
|
||||
...state,
|
||||
activeVersion: fallbackVer,
|
||||
previousVerifiedVersion: fallbackVer,
|
||||
status: 'verified',
|
||||
pendingAttempts: 0,
|
||||
}
|
||||
writeHotfixStateAtomic(userDataDir, nextState)
|
||||
return {
|
||||
overlayRoot: fallbackVer ? getHotfixBundleDir(userDataDir, fallbackVer) : null,
|
||||
activeBundleVersion: fallbackVer ?? shellVersion,
|
||||
pendingVerification: false,
|
||||
rolledBackFrom: badVersion,
|
||||
}
|
||||
}
|
||||
|
||||
if (state.status === 'pending') {
|
||||
if (state.pendingAttempts >= MAX_PENDING_ATTEMPTS) {
|
||||
const rolledBackFrom = state.activeVersion
|
||||
const blacklist = state.blacklistedVersions.includes(rolledBackFrom)
|
||||
? state.blacklistedVersions
|
||||
: [...state.blacklistedVersions, rolledBackFrom]
|
||||
const fallbackVer = resolveFallbackVersion(
|
||||
{ ...state, blacklistedVersions: blacklist },
|
||||
shellVersion,
|
||||
userDataDir,
|
||||
)
|
||||
const nextState: HotfixState = {
|
||||
activeVersion: fallbackVer,
|
||||
previousVerifiedVersion: fallbackVer,
|
||||
status: 'verified',
|
||||
pendingAttempts: 0,
|
||||
blacklistedVersions: blacklist,
|
||||
}
|
||||
writeHotfixStateAtomic(userDataDir, nextState)
|
||||
fs.rmSync(activeDir, { recursive: true, force: true })
|
||||
return {
|
||||
overlayRoot: fallbackVer ? getHotfixBundleDir(userDataDir, fallbackVer) : null,
|
||||
activeBundleVersion: fallbackVer ?? shellVersion,
|
||||
pendingVerification: false,
|
||||
rolledBackFrom,
|
||||
}
|
||||
}
|
||||
|
||||
const nextState: HotfixState = {
|
||||
...state,
|
||||
pendingAttempts: state.pendingAttempts + 1,
|
||||
}
|
||||
writeHotfixStateAtomic(userDataDir, nextState)
|
||||
return {
|
||||
overlayRoot: activeDir,
|
||||
activeBundleVersion: state.activeVersion,
|
||||
pendingVerification: true,
|
||||
rolledBackFrom: null,
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
overlayRoot: activeDir,
|
||||
activeBundleVersion: state.activeVersion,
|
||||
pendingVerification: false,
|
||||
rolledBackFrom: null,
|
||||
}
|
||||
}
|
||||
|
||||
export function markHotfixVerified(userDataDir: string): HotfixState {
|
||||
const state = readHotfixState(userDataDir)
|
||||
if (!state.activeVersion) {
|
||||
return state
|
||||
}
|
||||
const nextState: HotfixState = {
|
||||
...state,
|
||||
previousVerifiedVersion: state.activeVersion,
|
||||
status: 'verified',
|
||||
pendingAttempts: 0,
|
||||
}
|
||||
writeHotfixStateAtomic(userDataDir, nextState)
|
||||
const keep = new Set<string>([state.activeVersion])
|
||||
if (nextState.previousVerifiedVersion) {
|
||||
keep.add(nextState.previousVerifiedVersion)
|
||||
}
|
||||
pruneObsoleteBundles(userDataDir, keep)
|
||||
return nextState
|
||||
}
|
||||
|
||||
export function rollbackPendingHotfix(userDataDir: string, shellVersion: string): {
|
||||
rolledBackFrom: string | null
|
||||
overlayRoot: string | null
|
||||
activeBundleVersion: string
|
||||
} {
|
||||
const state = readHotfixState(userDataDir)
|
||||
if (!state.activeVersion || state.status !== 'pending') {
|
||||
const activeDir = state.activeVersion ? getHotfixBundleDir(userDataDir, state.activeVersion) : null
|
||||
const valid = Boolean(
|
||||
activeDir &&
|
||||
state.activeVersion &&
|
||||
compareSemver(state.activeVersion, shellVersion) > 0 &&
|
||||
hasValidBundleIndex(activeDir),
|
||||
)
|
||||
return {
|
||||
rolledBackFrom: null,
|
||||
overlayRoot: valid ? activeDir : null,
|
||||
activeBundleVersion: valid && state.activeVersion ? state.activeVersion : shellVersion,
|
||||
}
|
||||
}
|
||||
|
||||
const rolledBackFrom = state.activeVersion
|
||||
const blacklist = state.blacklistedVersions.includes(rolledBackFrom)
|
||||
? state.blacklistedVersions
|
||||
: [...state.blacklistedVersions, rolledBackFrom]
|
||||
const fallbackVer = resolveFallbackVersion(
|
||||
{ ...state, blacklistedVersions: blacklist },
|
||||
shellVersion,
|
||||
userDataDir,
|
||||
)
|
||||
const nextState: HotfixState = {
|
||||
activeVersion: fallbackVer,
|
||||
previousVerifiedVersion: fallbackVer,
|
||||
status: 'verified',
|
||||
pendingAttempts: 0,
|
||||
blacklistedVersions: blacklist,
|
||||
}
|
||||
writeHotfixStateAtomic(userDataDir, nextState)
|
||||
fs.rmSync(getHotfixBundleDir(userDataDir, rolledBackFrom), { recursive: true, force: true })
|
||||
|
||||
return {
|
||||
rolledBackFrom,
|
||||
overlayRoot: fallbackVer ? getHotfixBundleDir(userDataDir, fallbackVer) : null,
|
||||
activeBundleVersion: fallbackVer ?? shellVersion,
|
||||
}
|
||||
}
|
||||
|
||||
export function evaluateUpdateDecision(input: {
|
||||
shellVersion: string
|
||||
activeBundleVersion: string
|
||||
blacklistedVersions: string[]
|
||||
manifest: ClientUpdateManifest | null | undefined
|
||||
}): UpdateDecision {
|
||||
const manifest = input.manifest
|
||||
if (!manifest || typeof manifest !== 'object') {
|
||||
return { kind: 'up-to-date' }
|
||||
}
|
||||
|
||||
const shell = manifest.shell
|
||||
const hasShellDownload = Boolean(shell?.downloadUrl && typeof shell.downloadUrl === 'string')
|
||||
const shellMandatory = Boolean(
|
||||
hasShellDownload && shell?.minRequired && compareSemver(shell.minRequired, input.shellVersion) > 0,
|
||||
)
|
||||
const shellNewer = Boolean(
|
||||
hasShellDownload && shell?.version && compareSemver(shell.version, input.shellVersion) > 0,
|
||||
)
|
||||
if (shell && shellMandatory) {
|
||||
return { kind: 'shell-update', shell, mandatory: true }
|
||||
}
|
||||
|
||||
const bundle = manifest.bundle
|
||||
if (
|
||||
bundle &&
|
||||
typeof bundle.version === 'string' &&
|
||||
STRICT_VERSION_PATTERN.test(bundle.version) &&
|
||||
typeof bundle.url === 'string' &&
|
||||
bundle.url.trim().length > 0 &&
|
||||
typeof bundle.sha256 === 'string' &&
|
||||
SHA256_PATTERN.test(bundle.sha256.trim()) &&
|
||||
compareSemver(bundle.version, input.activeBundleVersion) > 0 &&
|
||||
compareSemver(input.shellVersion, bundle.minShellVersion || '0.0.0') >= 0 &&
|
||||
!input.blacklistedVersions.includes(bundle.version)
|
||||
) {
|
||||
return { kind: 'hotfix-update', bundle }
|
||||
}
|
||||
|
||||
if (shell && shellNewer) {
|
||||
return { kind: 'shell-update', shell, mandatory: false }
|
||||
}
|
||||
|
||||
return { kind: 'up-to-date' }
|
||||
}
|
||||
|
||||
export const PERIODIC_UPDATE_CHECK_INTERVAL_MS = 12 * 60 * 60 * 1000
|
||||
|
||||
export function getUpdatePromptKey(decision: UpdateDecision): string | null {
|
||||
if (decision.kind === 'hotfix-update') {
|
||||
return `hotfix:${decision.bundle.version}`
|
||||
}
|
||||
if (decision.kind === 'shell-update') {
|
||||
return `shell:${decision.shell.version}`
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export function shouldSuppressUpdatePrompt(
|
||||
decision: UpdateDecision,
|
||||
options: { manual: boolean; dismissedKeys: ReadonlySet<string> },
|
||||
): boolean {
|
||||
if (options.manual || decision.kind === 'up-to-date') {
|
||||
return false
|
||||
}
|
||||
const key = getUpdatePromptKey(decision)
|
||||
return Boolean(key && options.dismissedKeys.has(key))
|
||||
}
|
||||
|
||||
export function resolveUpdateAssetUrl(rawUrl: string, backendUrl: string): string {
|
||||
const trimmed = String(rawUrl || '').trim()
|
||||
if (!trimmed) {
|
||||
throw new Error('Empty update asset URL')
|
||||
}
|
||||
if (trimmed.startsWith('/')) {
|
||||
const base = new URL(backendUrl)
|
||||
return new URL(trimmed, `${base.origin}`).toString()
|
||||
}
|
||||
const parsed = new URL(trimmed)
|
||||
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
||||
throw new Error(`Unsupported update asset URL protocol: ${parsed.protocol}`)
|
||||
}
|
||||
return parsed.toString()
|
||||
}
|
||||
|
||||
export function installHotfixArchive(input: {
|
||||
userDataDir: string
|
||||
version: string
|
||||
archiveBuffer: Buffer
|
||||
expectedSha256: string
|
||||
}): { overlayRoot: string; filesCount: number } {
|
||||
const version = String(input.version || '').trim()
|
||||
if (!STRICT_VERSION_PATTERN.test(version)) {
|
||||
throw new Error(`Invalid hotfix bundle version: ${version}`)
|
||||
}
|
||||
const expected = String(input.expectedSha256 || '').trim().toLowerCase()
|
||||
if (!SHA256_PATTERN.test(expected)) {
|
||||
throw new Error('Invalid expected SHA-256 checksum')
|
||||
}
|
||||
|
||||
const actual = crypto.createHash('sha256').update(input.archiveBuffer).digest('hex').toLowerCase()
|
||||
if (actual !== expected) {
|
||||
throw new Error(`Hotfix SHA-256 mismatch (expected ${expected}, got ${actual})`)
|
||||
}
|
||||
|
||||
const rootDir = getHotfixRootDir(input.userDataDir)
|
||||
const bundlesDir = getHotfixBundlesDir(input.userDataDir)
|
||||
const targetDir = getHotfixBundleDir(input.userDataDir, version)
|
||||
const stagingDir = path.join(rootDir, `staging-${version}-${Date.now()}`)
|
||||
|
||||
try {
|
||||
const extracted = extractTarGzSafely(input.archiveBuffer, stagingDir)
|
||||
if (!hasValidBundleIndex(stagingDir)) {
|
||||
throw new Error('Hotfix archive is missing required index.html entry')
|
||||
}
|
||||
|
||||
fs.mkdirSync(bundlesDir, { recursive: true })
|
||||
fs.rmSync(targetDir, { recursive: true, force: true })
|
||||
fs.renameSync(stagingDir, targetDir)
|
||||
|
||||
const previousState = readHotfixState(input.userDataDir)
|
||||
const preservedVerified =
|
||||
previousState.status === 'verified' && previousState.activeVersion && previousState.activeVersion !== version
|
||||
? previousState.activeVersion
|
||||
: previousState.previousVerifiedVersion && previousState.previousVerifiedVersion !== version
|
||||
? previousState.previousVerifiedVersion
|
||||
: null
|
||||
|
||||
const nextState: HotfixState = {
|
||||
activeVersion: version,
|
||||
previousVerifiedVersion: preservedVerified,
|
||||
status: 'pending',
|
||||
pendingAttempts: 0,
|
||||
blacklistedVersions: previousState.blacklistedVersions.filter((item) => item !== version),
|
||||
installedAt: new Date().toISOString(),
|
||||
}
|
||||
writeHotfixStateAtomic(input.userDataDir, nextState)
|
||||
|
||||
return {
|
||||
overlayRoot: targetDir,
|
||||
filesCount: extracted.files.length,
|
||||
}
|
||||
} catch (error) {
|
||||
fs.rmSync(stagingDir, { recursive: true, force: true })
|
||||
throw error
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
import { dialog, net, shell, type BrowserWindow, type MessageBoxOptions } from 'electron'
|
||||
|
||||
import {
|
||||
evaluateUpdateDecision,
|
||||
getUpdatePromptKey,
|
||||
installHotfixArchive,
|
||||
markHotfixVerified,
|
||||
readHotfixState,
|
||||
resolveActiveEarthOverlay,
|
||||
resolveUpdateAssetUrl,
|
||||
rollbackPendingHotfix,
|
||||
shouldSuppressUpdatePrompt,
|
||||
type ClientUpdateManifest,
|
||||
} from './hot-update-core'
|
||||
|
||||
export interface HotUpdateVersionInfo {
|
||||
shellVersion: string
|
||||
activeBundleVersion: string
|
||||
usingHotfix: boolean
|
||||
pendingVerification: boolean
|
||||
}
|
||||
|
||||
export interface HotUpdateController {
|
||||
getOverlayRoot(): string | null
|
||||
getVersionInfo(): HotUpdateVersionInfo
|
||||
markStartupReady(): void
|
||||
handleRendererCrash(): void
|
||||
startStartupWatchdog(): void
|
||||
stopStartupWatchdog(): void
|
||||
checkForUpdates(options?: { manual?: boolean }): Promise<void>
|
||||
}
|
||||
|
||||
const MANIFEST_TIMEOUT_MS = 10_000
|
||||
const DOWNLOAD_TIMEOUT_MS = 60_000
|
||||
const STARTUP_VERIFY_TIMEOUT_MS = 15_000
|
||||
|
||||
async function fetchWithTimeout(
|
||||
fetchImpl: typeof fetch,
|
||||
url: string,
|
||||
timeoutMs: number,
|
||||
init: RequestInit = {},
|
||||
): Promise<Response> {
|
||||
const controller = new AbortController()
|
||||
const timer = setTimeout(() => controller.abort(), timeoutMs)
|
||||
try {
|
||||
return await fetchImpl(url, { ...init, signal: controller.signal })
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
}
|
||||
}
|
||||
|
||||
export function createHotUpdateController(options: {
|
||||
userDataDir: string
|
||||
shellVersion: string
|
||||
getBackendUrl: () => string
|
||||
getMainWindow: () => BrowserWindow | null
|
||||
onOverlayChanged: (nextOverlayRoot: string | null, nextBundleVersion: string) => void
|
||||
fetchImpl?: typeof fetch
|
||||
}): HotUpdateController {
|
||||
const fetchImpl = options.fetchImpl ?? ((input, init) => net.fetch(input as string, init))
|
||||
|
||||
const initial = resolveActiveEarthOverlay({
|
||||
userDataDir: options.userDataDir,
|
||||
shellVersion: options.shellVersion,
|
||||
})
|
||||
if (initial.rolledBackFrom) {
|
||||
console.warn(
|
||||
`[planet-client] Rolled back unverified hotfix v${initial.rolledBackFrom} -> v${initial.activeBundleVersion}`,
|
||||
)
|
||||
}
|
||||
|
||||
let overlayRoot = initial.overlayRoot
|
||||
let activeBundleVersion = initial.activeBundleVersion
|
||||
let pendingVerification = initial.pendingVerification
|
||||
let watchdogTimer: ReturnType<typeof setTimeout> | null = null
|
||||
let inFlightCheck: Promise<void> | null = null
|
||||
const dismissedPromptKeys = new Set<string>()
|
||||
|
||||
const notifyStatus = (message: string, type: 'info' | 'success' | 'error' = 'info') => {
|
||||
const win = options.getMainWindow()
|
||||
if (win && !win.isDestroyed() && !win.webContents.isDestroyed()) {
|
||||
win.webContents.send('planet:update-status', { message, type })
|
||||
}
|
||||
}
|
||||
|
||||
const showBox = (boxOptions: MessageBoxOptions) => {
|
||||
const win = options.getMainWindow()
|
||||
if (win && !win.isDestroyed()) {
|
||||
return dialog.showMessageBox(win, boxOptions)
|
||||
}
|
||||
return dialog.showMessageBox(boxOptions)
|
||||
}
|
||||
|
||||
const stopStartupWatchdog = () => {
|
||||
if (watchdogTimer) {
|
||||
clearTimeout(watchdogTimer)
|
||||
watchdogTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
const performRollbackAndReload = (reason: string) => {
|
||||
stopStartupWatchdog()
|
||||
const result = rollbackPendingHotfix(options.userDataDir, options.shellVersion)
|
||||
if (!result.rolledBackFrom) return
|
||||
console.warn(`[planet-client] ${reason}; rolled back v${result.rolledBackFrom} -> v${result.activeBundleVersion}`)
|
||||
overlayRoot = result.overlayRoot
|
||||
activeBundleVersion = result.activeBundleVersion
|
||||
pendingVerification = false
|
||||
options.onOverlayChanged(overlayRoot, activeBundleVersion)
|
||||
const win = options.getMainWindow()
|
||||
if (win && !win.isDestroyed() && !win.webContents.isDestroyed()) {
|
||||
win.webContents.reloadIgnoringCache()
|
||||
}
|
||||
}
|
||||
|
||||
const startStartupWatchdog = () => {
|
||||
stopStartupWatchdog()
|
||||
if (!pendingVerification) return
|
||||
watchdogTimer = setTimeout(() => {
|
||||
watchdogTimer = null
|
||||
if (!pendingVerification) return
|
||||
performRollbackAndReload('Hotfix startup verification timed out')
|
||||
}, STARTUP_VERIFY_TIMEOUT_MS)
|
||||
}
|
||||
|
||||
const markStartupReady = () => {
|
||||
stopStartupWatchdog()
|
||||
if (!pendingVerification) return
|
||||
pendingVerification = false
|
||||
markHotfixVerified(options.userDataDir)
|
||||
options.onOverlayChanged(overlayRoot, activeBundleVersion)
|
||||
notifyStatus(`热更新已生效 / Hotfix v${activeBundleVersion} active`, 'success')
|
||||
}
|
||||
|
||||
const handleRendererCrash = () => {
|
||||
if (!pendingVerification) return
|
||||
performRendererCrashRecovery()
|
||||
}
|
||||
|
||||
const performRendererCrashRecovery = () => {
|
||||
performRendererSafeRollback()
|
||||
}
|
||||
|
||||
const performRendererSafeRollback = () => {
|
||||
performRollbackAndReload('Renderer exited unexpectedly under pending hotfix')
|
||||
}
|
||||
|
||||
const applyHotfixBundle = async (bundleUrl: string, version: string, expectedSha256: string) => {
|
||||
notifyStatus(`正在下载热更新 v${version}… / Downloading hotfix v${version}…`, 'info')
|
||||
const response = await fetchWithTimeout(fetchImpl, bundleUrl, DOWNLOAD_TIMEOUT_MS, {
|
||||
cache: 'no-store',
|
||||
})
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}`)
|
||||
}
|
||||
const arrayBuf = await response.arrayBuffer()
|
||||
const archiveBuffer = Buffer.from(arrayBuf)
|
||||
|
||||
const installed = installHotfixArchive({
|
||||
userDataDir: options.userDataDir,
|
||||
version,
|
||||
archiveBuffer,
|
||||
expectedSha256,
|
||||
})
|
||||
|
||||
overlayRoot = installed.overlayRoot
|
||||
activeBundleVersion = version
|
||||
pendingVerification = true
|
||||
options.onOverlayChanged(overlayRoot, activeBundleVersion)
|
||||
startStartupWatchdog()
|
||||
|
||||
const win = options.getMainWindow()
|
||||
if (win && !win.isDestroyed() && !win.webContents.isDestroyed()) {
|
||||
win.webContents.reloadIgnoringCache()
|
||||
}
|
||||
}
|
||||
|
||||
const runCheck = async (manual: boolean): Promise<void> => {
|
||||
const backendUrl = options.getBackendUrl().replace(/\/+$/, '')
|
||||
const manifestUrl = new URL(`${backendUrl}/api/v1/client/update-manifest`)
|
||||
manifestUrl.searchParams.set('platform', process.platform)
|
||||
manifestUrl.searchParams.set('arch', process.arch)
|
||||
manifestUrl.searchParams.set('shell', options.shellVersion)
|
||||
manifestUrl.searchParams.set('bundle', activeBundleVersion)
|
||||
|
||||
let manifest: ClientUpdateManifest
|
||||
try {
|
||||
const response = await fetchWithTimeout(fetchImpl, manifestUrl.toString(), MANIFEST_TIMEOUT_MS, {
|
||||
cache: 'no-store',
|
||||
headers: { Accept: 'application/json' },
|
||||
})
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}`)
|
||||
}
|
||||
manifest = (await response.json()) as ClientUpdateManifest
|
||||
} catch (error) {
|
||||
const detail = error instanceof Error ? error.message : String(error)
|
||||
if (manual) {
|
||||
await showBox({
|
||||
type: 'warning',
|
||||
title: '检查更新失败 / Update Check Failed',
|
||||
message: '无法获取版本清单,请确认服务端连接正常。',
|
||||
detail,
|
||||
buttons: ['确定 / OK'],
|
||||
})
|
||||
} else {
|
||||
console.warn('[planet-client] Startup update check skipped:', detail)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
const state = readHotfixState(options.userDataDir)
|
||||
const decision = evaluateUpdateDecision({
|
||||
shellVersion: options.shellVersion,
|
||||
activeBundleVersion,
|
||||
blacklistedVersions: state.blacklistedVersions,
|
||||
manifest,
|
||||
})
|
||||
|
||||
if (decision.kind === 'up-to-date') {
|
||||
if (manual) {
|
||||
await showBox({
|
||||
type: 'info',
|
||||
title: '当前已是最新版本 / Up to Date',
|
||||
message: 'Planet Earth 客户端已是最新版本。',
|
||||
detail: `外壳版本 / Shell: v${options.shellVersion}\n地球业务包 / Earth Bundle: v${activeBundleVersion}`,
|
||||
buttons: ['确定 / OK'],
|
||||
})
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (shouldSuppressUpdatePrompt(decision, { manual, dismissedKeys: dismissedPromptKeys })) {
|
||||
return
|
||||
}
|
||||
|
||||
const promptKey = getUpdatePromptKey(decision)
|
||||
|
||||
if (decision.kind === 'hotfix-update') {
|
||||
const { bundle } = decision
|
||||
const notes = bundle.releaseNotes?.trim() ? `\n\n更新内容:\n${bundle.releaseNotes.trim()}` : ''
|
||||
const { response } = await showBox({
|
||||
type: 'info',
|
||||
title: '发现新版本 / Update Available',
|
||||
message: `发现 Planet Earth 增量热更新 v${bundle.version}`,
|
||||
detail: `当前地球版本 v${activeBundleVersion} → 最新版本 v${bundle.version}\n更新方式:轻量热更新(无需重新安装,应用后自动生效)${notes}`,
|
||||
buttons: ['立即更新 / Update Now', '稍后提醒 / Later'],
|
||||
defaultId: 0,
|
||||
cancelId: 1,
|
||||
})
|
||||
if (response !== 0) {
|
||||
if (promptKey) dismissedPromptKeys.add(promptKey)
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const assetUrl = resolveUpdateAssetUrl(bundle.url, backendUrl)
|
||||
await applyHotfixBundle(assetUrl, bundle.version, bundle.sha256)
|
||||
} catch (error) {
|
||||
const detail = error instanceof Error ? error.message : String(error)
|
||||
console.error('[planet-client] Hotfix installation failed:', detail)
|
||||
await showBox({
|
||||
type: 'error',
|
||||
title: '热更新失败 / Hotfix Failed',
|
||||
message: `热更新包 v${bundle.version} 下载或校验失败,已保留当前版本运行。`,
|
||||
detail,
|
||||
buttons: ['确定 / OK'],
|
||||
})
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
const { shell: shellInfo, mandatory } = decision
|
||||
const notes = shellInfo.releaseNotes?.trim() ? `\n\n更新说明:\n${shellInfo.releaseNotes.trim()}` : ''
|
||||
const { response } = await showBox({
|
||||
type: mandatory ? 'warning' : 'info',
|
||||
title: '发现客户端大版本更新 / Major Client Update',
|
||||
message: mandatory
|
||||
? `当前客户端版本 v${options.shellVersion} 过低,需升级至 v${shellInfo.version}`
|
||||
: `发现客户端新版本 v${shellInfo.version}`,
|
||||
detail: `当前客户端外壳:v${options.shellVersion}\n最新版本:v${shellInfo.version}\n该版本包含底层架构或原生壳变更,需下载安装包覆盖更新。${notes}`,
|
||||
buttons: ['前往下载 / Download', '稍后提醒 / Later'],
|
||||
defaultId: 0,
|
||||
cancelId: 1,
|
||||
})
|
||||
if (response === 0) {
|
||||
await shell.openExternal(shellInfo.downloadUrl)
|
||||
} else if (promptKey) {
|
||||
dismissedPromptKeys.add(promptKey)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
getOverlayRoot: () => overlayRoot,
|
||||
getVersionInfo: () => ({
|
||||
shellVersion: options.shellVersion,
|
||||
activeBundleVersion,
|
||||
usingHotfix: Boolean(overlayRoot),
|
||||
pendingVerification,
|
||||
}),
|
||||
markStartupReady,
|
||||
handleRendererCrash,
|
||||
startStartupWatchdog,
|
||||
stopStartupWatchdog,
|
||||
checkForUpdates(checkOpts = {}) {
|
||||
if (inFlightCheck) return inFlightCheck
|
||||
inFlightCheck = runCheck(Boolean(checkOpts.manual)).finally(() => {
|
||||
inFlightCheck = null
|
||||
})
|
||||
return inFlightCheck
|
||||
},
|
||||
}
|
||||
}
|
||||
+252
-40
@@ -1,29 +1,73 @@
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
|
||||
import { app, BrowserWindow, ipcMain, Menu, session, shell } from 'electron'
|
||||
import { app, BrowserWindow, dialog, ipcMain, Menu, session, shell } from 'electron'
|
||||
|
||||
import { DesktopConfigStore, normalizeSplashTheme, type ServerEndpoints } from './config'
|
||||
import { DesktopConfigStore, normalizeSplashTheme, readPreReadyGpuHandoff, readPreReadyGpuMode, type GpuRenderMode, type ServerEndpoints } from './config'
|
||||
import { DESKTOP_SCHEME, registerDesktopLink } from './desktop-link'
|
||||
import { createAdaptiveGpuMonitor, probeWindowsGpuEnvironmentSync } from './gpu-monitor'
|
||||
import { buildGpuHandoffArgs, chooseStartupGpuTarget, isGpuProcessCrash, resolveChromiumGpuSwitches, stripGpuOverrideArgs, type ResolvedGpuTarget } from './gpu-policy'
|
||||
import { PERIODIC_UPDATE_CHECK_INTERVAL_MS } from './hot-update-core'
|
||||
import { createHotUpdateController } from './hot-updater'
|
||||
import { buildApplicationMenu } from './menu'
|
||||
import { EARTH_ORIGIN, installEarthSessionHandlers, registerEarthScheme } from './protocol'
|
||||
import { createMainWindow, dismissMenuBarOnPointerDown, toggleWindowOrientation } from './window'
|
||||
import { createMainWindow, dismissMenuBarOnPointerDown, flushWindowState, toggleWindowOrientation } from './window'
|
||||
|
||||
registerEarthScheme()
|
||||
|
||||
const isHeadlessSmoke = process.argv.includes('--headless-smoke')
|
||||
if (isHeadlessSmoke) {
|
||||
app.commandLine.appendSwitch('disable-gpu')
|
||||
app.commandLine.appendSwitch('use-gl', 'angle')
|
||||
app.commandLine.appendSwitch('use-angle', 'swiftshader')
|
||||
app.commandLine.appendSwitch('enable-unsafe-swiftshader')
|
||||
} else {
|
||||
// Prioritize discrete/high-performance GPU and avoid throttling visible secondary-screen renders.
|
||||
app.commandLine.appendSwitch('force_high_performance_gpu')
|
||||
app.commandLine.appendSwitch('enable-gpu-rasterization')
|
||||
app.commandLine.appendSwitch('enable-zero-copy')
|
||||
app.commandLine.appendSwitch('disable-renderer-backgrounding')
|
||||
if (process.platform === 'linux') {
|
||||
app.commandLine.appendSwitch('ozone-platform-hint', 'auto')
|
||||
let preReadyUserDataDir = ''
|
||||
let preReadyExeDir = process.cwd()
|
||||
try {
|
||||
preReadyUserDataDir = app.getPath('userData')
|
||||
} catch {
|
||||
preReadyUserDataDir = ''
|
||||
}
|
||||
try {
|
||||
preReadyExeDir = path.dirname(app.getPath('exe'))
|
||||
} catch {
|
||||
preReadyExeDir = process.cwd()
|
||||
}
|
||||
|
||||
const requestedGpuMode = readPreReadyGpuMode({
|
||||
userDataDir: preReadyUserDataDir,
|
||||
exeDir: preReadyExeDir,
|
||||
resourcesDir: process.resourcesPath,
|
||||
argv: process.argv,
|
||||
})
|
||||
const preReadyHandoff = readPreReadyGpuHandoff(process.argv)
|
||||
const preReadyGpuEnv =
|
||||
!isHeadlessSmoke &&
|
||||
!preReadyHandoff.gpuHandoffTarget &&
|
||||
requestedGpuMode === 'auto' &&
|
||||
process.platform === 'win32'
|
||||
? probeWindowsGpuEnvironmentSync()
|
||||
: { vramSample: null, hasIntegratedGpu: false }
|
||||
|
||||
const startupGpuDecision = chooseStartupGpuTarget({
|
||||
platform: process.platform,
|
||||
headlessSmoke: isHeadlessSmoke,
|
||||
requestedMode: requestedGpuMode,
|
||||
handoffTarget: preReadyHandoff.gpuHandoffTarget,
|
||||
vramSample: preReadyGpuEnv.vramSample,
|
||||
hasIntegratedGpu: preReadyGpuEnv.hasIntegratedGpu,
|
||||
})
|
||||
|
||||
if (startupGpuDecision.reason === 'low-vram-igpu' || startupGpuDecision.reason === 'low-vram-software') {
|
||||
console.info(
|
||||
`[planet-client] Adaptive GPU selected ${startupGpuDecision.target} (reason=${startupGpuDecision.reason}, freeMiB=${startupGpuDecision.vramSample?.freeMiB ?? 'unknown'})`,
|
||||
)
|
||||
}
|
||||
|
||||
for (const sw of resolveChromiumGpuSwitches({
|
||||
platform: process.platform,
|
||||
headlessSmoke: isHeadlessSmoke,
|
||||
target: startupGpuDecision.target,
|
||||
})) {
|
||||
if (sw.value !== undefined) {
|
||||
app.commandLine.appendSwitch(sw.name, sw.value)
|
||||
} else {
|
||||
app.commandLine.appendSwitch(sw.name)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,24 +107,28 @@ function resolvePreloadPath(): string {
|
||||
}
|
||||
|
||||
let mainWindow: BrowserWindow | null = null
|
||||
let launchWindow: (() => void) | undefined
|
||||
|
||||
function showEarthWindow() {
|
||||
if (!mainWindow || mainWindow.isDestroyed()) {
|
||||
launchWindow?.()
|
||||
return
|
||||
}
|
||||
if (mainWindow.isMinimized()) mainWindow.restore()
|
||||
mainWindow.show()
|
||||
mainWindow.focus()
|
||||
}
|
||||
|
||||
const singleInstanceLock = isHeadlessSmoke ? true : app.requestSingleInstanceLock()
|
||||
if (!singleInstanceLock) {
|
||||
app.quit()
|
||||
} else {
|
||||
if (!isHeadlessSmoke && typeof app.setAsDefaultProtocolClient === 'function') {
|
||||
try {
|
||||
app.setAsDefaultProtocolClient('planet-earth')
|
||||
} catch {
|
||||
// Non-fatal in unpackaged dev sessions.
|
||||
}
|
||||
}
|
||||
|
||||
app.on('second-instance', () => {
|
||||
if (!mainWindow || mainWindow.isDestroyed()) return
|
||||
if (mainWindow.isMinimized()) mainWindow.restore()
|
||||
mainWindow.focus()
|
||||
app.on('open-url', (event, url) => {
|
||||
if (url !== `${DESKTOP_SCHEME}://open` && url !== `${DESKTOP_SCHEME}://open/`) return
|
||||
event.preventDefault()
|
||||
showEarthWindow()
|
||||
})
|
||||
app.on('second-instance', showEarthWindow)
|
||||
|
||||
app.on('window-all-closed', () => {
|
||||
if (process.platform !== 'darwin') {
|
||||
@@ -88,7 +136,24 @@ if (!singleInstanceLock) {
|
||||
}
|
||||
})
|
||||
|
||||
app.on('child-process-gone', (_event, details) => {
|
||||
if (!isGpuProcessCrash(details)) return
|
||||
console.warn('[planet-client] GPU process exited unexpectedly', {
|
||||
reason: details.reason,
|
||||
exitCode: details.exitCode,
|
||||
})
|
||||
if (mainWindow && !mainWindow.isDestroyed() && !mainWindow.webContents.isDestroyed()) {
|
||||
mainWindow.webContents.send('planet:gpu-process-gone', {
|
||||
reason: details.reason,
|
||||
exitCode: details.exitCode,
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
void app.whenReady().then(async () => {
|
||||
if (!isHeadlessSmoke) {
|
||||
void registerDesktopLink().catch(error => console.warn('Planet Earth protocol registration failed', error))
|
||||
}
|
||||
const configStore = new DesktopConfigStore({
|
||||
userDataDir: app.getPath('userData'),
|
||||
exeDir: path.dirname(app.getPath('exe')),
|
||||
@@ -97,11 +162,120 @@ if (!singleInstanceLock) {
|
||||
})
|
||||
|
||||
const earthBundleRoot = resolveEarthBundleRoot()
|
||||
const relaunchDesktopApp = (relaunchOptions?: {
|
||||
gpuHandoff?: boolean
|
||||
gpuHandoffTarget?: ResolvedGpuTarget
|
||||
}) => {
|
||||
flushWindowState(mainWindow)
|
||||
if (singleInstanceLock) {
|
||||
app.releaseSingleInstanceLock()
|
||||
}
|
||||
const rawArgs = process.argv.slice(1)
|
||||
const args = relaunchOptions?.gpuHandoff
|
||||
? buildGpuHandoffArgs(rawArgs, relaunchOptions.gpuHandoffTarget)
|
||||
: stripGpuOverrideArgs(rawArgs)
|
||||
app.relaunch({ args })
|
||||
app.exit(0)
|
||||
}
|
||||
|
||||
const hotUpdater = createHotUpdateController({
|
||||
userDataDir: app.getPath('userData'),
|
||||
shellVersion: app.getVersion(),
|
||||
getBackendUrl: () => configStore.get().backendUrl,
|
||||
getMainWindow: () => mainWindow,
|
||||
onOverlayChanged: () => {
|
||||
refreshApplicationMenu()
|
||||
},
|
||||
})
|
||||
|
||||
const gpuMonitor = createAdaptiveGpuMonitor({
|
||||
userDataDir: app.getPath('userData'),
|
||||
startupDecision: startupGpuDecision,
|
||||
getConfiguredMode: () => configStore.get().gpuMode,
|
||||
getMainWindow: () => mainWindow,
|
||||
onAutoSwitch: (nextTarget) => {
|
||||
relaunchDesktopApp({ gpuHandoff: true, gpuHandoffTarget: nextTarget })
|
||||
},
|
||||
onStatusUpdated: () => {
|
||||
refreshApplicationMenu()
|
||||
},
|
||||
})
|
||||
|
||||
const sendPendingHandoffToast = () => {
|
||||
if (isHeadlessSmoke || !mainWindow || mainWindow.isDestroyed() || mainWindow.webContents.isDestroyed()) {
|
||||
return
|
||||
}
|
||||
const toast = gpuMonitor.consumePendingHandoffToast()
|
||||
if (toast) {
|
||||
mainWindow.webContents.send('planet:update-status', toast)
|
||||
}
|
||||
}
|
||||
|
||||
const refreshApplicationMenu = () => {
|
||||
if (!mainWindow || mainWindow.isDestroyed()) return
|
||||
Menu.setApplicationMenu(
|
||||
buildApplicationMenu({
|
||||
mainWindow,
|
||||
configStore,
|
||||
getVersionInfo: () => hotUpdater.getVersionInfo(),
|
||||
onCheckForUpdates: () => {
|
||||
void hotUpdater.checkForUpdates({ manual: true })
|
||||
},
|
||||
getGpuStatus: () => gpuMonitor.getRuntimeSummary(),
|
||||
onSelectGpuMode: async (nextMode: GpuRenderMode) => {
|
||||
configStore.updateGpuMode(nextMode)
|
||||
refreshApplicationMenu()
|
||||
const targetWin = mainWindow && !mainWindow.isDestroyed() ? mainWindow : undefined
|
||||
const boxOptions = {
|
||||
type: 'info' as const,
|
||||
title: '渲染设备设置 / GPU Mode',
|
||||
message: '渲染设备模式已更新,需重启客户端生效',
|
||||
detail: '是否立即重启 Planet Earth?(重启约需 1-2 秒,将保留全部视觉特效)',
|
||||
buttons: ['立即重启 / Restart Now', '稍后手动重启 / Later'],
|
||||
defaultId: 0,
|
||||
cancelId: 1,
|
||||
}
|
||||
const { response } = targetWin
|
||||
? await dialog.showMessageBox(targetWin, boxOptions)
|
||||
: await dialog.showMessageBox(boxOptions)
|
||||
if (response === 0) {
|
||||
relaunchDesktopApp({ gpuHandoff: true })
|
||||
}
|
||||
},
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
installEarthSessionHandlers(session.defaultSession, {
|
||||
earthBundleRoot,
|
||||
getEarthOverlayRoot: () => hotUpdater.getOverlayRoot(),
|
||||
getBackendUrl: () => configStore.get().backendUrl,
|
||||
})
|
||||
|
||||
ipcMain.on('planet:earth-startup-ready', () => {
|
||||
if (!isHeadlessSmoke) {
|
||||
hotUpdater.markStartupReady()
|
||||
sendPendingHandoffToast()
|
||||
}
|
||||
})
|
||||
|
||||
ipcMain.on('planet:low-fps-report', (_event, payload: unknown) => {
|
||||
if (isHeadlessSmoke || !payload || typeof payload !== 'object') return
|
||||
const candidate = payload as { avgFps?: unknown; sustainedMs?: unknown }
|
||||
const avgFps = Number(candidate.avgFps)
|
||||
const sustainedMs = Number(candidate.sustainedMs)
|
||||
if (!Number.isFinite(avgFps) || avgFps <= 0 || !Number.isFinite(sustainedMs) || sustainedMs <= 0) {
|
||||
return
|
||||
}
|
||||
void gpuMonitor.handleLowFpsReport({ avgFps, sustainedMs })
|
||||
})
|
||||
|
||||
ipcMain.handle('planet:check-for-updates', async () => {
|
||||
await hotUpdater.checkForUpdates({ manual: true })
|
||||
})
|
||||
|
||||
ipcMain.handle('planet:get-version-info', () => hotUpdater.getVersionInfo())
|
||||
|
||||
ipcMain.on('planet:get-runtime-config', (event) => {
|
||||
const cfg = configStore.get()
|
||||
event.returnValue = {
|
||||
@@ -111,10 +285,14 @@ if (!singleInstanceLock) {
|
||||
wsUrl: cfg.wsUrl,
|
||||
forceShowFps: cfg.forceShowFps,
|
||||
splashTheme: cfg.splashTheme,
|
||||
gpuMode: cfg.gpuMode,
|
||||
gpuTarget: startupGpuDecision.target,
|
||||
gpuHandoff: cfg.gpuHandoff,
|
||||
headlessSmoke: cfg.headlessSmoke,
|
||||
isElectron: true,
|
||||
platform: process.platform,
|
||||
localMediaPipeBaseUrl: `${EARTH_ORIGIN}/earth/vendor/mediapipe`,
|
||||
localPoseModelUrl: `${EARTH_ORIGIN}/earth/vendor/mediapipe/pose_landmarker_lite.task`,
|
||||
}
|
||||
})
|
||||
|
||||
@@ -170,9 +348,7 @@ if (!singleInstanceLock) {
|
||||
|
||||
ipcMain.handle('planet:set-splash-theme', (_event, rawTheme: unknown) => {
|
||||
const next = configStore.updateSplashTheme(normalizeSplashTheme(rawTheme, configStore.get().splashTheme))
|
||||
if (mainWindow && !mainWindow.isDestroyed()) {
|
||||
Menu.setApplicationMenu(buildApplicationMenu({ mainWindow, configStore }))
|
||||
}
|
||||
refreshApplicationMenu()
|
||||
return next.splashTheme
|
||||
})
|
||||
|
||||
@@ -180,7 +356,7 @@ if (!singleInstanceLock) {
|
||||
dismissMenuBarOnPointerDown(mainWindow)
|
||||
})
|
||||
|
||||
const launchWindow = () => {
|
||||
launchWindow = () => {
|
||||
const preloadPath = resolvePreloadPath()
|
||||
mainWindow = createMainWindow({
|
||||
preloadPath,
|
||||
@@ -189,11 +365,48 @@ if (!singleInstanceLock) {
|
||||
configStore,
|
||||
})
|
||||
|
||||
Menu.setApplicationMenu(buildApplicationMenu({ mainWindow, configStore }))
|
||||
refreshApplicationMenu()
|
||||
if (process.platform !== 'darwin') {
|
||||
mainWindow.setMenuBarVisibility(false)
|
||||
}
|
||||
|
||||
if (!isHeadlessSmoke) {
|
||||
let autoUpdateTimer: ReturnType<typeof setTimeout> | null = null
|
||||
let periodicUpdateTimer: ReturnType<typeof setInterval> | null = null
|
||||
mainWindow.webContents.on('render-process-gone', () => {
|
||||
hotUpdater.handleRendererCrash()
|
||||
})
|
||||
hotUpdater.startStartupWatchdog()
|
||||
mainWindow.webContents.once('did-finish-load', () => {
|
||||
gpuMonitor.start()
|
||||
autoUpdateTimer = setTimeout(() => {
|
||||
autoUpdateTimer = null
|
||||
if (mainWindow && !mainWindow.isDestroyed()) {
|
||||
void hotUpdater.checkForUpdates({ manual: false })
|
||||
}
|
||||
}, 4000)
|
||||
if (!periodicUpdateTimer) {
|
||||
periodicUpdateTimer = setInterval(() => {
|
||||
if (mainWindow && !mainWindow.isDestroyed() && !mainWindow.isMinimized()) {
|
||||
void hotUpdater.checkForUpdates({ manual: false })
|
||||
}
|
||||
}, PERIODIC_UPDATE_CHECK_INTERVAL_MS)
|
||||
}
|
||||
})
|
||||
mainWindow.once('closed', () => {
|
||||
gpuMonitor.stop()
|
||||
if (autoUpdateTimer) {
|
||||
clearTimeout(autoUpdateTimer)
|
||||
autoUpdateTimer = null
|
||||
}
|
||||
if (periodicUpdateTimer) {
|
||||
clearInterval(periodicUpdateTimer)
|
||||
periodicUpdateTimer = null
|
||||
}
|
||||
hotUpdater.stopStartupWatchdog()
|
||||
})
|
||||
}
|
||||
|
||||
if (isHeadlessSmoke) {
|
||||
const smokeTimeout = setTimeout(() => {
|
||||
app.exit(1)
|
||||
@@ -259,19 +472,18 @@ if (!singleInstanceLock) {
|
||||
const img = sr?.querySelector('.splash-zju-emblem');
|
||||
const copy = sr?.querySelector('.splash-presenter-copy')?.textContent || '';
|
||||
const finishCheck = () => {
|
||||
window.planetDesktop.replaySplash('constellation');
|
||||
const firstSwitch = host?.dataset.splashTheme || '';
|
||||
window.planetDesktop.replaySplash('horizon');
|
||||
const secondSwitch = host?.dataset.splashTheme || '';
|
||||
const activeTheme = host?.dataset.splashTheme || '';
|
||||
const hasNoThemeSwitcher = !sr?.querySelector('.splash-switcher');
|
||||
window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
|
||||
resolve({
|
||||
mounted: Boolean(host && sr),
|
||||
hasPresentedBy: copy.includes('PRESENTED BY'),
|
||||
hasPresenterZh: copy.includes('临空智能媒体研究院'),
|
||||
hasPresenterEn: copy.includes('Institute of Intelligent Media'),
|
||||
hasPresenterEn: copy.includes('Intelligent Media Institute'),
|
||||
emblemLoaded: Boolean(img && img.complete && img.naturalWidth > 0),
|
||||
emblemWidth: img ? img.naturalWidth : 0,
|
||||
switchedThemes: [firstSwitch, secondSwitch],
|
||||
activeTheme,
|
||||
hasNoThemeSwitcher,
|
||||
});
|
||||
};
|
||||
if (!img || img.complete) {
|
||||
@@ -321,7 +533,7 @@ if (!singleInstanceLock) {
|
||||
|
||||
app.on('activate', () => {
|
||||
if (BrowserWindow.getAllWindows().length === 0) {
|
||||
launchWindow()
|
||||
launchWindow?.()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
+93
-24
@@ -1,11 +1,33 @@
|
||||
import { app, Menu, shell, type BrowserWindow, type MenuItemConstructorOptions } from 'electron'
|
||||
|
||||
import type { DesktopConfigStore, SplashTheme } from './config'
|
||||
import type { DesktopConfigStore, GpuRenderMode, SplashTheme } from './config'
|
||||
import type { GpuRuntimeSummary } from './gpu-monitor'
|
||||
import type { HotUpdateVersionInfo } from './hot-updater'
|
||||
import { openServerSettingsDialog, toggleWindowOrientation } from './window'
|
||||
|
||||
function formatGpuSummaryLabel(summary: GpuRuntimeSummary): string {
|
||||
const targetLabel =
|
||||
summary.activeTarget === 'low-power'
|
||||
? '集成核显'
|
||||
: summary.activeTarget === 'software'
|
||||
? 'CPU 软渲染'
|
||||
: summary.activeTarget === 'high-performance' || summary.latestVramSample
|
||||
? '独立显卡'
|
||||
: '硬件 GPU'
|
||||
const modeTag = summary.requestedMode === 'auto' ? '自动' : '手动'
|
||||
const vramTag = summary.latestVramSample
|
||||
? ` · 独显空闲 ${(summary.latestVramSample.freeMiB / 1024).toFixed(1)} GB`
|
||||
: ''
|
||||
return `当前生效: ${targetLabel} (${modeTag}${vramTag})`
|
||||
}
|
||||
|
||||
export function buildApplicationMenu(options: {
|
||||
mainWindow: BrowserWindow
|
||||
configStore: DesktopConfigStore
|
||||
getVersionInfo?: () => HotUpdateVersionInfo
|
||||
onCheckForUpdates?: () => void
|
||||
getGpuStatus?: () => GpuRuntimeSummary
|
||||
onSelectGpuMode?: (mode: GpuRenderMode) => void | Promise<void>
|
||||
}): Menu {
|
||||
const sendAction = (action: string) => {
|
||||
if (!options.mainWindow.isDestroyed()) {
|
||||
@@ -19,6 +41,8 @@ export function buildApplicationMenu(options: {
|
||||
}
|
||||
|
||||
const currentSplashTheme = options.configStore.get().splashTheme
|
||||
const currentGpuMode = options.configStore.get().gpuMode
|
||||
const gpuSummary = options.getGpuStatus?.()
|
||||
|
||||
const selectSplashTheme = (theme: SplashTheme) => {
|
||||
options.configStore.updateSplashTheme(theme)
|
||||
@@ -72,31 +96,13 @@ export function buildApplicationMenu(options: {
|
||||
},
|
||||
},
|
||||
{
|
||||
label: '启动画面方案 / Splash Screen',
|
||||
label: '启动画面 / Splash Screen',
|
||||
submenu: [
|
||||
{
|
||||
label: '方案 1:星核奇点展开 / Singularity Burst',
|
||||
type: 'radio',
|
||||
checked: currentSplashTheme === 'singularity',
|
||||
click: () => selectSplashTheme('singularity'),
|
||||
},
|
||||
{
|
||||
label: '方案 2:轨道星座校准 / Orbital Astrolabe',
|
||||
type: 'radio',
|
||||
checked: currentSplashTheme === 'constellation',
|
||||
click: () => selectSplashTheme('constellation'),
|
||||
},
|
||||
{
|
||||
label: '方案 3:晨昏日冕破晓 / Eclipse Horizon',
|
||||
type: 'radio',
|
||||
checked: currentSplashTheme === 'horizon',
|
||||
click: () => selectSplashTheme('horizon'),
|
||||
},
|
||||
{
|
||||
label: '关闭启动画面 / Off',
|
||||
type: 'radio',
|
||||
checked: currentSplashTheme === 'off',
|
||||
click: () => selectSplashTheme('off'),
|
||||
label: '启用启动画面 / Enable Splash Screen',
|
||||
type: 'checkbox',
|
||||
checked: currentSplashTheme !== 'off',
|
||||
click: () => selectSplashTheme(currentSplashTheme === 'off' ? 'singularity' : 'off'),
|
||||
},
|
||||
{ type: 'separator' },
|
||||
{
|
||||
@@ -106,6 +112,52 @@ export function buildApplicationMenu(options: {
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
label: '渲染设备 / GPU Mode',
|
||||
submenu: [
|
||||
...(gpuSummary
|
||||
? [
|
||||
{
|
||||
label: formatGpuSummaryLabel(gpuSummary),
|
||||
enabled: false,
|
||||
},
|
||||
{ type: 'separator' as const },
|
||||
]
|
||||
: []),
|
||||
{
|
||||
label: '自动(卡顿缺显存切核显,显存空出自动回独显) / Auto',
|
||||
type: 'radio',
|
||||
checked: currentGpuMode === 'auto',
|
||||
click: () => {
|
||||
void options.onSelectGpuMode?.('auto')
|
||||
},
|
||||
},
|
||||
{
|
||||
label: '独立显卡(高性能) / Discrete GPU',
|
||||
type: 'radio',
|
||||
checked: currentGpuMode === 'high-performance',
|
||||
click: () => {
|
||||
void options.onSelectGpuMode?.('high-performance')
|
||||
},
|
||||
},
|
||||
{
|
||||
label: '集成核显(不占独显显存) / Integrated GPU',
|
||||
type: 'radio',
|
||||
checked: currentGpuMode === 'low-power',
|
||||
click: () => {
|
||||
void options.onSelectGpuMode?.('low-power')
|
||||
},
|
||||
},
|
||||
{
|
||||
label: '纯 CPU 软渲染 / Software GL',
|
||||
type: 'radio',
|
||||
checked: currentGpuMode === 'software',
|
||||
click: () => {
|
||||
void options.onSelectGpuMode?.('software')
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{ type: 'separator' },
|
||||
{
|
||||
label: '打开运维控制台 / Open Admin Console',
|
||||
@@ -116,6 +168,23 @@ export function buildApplicationMenu(options: {
|
||||
click: () => openAdminPath('/docs/manual'),
|
||||
},
|
||||
{ type: 'separator' },
|
||||
{
|
||||
label: '检查更新 / Check for Updates...',
|
||||
click: () => options.onCheckForUpdates?.(),
|
||||
},
|
||||
...(options.getVersionInfo
|
||||
? [
|
||||
(() => {
|
||||
const info = options.getVersionInfo!()
|
||||
const suffix = info.usingHotfix ? ' (热更 / Hotfix)' : ''
|
||||
return {
|
||||
label: `当前版本: Shell v${info.shellVersion} · Earth v${info.activeBundleVersion}${suffix}`,
|
||||
enabled: false,
|
||||
}
|
||||
})(),
|
||||
]
|
||||
: []),
|
||||
{ type: 'separator' },
|
||||
{ role: 'quit', label: '退出 / Quit' },
|
||||
],
|
||||
},
|
||||
|
||||
@@ -101,3 +101,44 @@ export function computeLandscapeBounds(params: {
|
||||
const targetPos = pos ?? centerOnAnchor(anchorBounds, width, height)
|
||||
return clampBoundsToWorkArea({ x: targetPos.x, y: targetPos.y, width, height }, workArea)
|
||||
}
|
||||
|
||||
export function resolveInitialWindowBounds(params: {
|
||||
saved: {
|
||||
x?: number
|
||||
y?: number
|
||||
width: number
|
||||
height: number
|
||||
isMaximized?: boolean
|
||||
isFullScreen?: boolean
|
||||
}
|
||||
launchFullScreen: boolean
|
||||
headlessSmoke: boolean
|
||||
displayWorkArea: Rect
|
||||
displayBounds: Rect
|
||||
}): {
|
||||
initialBounds: { x?: number; y?: number; width: number; height: number }
|
||||
shouldRestoreNormalBoundsOnUnmaximize: boolean
|
||||
} {
|
||||
const { saved, launchFullScreen, headlessSmoke, displayWorkArea, displayBounds } = params
|
||||
if (!headlessSmoke && (launchFullScreen || saved.isFullScreen)) {
|
||||
return {
|
||||
initialBounds: { ...displayBounds },
|
||||
shouldRestoreNormalBoundsOnUnmaximize: Boolean(saved.isMaximized),
|
||||
}
|
||||
}
|
||||
if (!headlessSmoke && saved.isMaximized) {
|
||||
return {
|
||||
initialBounds: { ...displayWorkArea },
|
||||
shouldRestoreNormalBoundsOnUnmaximize: true,
|
||||
}
|
||||
}
|
||||
return {
|
||||
initialBounds: {
|
||||
x: saved.x,
|
||||
y: saved.y,
|
||||
width: saved.width,
|
||||
height: saved.height,
|
||||
},
|
||||
shouldRestoreNormalBoundsOnUnmaximize: false,
|
||||
}
|
||||
}
|
||||
@@ -156,6 +156,7 @@ export function createStaticFileResponse(filePath: string, requestHeaders: Heade
|
||||
|
||||
export function createEarthProtocolHandler(options: {
|
||||
earthBundleRoot: string
|
||||
getEarthOverlayRoot?: () => string | null
|
||||
getBackendUrl: () => string
|
||||
fetchImpl?: typeof fetch
|
||||
}): (request: Request) => Promise<Response> {
|
||||
@@ -172,6 +173,9 @@ export function createEarthProtocolHandler(options: {
|
||||
const forwardHeaders = new Headers(request.headers)
|
||||
forwardHeaders.delete('host')
|
||||
forwardHeaders.delete('content-length')
|
||||
if (!forwardHeaders.has('accept-encoding')) {
|
||||
forwardHeaders.set('accept-encoding', 'gzip, deflate, br')
|
||||
}
|
||||
|
||||
const method = request.method.toUpperCase()
|
||||
const hasBody = method !== 'GET' && method !== 'HEAD'
|
||||
@@ -180,6 +184,9 @@ export function createEarthProtocolHandler(options: {
|
||||
method,
|
||||
headers: forwardHeaders,
|
||||
}
|
||||
if (request.signal) {
|
||||
init.signal = request.signal
|
||||
}
|
||||
if (hasBody && request.body) {
|
||||
init.body = request.body
|
||||
init.duplex = 'half'
|
||||
@@ -188,12 +195,16 @@ export function createEarthProtocolHandler(options: {
|
||||
const responseHeaders = new Headers(upstream.headers)
|
||||
responseHeaders.delete('content-encoding')
|
||||
responseHeaders.delete('content-length')
|
||||
return new Response(upstream.body, {
|
||||
const isNullBodyStatus = upstream.status === 204 || upstream.status === 205 || upstream.status === 304
|
||||
return new Response(isNullBodyStatus ? null : upstream.body, {
|
||||
status: upstream.status,
|
||||
statusText: upstream.statusText,
|
||||
headers: responseHeaders,
|
||||
})
|
||||
} catch (error) {
|
||||
if (request.signal?.aborted) {
|
||||
throw error
|
||||
}
|
||||
return Response.json(
|
||||
{
|
||||
detail: 'Backend service unavailable',
|
||||
@@ -209,6 +220,21 @@ export function createEarthProtocolHandler(options: {
|
||||
if (!staticPath) {
|
||||
return new Response('Forbidden', { status: 403 })
|
||||
}
|
||||
|
||||
const overlayRoot = options.getEarthOverlayRoot?.()
|
||||
if (overlayRoot) {
|
||||
const overlayPath = resolveEarthStaticPath(overlayRoot, parsedUrl.pathname)
|
||||
if (overlayPath) {
|
||||
try {
|
||||
if (fs.statSync(overlayPath).isFile()) {
|
||||
return createStaticFileResponse(overlayPath, request.headers)
|
||||
}
|
||||
} catch {
|
||||
// Fall back to the built-in shell bundle for non-overlaid static assets.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return createStaticFileResponse(staticPath, request.headers)
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,14 @@
|
||||
import { net, protocol, type Session } from 'electron'
|
||||
import { net, protocol, systemPreferences, type Session } from 'electron'
|
||||
|
||||
import { createEarthProtocolHandler } from './protocol-core'
|
||||
|
||||
export const EARTH_ORIGIN = 'planet://earth'
|
||||
export const EARTH_ENTRY_URL = `${EARTH_ORIGIN}/earth/index.html`
|
||||
|
||||
function isEarthUrl(url: string): boolean {
|
||||
return url === EARTH_ORIGIN || url.startsWith(`${EARTH_ORIGIN}/`)
|
||||
}
|
||||
|
||||
export function registerEarthScheme(): void {
|
||||
protocol.registerSchemesAsPrivileged([
|
||||
{
|
||||
@@ -25,11 +29,13 @@ export function installEarthSessionHandlers(
|
||||
targetSession: Session,
|
||||
options: {
|
||||
earthBundleRoot: string
|
||||
getEarthOverlayRoot?: () => string | null
|
||||
getBackendUrl: () => string
|
||||
},
|
||||
): void {
|
||||
const handler = createEarthProtocolHandler({
|
||||
earthBundleRoot: options.earthBundleRoot,
|
||||
getEarthOverlayRoot: options.getEarthOverlayRoot,
|
||||
getBackendUrl: options.getBackendUrl,
|
||||
fetchImpl: (input, init) => net.fetch(input as string, init),
|
||||
})
|
||||
@@ -49,13 +55,35 @@ export function installEarthSessionHandlers(
|
||||
},
|
||||
)
|
||||
|
||||
targetSession.setPermissionRequestHandler((webContents, permission, callback) => {
|
||||
const pageUrl = webContents.getURL()
|
||||
const isEarthOrigin = pageUrl.startsWith(EARTH_ORIGIN)
|
||||
if (isEarthOrigin && (permission === 'media' || permission === 'fullscreen')) {
|
||||
targetSession.setPermissionRequestHandler((webContents, permission, callback, details) => {
|
||||
if (permission === 'fullscreen') {
|
||||
callback(isEarthUrl(webContents.getURL()))
|
||||
return
|
||||
}
|
||||
if (permission === 'media' && details.isMainFrame && isEarthUrl(details.requestingUrl)) {
|
||||
if ('mediaTypes' in details && details.mediaTypes?.includes('audio')) {
|
||||
callback(false)
|
||||
return
|
||||
}
|
||||
if (process.platform === 'darwin') {
|
||||
void systemPreferences.askForMediaAccess('camera').then(
|
||||
(granted) => callback(granted),
|
||||
() => callback(false),
|
||||
)
|
||||
return
|
||||
}
|
||||
callback(true)
|
||||
return
|
||||
}
|
||||
callback(false)
|
||||
})
|
||||
|
||||
targetSession.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {
|
||||
if (permission === 'fullscreen') return isEarthUrl(webContents?.getURL() || '')
|
||||
if (permission !== 'media' || details.mediaType === 'audio' || !details.isMainFrame) return false
|
||||
return (
|
||||
isEarthUrl(details.requestingUrl || requestingOrigin) &&
|
||||
(process.platform !== 'darwin' || systemPreferences.getMediaAccessStatus('camera') === 'granted')
|
||||
)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import zlib from 'node:zlib'
|
||||
|
||||
export interface TarEntryInput {
|
||||
path: string
|
||||
data: Uint8Array
|
||||
}
|
||||
|
||||
export interface ExtractTarGzOptions {
|
||||
maxFiles?: number
|
||||
maxTotalBytes?: number
|
||||
}
|
||||
|
||||
export interface ExtractTarGzResult {
|
||||
files: string[]
|
||||
totalBytes: number
|
||||
}
|
||||
|
||||
const TAR_BLOCK_SIZE = 512
|
||||
const DEFAULT_MAX_FILES = 2000
|
||||
const DEFAULT_MAX_TOTAL_BYTES = 64 * 1024 * 1024
|
||||
|
||||
export function normalizeArchiveEntryPath(rawPath: string): string {
|
||||
if (!rawPath || rawPath.includes('\0') || rawPath.includes('\\')) {
|
||||
throw new Error(`Invalid archive entry path: ${JSON.stringify(rawPath)}`)
|
||||
}
|
||||
let stripped = rawPath.replace(/^(?:\.\/)+/, '').replace(/\/+$/, '')
|
||||
if (!stripped || stripped.startsWith('/')) {
|
||||
throw new Error(`Unsafe archive entry path: ${JSON.stringify(rawPath)}`)
|
||||
}
|
||||
const segments = stripped.split('/')
|
||||
if (segments.some((seg) => !seg || seg === '.' || seg === '..')) {
|
||||
throw new Error(`Path traversal not allowed in archive entry: ${JSON.stringify(rawPath)}`)
|
||||
}
|
||||
stripped = segments.join('/')
|
||||
if (/^[A-Za-z]:/.test(stripped)) {
|
||||
throw new Error(`Drive-prefixed archive entry path not allowed: ${JSON.stringify(rawPath)}`)
|
||||
}
|
||||
return stripped
|
||||
}
|
||||
|
||||
function splitUstarPath(entryPath: string): { name: string; prefix: string } {
|
||||
const bytesLen = Buffer.byteLength(entryPath, 'utf8')
|
||||
if (bytesLen <= 100) {
|
||||
return { name: entryPath, prefix: '' }
|
||||
}
|
||||
if (bytesLen > 256) {
|
||||
throw new Error(`Archive entry path exceeds POSIX USTAR 256-byte limit: ${entryPath}`)
|
||||
}
|
||||
for (let idx = entryPath.indexOf('/', Math.max(0, entryPath.length - 101)); idx !== -1; idx = entryPath.indexOf('/', idx + 1)) {
|
||||
const prefix = entryPath.slice(0, idx)
|
||||
const name = entryPath.slice(idx + 1)
|
||||
if (name && Buffer.byteLength(name, 'utf8') <= 100 && Buffer.byteLength(prefix, 'utf8') <= 155) {
|
||||
return { name, prefix }
|
||||
}
|
||||
}
|
||||
throw new Error(`Cannot split archive entry path into USTAR prefix/name: ${entryPath}`)
|
||||
}
|
||||
|
||||
function writeOctalField(buf: Buffer, offset: number, length: number, value: number): void {
|
||||
const digits = length - 1
|
||||
const octal = Math.max(0, Math.floor(value)).toString(8)
|
||||
if (octal.length > digits) {
|
||||
throw new Error(`Tar numeric value overflows ${digits}-digit octal field: ${value}`)
|
||||
}
|
||||
buf.write(`${octal.padStart(digits, '0')}\0`, offset, length, 'ascii')
|
||||
}
|
||||
|
||||
export function createTarGz(entries: TarEntryInput[]): Buffer {
|
||||
const normalizedEntries = [...entries]
|
||||
.map((entry) => ({
|
||||
path: normalizeArchiveEntryPath(entry.path),
|
||||
data: entry.data instanceof Buffer ? entry.data : Buffer.from(entry.data),
|
||||
}))
|
||||
.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))
|
||||
|
||||
const chunks: Buffer[] = []
|
||||
for (const entry of normalizedEntries) {
|
||||
const { name, prefix } = splitUstarPath(entry.path)
|
||||
const header = Buffer.alloc(TAR_BLOCK_SIZE, 0)
|
||||
header.write(name, 0, 100, 'utf8')
|
||||
writeOctalField(header, 100, 8, 0o644)
|
||||
writeOctalField(header, 108, 8, 0)
|
||||
writeOctalField(header, 116, 8, 0)
|
||||
writeOctalField(header, 124, 12, entry.data.byteLength)
|
||||
writeOctalField(header, 136, 12, 0)
|
||||
header.fill(0x20, 148, 156)
|
||||
header.write('0', 156, 1, 'ascii')
|
||||
header.write('ustar\0', 257, 6, 'ascii')
|
||||
header.write('00', 263, 2, 'ascii')
|
||||
if (prefix) {
|
||||
header.write(prefix, 345, 155, 'utf8')
|
||||
}
|
||||
|
||||
let checksum = 0
|
||||
for (let i = 0; i < TAR_BLOCK_SIZE; i += 1) {
|
||||
checksum += header[i]
|
||||
}
|
||||
const chksumStr = `${checksum.toString(8).padStart(6, '0')}\0 `
|
||||
header.write(chksumStr, 148, 8, 'ascii')
|
||||
|
||||
chunks.push(header)
|
||||
if (entry.data.byteLength > 0) {
|
||||
chunks.push(entry.data)
|
||||
const remainder = entry.data.byteLength % TAR_BLOCK_SIZE
|
||||
if (remainder !== 0) {
|
||||
chunks.push(Buffer.alloc(TAR_BLOCK_SIZE - remainder, 0))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
chunks.push(Buffer.alloc(TAR_BLOCK_SIZE * 2, 0))
|
||||
const tarBuffer = Buffer.concat(chunks)
|
||||
return zlib.gzipSync(tarBuffer, { level: 9 })
|
||||
}
|
||||
|
||||
function readCString(buf: Buffer, start: number, length: number): string {
|
||||
const slice = buf.subarray(start, start + length)
|
||||
const nulIdx = slice.indexOf(0)
|
||||
return slice.subarray(0, nulIdx === -1 ? length : nulIdx).toString('utf8')
|
||||
}
|
||||
|
||||
function parseOctalField(buf: Buffer, start: number, length: number): number {
|
||||
const raw = readCString(buf, start, length).trim()
|
||||
if (!raw) return 0
|
||||
if (!/^[0-7]+$/.test(raw)) {
|
||||
throw new Error(`Invalid tar octal field: ${JSON.stringify(raw)}`)
|
||||
}
|
||||
return Number.parseInt(raw, 8)
|
||||
}
|
||||
|
||||
function isZeroBlock(block: Buffer): boolean {
|
||||
for (let i = 0; i < block.length; i += 1) {
|
||||
if (block[i] !== 0) return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
function verifyHeaderChecksum(header: Buffer): void {
|
||||
const stored = parseOctalField(header, 148, 8)
|
||||
let unsignedSum = 0
|
||||
for (let i = 0; i < TAR_BLOCK_SIZE; i += 1) {
|
||||
unsignedSum += i >= 148 && i < 156 ? 0x20 : header[i]
|
||||
}
|
||||
if (stored !== unsignedSum) {
|
||||
throw new Error(`Invalid tar header checksum (expected ${unsignedSum}, got ${stored})`)
|
||||
}
|
||||
}
|
||||
|
||||
export function extractTarGzSafely(
|
||||
archiveBuffer: Buffer,
|
||||
destDir: string,
|
||||
options: ExtractTarGzOptions = {},
|
||||
): ExtractTarGzResult {
|
||||
const maxFiles = options.maxFiles ?? DEFAULT_MAX_FILES
|
||||
const maxTotalBytes = options.maxTotalBytes ?? DEFAULT_MAX_TOTAL_BYTES
|
||||
const tarBuffer = zlib.gunzipSync(archiveBuffer, {
|
||||
maxOutputLength: maxTotalBytes + 2 * 1024 * 1024,
|
||||
})
|
||||
if (tarBuffer.byteLength % TAR_BLOCK_SIZE !== 0) {
|
||||
throw new Error('Corrupt tar archive: unaligned block length')
|
||||
}
|
||||
|
||||
const resolvedDest = path.resolve(destDir)
|
||||
fs.mkdirSync(resolvedDest, { recursive: true })
|
||||
|
||||
const extractedFiles: string[] = []
|
||||
let totalBytes = 0
|
||||
let offset = 0
|
||||
|
||||
while (offset + TAR_BLOCK_SIZE <= tarBuffer.byteLength) {
|
||||
const header = tarBuffer.subarray(offset, offset + TAR_BLOCK_SIZE)
|
||||
offset += TAR_BLOCK_SIZE
|
||||
if (isZeroBlock(header)) {
|
||||
break
|
||||
}
|
||||
|
||||
verifyHeaderChecksum(header)
|
||||
const rawName = readCString(header, 0, 100)
|
||||
const rawPrefix = readCString(header, 345, 155)
|
||||
const fullRawPath = rawPrefix ? `${rawPrefix}/${rawName}` : rawName
|
||||
const size = parseOctalField(header, 124, 12)
|
||||
const typeFlagByte = header[156]
|
||||
const typeFlag = typeFlagByte === 0 ? '0' : String.fromCharCode(typeFlagByte)
|
||||
|
||||
if (offset + size > tarBuffer.byteLength) {
|
||||
throw new Error(`Truncated tar entry data for ${fullRawPath}`)
|
||||
}
|
||||
const data = tarBuffer.subarray(offset, offset + size)
|
||||
const paddedSize = Math.ceil(size / TAR_BLOCK_SIZE) * TAR_BLOCK_SIZE
|
||||
offset += paddedSize
|
||||
|
||||
if (typeFlag === '5') {
|
||||
const normalizedDir = fullRawPath.replace(/^(?:\.\/)+/, '').replace(/\/+$/, '')
|
||||
if (normalizedDir && normalizedDir !== '.') {
|
||||
const safeDir = normalizeArchiveEntryPath(normalizedDir)
|
||||
const targetDir = path.resolve(resolvedDest, safeDir)
|
||||
if (targetDir !== resolvedDest && !targetDir.startsWith(`${resolvedDest}${path.sep}`)) {
|
||||
throw new Error(`Directory escapes extraction root: ${safeDir}`)
|
||||
}
|
||||
fs.mkdirSync(targetDir, { recursive: true })
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if (typeFlag !== '0') {
|
||||
throw new Error(`Unsupported or unsafe tar entry type ${JSON.stringify(typeFlag)} for ${fullRawPath}`)
|
||||
}
|
||||
|
||||
const safeRelPath = normalizeArchiveEntryPath(fullRawPath)
|
||||
if (extractedFiles.length + 1 > maxFiles) {
|
||||
throw new Error(`Archive exceeds maximum file count limit (${maxFiles})`)
|
||||
}
|
||||
totalBytes += size
|
||||
if (totalBytes > maxTotalBytes) {
|
||||
throw new Error(`Archive exceeds maximum uncompressed byte limit (${maxTotalBytes})`)
|
||||
}
|
||||
|
||||
const targetPath = path.resolve(resolvedDest, safeRelPath)
|
||||
if (!targetPath.startsWith(`${resolvedDest}${path.sep}`)) {
|
||||
throw new Error(`File escapes extraction root: ${safeRelPath}`)
|
||||
}
|
||||
fs.mkdirSync(path.dirname(targetPath), { recursive: true })
|
||||
fs.writeFileSync(targetPath, data)
|
||||
extractedFiles.push(safeRelPath)
|
||||
}
|
||||
|
||||
return {
|
||||
files: extractedFiles,
|
||||
totalBytes,
|
||||
}
|
||||
}
|
||||
Loaded 100 of 204 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user