536 lines
20 KiB
Python
536 lines
20 KiB
Python
"""Per-domain data freshness and intelligence blind-spot assessment service."""
|
||
|
||
from __future__ import annotations
|
||
|
||
from dataclasses import dataclass
|
||
from datetime import UTC, datetime, time as dt_time
|
||
import os
|
||
from typing import Any, Iterable
|
||
|
||
from sqlalchemy import func, select
|
||
from sqlalchemy.ext.asyncio import AsyncSession
|
||
|
||
from app.core.logging import get_logger
|
||
from app.core.time import to_iso8601_utc
|
||
from app.models.aircraft import ADSBSourceHealth, AircraftCurrentState
|
||
from app.models.bgp_incident import BGPIncident
|
||
from app.models.bgp_observation import BGPObservation
|
||
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.datasource import DataSource
|
||
from app.models.datasource_config import DataSourceConfig
|
||
from app.models.earth_news import EarthNewsItem
|
||
from app.models.gps_jamming import GPSJammingCell
|
||
from app.models.task import CollectionTask
|
||
from app.models.vessel import AISSourceHealth, VesselCurrentState
|
||
|
||
logger = get_logger(__name__, service="source_freshness")
|
||
|
||
VALID_FRESHNESS_STATUSES = (
|
||
"fresh",
|
||
"stale",
|
||
"very_stale",
|
||
"degraded",
|
||
"offline",
|
||
"disabled",
|
||
"not_configured",
|
||
)
|
||
_VERY_STALE_MULTIPLIER = 4.0
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class DomainFreshnessSpec:
|
||
"""Declarative freshness policy for a situational awareness domain."""
|
||
|
||
domain: str
|
||
label: str
|
||
label_en: str
|
||
threshold_seconds: int | None
|
||
sources: tuple[str, ...]
|
||
credential_env_hints: tuple[tuple[str, ...], ...] = ()
|
||
revision_based: bool = False
|
||
|
||
|
||
FRESHNESS_DOMAIN_SPECS: tuple[DomainFreshnessSpec, ...] = (
|
||
DomainFreshnessSpec(
|
||
domain="aircraft",
|
||
label="航空器 (ADS-B)",
|
||
label_en="Aircraft (ADS-B)",
|
||
threshold_seconds=5 * 60,
|
||
sources=("adsb_lol_aircraft", "opensky_aircraft", "aircraft_registry"),
|
||
credential_env_hints=(("OPENSKY_CLIENT_ID", "OPENSKY_CLIENT_SECRET"),),
|
||
),
|
||
DomainFreshnessSpec(
|
||
domain="vessels",
|
||
label="海运船舶 (AIS)",
|
||
label_en="Vessels (AIS)",
|
||
threshold_seconds=30 * 60,
|
||
sources=("aisstream_vessels", "barentswatch_vessels"),
|
||
credential_env_hints=(
|
||
("AISSTREAM_API_KEY",),
|
||
("BARENTSWATCH_CLIENT_ID", "BARENTSWATCH_CLIENT_SECRET"),
|
||
),
|
||
),
|
||
DomainFreshnessSpec(
|
||
domain="bgp",
|
||
label="BGP 路由态势",
|
||
label_en="BGP Routing",
|
||
threshold_seconds=30 * 60,
|
||
sources=("ris_live_bgp", "bgpstream_bgp"),
|
||
),
|
||
DomainFreshnessSpec(
|
||
domain="disasters",
|
||
label="自然灾害",
|
||
label_en="Natural Disasters",
|
||
threshold_seconds=60 * 60,
|
||
sources=(
|
||
"usgs_earthquakes",
|
||
"nasa_firms_wildfires",
|
||
"gdacs_disasters",
|
||
"nasa_eonet_events",
|
||
),
|
||
credential_env_hints=(("NASA_FIRMS_MAP_KEY",),),
|
||
),
|
||
DomainFreshnessSpec(
|
||
domain="gps_jamming",
|
||
label="GPS/GNSS 干扰",
|
||
label_en="GPS/GNSS Jamming",
|
||
threshold_seconds=36 * 3600,
|
||
sources=("gpsjam_interference",),
|
||
),
|
||
DomainFreshnessSpec(
|
||
domain="satellites",
|
||
label="在轨卫星 (TLE)",
|
||
label_en="Satellites (TLE)",
|
||
threshold_seconds=48 * 3600,
|
||
sources=("celestrak_tle", "spacetrack_tle"),
|
||
credential_env_hints=(("SPACETRACK_USERNAME", "SPACETRACK_PASSWORD"),),
|
||
),
|
||
DomainFreshnessSpec(
|
||
domain="cables",
|
||
label="海底光缆",
|
||
label_en="Submarine Cables",
|
||
threshold_seconds=14 * 86400,
|
||
sources=("telegeography_cables", "arcgis_cables"),
|
||
),
|
||
DomainFreshnessSpec(
|
||
domain="compute",
|
||
label="全球算力基线",
|
||
label_en="Global Compute",
|
||
threshold_seconds=None,
|
||
sources=("top500", "epoch_ai_gpu"),
|
||
revision_based=True,
|
||
),
|
||
DomainFreshnessSpec(
|
||
domain="news",
|
||
label="全球态势新闻",
|
||
label_en="Global News",
|
||
threshold_seconds=6 * 3600,
|
||
sources=("earth_news", "media_news_archive"),
|
||
),
|
||
)
|
||
|
||
DOMAIN_SPEC_BY_KEY: dict[str, DomainFreshnessSpec] = {
|
||
spec.domain: spec for spec in FRESHNESS_DOMAIN_SPECS
|
||
}
|
||
|
||
|
||
def _coerce_utc(value: Any) -> datetime | None:
|
||
if value is None:
|
||
return None
|
||
if isinstance(value, datetime):
|
||
return value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
|
||
# Date column (e.g. GPSJammingCell.observed_date)
|
||
if hasattr(value, "year") and hasattr(value, "month") and hasattr(value, "day"):
|
||
return datetime.combine(value, dt_time(12, 0, tzinfo=UTC))
|
||
if isinstance(value, str):
|
||
text = value.strip()
|
||
if not text:
|
||
return None
|
||
try:
|
||
parsed = datetime.fromisoformat(text.replace("Z", "+00:00"))
|
||
return parsed.replace(tzinfo=UTC) if parsed.tzinfo is None else parsed.astimezone(UTC)
|
||
except ValueError:
|
||
return None
|
||
return None
|
||
|
||
|
||
def _human_duration(seconds: float | None, *, english: bool = False) -> str:
|
||
if seconds is None:
|
||
return "unknown" if english else "未知"
|
||
sec = max(0, int(seconds))
|
||
if sec < 60:
|
||
return f"{sec}s" if english else f"{sec} 秒"
|
||
if sec < 3600:
|
||
mins = sec // 60
|
||
return f"{mins}m" if english else f"{mins} 分钟"
|
||
if sec < 86400:
|
||
hours = sec // 3600
|
||
return f"{hours}h" if english else f"{hours} 小时"
|
||
days = sec // 86400
|
||
return f"{days}d" if english else f"{days} 天"
|
||
|
||
|
||
def _is_offline_mode(explicit: bool | None = None) -> bool:
|
||
if explicit is not None:
|
||
return bool(explicit)
|
||
raw = str(os.getenv("PLANET_OFFLINE_MODE", "")).strip().lower()
|
||
return raw in {"1", "true", "yes", "on"}
|
||
|
||
|
||
def _max_ts(values: Iterable[datetime | None]) -> datetime | None:
|
||
cleaned = [dt for dt in (_coerce_utc(v) for v in values) if dt is not None]
|
||
return max(cleaned) if cleaned else None
|
||
|
||
|
||
def classify_domain_freshness(
|
||
spec: DomainFreshnessSpec,
|
||
*,
|
||
now: datetime,
|
||
last_success_at: datetime | None,
|
||
has_active_source: bool,
|
||
has_any_source: bool,
|
||
all_disabled: bool,
|
||
has_unconfigured_only: bool,
|
||
has_recent_failure: bool,
|
||
all_failed_offline: bool,
|
||
offline_mode: bool = False,
|
||
published_revision_id: str | None = None,
|
||
) -> dict[str, Any]:
|
||
"""Classify a single domain into one of the seven freshness states with sanitized reasons."""
|
||
threshold = spec.threshold_seconds
|
||
age_seconds: int | None = None
|
||
coerced_last = _coerce_utc(last_success_at)
|
||
if coerced_last is not None:
|
||
age_seconds = max(0, int((now - coerced_last).total_seconds()))
|
||
|
||
if spec.revision_based:
|
||
if published_revision_id:
|
||
status_val = "fresh"
|
||
reason = f"当前生效基线版本 {published_revision_id}"
|
||
reason_en = f"Active published baseline {published_revision_id}"
|
||
else:
|
||
status_val = "not_configured"
|
||
reason = "尚未发布算力基线版本"
|
||
reason_en = "No published compute baseline revision"
|
||
elif all_disabled:
|
||
status_val = "disabled"
|
||
reason = "该域数据源已停用"
|
||
reason_en = "All sources in this domain are disabled"
|
||
elif (offline_mode and coerced_last is None) or (all_failed_offline and coerced_last is None):
|
||
status_val = "offline"
|
||
reason = "离线模式或外部数据源暂不可达"
|
||
reason_en = "Offline mode or external sources currently unreachable"
|
||
elif offline_mode and age_seconds is not None and threshold is not None and age_seconds > threshold:
|
||
status_val = "offline"
|
||
reason = f"离线模式(仅保留 {_human_duration(age_seconds)} 前缓存)"
|
||
reason_en = f"Offline mode (cached snapshot from {_human_duration(age_seconds, english=True)} ago)"
|
||
elif has_unconfigured_only and coerced_last is None and not has_active_source:
|
||
status_val = "not_configured"
|
||
reason = "尚未配置所需采集凭据"
|
||
reason_en = "Required collector credentials are not configured"
|
||
elif coerced_last is None:
|
||
if has_recent_failure:
|
||
status_val = "degraded"
|
||
reason = "最近采集失败,尚无可用成功记录"
|
||
reason_en = "Recent collection attempt failed without prior success"
|
||
elif not has_any_source:
|
||
status_val = "not_configured"
|
||
reason = "尚未初始化该域数据源"
|
||
reason_en = "Domain data sources are not configured"
|
||
else:
|
||
status_val = "not_configured"
|
||
reason = "尚无成功采集记录"
|
||
reason_en = "No successful ingestion recorded yet"
|
||
elif threshold is not None and age_seconds is not None:
|
||
very_stale_limit = threshold * _VERY_STALE_MULTIPLIER
|
||
age_zh = _human_duration(age_seconds)
|
||
age_en = _human_duration(age_seconds, english=True)
|
||
thresh_zh = _human_duration(threshold)
|
||
thresh_en = _human_duration(threshold, english=True)
|
||
|
||
if age_seconds > very_stale_limit:
|
||
status_val = "very_stale"
|
||
reason = f"数据已严重滞后(距今 {age_zh},阈值 {thresh_zh})"
|
||
reason_en = f"Critically stale ({age_en} old vs {thresh_en} threshold)"
|
||
elif age_seconds > threshold:
|
||
status_val = "stale"
|
||
reason = f"数据已超过新鲜阈值(距今 {age_zh},阈值 {thresh_zh})"
|
||
reason_en = f"Stale ({age_en} old vs {thresh_en} threshold)"
|
||
elif all_failed_offline:
|
||
status_val = "offline"
|
||
reason = "外部上游暂不可达,当前仅展示缓存快照"
|
||
reason_en = "External upstream unreachable; showing cached snapshot"
|
||
elif has_recent_failure:
|
||
status_val = "degraded"
|
||
reason = f"部分采集源异常,数据仍处于降级可用窗口内({age_zh}前更新)"
|
||
reason_en = f"Degraded source health; cached data updated {age_en} ago"
|
||
else:
|
||
status_val = "fresh"
|
||
reason = f"数据正常(更新于 {age_zh} 前)"
|
||
reason_en = f"Fresh (updated {age_en} ago)"
|
||
else:
|
||
status_val = "fresh"
|
||
reason = "数据正常"
|
||
reason_en = "Fresh"
|
||
|
||
return {
|
||
"domain": spec.domain,
|
||
"label": spec.label,
|
||
"label_en": spec.label_en,
|
||
"status": status_val,
|
||
"is_blind_spot": status_val != "fresh",
|
||
"reason": reason,
|
||
"reason_en": reason_en,
|
||
"last_success_at": to_iso8601_utc(coerced_last),
|
||
"age_seconds": age_seconds,
|
||
"threshold_seconds": threshold,
|
||
}
|
||
|
||
|
||
async def _safe_scalar(db: AsyncSession, stmt: Any) -> Any:
|
||
if not hasattr(db, "execute"):
|
||
return None
|
||
try:
|
||
res = await db.execute(stmt)
|
||
if hasattr(res, "scalar"):
|
||
return res.scalar()
|
||
return None
|
||
except Exception as exc:
|
||
logger.debug_event(
|
||
"Skipped unavailable table/metric during freshness check",
|
||
event="source_freshness.scalar_skipped",
|
||
context={"error_type": type(exc).__name__},
|
||
)
|
||
return None
|
||
|
||
|
||
async def _safe_scalars_all(db: AsyncSession, stmt: Any) -> list[Any]:
|
||
if not hasattr(db, "execute"):
|
||
return []
|
||
try:
|
||
res = await db.execute(stmt)
|
||
if hasattr(res, "scalars"):
|
||
return list(res.scalars().all())
|
||
return []
|
||
except Exception as exc:
|
||
logger.debug_event(
|
||
"Skipped unavailable list query during freshness check",
|
||
event="source_freshness.list_skipped",
|
||
context={"error_type": type(exc).__name__},
|
||
)
|
||
return []
|
||
|
||
|
||
def _has_env_credentials(spec: DomainFreshnessSpec) -> bool:
|
||
for group in spec.credential_env_hints:
|
||
if group and all(bool(str(os.getenv(k, "")).strip()) for k in group):
|
||
return True
|
||
return False
|
||
|
||
|
||
async def _query_disaster_latest_ts(db: AsyncSession) -> datetime | None:
|
||
try:
|
||
from app.models.disaster import DisasterEvent # noqa: WPS433
|
||
|
||
return _coerce_utc(await _safe_scalar(db, select(func.max(DisasterEvent.observed_at))))
|
||
except Exception:
|
||
return None
|
||
|
||
|
||
async def _query_domain_latest_data_ts(db: AsyncSession, domain: str) -> datetime | None:
|
||
if domain == "aircraft":
|
||
ts_state = await _safe_scalar(db, select(func.max(AircraftCurrentState.observed_at)))
|
||
ts_health = await _safe_scalar(db, select(func.max(ADSBSourceHealth.last_success_at)))
|
||
return _max_ts([ts_state, ts_health])
|
||
if domain == "vessels":
|
||
ts_state = await _safe_scalar(db, select(func.max(VesselCurrentState.observed_at)))
|
||
ts_health = await _safe_scalar(db, select(func.max(AISSourceHealth.last_success_at)))
|
||
return _max_ts([ts_state, ts_health])
|
||
if domain == "bgp":
|
||
ts_inc = await _safe_scalar(db, select(func.max(BGPIncident.created_at)))
|
||
ts_obs = await _safe_scalar(db, select(func.max(BGPObservation.observed_at)))
|
||
return _max_ts([ts_inc, ts_obs])
|
||
if domain == "disasters":
|
||
return await _query_disaster_latest_ts(db)
|
||
if domain == "gps_jamming":
|
||
ts_ing = await _safe_scalar(db, select(func.max(GPSJammingCell.ingested_at)))
|
||
ts_date = await _safe_scalar(db, select(func.max(GPSJammingCell.observed_date)))
|
||
return _max_ts([ts_ing, ts_date])
|
||
if domain == "news":
|
||
ts_seen = await _safe_scalar(db, select(func.max(EarthNewsItem.last_seen_at)))
|
||
ts_pub = await _safe_scalar(db, select(func.max(EarthNewsItem.published_at)))
|
||
return _max_ts([ts_seen, ts_pub])
|
||
if domain in {"satellites", "cables"}:
|
||
sources = DOMAIN_SPEC_BY_KEY[domain].sources
|
||
ts_snap = await _safe_scalar(
|
||
db,
|
||
select(func.max(DataSnapshot.completed_at)).where(
|
||
DataSnapshot.source.in_(sources),
|
||
DataSnapshot.status == "success",
|
||
),
|
||
)
|
||
ts_col = await _safe_scalar(
|
||
db,
|
||
select(func.max(CollectedData.collected_at)).where(CollectedData.source.in_(sources)),
|
||
)
|
||
return _max_ts([ts_snap, ts_col])
|
||
return None
|
||
|
||
|
||
async def compute_domain_freshness(
|
||
db: AsyncSession,
|
||
*,
|
||
now: datetime | None = None,
|
||
offline_mode: bool | None = None,
|
||
) -> dict[str, Any]:
|
||
"""Evaluate freshness and intelligence blind spots across all built-in domains."""
|
||
current_now = now.astimezone(UTC) if now is not None else datetime.now(UTC)
|
||
effective_offline = _is_offline_mode(offline_mode)
|
||
|
||
all_sources = await _safe_scalars_all(db, select(DataSource))
|
||
ds_by_source: dict[str, DataSource] = {
|
||
str(getattr(row, "source", "") or ""): row for row in all_sources
|
||
}
|
||
|
||
configs = await _safe_scalars_all(db, select(DataSourceConfig).where(DataSourceConfig.is_active == True)) # noqa: E712
|
||
configured_names = {str(getattr(cfg, "name", "") or "").lower() for cfg in configs}
|
||
|
||
recent_tasks = await _safe_scalars_all(
|
||
db,
|
||
select(CollectionTask)
|
||
.order_by(CollectionTask.created_at.desc())
|
||
.limit(120),
|
||
)
|
||
latest_task_by_source: dict[str, CollectionTask] = {}
|
||
for task in recent_tasks:
|
||
src = str(getattr(task, "source", "") or "")
|
||
if src and src not in latest_task_by_source:
|
||
latest_task_by_source[src] = task
|
||
|
||
latest_compute_rev = None
|
||
if hasattr(db, "execute"):
|
||
rows = await _safe_scalars_all(
|
||
db,
|
||
select(ComputeConfigurationRevision)
|
||
.order_by(ComputeConfigurationRevision.published_at.desc(), ComputeConfigurationRevision.id.desc())
|
||
.limit(1),
|
||
)
|
||
if rows:
|
||
latest_compute_rev = rows[0]
|
||
|
||
domains: list[dict[str, Any]] = []
|
||
blind_spots: list[dict[str, Any]] = []
|
||
|
||
for spec in FRESHNESS_DOMAIN_SPECS:
|
||
matched_ds = [ds_by_source[s] for s in spec.sources if s in ds_by_source]
|
||
active_ds = [ds for ds in matched_ds if bool(getattr(ds, "is_active", True))]
|
||
all_disabled = bool(matched_ds) and len(active_ds) == 0
|
||
|
||
success_ds_ts = [
|
||
getattr(ds, "last_run_at", None)
|
||
for ds in matched_ds
|
||
if str(getattr(ds, "last_status", "") or "").lower() in {"success", "ok", "completed", ""}
|
||
]
|
||
snap_ts = None
|
||
if spec.sources:
|
||
snap_ts = await _safe_scalar(
|
||
db,
|
||
select(func.max(DataSnapshot.completed_at)).where(
|
||
DataSnapshot.source.in_(spec.sources),
|
||
DataSnapshot.status == "success",
|
||
),
|
||
)
|
||
if spec.revision_based and latest_compute_rev is not None:
|
||
data_ts = _coerce_utc(getattr(latest_compute_rev, "published_at", None))
|
||
pub_id = str(getattr(latest_compute_rev, "publish_id", "") or "") or None
|
||
else:
|
||
data_ts = await _query_domain_latest_data_ts(db, spec.domain)
|
||
pub_id = None
|
||
|
||
last_success_at = _max_ts([data_ts, snap_ts, *success_ds_ts])
|
||
|
||
# Sanitized status inspection from DataSource / latest task (never forward raw error text).
|
||
recent_failures = 0
|
||
offline_failures = 0
|
||
unconfigured_count = 0
|
||
for src in spec.sources:
|
||
ds = ds_by_source.get(src)
|
||
task = latest_task_by_source.get(src)
|
||
ds_status = str(getattr(ds, "last_status", "") or "").lower() if ds else ""
|
||
task_status = str(getattr(task, "status", "") or "").lower() if task else ""
|
||
err_msg = str(getattr(task, "error_message", "") or "").lower() if task else ""
|
||
if ds_status in {"not_configured", "missing_credentials"} or "not_configured" in err_msg:
|
||
unconfigured_count += 1
|
||
elif ds_status in {"offline", "unreachable"} or any(
|
||
tok in err_msg for tok in ("offline", "connecterror", "name resolution", "network is unreachable", "timed out")
|
||
):
|
||
offline_failures += 1
|
||
recent_failures += 1
|
||
elif ds_status in {"failed", "error", "degraded"} or task_status == "failed":
|
||
recent_failures += 1
|
||
|
||
has_unconfigured_only = bool(matched_ds) and (
|
||
unconfigured_count == len(matched_ds)
|
||
and not _has_env_credentials(spec)
|
||
and not any(s.lower() in configured_names for s in spec.sources)
|
||
)
|
||
source_pool_count = len(active_ds) or len(spec.sources)
|
||
all_failed_offline = offline_failures > 0 and offline_failures >= source_pool_count
|
||
|
||
entry = classify_domain_freshness(
|
||
spec,
|
||
now=current_now,
|
||
last_success_at=last_success_at,
|
||
has_active_source=bool(active_ds),
|
||
has_any_source=bool(matched_ds),
|
||
all_disabled=all_disabled,
|
||
has_unconfigured_only=has_unconfigured_only,
|
||
has_recent_failure=recent_failures > 0,
|
||
all_failed_offline=all_failed_offline,
|
||
offline_mode=effective_offline,
|
||
published_revision_id=pub_id,
|
||
)
|
||
entry["active_source_count"] = len(active_ds)
|
||
entry["configured_source_count"] = len(matched_ds)
|
||
domains.append(entry)
|
||
|
||
if entry["is_blind_spot"]:
|
||
blind_spots.append(
|
||
{
|
||
"domain": entry["domain"],
|
||
"label": entry["label"],
|
||
"label_en": entry["label_en"],
|
||
"status": entry["status"],
|
||
"last_success_at": entry["last_success_at"],
|
||
"reason": entry["reason"],
|
||
"reason_en": entry["reason_en"],
|
||
"guidance": "该域非最新(!= fresh),禁止将该域描述为“无事件”或“态势平静”。",
|
||
}
|
||
)
|
||
|
||
statuses = [d["status"] for d in domains]
|
||
if all(s == "fresh" for s in statuses):
|
||
overall = "fresh"
|
||
elif any(s == "offline" for s in statuses):
|
||
overall = "offline"
|
||
elif any(s in {"very_stale", "degraded"} for s in statuses):
|
||
overall = "degraded"
|
||
elif any(s == "stale" for s in statuses):
|
||
overall = "stale"
|
||
else:
|
||
overall = "partial"
|
||
|
||
fresh_count = sum(1 for d in domains if d["status"] == "fresh")
|
||
return {
|
||
"checked_at": to_iso8601_utc(current_now),
|
||
"overall_status": overall,
|
||
"offline_mode": effective_offline,
|
||
"fresh_count": fresh_count,
|
||
"total_domains": len(domains),
|
||
"blind_spot_count": len(blind_spots),
|
||
"domains": domains,
|
||
"blind_spots": blind_spots,
|
||
}
|