release: bump version to 0.84.0
This commit is contained in:
1 parent
3b1b9ef68c
commit
e1cc27f13d
241 files changed
+42779
-6027
No files matched your search
@@ -15,7 +15,9 @@ from app.api.v1 import (
|
||||
alerts,
|
||||
settings,
|
||||
collected_data,
|
||||
cloud_analysis,
|
||||
compute_intelligence,
|
||||
data_ledger,
|
||||
data_products,
|
||||
layers,
|
||||
visualization,
|
||||
@@ -28,6 +30,7 @@ from app.api.v1 import (
|
||||
situational_awareness,
|
||||
system_control,
|
||||
tv,
|
||||
wind_analysis,
|
||||
)
|
||||
|
||||
api_router = APIRouter()
|
||||
@@ -40,6 +43,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 +54,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,
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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
@@ -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,
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -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"""
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
|
||||
@@ -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}")
|
||||
@@ -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,131 @@ 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"],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
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 +195,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 +247,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,
|
||||
)
|
||||
@@ -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
|
||||
|
||||
@@ -43,6 +43,8 @@ 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")),
|
||||
("satellites", ("tle", "satellite", "spacetrack", "celestrak")),
|
||||
@@ -99,12 +101,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 +119,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
|
||||
|
||||
+404
-1
@@ -6,7 +6,8 @@ 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 +15,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 +55,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,
|
||||
)
|
||||
@@ -676,6 +680,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 +758,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
|
||||
@@ -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()
|
||||
|
||||
+120
-162
@@ -37,23 +37,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,6 +73,9 @@ 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"
|
||||
)
|
||||
@@ -296,7 +293,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 +723,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 +831,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 = {
|
||||
@@ -1693,7 +1714,7 @@ 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])
|
||||
@router.get("/terrain/terrarium/{z}/{x}/{y}.png", dependencies=[_vis_tile_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."""
|
||||
if not _is_valid_terrain_tile(z, x, y):
|
||||
@@ -1783,7 +1804,7 @@ async def _fetch_terrain_tile(
|
||||
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 +2116,8 @@ async def _build_compute_centers_geojson(
|
||||
"type": "FeatureCollection",
|
||||
"features": [],
|
||||
"unresolved": [],
|
||||
"withheld_count": 0,
|
||||
"withheld_by_status": {},
|
||||
"count": 0,
|
||||
"stats": {
|
||||
"total": 0,
|
||||
@@ -2140,6 +2163,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 +2213,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 +2229,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 +2261,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 +2268,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 +2351,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 +2372,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 +2389,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 +2407,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 +2464,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,
|
||||
|
||||
@@ -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)
|
||||
Reference in new issue
Block a user