Files
planet/backend/app/api/v1/disasters.py
T
linkong 1c0066edc6
ci / backend (push) Waiting to run
ci / frontend (push) Waiting to run
release: bump version to 0.85.0
2026-12-06 22:47:23 +08:00

81 lines
2.7 KiB
Python

"""Natural disaster telemetry snapshot API."""
from __future__ import annotations
from datetime import UTC, datetime, timedelta
from typing import Any
from fastapi import APIRouter, Depends, Query
from sqlalchemy import desc, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.access_gate import require_earth_or_api_access
from app.core.time import to_iso8601_utc
from app.db.session import get_db
from app.models.disaster import DisasterEvent
router = APIRouter(dependencies=[Depends(require_earth_or_api_access("visualization:read"))])
_DEFAULT_STALE_SECONDS = 60 * 60
def _coerce_utc(val: Any) -> datetime | None:
if isinstance(val, datetime):
return val.replace(tzinfo=UTC) if val.tzinfo is None else val.astimezone(UTC)
return None
@router.get("/snapshot")
async def get_disaster_snapshot(
types: str | None = Query(default=None, description="Comma-separated disaster event types"),
since_hours: int = Query(default=72, ge=1, le=720),
include_duplicates: bool = Query(default=False),
limit: int = Query(default=1000, ge=1, le=5000),
db: AsyncSession = Depends(get_db),
) -> dict[str, Any]:
"""Return recent normalized natural disaster events with freshness and provenance fields."""
now = datetime.now(UTC)
cutoff = now - timedelta(hours=since_hours)
stmt = (
select(DisasterEvent)
.where(DisasterEvent.observed_at >= cutoff)
.order_by(desc(DisasterEvent.observed_at), desc(DisasterEvent.id))
.limit(limit)
)
if types:
wanted = [t.strip().lower() for t in types.split(",") if t.strip()]
if wanted:
stmt = stmt.where(DisasterEvent.event_type.in_(wanted))
if not include_duplicates:
stmt = stmt.where(DisasterEvent.duplicate_of.is_(None))
rows = list((await db.execute(stmt)).scalars().all())
by_type: dict[str, int] = {}
high_count = 0
latest_obs: datetime | None = None
items: list[dict[str, Any]] = []
for row in rows:
obs = _coerce_utc(row.observed_at)
if obs and (latest_obs is None or obs > latest_obs):
latest_obs = obs
is_stale = bool(obs is None or (now - obs).total_seconds() > _DEFAULT_STALE_SECONDS)
ev_type = str(row.event_type or "other")
by_type[ev_type] = by_type.get(ev_type, 0) + 1
if str(row.severity or "").lower() == "high":
high_count += 1
payload = row.to_dict()
payload["is_stale"] = is_stale
items.append(payload)
return {
"generated_at": to_iso8601_utc(now),
"since_hours": since_hours,
"count": len(items),
"high_count": high_count,
"by_type": by_type,
"latest_observed_at": to_iso8601_utc(latest_obs),
"items": items,
}