Compare commits

..
4 Commits
Author SHA1 Message Date
linkong 1c0066edc6 release: bump version to 0.85.0
ci / backend (push) Waiting to run
ci / frontend (push) Waiting to run
2026-12-06 22:47:23 +08:00
rayd1o 30b44ec00d release: bump version to 0.84.2
ci / backend (push) Canceled after 0s
ci / frontend (push) Canceled after 0s
ci / delivery (push) Canceled after 0s
2026-12-05 01:56:03 +08:00
linkong 5e6352f524 release: bump version to 0.84.1
ci / backend (push) Canceled after 0s
ci / frontend (push) Canceled after 0s
ci / delivery (push) Canceled after 0s
2026-12-04 07:34:27 +08:00
linkong e1cc27f13d release: bump version to 0.84.0
ci / backend (push) Canceled after 0s
ci / frontend (push) Canceled after 0s
ci / delivery (push) Canceled after 0s
2026-12-04 07:07:19 +08:00
421 changed files with 75722 additions and 6739 deletions

No files matched your search

+3 -1
View File
@@ -187,7 +187,9 @@ and builds/uploads **only** the affected targets:
service image(s) + OCI `release-manifest:<tag>`, **skips creating a Gitea Release**,
skips desktop packaging and client hotfix updates, and deploys only the changed container(s) on production.
- `frontend/public/earth/**`-only changes (`client.mode == "hotfix"`): emits only the L1 Earth hotfix bundle
(`./planet.sh bundle --hotfix`) while keeping the prior desktop `shell_version`, and creates a Gitea Release with `release-manifest.json` + hotfix bundle.
(`./planet.sh bundle --hotfix`) while keeping the prior desktop `shell_version`, embeds the hotfix bundle and
release notes into OCI `release-manifest:<tag>` (`bundle_storage: "oci"`), and **skips creating a Gitea Release**
so `/releases/latest` always preserves full desktop installers while production auto-publishes the L1 hotfix.
- `client/**` changes (`client.mode == "full"`): builds cross-platform desktop installers (`--all`) plus the
L1 hotfix bundle, and creates a Gitea Release with installers + `release-manifest.json`.
+1 -1
View File
@@ -14,7 +14,7 @@
!config/
!config/earth-boundary-pov-policy.china-v1.json
!scripts/
!scripts/build_earth_boundary_china_pov_geojson.py
!scripts/earth_boundary_geometry.py
!scripts/build_earth_boundary_pmtiles.py
!scripts/db_migrate.py
!scripts/earth_boundary_policy.py
+9 -3
View File
@@ -170,10 +170,16 @@ temp/
# ----------------------
data/ai/bgp-briefs/
data/earth-boundary-sources/
data/earth-clouds/
data/earth-tiles/
data/earth-wind/
data/aircraft_registry/
data/earth-terrain-cache/
# Generated Earth boundary tile artifacts. Keep source configs and builders in
# Git; publish PMTiles/MVT artifacts through release/deploy storage instead of
# committing thousands of generated tile files.
# Earth boundary sources and generated PMTiles artifacts live in the backend
# boundary data volume (built by the Earth "高精" rebuild), never in Git or in
# the desktop Earth bundle.
backend/data/earth-boundaries/
frontend/public/earth/data/boundaries/
# Offline comparison originals; runtime 8K maps and provenance remain versioned.
+7 -5
View File
@@ -127,11 +127,13 @@ the user's login interactive shell instead of assuming a specific dotfile.
committed files.
- Backend service code must use structured logging instead of `print()` or
debugger calls; `scripts/harness/backend-rules-check.sh` enforces this.
- **Client-Only Gitea Releases**: Releases without client updates
(`client.mode == "none"`) push only changed container images plus OCI
`release-manifest:<tag>` and must **not** create a Gitea Release; only
`hotfix` or `full` client releases create a Gitea Release, and production
`planet-release-deploy` reconciles from Git tags + OCI `release-manifest:<tag>`.
- **Client-Only Gitea Releases**: Releases without desktop shell updates
(`client.mode == "none"` or `"hotfix"`) push changed container images plus OCI
`release-manifest:<tag>` (embedding L1 hotfix bundles in OCI for `hotfix`)
and must **not** create a Gitea Release; only `full` desktop client releases
create a Gitea Release so `/releases/latest` always carries installers, and
production `planet-release-deploy` reconciles from Git tags + OCI
`release-manifest:<tag>`.
- **Release Publish vs. Production Deployment (`发版 ≠ 已部署`)**:
`scripts/release_publish.py` only publishes container images, OCI
`release-manifest:<tag>`, and optional Gitea Releases; it never updates
+1 -1
View File
@@ -1 +1 @@
0.83.0
0.85.0
+100 -8
View File
@@ -126,6 +126,7 @@ class ProviderService:
native_web_search = bool(getattr(payload, "native_web_search", False))
images = self._normalize_images(getattr(payload, "images", None))
tool_calls: list[ToolCallRecord] = []
citation_urls: list[str] = []
stop_reason: str | None = None
if provider_api == "openai-completions":
@@ -160,6 +161,7 @@ class ProviderService:
content_blocks = self._extract_responses_blocks(data)
content = "".join(block.text for block in content_blocks if block.text)
tool_calls = self._extract_responses_tool_calls(data)
citation_urls = self._extract_responses_citations(data)
stop_reason = str(data.get("status") or "") or None
elif provider_api == "anthropic-messages":
data = await self._request_anthropic_messages(
@@ -177,6 +179,7 @@ class ProviderService:
content = self._extract_anthropic_content(data)
content_blocks = self._extract_anthropic_blocks(data)
tool_calls = self._extract_anthropic_tool_calls(data)
citation_urls = self._extract_anthropic_citations(data)
stop_reason = str(data.get("stop_reason") or "") or None
elif provider_api == "ollama-generate":
data = await self._request_ollama(
@@ -207,6 +210,7 @@ class ProviderService:
text_blocks=text_blocks,
thinking_blocks=thinking_blocks,
tool_calls=tool_calls,
citation_urls=citation_urls,
stop_reason=stop_reason,
raw_response=data,
)
@@ -332,7 +336,17 @@ class ProviderService:
anthropic_messages: list[dict[str, Any]] = []
source_messages = (
conversation_messages
if (conversation_messages and (len(conversation_messages) > 1 or any(m.get("role") == "tool" or m.get("tool_calls") for m in conversation_messages)))
if (
conversation_messages
and (
len(conversation_messages) > 1
or bool(tools)
or any(
m.get("role") == "tool" or m.get("tool_calls") or m.get("thinking_blocks")
for m in conversation_messages
)
)
)
else [{"role": "user", "content": prompt}]
)
for msg in source_messages:
@@ -354,8 +368,15 @@ class ProviderService:
else:
anthropic_messages.append({"role": "user", "content": [block]})
continue
if role == "assistant" and msg.get("tool_calls"):
if role == "assistant" and (msg.get("tool_calls") or msg.get("thinking_blocks")):
blocks: list[dict[str, Any]] = []
for tb in msg.get("thinking_blocks") or []:
if not isinstance(tb, dict):
continue
t_text = str(tb.get("thinking") or "")
sig = str(tb.get("signature") or "")
if t_text and sig:
blocks.append({"type": "thinking", "thinking": t_text, "signature": sig})
text = str(msg.get("content") or "").strip()
if text:
blocks.append({"type": "text", "text": text})
@@ -424,9 +445,12 @@ class ProviderService:
for tool in tools or []:
if not isinstance(tool, dict) or not tool.get("name"):
continue
tool_name = str(tool["name"])
if native_web_search and tool_name == "web_search":
continue
anthropic_tools.append(
{
"name": str(tool["name"]),
"name": tool_name,
"description": str(tool.get("description") or ""),
"input_schema": tool.get("parameters") or {"type": "object", "properties": {}},
}
@@ -437,13 +461,15 @@ class ProviderService:
request_body["tools"] = anthropic_tools
if isinstance(tool_choice, str):
if tool_choice == "required":
request_body["tool_choice"] = {"type": "any"}
request_body["tool_choice"] = {"type": "auto"} if thinking_active else {"type": "any"}
elif tool_choice == "auto":
request_body["tool_choice"] = {"type": "auto"}
elif tool_choice not in {"none", ""}:
request_body["tool_choice"] = {"type": "tool", "name": tool_choice}
request_body["tool_choice"] = {"type": "auto"} if thinking_active else {"type": "tool", "name": tool_choice}
elif isinstance(tool_choice, dict) and tool_choice.get("name"):
request_body["tool_choice"] = {"type": "tool", "name": str(tool_choice["name"])}
request_body["tool_choice"] = (
{"type": "auto"} if thinking_active else {"type": "tool", "name": str(tool_choice["name"])}
)
path = "/v1/messages" if self.provider == "minimax" and self.base_url.endswith("/anthropic") else "/messages"
headers = {
@@ -751,10 +777,15 @@ class ProviderService:
if not isinstance(item, dict)
else item.get("tool_calls")
)
or bool(
getattr(item, "thinking_blocks", None)
if not isinstance(item, dict)
else item.get("thinking_blocks")
)
)
for item in raw_items
)
if has_tool_turns:
if raw_items and (has_tool_turns or getattr(payload, "tools", None)):
preserved: list[dict[str, Any]] = []
for item in raw_items:
if isinstance(item, dict):
@@ -763,12 +794,14 @@ class ProviderService:
tool_call_id = item.get("tool_call_id")
name = item.get("name")
tool_calls = item.get("tool_calls")
thinking_blocks = item.get("thinking_blocks")
else:
role = str(getattr(item, "role", "") or "").strip().lower()
content = str(getattr(item, "content", "") or "")
tool_call_id = getattr(item, "tool_call_id", None)
name = getattr(item, "name", None)
tool_calls = getattr(item, "tool_calls", None)
thinking_blocks = getattr(item, "thinking_blocks", None)
if role not in {"user", "assistant", "tool"}:
continue
entry: dict[str, Any] = {"role": role, "content": content}
@@ -778,6 +811,8 @@ class ProviderService:
entry["name"] = str(name)
if tool_calls:
entry["tool_calls"] = list(tool_calls)
if thinking_blocks:
entry["thinking_blocks"] = list(thinking_blocks)
preserved.append(entry)
return preserved or [{"role": "user", "content": final_prompt}]
@@ -943,7 +978,14 @@ class ProviderService:
messages.append({"role": "system", "content": resolved_system_prompt})
source_messages = (
conversation_messages
if (conversation_messages and (len(conversation_messages) > 1 or any(m.get("role") == "tool" or m.get("tool_calls") for m in conversation_messages)))
if (
conversation_messages
and (
len(conversation_messages) > 1
or bool(tools)
or any(m.get("role") == "tool" or m.get("tool_calls") for m in conversation_messages)
)
)
else [{"role": "user", "content": prompt}]
)
for msg in source_messages:
@@ -1046,6 +1088,7 @@ class ProviderService:
conversation_messages
and (
len(conversation_messages) > 1
or bool(tools)
or any(m.get("role") == "tool" or m.get("tool_calls") for m in conversation_messages)
)
)
@@ -1480,3 +1523,52 @@ class ProviderService:
args = self._parse_tool_arguments(item.get("input"))
records.append(ToolCallRecord(id=call_id, name=name, arguments=args))
return records
@staticmethod
def _dedupe_urls(urls: list[str]) -> list[str]:
seen: set[str] = set()
out: list[str] = []
for raw in urls:
url = str(raw or "").strip()
if url.startswith(("http://", "https://")) and url not in seen:
seen.add(url)
out.append(url)
return out
def _extract_responses_citations(self, payload: dict[str, Any]) -> list[str]:
urls: list[str] = []
for item in payload.get("output") or []:
if not isinstance(item, dict):
continue
if item.get("type") == "message":
for part in item.get("content") or []:
if not isinstance(part, dict):
continue
for ann in part.get("annotations") or []:
if isinstance(ann, dict) and ann.get("type") == "url_citation" and ann.get("url"):
urls.append(str(ann["url"]))
elif item.get("type") == "web_search_call":
action = item.get("action") if isinstance(item.get("action"), dict) else {}
for src in action.get("sources") or []:
if isinstance(src, dict) and src.get("url"):
urls.append(str(src["url"]))
return self._dedupe_urls(urls)
def _extract_anthropic_citations(self, payload: dict[str, Any]) -> list[str]:
content = payload.get("content")
if not isinstance(content, list):
return []
urls: list[str] = []
for item in content:
if not isinstance(item, dict):
continue
item_type = str(item.get("type") or "")
if item_type == "web_search_tool_result":
for res in item.get("content") or []:
if isinstance(res, dict) and res.get("url"):
urls.append(str(res["url"]))
elif item_type == "text":
for cite in item.get("citations") or []:
if isinstance(cite, dict) and cite.get("url"):
urls.append(str(cite["url"]))
return self._dedupe_urls(urls)
+2
View File
@@ -9,6 +9,7 @@ class ChatMessage(BaseModel):
tool_call_id: str | None = Field(default=None, max_length=200)
name: str | None = Field(default=None, max_length=200)
tool_calls: list[dict[str, Any]] | None = None
thinking_blocks: list[dict[str, Any]] | None = None
class ToolCallRecord(BaseModel):
@@ -56,6 +57,7 @@ class SituationalAnalysisResponse(BaseModel):
text_blocks: list[str] = Field(default_factory=list)
thinking_blocks: list[str] = Field(default_factory=list)
tool_calls: list[ToolCallRecord] = Field(default_factory=list)
citation_urls: list[str] = Field(default_factory=list)
stop_reason: str | None = None
raw_response: dict[str, Any] = Field(default_factory=dict)
+23 -1
View File
@@ -4,6 +4,17 @@ ARG PYTHON_IMAGE=python:3.14-slim
ARG UV_IMAGE=ghcr.io/astral-sh/uv:latest
FROM ${UV_IMAGE} AS uv
# Earth boundary PMTiles builder (used by the Earth "高精" rebuild job).
FROM ${PYTHON_IMAGE} AS tippecanoe-build
ARG TIPPECANOE_REF=2.79.0
RUN apt-get update \
&& apt-get install -y --no-install-recommends build-essential ca-certificates git libsqlite3-dev zlib1g-dev \
&& rm -rf /var/lib/apt/lists/*
RUN git clone --depth 1 --branch "${TIPPECANOE_REF}" https://github.com/felt/tippecanoe.git /src/tippecanoe \
&& make -C /src/tippecanoe -j"$(nproc)" tippecanoe \
&& install -m 0755 /src/tippecanoe/tippecanoe /usr/local/bin/tippecanoe
FROM ${PYTHON_IMAGE}
COPY --from=uv /uv /uvx /bin/
@@ -20,8 +31,19 @@ RUN mkdir -p /root/.config/uv
RUN apt-get update && apt-get install -y --no-install-recommends \
curl \
libgl1 \
libglib2.0-0 \
libsm6 \
libsqlite3-0 \
libstdc++6 \
libxcb1 \
libxext6 \
libxrender1 \
zlib1g \
&& rm -rf /var/lib/apt/lists/*
COPY --from=tippecanoe-build /usr/local/bin/tippecanoe /usr/local/bin/tippecanoe
COPY pyproject.toml uv.lock /app/
RUN --mount=type=cache,target=/root/.cache/uv \
--mount=type=secret,id=planet_uv_config,target=/root/.config/uv/uv.toml,required=false \
@@ -29,8 +51,8 @@ RUN --mount=type=cache,target=/root/.cache/uv \
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/earth_boundary_geometry.py /app/scripts/earth_boundary_geometry.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
+3 -11
View File
@@ -31,21 +31,13 @@
"system_prompt": "你是 BGP 值班分析师。请直接输出面向值班人员的中文 Markdown 简报,只写最终研判内容;不要复述用户需求、提示词、写作计划、字段清单或“我将如何回答”。",
"prompt": "基于当前 BGP incidents、anomalies、原始观测事件、观测站覆盖与 prefix geography 证据,生成一份面向操作员的简明态势简报,突出区域热点、观测偏差、当前风险、证据和优先动作。"
},
{
"key": "location.factcheck.normalize",
"label": "位置事实核查结构化",
"group": "位置解析",
"version": "2026-05-16.1",
"system_prompt": "",
"prompt": "Convert the supplied location factcheck text into exactly one strict JSON object. Extract only facts present in the text or original query."
},
{
"key": "location.factcheck.resolve",
"label": "位置事实核查兜底",
"label": "位置事实核查单轮研判",
"group": "位置解析",
"version": "2026-05-16.1",
"version": "2026-12-03.3",
"system_prompt": "",
"prompt": "Return exactly one JSON object for the most likely physical location. Use only fact-checkable public knowledge; return null fields rather than guessing when evidence is weak."
"prompt": "严格基于输入的 evidence_items(编号 E1..En)与目标元数据判断物理部署城市与园区,输出严格 JSON 对象,禁止编造坐标或证据列表外的引用;reasoning 与 country_override_reason 必须使用不超过 120 字的简洁简体中文,严禁出现 E1、E6 等内部证据编号。"
},
{
"key": "datasource.mapping",
+24
View File
@@ -1,21 +1,30 @@
from app.api.v1 import card_images
from fastapi import APIRouter
from app.api.v1 import (
actions,
ai,
aircraft,
api_keys,
auth,
cases,
users,
datasource_config,
datasources,
disasters,
docs,
earth,
geofences,
gps_jamming,
incidents,
client_updates,
tasks,
dashboard,
alerts,
settings,
collected_data,
cloud_analysis,
compute_intelligence,
data_ledger,
data_products,
layers,
visualization,
@@ -23,11 +32,14 @@ from app.api.v1 import (
vessels,
bgp,
news,
ontology,
interactables,
realtime_sources,
replay,
situational_awareness,
system_control,
tv,
wind_analysis,
)
api_router = APIRouter()
@@ -40,6 +52,7 @@ api_router.include_router(
)
api_router.include_router(datasources.router, prefix="/datasources", tags=["datasources"])
api_router.include_router(collected_data.router, prefix="/collected", tags=["collected-data"])
api_router.include_router(data_ledger.router, prefix="/data-ledger", tags=["data-ledger"])
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"])
@@ -50,6 +63,8 @@ api_router.include_router(settings.router, prefix="/settings", tags=["settings"]
api_router.include_router(system_control.router, prefix="/system", tags=["system"])
api_router.include_router(api_keys.router, prefix="/system/api-keys", tags=["api-keys"])
api_router.include_router(data_products.router, prefix="/data-products", tags=["data-products"])
api_router.include_router(cloud_analysis.router, prefix="/data-products/clouds", tags=["clouds"])
api_router.include_router(wind_analysis.router, prefix="/data-products/wind", tags=["wind"])
api_router.include_router(compute_intelligence.router, prefix="/data-products/compute", tags=["compute"])
api_router.include_router(
situational_awareness.router,
@@ -64,10 +79,19 @@ api_router.include_router(
tags=["vessel-aggregation"],
)
api_router.include_router(vessels.router, prefix="/vessels", tags=["vessels"])
api_router.include_router(aircraft.router, prefix="/aircraft", tags=["aircraft"])
api_router.include_router(gps_jamming.router, prefix="/gps-jamming", tags=["gps-jamming"])
api_router.include_router(disasters.router, prefix="/disasters", tags=["disasters"])
api_router.include_router(geofences.router, prefix="/geofences", tags=["geofences"])
api_router.include_router(incidents.router, prefix="/incidents", tags=["incidents"])
api_router.include_router(cases.router, prefix="/cases", tags=["cases"])
api_router.include_router(actions.router, prefix="/actions", tags=["actions"])
api_router.include_router(bgp.router, prefix="/bgp", tags=["bgp"])
api_router.include_router(tv.router, prefix="/tv", tags=["tv"])
api_router.include_router(news.router, prefix="/news", tags=["news"])
api_router.include_router(ontology.router, prefix="/ontology", tags=["ontology"])
api_router.include_router(interactables.router, prefix="/interactables", tags=["interactables"])
api_router.include_router(realtime_sources.router, prefix="/realtime-sources", tags=["realtime-sources"])
api_router.include_router(replay.router, prefix="/replay", tags=["replay"])
api_router.include_router(card_images.router, prefix="/earth/card-images", tags=["card-images"])
+182
View File
@@ -0,0 +1,182 @@
"""Action Requests, Approval Matrix & Webhook Allowlist API (§4.5)."""
from __future__ import annotations
from typing import Any
from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import BaseModel, Field
from sqlalchemy import desc, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.access_gate import get_current_user, require_admin_user, require_earth_or_api_access
from app.core.enums import UserRole
from app.db.session import get_db
from app.models.action_request import ActionRequest
from app.models.system_setting import SystemSetting
from app.models.user import User
from app.services.actions import (
ACTION_TYPE_REGISTRY,
WEBHOOK_ALLOWLIST_CATEGORY,
WEBHOOK_ALLOWLIST_KEY,
ActionPermissionError,
ActionValidationError,
decide_action_request,
get_webhook_allowlist,
submit_action_request,
)
router = APIRouter()
_read_dep = Depends(require_earth_or_api_access("visualization:read"))
class ActionCreateBody(BaseModel):
action_type: str = Field(min_length=1, max_length=80)
target_object_ids: list[str] = Field(default_factory=list)
params: dict[str, Any] = Field(default_factory=dict)
source_workflow_run_id: str | None = None
ai_suggested: bool = False
class ActionDecisionBody(BaseModel):
decision_reason: str = Field(default="", max_length=1000)
class AllowlistUpdateBody(BaseModel):
urls: list[str] = Field(default_factory=list)
@router.get("/types", dependencies=[_read_dep])
async def list_action_types() -> dict[str, Any]:
return {"items": list(ACTION_TYPE_REGISTRY.values())}
@router.get("/webhook-allowlist")
async def read_webhook_allowlist(
db: AsyncSession = Depends(get_db),
_admin: User = Depends(require_admin_user),
) -> dict[str, Any]:
return {"urls": await get_webhook_allowlist(db)}
@router.put("/webhook-allowlist")
async def update_webhook_allowlist(
body: AllowlistUpdateBody,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(require_admin_user),
) -> dict[str, Any]:
if str(getattr(current_user, "role", "")).lower() != UserRole.SUPER_ADMIN.value:
raise HTTPException(status_code=403, detail="Only super_admin can update webhook allowlist")
cleaned = [str(u).strip() for u in body.urls if str(u).strip()]
row = (
await db.execute(
select(SystemSetting).where(SystemSetting.category == WEBHOOK_ALLOWLIST_CATEGORY)
)
).scalars().first()
if row is None:
row = SystemSetting(
category=WEBHOOK_ALLOWLIST_CATEGORY,
payload={WEBHOOK_ALLOWLIST_KEY: cleaned},
)
db.add(row)
else:
row.payload = {**dict(row.payload or {}), WEBHOOK_ALLOWLIST_KEY: cleaned}
await db.commit()
return {"urls": cleaned}
@router.get("", dependencies=[_read_dep])
async def list_action_requests(
object_id: str | None = Query(default=None),
status: str | None = Query(default=None),
limit: int = Query(default=100, ge=1, le=500),
db: AsyncSession = Depends(get_db),
) -> dict[str, Any]:
stmt = select(ActionRequest).order_by(desc(ActionRequest.requested_at), desc(ActionRequest.id)).limit(limit)
if status:
stmt = stmt.where(ActionRequest.status == status.strip())
rows = list((await db.execute(stmt)).scalars().all())
items = [r.to_dict() for r in rows]
if object_id:
oid = object_id.strip()
items = [it for it in items if oid in (it.get("target_object_ids") or [])]
return {"items": items, "count": len(items)}
@router.post("")
async def create_action_request(
body: ActionCreateBody,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(get_current_user),
) -> dict[str, Any]:
try:
req = await submit_action_request(
db,
action_type=body.action_type.strip(),
target_object_ids=body.target_object_ids,
params=body.params,
actor_id=getattr(current_user, "id", None),
actor_name=str(getattr(current_user, "username", "") or "unknown"),
actor_role=str(getattr(current_user, "role", "") or "viewer"),
source_workflow_run_id=body.source_workflow_run_id,
ai_suggested=bool(body.ai_suggested),
)
return req.to_dict()
except ActionPermissionError as exc:
raise HTTPException(status_code=403, detail=str(exc)) from exc
except ActionValidationError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
@router.post("/{action_id}/approve")
async def approve_action_request(
action_id: int,
body: ActionDecisionBody,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(require_admin_user),
) -> dict[str, Any]:
req = await db.get(ActionRequest, action_id)
if req is None:
raise HTTPException(status_code=404, detail="Action request not found")
try:
updated = await decide_action_request(
db,
req=req,
decision="approve",
decision_reason=body.decision_reason,
actor_id=getattr(current_user, "id", None),
actor_name=str(getattr(current_user, "username", "") or "admin"),
actor_role=str(getattr(current_user, "role", "") or "admin"),
)
return updated.to_dict()
except ActionPermissionError as exc:
raise HTTPException(status_code=403, detail=str(exc)) from exc
except ActionValidationError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
@router.post("/{action_id}/reject")
async def reject_action_request(
action_id: int,
body: ActionDecisionBody,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(require_admin_user),
) -> dict[str, Any]:
req = await db.get(ActionRequest, action_id)
if req is None:
raise HTTPException(status_code=404, detail="Action request not found")
try:
updated = await decide_action_request(
db,
req=req,
decision="reject",
decision_reason=body.decision_reason,
actor_id=getattr(current_user, "id", None),
actor_name=str(getattr(current_user, "username", "") or "admin"),
actor_role=str(getattr(current_user, "role", "") or "admin"),
)
return updated.to_dict()
except ActionPermissionError as exc:
raise HTTPException(status_code=403, detail=str(exc)) from exc
except ActionValidationError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
+10 -35
View File
@@ -63,12 +63,8 @@ from app.services.ai_client import get_ai_provider_client
from app.services.alert_ai_brief import build_alert_brief_request
from app.services.bgp_ai_brief import build_bgp_brief_request
from app.services.compute_center_locations import build_compute_center_location_query
from app.services.location.agent_resolver import (
run_controlled_location_agent,
run_l1_structured_facility_resolvers,
)
from app.services.location.workflow_tools import run_location_workflow
from app.services.situational_alert_ai_brief import build_situational_alert_brief_request
from app.api.v1.settings import get_web_search_client
router = APIRouter()
logger = get_logger(__name__, service="ai_workflows")
@@ -701,41 +697,20 @@ async def _resolve_playground_slash_or_workflow(
active_wf = "location.resolve_unknown"
target_name = trimmed[len("/locate") :].strip() or "Unknown Facility"
query = build_compute_center_location_query(name=target_name)
l1_candidates, _, _ = await run_l1_structured_facility_resolvers(query, db=db)
tool_trace.extend(["l0_normalize", "l1_knowledge"])
if l1_candidates:
c0 = l1_candidates[0]
extra_meta["direct_reply"] = (
f"已通过 **L1 设施知识库** (`{c0.source}`) 定位到 **{c0.display_name}**:\n\n"
f"- 国家/地区:{c0.country or '-'}\n"
f"- 坐标:`{c0.latitude:.5f}, {c0.longitude:.5f}`(精度 `{c0.precision}`,置信度 `{c0.confidence:.2f}`)\n"
f"- 说明:{c0.source_note}"
)
return active_wf, tool_trace, None, extra_meta
try:
provider_client = await get_ai_provider_client(db)
web_search_client = await get_web_search_client(db)
res, term = await run_controlled_location_agent(
provider_client=provider_client,
web_search_client=web_search_client,
res = await run_location_workflow(
db=db,
query=query,
entity_type="compute_center",
db=db,
earth_context=earth_context if isinstance(earth_context, dict) else {},
use_draft=use_draft,
record_run=False,
trigger_evolution=False,
)
tool_trace.extend(["l2_agent_research", "l3_geo_guardrail"])
if res.candidates:
c0 = res.candidates[0]
extra_meta["direct_reply"] = (
f"已通过 **L2/L3 位置 Agent** 核验 **{c0.display_name}**:\n\n"
f"- 坐标:`{c0.latitude:.5f}, {c0.longitude:.5f}`(精度 `{c0.precision}`)\n"
f"- 结论:{c0.source_note}"
)
elif term:
extra_meta["direct_reply"] = f"位置 Agent 判定该目标属于终态 `{term}`:{res.failure_reason or ''}"
else:
extra_meta["direct_reply"] = f"未能定位目标「{target_name}」:{res.failure_reason or '暂无可核验公开证据'}。"
tool_trace.extend(res.get("tool_trace") or ["l0_normalize"])
extra_meta["direct_reply"] = res.get("answer_markdown") or f"未能定位目标「{target_name}」。"
except Exception as exc:
extra_meta["direct_reply"] = f"位置 Agent 调试执行失败:{exc}"
extra_meta["direct_reply"] = f"位置工作流调试执行失败:{exc}"
extra_meta["direct_reply_error"] = str(exc)
return active_wf, tool_trace, None, extra_meta
+226
View File
@@ -0,0 +1,226 @@
"""Aircraft ADS-B columnar snapshot, detail, and track APIs."""
from __future__ import annotations
from datetime import UTC, datetime, timedelta
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy import desc, or_, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.api.v1.visualization import _parse_bbox
from app.core.access_gate import require_earth_or_api_access
from app.core.time import to_iso8601_utc
from app.db.session import get_db
from app.models.aircraft import (
ADSBSourceHealth,
AircraftCurrentState,
AircraftPosition,
AircraftStatic,
)
from app.services.aircraft_aggregation import coerce_utc_datetime
from app.services.aircraft_types import normalize_icao24
router = APIRouter()
AIRCRAFT_FRESHNESS_SECONDS = 300
MAX_AIRCRAFT_SNAPSHOT_LIMIT = 20000
AIRCRAFT_ATTRIBUTION = "adsb.lol (ODbL) · OpenSky Network (Non-Commercial / Research)"
SNAPSHOT_FIELDS: tuple[str, ...] = (
"icao24",
"callsign",
"lat",
"lon",
"altitude_m",
"ground_speed_ms",
"track_deg",
"vertical_rate_ms",
"category",
"is_military",
"is_emergency",
"emergency_code",
"on_ground",
"source",
"observed_at",
)
@router.get("/snapshot", dependencies=[Depends(require_earth_or_api_access("aircraft:read"))])
async def get_aircraft_snapshot(
bbox: Optional[str] = Query(None, description="Optional bbox as lon_min,lat_min,lon_max,lat_max"),
category: Optional[str] = Query(None, description="Comma-separated aircraft categories"),
include_ground: bool = Query(False, description="Include aircraft reported on ground"),
limit: int = Query(10000, ge=1, le=MAX_AIRCRAFT_SNAPSHOT_LIMIT),
since_minutes: int = Query(15, ge=1, le=1440),
db: AsyncSession = Depends(get_db),
):
now = datetime.now(UTC)
cutoff = now - timedelta(minutes=since_minutes)
stmt = select(AircraftCurrentState).where(AircraftCurrentState.observed_at >= cutoff)
if not include_ground:
stmt = stmt.where(AircraftCurrentState.on_ground.is_(False))
if bbox:
parsed = _parse_bbox(bbox)
if parsed is None:
raise HTTPException(status_code=400, detail="Invalid bbox parameter")
lon_min, lat_min, lon_max, lat_max = parsed
stmt = stmt.where(
AircraftCurrentState.lat >= lat_min,
AircraftCurrentState.lat <= lat_max,
)
if lon_min <= lon_max:
stmt = stmt.where(
AircraftCurrentState.lon >= lon_min,
AircraftCurrentState.lon <= lon_max,
)
else:
stmt = stmt.where(
or_(
AircraftCurrentState.lon >= lon_min,
AircraftCurrentState.lon <= lon_max,
)
)
if category:
categories = [part.strip().lower() for part in category.split(",") if part.strip()]
if categories:
stmt = stmt.where(AircraftCurrentState.category.in_(categories))
stmt = stmt.order_by(
desc(AircraftCurrentState.is_emergency),
desc(AircraftCurrentState.is_military),
desc(AircraftCurrentState.observed_at),
).limit(limit)
result = await db.execute(stmt)
records = list(result.scalars().all())
rows: list[list[object]] = []
for rec in records:
alt_m = rec.geo_altitude_m if rec.geo_altitude_m is not None else rec.baro_altitude_m
rows.append(
[
rec.icao24,
rec.callsign,
round(float(rec.lat), 5),
round(float(rec.lon), 5),
round(float(alt_m), 1) if alt_m is not None else None,
round(float(rec.ground_speed_ms), 2) if rec.ground_speed_ms is not None else None,
round(float(rec.track_deg), 1) if rec.track_deg is not None else None,
round(float(rec.vertical_rate_ms), 2) if rec.vertical_rate_ms is not None else None,
rec.category,
bool(rec.is_military),
bool(rec.is_emergency),
rec.emergency_code,
bool(rec.on_ground),
rec.source,
to_iso8601_utc(rec.observed_at),
]
)
health_res = await db.execute(select(ADSBSourceHealth))
source_health = {item.source: item.to_dict() for item in health_res.scalars().all()}
return {
"fields": list(SNAPSHOT_FIELDS),
"rows": rows,
"generated_at": to_iso8601_utc(now),
"source_health": source_health,
"attribution": AIRCRAFT_ATTRIBUTION,
}
@router.get("/{icao24}/track", dependencies=[Depends(require_earth_or_api_access("aircraft:read"))])
async def get_aircraft_track(
icao24: str,
hours: float = Query(3.0, ge=0.25, le=48.0),
db: AsyncSession = Depends(get_db),
):
norm_icao = normalize_icao24(icao24)
now = datetime.now(UTC)
cutoff = now - timedelta(hours=hours)
res = await db.execute(
select(AircraftPosition)
.where(AircraftPosition.icao24 == norm_icao)
.where(AircraftPosition.observed_at >= cutoff)
.order_by(AircraftPosition.observed_at.asc(), AircraftPosition.id.asc())
.limit(2000)
)
pts = list(res.scalars().all())
current = await db.get(AircraftCurrentState, norm_icao)
points = [
{
"lat": round(float(pt.lat), 5),
"lon": round(float(pt.lon), 5),
"altitude_m": pt.altitude_m,
"ground_speed_ms": pt.ground_speed_ms,
"track_deg": pt.track_deg,
"observed_at": to_iso8601_utc(pt.observed_at),
}
for pt in pts
]
if current is not None and not points:
points.append(
{
"lat": round(float(current.lat), 5),
"lon": round(float(current.lon), 5),
"altitude_m": current.geo_altitude_m if current.geo_altitude_m is not None else current.baro_altitude_m,
"ground_speed_ms": current.ground_speed_ms,
"track_deg": current.track_deg,
"observed_at": to_iso8601_utc(current.observed_at),
}
)
obs_at = current.observed_at if current is not None else (pts[-1].observed_at if pts else None)
ingested_at = current.ingested_at if current is not None else None
is_stale = True
if obs_at is not None:
is_stale = (now - coerce_utc_datetime(obs_at)).total_seconds() > AIRCRAFT_FRESHNESS_SECONDS
return {
"icao24": norm_icao,
"hours": hours,
"points": points,
"source": current.source if current is not None else "aircraft_position",
"observed_at": to_iso8601_utc(obs_at),
"ingested_at": to_iso8601_utc(ingested_at),
"is_stale": is_stale,
}
@router.get("/{icao24}", dependencies=[Depends(require_earth_or_api_access("aircraft:read"))])
async def get_aircraft_detail(
icao24: str,
db: AsyncSession = Depends(get_db),
):
norm_icao = normalize_icao24(icao24)
current = await db.get(AircraftCurrentState, norm_icao)
static = await db.get(AircraftStatic, norm_icao)
if current is None and static is None:
raise HTTPException(status_code=404, detail="Aircraft not found")
now = datetime.now(UTC)
obs_at = current.observed_at if current is not None else static.updated_at
ingested_at = current.ingested_at if current is not None else static.updated_at
is_stale = True
if obs_at is not None:
is_stale = (now - coerce_utc_datetime(obs_at)).total_seconds() > AIRCRAFT_FRESHNESS_SECONDS
return {
"icao24": norm_icao,
"current": current.to_dict() if current is not None else None,
"static": static.to_dict() if static is not None else None,
"source": current.source if current is not None else static.source,
"observed_at": to_iso8601_utc(obs_at),
"ingested_at": to_iso8601_utc(ingested_at),
"is_stale": is_stale,
"freshness_threshold_seconds": AIRCRAFT_FRESHNESS_SECONDS,
"attribution": AIRCRAFT_ATTRIBUTION,
}
+2 -1
View File
@@ -528,7 +528,8 @@ async def create_earth_session(
detail="Too many desktop Earth session requests",
)
client_header = await verify_desktop_handshake(request)
token, ttl_seconds = create_earth_session_token("desktop", client_id=client_header)
desktop_client_id = f"{client_ip}:{client_header}"
token, ttl_seconds = create_earth_session_token("desktop", client_id=desktop_client_id)
return {
"token": token,
"expires_in": ttl_seconds,
+48 -52
View File
@@ -15,16 +15,10 @@ from app.models.bgp_observation import BGPObservation
from app.models.user import User
from app.services.bgp_collector_locations import (
build_bgp_collector_location_query,
collect_bgp_collector_location_candidates,
get_bgp_collector_location_dict,
)
from app.services.bgp_collectors import build_bgp_collector_coverage
from app.services.ai_client import get_ai_provider_client
from app.api.v1.settings import get_web_search_client
from app.services.location.llm_fallback import (
collect_llm_location_fallback_candidate,
collect_location_search_evidence,
)
from app.services.location.workflow_tools import run_location_workflow
router = APIRouter()
@@ -307,56 +301,56 @@ async def collect_bgp_collector_location(
city = payload.city or legacy.get("city")
country = payload.country or legacy.get("country")
operator = payload.operator or "RIPE NCC"
candidates, attempted_queries = collect_bgp_collector_location_candidates(
query = build_bgp_collector_location_query(
collector=collector_id,
site=site,
city=city,
country=country,
operator=operator,
)
llm_failure_reason = None
if not candidates:
query = build_bgp_collector_location_query(
collector=collector_id,
site=site,
city=city,
country=country,
operator=operator,
)
llm_result = None
try:
web_search_client = await get_web_search_client(db)
search_result = await collect_location_search_evidence(
web_search_client=web_search_client,
query=query,
entity_type="bgp_collector",
)
attempted_queries = [*attempted_queries, *search_result.attempted_queries]
if not search_result.evidence:
llm_failure_reason = search_result.failure_reason
raise RuntimeError(search_result.failure_reason or "no WebSearch evidence")
provider_client = await get_ai_provider_client(db)
llm_result = await collect_llm_location_fallback_candidate(
provider_client=provider_client,
query=query,
entity_type="bgp_collector",
db=db,
attempted_queries=attempted_queries,
search_evidence=search_result.evidence,
)
except Exception as exc:
if llm_failure_reason is None:
llm_failure_reason = f"LLM location factcheck unavailable: {exc}"
attempted_queries = [
*attempted_queries,
f"llm_factcheck:bgp_collector:{collector_id or 'unknown'}",
]
if llm_result is not None:
attempted_queries = [*attempted_queries, *llm_result.attempted_queries]
candidates = llm_result.candidates
llm_failure_reason = llm_result.failure_reason
try:
res = await run_location_workflow(
db=db,
query=query,
entity_type="bgp_collector",
earth_context={
"collector_id": collector_id,
"name": collector_id,
"site": site,
"city": city,
"country": country,
"operator": operator,
},
record_run=True,
trigger_evolution=True,
)
except Exception as exc:
return {
"collector_id": collector_id,
"name": collector_id,
"success": False,
"failure_reason": (
"No source coordinates or online geocoding result reached"
" city-level precision for this collector."
),
"candidates": [],
"attempted_queries": [],
"llm_failure_reason": f"Location workflow unavailable: {exc}",
"workflow_run_id": None,
"context": {
"collector": collector_id,
"site": site,
"city": city,
"country": country,
"operator": operator,
},
}
candidates = res.get("candidates") or []
attempted_queries = list(res.get("attempted_queries") or [])
llm_failure_reason = res.get("failure_reason")
workflow_run_id = res.get("workflow_run_id")
context = {
"collector": collector_id,
"site": site,
@@ -375,8 +369,9 @@ async def collect_bgp_collector_location(
" city-level precision for this collector."
),
"candidates": [],
"attempted_queries": list(attempted_queries),
"attempted_queries": attempted_queries,
"llm_failure_reason": llm_failure_reason,
"workflow_run_id": workflow_run_id,
"context": context,
}
@@ -386,7 +381,8 @@ async def collect_bgp_collector_location(
"success": True,
"candidates": [candidate.to_dict() for candidate in candidates],
"best_candidate": candidates[0].to_dict(),
"attempted_queries": list(attempted_queries),
"attempted_queries": attempted_queries,
"workflow_run_id": workflow_run_id,
"context": context,
}
+75 -4
View File
@@ -1,6 +1,9 @@
"""Card-image configuration, upload, catalog selection and public resolution."""
from fastapi import APIRouter, Depends, File, HTTPException, Query, Response, UploadFile
import hashlib
import json
from fastapi import APIRouter, Depends, File, HTTPException, Query, Request, Response, UploadFile
from fastapi.responses import FileResponse
from sqlalchemy.ext.asyncio import AsyncSession
from starlette.concurrency import run_in_threadpool
@@ -28,6 +31,28 @@ from app.services.card_image_targets import get_target, search_targets
router = APIRouter()
def _etag_matches(if_none_match: str | None, etag: str) -> bool:
if not if_none_match:
return False
target = etag.strip()
if target.startswith("W/"):
target = 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 == target:
return True
return False
def _stable_fingerprint(payload: object) -> str:
raw = json.dumps(payload, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:24]
async def image_admin(user: User = Depends(get_current_user)) -> User:
if user.role not in {UserRole.ADMIN.value, UserRole.SUPER_ADMIN.value}:
raise HTTPException(403, "Administrator access required")
@@ -58,7 +83,14 @@ async def upload_image(file: UploadFile = File(...), _actor: User = Depends(imag
return await run_in_threadpool(store_image, content, (file.filename or "Image")[:200])
@router.get("/files/{filename}", dependencies=[Depends(require_earth_or_api_access("earth:read", allow_query_api_key=True))])
@router.get(
"/files/{filename}",
dependencies=[Depends(require_earth_or_api_access("earth:read", allow_query_api_key=True, rate_limit_tier="tile"))],
)
@router.head(
"/files/{filename}",
dependencies=[Depends(require_earth_or_api_access("earth:read", allow_query_api_key=True, rate_limit_tier="tile"))],
)
async def image_file(filename: str):
path = uploaded_path(filename)
if not path.is_file():
@@ -84,19 +116,58 @@ async def targets(
return {"items": await search_targets(db, entity_type, scope, q.strip(), limit)}
@router.get("/fingerprint", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
async def fingerprint(
request: Request,
response: Response,
db: AsyncSession = Depends(get_db),
):
envelope = await read_configuration(db)
revision = str(envelope["revision"])
etag = f'"{_stable_fingerprint({"revision": revision})}"'
headers = {
"Cache-Control": "private, no-cache",
"ETag": etag,
}
if _etag_matches(request.headers.get("if-none-match"), etag):
return Response(status_code=304, headers=headers)
response.headers.update(headers)
return {"revision": revision}
@router.get("/resolve", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
async def resolve(
request: Request,
response: Response,
entity_type: EntityType,
entity_id: str = Query(min_length=1, max_length=300),
db: AsyncSession = Depends(get_db),
):
response.headers["Cache-Control"] = "no-store"
envelope = await read_configuration(db)
config = CardImageConfiguration.model_validate(envelope["config"])
context = await get_target(db, entity_type, entity_id)
result = resolve_image(config, context)
return {**result, "revision": envelope["revision"], "entity": context}
fp = _stable_fingerprint(
{
"revision": envelope["revision"],
"suppressed": bool(result.get("suppressed")),
"image": result.get("image"),
}
)
etag = f'"{fp}"'
headers = {
"Cache-Control": "private, no-cache",
"ETag": etag,
}
if _etag_matches(request.headers.get("if-none-match"), etag):
return Response(status_code=304, headers=headers)
response.headers.update(headers)
return {
**result,
"revision": envelope["revision"],
"fingerprint": fp,
"entity": context,
}
@router.post("/preview")
+209
View File
@@ -0,0 +1,209 @@
"""Investigation Case Board API (§4.3)."""
from __future__ import annotations
from typing import Any
from fastapi import APIRouter, Depends, HTTPException, Query
from fastapi.responses import PlainTextResponse
from pydantic import BaseModel, Field
from sqlalchemy import desc, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.access_gate import require_admin_user, require_earth_or_api_access
from app.core.enums import UserRole
from app.db.session import get_db
from app.models.investigation_case import CaseItem, CaseVersion, InvestigationCase
from app.models.user import User
from app.services.investigation_cases import export_case_markdown, freeze_investigation_case
router = APIRouter()
_read_dep = Depends(require_earth_or_api_access("visualization:read"))
_ALLOWED_ITEM_TYPES = frozenset(
{"object", "incident", "evidence", "camera_bookmark", "note", "ai_result", "compute_revision"}
)
class CaseCreateRequest(BaseModel):
title: str = Field(min_length=1, max_length=240)
summary: str = Field(default="", max_length=4000)
is_shared: bool = True
class CaseUpdateRequest(BaseModel):
title: str | None = Field(default=None, min_length=1, max_length=240)
summary: str | None = Field(default=None, max_length=4000)
status: str | None = Field(default=None, max_length=32)
is_shared: bool | None = None
class CaseItemAddRequest(BaseModel):
item_type: str = Field(min_length=1, max_length=48)
ref_id: str = Field(min_length=1, max_length=200)
payload: dict[str, Any] = Field(default_factory=dict)
def _is_admin(user: User | Any) -> bool:
role = str(getattr(user, "role", "") or "").lower()
return role in {UserRole.ADMIN.value, UserRole.SUPER_ADMIN.value}
async def _load_accessible_case(db: AsyncSession, case_id: int, user: User | Any) -> InvestigationCase:
case = await db.get(InvestigationCase, case_id)
if case is None:
raise HTTPException(status_code=404, detail="Investigation case not found")
if not _is_admin(user) and not case.is_shared:
raise HTTPException(status_code=403, detail="This investigation case is not shared")
return case
@router.get("")
async def list_cases(
status: str | None = Query(default=None),
limit: int = Query(default=50, ge=1, le=200),
db: AsyncSession = Depends(get_db),
current_user: User = Depends(require_earth_or_api_access("visualization:read")),
) -> dict[str, Any]:
stmt = select(InvestigationCase).order_by(desc(InvestigationCase.updated_at), desc(InvestigationCase.id)).limit(limit)
if not _is_admin(current_user):
stmt = stmt.where(InvestigationCase.is_shared.is_(True))
if status:
stmt = stmt.where(InvestigationCase.status == status.strip())
rows = list((await db.execute(stmt)).scalars().all())
return {"items": [r.to_dict() for r in rows], "count": len(rows)}
@router.post("")
async def create_case(
body: CaseCreateRequest,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(require_admin_user),
) -> dict[str, Any]:
case = InvestigationCase(
title=body.title.strip(),
summary=body.summary.strip(),
status="draft",
owner_id=int(getattr(current_user, "id", 0) or 0),
owner_name=str(getattr(current_user, "username", "") or "admin"),
is_shared=bool(body.is_shared),
)
db.add(case)
await db.commit()
await db.refresh(case)
return case.to_dict()
@router.get("/{case_id}")
async def get_case_detail(
case_id: int,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(require_earth_or_api_access("visualization:read")),
) -> dict[str, Any]:
case = await _load_accessible_case(db, case_id, current_user)
items = list(
(await db.execute(select(CaseItem).where(CaseItem.case_id == case.id).order_by(CaseItem.id.asc())))
.scalars()
.all()
)
versions = list(
(await db.execute(select(CaseVersion).where(CaseVersion.case_id == case.id).order_by(desc(CaseVersion.version))))
.scalars()
.all()
)
return {
"case": case.to_dict(),
"items": [i.to_dict() for i in items],
"versions": [v.to_dict() for v in versions],
}
@router.patch("/{case_id}")
async def update_case(
case_id: int,
body: CaseUpdateRequest,
db: AsyncSession = Depends(get_db),
_admin: User = Depends(require_admin_user),
) -> dict[str, Any]:
case = await db.get(InvestigationCase, case_id)
if case is None:
raise HTTPException(status_code=404, detail="Investigation case not found")
if body.title is not None:
case.title = body.title.strip()
if body.summary is not None:
case.summary = body.summary.strip()
if body.status is not None and body.status in {"draft", "in_review", "frozen", "closed"}:
case.status = body.status
if body.is_shared is not None:
case.is_shared = bool(body.is_shared)
await db.commit()
await db.refresh(case)
return case.to_dict()
@router.post("/{case_id}/items")
async def add_case_item(
case_id: int,
body: CaseItemAddRequest,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(require_admin_user),
) -> dict[str, Any]:
case = await db.get(InvestigationCase, case_id)
if case is None:
raise HTTPException(status_code=404, detail="Investigation case not found")
if case.status == "closed":
raise HTTPException(status_code=409, detail="Closed cases cannot receive new items")
itype = body.item_type.strip().lower()
if itype not in _ALLOWED_ITEM_TYPES:
raise HTTPException(status_code=422, detail=f"Unsupported case item_type: {itype}")
item = CaseItem(
case_id=case.id,
item_type=itype,
ref_id=body.ref_id.strip(),
payload=dict(body.payload or {}),
added_by=str(getattr(current_user, "username", "") or "admin"),
)
db.add(item)
await db.commit()
await db.refresh(item)
return item.to_dict()
@router.post("/{case_id}/freeze")
async def freeze_case(
case_id: int,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(require_admin_user),
) -> dict[str, Any]:
case = await db.get(InvestigationCase, case_id)
if case is None:
raise HTTPException(status_code=404, detail="Investigation case not found")
ver = await freeze_investigation_case(
db, case, frozen_by=str(getattr(current_user, "username", "") or "admin")
)
return {"case": case.to_dict(), "version": ver.to_dict()}
@router.get("/{case_id}/export/markdown")
async def export_case_as_markdown(
case_id: int,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(require_earth_or_api_access("visualization:read")),
) -> PlainTextResponse:
case = await _load_accessible_case(db, case_id, current_user)
items = list(
(await db.execute(select(CaseItem).where(CaseItem.case_id == case.id).order_by(CaseItem.id.asc())))
.scalars()
.all()
)
versions = list(
(await db.execute(select(CaseVersion).where(CaseVersion.case_id == case.id).order_by(desc(CaseVersion.version))))
.scalars()
.all()
)
md = export_case_markdown(case, items, versions)
return PlainTextResponse(
md,
media_type="text/markdown; charset=utf-8",
headers={"Content-Disposition": f'attachment; filename="case-{case.id}.md"'},
)
+56
View File
@@ -0,0 +1,56 @@
"""Real-time cloud map spatial analytics & asset correlation APIs."""
from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import BaseModel, Field
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.access_gate import require_earth_or_api_access
from app.core.security import get_current_user
from app.db.session import get_db
from app.models.user import User
from app.services.earth_clouds import (
correlate_cloud_with_assets,
get_cloud_analysis_summary,
query_cloud_point,
)
router = APIRouter()
class CloudAssetCorrelateRequest(BaseModel):
domain: str = Field(default="vessels")
min_density: float = Field(default=55.0, ge=0.0, le=100.0)
limit: int = Field(default=25, ge=1, le=100)
@router.get("/summary", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
async def get_clouds_summary(db: AsyncSession = Depends(get_db)):
return await get_cloud_analysis_summary(db)
@router.get("/point", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
async def get_clouds_point(
lat: float = Query(..., ge=-90.0, le=90.0),
lon: float = Query(..., ge=-180.0, le=180.0),
db: AsyncSession = Depends(get_db),
):
return await query_cloud_point(lat, lon, db=db)
@router.post("/correlate")
async def post_clouds_correlate(
payload: CloudAssetCorrelateRequest,
_current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
try:
return await correlate_cloud_with_assets(
db,
domain=payload.domain,
min_density=payload.min_density,
limit=payload.limit,
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
+279 -157
View File
@@ -1,23 +1,32 @@
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query, status, Response
from fastapi.responses import StreamingResponse
from sqlalchemy import select, func, text
from sqlalchemy.ext.asyncio import AsyncSession
import json
import csv
import hashlib
import io
import json
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query, status
from fastapi.responses import StreamingResponse
from sqlalchemy import select, text
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.cache import cache
from app.core.collected_data_fields import get_metadata_field
from app.core.countries import COUNTRY_OPTIONS, get_country_search_variants, normalize_country
from app.core.security import get_current_user
from app.core.time import to_iso8601_utc
from app.db.session import get_db
from app.models.user import User
from app.core.security import get_current_user
from app.models.collected_data import CollectedData
from app.models.datasource import DataSource
from app.models.user import User
router = APIRouter()
DEFAULT_EXCLUDED_DATA_TYPES: tuple[str, ...] = ("prefix_geography",)
DEFAULT_EXCLUDED_SOURCES: frozenset[str] = frozenset(
{"iptoasn_prefix_geo", "opengeofeed_prefix_geo", "nro_delegated_prefix_geo"}
)
COLLECTED_FACETS_CACHE_KEY = "collected:facets:v1"
COLLECTED_FACETS_TTL_SECONDS = 300
COLLECTED_SUMMARY_TTL_SECONDS = 60
COUNTRY_SQL = "metadata->>'country'"
SEARCHABLE_SQL = [
@@ -46,6 +55,50 @@ def build_in_condition(field_sql: str, values: list[str], param_prefix: str, par
return f"{field_sql} IN ({', '.join(placeholders)})"
def build_not_in_condition(field_sql: str, values: tuple[str, ...], param_prefix: str, params: dict) -> str:
placeholders = []
for index, value in enumerate(values):
key = f"{param_prefix}_{index}"
params[key] = value
placeholders.append(f":{key}")
return f"{field_sql} NOT IN ({', '.join(placeholders)})"
def _includes_default_excluded(source_values: list[str], data_type_values: list[str]) -> bool:
if any(dt in DEFAULT_EXCLUDED_DATA_TYPES for dt in data_type_values):
return True
if any(src in DEFAULT_EXCLUDED_SOURCES for src in source_values):
return True
return False
def _facets_cache_key(mode: str) -> str:
return COLLECTED_FACETS_CACHE_KEY if mode != "history" else f"{COLLECTED_FACETS_CACHE_KEY}:history"
def _summary_cache_key(
*,
mode: str,
source: Optional[str],
data_type: Optional[str],
country: Optional[str],
search: Optional[str],
) -> str:
payload = json.dumps(
{
"mode": "history" if mode == "history" else "current",
"source": source or "",
"data_type": data_type or "",
"country": country or "",
"search": (search or "").strip(),
},
sort_keys=True,
ensure_ascii=False,
)
digest = hashlib.sha256(payload.encode("utf-8")).hexdigest()[:24]
return f"collected:summary:v1:{digest}"
def build_search_condition(search: Optional[str], params: dict) -> Optional[str]:
if not search:
return None
@@ -108,7 +161,14 @@ def serialize_collected_row(
*,
include_metadata: bool = True,
) -> dict:
metadata = row[7]
raw_metadata = row[7]
if isinstance(raw_metadata, str):
try:
metadata = json.loads(raw_metadata)
except json.JSONDecodeError:
metadata = None
else:
metadata = raw_metadata
source = row[1]
return {
"id": row[0],
@@ -141,6 +201,43 @@ async def get_source_name_map(db: AsyncSession) -> dict[str, str]:
return {row[0]: row[1] for row in result.fetchall()}
async def _load_collected_facets(
db: AsyncSession,
*,
mode: str,
source_name_map: dict[str, str] | None = None,
) -> list[dict]:
cache_key = _facets_cache_key(mode)
cached_facets = cache.get(cache_key)
if isinstance(cached_facets, list):
return cached_facets
where_sql = "is_current IS TRUE" if mode != "history" else "1=1"
result = await db.execute(
text(
f"""
SELECT source, data_type, COUNT(*) AS count
FROM collected_data
WHERE {where_sql}
GROUP BY source, data_type
ORDER BY source, data_type
"""
)
)
names = source_name_map if source_name_map is not None else await get_source_name_map(db)
facets = [
{
"source": row[0],
"source_name": names.get(row[0], row[0]),
"data_type": row[1],
"count": int(row[2] or 0),
}
for row in result.fetchall()
]
cache.set(cache_key, facets, expire_seconds=COLLECTED_FACETS_TTL_SECONDS)
return facets
@router.get("")
async def list_collected_data(
mode: str = Query("current", description="查询模式: current/history"),
@@ -155,55 +252,64 @@ async def list_collected_data(
db: AsyncSession = Depends(get_db),
):
"""查询采集的数据列表"""
normalized_country = normalize_country(country) if country else None
source_values = parse_multi_values(source)
data_type_values = parse_multi_values(data_type)
# Build WHERE clause
conditions = []
params = {}
if mode != "history":
conditions.append("COALESCE(is_current, TRUE) = TRUE")
if source_values:
conditions.append(build_in_condition("source", source_values, "source", params))
if data_type_values:
conditions.append(build_in_condition("data_type", data_type_values, "data_type", params))
if normalized_country:
conditions.append(f"{COUNTRY_SQL} = :country")
params["country"] = normalized_country
search_condition = build_search_condition(search, params)
if search_condition:
conditions.append(search_condition)
where_sql = " AND ".join(conditions) if conditions else "1=1"
search_rank_sql = build_search_rank_sql(search)
where_sql, params, include_excluded = build_where_clause(
source,
data_type,
country,
search,
mode=mode,
)
has_search = bool(search and search.strip())
# Calculate offset
offset = (page - 1) * page_size
source_name_map = await get_source_name_map(db)
# Query total count
count_query = text(f"SELECT COUNT(*) FROM collected_data WHERE {where_sql}")
count_result = await db.execute(count_query, params)
total = count_result.scalar()
if not country and not has_search:
facets = await _load_collected_facets(db, mode=mode, source_name_map=source_name_map)
source_set = set(parse_multi_values(source))
type_set = set(parse_multi_values(data_type))
total = sum(
item["count"]
for item in facets
if (include_excluded or item["data_type"] not in DEFAULT_EXCLUDED_DATA_TYPES)
and (not source_set or item["source"] in source_set)
and (not type_set or item["data_type"] in type_set)
)
else:
count_query = text(f"SELECT COUNT(*) FROM collected_data WHERE {where_sql}")
count_result = await db.execute(count_query, params)
total = int(count_result.scalar() or 0)
# Query data
query = text(f"""
SELECT id, source, source_id, data_type, name, title, description,
metadata, collected_at, reference_date, is_valid,
{search_rank_sql} AS search_rank
FROM collected_data
WHERE {where_sql}
ORDER BY search_rank DESC, collected_at DESC
LIMIT :limit OFFSET :offset
""")
params["limit"] = page_size
params["offset"] = offset
if has_search:
search_rank_sql = build_search_rank_sql(search)
query = text(
f"""
SELECT id, source, source_id, data_type, name, title, description,
metadata, collected_at, reference_date, is_valid,
{search_rank_sql} AS search_rank
FROM collected_data
WHERE {where_sql}
ORDER BY search_rank DESC, collected_at DESC
LIMIT :limit OFFSET :offset
"""
)
else:
query = text(
f"""
SELECT id, source, source_id, data_type, name, title, description,
metadata, collected_at, reference_date, is_valid
FROM collected_data
WHERE {where_sql}
ORDER BY collected_at DESC
LIMIT :limit OFFSET :offset
"""
)
result = await db.execute(query, params)
rows = result.fetchall()
source_name_map = await get_source_name_map(db)
data = []
for row in rows:
@@ -217,6 +323,40 @@ async def list_collected_data(
}
def _aggregate_summary_from_facets(facets: list[dict], *, overall_total: int) -> dict:
by_source: dict[str, dict[str, int]] = {}
source_acc: dict[str, dict] = {}
type_acc: dict[str, int] = {}
total = 0
for item in facets:
src = str(item["source"])
src_name = str(item.get("source_name") or src)
dt = str(item["data_type"])
cnt = int(item["count"] or 0)
if cnt <= 0:
continue
by_source.setdefault(src_name, {})[dt] = by_source.get(src_name, {}).get(dt, 0) + cnt
if src not in source_acc:
source_acc[src] = {"source": src, "source_name": src_name, "count": 0}
source_acc[src]["count"] += cnt
type_acc[dt] = type_acc.get(dt, 0) + cnt
total += cnt
source_totals = sorted(source_acc.values(), key=lambda x: (-x["count"], x["source"]))
type_totals = [
{"data_type": dt, "count": cnt}
for dt, cnt in sorted(type_acc.items(), key=lambda item: (-item[1], item[0]))
]
return {
"total_records": total,
"overall_total_records": overall_total,
"by_source": by_source,
"source_totals": source_totals,
"type_totals": type_totals,
}
@router.get("/summary")
async def get_data_summary(
mode: str = Query("current", description="查询模式: current/history"),
@@ -228,89 +368,76 @@ async def get_data_summary(
db: AsyncSession = Depends(get_db),
):
"""获取数据汇总统计"""
where_sql, params = build_where_clause(source, data_type, country, search)
if mode != "history":
where_sql = f"({where_sql}) AND COALESCE(is_current, TRUE) = TRUE"
overall_where_sql = "COALESCE(is_current, TRUE) = TRUE" if mode != "history" else "1=1"
overall_total_result = await db.execute(
text(f"SELECT COUNT(*) FROM collected_data WHERE {overall_where_sql}")
cache_key = _summary_cache_key(
mode=mode,
source=source,
data_type=data_type,
country=country,
search=search,
)
overall_total = overall_total_result.scalar() or 0
cached_summary = cache.get(cache_key)
if isinstance(cached_summary, dict):
return cached_summary
# By source and data_type
result = await db.execute(
text(f"""
SELECT source, data_type, COUNT(*) as count
FROM collected_data
WHERE {where_sql}
GROUP BY source, data_type
ORDER BY source, data_type
"""),
params,
)
rows = result.fetchall()
source_name_map = await get_source_name_map(db)
by_source = {}
total = 0
for row in rows:
source = row[0]
data_type = row[1]
count = row[2]
source_key = source_name_map.get(source, source)
if source_key not in by_source:
by_source[source_key] = {}
by_source[source_key][data_type] = count
total += count
# Total by source
source_totals = await db.execute(
text(f"""
SELECT source, COUNT(*) as count
FROM collected_data
WHERE {where_sql}
GROUP BY source
ORDER BY count DESC
"""),
params,
unfiltered_facets = await _load_collected_facets(
db, mode=mode, source_name_map=source_name_map
)
source_rows = source_totals.fetchall()
type_totals = await db.execute(
text(f"""
SELECT data_type, COUNT(*) as count
FROM collected_data
WHERE {where_sql}
GROUP BY data_type
ORDER BY count DESC, data_type
"""),
params,
source_values = parse_multi_values(source)
data_type_values = parse_multi_values(data_type)
include_excluded = _includes_default_excluded(source_values, data_type_values)
overall_total = sum(
int(item["count"] or 0)
for item in unfiltered_facets
if include_excluded or item["data_type"] not in DEFAULT_EXCLUDED_DATA_TYPES
)
type_rows = type_totals.fetchall()
return {
"total_records": total,
"overall_total_records": overall_total,
"by_source": by_source,
"source_totals": [
normalized_country = normalize_country(country) if country else None
has_search = bool(search and search.strip())
if not normalized_country and not has_search:
source_set = set(source_values)
type_set = set(data_type_values)
filtered_facets = [
item
for item in unfiltered_facets
if (include_excluded or item["data_type"] not in DEFAULT_EXCLUDED_DATA_TYPES)
and (not source_set or item["source"] in source_set)
and (not type_set or item["data_type"] in type_set)
]
else:
where_sql, params, _ = build_where_clause(
source,
data_type,
country,
search,
mode=mode,
)
result = await db.execute(
text(
f"""
SELECT source, data_type, COUNT(*) AS count
FROM collected_data
WHERE {where_sql}
GROUP BY source, data_type
ORDER BY source, data_type
"""
),
params,
)
filtered_facets = [
{
"source": row[0],
"source_name": source_name_map.get(row[0], row[0]),
"count": row[1],
"data_type": row[1],
"count": int(row[2] or 0),
}
for row in source_rows
],
"type_totals": [
{
"data_type": row[0],
"count": row[1],
}
for row in type_rows
],
}
for row in result.fetchall()
]
payload = _aggregate_summary_from_facets(filtered_facets, overall_total=overall_total)
cache.set(cache_key, payload, expire_seconds=COLLECTED_SUMMARY_TTL_SECONDS)
return payload
@router.get("/sources")
@@ -320,21 +447,17 @@ async def get_data_sources(
db: AsyncSession = Depends(get_db),
):
"""获取所有数据源列表"""
result = await db.execute(
text("""
SELECT DISTINCT source FROM collected_data
""" + ("WHERE COALESCE(is_current, TRUE) = TRUE " if mode != "history" else "") + """
ORDER BY source
""")
)
rows = result.fetchall()
source_name_map = await get_source_name_map(db)
facets = await _load_collected_facets(db, mode=mode)
seen: dict[str, str] = {}
for item in facets:
src = str(item["source"])
if src not in seen:
seen[src] = str(item.get("source_name") or src)
return {
"sources": [
{"source": row[0], "source_name": source_name_map.get(row[0], row[0])}
for row in rows
{"source": src, "source_name": seen[src]}
for src in sorted(seen.keys())
],
}
@@ -346,18 +469,10 @@ async def get_data_types(
db: AsyncSession = Depends(get_db),
):
"""获取所有数据类型列表"""
result = await db.execute(
text("""
SELECT DISTINCT data_type FROM collected_data
""" + ("WHERE COALESCE(is_current, TRUE) = TRUE " if mode != "history" else "") + """
ORDER BY data_type
""")
)
rows = result.fetchall()
facets = await _load_collected_facets(db, mode=mode)
types = sorted({str(item["data_type"]) for item in facets if item.get("data_type")})
return {
"data_types": [row[0] for row in rows],
"data_types": types,
}
@@ -403,20 +518,31 @@ async def get_collected_data(
def build_where_clause(
source: Optional[str], data_type: Optional[str], country: Optional[str], search: Optional[str]
):
"""Build WHERE clause and params for queries"""
source: Optional[str],
data_type: Optional[str],
country: Optional[str],
search: Optional[str],
*,
mode: str = "current",
) -> tuple[str, dict, bool]:
"""Build WHERE clause and params for queries."""
conditions = []
params = {}
params: dict = {}
if mode != "history":
conditions.append("is_current IS TRUE")
source_values = parse_multi_values(source)
data_type_values = parse_multi_values(data_type)
include_excluded = _includes_default_excluded(source_values, data_type_values)
if source_values:
conditions.append(build_in_condition("source", source_values, "source", params))
if data_type_values:
conditions.append(build_in_condition("data_type", data_type_values, "data_type", params))
normalized_country = normalize_country(country) if country else None
if not include_excluded and DEFAULT_EXCLUDED_DATA_TYPES:
conditions.append(build_not_in_condition("data_type", DEFAULT_EXCLUDED_DATA_TYPES, "excl_dt", params))
normalized_country = normalize_country(country) if country else None
if normalized_country:
conditions.append(f"{COUNTRY_SQL} = :country")
params["country"] = normalized_country
@@ -425,7 +551,7 @@ def build_where_clause(
conditions.append(search_condition)
where_sql = " AND ".join(conditions) if conditions else "1=1"
return where_sql, params
return where_sql, params, include_excluded
@router.get("/export/json")
@@ -441,9 +567,7 @@ async def export_json(
):
"""导出数据为 JSON 格式"""
where_sql, params = build_where_clause(source, data_type, country, search)
if mode != "history":
where_sql = f"({where_sql}) AND COALESCE(is_current, TRUE) = TRUE"
where_sql, params, _ = build_where_clause(source, data_type, country, search, mode=mode)
params["limit"] = limit
query = text(f"""
@@ -486,9 +610,7 @@ async def export_csv(
):
"""导出数据为 CSV 格式"""
where_sql, params = build_where_clause(source, data_type, country, search)
if mode != "history":
where_sql = f"({where_sql}) AND COALESCE(is_current, TRUE) = TRUE"
where_sql, params, _ = build_where_clause(source, data_type, country, search, mode=mode)
params["limit"] = limit
query = text(f"""
+149 -22
View File
@@ -1,6 +1,6 @@
"""Compute observations, administrator configuration and independent facility samples."""
from datetime import UTC, datetime
from datetime import UTC, date, datetime
from app.core.compute_types import COMPUTE_SITE_TYPES, compute_record_filter, compute_site_type_expression
from app.api.v1.visualization import convert_compute_centers_to_geojson
@@ -8,10 +8,11 @@ from app.core.access_gate import require_earth_or_api_access
from app.core.earth_geography_policy import display_country
from app.core.enums import UserRole
from app.core.logging import get_logger
from app.core.security import get_current_user
from app.core.security import get_current_user, get_optional_current_user
from app.core.websocket.broadcaster import broadcaster
from app.db.session import get_db
from app.models.collected_data import CollectedData
from app.models.compute_configuration_revision import ComputeConfigurationRevision
from app.models.data_snapshot import DataSnapshot
from app.models.user import User
from app.schemas.compute_configuration import (
@@ -29,10 +30,12 @@ from app.services.compute_center_locations import refresh_compute_center_locatio
from app.services.compute_configuration import (
DEFAULT_CONFIGURATION,
configuration_response,
list_configuration_revisions,
publish_configuration,
read_configuration,
)
from app.services.compute_history import ComputeSeriesMode, compute_history
from app.services.compute_lineage import build_observation_lineage, is_admin_user
from fastapi import APIRouter, Depends, HTTPException, Query, Response
from sqlalchemy import and_, case, func, or_, select
from sqlalchemy.ext.asyncio import AsyncSession
@@ -70,13 +73,35 @@ async def get_series(
countries: str = "CN,US",
mode: ComputeSeriesMode = "global_share",
db: AsyncSession = Depends(get_db),
as_of: str | None = None,
publish_id: str | None = None,
):
codes = selected_countries(countries)
envelope = await read_configuration(db)
envelope = await read_configuration(db, as_of=as_of, publish_id=publish_id)
response.headers["Cache-Control"] = "no-store"
if envelope.get("snapshot_unavailable"):
empty_cfg = ComputeConfiguration(
reviewed_at=date.today(), sources=[], observations=[], innovation=[]
)
result = compute_history(codes, mode, empty_cfg)
result.update(
version=None,
publish_id=None,
published_at=None,
as_of=envelope.get("as_of"),
snapshot_unavailable=True,
notice=envelope.get("notice"),
provenance="snapshot_unavailable",
)
return result
result = compute_history(codes, mode, ComputeConfiguration.model_validate(envelope["config"]))
effective_pid = envelope.get("publish_id") or envelope["revision"]
result.update(
version=envelope["revision"],
version=effective_pid,
publish_id=effective_pid,
published_at=envelope.get("published_at"),
as_of=envelope.get("as_of"),
snapshot_unavailable=False,
provenance="bundled_reports" if envelope["is_default"] else "admin_curated_reports",
)
return result
@@ -98,6 +123,108 @@ async def get_configuration(
return configuration_response(await read_configuration(db))
@router.get("/revisions")
async def get_configuration_revisions(
response: Response,
limit: int = Query(20, ge=1, le=100),
_actor: User = Depends(configuration_admin),
db: AsyncSession = Depends(get_db),
):
response.headers["Cache-Control"] = "no-store"
items = await list_configuration_revisions(db, limit=limit, redact=False)
return {"items": items}
@router.get(
"/revisions/public",
dependencies=[Depends(require_earth_or_api_access("data_products:read"))],
)
async def get_public_configuration_revisions(
response: Response,
limit: int = Query(20, ge=1, le=50),
db: AsyncSession = Depends(get_db),
):
response.headers["Cache-Control"] = "no-store"
items = await list_configuration_revisions(db, limit=limit, redact=True)
return {"items": items}
@router.get(
"/lineage",
dependencies=[Depends(require_earth_or_api_access("data_products:read"))],
)
async def get_compute_observation_lineage(
response: Response,
code: str = Query(..., min_length=2, max_length=32),
metric: ComputeSeriesMode = "global_share",
year: int = Query(..., ge=2000, le=2100),
publish_id: str | None = None,
as_of: str | None = None,
current_user: User | None = Depends(get_optional_current_user),
db: AsyncSession = Depends(get_db),
):
response.headers["Cache-Control"] = "no-store"
return await build_observation_lineage(
db,
code=code,
metric=metric,
year=year,
publish_id=publish_id,
as_of=as_of,
redact=not is_admin_user(current_user),
)
async def _deliver_revision_presentation(
db: AsyncSession,
envelope: dict,
) -> dict:
"""Trigger revision-driven presentation after commit; record failures for scheduled retry."""
publish_id = envelope.get("publish_id") or envelope.get("revision")
if not publish_id or envelope.get("no_changes"):
return envelope
rev_row = (
await db.execute(
select(ComputeConfigurationRevision).where(
ComputeConfigurationRevision.publish_id == publish_id
)
)
).scalar_one_or_none()
if not isinstance(rev_row, ComputeConfigurationRevision):
return envelope
if rev_row.presentation_status == "skipped":
envelope["presentation_status"] = "skipped"
return envelope
from app.services.ai.proactive_pipeline import process_compute_revision_presentation
try:
res = await process_compute_revision_presentation(db, rev_row.id)
await db.commit()
envelope["presentation_status"] = str(res.get("status") or rev_row.presentation_status)
except Exception as exc:
await db.rollback()
logger.warning_event(
"Compute revision presentation failed; queued for retry",
event="compute.revision.presentation_failed",
context={"publish_id": publish_id, "revision_id": rev_row.id, "error": str(exc)},
)
failed_row = (
await db.execute(
select(ComputeConfigurationRevision).where(
ComputeConfigurationRevision.publish_id == publish_id
)
)
).scalar_one_or_none()
if isinstance(failed_row, ComputeConfigurationRevision):
failed_row.presentation_status = "failed"
failed_row.presentation_attempts = int(failed_row.presentation_attempts or 0) + 1
failed_row.presentation_error = str(exc)[:1000]
await db.commit()
envelope["presentation_status"] = "failed"
return envelope
@router.put("/configuration")
async def update_configuration(
payload: ComputeConfigurationWrite,
@@ -105,16 +232,16 @@ async def update_configuration(
db: AsyncSession = Depends(get_db),
):
envelope = await publish_configuration(
db, revision=payload.revision, config=payload.config, actor=actor,
db,
revision=payload.revision,
config=payload.config,
actor=actor,
publish_note=payload.publish_note,
source_candidate_ids=payload.source_candidate_ids,
)
try:
from app.services.ai.proactive_pipeline import process_compute_config_proactive_delta
await process_compute_config_proactive_delta(db)
await db.commit()
except Exception:
pass
await _broadcast_compute_configuration_update()
if not envelope.get("no_changes"):
envelope = await _deliver_revision_presentation(db, envelope)
await _broadcast_compute_configuration_update()
return configuration_response(envelope)
@@ -125,16 +252,16 @@ async def reset_configuration(
db: AsyncSession = Depends(get_db),
):
envelope = await publish_configuration(
db, revision=payload.revision, config=DEFAULT_CONFIGURATION, actor=actor, reset=True,
db,
revision=payload.revision,
config=DEFAULT_CONFIGURATION,
actor=actor,
reset=True,
publish_note=payload.publish_note,
)
try:
from app.services.ai.proactive_pipeline import process_compute_config_proactive_delta
await process_compute_config_proactive_delta(db)
await db.commit()
except Exception:
pass
await _broadcast_compute_configuration_update()
if not envelope.get("no_changes"):
envelope = await _deliver_revision_presentation(db, envelope)
await _broadcast_compute_configuration_update()
return configuration_response(envelope)
+958
View File
@@ -0,0 +1,958 @@
"""Admin layer-based data ledger APIs (read-only per-layer views + compute review)."""
from __future__ import annotations
from dataclasses import dataclass
import re
from typing import Any, Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy import desc, func, or_, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.api.v1.collected_data import DEFAULT_EXCLUDED_DATA_TYPES, _load_collected_facets
from app.api.v1.data_products import PRODUCT_DEFINITIONS
from app.core.cache import cache
from app.core.collected_data_fields import get_record_field
from app.core.compute_types import COMPUTE_SITE_TYPES, compute_record_filter, compute_site_type
from app.core.countries import normalize_country
from app.core.security import get_current_user
from app.core.time import to_iso8601_utc
from app.db.session import get_db
from app.models.bgp_collector_location import BGPCollectorLocation
from app.models.bgp_incident import BGPIncident
from app.models.collected_data import CollectedData
from app.models.compute_center_location import ComputeCenterLocationRecord
from app.models.datasource import DataSource
from app.models.earth_news import EarthNewsItem
from app.models.situational_assessment import WorkflowRun
from app.models.vessel import VesselCurrentState
from app.services.compute_center_locations import resolve_compute_center_location_full
from app.services.location.workflow_tools import (
TERMINAL_UNLOCATABLE_STATUSES,
sanitize_user_facing_reasoning,
)
router = APIRouter(dependencies=[Depends(get_current_user)])
DATA_LEDGER_LAYERS_CACHE_KEY = "data_ledger:layers:v2"
DATA_LEDGER_LAYERS_TTL_SECONDS = 60
LAYER_ORDER: tuple[str, ...] = (
"compute",
"satellites",
"cables",
"vessels",
"bgp",
"news",
"weather",
"geo",
)
LAYER_KINDS: dict[str, tuple[dict[str, str], ...]] = {
"cables": (
{"id": "submarine_cable", "label": "海缆系统"},
{"id": "landing_point", "label": "登陆点"},
{"id": "cable_landing_relation", "label": "海缆登陆关系"},
),
"bgp": (
{"id": "collectors", "label": "观测站"},
{"id": "incidents", "label": "BGP 事件"},
),
"news": (
{"id": "items", "label": "新闻条目"},
{"id": "live_streams", "label": "Live 直播源"},
),
"weather": (
{"id": "all", "label": "气象图层"},
{"id": "cloud_map_record", "label": "云图记录"},
{"id": "wind_field_record", "label": "风场记录"},
),
}
@dataclass(frozen=True)
class _CollectedLayerSpec:
data_types: tuple[str, ...]
columns: tuple[dict[str, str], ...]
include_data_type_col: bool = False
_COLLECTED_LAYER_SPECS: dict[str, _CollectedLayerSpec] = {
"satellites": _CollectedLayerSpec(
data_types=("satellite_tle",),
columns=(
{"key": "name", "label": "名称"},
{"key": "source_id", "label": "NORAD ID"},
{"key": "international_designator", "label": "国际编号"},
{"key": "constellation_group", "label": "星座分组"},
{"key": "inclination", "label": "轨道倾角"},
{"key": "source", "label": "数据源"},
{"key": "collected_at", "label": "采集时间"},
),
),
"cables": _CollectedLayerSpec(
data_types=("submarine_cable", "landing_point", "cable_landing_relation"),
columns=(
{"key": "name", "label": "名称"},
{"key": "source_id", "label": "原始 ID"},
{"key": "source", "label": "数据源"},
{"key": "country", "label": "国家/地区"},
{"key": "collected_at", "label": "采集时间"},
),
),
"news:live_streams": _CollectedLayerSpec(
data_types=("news_live_stream",),
columns=(
{"key": "name", "label": "频道名称"},
{"key": "source", "label": "数据源"},
{"key": "region", "label": "区域"},
{"key": "language", "label": "语言"},
{"key": "collected_at", "label": "采集时间"},
),
),
"weather": _CollectedLayerSpec(
data_types=("cloud_map_record", "wind_field_record"),
include_data_type_col=True,
columns=(
{"key": "name", "label": "名称"},
{"key": "data_type", "label": "数据类型"},
{"key": "source", "label": "数据源"},
{"key": "reference_date", "label": "观测时间"},
{"key": "collected_at", "label": "采集时间"},
),
),
"geo": _CollectedLayerSpec(
data_types=("earth_tile_pyramid",),
columns=(
{"key": "name", "label": "瓦片数据集"},
{"key": "source", "label": "数据源"},
{"key": "reference_date", "label": "参考日期"},
{"key": "collected_at", "label": "采集时间"},
),
),
}
_US_CA_STATE_ZIP_RE = re.compile(r"^[A-Z]{2}(?:\s+\d{5}(?:-\d{4})?)?$")
_POSTAL_PREFIX_RE = re.compile(r"^\d{4,6}(?:-\d{3,4})?\s+")
_POSTAL_SUFFIX_RE = re.compile(r"\s+\d{4,6}(?:-\d{3,4})?$")
_STREET_ADDRESS_RE = re.compile(
r"^\d+\s+.*\b(rd|road|ave|avenue|st|street|blvd|dr|drive|way|lane|pkwy|hwy|floor|suite|building)\b",
re.IGNORECASE,
)
_VAGUE_LOCATION_TOKENS = (
"on prem",
"various",
"multiple",
"global",
"nordics",
"europe",
"asia",
"unknown",
)
_US_STATE_NAMES = frozenset(
{
"alabama",
"alaska",
"arizona",
"arkansas",
"california",
"colorado",
"connecticut",
"delaware",
"florida",
"georgia",
"hawaii",
"idaho",
"illinois",
"indiana",
"iowa",
"kansas",
"kentucky",
"louisiana",
"maine",
"maryland",
"massachusetts",
"michigan",
"minnesota",
"mississippi",
"missouri",
"montana",
"nebraska",
"nevada",
"new hampshire",
"new jersey",
"new mexico",
"new york",
"north carolina",
"north dakota",
"ohio",
"oklahoma",
"oregon",
"pennsylvania",
"rhode island",
"south carolina",
"south dakota",
"tennessee",
"texas",
"utah",
"vermont",
"virginia",
"washington",
"west virginia",
"wisconsin",
"wyoming",
"district of columbia",
}
)
def _normalize_ledger_country(value: Any) -> str | None:
if value is None:
return None
text = str(value).strip()
if not text:
return None
return normalize_country(text) or text
def _extract_city_from_location(location: Any, country: str | None = None) -> str | None:
if not isinstance(location, str):
return None
text = location.strip()
if not text:
return None
normalized_country = _normalize_ledger_country(country) if country else None
lines = [line.strip() for line in text.splitlines() if line.strip()]
for line in reversed(lines):
if "°" in line or '"' in line:
continue
lowered_line = line.casefold()
if any(token in lowered_line for token in _VAGUE_LOCATION_TOKENS):
continue
if "," not in line:
continue
parts = [part.strip() for part in line.split(",") if part.strip()]
while parts and normalize_country(parts[-1]) is not None:
parts.pop()
if not parts:
continue
if len(parts) >= 2:
tail = parts[-1]
if _US_CA_STATE_ZIP_RE.fullmatch(tail) or tail.casefold() in _US_STATE_NAMES:
parts.pop()
if not parts:
continue
candidate = parts[-1].strip()
candidate = _POSTAL_PREFIX_RE.sub("", candidate).strip()
candidate = _POSTAL_SUFFIX_RE.sub("", candidate).strip()
if not candidate or len(candidate) > 48:
continue
if candidate.isdigit():
continue
if _STREET_ADDRESS_RE.search(candidate):
continue
if normalize_country(candidate) is not None:
continue
if normalized_country and _normalize_ledger_country(candidate) == normalized_country:
continue
return candidate
return None
def _format_satellite_inclination(value: Any) -> str:
if value is None or value == "":
return "-"
try:
return f"{float(value):.2f}°"
except (TypeError, ValueError):
return "-"
async def _load_source_name_map(db: AsyncSession) -> dict[str, str]:
rows = (await db.execute(select(DataSource.source, DataSource.name))).all()
return {
str(source): str(name)
for source, name in rows
if source and name and str(name).strip()
}
def _has_valid_coords(latitude: Any, longitude: Any) -> bool:
try:
lat = float(latitude)
lon = float(longitude)
except (TypeError, ValueError):
return False
if lat == 0.0 or lon == 0.0:
return False
return -90.0 <= lat <= 90.0 and -180.0 <= lon <= 180.0
def _classify_compute_row(
record: CollectedData,
loc: ComputeCenterLocationRecord | None,
fallback_wf_run_id: str | None = None,
) -> dict[str, Any]:
metadata = record.extra_data if isinstance(record.extra_data, dict) else {}
site_type = compute_site_type(record)
operator = (
(loc.operator if loc else None)
or metadata.get("organization")
or metadata.get("operator")
or metadata.get("owner")
or metadata.get("manufacturer")
)
country = _normalize_ledger_country(
(loc.country if loc else None)
or get_record_field(record, "country")
or metadata.get("raw_country")
)
city = (loc.city if loc else None) or get_record_field(record, "city")
if not city:
city = _extract_city_from_location(metadata.get("location"), country)
lat = loc.latitude if loc else None
lon = loc.longitude if loc else None
precision = (loc.precision if loc else None) or "unknown"
confidence = loc.confidence if loc else None
location_source = (loc.location_source if loc else None) or ""
source_url = loc.source_url if loc else (metadata.get("source_url") or metadata.get("detail_url"))
raw_note = loc.source_note if loc else None
verification_status = str(loc.verification_status if loc else "").strip().lower()
raw_payload = (loc.raw_payload if loc and isinstance(loc.raw_payload, dict) else {}) or {}
workflow_run_id = raw_payload.get("workflow_run_id") or fallback_wf_run_id
terminal_status: str | None = None
if verification_status in TERMINAL_UNLOCATABLE_STATUSES:
status_bucket = "terminal"
terminal_status = verification_status
elif loc is None and metadata.get("compute_contract") == "v1" and metadata.get("anonymous"):
status_bucket = "terminal"
terminal_status = "anonymous"
verification_status = "anonymous"
location_source = "contract_anonymous"
raw_note = raw_note or "源数据声明为匿名集群,不披露具体物理设施。"
elif verification_status == "unverified":
status_bucket = "needs_confirmation"
elif (verification_status == "verified" and _has_valid_coords(lat, lon)) or (
verification_status == "source_provided" and _has_valid_coords(lat, lon)
):
status_bucket = "located"
elif loc is None:
resolved = resolve_compute_center_location_full(record, metadata)
if resolved.is_resolved and resolved.location and resolved.location.is_renderable:
res_loc = resolved.location
status_bucket = "needs_confirmation" if res_loc.needs_confirmation else "located"
lat = res_loc.latitude
lon = res_loc.longitude
precision = res_loc.location_precision
confidence = res_loc.location_confidence
location_source = res_loc.location_source or "source_coordinates"
verification_status = "unverified" if res_loc.needs_confirmation else "source_provided"
city = city or res_loc.city
country = country or _normalize_ledger_country(res_loc.country)
raw_note = res_loc.location_source_note or res_loc.estimated_reason
else:
status_bucket = "pending"
verification_status = "pending"
else:
status_bucket = "pending" if not _has_valid_coords(lat, lon) else "located"
if not verification_status:
verification_status = "pending"
sources_list = metadata.get("sources") if isinstance(metadata.get("sources"), list) else []
has_clues = bool(operator or city or sources_list)
is_anonymous_placeholder = bool(metadata.get("anonymous")) and not has_clues
updated_ts = (loc.verified_at or loc.updated_at if loc else None) or record.reference_date or record.collected_at
return {
"id": record.id,
"source": record.source,
"source_id": record.source_id,
"name": record.name or record.title or record.source_id,
"site_type": site_type,
"operator": operator,
"country": country,
"city": city,
"latitude": float(lat) if _has_valid_coords(lat, lon) else None,
"longitude": float(lon) if _has_valid_coords(lat, lon) else None,
"precision": precision,
"confidence": confidence,
"verification_status": verification_status,
"status_bucket": status_bucket,
"terminal_status": terminal_status,
"is_anonymous_placeholder": is_anonymous_placeholder,
"location_source": location_source or None,
"source_url": source_url,
"source_note": sanitize_user_facing_reasoning(raw_note) or None,
"workflow_run_id": workflow_run_id,
"updated_at": to_iso8601_utc(updated_ts),
}
def _compute_review_priority_tier(item: dict[str, Any]) -> int:
bucket = str(item.get("status_bucket") or "")
if bucket == "pending":
return 0
if bucket == "needs_confirmation":
return 1
if bucket == "located":
return 2
if item.get("is_anonymous_placeholder"):
return 4
return 3
async def _count_collected_types(db: AsyncSession, data_types: tuple[str, ...]) -> int:
stmt = (
select(func.count(CollectedData.id))
.where(CollectedData.is_current.is_(True))
.where(CollectedData.deleted_at.is_(None))
.where(CollectedData.data_type.in_(data_types))
)
if "satellite_tle" in data_types:
stmt = stmt.where(CollectedData.source_id.is_not(None)).where(CollectedData.source_id != "")
return int((await db.scalar(stmt)) or 0)
@router.get("/layers")
async def list_data_ledger_layers(db: AsyncSession = Depends(get_db)):
"""Return layer categories and item counts reusing `PRODUCT_DEFINITIONS`."""
cached = cache.get(DATA_LEDGER_LAYERS_CACHE_KEY)
if isinstance(cached, dict) and isinstance(cached.get("layers"), list):
return cached
compute_cnt = int(
(
await db.scalar(
select(func.count(CollectedData.id))
.where(CollectedData.is_current.is_(True))
.where(CollectedData.deleted_at.is_(None))
.where(compute_record_filter(CollectedData))
)
)
or 0
)
sat_cnt = await _count_collected_types(db, ("satellite_tle",))
cable_cnt = await _count_collected_types(
db, ("submarine_cable", "landing_point", "cable_landing_relation")
)
vessel_cnt = int((await db.scalar(select(func.count(VesselCurrentState.mmsi)))) or 0)
bgp_col_cnt = int((await db.scalar(select(func.count(BGPCollectorLocation.id)))) or 0)
bgp_inc_cnt = int((await db.scalar(select(func.count(BGPIncident.id)))) or 0)
news_items_cnt = int((await db.scalar(select(func.count(EarthNewsItem.id)))) or 0)
news_live_cnt = await _count_collected_types(db, ("news_live_stream",))
weather_cnt = await _count_collected_types(db, ("cloud_map_record", "wind_field_record"))
geo_cnt = await _count_collected_types(db, ("earth_tile_pyramid",))
facets = await _load_collected_facets(db, mode="current")
raw_cnt = sum(
int(item.get("count") or 0)
for item in facets
if item.get("data_type") not in DEFAULT_EXCLUDED_DATA_TYPES
)
counts_map = {
"compute": compute_cnt,
"satellites": sat_cnt,
"cables": cable_cnt,
"vessels": vessel_cnt,
"bgp": bgp_col_cnt + bgp_inc_cnt,
"news": news_items_cnt + news_live_cnt,
"weather": weather_cnt,
"geo": geo_cnt,
}
layers = [
{
"id": layer_id,
"name": str(PRODUCT_DEFINITIONS[layer_id]["name"]),
"count": counts_map[layer_id],
"kinds": list(LAYER_KINDS.get(layer_id, ())),
}
for layer_id in LAYER_ORDER
if layer_id in PRODUCT_DEFINITIONS
]
layers.append(
{
"id": "raw",
"name": "原始采集记录",
"count": raw_cnt,
"kinds": [],
}
)
payload = {"layers": layers}
cache.set(
DATA_LEDGER_LAYERS_CACHE_KEY,
payload,
expire_seconds=DATA_LEDGER_LAYERS_TTL_SECONDS,
)
return payload
@router.get("/compute-centers")
async def list_compute_center_ledger(
site_type: Optional[str] = Query(None),
status: Optional[str] = Query(None),
country: Optional[str] = Query(None),
search: Optional[str] = Query(None),
page: int = Query(1, ge=1),
page_size: int = Query(20, ge=1, le=200),
db: AsyncSession = Depends(get_db),
):
"""Return compute center review ledger with site-type and status bucket counts."""
records = (
await db.execute(
select(CollectedData)
.where(CollectedData.is_current.is_(True))
.where(CollectedData.deleted_at.is_(None))
.where(compute_record_filter(CollectedData))
.order_by(desc(CollectedData.collected_at), desc(CollectedData.id))
)
).scalars().all()
loc_rows = (await db.execute(select(ComputeCenterLocationRecord))).scalars().all()
loc_map = {(r.source, r.source_id): r for r in loc_rows}
wf_rows = (
await db.execute(
select(WorkflowRun)
.where(WorkflowRun.workflow_id == "location.resolve_unknown")
.order_by(desc(WorkflowRun.started_at))
)
).scalars().all()
latest_wf_by_sid: dict[str, str] = {}
for wf in wf_rows:
sid = None
if isinstance(wf.input_params, dict):
sid = wf.input_params.get("source_id")
if not sid and isinstance(wf.budget_used, dict):
sid = wf.budget_used.get("source_id")
if sid and str(sid) not in latest_wf_by_sid:
latest_wf_by_sid[str(sid)] = wf.id
all_rows = [
_classify_compute_row(
rec,
loc_map.get((rec.source, rec.source_id)),
fallback_wf_run_id=latest_wf_by_sid.get(str(rec.source_id)),
)
for rec in records
]
search_needle = (search or "").strip().lower()
country_needle = _normalize_ledger_country(country) or ""
def _matches_base(item: dict[str, Any]) -> bool:
if country_needle and str(item.get("country") or "") != country_needle:
return False
if search_needle:
haystack = " ".join(
str(item.get(k) or "")
for k in ("name", "source_id", "operator", "city", "country", "source_note")
).lower()
if search_needle not in haystack:
return False
return True
base_filtered = [item for item in all_rows if _matches_base(item)]
status_filter = (status or "").strip()
site_type_filter = (site_type or "").strip()
by_site_type = dict.fromkeys(COMPUTE_SITE_TYPES, 0)
for item in base_filtered:
if status_filter and item["status_bucket"] != status_filter:
continue
st = item["site_type"]
if st in by_site_type:
by_site_type[st] += 1
by_status = {
"located": 0,
"needs_confirmation": 0,
"terminal": 0,
"pending": 0,
}
for item in base_filtered:
if site_type_filter and item["site_type"] != site_type_filter:
continue
bucket = item["status_bucket"]
if bucket in by_status:
by_status[bucket] += 1
filtered = [
item
for item in base_filtered
if (not site_type_filter or item["site_type"] == site_type_filter)
and (not status_filter or item["status_bucket"] == status_filter)
]
filtered = [
item
for _, item in sorted(
enumerate(filtered),
key=lambda pair: (_compute_review_priority_tier(pair[1]), pair[0]),
)
]
countries = sorted({str(item["country"]) for item in all_rows if item.get("country")})
total = len(filtered)
start = (page - 1) * page_size
paginated = filtered[start : start + page_size]
return {
"items": paginated,
"total": total,
"page": page,
"page_size": page_size,
"counts": {
"total": len(all_rows),
"by_site_type": by_site_type,
"by_status": by_status,
},
"countries": countries,
}
async def _query_collected_layer_items(
db: AsyncSession,
*,
layer: str,
spec: _CollectedLayerSpec,
kind: str,
kinds: list[dict[str, str]],
search: str,
page: int,
page_size: int,
) -> dict[str, Any]:
target_types = spec.data_types
if kind and kind != "all" and kind in spec.data_types:
target_types = (kind,)
stmt = (
select(CollectedData)
.where(CollectedData.is_current.is_(True))
.where(CollectedData.deleted_at.is_(None))
.where(CollectedData.data_type.in_(target_types))
)
if "satellite_tle" in target_types:
stmt = stmt.where(CollectedData.source_id.is_not(None)).where(CollectedData.source_id != "")
if search:
pat = f"%{search}%"
stmt = stmt.where(
or_(
CollectedData.name.ilike(pat),
CollectedData.title.ilike(pat),
CollectedData.source_id.ilike(pat),
CollectedData.source.ilike(pat),
)
)
total = int((await db.scalar(select(func.count()).select_from(stmt.subquery()))) or 0)
rows_orm = (
await db.execute(
stmt.order_by(desc(CollectedData.collected_at), desc(CollectedData.id))
.limit(page_size)
.offset((page - 1) * page_size)
)
).scalars().all()
source_name_map = await _load_source_name_map(db)
rows = []
for rec in rows_orm:
meta = rec.extra_data if isinstance(rec.extra_data, dict) else {}
country_val = _normalize_ledger_country(get_record_field(rec, "country")) or "-"
constellation = meta.get("constellation_group") or meta.get("celestrak_query_group") or "-"
rows.append(
{
"id": rec.id,
"name": rec.name or rec.title or rec.source_id,
"source_id": rec.source_id,
"source": source_name_map.get(rec.source, rec.source),
"data_type": rec.data_type,
"country": country_val,
"international_designator": meta.get("international_designator") or "-",
"constellation_group": constellation,
"inclination": _format_satellite_inclination(meta.get("inclination")),
"region": meta.get("region") or meta.get("country") or "-",
"language": meta.get("language") or meta.get("lang") or "-",
"reference_date": to_iso8601_utc(rec.reference_date),
"collected_at": to_iso8601_utc(rec.collected_at),
}
)
return {
"layer": layer,
"kind": kind or (kinds[0]["id"] if kinds else "all"),
"kinds": kinds,
"columns": list(spec.columns),
"rows": rows,
"total": total,
"page": page,
"page_size": page_size,
}
async def _query_vessels_items(
db: AsyncSession, *, search: str, page: int, page_size: int
) -> dict[str, Any]:
stmt = select(VesselCurrentState)
if search:
pat = f"%{search}%"
stmt = stmt.where(
or_(
VesselCurrentState.name.ilike(pat),
VesselCurrentState.callsign.ilike(pat),
VesselCurrentState.flag.ilike(pat),
VesselCurrentState.vessel_type_name.ilike(pat),
)
)
total = int((await db.scalar(select(func.count()).select_from(stmt.subquery()))) or 0)
rows_orm = (
await db.execute(
stmt.order_by(desc(VesselCurrentState.observed_at), desc(VesselCurrentState.mmsi))
.limit(page_size)
.offset((page - 1) * page_size)
)
).scalars().all()
source_name_map = await _load_source_name_map(db)
rows = [
{
"id": str(v.mmsi),
"mmsi": str(v.mmsi),
"name": v.name or f"MMSI {v.mmsi}",
"vessel_type_name": v.vessel_type_name or "-",
"flag": v.flag or "-",
"coordinates": f"{v.lat:.4f}, {v.lon:.4f}",
"sog": f"{v.sog:.1f} kn" if v.sog is not None else "-",
"source": source_name_map.get(v.source, v.source),
"observed_at": to_iso8601_utc(v.observed_at),
}
for v in rows_orm
]
return {
"layer": "vessels",
"kind": "all",
"kinds": [],
"columns": [
{"key": "name", "label": "船名"},
{"key": "mmsi", "label": "MMSI"},
{"key": "vessel_type_name", "label": "船型"},
{"key": "flag", "label": "船旗"},
{"key": "coordinates", "label": "坐标"},
{"key": "sog", "label": "航速"},
{"key": "source", "label": "数据源"},
{"key": "observed_at", "label": "观测时间"},
],
"rows": rows,
"total": total,
"page": page,
"page_size": page_size,
}
async def _query_bgp_items(
db: AsyncSession, *, kind: str, kinds: list[dict[str, str]], search: str, page: int, page_size: int
) -> dict[str, Any]:
active_kind = kind if kind in {"collectors", "incidents"} else "collectors"
if active_kind == "collectors":
stmt = select(BGPCollectorLocation)
if search:
pat = f"%{search}%"
stmt = stmt.where(
or_(
BGPCollectorLocation.collector_id.ilike(pat),
BGPCollectorLocation.operator.ilike(pat),
BGPCollectorLocation.city.ilike(pat),
BGPCollectorLocation.country.ilike(pat),
)
)
total = int((await db.scalar(select(func.count()).select_from(stmt.subquery()))) or 0)
rows_orm = (
await db.execute(
stmt.order_by(desc(BGPCollectorLocation.updated_at), desc(BGPCollectorLocation.id))
.limit(page_size)
.offset((page - 1) * page_size)
)
).scalars().all()
rows = [
{
"id": r.id,
"collector_id": r.collector_id,
"operator": r.operator or "-",
"country": r.country or "-",
"city": r.city or "-",
"verification_status": r.verification_status,
"updated_at": to_iso8601_utc(r.updated_at or r.verified_at),
}
for r in rows_orm
]
columns = [
{"key": "collector_id", "label": "观测站 ID"},
{"key": "operator", "label": "运营机构"},
{"key": "country", "label": "国家/地区"},
{"key": "city", "label": "城市"},
{"key": "verification_status", "label": "核验状态"},
{"key": "updated_at", "label": "更新时间"},
]
else:
stmt = select(BGPIncident)
if search:
pat = f"%{search}%"
stmt = stmt.where(
or_(
BGPIncident.title.ilike(pat),
BGPIncident.incident_type.ilike(pat),
BGPIncident.source.ilike(pat),
)
)
total = int((await db.scalar(select(func.count()).select_from(stmt.subquery()))) or 0)
rows_orm = (
await db.execute(
stmt.order_by(desc(BGPIncident.started_at), desc(BGPIncident.id))
.limit(page_size)
.offset((page - 1) * page_size)
)
).scalars().all()
rows = [
{
"id": r.id,
"title": r.title,
"incident_type": r.incident_type,
"severity": r.severity,
"status": r.status,
"source": r.source,
"started_at": to_iso8601_utc(r.started_at),
}
for r in rows_orm
]
columns = [
{"key": "title", "label": "事件标题"},
{"key": "incident_type", "label": "事件类型"},
{"key": "severity", "label": "级别"},
{"key": "status", "label": "状态"},
{"key": "source", "label": "数据源"},
{"key": "started_at", "label": "开始时间"},
]
return {
"layer": "bgp",
"kind": active_kind,
"kinds": kinds,
"columns": columns,
"rows": rows,
"total": total,
"page": page,
"page_size": page_size,
}
async def _query_news_items(
db: AsyncSession, *, kind: str, kinds: list[dict[str, str]], search: str, page: int, page_size: int
) -> dict[str, Any]:
active_kind = kind if kind in {"items", "live_streams"} else "items"
if active_kind == "live_streams":
return await _query_collected_layer_items(
db,
layer="news",
spec=_COLLECTED_LAYER_SPECS["news:live_streams"],
kind=active_kind,
kinds=kinds,
search=search,
page=page,
page_size=page_size,
)
stmt = select(EarthNewsItem)
if search:
pat = f"%{search}%"
stmt = stmt.where(
or_(
EarthNewsItem.title.ilike(pat),
EarthNewsItem.source.ilike(pat),
EarthNewsItem.region.ilike(pat),
EarthNewsItem.location_label.ilike(pat),
)
)
total = int((await db.scalar(select(func.count()).select_from(stmt.subquery()))) or 0)
rows_orm = (
await db.execute(
stmt.order_by(
desc(func.coalesce(EarthNewsItem.published_at, EarthNewsItem.last_seen_at)),
desc(EarthNewsItem.id),
)
.limit(page_size)
.offset((page - 1) * page_size)
)
).scalars().all()
rows = [
{
"id": r.id,
"title": r.title,
"source": r.source or r.feed_name or "-",
"region": r.region,
"location_label": r.location_label,
"enrichment_status": r.enrichment_status,
"published_at": to_iso8601_utc(r.published_at or r.last_seen_at),
}
for r in rows_orm
]
return {
"layer": "news",
"kind": "items",
"kinds": kinds,
"columns": [
{"key": "title", "label": "新闻标题"},
{"key": "source", "label": "来源"},
{"key": "region", "label": "区域"},
{"key": "location_label", "label": "地理落点"},
{"key": "enrichment_status", "label": "处理状态"},
{"key": "published_at", "label": "发布时间"},
],
"rows": rows,
"total": total,
"page": page,
"page_size": page_size,
}
@router.get("/{layer}/items")
async def list_layer_ledger_items(
layer: str,
kind: Optional[str] = Query(None),
search: Optional[str] = Query(None),
page: int = Query(1, ge=1),
page_size: int = Query(20, ge=1, le=200),
db: AsyncSession = Depends(get_db),
):
"""Return paginated read-only ledger rows for non-compute Earth layers."""
kinds = list(LAYER_KINDS.get(layer, ()))
resolved_kind = (kind or "").strip() or (kinds[0]["id"] if kinds else "all")
search_str = (search or "").strip()
if layer == "vessels":
return await _query_vessels_items(db, search=search_str, page=page, page_size=page_size)
if layer == "bgp":
return await _query_bgp_items(
db, kind=resolved_kind, kinds=kinds, search=search_str, page=page, page_size=page_size
)
if layer == "news":
return await _query_news_items(
db, kind=resolved_kind, kinds=kinds, search=search_str, page=page, page_size=page_size
)
if layer in _COLLECTED_LAYER_SPECS:
return await _query_collected_layer_items(
db,
layer=layer,
spec=_COLLECTED_LAYER_SPECS[layer],
kind=resolved_kind,
kinds=kinds,
search=search_str,
page=page,
page_size=page_size,
)
raise HTTPException(status_code=404, detail=f"Unknown ledger layer: {layer}")
+202 -7
View File
@@ -1,12 +1,20 @@
from datetime import UTC, datetime
from typing import Any
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.api.v1.visualization import get_visualization_geo_summary
from app.core.access_gate import require_earth_or_api_access
from app.core.time import to_iso8601_utc
from app.db.session import get_db
from app.models.collected_data import CollectedData
from app.models.datasource import DataSource
from app.models.earth_news import EarthNewsItem
from app.models.task import CollectionTask
from app.services.data_jobs import JOB_STATUS_CANCELLING, JOB_STATUS_QUEUED, JOB_STATUS_RUNNING
from app.services.earth_clouds import get_cloud_map_runtime_meta
router = APIRouter(dependencies=[Depends(require_earth_or_api_access("data_products:read"))])
@@ -55,20 +63,154 @@ PRODUCT_DEFINITIONS: dict[str, dict] = {
"primary_stat_key": "compute_center_count",
"stat_keys": ["compute_center_count", "supercomputer_count", "gpu_cluster_count", "data_center_count", "cloud_center_count", "edge_node_count"],
},
"weather": {
"name": "气象",
"sources": ["global_cloud_map", "cloud_hd_tiles", "global_wind_gfs"],
"primary_stat_key": "cloud_frame_count",
"stat_keys": ["cloud_frame_count", "cloud_record_count", "wind_available_flag"],
},
"geo": {
"name": "地理/底图",
"sources": ["earth_imagery_sentinel2", "earth_imagery_viirs_daily"],
"primary_stat_key": "cached_tile_count",
"stat_keys": ["cached_tile_count"],
},
"news": {
"name": "新闻与直播",
"sources": ["earth_news", "news_live_streams"],
"primary_stat_key": "news_count",
"stat_keys": ["news_count"],
},
"aircraft": {
"name": "航空飞行器",
"sources": ["adsb_lol_aircraft", "opensky_aircraft", "aircraft_registry"],
"primary_stat_key": "aircraft_count",
"stat_keys": ["aircraft_count", "military_aircraft_count", "emergency_aircraft_count"],
},
"gps_jamming": {
"name": "GPS/GNSS 干扰",
"sources": ["gpsjam_interference"],
"primary_stat_key": "gps_jamming_cell_count",
"stat_keys": ["gps_jamming_cell_count", "gps_jamming_high_count"],
},
"disasters": {
"name": "自然灾害",
"sources": [
"usgs_earthquakes",
"nasa_firms_wildfires",
"gdacs_disasters",
"nasa_eonet_events",
],
"primary_stat_key": "disaster_event_count",
"stat_keys": ["disaster_event_count", "disaster_high_count"],
},
}
def _build_product_status(product_id: str, summary: dict) -> dict:
async def _load_collector_product_states(
db: AsyncSession,
source_names: list[str],
) -> tuple[dict[str, bool], set[str]]:
if not source_names:
return {}, set()
ds_rows = (
await db.execute(
select(DataSource.id, DataSource.source, DataSource.is_active).where(
DataSource.source.in_(source_names)
)
)
).all()
active_by_source = {str(source): bool(is_active) for _, source, is_active in ds_rows}
id_to_source = {int(ds_id): str(source) for ds_id, source, _ in ds_rows}
running_sources: set[str] = set()
if id_to_source:
task_rows = (
await db.execute(
select(CollectionTask.datasource_id, func.count(CollectionTask.id))
.where(CollectionTask.datasource_id.in_(list(id_to_source.keys())))
.where(
CollectionTask.status.in_(
(JOB_STATUS_QUEUED, JOB_STATUS_RUNNING, JOB_STATUS_CANCELLING)
)
)
.group_by(CollectionTask.datasource_id)
)
).all()
for ds_id, cnt in task_rows:
if int(cnt or 0) > 0 and int(ds_id) in id_to_source:
running_sources.add(id_to_source[int(ds_id)])
return active_by_source, running_sources
def _build_product_status(
product_id: str,
summary: dict,
*,
active_by_source: dict[str, bool],
running_sources: set[str],
weather_meta: dict[str, Any] | None = None,
wind_meta: dict[str, Any] | None = None,
basemap_meta: dict[str, Any] | None = None,
news_count: int | None = None,
) -> dict:
definition = PRODUCT_DEFINITIONS[product_id]
stats = summary.get("stats", {})
product_stats = {key: stats.get(key, 0) for key in definition["stat_keys"]}
total_count = int(product_stats.get(definition["primary_stat_key"]) or 0)
sources = definition["sources"]
total_collector_count = len(sources)
active_collector_count = sum(1 for src in sources if active_by_source.get(src, False))
running_collector_count = sum(1 for src in sources if src in running_sources)
if product_id == "weather":
meta = weather_meta or {}
w_meta = wind_meta or {}
frames = meta.get("frames") if isinstance(meta.get("frames"), list) else []
frame_count = len(frames)
clusters = meta.get("convective_clusters") if isinstance(meta.get("convective_clusters"), list) else []
regions = meta.get("regions") if isinstance(meta.get("regions"), list) else []
wind_has_data = bool(w_meta.get("has_data"))
product_stats = {
"cloud_frame_count": frame_count,
"cloud_record_count": (1 + len(regions) + len(clusters)) if frame_count > 0 else 0,
"wind_available_flag": 1 if wind_has_data else 0,
}
total_count = frame_count + (1 if wind_has_data else 0)
has_data = frame_count > 0 or wind_has_data
captured_at = meta.get("captured_at") or w_meta.get("captured_at")
elif product_id == "geo":
b_meta = basemap_meta or {}
tile_sources = [
item for item in (b_meta.get("sources") or [])
if isinstance(item, dict) and item.get("source") in sources
]
cached_tiles = sum(int(item.get("cached_tiles") or 0) for item in tile_sources)
product_stats = {"cached_tile_count": cached_tiles}
total_count = cached_tiles
has_data = cached_tiles > 0
captured_at = None
elif product_id == "news":
resolved_news_count = int(news_count or 0)
product_stats = {"news_count": resolved_news_count}
total_count = resolved_news_count
has_data = resolved_news_count > 0
captured_at = None
else:
stats = summary.get("stats", {})
product_stats = {key: stats.get(key, 0) for key in definition["stat_keys"]}
total_count = int(product_stats.get(definition["primary_stat_key"]) or 0)
has_data = total_count > 0
captured_at = None
return {
"product_id": product_id,
"name": definition["name"],
"sources": definition["sources"],
"sources": sources,
"generated_at": summary.get("generated_at") or to_iso8601_utc(datetime.now(UTC)),
"captured_at": captured_at,
"total_count": total_count,
"has_data": has_data,
"total_collector_count": total_collector_count,
"active_collector_count": active_collector_count,
"running_collector_count": running_collector_count,
"datasources_url": f"/datasources?product={product_id}",
"stats": product_stats,
"build_state": "ready",
"stats_scope": "global",
@@ -76,13 +218,48 @@ def _build_product_status(product_id: str, summary: dict) -> dict:
}
async def _load_news_product_count(db: AsyncSession) -> int:
try:
items_cnt = await db.scalar(select(func.count(EarthNewsItem.id)))
except Exception:
items_cnt = 0
try:
live_cnt = await db.scalar(
select(func.count(CollectedData.id))
.where(CollectedData.is_current.is_(True))
.where(CollectedData.deleted_at.is_(None))
.where(CollectedData.data_type == "news_live_stream")
)
except Exception:
live_cnt = 0
return int(items_cnt or 0) + int(live_cnt or 0)
@router.get("")
async def list_data_products(db: AsyncSession = Depends(get_db)):
from app.services.earth_tiles import get_basemap_runtime_meta
from app.services.earth_wind import get_wind_runtime_meta
summary = await get_visualization_geo_summary(db)
all_sources = [src for definition in PRODUCT_DEFINITIONS.values() for src in definition["sources"]]
active_by_source, running_sources = await _load_collector_product_states(db, all_sources)
weather_meta = await get_cloud_map_runtime_meta(db)
wind_meta = await get_wind_runtime_meta(db)
basemap_meta = await get_basemap_runtime_meta(db)
news_count = await _load_news_product_count(db)
return {
"generated_at": summary.get("generated_at"),
"data": [
_build_product_status(product_id, summary)
_build_product_status(
product_id,
summary,
active_by_source=active_by_source,
running_sources=running_sources,
weather_meta=weather_meta if product_id == "weather" else None,
wind_meta=wind_meta if product_id == "weather" else None,
basemap_meta=basemap_meta if product_id == "geo" else None,
news_count=news_count if product_id == "news" else None,
)
for product_id in PRODUCT_DEFINITIONS
],
}
@@ -93,7 +270,25 @@ async def get_data_product_status(
product_id: str,
db: AsyncSession = Depends(get_db),
):
from app.services.earth_tiles import get_basemap_runtime_meta
from app.services.earth_wind import get_wind_runtime_meta
if product_id not in PRODUCT_DEFINITIONS:
raise HTTPException(status_code=404, detail="Unknown data product")
summary = await get_visualization_geo_summary(db)
return _build_product_status(product_id, summary)
sources = PRODUCT_DEFINITIONS[product_id]["sources"]
active_by_source, running_sources = await _load_collector_product_states(db, sources)
weather_meta = await get_cloud_map_runtime_meta(db) if product_id == "weather" else None
wind_meta = await get_wind_runtime_meta(db) if product_id == "weather" else None
basemap_meta = await get_basemap_runtime_meta(db) if product_id == "geo" else None
news_count = await _load_news_product_count(db) if product_id == "news" else None
return _build_product_status(
product_id,
summary,
active_by_source=active_by_source,
running_sources=running_sources,
weather_meta=weather_meta,
wind_meta=wind_meta,
basemap_meta=basemap_meta,
news_count=news_count,
)
+190 -3
View File
@@ -44,8 +44,9 @@ from app.services.custom_datasource_runtime import (
)
from app.services.datasource_connectivity import (
_resolve_aisstream_api_key,
resolve_spacetrack_credentials,
get_builtin_connection_status,
get_connectivity_store,
resolve_spacetrack_credentials,
save_connectivity_success,
strip_connectivity_validation,
test_builtin_connectivity,
@@ -64,6 +65,70 @@ def _user_role_value(user: User) -> str:
return str(getattr(role, "value", role) or "").lower()
def mask_credential_value(value: Any, *, secret: bool = False, reveal_edges: bool = False) -> str:
"""Return a strictly non-plaintext masked representation of a credential or identifier."""
raw = str(value or "").strip()
if not raw:
return ""
if secret:
if reveal_edges and len(raw) >= 8:
return f"{raw[:3]}••••{raw[-4:]}"
return "••••••"
if len(raw) >= 6:
return f"{raw[:2]}•••{raw[-2:]}"
return "•••"
def build_masked_credential_preview(
*,
requires_credentials: bool,
auth_type: str | None,
auth_config: dict[str, Any] | None,
resolved_provider: str | None = None,
resolved_values: dict[str, str] | None = None,
) -> tuple[bool, str]:
"""Compute `(has_credentials, masked_preview)` without exposing plaintext secrets."""
cfg = auth_config if isinstance(auth_config, dict) else {}
resolved = resolved_values if isinstance(resolved_values, dict) else {}
norm_auth = str(auth_type or "none").strip().lower()
provider = str(resolved_provider or "").strip().lower()
if not requires_credentials and norm_auth in {"", "none"}:
return True, ""
if provider == "barentswatch" or "oauth" in norm_auth or cfg.get("client_id") or cfg.get("client_secret"):
client_id = str(resolved.get("client_id") or cfg.get("client_id") or "").strip()
client_secret = str(resolved.get("client_secret") or cfg.get("client_secret") or "").strip()
has_creds = bool(client_id and client_secret)
parts = [
mask_credential_value(client_id, secret=False),
mask_credential_value(client_secret, secret=True),
]
return has_creds, " · ".join(part for part in parts if part)
if provider == "spacetrack" or "basic" in norm_auth or cfg.get("username") or cfg.get("password"):
username = str(resolved.get("username") or cfg.get("username") or "").strip()
password = str(resolved.get("password") or cfg.get("password") or "").strip()
has_creds = bool(username and password)
parts = [
mask_credential_value(username, secret=False),
mask_credential_value(password, secret=True),
]
return has_creds, " · ".join(part for part in parts if part)
api_key = str(
resolved.get("api_key")
or cfg.get("api_key")
or cfg.get("token")
or cfg.get("bearer_token")
or ""
).strip()
if provider == "aisstream" or norm_auth in {"api_key", "bearer"} or api_key:
return bool(api_key), mask_credential_value(api_key, secret=True, reveal_edges=True)
return False, ""
def _user_display_name(user: User) -> str:
return str(getattr(user, "username", None) or getattr(user, "email", None) or getattr(user, "id", ""))
@@ -109,6 +174,45 @@ async def _ensure_datasource_secret_reveal_allowed(
)
def _default_builtin_config(name: str) -> dict[str, Any]:
if name == "global_cloud_map":
from app.services.earth_clouds import DEFAULT_CLOUD_CONFIG
return {
"primary_source": DEFAULT_CLOUD_CONFIG.primary_source,
"fallback_source": DEFAULT_CLOUD_CONFIG.fallback_source,
"resolution": DEFAULT_CLOUD_CONFIG.resolution,
"ir_threshold": DEFAULT_CLOUD_CONFIG.ir_threshold,
"contrast_gamma": DEFAULT_CLOUD_CONFIG.contrast_gamma,
"convective_threshold": DEFAULT_CLOUD_CONFIG.convective_threshold,
"min_cluster_area_km2": DEFAULT_CLOUD_CONFIG.min_cluster_area_km2,
"polar_feather_enabled": DEFAULT_CLOUD_CONFIG.polar_feather_enabled,
"max_history_frames": DEFAULT_CLOUD_CONFIG.max_history_frames,
"request_timeout_seconds": DEFAULT_CLOUD_CONFIG.request_timeout_seconds,
"geocolor_enabled": DEFAULT_CLOUD_CONFIG.geocolor_enabled,
"relief_shading_strength": DEFAULT_CLOUD_CONFIG.relief_shading_strength,
"optical_flow_enabled": DEFAULT_CLOUD_CONFIG.optical_flow_enabled,
}
if name == "cloud_hd_tiles":
return {
"warmup_max_zoom": 2,
"max_zoom": 6,
"max_cache_mb": 512,
"request_timeout_seconds": 15,
}
if name in {"earth_imagery_sentinel2", "earth_imagery_viirs_daily"}:
return {
"warmup_max_zoom": 3,
"max_zoom": 10 if name == "earth_imagery_sentinel2" else 9,
"max_cache_mb": 1024 if name == "earth_imagery_sentinel2" else 768,
"request_timeout_seconds": 15,
}
if name == "global_wind_gfs":
return {
"grid_step_deg": 2.0,
"gale_threshold_ms": 17.2,
"request_timeout_seconds": 25,
"max_history_runs": 12,
}
return {"timeout": 30, "retry": 3}
@@ -377,6 +481,8 @@ async def list_configs(
db: AsyncSession = Depends(get_db),
):
"""List all user-defined data source configurations"""
from app.api.v1.datasources import infer_datasource_product_key
query = select(DataSourceConfig)
if active_only:
query = query.where(DataSourceConfig.is_active)
@@ -391,10 +497,24 @@ async def list_configs(
{
"id": c.id,
"name": c.name,
"product": infer_datasource_product_key(c.name, c.description or "", c.name),
"description": c.description,
"source_type": c.source_type,
"endpoint": c.endpoint,
"auth_type": c.auth_type,
"requires_credentials": (c.auth_type or "none") != "none",
**(
lambda cred_state: {
"has_credentials": cred_state[0],
"credential_preview": cred_state[1],
}
)(
build_masked_credential_preview(
requires_credentials=(c.auth_type or "none") != "none",
auth_type=c.auth_type,
auth_config=c.auth_config,
)
),
"headers": c.headers,
"config": c.config,
"is_active": c.is_active,
@@ -412,12 +532,30 @@ async def list_all_datasources(
db: AsyncSession = Depends(get_db),
):
"""List all data sources: YAML defaults + DB overrides"""
from app.api.v1.datasources import infer_datasource_product_key
from app.core.data_sources import get_data_sources_config
config = get_data_sources_config()
db_query = await db.execute(select(DataSourceConfig))
db_configs = {c.name: c for c in db_query.scalars().all()}
connectivity_store = await get_connectivity_store(db)
resolved_provider_values: dict[str, dict[str, str]] = {}
bw_cfg = await resolve_barentswatch_config(db)
resolved_provider_values["barentswatch"] = {
"client_id": bw_cfg.client_id,
"client_secret": bw_cfg.client_secret,
}
st_user, st_pass, _ = await resolve_spacetrack_credentials(db)
resolved_provider_values["spacetrack"] = {
"username": st_user,
"password": st_pass,
}
ais_key, _ = await _resolve_aisstream_api_key(db)
resolved_provider_values["aisstream"] = {
"api_key": ais_key,
}
result = []
for name, metadata in DEFAULT_DATASOURCES.items():
@@ -426,13 +564,47 @@ async def list_all_datasources(
default_config = _default_builtin_config(name)
default_url = yaml_url
db_auth_config = db_config.auth_config or {} if db_config else {}
product = infer_datasource_product_key(name, str(metadata.get("name") or ""), name)
requires_credentials = bool(metadata.get("requires_credentials", False))
credential_provider = metadata.get("credential_provider")
provider_key = str(credential_provider or "").strip().lower()
effective_auth_type = db_config.auth_type if db_config else (
"oauth2" if provider_key == "barentswatch" else (
"basic" if provider_key == "spacetrack" else (
"api_key" if provider_key == "aisstream" else "none"
)
)
)
has_credentials, credential_preview = build_masked_credential_preview(
requires_credentials=requires_credentials,
auth_type=effective_auth_type,
auth_config=db_auth_config,
resolved_provider=provider_key,
resolved_values=resolved_provider_values.get(provider_key),
)
validation = connectivity_store.get(name) if isinstance(connectivity_store, dict) else None
connectivity_status = (
"missing_credentials"
if requires_credentials and not has_credentials
else (
"connected"
if isinstance(validation, dict) and validation.get("status") == "success"
else "unverified"
)
)
result.append(
{
"name": name,
"requires_credentials": bool(metadata.get("requires_credentials", False)),
"credential_provider": metadata.get("credential_provider"),
"display_name": metadata.get("display_name") or metadata.get("name") or name,
"product": product,
"requires_credentials": requires_credentials,
"credential_provider": credential_provider,
"credential_status": metadata.get("credential_status", "none"),
"has_credentials": has_credentials,
"credential_preview": credential_preview,
"connectivity_status": connectivity_status,
"connectivity_checked_at": validation.get("checked_at") if isinstance(validation, dict) else None,
"default_url": default_url,
"endpoint": db_config.endpoint if db_config else default_url,
"is_overridden": db_config is not None and db_config.endpoint != yaml_url
@@ -715,6 +887,9 @@ async def delete_config(
)
deleted_records["collected_data"] = collected_result.rowcount or 0
else:
from app.models.aircraft import ADSBSourceHealth, AircraftCurrentState
from app.models.gps_jamming import GPSJammingCell
collected_result = await db.execute(
delete(CollectedData).where(CollectedData.source == config.name)
)
@@ -727,11 +902,23 @@ async def delete_config(
health_result = await db.execute(
delete(AISSourceHealth).where(AISSourceHealth.source == config.name)
)
aircraft_result = await db.execute(
delete(AircraftCurrentState).where(AircraftCurrentState.source == config.name)
)
adsb_health_result = await db.execute(
delete(ADSBSourceHealth).where(ADSBSourceHealth.source == config.name)
)
jam_result = await db.execute(
delete(GPSJammingCell).where(GPSJammingCell.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,
"aircraft_current_state": aircraft_result.rowcount or 0,
"adsb_source_health": adsb_health_result.rowcount or 0,
"gps_jamming_cells": jam_result.rowcount or 0,
}
if delete_mappings or delete_source_data:
+20 -5
View File
@@ -43,8 +43,11 @@ DATASOURCE_ADMIN_ROLES = {UserRole.ADMIN.value, UserRole.SUPER_ADMIN.value}
PRODUCT_SOURCE_KEYWORDS: tuple[tuple[str, tuple[str, ...]], ...] = (
("geo", ("earth_imagery", "sentinel2", "viirs", "basemap", "imagery")),
("weather", ("cloud", "weather", "meteorolog", "atmosphere", "ir108", "wind", "gfs")),
("vessels", ("vessel", "ais")),
("cables", ("cable", "landing", "telegeography", "arcgis", "fao")),
("cables", ("cable", "landing", "telegeography", "arcgis", "fao", "nga_navigation")),
("disasters", ("usgs_earthquakes", "nasa_firms", "gdacs", "eonet", "disaster", "wildfire")),
("satellites", ("tle", "satellite", "spacetrack", "celestrak")),
("bgp", ("bgp", "asn", "prefix_geo", "opengeofeed", "nro")),
("compute", ("top500", "gpu", "supercomputer", "compute")),
@@ -99,12 +102,16 @@ def datasource_metadata(source: str) -> dict:
}
def datasource_product_key(datasource: DataSource) -> str:
def infer_datasource_product_key(
source: str = "",
name: str = "",
collector_class: str = "",
) -> str:
haystack = " ".join(
[
datasource.source or "",
datasource.name or "",
datasource.collector_class or "",
source or "",
name or "",
collector_class or "",
]
).lower()
for product, keywords in PRODUCT_SOURCE_KEYWORDS:
@@ -113,6 +120,14 @@ def datasource_product_key(datasource: DataSource) -> str:
return "other"
def datasource_product_key(datasource: DataSource) -> str:
return infer_datasource_product_key(
datasource.source or "",
datasource.name or "",
datasource.collector_class or "",
)
def is_due_for_collection(datasource: DataSource, now: datetime) -> bool:
if datasource.last_run_at is None:
return True
+80
View File
@@ -0,0 +1,80 @@
"""Natural disaster telemetry snapshot API."""
from __future__ import annotations
from datetime import UTC, datetime, timedelta
from typing import Any
from fastapi import APIRouter, Depends, Query
from sqlalchemy import desc, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.access_gate import require_earth_or_api_access
from app.core.time import to_iso8601_utc
from app.db.session import get_db
from app.models.disaster import DisasterEvent
router = APIRouter(dependencies=[Depends(require_earth_or_api_access("visualization:read"))])
_DEFAULT_STALE_SECONDS = 60 * 60
def _coerce_utc(val: Any) -> datetime | None:
if isinstance(val, datetime):
return val.replace(tzinfo=UTC) if val.tzinfo is None else val.astimezone(UTC)
return None
@router.get("/snapshot")
async def get_disaster_snapshot(
types: str | None = Query(default=None, description="Comma-separated disaster event types"),
since_hours: int = Query(default=72, ge=1, le=720),
include_duplicates: bool = Query(default=False),
limit: int = Query(default=1000, ge=1, le=5000),
db: AsyncSession = Depends(get_db),
) -> dict[str, Any]:
"""Return recent normalized natural disaster events with freshness and provenance fields."""
now = datetime.now(UTC)
cutoff = now - timedelta(hours=since_hours)
stmt = (
select(DisasterEvent)
.where(DisasterEvent.observed_at >= cutoff)
.order_by(desc(DisasterEvent.observed_at), desc(DisasterEvent.id))
.limit(limit)
)
if types:
wanted = [t.strip().lower() for t in types.split(",") if t.strip()]
if wanted:
stmt = stmt.where(DisasterEvent.event_type.in_(wanted))
if not include_duplicates:
stmt = stmt.where(DisasterEvent.duplicate_of.is_(None))
rows = list((await db.execute(stmt)).scalars().all())
by_type: dict[str, int] = {}
high_count = 0
latest_obs: datetime | None = None
items: list[dict[str, Any]] = []
for row in rows:
obs = _coerce_utc(row.observed_at)
if obs and (latest_obs is None or obs > latest_obs):
latest_obs = obs
is_stale = bool(obs is None or (now - obs).total_seconds() > _DEFAULT_STALE_SECONDS)
ev_type = str(row.event_type or "other")
by_type[ev_type] = by_type.get(ev_type, 0) + 1
if str(row.severity or "").lower() == "high":
high_count += 1
payload = row.to_dict()
payload["is_stale"] = is_stale
items.append(payload)
return {
"generated_at": to_iso8601_utc(now),
"since_hours": since_hours,
"count": len(items),
"high_count": high_count,
"by_type": by_type,
"latest_observed_at": to_iso8601_utc(latest_obs),
"items": items,
}
+444 -5
View File
@@ -2,11 +2,14 @@
from __future__ import annotations
import hashlib
import json
from pathlib import Path
from typing import Any
from uuid import uuid4
from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, Request, UploadFile, status
from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, Request, Response, UploadFile, status
from fastapi.responses import FileResponse
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from pydantic import BaseModel, Field
from sqlalchemy import delete, func, select, text
@@ -14,6 +17,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.core.access_gate import require_earth_or_api_access
from app.core.config import settings as app_settings
from app.core.enums import UserRole
from app.core.logging import get_logger
from app.core.security import (
decode_token,
@@ -53,6 +57,8 @@ from app.services.earth_boundaries import (
EarthBoundaryBuildError,
get_boundary_build_status,
get_boundary_status,
get_public_boundary_manifest,
resolve_boundary_artifact,
save_boundary_config,
start_boundary_build_job,
)
@@ -297,9 +303,37 @@ async def _broadcast_earth_config_update(layer: str) -> None:
logger.warning("Failed to broadcast %s update: %s", layer, exc)
def _etag_matches(if_none_match: str | None, etag: str) -> bool:
if not if_none_match:
return False
target = etag.strip()
if target.startswith("W/"):
target = 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 == target:
return True
return False
def _json_etag(payload: Any) -> str:
encoded = json.dumps(payload, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
return f'"{hashlib.sha256(encoded.encode("utf-8")).hexdigest()[:24]}"'
@router.get("/brand", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
async def get_earth_brand(db: AsyncSession = Depends(get_db)):
return await _get_earth_brand_payload(db)
async def get_earth_brand(request: Request, response: Response, db: AsyncSession = Depends(get_db)):
payload = await _get_earth_brand_payload(db)
etag = _json_etag(payload)
headers = {"Cache-Control": "private, no-cache", "ETag": etag}
if _etag_matches(request.headers.get("if-none-match"), etag):
return Response(status_code=304, headers=headers)
response.headers.update(headers)
return payload
@router.put("/brand")
@@ -368,8 +402,14 @@ async def upload_earth_brand_asset(
@router.get("/about", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
async def get_earth_about(db: AsyncSession = Depends(get_db)):
return await _get_earth_about_payload(db)
async def get_earth_about(request: Request, response: Response, db: AsyncSession = Depends(get_db)):
payload = await _get_earth_about_payload(db)
etag = _json_etag(payload)
headers = {"Cache-Control": "private, no-cache", "ETag": etag}
if _etag_matches(request.headers.get("if-none-match"), etag):
return Response(status_code=304, headers=headers)
response.headers.update(headers)
return payload
@router.put("/about")
@@ -676,6 +716,38 @@ async def get_earth_oobe_status(
async def get_earth_boundary_status():
return get_boundary_status()
@router.get("/boundaries/manifest", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
async def get_earth_boundary_manifest(response: Response):
manifest = get_public_boundary_manifest()
if manifest is None:
raise HTTPException(status_code=404, detail="Verified Earth boundary artifact not built")
response.headers["Cache-Control"] = "no-cache"
return manifest
BOUNDARY_ARTIFACT_MEDIA_TYPES = {".pmtiles": "application/vnd.pmtiles", ".json": "application/json"}
_boundary_file_access = Depends(
require_earth_or_api_access("earth:read", rate_limit_tier="tile")
)
@router.get("/boundaries/files/{name}", dependencies=[_boundary_file_access])
@router.head("/boundaries/files/{name}", include_in_schema=False, dependencies=[_boundary_file_access])
async def get_earth_boundary_file(name: str):
path = resolve_boundary_artifact(name)
if path is None:
raise HTTPException(status_code=404, detail="Earth boundary artifact not found")
# Artifact names embed the build hash, so clients may cache them forever.
# FileResponse answers Range requests with 206 for PMTiles reads.
return FileResponse(
path,
media_type=BOUNDARY_ARTIFACT_MEDIA_TYPES.get(path.suffix, "application/octet-stream"),
headers={"Cache-Control": "public, max-age=31536000, immutable"},
)
def _is_loopback_request(request: Request) -> bool:
host = request.client.host if request.client else ""
return host in {"127.0.0.1", "::1", "localhost"} or host.startswith("127.")
@@ -722,3 +794,370 @@ async def build_earth_boundary_assets(
@router.get("/boundaries/build/status", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
async def get_earth_boundary_build_status():
return get_boundary_build_status()
def _require_cloud_admin(user: User) -> None:
role = getattr(user.role, "value", user.role)
if str(role).lower() not in {UserRole.ADMIN.value, UserRole.SUPER_ADMIN.value}:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Only administrators can modify cloud map configuration",
)
def _require_cloud_operator(user: User) -> None:
role = getattr(user.role, "value", user.role)
if str(role).lower() not in {
UserRole.ADMIN.value,
UserRole.SUPER_ADMIN.value,
}:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Administrator access required",
)
class CloudMapConfigUpdatePayload(BaseModel):
revision: str = Field(..., min_length=4, max_length=128)
config: dict[str, Any] = Field(default_factory=dict)
class CloudMapSourceTestPayload(BaseModel):
source_id: str = Field(default="multi_sat_ir", max_length=64)
timeout_seconds: int = Field(default=15, ge=5, le=45)
@router.get("/clouds/meta", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
async def get_earth_clouds_meta(db: AsyncSession = Depends(get_db)):
from app.services.earth_clouds import get_cloud_map_runtime_meta
return await get_cloud_map_runtime_meta(db)
@router.get("/clouds/frames/{version}", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
async def get_earth_cloud_frame(version: str):
from app.services.earth_clouds import read_cloud_frame_bytes
content = read_cloud_frame_bytes(version)
if content is None:
raise HTTPException(status_code=404, detail="Cloud frame not found")
return Response(
content=content,
media_type="image/webp",
headers={"Cache-Control": "public, max-age=86400, immutable"},
)
@router.get("/clouds/configuration")
async def get_earth_cloud_configuration(
_current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
from app.services.earth_clouds import (
get_cloud_datasource_summary,
get_cloud_map_runtime_meta,
read_cloud_map_configuration,
)
envelope = await read_cloud_map_configuration(db)
meta = await get_cloud_map_runtime_meta(db)
datasource = await get_cloud_datasource_summary(db)
return {
**envelope,
"meta": meta,
"datasource": datasource,
}
@router.put("/clouds/configuration")
async def put_earth_cloud_configuration(
payload: CloudMapConfigUpdatePayload,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
from pydantic import ValidationError
from app.services.earth_clouds import (
CloudMapConfig,
CloudMapRevisionConflictError,
get_cloud_datasource_summary,
get_cloud_map_runtime_meta,
save_cloud_map_configuration,
)
_require_cloud_admin(current_user)
try:
validated = CloudMapConfig.model_validate(payload.config)
envelope = await save_cloud_map_configuration(
db,
revision=payload.revision,
config=validated,
actor=current_user,
reset=False,
)
except ValidationError as exc:
raise HTTPException(status_code=422, detail=exc.errors()) from exc
except CloudMapRevisionConflictError as exc:
raise HTTPException(status_code=409, detail=str(exc)) from exc
await _broadcast_earth_config_update("clouds")
return {
**envelope,
"meta": await get_cloud_map_runtime_meta(db),
"datasource": await get_cloud_datasource_summary(db),
}
@router.post("/clouds/configuration/reset")
async def reset_earth_cloud_configuration(
payload: CloudMapConfigUpdatePayload,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
from app.services.earth_clouds import (
CloudMapRevisionConflictError,
DEFAULT_CLOUD_CONFIG,
get_cloud_datasource_summary,
get_cloud_map_runtime_meta,
save_cloud_map_configuration,
)
_require_cloud_admin(current_user)
try:
envelope = await save_cloud_map_configuration(
db,
revision=payload.revision,
config=DEFAULT_CLOUD_CONFIG,
actor=current_user,
reset=True,
)
except CloudMapRevisionConflictError as exc:
raise HTTPException(status_code=409, detail=str(exc)) from exc
await _broadcast_earth_config_update("clouds")
return {
**envelope,
"meta": await get_cloud_map_runtime_meta(db),
"datasource": await get_cloud_datasource_summary(db),
}
@router.post("/clouds/test")
async def test_earth_cloud_source(
payload: CloudMapSourceTestPayload,
current_user: User = Depends(get_current_user),
):
from app.services.earth_clouds import test_cloud_map_source
_require_cloud_operator(current_user)
try:
return await test_cloud_map_source(payload.source_id, timeout_seconds=payload.timeout_seconds)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@router.delete("/clouds/cache")
async def clear_earth_cloud_cache(
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
from app.services.earth_clouds import clear_all_cloud_map_artifacts, get_cloud_map_runtime_meta
_require_cloud_admin(current_user)
removed = clear_all_cloud_map_artifacts()
await _broadcast_earth_config_update("clouds")
return {
"removed_files": removed,
"meta": await get_cloud_map_runtime_meta(db),
}
@router.get("/clouds/frames/{version}/visual", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
async def get_earth_cloud_visual_frame(version: str):
from app.services.earth_clouds import read_cloud_visual_frame_bytes
content = read_cloud_visual_frame_bytes(version)
if content is None:
raise HTTPException(status_code=404, detail="Cloud visual frame not found")
return Response(
content=content,
media_type="image/webp",
headers={"Cache-Control": "public, max-age=86400, immutable"},
)
@router.get("/clouds/flows/{version}", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
async def get_earth_cloud_flow_map(version: str):
from app.services.earth_clouds import read_cloud_flow_bytes
content = read_cloud_flow_bytes(version)
if content is None:
raise HTTPException(status_code=404, detail="Cloud optical flow map not found")
return Response(
content=content,
media_type="image/webp",
headers={"Cache-Control": "public, max-age=86400, immutable"},
)
class BasemapConfigUpdatePayload(BaseModel):
revision: str = Field(..., min_length=4, max_length=128)
config: dict[str, Any] = Field(default_factory=dict)
@router.get(
"/tiles/{source_key}/{z}/{x}/{y}.webp",
dependencies=[Depends(require_earth_or_api_access("earth:read", rate_limit_tier="tile"))],
)
async def get_earth_managed_tile(
source_key: str,
z: int,
x: int,
y: int,
db: AsyncSession = Depends(get_db),
):
from app.services.earth_tiles import get_or_fetch_tile
try:
content, allowed = await get_or_fetch_tile(source_key, z, x, y, db=db)
except ValueError as exc:
raise HTTPException(status_code=404, detail=str(exc)) from exc
if not allowed:
raise HTTPException(status_code=403, detail=f"Tile source '{source_key}' is disabled")
if content is None:
raise HTTPException(status_code=404, detail="Tile not available")
cache_max_age = 300 if source_key == "cloud_hd_tiles" else 86400
return Response(
content=content,
media_type="image/webp",
headers={"Cache-Control": f"public, max-age={cache_max_age}"},
)
@router.get("/basemap/meta", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
async def get_earth_basemap_meta(db: AsyncSession = Depends(get_db)):
from app.services.earth_tiles import get_basemap_runtime_meta
return await get_basemap_runtime_meta(db)
@router.get("/basemap/configuration")
async def get_earth_basemap_configuration(
_current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
from app.services.earth_tiles import get_basemap_runtime_meta, read_basemap_configuration
envelope = await read_basemap_configuration(db)
return {
**envelope,
"meta": await get_basemap_runtime_meta(db),
}
@router.put("/basemap/configuration")
async def put_earth_basemap_configuration(
payload: BasemapConfigUpdatePayload,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
from pydantic import ValidationError
from app.services.earth_tiles import (
BasemapConfig,
BasemapRevisionConflictError,
get_basemap_runtime_meta,
save_basemap_configuration,
)
_require_cloud_admin(current_user)
try:
validated = BasemapConfig.model_validate(payload.config)
envelope = await save_basemap_configuration(
db,
revision=payload.revision,
config=validated,
actor=current_user,
reset=False,
)
except ValidationError as exc:
raise HTTPException(status_code=422, detail=exc.errors()) from exc
except BasemapRevisionConflictError as exc:
raise HTTPException(status_code=409, detail=str(exc)) from exc
await _broadcast_earth_config_update("basemap")
return {
**envelope,
"meta": await get_basemap_runtime_meta(db),
}
@router.post("/basemap/configuration/reset")
async def reset_earth_basemap_configuration(
payload: BasemapConfigUpdatePayload,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
from app.services.earth_tiles import (
BasemapRevisionConflictError,
DEFAULT_BASEMAP_CONFIG,
get_basemap_runtime_meta,
save_basemap_configuration,
)
_require_cloud_admin(current_user)
try:
envelope = await save_basemap_configuration(
db,
revision=payload.revision,
config=DEFAULT_BASEMAP_CONFIG,
actor=current_user,
reset=True,
)
except BasemapRevisionConflictError as exc:
raise HTTPException(status_code=409, detail=str(exc)) from exc
await _broadcast_earth_config_update("basemap")
return {
**envelope,
"meta": await get_basemap_runtime_meta(db),
}
@router.delete("/tiles/{source_key}/cache")
async def clear_earth_tile_cache_route(
source_key: str,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
from app.services.earth_tiles import (
TILE_SOURCES,
clear_tile_source_cache,
get_basemap_runtime_meta,
)
_require_cloud_admin(current_user)
if source_key not in TILE_SOURCES:
raise HTTPException(status_code=404, detail="Unknown tile source")
removed = clear_tile_source_cache(source_key)
await _broadcast_earth_config_update("basemap")
return {
"source": source_key,
"removed_files": removed,
"meta": await get_basemap_runtime_meta(db),
}
@router.get("/wind/meta", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
async def get_earth_wind_meta(db: AsyncSession = Depends(get_db)):
from app.services.earth_wind import get_wind_runtime_meta
return await get_wind_runtime_meta(db)
@router.get("/wind/grid/{version}", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
async def get_earth_wind_grid(version: str):
from app.services.earth_wind import read_wind_grid_payload
payload = read_wind_grid_payload(version)
if payload is None:
raise HTTPException(status_code=404, detail="Wind grid snapshot not found")
return payload
+127
View File
@@ -0,0 +1,127 @@
"""Geofence CRUD & preset listing API (§3.8)."""
from __future__ import annotations
from typing import Any
from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import BaseModel, Field
from sqlalchemy import desc, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.access_gate import require_admin_user, require_earth_or_api_access
from app.db.session import get_db
from app.models.geofence import Geofence
from app.models.user import User
from app.services.fusion.anomaly_engine import ensure_preset_geofences
router = APIRouter()
_read_dep = Depends(require_earth_or_api_access("visualization:read"))
class GeofenceCreateRequest(BaseModel):
name: str = Field(min_length=1, max_length=200)
kind: str = Field(default="custom", max_length=32)
geometry: dict[str, Any]
rules: dict[str, Any] = Field(default_factory=dict)
enabled: bool = True
class GeofenceUpdateRequest(BaseModel):
name: str | None = Field(default=None, min_length=1, max_length=200)
geometry: dict[str, Any] | None = None
rules: dict[str, Any] | None = None
enabled: bool | None = None
def _validate_polygon_geometry(geometry: dict[str, Any]) -> None:
if not isinstance(geometry, dict):
raise HTTPException(status_code=422, detail="Geofence geometry must be a GeoJSON object")
gtype = geometry.get("type")
coords = geometry.get("coordinates")
if gtype not in {"Polygon", "MultiPolygon"} or not isinstance(coords, list) or not coords:
raise HTTPException(
status_code=422,
detail="Geofence geometry must be a GeoJSON Polygon or MultiPolygon",
)
@router.get("", dependencies=[_read_dep])
async def list_geofences(
enabled_only: bool = Query(default=False),
kind: str | None = Query(default=None),
ensure_presets: bool = Query(default=True),
db: AsyncSession = Depends(get_db),
) -> dict[str, Any]:
if ensure_presets:
await ensure_preset_geofences(db)
stmt = select(Geofence).order_by(desc(Geofence.id))
if enabled_only:
stmt = stmt.where(Geofence.enabled.is_(True))
if kind:
stmt = stmt.where(Geofence.kind == kind.strip())
rows = list((await db.execute(stmt)).scalars().all())
return {"items": [r.to_dict() for r in rows], "count": len(rows)}
@router.post("")
async def create_geofence(
body: GeofenceCreateRequest,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(require_admin_user),
) -> dict[str, Any]:
_validate_polygon_geometry(body.geometry)
gf = Geofence(
name=body.name.strip(),
kind="preset" if body.kind == "preset" else "custom",
geometry=body.geometry,
rules=body.rules or {
"enable_loitering": True,
"enable_dark_target": True,
"enable_surge": True,
"dark_threshold_minutes": 45,
"surge_sigma": 2.0,
},
enabled=bool(body.enabled),
created_by=current_user.username,
)
db.add(gf)
await db.commit()
return gf.to_dict()
@router.patch("/{geofence_id}")
async def update_geofence(
geofence_id: int,
body: GeofenceUpdateRequest,
db: AsyncSession = Depends(get_db),
_admin: User = Depends(require_admin_user),
) -> dict[str, Any]:
gf = await db.get(Geofence, geofence_id)
if gf is None:
raise HTTPException(status_code=404, detail="Geofence not found")
if body.name is not None:
gf.name = body.name.strip()
if body.geometry is not None:
_validate_polygon_geometry(body.geometry)
gf.geometry = body.geometry
if body.rules is not None:
gf.rules = body.rules
if body.enabled is not None:
gf.enabled = bool(body.enabled)
await db.commit()
return gf.to_dict()
@router.delete("/{geofence_id}")
async def delete_geofence(
geofence_id: int,
db: AsyncSession = Depends(get_db),
_admin: User = Depends(require_admin_user),
) -> dict[str, Any]:
gf = await db.get(Geofence, geofence_id)
if gf is None:
raise HTTPException(status_code=404, detail="Geofence not found")
await db.delete(gf)
await db.commit()
return {"deleted": True, "id": geofence_id}
+88
View File
@@ -0,0 +1,88 @@
"""GPS/GNSS H3 interference snapshot API."""
from __future__ import annotations
from datetime import UTC, datetime
from typing import Optional
from fastapi import APIRouter, Depends, Query
from sqlalchemy import desc, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.access_gate import require_earth_or_api_access
from app.core.time import to_iso8601_utc
from app.db.session import get_db
from app.models.gps_jamming import GPSJammingCell
from app.services.aircraft_aggregation import coerce_utc_datetime
router = APIRouter()
GPS_JAMMING_FRESHNESS_SECONDS = 36 * 3600
GPSJAM_ATTRIBUTION = "gpsjam.org (underlying telemetry via airplanes.live & ADS-B Exchange; aircraft-reported NIC/NACp)"
@router.get("/snapshot", dependencies=[Depends(require_earth_or_api_access("gps_jamming:read"))])
async def get_gps_jamming_snapshot(
date: Optional[str] = Query(None, description="Observed date YYYY-MM-DD (defaults to latest date)"),
level: Optional[str] = Query(None, description="Optional comma-separated severity levels: high,medium,low"),
db: AsyncSession = Depends(get_db),
):
now = datetime.now(UTC)
target_date = str(date or "").strip() or None
if not target_date:
latest_res = await db.execute(
select(GPSJammingCell.observed_date)
.order_by(desc(GPSJammingCell.observed_date))
.limit(1)
)
target_date = latest_res.scalar_one_or_none()
if not target_date:
return {
"date": None,
"cells": [],
"stats": {"total": 0, "high": 0, "medium": 0, "low": 0},
"source": "gpsjam_interference",
"observed_at": None,
"ingested_at": None,
"is_stale": True,
"generated_at": to_iso8601_utc(now),
"attribution": GPSJAM_ATTRIBUTION,
}
stmt = select(GPSJammingCell).where(GPSJammingCell.observed_date == target_date)
if level:
levels = [part.strip().lower() for part in level.split(",") if part.strip()]
if levels:
stmt = stmt.where(GPSJammingCell.level.in_(levels))
res = await db.execute(stmt.order_by(desc(GPSJammingCell.bad_ratio)))
rows = list(res.scalars().all())
counts = {"total": len(rows), "high": 0, "medium": 0, "low": 0}
cells: list[dict[str, object]] = []
latest_ingested: datetime | None = None
for row in rows:
lvl = str(row.level or "low").lower()
if lvl in counts:
counts[lvl] += 1
ing = coerce_utc_datetime(row.ingested_at) if row.ingested_at else None
if ing and (latest_ingested is None or ing > latest_ingested):
latest_ingested = ing
cells.append(row.to_dict())
observed_dt = coerce_utc_datetime(f"{target_date}T23:59:59+00:00", fallback=now)
ref_time = latest_ingested or observed_dt
is_stale = (now - ref_time).total_seconds() > GPS_JAMMING_FRESHNESS_SECONDS
return {
"date": target_date,
"cells": cells,
"stats": counts,
"source": "gpsjam_interference",
"observed_at": to_iso8601_utc(observed_dt),
"ingested_at": to_iso8601_utc(latest_ingested),
"is_stale": is_stale,
"generated_at": to_iso8601_utc(now),
"attribution": GPSJAM_ATTRIBUTION,
}
+203
View File
@@ -0,0 +1,203 @@
"""Situational incidents triage & Earth overlay API (§3.8 & §3.9)."""
from __future__ import annotations
from typing import Any
import h3
from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import BaseModel, Field
from sqlalchemy import desc, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.access_gate import require_admin_user, require_earth_or_api_access
from app.db.session import get_db
from app.models.geofence import SituationalIncident
from app.models.user import User
router = APIRouter()
_read_dep = Depends(require_earth_or_api_access("visualization:read"))
class IncidentTransitionRequest(BaseModel):
resolution_note: str | None = Field(default=None, max_length=1000)
class ScenarioRunRequest(BaseModel):
workflow_id: str = Field(min_length=3, max_length=80)
cable_id: str | None = None
suspect_vessel_mmsi: int | None = None
center_lat: float = 2.0
center_lon: float = 102.0
radius_km: float = 350.0
persist_incident: bool = True
@router.get("", dependencies=[_read_dep])
async def list_incidents(
status: str | None = Query(default=None),
assessment_kind: str | None = Query(default=None),
limit: int = Query(default=100, ge=1, le=500),
db: AsyncSession = Depends(get_db),
) -> dict[str, Any]:
stmt = select(SituationalIncident).order_by(desc(SituationalIncident.created_at), desc(SituationalIncident.id)).limit(limit)
if status:
stmt = stmt.where(SituationalIncident.status == status.strip())
if assessment_kind:
stmt = stmt.where(SituationalIncident.assessment_kind == assessment_kind.strip())
rows = list((await db.execute(stmt)).scalars().all())
return {"items": [r.to_dict() for r in rows], "count": len(rows)}
@router.get("/overlay", dependencies=[_read_dep])
async def get_incidents_overlay(
limit: int = Query(default=100, ge=1, le=300),
db: AsyncSession = Depends(get_db),
) -> dict[str, Any]:
"""Return H3 hex cells for `candidate_correlation` and solid arcs for `dependency_impact`."""
stmt = (
select(SituationalIncident)
.where(SituationalIncident.status.in_(["open", "acknowledged"]))
.order_by(desc(SituationalIncident.created_at))
.limit(limit)
)
rows = list((await db.execute(stmt)).scalars().all())
candidate_cells: list[dict[str, Any]] = []
dependency_arcs: list[dict[str, Any]] = []
for row in rows:
if row.assessment_kind == "candidate_correlation" and row.h3_index:
try:
boundary = [
[float(lat), float(lon)]
for lat, lon in h3.cell_to_boundary(row.h3_index)
]
center_lat, center_lon = h3.cell_to_latlng(row.h3_index)
except Exception:
boundary = []
center_lat, center_lon = None, None
candidate_cells.append(
{
"incident_id": row.id,
"h3_index": row.h3_index,
"title": row.title,
"label": "待核查",
"status": row.status,
"center": [center_lat, center_lon],
"boundary": boundary,
"signal_types": (row.signal_summary or {}).get("signal_types", []),
}
)
elif row.assessment_kind == "dependency_impact":
for arc in (row.signal_summary or {}).get("impact_arcs", []) or []:
dependency_arcs.append(
{
**arc,
"incident_id": row.id,
"status": row.status,
"title": row.title,
}
)
return {
"candidate_cells": candidate_cells,
"dependency_arcs": dependency_arcs,
}
@router.get("/{incident_id}", dependencies=[_read_dep])
async def get_incident(
incident_id: int,
db: AsyncSession = Depends(get_db),
) -> dict[str, Any]:
row = await db.get(SituationalIncident, incident_id)
if row is None:
raise HTTPException(status_code=404, detail="Incident not found")
return row.to_dict()
@router.post("/{incident_id}/acknowledge")
async def acknowledge_incident(
incident_id: int,
body: IncidentTransitionRequest | None = None,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(require_admin_user),
) -> dict[str, Any]:
row = await db.get(SituationalIncident, incident_id)
if row is None:
raise HTTPException(status_code=404, detail="Incident not found")
row.status = "acknowledged"
row.updated_by = current_user.username
if body and body.resolution_note and body.resolution_note.strip():
row.resolution_note = body.resolution_note.strip()
await db.commit()
return row.to_dict()
@router.post("/{incident_id}/dismiss")
async def dismiss_incident(
incident_id: int,
body: IncidentTransitionRequest,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(require_admin_user),
) -> dict[str, Any]:
reason = str(body.resolution_note or "").strip() if body else ""
if not reason:
raise HTTPException(status_code=422, detail="Dismissing an incident requires a resolution_note")
row = await db.get(SituationalIncident, incident_id)
if row is None:
raise HTTPException(status_code=404, detail="Incident not found")
row.status = "dismissed"
row.updated_by = current_user.username
row.resolution_note = reason
await db.commit()
return row.to_dict()
@router.post("/{incident_id}/resolve")
async def resolve_incident(
incident_id: int,
body: IncidentTransitionRequest | None = None,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(require_admin_user),
) -> dict[str, Any]:
row = await db.get(SituationalIncident, incident_id)
if row is None:
raise HTTPException(status_code=404, detail="Incident not found")
row.status = "resolved"
row.updated_by = current_user.username
if body and body.resolution_note and body.resolution_note.strip():
row.resolution_note = body.resolution_note.strip()
await db.commit()
return row.to_dict()
@router.post("/scenarios/run")
async def run_wargame_scenario_endpoint(
body: ScenarioRunRequest,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(require_admin_user),
) -> dict[str, Any]:
"""Execute one built-in §3.10 wargame scenario (`wargame.cable_protection` or `wargame.air_sea_em`)."""
from app.services.fusion.wargame_scenarios import (
run_air_sea_em_scenario,
run_cable_protection_scenario,
)
wf = body.workflow_id.strip()
if wf == "wargame.cable_protection":
return await run_cable_protection_scenario(
db,
cable_id=body.cable_id or "apg-1",
suspect_vessel_mmsi=body.suspect_vessel_mmsi,
persist_incident=bool(body.persist_incident),
)
if wf == "wargame.air_sea_em":
return await run_air_sea_em_scenario(
db,
center_lat=body.center_lat,
center_lon=body.center_lon,
radius_km=body.radius_km,
persist_incident=bool(body.persist_incident),
)
raise HTTPException(status_code=400, detail=f"Unsupported scenario workflow: {wf}")
+92 -2
View File
@@ -5,11 +5,11 @@ from __future__ import annotations
from datetime import UTC, datetime
from typing import Any
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, Response, UploadFile, status
from pydantic import BaseModel, Field, field_validator
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.access_gate import require_earth_or_api_access
from app.core.access_gate import require_admin_user, require_earth_or_api_access
from app.core.security import get_current_user
from app.db.session import get_db
from app.models.earth_interactable import EarthInteractable
@@ -100,6 +100,96 @@ async def get_interactables_geojson(
return payload
class PrivateRestPreviewRequest(BaseModel):
rest_url: str | None = None
root_path: str | None = None
records: list[dict[str, Any]] | None = None
field_mapping: dict[str, Any] | None = None
class PrivateCommitRequest(BaseModel):
records: list[dict[str, Any]]
field_mapping: dict[str, Any]
default_kind: str = "private_asset"
layer_name: str = "interactables"
source_label: str = "private_upload"
@router.post("/upload/preview")
async def preview_private_upload(
file: UploadFile | None = File(default=None),
fmt: str = Form(default="csv"),
rest_url: str | None = Form(default=None),
root_path: str | None = Form(default=None),
_admin: User = Depends(require_admin_user),
) -> dict[str, Any]:
"""Preview columns & suggested field mapping from uploaded CSV/JSON or REST endpoint."""
from app.services.private_data_ingest import (
fetch_rest_records_for_upload,
parse_tabular_or_json_bytes,
preview_private_mapping,
)
try:
if file is not None:
raw = await file.read()
detected_fmt = fmt
if file.filename and file.filename.lower().endswith(".json"):
detected_fmt = "json"
records = parse_tabular_or_json_bytes(raw, fmt=detected_fmt)
elif rest_url:
records = await fetch_rest_records_for_upload(rest_url.strip(), root_path=root_path)
else:
raise HTTPException(status_code=422, detail="file or rest_url is required")
except ValueError as exc:
raise HTTPException(status_code=413 if "超出上限" in str(exc) else 422, detail=str(exc)) from exc
return preview_private_mapping(records) | {"records": records[:200]}
@router.post("/upload/preview-json")
async def preview_private_json_payload(
body: PrivateRestPreviewRequest,
_admin: User = Depends(require_admin_user),
) -> dict[str, Any]:
from app.services.private_data_ingest import (
fetch_rest_records_for_upload,
preview_private_mapping,
)
try:
if body.records is not None:
records = list(body.records)
elif body.rest_url:
records = await fetch_rest_records_for_upload(body.rest_url.strip(), root_path=body.root_path)
else:
raise HTTPException(status_code=422, detail="records or rest_url is required")
except ValueError as exc:
raise HTTPException(status_code=413 if "超出上限" in str(exc) else 422, detail=str(exc)) from exc
return preview_private_mapping(records, custom_mapping=body.field_mapping) | {"records": records}
@router.post("/upload/commit")
async def commit_private_upload(
body: PrivateCommitRequest,
db: AsyncSession = Depends(get_db),
_admin: User = Depends(require_admin_user),
) -> dict[str, Any]:
"""Commit mapped private objects into `earth_interactables` (`interactable:{id}`)."""
from app.services.private_data_ingest import commit_private_records_to_globe
result = await commit_private_records_to_globe(
db,
records=body.records,
field_mapping=body.field_mapping,
default_kind=body.default_kind,
layer_name=body.layer_name,
source_label=body.source_label,
)
invalidate_interactable_cache(body.layer_name)
return result
@router.post("", status_code=status.HTTP_201_CREATED)
async def create_interactable(
payload: InteractableCreate,
+2
View File
@@ -161,6 +161,7 @@ async def get_earth_feed(
),
categories: str | None = Query(None, description="Comma-separated news category keys"),
sources: str | None = Query(None, description="Comma-separated news source ids"),
theater: str | None = Query(None, description="Theater preset filter: global/russo_ukrainian/middle_east/indo_pacific/europe"),
limit: int | None = Query(None, description="Maximum news items to return, capped at 100"),
locale: str | None = Query(None, description="Display locale, zh-CN or en-US"),
db: AsyncSession = Depends(get_db),
@@ -183,6 +184,7 @@ async def get_earth_feed(
region=normalized_region,
categories=_parse_categories(categories),
source_ids=_parse_source_ids(sources),
theater=theater,
limit=_parse_limit(limit),
locale=_parse_locale(locale),
db=db,
+185
View File
@@ -0,0 +1,185 @@
"""Ontology object inspection, neighborhood traversal, aliases, and analyst links API (§3.7)."""
from __future__ import annotations
from typing import Any
from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import BaseModel, Field
from sqlalchemy import desc, select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.access_gate import require_admin_user, require_earth_or_api_access
from app.db.session import get_db
from app.models.ontology import AnalystLink, OntologyEntityAlias
from app.models.user import User
from app.services.ai.entity_resolver import (
parse_object_id,
resolve_ontology_neighborhood,
resolve_ontology_object,
)
router = APIRouter()
_read_dep = Depends(require_earth_or_api_access("visualization:read"))
class AliasCreateRequest(BaseModel):
alias: str = Field(min_length=1, max_length=200)
object_id: str = Field(min_length=3, max_length=160)
source: str = Field(default="analyst", max_length=80)
class AnalystLinkCreateRequest(BaseModel):
from_object_id: str = Field(min_length=3, max_length=160)
to_object_id: str = Field(min_length=3, max_length=160)
relation_type: str = Field(min_length=1, max_length=80)
note: str = Field(default="", max_length=1000)
evidence_ids: list[str] = Field(default_factory=list)
@router.get("/objects/{object_id:path}/neighborhood", dependencies=[_read_dep])
async def get_ontology_object_neighborhood(
object_id: str,
depth: int = Query(default=1, ge=1, le=2),
radius_km: float = Query(default=150.0, ge=5.0, le=1500.0),
limit: int = Query(default=40, ge=1, le=120),
db: AsyncSession = Depends(get_db),
) -> dict[str, Any]:
"""Return 1-to-2 hop read-time derived neighborhood + analyst-asserted links."""
try:
payload = await resolve_ontology_neighborhood(
db, object_id, depth=depth, radius_km=radius_km, limit=limit
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
if payload is None:
raise HTTPException(status_code=404, detail=f"Ontology object not found: {object_id}")
return payload
@router.get("/objects/{object_id:path}", dependencies=[_read_dep])
async def get_ontology_object(
object_id: str,
db: AsyncSession = Depends(get_db),
) -> dict[str, Any]:
"""Resolve canonical ontology object `{type}:{id}` with provenance & freshness."""
try:
payload = await resolve_ontology_object(db, object_id)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
if payload is None:
raise HTTPException(status_code=404, detail=f"Ontology object not found: {object_id}")
return payload
@router.get("/aliases", dependencies=[_read_dep])
async def list_ontology_aliases(
object_id: str | None = Query(default=None),
limit: int = Query(default=100, ge=1, le=500),
db: AsyncSession = Depends(get_db),
) -> dict[str, Any]:
stmt = select(OntologyEntityAlias).order_by(desc(OntologyEntityAlias.id)).limit(limit)
if object_id:
stmt = stmt.where(OntologyEntityAlias.object_id == object_id.strip())
rows = list((await db.execute(stmt)).scalars().all())
return {"items": [r.to_dict() for r in rows], "count": len(rows)}
@router.post("/aliases")
async def create_ontology_alias(
body: AliasCreateRequest,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(require_admin_user),
) -> dict[str, Any]:
try:
otype, ident = parse_object_id(body.object_id)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
canonical_id = f"{otype}:{ident}"
row = OntologyEntityAlias(
alias=body.alias.strip(),
object_id=canonical_id,
source=body.source.strip() or "analyst",
created_by=current_user.username,
)
db.add(row)
try:
await db.commit()
except IntegrityError as exc:
await db.rollback()
raise HTTPException(status_code=409, detail="Alias already exists for this object") from exc
return row.to_dict()
@router.delete("/aliases/{alias_id}")
async def delete_ontology_alias(
alias_id: int,
db: AsyncSession = Depends(get_db),
_admin: User = Depends(require_admin_user),
) -> dict[str, Any]:
row = await db.get(OntologyEntityAlias, alias_id)
if row is None:
raise HTTPException(status_code=404, detail="Alias not found")
await db.delete(row)
await db.commit()
return {"deleted": True, "id": alias_id}
@router.get("/links", dependencies=[_read_dep])
async def list_analyst_links(
object_id: str | None = Query(default=None),
include_revoked: bool = Query(default=False),
limit: int = Query(default=100, ge=1, le=500),
db: AsyncSession = Depends(get_db),
) -> dict[str, Any]:
stmt = select(AnalystLink).order_by(desc(AnalystLink.id)).limit(limit)
if not include_revoked:
stmt = stmt.where(AnalystLink.status == "active")
if object_id:
oid = object_id.strip()
stmt = stmt.where(
(AnalystLink.from_object_id == oid) | (AnalystLink.to_object_id == oid)
)
rows = list((await db.execute(stmt)).scalars().all())
return {"items": [r.to_dict() for r in rows], "count": len(rows)}
@router.post("/links")
async def create_analyst_link(
body: AnalystLinkCreateRequest,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(require_admin_user),
) -> dict[str, Any]:
try:
ftype, fident = parse_object_id(body.from_object_id)
ttype, tident = parse_object_id(body.to_object_id)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
link = AnalystLink(
from_object_id=f"{ftype}:{fident}",
to_object_id=f"{ttype}:{tident}",
relation_type=body.relation_type.strip(),
note=body.note.strip(),
evidence_ids=list(body.evidence_ids or []),
created_by=current_user.username,
status="active",
)
db.add(link)
await db.commit()
return link.to_dict()
@router.delete("/links/{link_id}")
async def revoke_analyst_link(
link_id: int,
db: AsyncSession = Depends(get_db),
_admin: User = Depends(require_admin_user),
) -> dict[str, Any]:
link = await db.get(AnalystLink, link_id)
if link is None:
raise HTTPException(status_code=404, detail="Analyst link not found")
link.status = "revoked"
await db.commit()
return link.to_dict()
+421
View File
@@ -0,0 +1,421 @@
"""4D temporal replay keyframes & layer availability API (§4.1)."""
from __future__ import annotations
from datetime import UTC, datetime, timedelta
from typing import Any
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.access_gate import require_earth_or_api_access
from app.core.time import to_iso8601_utc
from app.db.session import get_db
from app.models.aircraft import AircraftPosition
from app.models.bgp_incident import BGPIncident
from app.models.collected_data import CollectedData
from app.models.compute_configuration_revision import ComputeConfigurationRevision
from app.models.disaster import DisasterEvent
from app.models.earth_news import EarthNewsItem
from app.models.geofence import SituationalIncident
from app.models.vessel import VesselPosition
from app.services.aircraft_aggregation import DEFAULT_POSITION_RETENTION_HOURS
from app.services.vessel_ais_aggregation import VESSEL_TRACK_RETENTION_HOURS
router = APIRouter(dependencies=[Depends(require_earth_or_api_access("visualization:read"))])
MAX_REPLAY_SPAN_SECONDS = 6 * 3600
def _coerce_utc(val: Any) -> datetime | None:
if isinstance(val, datetime):
return val.replace(tzinfo=UTC) if val.tzinfo is None else val.astimezone(UTC)
if isinstance(val, str) and val.strip():
try:
parsed = datetime.fromisoformat(val.strip().replace("Z", "+00:00"))
return parsed.replace(tzinfo=UTC) if parsed.tzinfo is None else parsed.astimezone(UTC)
except ValueError:
return None
return None
def _parse_bbox(raw_bbox: str | None) -> tuple[float, float, float, float] | None:
if not raw_bbox:
return None
parts = [p.strip() for p in raw_bbox.split(",") if p.strip()]
if len(parts) != 4:
raise HTTPException(status_code=422, detail="bbox must be min_lon,min_lat,max_lon,max_lat")
try:
min_lon, min_lat, max_lon, max_lat = (float(x) for x in parts)
except ValueError as exc:
raise HTTPException(status_code=422, detail="Invalid numeric coordinate in bbox") from exc
return min_lon, min_lat, max_lon, max_lat
def _in_bbox(lat: float, lon: float, bbox: tuple[float, float, float, float] | None) -> bool:
if bbox is None:
return True
min_lon, min_lat, max_lon, max_lat = bbox
return min_lat <= lat <= max_lat and min_lon <= lon <= max_lon
async def compute_replay_availability(db: AsyncSession, *, now: datetime | None = None) -> dict[str, Any]:
ref_now = now or datetime.now(UTC)
async def _min_max(col):
row = (await db.execute(select(func.min(col), func.max(col)))).first()
if not row:
return None, None
return _coerce_utc(row[0]), _coerce_utc(row[1])
air_min, air_max = await _min_max(AircraftPosition.observed_at)
ves_min, ves_max = await _min_max(VesselPosition.received_at)
bgp_min, bgp_max = await _min_max(BGPIncident.started_at)
dis_min, dis_max = await _min_max(DisasterEvent.observed_at)
news_min, news_max = await _min_max(EarthNewsItem.published_at)
inc_min, inc_max = await _min_max(SituationalIncident.created_at)
comp_min, comp_max = await _min_max(ComputeConfigurationRevision.published_at)
air_policy_from = ref_now - timedelta(hours=DEFAULT_POSITION_RETENTION_HOURS)
ves_policy_from = ref_now - timedelta(hours=VESSEL_TRACK_RETENTION_HOURS)
layers = {
"aircraft": {
"retention_hours": DEFAULT_POSITION_RETENTION_HOURS,
"policy_from": to_iso8601_utc(air_policy_from),
"available_from": to_iso8601_utc(max(air_min, air_policy_from) if air_min else air_policy_from),
"available_to": to_iso8601_utc(air_max or ref_now),
"mode": "columnar_positions",
},
"vessels": {
"retention_hours": VESSEL_TRACK_RETENTION_HOURS,
"policy_from": to_iso8601_utc(ves_policy_from),
"available_from": to_iso8601_utc(max(ves_min, ves_policy_from) if ves_min else ves_policy_from),
"available_to": to_iso8601_utc(ves_max or ref_now),
"mode": "columnar_positions",
},
"bgp": {
"retention_hours": 7 * 24,
"policy_from": to_iso8601_utc(ref_now - timedelta(days=7)),
"available_from": to_iso8601_utc(bgp_min or (ref_now - timedelta(days=7))),
"available_to": to_iso8601_utc(bgp_max or ref_now),
"mode": "interval_events",
},
"disasters": {
"retention_hours": 30 * 24,
"policy_from": to_iso8601_utc(ref_now - timedelta(days=30)),
"available_from": to_iso8601_utc(dis_min or (ref_now - timedelta(days=30))),
"available_to": to_iso8601_utc(dis_max or ref_now),
"mode": "point_events",
},
"news": {
"retention_hours": 30 * 24,
"policy_from": to_iso8601_utc(ref_now - timedelta(days=30)),
"available_from": to_iso8601_utc(news_min or (ref_now - timedelta(days=30))),
"available_to": to_iso8601_utc(news_max or ref_now),
"mode": "point_events",
},
"incidents": {
"retention_hours": 30 * 24,
"policy_from": to_iso8601_utc(ref_now - timedelta(days=30)),
"available_from": to_iso8601_utc(inc_min or (ref_now - timedelta(days=30))),
"available_to": to_iso8601_utc(inc_max or ref_now),
"mode": "interval_events",
},
"satellites": {
"retention_hours": None,
"available_from": to_iso8601_utc(ref_now - timedelta(days=7)),
"available_to": to_iso8601_utc(ref_now + timedelta(hours=12)),
"mode": "tle_live_propagation",
},
"compute": {
"retention_hours": None,
"available_from": to_iso8601_utc(comp_min),
"available_to": to_iso8601_utc(comp_max or ref_now),
"mode": "as_of_revision",
},
}
return {
"checked_at": to_iso8601_utc(ref_now),
"max_chunk_seconds": MAX_REPLAY_SPAN_SECONDS,
"layers": layers,
}
@router.get("/availability")
async def get_replay_availability(db: AsyncSession = Depends(get_db)) -> dict[str, Any]:
"""Report actual retention window and propagation capabilities per replay layer."""
return await compute_replay_availability(db)
@router.get("/frames")
async def get_replay_frames(
start: str = Query(..., description="ISO-8601 UTC window start"),
end: str = Query(..., description="ISO-8601 UTC window end (max 6 hours after start)"),
step_sec: int = Query(default=60, ge=10, le=900),
layers: str = Query(default="aircraft,vessels,disasters,incidents,bgp,satellites,compute"),
bbox: str | None = Query(default=None),
db: AsyncSession = Depends(get_db),
) -> dict[str, Any]:
"""Return columnar keyframes + compute as_of timeline for chunked <=6h 4D playback."""
start_dt = _coerce_utc(start)
end_dt = _coerce_utc(end)
if start_dt is None or end_dt is None:
raise HTTPException(status_code=422, detail="Invalid start or end ISO-8601 timestamp")
span_sec = (end_dt - start_dt).total_seconds()
if span_sec <= 0:
raise HTTPException(status_code=400, detail="end must be strictly after start")
if span_sec > MAX_REPLAY_SPAN_SECONDS:
raise HTTPException(
status_code=400,
detail=f"Replay chunk span exceeds 6 hours ({int(span_sec)}s > {MAX_REPLAY_SPAN_SECONDS}s)",
)
parsed_bbox = _parse_bbox(bbox)
requested_layers = [x.strip().lower() for x in layers.split(",") if x.strip()]
now = datetime.now(UTC)
timestamps: list[datetime] = []
cursor = start_dt
while cursor <= end_dt and len(timestamps) < 365:
timestamps.append(cursor)
cursor += timedelta(seconds=step_sec)
if not timestamps or timestamps[-1] < end_dt:
timestamps.append(end_dt)
availability = await compute_replay_availability(db, now=now)
layer_Meta = availability["layers"]
out_layers: dict[str, Any] = {}
if "aircraft" in requested_layers:
policy_from = _coerce_utc(layer_Meta["aircraft"]["policy_from"])
if policy_from and end_dt < policy_from:
out_layers["aircraft"] = {
"status": "unavailable",
"reason": "outside_retention_window",
"retention_hours": DEFAULT_POSITION_RETENTION_HOURS,
"available_from": layer_Meta["aircraft"]["policy_from"],
"available_to": layer_Meta["aircraft"]["available_to"],
"frames": [],
}
else:
rows = list(
(
await db.execute(
select(AircraftPosition)
.where(
AircraftPosition.observed_at >= start_dt - timedelta(seconds=step_sec),
AircraftPosition.observed_at <= end_dt,
)
.order_by(AircraftPosition.observed_at.asc())
.limit(20000)
)
)
.scalars()
.all()
)
frames = []
for ts in timestamps:
lo = ts - timedelta(seconds=step_sec * 1.5)
latest_by_id: dict[str, AircraftPosition] = {}
for r in rows:
obs = _coerce_utc(r.observed_at)
if obs and lo <= obs <= ts and _in_bbox(float(r.lat), float(r.lon), parsed_bbox):
latest_by_id[r.icao24] = r
vals = list(latest_by_id.values())
frames.append(
{
"ids": [v.icao24 for v in vals],
"lats": [round(float(v.lat), 5) for v in vals],
"lons": [round(float(v.lon), 5) for v in vals],
"headings": [float(v.track_deg or 0.0) for v in vals],
"alts": [float(v.altitude_m or 0.0) for v in vals],
}
)
out_layers["aircraft"] = {
"status": "ok",
"partial": bool(policy_from and start_dt < policy_from),
"available_from": layer_Meta["aircraft"]["policy_from"],
"frames": frames,
}
if "vessels" in requested_layers:
policy_from = _coerce_utc(layer_Meta["vessels"]["policy_from"])
if policy_from and end_dt < policy_from:
out_layers["vessels"] = {
"status": "unavailable",
"reason": "outside_retention_window",
"retention_hours": VESSEL_TRACK_RETENTION_HOURS,
"available_from": layer_Meta["vessels"]["policy_from"],
"available_to": layer_Meta["vessels"]["available_to"],
"frames": [],
}
else:
rows = list(
(
await db.execute(
select(VesselPosition)
.where(
VesselPosition.received_at >= start_dt - timedelta(seconds=step_sec),
VesselPosition.received_at <= end_dt,
)
.order_by(VesselPosition.received_at.asc())
.limit(20000)
)
)
.scalars()
.all()
)
frames = []
for ts in timestamps:
lo = ts - timedelta(seconds=max(300, step_sec * 2))
latest_by_id: dict[int, VesselPosition] = {}
for r in rows:
obs = _coerce_utc(r.received_at)
if obs and lo <= obs <= ts and _in_bbox(float(r.lat), float(r.lon), parsed_bbox):
latest_by_id[r.mmsi] = r
vals = list(latest_by_id.values())
frames.append(
{
"ids": [str(v.mmsi) for v in vals],
"lats": [round(float(v.lat), 5) for v in vals],
"lons": [round(float(v.lon), 5) for v in vals],
"headings": [float(v.cog if v.cog is not None else (v.heading or 0.0)) for v in vals],
"sogs": [float(v.sog or 0.0) for v in vals],
}
)
out_layers["vessels"] = {
"status": "ok",
"partial": bool(policy_from and start_dt < policy_from),
"available_from": layer_Meta["vessels"]["policy_from"],
"frames": frames,
}
if "disasters" in requested_layers:
rows = list(
(
await db.execute(
select(DisasterEvent)
.where(
DisasterEvent.duplicate_of.is_(None),
DisasterEvent.observed_at >= start_dt - timedelta(hours=24),
DisasterEvent.observed_at <= end_dt,
)
.limit(1000)
)
)
.scalars()
.all()
)
items = [
r.to_dict()
for r in rows
if _in_bbox(float(r.lat), float(r.lon), parsed_bbox)
]
out_layers["disasters"] = {"status": "ok", "items": items}
if "incidents" in requested_layers:
rows = list(
(
await db.execute(
select(SituationalIncident)
.where(
SituationalIncident.created_at >= start_dt - timedelta(hours=12),
SituationalIncident.created_at <= end_dt,
)
.order_by(SituationalIncident.created_at.asc())
.limit(500)
)
)
.scalars()
.all()
)
out_layers["incidents"] = {"status": "ok", "items": [r.to_dict() for r in rows]}
if "bgp" in requested_layers:
rows = list(
(
await db.execute(
select(BGPIncident)
.where(
BGPIncident.started_at >= start_dt - timedelta(hours=12),
BGPIncident.started_at <= end_dt,
)
.limit(300)
)
)
.scalars()
.all()
)
out_layers["bgp"] = {"status": "ok", "items": [r.to_dict() for r in rows]}
if "satellites" in requested_layers:
tle_rows = list(
(
await db.execute(
select(CollectedData)
.where(
CollectedData.source == "celestrak_tle",
CollectedData.is_current.is_(True),
)
.limit(500)
)
)
.scalars()
.all()
)
tles = []
for tr in tle_rows:
ex = tr.extra_data or {}
if ex.get("tle_line1") and ex.get("tle_line2"):
tles.append(
{
"norad_id": ex.get("norad_id") or tr.source_id,
"name": tr.name,
"tle_line1": ex["tle_line1"],
"tle_line2": ex["tle_line2"],
}
)
out_layers["satellites"] = {
"status": "ok",
"mode": "tle_live_propagation",
"tle_count": len(tles),
"tles": tles,
}
# Link every replay step to Phase 1 ComputeConfigurationRevision active `as_of` that timestamp
revs = list(
(
await db.execute(
select(ComputeConfigurationRevision)
.where(ComputeConfigurationRevision.published_at <= end_dt)
.order_by(ComputeConfigurationRevision.published_at.asc())
)
)
.scalars()
.all()
)
compute_as_of: list[dict[str, Any] | None] = []
for ts in timestamps:
active = None
for rev in revs:
pub_at = _coerce_utc(rev.published_at)
if pub_at and pub_at <= ts:
active = {
"publish_id": rev.publish_id,
"action": rev.action,
"published_at": to_iso8601_utc(pub_at),
}
else:
break
compute_as_of.append(active)
return {
"start": to_iso8601_utc(start_dt),
"end": to_iso8601_utc(end_dt),
"step_sec": step_sec,
"timestamps": [to_iso8601_utc(ts) for ts in timestamps],
"compute_as_of": compute_as_of,
"layers": out_layers,
}
+16 -3
View File
@@ -31,6 +31,7 @@ from app.models.datasource import DataSource
from app.models.datasource_config import DataSourceConfig
from app.models.system_setting import SystemSetting
from app.models.user import User
from app.models.aircraft import ADSBSourceHealth
from app.models.vessel import AISSourceHealth
from app.schemas.ai import SituationalAnalysisRequest
from app.services.barentswatch import (
@@ -1271,10 +1272,16 @@ 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()}
async def get_adsb_source_health_by_source(db: AsyncSession) -> dict[str, dict]:
result = await db.execute(select(ADSBSourceHealth))
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,
storage_policy: dict | None = None,
adsb_health_by_source: dict[str, dict] | None = None,
) -> dict:
defaults = DEFAULT_DATASOURCES.get(datasource.source, {})
effective_mode = resolve_snapshot_mode(storage_policy, datasource.source)
@@ -1297,6 +1304,7 @@ def serialize_collector(
"credential_provider": defaults.get("credential_provider"),
"credential_status": defaults.get("credential_status", "none"),
"ais_health": (ais_health_by_source or {}).get(datasource.source),
"adsb_health": (adsb_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)),
@@ -2281,12 +2289,14 @@ 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)
adsb_health_by_source = await get_adsb_source_health_by_source(db)
storage_policy = await get_storage_policy(db)
return {
"collectors": [
serialize_collector(datasource, ais_health_by_source, storage_policy)
serialize_collector(datasource, ais_health_by_source, storage_policy, adsb_health_by_source)
for datasource in datasources
],
"adsb_source_health": list(adsb_health_by_source.values()),
"storage_policy": summarize_storage_policy(
storage_policy,
[datasource.source for datasource in datasources],
@@ -2343,10 +2353,11 @@ async def update_collector_settings(
await sync_datasource_job(datasource.id)
ais_health_by_source = await get_ais_source_health_by_source(db)
adsb_health_by_source = await get_adsb_source_health_by_source(db)
sources = await _load_known_collector_sources(db)
return {
"status": "updated",
"collector": serialize_collector(datasource, ais_health_by_source, storage_policy),
"collector": serialize_collector(datasource, ais_health_by_source, storage_policy, adsb_health_by_source),
"storage_policy": summarize_storage_policy(storage_policy, sources),
}
@@ -2363,6 +2374,7 @@ async def get_all_settings(
["system", "notifications", "security"],
)
ais_health_by_source = await get_ais_source_health_by_source(db)
adsb_health_by_source = await get_adsb_source_health_by_source(db)
storage_policy = await get_storage_policy(db)
return {
"system": setting_payloads["system"],
@@ -2371,9 +2383,10 @@ async def get_all_settings(
"tv": await get_tv_settings_payload(db),
"integrations": await serialize_external_integrations(db),
"collectors": [
serialize_collector(datasource, ais_health_by_source, storage_policy)
serialize_collector(datasource, ais_health_by_source, storage_policy, adsb_health_by_source)
for datasource in datasources
],
"adsb_source_health": list(adsb_health_by_source.values()),
"storage_policy": summarize_storage_policy(
storage_policy,
[datasource.source for datasource in datasources],
+239 -14
View File
@@ -4,12 +4,14 @@ from __future__ import annotations
from dataclasses import replace
from datetime import UTC, datetime
import hashlib
import json
import uuid
from typing import Any, Literal
from typing import Any, Literal, Self
from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, ConfigDict, Field
from pydantic import BaseModel, ConfigDict, Field, model_validator
from sqlalchemy import desc, select
from sqlalchemy.ext.asyncio import AsyncSession
@@ -18,12 +20,16 @@ from app.core.access_gate import require_earth_or_api_access
from app.db.session import get_db
from app.models.situational_assessment import (
ComputeEvidenceCandidate,
EvidenceRecord,
InvestigationSession,
TopicWatch,
WorkflowRun,
)
from app.models.system_log import AuditLog
from app.models.user import User
from app.schemas.compute_configuration import ComputeConfiguration, source_for
from app.services.compute_configuration import read_configuration
from app.services.compute_history import MODE_DENOMINATOR, ComputeSeriesMode
from app.services.ai.access_policy import (
AccessContext,
enforce_paid_research_gate,
@@ -44,7 +50,7 @@ from app.services.ai.presentation_compiler import (
from app.services.ai.proactive_pipeline import (
audit_situational_hygiene,
process_bgp_snapshot_proactive_delta,
process_compute_config_proactive_delta,
retry_pending_compute_presentations,
)
from app.services.ai.semantic_delta import extract_compute_candidates_deterministic
from app.services.ai.tool_registry import TimeBasis, query_compute_posture_tool
@@ -57,7 +63,6 @@ from app.services.ai.workflow_runtime import (
)
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
router = APIRouter()
@@ -73,6 +78,8 @@ class SessionCreateRequest(BaseModel):
visible_layers: dict[str, bool] = Field(default_factory=dict)
time_basis: TimeBasis = "retrospective"
cutoff_at: str | None = Field(default=None, max_length=40)
publish_id: str | None = Field(default=None, max_length=64)
as_of: str | None = Field(default=None, max_length=64)
include_drill: bool = False
@@ -116,6 +123,8 @@ class SessionTurnRequest(BaseModel):
visible_layers: dict[str, bool] | None = None
time_basis: TimeBasis | None = None
cutoff_at: str | None = Field(default=None, max_length=40)
publish_id: str | None = Field(default=None, max_length=64)
as_of: str | None = Field(default=None, max_length=64)
include_drill: bool | None = None
preset: ViewPreset | None = None
prefer_llm: bool | Literal["auto"] = False
@@ -160,6 +169,8 @@ class SpatialInvestigateRequest(BaseModel):
question: str = Field(min_length=2, max_length=1000)
time_basis: TimeBasis = "retrospective"
cutoff_at: str | None = Field(default=None, max_length=40)
publish_id: str | None = Field(default=None, max_length=64)
as_of: str | None = Field(default=None, max_length=64)
include_drill: bool = False
external_urls: list[str] = Field(default_factory=list, max_length=3)
@@ -177,6 +188,25 @@ class ReportExportRequest(BaseModel):
cutoff_at: str | None = Field(default=None, max_length=40)
APPROVE_REASON_CODES = frozenset(
{
"newer_authoritative_report",
"corrects_prior_error",
"adds_missing_observation",
"methodology_update",
}
)
REJECT_REASON_CODES = frozenset(
{
"unverifiable_source",
"denominator_mismatch",
"extraction_error",
"superseded",
"duplicate",
}
)
class CandidateExtractRequest(BaseModel):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
@@ -187,12 +217,36 @@ class CandidateExtractRequest(BaseModel):
source_url: str = Field(min_length=8, max_length=2000)
publisher: str = Field(default="Research Institute", max_length=200)
locator: str = Field(default="Extracted excerpt", max_length=300)
period_label: str | None = Field(default=None, max_length=40)
published_at: str | None = Field(default=None, max_length=40)
report_year: int | None = Field(default=None, ge=2000, le=2100)
class CandidateReviewRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
decision: Literal["approved", "rejected"]
reason_code: Literal[
"newer_authoritative_report",
"corrects_prior_error",
"adds_missing_observation",
"methodology_update",
"unverifiable_source",
"denominator_mismatch",
"extraction_error",
"superseded",
"duplicate",
]
reason: str = Field(min_length=2, max_length=1000)
@model_validator(mode="after")
def matching_reason_code(self) -> Self:
allowed = APPROVE_REASON_CODES if self.decision == "approved" else REJECT_REASON_CODES
if self.reason_code not in allowed:
raise ValueError(
f"reason_code '{self.reason_code}' is not valid for decision '{self.decision}'"
)
return self
# ============================================================================
@@ -219,6 +273,8 @@ async def create_investigation_session(
"visible_layers": dict(payload.visible_layers or {}),
"time_basis": payload.time_basis,
"cutoff_at": payload.cutoff_at,
"publish_id": payload.publish_id,
"as_of": payload.as_of,
"include_drill": payload.include_drill,
"active_result_id": None,
"active_revision": None,
@@ -349,6 +405,8 @@ async def create_session_turn(
"visible_layers": payload.visible_layers,
"time_basis": payload.time_basis,
"cutoff_at": payload.cutoff_at,
"publish_id": payload.publish_id,
"as_of": payload.as_of,
"include_drill": payload.include_drill,
}
turn_result = await execute_session_turn(
@@ -404,6 +462,8 @@ async def stream_investigation_session_turn(
"visible_layers": payload.visible_layers,
"time_basis": payload.time_basis,
"cutoff_at": payload.cutoff_at,
"publish_id": payload.publish_id,
"as_of": payload.as_of,
"include_drill": payload.include_drill,
}
headers = {
@@ -702,7 +762,7 @@ async def evaluate_proactive_snapshot(
db: AsyncSession = Depends(get_db),
) -> dict[str, Any]:
if payload.domain == "compute":
res = await process_compute_config_proactive_delta(db)
res = await retry_pending_compute_presentations(db)
else:
res = await process_bgp_snapshot_proactive_delta(
db,
@@ -723,6 +783,8 @@ async def get_compute_posture(
mode: ComputeSeriesMode = "global_share",
time_basis: TimeBasis = "retrospective",
cutoff_at: str | None = None,
as_of: str | None = None,
publish_id: str | None = None,
prefer_llm: bool = False,
access: AccessContext = Depends(resolve_access_context),
db: AsyncSession = Depends(get_db),
@@ -733,7 +795,13 @@ async def get_compute_posture(
codes = selected_countries(countries)
response.headers["Cache-Control"] = "no-store"
series = await query_compute_posture_tool(
db, codes, mode=mode, time_basis=time_basis, cutoff_at=cutoff_at
db,
codes,
mode=mode,
time_basis=time_basis,
cutoff_at=cutoff_at,
as_of=as_of,
publish_id=publish_id,
)
# GET is strictly 100% read-only (`persist=False`) when `prefer_llm=False`
return await generate_or_get_compute_posture(
@@ -779,6 +847,8 @@ async def investigate_spatial_context(
question=payload.question,
time_basis=payload.time_basis,
cutoff_at=payload.cutoff_at,
publish_id=payload.publish_id,
as_of=payload.as_of,
allow_drill=payload.include_drill,
ai_client=ai_client,
)
@@ -819,48 +889,190 @@ async def list_compute_candidates(
return {"items": [row.to_dict() for row in rows]}
def _candidate_dedupe_fingerprint(
*,
source_id: str,
metric: str,
year: int,
period_label: str | None,
values: dict[str, Any],
) -> str:
sorted_vals = {
str(k): round(float(v), 6)
for k, v in sorted((values or {}).items(), key=lambda kv: str(kv[0]))
}
raw = f"{source_id}|{metric}|{year}|{period_label or ''}|{json.dumps(sorted_vals, sort_keys=True, separators=(',', ':'))}"
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
def _build_candidate_comparison(
*,
current_config: ComputeConfiguration,
current_publish_id: str,
proposed: dict[str, Any],
) -> dict[str, Any]:
metric = str(proposed.get("metric") or "global_share")
year = int(proposed.get("year") or 0)
proposed_period = (proposed.get("period_label") or None)
existing_row = next(
(obs for obs in current_config.observations if obs.metric == metric and obs.year == year),
None,
)
existing_period = existing_row.period_label if existing_row is not None else None
period_conflict = bool(
existing_row is not None and (existing_period or None) != (proposed_period or None)
)
codes_comparison: dict[str, dict[str, Any]] = {}
has_historical_revision = False
for code, raw_new in sorted((proposed.get("values") or {}).items()):
new_val = float(raw_new)
if existing_row is not None and code in existing_row.values:
old_val = float(existing_row.values[code])
old_src = source_for(existing_row, code)
delta = round(new_val - old_val, 4)
change_kind = "historical_revision" if delta != 0 else "unchanged"
if change_kind == "historical_revision":
has_historical_revision = True
else:
old_val = None
old_src = None
delta = round(new_val, 4)
change_kind = "new_observation"
codes_comparison[code] = {
"old_value": old_val,
"new_value": new_val,
"delta": delta,
"change_kind": change_kind,
"old_source_id": old_src,
}
return {
"publish_id": current_publish_id,
"metric": metric,
"year": year,
"period_label": proposed_period,
"existing_period_label": existing_period,
"period_conflict": period_conflict,
"denominator": MODE_DENOMINATOR.get(metric),
"codes": codes_comparison,
"has_historical_revision": has_historical_revision,
}
@router.post("/candidates/extract")
async def extract_compute_candidates(
payload: CandidateExtractRequest,
actor: User = Depends(configuration_admin),
db: AsyncSession = Depends(get_db),
) -> dict[str, Any]:
source_meta = {
effective_report_year = payload.report_year or payload.year
source_meta: dict[str, Any] = {
"id": payload.source_id,
"title": payload.source_title,
"url": payload.source_url,
"publisher": payload.publisher,
"report_year": payload.year,
"report_year": effective_report_year,
"published_at": payload.published_at,
"locator": payload.locator,
}
extracted = extract_compute_candidates_deterministic(
payload.excerpt, year=payload.year, source_meta=source_meta
payload.excerpt,
year=payload.year,
source_meta=source_meta,
period_label=payload.period_label,
)
envelope = await read_configuration(db)
current_config = ComputeConfiguration.model_validate(envelope["config"])
current_publish_id = str(envelope.get("publish_id") or envelope["revision"])
# Upsert immutable EvidenceRecord without overwriting existing record.
if extracted and hasattr(db, "execute") and hasattr(db, "add"):
existing_ev = (
await db.execute(select(EvidenceRecord).where(EvidenceRecord.id == payload.source_id))
).scalar_one_or_none()
if existing_ev is None:
db.add(
EvidenceRecord(
id=payload.source_id,
source_type="curated_report",
title=payload.source_title,
publisher=payload.publisher,
url=payload.source_url,
locator=payload.locator,
excerpt=payload.excerpt,
content_sha256=hashlib.sha256(payload.excerpt.encode("utf-8")).hexdigest(),
published_at=payload.published_at or str(effective_report_year),
metadata_json={
"report_year": effective_report_year,
"period_label": payload.period_label,
},
)
)
created: list[ComputeEvidenceCandidate] = []
ordered_entries: list[tuple[ComputeEvidenceCandidate, bool]] = []
for item in extracted:
proposed = item["proposed_payload"]
fp = _candidate_dedupe_fingerprint(
source_id=str(proposed.get("source_id") or payload.source_id),
metric=str(proposed.get("metric") or "global_share"),
year=int(proposed.get("year") or payload.year),
period_label=proposed.get("period_label"),
values=proposed.get("values") or {},
)
existing_cand = (
await db.execute(
select(ComputeEvidenceCandidate)
.where(ComputeEvidenceCandidate.dedupe_fingerprint == fp)
.order_by(desc(ComputeEvidenceCandidate.id))
.limit(1)
)
).scalar_one_or_none()
if existing_cand is not None:
ordered_entries.append((existing_cand, True))
continue
comparison = _build_candidate_comparison(
current_config=current_config,
current_publish_id=current_publish_id,
proposed=proposed,
)
record = ComputeEvidenceCandidate(
status="pending",
candidate_type=item["candidate_type"],
proposed_payload=item["proposed_payload"],
proposed_payload=proposed,
source_payload=item["source_payload"],
comparison=comparison,
dedupe_fingerprint=fp,
confidence=item["confidence"],
extractor_note=item["extractor_note"],
)
db.add(record)
created.append(record)
ordered_entries.append((record, False))
db.add(
AuditLog(
actor_id=actor.id,
actor_name=actor.username,
action="compute_candidates.extract",
target_type="compute_evidence_candidates",
target_id=payload.source_id,
details={"count": len(created), "year": payload.year},
details={
"count": len(created),
"duplicates": sum(1 for _, is_dup in ordered_entries if is_dup),
"year": payload.year,
},
)
)
await db.commit()
for rec in created:
await db.refresh(rec)
return {"items": [rec.to_dict() for rec in created]}
return {
"items": [
{**rec.to_dict(), "duplicate": is_dup}
for rec, is_dup in ordered_entries
]
}
@router.post("/candidates/{candidate_id}/review")
@@ -877,17 +1089,30 @@ async def review_compute_candidate(
).scalar_one_or_none()
if record is None:
raise HTTPException(status_code=404, detail="Candidate not found")
if record.published_publish_id:
raise HTTPException(
status_code=409,
detail="Candidate has already been published and cannot be modified.",
)
previous_status = record.status
record.status = payload.decision
record.review_reason_code = payload.reason_code
record.review_reason = payload.reason
record.reviewed_by = actor.username
record.reviewed_at = datetime.now(UTC)
db.add(
AuditLog(
actor_id=actor.id,
actor_name=actor.username,
action=f"compute_candidates.{payload.decision}",
target_type="compute_evidence_candidates",
target_id=str(candidate_id),
details={"before_status": previous_status, "after_status": payload.decision},
details={
"before_status": previous_status,
"after_status": payload.decision,
"reason_code": payload.reason_code,
"reason": payload.reason,
},
)
)
await db.commit()
+11
View File
@@ -13,6 +13,7 @@ from pydantic import BaseModel
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.config import ROOT_DIR, settings
from app.core.access_gate import require_earth_or_api_access
from app.core.enums import UserRole
from app.core.security import get_current_user
from app.db.session import get_db
@@ -45,6 +46,7 @@ from app.services.system_logs import (
read_observability_raw_events,
)
from app.services.earth_layer_cache import earth_layer_cache
from app.services.source_freshness import compute_domain_freshness
router = APIRouter()
@@ -746,3 +748,12 @@ async def get_external_openapi_schema(
):
"""Return curated external/UE5 OpenAPI schema excluding internal admin endpoints."""
return _build_external_openapi_schema(request.app.openapi())
@router.get("/freshness")
async def get_system_source_freshness(
db: AsyncSession = Depends(get_db),
_access=Depends(require_earth_or_api_access("visualization:read")),
):
"""Return sanitized per-domain data freshness and intelligence blind spots for Earth HUD."""
return await compute_domain_freshness(db)
+19
View File
@@ -8,6 +8,10 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.api.v1.visualization import _parse_bbox, build_vessel_snapshot_response
from app.core.access_gate import require_earth_or_api_access
from app.db.session import get_db
from app.services.maritime_geography import (
compute_chokepoint_vessel_summary,
load_strategic_ports,
)
from app.services.vessel_ais_aggregation import MAX_SNAPSHOT_LIMIT
router = APIRouter()
@@ -40,3 +44,18 @@ async def get_vessel_snapshot(
since_minutes=since_minutes,
response=response,
)
@router.get("/maritime-context", dependencies=[Depends(require_earth_or_api_access("vessels:read"))])
async def get_maritime_context(
db: AsyncSession = Depends(get_db),
):
"""Return cited maritime chokepoints with live/baseline counts and strategic ports."""
chokepoints = await compute_chokepoint_vessel_summary(db)
ports = load_strategic_ports()
return {
"chokepoint_count": len(chokepoints),
"chokepoints": chokepoints,
"port_count": len(ports),
"ports": ports,
}
+384 -192
View File
@@ -6,11 +6,14 @@ Returns GeoJSON format compatible with Three.js, CesiumJS, and Unreal Cesium.
import asyncio
import base64
from collections import OrderedDict
from contextlib import aclosing
from contextlib import aclosing, suppress
from datetime import UTC, datetime, timedelta
import hashlib
import math
import os
from pathlib import Path
import re
from uuid import uuid4
import httpx
from fastapi import APIRouter, HTTPException, Depends, Query, Request, Response
from pydantic import BaseModel, Field
@@ -26,10 +29,12 @@ from app.core.satellite_tle import build_tle_lines_from_elements
from app.core.time import to_iso8601_utc
from app.db.session import get_db
from app.core.satellite_presentation import satellite_constellation_group as _normalize_satellite_constellation_group
from app.models.aircraft import AircraftCurrentState
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.gps_jamming import GPSJammingCell
from app.models.user import User
from app.models.vessel import AISSourceHealth, VesselCurrentState, VesselPosition, VesselStatic
from app.services.bgp_collectors import build_bgp_collector_coverage
@@ -37,23 +42,17 @@ from app.services.cable_graph import build_graph_from_data, CableGraph, haversin
from app.services.compute_center_locations import (
RENDERABLE_PRECISIONS,
ResolutionDiagnostic,
build_compute_center_location_query,
collect_location_candidates,
get_compute_center_location_dict,
refresh_compute_center_location_cache,
resolve_compute_center_location_full,
upsert_compute_center_location,
)
from app.services.ai_client import get_ai_provider_client
from app.api.v1.settings import get_runtime_web_search_config, get_web_search_client
from app.api.v1.settings import get_runtime_web_search_config
from app.services.ai_tools.web_search import normalize_web_search_provider
from app.services.collectors.bgp_common import RIPE_RIS_COLLECTOR_COORDS
from app.services.location.llm_fallback import (
collect_llm_location_fallback_candidate,
collect_location_search_evidence,
)
from app.services.location.agent_resolver import (
run_controlled_location_agent,
run_l1_structured_facility_resolvers,
from app.services.location.workflow_tools import (
TERMINAL_UNLOCATABLE_STATUSES,
run_location_workflow,
)
from app.services.persistent_logs import record_system_log
from app.services.vessel_ais_aggregation import (
@@ -79,13 +78,17 @@ from app.core.logging import get_logger
router = APIRouter()
logger = get_logger(__name__, service="api")
_vis_read_dep = Depends(require_earth_or_api_access("visualization:read"))
_vis_tile_read_dep = Depends(
require_earth_or_api_access("visualization:read", rate_limit_tier="tile")
)
TERRAIN_TILE_URL_TEMPLATE = (
"https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png"
)
TERRAIN_TILE_CACHE_MAX_ITEMS = 512
TERRAIN_REPO_ROOT = Path(__file__).resolve().parents[4]
TERRAIN_CACHE_DEFAULT_DIR = TERRAIN_REPO_ROOT / "data" / "earth-terrain-cache"
TERRAIN_CACHE_MAX_BYTES_DEFAULT = 128 * 1024 * 1024
TERRAIN_TILE_BATCH_MAX_ITEMS = 128
TERRAIN_TILE_BATCH_CONCURRENCY = 16
_terrain_tile_cache: OrderedDict[tuple[int, int, int], tuple[bytes, str, dict[str, str]]] = OrderedDict()
VESSEL_NAME_FALLBACK_PATTERN = re.compile(r"^mmsi\s*\d+$", re.IGNORECASE)
SECONDS_PER_MINUTE = 60
BYTES_PER_MIB = 1024 * 1024
@@ -296,7 +299,14 @@ def _extract_satellite_record(record: CollectedData) -> tuple[dict[str, Any], An
tle_line1 = metadata.get("tle_line1")
tle_line2 = metadata.get("tle_line2")
if not tle_line1 or not tle_line2:
# Stored 6-digit NORAD TLE lines (70+ chars) shift orbital element columns; regenerate using Alpha-5.
valid_tle = (
isinstance(tle_line1, str)
and isinstance(tle_line2, str)
and len(tle_line1.rstrip()) == 69
and len(tle_line2.rstrip()) == 69
)
if not valid_tle:
tle_line1, tle_line2 = build_tle_lines_from_elements(
norad_cat_id=norad_id,
epoch=metadata.get("epoch"),
@@ -719,16 +729,27 @@ def convert_compute_centers_to_geojson(records: List[CollectedData]) -> Dict[str
features: List[Dict[str, Any]] = []
unresolved: List[Dict[str, Any]] = []
withheld_count = 0
withheld_by_status: Dict[str, int] = {}
for record in records:
metadata = record.extra_data or {}
if metadata.get("compute_contract") == "v1" and metadata.get("anonymous"):
withheld_count += 1
withheld_by_status["anonymous"] = withheld_by_status.get("anonymous", 0) + 1
continue
result = resolve_compute_center_location_full(record, metadata)
site_type = compute_site_type(record)
if not result.is_resolved:
stored_loc = get_compute_center_location_dict(
getattr(record, "source", None),
getattr(record, "source_id", None),
)
stored_status = str(stored_loc.get("verification_status") or "").strip().lower()
if stored_status in TERMINAL_UNLOCATABLE_STATUSES:
withheld_count += 1
withheld_by_status[stored_status] = withheld_by_status.get(stored_status, 0) + 1
continue
diagnostic = result.diagnostic or ResolutionDiagnostic(
failure_reason="Unknown resolver failure",
attempted_queries=(),
@@ -816,7 +837,13 @@ def convert_compute_centers_to_geojson(records: List[CollectedData]) -> Dict[str
}
)
return {"type": "FeatureCollection", "features": features, "unresolved": unresolved, "withheld_count": withheld_count}
return {
"type": "FeatureCollection",
"features": features,
"unresolved": unresolved,
"withheld_count": withheld_count,
"withheld_by_status": withheld_by_status,
}
VESSEL_TYPE_FILTERS = {
@@ -1182,11 +1209,24 @@ async def build_vessel_snapshot_response(
bbox=bbox,
requested_types=requested_types,
)[:safe_limit]
chokepoints = []
try:
from app.services.maritime_geography import (
compute_chokepoint_vessel_summary,
enrich_vessel_feature_roles,
)
for feat in features:
enrich_vessel_feature_roles(feat)
chokepoints = await compute_chokepoint_vessel_summary(db, features)
except Exception:
chokepoints = []
return {
"type": "FeatureCollection",
"features": features,
"count": len(features),
"stats": _build_vessel_stats(features),
"chokepoints": chokepoints,
"generated_at": to_iso8601_utc(snapshot_started_at),
"diagnostics": {
**diagnostics,
@@ -1617,8 +1657,34 @@ async def get_cables_geojson(db: AsyncSession = Depends(get_db), response: Respo
async def _build_cables_geojson(db: AsyncSession) -> dict[str, Any]:
try:
records = await _load_current_collected_data(db, "arcgis_cables")
geojson = convert_cable_to_geojson(records)
try:
from app.services.nga_advisories import map_advisories_by_cable_id
return convert_cable_to_geojson(records)
advisories_by_id = await map_advisories_by_cable_id(db)
if advisories_by_id:
for feat in geojson.get("features") or []:
props = feat.get("properties")
if not isinstance(props, dict):
continue
cid = str(
props.get("cable_id")
or props.get("id")
or props.get("Name")
or props.get("name")
or ""
).strip()
matched = advisories_by_id.get(cid) or []
if matched:
props["advisories"] = matched
props["has_advisory"] = True
except Exception as adv_exc:
logger.debug_event(
"Skipped attaching cable advisories",
event="visualization.cables.advisories_skipped",
context={"error_type": type(adv_exc).__name__},
)
return geojson
except Exception as e:
logger.exception_event(
"Failed to build cables GeoJSON response",
@@ -1693,12 +1759,23 @@ async def _build_landing_points_geojson(db: AsyncSession) -> dict[str, Any]:
raise HTTPException(status_code=500, detail=f"Internal error: {str(e)}")
@router.get("/terrain/terrarium/{z}/{x}/{y}.png", dependencies=[_vis_read_dep])
async def get_terrarium_tile(z: int, x: int, y: int):
"""Proxy Terrarium elevation tiles through the backend to avoid browser CORS issues."""
@router.get("/terrain/terrarium/{z}/{x}/{y}.png", dependencies=[_vis_tile_read_dep])
@router.head("/terrain/terrarium/{z}/{x}/{y}.png", dependencies=[_vis_tile_read_dep])
async def get_terrarium_tile(request: Request, z: int, x: int, y: int):
"""Proxy Terrarium elevation tiles with bounded disk LRU + conditional 304 validation."""
if not _is_valid_terrain_tile(z, x, y):
raise HTTPException(status_code=400, detail="Invalid terrain tile coordinates")
cached = _get_cached_terrain_tile(z, x, y)
if cached is not None:
content, content_type, headers = cached
etag = headers.get("ETag")
if etag and _etag_matches(request.headers.get("if-none-match"), etag):
return Response(status_code=304, headers=headers)
if request.method == "HEAD":
return Response(status_code=200, media_type=content_type, headers=headers)
return Response(content=content, media_type=content_type, headers=headers)
try:
async with httpx.AsyncClient(timeout=20.0, follow_redirects=True) as client:
content, content_type, headers = await _fetch_terrain_tile(client, z, x, y)
@@ -1713,6 +1790,11 @@ async def get_terrarium_tile(z: int, x: int, y: int):
detail=f"Terrain tile fetch failed: {exc}",
) from exc
etag = headers.get("ETag")
if etag and _etag_matches(request.headers.get("if-none-match"), etag):
return Response(status_code=304, headers=headers)
if request.method == "HEAD":
return Response(status_code=200, media_type=content_type, headers=headers)
return Response(
content=content,
media_type=content_type,
@@ -1720,6 +1802,74 @@ async def get_terrarium_tile(z: int, x: int, y: int):
)
def _etag_matches(if_none_match: str | None, etag: str) -> bool:
if not if_none_match:
return False
target = etag.strip()
if target.startswith("W/"):
target = 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 == target:
return True
return False
def _terrain_cache_dir() -> Path:
configured = str(os.environ.get("PLANET_TERRAIN_CACHE_DIR") or "").strip()
return Path(configured).expanduser() if configured else TERRAIN_CACHE_DEFAULT_DIR
def _terrain_cache_max_bytes() -> int:
raw = str(os.environ.get("PLANET_TERRAIN_CACHE_MAX_BYTES") or "").strip()
if raw:
try:
return max(1024, int(raw))
except ValueError:
pass
return TERRAIN_CACHE_MAX_BYTES_DEFAULT
def _terrain_tile_path(z: int, x: int, y: int) -> Path:
return _terrain_cache_dir() / f"{z}_{x}_{y}.png"
def _terrain_tile_headers(content: bytes, *, cache_control: str = "public, max-age=86400") -> dict[str, str]:
digest = hashlib.sha256(content).hexdigest()[:24]
return {
"Cache-Control": cache_control,
"ETag": f'"{digest}"',
}
def _prune_terrain_disk_cache(cache_dir: Path, max_bytes: int) -> None:
try:
entries: list[tuple[float, int, Path]] = []
total = 0
for item in cache_dir.iterdir():
if not item.is_file() or not item.name.endswith(".png"):
continue
stat = item.stat()
total += stat.st_size
entries.append((stat.st_mtime, stat.st_size, item))
if total <= max_bytes:
return
target = int(max_bytes * 0.85)
entries.sort(key=lambda row: row[0])
for _mtime, size, item in entries:
if total <= target:
break
with suppress(OSError):
item.unlink(missing_ok=True)
total -= size
except OSError:
return
def _is_valid_terrain_tile(z: int, x: int, y: int) -> bool:
if z < 0 or x < 0 or y < 0:
return False
@@ -1728,13 +1878,16 @@ def _is_valid_terrain_tile(z: int, x: int, y: int) -> bool:
def _get_cached_terrain_tile(z: int, x: int, y: int) -> tuple[bytes, str, dict[str, str]] | None:
key = (z, x, y)
cached = _terrain_tile_cache.get(key)
if cached is None:
path = _terrain_tile_path(z, x, y)
if not path.is_file():
return None
_terrain_tile_cache.move_to_end(key)
content, content_type, headers = cached
return content, content_type, dict(headers)
try:
content = path.read_bytes()
with suppress(OSError):
os.utime(path, None)
except OSError:
return None
return content, "image/png", _terrain_tile_headers(content)
def _cache_terrain_tile(
@@ -1742,14 +1895,21 @@ def _cache_terrain_tile(
x: int,
y: int,
content: bytes,
content_type: str,
headers: dict[str, str],
_content_type: str,
_headers: dict[str, str],
) -> None:
key = (z, x, y)
_terrain_tile_cache[key] = (content, content_type, dict(headers))
_terrain_tile_cache.move_to_end(key)
while len(_terrain_tile_cache) > TERRAIN_TILE_CACHE_MAX_ITEMS:
_terrain_tile_cache.popitem(last=False)
cache_dir = _terrain_cache_dir()
cache_dir.mkdir(parents=True, exist_ok=True)
path = _terrain_tile_path(z, x, y)
tmp_path = path.with_suffix(f".{uuid4().hex}.tmp")
try:
tmp_path.write_bytes(content)
tmp_path.replace(path)
except OSError:
with suppress(OSError):
tmp_path.unlink(missing_ok=True)
return
_prune_terrain_disk_cache(cache_dir, _terrain_cache_max_bytes())
async def _fetch_terrain_tile(
@@ -1767,23 +1927,14 @@ async def _fetch_terrain_tile(
upstream.raise_for_status()
cache_control = upstream.headers.get("cache-control") or "public, max-age=86400"
headers = {
"Cache-Control": cache_control,
}
etag = upstream.headers.get("etag")
last_modified = upstream.headers.get("last-modified")
if etag:
headers["ETag"] = etag
if last_modified:
headers["Last-Modified"] = last_modified
content_type = upstream.headers.get("content-type", "image/png")
content = upstream.content
headers = _terrain_tile_headers(content, cache_control=cache_control)
_cache_terrain_tile(z, x, y, content, content_type, headers)
return content, content_type, dict(headers)
@router.post("/terrain/terrarium/batch", dependencies=[_vis_read_dep])
@router.post("/terrain/terrarium/batch", dependencies=[_vis_tile_read_dep])
async def get_terrarium_tile_batch(payload: TerrariumTileBatchRequest):
"""Fetch Terrarium elevation tiles in batches so the browser avoids many tiny requests."""
unique_tiles: list[TerrariumTileRequest] = []
@@ -2095,6 +2246,8 @@ async def _build_compute_centers_geojson(
"type": "FeatureCollection",
"features": [],
"unresolved": [],
"withheld_count": 0,
"withheld_by_status": {},
"count": 0,
"stats": {
"total": 0,
@@ -2140,6 +2293,8 @@ async def _build_compute_centers_geojson(
"type": "FeatureCollection",
"features": sanitized_features,
"unresolved": unresolved,
"withheld_count": int(geojson.get("withheld_count") or 0),
"withheld_by_status": geojson.get("withheld_by_status") or {},
"count": len(sanitized_features),
"stats": {
"total": len(sanitized_features),
@@ -2188,6 +2343,8 @@ class SaveComputeCenterLocationRequest(BaseModel):
raw_payload: Dict[str, Any] = Field(default_factory=dict)
needs_confirmation: bool = False
verification_status: Optional[str] = None
workflow_run_id: Optional[str] = None
feedback_rating: Optional[int] = None
model_config = {"populate_by_name": True}
@@ -2202,7 +2359,11 @@ async def _compute_center_location_web_search_capability(db: AsyncSession) -> Di
"reason": f"WebSearch 配置读取失败:{exc}",
}
provider_config = config.active_provider_config
has_api_key = bool((provider_config.api_key or "").strip()) or not provider_config.api_key_env
provider_name = normalize_web_search_provider(provider_config.provider)
has_api_key = (
provider_name == "searxng"
or bool((provider_config.api_key or "").strip())
)
if not config.enabled:
return {
"enabled": False,
@@ -2230,9 +2391,6 @@ async def get_compute_center_location_capability(
return await _compute_center_location_web_search_capability(db)
_TERMINAL_UNLOCATABLE_STATUSES = frozenset({"undisclosed", "multi_site", "anonymous"})
@router.post("/compute-centers/{source_id}/collect-location")
async def collect_compute_center_location(
source_id: str,
@@ -2240,155 +2398,78 @@ async def collect_compute_center_location(
_admin: User = Depends(require_admin_user),
db: AsyncSession = Depends(get_db),
):
"""Run deterministic facility lookups, Wikidata/PeeringDB, and controlled Tool-Calling location resolution."""
"""Run the unified `location.resolve_unknown` DAG workflow to locate a compute facility."""
if not source_id or not source_id.strip():
raise HTTPException(status_code=400, detail="source_id is required")
record = await _load_compute_center_record(db, source_id)
name = payload.name or (record.name if record else None)
metadata = (record.extra_data or {}) if record else {}
operator = payload.operator or metadata.get("operator") or metadata.get("organization") or metadata.get("owner")
site = payload.site or metadata.get("site")
organization = payload.organization or metadata.get("organization")
city = payload.city or get_record_field(record, "city") if record else payload.city
city = payload.city or (get_record_field(record, "city") if record else None)
country = payload.country or (get_record_field(record, "country") if record else None)
source = payload.source or (record.source if record else None)
record_id = payload.record_id or (record.id if record else None)
raw_sources = metadata.get("sources") if isinstance(metadata.get("sources"), list) else []
raw_sources = list(metadata.get("sources") if isinstance(metadata.get("sources"), list) else [])
source_url = metadata.get("source_url") or metadata.get("detail_url")
builds_upon = metadata.get("builds_upon")
source_raw_country = metadata.get("raw_country")
if not payload.force and source and source_id:
cached = get_compute_center_location_dict(source, source_id)
cached_status = str(cached.get("verification_status") or "").strip().lower()
if cached_status in _TERMINAL_UNLOCATABLE_STATUSES:
return {
"source_id": source_id,
"record_id": record_id,
"name": name,
"success": False,
"terminal_status": cached_status,
"failure_reason": cached.get("source_note") or f"Marked as {cached_status}",
"candidates": [],
"attempted_queries": [],
"llm_failure_reason": None,
"context": {
"name": name,
"operator": operator,
"site": site,
"city": city,
"country": country,
},
}
earth_ctx = {
"entity_type": "compute_center",
"source_id": source_id,
"record_id": record_id,
"source": source,
"name": name,
"operator": operator,
"site": site,
"organization": organization,
"city": city,
"country": country,
"sources": raw_sources,
"source_url": source_url,
"builds_upon": builds_upon,
"source_raw_country": source_raw_country,
"force": bool(payload.force),
}
candidates, attempted_queries = await asyncio.to_thread(
collect_location_candidates,
name=name,
source=source,
source_id=source_id,
operator=operator,
site=site,
organization=organization,
city=city,
country=country,
record_id=record_id,
sources=raw_sources,
source_url=source_url,
builds_upon=builds_upon,
source_raw_country=source_raw_country,
res = await run_location_workflow(
db=db,
entity_type="compute_center",
earth_context=earth_ctx,
targets=[{"entity_type": "compute_center", "entity_id": source_id, "label": name or source_id}],
record_run=True,
trigger_evolution=True,
)
llm_failure_reason = None
terminal_status: str | None = None
query = build_compute_center_location_query(
name=name,
source=source,
source_id=source_id,
operator=operator,
site=site,
organization=organization,
city=city,
country=country,
sources=raw_sources,
source_url=source_url,
builds_upon=builds_upon,
source_raw_country=source_raw_country,
)
if not candidates:
l1_candidates, l1_queries, _allow_low_short_circuit = await run_l1_structured_facility_resolvers(
query, db=db
)
if l1_candidates:
candidates = l1_candidates
attempted_queries = [*attempted_queries, *l1_queries]
if not candidates:
capability = await _compute_center_location_web_search_capability(db)
llm_result = None
if not capability.get("enabled") and not raw_sources and not source_url:
llm_failure_reason = str(capability.get("reason") or "WebSearch unavailable")
else:
try:
provider_client = await get_ai_provider_client(db)
web_search_client = await get_web_search_client(db)
if hasattr(provider_client, "analyze"):
llm_result, terminal_status = await run_controlled_location_agent(
provider_client=provider_client,
web_search_client=web_search_client,
query=query,
entity_type="compute_center",
db=db,
attempted_queries=[],
)
else:
search_result = await collect_location_search_evidence(
web_search_client=web_search_client,
query=query,
entity_type="compute_center",
)
attempted_queries = [*attempted_queries, *search_result.attempted_queries]
if not search_result.evidence:
llm_failure_reason = search_result.failure_reason
raise RuntimeError(search_result.failure_reason or "no WebSearch evidence")
llm_result = await collect_llm_location_fallback_candidate(
provider_client=provider_client,
query=query,
entity_type="compute_center",
db=db,
attempted_queries=attempted_queries,
search_evidence=search_result.evidence,
)
except Exception as exc:
if llm_failure_reason is None:
llm_failure_reason = f"LLM location factcheck unavailable: {exc}"
attempted_queries = [
*attempted_queries,
f"llm_factcheck:compute_center:{name or source_id or 'unknown'}",
]
if llm_result is not None:
attempted_queries = [*attempted_queries, *llm_result.attempted_queries]
candidates = llm_result.candidates
llm_failure_reason = llm_result.failure_reason
candidates = res.get("candidates") or []
terminal_status = res.get("terminal_status")
failure_reason = res.get("failure_reason")
attempted_queries = list(res.get("attempted_queries") or [])
workflow_run_id = res.get("workflow_run_id")
context = {
"name": name,
"operator": operator,
"site": site,
"city": city,
"country": country,
}
if terminal_status in _TERMINAL_UNLOCATABLE_STATUSES:
if terminal_status in TERMINAL_UNLOCATABLE_STATUSES:
return {
"source_id": source_id,
"record_id": record_id,
"name": name,
"success": False,
"terminal_status": terminal_status,
"failure_reason": llm_failure_reason or f"Marked as {terminal_status}",
"failure_reason": failure_reason or f"Marked as {terminal_status}",
"candidates": [],
"attempted_queries": list(attempted_queries),
"llm_failure_reason": llm_failure_reason,
"context": {
"name": name,
"operator": operator,
"site": site,
"city": city,
"country": country,
},
"attempted_queries": attempted_queries,
"llm_failure_reason": failure_reason,
"workflow_run_id": workflow_run_id,
"context": context,
}
if not candidates:
@@ -2400,8 +2481,9 @@ async def collect_compute_center_location(
"record_id": record_id,
"name": name,
"success": False,
"llm_failure_reason": llm_failure_reason,
"attempted_queries": list(attempted_queries),
"llm_failure_reason": failure_reason,
"attempted_queries": attempted_queries,
"workflow_run_id": workflow_run_id,
"context": {
"operator": operator,
"site": site,
@@ -2420,15 +2502,10 @@ async def collect_compute_center_location(
" result reached city-level precision."
),
"candidates": [],
"attempted_queries": list(attempted_queries),
"llm_failure_reason": llm_failure_reason,
"context": {
"name": name,
"operator": operator,
"site": site,
"city": city,
"country": country,
},
"attempted_queries": attempted_queries,
"llm_failure_reason": failure_reason,
"workflow_run_id": workflow_run_id,
"context": context,
}
best_candidate = candidates[0].to_dict()
@@ -2442,8 +2519,9 @@ async def collect_compute_center_location(
"success": True,
"candidate_count": len(candidates),
"best_candidate": best_candidate,
"llm_failure_reason": llm_failure_reason,
"attempted_queries": list(attempted_queries),
"llm_failure_reason": failure_reason,
"attempted_queries": attempted_queries,
"workflow_run_id": workflow_run_id,
"context": {
"operator": operator,
"site": site,
@@ -2459,14 +2537,9 @@ async def collect_compute_center_location(
"success": True,
"candidates": [candidate.to_dict() for candidate in candidates],
"best_candidate": best_candidate,
"attempted_queries": list(attempted_queries),
"context": {
"name": name,
"operator": operator,
"site": site,
"city": city,
"country": country,
},
"attempted_queries": attempted_queries,
"workflow_run_id": workflow_run_id,
"context": context,
}
@@ -2521,6 +2594,21 @@ async def save_compute_center_location(
or ("unverified" if payload.needs_confirmation else "verified"),
)
if payload.workflow_run_id:
try:
from app.services.ai.workflow_evolver import record_run_feedback
rating = payload.feedback_rating if payload.feedback_rating in (-1, 0, 1) else 1
await record_run_feedback(
db,
payload.workflow_run_id,
rating=rating,
note=f"Adopted compute-center location for {source_id}",
actor=f"admin:{getattr(_admin, 'username', 'admin')}",
)
except Exception:
pass
return {
"success": True,
"source": saved.source,
@@ -3000,6 +3088,103 @@ async def _build_visualization_geo_summary(db: AsyncSession) -> dict[str, Any]:
vessel_count = int(vessel_current_result.scalar() or 0)
aisstream_health = await db.get(AISSourceHealth, "aisstream_vessels")
def _safe_non_negative_int(value: Any) -> int:
if isinstance(value, bool) or not isinstance(value, (int, float)):
return 0
return max(0, int(value))
aircraft_cutoff = datetime.now(UTC) - timedelta(minutes=15)
aircraft_count = _safe_non_negative_int(
(
await db.execute(
select(func.count(AircraftCurrentState.icao24)).where(
AircraftCurrentState.observed_at >= aircraft_cutoff
)
)
).scalar()
)
military_aircraft_count = _safe_non_negative_int(
(
await db.execute(
select(func.count(AircraftCurrentState.icao24)).where(
AircraftCurrentState.observed_at >= aircraft_cutoff,
AircraftCurrentState.is_military.is_(True),
)
)
).scalar()
)
emergency_aircraft_count = _safe_non_negative_int(
(
await db.execute(
select(func.count(AircraftCurrentState.icao24)).where(
AircraftCurrentState.observed_at >= aircraft_cutoff,
AircraftCurrentState.is_emergency.is_(True),
)
)
).scalar()
)
latest_jam_date = (
await db.execute(select(func.max(GPSJammingCell.observed_date)))
).scalar()
gps_jamming_high_count = 0
gps_jamming_cell_count = 0
if (
isinstance(latest_jam_date, str)
and len(latest_jam_date) == 10
and latest_jam_date[4] == "-"
and latest_jam_date[7] == "-"
):
gps_jamming_cell_count = _safe_non_negative_int(
(
await db.execute(
select(func.count(GPSJammingCell.h3_index)).where(
GPSJammingCell.observed_date == latest_jam_date,
)
)
).scalar()
)
gps_jamming_high_count = _safe_non_negative_int(
(
await db.execute(
select(func.count(GPSJammingCell.h3_index)).where(
GPSJammingCell.observed_date == latest_jam_date,
GPSJammingCell.level == "high",
)
)
).scalar()
)
disaster_event_count = 0
disaster_high_count = 0
try:
from app.models.disaster import DisasterEvent
disaster_cutoff = datetime.now(UTC) - timedelta(hours=72)
disaster_event_count = _safe_non_negative_int(
(
await db.execute(
select(func.count(DisasterEvent.id)).where(
DisasterEvent.observed_at >= disaster_cutoff,
DisasterEvent.duplicate_of.is_(None),
)
)
).scalar()
)
disaster_high_count = _safe_non_negative_int(
(
await db.execute(
select(func.count(DisasterEvent.id)).where(
DisasterEvent.observed_at >= disaster_cutoff,
DisasterEvent.duplicate_of.is_(None),
DisasterEvent.severity == "high",
)
)
).scalar()
)
except Exception:
disaster_event_count = 0
disaster_high_count = 0
return {
"generated_at": to_iso8601_utc(datetime.now(UTC)),
"stats": {
@@ -3012,6 +3197,13 @@ async def _build_visualization_geo_summary(db: AsyncSession) -> dict[str, Any]:
"vessel_current_window_minutes": vessel_current_window_minutes,
"vessel_raw_unique_mmsi": 0,
"vessel_legacy_unique_mmsi": 0,
"aircraft_count": aircraft_count,
"military_aircraft_count": military_aircraft_count,
"emergency_aircraft_count": emergency_aircraft_count,
"gps_jamming_cell_count": gps_jamming_cell_count,
"gps_jamming_high_count": gps_jamming_high_count,
"disaster_event_count": disaster_event_count,
"disaster_high_count": disaster_high_count,
"aisstream_connection_state": aisstream_health.connection_state if aisstream_health else None,
"aisstream_last_seen_at": to_iso8601_utc(aisstream_health.last_seen_at) if aisstream_health else None,
"aisstream_message_rate": aisstream_health.message_rate if aisstream_health else None,
+26
View File
@@ -0,0 +1,26 @@
"""Real-time global 10m wind field analytics & spatial point query APIs."""
from __future__ import annotations
from fastapi import APIRouter, Depends, Query
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.access_gate import require_earth_or_api_access
from app.db.session import get_db
from app.services.earth_wind import get_wind_analysis_summary, query_wind_point
router = APIRouter()
@router.get("/summary", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
async def get_wind_summary(db: AsyncSession = Depends(get_db)):
return await get_wind_analysis_summary(db)
@router.get("/point", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
async def get_wind_point(
lat: float = Query(..., ge=-90.0, le=90.0),
lon: float = Query(..., ge=-180.0, le=180.0),
db: AsyncSession = Depends(get_db),
):
return await query_wind_point(lat, lon, db=db)
+64 -9
View File
@@ -47,6 +47,14 @@ TURNSTILE_VERIFY_URL = "https://challenges.cloudflare.com/turnstile/v0/siteverif
_EARTH_SESSION_TOKEN_TYPE = "earth_session"
_MAX_DESKTOP_CLOCK_SKEW_SECONDS = 300
_EARTH_SESSION_RATE_LIMIT_PER_MIN = 600
_EARTH_SESSION_TILE_RATE_LIMIT_PER_MIN = 3000
_RATE_LIMIT_LUA = """
local count = redis.call('INCR', KEYS[1])
if count == 1 or redis.call('TTL', KEYS[1]) < 0 then
redis.call('EXPIRE', KEYS[1], tonumber(ARGV[1]))
end
return count
"""
_LOCAL_SLIDING_WINDOWS: dict[str, deque[float]] = defaultdict(deque)
_LOCAL_NONCES: dict[str, float] = {}
_MAX_LOCAL_ENTRIES = 20_000
@@ -91,15 +99,31 @@ async def check_sliding_rate_limit(
redis_key = f"access_gate:{bucket}"
try:
client = _AsyncRedisClient.get_client()
count = await asyncio.wait_for(
client.incr(redis_key),
timeout=REDIS_OP_TIMEOUT_SECONDS,
)
if int(count) == 1:
await asyncio.wait_for(
client.expire(redis_key, window_seconds),
if callable(getattr(client, "eval", None)):
count = await asyncio.wait_for(
client.eval(_RATE_LIMIT_LUA, 1, redis_key, window_seconds),
timeout=REDIS_OP_TIMEOUT_SECONDS,
)
else:
count = await asyncio.wait_for(
client.incr(redis_key),
timeout=REDIS_OP_TIMEOUT_SECONDS,
)
if int(count) == 1:
await asyncio.wait_for(
client.expire(redis_key, window_seconds),
timeout=REDIS_OP_TIMEOUT_SECONDS,
)
elif callable(getattr(client, "ttl", None)):
ttl = await asyncio.wait_for(
client.ttl(redis_key),
timeout=REDIS_OP_TIMEOUT_SECONDS,
)
if int(ttl) < 0:
await asyncio.wait_for(
client.expire(redis_key, window_seconds),
timeout=REDIS_OP_TIMEOUT_SECONDS,
)
if int(count) > limit:
raise HTTPException(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
@@ -386,13 +410,43 @@ async def _validate_bearer_api_user(
return user
EarthRateLimitTier = Literal["default", "tile"]
def _resolve_earth_session_rate_limit(tier: EarthRateLimitTier) -> int:
if tier == "tile":
return max(
1,
int(
getattr(
settings,
"EARTH_SESSION_TILE_RATE_LIMIT_PER_MIN",
_EARTH_SESSION_TILE_RATE_LIMIT_PER_MIN,
)
),
)
return max(
1,
int(
getattr(
settings,
"EARTH_SESSION_RATE_LIMIT_PER_MIN",
_EARTH_SESSION_RATE_LIMIT_PER_MIN,
)
),
)
def require_earth_or_api_access(
scope: str,
*,
allow_query_api_key: bool = False,
rate_limit_tier: EarthRateLimitTier = "default",
):
"""Build a FastAPI dependency allowing API Keys, authorized JWT users, or Earth sessions."""
bucket_suffix = ":tile" if rate_limit_tier == "tile" else ""
async def _dependency(
request: Request,
credentials: HTTPAuthorizationCredentials | None = Depends(optional_bearer),
@@ -425,9 +479,10 @@ def require_earth_or_api_access(
if claims is not None:
channel = "earth_desktop" if claims.get("channel") == "desktop" else "earth_web"
cid = str(claims.get("cid") or "anon")
effective_limit = _resolve_earth_session_rate_limit(rate_limit_tier)
await check_sliding_rate_limit(
f"earth:{channel}:{cid}",
limit=_EARTH_SESSION_RATE_LIMIT_PER_MIN,
f"earth:{channel}:{cid}{bucket_suffix}",
limit=effective_limit,
window_seconds=60,
detail="Earth session rate limit exceeded",
)
+2
View File
@@ -94,6 +94,8 @@ class Settings(BaseSettings):
EARTH_API_AUTH_MODE: str = ""
EARTH_SESSION_TTL_MINUTES: int = 30
EARTH_SESSION_RATE_LIMIT_PER_MIN: int = 600
EARTH_SESSION_TILE_RATE_LIMIT_PER_MIN: int = 3000
EARTH_WEB_ALLOWED_ORIGINS: List[str] = []
EARTH_DESKTOP_HANDSHAKE_SECRET: str = ""
TURNSTILE_SECRET_KEY: str = ""
+22 -21
View File
@@ -12,14 +12,14 @@ COUNTRY_ENTRIES = [
("阿根廷", ["Argentina", "AR", "ARG"]),
("亚美尼亚", ["Armenia", "AM", "ARM"]),
("澳大利亚", ["Australia", "AU", "AUS"]),
("奥地利", ["Austria", "AT", "AUT"]),
("奥地利", ["Austria", "AT", "AUT", "Österreich"]),
("阿塞拜疆", ["Azerbaijan", "AZ", "AZE"]),
("巴哈马", ["Bahamas", "BS", "BHS"]),
("巴林", ["Bahrain", "BH", "BHR"]),
("孟加拉国", ["Bangladesh", "BD", "BGD"]),
("巴巴多斯", ["Barbados", "BB", "BRB"]),
("白俄罗斯", ["Belarus", "BY", "BLR"]),
("比利时", ["Belgium", "BE", "BEL"]),
("比利时", ["Belgium", "BE", "BEL", "België", "Belgique"]),
("伯利兹", ["Belize", "BZ", "BLZ"]),
("贝宁", ["Benin", "BJ", "BEN"]),
("不丹", ["Bhutan", "BT", "BTN"]),
@@ -51,8 +51,8 @@ COUNTRY_ENTRIES = [
("克罗地亚", ["Croatia", "HR", "HRV"]),
("古巴", ["Cuba", "CU", "CUB"]),
("塞浦路斯", ["Cyprus", "CY", "CYP"]),
("捷克", ["Czech Republic", "Czechia", "CZ", "CZE"]),
("丹麦", ["Denmark", "DK", "DNK"]),
("捷克", ["Czech Republic", "Czechia", "CZ", "CZE", "Česko"]),
("丹麦", ["Denmark", "DK", "DNK", "Danmark"]),
("吉布提", ["Djibouti", "DJ", "DJI"]),
("多米尼克", ["Dominica", "DM", "DMA"]),
("多米尼加", ["Dominican Republic", "DO", "DOM"]),
@@ -65,14 +65,14 @@ COUNTRY_ENTRIES = [
("埃斯瓦蒂尼", ["Eswatini", "SZ", "SWZ", "Swaziland"]),
("埃塞俄比亚", ["Ethiopia", "ET", "ETH"]),
("斐济", ["Fiji", "FJ", "FJI"]),
("芬兰", ["Finland", "FI", "FIN"]),
("芬兰", ["Finland", "FI", "FIN", "Suomi"]),
("法国", ["France", "FR", "FRA"]),
("加蓬", ["Gabon", "GA", "GAB"]),
("冈比亚", ["Gambia", "GM", "GMB"]),
("格鲁吉亚", ["Georgia", "GE", "GEO"]),
("德国", ["Germany", "DE", "DEU"]),
("德国", ["Germany", "DE", "DEU", "Deutschland"]),
("加纳", ["Ghana", "GH", "GHA"]),
("希腊", ["Greece", "GR", "GRC"]),
("希腊", ["Greece", "GR", "GRC", "Ελλάς", "Ελλάδα"]),
("格林纳达", ["Grenada", "GD", "GRD"]),
("危地马拉", ["Guatemala", "GT", "GTM"]),
("几内亚", ["Guinea", "GN", "GIN"]),
@@ -80,15 +80,15 @@ COUNTRY_ENTRIES = [
("圭亚那", ["Guyana", "GY", "GUY"]),
("海地", ["Haiti", "HT", "HTI"]),
("洪都拉斯", ["Honduras", "HN", "HND"]),
("匈牙利", ["Hungary", "HU", "HUN"]),
("冰岛", ["Iceland", "IS", "ISL"]),
("匈牙利", ["Hungary", "HU", "HUN", "Magyarország"]),
("冰岛", ["Iceland", "IS", "ISL", "Ísland", "Island"]),
("印度", ["India", "IN", "IND"]),
("印度尼西亚", ["Indonesia", "ID", "IDN"]),
("伊朗", ["Iran", "IR", "IRN", "Iran (Islamic Republic of)"]),
("伊拉克", ["Iraq", "IQ", "IRQ"]),
("爱尔兰", ["Ireland", "IE", "IRL"]),
("以色列", ["Israel", "IL", "ISR"]),
("意大利", ["Italy", "IT", "ITA"]),
("爱尔兰", ["Ireland", "IE", "IRL", "Éire"]),
("以色列", ["Israel", "IL", "ISR", "ישראל"]),
("意大利", ["Italy", "IT", "ITA", "Italia"]),
("牙买加", ["Jamaica", "JM", "JAM"]),
("日本", ["Japan", "JP", "JPN"]),
("约旦", ["Jordan", "JO", "JOR"]),
@@ -96,7 +96,7 @@ COUNTRY_ENTRIES = [
("肯尼亚", ["Kenya", "KE", "KEN"]),
("基里巴斯", ["Kiribati", "KI", "KIR"]),
("朝鲜", ["North Korea", "Korea, DPRK", "Democratic People's Republic of Korea", "KP", "PRK"]),
("韩国", ["South Korea", "Republic of Korea", "Korea", "KR", "KOR"]),
("韩国", ["South Korea", "Republic of Korea", "Korea", "KR", "KOR", "대한민국"]),
("科威特", ["Kuwait", "KW", "KWT"]),
("吉尔吉斯斯坦", ["Kyrgyzstan", "KG", "KGZ"]),
("老挝", ["Laos", "Lao PDR", "Lao People's Democratic Republic", "LA", "LAO"]),
@@ -129,13 +129,13 @@ COUNTRY_ENTRIES = [
("纳米比亚", ["Namibia", "NA", "NAM"]),
("瑙鲁", ["Nauru", "NR", "NRU"]),
("尼泊尔", ["Nepal", "NP", "NPL"]),
("荷兰", ["Netherlands", "NL", "NLD"]),
("荷兰", ["Netherlands", "NL", "NLD", "Nederland"]),
("新西兰", ["New Zealand", "NZ", "NZL"]),
("尼加拉瓜", ["Nicaragua", "NI", "NIC"]),
("尼日尔", ["Niger", "NE", "NER"]),
("尼日利亚", ["Nigeria", "NG", "NGA"]),
("北马其顿", ["North Macedonia", "MK", "MKD", "Macedonia"]),
("挪威", ["Norway", "NO", "NOR"]),
("挪威", ["Norway", "NO", "NOR", "Norge"]),
("阿曼", ["Oman", "OM", "OMN"]),
("巴基斯坦", ["Pakistan", "PK", "PAK"]),
("帕劳", ["Palau", "PW", "PLW"]),
@@ -145,11 +145,11 @@ COUNTRY_ENTRIES = [
("巴拉圭", ["Paraguay", "PY", "PRY"]),
("秘鲁", ["Peru", "PE", "PER"]),
("菲律宾", ["Philippines", "PH", "PHL"]),
("波兰", ["Poland", "PL", "POL"]),
("波兰", ["Poland", "PL", "POL", "Polska"]),
("葡萄牙", ["Portugal", "PT", "PRT"]),
("卡塔尔", ["Qatar", "QA", "QAT"]),
("罗马尼亚", ["Romania", "RO", "ROU"]),
("俄罗斯", ["Russia", "Russian Federation", "RU", "RUS"]),
("俄罗斯", ["Russia", "Russian Federation", "RU", "RUS", "Россия"]),
("卢旺达", ["Rwanda", "RW", "RWA"]),
("圣基茨和尼维斯", ["Saint Kitts and Nevis", "KN", "KNA"]),
("圣卢西亚", ["Saint Lucia", "LC", "LCA"]),
@@ -169,12 +169,12 @@ COUNTRY_ENTRIES = [
("索马里", ["Somalia", "SO", "SOM"]),
("南非", ["South Africa", "ZA", "ZAF"]),
("南苏丹", ["South Sudan", "SS", "SSD"]),
("西班牙", ["Spain", "ES", "ESP"]),
("西班牙", ["Spain", "ES", "ESP", "España"]),
("斯里兰卡", ["Sri Lanka", "LK", "LKA"]),
("苏丹", ["Sudan", "SD", "SDN"]),
("苏里南", ["Suriname", "SR", "SUR"]),
("瑞典", ["Sweden", "SE", "SWE"]),
("瑞士", ["Switzerland", "CH", "CHE"]),
("瑞典", ["Sweden", "SE", "SWE", "Sverige"]),
("瑞士", ["Switzerland", "CH", "CHE", "Schweiz", "Suisse", "Svizzera"]),
("叙利亚", ["Syria", "SY", "SYR", "Syrian Arab Republic"]),
("塔吉克斯坦", ["Tajikistan", "TJ", "TJK"]),
("坦桑尼亚", ["Tanzania", "TZ", "TZA", "United Republic of Tanzania"]),
@@ -188,7 +188,7 @@ COUNTRY_ENTRIES = [
("土库曼斯坦", ["Turkmenistan", "TM", "TKM"]),
("图瓦卢", ["Tuvalu", "TV", "TUV"]),
("乌干达", ["Uganda", "UG", "UGA"]),
("乌克兰", ["Ukraine", "UA", "UKR"]),
("乌克兰", ["Ukraine", "UA", "UKR", "Україна"]),
("阿联酋", ["United Arab Emirates", "AE", "ARE", "UAE"]),
("英国", ["United Kingdom", "UK", "GB", "GBR", "Great Britain", "Britain", "England"]),
("美国", ["United States", "United States of America", "US", "USA", "U.S.", "U.S.A."]),
@@ -292,6 +292,7 @@ def normalize_country(value: Any) -> Optional[str]:
normalized = re.sub(r"\s+", " ", value.strip())
normalized = normalized.replace("(", "(").replace(")", ")")
normalized = re.sub(r"\s*(the)$", "", normalized, flags=re.IGNORECASE).strip()
if not normalized:
return None
+14
View File
@@ -32,6 +32,20 @@ COLLECTOR_URL_KEYS = {
"news_live_streams": "news_live_streams.channels_url",
"barentswatch_vessels": "barentswatch_vessels.url",
"aisstream_vessels": "aisstream_vessels.url",
"global_cloud_map": "global_cloud_map.wms_url",
"cloud_hd_tiles": "cloud_hd_tiles.wmts_url",
"earth_imagery_sentinel2": "earth_imagery_sentinel2.wmts_url",
"earth_imagery_viirs_daily": "earth_imagery_viirs_daily.wmts_url",
"global_wind_gfs": "global_wind_gfs.erddap_url",
"adsb_lol_aircraft": "adsb_lol_aircraft.base_url",
"opensky_aircraft": "opensky_aircraft.states_url",
"gpsjam_interference": "gpsjam_interference.manifest_url",
"aircraft_registry": "aircraft_registry.csv_url",
"usgs_earthquakes": "usgs_earthquakes.url",
"nasa_firms_wildfires": "nasa_firms_wildfires.url",
"gdacs_disasters": "gdacs_disasters.url",
"nasa_eonet_events": "nasa_eonet_events.url",
"nga_navigation_warnings": "nga_navigation_warnings.url",
}
+63
View File
@@ -102,3 +102,66 @@ barentswatch_vessels:
aisstream_vessels:
# AISStream realtime WebSocket endpoint. Requires an AISStream API key.
url: "wss://stream.aisstream.io/v0/stream"
global_cloud_map:
# NASA GIBS WMS EPSG:4326 endpoint (multi-satellite IR composite primary)
wms_url: "https://gibs.earthdata.nasa.gov/wms/epsg4326/best/wms.cgi"
# Matt Eason equirectangular cloud map fallback URL
fallback_url: "https://clouds.matteason.co.uk/images/2048x1024/clouds-alpha.png"
cloud_hd_tiles:
# NASA GIBS WMTS EPSG:3857 GeoColor / Band13 tile template
wmts_url: "https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/GOES-East_ABI_GeoColor/default/default/GoogleMapsCompatible_Level7/{z}/{y}/{x}.png"
earth_imagery_sentinel2:
# EOX Sentinel-2 Cloudless 2024 global WMTS template
wmts_url: "https://tiles.maps.eox.at/wmts/1.0.0/s2cloudless-2024_3857/default/GoogleMapsCompatible/{z}/{y}/{x}.jpg"
earth_imagery_viirs_daily:
# NASA GIBS VIIRS SNPP Daily TrueColor WMTS template
wmts_url: "https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/VIIRS_SNPP_CorrectedReflectance_TrueColor/default/default/GoogleMapsCompatible_Level9/{z}/{y}/{x}.jpg"
global_wind_gfs:
# PacIOOS ERDDAP NCEP GFS global 0.5-deg 10m wind CSV0 endpoint
erddap_url: "https://pae-paha.pacioos.hawaii.edu/erddap/griddap/ncep_global.csv0"
adsb_lol_aircraft:
# adsb.lol open ADS-B API (ODbL attribution required)
base_url: "https://api.adsb.lol"
opensky_aircraft:
# OpenSky Network REST API (OAuth2 client credentials; non-commercial / research use)
states_url: "https://opensky-network.org/api/states/all"
token_url: "https://auth.opensky-network.org/auth/realms/opensky-network/protocol/openid-connect/token"
gpsjam_interference:
# gpsjam.org daily H3 resolution-4 interference manifest & CSV base
manifest_url: "https://gpsjam.org/data/manifest.csv"
base_data_url: "https://gpsjam.org/data"
aircraft_registry:
# Open ICAO24 aircraft registry CSV (OpenSky Aircraft Database primary, tar1090-db fallback)
csv_url: "https://s3.opensky-network.org/data-samples/metadata/aircraft-database-complete-2025-02.csv"
fallback_url: "https://github.com/wiedehopf/tar1090-db/raw/csv/aircraft.csv.gz"
usgs_earthquakes:
# USGS Earthquake Hazards Program M4.5+ past-day GeoJSON feed
url: "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_day.geojson"
nasa_firms_wildfires:
# NASA FIRMS VIIRS SNPP NRT active fire area CSV API (requires free MAP_KEY)
url: "https://firms.modaps.eosdis.nasa.gov/api/area/csv"
sensor: "VIIRS_SNPP_NRT"
days: 1
gdacs_disasters:
# GDACS Global Disaster Alert and Coordination System RSS/GeoJSON search
url: "https://www.gdacs.org/gdacsapi/api/events/geteventlist/SEARCH"
nasa_eonet_events:
# NASA Earth Observatory Natural Event Tracker v3 open events API
url: "https://eonet.gsfc.nasa.gov/api/v3/events?status=open&limit=100"
nga_navigation_warnings:
# NGA Maritime Safety Information Broadcast Warnings API
url: "https://msi.nga.mil/api/publications/broadcast-warn?output=json"
+144
View File
@@ -267,6 +267,150 @@ DEFAULT_DATASOURCES = {
"is_free": True,
"requires_credentials": False,
},
"global_cloud_map": {
"id": 34,
"name": "Global Satellite Cloud Map",
"display_name": "全球卫星红外云图",
"module": "L2",
"priority": "P1",
"frequency_minutes": 30,
"is_free": True,
"requires_credentials": False,
},
"cloud_hd_tiles": {
"id": 35,
"name": "HD Satellite Cloud Tiles",
"display_name": "高清云图瓦片金字塔",
"module": "L2",
"priority": "P1",
"frequency_minutes": 60,
"is_free": True,
"requires_credentials": False,
},
"earth_imagery_sentinel2": {
"id": 36,
"name": "Sentinel-2 Cloudless 2024 Imagery",
"display_name": "Sentinel-2 无云高分底图",
"module": "L1",
"priority": "P2",
"frequency_minutes": 1440,
"is_free": True,
"requires_credentials": False,
},
"earth_imagery_viirs_daily": {
"id": 37,
"name": "NASA GIBS Daily TrueColor Imagery",
"display_name": "NASA 每日真彩色卫星底图",
"module": "L1",
"priority": "P2",
"frequency_minutes": 720,
"is_free": True,
"requires_credentials": False,
},
"global_wind_gfs": {
"id": 38,
"name": "NOAA GFS Global 10m Wind Field",
"display_name": "全球 10m 风场 (NOAA GFS)",
"module": "L2",
"priority": "P1",
"frequency_minutes": 180,
"is_free": True,
"requires_credentials": False,
},
"adsb_lol_aircraft": {
"id": 39,
"name": "adsb.lol Military & Emergency ADS-B",
"display_name": "全球军机与紧急航班 (adsb.lol · ODbL)",
"module": "L4",
"priority": "P1",
"frequency_minutes": 1,
"is_free": True,
"requires_credentials": False,
},
"opensky_aircraft": {
"id": 40,
"name": "OpenSky Network Global Aircraft States (Non-Commercial / Research)",
"display_name": "OpenSky 全球空域状态(仅限非商业/研究用途)",
"module": "L4",
"priority": "P1",
"frequency_minutes": 2,
"is_free": True,
"requires_credentials": True,
"credential_provider": "opensky",
"credential_status": "supported",
},
"gpsjam_interference": {
"id": 41,
"name": "GPSJAM Daily H3 GNSS Interference",
"display_name": "GPS/GNSS 干扰监测 (gpsjam.org)",
"module": "L4",
"priority": "P2",
"frequency_minutes": 360,
"is_free": True,
"requires_credentials": False,
},
"aircraft_registry": {
"id": 42,
"name": "Open ICAO24 Aircraft Registry Database",
"display_name": "ICAO24 机型与运营方注册库",
"module": "L4",
"priority": "P2",
"frequency_minutes": 10080,
"is_free": True,
"requires_credentials": False,
},
"usgs_earthquakes": {
"id": 43,
"name": "USGS M4.5+ Earthquakes",
"display_name": "USGS 全球 M4.5+ 地震监测",
"module": "L4",
"priority": "P1",
"frequency_minutes": 5,
"is_free": True,
"requires_credentials": False,
},
"nasa_firms_wildfires": {
"id": 44,
"name": "NASA FIRMS VIIRS Active Fires",
"display_name": "NASA FIRMS VIIRS 全球林火热点",
"module": "L4",
"priority": "P1",
"frequency_minutes": 30,
"is_free": True,
"requires_credentials": True,
"credential_provider": "nasa_firms",
"credential_status": "supported",
},
"gdacs_disasters": {
"id": 45,
"name": "GDACS Global Disaster Alerts",
"display_name": "GDACS 联合国灾害预警 (橙/红)",
"module": "L4",
"priority": "P1",
"frequency_minutes": 15,
"is_free": True,
"requires_credentials": False,
},
"nasa_eonet_events": {
"id": 46,
"name": "NASA EONET Natural Events",
"display_name": "NASA EONET 全球自然异常事件",
"module": "L4",
"priority": "P2",
"frequency_minutes": 30,
"is_free": True,
"requires_credentials": False,
},
"nga_navigation_warnings": {
"id": 47,
"name": "NGA MSI Maritime Navigation Warnings",
"display_name": "NGA 航海警告与海缆安全通告",
"module": "L4",
"priority": "P1",
"frequency_minutes": 360,
"is_free": True,
"requires_credentials": False,
},
}
ID_TO_COLLECTOR = {info["id"]: name for name, info in DEFAULT_DATASOURCES.items()}
+25 -4
View File
@@ -29,10 +29,30 @@ def _parse_epoch(value: Any) -> Optional[datetime]:
return None
_ALPHA5_PREFIX = "ABCDEFGHJKLMNPQRSTUVWXYZ"
def format_tle_norad_id(norad_cat_id: Any) -> Optional[str]:
"""Encode a NORAD catalog id into a 5-character TLE field (Alpha-5 for >= 100000)."""
try:
norad = int(norad_cat_id)
except (TypeError, ValueError):
return None
if norad <= 0:
return None
if norad < 100000:
return f"{norad:05d}"
lead = norad // 10000
if 10 <= lead <= 33:
return f"{_ALPHA5_PREFIX[lead - 10]}{norad % 10000:04d}"
return f"{norad % 100000:05d}"
def build_tle_line1(norad_cat_id: Any, epoch: Any) -> Optional[str]:
"""Build a valid TLE line 1 from the NORAD id and epoch."""
epoch_date = _parse_epoch(epoch)
if not norad_cat_id or epoch_date is None:
norad_field = format_tle_norad_id(norad_cat_id)
if not norad_field or epoch_date is None:
return None
epoch_year = epoch_date.year % 100
@@ -49,7 +69,7 @@ def build_tle_line1(norad_cat_id: Any, epoch: Any) -> Optional[str]:
epoch_str = f"{epoch_year:02d}{day_of_year:03d}{decimal_fraction}"
core = (
f"1 {int(norad_cat_id):05d}U 00001A {epoch_str}"
f"1 {norad_field}U 00001A {epoch_str}"
" .00000000 00000-0 00000-0 0 999"
)
return core + compute_tle_checksum(core)
@@ -65,8 +85,9 @@ def build_tle_line2(
mean_motion: Any,
) -> Optional[str]:
"""Build a valid TLE line 2 from the standard orbital elements."""
norad_field = format_tle_norad_id(norad_cat_id)
required = [
norad_cat_id,
norad_field,
inclination,
raan,
eccentricity,
@@ -79,7 +100,7 @@ def build_tle_line2(
eccentricity_digits = str(round(float(eccentricity) * 10_000_000)).zfill(7)
core = (
f"2 {int(norad_cat_id):05d}"
f"2 {norad_field}"
f" {float(inclination):8.4f}"
f" {float(raan):8.4f}"
f" {eccentricity_digits}"
+23
View File
@@ -21,6 +21,7 @@ from app.models.user import User
logger = get_logger(__name__, service="security")
oauth2_scheme = HTTPBearer()
optional_oauth2_scheme = HTTPBearer(auto_error=False)
REVOKED_KEY_PREFIX = "revoked_jwt:"
LOCAL_REVOKED_MAX_ENTRIES = 10_000
@@ -297,6 +298,28 @@ async def get_current_user(
return await _load_active_user(user_id, db)
async def get_optional_current_user(
credentials: HTTPAuthorizationCredentials | None = Depends(optional_oauth2_scheme),
db: AsyncSession = Depends(get_db),
) -> User | None:
"""Resolve the active authenticated user when a valid Bearer token is present; otherwise return None."""
if credentials is None or not credentials.credentials:
return None
token = credentials.credentials
if await is_token_blacklisted(token):
return None
payload = decode_token(token)
if payload is None or payload.get("type") != "access":
return None
user_id = payload.get("sub")
if user_id is None:
return None
try:
return await _load_active_user(user_id, db)
except HTTPException:
return None
async def get_current_user_refresh(
credentials: HTTPAuthorizationCredentials = Depends(oauth2_scheme),
db: AsyncSession = Depends(get_db),
+7 -2
View File
@@ -5,15 +5,20 @@ from __future__ import annotations
from datetime import UTC, datetime
def ensure_utc(value: datetime | None) -> datetime | None:
def ensure_utc(value: datetime | str | None) -> datetime | None:
if value is None:
return None
if isinstance(value, str):
stripped = value.strip()
if not stripped:
return None
value = datetime.fromisoformat(stripped.replace("Z", "+00:00"))
if value.tzinfo is None:
return value.replace(tzinfo=UTC)
return value.astimezone(UTC)
def to_iso8601_utc(value: datetime | None) -> str | None:
def to_iso8601_utc(value: datetime | str | None) -> str | None:
normalized = ensure_utc(value)
if normalized is None:
return None
@@ -0,0 +1,83 @@
[
{
"id": "malacca_strait",
"name": "马六甲海峡",
"name_en": "Strait of Malacca",
"category": "energy_container_chokepoint",
"center": [2.2, 101.8],
"polygon": [[98.0, 5.8], [100.3, 5.5], [103.9, 1.35], [104.6, 1.15], [104.2, 0.7], [100.8, 2.2], [97.4, 5.0], [98.0, 5.8]],
"source_citation": "IHO S-23 Limits of Oceans and Seas & UNCTAD Review of Maritime Transport"
},
{
"id": "strait_of_hormuz",
"name": "霍尔木兹海峡",
"name_en": "Strait of Hormuz",
"category": "energy_chokepoint",
"center": [26.55, 56.35],
"polygon": [[55.6, 26.8], [56.5, 27.15], [57.3, 26.4], [56.8, 25.7], [55.9, 25.9], [55.6, 26.8]],
"source_citation": "EIA World Oil Transit Chokepoints & UKHO Admiralty Chart boundaries"
},
{
"id": "bab_el_mandeb",
"name": "曼德海峡",
"name_en": "Bab el-Mandeb Strait",
"category": "cable_energy_chokepoint",
"center": [12.65, 43.35],
"polygon": [[42.8, 13.1], [43.55, 13.1], [43.7, 12.35], [43.0, 12.25], [42.8, 13.1]],
"source_citation": "IHO S-23 Limits of Oceans and Seas & NGA Pub. 172 Sailing Directions"
},
{
"id": "suez_canal",
"name": "苏伊士运河通道",
"name_en": "Suez Canal Corridor",
"category": "cable_container_chokepoint",
"center": [30.55, 32.35],
"polygon": [[32.1, 31.35], [32.65, 31.35], [32.7, 29.85], [32.15, 29.85], [32.1, 31.35]],
"source_citation": "Suez Canal Authority Navigation Rules & TeleGeography Submarine Cable Atlas"
},
{
"id": "panama_canal",
"name": "巴拿马运河",
"name_en": "Panama Canal",
"category": "container_chokepoint",
"center": [9.1, -79.72],
"polygon": [[-80.1, 9.5], [-79.4, 9.5], [-79.35, 8.75], [-79.95, 8.75], [-80.1, 9.5]],
"source_citation": "Autoridad del Canal de Panama Vessel Requirements & NGA Pub. 148"
},
{
"id": "strait_of_gibraltar",
"name": "直布罗陀海峡",
"name_en": "Strait of Gibraltar",
"category": "cable_maritime_chokepoint",
"center": [35.96, -5.58],
"polygon": [[-6.1, 36.2], [-5.2, 36.2], [-5.2, 35.75], [-6.1, 35.75], [-6.1, 36.2]],
"source_citation": "IHO S-23 Mediterranean Western Limit & UKHO Traffic Separation Scheme"
},
{
"id": "bosphorus_strait",
"name": "博斯普鲁斯海峡",
"name_en": "Bosphorus Strait",
"category": "energy_grain_chokepoint",
"center": [41.12, 29.08],
"polygon": [[28.92, 41.28], [29.24, 41.28], [29.18, 40.96], [28.90, 40.96], [28.92, 41.28]],
"source_citation": "Montreux Convention Transit Zone & Turkish Straits VTS"
},
{
"id": "taiwan_strait",
"name": "台湾海峡",
"name_en": "Taiwan Strait",
"category": "cable_container_chokepoint",
"center": [24.3, 119.5],
"polygon": [[118.2, 25.4], [121.1, 25.4], [120.4, 22.8], [117.7, 23.2], [118.2, 25.4]],
"source_citation": "NGA World Port Index & TeleGeography Asia-Pacific Cable Corridor"
},
{
"id": "korea_strait",
"name": "朝鲜海峡(对马海峡)",
"name_en": "Korea / Tsushima Strait",
"category": "maritime_chokepoint",
"center": [34.4, 129.3],
"polygon": [[128.4, 35.2], [130.3, 35.0], [130.0, 33.4], [128.1, 33.7], [128.4, 35.2]],
"source_citation": "IHO S-23 & Japan Coast Guard / KHOA Maritime TSS"
}
]
+26
View File
@@ -0,0 +1,26 @@
[
{"id": "port_shanghai", "name": "上海港", "name_en": "Port of Shanghai", "country": "China", "lat": 31.36, "lon": 121.62, "port_type": "container", "throughput_rank": 1, "source_citation": "Lloyd's List Top 100 Ports 2024"},
{"id": "port_singapore", "name": "新加坡港", "name_en": "Port of Singapore", "country": "Singapore", "lat": 1.26, "lon": 103.82, "port_type": "mixed", "throughput_rank": 2, "source_citation": "Lloyd's List Top 100 Ports 2024"},
{"id": "port_ningbo", "name": "宁波舟山港", "name_en": "Port of Ningbo-Zhoushan", "country": "China", "lat": 29.93, "lon": 121.85, "port_type": "mixed", "throughput_rank": 3, "source_citation": "Lloyd's List Top 100 Ports 2024"},
{"id": "port_shenzhen", "name": "深圳港", "name_en": "Port of Shenzhen", "country": "China", "lat": 22.50, "lon": 113.88, "port_type": "container", "throughput_rank": 4, "source_citation": "Lloyd's List Top 100 Ports 2024"},
{"id": "port_qingdao", "name": "青岛港", "name_en": "Port of Qingdao", "country": "China", "lat": 36.08, "lon": 120.32, "port_type": "mixed", "throughput_rank": 5, "source_citation": "Lloyd's List Top 100 Ports 2024"},
{"id": "port_busan", "name": "釜山港", "name_en": "Port of Busan", "country": "South Korea", "lat": 35.10, "lon": 129.04, "port_type": "container", "throughput_rank": 7, "source_citation": "Lloyd's List Top 100 Ports 2024"},
{"id": "port_jebel_ali", "name": "杰贝阿里港", "name_en": "Port of Jebel Ali", "country": "UAE", "lat": 25.00, "lon": 55.06, "port_type": "container", "throughput_rank": 9, "source_citation": "Lloyd's List Top 100 Ports 2024"},
{"id": "port_rotterdam", "name": "鹿特丹港", "name_en": "Port of Rotterdam", "country": "Netherlands", "lat": 51.90, "lon": 4.25, "port_type": "mixed", "throughput_rank": 10, "source_citation": "Lloyd's List Top 100 Ports 2024"},
{"id": "port_antwerp", "name": "安特卫普-布鲁日港", "name_en": "Port of Antwerp-Bruges", "country": "Belgium", "lat": 51.27, "lon": 4.34, "port_type": "container", "throughput_rank": 11, "source_citation": "Lloyd's List Top 100 Ports 2024"},
{"id": "port_kaohsiung", "name": "高雄港", "name_en": "Port of Kaohsiung", "country": "China", "lat": 22.61, "lon": 120.28, "port_type": "container", "throughput_rank": 18, "source_citation": "Lloyd's List Top 100 Ports 2024"},
{"id": "port_los_angeles", "name": "洛杉矶-长滩港", "name_en": "Port of Los Angeles / Long Beach", "country": "United States", "lat": 33.74, "lon": -118.26, "port_type": "container", "throughput_rank": 8, "source_citation": "Lloyd's List Top 100 Ports 2024"},
{"id": "port_port_said", "name": "塞得港", "name_en": "Port Said", "country": "Egypt", "lat": 31.26, "lon": 32.31, "port_type": "container", "throughput_rank": 29, "source_citation": "UNCTAD Port Statistics & NGA World Port Index"},
{"id": "port_ras_tanura", "name": "拉斯塔努拉油港", "name_en": "Ras Tanura Oil Terminal", "country": "Saudi Arabia", "lat": 26.64, "lon": 50.16, "port_type": "oil_lng", "throughput_rank": 1, "source_citation": "EIA Saudi Crude Export Terminal Data"},
{"id": "port_ras_laffan", "name": "拉斯拉凡 LNG 港", "name_en": "Ras Laffan LNG Terminal", "country": "Qatar", "lat": 25.93, "lon": 51.54, "port_type": "oil_lng", "throughput_rank": 2, "source_citation": "GIIGNL Annual LNG Terminal Report"},
{"id": "port_sabine_pass", "name": "萨宾帕斯 LNG 港", "name_en": "Sabine Pass LNG Terminal", "country": "United States", "lat": 29.74, "lon": -93.87, "port_type": "oil_lng", "throughput_rank": 3, "source_citation": "US FERC & EIA Natural Gas Export Registry"},
{"id": "port_hedland", "name": "黑德兰港", "name_en": "Port Hedland", "country": "Australia", "lat": -20.31, "lon": 118.58, "port_type": "bulk", "throughput_rank": 1, "source_citation": "Pilbara Ports Authority Annual Tonnage Report"},
{"id": "port_norfolk", "name": "诺福克海军基地", "name_en": "Naval Station Norfolk", "country": "United States", "lat": 36.95, "lon": -76.33, "port_type": "naval", "throughput_rank": null, "source_citation": "NGA World Port Index WPI-25080"},
{"id": "port_yokosuka", "name": "横须贺军港", "name_en": "Yokosuka Naval Base", "country": "Japan", "lat": 35.29, "lon": 139.66, "port_type": "naval", "throughput_rank": null, "source_citation": "NGA World Port Index WPI-61370"},
{"id": "port_portsmouth", "name": "朴次茅斯军港", "name_en": "HMNB Portsmouth", "country": "United Kingdom", "lat": 50.80, "lon": -1.11, "port_type": "naval", "throughput_rank": null, "source_citation": "UKHO Admiralty Port Registry & NGA WPI"},
{"id": "port_toulon", "name": "土伦军港", "name_en": "Toulon Naval Base", "country": "France", "lat": 43.11, "lon": 5.91, "port_type": "naval", "throughput_rank": null, "source_citation": "SHOM Mediterranean Naval Ports & NGA WPI"},
{"id": "port_djibouti", "name": "吉布提港", "name_en": "Port of Djibouti", "country": "Djibouti", "lat": 11.60, "lon": 43.14, "port_type": "mixed", "throughput_rank": null, "source_citation": "NGA World Port Index WPI-47850"},
{"id": "port_balboa", "name": "巴尔博亚港", "name_en": "Port of Balboa", "country": "Panama", "lat": 8.95, "lon": -79.57, "port_type": "container", "throughput_rank": 40, "source_citation": "Panama Maritime Authority & NGA WPI"},
{"id": "port_algeciras", "name": "阿尔赫西拉斯港", "name_en": "Port of Algeciras", "country": "Spain", "lat": 36.13, "lon": -5.43, "port_type": "container", "throughput_rank": 33, "source_citation": "Lloyd's List Top 100 Ports 2024"},
{"id": "port_novorossiysk", "name": "新罗西斯克港", "name_en": "Port of Novorossiysk", "country": "Russia", "lat": 44.72, "lon": 37.78, "port_type": "bulk", "throughput_rank": null, "source_citation": "NGA World Port Index Black Sea Terminals"}
]
@@ -0,0 +1,177 @@
"""Create compute_configuration_revisions table and extend compute_evidence_candidates columns."""
from __future__ import annotations
from sqlalchemy import text
VERSION = "0007"
NAME = "add_compute_configuration_revisions"
async def upgrade(conn) -> None:
"""Apply compute revision ledger table and candidate review/comparison columns idempotently."""
dialect = getattr(getattr(conn, "dialect", None), "name", "")
if dialect == "postgresql":
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS compute_configuration_revisions (
id SERIAL PRIMARY KEY,
publish_id VARCHAR(64) NOT NULL UNIQUE,
parent_publish_id VARCHAR(64),
action VARCHAR(16) NOT NULL DEFAULT 'publish',
content_fingerprint VARCHAR(64) NOT NULL,
is_default_content BOOLEAN NOT NULL DEFAULT FALSE,
config_payload JSONB NOT NULL DEFAULT '{}'::jsonb,
diff_summary JSONB NOT NULL DEFAULT '[]'::jsonb,
source_candidate_ids JSONB NOT NULL DEFAULT '[]'::jsonb,
publish_note TEXT NOT NULL DEFAULT '',
published_by_id INTEGER,
published_by_name VARCHAR(120),
published_by_role VARCHAR(40),
published_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
presentation_status VARCHAR(16) NOT NULL DEFAULT 'pending',
presentation_attempts INTEGER NOT NULL DEFAULT 0,
presentation_error TEXT NOT NULL DEFAULT '',
presentation_delivered_at TIMESTAMPTZ
)
"""
)
)
await conn.execute(
text(
"""
CREATE INDEX IF NOT EXISTS idx_compute_config_revisions_published_at
ON compute_configuration_revisions (published_at)
"""
)
)
await conn.execute(
text(
"""
CREATE INDEX IF NOT EXISTS idx_compute_config_revisions_fingerprint
ON compute_configuration_revisions (content_fingerprint)
"""
)
)
await conn.execute(
text(
"""
CREATE INDEX IF NOT EXISTS idx_compute_config_revisions_pres_status
ON compute_configuration_revisions (presentation_status, id)
"""
)
)
await conn.execute(
text(
"""
ALTER TABLE compute_evidence_candidates
ADD COLUMN IF NOT EXISTS comparison JSONB NOT NULL DEFAULT '{}'::jsonb,
ADD COLUMN IF NOT EXISTS dedupe_fingerprint VARCHAR(64),
ADD COLUMN IF NOT EXISTS review_reason_code VARCHAR(40),
ADD COLUMN IF NOT EXISTS review_reason TEXT NOT NULL DEFAULT '',
ADD COLUMN IF NOT EXISTS published_publish_id VARCHAR(64)
"""
)
)
await conn.execute(
text(
"""
CREATE INDEX IF NOT EXISTS idx_compute_evidence_candidates_dedupe_fp
ON compute_evidence_candidates (dedupe_fingerprint)
"""
)
)
await conn.execute(
text(
"""
CREATE INDEX IF NOT EXISTS idx_compute_evidence_candidates_published_pid
ON compute_evidence_candidates (published_publish_id)
"""
)
)
return
# SQLite path
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS compute_configuration_revisions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
publish_id VARCHAR(64) NOT NULL UNIQUE,
parent_publish_id VARCHAR(64),
action VARCHAR(16) NOT NULL DEFAULT 'publish',
content_fingerprint VARCHAR(64) NOT NULL,
is_default_content BOOLEAN NOT NULL DEFAULT 0,
config_payload JSON NOT NULL DEFAULT '{}',
diff_summary JSON NOT NULL DEFAULT '[]',
source_candidate_ids JSON NOT NULL DEFAULT '[]',
publish_note TEXT NOT NULL DEFAULT '',
published_by_id INTEGER,
published_by_name VARCHAR(120),
published_by_role VARCHAR(40),
published_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
presentation_status VARCHAR(16) NOT NULL DEFAULT 'pending',
presentation_attempts INTEGER NOT NULL DEFAULT 0,
presentation_error TEXT NOT NULL DEFAULT '',
presentation_delivered_at TIMESTAMP
)
"""
)
)
await conn.execute(
text(
"""
CREATE INDEX IF NOT EXISTS idx_compute_config_revisions_published_at
ON compute_configuration_revisions (published_at)
"""
)
)
await conn.execute(
text(
"""
CREATE INDEX IF NOT EXISTS idx_compute_config_revisions_fingerprint
ON compute_configuration_revisions (content_fingerprint)
"""
)
)
await conn.execute(
text(
"""
CREATE INDEX IF NOT EXISTS idx_compute_config_revisions_pres_status
ON compute_configuration_revisions (presentation_status, id)
"""
)
)
res = await conn.execute(text("PRAGMA table_info(compute_evidence_candidates)"))
columns = {str(row[1]) for row in res.fetchall()}
if columns:
alter_specs = [
("comparison", "JSON NOT NULL DEFAULT '{}'"),
("dedupe_fingerprint", "VARCHAR(64)"),
("review_reason_code", "VARCHAR(40)"),
("review_reason", "TEXT NOT NULL DEFAULT ''"),
("published_publish_id", "VARCHAR(64)"),
]
for col_name, col_ddl in alter_specs:
if col_name not in columns:
await conn.execute(
text(f"ALTER TABLE compute_evidence_candidates ADD COLUMN {col_name} {col_ddl}")
)
await conn.execute(
text(
"""
CREATE INDEX IF NOT EXISTS idx_compute_evidence_candidates_dedupe_fp
ON compute_evidence_candidates (dedupe_fingerprint)
"""
)
)
await conn.execute(
text(
"""
CREATE INDEX IF NOT EXISTS idx_compute_evidence_candidates_published_pid
ON compute_evidence_candidates (published_publish_id)
"""
)
)
@@ -0,0 +1,325 @@
"""Create aircraft ADS-B, source health, and GPS jamming tables with PG outbox triggers."""
from __future__ import annotations
from sqlalchemy import text
VERSION = "0008"
NAME = "add_aircraft_and_gps_jamming"
async def upgrade(conn) -> None:
"""Create aircraft & GPS jamming tables, indexes, and PG outbox triggers idempotently."""
dialect = getattr(getattr(conn, "dialect", None), "name", "")
if dialect == "postgresql":
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS aircraft_static (
icao24 VARCHAR(12) PRIMARY KEY,
registration VARCHAR(32),
aircraft_type VARCHAR(16),
type_description VARCHAR(128),
operator VARCHAR(128),
owner VARCHAR(128),
origin_country VARCHAR(64),
category VARCHAR(32),
is_military BOOLEAN NOT NULL DEFAULT FALSE,
source VARCHAR(64) NOT NULL DEFAULT 'aircraft_registry',
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
"""
)
)
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS aircraft_current_state (
icao24 VARCHAR(12) PRIMARY KEY,
callsign VARCHAR(16),
lat DOUBLE PRECISION NOT NULL,
lon DOUBLE PRECISION NOT NULL,
baro_altitude_m DOUBLE PRECISION,
geo_altitude_m DOUBLE PRECISION,
ground_speed_ms DOUBLE PRECISION,
track_deg DOUBLE PRECISION,
vertical_rate_ms DOUBLE PRECISION,
squawk VARCHAR(8),
on_ground BOOLEAN NOT NULL DEFAULT FALSE,
category VARCHAR(32) NOT NULL DEFAULT 'other',
is_military BOOLEAN NOT NULL DEFAULT FALSE,
is_emergency BOOLEAN NOT NULL DEFAULT FALSE,
emergency_code VARCHAR(8),
source VARCHAR(64) NOT NULL,
observed_at TIMESTAMPTZ NOT NULL,
ingested_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
"""
)
)
await conn.execute(
text(
"""
CREATE INDEX IF NOT EXISTS idx_aircraft_current_bbox
ON aircraft_current_state (lon, lat)
"""
)
)
await conn.execute(
text(
"""
CREATE INDEX IF NOT EXISTS idx_aircraft_current_observed
ON aircraft_current_state (observed_at DESC)
"""
)
)
await conn.execute(
text(
"""
CREATE INDEX IF NOT EXISTS idx_aircraft_current_category
ON aircraft_current_state (category)
"""
)
)
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS aircraft_position (
id SERIAL PRIMARY KEY,
icao24 VARCHAR(12) NOT NULL,
lat DOUBLE PRECISION NOT NULL,
lon DOUBLE PRECISION NOT NULL,
altitude_m DOUBLE PRECISION,
ground_speed_ms DOUBLE PRECISION,
track_deg DOUBLE PRECISION,
observed_at TIMESTAMPTZ NOT NULL
)
"""
)
)
await conn.execute(
text(
"""
CREATE INDEX IF NOT EXISTS idx_aircraft_pos_icao24_time
ON aircraft_position (icao24, observed_at)
"""
)
)
await conn.execute(
text(
"""
CREATE INDEX IF NOT EXISTS idx_aircraft_pos_time
ON aircraft_position (observed_at)
"""
)
)
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS adsb_source_health (
source VARCHAR(64) PRIMARY KEY,
connection_state VARCHAR(32) NOT NULL DEFAULT 'disconnected',
active_count INTEGER NOT NULL DEFAULT 0,
last_success_at TIMESTAMPTZ,
last_error VARCHAR(500),
cooldown_until TIMESTAMPTZ,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
"""
)
)
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS gps_jamming_cells (
h3_index VARCHAR(32) NOT NULL,
observed_date VARCHAR(10) NOT NULL,
lat DOUBLE PRECISION NOT NULL,
lon DOUBLE PRECISION NOT NULL,
resolution INTEGER NOT NULL DEFAULT 4,
level VARCHAR(16) NOT NULL,
bad_ratio DOUBLE PRECISION NOT NULL DEFAULT 0.0,
aircraft_count INTEGER NOT NULL DEFAULT 0,
boundary JSONB NOT NULL DEFAULT '[]'::jsonb,
source VARCHAR(64) NOT NULL DEFAULT 'gpsjam_interference',
ingested_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (h3_index, observed_date)
)
"""
)
)
await conn.execute(
text(
"""
CREATE INDEX IF NOT EXISTS idx_gps_jamming_date_level
ON gps_jamming_cells (observed_date, level)
"""
)
)
# Attach Earth outbox triggers when trigger helper already exists (migrator or session init).
res = await conn.execute(
text(
"SELECT EXISTS (SELECT 1 FROM pg_proc WHERE proname = 'planet_notify_earth_table_changed_statement')"
)
)
if bool(res.scalar()):
for table_name in ("aircraft_current_state", "gps_jamming_cells"):
for op, ref in (
("insert", "REFERENCING NEW TABLE AS new_rows"),
("update", "REFERENCING OLD TABLE AS old_rows NEW TABLE AS new_rows"),
("delete", "REFERENCING OLD TABLE AS old_rows"),
):
await conn.execute(
text(f"DROP TRIGGER IF EXISTS tr_planet_{table_name}_changed_{op} ON {table_name}")
)
await conn.execute(
text(
f"""
CREATE TRIGGER tr_planet_{table_name}_changed_{op}
AFTER {op.upper()} ON {table_name}
{ref}
FOR EACH STATEMENT
EXECUTE FUNCTION planet_notify_earth_table_changed_statement()
"""
)
)
return
# SQLite path
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS aircraft_static (
icao24 VARCHAR(12) PRIMARY KEY,
registration VARCHAR(32),
aircraft_type VARCHAR(16),
type_description VARCHAR(128),
operator VARCHAR(128),
owner VARCHAR(128),
origin_country VARCHAR(64),
category VARCHAR(32),
is_military BOOLEAN NOT NULL DEFAULT 0,
source VARCHAR(64) NOT NULL DEFAULT 'aircraft_registry',
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
)
"""
)
)
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS aircraft_current_state (
icao24 VARCHAR(12) PRIMARY KEY,
callsign VARCHAR(16),
lat FLOAT NOT NULL,
lon FLOAT NOT NULL,
baro_altitude_m FLOAT,
geo_altitude_m FLOAT,
ground_speed_ms FLOAT,
track_deg FLOAT,
vertical_rate_ms FLOAT,
squawk VARCHAR(8),
on_ground BOOLEAN NOT NULL DEFAULT 0,
category VARCHAR(32) NOT NULL DEFAULT 'other',
is_military BOOLEAN NOT NULL DEFAULT 0,
is_emergency BOOLEAN NOT NULL DEFAULT 0,
emergency_code VARCHAR(8),
source VARCHAR(64) NOT NULL,
observed_at TIMESTAMP NOT NULL,
ingested_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
)
"""
)
)
await conn.execute(
text(
"""
CREATE INDEX IF NOT EXISTS idx_aircraft_current_bbox
ON aircraft_current_state (lon, lat)
"""
)
)
await conn.execute(
text(
"""
CREATE INDEX IF NOT EXISTS idx_aircraft_current_observed
ON aircraft_current_state (observed_at)
"""
)
)
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS aircraft_position (
id INTEGER PRIMARY KEY AUTOINCREMENT,
icao24 VARCHAR(12) NOT NULL,
lat FLOAT NOT NULL,
lon FLOAT NOT NULL,
altitude_m FLOAT,
ground_speed_ms FLOAT,
track_deg FLOAT,
observed_at TIMESTAMP NOT NULL
)
"""
)
)
await conn.execute(
text(
"""
CREATE INDEX IF NOT EXISTS idx_aircraft_pos_icao24_time
ON aircraft_position (icao24, observed_at)
"""
)
)
await conn.execute(
text(
"""
CREATE INDEX IF NOT EXISTS idx_aircraft_pos_time
ON aircraft_position (observed_at)
"""
)
)
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS adsb_source_health (
source VARCHAR(64) PRIMARY KEY,
connection_state VARCHAR(32) NOT NULL DEFAULT 'disconnected',
active_count INTEGER NOT NULL DEFAULT 0,
last_success_at TIMESTAMP,
last_error VARCHAR(500),
cooldown_until TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
)
"""
)
)
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS gps_jamming_cells (
h3_index VARCHAR(32) NOT NULL,
observed_date VARCHAR(10) NOT NULL,
lat FLOAT NOT NULL,
lon FLOAT NOT NULL,
resolution INTEGER NOT NULL DEFAULT 4,
level VARCHAR(16) NOT NULL,
bad_ratio FLOAT NOT NULL DEFAULT 0.0,
aircraft_count INTEGER NOT NULL DEFAULT 0,
boundary JSON NOT NULL DEFAULT '[]',
source VARCHAR(64) NOT NULL DEFAULT 'gpsjam_interference',
ingested_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (h3_index, observed_date)
)
"""
)
)
await conn.execute(
text(
"""
CREATE INDEX IF NOT EXISTS idx_gps_jamming_date_level
ON gps_jamming_cells (observed_date, level)
"""
)
)
@@ -0,0 +1,218 @@
"""Create disaster_events, cable_advisories, and news credibility columns."""
from __future__ import annotations
from sqlalchemy import text
VERSION = "0009"
NAME = "add_disaster_and_maritime_intelligence"
async def upgrade(conn) -> None:
"""Create disaster_events, cable_advisories, and add news credibility/theater columns idempotently."""
dialect = getattr(getattr(conn, "dialect", None), "name", "")
if dialect == "postgresql":
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS disaster_events (
id SERIAL PRIMARY KEY,
source VARCHAR(64) NOT NULL,
source_event_id VARCHAR(160) NOT NULL,
event_type VARCHAR(32) NOT NULL,
severity VARCHAR(24) NOT NULL DEFAULT 'medium',
title VARCHAR(500) NOT NULL,
lat DOUBLE PRECISION NOT NULL,
lon DOUBLE PRECISION NOT NULL,
magnitude DOUBLE PRECISION,
started_at TIMESTAMPTZ,
ended_at TIMESTAMPTZ,
url TEXT,
observed_at TIMESTAMPTZ NOT NULL,
ingested_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
duplicate_of INTEGER,
cluster_count INTEGER NOT NULL DEFAULT 1,
max_brightness_k DOUBLE PRECISION,
raw JSONB DEFAULT '{}'::jsonb,
CONSTRAINT uq_disaster_source_event UNIQUE (source, source_event_id)
)
"""
)
)
await conn.execute(
text(
"CREATE INDEX IF NOT EXISTS idx_disaster_source ON disaster_events (source)"
)
)
await conn.execute(
text(
"CREATE INDEX IF NOT EXISTS idx_disaster_type_observed ON disaster_events (event_type, observed_at)"
)
)
await conn.execute(
text(
"CREATE INDEX IF NOT EXISTS idx_disaster_geo ON disaster_events (lon, lat)"
)
)
await conn.execute(
text(
"CREATE INDEX IF NOT EXISTS idx_disaster_duplicate_of ON disaster_events (duplicate_of)"
)
)
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS cable_advisories (
id SERIAL PRIMARY KEY,
source_warning_id VARCHAR(120) UNIQUE NOT NULL,
text TEXT NOT NULL,
lat DOUBLE PRECISION,
lon DOUBLE PRECISION,
polygon JSONB,
issued_at TIMESTAMPTZ,
cancelled_at TIMESTAMPTZ,
matched_cable_ids JSONB NOT NULL DEFAULT '[]'::jsonb,
match_method VARCHAR(64),
ingested_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
"""
)
)
await conn.execute(
text(
"CREATE INDEX IF NOT EXISTS idx_cable_advisories_issued ON cable_advisories (issued_at)"
)
)
# News credibility & theater columns (credibility_tier defaults NULL = unrated)
await conn.execute(
text(
"ALTER TABLE earth_news_items ADD COLUMN IF NOT EXISTS credibility_tier INTEGER"
)
)
await conn.execute(
text(
"ALTER TABLE earth_news_items ADD COLUMN IF NOT EXISTS state_affiliated BOOLEAN NOT NULL DEFAULT FALSE"
)
)
await conn.execute(
text(
"ALTER TABLE earth_news_items ADD COLUMN IF NOT EXISTS theater_tags JSONB NOT NULL DEFAULT '[]'::jsonb"
)
)
await conn.execute(
text(
"CREATE INDEX IF NOT EXISTS idx_earth_news_credibility_tier ON earth_news_items (credibility_tier)"
)
)
# Register PG outbox notification triggers when helper function is present
fn_exists = await conn.execute(
text(
"SELECT 1 FROM pg_proc WHERE proname = 'planet_notify_earth_table_changed_statement'"
)
)
if fn_exists.scalar() is not None:
for table_name in ("disaster_events", "cable_advisories"):
for op, ref in (
("insert", "REFERENCING NEW TABLE AS new_rows"),
("update", "REFERENCING OLD TABLE AS old_rows NEW TABLE AS new_rows"),
("delete", "REFERENCING OLD TABLE AS old_rows"),
):
await conn.execute(
text(
f"DROP TRIGGER IF EXISTS tr_planet_{table_name}_changed_{op} ON {table_name}"
)
)
await conn.execute(
text(
f"""
CREATE TRIGGER tr_planet_{table_name}_changed_{op}
AFTER {op.upper()} ON {table_name}
{ref}
FOR EACH STATEMENT
EXECUTE FUNCTION planet_notify_earth_table_changed_statement()
"""
)
)
return
# SQLite path
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS disaster_events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
source VARCHAR(64) NOT NULL,
source_event_id VARCHAR(160) NOT NULL,
event_type VARCHAR(32) NOT NULL,
severity VARCHAR(24) NOT NULL DEFAULT 'medium',
title VARCHAR(500) NOT NULL,
lat FLOAT NOT NULL,
lon FLOAT NOT NULL,
magnitude FLOAT,
started_at TIMESTAMP,
ended_at TIMESTAMP,
url TEXT,
observed_at TIMESTAMP NOT NULL,
ingested_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
duplicate_of INTEGER,
cluster_count INTEGER NOT NULL DEFAULT 1,
max_brightness_k FLOAT,
raw JSON DEFAULT '{}',
UNIQUE (source, source_event_id)
)
"""
)
)
await conn.execute(
text(
"CREATE INDEX IF NOT EXISTS idx_disaster_type_observed ON disaster_events (event_type, observed_at)"
)
)
await conn.execute(
text("CREATE INDEX IF NOT EXISTS idx_disaster_geo ON disaster_events (lon, lat)")
)
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS cable_advisories (
id INTEGER PRIMARY KEY AUTOINCREMENT,
source_warning_id VARCHAR(120) UNIQUE NOT NULL,
text TEXT NOT NULL,
lat FLOAT,
lon FLOAT,
polygon JSON,
issued_at TIMESTAMP,
cancelled_at TIMESTAMP,
matched_cable_ids JSON NOT NULL DEFAULT '[]',
match_method VARCHAR(64),
ingested_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
)
"""
)
)
# Add earth_news_items columns if the table exists in this SQLite db
tbl_check = await conn.execute(
text("SELECT name FROM sqlite_master WHERE type='table' AND name='earth_news_items'")
)
if tbl_check.scalar() is not None:
cols_res = await conn.execute(text("PRAGMA table_info(earth_news_items)"))
existing_cols = {row[1] for row in cols_res.fetchall()}
if "credibility_tier" not in existing_cols:
await conn.execute(
text("ALTER TABLE earth_news_items ADD COLUMN credibility_tier INTEGER")
)
if "state_affiliated" not in existing_cols:
await conn.execute(
text(
"ALTER TABLE earth_news_items ADD COLUMN state_affiliated BOOLEAN NOT NULL DEFAULT 0"
)
)
if "theater_tags" not in existing_cols:
await conn.execute(
text(
"ALTER TABLE earth_news_items ADD COLUMN theater_tags JSON NOT NULL DEFAULT '[]'"
)
)
@@ -0,0 +1,117 @@
"""Create ontology_entity_aliases and analyst_links tables."""
from __future__ import annotations
from sqlalchemy import text
VERSION = "0010"
NAME = "add_ontology_curation"
async def upgrade(conn) -> None:
"""Create non-derivable ontology curation tables idempotently for PostgreSQL and SQLite."""
dialect = getattr(getattr(conn, "dialect", None), "name", "")
if dialect == "postgresql":
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS ontology_entity_aliases (
id SERIAL PRIMARY KEY,
alias VARCHAR(200) NOT NULL,
object_id VARCHAR(160) NOT NULL,
source VARCHAR(80) NOT NULL DEFAULT 'analyst',
created_by VARCHAR(120) NOT NULL DEFAULT 'system',
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
CONSTRAINT uq_ontology_alias_object UNIQUE (alias, object_id)
)
"""
)
)
await conn.execute(
text(
"CREATE INDEX IF NOT EXISTS idx_ontology_alias_alias ON ontology_entity_aliases (alias)"
)
)
await conn.execute(
text(
"CREATE INDEX IF NOT EXISTS idx_ontology_alias_object_id ON ontology_entity_aliases (object_id)"
)
)
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS analyst_links (
id SERIAL PRIMARY KEY,
from_object_id VARCHAR(160) NOT NULL,
to_object_id VARCHAR(160) NOT NULL,
relation_type VARCHAR(80) NOT NULL,
note TEXT NOT NULL DEFAULT '',
evidence_ids JSONB NOT NULL DEFAULT '[]'::jsonb,
created_by VARCHAR(120) NOT NULL DEFAULT 'analyst',
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
status VARCHAR(32) NOT NULL DEFAULT 'active'
)
"""
)
)
await conn.execute(
text(
"CREATE INDEX IF NOT EXISTS idx_analyst_links_pair ON analyst_links (from_object_id, to_object_id, status)"
)
)
await conn.execute(
text(
"CREATE INDEX IF NOT EXISTS idx_analyst_links_to ON analyst_links (to_object_id)"
)
)
return
# SQLite path
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS ontology_entity_aliases (
id INTEGER PRIMARY KEY AUTOINCREMENT,
alias VARCHAR(200) NOT NULL,
object_id VARCHAR(160) NOT NULL,
source VARCHAR(80) NOT NULL DEFAULT 'analyst',
created_by VARCHAR(120) NOT NULL DEFAULT 'system',
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE (alias, object_id)
)
"""
)
)
await conn.execute(
text(
"CREATE INDEX IF NOT EXISTS idx_ontology_alias_alias ON ontology_entity_aliases (alias)"
)
)
await conn.execute(
text(
"CREATE INDEX IF NOT EXISTS idx_ontology_alias_object_id ON ontology_entity_aliases (object_id)"
)
)
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS analyst_links (
id INTEGER PRIMARY KEY AUTOINCREMENT,
from_object_id VARCHAR(160) NOT NULL,
to_object_id VARCHAR(160) NOT NULL,
relation_type VARCHAR(80) NOT NULL,
note TEXT NOT NULL DEFAULT '',
evidence_ids JSON NOT NULL DEFAULT '[]',
created_by VARCHAR(120) NOT NULL DEFAULT 'analyst',
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
status VARCHAR(32) NOT NULL DEFAULT 'active'
)
"""
)
)
await conn.execute(
text(
"CREATE INDEX IF NOT EXISTS idx_analyst_links_pair ON analyst_links (from_object_id, to_object_id, status)"
)
)
@@ -0,0 +1,155 @@
"""Create geofences and situational_incidents tables (§3.8)."""
from __future__ import annotations
from sqlalchemy import text
VERSION = "0011"
NAME = "add_geofences_and_incidents"
async def upgrade(conn) -> None:
"""Create geofences and situational_incidents idempotently for PostgreSQL and SQLite."""
dialect = getattr(getattr(conn, "dialect", None), "name", "")
if dialect == "postgresql":
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS geofences (
id SERIAL PRIMARY KEY,
name VARCHAR(200) NOT NULL,
kind VARCHAR(32) NOT NULL DEFAULT 'custom',
geometry JSONB NOT NULL DEFAULT '{}'::jsonb,
rules JSONB NOT NULL DEFAULT '{}'::jsonb,
enabled BOOLEAN NOT NULL DEFAULT TRUE,
created_by VARCHAR(120) NOT NULL DEFAULT 'system',
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
"""
)
)
await conn.execute(
text("CREATE INDEX IF NOT EXISTS idx_geofences_kind_enabled ON geofences (kind, enabled)")
)
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS situational_incidents (
id SERIAL PRIMARY KEY,
incident_type VARCHAR(80) NOT NULL,
severity VARCHAR(24) NOT NULL DEFAULT 'medium',
status VARCHAR(32) NOT NULL DEFAULT 'open',
h3_index VARCHAR(32),
window_start TIMESTAMPTZ,
window_end TIMESTAMPTZ,
object_ids JSONB NOT NULL DEFAULT '[]'::jsonb,
signal_summary JSONB NOT NULL DEFAULT '{}'::jsonb,
evidence JSONB NOT NULL DEFAULT '[]'::jsonb,
assessment_kind VARCHAR(48) NOT NULL DEFAULT 'rule_alert',
title VARCHAR(320) NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_by VARCHAR(120),
resolution_note TEXT
)
"""
)
)
await conn.execute(
text(
"CREATE INDEX IF NOT EXISTS idx_situational_incidents_kind_status ON situational_incidents (assessment_kind, status, created_at)"
)
)
await conn.execute(
text(
"CREATE INDEX IF NOT EXISTS idx_situational_incidents_h3 ON situational_incidents (h3_index)"
)
)
fn_exists = await conn.execute(
text(
"SELECT 1 FROM pg_proc WHERE proname = 'planet_notify_earth_table_changed_statement'"
)
)
if fn_exists.scalar() is not None:
for table_name in ("geofences", "situational_incidents"):
for op, ref in (
("insert", "REFERENCING NEW TABLE AS new_rows"),
("update", "REFERENCING OLD TABLE AS old_rows NEW TABLE AS new_rows"),
("delete", "REFERENCING OLD TABLE AS old_rows"),
):
await conn.execute(
text(
f"DROP TRIGGER IF EXISTS tr_planet_{table_name}_changed_{op} ON {table_name}"
)
)
await conn.execute(
text(
f"""
CREATE TRIGGER tr_planet_{table_name}_changed_{op}
AFTER {op.upper()} ON {table_name}
{ref}
FOR EACH STATEMENT
EXECUTE FUNCTION planet_notify_earth_table_changed_statement()
"""
)
)
return
# SQLite path
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS geofences (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCHAR(200) NOT NULL,
kind VARCHAR(32) NOT NULL DEFAULT 'custom',
geometry JSON NOT NULL DEFAULT '{}',
rules JSON NOT NULL DEFAULT '{}',
enabled BOOLEAN NOT NULL DEFAULT 1,
created_by VARCHAR(120) NOT NULL DEFAULT 'system',
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
)
"""
)
)
await conn.execute(
text("CREATE INDEX IF NOT EXISTS idx_geofences_kind_enabled ON geofences (kind, enabled)")
)
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS situational_incidents (
id INTEGER PRIMARY KEY AUTOINCREMENT,
incident_type VARCHAR(80) NOT NULL,
severity VARCHAR(24) NOT NULL DEFAULT 'medium',
status VARCHAR(32) NOT NULL DEFAULT 'open',
h3_index VARCHAR(32),
window_start TIMESTAMP,
window_end TIMESTAMP,
object_ids JSON NOT NULL DEFAULT '[]',
signal_summary JSON NOT NULL DEFAULT '{}',
evidence JSON NOT NULL DEFAULT '[]',
assessment_kind VARCHAR(48) NOT NULL DEFAULT 'rule_alert',
title VARCHAR(320) NOT NULL DEFAULT '',
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_by VARCHAR(120),
resolution_note TEXT
)
"""
)
)
await conn.execute(
text(
"CREATE INDEX IF NOT EXISTS idx_situational_incidents_kind_status ON situational_incidents (assessment_kind, status, created_at)"
)
)
await conn.execute(
text(
"CREATE INDEX IF NOT EXISTS idx_situational_incidents_h3 ON situational_incidents (h3_index)"
)
)
@@ -0,0 +1,117 @@
"""Create investigation_cases, case_items, and case_versions tables (§4.3)."""
from __future__ import annotations
from sqlalchemy import text
VERSION = "0012"
NAME = "add_investigation_cases"
async def upgrade(conn) -> None:
"""Create investigation case tables idempotently for PostgreSQL and SQLite."""
dialect = getattr(getattr(conn, "dialect", None), "name", "")
if dialect == "postgresql":
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS investigation_cases (
id SERIAL PRIMARY KEY,
title VARCHAR(240) NOT NULL,
status VARCHAR(32) NOT NULL DEFAULT 'draft',
owner_id INTEGER NOT NULL,
owner_name VARCHAR(120) NOT NULL DEFAULT '',
summary TEXT NOT NULL DEFAULT '',
is_shared BOOLEAN NOT NULL DEFAULT TRUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
"""
)
)
await conn.execute(
text("CREATE INDEX IF NOT EXISTS idx_cases_status ON investigation_cases (status, is_shared)")
)
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS case_items (
id SERIAL PRIMARY KEY,
case_id INTEGER NOT NULL REFERENCES investigation_cases(id) ON DELETE CASCADE,
item_type VARCHAR(48) NOT NULL,
ref_id VARCHAR(200) NOT NULL,
payload JSONB NOT NULL DEFAULT '{}'::jsonb,
added_by VARCHAR(120) NOT NULL DEFAULT 'analyst',
added_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
"""
)
)
await conn.execute(text("CREATE INDEX IF NOT EXISTS idx_case_items_case_id ON case_items (case_id)"))
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS case_versions (
id SERIAL PRIMARY KEY,
case_id INTEGER NOT NULL REFERENCES investigation_cases(id) ON DELETE CASCADE,
version INTEGER NOT NULL,
snapshot JSONB NOT NULL DEFAULT '{}'::jsonb,
content_sha256 VARCHAR(64) NOT NULL,
frozen_by VARCHAR(120) NOT NULL,
frozen_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
CONSTRAINT idx_case_versions_case_ver UNIQUE (case_id, version)
)
"""
)
)
return
# SQLite path
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS investigation_cases (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title VARCHAR(240) NOT NULL,
status VARCHAR(32) NOT NULL DEFAULT 'draft',
owner_id INTEGER NOT NULL,
owner_name VARCHAR(120) NOT NULL DEFAULT '',
summary TEXT NOT NULL DEFAULT '',
is_shared BOOLEAN NOT NULL DEFAULT 1,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
)
"""
)
)
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS case_items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
case_id INTEGER NOT NULL REFERENCES investigation_cases(id) ON DELETE CASCADE,
item_type VARCHAR(48) NOT NULL,
ref_id VARCHAR(200) NOT NULL,
payload JSON NOT NULL DEFAULT '{}',
added_by VARCHAR(120) NOT NULL DEFAULT 'analyst',
added_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
)
"""
)
)
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS case_versions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
case_id INTEGER NOT NULL REFERENCES investigation_cases(id) ON DELETE CASCADE,
version INTEGER NOT NULL,
snapshot JSON NOT NULL DEFAULT '{}',
content_sha256 VARCHAR(64) NOT NULL,
frozen_by VARCHAR(120) NOT NULL,
frozen_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE (case_id, version)
)
"""
)
)
@@ -0,0 +1,62 @@
"""Create action_requests table (§4.5)."""
from __future__ import annotations
from sqlalchemy import text
VERSION = "0013"
NAME = "add_action_requests"
async def upgrade(conn) -> None:
"""Create action_requests table idempotently for PostgreSQL and SQLite."""
dialect = getattr(getattr(conn, "dialect", None), "name", "")
if dialect == "postgresql":
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS action_requests (
id SERIAL PRIMARY KEY,
action_type VARCHAR(80) NOT NULL,
target_object_ids JSONB NOT NULL DEFAULT '[]'::jsonb,
params JSONB NOT NULL DEFAULT '{}'::jsonb,
risk_level VARCHAR(24) NOT NULL DEFAULT 'low',
status VARCHAR(32) NOT NULL DEFAULT 'pending',
requested_by VARCHAR(120) NOT NULL,
requested_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
approved_by VARCHAR(120),
approved_at TIMESTAMPTZ,
decision_reason TEXT,
execution_result JSONB NOT NULL DEFAULT '{}'::jsonb,
source_workflow_run_id VARCHAR(120)
)
"""
)
)
await conn.execute(
text("CREATE INDEX IF NOT EXISTS idx_action_requests_status ON action_requests (status, risk_level)")
)
return
# SQLite path
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS action_requests (
id INTEGER PRIMARY KEY AUTOINCREMENT,
action_type VARCHAR(80) NOT NULL,
target_object_ids JSON NOT NULL DEFAULT '[]',
params JSON NOT NULL DEFAULT '{}',
risk_level VARCHAR(24) NOT NULL DEFAULT 'low',
status VARCHAR(32) NOT NULL DEFAULT 'pending',
requested_by VARCHAR(120) NOT NULL,
requested_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
approved_by VARCHAR(120),
approved_at TIMESTAMP,
decision_reason TEXT,
execution_result JSON NOT NULL DEFAULT '{}',
source_workflow_run_id VARCHAR(120)
)
"""
)
)
+79 -3
View File
@@ -50,7 +50,9 @@ BEGIN
NULLIF(row_data->>'source_id', ''),
NULLIF(row_data->>'incident_key', ''),
NULLIF(row_data->>'id', ''),
NULLIF(row_data->>'mmsi', '')
NULLIF(row_data->>'mmsi', ''),
NULLIF(row_data->>'icao24', ''),
NULLIF(row_data->>'h3_index', '')
)
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
@@ -81,7 +83,9 @@ BEGIN
NULLIF(row_data->>'source_id', ''),
NULLIF(row_data->>'incident_key', ''),
NULLIF(row_data->>'id', ''),
NULLIF(row_data->>'mmsi', '')
NULLIF(row_data->>'mmsi', ''),
NULLIF(row_data->>'icao24', ''),
NULLIF(row_data->>'h3_index', '')
)
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
@@ -129,7 +133,9 @@ BEGIN
NULLIF(row_data->>'source_id', ''),
NULLIF(row_data->>'incident_key', ''),
NULLIF(row_data->>'id', ''),
NULLIF(row_data->>'mmsi', '')
NULLIF(row_data->>'mmsi', ''),
NULLIF(row_data->>'icao24', ''),
NULLIF(row_data->>'h3_index', '')
)
FROM (
SELECT to_jsonb(t) AS row_data FROM new_rows AS t
@@ -484,6 +490,7 @@ async def init_db():
import app.models.bgp_observation # noqa: F401
import app.models.collected_data # noqa: F401
import app.models.compute_center_location # noqa: F401
import app.models.compute_configuration_revision # noqa: F401
import app.models.system_setting # noqa: F401
import app.models.playground_session # noqa: F401
import app.models.playground_message # noqa: F401
@@ -824,6 +831,12 @@ async def _init_db_ddl_and_seed():
"vessel_current_state",
"ais_raw_observations",
"ais_source_health",
"aircraft_current_state",
"gps_jamming_cells",
"disaster_events",
"cable_advisories",
"geofences",
"situational_incidents",
"compute_center_locations",
"earth_interactables",
"earth_news_items",
@@ -919,6 +932,34 @@ async def _init_db_ddl_and_seed():
"""
)
)
await conn.execute(
text(
"""
ALTER TABLE compute_evidence_candidates
ADD COLUMN IF NOT EXISTS comparison JSONB NOT NULL DEFAULT '{}'::jsonb,
ADD COLUMN IF NOT EXISTS dedupe_fingerprint VARCHAR(64),
ADD COLUMN IF NOT EXISTS review_reason_code VARCHAR(40),
ADD COLUMN IF NOT EXISTS review_reason TEXT NOT NULL DEFAULT '',
ADD COLUMN IF NOT EXISTS published_publish_id VARCHAR(64)
"""
)
)
await conn.execute(
text(
"""
CREATE INDEX IF NOT EXISTS idx_compute_evidence_candidates_dedupe_fp
ON compute_evidence_candidates (dedupe_fingerprint)
"""
)
)
await conn.execute(
text(
"""
CREATE INDEX IF NOT EXISTS idx_compute_evidence_candidates_published_pid
ON compute_evidence_candidates (published_publish_id)
"""
)
)
await conn.execute(
text(
"""
@@ -1116,6 +1157,28 @@ async def _init_db_ddl_and_seed():
await ensure_baseline_stamped(conn)
if engine.dialect.name == "postgresql":
async with engine.connect() as base_conn:
auto_conn = await base_conn.execution_options(isolation_level="AUTOCOMMIT")
await auto_conn.execute(
text(
"""
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_collected_data_current_collected_at
ON collected_data (collected_at DESC)
WHERE is_current IS TRUE
"""
)
)
await auto_conn.execute(
text(
"""
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_collected_data_current_source_type
ON collected_data (source, data_type)
WHERE is_current IS TRUE
"""
)
)
async with async_session_factory() as session:
from app.services.bgp_collector_locations import (
seed_default_bgp_collector_locations,
@@ -1131,6 +1194,19 @@ async def _init_db_ddl_and_seed():
await purge_legacy_earth_boundary_datasources(session)
await ensure_default_admin_user(session)
await ensure_default_storage_policy(session)
from app.services.ai.proactive_pipeline import retry_pending_compute_presentations
from app.services.ai.workflow_registry import ensure_builtin_workflows
from app.services.compute_configuration import ensure_compute_revision_baseline
await ensure_builtin_workflows(session)
await ensure_compute_revision_baseline(session)
try:
await retry_pending_compute_presentations(session)
await session.commit()
except Exception as exc:
await session.rollback()
logger.warning_event(
"Startup retry of pending compute presentations failed",
event="compute.revision.presentation_failed",
context={"phase": "startup", "error": str(exc)},
)
+7 -1
View File
@@ -90,7 +90,9 @@ async def lifespan(app: FastAPI):
if settings.should_run_scheduler:
if await acquire_scheduler_leader_lock():
leader_lock_acquired = True
await cleanup_stale_running_tasks()
await cleanup_stale_running_tasks(
include_all_running=(settings.normalized_role == "all")
)
start_scheduler()
scheduler_started = True
await sync_scheduler_with_datasources()
@@ -201,6 +203,10 @@ class NonStreamingGZipMiddleware:
if path.endswith("/stream") or b"text/event-stream" in accept:
await self.app(scope, receive, send)
return
# PMTiles clients read byte ranges; re-encoding would break Content-Range.
if path.endswith(".pmtiles"):
await self.app(scope, receive, send)
return
await self.gzip_app(scope, receive, send)
+28
View File
@@ -17,9 +17,22 @@ from app.models.playground_session import PlaygroundSession
from app.models.playground_message import PlaygroundMessage
from app.models.system_log import AuditLog, ObservabilityEvent, ObservabilityEventGroup, SystemLog
from app.models.vessel import AISConflictRecord, AISRawObservation, AISSourceHealth, VesselPosition, VesselStatic
from app.models.aircraft import (
ADSBSourceHealth,
AircraftCurrentState,
AircraftPosition,
AircraftStatic,
)
from app.models.gps_jamming import GPSJammingCell
from app.models.disaster import DisasterEvent
from app.models.maritime_advisory import CableAdvisory
from app.models.datasource_mapping import DataSourceMappingTemplate
from app.models.earth_news import EarthNewsItem
from app.models.earth_interactable import EarthInteractable
from app.models.ontology import AnalystLink, OntologyEntityAlias
from app.models.geofence import Geofence, SituationalIncident
from app.models.investigation_case import CaseItem, CaseVersion, InvestigationCase
from app.models.action_request import ActionRequest
from app.models.situational_assessment import (
ComputeEvidenceCandidate,
EvidenceRecord,
@@ -61,9 +74,24 @@ __all__ = [
"AISRawObservation",
"AISConflictRecord",
"AISSourceHealth",
"AircraftStatic",
"AircraftCurrentState",
"AircraftPosition",
"ADSBSourceHealth",
"GPSJammingCell",
"DisasterEvent",
"CableAdvisory",
"DataSourceMappingTemplate",
"EarthNewsItem",
"EarthInteractable",
"OntologyEntityAlias",
"AnalystLink",
"Geofence",
"SituationalIncident",
"InvestigationCase",
"CaseItem",
"CaseVersion",
"ActionRequest",
"EvidenceRecord",
"InvestigationSession",
"SituationalAssessment",
+44
View File
@@ -0,0 +1,44 @@
"""Action Request model for human-in-the-loop operations & webhooks (§4.5)."""
from __future__ import annotations
from sqlalchemy import Column, DateTime, Integer, JSON, String, Text
from sqlalchemy.sql import func
from app.core.time import to_iso8601_utc
from app.db.session import Base
class ActionRequest(Base):
__tablename__ = "action_requests"
id = Column(Integer, primary_key=True, autoincrement=True)
action_type = Column(String(80), nullable=False, index=True)
target_object_ids = Column(JSON, nullable=False, default=list)
params = Column(JSON, nullable=False, default=dict)
risk_level = Column(String(24), nullable=False, default="low", index=True)
status = Column(String(32), nullable=False, default="pending", index=True)
requested_by = Column(String(120), nullable=False, index=True)
requested_at = Column(DateTime(timezone=True), nullable=False, server_default=func.now())
approved_by = Column(String(120), nullable=True, index=True)
approved_at = Column(DateTime(timezone=True), nullable=True)
decision_reason = Column(Text, nullable=True)
execution_result = Column(JSON, nullable=False, default=dict)
source_workflow_run_id = Column(String(120), nullable=True, index=True)
def to_dict(self) -> dict:
return {
"id": self.id,
"action_type": self.action_type,
"target_object_ids": list(self.target_object_ids or []),
"params": dict(self.params or {}),
"risk_level": self.risk_level,
"status": self.status,
"requested_by": self.requested_by,
"requested_at": to_iso8601_utc(self.requested_at),
"approved_by": self.approved_by,
"approved_at": to_iso8601_utc(self.approved_at),
"decision_reason": self.decision_reason,
"execution_result": dict(self.execution_result or {}),
"source_workflow_run_id": self.source_workflow_run_id,
}
+152
View File
@@ -0,0 +1,152 @@
"""Aircraft ADS-B and registry database models."""
from __future__ import annotations
from sqlalchemy import Boolean, Column, DateTime, Float, Index, Integer, String
from sqlalchemy.sql import func
from app.core.enums import ConnectionState
from app.core.time import to_iso8601_utc
from app.db.session import Base
class AircraftStatic(Base):
"""Reference aircraft metadata populated from open ICAO24 registries."""
__tablename__ = "aircraft_static"
icao24 = Column(String(12), primary_key=True)
registration = Column(String(32), nullable=True, index=True)
aircraft_type = Column(String(16), nullable=True, index=True)
type_description = Column(String(128), nullable=True)
operator = Column(String(128), nullable=True)
owner = Column(String(128), nullable=True)
origin_country = Column(String(64), nullable=True, index=True)
category = Column(String(32), nullable=True, index=True)
is_military = Column(Boolean, nullable=False, default=False, index=True)
source = Column(String(64), nullable=False, default="aircraft_registry")
updated_at = Column(DateTime(timezone=True), nullable=False, server_default=func.now())
def to_dict(self) -> dict:
return {
"icao24": self.icao24,
"registration": self.registration,
"aircraft_type": self.aircraft_type,
"type_description": self.type_description,
"operator": self.operator,
"owner": self.owner,
"origin_country": self.origin_country,
"category": self.category,
"is_military": bool(self.is_military),
"source": self.source,
"updated_at": to_iso8601_utc(self.updated_at),
}
class AircraftCurrentState(Base):
"""Latest merged state per active aircraft for low-latency snapshot serving."""
__tablename__ = "aircraft_current_state"
icao24 = Column(String(12), primary_key=True)
callsign = Column(String(16), nullable=True, index=True)
lat = Column(Float, nullable=False)
lon = Column(Float, nullable=False)
baro_altitude_m = Column(Float, nullable=True)
geo_altitude_m = Column(Float, nullable=True)
ground_speed_ms = Column(Float, nullable=True)
track_deg = Column(Float, nullable=True)
vertical_rate_ms = Column(Float, nullable=True)
squawk = Column(String(8), nullable=True, index=True)
on_ground = Column(Boolean, nullable=False, default=False)
category = Column(String(32), nullable=False, default="other", index=True)
is_military = Column(Boolean, nullable=False, default=False, index=True)
is_emergency = Column(Boolean, nullable=False, default=False, index=True)
emergency_code = Column(String(8), nullable=True)
source = Column(String(64), nullable=False, index=True)
observed_at = Column(DateTime(timezone=True), nullable=False)
ingested_at = Column(DateTime(timezone=True), nullable=False, server_default=func.now())
__table_args__ = (
Index("idx_aircraft_current_bbox", "lon", "lat"),
Index("idx_aircraft_current_observed", "observed_at"),
)
def to_dict(self) -> dict:
return {
"icao24": self.icao24,
"callsign": self.callsign,
"lat": self.lat,
"lon": self.lon,
"baro_altitude_m": self.baro_altitude_m,
"geo_altitude_m": self.geo_altitude_m,
"ground_speed_ms": self.ground_speed_ms,
"track_deg": self.track_deg,
"vertical_rate_ms": self.vertical_rate_ms,
"squawk": self.squawk,
"on_ground": bool(self.on_ground),
"category": self.category,
"is_military": bool(self.is_military),
"is_emergency": bool(self.is_emergency),
"emergency_code": self.emergency_code,
"source": self.source,
"observed_at": to_iso8601_utc(self.observed_at),
"ingested_at": to_iso8601_utc(self.ingested_at),
}
class AircraftPosition(Base):
"""Downsampled aircraft track points retained 24h for trails and 4D replay."""
__tablename__ = "aircraft_position"
id = Column(Integer, primary_key=True, autoincrement=True)
icao24 = Column(String(12), nullable=False)
lat = Column(Float, nullable=False)
lon = Column(Float, nullable=False)
altitude_m = Column(Float, nullable=True)
ground_speed_ms = Column(Float, nullable=True)
track_deg = Column(Float, nullable=True)
observed_at = Column(DateTime(timezone=True), nullable=False)
__table_args__ = (
Index("idx_aircraft_pos_icao24_time", "icao24", "observed_at"),
Index("idx_aircraft_pos_time", "observed_at"),
)
def to_dict(self) -> dict:
return {
"id": self.id,
"icao24": self.icao24,
"lat": self.lat,
"lon": self.lon,
"altitude_m": self.altitude_m,
"ground_speed_ms": self.ground_speed_ms,
"track_deg": self.track_deg,
"observed_at": to_iso8601_utc(self.observed_at),
}
class ADSBSourceHealth(Base):
"""Runtime health & cooldown state per aircraft ADS-B source."""
__tablename__ = "adsb_source_health"
source = Column(String(64), primary_key=True)
connection_state = Column(String(32), nullable=False, default=ConnectionState.DISCONNECTED.value, index=True)
active_count = Column(Integer, nullable=False, default=0)
last_success_at = Column(DateTime(timezone=True), nullable=True, index=True)
last_error = Column(String(500), nullable=True)
cooldown_until = Column(DateTime(timezone=True), nullable=True, index=True)
updated_at = Column(DateTime(timezone=True), nullable=False, server_default=func.now(), index=True)
def to_dict(self) -> dict:
return {
"source": self.source,
"connection_state": self.connection_state,
"active_count": int(self.active_count or 0),
"last_success_at": to_iso8601_utc(self.last_success_at),
"last_error": self.last_error,
"cooldown_until": to_iso8601_utc(self.cooldown_until),
"updated_at": to_iso8601_utc(self.updated_at),
}
+2 -2
View File
@@ -1,6 +1,6 @@
"""Collected Data model for storing data from all collectors"""
from sqlalchemy import Boolean, Column, DateTime, ForeignKey, Integer, String, Text, JSON, Index
from sqlalchemy import Boolean, Column, DateTime, ForeignKey, Integer, String, Text, JSON, Index, text
from sqlalchemy.sql import func
from app.core.collected_data_fields import get_record_field
@@ -39,7 +39,7 @@ class CollectedData(Base):
# Status
is_valid = Column(Integer, default=1) # 1=valid, 0=invalid
is_current = Column(Boolean, default=True, index=True)
is_current = Column(Boolean, default=True, nullable=False, server_default=text("true"), index=True)
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={})
@@ -0,0 +1,62 @@
"""Versioned history table for curated compute comparison configurations."""
from __future__ import annotations
from sqlalchemy import Boolean, Column, DateTime, Index, Integer, JSON, String, Text
from sqlalchemy.sql import func
from app.core.time import to_iso8601_utc
from app.db.session import Base
class ComputeConfigurationRevision(Base):
"""Immutable snapshot ledger of published compute comparison configurations."""
__tablename__ = "compute_configuration_revisions"
id = Column(Integer, primary_key=True, autoincrement=True, index=True)
publish_id = Column(String(64), unique=True, nullable=False, index=True)
parent_publish_id = Column(String(64), nullable=True, index=True)
action = Column(String(16), nullable=False, default="publish")
content_fingerprint = Column(String(64), nullable=False, index=True)
is_default_content = Column(Boolean, nullable=False, default=False)
config_payload = Column(JSON, nullable=False, default=dict)
diff_summary = Column(JSON, nullable=False, default=list)
source_candidate_ids = Column(JSON, nullable=False, default=list)
publish_note = Column(Text, nullable=False, default="")
published_by_id = Column(Integer, nullable=True)
published_by_name = Column(String(120), nullable=True)
published_by_role = Column(String(40), nullable=True)
published_at = Column(
DateTime(timezone=True), server_default=func.now(), nullable=False, index=True
)
presentation_status = Column(String(16), nullable=False, default="pending", index=True)
presentation_attempts = Column(Integer, nullable=False, default=0)
presentation_error = Column(Text, nullable=False, default="")
presentation_delivered_at = Column(DateTime(timezone=True), nullable=True)
__table_args__ = (
Index("idx_compute_config_revisions_published_at", "published_at"),
Index("idx_compute_config_revisions_pres_status", "presentation_status", "id"),
)
def to_dict(self) -> dict:
return {
"id": self.id,
"publish_id": self.publish_id,
"parent_publish_id": self.parent_publish_id,
"action": self.action,
"content_fingerprint": self.content_fingerprint,
"is_default_content": bool(self.is_default_content),
"diff_summary": list(self.diff_summary or []),
"source_candidate_ids": list(self.source_candidate_ids or []),
"publish_note": self.publish_note or "",
"published_by_id": self.published_by_id,
"published_by_name": self.published_by_name,
"published_by_role": self.published_by_role,
"published_at": to_iso8601_utc(self.published_at),
"presentation_status": self.presentation_status,
"presentation_attempts": int(self.presentation_attempts or 0),
"presentation_error": self.presentation_error or "",
"presentation_delivered_at": to_iso8601_utc(self.presentation_delivered_at),
}
+59
View File
@@ -0,0 +1,59 @@
"""Natural disaster and hazard telemetry model."""
from __future__ import annotations
from sqlalchemy import Column, DateTime, Float, Index, Integer, JSON, String, Text, UniqueConstraint
from sqlalchemy.sql import func
from app.core.time import to_iso8601_utc
from app.db.session import Base
class DisasterEvent(Base):
__tablename__ = "disaster_events"
id = Column(Integer, primary_key=True, autoincrement=True)
source = Column(String(64), nullable=False, index=True)
source_event_id = Column(String(160), nullable=False)
event_type = Column(String(32), nullable=False, index=True)
severity = Column(String(24), nullable=False, default="medium", index=True)
title = Column(String(500), nullable=False)
lat = Column(Float, nullable=False)
lon = Column(Float, nullable=False)
magnitude = Column(Float, nullable=True)
started_at = Column(DateTime(timezone=True), nullable=True)
ended_at = Column(DateTime(timezone=True), nullable=True)
url = Column(Text, nullable=True)
observed_at = Column(DateTime(timezone=True), nullable=False, index=True)
ingested_at = Column(DateTime(timezone=True), nullable=False, server_default=func.now())
duplicate_of = Column(Integer, nullable=True, index=True)
cluster_count = Column(Integer, nullable=False, default=1)
max_brightness_k = Column(Float, nullable=True)
raw = Column(JSON, nullable=True, default=dict)
__table_args__ = (
UniqueConstraint("source", "source_event_id", name="uq_disaster_source_event"),
Index("idx_disaster_type_observed", "event_type", "observed_at"),
Index("idx_disaster_geo", "lon", "lat"),
)
def to_dict(self) -> dict:
return {
"id": self.id,
"source": self.source,
"source_event_id": self.source_event_id,
"event_type": self.event_type,
"severity": self.severity,
"title": self.title,
"lat": self.lat,
"lon": self.lon,
"magnitude": self.magnitude,
"started_at": to_iso8601_utc(self.started_at),
"ended_at": to_iso8601_utc(self.ended_at),
"url": self.url,
"observed_at": to_iso8601_utc(self.observed_at),
"ingested_at": to_iso8601_utc(self.ingested_at),
"duplicate_of": self.duplicate_of,
"cluster_count": int(self.cluster_count or 1),
"max_brightness_k": self.max_brightness_k,
}
+4 -1
View File
@@ -1,4 +1,4 @@
from sqlalchemy import Boolean, Column, DateTime, Float, Index, JSON, String, Text
from sqlalchemy import Boolean, Column, DateTime, Float, Index, Integer, JSON, String, Text
from sqlalchemy.sql import func
from app.db.session import Base
@@ -33,6 +33,9 @@ class EarthNewsItem(Base):
enrichment_error = Column(Text, nullable=True)
enriched_at = Column(DateTime(timezone=True), nullable=True, index=True)
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
credibility_tier = Column(Integer, nullable=True, index=True)
state_affiliated = Column(Boolean, nullable=False, default=False)
theater_tags = Column(JSON, nullable=False, default=list)
__table_args__ = (
Index("idx_earth_news_region_published", "region", "published_at"),
+85
View File
@@ -0,0 +1,85 @@
"""Geofences and fused situational incident models (§3.8 & §3.9)."""
from __future__ import annotations
from sqlalchemy import Boolean, Column, DateTime, Index, Integer, JSON, String, Text
from sqlalchemy.sql import func
from app.core.time import to_iso8601_utc
from app.db.session import Base
class Geofence(Base):
"""Preset (chokepoint / cable corridor) or user-drawn geographic polygon geofence."""
__tablename__ = "geofences"
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(String(200), nullable=False, index=True)
kind = Column(String(32), nullable=False, default="custom", index=True)
geometry = Column(JSON, nullable=False, default=dict)
rules = Column(JSON, nullable=False, default=dict)
enabled = Column(Boolean, nullable=False, default=True, index=True)
created_by = Column(String(120), nullable=False, default="system")
created_at = Column(DateTime(timezone=True), nullable=False, server_default=func.now())
updated_at = Column(DateTime(timezone=True), nullable=False, server_default=func.now(), onupdate=func.now())
def to_dict(self) -> dict:
return {
"id": self.id,
"name": self.name,
"kind": self.kind,
"geometry": self.geometry or {},
"rules": self.rules or {},
"enabled": bool(self.enabled),
"created_by": self.created_by,
"created_at": to_iso8601_utc(self.created_at),
"updated_at": to_iso8601_utc(self.updated_at),
}
class SituationalIncident(Base):
"""Rule alerts, candidate correlations (待核查关联), and dependency-impact incidents."""
__tablename__ = "situational_incidents"
id = Column(Integer, primary_key=True, autoincrement=True)
incident_type = Column(String(80), nullable=False, index=True)
severity = Column(String(24), nullable=False, default="medium", index=True)
status = Column(String(32), nullable=False, default="open", index=True)
h3_index = Column(String(32), nullable=True, index=True)
window_start = Column(DateTime(timezone=True), nullable=True)
window_end = Column(DateTime(timezone=True), nullable=True)
object_ids = Column(JSON, nullable=False, default=list)
signal_summary = Column(JSON, nullable=False, default=dict)
evidence = Column(JSON, nullable=False, default=list)
assessment_kind = Column(String(48), nullable=False, default="rule_alert", index=True)
title = Column(String(320), nullable=False, default="")
created_at = Column(DateTime(timezone=True), nullable=False, server_default=func.now(), index=True)
updated_at = Column(DateTime(timezone=True), nullable=False, server_default=func.now(), onupdate=func.now())
updated_by = Column(String(120), nullable=True)
resolution_note = Column(Text, nullable=True)
__table_args__ = (
Index("idx_situational_incidents_kind_status", "assessment_kind", "status", "created_at"),
)
def to_dict(self) -> dict:
return {
"id": self.id,
"incident_type": self.incident_type,
"severity": self.severity,
"status": self.status,
"h3_index": self.h3_index,
"window_start": to_iso8601_utc(self.window_start),
"window_end": to_iso8601_utc(self.window_end),
"object_ids": list(self.object_ids or []),
"signal_summary": dict(self.signal_summary or {}),
"evidence": list(self.evidence or []),
"assessment_kind": self.assessment_kind,
"title": self.title,
"created_at": to_iso8601_utc(self.created_at),
"updated_at": to_iso8601_utc(self.updated_at),
"updated_by": self.updated_by,
"resolution_note": self.resolution_note,
}
+46
View File
@@ -0,0 +1,46 @@
"""GPS/GNSS interference cell model derived from H3 daily summaries."""
from __future__ import annotations
from sqlalchemy import Column, DateTime, Float, Index, Integer, JSON, String
from sqlalchemy.sql import func
from app.core.time import to_iso8601_utc
from app.db.session import Base
class GPSJammingCell(Base):
"""Daily H3 hexagon summary of GPS/GNSS interference."""
__tablename__ = "gps_jamming_cells"
h3_index = Column(String(32), primary_key=True)
observed_date = Column(String(10), primary_key=True)
lat = Column(Float, nullable=False)
lon = Column(Float, nullable=False)
resolution = Column(Integer, nullable=False, default=4)
level = Column(String(16), nullable=False, index=True)
bad_ratio = Column(Float, nullable=False, default=0.0)
aircraft_count = Column(Integer, nullable=False, default=0)
boundary = Column(JSON, nullable=False, default=list)
source = Column(String(64), nullable=False, default="gpsjam_interference")
ingested_at = Column(DateTime(timezone=True), nullable=False, server_default=func.now())
__table_args__ = (
Index("idx_gps_jamming_date_level", "observed_date", "level"),
)
def to_dict(self) -> dict:
return {
"h3_index": self.h3_index,
"observed_date": self.observed_date,
"lat": self.lat,
"lon": self.lon,
"resolution": int(self.resolution or 4),
"level": self.level,
"bad_ratio": float(self.bad_ratio or 0.0),
"aircraft_count": int(self.aircraft_count or 0),
"boundary": self.boundary or [],
"source": self.source,
"ingested_at": to_iso8601_utc(self.ingested_at),
}
+86
View File
@@ -0,0 +1,86 @@
"""Investigation Case Board, items, and immutable SHA-256 frozen versions (§4.3)."""
from __future__ import annotations
from sqlalchemy import Boolean, Column, DateTime, ForeignKey, Index, Integer, JSON, String, Text
from sqlalchemy.sql import func
from app.core.time import to_iso8601_utc
from app.db.session import Base
class InvestigationCase(Base):
__tablename__ = "investigation_cases"
id = Column(Integer, primary_key=True, autoincrement=True)
title = Column(String(240), nullable=False, index=True)
status = Column(String(32), nullable=False, default="draft", index=True)
owner_id = Column(Integer, nullable=False, index=True)
owner_name = Column(String(120), nullable=False, default="")
summary = Column(Text, nullable=False, default="")
is_shared = Column(Boolean, nullable=False, default=True, index=True)
created_at = Column(DateTime(timezone=True), nullable=False, server_default=func.now())
updated_at = Column(DateTime(timezone=True), nullable=False, server_default=func.now(), onupdate=func.now())
def to_dict(self) -> dict:
return {
"id": self.id,
"title": self.title,
"status": self.status,
"owner_id": self.owner_id,
"owner_name": self.owner_name,
"summary": self.summary,
"is_shared": bool(self.is_shared),
"created_at": to_iso8601_utc(self.created_at),
"updated_at": to_iso8601_utc(self.updated_at),
}
class CaseItem(Base):
__tablename__ = "case_items"
id = Column(Integer, primary_key=True, autoincrement=True)
case_id = Column(Integer, ForeignKey("investigation_cases.id", ondelete="CASCADE"), nullable=False, index=True)
item_type = Column(String(48), nullable=False, index=True)
ref_id = Column(String(200), nullable=False)
payload = Column(JSON, nullable=False, default=dict)
added_by = Column(String(120), nullable=False, default="analyst")
added_at = Column(DateTime(timezone=True), nullable=False, server_default=func.now())
def to_dict(self) -> dict:
return {
"id": self.id,
"case_id": self.case_id,
"item_type": self.item_type,
"ref_id": self.ref_id,
"payload": dict(self.payload or {}),
"added_by": self.added_by,
"added_at": to_iso8601_utc(self.added_at),
}
class CaseVersion(Base):
__tablename__ = "case_versions"
id = Column(Integer, primary_key=True, autoincrement=True)
case_id = Column(Integer, ForeignKey("investigation_cases.id", ondelete="CASCADE"), nullable=False, index=True)
version = Column(Integer, nullable=False)
snapshot = Column(JSON, nullable=False, default=dict)
content_sha256 = Column(String(64), nullable=False, index=True)
frozen_by = Column(String(120), nullable=False)
frozen_at = Column(DateTime(timezone=True), nullable=False, server_default=func.now())
__table_args__ = (
Index("idx_case_versions_case_ver", "case_id", "version", unique=True),
)
def to_dict(self) -> dict:
return {
"id": self.id,
"case_id": self.case_id,
"version": int(self.version),
"snapshot": dict(self.snapshot or {}),
"content_sha256": self.content_sha256,
"frozen_by": self.frozen_by,
"frozen_at": to_iso8601_utc(self.frozen_at),
}
+40
View File
@@ -0,0 +1,40 @@
"""NGA MSI maritime navigational warnings and submarine cable advisories model."""
from __future__ import annotations
from sqlalchemy import Column, DateTime, Float, Integer, JSON, String, Text
from sqlalchemy.sql import func
from app.core.time import to_iso8601_utc
from app.db.session import Base
class CableAdvisory(Base):
__tablename__ = "cable_advisories"
id = Column(Integer, primary_key=True, autoincrement=True)
source_warning_id = Column(String(120), unique=True, nullable=False, index=True)
text = Column(Text, nullable=False)
lat = Column(Float, nullable=True)
lon = Column(Float, nullable=True)
polygon = Column(JSON, nullable=True)
issued_at = Column(DateTime(timezone=True), nullable=True, index=True)
cancelled_at = Column(DateTime(timezone=True), nullable=True, index=True)
matched_cable_ids = Column(JSON, nullable=False, default=list)
match_method = Column(String(64), nullable=True)
ingested_at = Column(DateTime(timezone=True), nullable=False, server_default=func.now())
def to_dict(self) -> dict:
return {
"id": self.id,
"source_warning_id": self.source_warning_id,
"text": self.text,
"lat": self.lat,
"lon": self.lon,
"polygon": list(self.polygon or []) if isinstance(self.polygon, list) else None,
"issued_at": to_iso8601_utc(self.issued_at),
"cancelled_at": to_iso8601_utc(self.cancelled_at),
"matched_cable_ids": list(self.matched_cable_ids or []),
"match_method": self.match_method,
"ingested_at": to_iso8601_utc(self.ingested_at),
}
+70
View File
@@ -0,0 +1,70 @@
"""Ontology curation models storing only non-derivable aliases and analyst-asserted links."""
from __future__ import annotations
from sqlalchemy import Column, DateTime, Index, Integer, JSON, String, Text, UniqueConstraint
from sqlalchemy.sql import func
from app.core.time import to_iso8601_utc
from app.db.session import Base
class OntologyEntityAlias(Base):
"""Confirmed external alias mapping (vessel/ship/cable/airline names) to `{type}:{id}`."""
__tablename__ = "ontology_entity_aliases"
id = Column(Integer, primary_key=True, autoincrement=True)
alias = Column(String(200), nullable=False, index=True)
object_id = Column(String(160), nullable=False, index=True)
source = Column(String(80), nullable=False, default="analyst")
created_by = Column(String(120), nullable=False, default="system")
created_at = Column(DateTime(timezone=True), nullable=False, server_default=func.now())
__table_args__ = (
UniqueConstraint("alias", "object_id", name="uq_ontology_alias_object"),
)
def to_dict(self) -> dict:
return {
"id": self.id,
"alias": self.alias,
"object_id": self.object_id,
"source": self.source,
"created_by": self.created_by,
"created_at": to_iso8601_utc(self.created_at),
}
class AnalystLink(Base):
"""Non-derivable analyst-asserted relationship between two `{type}:{id}` objects."""
__tablename__ = "analyst_links"
id = Column(Integer, primary_key=True, autoincrement=True)
from_object_id = Column(String(160), nullable=False, index=True)
to_object_id = Column(String(160), nullable=False, index=True)
relation_type = Column(String(80), nullable=False, index=True)
note = Column(Text, nullable=False, default="")
evidence_ids = Column(JSON, nullable=False, default=list)
created_by = Column(String(120), nullable=False, default="analyst")
created_at = Column(DateTime(timezone=True), nullable=False, server_default=func.now())
status = Column(String(32), nullable=False, default="active", index=True)
__table_args__ = (
Index("idx_analyst_links_pair", "from_object_id", "to_object_id", "status"),
)
def to_dict(self) -> dict:
return {
"id": self.id,
"from_object_id": self.from_object_id,
"to_object_id": self.to_object_id,
"relation_type": self.relation_type,
"note": self.note,
"evidence_ids": list(self.evidence_ids or []),
"created_by": self.created_by,
"created_at": to_iso8601_utc(self.created_at),
"status": self.status,
"relation_source": "analyst_asserted",
}
@@ -235,8 +235,13 @@ class ComputeEvidenceCandidate(Base):
candidate_type = Column(String(40), nullable=False, default="observation")
proposed_payload = Column(JSON, nullable=False, default=dict)
source_payload = Column(JSON, nullable=False, default=dict)
comparison = Column(JSON, nullable=False, default=dict)
dedupe_fingerprint = Column(String(64), nullable=True, index=True)
confidence = Column(Float, nullable=False, default=0.8)
extractor_note = Column(Text, nullable=False, default="")
review_reason_code = Column(String(40), nullable=True)
review_reason = Column(Text, nullable=False, default="")
published_publish_id = Column(String(64), nullable=True, index=True)
reviewed_by = Column(String(120), nullable=True)
reviewed_at = Column(DateTime(timezone=True), nullable=True)
created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False, index=True)
@@ -248,8 +253,13 @@ class ComputeEvidenceCandidate(Base):
"candidate_type": self.candidate_type,
"proposed_payload": self.proposed_payload or {},
"source_payload": self.source_payload or {},
"comparison": self.comparison or {},
"dedupe_fingerprint": self.dedupe_fingerprint,
"confidence": self.confidence,
"extractor_note": self.extractor_note,
"review_reason_code": self.review_reason_code,
"review_reason": self.review_reason or "",
"published_publish_id": self.published_publish_id,
"reviewed_by": self.reviewed_by,
"reviewed_at": to_iso8601_utc(self.reviewed_at),
"created_at": to_iso8601_utc(self.created_at),
+2
View File
@@ -11,6 +11,7 @@ class ChatMessage(BaseModel):
tool_call_id: str | None = Field(default=None, max_length=200)
name: str | None = Field(default=None, max_length=200)
tool_calls: list[dict[str, Any]] | None = None
thinking_blocks: list[dict[str, Any]] | None = None
class ToolCallRecord(BaseModel):
@@ -77,6 +78,7 @@ class SituationalAnalysisResponse(BaseModel):
text_blocks: list[str] = Field(default_factory=list)
thinking_blocks: list[str] = Field(default_factory=list)
tool_calls: list[ToolCallRecord] = Field(default_factory=list)
citation_urls: list[str] = Field(default_factory=list)
stop_reason: str | None = None
raw_response: dict[str, Any] = Field(default_factory=dict)
@@ -56,6 +56,7 @@ class ComputeObservation(ConfigurationModel):
metric: ComputeMetric
source_id: Identifier
values: dict[str, Value] = Field(min_length=1, max_length=250)
value_sources: dict[str, Identifier] | None = None
period_label: PeriodLabel | None = None
global_total: Value | None = None
@@ -65,11 +66,36 @@ class ComputeObservation(ConfigurationModel):
raise ValueError(
"Use countries from the canonical compute catalog, not regional totals"
)
if self.value_sources is not None:
invalid_keys = [code for code in self.value_sources if code not in self.values]
if invalid_keys:
raise ValueError(
"Per-country value_sources keys must be a subset of observation values"
)
if self.metric in SHARE_METRICS and sum(self.values.values()) > 100.000001:
raise ValueError("Global shares for one year must total at most 100 percent")
return self
def source_for(row: ComputeObservation, code: str) -> str:
"""Resolve the authoritative source_id for one country inside an observation row."""
if row.value_sources and code in row.value_sources:
return row.value_sources[code]
return row.source_id
def row_source_ids(row: ComputeObservation) -> list[str]:
"""Return deduplicated source IDs referenced across all countries in an observation row."""
if not row.values:
return [row.source_id]
return list(dict.fromkeys(source_for(row, code) for code in row.values))
def has_mixed_sources(row: ComputeObservation) -> bool:
"""Return True when countries in one observation row cite more than one distinct source."""
return len(row_source_ids(row)) > 1
class ComputeStructureObservation(ConfigurationModel):
scope: str = Field(min_length=2, max_length=16)
year: Year
@@ -176,6 +202,14 @@ class ComputeConfiguration(ConfigurationModel):
raise ValueError(f"Missing report source: {row.source_id}")
if row.year > source.report_year:
raise ValueError("Observation year must not be after its report year")
for obs in self.observations:
if obs.value_sources:
for code, src_id in obs.value_sources.items():
source = sources.get(src_id)
if source is None:
raise ValueError(f"Missing report source: {src_id}")
if obs.year > source.report_year:
raise ValueError("Observation year must not be after its report year")
hub_id_set = set(hub_ids)
for hub in self.national_hubs:
if hub.source_id not in sources:
@@ -190,7 +224,10 @@ class ComputeConfiguration(ConfigurationModel):
class ComputeConfigurationWrite(ConfigurationModel):
revision: str = Field(min_length=1, max_length=80)
config: ComputeConfiguration
publish_note: str = Field(default="", max_length=1000)
source_candidate_ids: list[int] = Field(default_factory=list, max_length=50)
class ComputeConfigurationReset(ConfigurationModel):
revision: str = Field(min_length=1, max_length=80)
publish_note: str = Field(default="", max_length=1000)
+369
View File
@@ -0,0 +1,369 @@
"""Action registry, 3-role x risk approval matrix, SSRF-guarded webhook executor, and AuditLog (§4.5)."""
from __future__ import annotations
from datetime import UTC, datetime
import hashlib
import hmac
import json
from typing import Any
import httpx
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.enums import UserRole
from app.core.logging import get_logger
from app.models.action_request import ActionRequest
from app.models.investigation_case import InvestigationCase
from app.models.system_log import AuditLog
from app.models.system_setting import SystemSetting
from app.services.ai.tool_registry import SSRFBlockedError, validate_public_http_url
logger = get_logger(__name__, service="actions_service")
WEBHOOK_ALLOWLIST_CATEGORY = "actions"
WEBHOOK_ALLOWLIST_KEY = "webhook_allowlist"
WEBHOOK_SECRET_KEY = "webhook_signing_secret"
ACTION_TYPE_REGISTRY: dict[str, dict[str, Any]] = {
"add_to_watchlist": {
"action_type": "add_to_watchlist",
"label": "加入持续关注清单",
"label_en": "Add to Watchlist",
"risk_level": "low",
"description": "将目标对象纳入关注态势列表",
},
"create_case": {
"action_type": "create_case",
"label": "新建研判卷宗",
"label_en": "Create Investigation Case",
"risk_level": "low",
"description": "基于目标对象自动初始化研判卷宗",
},
"create_ticket_webhook": {
"action_type": "create_ticket_webhook",
"label": "推送工单系统 Webhook",
"label_en": "Dispatch Ticket Webhook",
"risk_level": "high",
"description": "向管理员白名单内的工单网关发送结构化处置请求",
},
"notify_webhook": {
"action_type": "notify_webhook",
"label": "推送协同群机器人通知",
"label_en": "Notify Team Bot Webhook",
"risk_level": "high",
"description": "支持通用 JSON、企业微信、钉钉或飞书机器人消息格式推送告警",
},
}
class ActionPermissionError(PermissionError):
"""Raised when actor lacks RBAC permission or violates dual-person high-risk rule."""
class ActionValidationError(ValueError):
"""Raised on missing decision reason, unknown action type, allowlist miss, or SSRF block."""
async def _write_audit(
db: AsyncSession,
*,
actor_id: int | None,
actor_name: str,
action: str,
target_id: str,
result: str,
details: dict[str, Any],
) -> None:
db.add(
AuditLog(
actor_id=actor_id,
actor_name=actor_name,
action=action,
target_type="action_request",
target_id=target_id,
result=result,
details=details,
)
)
async def get_webhook_allowlist(db: AsyncSession) -> list[str]:
row = (
await db.execute(
select(SystemSetting).where(SystemSetting.category == WEBHOOK_ALLOWLIST_CATEGORY)
)
).scalars().first()
if not row or not isinstance(row.payload, dict):
return []
raw = row.payload.get(WEBHOOK_ALLOWLIST_KEY)
if isinstance(raw, list):
return [str(u).strip() for u in raw if str(u).strip()]
return []
async def get_webhook_signing_secret(db: AsyncSession) -> str:
row = (
await db.execute(
select(SystemSetting).where(SystemSetting.category == WEBHOOK_ALLOWLIST_CATEGORY)
)
).scalars().first()
if not row or not isinstance(row.payload, dict):
return ""
return str(row.payload.get(WEBHOOK_SECRET_KEY) or "").strip()
def format_webhook_payload(
*,
channel: str,
title: str,
summary: str,
request_obj: ActionRequest,
) -> dict[str, Any]:
"""Build payload tailored for generic JSON, WeCom, DingTalk, or Feishu bot."""
fmt = str(channel or "generic").strip().lower()
if fmt == "wecom":
return {
"msgtype": "markdown",
"markdown": {"content": f"### {title}\n{summary}\n> Targets: {', '.join(request_obj.target_object_ids or [])}"},
}
if fmt == "dingtalk":
return {
"msgtype": "markdown",
"markdown": {"title": title, "text": f"### {title}\n\n{summary}"},
}
if fmt == "feishu":
return {
"msg_type": "text",
"content": {"text": f"[{title}] {summary}"},
}
return {
"event": "planet.action_request",
"request_id": request_obj.id,
"action_type": request_obj.action_type,
"target_object_ids": list(request_obj.target_object_ids or []),
"title": title,
"summary": summary,
"requested_by": request_obj.requested_by,
"approved_by": request_obj.approved_by,
}
def validate_allowlisted_webhook_url(url: str, allowlist: list[str]) -> str:
"""Ensure URL is in admin allowlist AND passes existing SSRF public HTTP check."""
clean = str(url or "").strip()
if not clean:
raise ActionValidationError("Webhook target URL is required")
try:
validated = validate_public_http_url(clean, resolve_dns=True)
except SSRFBlockedError as exc:
raise ActionValidationError(f"SSRF check blocked webhook target: {exc}") from exc
allowed = False
for prefix in allowlist:
p = str(prefix or "").strip()
if not p:
continue
if validated == p or validated.startswith(p.rstrip("/") + "/"):
allowed = True
break
if not allowed:
raise ActionValidationError("Webhook target URL is not in administrator allowlist")
return validated
async def _execute_action_request(
db: AsyncSession,
req: ActionRequest,
*,
actor_id: int | None,
actor_name: str,
http_post_fn=None,
) -> ActionRequest:
params = dict(req.params or {})
if req.action_type == "add_to_watchlist":
req.status = "executed"
req.execution_result = {
"watched_objects": list(req.target_object_ids or []),
"executed_at": datetime.now(UTC).isoformat(),
}
elif req.action_type == "create_case":
case = InvestigationCase(
title=str(params.get("title") or f"Action Case #{req.id}"),
summary=str(params.get("summary") or "Auto-created via approved action request"),
status="draft",
owner_id=int(actor_id or 0),
owner_name=actor_name,
is_shared=True,
)
db.add(case)
await db.flush()
req.status = "executed"
req.execution_result = {"case_id": case.id, "title": case.title}
elif req.action_type in {"create_ticket_webhook", "notify_webhook"}:
target_url = str(params.get("webhook_url") or "")
allowlist = await get_webhook_allowlist(db)
validated_url = validate_allowlisted_webhook_url(target_url, allowlist)
payload = format_webhook_payload(
channel=str(params.get("channel") or "generic"),
title=str(params.get("title") or f"Planet Action #{req.id}"),
summary=str(params.get("summary") or ""),
request_obj=req,
)
body_bytes = json.dumps(payload, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
headers = {"Content-Type": "application/json"}
secret = await get_webhook_signing_secret(db)
if secret:
sig = hmac.new(secret.encode("utf-8"), body_bytes, hashlib.sha256).hexdigest()
headers["X-Planet-Signature"] = f"sha256={sig}"
attempts = 0
last_err = ""
status_code = 0
while attempts < 2:
attempts += 1
try:
if http_post_fn is not None:
res = await http_post_fn(validated_url, body_bytes, headers)
status_code = int(res.get("status_code", 200))
else:
async with httpx.AsyncClient(timeout=8.0) as client:
resp = await client.post(validated_url, content=body_bytes, headers=headers)
status_code = resp.status_code
if 200 <= status_code < 300:
req.status = "executed"
req.execution_result = {
"webhook_url": validated_url,
"status_code": status_code,
"attempts": attempts,
"signed": bool(secret),
}
last_err = ""
break
last_err = f"HTTP {status_code}"
except Exception as exc:
last_err = str(exc)
if last_err:
req.status = "failed"
req.execution_result = {"webhook_url": validated_url, "error": last_err, "attempts": attempts}
await _write_audit(
db,
actor_id=actor_id,
actor_name=actor_name,
action=f"action.{req.action_type}.{req.status}",
target_id=str(req.id),
result=req.status,
details={"risk_level": req.risk_level, "execution_result": req.execution_result},
)
return req
async def submit_action_request(
db: AsyncSession,
*,
action_type: str,
target_object_ids: list[str],
params: dict[str, Any],
actor_id: int | None,
actor_name: str,
actor_role: str,
source_workflow_run_id: str | None = None,
ai_suggested: bool = False,
) -> ActionRequest:
"""Create action request; low-risk admin submissions execute immediately unless `ai_suggested`."""
role = str(actor_role or "").lower()
if role == UserRole.VIEWER.value or role not in {UserRole.ADMIN.value, UserRole.SUPER_ADMIN.value}:
raise ActionPermissionError("Viewer role cannot initiate action requests")
spec = ACTION_TYPE_REGISTRY.get(action_type)
if spec is None:
raise ActionValidationError(f"Unknown action_type: {action_type}")
risk = spec["risk_level"]
req = ActionRequest(
action_type=action_type,
target_object_ids=list(target_object_ids or []),
params=dict(params or {}),
risk_level=risk,
status="pending",
requested_by=actor_name,
requested_at=datetime.now(UTC),
source_workflow_run_id=source_workflow_run_id,
)
db.add(req)
await db.flush()
await _write_audit(
db,
actor_id=actor_id,
actor_name=actor_name,
action=f"action.{action_type}.requested",
target_id=str(req.id),
result="pending",
details={"risk_level": risk, "ai_suggested": ai_suggested},
)
if not ai_suggested and risk == "low":
req.approved_by = actor_name
req.approved_at = datetime.now(UTC)
req.decision_reason = "Low-risk action executed directly by administrator"
await _execute_action_request(db, req, actor_id=actor_id, actor_name=actor_name)
await db.commit()
return req
async def decide_action_request(
db: AsyncSession,
*,
req: ActionRequest,
decision: str,
decision_reason: str,
actor_id: int | None,
actor_name: str,
actor_role: str,
http_post_fn=None,
) -> ActionRequest:
"""Approve or reject a pending action request enforcing strict 3-role x risk matrix."""
role = str(actor_role or "").lower()
if role not in {UserRole.ADMIN.value, UserRole.SUPER_ADMIN.value}:
raise ActionPermissionError("Insufficient permissions to decide action requests")
reason = str(decision_reason or "").strip()
if not reason:
raise ActionValidationError("Approval or rejection requires a non-empty decision_reason")
if req.status != "pending":
raise ActionValidationError(f"Action request #{req.id} is already {req.status}")
if req.risk_level == "high":
if role != UserRole.SUPER_ADMIN.value:
raise ActionPermissionError("High-risk actions require super_admin approval")
if actor_name == req.requested_by:
raise ActionPermissionError("High-risk approver must differ from requester")
req.approved_by = actor_name
req.approved_at = datetime.now(UTC)
req.decision_reason = reason
if decision == "reject":
req.status = "rejected"
await _write_audit(
db,
actor_id=actor_id,
actor_name=actor_name,
action=f"action.{req.action_type}.rejected",
target_id=str(req.id),
result="rejected",
details={"reason": reason},
)
await db.commit()
return req
req.status = "approved"
await _execute_action_request(
db, req, actor_id=actor_id, actor_name=actor_name, http_post_fn=http_post_fn
)
await db.commit()
return req
+187 -27
View File
@@ -7,7 +7,7 @@ from datetime import UTC, datetime
import hashlib
import json
import re
from typing import Any, Literal
from typing import Any
from fastapi import HTTPException
from pydantic import BaseModel, ConfigDict, Field
@@ -38,6 +38,10 @@ from app.services.ai.thinking_sanitizer import (
)
from app.services.ai.tool_registry import TimeBasis, query_compute_posture_tool
from app.services.ai_client import AIProviderClient
from app.services.compute_lineage import (
build_revision_change_context,
is_revision_question,
)
logger = get_logger(__name__, service="ai_copilot")
@@ -82,6 +86,7 @@ def _deterministic_compute_copilot_reply(
*,
codes: list[str] | None = None,
mode: str = "global_share",
revision_context: dict[str, Any] | None = None,
) -> CopilotInvestigationReply:
evidence = series.get("evidence") or {}
rpi = series.get("bilateral_rpi") or {}
@@ -95,6 +100,7 @@ def _deterministic_compute_copilot_reply(
time_basis = series.get("time_basis") or "retrospective"
cutoff_at = series.get("cutoff_at")
withheld_sources = series.get("withheld_source_ids") or []
publish_id = series.get("publish_id") or series.get("version")
fallback_eid = next(iter(evidence.keys()), "unconfigured")
q_lower = question.lower()
@@ -102,6 +108,19 @@ def _deterministic_compute_copilot_reply(
if entity_id:
highlights.append(entity_id)
if series.get("snapshot_unavailable"):
notice = str(
series.get("notice")
or "当前所选历史发布时间早于版本库基线时间,历史快照不完整,无法恢复当时台账。"
)
return CopilotInvestigationReply(
answer_markdown=f"### 历史快照不完整\n\n- {notice}",
key_points=[],
highlight_entities=list(dict.fromkeys([*(codes or []), *highlights]))[:8],
suggested_followups=["回到当前已发布的最新版本"],
evidence_ids=["unconfigured"],
)
cutoff_note = (
f"\n\n> **历史回放截点**:当前按 `as_known_then`(截至 `{cutoff_at}`)过滤,已隔离 `{len(withheld_sources)}` 份截点后发布报告。"
if time_basis == "as_known_then" and cutoff_at
@@ -121,6 +140,83 @@ def _deterministic_compute_copilot_reply(
evidence_ids=["unconfigured"],
)
if is_revision_question(question) and isinstance(revision_context, dict):
diff_entries = [
entry
for entry in (revision_context.get("diff_summary") or [])
if isinstance(entry, dict) and entry.get("kind") == "observation_value"
]
rev_pid = str(revision_context.get("publish_id") or publish_id or "")
rev_eids: list[str] = []
for entry in diff_entries:
for k in ("new_source_id", "old_source_id"):
sid = entry.get(k)
if isinstance(sid, str) and sid in evidence and sid not in rev_eids:
rev_eids.append(sid)
for cr in revision_context.get("candidate_reasons") or []:
sid = cr.get("source_id") if isinstance(cr, dict) else None
if isinstance(sid, str) and sid in evidence and sid not in rev_eids:
rev_eids.append(sid)
if not rev_eids:
rev_eids = [fallback_eid]
if diff_entries:
has_hist = any(e.get("change_kind") == "historical_revision" for e in diff_entries)
bullet_lines = [f"- {e.get('summary') or ''}" for e in diff_entries[:8] if e.get("summary")]
reason_lines: list[str] = []
for cr in (revision_context.get("candidate_reasons") or [])[:4]:
if not isinstance(cr, dict):
continue
r_label = cr.get("review_reason_label") or cr.get("review_reason_code") or "人工复核采纳"
r_detail = cr.get("review_reason")
if r_detail:
reason_lines.append(f"- **复核理由({r_label})**:{r_detail}")
else:
reason_lines.append(f"- **复核理由类别**:{r_label}")
note_line = (
f"- **发布说明**:{revision_context['publish_note']}"
if revision_context.get("publish_note")
else ""
)
hist_banner = (
"\n\n> **性质说明**:本次变动属于对历史统计观测的修订,不代表当期算力规模跃升。"
if has_hist
else ""
)
changed_codes = [
str(e.get("code"))
for e in diff_entries
if isinstance(e.get("code"), str)
]
highlights.extend(changed_codes or (codes or ["CN", "US"]))
md_parts = [
f"### 算力台账修订说明(版本 `{rev_pid}`)",
"",
*bullet_lines,
*reason_lines,
*([note_line] if note_line else []),
]
return CopilotInvestigationReply(
answer_markdown=("\n".join(md_parts) + hist_banner + cutoff_note).strip(),
key_points=[
CopilotKeyPoint(
claim=str(e.get("summary") or f"版本 {rev_pid} 发生观测值修订"),
evidence_ids=[
e["new_source_id"]
if isinstance(e.get("new_source_id"), str) and e["new_source_id"] in evidence
else rev_eids[0]
],
)
for e in diff_entries[:4]
],
highlight_entities=list(dict.fromkeys(highlights))[:8],
suggested_followups=[
"切回修订前的系统发布版本对比旧值",
"查看该数值的完整血缘与报告原文出处",
],
evidence_ids=rev_eids,
)
if any(kw in q_lower for kw in ("枢纽", "东数西算", "绿电", "pue", "hub", "west")) and hubs:
hub_ids = [h["id"] for h in hubs]
highlights.extend(["CN", *hub_ids[:8]])
@@ -174,11 +270,34 @@ def _deterministic_compute_copilot_reply(
)
highlights.extend(codes or ["CN", "US"])
eids = [
chip_eids = [
eid
for eid in ("caict-2025", "caict-2024", "caict-2023", "epoch-chip-imports-2026", "innovation-2026")
if eid in evidence
] or [fallback_eid]
for eid in (
chip.get("cn_evidence_id"),
chip.get("us_evidence_id"),
chip.get("evidence_id"),
)
if isinstance(eid, str) and eid in evidence
]
eids = list(
dict.fromkeys(
[
*(chip_eids if mode == "chip_inflow_share" else []),
*(
eid
for eid in (
"caict-2025",
"caict-2024",
"caict-2023",
"epoch-chip-imports-2026",
"innovation-2026",
)
if eid in evidence
),
*chip_eids,
]
)
) or [fallback_eid]
if not tot:
# Multilateral or non-CN/US comparison (e.g. JP / EUROPE / DE)
@@ -204,11 +323,18 @@ def _deterministic_compute_copilot_reply(
evidence_ids=eids[:2],
)
mode_banner = (
f"当前聚焦口径:**智能算力全球份额**(中国 `{intel['cn_value']}%` vs 美国 `{intel['us_value']}%`,RPI `{intel['rpi_percent']}%`)。"
if mode == "intelligent_share" and intel
else f"当前聚焦口径:**{tot.get('year')} 年全球总算力份额**(中国 `{tot.get('cn_value')}%` vs 美国 `{tot.get('us_value')}%`,RPI `{tot.get('rpi_percent')}%`)。"
)
if mode == "chip_inflow_share" and chip:
mode_banner = (
f"当前聚焦口径:**{chip.get('year')} 年高端 AI 算力卡新增流向占比**(中国 `{chip['cn_value']}%` vs 美国 `{chip['us_value']}%`,RPI `{chip['rpi_percent']}%`)。"
)
elif mode == "intelligent_share" and intel:
mode_banner = (
f"当前聚焦口径:**智能算力全球份额**(中国 `{intel['cn_value']}%` vs 美国 `{intel['us_value']}%`,RPI `{intel['rpi_percent']}%`)。"
)
else:
mode_banner = (
f"当前聚焦口径:**{tot.get('year')} 年全球总算力份额**(中国 `{tot.get('cn_value')}%` vs 美国 `{tot.get('us_value')}%`,RPI `{tot.get('rpi_percent')}%`)。"
)
denom_line = (
f"- **分母膨胀数学分解**:我国绝对总算力由 `{attr['country_from']:.0f}` 跃升至 `{attr['country_to']:.0f}` EFlops(`+{attr['country_growth_pct']}%`),全球总算力由 `{attr['global_from']:.0f}` 增至 `{attr['global_to']:.0f}` EFlops(`+{attr['global_growth_pct']}%`),相对份额回落源于全球分母扩张更快。\n"
if attr and attr.get("global_to")
@@ -259,9 +385,12 @@ async def run_contextual_copilot(
question: str,
time_basis: TimeBasis = "retrospective",
cutoff_at: str | None = None,
publish_id: str | None = None,
as_of: str | None = None,
allow_drill: bool = False,
series_override: dict[str, Any] | None = None,
posture_override: dict[str, Any] | None = None,
revision_context: dict[str, Any] | None = None,
ai_client: AIProviderClient | None = None,
cancel_event: asyncio.Event | None = None,
) -> dict[str, Any]:
@@ -388,9 +517,26 @@ async def run_contextual_copilot(
}
series = series_override or await query_compute_posture_tool(
db, codes, mode=mode, time_basis=time_basis, cutoff_at=cutoff_at
db,
codes,
mode=mode,
time_basis=time_basis,
cutoff_at=cutoff_at,
as_of=as_of,
publish_id=publish_id,
)
_raise_if_cancelled(cancel_event)
effective_revision_context = revision_context
if (
effective_revision_context is None
and is_revision_question(question)
and not series.get("snapshot_unavailable")
):
effective_revision_context = await build_revision_change_context(
db,
publish_id=series.get("publish_id") or publish_id,
redact=True,
)
posture = posture_override or await generate_or_get_compute_posture(
db,
countries=codes,
@@ -421,6 +567,26 @@ async def run_contextual_copilot(
}
for eid, ev in evidence_map.items()
}
llm_context: dict[str, Any] = {
"domain": domain,
"selected_codes": codes,
"focus_year": focus_year,
"mode": mode,
"publish_id": series.get("publish_id") or series.get("version"),
"published_at": series.get("published_at"),
"as_of": series.get("as_of") or as_of,
"time_basis": time_basis,
"cutoff_at": cutoff_at,
"entity_id": entity_id,
"bilateral_rpi": series.get("bilateral_rpi"),
"denominator_attribution": series.get("denominator_attribution"),
"structures": series.get("structures"),
"innovation_summary": series.get("innovation_summary"),
"national_hubs": series.get("national_hubs"),
"evidence": compact_evidence,
}
if effective_revision_context:
llm_context["revision_context"] = effective_revision_context
llm_resp = await effective_ai_client.analyze(
SituationalAnalysisRequest(
title="地球空间上下文追问",
@@ -432,21 +598,7 @@ async def run_contextual_copilot(
'"highlight_entities": [str], "suggested_followups": [str], "evidence_ids": [str]}'
),
system_prompt=prompt_def.system_prompt,
context={
"domain": domain,
"selected_codes": codes,
"focus_year": focus_year,
"mode": mode,
"time_basis": time_basis,
"cutoff_at": cutoff_at,
"entity_id": entity_id,
"bilateral_rpi": series.get("bilateral_rpi"),
"denominator_attribution": series.get("denominator_attribution"),
"structures": series.get("structures"),
"innovation_summary": series.get("innovation_summary"),
"national_hubs": series.get("national_hubs"),
"evidence": compact_evidence,
},
context=llm_context,
constraints=[
"Return strict JSON matching CopilotInvestigationReply.",
"Every evidence_id must exist in context.evidence.",
@@ -480,7 +632,12 @@ async def run_contextual_copilot(
if reply_obj is None:
reply_obj = _deterministic_compute_copilot_reply(
question, series, entity_id, codes=codes, mode=mode
question,
series,
entity_id,
codes=codes,
mode=mode,
revision_context=effective_revision_context,
)
return {
@@ -488,6 +645,9 @@ async def run_contextual_copilot(
"subject_key": posture["subject_key"],
"revision": posture["revision"],
"config_version": series.get("version"),
"publish_id": series.get("publish_id") or series.get("version"),
"published_at": series.get("published_at"),
"as_of": series.get("as_of") or as_of,
"generation_mode": generation_mode,
"usage": llm_usage,
"reply": reply_obj.model_dump(mode="json"),
+143
View File
@@ -0,0 +1,143 @@
"""Shared URL-normalized evidence ledger for workflow DAG nodes and guardrails."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Sequence
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
_TRACKING_QUERY_PARAMS: frozenset[str] = frozenset({"fbclid", "gclid", "mc_cid", "mc_eid"})
_IGNORED_DOC_EXTENSIONS: tuple[str, ...] = (".csv", ".tsv", ".xlsx", ".xls", ".parquet", ".json")
def normalize_evidence_url(url: Any) -> str:
"""Canonicalize an HTTP(S) URL for deduplication and anti-hallucination matching."""
raw = str(url or "").strip()
if not raw:
return ""
try:
parts = urlsplit(raw)
except ValueError:
return raw.rstrip("/").lower()
scheme = (parts.scheme or "https").lower()
if scheme == "http":
scheme = "https"
netloc = parts.netloc.lower()
path = parts.path.rstrip("/")
kept_query = sorted(
(k, v)
for k, v in parse_qsl(parts.query, keep_blank_values=True)
if not k.lower().startswith("utm_") and k.lower() not in _TRACKING_QUERY_PARAMS
)
return urlunsplit((scheme, netloc, path, urlencode(kept_query), ""))
def is_tabular_dataset_url(url: Any) -> bool:
"""Return True for raw bulk-data files (e.g. Epoch csv exports) unsuitable for webpage fetch."""
raw = str(url or "").strip()
if not raw:
return False
try:
path = urlsplit(raw).path.lower()
except ValueError:
path = raw.lower()
return path.endswith(_IGNORED_DOC_EXTENSIONS)
@dataclass
class EvidenceLedger:
"""Assigns sequential ``E1..En`` IDs to tool-observed URLs and resolves citations safely."""
items: list[dict[str, Any]] = field(default_factory=list)
by_id: dict[str, dict[str, Any]] = field(default_factory=dict)
by_norm_url: dict[str, dict[str, Any]] = field(default_factory=dict)
evidence_calls: int = 0
def record_call(self) -> None:
self.evidence_calls += 1
def add(
self,
*,
url: str,
title: str = "",
snippet: str = "",
tool: str = "",
query: str = "",
) -> str | None:
cleaned_url = str(url or "").strip()
if not cleaned_url:
return None
norm = normalize_evidence_url(cleaned_url)
if not norm:
return None
existing = self.by_norm_url.get(norm)
cleaned_snippet = str(snippet or "").strip()
cleaned_title = str(title or "").strip()
if existing is not None:
if len(cleaned_snippet) > len(str(existing.get("snippet") or "")):
existing["snippet"] = cleaned_snippet[:1500]
if cleaned_title and not existing.get("title"):
existing["title"] = cleaned_title[:200]
return str(existing["id"])
eid = f"E{len(self.items) + 1}"
entry = {
"id": eid,
"url": cleaned_url,
"norm_url": norm,
"title": cleaned_title[:200],
"snippet": cleaned_snippet[:1500],
"tool": tool,
"query": query,
}
self.items.append(entry)
self.by_id[eid] = entry
self.by_norm_url[norm] = entry
return eid
def resolve_refs(self, refs: Sequence[Any]) -> tuple[list[str], list[str]]:
"""Map ``['E1', 'https://...']`` references back to verified IDs and original URLs."""
verified_ids: list[str] = []
verified_urls: list[str] = []
seen_urls: set[str] = set()
for raw in refs:
token = str(raw or "").strip()
if not token:
continue
entry = self.by_id.get(token.upper())
if entry is None:
entry = self.by_norm_url.get(normalize_evidence_url(token))
if entry is None:
continue
eid = str(entry["id"])
url = str(entry["url"])
norm = str(entry["norm_url"])
if eid not in verified_ids:
verified_ids.append(eid)
if norm not in seen_urls:
seen_urls.add(norm)
verified_urls.append(url)
return verified_ids, verified_urls
def to_prompt_items(self, limit: int = 14) -> list[dict[str, str]]:
return [
{
"id": str(item["id"]),
"title": str(item.get("title") or ""),
"url": str(item.get("url") or ""),
"tool": str(item.get("tool") or ""),
"excerpt": str(item.get("snippet") or "")[:900],
}
for item in self.items[:limit]
]
def to_evidence_dict(self) -> dict[str, dict[str, str]]:
return {
str(item["id"]): {
"url": str(item.get("url") or ""),
"title": str(item.get("title") or ""),
"source": str(item.get("tool") or "web"),
}
for item in self.items
}
+502 -57
View File
@@ -4,12 +4,14 @@ from __future__ import annotations
import asyncio
from collections import defaultdict, deque
from datetime import UTC, datetime
import json
import re
from typing import Any, AsyncIterator
from app.core.logging import get_logger
from app.schemas.ai import ChatMessage, ImageAttachment, SituationalAnalysisRequest
from app.services.ai.dag_evidence import EvidenceLedger
from app.services.ai.scene_directives import (
INFLUENCE_ZONE_GUIDANCE,
consume_text_holding_scene_tag,
@@ -20,18 +22,22 @@ from app.services.ai.thinking_sanitizer import strip_thinking_text
from app.services.ai.tool_registry import (
TimeBasis,
isolate_untrusted_external_text,
query_aircraft_posture_tool,
query_bgp_incidents_tool,
query_cable_posture_tool,
query_cloud_posture_tool,
query_compute_posture_tool,
query_disaster_posture_tool,
query_global_situational_tool,
query_gps_jamming_posture_tool,
query_ontology_neighborhood_tool,
query_recent_earth_news_tool,
query_satellite_posture_tool,
query_vessel_posture_tool,
query_wind_posture_tool,
safe_web_fetch,
)
from app.services.ai.workflow_registry import MAX_WORKFLOW_NODES, _extract_first_json_object
from app.services.compute_center_locations import build_compute_center_location_query
from app.services.location.agent_resolver import run_l1_structured_facility_resolvers
logger = get_logger(__name__, service="ai_dag_executor")
@@ -65,6 +71,8 @@ def render_workflow_template(
question: str = "",
targets: list[dict[str, Any]] | None = None,
node_outputs: dict[str, str] | None = None,
node_data: dict[str, dict[str, Any]] | None = None,
workflow_state: dict[str, Any] | None = None,
) -> str:
"""Interpolate `{{...}}` placeholders safely without Python `.format` or eval."""
raw = str(template or "")
@@ -72,8 +80,17 @@ def render_workflow_template(
return raw
first = targets[0] if targets else {}
outputs = node_outputs or {}
structured = node_data or {}
state = workflow_state or {}
targets_summary = summarize_targets(targets)
def _serialize_val(val: Any) -> str:
if val is None:
return ""
if isinstance(val, (dict, list)):
return json.dumps(val, ensure_ascii=False, default=str)[:4000]
return str(val)[:4000]
def _lookup(key: str) -> str:
if key == "question":
return question
@@ -96,9 +113,17 @@ def render_workflow_template(
if sub in {"kind", "layer"}:
return str(first.get(sub) or "")
return ""
if key.startswith("state."):
skey = key[len("state.") :]
return _serialize_val(state.get(skey))
if key.startswith("node."):
nid = key[len("node.") :]
return str(outputs.get(nid) or "")[:4000]
rest = key[len("node.") :]
if "." in rest:
nid, sub = rest.split(".", 1)
nd = structured.get(nid) or {}
if sub in nd:
return _serialize_val(nd.get(sub))
return str(outputs.get(rest) or "")[:4000]
if key.endswith(".output"):
nid = key[: -len(".output")]
return str(outputs.get(nid) or "")[:4000]
@@ -142,6 +167,7 @@ _BGP_ENTITY_TYPES = frozenset({"bgp"})
_CABLE_ENTITY_TYPES = frozenset({"cable", "landing_point"})
_SATELLITE_ENTITY_TYPES = frozenset({"satellite"})
_VESSEL_ENTITY_TYPES = frozenset({"vessel"})
_AIRCRAFT_ENTITY_TYPES = frozenset({"aircraft"})
_COMPUTE_FACILITY_TYPES = frozenset(
{"supercomputer", "gpu_cluster", "data_center", "cloud_center", "edge_node", "compute_center_unresolved"}
)
@@ -155,8 +181,58 @@ async def _execute_tool(
targets: list[dict[str, Any]],
earth_context: dict[str, Any],
allow_external_tools: bool,
node_params: dict[str, Any] | None = None,
node_data: dict[str, dict[str, Any]] | None = None,
workflow_state: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Execute one whitelisted read-only or controlled external tool cleanly."""
"""Execute one whitelisted read-only or controlled workflow tool cleanly."""
state = workflow_state if workflow_state is not None else {}
params = node_params or {}
if tool_id == "location_normalize_context":
from app.services.location.workflow_tools import tool_location_normalize_context
return await tool_location_normalize_context(
db,
question=question,
targets=targets,
earth_context=earth_context,
node_params=params,
workflow_state=state,
)
if tool_id == "location_knowledge_lookup" or tool_id in _L1_KNOWLEDGE_TOOL_IDS:
from app.services.location.workflow_tools import tool_location_knowledge_lookup
return await tool_location_knowledge_lookup(
db,
question=question,
targets=targets,
earth_context=earth_context,
node_params=params,
workflow_state=state,
)
if tool_id == "location_web_research":
from app.services.location.workflow_tools import tool_location_web_research
return await tool_location_web_research(
db,
node_params=params,
workflow_state=state,
allow_external_tools=allow_external_tools,
)
if tool_id in {"location_geocode_verify", "geocode_verify"}:
from app.services.location.workflow_tools import tool_location_geocode_verify
return await tool_location_geocode_verify(workflow_state=state)
if tool_id == "location_persist_outcome":
from app.services.location.workflow_tools import tool_location_persist_outcome
return await tool_location_persist_outcome(
db,
node_params=params,
workflow_state=state,
)
codes, mode = _extract_codes_and_mode(earth_context)
time_basis: TimeBasis = str(earth_context.get("time_basis") or "retrospective") # type: ignore[assignment]
if time_basis not in {"live", "as_known_then", "retrospective"}:
@@ -174,13 +250,26 @@ async def _execute_tool(
cutoff_at=cutoff_at,
)
if tool_id == "query_compute_posture":
return await query_compute_posture_tool(
res = await query_compute_posture_tool(
db,
countries=codes,
mode=mode,
time_basis=time_basis,
cutoff_at=cutoff_at,
as_of=earth_context.get("as_of"),
publish_id=earth_context.get("publish_id"),
)
from app.services.compute_lineage import build_revision_change_context, is_revision_question
if is_revision_question(question) and not res.get("snapshot_unavailable"):
rev_ctx = await build_revision_change_context(
db,
publish_id=res.get("publish_id") or earth_context.get("publish_id"),
redact=not allow_external_tools,
)
if rev_ctx:
res["revision_context"] = rev_ctx
return res
if tool_id == "query_bgp_incidents":
incidents = await query_bgp_incidents_tool(
db,
@@ -211,43 +300,78 @@ async def _execute_tool(
cutoff_at=cutoff_at,
entity_id=_target_id_for_types(targets, _VESSEL_ENTITY_TYPES),
)
if tool_id == "query_aircraft_posture":
return await query_aircraft_posture_tool(
db,
time_basis=time_basis,
cutoff_at=cutoff_at,
entity_id=_target_id_for_types(targets, _AIRCRAFT_ENTITY_TYPES),
)
if tool_id == "query_gps_jamming_posture":
return await query_gps_jamming_posture_tool(
db,
time_basis=time_basis,
cutoff_at=cutoff_at,
)
if tool_id == "query_disaster_posture":
return await query_disaster_posture_tool(
db,
time_basis=time_basis,
cutoff_at=cutoff_at,
)
if tool_id == "query_ontology_neighborhood":
first = targets[0] if targets else {}
oid = str(first.get("object_id") or "")
if not oid and first.get("entity_type") and first.get("entity_id"):
oid = f"{first['entity_type']}:{first['entity_id']}"
if not oid:
oid = "chokepoint:malacca_strait"
return await query_ontology_neighborhood_tool(
db,
object_id=oid,
depth=2,
time_basis=time_basis,
cutoff_at=cutoff_at,
)
if tool_id == "query_cloud_posture":
first = targets[0] if targets else {}
return await query_cloud_posture_tool(
db,
time_basis=time_basis,
cutoff_at=cutoff_at,
latitude=first.get("latitude"),
longitude=first.get("longitude"),
)
if tool_id == "query_wind_posture":
first = targets[0] if targets else {}
return await query_wind_posture_tool(
db,
time_basis=time_basis,
cutoff_at=cutoff_at,
latitude=first.get("latitude"),
longitude=first.get("longitude"),
)
if tool_id == "query_recent_earth_news":
news_ctx = earth_context.get("news_context") if isinstance(earth_context.get("news_context"), dict) else {}
region = str(news_ctx.get("region_key") or "").strip() or None
return await query_recent_earth_news_tool(db, region=region, limit=10)
if tool_id in _L1_KNOWLEDGE_TOOL_IDS:
facility = next(
(t for t in targets if _target_entity_type(t) in _COMPUTE_FACILITY_TYPES),
targets[0] if targets else {},
)
target_name = str(facility.get("label") or question or "Unknown Facility").strip()
query = build_compute_center_location_query(name=target_name)
candidates, resolver_log, _ = await run_l1_structured_facility_resolvers(query, db=db)
return {
"candidates": [
{
"display_name": c.display_name,
"country": c.country,
"latitude": c.latitude,
"longitude": c.longitude,
"precision": c.precision,
"confidence": c.confidence,
"source": c.source,
"source_note": c.source_note,
}
for c in candidates[:5]
],
"resolver_log": resolver_log,
}
if tool_id == "web_search":
if not allow_external_tools:
return {"skipped": "external_web_search_admin_only"}
from app.api.v1.settings import get_web_search_client
client = await get_web_search_client(db)
search_q = " ".join(
part for part in [summarize_targets(targets) if targets else "", question] if part
).strip()[:200]
custom_q = render_workflow_template(
str(params.get("query_template") or ""),
question=question,
targets=targets,
node_data=node_data,
workflow_state=state,
).strip()
search_q = (
custom_q
or " ".join(part for part in [summarize_targets(targets) if targets else "", question] if part).strip()
)[:200]
if not search_q:
return {"items": []}
hits = await client.search(search_q, max_results=5)
@@ -267,7 +391,14 @@ async def _execute_tool(
return {"skipped": "external_fetch_admin_only"}
news_ctx = earth_context.get("news_context") if isinstance(earth_context.get("news_context"), dict) else {}
target_props = targets[0].get("properties") if targets and isinstance(targets[0].get("properties"), dict) else {}
url = str(news_ctx.get("url") or target_props.get("url") or "").strip()
custom_u = render_workflow_template(
str(params.get("url_template") or ""),
question=question,
targets=targets,
node_data=node_data,
workflow_state=state,
).strip()
url = (custom_u or str(news_ctx.get("url") or target_props.get("url") or "")).strip()
if not url:
return {"skipped": "no_target_url"}
fetched = await safe_web_fetch(url)
@@ -281,11 +412,15 @@ def _has_meaningful_tool_data(tool_results: dict[str, Any]) -> bool:
continue
if val.get("skipped") or val.get("error"):
continue
for key in ("items", "candidates", "cables", "landing_points", "series", "satellites", "vessels"):
for key in ("items", "candidates", "cables", "landing_points", "series", "satellites", "vessels", "new_ids"):
seq = val.get(key)
if isinstance(seq, list) and len(seq) > 0:
return True
if val.get("excerpt") or val.get("summary"):
if val.get("excerpt") or val.get("summary") or val.get("found") is True or val.get("is_terminal") is True:
return True
if isinstance(val.get("evidence_count"), int) and val["evidence_count"] > 0:
return True
if isinstance(val.get("context"), dict) and val["context"]:
return True
return False
@@ -354,14 +489,45 @@ def _eval_edge_condition(
pred_state: dict[str, Any],
targets: list[dict[str, Any]],
trigger_source: str = "interactive",
pred_data: dict[str, Any] | None = None,
) -> bool:
cond = str(edge.get("condition") or "always").strip()
data = pred_data if isinstance(pred_data, dict) else (
pred_state.get("data") if isinstance(pred_state.get("data"), dict) else {}
)
if cond in TRIGGER_SOURCES:
# Background RSS ingest and user-clicked analysis share one graph; only the branch
# matching the actual trigger may run (avoids a second model call and leaked JSON).
return cond == trigger_source
if cond in {"always", "", "not_terminal", "high_confidence_hit", "fallback_to_agent"}:
if cond in {"always", ""}:
return True
if cond == "not_terminal":
return not bool(pred_state.get("is_terminal") or data.get("is_terminal"))
if cond == "on_terminal":
return bool(pred_state.get("is_terminal") or data.get("is_terminal"))
if cond == "high_confidence_hit":
return bool(pred_state.get("high_confidence_hit") or data.get("high_confidence_hit"))
if cond == "fallback_to_agent":
return not bool(pred_state.get("high_confidence_hit") or data.get("high_confidence_hit"))
if cond == "on_guardrail_passed":
return bool(pred_state.get("guardrail_passed", True))
if cond == "on_guardrail_failed":
return not bool(pred_state.get("guardrail_passed", True))
if cond == "on_field_equals":
raw_expr = str(edge.get("condition_value") or "").strip()
if "=" not in raw_expr:
return False
field_name, expected_raw = raw_expr.split("=", 1)
field_key = field_name.strip()
wanted = {item.strip().lower() for item in expected_raw.split(",") if item.strip()}
if not field_key or not wanted:
return False
actual = data.get(field_key)
if actual is None:
actual = pred_state.get(field_key)
if actual is None:
return False
return str(actual).strip().lower() in wanted
if cond == "on_empty_or_low_confidence":
return bool(pred_state.get("is_empty")) or float(pred_state.get("confidence", 1.0)) < 0.6
if cond == "on_entity_type":
@@ -500,12 +666,15 @@ def _compile_compute_workbench(
from app.services.ai.workflow_runtime import compile_compute_view_spec
codes, mode = _extract_codes_and_mode(earth_context)
raw_focus_year = earth_context.get("focus_year")
focus_year = int(raw_focus_year) if isinstance(raw_focus_year, int) else None
try:
view, scene = compile_compute_view_spec(
codes=codes,
mode=mode,
series=series,
posture={"payload": brief.model_dump(mode="json")},
focus_year=focus_year,
)
except Exception as exc:
logger.warning_event(
@@ -537,6 +706,55 @@ def _build_evidence_gap_markdown(tool_results: dict[str, Any], warnings: list[st
return "\n".join(lines)
def _render_output_schema_prompt(schema: dict[str, Any]) -> str:
"""Render an inline JSON Schema contract directly into the system prompt for cross-provider reliability."""
props = schema.get("properties") if isinstance(schema.get("properties"), dict) else {}
required = set(str(k) for k in (schema.get("required") or []) if k)
field_lines: list[str] = []
for name, spec in props.items():
if not isinstance(spec, dict):
continue
req_tag = "必填" if name in required else "可选"
enum_vals = spec.get("enum")
type_desc = (
f"枚举: {' | '.join(str(v) for v in enum_vals)}"
if isinstance(enum_vals, list) and enum_vals
else str(spec.get("type") or "string")
)
desc = str(spec.get("description") or "").strip()
line = f'- "{name}" ({req_tag}, {type_desc})'
if desc:
line += f": {desc}"
field_lines.append(line)
return (
"【严格输出要求】仅返回单个合法 JSON 对象(禁止输出 Markdown 围栏外文字或思考过程)。字段契约:\n"
+ "\n".join(field_lines)
)
async def _repair_json_once(
*,
ai_client: Any,
schema_hint: str,
prior_text: str,
timeout_sec: int,
) -> dict[str, Any] | None:
"""Single no-search JSON format repair pass when a structured llm_agent returns non-JSON."""
req = SituationalAnalysisRequest(
title="Repair structured workflow JSON",
objective="Convert prior output into one valid JSON object matching the required schema.",
system_prompt=f"{schema_hint}\n严禁新增原始回复中未出现的 URL、evidence_ids 或事实。",
context={"prior_output": prior_text[:2500]},
thinking={"mode": "off"},
)
try:
resp = await asyncio.wait_for(ai_client.analyze(req), timeout=min(timeout_sec, 45))
except Exception:
return None
clean_text, _ = strip_thinking_text(str(getattr(resp, "content", "") or ""))
return _extract_first_json_object(clean_text or str(getattr(resp, "content", "") or ""))
async def run_workflow_dag_stream(
*,
db: Any,
@@ -579,6 +797,7 @@ async def run_workflow_dag_stream(
clean_targets = [t for t in (targets or []) if isinstance(t, dict)][:8]
clean_earth_ctx = dict(earth_context or {})
location_runtime = clean_earth_ctx.pop("_location_runtime", None)
planned_ids = [str(n["id"]) for n in ordered_nodes]
yield {
@@ -604,19 +823,29 @@ async def run_workflow_dag_stream(
ai_ready, provider_name, default_model = await ai_client.is_ready()
except Exception:
ai_ready = False
elif ai_client is not None and (hasattr(ai_client, "analyze") or hasattr(ai_client, "stream_analyze")):
ai_ready = True
node_states: dict[str, dict[str, Any]] = {}
node_outputs: dict[str, str] = {}
node_data: dict[str, dict[str, Any]] = {}
tool_results: dict[str, Any] = {}
evidence: dict[str, Any] = {}
executed_trace: list[str] = []
node_traces: list[dict[str, Any]] = []
evidence_ledger = EvidenceLedger()
workflow_state: dict[str, Any] = {
"evidence_ledger": evidence_ledger,
"attempted_queries": [],
**(location_runtime if isinstance(location_runtime, dict) else {}),
}
effective_question = question.strip()
final_answer_md = ""
final_reasoning_md = ""
generation_mode = "deterministic_baseline"
zero_token = True
resolved_provider: str | None = None
resolved_model: str | None = None
resolved_provider: str | None = provider_name or None
resolved_model: str | None = default_model or None
scene_spec: dict[str, Any] | None = None
parsed_dag_scene: dict[str, Any] | None = None
view_spec: dict[str, Any] | None = None
@@ -632,26 +861,46 @@ async def run_workflow_dag_stream(
nid = str(node["id"])
ntype = str(node.get("node_type") or "llm_agent")
ntitle = str(node.get("title") or nid)
node_params = node.get("params") if isinstance(node.get("params"), dict) else {}
inc_edges = incoming_map.get(nid) or []
if inc_edges:
passed = False
for edge in inc_edges:
pred_id = str(edge.get("source") or "")
pred_state = node_states.get(pred_id)
if not pred_state or pred_state.get("skipped"):
continue
if _eval_edge_condition(edge, pred_state, clean_targets, trigger_source):
passed = True
break
join_mode = str(node_params.get("join_mode") or "any").strip().lower()
if join_mode == "all":
passed = True
for edge in inc_edges:
pred_id = str(edge.get("source") or "")
pred_state = node_states.get(pred_id)
if not pred_state or pred_state.get("skipped"):
passed = False
break
if not _eval_edge_condition(
edge, pred_state, clean_targets, trigger_source, pred_data=node_data.get(pred_id)
):
passed = False
break
else:
passed = False
for edge in inc_edges:
pred_id = str(edge.get("source") or "")
pred_state = node_states.get(pred_id)
if not pred_state or pred_state.get("skipped"):
continue
if _eval_edge_condition(
edge, pred_state, clean_targets, trigger_source, pred_data=node_data.get(pred_id)
):
passed = True
break
if not passed:
node_states[nid] = {"skipped": True, "confidence": 1.0, "is_empty": False}
node_traces.append({"node_id": nid, "node_type": ntype, "status": "skipped", "duration_ms": 0})
yield {
"event": "node",
"data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "skipped"},
}
continue
node_started = datetime.now(UTC)
yield {
"event": "node",
"data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "running"},
@@ -665,11 +914,15 @@ async def run_workflow_dag_stream(
question=effective_question,
targets=clean_targets,
node_outputs=node_outputs,
node_data=node_data,
workflow_state=workflow_state,
).strip()
summary = summarize_targets(clean_targets)
node_outputs[nid] = summary
node_states[nid] = {"skipped": False, "confidence": 1.0, "is_empty": False}
executed_trace.append(nid)
dur_ms = max(0, int((datetime.now(UTC) - node_started).total_seconds() * 1000))
node_traces.append({"node_id": nid, "node_type": ntype, "status": "completed", "duration_ms": dur_ms})
yield {
"event": "node",
"data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "completed"},
@@ -678,6 +931,7 @@ async def run_workflow_dag_stream(
if ntype == "deterministic":
local_results: dict[str, Any] = {}
merged_data: dict[str, Any] = {}
l1_ran = False
for tid in node.get("tools") or []:
if tid in _L1_KNOWLEDGE_TOOL_IDS:
@@ -695,11 +949,16 @@ async def run_workflow_dag_stream(
targets=clean_targets,
earth_context=clean_earth_ctx,
allow_external_tools=allow_external_tools,
node_params=node_params,
node_data=node_data,
workflow_state=workflow_state,
)
local_results[result_key] = res
tool_results[result_key] = res
if isinstance(res, dict) and isinstance(res.get("evidence"), dict):
evidence.update(res["evidence"])
if isinstance(res, dict):
merged_data.update(res)
if isinstance(res.get("evidence"), dict):
evidence.update(res["evidence"])
executed_trace.append(f"{nid}:{tid}")
except Exception as exc:
logger.warning_event(
@@ -708,15 +967,23 @@ async def run_workflow_dag_stream(
context={"workflow_id": wf_id, "node_id": nid, "tool_id": tid, "error": str(exc)},
)
local_results[result_key] = {"error": str(exc)}
if evidence_ledger.items:
evidence.update(evidence_ledger.to_evidence_dict())
has_data = _has_meaningful_tool_data(local_results)
node_data[nid] = merged_data
node_outputs[nid] = json.dumps(local_results, ensure_ascii=False, default=str)[:4000]
node_states[nid] = {
"skipped": False,
"confidence": 0.9 if has_data else 0.4,
"is_empty": not has_data,
"is_terminal": bool(merged_data.get("is_terminal")),
"high_confidence_hit": bool(merged_data.get("high_confidence_hit")),
"data": merged_data,
}
if nid not in executed_trace:
executed_trace.append(nid)
dur_ms = max(0, int((datetime.now(UTC) - node_started).total_seconds() * 1000))
node_traces.append({"node_id": nid, "node_type": ntype, "status": "completed", "duration_ms": dur_ms})
yield {
"event": "node",
"data": {
@@ -731,28 +998,37 @@ async def run_workflow_dag_stream(
if ntype in {"llm_agent", "tool_agent"}:
has_next_llm = _has_downstream_llm(nid, adj, node_types)
schema_spec = node_params.get("output_schema") if isinstance(node_params.get("output_schema"), dict) else None
sys_prompt = render_workflow_template(
str(node.get("system_prompt") or "").strip()
or "你是智能星球(Planet)AI 参谋。结合当前地球上下文、选中交互物件与工具证据,给出严谨客观的中文分析。",
question=effective_question or question,
targets=clean_targets,
node_outputs=node_outputs,
node_data=node_data,
workflow_state=workflow_state,
)
node_prompt = render_workflow_template(
str(node.get("prompt") or "").strip(),
question=effective_question or question,
targets=clean_targets,
node_outputs=node_outputs,
node_data=node_data,
workflow_state=workflow_state,
)
objective = (
f"{node_prompt}\n\n用户请求:{effective_question or question}"
if node_prompt
else (effective_question or question)
)
structured = _node_wants_structured_json(node)
structured = _node_wants_structured_json(node) or bool(schema_spec)
is_compute_brief = str(node.get("prompt_key") or "") == COMPUTE_BRIEF_PROMPT_KEY
if is_compute_brief:
objective = f"{objective}\n\n{_COMPUTE_BRIEF_SCHEMA_HINT}"
schema_hint = _render_output_schema_prompt(schema_spec) if schema_spec else ""
if schema_hint:
sys_prompt = f"{sys_prompt}\n\n{schema_hint}".strip()
wants_scene_zones = (
not has_next_llm
and not structured
@@ -779,6 +1055,9 @@ async def run_workflow_dag_stream(
targets=clean_targets,
earth_context=clean_earth_ctx,
allow_external_tools=allow_external_tools,
node_params=node_params,
node_data=node_data,
workflow_state=workflow_state,
)
node_tool_results[tid] = res
tool_results[tid] = res
@@ -786,6 +1065,8 @@ async def run_workflow_dag_stream(
evidence.update(res["evidence"])
except Exception as exc:
node_tool_results[tid] = {"error": str(exc)}
if evidence_ledger.items:
evidence.update(evidence_ledger.to_evidence_dict())
ctx_payload: dict[str, Any] = {
"targets": clean_targets,
@@ -794,6 +1075,10 @@ async def run_workflow_dag_stream(
"upstream_outputs": {k: v[:2000] for k, v in node_outputs.items()},
"evidence": evidence,
}
if workflow_state.get("location_ctx"):
ctx_payload["location_target"] = workflow_state["location_ctx"]
if evidence_ledger.items:
ctx_payload["evidence_items"] = evidence_ledger.to_prompt_items()
if clean_earth_ctx:
ctx_payload["earth_context"] = clean_earth_ctx
if wants_scene_zones:
@@ -820,6 +1105,7 @@ async def run_workflow_dag_stream(
or str(node.get("model_override") or "").strip()
or None
)
native_search = bool(node.get("native_web_search", False)) and allow_external_tools
req = SituationalAnalysisRequest(
title=f"Planet AI Advisor · {wf_name}",
objective=objective[:24000],
@@ -827,13 +1113,96 @@ async def run_workflow_dag_stream(
context=ctx_payload,
preferred_model=preferred_model,
thinking={"mode": "auto"} if bool(node.get("thinking_enabled", True)) else {"mode": "off"},
native_web_search=bool(node.get("native_web_search", False)) and allow_external_tools,
messages=[] if has_next_llm else chat_msgs,
native_web_search=native_search,
messages=[] if (has_next_llm or schema_spec) else chat_msgs,
images=parsed_images,
)
compute_series = _compute_series_from_tools(tool_results) if is_compute_brief else None
if schema_spec is not None:
cap_reason = str(workflow_state.get("capability_reason") or "").strip()
if not ai_ready or ai_client is None:
parsed_schema = {
"decision": "unresolved",
"reasoning": cap_reason or "当前未配置可用 AI Provider",
}
elif (
cap_reason
and evidence_ledger.evidence_calls == 0
and not native_search
):
parsed_schema = {"decision": "unresolved", "reasoning": cap_reason}
else:
timeout_sec = max(5, min(int(node.get("timeout_seconds") or 60), 300))
try:
resp = await asyncio.wait_for(ai_client.analyze(req), timeout=timeout_sec)
except Exception as exc:
parsed_schema = {
"decision": "unresolved",
"reasoning": f"模型研判请求失败:{exc}",
}
else:
raw_out = str(getattr(resp, "content", "") or "")
clean_text, inline_thoughts = strip_thinking_text(raw_out)
resolved_provider = getattr(resp, "provider", None) or resolved_provider or None
resolved_model = getattr(resp, "model", None) or preferred_model or resolved_model or None
if inline_thoughts:
final_reasoning_md = f"{final_reasoning_md}\n\n" + "\n\n".join(inline_thoughts)
final_reasoning_md = final_reasoning_md.strip()
for cite_u in getattr(resp, "citation_urls", None) or []:
u_str = str(cite_u or "").strip()
if u_str:
evidence_ledger.record_call()
evidence_ledger.add(url=u_str, title="Provider Web Citation", tool="native_web_search")
if evidence_ledger.items:
evidence.update(evidence_ledger.to_evidence_dict())
generation_mode = "llm_verified"
zero_token = False
parsed_schema = _extract_first_json_object(clean_text or raw_out)
if parsed_schema is None and (clean_text or raw_out).strip():
parsed_schema = await _repair_json_once(
ai_client=ai_client,
schema_hint=schema_hint,
prior_text=clean_text or raw_out,
timeout_sec=timeout_sec,
)
if parsed_schema is None:
parsed_schema = {
"decision": "unresolved",
"reasoning": "模型未返回可解析的结构化 JSON 结论",
}
if (
node_params.get("allow_followup") is False
and str(parsed_schema.get("decision") or "").strip().lower() == "need_followup"
):
parsed_schema["decision"] = "unresolved"
node_data[nid] = parsed_schema
workflow_state["latest_llm_data"] = parsed_schema
node_outputs[nid] = json.dumps(parsed_schema, ensure_ascii=False, default=str)[:4000]
node_states[nid] = {
"skipped": False,
"confidence": float(parsed_schema.get("confidence") or 0.7),
"is_empty": False,
"data": parsed_schema,
}
executed_trace.append(nid)
dur_ms = max(0, int((datetime.now(UTC) - node_started).total_seconds() * 1000))
node_traces.append(
{
"node_id": nid,
"node_type": ntype,
"status": "completed",
"duration_ms": dur_ms,
"decision": parsed_schema.get("decision"),
}
)
yield {
"event": "node",
"data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "completed"},
}
continue
if not ai_ready or ai_client is None:
if compute_series is not None and not has_next_llm:
compute_brief, compute_brief_llm_verified = _resolve_compute_brief(None, compute_series)
@@ -855,6 +1224,8 @@ async def run_workflow_dag_stream(
if not has_next_llm:
final_answer_md = fallback_md
yield {"event": "text", "data": {"delta": fallback_md}}
dur_ms = max(0, int((datetime.now(UTC) - node_started).total_seconds() * 1000))
node_traces.append({"node_id": nid, "node_type": ntype, "status": "completed", "duration_ms": dur_ms})
yield {
"event": "node",
"data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "completed"},
@@ -882,6 +1253,8 @@ async def run_workflow_dag_stream(
zero_token = False
if structured and not has_next_llm:
parsed = _extract_first_json_object(node_outputs[nid])
if isinstance(parsed, dict):
node_data[nid] = parsed
narrative = ""
if compute_series is not None:
compute_brief, compute_brief_llm_verified = _resolve_compute_brief(parsed, compute_series)
@@ -900,8 +1273,11 @@ async def run_workflow_dag_stream(
"skipped": False,
"confidence": 0.85 if node_outputs[nid] else 0.4,
"is_empty": not bool(node_outputs[nid].strip()),
**({"data": node_data[nid]} if nid in node_data else {}),
}
executed_trace.append(nid)
dur_ms = max(0, int((datetime.now(UTC) - node_started).total_seconds() * 1000))
node_traces.append({"node_id": nid, "node_type": ntype, "status": "completed", "duration_ms": dur_ms})
yield {
"event": "node",
"data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "completed"},
@@ -980,6 +1356,8 @@ async def run_workflow_dag_stream(
"is_empty": not bool(final_answer_md),
}
executed_trace.append(nid)
dur_ms = max(0, int((datetime.now(UTC) - node_started).total_seconds() * 1000))
node_traces.append({"node_id": nid, "node_type": ntype, "status": "completed", "duration_ms": dur_ms})
yield {
"event": "node",
"data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "completed"},
@@ -1003,6 +1381,25 @@ async def run_workflow_dag_stream(
if hits:
passed = False
warnings.append("命中禁用表述: " + ", ".join(hits[:5]))
if gr.get("geo_verification") or any(
k in gr
for k in (
"min_confidence",
"enforce_country_match",
"require_tool_cited_urls",
"downgrade_geocoded_site_to_city",
)
):
from app.services.location.workflow_tools import evaluate_location_geo_guardrail
geo_eval = evaluate_location_geo_guardrail(gr, workflow_state)
node_data[nid] = geo_eval
if not geo_eval.get("passed", False):
passed = False
for gw in geo_eval.get("warnings") or []:
if gw and gw not in warnings:
warnings.append(str(gw))
disclaimer = str(gr.get("append_disclaimer") or "").strip()
if disclaimer and final_answer_md and disclaimer not in final_answer_md:
extra_block = f"\n\n> {disclaimer}"
@@ -1020,9 +1417,22 @@ async def run_workflow_dag_stream(
"skipped": False,
"confidence": 0.95 if passed else 0.45,
"is_empty": False,
"guardrail_passed": passed,
"warnings": warnings,
**({"data": node_data[nid]} if nid in node_data else {}),
}
executed_trace.append(nid)
dur_ms = max(0, int((datetime.now(UTC) - node_started).total_seconds() * 1000))
node_traces.append(
{
"node_id": nid,
"node_type": ntype,
"status": "completed",
"duration_ms": dur_ms,
"guardrail_passed": passed,
**({"warnings": warnings[:3]} if warnings else {}),
}
)
yield {
"event": "node",
"data": {
@@ -1036,9 +1446,35 @@ async def run_workflow_dag_stream(
continue
if ntype == "output":
params = node.get("params") if isinstance(node.get("params"), dict) else {}
params = node_params
for tid in node.get("tools") or []:
try:
out_res = await _execute_tool(
db,
tid,
question=effective_question or question,
targets=clean_targets,
earth_context=clean_earth_ctx,
allow_external_tools=allow_external_tools,
node_params=params,
node_data=node_data,
workflow_state=workflow_state,
)
if isinstance(out_res, dict):
node_data[nid] = out_res
except Exception as exc:
logger.warning_event(
"Output DAG tool failed",
event="ai_dag.output_tool.failed",
context={"workflow_id": wf_id, "node_id": nid, "tool_id": tid, "error": str(exc)},
)
if isinstance(workflow_state.get("final_answer_markdown"), str) and workflow_state["final_answer_markdown"]:
final_answer_md = workflow_state["final_answer_markdown"]
yield {"event": "text", "data": {"delta": final_answer_md}}
if isinstance(workflow_state.get("final_scene_spec"), dict):
scene_spec = workflow_state["final_scene_spec"]
fly_enabled = bool(params.get("fly_to_target", True))
if fly_enabled and clean_targets:
if scene_spec is None and fly_enabled and clean_targets:
first = clean_targets[0]
lat = first.get("latitude")
lon = first.get("longitude")
@@ -1064,7 +1500,10 @@ async def run_workflow_dag_stream(
if scene_spec is None and compute_scene is not None:
scene_spec = compute_scene
node_states[nid] = {"skipped": False, "confidence": 1.0, "is_empty": False}
executed_trace.append(nid)
outcome_tag = str(workflow_state.get("outcome_tag") or "").strip()
executed_trace.append(f"{nid}:{outcome_tag}" if outcome_tag else nid)
dur_ms = max(0, int((datetime.now(UTC) - node_started).total_seconds() * 1000))
node_traces.append({"node_id": nid, "node_type": ntype, "status": "completed", "duration_ms": dur_ms})
yield {
"event": "node",
"data": {"node_id": nid, "title": ntitle, "node_type": ntype, "status": "completed"},
@@ -1092,7 +1531,11 @@ async def run_workflow_dag_stream(
"data": {"run_id": run_id, "domain": "compute", "view_spec": view_spec, "scene_spec": scene_spec},
}
if isinstance(scene_spec, dict) and (scene_spec.get("influence_zones") or parsed_dag_scene):
if isinstance(scene_spec, dict) and (
scene_spec.get("influence_zones")
or parsed_dag_scene
or isinstance(workflow_state.get("final_scene_spec"), dict)
):
yield {"event": "scene", "data": {"scene_spec": scene_spec}}
verification = {
@@ -1119,5 +1562,7 @@ async def run_workflow_dag_stream(
"answer_markdown": final_answer_md,
"reasoning_markdown": final_reasoning_md,
"text_length": len(final_answer_md),
**({"structured_output": workflow_state["structured_output"]} if "structured_output" in workflow_state else {}),
"node_traces": node_traces,
},
}
File diff suppressed because it is too large. Load diff
+81 -5
View File
@@ -116,7 +116,18 @@ def build_deterministic_posture_brief(series_payload: dict[str, Any]) -> Strateg
tot = rpi["latest_total"]
intel = rpi.get("latest_intelligent")
chip = rpi.get("latest_chip_inflow")
tot_ev = tot["evidence_id"]
def _pair_eids(pair: dict[str, Any] | None) -> list[str]:
if not pair:
return []
candidates = [
pair.get("cn_evidence_id"),
pair.get("us_evidence_id"),
pair.get("evidence_id"),
]
return list(dict.fromkeys(str(eid) for eid in candidates if eid and eid in evidence))
tot_eids = _pair_eids(tot)
tot_ev = tot_eids[0] if tot_eids else tot["evidence_id"]
near_parity = float(tot["rpi_percent"]) >= 85.0
if near_parity:
headline = (
@@ -174,7 +185,8 @@ def build_deterministic_posture_brief(series_payload: dict[str, Any]) -> Strateg
evidence_ids=[eid for eid in (attribution["evidence_ids"] if attribution else [tot_ev]) if eid in evidence] or [tot_ev],
)
]
if intel and intel.get("evidence_id") in evidence:
intel_eids = _pair_eids(intel)
if intel and intel_eids:
causes.append(
PostureBullet(
label="智能算力竞争成为核心分化面",
@@ -184,10 +196,11 @@ def build_deterministic_posture_brief(series_payload: dict[str, Any]) -> Strateg
f"高端训练集群供给差异直接拉开了总算力剪刀差。"
),
detail_en=f"U.S. holds {intel['us_value']}% of global intelligent compute vs China's {intel['cn_value']}%.",
evidence_ids=[intel["evidence_id"]],
evidence_ids=intel_eids,
)
)
if chip and chip.get("evidence_id") in evidence:
chip_eids = _pair_eids(chip)
if chip and chip_eids:
causes.append(
PostureBullet(
label="先进芯片管制重塑新增算力流向",
@@ -196,7 +209,7 @@ def build_deterministic_posture_brief(series_payload: dict[str, Any]) -> Strateg
f"公开样本显示高端 AI 加速卡新增算力约 {chip['us_value']}% 流向美国,我国公开可统计流入约 {chip['cn_value']}%。"
),
detail_en=f"~{chip['us_value']}% of tracked H100-equivalent compute inflows went to the U.S. vs ~{chip['cn_value']}% to China.",
evidence_ids=[chip["evidence_id"]],
evidence_ids=chip_eids,
)
)
@@ -348,12 +361,56 @@ async def generate_or_get_compute_posture(
_raise_if_cancelled(cancel_event)
effective_basis = str(time_basis or series_payload.get("time_basis") or "retrospective")
effective_cutoff = cutoff_at if cutoff_at is not None else series_payload.get("cutoff_at")
effective_publish_id = series_payload.get("publish_id") or series_payload.get("version")
effective_published_at = series_payload.get("published_at")
effective_as_of = series_payload.get("as_of")
snapshot_unavailable = bool(series_payload.get("snapshot_unavailable"))
basis_suffix = (
f":as_known_then:{effective_cutoff}"
if effective_basis == "as_known_then" and effective_cutoff
else ""
)
subject_key = f"compute:{','.join(countries)}:{mode}{basis_suffix}"
if snapshot_unavailable:
notice = str(
series_payload.get("notice")
or "历史快照不完整:所选系统发布时间早于版本库基线时间,无法还原当时的系统台账。"
)
brief_unavail = StrategicPostureBrief(
headline="历史快照不完整",
headline_en="Incomplete Historical Snapshot",
executive_assertion=notice,
executive_assertion_en=(
"Historical snapshot incomplete: requested system publish timestamp precedes the revision baseline."
),
causes=[],
breakthrough_levers=[],
blind_spots=[notice],
evidence_ids=["snapshot_unavailable"],
)
return {
"id": None,
"result_id": subject_key,
"subject_type": "compute_posture",
"subject_key": subject_key,
"input_fingerprint": "snapshot_unavailable",
"revision": 0,
"generation_mode": "deterministic_baseline",
"payload": brief_unavail.model_dump(mode="json"),
"evidence_ids": [],
"cache_hit": False,
"time_basis": effective_basis,
"cutoff_at": effective_cutoff if effective_basis == "as_known_then" else None,
"publish_id": None,
"published_at": None,
"as_of": effective_as_of,
"snapshot_unavailable": True,
"notice": notice,
"usage": {},
"evidence": {},
}
fingerprint = compute_posture_fingerprint(
countries,
mode,
@@ -410,6 +467,10 @@ async def generate_or_get_compute_posture(
"cache_hit": True,
"time_basis": effective_basis,
"cutoff_at": effective_cutoff if effective_basis == "as_known_then" else None,
"publish_id": (cached.audit_meta or {}).get("publish_id") or effective_publish_id,
"published_at": (cached.audit_meta or {}).get("published_at") or effective_published_at,
"as_of": effective_as_of,
"snapshot_unavailable": False,
"usage": (cached.audit_meta or {}).get("llm_usage") or {},
"evidence": {
eid: cached_evidence_map[eid]
@@ -424,6 +485,9 @@ async def generate_or_get_compute_posture(
frozen_series_snapshot = _freeze_json_snapshot(series_payload)
audit_meta: dict[str, Any] = {
"fingerprint": fingerprint,
"publish_id": effective_publish_id,
"published_at": effective_published_at,
"as_of": effective_as_of,
"time_basis": effective_basis,
"cutoff_at": effective_cutoff if effective_basis == "as_known_then" else None,
"countries": list(countries),
@@ -510,6 +574,10 @@ async def generate_or_get_compute_posture(
"cache_hit": True,
"time_basis": effective_basis,
"cutoff_at": effective_cutoff if effective_basis == "as_known_then" else None,
"publish_id": (fallback_cached.audit_meta or {}).get("publish_id") or effective_publish_id,
"published_at": (fallback_cached.audit_meta or {}).get("published_at") or effective_published_at,
"as_of": effective_as_of,
"snapshot_unavailable": False,
"usage": {},
"evidence": {
eid: fallback_evidence_map[eid]
@@ -557,6 +625,10 @@ async def generate_or_get_compute_posture(
"cache_hit": False,
"time_basis": effective_basis,
"cutoff_at": effective_cutoff if effective_basis == "as_known_then" else None,
"publish_id": effective_publish_id,
"published_at": effective_published_at,
"as_of": effective_as_of,
"snapshot_unavailable": False,
"usage": llm_usage,
"evidence": {eid: evidence_map[eid] for eid in valid_eids},
}
@@ -580,6 +652,10 @@ async def generate_or_get_compute_posture(
"cache_hit": False,
"time_basis": effective_basis,
"cutoff_at": effective_cutoff if effective_basis == "as_known_then" else None,
"publish_id": effective_publish_id,
"published_at": effective_published_at,
"as_of": effective_as_of,
"snapshot_unavailable": False,
"usage": llm_usage,
"evidence": {eid: evidence_map[eid] for eid in valid_eids},
}
@@ -15,7 +15,6 @@ from app.models.situational_assessment import StagePresentation
from app.services.ai.domain_catalog import SPATIAL_POSTURE_DOMAINS, SpatialDomain, WorkbenchDomain
from app.services.ai.incident_agent import (
DRILL_INCIDENT_KEY,
HISTORICAL_INCIDENT_SAMPLE,
investigate_infrastructure_incident,
)
from app.services.ai.spatial_domain_agent import investigate_spatial_domain
@@ -72,6 +71,10 @@ class StageStepSpec(BaseModel):
spotlight_Statistic_codes: list[str] = Field(default_factory=list)
highlight_milestone_id: str | None = None
enable_national_hubs: bool = False
workflow_params: dict[str, Any] = Field(default_factory=dict)
spotlight_card_keys: list[str] = Field(default_factory=list)
overlays: list[str] = Field(default_factory=list)
spatial_cards: list[dict[str, Any]] = Field(default_factory=list)
logical_arcs: list[StageArcSpec] = Field(default_factory=list)
measured_impact_regions: list[str] = Field(default_factory=list)
evidence_ids: list[str] = Field(default_factory=list)
@@ -84,6 +87,7 @@ class StagePresentationContract(BaseModel):
domain: WorkbenchDomain
time_basis: TimeBasis
cutoff_date: str | None = None
publish_id: str | None = None
is_drill: bool = False
title: str
title_en: str
@@ -515,13 +519,185 @@ def _wrap_ephemeral_contract(contract: StagePresentationContract, cursor: int, r
}
_COUNTRY_CAMERA_ANCHORS: dict[str, tuple[float, float, float]] = {
"CN": (35.0, 105.0, 1.18),
"US": (39.0, -98.0, 1.12),
"JP": (36.2, 138.2, 1.25),
"DE": (51.1, 10.4, 1.25),
"GB": (54.0, -2.0, 1.25),
"FR": (46.6, 2.2, 1.25),
"KR": (36.5, 127.8, 1.28),
"IN": (21.5, 79.0, 1.18),
}
_REVISION_METRIC_LABELS_EN: dict[str, str] = {
"global_share": "Global Compute Share",
"intelligent_share": "Global AI Compute Share",
"absolute": "Total Compute Capacity",
"frontier_cluster_share": "Frontier AI Cluster Share",
"chip_inflow_share": "AI Chip Inflow Share",
}
def compile_compute_revision_presentation(
*,
publish_id: str,
action: str,
series: dict[str, Any],
value_diffs: list[dict[str, Any]],
time_basis: TimeBasis = "retrospective",
) -> StagePresentationContract:
"""Compile a revision-driven stage presentation notice from structured observation diffs."""
from app.services.compute_revision_diff import COUNTRY_ZH_LABELS, METRIC_ZH_LABELS
raw_evidence = series.get("evidence") or {}
evidence = dict(raw_evidence)
historical_diffs = [d for d in value_diffs if d.get("change_kind") == "historical_revision"]
has_historical = bool(historical_diffs)
primary = historical_diffs[0] if has_historical else value_diffs[0]
metric = str(primary.get("metric") or "global_share")
year = int(primary.get("year") or 2024)
metric_zh = METRIC_ZH_LABELS.get(metric, metric)
metric_en = _REVISION_METRIC_LABELS_EN.get(metric, metric)
spotlight_codes = list(
dict.fromkeys(str(d.get("code")) for d in value_diffs if d.get("code"))
) or ["CN", "US"]
first_code = spotlight_codes[0]
cam_lat, cam_lon, cam_zoom = _COUNTRY_CAMERA_ANCHORS.get(first_code, (34.5, 110.0, 1.12))
change_lines_zh: list[str] = []
change_lines_en: list[str] = []
referenced_eids: list[str] = []
for item in value_diffs[:4]:
code = str(item.get("code") or "")
c_zh = COUNTRY_ZH_LABELS.get(code, code)
item_metric = str(item.get("metric") or metric)
item_unit = " EFlops" if item_metric == "absolute" else "%"
item_delta_unit = " EFlops" if item_metric == "absolute" else "pp"
old_val = item.get("old_value")
new_val = item.get("new_value")
delta = float(item.get("delta") or 0.0)
if old_val is not None and new_val is not None:
change_lines_zh.append(
f"{c_zh} {old_val}{item_unit} → {new_val}{item_unit}({delta:+.2g}{item_delta_unit})"
)
change_lines_en.append(
f"{code} {old_val}{item_unit} -> {new_val}{item_unit} ({delta:+.2g}{item_delta_unit})"
)
elif new_val is not None:
change_lines_zh.append(f"{c_zh} 新增 {new_val}{item_unit}")
change_lines_en.append(f"{code} added {new_val}{item_unit}")
elif old_val is not None:
change_lines_zh.append(f"{c_zh} 移除(原 {old_val}{item_unit})")
change_lines_en.append(f"{code} removed (was {old_val}{item_unit})")
for src_key in ("new_source_id", "old_source_id"):
eid = item.get(src_key)
if eid and eid in evidence and eid not in referenced_eids:
referenced_eids.append(str(eid))
if not referenced_eids:
referenced_eids = list(evidence.keys())[:2]
changes_zh = ";".join(change_lines_zh)
changes_en = "; ".join(change_lines_en)
if has_historical:
title_zh = f"{year} 年{metric_zh}数据获修订"
title_en = f"{year} {metric_en} Data Revised"
caption_zh = f"{changes_zh}。这是对历史数据的修订,不代表当期算力跃升。"
caption_en = f"{changes_en}. This is a historical data revision, not a current-period jump."
elif action == "reset":
title_zh = f"{year} 年{metric_zh}已恢复内置版本"
title_en = f"{year} {metric_en} Restored to Bundled Baseline"
caption_zh = f"{changes_zh}。台账已恢复至内置权威报告基线。"
caption_en = f"{changes_en}. Ledger restored to bundled authoritative report baseline."
else:
title_zh = f"{year} 年{metric_zh}台账已更新"
title_en = f"{year} {metric_en} Ledger Updated"
caption_zh = f"{changes_zh}。"
caption_en = f"{changes_en}."
steps = [
StageStepSpec(
step_id="rev-act-1-notice",
stage="overview",
title=title_zh,
title_en=title_en,
caption=caption_zh,
caption_en=caption_en,
dwell_ms=6400,
camera=StageCameraPose(lat=cam_lat, lon=cam_lon, zoom=cam_zoom),
compute_mode=metric,
focus_year=year,
spotlight_Statistic_codes=spotlight_codes,
evidence_ids=referenced_eids,
),
StageStepSpec(
step_id="rev-act-2-lineage",
stage="attribution",
title=f"版本 {publish_id[:8]} · 证据溯源与口径校验",
title_en=f"Revision {publish_id[:8]} · Evidence & Denominator Check",
caption=(
f"当前已生效版本 {publish_id[:8]},共更新 {len(value_diffs)} 项观测值(口径:{metric_zh},{year} 年)。"
"点击卡片数值旁溯源按钮可查看报告原文页码、复核记录与历史对比。"
),
caption_en=(
f"Active revision {publish_id[:8]} updated {len(value_diffs)} observation value(s) "
f"({metric_en}, {year}). Inspect lineage from the compute card for full provenance."
),
dwell_ms=5600,
camera=StageCameraPose(lat=cam_lat, lon=cam_lon, zoom=max(0.95, cam_zoom - 0.1)),
compute_mode=metric,
focus_year=year,
spotlight_Statistic_codes=spotlight_codes,
evidence_ids=referenced_eids,
),
]
return StagePresentationContract(
presentation_key="compute-revision-notice",
domain="compute",
time_basis=time_basis,
publish_id=publish_id,
is_drill=False,
title=title_zh,
title_en=title_en,
summary=caption_zh,
summary_en=caption_en,
steps=steps,
evidence=evidence,
)
async def publish_stage_contract(
db: AsyncSession,
contract: StagePresentationContract,
*,
explicit_revision: int | None = None,
) -> StagePresentation | None:
"""Idempotently persist a `StagePresentation` ONLY on explicit write-side snapshot/config pipelines."""
if not hasattr(db, "execute") or not hasattr(db, "add") or not hasattr(db, "flush"):
return None
if contract.publish_id:
existing_rows = (
(
await db.execute(
select(StagePresentation)
.where(
StagePresentation.presentation_key == contract.presentation_key,
StagePresentation.time_basis == contract.time_basis,
)
.order_by(desc(StagePresentation.revision), desc(StagePresentation.id))
.limit(50)
)
)
.scalars()
.all()
)
for row in existing_rows:
if isinstance(row.contract, dict) and row.contract.get("publish_id") == contract.publish_id:
return row
new_fp = _contract_fingerprint(contract)
existing = (
await db.execute(
@@ -535,7 +711,9 @@ async def publish_stage_contract(
)
).scalar_one_or_none()
if isinstance(existing, StagePresentation) and existing.contract:
if explicit_revision is not None:
next_rev = int(explicit_revision)
elif isinstance(existing, StagePresentation) and existing.contract:
old_fp = hashlib.sha256(
json.dumps(existing.contract, sort_keys=True, ensure_ascii=False).encode("utf-8")
).hexdigest()
+316 -71
View File
@@ -10,6 +10,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.core.logging import get_logger
from app.models.bgp_incident import BGPIncident
from app.models.compute_configuration_revision import ComputeConfigurationRevision
from app.models.situational_assessment import (
SituationalAssessment,
StagePresentation,
@@ -19,7 +20,7 @@ from app.models.situational_assessment import (
from app.services.ai.incident_agent import DRILL_INCIDENT_KEY, investigate_infrastructure_incident
from app.services.ai.posture_agent import generate_or_get_compute_posture
from app.services.ai.presentation_compiler import (
compile_compute_posture_presentation,
compile_compute_revision_presentation,
compile_incident_five_act_presentation,
publish_stage_contract,
)
@@ -29,7 +30,6 @@ from app.services.ai.tool_registry import query_compute_posture_tool
logger = get_logger(__name__, service="ai_proactive")
_BGP_STATE_KEY = "situational_bgp_snapshot_state"
_COMPUTE_STATE_KEY = "situational_compute_snapshot_state"
async def _load_state_setting(db: AsyncSession, key: str) -> tuple[SituationalAssessment | None, dict[str, Any] | None]:
@@ -280,80 +280,227 @@ async def process_bgp_snapshot_proactive_delta(
}
async def process_compute_revision_presentation(
db: AsyncSession,
revision_id: int,
*,
countries: list[str] | None = None,
) -> dict[str, Any]:
"""Emit an idempotent StagePresentation driven directly by one `ComputeConfigurationRevision`."""
row = (
await db.execute(
select(ComputeConfigurationRevision).where(
ComputeConfigurationRevision.id == revision_id
)
)
).scalar_one_or_none()
if not isinstance(row, ComputeConfigurationRevision):
return {
"domain": "compute",
"status": "not_found",
"revision_id": revision_id,
"emitted_presentations": [],
"triggered_watches": [],
}
if row.presentation_status in {"delivered", "skipped"}:
return {
"domain": "compute",
"status": row.presentation_status,
"publish_id": row.publish_id,
"revision_id": row.id,
"idempotent": True,
"emitted_presentations": [],
"triggered_watches": [],
}
value_diffs = [
item
for item in (row.diff_summary or [])
if item.get("kind") == "observation_value"
and item.get("delta") is not None
and float(item["delta"]) != 0.0
]
if not value_diffs:
row.presentation_status = "skipped"
row.presentation_error = ""
await db.flush()
return {
"domain": "compute",
"status": "skipped",
"publish_id": row.publish_id,
"revision_id": row.id,
"emitted_presentations": [],
"triggered_watches": [],
}
historical = [d for d in value_diffs if d.get("change_kind") == "historical_revision"]
primary = historical[0] if historical else value_diffs[0]
primary_mode = str(primary.get("metric") or "global_share")
changed_codes = [str(d["code"]) for d in value_diffs if d.get("code")]
codes = list(dict.fromkeys([*(countries or ["CN", "US"]), *changed_codes]))
series = await query_compute_posture_tool(
db, codes, mode=primary_mode, publish_id=row.publish_id
)
posture = await generate_or_get_compute_posture(
db,
countries=codes,
mode=primary_mode,
series_payload=series,
persist=True,
)
existing_stage_rows = (
(
await db.execute(
select(StagePresentation)
.where(
StagePresentation.presentation_key == "compute-revision-notice",
StagePresentation.time_basis == "retrospective",
)
.order_by(desc(StagePresentation.id))
.limit(50)
)
)
.scalars()
.all()
)
existing_for_publish = next(
(
st
for st in existing_stage_rows
if isinstance(st.contract, dict) and st.contract.get("publish_id") == row.publish_id
),
None,
)
if existing_for_publish is not None:
published = existing_for_publish
else:
contract = compile_compute_revision_presentation(
publish_id=row.publish_id,
action=row.action,
series=series,
value_diffs=value_diffs,
time_basis="retrospective",
)
published = await publish_stage_contract(db, contract, explicit_revision=int(row.id))
row.presentation_status = "delivered"
row.presentation_attempts = int(row.presentation_attempts or 0) + 1
row.presentation_error = ""
row.presentation_delivered_at = datetime.now(UTC)
await db.flush()
triggered_watches = await _evaluate_topic_watches(
db,
domain="compute",
target_keys=[posture["subject_key"]],
revision=int(row.id),
)
return {
"domain": "compute",
"status": "delivered",
"publish_id": row.publish_id,
"revision_id": row.id,
"emitted_presentations": [published.to_dict()] if published is not None else [],
"triggered_watches": triggered_watches,
}
async def retry_pending_compute_presentations(
db: AsyncSession,
*,
max_attempts: int = 3,
) -> dict[str, Any]:
"""Retry pending or failed compute revision presentations in ascending revision order."""
if not hasattr(db, "execute"):
return {"domain": "compute", "processed": 0, "delivered": 0, "skipped": 0, "failed": 0, "results": []}
rows = (
(
await db.execute(
select(ComputeConfigurationRevision)
.where(
ComputeConfigurationRevision.presentation_status.in_(["pending", "failed"]),
ComputeConfigurationRevision.presentation_attempts < max_attempts,
)
.order_by(ComputeConfigurationRevision.id.asc())
.limit(20)
)
)
.scalars()
.all()
)
delivered = 0
skipped = 0
failed = 0
results: list[dict[str, Any]] = []
for row in rows:
try:
res = await process_compute_revision_presentation(db, row.id)
results.append(res)
if res.get("status") == "delivered":
delivered += 1
elif res.get("status") == "skipped":
skipped += 1
except Exception as exc:
failed += 1
row.presentation_status = "failed"
row.presentation_attempts = int(row.presentation_attempts or 0) + 1
row.presentation_error = str(exc)[:1000]
await db.flush()
logger.warning_event(
"Compute revision presentation retry failed",
event="compute.revision.presentation_failed",
context={
"revision_id": row.id,
"publish_id": row.publish_id,
"attempts": row.presentation_attempts,
"error": str(exc),
},
)
results.append(
{
"domain": "compute",
"status": "failed",
"publish_id": row.publish_id,
"revision_id": row.id,
"error": str(exc),
}
)
return {
"domain": "compute",
"processed": len(rows),
"delivered": delivered,
"skipped": skipped,
"failed": failed,
"results": results,
}
async def process_compute_config_proactive_delta(
db: AsyncSession,
*,
countries: list[str] | None = None,
publish_id: str | None = None,
) -> dict[str, Any]:
"""Evaluate a newly published compute configuration and emit idempotent stage & watch updates."""
codes = countries or ["CN", "US"]
setting_row, prev_state = await _load_state_setting(db, _COMPUTE_STATE_KEY)
prev_snapshot = prev_state.get("snapshot") if prev_state else None
seen_fps: set[str] = set(prev_state.get("seen_fingerprints") or []) if prev_state else set()
series = await query_compute_posture_tool(db, codes, mode="global_share")
rpi = series.get("bilateral_rpi") or {}
tot = rpi.get("latest_total") or {}
intel = rpi.get("latest_intelligent") or {}
curr_snapshot: dict[str, Any] = {
"status": "success",
"completed_at": datetime.now(UTC).isoformat(),
"record_count": len(series.get("evidence") or {}) or 1,
"active_keys": [f"config:{series.get('version')}"],
"metrics": {
"cn_total_share": float(tot.get("cn_value") or 0.0),
"us_total_share": float(tot.get("us_value") or 0.0),
"cn_intel_share": float(intel.get("cn_value") or 0.0),
},
}
curr_snapshot["fingerprint"] = snapshot_fingerprint(curr_snapshot)
delta = classify_snapshot_delta(
prev_snapshot,
curr_snapshot,
seen_fingerprints=seen_fps,
)
emitted: list[dict[str, Any]] = []
triggered_watches: list[dict[str, Any]] = []
if delta["emit_event"]:
posture = await generate_or_get_compute_posture(
db,
countries=codes,
mode="global_share",
series_payload=series,
persist=True,
)
for tb in ("live", "retrospective"):
contract = compile_compute_posture_presentation(series, time_basis=tb)
published = await publish_stage_contract(db, contract)
if published is not None and tb == "retrospective":
emitted.append(published.to_dict())
triggered_watches = await _evaluate_topic_watches(
db,
domain="compute",
target_keys=[posture["subject_key"]],
revision=int(posture.get("revision") or 1),
)
await _save_state_setting(
db,
setting_row,
_COMPUTE_STATE_KEY,
{
"snapshot": curr_snapshot,
"seen_fingerprints": sorted(seen_fps)[-32:],
"last_verdict": delta["verdict"],
},
)
return {
"domain": "compute",
"delta": delta,
"emitted_presentations": emitted,
"triggered_watches": triggered_watches,
}
"""Compatibility wrapper delegating to `process_compute_revision_presentation` for the target/latest revision."""
stmt = select(ComputeConfigurationRevision)
if publish_id:
stmt = stmt.where(ComputeConfigurationRevision.publish_id == publish_id)
else:
stmt = stmt.order_by(desc(ComputeConfigurationRevision.id))
row = (await db.execute(stmt.limit(1))).scalar_one_or_none()
if not isinstance(row, ComputeConfigurationRevision):
return {
"domain": "compute",
"status": "skipped",
"emitted_presentations": [],
"triggered_watches": [],
}
return await process_compute_revision_presentation(db, row.id, countries=countries)
async def audit_situational_hygiene(db: AsyncSession) -> dict[str, Any]:
@@ -459,3 +606,101 @@ async def audit_situational_hygiene(db: AsyncSession) -> dict[str, Any]:
"R1 write-on-GET feedback loop severed; SituationalAssessment & StagePresentation writes are now strictly content-fingerprint idempotent."
),
}
async def process_fusion_incident(
db: AsyncSession,
incident: Any,
*,
execute_workflow: bool = True,
) -> dict[str, Any]:
"""Emit idempotent StagePresentation & workflow linkage for candidate_correlation / dependency_impact."""
from app.services.ai.presentation_compiler import (
StageCameraPose,
StagePresentationContract,
StageStepSpec,
)
inc_id = getattr(incident, "id", None) or "adhoc"
kind = str(getattr(incident, "assessment_kind", None) or "candidate_correlation")
inc_type = str(getattr(incident, "incident_type", None) or "")
title = str(getattr(incident, "title", None) or f"Fusion Incident #{inc_id}")
summary = dict(getattr(incident, "signal_summary", None) or {})
obj_ids = list(getattr(incident, "object_ids", None) or [])
is_cable_scenario = (
kind == "dependency_impact"
or "cable" in inc_type
or any(str(oid).startswith("cable:") for oid in obj_ids)
)
workflow_id = "wargame.cable_protection" if is_cable_scenario else "wargame.air_sea_em"
domain = "cable" if is_cable_scenario else "global"
lat = float(summary.get("lat")) if isinstance(summary.get("lat"), (int, float)) else 1.3
lon = float(summary.get("lon")) if isinstance(summary.get("lon"), (int, float)) else 103.8
overlays = ["chokepoints", "geofences"]
if kind == "dependency_impact":
overlays.append("dependency_arcs")
spatial_cards = [
{
"key": f"fusion-{inc_id}",
"title": title[:80],
"title_en": f"{workflow_id} · #{inc_id}",
"summary": summary.get("co_occurrence_note") or title,
"anchor": {"latitude": lat, "longitude": lon},
"side": "right",
"blocks": [
{
"block_id": f"samples-{inc_id}",
"block_type": "entity_samples",
"data": {
"title": "关联目标样本",
"items": [{"object_id": oid, "label": oid} for oid in obj_ids[:6]],
},
}
],
}
]
pres_key = f"fusion-incident:{inc_id}:{kind}"
contract = StagePresentationContract(
presentation_key=pres_key,
domain=domain,
time_basis="retrospective",
title=title[:180],
title_en=f"Situational Fusion · #{inc_id}",
summary=str(summary.get("co_occurrence_note") or title)[:400],
summary_en=f"Workflow {workflow_id} presentation for {kind}",
steps=[
StageStepSpec(
step_id=f"fusion-{inc_id}-step-1",
stage="discover" if kind == "candidate_correlation" else "impact",
title="第一幕 · 多域信号叠加" if kind == "candidate_correlation" else "第一幕 · 独立证据与依赖影响",
title_en="Act 1 · Multi-Domain Signals" if kind == "candidate_correlation" else "Act 1 · Grounded Dependency Impact",
caption=title[:480],
caption_en=title[:500],
dwell_ms=5200,
camera=StageCameraPose(lat=lat, lon=lon, zoom=1.35),
workflow_params={"workflow_id": workflow_id, "incident_id": inc_id, "assessment_kind": kind},
spotlight_card_keys=[f"fusion-{inc_id}"],
overlays=overlays,
spatial_cards=spatial_cards,
)
],
)
published_dict: dict[str, Any] | None = None
if execute_workflow:
published = await publish_stage_contract(db, contract)
if published is not None:
published_dict = published.to_dict()
return {
"incident_id": inc_id,
"assessment_kind": kind,
"workflow_id": workflow_id,
"presentation_key": pres_key,
"published_presentation": published_dict,
}
+57 -1
View File
@@ -74,6 +74,56 @@ def _parse_scene_json_candidate(raw_json: str) -> dict[str, Any] | None:
return None
def sanitize_spatial_cards(raw: Any) -> list[dict[str, Any]]:
if not isinstance(raw, list):
return []
cleaned: list[dict[str, Any]] = []
for item in raw[:8]:
if not isinstance(item, dict):
continue
key = str(item.get("key") or "").strip()
anchor = item.get("anchor")
if not key or not isinstance(anchor, dict):
continue
lat = anchor.get("latitude")
lon = anchor.get("longitude")
if not isinstance(lat, (int, float)) or not isinstance(lon, (int, float)):
continue
blocks = item.get("blocks") if isinstance(item.get("blocks"), list) else []
side = str(item.get("side") or "").strip().lower()
cleaned.append(
{
"key": key,
"title": str(item.get("title") or key),
"title_en": str(item.get("title_en") or item.get("title") or key),
"summary": str(item.get("summary") or "") or None,
"anchor": {
"latitude": float(lat),
"longitude": float(lon),
"label": str(anchor.get("label") or "") or None,
},
"side": side if side in {"left", "right"} else None,
"partner_key": str(item.get("partner_key") or "") or None,
"blocks": [b for b in blocks if isinstance(b, dict)],
}
)
return cleaned
_ALLOWED_SCENE_OVERLAYS = frozenset({"national_hubs", "chokepoints", "geofences", "dependency_arcs"})
def sanitize_scene_overlays(raw: Any) -> list[str]:
if not isinstance(raw, list):
return []
out: list[str] = []
for item in raw:
key = str(item or "").strip().lower()
if key in _ALLOWED_SCENE_OVERLAYS and key not in out:
out.append(key)
return out
def extract_planet_scene_from_text(text: str) -> tuple[str, dict[str, Any] | None]:
"""Strip `<planet_scene>...</planet_scene>` blocks and return validated scene spec fields."""
if not text:
@@ -86,12 +136,18 @@ def extract_planet_scene_from_text(text: str) -> tuple[str, dict[str, Any] | Non
continue
zones = [z.model_dump(mode="json") for z in validate_influence_zones(payload.get("influence_zones"))]
camera_hint = sanitize_camera_hint(payload.get("camera_hint"))
if zones or camera_hint:
spatial_cards = sanitize_spatial_cards(payload.get("spatial_cards"))
overlays = sanitize_scene_overlays(payload.get("overlays"))
if zones or camera_hint or spatial_cards or overlays:
parsed_scene = {}
if zones:
parsed_scene["influence_zones"] = zones
if camera_hint:
parsed_scene["camera_hint"] = camera_hint
if spatial_cards:
parsed_scene["spatial_cards"] = spatial_cards
if overlays:
parsed_scene["overlays"] = overlays
if matches and parsed_scene is not None:
extracted_zones = parsed_scene.get("influence_zones") or []
+56 -8
View File
@@ -174,7 +174,31 @@ def classify_snapshot_delta(
_SHARE_PATTERN = re.compile(
r"(?P<country>美国|中国|日本)\s*(?:全球)?(?P<metric>智能算力|总算力|算力)份额[^\d]{0,10}(?P<value>\d{1,2}(?:\.\d+)?)\s*%"
)
_COUNTRY_MAP = {"美国": "US", "中国": "CN", "日本": "JP"}
_CHIP_INFLOW_ZH_PATTERN = re.compile(
r"(?P<country>美国|中国|日本)\s*(?:高端)?(?:AI)?(?:算力)?芯片(?:新增)?流向(?:算力)?份额[^\d]{0,12}(?P<value>\d{1,2}(?:\.\d+)?)\s*%"
)
_CHIP_INFLOW_CONTEXT_RE = re.compile(
r"\b(?:h100e?|h20|ai\s+chip|chip\s+import|chip\s+inflow|world\s+arrivals|cumulative\s+world\s+arrivals)\b",
re.IGNORECASE,
)
_CHIP_INFLOW_EN_TO_PATTERN = re.compile(
r"\b(?P<country>United States|U\.S\.|US|China|Japan)(?:['’]s|['’])?\s+share\b[^,;]{0,90}?\bto\s+(?P<value>\d{1,2}(?:\.\d+)?)\s*%",
re.IGNORECASE,
)
_CHIP_INFLOW_EN_RECEIVED_PATTERN = re.compile(
r"\b(?P<country>United States|U\.S\.|US|China|Japan)\s+(?:received|accounted for|captured)\s+(?:about\s+|approximately\s+|roughly\s+)?(?P<value>\d{1,2}(?:\.\d+)?)\s*%\s+of\s+(?:that\s+|global\s+|world\s+)?(?:compute|arrivals|inflow)",
re.IGNORECASE,
)
_COUNTRY_MAP = {
"美国": "US",
"中国": "CN",
"日本": "JP",
"united states": "US",
"u.s.": "US",
"us": "US",
"china": "CN",
"japan": "JP",
}
def extract_compute_candidates_deterministic(
@@ -182,10 +206,12 @@ def extract_compute_candidates_deterministic(
*,
year: int,
source_meta: dict[str, Any],
period_label: str | None = None,
) -> list[dict[str, Any]]:
"""Deterministic extractor fallback producing reviewable `ComputeEvidenceCandidate` dicts."""
text = excerpt or ""
by_metric: dict[str, dict[str, float]] = {}
for match in _SHARE_PATTERN.finditer(excerpt or ""):
for match in _SHARE_PATTERN.finditer(text):
code = _COUNTRY_MAP.get(match.group("country"))
if not code:
continue
@@ -194,19 +220,41 @@ def extract_compute_candidates_deterministic(
if 0 <= value <= 100:
by_metric.setdefault(metric_key, {})[code] = value
for match in _CHIP_INFLOW_ZH_PATTERN.finditer(text):
code = _COUNTRY_MAP.get(match.group("country"))
if not code:
continue
value = float(match.group("value"))
if 0 <= value <= 100:
by_metric.setdefault("chip_inflow_share", {})[code] = value
if _CHIP_INFLOW_CONTEXT_RE.search(text):
for pattern in (_CHIP_INFLOW_EN_TO_PATTERN, _CHIP_INFLOW_EN_RECEIVED_PATTERN):
for match in pattern.finditer(text):
code = _COUNTRY_MAP.get(match.group("country").lower())
if not code:
continue
value = float(match.group("value"))
if 0 <= value <= 100 and code not in by_metric.get("chip_inflow_share", {}):
by_metric.setdefault("chip_inflow_share", {})[code] = value
clean_period = (period_label or "").strip() or None
candidates: list[dict[str, Any]] = []
for metric_key, values in by_metric.items():
if sum(values.values()) > 100.0:
continue
proposed: dict[str, Any] = {
"year": year,
"metric": metric_key,
"source_id": source_meta.get("id") or f"candidate-src-{year}",
"values": values,
}
if clean_period is not None:
proposed["period_label"] = clean_period
candidates.append(
{
"candidate_type": "observation",
"proposed_payload": {
"year": year,
"metric": metric_key,
"source_id": source_meta.get("id") or f"candidate-src-{year}",
"values": values,
},
"proposed_payload": proposed,
"source_payload": source_meta,
"confidence": 0.86,
"extractor_note": f"从报告摘录自动提取 {year} 年 {metric_key} 候选值,待管理员人工核验后入库。",
+26
View File
@@ -47,6 +47,10 @@ from app.services.ai.workflow_runtime import (
unregister_active_run_handle,
)
from app.services.ai_client import AIProviderClient
from app.services.compute_lineage import (
build_revision_change_context,
is_revision_question,
)
logger = get_logger(__name__, service="ai_stream")
@@ -237,13 +241,19 @@ def _build_telemetry_stream_request(
conversation_summary: str = "",
memory_notes: list[str] | None = None,
pinned_summaries: list[str] | None = None,
revision_context: dict[str, Any] | None = None,
) -> SituationalAnalysisRequest:
context: dict[str, Any] = {
"domain": domain,
"verified_baseline_summary": base_answer_md,
"evidence": evidence,
"view_headline": (view_spec or {}).get("headline"),
"publish_id": (view_spec or {}).get("publish_id"),
"mode": (view_spec or {}).get("mode"),
"focus_year": (view_spec or {}).get("focus_year"),
}
if revision_context:
context["revision_context"] = revision_context
if recent_news and recent_news.get("items"):
context["recent_news_headlines"] = (recent_news.get("items") or [])[:10]
if conversation_summary:
@@ -308,6 +318,10 @@ async def stream_session_turn(
for k, v in context_override.items():
if v is not None:
merged_ctx[k] = v
if context_override.get("publish_id") and not context_override.get("as_of"):
merged_ctx["as_of"] = None
elif context_override.get("as_of") and not context_override.get("publish_id"):
merged_ctx["publish_id"] = None
raw_history = history if history else merged_ctx.get("recent_messages")
existing_summary = str(
@@ -338,6 +352,8 @@ async def stream_session_turn(
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")
publish_id: str | None = merged_ctx.get("publish_id")
as_of: str | None = merged_ctx.get("as_of")
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 {})
@@ -401,6 +417,8 @@ async def stream_session_turn(
"visible_layers": visible_layers,
"time_basis": time_basis,
"cutoff_at": cutoff_at,
"publish_id": publish_id,
"as_of": as_of,
}
if news_context:
wf_earth_ctx["news_context"] = news_context
@@ -679,6 +697,13 @@ async def stream_session_turn(
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)
revision_context: dict[str, Any] | None = None
if domain == "compute" and is_revision_question(question):
revision_context = await build_revision_change_context(
db,
publish_id=(view_spec or {}).get("publish_id") or publish_id,
redact=(getattr(access, "tier", "public_zero_cost") != "admin"),
)
analysis_req = (
_build_news_analysis_request(
question=question,
@@ -710,6 +735,7 @@ async def stream_session_turn(
conversation_summary=compacted_summary,
memory_notes=clean_memory_notes,
pinned_summaries=clean_pinned_summaries,
revision_context=revision_context,
)
)
+649 -10
View File
@@ -2,7 +2,7 @@
from __future__ import annotations
from datetime import UTC, datetime
from datetime import UTC, date, datetime, timedelta
import hashlib
import ipaddress
import socket
@@ -18,7 +18,7 @@ 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.schemas.compute_configuration import ComputeConfiguration, ComputeObservation, source_for
from app.services.ai_tools.schemas import FetchedEvidence
from app.services.compute_configuration import read_configuration
from app.services.compute_history import compute_history
@@ -210,10 +210,42 @@ def filter_compute_config_by_cutoff(
kept_sources.append(src)
kept_source_ids = {s.id for s in kept_sources}
kept_obs = [
obs for obs in config.observations
if obs.year <= cutoff_year and obs.source_id in kept_source_ids
]
kept_obs: list[ComputeObservation] = []
for obs in config.observations:
if obs.year > cutoff_year:
continue
surviving_values = {
code: val
for code, val in obs.values.items()
if source_for(obs, code) in kept_source_ids
}
if not surviving_values:
continue
per_code_sources = {code: source_for(obs, code) for code in surviving_values}
row_src = (
obs.source_id
if obs.source_id in kept_source_ids
else next(iter(per_code_sources.values()))
)
unique_sources = list(dict.fromkeys(per_code_sources.values()))
if len(unique_sources) == 1:
row_src = unique_sources[0]
cleaned_vs = None
else:
cleaned_vs = {
code: src_id
for code, src_id in per_code_sources.items()
if src_id != row_src
} or None
kept_obs.append(
obs.model_copy(
update={
"source_id": row_src,
"values": surviving_values,
"value_sources": cleaned_vs,
}
)
)
kept_innov = [
inn for inn in config.innovation
if inn.year <= cutoff_year and inn.source_id in kept_source_ids
@@ -259,9 +291,28 @@ async def query_compute_posture_tool(
*,
time_basis: TimeBasis = "retrospective",
cutoff_at: str | None = None,
as_of: str | None = None,
publish_id: str | None = None,
) -> dict[str, Any]:
"""Read-only tool returning deterministic multi-metric compute series and provenance."""
envelope = await read_configuration(db)
envelope = await read_configuration(db, as_of=as_of, publish_id=publish_id)
if envelope.get("snapshot_unavailable"):
empty_config = ComputeConfiguration(
reviewed_at=date.today(), sources=[], observations=[], innovation=[]
)
result = compute_history(countries, mode, empty_config)
result["version"] = None
result["publish_id"] = None
result["published_at"] = None
result["as_of"] = envelope.get("as_of")
result["snapshot_unavailable"] = True
result["notice"] = envelope.get("notice")
result["is_default"] = False
result["time_basis"] = time_basis
result["cutoff_at"] = cutoff_at if time_basis == "as_known_then" else None
result["withheld_source_ids"] = []
return result
raw_config = ComputeConfiguration.model_validate(envelope["config"])
effective_config, withheld_sources = filter_compute_config_by_cutoff(
raw_config, time_basis=time_basis, cutoff_at=cutoff_at
@@ -278,7 +329,12 @@ async def query_compute_posture_tool(
result["innovation"] = [
r for r in (result.get("innovation") or []) if int(r.get("year") or 0) <= cutoff_year
]
result["version"] = envelope["revision"]
effective_pid = envelope.get("publish_id") or envelope["revision"]
result["version"] = effective_pid
result["publish_id"] = effective_pid
result["published_at"] = envelope.get("published_at")
result["as_of"] = envelope.get("as_of")
result["snapshot_unavailable"] = False
result["is_default"] = envelope["is_default"]
result["time_basis"] = time_basis
result["cutoff_at"] = cutoff_at if time_basis == "as_known_then" else None
@@ -554,12 +610,27 @@ async def query_cable_posture_tool(
if time_basis == "as_known_then":
limitations.append("海缆资产库按当前目录快照读取,不具备历史逐日断缆回放快照,仅作当下资产基线参考。")
from app.services.nga_advisories import list_active_cable_advisories
advisories = await list_active_cable_advisories(db, limit=30)
if advisories:
base_evidence["ev-cable-nga-1"] = {
"id": "ev-cable-nga-1",
"title": "NGA MSI 航海通告与海缆安全告警(nga_navigation_warnings)",
"publisher": "National Geospatial-Intelligence Agency (NGA MSI)",
"url": "https://msi.nga.mil/NavWarnings",
"published_at": datetime.now(UTC).date().isoformat(),
"locator": "builtin:cable_advisories",
}
return {
"domain": "cable",
"available": len(cable_features) > 0 or len(landing_features) > 0,
"cables_total": len(cable_features),
"landing_points_total": len(landing_features),
"status_counts": status_counts,
"advisory_count": len(advisories),
"advisories": advisories,
"top_longest_cables": cables_parsed[: max(1, min(limit, 12))],
"top_landing_countries": top_countries,
"top_landing_hubs": landing_hubs[: max(1, min(limit, 12))],
@@ -730,18 +801,32 @@ async def query_recent_earth_news_tool(
)
if region:
stmt = stmt.where(EarthNewsItem.region == region)
rows = (await db.execute(stmt)).scalars().all()
rows = list((await db.execute(stmt)).scalars().all())
rows.sort(
key=lambda r: (
getattr(r, "credibility_tier", None) is None,
int(getattr(r, "credibility_tier", None) or 99),
-(r.published_at.timestamp() if r.published_at else (r.last_seen_at.timestamp() if r.last_seen_at else 0.0)),
)
)
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 {}
tier = getattr(row, "credibility_tier", None)
state_aff = bool(getattr(row, "state_affiliated", False))
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,
"credibility_tier": tier,
"credibility_label": f"Tier {tier}" if tier is not None else "未分级",
"state_affiliated": state_aff,
"state_affiliation_label": "国家背景媒体" if state_aff else None,
"theater_tags": list(getattr(row, "theater_tags", None) or []),
"region": row.region,
"location_label": row.location_label,
"category": news_meta.get("category") or "other",
@@ -868,6 +953,13 @@ async def query_vessel_posture_tool(
parsed_vessels.sort(key=lambda r: (r["sog"] or -1.0, r["name"]), reverse=True)
sorted_flags = dict(sorted(top_flags.items(), key=lambda kv: kv[1], reverse=True)[:8])
from app.services.maritime_geography import compute_chokepoint_vessel_summary
chokepoints = await compute_chokepoint_vessel_summary(db, features)
warship_count = sum(1 for f in features if (f.get("properties") or {}).get("is_warship"))
cable_ship_count = sum(1 for f in features if (f.get("properties") or {}).get("is_cable_ship"))
if time_basis == "as_known_then":
limitations.append(f"AIS 船舶快照仅覆盖近 {since_minutes} 分钟滑动窗口,不支持历史截点静态重放。")
@@ -877,6 +969,9 @@ async def query_vessel_posture_tool(
"vessels_total": int(stats.get("total") or len(features)),
"underway": int(stats.get("underway") or 0),
"anchored_or_moored": int(stats.get("anchored_or_moored") or 0),
"warship_count": warship_count,
"cable_ship_count": cable_ship_count,
"chokepoints": chokepoints,
"by_type": dict(stats.get("by_type") or {}),
"top_flags": sorted_flags,
"sample_vessels": parsed_vessels[:8],
@@ -890,6 +985,119 @@ async def query_vessel_posture_tool(
}
async def query_cloud_posture_tool(
db: AsyncSession,
*,
time_basis: TimeBasis = "live",
cutoff_at: str | None = None,
correlate_domain: str | None = None,
latitude: float | None = None,
longitude: float | None = None,
) -> dict[str, Any]:
"""Read-only meteorological cloud cover, convective cluster, and asset correlation summary."""
from app.services.earth_clouds import (
correlate_cloud_with_assets,
get_cloud_analysis_summary,
query_cloud_point,
)
summary = await get_cloud_analysis_summary(db)
point_info = None
if isinstance(latitude, (int, float)) and isinstance(longitude, (int, float)):
point_info = await query_cloud_point(float(latitude), float(longitude), db=db)
correlation = None
if correlate_domain and hasattr(db, "execute"):
try:
correlation = await correlate_cloud_with_assets(
db, domain=correlate_domain, min_density=55.0, limit=12
)
except Exception:
correlation = None
ev_id = "ev-cloud-1"
return {
"domain": "cloud",
"available": bool(summary.get("available")),
"mode": summary.get("mode"),
"degraded": summary.get("degraded"),
"version": summary.get("version"),
"captured_at": summary.get("captured_at"),
"source": summary.get("source"),
"satellites": summary.get("satellites") or [],
"global_summary": summary.get("global_summary") or {},
"regions": summary.get("regions") or [],
"convective_clusters": (summary.get("convective_clusters") or [])[:12],
"point_query": point_info,
"asset_correlation": correlation,
"time_basis": time_basis,
"cutoff_at": cutoff_at if time_basis == "as_known_then" else None,
"evidence": {
ev_id: {
"id": ev_id,
"title": "Planet 全球静止气象卫星实时红外云图与强对流分析(global_cloud_map)",
"publisher": "NASA GIBS / EUMETSAT / Planet Earth Cloud Analytics",
"url": "/api/v1/data-products/clouds/summary",
"published_at": str(summary.get("captured_at") or datetime.now(UTC).date().isoformat()),
"locator": f"builtin:cloud:{summary.get('version') or 'static'}",
}
},
"limitations": (
[]
if summary.get("available")
else ["尚未采集实时卫星云图快照,当前无可分析的实时云量栅格。"]
),
}
async def query_wind_posture_tool(
db: AsyncSession,
*,
time_basis: TimeBasis = "live",
cutoff_at: str | None = None,
latitude: float | None = None,
longitude: float | None = None,
) -> dict[str, Any]:
"""Read-only NOAA GFS 10m global wind velocity, gale zones, and point vector summary."""
from app.services.earth_wind import get_wind_analysis_summary, query_wind_point
summary = await get_wind_analysis_summary(db)
point_info = None
if isinstance(latitude, (int, float)) and isinstance(longitude, (int, float)):
point_info = await query_wind_point(float(latitude), float(longitude), db=db)
ev_id = "ev-wind-1"
return {
"domain": "wind",
"available": bool(summary.get("available")),
"is_active": bool(summary.get("is_active")),
"version": summary.get("version"),
"captured_at": summary.get("captured_at"),
"forecast_time": summary.get("forecast_time"),
"global_summary": summary.get("global_summary") or {},
"regions": summary.get("regions") or [],
"storm_cores": (summary.get("storm_cores") or [])[:12],
"point_query": point_info,
"time_basis": time_basis,
"cutoff_at": cutoff_at if time_basis == "as_known_then" else None,
"evidence": {
ev_id: {
"id": ev_id,
"title": "NOAA GFS 全球 10m 海表风场与大风核分析(global_wind_gfs)",
"publisher": "NOAA NCEP / PacIOOS ERDDAP",
"url": "/api/v1/data-products/wind/summary",
"published_at": str(summary.get("forecast_time") or summary.get("captured_at") or datetime.now(UTC).date().isoformat()),
"locator": f"builtin:wind:{summary.get('version') or 'static'}",
}
},
"limitations": (
[]
if summary.get("available")
else ["尚未采集全球 10m 风场快照,当前无可分析的 GFS 风速网格。"]
),
}
async def query_global_situational_tool(
db: AsyncSession,
*,
@@ -926,6 +1134,7 @@ async def query_global_situational_tool(
cable_data = await query_cable_posture_tool(db, time_basis=time_basis, cutoff_at=cutoff_at)
sat_data = await query_satellite_posture_tool(db, time_basis=time_basis, cutoff_at=cutoff_at)
vessel_data = await query_vessel_posture_tool(db, time_basis=time_basis, cutoff_at=cutoff_at)
cloud_data = await query_cloud_posture_tool(db, time_basis=time_basis, cutoff_at=cutoff_at)
vis = dict(visible_layers or {})
active_bgp = [it for it in bgp_items if str(it.get("status") or "").lower() == "active"]
@@ -943,7 +1152,7 @@ async def query_global_situational_tool(
"locator": f"builtin:global:codes={','.join(codes)}:basis={time_basis}",
}
}
for sub in (compute_data, cable_data, sat_data, vessel_data):
for sub in (compute_data, cable_data, sat_data, vessel_data, cloud_data):
for k, v in (sub.get("evidence") or {}).items():
if k not in evidence and len(evidence) < 12:
evidence[k] = v
@@ -994,11 +1203,32 @@ async def query_global_situational_tool(
"metric_text": f"{len(bgp_items)} 条(活跃 {len(active_bgp)})",
"status": "incident_active" if active_bgp else ("telemetry_online" if bgp_items else "quiet"),
},
{
"domain": "cloud",
"label": "气象云图",
"layer_visible": bool(vis.get("clouds", True)),
"count": int((cloud_data.get("global_summary") or {}).get("convective_cluster_count") or 0),
"secondary_count": round(float((cloud_data.get("global_summary") or {}).get("global_cloud_cover_pct") or 0.0), 1),
"metric_text": (
f"全球云量 {(cloud_data.get('global_summary') or {}).get('global_cloud_cover_pct', 0)}% · "
f"强对流 {(cloud_data.get('global_summary') or {}).get('convective_cluster_count', 0)} 个"
if cloud_data.get("available")
else "未采集实时云图"
),
"status": "telemetry_online" if cloud_data.get("available") else "standby_or_empty",
},
]
from app.services.source_freshness import compute_domain_freshness
freshness_report = await compute_domain_freshness(db)
blind_spots = list(freshness_report.get("blind_spots") or [])
limitations: list[str] = []
if time_basis == "as_known_then":
limitations.append("全局综合面板中算力与 BGP 遵循历史截点过滤,其余实时图层(海缆/卫星/AIS)按当前资产目录展示。")
for spot in blind_spots[:5]:
limitations.append(f"盲区提示:{spot.get('label')}({spot.get('status')})- {spot.get('reason')}")
return {
"domain": "global",
@@ -1006,6 +1236,8 @@ async def query_global_situational_tool(
"selected_codes": codes,
"visible_layers": vis,
"domain_summaries": domain_summaries,
"freshness": freshness_report.get("domains") or [],
"blind_spots": blind_spots,
"compute_summary": {
"latest_year": latest_compute_year,
"mode": compute_data.get("mode") or "global_share",
@@ -1031,8 +1263,415 @@ async def query_global_situational_tool(
"underway": vessel_data.get("underway", 0),
"by_type": vessel_data.get("by_type") or {},
},
"cloud_summary": {
"available": cloud_data.get("available", False),
"captured_at": cloud_data.get("captured_at"),
"global_cloud_cover_pct": (cloud_data.get("global_summary") or {}).get("global_cloud_cover_pct"),
"convective_cluster_count": (cloud_data.get("global_summary") or {}).get("convective_cluster_count", 0),
"top_clusters": (cloud_data.get("convective_clusters") or [])[:3],
},
"time_basis": time_basis,
"cutoff_at": cutoff_at if time_basis == "as_known_then" else None,
"evidence": evidence,
"limitations": limitations,
}
def _classify_airspace_corridor(lat: float, lon: float) -> str:
if 30.0 <= lat <= 72.0 and -12.0 <= lon <= 45.0:
return "europe_black_sea"
if 10.0 <= lat <= 42.0 and 25.0 <= lon <= 65.0:
return "middle_east_red_sea"
if 0.0 <= lat <= 46.0 and 95.0 <= lon <= 150.0:
return "indo_west_pacific"
if 24.0 <= lat <= 60.0 and -130.0 <= lon <= -55.0:
return "north_america"
if 35.0 <= lat <= 65.0 and -55.0 <= lon < -12.0:
return "north_atlantic"
return "other_airspace"
async def query_aircraft_posture_tool(
db: AsyncSession,
*,
time_basis: TimeBasis = "retrospective",
cutoff_at: str | None = None,
entity_id: str | None = None,
limit: int = 800,
since_minutes: int = 15,
) -> dict[str, Any]:
"""Read-only built-in telemetry summary for live ADS-B aircraft traffic."""
base_ev_id = "ev-aircraft-1"
base_evidence = {
base_ev_id: {
"id": base_ev_id,
"title": "Planet 内置全球 ADS-B 空域态势快照(aircraft/snapshot)",
"publisher": "adsb.lol (ODbL) & OpenSky Network",
"url": "/api/v1/aircraft/snapshot",
"published_at": datetime.now(UTC).date().isoformat(),
"locator": f"builtin:aircraft:{entity_id or 'global'}:since={since_minutes}m",
}
}
if not hasattr(db, "execute"):
return {
"domain": "aircraft",
"available": False,
"aircraft_total": 0,
"military_count": 0,
"emergency_count": 0,
"by_category": {},
"key_airspaces": {},
"sample_aircraft": [],
"focused_entity": None,
"time_basis": time_basis,
"cutoff_at": cutoff_at if time_basis == "as_known_then" else None,
"evidence": base_evidence,
"limitations": ["当前离线/无实时数据库会话,未读取 ADS-B 空域快照。"],
}
from app.models.aircraft import AircraftCurrentState
cutoff = datetime.now(UTC) - timedelta(minutes=max(1, int(since_minutes)))
safe_limit = max(50, min(int(limit or 800), 2000))
rows: list[AircraftCurrentState] = []
limitations: list[str] = []
try:
res = await db.execute(
select(AircraftCurrentState)
.where(AircraftCurrentState.observed_at >= cutoff)
.order_by(
desc(AircraftCurrentState.is_emergency),
desc(AircraftCurrentState.is_military),
desc(AircraftCurrentState.observed_at),
)
.limit(safe_limit)
)
rows = list(res.scalars().all())
except Exception as exc:
logger.warning_event(
"Aircraft posture query degraded",
event="ai_tool.aircraft_posture.degraded",
context={"error": str(exc)},
)
limitations.append("ADS-B 空域快照查询受限")
by_category: dict[str, int] = {}
key_airspaces: dict[str, dict[str, int]] = {}
military_count = 0
emergency_count = 0
focused_entity: dict[str, Any] | None = None
query_norm = str(entity_id or "").strip().lower()
sample_aircraft: list[dict[str, Any]] = []
for row in rows:
cat = str(row.category or "other")
by_category[cat] = by_category.get(cat, 0) + 1
if row.is_military:
military_count += 1
if row.is_emergency:
emergency_count += 1
corridor = _classify_airspace_corridor(float(row.lat), float(row.lon))
bucket = key_airspaces.setdefault(
corridor,
{"total": 0, "military": 0, "emergency": 0, "commercial": 0},
)
bucket["total"] += 1
if row.is_military:
bucket["military"] += 1
if row.is_emergency:
bucket["emergency"] += 1
if cat == "commercial":
bucket["commercial"] += 1
item = row.to_dict()
if len(sample_aircraft) < 20:
sample_aircraft.append(item)
if query_norm and focused_entity is None and (
query_norm == str(row.icao24).lower()
or query_norm in str(row.callsign or "").lower()
):
focused_entity = {"kind": "aircraft", **item}
if time_basis == "as_known_then":
limitations.append(f"实时空域快照仅覆盖近 {since_minutes} 分钟窗口。")
return {
"domain": "aircraft",
"available": bool(rows),
"aircraft_total": len(rows),
"military_count": military_count,
"emergency_count": emergency_count,
"by_category": by_category,
"key_airspaces": key_airspaces,
"sample_aircraft": sample_aircraft,
"focused_entity": focused_entity,
"time_basis": time_basis,
"cutoff_at": cutoff_at if time_basis == "as_known_then" else None,
"evidence": base_evidence,
"limitations": limitations,
}
async def query_gps_jamming_posture_tool(
db: AsyncSession,
*,
time_basis: TimeBasis = "retrospective",
cutoff_at: str | None = None,
observed_date: str | None = None,
limit: int = 200,
) -> dict[str, Any]:
"""Read-only built-in summary of daily H3 GNSS/GPS interference hotspots."""
base_ev_id = "ev-gpsjam-1"
base_evidence = {
base_ev_id: {
"id": base_ev_id,
"title": "Planet 内置 GPS/GNSS 干扰监测快照(gpsjam.org H3-4)",
"publisher": "gpsjam.org (airplanes.live / ADS-B Exchange)",
"url": "/api/v1/gps-jamming/snapshot",
"published_at": datetime.now(UTC).date().isoformat(),
"locator": f"builtin:gps_jamming:{observed_date or 'latest'}",
}
}
if not hasattr(db, "execute"):
return {
"domain": "gps_jamming",
"available": False,
"observed_date": None,
"cells_total": 0,
"high_count": 0,
"medium_count": 0,
"high_zones": [],
"medium_zones": [],
"time_basis": time_basis,
"cutoff_at": cutoff_at if time_basis == "as_known_then" else None,
"evidence": base_evidence,
"limitations": ["当前离线/无实时数据库会话,未读取 GPS 干扰快照。"],
}
from app.models.gps_jamming import GPSJammingCell
target_date = str(observed_date or "").strip() or None
if not target_date:
target_date = (
await db.execute(
select(GPSJammingCell.observed_date)
.order_by(desc(GPSJammingCell.observed_date))
.limit(1)
)
).scalar_one_or_none()
if not target_date:
return {
"domain": "gps_jamming",
"available": False,
"observed_date": None,
"cells_total": 0,
"high_count": 0,
"medium_count": 0,
"high_zones": [],
"medium_zones": [],
"time_basis": time_basis,
"cutoff_at": cutoff_at if time_basis == "as_known_then" else None,
"evidence": base_evidence,
"limitations": ["暂无已采集的 gpsjam 日度干扰栅格。"],
}
rows = list(
(
await db.execute(
select(GPSJammingCell)
.where(GPSJammingCell.observed_date == target_date)
.where(GPSJammingCell.level.in_(["high", "medium"]))
.order_by(desc(GPSJammingCell.bad_ratio))
.limit(max(20, min(int(limit or 200), 1000)))
)
).scalars().all()
)
high_zones = [
{
"h3_index": r.h3_index,
"lat": r.lat,
"lon": r.lon,
"bad_ratio": r.bad_ratio,
"aircraft_count": r.aircraft_count,
"region": _classify_airspace_corridor(float(r.lat), float(r.lon)),
}
for r in rows
if r.level == "high"
]
medium_zones = [
{
"h3_index": r.h3_index,
"lat": r.lat,
"lon": r.lon,
"bad_ratio": r.bad_ratio,
"aircraft_count": r.aircraft_count,
"region": _classify_airspace_corridor(float(r.lat), float(r.lon)),
}
for r in rows
if r.level == "medium"
]
return {
"domain": "gps_jamming",
"available": bool(rows),
"observed_date": target_date,
"cells_total": len(rows),
"high_count": len(high_zones),
"medium_count": len(medium_zones),
"high_zones": high_zones[:20],
"medium_zones": medium_zones[:20],
"time_basis": time_basis,
"cutoff_at": cutoff_at if time_basis == "as_known_then" else None,
"evidence": base_evidence,
"limitations": [
"gpsjam 反映高空航空器报告的 GNSS 导航精度下降指标,地面受影响范围可能与高空视线存在差异。"
],
}
async def query_disaster_posture_tool(
db: AsyncSession,
*,
time_basis: TimeBasis = "retrospective",
cutoff_at: str | None = None,
event_types: list[str] | None = None,
since_hours: int = 72,
limit: int = 200,
) -> dict[str, Any]:
"""Read-only built-in telemetry summary for recent natural disasters."""
base_ev_id = "ev-disasters-1"
base_evidence = {
base_ev_id: {
"id": base_ev_id,
"title": "Planet 全球自然灾害快照(disasters/snapshot)",
"publisher": "USGS / NASA FIRMS / GDACS / NASA EONET",
"url": "/api/v1/disasters/snapshot",
"published_at": datetime.now(UTC).date().isoformat(),
"locator": f"builtin:disasters:since={since_hours}h",
}
}
if not hasattr(db, "execute"):
return {
"domain": "disasters",
"available": False,
"count": 0,
"high_count": 0,
"by_type": {},
"events": [],
"time_basis": time_basis,
"cutoff_at": cutoff_at if time_basis == "as_known_then" else None,
"evidence": base_evidence,
"limitations": ["当前离线/无实时数据库会话,未读取自然灾害库。"],
}
from app.models.disaster import DisasterEvent
cutoff = datetime.now(UTC) - timedelta(hours=max(1, int(since_hours)))
stmt = (
select(DisasterEvent)
.where(DisasterEvent.observed_at >= cutoff, DisasterEvent.duplicate_of.is_(None))
.order_by(desc(DisasterEvent.observed_at))
.limit(max(20, min(int(limit or 200), 1000)))
)
if event_types:
stmt = stmt.where(DisasterEvent.event_type.in_(event_types))
rows: list[DisasterEvent] = []
try:
rows = list((await db.execute(stmt)).scalars().all())
except Exception as exc:
logger.warning_event(
"Disaster posture query degraded",
event="ai_tool.disaster_posture.degraded",
context={"error": str(exc)},
)
by_type: dict[str, int] = {}
high_count = 0
samples: list[dict[str, Any]] = []
for row in rows:
ev_t = str(row.event_type or "other")
by_type[ev_t] = by_type.get(ev_t, 0) + 1
if str(row.severity or "").lower() == "high":
high_count += 1
if len(samples) < 25:
samples.append(row.to_dict())
return {
"domain": "disasters",
"available": bool(rows),
"count": len(rows),
"high_count": high_count,
"by_type": by_type,
"events": samples,
"time_basis": time_basis,
"cutoff_at": cutoff_at if time_basis == "as_known_then" else None,
"evidence": base_evidence,
"limitations": [] if rows else ["近72小时内暂无已去重的自然灾害告警记录。"],
}
async def query_ontology_neighborhood_tool(
db: Any,
*,
object_id: str,
depth: int = 1,
radius_km: float = 150.0,
time_basis: TimeBasis = "current",
cutoff_at: str | None = None,
) -> dict[str, Any]:
"""Read-only built-in ontology object & 1-2 hop neighborhood lookup tool."""
from app.services.ai.entity_resolver import resolve_ontology_neighborhood
base_ev_id = "ev-ontology-1"
evidence = {
base_ev_id: {
"id": base_ev_id,
"title": f"Planet 联邦本体邻域图谱 ({object_id})",
"publisher": "Planet Ontology Read-Time Resolver",
"url": f"/api/v1/ontology/objects/{object_id}/neighborhood?depth={depth}",
"published_at": datetime.now(UTC).date().isoformat(),
"locator": f"ontology:{object_id}:depth={depth}",
}
}
if not hasattr(db, "execute"):
return {
"domain": "ontology",
"available": False,
"object_id": object_id,
"root": None,
"nodes": [],
"edges": [],
"time_basis": time_basis,
"cutoff_at": cutoff_at if time_basis == "as_known_then" else None,
"evidence": evidence,
"limitations": ["当前离线/无实时数据库会话,未能查询本体邻域。"],
}
result = await resolve_ontology_neighborhood(db, object_id, depth=depth, radius_km=radius_km)
if result is None:
return {
"domain": "ontology",
"available": False,
"object_id": object_id,
"root": None,
"nodes": [],
"edges": [],
"time_basis": time_basis,
"cutoff_at": cutoff_at if time_basis == "as_known_then" else None,
"evidence": evidence,
"limitations": [f"未在本体库中解析到对象 {object_id}。"],
}
return {
"domain": "ontology",
"available": True,
"object_id": result["root"]["object_id"],
"root": result["root"],
"depth": result["depth"],
"nodes": result["nodes"],
"edges": result["edges"],
"relation_sources": result["relation_sources"],
"time_basis": time_basis,
"cutoff_at": cutoff_at if time_basis == "as_known_then" else None,
"evidence": evidence,
"limitations": [],
}
+23 -3
View File
@@ -1286,10 +1286,27 @@ def _deterministic_business_patches(
bad_runs: list[dict[str, Any]],
) -> tuple[str, list[dict[str, Any]]]:
nodes = [n for n in (base_graph.get("nodes") or []) if isinstance(n, dict)]
llm_node = next((n for n in nodes if n.get("node_type") in {"llm_agent", "tool_agent"}), None)
if llm_node is None:
llm_nodes = [n for n in nodes if n.get("node_type") in {"llm_agent", "tool_agent"}]
if not llm_nodes:
return "当前工作流无可扩展推理节点。", []
llm_node = llm_nodes[0]
if bad_runs:
failed_node_counts: dict[str, int] = {}
for br in bad_runs:
traces = (br.get("budget_used") or {}).get("node_traces") if isinstance(br.get("budget_used"), dict) else None
if not isinstance(traces, list):
continue
for item in traces:
if not isinstance(item, dict):
continue
nid = str(item.get("node_id") or "")
if item.get("status") in {"completed", "failed"} and any(n.get("id") == nid for n in llm_nodes):
failed_node_counts[nid] = failed_node_counts.get(nid, 0) + 1
if failed_node_counts:
top_nid = max(failed_node_counts, key=lambda k: failed_node_counts[k])
llm_node = next((n for n in llm_nodes if n.get("id") == top_nid), llm_node)
patches: list[dict[str, Any]] = []
if mode == "model_adapt":
profile = health.get("active_model_profile") or {}
@@ -1909,15 +1926,18 @@ async def _run_graph_single_sample(
nodes_done: list[str] = []
verification: dict[str, Any] = {}
evidence_count = 0
targets = earth_context.get("targets") if isinstance(earth_context.get("targets"), list) else None
allow_external = bool(earth_context.get("allow_external_tools", False))
try:
async for ev in run_workflow_dag_stream(
db=db,
workflow=test_wf,
question=question,
use_draft=True,
targets=targets,
earth_context=earth_context,
ai_client=ai_client,
allow_external_tools=False,
allow_external_tools=allow_external,
):
ev_name = str(ev.get("event") or "")
ev_data = ev.get("data") if isinstance(ev.get("data"), dict) else {}
+423 -46
View File
@@ -19,6 +19,10 @@ from app.models.ai_workflow import AIWorkflow, AIWorkflowFixture, AIWorkflowRevi
from app.models.situational_assessment import WorkflowRun
from app.schemas.ai import SituationalAnalysisRequest
from app.services.ai.thinking_sanitizer import strip_thinking_text
from app.services.location.workflow_tools import (
LOCATION_JUDGE_FINAL_SCHEMA,
LOCATION_JUDGE_R1_SCHEMA,
)
logger = get_logger(__name__, service="ai_workflow_registry")
@@ -65,6 +69,41 @@ TOOL_CATALOG: list[dict[str, Any]] = [
"category": "internal_read",
"description": "查询航运密度、关键海峡通道船只态势。",
},
{
"id": "query_aircraft_posture",
"name": "全球 ADS-B 空域航班快照",
"name_en": "ADS-B Aircraft Airspace Snapshot",
"category": "internal_read",
"description": "按区域统计军机、紧急应答机与民航数量及重点空域态势。",
},
{
"id": "query_gps_jamming_posture",
"name": "GPS/GNSS 电子干扰区域快照",
"name_en": "GPS/GNSS Interference Zones Snapshot",
"category": "internal_read",
"description": "查询日度 H3 高/中干扰区域分布与覆盖范围。",
},
{
"id": "query_disaster_posture",
"name": "全球自然灾害态势快照",
"name_en": "Global Natural Disaster Snapshot",
"category": "internal_read",
"description": "查询地震、林火热点簇、气旋、洪水与火山等已去重多源灾害告警。",
},
{
"id": "query_cloud_posture",
"name": "全球实时红外云图与强对流分析",
"name_en": "Live Satellite Cloud & Convection Analytics",
"category": "internal_read",
"description": "读取全球与重点航运/算力区域云量、强对流云团与云顶亮温数据。",
},
{
"id": "query_wind_posture",
"name": "全球 10m 风场与大风区态势",
"name_en": "Global 10m Wind Field & Gale Analytics",
"category": "internal_read",
"description": "读取 NOAA GFS 全球 10m 风速、风向、大风核心区域与重点航道风场态势。",
},
{
"id": "query_recent_earth_news",
"name": "Earth 近期新闻动态",
@@ -72,6 +111,13 @@ TOOL_CATALOG: list[dict[str, Any]] = [
"category": "internal_read",
"description": "检索全球近期已入库/汉化新闻头条与地理锚点。",
},
{
"id": "query_ontology_neighborhood",
"name": "联邦本体邻域图谱检索",
"name_en": "Ontology Neighborhood Lookup",
"category": "internal_read",
"description": "按 `{type}:{id}` 读取时推导对象 1–2 跳拓扑/空间邻域与人工关系。",
},
{
"id": "builds_upon_inherit",
"name": "Epoch builds_upon 父集群继承",
@@ -133,7 +179,42 @@ TOOL_CATALOG: list[dict[str, Any]] = [
"name": "位置结果强约束提交",
"name_en": "Constrained Location Submit",
"category": "location_guardrail",
"description": "通过 Schema 工具提交定位结论或 undisclosed/multi_site 终态。",
"description": "兼容旧版工具式位置提交定义。",
},
{
"id": "location_normalize_context",
"name": "L0 位置上下文归一化与终态检查",
"name_en": "L0 Location Normalize & Terminal Check",
"category": "location_knowledge",
"description": "水合数据库与跨源线索、统一英文国名,并在已确认终态时短路。",
},
{
"id": "location_knowledge_lookup",
"name": "L1 确定性设施知识库查询",
"name_en": "L1 Facility Knowledge Lookup",
"category": "location_knowledge",
"description": "串并行组合查询 builds_upon、ROR、Wikidata(P17) 与 PeeringDB(/api/fac)。",
},
{
"id": "location_web_research",
"name": "L2 并行网页取证与证据编号",
"name_en": "L2 Parallel Web Research",
"category": "external_evidence",
"description": "按轮次并行抓取一手正文并执行结构化英文 WebSearch,为证据编号 E1..En。",
},
{
"id": "location_geocode_verify",
"name": "L3 多粒度级联地理编码校验",
"name_en": "L3 Cascade Geocoder Verify",
"category": "location_guardrail",
"description": "按 街道地址 -> 设施名 -> 城市+省州 -> 城市 级联查 Nominatim 并校验国家与粒度。",
},
{
"id": "location_persist_outcome",
"name": "L4 位置结果输出与终态持久化",
"name_en": "L4 Location Output & Persist",
"category": "location_guardrail",
"description": "输出标准候选坐标载荷与地球联动视角,或在有实证时落库不可定位终态。",
},
]
@@ -145,10 +226,17 @@ VALID_NODE_TYPES: frozenset[str] = frozenset(
{"trigger", "deterministic", "llm_agent", "guardrail", "output"}
)
VALID_EDGE_CONDITIONS: frozenset[str] = frozenset(
{"always", "on_empty_or_low_confidence", "on_entity_type"}
{
"always",
"on_empty_or_low_confidence",
"on_entity_type",
"on_field_equals",
"on_guardrail_passed",
"on_guardrail_failed",
}
)
PRESERVED_BUILTIN_EDGE_CONDITIONS: frozenset[str] = frozenset(
{"not_terminal", "high_confidence_hit", "fallback_to_agent", "ingest", "interactive"}
{"not_terminal", "on_terminal", "high_confidence_hit", "fallback_to_agent", "ingest", "interactive"}
)
ALLOWED_EDGE_CONDITIONS: frozenset[str] = VALID_EDGE_CONDITIONS | PRESERVED_BUILTIN_EDGE_CONDITIONS
@@ -157,6 +245,8 @@ EARTH_ENTITY_TYPES: list[dict[str, str]] = [
{"id": "landing_point", "name": "海缆登陆站", "name_en": "Landing Point", "group": "infrastructure"},
{"id": "satellite", "name": "在轨卫星", "name_en": "Satellite", "group": "infrastructure"},
{"id": "vessel", "name": "AIS 船舶", "name_en": "AIS Vessel", "group": "infrastructure"},
{"id": "aircraft", "name": "ADS-B 航空器", "name_en": "ADS-B Aircraft", "group": "infrastructure"},
{"id": "gps_jamming_cell", "name": "GPS 干扰单元", "name_en": "GPS Jamming Cell", "group": "infrastructure"},
{"id": "bgp", "name": "BGP 异常事件", "name_en": "BGP Incident", "group": "infrastructure"},
{"id": "bgp_collector", "name": "BGP 观测站", "name_en": "BGP Collector", "group": "infrastructure"},
{"id": "supercomputer", "name": "超级计算机", "name_en": "Supercomputer", "group": "compute"},
@@ -355,6 +445,8 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [
"landing_point",
"satellite",
"vessel",
"aircraft",
"gps_jamming_cell",
"bgp",
"bgp_collector",
"supercomputer",
@@ -399,9 +491,9 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [
140,
description="结合本地记忆与系统遥测输出结构化研判;区分事实与推演。",
prompt_key="situational.copilot.reply",
system_prompt="你是智能星球(Planet)首席态势参谋。仅基于传入事实与工具证据作答,严谨区分确认事实、概率推断与待核验缺口。",
system_prompt="你是智能星球(Planet)首席态势参谋。仅基于传入事实与工具证据作答,严谨区分确认事实、概率推断与待核验缺口。回答中必须单独列出情报盲区(blind_spots);凡新鲜度状态不是 fresh 的业务域,严禁描述为“无事件”或“态势平静”。",
prompt="结合用户聚焦的地球空间上下文、历史记忆与工具数据,给出清晰、可执行、引用可追溯的专业中文分析(若用户使用英文则用英文)。",
tools=["query_global_situational", "query_compute_posture", "query_bgp_incidents", "query_recent_earth_news", "web_search"],
tools=["query_global_situational", "query_compute_posture", "query_bgp_incidents", "query_aircraft_posture", "query_gps_jamming_posture", "query_recent_earth_news", "web_search"],
thinking_enabled=True,
max_steps=3,
timeout_seconds=60,
@@ -428,8 +520,8 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [
"name": "算力/设施未知位置定位工作流",
"name_en": "Compute & Facility Location Agent",
"category": "location",
"description": "整合 builds_upon 继承、Wikidata、PeeringDB、可控 Tool-Calling 取证与地理编码硬校验的完整定位管线。",
"description_en": "Tiered facility geolocation combining builds_upon, Wikidata, PeeringDB, controlled tool-calling evidence, and geocoder verification.",
"description": "真正的条件路由 DAG 工作流:L0 归一化与终态短路 → L1 知识库 → 两轮并行联网取证与单轮结构化研判 → 级联地理编码与 3 条硬护栏。",
"description_en": "True conditional DAG workflow: L0 normalize -> L1 knowledge lookup -> 2-round parallel web research & JSON judgment -> cascade geocoder & 3 hard guardrails.",
"is_default": False,
"bindings": {
"enabled": True,
@@ -444,12 +536,13 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [
"nodes": [
_node(
"l0_normalize",
"trigger",
"L0:实体归一化与终态短路",
"deterministic",
"L0:实体归一化与终态检查",
"L0: Normalize & Terminal Check",
40,
160,
description="切分 name_short、注入 Epoch Source 1..5/TOP500 一手链接与 builds_upon,若已标记 undisclosed/multi_site 则直接短路。",
180,
description="水合数据库与跨源兄弟线索、转换英文国家名、过滤 .csv 原始表并在已确认终态时直接短路。",
tools=["location_normalize_context"],
params={"short_circuit_terminal_statuses": True},
),
_node(
@@ -457,55 +550,138 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [
"deterministic",
"L1:确定性设施知识库查询",
"L1: Knowledge Resolvers",
420,
160,
description="依次匹配 builds_upon 继承、Wikidata P625、PeeringDB /api/fac 及带商业云过滤的 ROR。",
tools=["builds_upon_inherit", "wikidata_lookup", "peeringdb_fac_lookup", "ror_lookup"],
params={"allow_low_confidence_short_circuit": False, "wikidata_enabled": True, "peeringdb_enabled": True},
380,
80,
description="依次匹配 builds_upon、ROR,并行查询 Wikidata(P625+P17) 与 PeeringDB(/api/fac)。",
tools=["location_knowledge_lookup"],
params={
"builds_upon_enabled": True,
"ror_enabled": True,
"wikidata_enabled": True,
"peeringdb_enabled": True,
},
),
_node(
"l2_agent_research",
"l2_research_r1",
"deterministic",
"L2-R1:并行一手抓取与英文搜索",
"L2-R1: Parallel Web Research",
720,
220,
description="并行抓取一手正文链接与 2 条精简英文搜索,为全部证据分配 E1..En 唯一编号。",
tools=["location_web_research"],
params={"round": 1, "max_search_queries": 2, "max_fetch_urls": 2},
),
_node(
"l2_judge_r1",
"llm_agent",
"L2:多步 Tool-Calling 取证 Agent",
"L2: Tool-Calling Evidence Agent",
800,
300,
description="优先读取一手 source_url/Source 1..5,必要时多轮改写短查询搜索并调用 geocode_verify 落点。",
"L2-J1:首轮证据语义研判",
"L2-J1: Round-1 Judgment",
1060,
220,
description="基于 E1..En 证据输出单轮结构化 JSON:直接定位 / 发起定点补查 / 确认终态。",
prompt_key="location.factcheck.resolve",
system_prompt="你是基础设施物理位置核查 Agent。严禁直接猜测或编造经纬度!必须先通过 fetch_source_url(优先使用元数据自带一手链接)或 web_search 找到物理设施/园区地址证据,再调用 geocode_verify 获取候选坐标 ID,最后调用 submit_location_result 提交结果。若确认为跨地域多站点或未披露地址,提交 multi_site 或 undisclosed。",
prompt="核查给定算力中心或 BGP 观测站的真实物理所在城市与设施位置。",
tools=["fetch_source_url", "web_search", "geocode_verify", "submit_location_result"],
system_prompt=(
"你是基础设施物理位置核查分析师。严格基于输入的 evidence_items(编号 E1..En)和 location_target 进行判断,严禁猜测或编造坐标/URL!\n"
"规则:\n"
"1) 只要证据已明确指出物理所在城市/园区(如数据中心运营商页面、政府规划/新闻稿、HPC 官网),直接设 decision='located' 并填写 city/country(英文国名)/facility_name/address 及引用的 evidence_ids;无需为追门牌号拖延。\n"
"2) 若发现重要线索但还缺关键城市名或正文细节,设 decision='need_followup',给出最多 2 条精准英文 followup_queries 或需全文抓取的 fetch_urls。\n"
"3) 若多条权威证据确认物理机房国与源登记国(总部国)不同,country 填实证物理部署国并在 country_override_reason 说明依据。\n"
"4) 仅当权威证据明确指出未披露、多地分布式、规划中、纯云端无实体时,才选对应终态(undisclosed/multi_site/planned/cloud_only)。\n"
"5) 输出语言规范:reasoning 和 country_override_reason 必须使用简洁的简体中文、不超过 120 字,且严禁出现 E1、E6、E1-E5 等内部证据编号(仅在 evidence_ids 数组填写编号供校验)。"
),
prompt="核查给定设施的真实物理所在城市与园区位置,并按 JSON 契约返回初判结论。",
thinking_enabled=True,
max_steps=4,
timeout_seconds=90,
max_steps=1,
timeout_seconds=60,
native_web_search=False,
params={"output_schema": LOCATION_JUDGE_R1_SCHEMA, "allow_followup": True},
),
_node(
"l2_research_r2",
"deterministic",
"L2-R2:定向补搜与正文全文抓取",
"L2-R2: Targeted Follow-up Research",
1400,
340,
description="仅当 J1 判定需要补查时触发,执行 J1 给出的精准补搜词与候选页全文抓取。",
tools=["location_web_research"],
params={"round": 2, "max_search_queries": 2, "max_fetch_urls": 2},
),
_node(
"l2_judge_r2",
"llm_agent",
"L2-J2:综合全部证据终判",
"L2-J2: Final Evidence Judgment",
1740,
340,
description="结合两轮全部 E1..En 证据给出最终位置研判或明确无法定位原因。",
prompt_key="location.factcheck.resolve",
system_prompt=(
"你是基础设施物理位置终判分析师。严格依据两轮汇总的 evidence_items(E1..En)给出最终判定,禁止继续追问!\n"
"若证据支持某城市或园区,请设 decision='located' 并写明 city、country(英文)、facility_name、evidence_ids 与 confidence;"
"若跨国部署,填写 country_override_reason;若证据仍不足或明确未披露,输出 unresolved 或对应终态。\n"
"输出语言规范:reasoning 和 country_override_reason 必须使用简洁的简体中文、不超过 120 字,直接说明物理部署结论或具体信息缺口,严禁出现 E1、E6、E1-E5 等内部证据编号(evidence_ids 数组照常填写供校验)。"
),
prompt="综合两轮证据完成最终物理位置裁决。",
thinking_enabled=True,
max_steps=1,
timeout_seconds=60,
native_web_search=False,
params={"output_schema": LOCATION_JUDGE_FINAL_SCHEMA, "allow_followup": False},
),
_node(
"l3_geocode",
"deterministic",
"L3:多粒度级联地理编码",
"L3: Cascade Geocoder",
2080,
180,
description="由代码按 街道地址 → 设施+城市 → 城市+省州 → 城市 级联查 Nominatim 落点并校验国家。",
tools=["location_geocode_verify"],
),
_node(
"l3_geo_guardrail",
"guardrail",
"L3:国家边界硬校验与证据核验",
"L3: Geo Boundary Guardrail",
1180,
160,
description="强制校验经纬度范围、国家匹配一致性、引用 URL 真实性及城市级回退降级。",
guardrails={"min_confidence": 0.55, "enforce_country_match": True, "require_tool_cited_urls": True, "downgrade_geocoded_site_to_city": True},
"L3:抗幻觉地理硬护栏",
"L3: Geo Anti-Hallucination Guardrail",
2420,
180,
description="校验证据真实引用(evidence_ids)、坐标>=城市级精度、置信度下限及受控跨国覆写。",
guardrails={
"geo_verification": True,
"min_confidence": 0.55,
"enforce_country_match": True,
"require_tool_cited_urls": True,
"downgrade_geocoded_site_to_city": True,
},
),
_node(
"l4_persist_outcome",
"output",
"L4:候选输出或终态落库",
"L4: Candidate / Terminal State",
1560,
160,
description="返回高可信待确认候选坐标,或写入 undisclosed/multi_site/anonymous 防重复消耗。",
"L4:候选输出与终态落库",
"L4: Persist & Structured Output",
2760,
180,
description="输出标准化候选坐标载荷与地球聚焦视角,或在有实证时落库终态。",
tools=["location_persist_outcome"],
params={"persist_terminal_statuses": True, "fly_to_target": True},
),
],
"edges": [
_edge("loc-e1", "l0_normalize", "l1_knowledge", "未标记终态", "Not terminal", "not_terminal"),
_edge("loc-e2", "l1_knowledge", "l3_geo_guardrail", "高置信度命中", "Verified site hit", "high_confidence_hit"),
_edge("loc-e3", "l1_knowledge", "l2_agent_research", "未命中/需核查", "Miss or unverified", "fallback_to_agent"),
_edge("loc-e4", "l2_agent_research", "l3_geo_guardrail", "提交候选", "Submitted", "always"),
_edge("loc-e5", "l3_geo_guardrail", "l4_persist_outcome", "校验完成", "Validated", "always"),
_edge("loc-e2", "l0_normalize", "l4_persist_outcome", "已有终态缓存", "Cached terminal", "on_terminal"),
_edge("loc-e3", "l1_knowledge", "l4_persist_outcome", "知识库命中", "L1 hit", "high_confidence_hit"),
_edge("loc-e4", "l1_knowledge", "l2_research_r1", "未命中进联网取证", "Miss -> L2 research", "fallback_to_agent"),
_edge("loc-e5", "l2_research_r1", "l2_judge_r1", "首轮证据就绪", "R1 evidence ready", "always"),
_edge("loc-e6", "l2_judge_r1", "l2_research_r2", "需定向补查", "Need followup", "on_field_equals", "decision=need_followup"),
_edge("loc-e7", "l2_research_r2", "l2_judge_r2", "补查证据就绪", "R2 evidence ready", "always"),
_edge("loc-e8", "l2_judge_r1", "l3_geocode", "J1 定位成功", "J1 located", "on_field_equals", "decision=located"),
_edge("loc-e9", "l2_judge_r2", "l3_geocode", "J2 定位成功", "J2 located", "on_field_equals", "decision=located"),
_edge("loc-e10", "l3_geocode", "l3_geo_guardrail", "送入硬护栏", "Verify geo", "always"),
_edge("loc-e11", "l2_judge_r1", "l3_geo_guardrail", "J1 终态/未定论", "J1 non-located", "on_field_equals", "decision=undisclosed,multi_site,planned,cloud_only,anonymous,unresolved"),
_edge("loc-e12", "l2_judge_r2", "l3_geo_guardrail", "J2 终态/未定论", "J2 non-located", "on_field_equals", "decision=undisclosed,multi_site,planned,cloud_only,anonymous,unresolved"),
_edge("loc-e13", "l3_geo_guardrail", "l4_persist_outcome", "输出结论", "Emit outcome", "always"),
],
},
},
@@ -638,7 +814,7 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [
"bindings": {
"enabled": True,
"surfaces": ["info_card", "multi_select", "copilot_quick"],
"entity_types": ["cable", "landing_point", "bgp", "vessel", "satellite", "global"],
"entity_types": ["cable", "landing_point", "bgp", "vessel", "aircraft", "gps_jamming_cell", "satellite", "global"],
"action_label": "多域兵棋推演",
"action_label_en": "Multi-Domain Wargame",
"icon": "hub",
@@ -654,7 +830,7 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [
"Isolated Domain Snapshots",
420,
140,
tools=["query_bgp_incidents", "query_cable_posture", "query_satellite_posture", "query_vessel_posture"],
tools=["query_bgp_incidents", "query_cable_posture", "query_satellite_posture", "query_vessel_posture", "query_aircraft_posture", "query_gps_jamming_posture"],
),
_node(
"wg_investigator",
@@ -664,9 +840,9 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [
800,
140,
prompt_key="incident.investigator.brief",
system_prompt="你是全球互联网与海缆基础设施取证参谋。严格区分 confirmed_facts、candidate_explanations、counter_evidence 与 open_gaps;无独立海缆告警证据时严禁将地理邻近推断为物理断缆。",
system_prompt="你是全球互联网与海缆基础设施取证参谋。严格区分 confirmed_facts、candidate_explanations、counter_evidence 与 open_gaps;无独立海缆告警证据时严禁将地理邻近推断为物理断缆。必须在 open_gaps 中列出当前情报盲区(blind_spots),任何新鲜度状态非 fresh 的域不得描述为“无事件”。",
prompt="结合内部多域快照与受控外部取证槽位,生成结构化事件研判 JSON 与地球高亮实体。",
tools=["query_bgp_incidents", "query_cable_posture", "query_satellite_posture", "query_vessel_posture", "web_search", "safe_web_fetch"],
tools=["query_bgp_incidents", "query_cable_posture", "query_satellite_posture", "query_vessel_posture", "query_aircraft_posture", "query_gps_jamming_posture", "web_search", "safe_web_fetch"],
thinking_enabled=True,
max_steps=3,
guardrails={"disallow_unverified_cable_cut": True},
@@ -884,6 +1060,109 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [
],
},
},
{
"workflow_id": "wargame.cable_protection",
"name": "海缆安全护卫兵棋工作流",
"name_en": "Subsea Cable Protection Wargame",
"category": "wargame",
"description": "综合海缆路径、走廊船舶徘徊、NGA 航行警告、BGP 路由与本体拓扑,严格区分待核查关联与独立证据支撑的依赖影响链。",
"description_en": "Correlates subsea cables, vessel loitering, NGA warnings, BGP events, and ontology topology to distinguish candidate correlations from corroborated dependency impact chains.",
"is_default": False,
"graph": {
"nodes": [
_node("cable_wg_trig", "trigger", "走廊告警入口", "Corridor Trigger", 40, 140),
_node(
"cable_wg_fetch",
"deterministic",
"读取海缆/船舶/NGA/BGP 与本体邻域",
"Fetch Cable, Vessel, NGA, BGP & Ontology",
380,
140,
tools=[
"query_cable_posture",
"query_vessel_posture",
"query_bgp_incidents",
"query_ontology_neighborhood",
"query_global_situational",
],
),
_node(
"cable_wg_analyst",
"llm_agent",
"证据分级与影响链研判",
"Evidence Tier & Impact Analysis",
720,
140,
system_prompt=(
"你是海缆安全护卫推演专家。规则:"
"1) 只有邻近船舶与同时段异常、缺少独立 NGA 航行警告或运营方/直接 BGP 断链证据时,严格定性为“待核查关联”,严禁断言因果;"
"2) 仅当存在独立 NGA 警告、运营方通告或直接 BGP 证据时才升级为“依赖影响”,并列出受影响国家、算力中心及备用海缆;"
"3) 必须明确列出 `blind_spots` 情报盲区;结尾附 <planet_scene> 输出 spatial_cards 与 overlays。"
),
prompt="结合多域证据输出海缆护卫推演结论、影响清单、盲区及空间卡片。",
thinking_enabled=True,
),
_node("cable_wg_out", "output", "推演结论与演播", "Briefing & Presentation", 1060, 140),
],
"edges": [
_edge("cw-e1", "cable_wg_trig", "cable_wg_fetch"),
_edge("cw-e2", "cable_wg_fetch", "cable_wg_analyst"),
_edge("cw-e3", "cable_wg_analyst", "cable_wg_out"),
],
},
},
{
"workflow_id": "wargame.air_sea_em",
"name": "空海电磁联合态势工作流",
"name_en": "Air-Sea Electromagnetic Joint Posture",
"category": "wargame",
"description": "聚合空域军机/紧急应答机、GPS/GNSS 干扰热区、咽喉要道舰艇、自然灾害与分级新闻,生成无因果越界的多域空间对比卡片与盲区简报。",
"description_en": "Aggregates military/emergency aircraft, GNSS jamming cells, chokepoint vessels, disasters, and tiered news into non-causal multi-domain spatial cards and blind-spot briefings.",
"is_default": False,
"graph": {
"nodes": [
_node("em_wg_trig", "trigger", "空海电磁网格触发", "H3 Convergence Trigger", 40, 140),
_node(
"em_wg_fetch",
"deterministic",
"采集空海电磁与本体上下文",
"Collect Air-Sea-EM & Ontology Context",
380,
140,
tools=[
"query_aircraft_posture",
"query_gps_jamming_posture",
"query_vessel_posture",
"query_disaster_posture",
"query_recent_earth_news",
"query_global_situational",
],
),
_node(
"em_wg_analyst",
"llm_agent",
"无因果约束联合简报生成",
"Non-Causal Joint Briefing",
720,
140,
system_prompt=(
"你是空海电磁联合态势推演专家。必须严格遵守:"
"1) 多域并存默认定性为“待核查关联”,严禁将空间巧合写成“导致/引发/袭击”;"
"2) 必须显式列出所有非 fresh 数据域作为情报盲区(`blind_spots`),非 fresh 域不得称为无事件;"
"3) 新闻引用按可信度分级排序并标注国家背景;结尾输出含 spatial_cards 与 overlays 的 <planet_scene>。"
),
prompt="汇总区域多域目标与盲区,输出对比卡片与空海电磁简报。",
thinking_enabled=True,
),
_node("em_wg_out", "output", "态势输出", "Posture Output", 1060, 140),
],
"edges": [
_edge("ew-e1", "em_wg_trig", "em_wg_fetch"),
_edge("ew-e2", "em_wg_fetch", "em_wg_analyst"),
_edge("ew-e3", "em_wg_analyst", "em_wg_out"),
],
},
},
]
_BUILTIN_BY_ID: dict[str, dict[str, Any]] = {
@@ -983,6 +1262,100 @@ def _upgrade_untouched_legacy_positions(row: AIWorkflow, spec: dict[str, Any]) -
return True
_LEGACY_LOC_NODE_IDS = frozenset(
{"l0_normalize", "l1_knowledge", "l2_agent_research", "l3_geo_guardrail", "l4_persist_outcome"}
)
def _upgrade_untouched_location_v1(row: AIWorkflow, spec: dict[str, Any]) -> bool:
"""Upgrade retired 5-node `location.resolve_unknown` graphs (and legacy 5-node drafts) to the 9-node DAG."""
if row.workflow_id != "location.resolve_unknown":
return False
changed = False
graph = row.published_graph if isinstance(row.published_graph, dict) else None
if graph:
node_ids = {
str(n.get("id") or "")
for n in (graph.get("nodes") or [])
if isinstance(n, dict) and n.get("id")
}
if node_ids == _LEGACY_LOC_NODE_IDS:
row.published_graph = copy.deepcopy(spec["graph"])
changed = True
draft = row.draft_graph if isinstance(row.draft_graph, dict) else None
if draft:
draft_ids = {
str(n.get("id") or "")
for n in (draft.get("nodes") or [])
if isinstance(n, dict) and n.get("id")
}
if draft_ids == _LEGACY_LOC_NODE_IDS:
row.draft_graph = None
changed = True
return changed
_PREV_LOC_JUDGE_PROMPTS: dict[str, str] = {
"l2_judge_r1": (
"你是基础设施物理位置核查分析师。严格基于输入的 evidence_items(编号 E1..En)和 location_target 进行判断,严禁猜测或编造坐标/URL!\n"
"规则:\n"
"1) 只要证据已明确指出物理所在城市/园区(如数据中心运营商页面、政府规划/新闻稿、HPC 官网),直接设 decision='located' 并填写 city/country(英文国名)/facility_name/address 及引用的 evidence_ids;无需为追门牌号拖延。\n"
"2) 若发现重要线索但还缺关键城市名或正文细节,设 decision='need_followup',给出最多 2 条精准英文 followup_queries 或需全文抓取的 fetch_urls。\n"
"3) 若多条权威证据确认物理机房国与源登记国(总部国)不同,country 填实证物理部署国并在 country_override_reason 说明依据。\n"
"4) 仅当权威证据明确指出未披露、多地分布式、规划中、纯云端无实体时,才选对应终态(undisclosed/multi_site/planned/cloud_only)。"
),
"l2_judge_r2": (
"你是基础设施物理位置终判分析师。严格依据两轮汇总的 evidence_items(E1..En)给出最终判定,禁止继续追问!\n"
"若证据支持某城市或园区,请设 decision='located' 并写明 city、country(英文)、facility_name、evidence_ids 与 confidence;"
"若跨国部署,填写 country_override_reason;若证据仍不足或明确未披露,输出 unresolved 或对应终态,并在 reasoning 说明具体缺口。"
),
}
def _upgrade_untouched_location_judge_prompts(row: AIWorkflow, spec: dict[str, Any]) -> bool:
"""Update untouched stock `l2_judge_r1` / `l2_judge_r2` prompts while preserving user edits."""
if row.workflow_id != "location.resolve_unknown":
return False
target_prompts = {
str(n.get("id") or ""): str(n.get("system_prompt") or "")
for n in spec.get("graph", {}).get("nodes", [])
if isinstance(n, dict) and n.get("id") in _PREV_LOC_JUDGE_PROMPTS
}
if len(target_prompts) != len(_PREV_LOC_JUDGE_PROMPTS):
return False
def _patch_graph(raw_graph: Any) -> tuple[dict[str, Any] | None, bool]:
if not isinstance(raw_graph, dict):
return None, False
nodes = raw_graph.get("nodes")
if not isinstance(nodes, list):
return None, False
cloned = copy.deepcopy(raw_graph)
graph_changed = False
for node in cloned.get("nodes", []):
if not isinstance(node, dict):
continue
nid = str(node.get("id") or "")
if nid not in _PREV_LOC_JUDGE_PROMPTS:
continue
current_prompt = str(node.get("system_prompt") or "")
if current_prompt == _PREV_LOC_JUDGE_PROMPTS[nid]:
node["system_prompt"] = target_prompts[nid]
graph_changed = True
return (cloned, True) if graph_changed else (None, False)
changed = False
new_pub, pub_changed = _patch_graph(row.published_graph)
if pub_changed and new_pub is not None:
row.published_graph = new_pub
changed = True
new_draft, draft_changed = _patch_graph(row.draft_graph)
if draft_changed and new_draft is not None:
row.draft_graph = new_draft
changed = True
return changed
async def ensure_builtin_workflows(db: AsyncSession) -> None:
"""Idempotently seed all 9 built-in workflows into `ai_workflows`."""
if not hasattr(db, "execute"):
@@ -1000,6 +1373,10 @@ async def ensure_builtin_workflows(db: AsyncSession) -> None:
existing_row = existing_by_id[wf_id]
if _upgrade_untouched_legacy_positions(existing_row, spec):
changed = True
if _upgrade_untouched_location_v1(existing_row, spec):
changed = True
if _upgrade_untouched_location_judge_prompts(existing_row, spec):
changed = True
if not existing_row.bindings and spec.get("bindings"):
existing_row.bindings = default_bindings
changed = True
+51 -3
View File
@@ -45,9 +45,13 @@ from app.services.ai.spatial_domain_agent import (
investigate_spatial_domain,
)
from app.services.ai.thinking_sanitizer import merge_usage_dicts
from app.services.ai.tool_registry import TimeBasis, query_bgp_incidents_tool, query_compute_posture_tool
from app.services.ai.tool_registry import TimeBasis, query_compute_posture_tool
from app.services.ai_client import AIProviderClient
from app.services.compute_catalog import PARTICIPANTS
from app.services.compute_lineage import (
build_revision_change_context,
is_revision_question,
)
logger = get_logger(__name__, service="ai_workflow")
@@ -648,6 +652,9 @@ class ViewSpec(BaseModel):
is_drill: bool = False
time_basis: TimeBasis = "retrospective"
cutoff_at: str | None = None
publish_id: str | None = None
mode: str | None = None
focus_year: int | None = None
replay_supported: bool = True
replay_status: Literal["frozen", "incomplete_snapshot"] = "frozen"
replay_notice: str | None = None
@@ -881,6 +888,8 @@ def classify_turn_intent(
"incident_focus": focus,
"time_basis": time_basis,
"cutoff_at": cutoff_at,
"publish_id": ctx.get("publish_id"),
"as_of": ctx.get("as_of"),
"include_drill": include_drill,
"visible_layers": visible_layers,
}
@@ -916,6 +925,8 @@ def classify_turn_intent(
"incident_focus": "overview",
"time_basis": time_basis,
"cutoff_at": cutoff_at,
"publish_id": ctx.get("publish_id"),
"as_of": ctx.get("as_of"),
"include_drill": include_drill,
"visible_layers": visible_layers,
}
@@ -959,7 +970,7 @@ def classify_turn_intent(
elif any(kw in q for kw in ("趋势", "走势", "历年", "演变", "走廊", "2020", "trend", "trajectory")):
workflow_id = "compute.compare"
view_preset = "trend"
elif any(kw in q for kw in ("为什么", "成因", "归因", "稀释", "回落", "剪刀差", "创新", "东数西算", "枢纽", "解释", "why", "explain")):
elif any(kw in q for kw in ("为什么", "成因", "归因", "稀释", "回落", "剪刀差", "创新", "东数西算", "枢纽", "解释", "修订", "改了", "变化", "重述", "why", "explain", "revised")):
workflow_id = "compute.explain_gap"
view_preset = "causal"
elif metric_switched or any(kw in q for kw in ("只看", "切换", "改看", "switch")):
@@ -982,6 +993,8 @@ def classify_turn_intent(
"incident_focus": "overview",
"time_basis": time_basis,
"cutoff_at": cutoff_at,
"publish_id": ctx.get("publish_id"),
"as_of": ctx.get("as_of"),
"include_drill": include_drill,
"visible_layers": visible_layers,
}
@@ -1015,6 +1028,7 @@ def compile_compute_view_spec(
series: dict[str, Any],
posture: dict[str, Any],
preset: ViewPreset = "default",
focus_year: int | None = None,
enable_hubs: bool = False,
auto_play: bool = False,
replay_supported: bool = True,
@@ -1025,6 +1039,10 @@ def compile_compute_view_spec(
evidence_map = series.get("evidence") or {}
time_basis: TimeBasis = series.get("time_basis") or "retrospective"
cutoff_at = series.get("cutoff_at")
effective_publish_id = series.get("publish_id") or series.get("version") or posture.get("publish_id")
if series.get("snapshot_unavailable"):
replay_supported = False
replay_notice = replay_notice or series.get("notice")
metric_zh, metric_en, default_unit = _METRIC_LABELS.get(mode, ("算力指标", "Compute Metric", "%"))
unit = str(series.get("unit") or default_unit)
effective_replay_notice = replay_notice or (_INCOMPLETE_COMPUTE_REPLAY_NOTICE if not replay_supported else None)
@@ -1036,6 +1054,7 @@ def compile_compute_view_spec(
if any(r.get("values", {}).get(c) is not None for c in codes)
]
latest_year = int(observed_rows[-1]["year"]) if observed_rows else (years[-1] if years else None)
effective_focus_year = int(focus_year) if focus_year is not None else latest_year
matrix_rows: list[dict[str, Any]] = []
max_numeric = 0.0
@@ -1325,6 +1344,9 @@ def compile_compute_view_spec(
is_drill=False,
time_basis=time_basis,
cutoff_at=cutoff_at,
publish_id=effective_publish_id,
mode=mode,
focus_year=effective_focus_year,
replay_supported=replay_supported,
replay_status="frozen" if replay_supported else "incomplete_snapshot",
replay_notice=effective_replay_notice,
@@ -1335,7 +1357,7 @@ def compile_compute_view_spec(
domain="compute",
highlight_entities=highlight_ids,
compute_mode=mode,
focus_year=latest_year,
focus_year=effective_focus_year,
enable_national_hubs=enable_hubs,
presentation_key="compute-posture-cn-us",
auto_play_presentation=auto_play,
@@ -1692,6 +1714,10 @@ async def execute_session_turn(
for k, v in context_override.items():
if v is not None:
merged_ctx[k] = v
if context_override.get("publish_id") and not context_override.get("as_of"):
merged_ctx["as_of"] = None
elif context_override.get("as_of") and not context_override.get("publish_id"):
merged_ctx["publish_id"] = None
routed = classify_turn_intent(question, merged_ctx)
workflow_id = routed["workflow_id"]
@@ -1752,6 +1778,8 @@ async def execute_session_turn(
domain = routed["domain"]
time_basis: TimeBasis = routed["time_basis"]
cutoff_at: str | None = routed["cutoff_at"]
publish_id: str | None = routed.get("publish_id")
as_of: str | None = routed.get("as_of")
run_record = WorkflowRun(
id=run_id,
@@ -1813,11 +1841,14 @@ async def execute_session_turn(
and domain == merged_ctx.get("domain")
and time_basis == (merged_ctx.get("time_basis") or time_basis)
and cutoff_at == merged_ctx.get("cutoff_at")
and publish_id == merged_ctx.get("publish_id")
and as_of == merged_ctx.get("as_of")
and (
domain != "compute"
or (
routed["selected_codes"] == (merged_ctx.get("selected_codes") or routed["selected_codes"])
and routed["mode"] == (merged_ctx.get("mode") or routed["mode"])
and routed["focus_year"] == merged_ctx.get("focus_year")
)
)
)
@@ -1967,8 +1998,17 @@ async def execute_session_turn(
mode=mode,
time_basis=time_basis,
cutoff_at=cutoff_at,
as_of=as_of,
publish_id=publish_id,
)
_check_cancelled()
revision_context: dict[str, Any] | None = None
if is_revision_question(question) and not series.get("snapshot_unavailable"):
revision_context = await build_revision_change_context(
db,
publish_id=series.get("publish_id") or publish_id,
redact=(access.tier != "admin"),
)
posture = await generate_or_get_compute_posture(
db,
countries=codes,
@@ -1996,8 +2036,11 @@ async def execute_session_turn(
question=question,
time_basis=time_basis,
cutoff_at=cutoff_at,
publish_id=publish_id,
as_of=as_of,
series_override=series,
posture_override=posture,
revision_context=revision_context,
ai_client=ai_client if (use_paid_llm and access.can_use_paid_llm) else None,
cancel_event=handle.cancel_event,
)
@@ -2012,6 +2055,7 @@ async def execute_session_turn(
series=series,
posture=posture,
preset=preset,
focus_year=routed["focus_year"],
enable_hubs=enable_hubs,
auto_play=routed["auto_play_presentation"],
)
@@ -2112,6 +2156,8 @@ async def execute_session_turn(
"visible_layers": routed.get("visible_layers") or {},
"time_basis": time_basis,
"cutoff_at": cutoff_at,
"publish_id": publish_id,
"as_of": as_of,
"include_drill": routed["include_drill"],
"active_result_id": subject_key,
"active_revision": revision,
@@ -2157,6 +2203,8 @@ async def execute_session_turn(
"generation_mode": generation_mode,
"time_basis": time_basis,
"cutoff_at": cutoff_at,
"publish_id": view_spec.publish_id,
"as_of": as_of,
"context_state": next_context,
"reply": {
"answer_markdown": answer_md,
@@ -0,0 +1,430 @@
"""Multi-source aircraft state merge, downsampled 24h track logging, pruning, and health updates."""
from __future__ import annotations
from datetime import UTC, datetime, timedelta
import math
from typing import Any
from sqlalchemy import delete, func, select
from sqlalchemy.dialects.postgresql import insert as pg_insert
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.logging import get_logger
from app.models.aircraft import (
ADSBSourceHealth,
AircraftCurrentState,
AircraftPosition,
AircraftStatic,
)
from app.services.aircraft_types import classify_aircraft, normalize_icao24
logger = get_logger(__name__, service="aircraft_aggregation")
DEFAULT_CURRENT_STALE_MINUTES = 15
DEFAULT_POSITION_RETENTION_HOURS = 24
TRACK_MIN_INTERVAL_SECONDS = 30.0
TRACK_MIN_HEADING_DELTA_DEG = 10.0
TRACK_MIN_ALTITUDE_DELTA_M = 300.0
SQL_BATCH_SIZE = 500
def coerce_utc_datetime(value: Any, fallback: datetime | None = None) -> datetime:
"""Convert Unix seconds, ISO strings, or naive datetimes to aware UTC datetimes."""
if isinstance(value, datetime):
return value.astimezone(UTC) if value.tzinfo else value.replace(tzinfo=UTC)
if isinstance(value, (int, float)) and math.isfinite(float(value)):
return datetime.fromtimestamp(float(value), tz=UTC)
if isinstance(value, str):
raw = value.strip()
if raw:
try:
return datetime.fromtimestamp(float(raw), tz=UTC)
except ValueError:
pass
try:
parsed = datetime.fromisoformat(raw.replace("Z", "+00:00"))
return parsed.astimezone(UTC) if parsed.tzinfo else parsed.replace(tzinfo=UTC)
except ValueError:
pass
return fallback or datetime.now(UTC)
def wrapped_angle_diff_deg(a: float | None, b: float | None) -> float:
"""Smallest angular difference on a 360-degree circle."""
if a is None or b is None or not (math.isfinite(a) and math.isfinite(b)):
return 0.0
diff = abs(float(a) - float(b)) % 360.0
return 360.0 - diff if diff > 180.0 else diff
def should_record_aircraft_track_point(
previous: dict[str, Any] | None,
*,
observed_at: datetime,
altitude_m: float | None,
track_deg: float | None,
) -> bool:
"""Return True if a track sample exceeds 30s, 10 deg heading change, or 300m altitude delta."""
if previous is None:
return True
prev_time = coerce_utc_datetime(previous.get("observed_at"))
if abs((observed_at - prev_time).total_seconds()) >= TRACK_MIN_INTERVAL_SECONDS:
return True
if wrapped_angle_diff_deg(track_deg, previous.get("track_deg")) > TRACK_MIN_HEADING_DELTA_DEG:
return True
prev_alt = previous.get("altitude_m")
if altitude_m is not None and prev_alt is not None:
if abs(float(altitude_m) - float(prev_alt)) > TRACK_MIN_ALTITUDE_DELTA_M:
return True
return False
def _source_priority(source: str) -> int:
normalized = str(source or "").strip().lower()
if "adsb_lol" in normalized:
return 2
return 1
def _should_replace_existing(
existing: dict[str, Any],
incoming: dict[str, Any],
) -> bool:
ext_obs = coerce_utc_datetime(existing["observed_at"])
inc_obs = coerce_utc_datetime(incoming["observed_at"])
if inc_obs > ext_obs:
return True
if inc_obs < ext_obs:
return False
return _source_priority(incoming["source"]) >= _source_priority(existing["source"])
async def _load_static_metadata_map(
db: AsyncSession,
icao24s: list[str],
) -> dict[str, AircraftStatic]:
if not icao24s:
return {}
mapping: dict[str, AircraftStatic] = {}
for offset in range(0, len(icao24s), SQL_BATCH_SIZE):
chunk = icao24s[offset : offset + SQL_BATCH_SIZE]
res = await db.execute(select(AircraftStatic).where(AircraftStatic.icao24.in_(chunk)))
for row in res.scalars().all():
mapping[row.icao24] = row
return mapping
async def _load_existing_current_map(
db: AsyncSession,
icao24s: list[str],
) -> dict[str, dict[str, Any]]:
if not icao24s:
return {}
mapping: dict[str, dict[str, Any]] = {}
for offset in range(0, len(icao24s), SQL_BATCH_SIZE):
chunk = icao24s[offset : offset + SQL_BATCH_SIZE]
res = await db.execute(
select(AircraftCurrentState).where(AircraftCurrentState.icao24.in_(chunk))
)
for row in res.scalars().all():
mapping[row.icao24] = {
"observed_at": coerce_utc_datetime(row.observed_at),
"source": row.source,
"is_military": bool(row.is_military),
"category": row.category,
}
return mapping
async def _load_latest_position_map(
db: AsyncSession,
icao24s: list[str],
) -> dict[str, dict[str, Any]]:
"""Fetch the most recent aircraft_position sample per icao24 for downsampling checks."""
if not icao24s:
return {}
mapping: dict[str, dict[str, Any]] = {}
for offset in range(0, len(icao24s), SQL_BATCH_SIZE):
chunk = icao24s[offset : offset + SQL_BATCH_SIZE]
subq = (
select(
AircraftPosition.icao24,
func.max(AircraftPosition.observed_at).label("max_obs"),
)
.where(AircraftPosition.icao24.in_(chunk))
.group_by(AircraftPosition.icao24)
.subquery()
)
stmt = select(AircraftPosition).join(
subq,
(AircraftPosition.icao24 == subq.c.icao24)
& (AircraftPosition.observed_at == subq.c.max_obs),
)
res = await db.execute(stmt)
for row in res.scalars().all():
mapping[row.icao24] = {
"observed_at": coerce_utc_datetime(row.observed_at),
"altitude_m": row.altitude_m,
"track_deg": row.track_deg,
}
return mapping
async def upsert_aircraft_observations(
db: AsyncSession,
observations: list[dict[str, Any]],
*,
default_source: str,
ingested_at: datetime | None = None,
) -> dict[str, int]:
"""Merge multi-source aircraft observations into aircraft_current_state and downsampled aircraft_position."""
if not observations:
return {"states_upserted": 0, "positions_inserted": 0}
now = coerce_utc_datetime(ingested_at) if ingested_at else datetime.now(UTC)
deduped: dict[str, dict[str, Any]] = {}
for raw in observations:
icao24 = normalize_icao24(raw.get("icao24"))
lat = raw.get("lat")
lon = raw.get("lon")
if len(icao24) != 6 or lat is None or lon is None:
continue
try:
lat_f = float(lat)
lon_f = float(lon)
except (TypeError, ValueError):
continue
if not (-90.0 <= lat_f <= 90.0 and -180.0 <= lon_f <= 180.0):
continue
src = str(raw.get("source") or default_source).strip() or default_source
obs_at = coerce_utc_datetime(raw.get("observed_at"), fallback=now)
candidate = {
"icao24": icao24,
"callsign": (str(raw.get("callsign") or "").strip().upper()[:16] or None),
"lat": lat_f,
"lon": lon_f,
"baro_altitude_m": raw.get("baro_altitude_m"),
"geo_altitude_m": raw.get("geo_altitude_m"),
"ground_speed_ms": raw.get("ground_speed_ms"),
"track_deg": raw.get("track_deg"),
"vertical_rate_ms": raw.get("vertical_rate_ms"),
"squawk": (str(raw.get("squawk") or "").strip()[:8] or None),
"on_ground": bool(raw.get("on_ground", False)),
"adsb_category": raw.get("adsb_category"),
"aircraft_type": raw.get("aircraft_type"),
"db_flags": raw.get("db_flags"),
"source_is_military": bool(raw.get("source_is_military", False)),
"source": src,
"observed_at": obs_at,
}
prior = deduped.get(icao24)
if prior is None:
deduped[icao24] = candidate
else:
if _should_replace_existing(prior, candidate):
candidate["source_is_military"] = bool(
candidate["source_is_military"] or prior["source_is_military"]
)
deduped[icao24] = candidate
else:
prior["source_is_military"] = bool(
prior["source_is_military"] or candidate["source_is_military"]
)
if not deduped:
return {"states_upserted": 0, "positions_inserted": 0}
icao_list = list(deduped.keys())
static_map = await _load_static_metadata_map(db, icao_list)
existing_map = await _load_existing_current_map(db, icao_list)
latest_pos_map = await _load_latest_position_map(db, icao_list)
upsert_rows: list[dict[str, Any]] = []
position_rows: list[dict[str, Any]] = []
for icao24, item in deduped.items():
static_rec = static_map.get(icao24)
existing = existing_map.get(icao24)
preserved_mil = bool(existing and existing.get("is_military"))
cls = classify_aircraft(
icao24=icao24,
callsign=item["callsign"],
squawk=item["squawk"],
aircraft_type=item.get("aircraft_type") or (static_rec.aircraft_type if static_rec else None),
adsb_category=item.get("adsb_category"),
db_flags=item.get("db_flags"),
static_is_military=bool(static_rec and static_rec.is_military) or preserved_mil,
static_category=static_rec.category if static_rec else None,
source_is_military_feed=bool(item.get("source_is_military")),
)
# Even if DB has newer observed_at from another source, never lose military marker from adsb.lol.
if existing and not _should_replace_existing(existing, item):
continue
row_payload = {
"icao24": icao24,
"callsign": item["callsign"],
"lat": item["lat"],
"lon": item["lon"],
"baro_altitude_m": item["baro_altitude_m"],
"geo_altitude_m": item["geo_altitude_m"],
"ground_speed_ms": item["ground_speed_ms"],
"track_deg": item["track_deg"],
"vertical_rate_ms": item["vertical_rate_ms"],
"squawk": item["squawk"],
"on_ground": item["on_ground"],
"category": str(cls["category"]),
"is_military": bool(cls["is_military"]),
"is_emergency": bool(cls["is_emergency"]),
"emergency_code": cls["emergency_code"],
"source": item["source"],
"observed_at": item["observed_at"],
"ingested_at": now,
}
upsert_rows.append(row_payload)
alt_m = (
item["geo_altitude_m"]
if item["geo_altitude_m"] is not None
else item["baro_altitude_m"]
)
prev_pos = latest_pos_map.get(icao24)
if should_record_aircraft_track_point(
prev_pos,
observed_at=item["observed_at"],
altitude_m=alt_m,
track_deg=item["track_deg"],
):
position_rows.append(
{
"icao24": icao24,
"lat": item["lat"],
"lon": item["lon"],
"altitude_m": alt_m,
"ground_speed_ms": item["ground_speed_ms"],
"track_deg": item["track_deg"],
"observed_at": item["observed_at"],
}
)
dialect = getattr(getattr(db.get_bind(), "dialect", None), "name", "sqlite")
for offset in range(0, len(upsert_rows), SQL_BATCH_SIZE):
batch = upsert_rows[offset : offset + SQL_BATCH_SIZE]
if dialect == "postgresql":
stmt = pg_insert(AircraftCurrentState).values(batch)
stmt = stmt.on_conflict_do_update(
index_elements=[AircraftCurrentState.icao24],
set_={
"callsign": stmt.excluded.callsign,
"lat": stmt.excluded.lat,
"lon": stmt.excluded.lon,
"baro_altitude_m": stmt.excluded.baro_altitude_m,
"geo_altitude_m": stmt.excluded.geo_altitude_m,
"ground_speed_ms": stmt.excluded.ground_speed_ms,
"track_deg": stmt.excluded.track_deg,
"vertical_rate_ms": stmt.excluded.vertical_rate_ms,
"squawk": stmt.excluded.squawk,
"on_ground": stmt.excluded.on_ground,
"category": stmt.excluded.category,
"is_military": stmt.excluded.is_military,
"is_emergency": stmt.excluded.is_emergency,
"emergency_code": stmt.excluded.emergency_code,
"source": stmt.excluded.source,
"observed_at": stmt.excluded.observed_at,
"ingested_at": stmt.excluded.ingested_at,
},
)
await db.execute(stmt)
else:
stmt_sq = sqlite_insert(AircraftCurrentState).values(batch)
stmt_sq = stmt_sq.on_conflict_do_update(
index_elements=[AircraftCurrentState.icao24],
set_={
"callsign": stmt_sq.excluded.callsign,
"lat": stmt_sq.excluded.lat,
"lon": stmt_sq.excluded.lon,
"baro_altitude_m": stmt_sq.excluded.baro_altitude_m,
"geo_altitude_m": stmt_sq.excluded.geo_altitude_m,
"ground_speed_ms": stmt_sq.excluded.ground_speed_ms,
"track_deg": stmt_sq.excluded.track_deg,
"vertical_rate_ms": stmt_sq.excluded.vertical_rate_ms,
"squawk": stmt_sq.excluded.squawk,
"on_ground": stmt_sq.excluded.on_ground,
"category": stmt_sq.excluded.category,
"is_military": stmt_sq.excluded.is_military,
"is_emergency": stmt_sq.excluded.is_emergency,
"emergency_code": stmt_sq.excluded.emergency_code,
"source": stmt_sq.excluded.source,
"observed_at": stmt_sq.excluded.observed_at,
"ingested_at": stmt_sq.excluded.ingested_at,
},
)
await db.execute(stmt_sq)
for offset in range(0, len(position_rows), SQL_BATCH_SIZE):
batch = position_rows[offset : offset + SQL_BATCH_SIZE]
await db.execute(AircraftPosition.__table__.insert().values(batch))
return {
"states_upserted": len(upsert_rows),
"positions_inserted": len(position_rows),
}
async def prune_aircraft_tables(
db: AsyncSession,
*,
current_stale_minutes: int = DEFAULT_CURRENT_STALE_MINUTES,
position_retention_hours: int = DEFAULT_POSITION_RETENTION_HOURS,
now: datetime | None = None,
) -> dict[str, int]:
"""Delete expired current aircraft (>15m) and expired track history (>24h default)."""
ref = coerce_utc_datetime(now) if now else datetime.now(UTC)
current_cutoff = ref - timedelta(minutes=max(1, int(current_stale_minutes)))
pos_cutoff = ref - timedelta(hours=max(1, int(position_retention_hours)))
curr_res = await db.execute(
delete(AircraftCurrentState).where(AircraftCurrentState.observed_at < current_cutoff)
)
pos_res = await db.execute(
delete(AircraftPosition).where(AircraftPosition.observed_at < pos_cutoff)
)
return {
"current_deleted": int(curr_res.rowcount or 0),
"positions_deleted": int(pos_res.rowcount or 0),
}
async def update_adsb_source_health(
db: AsyncSession,
*,
source: str,
connection_state: str,
active_count: int = 0,
last_success_at: datetime | None = None,
last_error: str | None = None,
cooldown_until: datetime | None = None,
clear_cooldown: bool = False,
) -> ADSBSourceHealth:
"""Upsert runtime ADS-B health status and optional cooldown timestamp."""
now = datetime.now(UTC)
record = await db.get(ADSBSourceHealth, source)
if record is None:
record = ADSBSourceHealth(source=source)
db.add(record)
record.connection_state = connection_state
record.active_count = max(0, int(active_count))
if last_success_at is not None:
record.last_success_at = coerce_utc_datetime(last_success_at)
record.last_error = last_error[:500] if last_error else None
if clear_cooldown:
record.cooldown_until = None
elif cooldown_until is not None:
record.cooldown_until = coerce_utc_datetime(cooldown_until)
record.updated_at = now
return record
+319
View File
@@ -0,0 +1,319 @@
"""Open ICAO24 aircraft registry downloader, parser, and offline cache manager (Source 42)."""
from __future__ import annotations
import csv
from datetime import UTC, datetime
import gzip
import io
import os
from pathlib import Path
from typing import Any
import httpx
from sqlalchemy import func, select
from sqlalchemy.dialects.postgresql import insert as pg_insert
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.config import ROOT_DIR
from app.core.data_sources import get_data_sources_config
from app.core.logging import get_logger
from app.models.aircraft import AircraftStatic
from app.services.aircraft_types import classify_aircraft, normalize_icao24
logger = get_logger(__name__, service="aircraft_registry")
MAX_REGISTRY_BYTES = 200 * 1024 * 1024 # safety ceiling for remote CSV/CSV.GZ downloads
UPSERT_BATCH_SIZE = 1000
def get_aircraft_registry_cache_dir(configured_dir: str | None = None) -> Path:
"""Resolve configurable local directory for cached ICAO24 registry CSVs."""
raw = str(configured_dir or os.getenv("PLANET_AIRCRAFT_REGISTRY_DIR") or "").strip()
if raw:
path = Path(raw)
else:
path = ROOT_DIR / "data" / "aircraft_registry"
return path
def _clean_text(value: Any, max_len: int) -> str | None:
text = str(value or "").strip()
if not text or text.lower() in {"nan", "null", "none", "n/a"}:
return None
return text[:max_len]
def _pick_header(fieldnames: list[str], *candidates: str) -> str | None:
lowered = {name.strip().lower(): name for name in fieldnames if name}
for cand in candidates:
matched = lowered.get(cand.lower())
if matched:
return matched
return None
def parse_aircraft_registry_csv(text: str, *, max_rows: int | None = None) -> list[dict[str, Any]]:
"""Parse OpenSky aircraft database CSV or tar1090 semicolon CSV into normalized records."""
cleaned = text.lstrip("\ufeff")
if not cleaned.strip():
return []
first_line = next((line for line in cleaned.splitlines() if line.strip()), "")
delimiter = ";" if first_line.count(";") > first_line.count(",") else ","
records: list[dict[str, Any]] = []
if delimiter == ";" and "icao" not in first_line.lower():
# Headerless tar1090 CSV format: icao24;reg;typecode;flags;description;year;...
reader = csv.reader(io.StringIO(cleaned), delimiter=";")
for row in reader:
if not row or len(row) < 3:
continue
icao24 = normalize_icao24(row[0])
if len(icao24) != 6:
continue
reg = _clean_text(row[1] if len(row) > 1 else None, 32)
typecode = _clean_text(row[2] if len(row) > 2 else None, 16)
flags_raw = row[3].strip() if len(row) > 3 else ""
try:
db_flags = int(flags_raw) if flags_raw else 0
except ValueError:
db_flags = 0
desc = _clean_text(row[4] if len(row) > 4 else None, 128)
cls = classify_aircraft(icao24=icao24, aircraft_type=typecode, db_flags=db_flags)
records.append(
{
"icao24": icao24,
"registration": reg,
"aircraft_type": typecode,
"type_description": desc,
"operator": None,
"owner": None,
"origin_country": None,
"category": cls["category"],
"is_military": bool(cls["is_military"]),
"source": "aircraft_registry",
}
)
if max_rows is not None and len(records) >= max_rows:
break
return records
dict_reader = csv.DictReader(io.StringIO(cleaned), delimiter=delimiter)
fieldnames = list(dict_reader.fieldnames or [])
if not fieldnames:
return []
col_icao = _pick_header(fieldnames, "icao24", "icao", "hex")
if not col_icao:
return []
col_reg = _pick_header(fieldnames, "registration", "reg")
col_type = _pick_header(fieldnames, "typecode", "aircraft_type", "icaoaircrafttype", "t")
col_desc = _pick_header(fieldnames, "model", "type_description", "desc", "categorydescription")
col_op = _pick_header(fieldnames, "operator", "operatoricao", "operatorcallsign", "ownop")
col_owner = _pick_header(fieldnames, "owner", "registeredowners")
col_country = _pick_header(fieldnames, "country", "origin_country")
col_flags = _pick_header(fieldnames, "dbflags", "flags", "mil")
for row in dict_reader:
icao24 = normalize_icao24(row.get(col_icao))
if len(icao24) != 6:
continue
typecode = _clean_text(row.get(col_type) if col_type else None, 16)
raw_flags = str(row.get(col_flags) or "").strip() if col_flags else ""
try:
db_flags = int(raw_flags) if raw_flags else 0
except ValueError:
db_flags = 1 if raw_flags.lower() in {"true", "yes", "mil", "military"} else 0
cls = classify_aircraft(icao24=icao24, aircraft_type=typecode, db_flags=db_flags)
records.append(
{
"icao24": icao24,
"registration": _clean_text(row.get(col_reg) if col_reg else None, 32),
"aircraft_type": typecode,
"type_description": _clean_text(row.get(col_desc) if col_desc else None, 128),
"operator": _clean_text(row.get(col_op) if col_op else None, 128),
"owner": _clean_text(row.get(col_owner) if col_owner else None, 128),
"origin_country": _clean_text(row.get(col_country) if col_country else None, 64),
"category": cls["category"],
"is_military": bool(cls["is_military"]),
"source": "aircraft_registry",
}
)
if max_rows is not None and len(records) >= max_rows:
break
return records
def decode_registry_payload(raw_bytes: bytes, source_url: str = "") -> str:
"""Decompress gzipped CSV when applicable and decode UTF-8 safely."""
if source_url.lower().endswith(".gz") or raw_bytes[:2] == b"\x1f\x8b":
raw_bytes = gzip.decompress(raw_bytes)
return raw_bytes.decode("utf-8", errors="replace")
async def upsert_aircraft_static_records(
db: AsyncSession,
records: list[dict[str, Any]],
) -> int:
"""Upsert parsed aircraft_static metadata rows in batches."""
if not records:
return 0
now = datetime.now(UTC)
dialect = getattr(getattr(db.get_bind(), "dialect", None), "name", "sqlite")
written = 0
for offset in range(0, len(records), UPSERT_BATCH_SIZE):
batch = []
for item in records[offset : offset + UPSERT_BATCH_SIZE]:
batch.append(
{
"icao24": item["icao24"],
"registration": item.get("registration"),
"aircraft_type": item.get("aircraft_type"),
"type_description": item.get("type_description"),
"operator": item.get("operator"),
"owner": item.get("owner"),
"origin_country": item.get("origin_country"),
"category": item.get("category") or "other",
"is_military": bool(item.get("is_military", False)),
"source": item.get("source") or "aircraft_registry",
"updated_at": now,
}
)
if not batch:
continue
if dialect == "postgresql":
stmt = pg_insert(AircraftStatic).values(batch)
stmt = stmt.on_conflict_do_update(
index_elements=[AircraftStatic.icao24],
set_={
"registration": stmt.excluded.registration,
"aircraft_type": stmt.excluded.aircraft_type,
"type_description": stmt.excluded.type_description,
"operator": stmt.excluded.operator,
"owner": stmt.excluded.owner,
"origin_country": stmt.excluded.origin_country,
"category": stmt.excluded.category,
"is_military": stmt.excluded.is_military,
"source": stmt.excluded.source,
"updated_at": stmt.excluded.updated_at,
},
)
await db.execute(stmt)
else:
stmt_sq = sqlite_insert(AircraftStatic).values(batch)
stmt_sq = stmt_sq.on_conflict_do_update(
index_elements=[AircraftStatic.icao24],
set_={
"registration": stmt_sq.excluded.registration,
"aircraft_type": stmt_sq.excluded.aircraft_type,
"type_description": stmt_sq.excluded.type_description,
"operator": stmt_sq.excluded.operator,
"owner": stmt_sq.excluded.owner,
"origin_country": stmt_sq.excluded.origin_country,
"category": stmt_sq.excluded.category,
"is_military": stmt_sq.excluded.is_military,
"source": stmt_sq.excluded.source,
"updated_at": stmt_sq.excluded.updated_at,
},
)
await db.execute(stmt_sq)
written += len(batch)
return written
async def sync_aircraft_registry(
db: AsyncSession,
*,
primary_url: str | None = None,
fallback_url: str | None = None,
cache_dir: str | None = None,
max_rows: int | None = None,
timeout_seconds: float = 60.0,
) -> dict[str, Any]:
"""Download open ICAO24 registry CSV (or use cached/existing DB on failure offline)."""
cfg = get_data_sources_config()
primary_resolved = primary_url if primary_url is not None else cfg.get_yaml_url("aircraft_registry")
fallback_resolved = (
fallback_url
if fallback_url is not None
else cfg.get_yaml_value("aircraft_registry.fallback_url")
)
urls = [
url
for url in (primary_resolved, fallback_resolved)
if isinstance(url, str) and url.strip()
]
target_dir = get_aircraft_registry_cache_dir(cache_dir)
target_dir.mkdir(parents=True, exist_ok=True)
cached_csv_path = target_dir / "aircraft_registry.csv"
downloaded_text: str | None = None
used_url: str | None = None
last_error: str | None = None
for candidate_url in urls:
try:
async with httpx.AsyncClient(timeout=timeout_seconds, follow_redirects=True) as client:
response = await client.get(
candidate_url,
headers={"User-Agent": "Planet-Intelligence-System/1.0 (aircraft-registry)"},
)
response.raise_for_status()
if len(response.content) > MAX_REGISTRY_BYTES:
raise ValueError(f"Registry file exceeds {MAX_REGISTRY_BYTES} bytes limit")
downloaded_text = decode_registry_payload(response.content, candidate_url)
tmp_path = target_dir / "aircraft_registry.csv.tmp"
tmp_path.write_text(downloaded_text, encoding="utf-8")
tmp_path.replace(cached_csv_path)
used_url = candidate_url
break
except Exception as exc:
last_error = f"{exc.__class__.__name__}: {exc}"
logger.warning_event(
"Aircraft registry download failed; trying fallback or offline cache",
event="aircraft_registry.download_failed",
context={"url": candidate_url, "error": last_error},
)
if downloaded_text is None and cached_csv_path.exists():
try:
downloaded_text = cached_csv_path.read_text(encoding="utf-8", errors="replace")
used_url = f"file://{cached_csv_path}"
except OSError as exc:
last_error = f"{exc.__class__.__name__}: {exc}"
if downloaded_text is None:
existing_count = int((await db.execute(select(func.count(AircraftStatic.icao24)))).scalar() or 0)
return {
"status": "offline_retained",
"upserted": 0,
"existing_count": existing_count,
"source_url": None,
"error": last_error,
}
records = parse_aircraft_registry_csv(downloaded_text, max_rows=max_rows)
if not records:
existing_count = int((await db.execute(select(func.count(AircraftStatic.icao24)))).scalar() or 0)
return {
"status": "empty_retained",
"upserted": 0,
"existing_count": existing_count,
"source_url": used_url,
"error": last_error,
}
upserted = await upsert_aircraft_static_records(db, records)
await db.commit()
return {
"status": "updated" if not str(used_url or "").startswith("file://") else "cache_loaded",
"upserted": upserted,
"existing_count": upserted,
"source_url": used_url,
"error": last_error,
}
+240
View File
@@ -0,0 +1,240 @@
"""Aircraft ICAO24 military allocation table, callsign heuristics, and category classification."""
from __future__ import annotations
import re
from typing import Final
AIRCRAFT_CATEGORIES: Final[frozenset[str]] = frozenset(
{
"commercial",
"cargo",
"military",
"emergency",
"general",
"helicopter",
"other",
}
)
EMERGENCY_SQUAWKS: Final[dict[str, str]] = {
"7500": "hijack",
"7600": "radio_failure",
"7700": "emergency",
}
# ICAO 24-bit military address blocks compiled from published ICAO Annex 10 national
# allocations and community ADS-B reference registries (tar1090 / mictronics / adsbexchange docs).
MILITARY_ICAO24_HEX_RANGES: Final[tuple[tuple[int, int, str], ...]] = (
(0xADF7C8, 0xAFFFFF, "US Military (DoD/USAF/USN/USCG)"),
(0x43C000, 0x43CFFF, "UK Ministry of Defence (RAF/RN)"),
(0x3AA000, 0x3AFFFF, "French Military (Armée de l'Air/Marine)"),
(0x3B0000, 0x3BFFFF, "French State/Military"),
(0x3EA000, 0x3EBFFF, "German Armed Forces (Bundeswehr)"),
(0x3F4000, 0x3F7FFF, "German Military Tactical"),
(0x33FF00, 0x33FFFF, "Italian Air Force"),
(0x44F000, 0x44FFFF, "Belgian Air Component"),
(0x480000, 0x480FFF, "Royal Netherlands Air Force"),
(0x478100, 0x4781FF, "Royal Norwegian Air Force"),
(0x48D800, 0x48DFFF, "Polish Air Force"),
(0x4B8200, 0x4B82FF, "Turkish Air Force"),
(0x4D0000, 0x4D03FF, "NATO Airborne Early Warning (Luxembourg)"),
(0x71BC00, 0x71BFFF, "Republic of Korea Air Force"),
(0x738A00, 0x738BFF, "Israeli Air Force"),
(0x7CF800, 0x7CFFFF, "Royal Australian Air Force"),
(0x800200, 0x8002FF, "Indian Air Force"),
(0x840000, 0x840FFF, "Japan Self-Defense Forces"),
(0x87F000, 0x87FFFF, "Japan Self-Defense Forces (Secondary)"),
(0xC2B300, 0xC2C3FF, "Royal Canadian Air Force"),
(0xE40000, 0xE400FF, "Brazilian Air Force"),
)
MILITARY_CALLSIGN_PREFIXES: Final[tuple[str, ...]] = (
"RCH",
"REACH",
"CNV",
"CONVOY",
"ASY",
"ASCOT",
"RRR",
"GAF",
"CTM",
"FAF",
"IAM",
"NATO",
"MMF",
"SAM",
"EXEC",
"SPAR",
"PAT",
"NAVY",
"USAF",
"USMC",
"CFC",
"CANF",
"KIWI",
"AUSSIE",
"ASY",
"PLF",
"BAF",
"HVK",
"JASDF",
"KAF",
"IAF",
)
CARGO_CALLSIGN_PREFIXES: Final[tuple[str, ...]] = (
"FDX",
"UPS",
"GTI",
"CLX",
"ABX",
"ATN",
"BOX",
"CKK",
"CSS",
"PAC",
"BCS",
"GEC",
"DHK",
"SOO",
"KFS",
"CJT",
)
HELICOPTER_TYPE_CODES: Final[frozenset[str]] = frozenset(
{
"EC35",
"EC45",
"EC55",
"H125",
"H135",
"H145",
"H160",
"H175",
"S76",
"S92",
"UH60",
"H60",
"CH47",
"H47",
"AH64",
"H64",
"B06",
"B407",
"B412",
"B429",
"AS32",
"AS50",
"AS65",
"MI8",
"MI24",
"NH90",
"A109",
"A139",
"AW139",
"AW189",
"R22",
"R44",
"R66",
"V22",
}
)
_COMMERCIAL_CALLSIGN_RE = re.compile(r"^[A-Z]{3}[0-9]{1,4}[A-Z]{0,2}$")
def normalize_icao24(value: str | None) -> str:
"""Normalize an ICAO 24-bit hex identifier to lowercase 6-char hex when valid."""
cleaned = str(value or "").strip().lower().lstrip("~")
return cleaned
def is_military_icao24(icao24: str | None) -> bool:
"""Return True if the 24-bit ICAO hex address falls within a known military block."""
normalized = normalize_icao24(icao24)
if len(normalized) != 6:
return False
try:
addr = int(normalized, 16)
except ValueError:
return False
return any(low <= addr <= high for low, high, _label in MILITARY_ICAO24_HEX_RANGES)
def is_military_callsign(callsign: str | None) -> bool:
"""Return True when the trimmed flight callsign starts with a known military designator."""
cs = str(callsign or "").strip().upper()
if not cs:
return False
for prefix in MILITARY_CALLSIGN_PREFIXES:
if cs == prefix or (cs.startswith(prefix) and len(cs) > len(prefix) and cs[len(prefix)].isdigit()):
return True
return False
def classify_aircraft(
*,
icao24: str | None,
callsign: str | None = None,
squawk: str | None = None,
aircraft_type: str | None = None,
adsb_category: str | None = None,
db_flags: int | None = None,
static_is_military: bool = False,
static_category: str | None = None,
source_is_military_feed: bool = False,
) -> dict[str, object]:
"""Classify aircraft operational category, military flag, and emergency status."""
norm_squawk = str(squawk or "").strip()
is_emergency = norm_squawk in EMERGENCY_SQUAWKS
emergency_code = norm_squawk if is_emergency else None
db_mil = bool(db_flags is not None and (int(db_flags) & 1))
is_military = bool(
static_is_military
or db_mil
or source_is_military_feed
or is_military_icao24(icao24)
or is_military_callsign(callsign)
)
cs = str(callsign or "").strip().upper()
type_upper = str(aircraft_type or "").strip().upper()
emitter = str(adsb_category or "").strip().upper()
static_cat = str(static_category or "").strip().lower()
is_helicopter = (
emitter == "A7"
or type_upper in HELICOPTER_TYPE_CODES
or static_cat == "helicopter"
)
is_cargo = bool(
cs and any(cs.startswith(p) and len(cs) > len(p) and cs[len(p)].isdigit() for p in CARGO_CALLSIGN_PREFIXES)
) or static_cat == "cargo"
if is_emergency:
category = "emergency"
elif is_military:
category = "military"
elif is_helicopter:
category = "helicopter"
elif is_cargo:
category = "cargo"
elif emitter in {"A3", "A4", "A5"} or (_COMMERCIAL_CALLSIGN_RE.match(cs) is not None):
category = "commercial"
elif emitter in {"A1", "A2"} or static_cat == "general":
category = "general"
elif static_cat in AIRCRAFT_CATEGORIES:
category = static_cat
elif cs:
category = "general"
else:
category = "other"
return {
"category": category,
"is_military": is_military,
"is_emergency": is_emergency,
"emergency_code": emergency_code,
}
+2
View File
@@ -29,6 +29,8 @@ EARTH_READ_SCOPES: frozenset[str] = frozenset(
"visualization:read",
"layers:read",
"vessels:read",
"aircraft:read",
"gps_jamming:read",
"news:read",
"data_products:read",
"situational:read",
@@ -38,7 +38,25 @@ from app.services.collectors.nro_delegated import NRODelegatedPrefixGeoCollector
from app.services.collectors.news_live_streams import NewsLiveStreamsCollector
from app.services.collectors.media_news_archive import MediaNewsArchiveCollector
from app.services.collectors.aisstream import AISStreamCollector
from app.services.collectors.cloud_map import EarthCloudMapCollector
from app.services.collectors.earth_tiles import (
CloudHDTilesCollector,
Sentinel2ImageryCollector,
VIIRSDailyImageryCollector,
)
from app.services.collectors.vessel_ais import VesselAISCollector
from app.services.collectors.wind_gfs import EarthWindGFSCollector
from app.services.collectors.adsb_lol import ADSBLolCollector
from app.services.collectors.opensky import OpenSkyAircraftCollector
from app.services.collectors.gps_jamming import GPSJammingCollector
from app.services.collectors.aircraft_registry import AircraftRegistryCollector
from app.services.collectors.disasters import (
GDACSDisasterCollector,
NASAEonetCollector,
NASAFirmsWildfireCollector,
USGSEarthquakeCollector,
)
from app.services.collectors.nga_warnings import NGANavigationWarningsCollector
collector_registry.register(TOP500Collector())
collector_registry.register(EpochAIGPUCollector())
@@ -69,6 +87,20 @@ collector_registry.register(NewsLiveStreamsCollector())
collector_registry.register(MediaNewsArchiveCollector())
collector_registry.register(VesselAISCollector())
collector_registry.register(AISStreamCollector())
collector_registry.register(EarthCloudMapCollector())
collector_registry.register(CloudHDTilesCollector())
collector_registry.register(Sentinel2ImageryCollector())
collector_registry.register(VIIRSDailyImageryCollector())
collector_registry.register(EarthWindGFSCollector())
collector_registry.register(ADSBLolCollector())
collector_registry.register(OpenSkyAircraftCollector())
collector_registry.register(GPSJammingCollector())
collector_registry.register(AircraftRegistryCollector())
collector_registry.register(USGSEarthquakeCollector())
collector_registry.register(NASAFirmsWildfireCollector())
collector_registry.register(GDACSDisasterCollector())
collector_registry.register(NASAEonetCollector())
collector_registry.register(NGANavigationWarningsCollector())
__all__ = [
"BaseCollector",
@@ -105,4 +137,18 @@ __all__ = [
"MediaNewsArchiveCollector",
"VesselAISCollector",
"AISStreamCollector",
"EarthCloudMapCollector",
"CloudHDTilesCollector",
"Sentinel2ImageryCollector",
"VIIRSDailyImageryCollector",
"EarthWindGFSCollector",
"ADSBLolCollector",
"OpenSkyAircraftCollector",
"GPSJammingCollector",
"AircraftRegistryCollector",
"USGSEarthquakeCollector",
"NASAFirmsWildfireCollector",
"GDACSDisasterCollector",
"NASAEonetCollector",
"NGANavigationWarningsCollector",
]
+324
View File
@@ -0,0 +1,324 @@
"""adsb.lol ADS-B collector (Source 39) with optional opt-in non-commercial gap-fill."""
from __future__ import annotations
import asyncio
from datetime import UTC, datetime, timedelta
from typing import Any
import httpx
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.data_sources import get_data_sources_config
from app.core.enums import ConnectionState, SnapshotStatus
from app.core.logging import get_logger
from app.core.websocket.broadcaster import broadcaster
from app.models.data_snapshot import DataSnapshot
from app.models.datasource_config import DataSourceConfig
from app.services.aircraft_aggregation import (
DEFAULT_CURRENT_STALE_MINUTES,
DEFAULT_POSITION_RETENTION_HOURS,
prune_aircraft_tables,
update_adsb_source_health,
upsert_aircraft_observations,
)
from app.services.collectors.base import BaseCollector
logger = get_logger(__name__, service="collector.adsb_lol")
ADSB_LOL_DEFAULT_BASE_URL = "https://api.adsb.lol"
AIRPLANES_LIVE_BASE_URL = "https://api.airplanes.live"
ADSB_FI_BASE_URL = "https://opendata.adsb.fi/api"
FEET_TO_METERS = 0.3048
KNOTS_TO_MS = 0.514444
FTMIN_TO_MS = 0.00508
MAX_ENDPOINT_RETRIES = 2
def _as_float(val: Any) -> float | None:
if val in (None, "", "ground"):
return None
try:
return float(val)
except (TypeError, ValueError):
return None
def _as_int(val: Any) -> int | None:
if val in (None, ""):
return None
try:
return int(val)
except (TypeError, ValueError):
return None
def parse_adsb_lol_payload(
payload: dict[str, Any] | list[Any],
*,
source: str = "adsb_lol_aircraft",
is_military_endpoint: bool = False,
squawk_hint: str | None = None,
fallback_time: datetime | None = None,
) -> list[dict[str, Any]]:
"""Parse an adsb.lol v2 API JSON payload into normalized aircraft observations."""
ref_now = fallback_time or datetime.now(UTC)
if isinstance(payload, dict) and payload.get("now") is not None:
raw_now = _as_float(payload.get("now"))
if raw_now is not None:
if raw_now > 10_000_000_000:
raw_now /= 1000.0
ref_now = datetime.fromtimestamp(raw_now, tz=UTC)
items = payload.get("ac") if isinstance(payload, dict) else payload
if not isinstance(items, list):
return []
records: list[dict[str, Any]] = []
for item in items:
if not isinstance(item, dict):
continue
icao24 = str(item.get("hex") or "").strip().lower().lstrip("~")
lat = _as_float(item.get("lat"))
lon = _as_float(item.get("lon"))
if len(icao24) != 6 or lat is None or lon is None:
continue
raw_baro = item.get("alt_baro")
on_ground = raw_baro == "ground"
baro_ft = _as_float(raw_baro)
geom_ft = _as_float(item.get("alt_geom"))
baro_m = 0.0 if on_ground else (baro_ft * FEET_TO_METERS if baro_ft is not None else None)
geom_m = geom_ft * FEET_TO_METERS if geom_ft is not None else None
gs_knots = _as_float(item.get("gs"))
speed_ms = gs_knots * KNOTS_TO_MS if gs_knots is not None else None
track_deg = _as_float(item.get("track"))
vrate_fpm = _as_float(item.get("baro_rate") if item.get("baro_rate") is not None else item.get("geom_rate"))
vrate_ms = vrate_fpm * FTMIN_TO_MS if vrate_fpm is not None else None
seen_pos = _as_float(item.get("seen_pos") if item.get("seen_pos") is not None else item.get("seen"))
obs_at = ref_now - timedelta(seconds=max(0.0, seen_pos or 0.0))
squawk = str(item.get("squawk") or squawk_hint or "").strip()[:8] or None
db_flags = _as_int(item.get("dbFlags"))
records.append(
{
"icao24": icao24,
"callsign": str(item.get("flight") or "").strip()[:16] or None,
"lat": lat,
"lon": lon,
"baro_altitude_m": baro_m,
"geo_altitude_m": geom_m,
"ground_speed_ms": speed_ms,
"track_deg": track_deg,
"vertical_rate_ms": vrate_ms,
"squawk": squawk,
"on_ground": on_ground,
"aircraft_type": str(item.get("t") or "").strip()[:16] or None,
"adsb_category": str(item.get("category") or "").strip()[:8] or None,
"db_flags": db_flags,
"source_is_military": bool(is_military_endpoint or (db_flags is not None and (db_flags & 1))),
"source": source,
"observed_at": obs_at,
}
)
return records
class ADSBLolCollector(BaseCollector):
"""Collect military, emergency squawk, and configured focus-area ADS-B traffic from adsb.lol."""
name = "adsb_lol_aircraft"
priority = "P1"
module = "L4"
frequency_hours = 1
data_type = "aircraft_adsb"
fail_on_empty = False
preserve_snapshot_on_failure = True
@property
def base_url(self) -> str:
raw = self._resolved_url or get_data_sources_config().get_yaml_url(self.name) or ADSB_LOL_DEFAULT_BASE_URL
return raw.rstrip("/")
async def _load_runtime_config(self) -> dict[str, Any]:
db = getattr(self, "_db_session", None)
if db is None or not callable(getattr(db, "execute", None)):
return {}
try:
res = await db.execute(
select(DataSourceConfig)
.where(DataSourceConfig.name == self.name)
.where(DataSourceConfig.is_active.is_(True))
)
rec = res.scalar_one_or_none()
return dict(rec.config or {}) if rec and isinstance(rec.config, dict) else {}
except Exception as exc:
logger.warning_event(
"Could not load adsb_lol_aircraft runtime config; using defaults",
event="adsb_lol.config_load_failed",
context={"error": str(exc)},
)
return {}
async def _get_with_retry(
self,
client: httpx.AsyncClient,
url: str,
) -> dict[str, Any] | None:
last_exc: Exception | None = None
for attempt in range(MAX_ENDPOINT_RETRIES + 1):
try:
resp = await client.get(
url,
headers={"User-Agent": "Planet-Intelligence-System/1.0 (adsb.lol ODbL)"},
)
resp.raise_for_status()
payload = resp.json()
return payload if isinstance(payload, dict) else None
except Exception as exc:
last_exc = exc
if attempt < MAX_ENDPOINT_RETRIES:
await asyncio.sleep(0.5 * (2**attempt))
logger.warning_event(
"adsb.lol endpoint failed after retries",
event="adsb_lol.endpoint_failed",
context={"url": url, "error": str(last_exc) if last_exc else "unknown"},
)
return None
async def fetch(self) -> list[dict[str, Any]]:
cfg = await self._load_runtime_config()
focus_points = cfg.get("focus_points") if isinstance(cfg.get("focus_points"), list) else []
gap_fill_enabled = bool(cfg.get("gap_fill_noncommercial_enabled", False))
gap_fill_provider = str(cfg.get("gap_fill_provider") or "airplanes_live").strip().lower()
endpoints: list[tuple[str, bool, str | None, str]] = [
(f"{self.base_url}/v2/mil", True, None, self.name),
(f"{self.base_url}/v2/sqk/7500", False, "7500", self.name),
(f"{self.base_url}/v2/sqk/7600", False, "7600", self.name),
(f"{self.base_url}/v2/sqk/7700", False, "7700", self.name),
]
for pt in focus_points[:8]:
if not isinstance(pt, dict):
continue
lat = _as_float(pt.get("lat"))
lon = _as_float(pt.get("lon"))
radius = max(10, min(int(_as_float(pt.get("radius_nm")) or 250), 250))
if lat is not None and lon is not None:
endpoints.append((f"{self.base_url}/v2/point/{lat}/{lon}/{radius}", False, None, self.name))
if gap_fill_enabled:
if gap_fill_provider == "adsb_fi":
endpoints.append(
(f"{ADSB_FI_BASE_URL}/v2/lat/{lat}/lon/{lon}/dist/{radius}", False, None, "adsb_fi")
)
else:
endpoints.append(
(f"{AIRPLANES_LIVE_BASE_URL}/v2/point/{lat}/{lon}/{radius}", False, None, "airplanes_live")
)
all_records: list[dict[str, Any]] = []
any_succeeded = False
async with httpx.AsyncClient(timeout=20.0, follow_redirects=True) as client:
for url, is_mil, squawk_hint, src in endpoints:
payload = await self._get_with_retry(client, url)
if payload is not None:
any_succeeded = True
all_records.extend(
parse_adsb_lol_payload(
payload,
source=src,
is_military_endpoint=is_mil,
squawk_hint=squawk_hint,
)
)
self._last_fetch_succeeded = any_succeeded
return all_records
def transform(self, raw_data: list[dict[str, Any]]) -> list[dict[str, Any]]:
return [item for item in raw_data if isinstance(item, dict) and item.get("icao24")]
async def _save_data(
self,
db: AsyncSession,
data: list[dict[str, Any]],
task_id: int | None = None,
snapshot_id: int | None = None,
) -> int:
now = datetime.now(UTC)
cfg = await self._load_runtime_config()
stale_minutes = int(cfg.get("current_stale_minutes") or DEFAULT_CURRENT_STALE_MINUTES)
retention_hours = int(cfg.get("position_retention_hours") or DEFAULT_POSITION_RETENTION_HOURS)
fetch_ok = getattr(self, "_last_fetch_succeeded", True)
if not fetch_ok and not data:
await update_adsb_source_health(
db,
source=self.name,
connection_state=ConnectionState.DISCONNECTED.value,
active_count=0,
last_error="All adsb.lol endpoints failed; retaining previous state until expiry",
)
await db.commit()
return 0
summary = await upsert_aircraft_observations(
db,
data,
default_source=self.name,
ingested_at=now,
)
await prune_aircraft_tables(
db,
current_stale_minutes=stale_minutes,
position_retention_hours=retention_hours,
now=now,
)
await update_adsb_source_health(
db,
source=self.name,
connection_state=ConnectionState.CONNECTED.value,
active_count=summary["states_upserted"],
last_success_at=now,
last_error=None,
clear_cooldown=True,
)
if snapshot_id is not None:
snapshot = await db.get(DataSnapshot, snapshot_id)
if snapshot:
snapshot.record_count = summary["states_upserted"]
snapshot.status = SnapshotStatus.SUCCESS.value
snapshot.completed_at = now
snapshot.summary = {
"created": summary["states_upserted"],
"positions_inserted": summary["positions_inserted"],
"storage": "aircraft_current_state_and_24h_position",
}
await db.commit()
if summary["states_upserted"] > 0:
try:
await broadcaster.broadcast_earth_update(
{
"event": "earth.layer.changed",
"action": "database_changed",
"source": self.name,
"layers": ["aircraft"],
"refresh_strategy": "reload",
"records_processed": summary["states_upserted"],
}
)
except Exception as exc:
logger.warning_event(
"Failed to broadcast aircraft update after adsb.lol ingestion",
event="adsb_lol.broadcast_failed",
context={"error": str(exc)},
)
return summary["states_upserted"]
@@ -0,0 +1,52 @@
"""Collector entrypoint for open ICAO24 aircraft registry synchronization (Source 42)."""
from __future__ import annotations
from datetime import UTC, datetime
from typing import Any
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.enums import SnapshotStatus
from app.models.data_snapshot import DataSnapshot
from app.services.aircraft_registry import sync_aircraft_registry
from app.services.collectors.base import BaseCollector
class AircraftRegistryCollector(BaseCollector):
"""Download/update local ICAO24 aircraft_static metadata with offline graceful retention."""
name = "aircraft_registry"
priority = "P2"
module = "L4"
frequency_hours = 168
data_type = "aircraft_registry"
fail_on_empty = False
preserve_snapshot_on_failure = True
async def fetch(self) -> list[dict[str, Any]]:
db = getattr(self, "_db_session", None)
if db is None:
return []
result = await sync_aircraft_registry(db, primary_url=self._resolved_url)
return [result]
async def _save_data(
self,
db: AsyncSession,
data: list[dict[str, Any]],
task_id: int | None = None,
snapshot_id: int | None = None,
) -> int:
now = datetime.now(UTC)
summary = data[0] if data and isinstance(data[0], dict) else {}
written = int(summary.get("upserted") or 0)
if snapshot_id is not None:
snapshot = await db.get(DataSnapshot, snapshot_id)
if snapshot:
snapshot.record_count = written
snapshot.status = SnapshotStatus.SUCCESS.value
snapshot.completed_at = now
snapshot.summary = summary
await db.commit()
return written
@@ -0,0 +1,184 @@
"""Built-in collector for global real-time satellite IR cloud imagery and spatial analytics."""
from __future__ import annotations
from typing import Any
from sqlalchemy import select
from app.core.websocket.broadcaster import broadcaster
from app.models.datasource_config import DataSourceConfig
from app.services.collectors.base import BaseCollector
from app.services.earth_clouds import collect_latest_cloud_frame
class EarthCloudMapCollector(BaseCollector):
"""Collect multi-satellite IR cloud map frames and structured atmospheric analytics."""
name = "global_cloud_map"
priority = "P1"
module = "L2"
frequency_hours = 1
data_type = "cloud_map_record"
fail_on_empty = True
preserve_snapshot_on_failure = True
full_snapshot_reconcile = True
async def _load_override_config(self) -> dict[str, Any]:
if not self._db_session or not callable(getattr(self._db_session, "execute", None)):
return {}
try:
result = await self._db_session.execute(
select(DataSourceConfig)
.where(DataSourceConfig.name == self.name)
.where(DataSourceConfig.is_active.is_(True))
.limit(1)
)
record = result.scalar_one_or_none()
if record and isinstance(record.config, dict):
return {
key: value
for key, value in record.config.items()
if key
in {
"enabled",
"primary_source",
"fallback_source",
"resolution",
"ir_threshold",
"contrast_gamma",
"convective_threshold",
"min_cluster_area_km2",
"polar_feather_enabled",
"max_history_frames",
"request_timeout_seconds",
"geocolor_enabled",
"relief_shading_strength",
"optical_flow_enabled",
}
and value is not None
}
except Exception:
return {}
return {}
async def fetch(self) -> list[dict[str, Any]]:
override = await self._load_override_config()
result = await collect_latest_cloud_frame(self._db_session, override_config=override)
return [result]
def transform(self, raw_data: list[dict[str, Any]]) -> list[dict[str, Any]]:
if not raw_data:
return []
bundle = raw_data[0]
frame = bundle.get("frame") or {}
summary = bundle.get("global_summary") or {}
regions = bundle.get("regions") or []
clusters = bundle.get("convective_clusters") or []
version = str(frame.get("version") or "")
captured_at = frame.get("captured_at")
source_used = str(frame.get("source") or "multi_sat_ir")
satellites = list(frame.get("satellites") or [])
degraded = bool(frame.get("degraded", False))
records: list[dict[str, Any]] = [
{
"source_id": "cloud_snapshot:latest",
"name": "全球实时红外云图快照",
"title": f"全球云图 {version}",
"description": (
f"来源={source_used}, 全球平均云量={summary.get('global_cloud_cover_pct')}%, "
f"强对流云团={summary.get('convective_cluster_count', 0)} 个"
),
"latitude": 0.0,
"longitude": 0.0,
"value": summary.get("global_cloud_cover_pct"),
"unit": "%",
"reference_date": captured_at,
"metadata": {
"record_kind": "cloud_map_snapshot",
"version": version,
"captured_at": captured_at,
"cloud_source": source_used,
"satellites": satellites,
"degraded": degraded,
"resolution": frame.get("resolution"),
"image_url": frame.get("image_url"),
"file_size_bytes": frame.get("file_size_bytes"),
"sha256": frame.get("sha256"),
**summary,
},
}
]
for region in regions:
key = str(region.get("key") or "")
records.append(
{
"source_id": f"cloud_region:{key}",
"name": str(region.get("name") or key),
"title": f"区域云量 · {region.get('name') or key}",
"description": (
f"云量 {region.get('cloud_cover_pct')}%, "
f"厚云 {region.get('overcast_coverage_pct')}%, "
f"最低亮温 {region.get('min_brightness_temp_c')}°C"
),
"latitude": region.get("center_lat"),
"longitude": region.get("center_lon"),
"value": region.get("cloud_cover_pct"),
"unit": "%",
"reference_date": captured_at,
"metadata": {
"record_kind": "cloud_region_summary",
"version": version,
"captured_at": captured_at,
**region,
},
}
)
for cluster in clusters:
cid = str(cluster.get("cluster_id") or "")
records.append(
{
"source_id": f"cloud_cluster:{cid}",
"name": f"强对流云团 {cid} ({cluster.get('region') or ''})",
"title": f"强对流核 {cid} · {cluster.get('min_brightness_temp_c')}°C",
"description": (
f"估算面积 {cluster.get('area_km2')} km², "
f"峰值强度 {cluster.get('peak_intensity')}%, "
f"最低亮温 {cluster.get('min_brightness_temp_c')}°C"
),
"latitude": cluster.get("latitude"),
"longitude": cluster.get("longitude"),
"value": cluster.get("area_km2"),
"unit": "km2",
"reference_date": captured_at,
"metadata": {
"record_kind": "cloud_convective_cluster",
"version": version,
"captured_at": captured_at,
**cluster,
},
}
)
return records
async def run(self, db) -> dict[str, Any]:
result = await super().run(db)
if result.get("status") == "success":
try:
await broadcaster.broadcast_earth_update(
{
"event": "earth.layer.changed",
"action": "cloud_map_updated",
"source": self.name,
"layers": ["clouds"],
"refresh_strategy": "reload",
}
)
except Exception:
pass
return result
@@ -0,0 +1,279 @@
"""Natural disaster collectors: USGS (43), NASA FIRMS (44), GDACS (45), NASA EONET (46)."""
from __future__ import annotations
from datetime import UTC, datetime
from typing import Any
import httpx
from sqlalchemy import update
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.data_sources import get_data_sources_config
from app.core.enums import SnapshotStatus
from app.core.logging import get_logger
from app.core.websocket.broadcaster import broadcaster
from app.models.data_snapshot import DataSnapshot
from app.models.datasource import DataSource
from app.services.collectors.base import BaseCollector
from app.services.datasource_connectivity import resolve_nasa_firms_map_key
from app.services.disaster_aggregation import (
parse_gdacs_events,
parse_nasa_eonet_events,
parse_nasa_firms_csv,
parse_usgs_earthquakes,
upsert_disaster_events,
)
logger = get_logger(__name__, service="collector.disasters")
USGS_URL_DEFAULT = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_day.geojson"
NASA_FIRMS_BASE_DEFAULT = "https://firms.modaps.eosdis.nasa.gov/api/area/csv"
GDACS_URL_DEFAULT = "https://www.gdacs.org/gdacsapi/api/events/geteventlist/SEARCH"
NASA_EONET_URL_DEFAULT = "https://eonet.gsfc.nasa.gov/api/v3/events?status=open&limit=100"
async def _mark_source_status(db: AsyncSession, source_name: str, status_val: str) -> None:
try:
await db.execute(
update(DataSource)
.where(DataSource.source == source_name)
.values(last_status=status_val, last_run_at=datetime.now(UTC))
)
await db.commit()
except Exception as exc:
logger.debug_event(
"Skipped datasource status update",
event="disaster_collector.status_update_skipped",
context={"source": source_name, "error_type": type(exc).__name__},
)
async def _persist_disaster_batch(
db: AsyncSession,
*,
source_name: str,
records: list[dict[str, Any]],
snapshot_id: int | None = None,
) -> int:
saved = await upsert_disaster_events(db, records)
now = datetime.now(UTC)
if snapshot_id is not None:
snap = await db.get(DataSnapshot, snapshot_id)
if snap is not None:
snap.record_count = saved
snap.status = SnapshotStatus.SUCCESS.value
snap.completed_at = now
snap.summary = {"created": saved, "storage": "disaster_events"}
await db.commit()
if saved > 0:
try:
await broadcaster.broadcast_earth_update(
{
"event": "earth.layer.changed",
"action": "database_changed",
"source": source_name,
"layers": ["disasters"],
"refresh_strategy": "reload",
"records_processed": saved,
}
)
except Exception as exc:
logger.warning_event(
"Failed to broadcast disasters update",
event="disasters.broadcast_failed",
context={"source": source_name, "error": str(exc)},
)
return saved
class USGSEarthquakeCollector(BaseCollector):
"""Collector 43: USGS M4.5+ global earthquakes."""
name = "usgs_earthquakes"
priority = "P1"
module = "L4"
frequency_hours = 1
data_type = "disasters"
fail_on_empty = False
preserve_snapshot_on_failure = True
def _resolve_url(self) -> str:
val = self._resolved_url or get_data_sources_config().get_yaml_value("usgs_earthquakes.url")
return str(val or USGS_URL_DEFAULT)
async def fetch(self) -> list[dict[str, Any]]:
url = self._resolve_url()
async with httpx.AsyncClient(timeout=20.0, follow_redirects=True) as client:
resp = await client.get(url, headers={"User-Agent": "Planet-Intelligence-System/1.0"})
resp.raise_for_status()
payload = resp.json()
return parse_usgs_earthquakes(payload, source=self.name)
def transform(self, raw_data: list[dict[str, Any]]) -> list[dict[str, Any]]:
return [r for r in raw_data if isinstance(r, dict) and r.get("source_event_id")]
async def _save_data(
self,
db: AsyncSession,
data: list[dict[str, Any]],
task_id: int | None = None,
snapshot_id: int | None = None,
) -> int:
return await _persist_disaster_batch(db, source_name=self.name, records=data, snapshot_id=snapshot_id)
async def collect(self, db: AsyncSession, **kwargs) -> dict[str, Any]:
records = self.transform(await self.fetch())
saved = await self._save_data(db, records)
await _mark_source_status(db, self.name, "success")
return {"source": self.name, "status": "success", "records_saved": saved}
class NASAFirmsWildfireCollector(BaseCollector):
"""Collector 44: NASA FIRMS VIIRS active fires (requires free MAP_KEY)."""
name = "nasa_firms_wildfires"
priority = "P1"
module = "L4"
frequency_hours = 1
data_type = "disasters"
fail_on_empty = False
preserve_snapshot_on_failure = True
def _resolve_base_url(self) -> str:
val = self._resolved_url or get_data_sources_config().get_yaml_value("nasa_firms_wildfires.url")
return str(val or NASA_FIRMS_BASE_DEFAULT).rstrip("/")
async def fetch_with_db(self, db: AsyncSession | None = None) -> tuple[list[dict[str, Any]], str]:
map_key, _cred_source = await resolve_nasa_firms_map_key(db)
if not map_key:
return [], "not_configured"
cfg = get_data_sources_config()
sensor = str(cfg.get_yaml_value("nasa_firms_wildfires.sensor") or "VIIRS_SNPP_NRT")
days = int(cfg.get_yaml_value("nasa_firms_wildfires.days") or 1)
url = f"{self._resolve_base_url()}/{map_key}/{sensor}/world/{days}"
async with httpx.AsyncClient(timeout=30.0, follow_redirects=True) as client:
resp = await client.get(url, headers={"User-Agent": "Planet-Intelligence-System/1.0"})
resp.raise_for_status()
csv_text = resp.text
return parse_nasa_firms_csv(csv_text, source=self.name), "success"
async def fetch(self) -> list[dict[str, Any]]:
records, _ = await self.fetch_with_db(self._db_session)
return records
def transform(self, raw_data: list[dict[str, Any]]) -> list[dict[str, Any]]:
return [r for r in raw_data if isinstance(r, dict) and r.get("source_event_id")]
async def _save_data(
self,
db: AsyncSession,
data: list[dict[str, Any]],
task_id: int | None = None,
snapshot_id: int | None = None,
) -> int:
return await _persist_disaster_batch(db, source_name=self.name, records=data, snapshot_id=snapshot_id)
async def collect(self, db: AsyncSession, **kwargs) -> dict[str, Any]:
records, status_val = await self.fetch_with_db(db)
if status_val == "not_configured":
await _mark_source_status(db, self.name, "not_configured")
logger.info_event(
"NASA FIRMS MAP_KEY missing; skipping cleanly",
event="nasa_firms.not_configured",
)
return {"source": self.name, "status": "not_configured", "records_saved": 0}
saved = await self._save_data(db, self.transform(records))
await _mark_source_status(db, self.name, "success")
return {"source": self.name, "status": "success", "records_saved": saved}
class GDACSDisasterCollector(BaseCollector):
"""Collector 45: GDACS Orange/Red global disaster alerts."""
name = "gdacs_disasters"
priority = "P1"
module = "L4"
frequency_hours = 1
data_type = "disasters"
fail_on_empty = False
preserve_snapshot_on_failure = True
def _resolve_url(self) -> str:
val = self._resolved_url or get_data_sources_config().get_yaml_value("gdacs_disasters.url")
return str(val or GDACS_URL_DEFAULT)
async def fetch(self) -> list[dict[str, Any]]:
url = self._resolve_url()
async with httpx.AsyncClient(timeout=20.0, follow_redirects=True) as client:
resp = await client.get(
url,
headers={
"User-Agent": "Planet-Intelligence-System/1.0",
"Accept": "application/json, application/xml, text/xml",
},
)
resp.raise_for_status()
content_type = str(resp.headers.get("content-type") or "").lower()
raw: dict[str, Any] | str = resp.json() if "json" in content_type else resp.text
return parse_gdacs_events(raw, source=self.name)
def transform(self, raw_data: list[dict[str, Any]]) -> list[dict[str, Any]]:
return [r for r in raw_data if isinstance(r, dict) and r.get("source_event_id")]
async def _save_data(
self,
db: AsyncSession,
data: list[dict[str, Any]],
task_id: int | None = None,
snapshot_id: int | None = None,
) -> int:
return await _persist_disaster_batch(db, source_name=self.name, records=data, snapshot_id=snapshot_id)
async def collect(self, db: AsyncSession, **kwargs) -> dict[str, Any]:
records = self.transform(await self.fetch())
saved = await self._save_data(db, records)
await _mark_source_status(db, self.name, "success")
return {"source": self.name, "status": "success", "records_saved": saved}
class NASAEonetCollector(BaseCollector):
"""Collector 46: NASA EONET natural events (excluding earthquakes)."""
name = "nasa_eonet_events"
priority = "P2"
module = "L4"
frequency_hours = 1
data_type = "disasters"
fail_on_empty = False
preserve_snapshot_on_failure = True
def _resolve_url(self) -> str:
val = self._resolved_url or get_data_sources_config().get_yaml_value("nasa_eonet_events.url")
return str(val or NASA_EONET_URL_DEFAULT)
async def fetch(self) -> list[dict[str, Any]]:
url = self._resolve_url()
async with httpx.AsyncClient(timeout=20.0, follow_redirects=True) as client:
resp = await client.get(url, headers={"User-Agent": "Planet-Intelligence-System/1.0"})
resp.raise_for_status()
payload = resp.json()
return parse_nasa_eonet_events(payload, source=self.name)
def transform(self, raw_data: list[dict[str, Any]]) -> list[dict[str, Any]]:
return [r for r in raw_data if isinstance(r, dict) and r.get("source_event_id")]
async def _save_data(
self,
db: AsyncSession,
data: list[dict[str, Any]],
task_id: int | None = None,
snapshot_id: int | None = None,
) -> int:
return await _persist_disaster_batch(db, source_name=self.name, records=data, snapshot_id=snapshot_id)
async def collect(self, db: AsyncSession, **kwargs) -> dict[str, Any]:
records = self.transform(await self.fetch())
saved = await self._save_data(db, records)
await _mark_source_status(db, self.name, "success")
return {"source": self.name, "status": "success", "records_saved": saved}
@@ -0,0 +1,106 @@
"""Collectors for NASA/EOX Earth tile pyramids (`cloud_hd_tiles`, Sentinel-2, VIIRS)."""
from __future__ import annotations
from datetime import UTC, datetime
from typing import Any
from app.core.logging import get_logger
from app.core.time import to_iso8601_utc
from app.core.websocket.broadcaster import broadcaster
from app.services.collectors.base import BaseCollector
from app.services.earth_tiles import TILE_SOURCES, warmup_tile_source
logger = get_logger(__name__, service="collector.earth_tiles")
class _BaseEarthTileCollector(BaseCollector):
"""Base BaseCollector implementation for managed Web-Mercator tile pyramids."""
priority = "P2"
module = "L1"
frequency_hours = 24
data_type = "earth_tile_pyramid"
fail_on_empty = False
preserve_snapshot_on_failure = True
full_snapshot_reconcile = True
broadcast_layer = "basemap"
async def fetch(self) -> list[dict[str, Any]]:
summary = await warmup_tile_source(self.name, db=self._db_session)
return [summary]
def transform(self, raw_data: list[dict[str, Any]]) -> list[dict[str, Any]]:
if not raw_data:
return []
summary = raw_data[0]
cache_stats = summary.get("cache_stats") or {}
tile_count = int(cache_stats.get("tile_count") or 0)
total_mb = float(cache_stats.get("total_mb") or 0.0)
captured_at = to_iso8601_utc(datetime.now(UTC))
return [
{
"source_id": f"tile_pyramid:{self.name}",
"name": self.name,
"title": f"瓦片金字塔预热 · {self.name} (Z0–Z{summary.get('warmup_max_zoom', 3)})",
"description": (
f"新抓取 {summary.get('fetched', 0)} 块,缓存命中 {summary.get('cached_hits', 0)} 块,"
f"累计 {tile_count} 块 ({total_mb} MB)"
),
"latitude": 0.0,
"longitude": 0.0,
"value": tile_count,
"unit": "tiles",
"reference_date": captured_at,
"metadata": {
"record_kind": "earth_tile_pyramid",
"captured_at": captured_at,
**summary,
},
}
]
async def run(self, db) -> dict[str, Any]:
result = await super().run(db)
if result.get("status") == "success":
try:
await broadcaster.broadcast_earth_update(
{
"event": "earth.layer.changed",
"action": "tile_pyramid_warmed",
"source": self.name,
"layers": [self.broadcast_layer],
"refresh_strategy": "reload",
}
)
except Exception:
pass
return result
class CloudHDTilesCollector(_BaseEarthTileCollector):
name = "cloud_hd_tiles"
priority = "P1"
module = "L2"
frequency_hours = 1
broadcast_layer = "clouds"
class Sentinel2ImageryCollector(_BaseEarthTileCollector):
name = "earth_imagery_sentinel2"
frequency_hours = 24
broadcast_layer = "basemap"
class VIIRSDailyImageryCollector(_BaseEarthTileCollector):
name = "earth_imagery_viirs_daily"
frequency_hours = 12
broadcast_layer = "basemap"
__all__ = [
"TILE_SOURCES",
"CloudHDTilesCollector",
"Sentinel2ImageryCollector",
"VIIRSDailyImageryCollector",
]
@@ -0,0 +1,246 @@
"""gpsjam.org daily H3 GNSS interference collector (Source 41)."""
from __future__ import annotations
import csv
from datetime import UTC, datetime
import io
import re
from typing import Any
import h3
import httpx
from sqlalchemy.dialects.postgresql import insert as pg_insert
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.data_sources import get_data_sources_config
from app.core.enums import SnapshotStatus
from app.core.logging import get_logger
from app.core.websocket.broadcaster import broadcaster
from app.models.data_snapshot import DataSnapshot
from app.models.gps_jamming import GPSJammingCell
from app.services.collectors.base import BaseCollector
logger = get_logger(__name__, service="collector.gps_jamming")
GPSJAM_MANIFEST_URL = "https://gpsjam.org/data/manifest.csv"
GPSJAM_DATA_BASE_URL = "https://gpsjam.org/data"
_DATE_RE = re.compile(r"\b(\d{4}-\d{2}-\d{2})\b")
def parse_manifest_latest_date(manifest_text: str) -> str | None:
"""Return the latest YYYY-MM-DD entry found in gpsjam manifest.csv."""
dates = _DATE_RE.findall(manifest_text or "")
return max(dates) if dates else None
def classify_jamming_level(bad_ratio: float) -> str:
"""Classify GNSS interference level from bad_ratio into low/medium/high."""
if bad_ratio > 0.10:
return "high"
if bad_ratio >= 0.02:
return "medium"
return "low"
def _pick_col(fieldnames: list[str], *candidates: str) -> str | None:
lowered = {f.strip().lower(): f for f in fieldnames if f}
for cand in candidates:
if cand.lower() in lowered:
return lowered[cand.lower()]
return None
def parse_gpsjam_csv(
csv_text: str,
*,
observed_date: str,
source: str = "gpsjam_interference",
) -> list[dict[str, Any]]:
"""Parse gpsjam `{date}-h3_4.csv` text and generate H3 center & boundary polygons."""
cleaned = str(csv_text or "").lstrip("\ufeff").strip()
if not cleaned:
return []
reader = csv.DictReader(io.StringIO(cleaned))
fieldnames = list(reader.fieldnames or [])
col_hex = _pick_col(fieldnames, "hex", "h3", "h3_index", "gnssCellKey")
if not col_hex:
return []
col_good = _pick_col(fieldnames, "count_good_aircraft", "good", "good_count")
col_bad = _pick_col(fieldnames, "count_bad_aircraft", "bad", "bad_count")
col_total = _pick_col(fieldnames, "aircraft_count", "total")
col_ratio = _pick_col(fieldnames, "bad_ratio", "ratio")
cells: dict[str, dict[str, Any]] = {}
for row in reader:
h3_index = str(row.get(col_hex) or "").strip()
if not h3_index or not h3.is_valid_cell(h3_index):
continue
good = int(float(row.get(col_good) or 0)) if col_good and row.get(col_good) not in (None, "") else 0
bad = int(float(row.get(col_bad) or 0)) if col_bad and row.get(col_bad) not in (None, "") else 0
total = (
int(float(row.get(col_total)))
if col_total and row.get(col_total) not in (None, "")
else (good + bad)
)
if total <= 0 and bad <= 0:
continue
if col_ratio and row.get(col_ratio) not in (None, ""):
bad_ratio = max(0.0, min(1.0, float(row[col_ratio])))
else:
bad_ratio = (bad / total) if total > 0 else 0.0
if bad_ratio <= 0.0:
continue
lat, lon = h3.cell_to_latlng(h3_index)
boundary = [
[round(float(b_lat), 5), round(float(b_lon), 5)]
for b_lat, b_lon in h3.cell_to_boundary(h3_index)
]
cells[h3_index] = {
"h3_index": h3_index,
"observed_date": observed_date,
"lat": round(float(lat), 5),
"lon": round(float(lon), 5),
"resolution": int(h3.get_resolution(h3_index)),
"level": classify_jamming_level(bad_ratio),
"bad_ratio": round(float(bad_ratio), 6),
"aircraft_count": total,
"boundary": boundary,
"source": source,
}
return list(cells.values())
class GPSJammingCollector(BaseCollector):
"""Collect daily GPS/GNSS interference hexagons from gpsjam.org."""
name = "gpsjam_interference"
priority = "P2"
module = "L4"
frequency_hours = 6
data_type = "gps_jamming"
fail_on_empty = False
preserve_snapshot_on_failure = True
@property
def manifest_url(self) -> str:
return (
self._resolved_url
or get_data_sources_config().get_yaml_url(self.name)
or GPSJAM_MANIFEST_URL
)
@property
def base_data_url(self) -> str:
val = get_data_sources_config().get_yaml_value("gpsjam_interference.base_data_url")
return str(val or GPSJAM_DATA_BASE_URL).rstrip("/")
async def fetch(self) -> list[dict[str, Any]]:
async with httpx.AsyncClient(timeout=30.0, follow_redirects=True) as client:
manifest_resp = await client.get(
self.manifest_url,
headers={"User-Agent": "Planet-Intelligence-System/1.0 (gpsjam)"},
)
manifest_resp.raise_for_status()
latest_date = parse_manifest_latest_date(manifest_resp.text)
if not latest_date:
return []
csv_url = f"{self.base_data_url}/{latest_date}-h3_4.csv"
data_resp = await client.get(
csv_url,
headers={"User-Agent": "Planet-Intelligence-System/1.0 (gpsjam)"},
)
data_resp.raise_for_status()
return parse_gpsjam_csv(data_resp.text, observed_date=latest_date, source=self.name)
def transform(self, raw_data: list[dict[str, Any]]) -> list[dict[str, Any]]:
return [item for item in raw_data if isinstance(item, dict) and item.get("h3_index")]
async def _save_data(
self,
db: AsyncSession,
data: list[dict[str, Any]],
task_id: int | None = None,
snapshot_id: int | None = None,
) -> int:
now = datetime.now(UTC)
dialect = getattr(getattr(db.get_bind(), "dialect", None), "name", "sqlite")
written = 0
for offset in range(0, len(data), 500):
batch = [{**row, "ingested_at": now} for row in data[offset : offset + 500]]
if not batch:
continue
if dialect == "postgresql":
stmt = pg_insert(GPSJammingCell).values(batch)
stmt = stmt.on_conflict_do_update(
index_elements=[GPSJammingCell.h3_index, GPSJammingCell.observed_date],
set_={
"lat": stmt.excluded.lat,
"lon": stmt.excluded.lon,
"resolution": stmt.excluded.resolution,
"level": stmt.excluded.level,
"bad_ratio": stmt.excluded.bad_ratio,
"aircraft_count": stmt.excluded.aircraft_count,
"boundary": stmt.excluded.boundary,
"source": stmt.excluded.source,
"ingested_at": stmt.excluded.ingested_at,
},
)
await db.execute(stmt)
else:
stmt_sq = sqlite_insert(GPSJammingCell).values(batch)
stmt_sq = stmt_sq.on_conflict_do_update(
index_elements=[GPSJammingCell.h3_index, GPSJammingCell.observed_date],
set_={
"lat": stmt_sq.excluded.lat,
"lon": stmt_sq.excluded.lon,
"resolution": stmt_sq.excluded.resolution,
"level": stmt_sq.excluded.level,
"bad_ratio": stmt_sq.excluded.bad_ratio,
"aircraft_count": stmt_sq.excluded.aircraft_count,
"boundary": stmt_sq.excluded.boundary,
"source": stmt_sq.excluded.source,
"ingested_at": stmt_sq.excluded.ingested_at,
},
)
await db.execute(stmt_sq)
written += len(batch)
if snapshot_id is not None:
snapshot = await db.get(DataSnapshot, snapshot_id)
if snapshot:
snapshot.record_count = written
snapshot.status = SnapshotStatus.SUCCESS.value
snapshot.completed_at = now
snapshot.summary = {
"created": written,
"storage": "gps_jamming_cells",
}
await db.commit()
if written > 0:
try:
await broadcaster.broadcast_earth_update(
{
"event": "earth.layer.changed",
"action": "database_changed",
"source": self.name,
"layers": ["gpsJamming"],
"refresh_strategy": "reload",
"records_processed": written,
}
)
except Exception as exc:
logger.warning_event(
"Failed to broadcast gpsJamming update",
event="gpsjam.broadcast_failed",
context={"error": str(exc)},
)
return written
Loaded 100 of 421 files, more files were not shown because too many files have changed in this diff. Show more