959 lines
33 KiB
Python
959 lines
33 KiB
Python
"""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}")
|