Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1c0066edc6 | ||
|
|
30b44ec00d |
No files matched your search
@@ -187,7 +187,9 @@ and builds/uploads **only** the affected targets:
|
||||
service image(s) + OCI `release-manifest:<tag>`, **skips creating a Gitea Release**,
|
||||
skips desktop packaging and client hotfix updates, and deploys only the changed container(s) on production.
|
||||
- `frontend/public/earth/**`-only changes (`client.mode == "hotfix"`): emits only the L1 Earth hotfix bundle
|
||||
(`./planet.sh bundle --hotfix`) while keeping the prior desktop `shell_version`, and creates a Gitea Release with `release-manifest.json` + hotfix bundle.
|
||||
(`./planet.sh bundle --hotfix`) while keeping the prior desktop `shell_version`, embeds the hotfix bundle and
|
||||
release notes into OCI `release-manifest:<tag>` (`bundle_storage: "oci"`), and **skips creating a Gitea Release**
|
||||
so `/releases/latest` always preserves full desktop installers while production auto-publishes the L1 hotfix.
|
||||
- `client/**` changes (`client.mode == "full"`): builds cross-platform desktop installers (`--all`) plus the
|
||||
L1 hotfix bundle, and creates a Gitea Release with installers + `release-manifest.json`.
|
||||
|
||||
|
||||
@@ -173,6 +173,8 @@ data/earth-boundary-sources/
|
||||
data/earth-clouds/
|
||||
data/earth-tiles/
|
||||
data/earth-wind/
|
||||
data/aircraft_registry/
|
||||
data/earth-terrain-cache/
|
||||
|
||||
# Earth boundary sources and generated PMTiles artifacts live in the backend
|
||||
# boundary data volume (built by the Earth "高精" rebuild), never in Git or in
|
||||
|
||||
@@ -127,11 +127,13 @@ the user's login interactive shell instead of assuming a specific dotfile.
|
||||
committed files.
|
||||
- Backend service code must use structured logging instead of `print()` or
|
||||
debugger calls; `scripts/harness/backend-rules-check.sh` enforces this.
|
||||
- **Client-Only Gitea Releases**: Releases without client updates
|
||||
(`client.mode == "none"`) push only changed container images plus OCI
|
||||
`release-manifest:<tag>` and must **not** create a Gitea Release; only
|
||||
`hotfix` or `full` client releases create a Gitea Release, and production
|
||||
`planet-release-deploy` reconciles from Git tags + OCI `release-manifest:<tag>`.
|
||||
- **Client-Only Gitea Releases**: Releases without desktop shell updates
|
||||
(`client.mode == "none"` or `"hotfix"`) push changed container images plus OCI
|
||||
`release-manifest:<tag>` (embedding L1 hotfix bundles in OCI for `hotfix`)
|
||||
and must **not** create a Gitea Release; only `full` desktop client releases
|
||||
create a Gitea Release so `/releases/latest` always carries installers, and
|
||||
production `planet-release-deploy` reconciles from Git tags + OCI
|
||||
`release-manifest:<tag>`.
|
||||
- **Release Publish vs. Production Deployment (`发版 ≠ 已部署`)**:
|
||||
`scripts/release_publish.py` only publishes container images, OCI
|
||||
`release-manifest:<tag>`, and optional Gitea Releases; it never updates
|
||||
|
||||
@@ -1,14 +1,21 @@
|
||||
from app.api.v1 import card_images
|
||||
from fastapi import APIRouter
|
||||
from app.api.v1 import (
|
||||
actions,
|
||||
ai,
|
||||
aircraft,
|
||||
api_keys,
|
||||
auth,
|
||||
cases,
|
||||
users,
|
||||
datasource_config,
|
||||
datasources,
|
||||
disasters,
|
||||
docs,
|
||||
earth,
|
||||
geofences,
|
||||
gps_jamming,
|
||||
incidents,
|
||||
client_updates,
|
||||
tasks,
|
||||
dashboard,
|
||||
@@ -25,8 +32,10 @@ from app.api.v1 import (
|
||||
vessels,
|
||||
bgp,
|
||||
news,
|
||||
ontology,
|
||||
interactables,
|
||||
realtime_sources,
|
||||
replay,
|
||||
situational_awareness,
|
||||
system_control,
|
||||
tv,
|
||||
@@ -70,10 +79,19 @@ api_router.include_router(
|
||||
tags=["vessel-aggregation"],
|
||||
)
|
||||
api_router.include_router(vessels.router, prefix="/vessels", tags=["vessels"])
|
||||
api_router.include_router(aircraft.router, prefix="/aircraft", tags=["aircraft"])
|
||||
api_router.include_router(gps_jamming.router, prefix="/gps-jamming", tags=["gps-jamming"])
|
||||
api_router.include_router(disasters.router, prefix="/disasters", tags=["disasters"])
|
||||
api_router.include_router(geofences.router, prefix="/geofences", tags=["geofences"])
|
||||
api_router.include_router(incidents.router, prefix="/incidents", tags=["incidents"])
|
||||
api_router.include_router(cases.router, prefix="/cases", tags=["cases"])
|
||||
api_router.include_router(actions.router, prefix="/actions", tags=["actions"])
|
||||
api_router.include_router(bgp.router, prefix="/bgp", tags=["bgp"])
|
||||
api_router.include_router(tv.router, prefix="/tv", tags=["tv"])
|
||||
api_router.include_router(news.router, prefix="/news", tags=["news"])
|
||||
api_router.include_router(ontology.router, prefix="/ontology", tags=["ontology"])
|
||||
api_router.include_router(interactables.router, prefix="/interactables", tags=["interactables"])
|
||||
api_router.include_router(realtime_sources.router, prefix="/realtime-sources", tags=["realtime-sources"])
|
||||
api_router.include_router(replay.router, prefix="/replay", tags=["replay"])
|
||||
|
||||
api_router.include_router(card_images.router, prefix="/earth/card-images", tags=["card-images"])
|
||||
@@ -0,0 +1,182 @@
|
||||
"""Action Requests, Approval Matrix & Webhook Allowlist API (§4.5)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy import desc, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.access_gate import get_current_user, require_admin_user, require_earth_or_api_access
|
||||
from app.core.enums import UserRole
|
||||
from app.db.session import get_db
|
||||
from app.models.action_request import ActionRequest
|
||||
from app.models.system_setting import SystemSetting
|
||||
from app.models.user import User
|
||||
from app.services.actions import (
|
||||
ACTION_TYPE_REGISTRY,
|
||||
WEBHOOK_ALLOWLIST_CATEGORY,
|
||||
WEBHOOK_ALLOWLIST_KEY,
|
||||
ActionPermissionError,
|
||||
ActionValidationError,
|
||||
decide_action_request,
|
||||
get_webhook_allowlist,
|
||||
submit_action_request,
|
||||
)
|
||||
|
||||
router = APIRouter()
|
||||
_read_dep = Depends(require_earth_or_api_access("visualization:read"))
|
||||
|
||||
|
||||
class ActionCreateBody(BaseModel):
|
||||
action_type: str = Field(min_length=1, max_length=80)
|
||||
target_object_ids: list[str] = Field(default_factory=list)
|
||||
params: dict[str, Any] = Field(default_factory=dict)
|
||||
source_workflow_run_id: str | None = None
|
||||
ai_suggested: bool = False
|
||||
|
||||
|
||||
class ActionDecisionBody(BaseModel):
|
||||
decision_reason: str = Field(default="", max_length=1000)
|
||||
|
||||
|
||||
class AllowlistUpdateBody(BaseModel):
|
||||
urls: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
@router.get("/types", dependencies=[_read_dep])
|
||||
async def list_action_types() -> dict[str, Any]:
|
||||
return {"items": list(ACTION_TYPE_REGISTRY.values())}
|
||||
|
||||
|
||||
@router.get("/webhook-allowlist")
|
||||
async def read_webhook_allowlist(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
_admin: User = Depends(require_admin_user),
|
||||
) -> dict[str, Any]:
|
||||
return {"urls": await get_webhook_allowlist(db)}
|
||||
|
||||
|
||||
@router.put("/webhook-allowlist")
|
||||
async def update_webhook_allowlist(
|
||||
body: AllowlistUpdateBody,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(require_admin_user),
|
||||
) -> dict[str, Any]:
|
||||
if str(getattr(current_user, "role", "")).lower() != UserRole.SUPER_ADMIN.value:
|
||||
raise HTTPException(status_code=403, detail="Only super_admin can update webhook allowlist")
|
||||
cleaned = [str(u).strip() for u in body.urls if str(u).strip()]
|
||||
row = (
|
||||
await db.execute(
|
||||
select(SystemSetting).where(SystemSetting.category == WEBHOOK_ALLOWLIST_CATEGORY)
|
||||
)
|
||||
).scalars().first()
|
||||
if row is None:
|
||||
row = SystemSetting(
|
||||
category=WEBHOOK_ALLOWLIST_CATEGORY,
|
||||
payload={WEBHOOK_ALLOWLIST_KEY: cleaned},
|
||||
)
|
||||
db.add(row)
|
||||
else:
|
||||
row.payload = {**dict(row.payload or {}), WEBHOOK_ALLOWLIST_KEY: cleaned}
|
||||
await db.commit()
|
||||
return {"urls": cleaned}
|
||||
|
||||
|
||||
@router.get("", dependencies=[_read_dep])
|
||||
async def list_action_requests(
|
||||
object_id: str | None = Query(default=None),
|
||||
status: str | None = Query(default=None),
|
||||
limit: int = Query(default=100, ge=1, le=500),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> dict[str, Any]:
|
||||
stmt = select(ActionRequest).order_by(desc(ActionRequest.requested_at), desc(ActionRequest.id)).limit(limit)
|
||||
if status:
|
||||
stmt = stmt.where(ActionRequest.status == status.strip())
|
||||
rows = list((await db.execute(stmt)).scalars().all())
|
||||
items = [r.to_dict() for r in rows]
|
||||
if object_id:
|
||||
oid = object_id.strip()
|
||||
items = [it for it in items if oid in (it.get("target_object_ids") or [])]
|
||||
return {"items": items, "count": len(items)}
|
||||
|
||||
|
||||
@router.post("")
|
||||
async def create_action_request(
|
||||
body: ActionCreateBody,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
) -> dict[str, Any]:
|
||||
try:
|
||||
req = await submit_action_request(
|
||||
db,
|
||||
action_type=body.action_type.strip(),
|
||||
target_object_ids=body.target_object_ids,
|
||||
params=body.params,
|
||||
actor_id=getattr(current_user, "id", None),
|
||||
actor_name=str(getattr(current_user, "username", "") or "unknown"),
|
||||
actor_role=str(getattr(current_user, "role", "") or "viewer"),
|
||||
source_workflow_run_id=body.source_workflow_run_id,
|
||||
ai_suggested=bool(body.ai_suggested),
|
||||
)
|
||||
return req.to_dict()
|
||||
except ActionPermissionError as exc:
|
||||
raise HTTPException(status_code=403, detail=str(exc)) from exc
|
||||
except ActionValidationError as exc:
|
||||
raise HTTPException(status_code=422, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@router.post("/{action_id}/approve")
|
||||
async def approve_action_request(
|
||||
action_id: int,
|
||||
body: ActionDecisionBody,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(require_admin_user),
|
||||
) -> dict[str, Any]:
|
||||
req = await db.get(ActionRequest, action_id)
|
||||
if req is None:
|
||||
raise HTTPException(status_code=404, detail="Action request not found")
|
||||
try:
|
||||
updated = await decide_action_request(
|
||||
db,
|
||||
req=req,
|
||||
decision="approve",
|
||||
decision_reason=body.decision_reason,
|
||||
actor_id=getattr(current_user, "id", None),
|
||||
actor_name=str(getattr(current_user, "username", "") or "admin"),
|
||||
actor_role=str(getattr(current_user, "role", "") or "admin"),
|
||||
)
|
||||
return updated.to_dict()
|
||||
except ActionPermissionError as exc:
|
||||
raise HTTPException(status_code=403, detail=str(exc)) from exc
|
||||
except ActionValidationError as exc:
|
||||
raise HTTPException(status_code=422, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@router.post("/{action_id}/reject")
|
||||
async def reject_action_request(
|
||||
action_id: int,
|
||||
body: ActionDecisionBody,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(require_admin_user),
|
||||
) -> dict[str, Any]:
|
||||
req = await db.get(ActionRequest, action_id)
|
||||
if req is None:
|
||||
raise HTTPException(status_code=404, detail="Action request not found")
|
||||
try:
|
||||
updated = await decide_action_request(
|
||||
db,
|
||||
req=req,
|
||||
decision="reject",
|
||||
decision_reason=body.decision_reason,
|
||||
actor_id=getattr(current_user, "id", None),
|
||||
actor_name=str(getattr(current_user, "username", "") or "admin"),
|
||||
actor_role=str(getattr(current_user, "role", "") or "admin"),
|
||||
)
|
||||
return updated.to_dict()
|
||||
except ActionPermissionError as exc:
|
||||
raise HTTPException(status_code=403, detail=str(exc)) from exc
|
||||
except ActionValidationError as exc:
|
||||
raise HTTPException(status_code=422, detail=str(exc)) from exc
|
||||
@@ -0,0 +1,226 @@
|
||||
"""Aircraft ADS-B columnar snapshot, detail, and track APIs."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from sqlalchemy import desc, or_, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.api.v1.visualization import _parse_bbox
|
||||
from app.core.access_gate import require_earth_or_api_access
|
||||
from app.core.time import to_iso8601_utc
|
||||
from app.db.session import get_db
|
||||
from app.models.aircraft import (
|
||||
ADSBSourceHealth,
|
||||
AircraftCurrentState,
|
||||
AircraftPosition,
|
||||
AircraftStatic,
|
||||
)
|
||||
from app.services.aircraft_aggregation import coerce_utc_datetime
|
||||
from app.services.aircraft_types import normalize_icao24
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
AIRCRAFT_FRESHNESS_SECONDS = 300
|
||||
MAX_AIRCRAFT_SNAPSHOT_LIMIT = 20000
|
||||
AIRCRAFT_ATTRIBUTION = "adsb.lol (ODbL) · OpenSky Network (Non-Commercial / Research)"
|
||||
|
||||
SNAPSHOT_FIELDS: tuple[str, ...] = (
|
||||
"icao24",
|
||||
"callsign",
|
||||
"lat",
|
||||
"lon",
|
||||
"altitude_m",
|
||||
"ground_speed_ms",
|
||||
"track_deg",
|
||||
"vertical_rate_ms",
|
||||
"category",
|
||||
"is_military",
|
||||
"is_emergency",
|
||||
"emergency_code",
|
||||
"on_ground",
|
||||
"source",
|
||||
"observed_at",
|
||||
)
|
||||
|
||||
|
||||
@router.get("/snapshot", dependencies=[Depends(require_earth_or_api_access("aircraft:read"))])
|
||||
async def get_aircraft_snapshot(
|
||||
bbox: Optional[str] = Query(None, description="Optional bbox as lon_min,lat_min,lon_max,lat_max"),
|
||||
category: Optional[str] = Query(None, description="Comma-separated aircraft categories"),
|
||||
include_ground: bool = Query(False, description="Include aircraft reported on ground"),
|
||||
limit: int = Query(10000, ge=1, le=MAX_AIRCRAFT_SNAPSHOT_LIMIT),
|
||||
since_minutes: int = Query(15, ge=1, le=1440),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
now = datetime.now(UTC)
|
||||
cutoff = now - timedelta(minutes=since_minutes)
|
||||
|
||||
stmt = select(AircraftCurrentState).where(AircraftCurrentState.observed_at >= cutoff)
|
||||
if not include_ground:
|
||||
stmt = stmt.where(AircraftCurrentState.on_ground.is_(False))
|
||||
|
||||
if bbox:
|
||||
parsed = _parse_bbox(bbox)
|
||||
if parsed is None:
|
||||
raise HTTPException(status_code=400, detail="Invalid bbox parameter")
|
||||
lon_min, lat_min, lon_max, lat_max = parsed
|
||||
stmt = stmt.where(
|
||||
AircraftCurrentState.lat >= lat_min,
|
||||
AircraftCurrentState.lat <= lat_max,
|
||||
)
|
||||
if lon_min <= lon_max:
|
||||
stmt = stmt.where(
|
||||
AircraftCurrentState.lon >= lon_min,
|
||||
AircraftCurrentState.lon <= lon_max,
|
||||
)
|
||||
else:
|
||||
stmt = stmt.where(
|
||||
or_(
|
||||
AircraftCurrentState.lon >= lon_min,
|
||||
AircraftCurrentState.lon <= lon_max,
|
||||
)
|
||||
)
|
||||
|
||||
if category:
|
||||
categories = [part.strip().lower() for part in category.split(",") if part.strip()]
|
||||
if categories:
|
||||
stmt = stmt.where(AircraftCurrentState.category.in_(categories))
|
||||
|
||||
stmt = stmt.order_by(
|
||||
desc(AircraftCurrentState.is_emergency),
|
||||
desc(AircraftCurrentState.is_military),
|
||||
desc(AircraftCurrentState.observed_at),
|
||||
).limit(limit)
|
||||
|
||||
result = await db.execute(stmt)
|
||||
records = list(result.scalars().all())
|
||||
|
||||
rows: list[list[object]] = []
|
||||
for rec in records:
|
||||
alt_m = rec.geo_altitude_m if rec.geo_altitude_m is not None else rec.baro_altitude_m
|
||||
rows.append(
|
||||
[
|
||||
rec.icao24,
|
||||
rec.callsign,
|
||||
round(float(rec.lat), 5),
|
||||
round(float(rec.lon), 5),
|
||||
round(float(alt_m), 1) if alt_m is not None else None,
|
||||
round(float(rec.ground_speed_ms), 2) if rec.ground_speed_ms is not None else None,
|
||||
round(float(rec.track_deg), 1) if rec.track_deg is not None else None,
|
||||
round(float(rec.vertical_rate_ms), 2) if rec.vertical_rate_ms is not None else None,
|
||||
rec.category,
|
||||
bool(rec.is_military),
|
||||
bool(rec.is_emergency),
|
||||
rec.emergency_code,
|
||||
bool(rec.on_ground),
|
||||
rec.source,
|
||||
to_iso8601_utc(rec.observed_at),
|
||||
]
|
||||
)
|
||||
|
||||
health_res = await db.execute(select(ADSBSourceHealth))
|
||||
source_health = {item.source: item.to_dict() for item in health_res.scalars().all()}
|
||||
|
||||
return {
|
||||
"fields": list(SNAPSHOT_FIELDS),
|
||||
"rows": rows,
|
||||
"generated_at": to_iso8601_utc(now),
|
||||
"source_health": source_health,
|
||||
"attribution": AIRCRAFT_ATTRIBUTION,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/{icao24}/track", dependencies=[Depends(require_earth_or_api_access("aircraft:read"))])
|
||||
async def get_aircraft_track(
|
||||
icao24: str,
|
||||
hours: float = Query(3.0, ge=0.25, le=48.0),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
norm_icao = normalize_icao24(icao24)
|
||||
now = datetime.now(UTC)
|
||||
cutoff = now - timedelta(hours=hours)
|
||||
|
||||
res = await db.execute(
|
||||
select(AircraftPosition)
|
||||
.where(AircraftPosition.icao24 == norm_icao)
|
||||
.where(AircraftPosition.observed_at >= cutoff)
|
||||
.order_by(AircraftPosition.observed_at.asc(), AircraftPosition.id.asc())
|
||||
.limit(2000)
|
||||
)
|
||||
pts = list(res.scalars().all())
|
||||
current = await db.get(AircraftCurrentState, norm_icao)
|
||||
|
||||
points = [
|
||||
{
|
||||
"lat": round(float(pt.lat), 5),
|
||||
"lon": round(float(pt.lon), 5),
|
||||
"altitude_m": pt.altitude_m,
|
||||
"ground_speed_ms": pt.ground_speed_ms,
|
||||
"track_deg": pt.track_deg,
|
||||
"observed_at": to_iso8601_utc(pt.observed_at),
|
||||
}
|
||||
for pt in pts
|
||||
]
|
||||
|
||||
if current is not None and not points:
|
||||
points.append(
|
||||
{
|
||||
"lat": round(float(current.lat), 5),
|
||||
"lon": round(float(current.lon), 5),
|
||||
"altitude_m": current.geo_altitude_m if current.geo_altitude_m is not None else current.baro_altitude_m,
|
||||
"ground_speed_ms": current.ground_speed_ms,
|
||||
"track_deg": current.track_deg,
|
||||
"observed_at": to_iso8601_utc(current.observed_at),
|
||||
}
|
||||
)
|
||||
|
||||
obs_at = current.observed_at if current is not None else (pts[-1].observed_at if pts else None)
|
||||
ingested_at = current.ingested_at if current is not None else None
|
||||
is_stale = True
|
||||
if obs_at is not None:
|
||||
is_stale = (now - coerce_utc_datetime(obs_at)).total_seconds() > AIRCRAFT_FRESHNESS_SECONDS
|
||||
|
||||
return {
|
||||
"icao24": norm_icao,
|
||||
"hours": hours,
|
||||
"points": points,
|
||||
"source": current.source if current is not None else "aircraft_position",
|
||||
"observed_at": to_iso8601_utc(obs_at),
|
||||
"ingested_at": to_iso8601_utc(ingested_at),
|
||||
"is_stale": is_stale,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/{icao24}", dependencies=[Depends(require_earth_or_api_access("aircraft:read"))])
|
||||
async def get_aircraft_detail(
|
||||
icao24: str,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
norm_icao = normalize_icao24(icao24)
|
||||
current = await db.get(AircraftCurrentState, norm_icao)
|
||||
static = await db.get(AircraftStatic, norm_icao)
|
||||
if current is None and static is None:
|
||||
raise HTTPException(status_code=404, detail="Aircraft not found")
|
||||
|
||||
now = datetime.now(UTC)
|
||||
obs_at = current.observed_at if current is not None else static.updated_at
|
||||
ingested_at = current.ingested_at if current is not None else static.updated_at
|
||||
is_stale = True
|
||||
if obs_at is not None:
|
||||
is_stale = (now - coerce_utc_datetime(obs_at)).total_seconds() > AIRCRAFT_FRESHNESS_SECONDS
|
||||
|
||||
return {
|
||||
"icao24": norm_icao,
|
||||
"current": current.to_dict() if current is not None else None,
|
||||
"static": static.to_dict() if static is not None else None,
|
||||
"source": current.source if current is not None else static.source,
|
||||
"observed_at": to_iso8601_utc(obs_at),
|
||||
"ingested_at": to_iso8601_utc(ingested_at),
|
||||
"is_stale": is_stale,
|
||||
"freshness_threshold_seconds": AIRCRAFT_FRESHNESS_SECONDS,
|
||||
"attribution": AIRCRAFT_ATTRIBUTION,
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
"""Card-image configuration, upload, catalog selection and public resolution."""
|
||||
|
||||
from fastapi import APIRouter, Depends, File, HTTPException, Query, Response, UploadFile
|
||||
import hashlib
|
||||
import json
|
||||
|
||||
from fastapi import APIRouter, Depends, File, HTTPException, Query, Request, Response, UploadFile
|
||||
from fastapi.responses import FileResponse
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
@@ -28,6 +31,28 @@ from app.services.card_image_targets import get_target, search_targets
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _etag_matches(if_none_match: str | None, etag: str) -> bool:
|
||||
if not if_none_match:
|
||||
return False
|
||||
target = etag.strip()
|
||||
if target.startswith("W/"):
|
||||
target = target[2:].strip()
|
||||
for candidate in if_none_match.split(","):
|
||||
token = candidate.strip()
|
||||
if token == "*":
|
||||
return True
|
||||
if token.startswith("W/"):
|
||||
token = token[2:].strip()
|
||||
if token == target:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _stable_fingerprint(payload: object) -> str:
|
||||
raw = json.dumps(payload, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
|
||||
return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:24]
|
||||
|
||||
|
||||
async def image_admin(user: User = Depends(get_current_user)) -> User:
|
||||
if user.role not in {UserRole.ADMIN.value, UserRole.SUPER_ADMIN.value}:
|
||||
raise HTTPException(403, "Administrator access required")
|
||||
@@ -58,7 +83,14 @@ async def upload_image(file: UploadFile = File(...), _actor: User = Depends(imag
|
||||
return await run_in_threadpool(store_image, content, (file.filename or "Image")[:200])
|
||||
|
||||
|
||||
@router.get("/files/{filename}", dependencies=[Depends(require_earth_or_api_access("earth:read", allow_query_api_key=True))])
|
||||
@router.get(
|
||||
"/files/{filename}",
|
||||
dependencies=[Depends(require_earth_or_api_access("earth:read", allow_query_api_key=True, rate_limit_tier="tile"))],
|
||||
)
|
||||
@router.head(
|
||||
"/files/{filename}",
|
||||
dependencies=[Depends(require_earth_or_api_access("earth:read", allow_query_api_key=True, rate_limit_tier="tile"))],
|
||||
)
|
||||
async def image_file(filename: str):
|
||||
path = uploaded_path(filename)
|
||||
if not path.is_file():
|
||||
@@ -84,19 +116,58 @@ async def targets(
|
||||
return {"items": await search_targets(db, entity_type, scope, q.strip(), limit)}
|
||||
|
||||
|
||||
@router.get("/fingerprint", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
|
||||
async def fingerprint(
|
||||
request: Request,
|
||||
response: Response,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
envelope = await read_configuration(db)
|
||||
revision = str(envelope["revision"])
|
||||
etag = f'"{_stable_fingerprint({"revision": revision})}"'
|
||||
headers = {
|
||||
"Cache-Control": "private, no-cache",
|
||||
"ETag": etag,
|
||||
}
|
||||
if _etag_matches(request.headers.get("if-none-match"), etag):
|
||||
return Response(status_code=304, headers=headers)
|
||||
response.headers.update(headers)
|
||||
return {"revision": revision}
|
||||
|
||||
|
||||
@router.get("/resolve", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
|
||||
async def resolve(
|
||||
request: Request,
|
||||
response: Response,
|
||||
entity_type: EntityType,
|
||||
entity_id: str = Query(min_length=1, max_length=300),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
response.headers["Cache-Control"] = "no-store"
|
||||
envelope = await read_configuration(db)
|
||||
config = CardImageConfiguration.model_validate(envelope["config"])
|
||||
context = await get_target(db, entity_type, entity_id)
|
||||
result = resolve_image(config, context)
|
||||
return {**result, "revision": envelope["revision"], "entity": context}
|
||||
fp = _stable_fingerprint(
|
||||
{
|
||||
"revision": envelope["revision"],
|
||||
"suppressed": bool(result.get("suppressed")),
|
||||
"image": result.get("image"),
|
||||
}
|
||||
)
|
||||
etag = f'"{fp}"'
|
||||
headers = {
|
||||
"Cache-Control": "private, no-cache",
|
||||
"ETag": etag,
|
||||
}
|
||||
if _etag_matches(request.headers.get("if-none-match"), etag):
|
||||
return Response(status_code=304, headers=headers)
|
||||
response.headers.update(headers)
|
||||
return {
|
||||
**result,
|
||||
"revision": envelope["revision"],
|
||||
"fingerprint": fp,
|
||||
"entity": context,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/preview")
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
"""Investigation Case Board API (§4.3)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from fastapi.responses import PlainTextResponse
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy import desc, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.access_gate import require_admin_user, require_earth_or_api_access
|
||||
from app.core.enums import UserRole
|
||||
from app.db.session import get_db
|
||||
from app.models.investigation_case import CaseItem, CaseVersion, InvestigationCase
|
||||
from app.models.user import User
|
||||
from app.services.investigation_cases import export_case_markdown, freeze_investigation_case
|
||||
|
||||
router = APIRouter()
|
||||
_read_dep = Depends(require_earth_or_api_access("visualization:read"))
|
||||
|
||||
_ALLOWED_ITEM_TYPES = frozenset(
|
||||
{"object", "incident", "evidence", "camera_bookmark", "note", "ai_result", "compute_revision"}
|
||||
)
|
||||
|
||||
|
||||
class CaseCreateRequest(BaseModel):
|
||||
title: str = Field(min_length=1, max_length=240)
|
||||
summary: str = Field(default="", max_length=4000)
|
||||
is_shared: bool = True
|
||||
|
||||
|
||||
class CaseUpdateRequest(BaseModel):
|
||||
title: str | None = Field(default=None, min_length=1, max_length=240)
|
||||
summary: str | None = Field(default=None, max_length=4000)
|
||||
status: str | None = Field(default=None, max_length=32)
|
||||
is_shared: bool | None = None
|
||||
|
||||
|
||||
class CaseItemAddRequest(BaseModel):
|
||||
item_type: str = Field(min_length=1, max_length=48)
|
||||
ref_id: str = Field(min_length=1, max_length=200)
|
||||
payload: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
|
||||
def _is_admin(user: User | Any) -> bool:
|
||||
role = str(getattr(user, "role", "") or "").lower()
|
||||
return role in {UserRole.ADMIN.value, UserRole.SUPER_ADMIN.value}
|
||||
|
||||
|
||||
async def _load_accessible_case(db: AsyncSession, case_id: int, user: User | Any) -> InvestigationCase:
|
||||
case = await db.get(InvestigationCase, case_id)
|
||||
if case is None:
|
||||
raise HTTPException(status_code=404, detail="Investigation case not found")
|
||||
if not _is_admin(user) and not case.is_shared:
|
||||
raise HTTPException(status_code=403, detail="This investigation case is not shared")
|
||||
return case
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_cases(
|
||||
status: str | None = Query(default=None),
|
||||
limit: int = Query(default=50, ge=1, le=200),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(require_earth_or_api_access("visualization:read")),
|
||||
) -> dict[str, Any]:
|
||||
stmt = select(InvestigationCase).order_by(desc(InvestigationCase.updated_at), desc(InvestigationCase.id)).limit(limit)
|
||||
if not _is_admin(current_user):
|
||||
stmt = stmt.where(InvestigationCase.is_shared.is_(True))
|
||||
if status:
|
||||
stmt = stmt.where(InvestigationCase.status == status.strip())
|
||||
rows = list((await db.execute(stmt)).scalars().all())
|
||||
return {"items": [r.to_dict() for r in rows], "count": len(rows)}
|
||||
|
||||
|
||||
@router.post("")
|
||||
async def create_case(
|
||||
body: CaseCreateRequest,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(require_admin_user),
|
||||
) -> dict[str, Any]:
|
||||
case = InvestigationCase(
|
||||
title=body.title.strip(),
|
||||
summary=body.summary.strip(),
|
||||
status="draft",
|
||||
owner_id=int(getattr(current_user, "id", 0) or 0),
|
||||
owner_name=str(getattr(current_user, "username", "") or "admin"),
|
||||
is_shared=bool(body.is_shared),
|
||||
)
|
||||
db.add(case)
|
||||
await db.commit()
|
||||
await db.refresh(case)
|
||||
return case.to_dict()
|
||||
|
||||
|
||||
@router.get("/{case_id}")
|
||||
async def get_case_detail(
|
||||
case_id: int,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(require_earth_or_api_access("visualization:read")),
|
||||
) -> dict[str, Any]:
|
||||
case = await _load_accessible_case(db, case_id, current_user)
|
||||
items = list(
|
||||
(await db.execute(select(CaseItem).where(CaseItem.case_id == case.id).order_by(CaseItem.id.asc())))
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
versions = list(
|
||||
(await db.execute(select(CaseVersion).where(CaseVersion.case_id == case.id).order_by(desc(CaseVersion.version))))
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
return {
|
||||
"case": case.to_dict(),
|
||||
"items": [i.to_dict() for i in items],
|
||||
"versions": [v.to_dict() for v in versions],
|
||||
}
|
||||
|
||||
|
||||
@router.patch("/{case_id}")
|
||||
async def update_case(
|
||||
case_id: int,
|
||||
body: CaseUpdateRequest,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
_admin: User = Depends(require_admin_user),
|
||||
) -> dict[str, Any]:
|
||||
case = await db.get(InvestigationCase, case_id)
|
||||
if case is None:
|
||||
raise HTTPException(status_code=404, detail="Investigation case not found")
|
||||
if body.title is not None:
|
||||
case.title = body.title.strip()
|
||||
if body.summary is not None:
|
||||
case.summary = body.summary.strip()
|
||||
if body.status is not None and body.status in {"draft", "in_review", "frozen", "closed"}:
|
||||
case.status = body.status
|
||||
if body.is_shared is not None:
|
||||
case.is_shared = bool(body.is_shared)
|
||||
await db.commit()
|
||||
await db.refresh(case)
|
||||
return case.to_dict()
|
||||
|
||||
|
||||
@router.post("/{case_id}/items")
|
||||
async def add_case_item(
|
||||
case_id: int,
|
||||
body: CaseItemAddRequest,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(require_admin_user),
|
||||
) -> dict[str, Any]:
|
||||
case = await db.get(InvestigationCase, case_id)
|
||||
if case is None:
|
||||
raise HTTPException(status_code=404, detail="Investigation case not found")
|
||||
if case.status == "closed":
|
||||
raise HTTPException(status_code=409, detail="Closed cases cannot receive new items")
|
||||
itype = body.item_type.strip().lower()
|
||||
if itype not in _ALLOWED_ITEM_TYPES:
|
||||
raise HTTPException(status_code=422, detail=f"Unsupported case item_type: {itype}")
|
||||
item = CaseItem(
|
||||
case_id=case.id,
|
||||
item_type=itype,
|
||||
ref_id=body.ref_id.strip(),
|
||||
payload=dict(body.payload or {}),
|
||||
added_by=str(getattr(current_user, "username", "") or "admin"),
|
||||
)
|
||||
db.add(item)
|
||||
await db.commit()
|
||||
await db.refresh(item)
|
||||
return item.to_dict()
|
||||
|
||||
|
||||
@router.post("/{case_id}/freeze")
|
||||
async def freeze_case(
|
||||
case_id: int,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(require_admin_user),
|
||||
) -> dict[str, Any]:
|
||||
case = await db.get(InvestigationCase, case_id)
|
||||
if case is None:
|
||||
raise HTTPException(status_code=404, detail="Investigation case not found")
|
||||
ver = await freeze_investigation_case(
|
||||
db, case, frozen_by=str(getattr(current_user, "username", "") or "admin")
|
||||
)
|
||||
return {"case": case.to_dict(), "version": ver.to_dict()}
|
||||
|
||||
|
||||
@router.get("/{case_id}/export/markdown")
|
||||
async def export_case_as_markdown(
|
||||
case_id: int,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(require_earth_or_api_access("visualization:read")),
|
||||
) -> PlainTextResponse:
|
||||
case = await _load_accessible_case(db, case_id, current_user)
|
||||
items = list(
|
||||
(await db.execute(select(CaseItem).where(CaseItem.case_id == case.id).order_by(CaseItem.id.asc())))
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
versions = list(
|
||||
(await db.execute(select(CaseVersion).where(CaseVersion.case_id == case.id).order_by(desc(CaseVersion.version))))
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
md = export_case_markdown(case, items, versions)
|
||||
return PlainTextResponse(
|
||||
md,
|
||||
media_type="text/markdown; charset=utf-8",
|
||||
headers={"Content-Disposition": f'attachment; filename="case-{case.id}.md"'},
|
||||
)
|
||||
@@ -81,6 +81,29 @@ PRODUCT_DEFINITIONS: dict[str, dict] = {
|
||||
"primary_stat_key": "news_count",
|
||||
"stat_keys": ["news_count"],
|
||||
},
|
||||
"aircraft": {
|
||||
"name": "航空飞行器",
|
||||
"sources": ["adsb_lol_aircraft", "opensky_aircraft", "aircraft_registry"],
|
||||
"primary_stat_key": "aircraft_count",
|
||||
"stat_keys": ["aircraft_count", "military_aircraft_count", "emergency_aircraft_count"],
|
||||
},
|
||||
"gps_jamming": {
|
||||
"name": "GPS/GNSS 干扰",
|
||||
"sources": ["gpsjam_interference"],
|
||||
"primary_stat_key": "gps_jamming_cell_count",
|
||||
"stat_keys": ["gps_jamming_cell_count", "gps_jamming_high_count"],
|
||||
},
|
||||
"disasters": {
|
||||
"name": "自然灾害",
|
||||
"sources": [
|
||||
"usgs_earthquakes",
|
||||
"nasa_firms_wildfires",
|
||||
"gdacs_disasters",
|
||||
"nasa_eonet_events",
|
||||
],
|
||||
"primary_stat_key": "disaster_event_count",
|
||||
"stat_keys": ["disaster_event_count", "disaster_high_count"],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -887,6 +887,9 @@ async def delete_config(
|
||||
)
|
||||
deleted_records["collected_data"] = collected_result.rowcount or 0
|
||||
else:
|
||||
from app.models.aircraft import ADSBSourceHealth, AircraftCurrentState
|
||||
from app.models.gps_jamming import GPSJammingCell
|
||||
|
||||
collected_result = await db.execute(
|
||||
delete(CollectedData).where(CollectedData.source == config.name)
|
||||
)
|
||||
@@ -899,11 +902,23 @@ async def delete_config(
|
||||
health_result = await db.execute(
|
||||
delete(AISSourceHealth).where(AISSourceHealth.source == config.name)
|
||||
)
|
||||
aircraft_result = await db.execute(
|
||||
delete(AircraftCurrentState).where(AircraftCurrentState.source == config.name)
|
||||
)
|
||||
adsb_health_result = await db.execute(
|
||||
delete(ADSBSourceHealth).where(ADSBSourceHealth.source == config.name)
|
||||
)
|
||||
jam_result = await db.execute(
|
||||
delete(GPSJammingCell).where(GPSJammingCell.source == config.name)
|
||||
)
|
||||
deleted_records = {
|
||||
"collected_data": collected_result.rowcount or 0,
|
||||
"ais_raw_observations": raw_result.rowcount or 0,
|
||||
"vessel_current_state": current_vessel_result.rowcount or 0,
|
||||
"ais_source_health": health_result.rowcount or 0,
|
||||
"aircraft_current_state": aircraft_result.rowcount or 0,
|
||||
"adsb_source_health": adsb_health_result.rowcount or 0,
|
||||
"gps_jamming_cells": jam_result.rowcount or 0,
|
||||
}
|
||||
|
||||
if delete_mappings or delete_source_data:
|
||||
|
||||
@@ -46,7 +46,8 @@ PRODUCT_SOURCE_KEYWORDS: tuple[tuple[str, tuple[str, ...]], ...] = (
|
||||
("geo", ("earth_imagery", "sentinel2", "viirs", "basemap", "imagery")),
|
||||
("weather", ("cloud", "weather", "meteorolog", "atmosphere", "ir108", "wind", "gfs")),
|
||||
("vessels", ("vessel", "ais")),
|
||||
("cables", ("cable", "landing", "telegeography", "arcgis", "fao")),
|
||||
("cables", ("cable", "landing", "telegeography", "arcgis", "fao", "nga_navigation")),
|
||||
("disasters", ("usgs_earthquakes", "nasa_firms", "gdacs", "eonet", "disaster", "wildfire")),
|
||||
("satellites", ("tle", "satellite", "spacetrack", "celestrak")),
|
||||
("bgp", ("bgp", "asn", "prefix_geo", "opengeofeed", "nro")),
|
||||
("compute", ("top500", "gpu", "supercomputer", "compute")),
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
"""Natural disaster telemetry snapshot API."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from sqlalchemy import desc, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.access_gate import require_earth_or_api_access
|
||||
from app.core.time import to_iso8601_utc
|
||||
from app.db.session import get_db
|
||||
from app.models.disaster import DisasterEvent
|
||||
|
||||
router = APIRouter(dependencies=[Depends(require_earth_or_api_access("visualization:read"))])
|
||||
|
||||
_DEFAULT_STALE_SECONDS = 60 * 60
|
||||
|
||||
|
||||
def _coerce_utc(val: Any) -> datetime | None:
|
||||
if isinstance(val, datetime):
|
||||
return val.replace(tzinfo=UTC) if val.tzinfo is None else val.astimezone(UTC)
|
||||
return None
|
||||
|
||||
|
||||
@router.get("/snapshot")
|
||||
async def get_disaster_snapshot(
|
||||
types: str | None = Query(default=None, description="Comma-separated disaster event types"),
|
||||
since_hours: int = Query(default=72, ge=1, le=720),
|
||||
include_duplicates: bool = Query(default=False),
|
||||
limit: int = Query(default=1000, ge=1, le=5000),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> dict[str, Any]:
|
||||
"""Return recent normalized natural disaster events with freshness and provenance fields."""
|
||||
now = datetime.now(UTC)
|
||||
cutoff = now - timedelta(hours=since_hours)
|
||||
|
||||
stmt = (
|
||||
select(DisasterEvent)
|
||||
.where(DisasterEvent.observed_at >= cutoff)
|
||||
.order_by(desc(DisasterEvent.observed_at), desc(DisasterEvent.id))
|
||||
.limit(limit)
|
||||
)
|
||||
if types:
|
||||
wanted = [t.strip().lower() for t in types.split(",") if t.strip()]
|
||||
if wanted:
|
||||
stmt = stmt.where(DisasterEvent.event_type.in_(wanted))
|
||||
if not include_duplicates:
|
||||
stmt = stmt.where(DisasterEvent.duplicate_of.is_(None))
|
||||
|
||||
rows = list((await db.execute(stmt)).scalars().all())
|
||||
|
||||
by_type: dict[str, int] = {}
|
||||
high_count = 0
|
||||
latest_obs: datetime | None = None
|
||||
items: list[dict[str, Any]] = []
|
||||
for row in rows:
|
||||
obs = _coerce_utc(row.observed_at)
|
||||
if obs and (latest_obs is None or obs > latest_obs):
|
||||
latest_obs = obs
|
||||
is_stale = bool(obs is None or (now - obs).total_seconds() > _DEFAULT_STALE_SECONDS)
|
||||
ev_type = str(row.event_type or "other")
|
||||
by_type[ev_type] = by_type.get(ev_type, 0) + 1
|
||||
if str(row.severity or "").lower() == "high":
|
||||
high_count += 1
|
||||
payload = row.to_dict()
|
||||
payload["is_stale"] = is_stale
|
||||
items.append(payload)
|
||||
|
||||
return {
|
||||
"generated_at": to_iso8601_utc(now),
|
||||
"since_hours": since_hours,
|
||||
"count": len(items),
|
||||
"high_count": high_count,
|
||||
"by_type": by_type,
|
||||
"latest_observed_at": to_iso8601_utc(latest_obs),
|
||||
"items": items,
|
||||
}
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
@@ -301,9 +303,37 @@ async def _broadcast_earth_config_update(layer: str) -> None:
|
||||
logger.warning("Failed to broadcast %s update: %s", layer, exc)
|
||||
|
||||
|
||||
def _etag_matches(if_none_match: str | None, etag: str) -> bool:
|
||||
if not if_none_match:
|
||||
return False
|
||||
target = etag.strip()
|
||||
if target.startswith("W/"):
|
||||
target = target[2:].strip()
|
||||
for candidate in if_none_match.split(","):
|
||||
token = candidate.strip()
|
||||
if token == "*":
|
||||
return True
|
||||
if token.startswith("W/"):
|
||||
token = token[2:].strip()
|
||||
if token == target:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _json_etag(payload: Any) -> str:
|
||||
encoded = json.dumps(payload, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
|
||||
return f'"{hashlib.sha256(encoded.encode("utf-8")).hexdigest()[:24]}"'
|
||||
|
||||
|
||||
@router.get("/brand", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
|
||||
async def get_earth_brand(db: AsyncSession = Depends(get_db)):
|
||||
return await _get_earth_brand_payload(db)
|
||||
async def get_earth_brand(request: Request, response: Response, db: AsyncSession = Depends(get_db)):
|
||||
payload = await _get_earth_brand_payload(db)
|
||||
etag = _json_etag(payload)
|
||||
headers = {"Cache-Control": "private, no-cache", "ETag": etag}
|
||||
if _etag_matches(request.headers.get("if-none-match"), etag):
|
||||
return Response(status_code=304, headers=headers)
|
||||
response.headers.update(headers)
|
||||
return payload
|
||||
|
||||
|
||||
@router.put("/brand")
|
||||
@@ -372,8 +402,14 @@ async def upload_earth_brand_asset(
|
||||
|
||||
|
||||
@router.get("/about", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
|
||||
async def get_earth_about(db: AsyncSession = Depends(get_db)):
|
||||
return await _get_earth_about_payload(db)
|
||||
async def get_earth_about(request: Request, response: Response, db: AsyncSession = Depends(get_db)):
|
||||
payload = await _get_earth_about_payload(db)
|
||||
etag = _json_etag(payload)
|
||||
headers = {"Cache-Control": "private, no-cache", "ETag": etag}
|
||||
if _etag_matches(request.headers.get("if-none-match"), etag):
|
||||
return Response(status_code=304, headers=headers)
|
||||
response.headers.update(headers)
|
||||
return payload
|
||||
|
||||
|
||||
@router.put("/about")
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
"""Geofence CRUD & preset listing API (§3.8)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy import desc, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.access_gate import require_admin_user, require_earth_or_api_access
|
||||
from app.db.session import get_db
|
||||
from app.models.geofence import Geofence
|
||||
from app.models.user import User
|
||||
from app.services.fusion.anomaly_engine import ensure_preset_geofences
|
||||
|
||||
router = APIRouter()
|
||||
_read_dep = Depends(require_earth_or_api_access("visualization:read"))
|
||||
|
||||
|
||||
class GeofenceCreateRequest(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=200)
|
||||
kind: str = Field(default="custom", max_length=32)
|
||||
geometry: dict[str, Any]
|
||||
rules: dict[str, Any] = Field(default_factory=dict)
|
||||
enabled: bool = True
|
||||
|
||||
|
||||
class GeofenceUpdateRequest(BaseModel):
|
||||
name: str | None = Field(default=None, min_length=1, max_length=200)
|
||||
geometry: dict[str, Any] | None = None
|
||||
rules: dict[str, Any] | None = None
|
||||
enabled: bool | None = None
|
||||
|
||||
|
||||
def _validate_polygon_geometry(geometry: dict[str, Any]) -> None:
|
||||
if not isinstance(geometry, dict):
|
||||
raise HTTPException(status_code=422, detail="Geofence geometry must be a GeoJSON object")
|
||||
gtype = geometry.get("type")
|
||||
coords = geometry.get("coordinates")
|
||||
if gtype not in {"Polygon", "MultiPolygon"} or not isinstance(coords, list) or not coords:
|
||||
raise HTTPException(
|
||||
status_code=422,
|
||||
detail="Geofence geometry must be a GeoJSON Polygon or MultiPolygon",
|
||||
)
|
||||
|
||||
|
||||
@router.get("", dependencies=[_read_dep])
|
||||
async def list_geofences(
|
||||
enabled_only: bool = Query(default=False),
|
||||
kind: str | None = Query(default=None),
|
||||
ensure_presets: bool = Query(default=True),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> dict[str, Any]:
|
||||
if ensure_presets:
|
||||
await ensure_preset_geofences(db)
|
||||
stmt = select(Geofence).order_by(desc(Geofence.id))
|
||||
if enabled_only:
|
||||
stmt = stmt.where(Geofence.enabled.is_(True))
|
||||
if kind:
|
||||
stmt = stmt.where(Geofence.kind == kind.strip())
|
||||
rows = list((await db.execute(stmt)).scalars().all())
|
||||
return {"items": [r.to_dict() for r in rows], "count": len(rows)}
|
||||
|
||||
|
||||
@router.post("")
|
||||
async def create_geofence(
|
||||
body: GeofenceCreateRequest,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(require_admin_user),
|
||||
) -> dict[str, Any]:
|
||||
_validate_polygon_geometry(body.geometry)
|
||||
gf = Geofence(
|
||||
name=body.name.strip(),
|
||||
kind="preset" if body.kind == "preset" else "custom",
|
||||
geometry=body.geometry,
|
||||
rules=body.rules or {
|
||||
"enable_loitering": True,
|
||||
"enable_dark_target": True,
|
||||
"enable_surge": True,
|
||||
"dark_threshold_minutes": 45,
|
||||
"surge_sigma": 2.0,
|
||||
},
|
||||
enabled=bool(body.enabled),
|
||||
created_by=current_user.username,
|
||||
)
|
||||
db.add(gf)
|
||||
await db.commit()
|
||||
return gf.to_dict()
|
||||
|
||||
|
||||
@router.patch("/{geofence_id}")
|
||||
async def update_geofence(
|
||||
geofence_id: int,
|
||||
body: GeofenceUpdateRequest,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
_admin: User = Depends(require_admin_user),
|
||||
) -> dict[str, Any]:
|
||||
gf = await db.get(Geofence, geofence_id)
|
||||
if gf is None:
|
||||
raise HTTPException(status_code=404, detail="Geofence not found")
|
||||
if body.name is not None:
|
||||
gf.name = body.name.strip()
|
||||
if body.geometry is not None:
|
||||
_validate_polygon_geometry(body.geometry)
|
||||
gf.geometry = body.geometry
|
||||
if body.rules is not None:
|
||||
gf.rules = body.rules
|
||||
if body.enabled is not None:
|
||||
gf.enabled = bool(body.enabled)
|
||||
await db.commit()
|
||||
return gf.to_dict()
|
||||
|
||||
|
||||
@router.delete("/{geofence_id}")
|
||||
async def delete_geofence(
|
||||
geofence_id: int,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
_admin: User = Depends(require_admin_user),
|
||||
) -> dict[str, Any]:
|
||||
gf = await db.get(Geofence, geofence_id)
|
||||
if gf is None:
|
||||
raise HTTPException(status_code=404, detail="Geofence not found")
|
||||
await db.delete(gf)
|
||||
await db.commit()
|
||||
return {"deleted": True, "id": geofence_id}
|
||||
@@ -0,0 +1,88 @@
|
||||
"""GPS/GNSS H3 interference snapshot API."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from sqlalchemy import desc, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.access_gate import require_earth_or_api_access
|
||||
from app.core.time import to_iso8601_utc
|
||||
from app.db.session import get_db
|
||||
from app.models.gps_jamming import GPSJammingCell
|
||||
from app.services.aircraft_aggregation import coerce_utc_datetime
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
GPS_JAMMING_FRESHNESS_SECONDS = 36 * 3600
|
||||
GPSJAM_ATTRIBUTION = "gpsjam.org (underlying telemetry via airplanes.live & ADS-B Exchange; aircraft-reported NIC/NACp)"
|
||||
|
||||
|
||||
@router.get("/snapshot", dependencies=[Depends(require_earth_or_api_access("gps_jamming:read"))])
|
||||
async def get_gps_jamming_snapshot(
|
||||
date: Optional[str] = Query(None, description="Observed date YYYY-MM-DD (defaults to latest date)"),
|
||||
level: Optional[str] = Query(None, description="Optional comma-separated severity levels: high,medium,low"),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
now = datetime.now(UTC)
|
||||
target_date = str(date or "").strip() or None
|
||||
if not target_date:
|
||||
latest_res = await db.execute(
|
||||
select(GPSJammingCell.observed_date)
|
||||
.order_by(desc(GPSJammingCell.observed_date))
|
||||
.limit(1)
|
||||
)
|
||||
target_date = latest_res.scalar_one_or_none()
|
||||
|
||||
if not target_date:
|
||||
return {
|
||||
"date": None,
|
||||
"cells": [],
|
||||
"stats": {"total": 0, "high": 0, "medium": 0, "low": 0},
|
||||
"source": "gpsjam_interference",
|
||||
"observed_at": None,
|
||||
"ingested_at": None,
|
||||
"is_stale": True,
|
||||
"generated_at": to_iso8601_utc(now),
|
||||
"attribution": GPSJAM_ATTRIBUTION,
|
||||
}
|
||||
|
||||
stmt = select(GPSJammingCell).where(GPSJammingCell.observed_date == target_date)
|
||||
if level:
|
||||
levels = [part.strip().lower() for part in level.split(",") if part.strip()]
|
||||
if levels:
|
||||
stmt = stmt.where(GPSJammingCell.level.in_(levels))
|
||||
|
||||
res = await db.execute(stmt.order_by(desc(GPSJammingCell.bad_ratio)))
|
||||
rows = list(res.scalars().all())
|
||||
|
||||
counts = {"total": len(rows), "high": 0, "medium": 0, "low": 0}
|
||||
cells: list[dict[str, object]] = []
|
||||
latest_ingested: datetime | None = None
|
||||
for row in rows:
|
||||
lvl = str(row.level or "low").lower()
|
||||
if lvl in counts:
|
||||
counts[lvl] += 1
|
||||
ing = coerce_utc_datetime(row.ingested_at) if row.ingested_at else None
|
||||
if ing and (latest_ingested is None or ing > latest_ingested):
|
||||
latest_ingested = ing
|
||||
cells.append(row.to_dict())
|
||||
|
||||
observed_dt = coerce_utc_datetime(f"{target_date}T23:59:59+00:00", fallback=now)
|
||||
ref_time = latest_ingested or observed_dt
|
||||
is_stale = (now - ref_time).total_seconds() > GPS_JAMMING_FRESHNESS_SECONDS
|
||||
|
||||
return {
|
||||
"date": target_date,
|
||||
"cells": cells,
|
||||
"stats": counts,
|
||||
"source": "gpsjam_interference",
|
||||
"observed_at": to_iso8601_utc(observed_dt),
|
||||
"ingested_at": to_iso8601_utc(latest_ingested),
|
||||
"is_stale": is_stale,
|
||||
"generated_at": to_iso8601_utc(now),
|
||||
"attribution": GPSJAM_ATTRIBUTION,
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
"""Situational incidents triage & Earth overlay API (§3.8 & §3.9)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import h3
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy import desc, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.access_gate import require_admin_user, require_earth_or_api_access
|
||||
from app.db.session import get_db
|
||||
from app.models.geofence import SituationalIncident
|
||||
from app.models.user import User
|
||||
|
||||
router = APIRouter()
|
||||
_read_dep = Depends(require_earth_or_api_access("visualization:read"))
|
||||
|
||||
|
||||
class IncidentTransitionRequest(BaseModel):
|
||||
resolution_note: str | None = Field(default=None, max_length=1000)
|
||||
|
||||
|
||||
class ScenarioRunRequest(BaseModel):
|
||||
workflow_id: str = Field(min_length=3, max_length=80)
|
||||
cable_id: str | None = None
|
||||
suspect_vessel_mmsi: int | None = None
|
||||
center_lat: float = 2.0
|
||||
center_lon: float = 102.0
|
||||
radius_km: float = 350.0
|
||||
persist_incident: bool = True
|
||||
|
||||
|
||||
@router.get("", dependencies=[_read_dep])
|
||||
async def list_incidents(
|
||||
status: str | None = Query(default=None),
|
||||
assessment_kind: str | None = Query(default=None),
|
||||
limit: int = Query(default=100, ge=1, le=500),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> dict[str, Any]:
|
||||
stmt = select(SituationalIncident).order_by(desc(SituationalIncident.created_at), desc(SituationalIncident.id)).limit(limit)
|
||||
if status:
|
||||
stmt = stmt.where(SituationalIncident.status == status.strip())
|
||||
if assessment_kind:
|
||||
stmt = stmt.where(SituationalIncident.assessment_kind == assessment_kind.strip())
|
||||
rows = list((await db.execute(stmt)).scalars().all())
|
||||
return {"items": [r.to_dict() for r in rows], "count": len(rows)}
|
||||
|
||||
|
||||
@router.get("/overlay", dependencies=[_read_dep])
|
||||
async def get_incidents_overlay(
|
||||
limit: int = Query(default=100, ge=1, le=300),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> dict[str, Any]:
|
||||
"""Return H3 hex cells for `candidate_correlation` and solid arcs for `dependency_impact`."""
|
||||
stmt = (
|
||||
select(SituationalIncident)
|
||||
.where(SituationalIncident.status.in_(["open", "acknowledged"]))
|
||||
.order_by(desc(SituationalIncident.created_at))
|
||||
.limit(limit)
|
||||
)
|
||||
rows = list((await db.execute(stmt)).scalars().all())
|
||||
candidate_cells: list[dict[str, Any]] = []
|
||||
dependency_arcs: list[dict[str, Any]] = []
|
||||
|
||||
for row in rows:
|
||||
if row.assessment_kind == "candidate_correlation" and row.h3_index:
|
||||
try:
|
||||
boundary = [
|
||||
[float(lat), float(lon)]
|
||||
for lat, lon in h3.cell_to_boundary(row.h3_index)
|
||||
]
|
||||
center_lat, center_lon = h3.cell_to_latlng(row.h3_index)
|
||||
except Exception:
|
||||
boundary = []
|
||||
center_lat, center_lon = None, None
|
||||
candidate_cells.append(
|
||||
{
|
||||
"incident_id": row.id,
|
||||
"h3_index": row.h3_index,
|
||||
"title": row.title,
|
||||
"label": "待核查",
|
||||
"status": row.status,
|
||||
"center": [center_lat, center_lon],
|
||||
"boundary": boundary,
|
||||
"signal_types": (row.signal_summary or {}).get("signal_types", []),
|
||||
}
|
||||
)
|
||||
elif row.assessment_kind == "dependency_impact":
|
||||
for arc in (row.signal_summary or {}).get("impact_arcs", []) or []:
|
||||
dependency_arcs.append(
|
||||
{
|
||||
**arc,
|
||||
"incident_id": row.id,
|
||||
"status": row.status,
|
||||
"title": row.title,
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
"candidate_cells": candidate_cells,
|
||||
"dependency_arcs": dependency_arcs,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/{incident_id}", dependencies=[_read_dep])
|
||||
async def get_incident(
|
||||
incident_id: int,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> dict[str, Any]:
|
||||
row = await db.get(SituationalIncident, incident_id)
|
||||
if row is None:
|
||||
raise HTTPException(status_code=404, detail="Incident not found")
|
||||
return row.to_dict()
|
||||
|
||||
|
||||
@router.post("/{incident_id}/acknowledge")
|
||||
async def acknowledge_incident(
|
||||
incident_id: int,
|
||||
body: IncidentTransitionRequest | None = None,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(require_admin_user),
|
||||
) -> dict[str, Any]:
|
||||
row = await db.get(SituationalIncident, incident_id)
|
||||
if row is None:
|
||||
raise HTTPException(status_code=404, detail="Incident not found")
|
||||
row.status = "acknowledged"
|
||||
row.updated_by = current_user.username
|
||||
if body and body.resolution_note and body.resolution_note.strip():
|
||||
row.resolution_note = body.resolution_note.strip()
|
||||
await db.commit()
|
||||
return row.to_dict()
|
||||
|
||||
|
||||
@router.post("/{incident_id}/dismiss")
|
||||
async def dismiss_incident(
|
||||
incident_id: int,
|
||||
body: IncidentTransitionRequest,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(require_admin_user),
|
||||
) -> dict[str, Any]:
|
||||
reason = str(body.resolution_note or "").strip() if body else ""
|
||||
if not reason:
|
||||
raise HTTPException(status_code=422, detail="Dismissing an incident requires a resolution_note")
|
||||
row = await db.get(SituationalIncident, incident_id)
|
||||
if row is None:
|
||||
raise HTTPException(status_code=404, detail="Incident not found")
|
||||
row.status = "dismissed"
|
||||
row.updated_by = current_user.username
|
||||
row.resolution_note = reason
|
||||
await db.commit()
|
||||
return row.to_dict()
|
||||
|
||||
|
||||
@router.post("/{incident_id}/resolve")
|
||||
async def resolve_incident(
|
||||
incident_id: int,
|
||||
body: IncidentTransitionRequest | None = None,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(require_admin_user),
|
||||
) -> dict[str, Any]:
|
||||
row = await db.get(SituationalIncident, incident_id)
|
||||
if row is None:
|
||||
raise HTTPException(status_code=404, detail="Incident not found")
|
||||
row.status = "resolved"
|
||||
row.updated_by = current_user.username
|
||||
if body and body.resolution_note and body.resolution_note.strip():
|
||||
row.resolution_note = body.resolution_note.strip()
|
||||
await db.commit()
|
||||
return row.to_dict()
|
||||
|
||||
|
||||
@router.post("/scenarios/run")
|
||||
async def run_wargame_scenario_endpoint(
|
||||
body: ScenarioRunRequest,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(require_admin_user),
|
||||
) -> dict[str, Any]:
|
||||
"""Execute one built-in §3.10 wargame scenario (`wargame.cable_protection` or `wargame.air_sea_em`)."""
|
||||
from app.services.fusion.wargame_scenarios import (
|
||||
run_air_sea_em_scenario,
|
||||
run_cable_protection_scenario,
|
||||
)
|
||||
|
||||
wf = body.workflow_id.strip()
|
||||
if wf == "wargame.cable_protection":
|
||||
return await run_cable_protection_scenario(
|
||||
db,
|
||||
cable_id=body.cable_id or "apg-1",
|
||||
suspect_vessel_mmsi=body.suspect_vessel_mmsi,
|
||||
persist_incident=bool(body.persist_incident),
|
||||
)
|
||||
if wf == "wargame.air_sea_em":
|
||||
return await run_air_sea_em_scenario(
|
||||
db,
|
||||
center_lat=body.center_lat,
|
||||
center_lon=body.center_lon,
|
||||
radius_km=body.radius_km,
|
||||
persist_incident=bool(body.persist_incident),
|
||||
)
|
||||
raise HTTPException(status_code=400, detail=f"Unsupported scenario workflow: {wf}")
|
||||
@@ -5,11 +5,11 @@ from __future__ import annotations
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
|
||||
from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, Response, UploadFile, status
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.access_gate import require_earth_or_api_access
|
||||
from app.core.access_gate import require_admin_user, require_earth_or_api_access
|
||||
from app.core.security import get_current_user
|
||||
from app.db.session import get_db
|
||||
from app.models.earth_interactable import EarthInteractable
|
||||
@@ -100,6 +100,96 @@ async def get_interactables_geojson(
|
||||
return payload
|
||||
|
||||
|
||||
class PrivateRestPreviewRequest(BaseModel):
|
||||
rest_url: str | None = None
|
||||
root_path: str | None = None
|
||||
records: list[dict[str, Any]] | None = None
|
||||
field_mapping: dict[str, Any] | None = None
|
||||
|
||||
|
||||
class PrivateCommitRequest(BaseModel):
|
||||
records: list[dict[str, Any]]
|
||||
field_mapping: dict[str, Any]
|
||||
default_kind: str = "private_asset"
|
||||
layer_name: str = "interactables"
|
||||
source_label: str = "private_upload"
|
||||
|
||||
|
||||
@router.post("/upload/preview")
|
||||
async def preview_private_upload(
|
||||
file: UploadFile | None = File(default=None),
|
||||
fmt: str = Form(default="csv"),
|
||||
rest_url: str | None = Form(default=None),
|
||||
root_path: str | None = Form(default=None),
|
||||
_admin: User = Depends(require_admin_user),
|
||||
) -> dict[str, Any]:
|
||||
"""Preview columns & suggested field mapping from uploaded CSV/JSON or REST endpoint."""
|
||||
from app.services.private_data_ingest import (
|
||||
fetch_rest_records_for_upload,
|
||||
parse_tabular_or_json_bytes,
|
||||
preview_private_mapping,
|
||||
)
|
||||
|
||||
try:
|
||||
if file is not None:
|
||||
raw = await file.read()
|
||||
detected_fmt = fmt
|
||||
if file.filename and file.filename.lower().endswith(".json"):
|
||||
detected_fmt = "json"
|
||||
records = parse_tabular_or_json_bytes(raw, fmt=detected_fmt)
|
||||
elif rest_url:
|
||||
records = await fetch_rest_records_for_upload(rest_url.strip(), root_path=root_path)
|
||||
else:
|
||||
raise HTTPException(status_code=422, detail="file or rest_url is required")
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=413 if "超出上限" in str(exc) else 422, detail=str(exc)) from exc
|
||||
|
||||
return preview_private_mapping(records) | {"records": records[:200]}
|
||||
|
||||
|
||||
@router.post("/upload/preview-json")
|
||||
async def preview_private_json_payload(
|
||||
body: PrivateRestPreviewRequest,
|
||||
_admin: User = Depends(require_admin_user),
|
||||
) -> dict[str, Any]:
|
||||
from app.services.private_data_ingest import (
|
||||
fetch_rest_records_for_upload,
|
||||
preview_private_mapping,
|
||||
)
|
||||
|
||||
try:
|
||||
if body.records is not None:
|
||||
records = list(body.records)
|
||||
elif body.rest_url:
|
||||
records = await fetch_rest_records_for_upload(body.rest_url.strip(), root_path=body.root_path)
|
||||
else:
|
||||
raise HTTPException(status_code=422, detail="records or rest_url is required")
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=413 if "超出上限" in str(exc) else 422, detail=str(exc)) from exc
|
||||
return preview_private_mapping(records, custom_mapping=body.field_mapping) | {"records": records}
|
||||
|
||||
|
||||
@router.post("/upload/commit")
|
||||
async def commit_private_upload(
|
||||
body: PrivateCommitRequest,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
_admin: User = Depends(require_admin_user),
|
||||
) -> dict[str, Any]:
|
||||
"""Commit mapped private objects into `earth_interactables` (`interactable:{id}`)."""
|
||||
from app.services.private_data_ingest import commit_private_records_to_globe
|
||||
|
||||
result = await commit_private_records_to_globe(
|
||||
db,
|
||||
records=body.records,
|
||||
field_mapping=body.field_mapping,
|
||||
default_kind=body.default_kind,
|
||||
layer_name=body.layer_name,
|
||||
source_label=body.source_label,
|
||||
)
|
||||
invalidate_interactable_cache(body.layer_name)
|
||||
return result
|
||||
|
||||
|
||||
@router.post("", status_code=status.HTTP_201_CREATED)
|
||||
async def create_interactable(
|
||||
payload: InteractableCreate,
|
||||
|
||||
@@ -161,6 +161,7 @@ async def get_earth_feed(
|
||||
),
|
||||
categories: str | None = Query(None, description="Comma-separated news category keys"),
|
||||
sources: str | None = Query(None, description="Comma-separated news source ids"),
|
||||
theater: str | None = Query(None, description="Theater preset filter: global/russo_ukrainian/middle_east/indo_pacific/europe"),
|
||||
limit: int | None = Query(None, description="Maximum news items to return, capped at 100"),
|
||||
locale: str | None = Query(None, description="Display locale, zh-CN or en-US"),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
@@ -183,6 +184,7 @@ async def get_earth_feed(
|
||||
region=normalized_region,
|
||||
categories=_parse_categories(categories),
|
||||
source_ids=_parse_source_ids(sources),
|
||||
theater=theater,
|
||||
limit=_parse_limit(limit),
|
||||
locale=_parse_locale(locale),
|
||||
db=db,
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
"""Ontology object inspection, neighborhood traversal, aliases, and analyst links API (§3.7)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy import desc, select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.access_gate import require_admin_user, require_earth_or_api_access
|
||||
from app.db.session import get_db
|
||||
from app.models.ontology import AnalystLink, OntologyEntityAlias
|
||||
from app.models.user import User
|
||||
from app.services.ai.entity_resolver import (
|
||||
parse_object_id,
|
||||
resolve_ontology_neighborhood,
|
||||
resolve_ontology_object,
|
||||
)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
_read_dep = Depends(require_earth_or_api_access("visualization:read"))
|
||||
|
||||
|
||||
class AliasCreateRequest(BaseModel):
|
||||
alias: str = Field(min_length=1, max_length=200)
|
||||
object_id: str = Field(min_length=3, max_length=160)
|
||||
source: str = Field(default="analyst", max_length=80)
|
||||
|
||||
|
||||
class AnalystLinkCreateRequest(BaseModel):
|
||||
from_object_id: str = Field(min_length=3, max_length=160)
|
||||
to_object_id: str = Field(min_length=3, max_length=160)
|
||||
relation_type: str = Field(min_length=1, max_length=80)
|
||||
note: str = Field(default="", max_length=1000)
|
||||
evidence_ids: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
@router.get("/objects/{object_id:path}/neighborhood", dependencies=[_read_dep])
|
||||
async def get_ontology_object_neighborhood(
|
||||
object_id: str,
|
||||
depth: int = Query(default=1, ge=1, le=2),
|
||||
radius_km: float = Query(default=150.0, ge=5.0, le=1500.0),
|
||||
limit: int = Query(default=40, ge=1, le=120),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> dict[str, Any]:
|
||||
"""Return 1-to-2 hop read-time derived neighborhood + analyst-asserted links."""
|
||||
try:
|
||||
payload = await resolve_ontology_neighborhood(
|
||||
db, object_id, depth=depth, radius_km=radius_km, limit=limit
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
if payload is None:
|
||||
raise HTTPException(status_code=404, detail=f"Ontology object not found: {object_id}")
|
||||
return payload
|
||||
|
||||
|
||||
@router.get("/objects/{object_id:path}", dependencies=[_read_dep])
|
||||
async def get_ontology_object(
|
||||
object_id: str,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> dict[str, Any]:
|
||||
"""Resolve canonical ontology object `{type}:{id}` with provenance & freshness."""
|
||||
try:
|
||||
payload = await resolve_ontology_object(db, object_id)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
if payload is None:
|
||||
raise HTTPException(status_code=404, detail=f"Ontology object not found: {object_id}")
|
||||
return payload
|
||||
|
||||
|
||||
@router.get("/aliases", dependencies=[_read_dep])
|
||||
async def list_ontology_aliases(
|
||||
object_id: str | None = Query(default=None),
|
||||
limit: int = Query(default=100, ge=1, le=500),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> dict[str, Any]:
|
||||
stmt = select(OntologyEntityAlias).order_by(desc(OntologyEntityAlias.id)).limit(limit)
|
||||
if object_id:
|
||||
stmt = stmt.where(OntologyEntityAlias.object_id == object_id.strip())
|
||||
rows = list((await db.execute(stmt)).scalars().all())
|
||||
return {"items": [r.to_dict() for r in rows], "count": len(rows)}
|
||||
|
||||
|
||||
@router.post("/aliases")
|
||||
async def create_ontology_alias(
|
||||
body: AliasCreateRequest,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(require_admin_user),
|
||||
) -> dict[str, Any]:
|
||||
try:
|
||||
otype, ident = parse_object_id(body.object_id)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
canonical_id = f"{otype}:{ident}"
|
||||
row = OntologyEntityAlias(
|
||||
alias=body.alias.strip(),
|
||||
object_id=canonical_id,
|
||||
source=body.source.strip() or "analyst",
|
||||
created_by=current_user.username,
|
||||
)
|
||||
db.add(row)
|
||||
try:
|
||||
await db.commit()
|
||||
except IntegrityError as exc:
|
||||
await db.rollback()
|
||||
raise HTTPException(status_code=409, detail="Alias already exists for this object") from exc
|
||||
return row.to_dict()
|
||||
|
||||
|
||||
@router.delete("/aliases/{alias_id}")
|
||||
async def delete_ontology_alias(
|
||||
alias_id: int,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
_admin: User = Depends(require_admin_user),
|
||||
) -> dict[str, Any]:
|
||||
row = await db.get(OntologyEntityAlias, alias_id)
|
||||
if row is None:
|
||||
raise HTTPException(status_code=404, detail="Alias not found")
|
||||
await db.delete(row)
|
||||
await db.commit()
|
||||
return {"deleted": True, "id": alias_id}
|
||||
|
||||
|
||||
@router.get("/links", dependencies=[_read_dep])
|
||||
async def list_analyst_links(
|
||||
object_id: str | None = Query(default=None),
|
||||
include_revoked: bool = Query(default=False),
|
||||
limit: int = Query(default=100, ge=1, le=500),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> dict[str, Any]:
|
||||
stmt = select(AnalystLink).order_by(desc(AnalystLink.id)).limit(limit)
|
||||
if not include_revoked:
|
||||
stmt = stmt.where(AnalystLink.status == "active")
|
||||
if object_id:
|
||||
oid = object_id.strip()
|
||||
stmt = stmt.where(
|
||||
(AnalystLink.from_object_id == oid) | (AnalystLink.to_object_id == oid)
|
||||
)
|
||||
rows = list((await db.execute(stmt)).scalars().all())
|
||||
return {"items": [r.to_dict() for r in rows], "count": len(rows)}
|
||||
|
||||
|
||||
@router.post("/links")
|
||||
async def create_analyst_link(
|
||||
body: AnalystLinkCreateRequest,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(require_admin_user),
|
||||
) -> dict[str, Any]:
|
||||
try:
|
||||
ftype, fident = parse_object_id(body.from_object_id)
|
||||
ttype, tident = parse_object_id(body.to_object_id)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
link = AnalystLink(
|
||||
from_object_id=f"{ftype}:{fident}",
|
||||
to_object_id=f"{ttype}:{tident}",
|
||||
relation_type=body.relation_type.strip(),
|
||||
note=body.note.strip(),
|
||||
evidence_ids=list(body.evidence_ids or []),
|
||||
created_by=current_user.username,
|
||||
status="active",
|
||||
)
|
||||
db.add(link)
|
||||
await db.commit()
|
||||
return link.to_dict()
|
||||
|
||||
|
||||
@router.delete("/links/{link_id}")
|
||||
async def revoke_analyst_link(
|
||||
link_id: int,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
_admin: User = Depends(require_admin_user),
|
||||
) -> dict[str, Any]:
|
||||
link = await db.get(AnalystLink, link_id)
|
||||
if link is None:
|
||||
raise HTTPException(status_code=404, detail="Analyst link not found")
|
||||
link.status = "revoked"
|
||||
await db.commit()
|
||||
return link.to_dict()
|
||||
@@ -0,0 +1,421 @@
|
||||
"""4D temporal replay keyframes & layer availability API (§4.1)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.access_gate import require_earth_or_api_access
|
||||
from app.core.time import to_iso8601_utc
|
||||
from app.db.session import get_db
|
||||
from app.models.aircraft import AircraftPosition
|
||||
from app.models.bgp_incident import BGPIncident
|
||||
from app.models.collected_data import CollectedData
|
||||
from app.models.compute_configuration_revision import ComputeConfigurationRevision
|
||||
from app.models.disaster import DisasterEvent
|
||||
from app.models.earth_news import EarthNewsItem
|
||||
from app.models.geofence import SituationalIncident
|
||||
from app.models.vessel import VesselPosition
|
||||
from app.services.aircraft_aggregation import DEFAULT_POSITION_RETENTION_HOURS
|
||||
from app.services.vessel_ais_aggregation import VESSEL_TRACK_RETENTION_HOURS
|
||||
|
||||
router = APIRouter(dependencies=[Depends(require_earth_or_api_access("visualization:read"))])
|
||||
|
||||
MAX_REPLAY_SPAN_SECONDS = 6 * 3600
|
||||
|
||||
|
||||
def _coerce_utc(val: Any) -> datetime | None:
|
||||
if isinstance(val, datetime):
|
||||
return val.replace(tzinfo=UTC) if val.tzinfo is None else val.astimezone(UTC)
|
||||
if isinstance(val, str) and val.strip():
|
||||
try:
|
||||
parsed = datetime.fromisoformat(val.strip().replace("Z", "+00:00"))
|
||||
return parsed.replace(tzinfo=UTC) if parsed.tzinfo is None else parsed.astimezone(UTC)
|
||||
except ValueError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def _parse_bbox(raw_bbox: str | None) -> tuple[float, float, float, float] | None:
|
||||
if not raw_bbox:
|
||||
return None
|
||||
parts = [p.strip() for p in raw_bbox.split(",") if p.strip()]
|
||||
if len(parts) != 4:
|
||||
raise HTTPException(status_code=422, detail="bbox must be min_lon,min_lat,max_lon,max_lat")
|
||||
try:
|
||||
min_lon, min_lat, max_lon, max_lat = (float(x) for x in parts)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=422, detail="Invalid numeric coordinate in bbox") from exc
|
||||
return min_lon, min_lat, max_lon, max_lat
|
||||
|
||||
|
||||
def _in_bbox(lat: float, lon: float, bbox: tuple[float, float, float, float] | None) -> bool:
|
||||
if bbox is None:
|
||||
return True
|
||||
min_lon, min_lat, max_lon, max_lat = bbox
|
||||
return min_lat <= lat <= max_lat and min_lon <= lon <= max_lon
|
||||
|
||||
|
||||
async def compute_replay_availability(db: AsyncSession, *, now: datetime | None = None) -> dict[str, Any]:
|
||||
ref_now = now or datetime.now(UTC)
|
||||
|
||||
async def _min_max(col):
|
||||
row = (await db.execute(select(func.min(col), func.max(col)))).first()
|
||||
if not row:
|
||||
return None, None
|
||||
return _coerce_utc(row[0]), _coerce_utc(row[1])
|
||||
|
||||
air_min, air_max = await _min_max(AircraftPosition.observed_at)
|
||||
ves_min, ves_max = await _min_max(VesselPosition.received_at)
|
||||
bgp_min, bgp_max = await _min_max(BGPIncident.started_at)
|
||||
dis_min, dis_max = await _min_max(DisasterEvent.observed_at)
|
||||
news_min, news_max = await _min_max(EarthNewsItem.published_at)
|
||||
inc_min, inc_max = await _min_max(SituationalIncident.created_at)
|
||||
comp_min, comp_max = await _min_max(ComputeConfigurationRevision.published_at)
|
||||
|
||||
air_policy_from = ref_now - timedelta(hours=DEFAULT_POSITION_RETENTION_HOURS)
|
||||
ves_policy_from = ref_now - timedelta(hours=VESSEL_TRACK_RETENTION_HOURS)
|
||||
|
||||
layers = {
|
||||
"aircraft": {
|
||||
"retention_hours": DEFAULT_POSITION_RETENTION_HOURS,
|
||||
"policy_from": to_iso8601_utc(air_policy_from),
|
||||
"available_from": to_iso8601_utc(max(air_min, air_policy_from) if air_min else air_policy_from),
|
||||
"available_to": to_iso8601_utc(air_max or ref_now),
|
||||
"mode": "columnar_positions",
|
||||
},
|
||||
"vessels": {
|
||||
"retention_hours": VESSEL_TRACK_RETENTION_HOURS,
|
||||
"policy_from": to_iso8601_utc(ves_policy_from),
|
||||
"available_from": to_iso8601_utc(max(ves_min, ves_policy_from) if ves_min else ves_policy_from),
|
||||
"available_to": to_iso8601_utc(ves_max or ref_now),
|
||||
"mode": "columnar_positions",
|
||||
},
|
||||
"bgp": {
|
||||
"retention_hours": 7 * 24,
|
||||
"policy_from": to_iso8601_utc(ref_now - timedelta(days=7)),
|
||||
"available_from": to_iso8601_utc(bgp_min or (ref_now - timedelta(days=7))),
|
||||
"available_to": to_iso8601_utc(bgp_max or ref_now),
|
||||
"mode": "interval_events",
|
||||
},
|
||||
"disasters": {
|
||||
"retention_hours": 30 * 24,
|
||||
"policy_from": to_iso8601_utc(ref_now - timedelta(days=30)),
|
||||
"available_from": to_iso8601_utc(dis_min or (ref_now - timedelta(days=30))),
|
||||
"available_to": to_iso8601_utc(dis_max or ref_now),
|
||||
"mode": "point_events",
|
||||
},
|
||||
"news": {
|
||||
"retention_hours": 30 * 24,
|
||||
"policy_from": to_iso8601_utc(ref_now - timedelta(days=30)),
|
||||
"available_from": to_iso8601_utc(news_min or (ref_now - timedelta(days=30))),
|
||||
"available_to": to_iso8601_utc(news_max or ref_now),
|
||||
"mode": "point_events",
|
||||
},
|
||||
"incidents": {
|
||||
"retention_hours": 30 * 24,
|
||||
"policy_from": to_iso8601_utc(ref_now - timedelta(days=30)),
|
||||
"available_from": to_iso8601_utc(inc_min or (ref_now - timedelta(days=30))),
|
||||
"available_to": to_iso8601_utc(inc_max or ref_now),
|
||||
"mode": "interval_events",
|
||||
},
|
||||
"satellites": {
|
||||
"retention_hours": None,
|
||||
"available_from": to_iso8601_utc(ref_now - timedelta(days=7)),
|
||||
"available_to": to_iso8601_utc(ref_now + timedelta(hours=12)),
|
||||
"mode": "tle_live_propagation",
|
||||
},
|
||||
"compute": {
|
||||
"retention_hours": None,
|
||||
"available_from": to_iso8601_utc(comp_min),
|
||||
"available_to": to_iso8601_utc(comp_max or ref_now),
|
||||
"mode": "as_of_revision",
|
||||
},
|
||||
}
|
||||
return {
|
||||
"checked_at": to_iso8601_utc(ref_now),
|
||||
"max_chunk_seconds": MAX_REPLAY_SPAN_SECONDS,
|
||||
"layers": layers,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/availability")
|
||||
async def get_replay_availability(db: AsyncSession = Depends(get_db)) -> dict[str, Any]:
|
||||
"""Report actual retention window and propagation capabilities per replay layer."""
|
||||
return await compute_replay_availability(db)
|
||||
|
||||
|
||||
@router.get("/frames")
|
||||
async def get_replay_frames(
|
||||
start: str = Query(..., description="ISO-8601 UTC window start"),
|
||||
end: str = Query(..., description="ISO-8601 UTC window end (max 6 hours after start)"),
|
||||
step_sec: int = Query(default=60, ge=10, le=900),
|
||||
layers: str = Query(default="aircraft,vessels,disasters,incidents,bgp,satellites,compute"),
|
||||
bbox: str | None = Query(default=None),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> dict[str, Any]:
|
||||
"""Return columnar keyframes + compute as_of timeline for chunked <=6h 4D playback."""
|
||||
start_dt = _coerce_utc(start)
|
||||
end_dt = _coerce_utc(end)
|
||||
if start_dt is None or end_dt is None:
|
||||
raise HTTPException(status_code=422, detail="Invalid start or end ISO-8601 timestamp")
|
||||
span_sec = (end_dt - start_dt).total_seconds()
|
||||
if span_sec <= 0:
|
||||
raise HTTPException(status_code=400, detail="end must be strictly after start")
|
||||
if span_sec > MAX_REPLAY_SPAN_SECONDS:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Replay chunk span exceeds 6 hours ({int(span_sec)}s > {MAX_REPLAY_SPAN_SECONDS}s)",
|
||||
)
|
||||
|
||||
parsed_bbox = _parse_bbox(bbox)
|
||||
requested_layers = [x.strip().lower() for x in layers.split(",") if x.strip()]
|
||||
now = datetime.now(UTC)
|
||||
|
||||
timestamps: list[datetime] = []
|
||||
cursor = start_dt
|
||||
while cursor <= end_dt and len(timestamps) < 365:
|
||||
timestamps.append(cursor)
|
||||
cursor += timedelta(seconds=step_sec)
|
||||
if not timestamps or timestamps[-1] < end_dt:
|
||||
timestamps.append(end_dt)
|
||||
|
||||
availability = await compute_replay_availability(db, now=now)
|
||||
layer_Meta = availability["layers"]
|
||||
out_layers: dict[str, Any] = {}
|
||||
|
||||
if "aircraft" in requested_layers:
|
||||
policy_from = _coerce_utc(layer_Meta["aircraft"]["policy_from"])
|
||||
if policy_from and end_dt < policy_from:
|
||||
out_layers["aircraft"] = {
|
||||
"status": "unavailable",
|
||||
"reason": "outside_retention_window",
|
||||
"retention_hours": DEFAULT_POSITION_RETENTION_HOURS,
|
||||
"available_from": layer_Meta["aircraft"]["policy_from"],
|
||||
"available_to": layer_Meta["aircraft"]["available_to"],
|
||||
"frames": [],
|
||||
}
|
||||
else:
|
||||
rows = list(
|
||||
(
|
||||
await db.execute(
|
||||
select(AircraftPosition)
|
||||
.where(
|
||||
AircraftPosition.observed_at >= start_dt - timedelta(seconds=step_sec),
|
||||
AircraftPosition.observed_at <= end_dt,
|
||||
)
|
||||
.order_by(AircraftPosition.observed_at.asc())
|
||||
.limit(20000)
|
||||
)
|
||||
)
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
frames = []
|
||||
for ts in timestamps:
|
||||
lo = ts - timedelta(seconds=step_sec * 1.5)
|
||||
latest_by_id: dict[str, AircraftPosition] = {}
|
||||
for r in rows:
|
||||
obs = _coerce_utc(r.observed_at)
|
||||
if obs and lo <= obs <= ts and _in_bbox(float(r.lat), float(r.lon), parsed_bbox):
|
||||
latest_by_id[r.icao24] = r
|
||||
vals = list(latest_by_id.values())
|
||||
frames.append(
|
||||
{
|
||||
"ids": [v.icao24 for v in vals],
|
||||
"lats": [round(float(v.lat), 5) for v in vals],
|
||||
"lons": [round(float(v.lon), 5) for v in vals],
|
||||
"headings": [float(v.track_deg or 0.0) for v in vals],
|
||||
"alts": [float(v.altitude_m or 0.0) for v in vals],
|
||||
}
|
||||
)
|
||||
out_layers["aircraft"] = {
|
||||
"status": "ok",
|
||||
"partial": bool(policy_from and start_dt < policy_from),
|
||||
"available_from": layer_Meta["aircraft"]["policy_from"],
|
||||
"frames": frames,
|
||||
}
|
||||
|
||||
if "vessels" in requested_layers:
|
||||
policy_from = _coerce_utc(layer_Meta["vessels"]["policy_from"])
|
||||
if policy_from and end_dt < policy_from:
|
||||
out_layers["vessels"] = {
|
||||
"status": "unavailable",
|
||||
"reason": "outside_retention_window",
|
||||
"retention_hours": VESSEL_TRACK_RETENTION_HOURS,
|
||||
"available_from": layer_Meta["vessels"]["policy_from"],
|
||||
"available_to": layer_Meta["vessels"]["available_to"],
|
||||
"frames": [],
|
||||
}
|
||||
else:
|
||||
rows = list(
|
||||
(
|
||||
await db.execute(
|
||||
select(VesselPosition)
|
||||
.where(
|
||||
VesselPosition.received_at >= start_dt - timedelta(seconds=step_sec),
|
||||
VesselPosition.received_at <= end_dt,
|
||||
)
|
||||
.order_by(VesselPosition.received_at.asc())
|
||||
.limit(20000)
|
||||
)
|
||||
)
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
frames = []
|
||||
for ts in timestamps:
|
||||
lo = ts - timedelta(seconds=max(300, step_sec * 2))
|
||||
latest_by_id: dict[int, VesselPosition] = {}
|
||||
for r in rows:
|
||||
obs = _coerce_utc(r.received_at)
|
||||
if obs and lo <= obs <= ts and _in_bbox(float(r.lat), float(r.lon), parsed_bbox):
|
||||
latest_by_id[r.mmsi] = r
|
||||
vals = list(latest_by_id.values())
|
||||
frames.append(
|
||||
{
|
||||
"ids": [str(v.mmsi) for v in vals],
|
||||
"lats": [round(float(v.lat), 5) for v in vals],
|
||||
"lons": [round(float(v.lon), 5) for v in vals],
|
||||
"headings": [float(v.cog if v.cog is not None else (v.heading or 0.0)) for v in vals],
|
||||
"sogs": [float(v.sog or 0.0) for v in vals],
|
||||
}
|
||||
)
|
||||
out_layers["vessels"] = {
|
||||
"status": "ok",
|
||||
"partial": bool(policy_from and start_dt < policy_from),
|
||||
"available_from": layer_Meta["vessels"]["policy_from"],
|
||||
"frames": frames,
|
||||
}
|
||||
|
||||
if "disasters" in requested_layers:
|
||||
rows = list(
|
||||
(
|
||||
await db.execute(
|
||||
select(DisasterEvent)
|
||||
.where(
|
||||
DisasterEvent.duplicate_of.is_(None),
|
||||
DisasterEvent.observed_at >= start_dt - timedelta(hours=24),
|
||||
DisasterEvent.observed_at <= end_dt,
|
||||
)
|
||||
.limit(1000)
|
||||
)
|
||||
)
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
items = [
|
||||
r.to_dict()
|
||||
for r in rows
|
||||
if _in_bbox(float(r.lat), float(r.lon), parsed_bbox)
|
||||
]
|
||||
out_layers["disasters"] = {"status": "ok", "items": items}
|
||||
|
||||
if "incidents" in requested_layers:
|
||||
rows = list(
|
||||
(
|
||||
await db.execute(
|
||||
select(SituationalIncident)
|
||||
.where(
|
||||
SituationalIncident.created_at >= start_dt - timedelta(hours=12),
|
||||
SituationalIncident.created_at <= end_dt,
|
||||
)
|
||||
.order_by(SituationalIncident.created_at.asc())
|
||||
.limit(500)
|
||||
)
|
||||
)
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
out_layers["incidents"] = {"status": "ok", "items": [r.to_dict() for r in rows]}
|
||||
|
||||
if "bgp" in requested_layers:
|
||||
rows = list(
|
||||
(
|
||||
await db.execute(
|
||||
select(BGPIncident)
|
||||
.where(
|
||||
BGPIncident.started_at >= start_dt - timedelta(hours=12),
|
||||
BGPIncident.started_at <= end_dt,
|
||||
)
|
||||
.limit(300)
|
||||
)
|
||||
)
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
out_layers["bgp"] = {"status": "ok", "items": [r.to_dict() for r in rows]}
|
||||
|
||||
if "satellites" in requested_layers:
|
||||
tle_rows = list(
|
||||
(
|
||||
await db.execute(
|
||||
select(CollectedData)
|
||||
.where(
|
||||
CollectedData.source == "celestrak_tle",
|
||||
CollectedData.is_current.is_(True),
|
||||
)
|
||||
.limit(500)
|
||||
)
|
||||
)
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
tles = []
|
||||
for tr in tle_rows:
|
||||
ex = tr.extra_data or {}
|
||||
if ex.get("tle_line1") and ex.get("tle_line2"):
|
||||
tles.append(
|
||||
{
|
||||
"norad_id": ex.get("norad_id") or tr.source_id,
|
||||
"name": tr.name,
|
||||
"tle_line1": ex["tle_line1"],
|
||||
"tle_line2": ex["tle_line2"],
|
||||
}
|
||||
)
|
||||
out_layers["satellites"] = {
|
||||
"status": "ok",
|
||||
"mode": "tle_live_propagation",
|
||||
"tle_count": len(tles),
|
||||
"tles": tles,
|
||||
}
|
||||
|
||||
# Link every replay step to Phase 1 ComputeConfigurationRevision active `as_of` that timestamp
|
||||
revs = list(
|
||||
(
|
||||
await db.execute(
|
||||
select(ComputeConfigurationRevision)
|
||||
.where(ComputeConfigurationRevision.published_at <= end_dt)
|
||||
.order_by(ComputeConfigurationRevision.published_at.asc())
|
||||
)
|
||||
)
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
compute_as_of: list[dict[str, Any] | None] = []
|
||||
for ts in timestamps:
|
||||
active = None
|
||||
for rev in revs:
|
||||
pub_at = _coerce_utc(rev.published_at)
|
||||
if pub_at and pub_at <= ts:
|
||||
active = {
|
||||
"publish_id": rev.publish_id,
|
||||
"action": rev.action,
|
||||
"published_at": to_iso8601_utc(pub_at),
|
||||
}
|
||||
else:
|
||||
break
|
||||
compute_as_of.append(active)
|
||||
|
||||
return {
|
||||
"start": to_iso8601_utc(start_dt),
|
||||
"end": to_iso8601_utc(end_dt),
|
||||
"step_sec": step_sec,
|
||||
"timestamps": [to_iso8601_utc(ts) for ts in timestamps],
|
||||
"compute_as_of": compute_as_of,
|
||||
"layers": out_layers,
|
||||
}
|
||||
@@ -31,6 +31,7 @@ from app.models.datasource import DataSource
|
||||
from app.models.datasource_config import DataSourceConfig
|
||||
from app.models.system_setting import SystemSetting
|
||||
from app.models.user import User
|
||||
from app.models.aircraft import ADSBSourceHealth
|
||||
from app.models.vessel import AISSourceHealth
|
||||
from app.schemas.ai import SituationalAnalysisRequest
|
||||
from app.services.barentswatch import (
|
||||
@@ -1271,10 +1272,16 @@ async def get_ais_source_health_by_source(db: AsyncSession) -> dict[str, dict]:
|
||||
return {item.source: item.to_dict() for item in result.scalars().all()}
|
||||
|
||||
|
||||
async def get_adsb_source_health_by_source(db: AsyncSession) -> dict[str, dict]:
|
||||
result = await db.execute(select(ADSBSourceHealth))
|
||||
return {item.source: item.to_dict() for item in result.scalars().all()}
|
||||
|
||||
|
||||
def serialize_collector(
|
||||
datasource: DataSource,
|
||||
ais_health_by_source: dict[str, dict] | None = None,
|
||||
storage_policy: dict | None = None,
|
||||
adsb_health_by_source: dict[str, dict] | None = None,
|
||||
) -> dict:
|
||||
defaults = DEFAULT_DATASOURCES.get(datasource.source, {})
|
||||
effective_mode = resolve_snapshot_mode(storage_policy, datasource.source)
|
||||
@@ -1297,6 +1304,7 @@ def serialize_collector(
|
||||
"credential_provider": defaults.get("credential_provider"),
|
||||
"credential_status": defaults.get("credential_status", "none"),
|
||||
"ais_health": (ais_health_by_source or {}).get(datasource.source),
|
||||
"adsb_health": (adsb_health_by_source or {}).get(datasource.source),
|
||||
"snapshot_mode": effective_mode,
|
||||
"snapshot_overridden": datasource.source in overrides,
|
||||
"snapshot_locked": bool((storage_policy or {}).get("global_single_lock", False)),
|
||||
@@ -2281,12 +2289,14 @@ async def get_collector_settings(
|
||||
result = await db.execute(select(DataSource).order_by(DataSource.module, DataSource.id))
|
||||
datasources = result.scalars().all()
|
||||
ais_health_by_source = await get_ais_source_health_by_source(db)
|
||||
adsb_health_by_source = await get_adsb_source_health_by_source(db)
|
||||
storage_policy = await get_storage_policy(db)
|
||||
return {
|
||||
"collectors": [
|
||||
serialize_collector(datasource, ais_health_by_source, storage_policy)
|
||||
serialize_collector(datasource, ais_health_by_source, storage_policy, adsb_health_by_source)
|
||||
for datasource in datasources
|
||||
],
|
||||
"adsb_source_health": list(adsb_health_by_source.values()),
|
||||
"storage_policy": summarize_storage_policy(
|
||||
storage_policy,
|
||||
[datasource.source for datasource in datasources],
|
||||
@@ -2343,10 +2353,11 @@ async def update_collector_settings(
|
||||
|
||||
await sync_datasource_job(datasource.id)
|
||||
ais_health_by_source = await get_ais_source_health_by_source(db)
|
||||
adsb_health_by_source = await get_adsb_source_health_by_source(db)
|
||||
sources = await _load_known_collector_sources(db)
|
||||
return {
|
||||
"status": "updated",
|
||||
"collector": serialize_collector(datasource, ais_health_by_source, storage_policy),
|
||||
"collector": serialize_collector(datasource, ais_health_by_source, storage_policy, adsb_health_by_source),
|
||||
"storage_policy": summarize_storage_policy(storage_policy, sources),
|
||||
}
|
||||
|
||||
@@ -2363,6 +2374,7 @@ async def get_all_settings(
|
||||
["system", "notifications", "security"],
|
||||
)
|
||||
ais_health_by_source = await get_ais_source_health_by_source(db)
|
||||
adsb_health_by_source = await get_adsb_source_health_by_source(db)
|
||||
storage_policy = await get_storage_policy(db)
|
||||
return {
|
||||
"system": setting_payloads["system"],
|
||||
@@ -2371,9 +2383,10 @@ async def get_all_settings(
|
||||
"tv": await get_tv_settings_payload(db),
|
||||
"integrations": await serialize_external_integrations(db),
|
||||
"collectors": [
|
||||
serialize_collector(datasource, ais_health_by_source, storage_policy)
|
||||
serialize_collector(datasource, ais_health_by_source, storage_policy, adsb_health_by_source)
|
||||
for datasource in datasources
|
||||
],
|
||||
"adsb_source_health": list(adsb_health_by_source.values()),
|
||||
"storage_policy": summarize_storage_policy(
|
||||
storage_policy,
|
||||
[datasource.source for datasource in datasources],
|
||||
|
||||
@@ -13,6 +13,7 @@ from pydantic import BaseModel
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.config import ROOT_DIR, settings
|
||||
from app.core.access_gate import require_earth_or_api_access
|
||||
from app.core.enums import UserRole
|
||||
from app.core.security import get_current_user
|
||||
from app.db.session import get_db
|
||||
@@ -45,6 +46,7 @@ from app.services.system_logs import (
|
||||
read_observability_raw_events,
|
||||
)
|
||||
from app.services.earth_layer_cache import earth_layer_cache
|
||||
from app.services.source_freshness import compute_domain_freshness
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -746,3 +748,12 @@ async def get_external_openapi_schema(
|
||||
):
|
||||
"""Return curated external/UE5 OpenAPI schema excluding internal admin endpoints."""
|
||||
return _build_external_openapi_schema(request.app.openapi())
|
||||
|
||||
|
||||
@router.get("/freshness")
|
||||
async def get_system_source_freshness(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
_access=Depends(require_earth_or_api_access("visualization:read")),
|
||||
):
|
||||
"""Return sanitized per-domain data freshness and intelligence blind spots for Earth HUD."""
|
||||
return await compute_domain_freshness(db)
|
||||
@@ -8,6 +8,10 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from app.api.v1.visualization import _parse_bbox, build_vessel_snapshot_response
|
||||
from app.core.access_gate import require_earth_or_api_access
|
||||
from app.db.session import get_db
|
||||
from app.services.maritime_geography import (
|
||||
compute_chokepoint_vessel_summary,
|
||||
load_strategic_ports,
|
||||
)
|
||||
from app.services.vessel_ais_aggregation import MAX_SNAPSHOT_LIMIT
|
||||
|
||||
router = APIRouter()
|
||||
@@ -40,3 +44,18 @@ async def get_vessel_snapshot(
|
||||
since_minutes=since_minutes,
|
||||
response=response,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/maritime-context", dependencies=[Depends(require_earth_or_api_access("vessels:read"))])
|
||||
async def get_maritime_context(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Return cited maritime chokepoints with live/baseline counts and strategic ports."""
|
||||
chokepoints = await compute_chokepoint_vessel_summary(db)
|
||||
ports = load_strategic_ports()
|
||||
return {
|
||||
"chokepoint_count": len(chokepoints),
|
||||
"chokepoints": chokepoints,
|
||||
"port_count": len(ports),
|
||||
"ports": ports,
|
||||
}
|
||||
@@ -6,11 +6,14 @@ Returns GeoJSON format compatible with Three.js, CesiumJS, and Unreal Cesium.
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
from collections import OrderedDict
|
||||
from contextlib import aclosing
|
||||
from contextlib import aclosing, suppress
|
||||
from datetime import UTC, datetime, timedelta
|
||||
import hashlib
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
from uuid import uuid4
|
||||
import httpx
|
||||
from fastapi import APIRouter, HTTPException, Depends, Query, Request, Response
|
||||
from pydantic import BaseModel, Field
|
||||
@@ -26,10 +29,12 @@ from app.core.satellite_tle import build_tle_lines_from_elements
|
||||
from app.core.time import to_iso8601_utc
|
||||
from app.db.session import get_db
|
||||
from app.core.satellite_presentation import satellite_constellation_group as _normalize_satellite_constellation_group
|
||||
from app.models.aircraft import AircraftCurrentState
|
||||
from app.models.bgp_anomaly import BGPAnomaly
|
||||
from app.models.bgp_incident import BGPIncident
|
||||
from app.models.bgp_observation import BGPObservation
|
||||
from app.models.collected_data import CollectedData
|
||||
from app.models.gps_jamming import GPSJammingCell
|
||||
from app.models.user import User
|
||||
from app.models.vessel import AISSourceHealth, VesselCurrentState, VesselPosition, VesselStatic
|
||||
from app.services.bgp_collectors import build_bgp_collector_coverage
|
||||
@@ -79,10 +84,11 @@ _vis_tile_read_dep = Depends(
|
||||
TERRAIN_TILE_URL_TEMPLATE = (
|
||||
"https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png"
|
||||
)
|
||||
TERRAIN_TILE_CACHE_MAX_ITEMS = 512
|
||||
TERRAIN_REPO_ROOT = Path(__file__).resolve().parents[4]
|
||||
TERRAIN_CACHE_DEFAULT_DIR = TERRAIN_REPO_ROOT / "data" / "earth-terrain-cache"
|
||||
TERRAIN_CACHE_MAX_BYTES_DEFAULT = 128 * 1024 * 1024
|
||||
TERRAIN_TILE_BATCH_MAX_ITEMS = 128
|
||||
TERRAIN_TILE_BATCH_CONCURRENCY = 16
|
||||
_terrain_tile_cache: OrderedDict[tuple[int, int, int], tuple[bytes, str, dict[str, str]]] = OrderedDict()
|
||||
VESSEL_NAME_FALLBACK_PATTERN = re.compile(r"^mmsi\s*\d+$", re.IGNORECASE)
|
||||
SECONDS_PER_MINUTE = 60
|
||||
BYTES_PER_MIB = 1024 * 1024
|
||||
@@ -1203,11 +1209,24 @@ async def build_vessel_snapshot_response(
|
||||
bbox=bbox,
|
||||
requested_types=requested_types,
|
||||
)[:safe_limit]
|
||||
chokepoints = []
|
||||
try:
|
||||
from app.services.maritime_geography import (
|
||||
compute_chokepoint_vessel_summary,
|
||||
enrich_vessel_feature_roles,
|
||||
)
|
||||
|
||||
for feat in features:
|
||||
enrich_vessel_feature_roles(feat)
|
||||
chokepoints = await compute_chokepoint_vessel_summary(db, features)
|
||||
except Exception:
|
||||
chokepoints = []
|
||||
return {
|
||||
"type": "FeatureCollection",
|
||||
"features": features,
|
||||
"count": len(features),
|
||||
"stats": _build_vessel_stats(features),
|
||||
"chokepoints": chokepoints,
|
||||
"generated_at": to_iso8601_utc(snapshot_started_at),
|
||||
"diagnostics": {
|
||||
**diagnostics,
|
||||
@@ -1638,8 +1657,34 @@ async def get_cables_geojson(db: AsyncSession = Depends(get_db), response: Respo
|
||||
async def _build_cables_geojson(db: AsyncSession) -> dict[str, Any]:
|
||||
try:
|
||||
records = await _load_current_collected_data(db, "arcgis_cables")
|
||||
geojson = convert_cable_to_geojson(records)
|
||||
try:
|
||||
from app.services.nga_advisories import map_advisories_by_cable_id
|
||||
|
||||
return convert_cable_to_geojson(records)
|
||||
advisories_by_id = await map_advisories_by_cable_id(db)
|
||||
if advisories_by_id:
|
||||
for feat in geojson.get("features") or []:
|
||||
props = feat.get("properties")
|
||||
if not isinstance(props, dict):
|
||||
continue
|
||||
cid = str(
|
||||
props.get("cable_id")
|
||||
or props.get("id")
|
||||
or props.get("Name")
|
||||
or props.get("name")
|
||||
or ""
|
||||
).strip()
|
||||
matched = advisories_by_id.get(cid) or []
|
||||
if matched:
|
||||
props["advisories"] = matched
|
||||
props["has_advisory"] = True
|
||||
except Exception as adv_exc:
|
||||
logger.debug_event(
|
||||
"Skipped attaching cable advisories",
|
||||
event="visualization.cables.advisories_skipped",
|
||||
context={"error_type": type(adv_exc).__name__},
|
||||
)
|
||||
return geojson
|
||||
except Exception as e:
|
||||
logger.exception_event(
|
||||
"Failed to build cables GeoJSON response",
|
||||
@@ -1715,11 +1760,22 @@ async def _build_landing_points_geojson(db: AsyncSession) -> dict[str, Any]:
|
||||
|
||||
|
||||
@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."""
|
||||
@router.head("/terrain/terrarium/{z}/{x}/{y}.png", dependencies=[_vis_tile_read_dep])
|
||||
async def get_terrarium_tile(request: Request, z: int, x: int, y: int):
|
||||
"""Proxy Terrarium elevation tiles with bounded disk LRU + conditional 304 validation."""
|
||||
if not _is_valid_terrain_tile(z, x, y):
|
||||
raise HTTPException(status_code=400, detail="Invalid terrain tile coordinates")
|
||||
|
||||
cached = _get_cached_terrain_tile(z, x, y)
|
||||
if cached is not None:
|
||||
content, content_type, headers = cached
|
||||
etag = headers.get("ETag")
|
||||
if etag and _etag_matches(request.headers.get("if-none-match"), etag):
|
||||
return Response(status_code=304, headers=headers)
|
||||
if request.method == "HEAD":
|
||||
return Response(status_code=200, media_type=content_type, headers=headers)
|
||||
return Response(content=content, media_type=content_type, headers=headers)
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=20.0, follow_redirects=True) as client:
|
||||
content, content_type, headers = await _fetch_terrain_tile(client, z, x, y)
|
||||
@@ -1734,6 +1790,11 @@ async def get_terrarium_tile(z: int, x: int, y: int):
|
||||
detail=f"Terrain tile fetch failed: {exc}",
|
||||
) from exc
|
||||
|
||||
etag = headers.get("ETag")
|
||||
if etag and _etag_matches(request.headers.get("if-none-match"), etag):
|
||||
return Response(status_code=304, headers=headers)
|
||||
if request.method == "HEAD":
|
||||
return Response(status_code=200, media_type=content_type, headers=headers)
|
||||
return Response(
|
||||
content=content,
|
||||
media_type=content_type,
|
||||
@@ -1741,6 +1802,74 @@ async def get_terrarium_tile(z: int, x: int, y: int):
|
||||
)
|
||||
|
||||
|
||||
def _etag_matches(if_none_match: str | None, etag: str) -> bool:
|
||||
if not if_none_match:
|
||||
return False
|
||||
target = etag.strip()
|
||||
if target.startswith("W/"):
|
||||
target = target[2:].strip()
|
||||
for candidate in if_none_match.split(","):
|
||||
token = candidate.strip()
|
||||
if token == "*":
|
||||
return True
|
||||
if token.startswith("W/"):
|
||||
token = token[2:].strip()
|
||||
if token == target:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _terrain_cache_dir() -> Path:
|
||||
configured = str(os.environ.get("PLANET_TERRAIN_CACHE_DIR") or "").strip()
|
||||
return Path(configured).expanduser() if configured else TERRAIN_CACHE_DEFAULT_DIR
|
||||
|
||||
|
||||
def _terrain_cache_max_bytes() -> int:
|
||||
raw = str(os.environ.get("PLANET_TERRAIN_CACHE_MAX_BYTES") or "").strip()
|
||||
if raw:
|
||||
try:
|
||||
return max(1024, int(raw))
|
||||
except ValueError:
|
||||
pass
|
||||
return TERRAIN_CACHE_MAX_BYTES_DEFAULT
|
||||
|
||||
|
||||
def _terrain_tile_path(z: int, x: int, y: int) -> Path:
|
||||
return _terrain_cache_dir() / f"{z}_{x}_{y}.png"
|
||||
|
||||
|
||||
def _terrain_tile_headers(content: bytes, *, cache_control: str = "public, max-age=86400") -> dict[str, str]:
|
||||
digest = hashlib.sha256(content).hexdigest()[:24]
|
||||
return {
|
||||
"Cache-Control": cache_control,
|
||||
"ETag": f'"{digest}"',
|
||||
}
|
||||
|
||||
|
||||
def _prune_terrain_disk_cache(cache_dir: Path, max_bytes: int) -> None:
|
||||
try:
|
||||
entries: list[tuple[float, int, Path]] = []
|
||||
total = 0
|
||||
for item in cache_dir.iterdir():
|
||||
if not item.is_file() or not item.name.endswith(".png"):
|
||||
continue
|
||||
stat = item.stat()
|
||||
total += stat.st_size
|
||||
entries.append((stat.st_mtime, stat.st_size, item))
|
||||
if total <= max_bytes:
|
||||
return
|
||||
target = int(max_bytes * 0.85)
|
||||
entries.sort(key=lambda row: row[0])
|
||||
for _mtime, size, item in entries:
|
||||
if total <= target:
|
||||
break
|
||||
with suppress(OSError):
|
||||
item.unlink(missing_ok=True)
|
||||
total -= size
|
||||
except OSError:
|
||||
return
|
||||
|
||||
|
||||
def _is_valid_terrain_tile(z: int, x: int, y: int) -> bool:
|
||||
if z < 0 or x < 0 or y < 0:
|
||||
return False
|
||||
@@ -1749,13 +1878,16 @@ def _is_valid_terrain_tile(z: int, x: int, y: int) -> bool:
|
||||
|
||||
|
||||
def _get_cached_terrain_tile(z: int, x: int, y: int) -> tuple[bytes, str, dict[str, str]] | None:
|
||||
key = (z, x, y)
|
||||
cached = _terrain_tile_cache.get(key)
|
||||
if cached is None:
|
||||
path = _terrain_tile_path(z, x, y)
|
||||
if not path.is_file():
|
||||
return None
|
||||
_terrain_tile_cache.move_to_end(key)
|
||||
content, content_type, headers = cached
|
||||
return content, content_type, dict(headers)
|
||||
try:
|
||||
content = path.read_bytes()
|
||||
with suppress(OSError):
|
||||
os.utime(path, None)
|
||||
except OSError:
|
||||
return None
|
||||
return content, "image/png", _terrain_tile_headers(content)
|
||||
|
||||
|
||||
def _cache_terrain_tile(
|
||||
@@ -1763,14 +1895,21 @@ def _cache_terrain_tile(
|
||||
x: int,
|
||||
y: int,
|
||||
content: bytes,
|
||||
content_type: str,
|
||||
headers: dict[str, str],
|
||||
_content_type: str,
|
||||
_headers: dict[str, str],
|
||||
) -> None:
|
||||
key = (z, x, y)
|
||||
_terrain_tile_cache[key] = (content, content_type, dict(headers))
|
||||
_terrain_tile_cache.move_to_end(key)
|
||||
while len(_terrain_tile_cache) > TERRAIN_TILE_CACHE_MAX_ITEMS:
|
||||
_terrain_tile_cache.popitem(last=False)
|
||||
cache_dir = _terrain_cache_dir()
|
||||
cache_dir.mkdir(parents=True, exist_ok=True)
|
||||
path = _terrain_tile_path(z, x, y)
|
||||
tmp_path = path.with_suffix(f".{uuid4().hex}.tmp")
|
||||
try:
|
||||
tmp_path.write_bytes(content)
|
||||
tmp_path.replace(path)
|
||||
except OSError:
|
||||
with suppress(OSError):
|
||||
tmp_path.unlink(missing_ok=True)
|
||||
return
|
||||
_prune_terrain_disk_cache(cache_dir, _terrain_cache_max_bytes())
|
||||
|
||||
|
||||
async def _fetch_terrain_tile(
|
||||
@@ -1788,18 +1927,9 @@ async def _fetch_terrain_tile(
|
||||
upstream.raise_for_status()
|
||||
|
||||
cache_control = upstream.headers.get("cache-control") or "public, max-age=86400"
|
||||
headers = {
|
||||
"Cache-Control": cache_control,
|
||||
}
|
||||
etag = upstream.headers.get("etag")
|
||||
last_modified = upstream.headers.get("last-modified")
|
||||
if etag:
|
||||
headers["ETag"] = etag
|
||||
if last_modified:
|
||||
headers["Last-Modified"] = last_modified
|
||||
|
||||
content_type = upstream.headers.get("content-type", "image/png")
|
||||
content = upstream.content
|
||||
headers = _terrain_tile_headers(content, cache_control=cache_control)
|
||||
_cache_terrain_tile(z, x, y, content, content_type, headers)
|
||||
return content, content_type, dict(headers)
|
||||
|
||||
@@ -2958,6 +3088,103 @@ async def _build_visualization_geo_summary(db: AsyncSession) -> dict[str, Any]:
|
||||
vessel_count = int(vessel_current_result.scalar() or 0)
|
||||
aisstream_health = await db.get(AISSourceHealth, "aisstream_vessels")
|
||||
|
||||
def _safe_non_negative_int(value: Any) -> int:
|
||||
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
||||
return 0
|
||||
return max(0, int(value))
|
||||
|
||||
aircraft_cutoff = datetime.now(UTC) - timedelta(minutes=15)
|
||||
aircraft_count = _safe_non_negative_int(
|
||||
(
|
||||
await db.execute(
|
||||
select(func.count(AircraftCurrentState.icao24)).where(
|
||||
AircraftCurrentState.observed_at >= aircraft_cutoff
|
||||
)
|
||||
)
|
||||
).scalar()
|
||||
)
|
||||
military_aircraft_count = _safe_non_negative_int(
|
||||
(
|
||||
await db.execute(
|
||||
select(func.count(AircraftCurrentState.icao24)).where(
|
||||
AircraftCurrentState.observed_at >= aircraft_cutoff,
|
||||
AircraftCurrentState.is_military.is_(True),
|
||||
)
|
||||
)
|
||||
).scalar()
|
||||
)
|
||||
emergency_aircraft_count = _safe_non_negative_int(
|
||||
(
|
||||
await db.execute(
|
||||
select(func.count(AircraftCurrentState.icao24)).where(
|
||||
AircraftCurrentState.observed_at >= aircraft_cutoff,
|
||||
AircraftCurrentState.is_emergency.is_(True),
|
||||
)
|
||||
)
|
||||
).scalar()
|
||||
)
|
||||
latest_jam_date = (
|
||||
await db.execute(select(func.max(GPSJammingCell.observed_date)))
|
||||
).scalar()
|
||||
gps_jamming_high_count = 0
|
||||
gps_jamming_cell_count = 0
|
||||
if (
|
||||
isinstance(latest_jam_date, str)
|
||||
and len(latest_jam_date) == 10
|
||||
and latest_jam_date[4] == "-"
|
||||
and latest_jam_date[7] == "-"
|
||||
):
|
||||
gps_jamming_cell_count = _safe_non_negative_int(
|
||||
(
|
||||
await db.execute(
|
||||
select(func.count(GPSJammingCell.h3_index)).where(
|
||||
GPSJammingCell.observed_date == latest_jam_date,
|
||||
)
|
||||
)
|
||||
).scalar()
|
||||
)
|
||||
gps_jamming_high_count = _safe_non_negative_int(
|
||||
(
|
||||
await db.execute(
|
||||
select(func.count(GPSJammingCell.h3_index)).where(
|
||||
GPSJammingCell.observed_date == latest_jam_date,
|
||||
GPSJammingCell.level == "high",
|
||||
)
|
||||
)
|
||||
).scalar()
|
||||
)
|
||||
|
||||
disaster_event_count = 0
|
||||
disaster_high_count = 0
|
||||
try:
|
||||
from app.models.disaster import DisasterEvent
|
||||
|
||||
disaster_cutoff = datetime.now(UTC) - timedelta(hours=72)
|
||||
disaster_event_count = _safe_non_negative_int(
|
||||
(
|
||||
await db.execute(
|
||||
select(func.count(DisasterEvent.id)).where(
|
||||
DisasterEvent.observed_at >= disaster_cutoff,
|
||||
DisasterEvent.duplicate_of.is_(None),
|
||||
)
|
||||
)
|
||||
).scalar()
|
||||
)
|
||||
disaster_high_count = _safe_non_negative_int(
|
||||
(
|
||||
await db.execute(
|
||||
select(func.count(DisasterEvent.id)).where(
|
||||
DisasterEvent.observed_at >= disaster_cutoff,
|
||||
DisasterEvent.duplicate_of.is_(None),
|
||||
DisasterEvent.severity == "high",
|
||||
)
|
||||
)
|
||||
).scalar()
|
||||
)
|
||||
except Exception:
|
||||
disaster_event_count = 0
|
||||
disaster_high_count = 0
|
||||
|
||||
return {
|
||||
"generated_at": to_iso8601_utc(datetime.now(UTC)),
|
||||
"stats": {
|
||||
@@ -2970,6 +3197,13 @@ async def _build_visualization_geo_summary(db: AsyncSession) -> dict[str, Any]:
|
||||
"vessel_current_window_minutes": vessel_current_window_minutes,
|
||||
"vessel_raw_unique_mmsi": 0,
|
||||
"vessel_legacy_unique_mmsi": 0,
|
||||
"aircraft_count": aircraft_count,
|
||||
"military_aircraft_count": military_aircraft_count,
|
||||
"emergency_aircraft_count": emergency_aircraft_count,
|
||||
"gps_jamming_cell_count": gps_jamming_cell_count,
|
||||
"gps_jamming_high_count": gps_jamming_high_count,
|
||||
"disaster_event_count": disaster_event_count,
|
||||
"disaster_high_count": disaster_high_count,
|
||||
"aisstream_connection_state": aisstream_health.connection_state if aisstream_health else None,
|
||||
"aisstream_last_seen_at": to_iso8601_utc(aisstream_health.last_seen_at) if aisstream_health else None,
|
||||
"aisstream_message_rate": aisstream_health.message_rate if aisstream_health else None,
|
||||
|
||||
@@ -37,6 +37,15 @@ COLLECTOR_URL_KEYS = {
|
||||
"earth_imagery_sentinel2": "earth_imagery_sentinel2.wmts_url",
|
||||
"earth_imagery_viirs_daily": "earth_imagery_viirs_daily.wmts_url",
|
||||
"global_wind_gfs": "global_wind_gfs.erddap_url",
|
||||
"adsb_lol_aircraft": "adsb_lol_aircraft.base_url",
|
||||
"opensky_aircraft": "opensky_aircraft.states_url",
|
||||
"gpsjam_interference": "gpsjam_interference.manifest_url",
|
||||
"aircraft_registry": "aircraft_registry.csv_url",
|
||||
"usgs_earthquakes": "usgs_earthquakes.url",
|
||||
"nasa_firms_wildfires": "nasa_firms_wildfires.url",
|
||||
"gdacs_disasters": "gdacs_disasters.url",
|
||||
"nasa_eonet_events": "nasa_eonet_events.url",
|
||||
"nga_navigation_warnings": "nga_navigation_warnings.url",
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -124,3 +124,44 @@ earth_imagery_viirs_daily:
|
||||
global_wind_gfs:
|
||||
# PacIOOS ERDDAP NCEP GFS global 0.5-deg 10m wind CSV0 endpoint
|
||||
erddap_url: "https://pae-paha.pacioos.hawaii.edu/erddap/griddap/ncep_global.csv0"
|
||||
|
||||
adsb_lol_aircraft:
|
||||
# adsb.lol open ADS-B API (ODbL attribution required)
|
||||
base_url: "https://api.adsb.lol"
|
||||
|
||||
opensky_aircraft:
|
||||
# OpenSky Network REST API (OAuth2 client credentials; non-commercial / research use)
|
||||
states_url: "https://opensky-network.org/api/states/all"
|
||||
token_url: "https://auth.opensky-network.org/auth/realms/opensky-network/protocol/openid-connect/token"
|
||||
|
||||
gpsjam_interference:
|
||||
# gpsjam.org daily H3 resolution-4 interference manifest & CSV base
|
||||
manifest_url: "https://gpsjam.org/data/manifest.csv"
|
||||
base_data_url: "https://gpsjam.org/data"
|
||||
|
||||
aircraft_registry:
|
||||
# Open ICAO24 aircraft registry CSV (OpenSky Aircraft Database primary, tar1090-db fallback)
|
||||
csv_url: "https://s3.opensky-network.org/data-samples/metadata/aircraft-database-complete-2025-02.csv"
|
||||
fallback_url: "https://github.com/wiedehopf/tar1090-db/raw/csv/aircraft.csv.gz"
|
||||
|
||||
usgs_earthquakes:
|
||||
# USGS Earthquake Hazards Program M4.5+ past-day GeoJSON feed
|
||||
url: "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_day.geojson"
|
||||
|
||||
nasa_firms_wildfires:
|
||||
# NASA FIRMS VIIRS SNPP NRT active fire area CSV API (requires free MAP_KEY)
|
||||
url: "https://firms.modaps.eosdis.nasa.gov/api/area/csv"
|
||||
sensor: "VIIRS_SNPP_NRT"
|
||||
days: 1
|
||||
|
||||
gdacs_disasters:
|
||||
# GDACS Global Disaster Alert and Coordination System RSS/GeoJSON search
|
||||
url: "https://www.gdacs.org/gdacsapi/api/events/geteventlist/SEARCH"
|
||||
|
||||
nasa_eonet_events:
|
||||
# NASA Earth Observatory Natural Event Tracker v3 open events API
|
||||
url: "https://eonet.gsfc.nasa.gov/api/v3/events?status=open&limit=100"
|
||||
|
||||
nga_navigation_warnings:
|
||||
# NGA Maritime Safety Information Broadcast Warnings API
|
||||
url: "https://msi.nga.mil/api/publications/broadcast-warn?output=json"
|
||||
@@ -317,6 +317,100 @@ DEFAULT_DATASOURCES = {
|
||||
"is_free": True,
|
||||
"requires_credentials": False,
|
||||
},
|
||||
"adsb_lol_aircraft": {
|
||||
"id": 39,
|
||||
"name": "adsb.lol Military & Emergency ADS-B",
|
||||
"display_name": "全球军机与紧急航班 (adsb.lol · ODbL)",
|
||||
"module": "L4",
|
||||
"priority": "P1",
|
||||
"frequency_minutes": 1,
|
||||
"is_free": True,
|
||||
"requires_credentials": False,
|
||||
},
|
||||
"opensky_aircraft": {
|
||||
"id": 40,
|
||||
"name": "OpenSky Network Global Aircraft States (Non-Commercial / Research)",
|
||||
"display_name": "OpenSky 全球空域状态(仅限非商业/研究用途)",
|
||||
"module": "L4",
|
||||
"priority": "P1",
|
||||
"frequency_minutes": 2,
|
||||
"is_free": True,
|
||||
"requires_credentials": True,
|
||||
"credential_provider": "opensky",
|
||||
"credential_status": "supported",
|
||||
},
|
||||
"gpsjam_interference": {
|
||||
"id": 41,
|
||||
"name": "GPSJAM Daily H3 GNSS Interference",
|
||||
"display_name": "GPS/GNSS 干扰监测 (gpsjam.org)",
|
||||
"module": "L4",
|
||||
"priority": "P2",
|
||||
"frequency_minutes": 360,
|
||||
"is_free": True,
|
||||
"requires_credentials": False,
|
||||
},
|
||||
"aircraft_registry": {
|
||||
"id": 42,
|
||||
"name": "Open ICAO24 Aircraft Registry Database",
|
||||
"display_name": "ICAO24 机型与运营方注册库",
|
||||
"module": "L4",
|
||||
"priority": "P2",
|
||||
"frequency_minutes": 10080,
|
||||
"is_free": True,
|
||||
"requires_credentials": False,
|
||||
},
|
||||
"usgs_earthquakes": {
|
||||
"id": 43,
|
||||
"name": "USGS M4.5+ Earthquakes",
|
||||
"display_name": "USGS 全球 M4.5+ 地震监测",
|
||||
"module": "L4",
|
||||
"priority": "P1",
|
||||
"frequency_minutes": 5,
|
||||
"is_free": True,
|
||||
"requires_credentials": False,
|
||||
},
|
||||
"nasa_firms_wildfires": {
|
||||
"id": 44,
|
||||
"name": "NASA FIRMS VIIRS Active Fires",
|
||||
"display_name": "NASA FIRMS VIIRS 全球林火热点",
|
||||
"module": "L4",
|
||||
"priority": "P1",
|
||||
"frequency_minutes": 30,
|
||||
"is_free": True,
|
||||
"requires_credentials": True,
|
||||
"credential_provider": "nasa_firms",
|
||||
"credential_status": "supported",
|
||||
},
|
||||
"gdacs_disasters": {
|
||||
"id": 45,
|
||||
"name": "GDACS Global Disaster Alerts",
|
||||
"display_name": "GDACS 联合国灾害预警 (橙/红)",
|
||||
"module": "L4",
|
||||
"priority": "P1",
|
||||
"frequency_minutes": 15,
|
||||
"is_free": True,
|
||||
"requires_credentials": False,
|
||||
},
|
||||
"nasa_eonet_events": {
|
||||
"id": 46,
|
||||
"name": "NASA EONET Natural Events",
|
||||
"display_name": "NASA EONET 全球自然异常事件",
|
||||
"module": "L4",
|
||||
"priority": "P2",
|
||||
"frequency_minutes": 30,
|
||||
"is_free": True,
|
||||
"requires_credentials": False,
|
||||
},
|
||||
"nga_navigation_warnings": {
|
||||
"id": 47,
|
||||
"name": "NGA MSI Maritime Navigation Warnings",
|
||||
"display_name": "NGA 航海警告与海缆安全通告",
|
||||
"module": "L4",
|
||||
"priority": "P1",
|
||||
"frequency_minutes": 360,
|
||||
"is_free": True,
|
||||
"requires_credentials": False,
|
||||
},
|
||||
}
|
||||
|
||||
ID_TO_COLLECTOR = {info["id"]: name for name, info in DEFAULT_DATASOURCES.items()}
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
[
|
||||
{
|
||||
"id": "malacca_strait",
|
||||
"name": "马六甲海峡",
|
||||
"name_en": "Strait of Malacca",
|
||||
"category": "energy_container_chokepoint",
|
||||
"center": [2.2, 101.8],
|
||||
"polygon": [[98.0, 5.8], [100.3, 5.5], [103.9, 1.35], [104.6, 1.15], [104.2, 0.7], [100.8, 2.2], [97.4, 5.0], [98.0, 5.8]],
|
||||
"source_citation": "IHO S-23 Limits of Oceans and Seas & UNCTAD Review of Maritime Transport"
|
||||
},
|
||||
{
|
||||
"id": "strait_of_hormuz",
|
||||
"name": "霍尔木兹海峡",
|
||||
"name_en": "Strait of Hormuz",
|
||||
"category": "energy_chokepoint",
|
||||
"center": [26.55, 56.35],
|
||||
"polygon": [[55.6, 26.8], [56.5, 27.15], [57.3, 26.4], [56.8, 25.7], [55.9, 25.9], [55.6, 26.8]],
|
||||
"source_citation": "EIA World Oil Transit Chokepoints & UKHO Admiralty Chart boundaries"
|
||||
},
|
||||
{
|
||||
"id": "bab_el_mandeb",
|
||||
"name": "曼德海峡",
|
||||
"name_en": "Bab el-Mandeb Strait",
|
||||
"category": "cable_energy_chokepoint",
|
||||
"center": [12.65, 43.35],
|
||||
"polygon": [[42.8, 13.1], [43.55, 13.1], [43.7, 12.35], [43.0, 12.25], [42.8, 13.1]],
|
||||
"source_citation": "IHO S-23 Limits of Oceans and Seas & NGA Pub. 172 Sailing Directions"
|
||||
},
|
||||
{
|
||||
"id": "suez_canal",
|
||||
"name": "苏伊士运河通道",
|
||||
"name_en": "Suez Canal Corridor",
|
||||
"category": "cable_container_chokepoint",
|
||||
"center": [30.55, 32.35],
|
||||
"polygon": [[32.1, 31.35], [32.65, 31.35], [32.7, 29.85], [32.15, 29.85], [32.1, 31.35]],
|
||||
"source_citation": "Suez Canal Authority Navigation Rules & TeleGeography Submarine Cable Atlas"
|
||||
},
|
||||
{
|
||||
"id": "panama_canal",
|
||||
"name": "巴拿马运河",
|
||||
"name_en": "Panama Canal",
|
||||
"category": "container_chokepoint",
|
||||
"center": [9.1, -79.72],
|
||||
"polygon": [[-80.1, 9.5], [-79.4, 9.5], [-79.35, 8.75], [-79.95, 8.75], [-80.1, 9.5]],
|
||||
"source_citation": "Autoridad del Canal de Panama Vessel Requirements & NGA Pub. 148"
|
||||
},
|
||||
{
|
||||
"id": "strait_of_gibraltar",
|
||||
"name": "直布罗陀海峡",
|
||||
"name_en": "Strait of Gibraltar",
|
||||
"category": "cable_maritime_chokepoint",
|
||||
"center": [35.96, -5.58],
|
||||
"polygon": [[-6.1, 36.2], [-5.2, 36.2], [-5.2, 35.75], [-6.1, 35.75], [-6.1, 36.2]],
|
||||
"source_citation": "IHO S-23 Mediterranean Western Limit & UKHO Traffic Separation Scheme"
|
||||
},
|
||||
{
|
||||
"id": "bosphorus_strait",
|
||||
"name": "博斯普鲁斯海峡",
|
||||
"name_en": "Bosphorus Strait",
|
||||
"category": "energy_grain_chokepoint",
|
||||
"center": [41.12, 29.08],
|
||||
"polygon": [[28.92, 41.28], [29.24, 41.28], [29.18, 40.96], [28.90, 40.96], [28.92, 41.28]],
|
||||
"source_citation": "Montreux Convention Transit Zone & Turkish Straits VTS"
|
||||
},
|
||||
{
|
||||
"id": "taiwan_strait",
|
||||
"name": "台湾海峡",
|
||||
"name_en": "Taiwan Strait",
|
||||
"category": "cable_container_chokepoint",
|
||||
"center": [24.3, 119.5],
|
||||
"polygon": [[118.2, 25.4], [121.1, 25.4], [120.4, 22.8], [117.7, 23.2], [118.2, 25.4]],
|
||||
"source_citation": "NGA World Port Index & TeleGeography Asia-Pacific Cable Corridor"
|
||||
},
|
||||
{
|
||||
"id": "korea_strait",
|
||||
"name": "朝鲜海峡(对马海峡)",
|
||||
"name_en": "Korea / Tsushima Strait",
|
||||
"category": "maritime_chokepoint",
|
||||
"center": [34.4, 129.3],
|
||||
"polygon": [[128.4, 35.2], [130.3, 35.0], [130.0, 33.4], [128.1, 33.7], [128.4, 35.2]],
|
||||
"source_citation": "IHO S-23 & Japan Coast Guard / KHOA Maritime TSS"
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,26 @@
|
||||
[
|
||||
{"id": "port_shanghai", "name": "上海港", "name_en": "Port of Shanghai", "country": "China", "lat": 31.36, "lon": 121.62, "port_type": "container", "throughput_rank": 1, "source_citation": "Lloyd's List Top 100 Ports 2024"},
|
||||
{"id": "port_singapore", "name": "新加坡港", "name_en": "Port of Singapore", "country": "Singapore", "lat": 1.26, "lon": 103.82, "port_type": "mixed", "throughput_rank": 2, "source_citation": "Lloyd's List Top 100 Ports 2024"},
|
||||
{"id": "port_ningbo", "name": "宁波舟山港", "name_en": "Port of Ningbo-Zhoushan", "country": "China", "lat": 29.93, "lon": 121.85, "port_type": "mixed", "throughput_rank": 3, "source_citation": "Lloyd's List Top 100 Ports 2024"},
|
||||
{"id": "port_shenzhen", "name": "深圳港", "name_en": "Port of Shenzhen", "country": "China", "lat": 22.50, "lon": 113.88, "port_type": "container", "throughput_rank": 4, "source_citation": "Lloyd's List Top 100 Ports 2024"},
|
||||
{"id": "port_qingdao", "name": "青岛港", "name_en": "Port of Qingdao", "country": "China", "lat": 36.08, "lon": 120.32, "port_type": "mixed", "throughput_rank": 5, "source_citation": "Lloyd's List Top 100 Ports 2024"},
|
||||
{"id": "port_busan", "name": "釜山港", "name_en": "Port of Busan", "country": "South Korea", "lat": 35.10, "lon": 129.04, "port_type": "container", "throughput_rank": 7, "source_citation": "Lloyd's List Top 100 Ports 2024"},
|
||||
{"id": "port_jebel_ali", "name": "杰贝阿里港", "name_en": "Port of Jebel Ali", "country": "UAE", "lat": 25.00, "lon": 55.06, "port_type": "container", "throughput_rank": 9, "source_citation": "Lloyd's List Top 100 Ports 2024"},
|
||||
{"id": "port_rotterdam", "name": "鹿特丹港", "name_en": "Port of Rotterdam", "country": "Netherlands", "lat": 51.90, "lon": 4.25, "port_type": "mixed", "throughput_rank": 10, "source_citation": "Lloyd's List Top 100 Ports 2024"},
|
||||
{"id": "port_antwerp", "name": "安特卫普-布鲁日港", "name_en": "Port of Antwerp-Bruges", "country": "Belgium", "lat": 51.27, "lon": 4.34, "port_type": "container", "throughput_rank": 11, "source_citation": "Lloyd's List Top 100 Ports 2024"},
|
||||
{"id": "port_kaohsiung", "name": "高雄港", "name_en": "Port of Kaohsiung", "country": "China", "lat": 22.61, "lon": 120.28, "port_type": "container", "throughput_rank": 18, "source_citation": "Lloyd's List Top 100 Ports 2024"},
|
||||
{"id": "port_los_angeles", "name": "洛杉矶-长滩港", "name_en": "Port of Los Angeles / Long Beach", "country": "United States", "lat": 33.74, "lon": -118.26, "port_type": "container", "throughput_rank": 8, "source_citation": "Lloyd's List Top 100 Ports 2024"},
|
||||
{"id": "port_port_said", "name": "塞得港", "name_en": "Port Said", "country": "Egypt", "lat": 31.26, "lon": 32.31, "port_type": "container", "throughput_rank": 29, "source_citation": "UNCTAD Port Statistics & NGA World Port Index"},
|
||||
{"id": "port_ras_tanura", "name": "拉斯塔努拉油港", "name_en": "Ras Tanura Oil Terminal", "country": "Saudi Arabia", "lat": 26.64, "lon": 50.16, "port_type": "oil_lng", "throughput_rank": 1, "source_citation": "EIA Saudi Crude Export Terminal Data"},
|
||||
{"id": "port_ras_laffan", "name": "拉斯拉凡 LNG 港", "name_en": "Ras Laffan LNG Terminal", "country": "Qatar", "lat": 25.93, "lon": 51.54, "port_type": "oil_lng", "throughput_rank": 2, "source_citation": "GIIGNL Annual LNG Terminal Report"},
|
||||
{"id": "port_sabine_pass", "name": "萨宾帕斯 LNG 港", "name_en": "Sabine Pass LNG Terminal", "country": "United States", "lat": 29.74, "lon": -93.87, "port_type": "oil_lng", "throughput_rank": 3, "source_citation": "US FERC & EIA Natural Gas Export Registry"},
|
||||
{"id": "port_hedland", "name": "黑德兰港", "name_en": "Port Hedland", "country": "Australia", "lat": -20.31, "lon": 118.58, "port_type": "bulk", "throughput_rank": 1, "source_citation": "Pilbara Ports Authority Annual Tonnage Report"},
|
||||
{"id": "port_norfolk", "name": "诺福克海军基地", "name_en": "Naval Station Norfolk", "country": "United States", "lat": 36.95, "lon": -76.33, "port_type": "naval", "throughput_rank": null, "source_citation": "NGA World Port Index WPI-25080"},
|
||||
{"id": "port_yokosuka", "name": "横须贺军港", "name_en": "Yokosuka Naval Base", "country": "Japan", "lat": 35.29, "lon": 139.66, "port_type": "naval", "throughput_rank": null, "source_citation": "NGA World Port Index WPI-61370"},
|
||||
{"id": "port_portsmouth", "name": "朴次茅斯军港", "name_en": "HMNB Portsmouth", "country": "United Kingdom", "lat": 50.80, "lon": -1.11, "port_type": "naval", "throughput_rank": null, "source_citation": "UKHO Admiralty Port Registry & NGA WPI"},
|
||||
{"id": "port_toulon", "name": "土伦军港", "name_en": "Toulon Naval Base", "country": "France", "lat": 43.11, "lon": 5.91, "port_type": "naval", "throughput_rank": null, "source_citation": "SHOM Mediterranean Naval Ports & NGA WPI"},
|
||||
{"id": "port_djibouti", "name": "吉布提港", "name_en": "Port of Djibouti", "country": "Djibouti", "lat": 11.60, "lon": 43.14, "port_type": "mixed", "throughput_rank": null, "source_citation": "NGA World Port Index WPI-47850"},
|
||||
{"id": "port_balboa", "name": "巴尔博亚港", "name_en": "Port of Balboa", "country": "Panama", "lat": 8.95, "lon": -79.57, "port_type": "container", "throughput_rank": 40, "source_citation": "Panama Maritime Authority & NGA WPI"},
|
||||
{"id": "port_algeciras", "name": "阿尔赫西拉斯港", "name_en": "Port of Algeciras", "country": "Spain", "lat": 36.13, "lon": -5.43, "port_type": "container", "throughput_rank": 33, "source_citation": "Lloyd's List Top 100 Ports 2024"},
|
||||
{"id": "port_novorossiysk", "name": "新罗西斯克港", "name_en": "Port of Novorossiysk", "country": "Russia", "lat": 44.72, "lon": 37.78, "port_type": "bulk", "throughput_rank": null, "source_citation": "NGA World Port Index Black Sea Terminals"}
|
||||
]
|
||||
@@ -0,0 +1,325 @@
|
||||
"""Create aircraft ADS-B, source health, and GPS jamming tables with PG outbox triggers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
VERSION = "0008"
|
||||
NAME = "add_aircraft_and_gps_jamming"
|
||||
|
||||
|
||||
async def upgrade(conn) -> None:
|
||||
"""Create aircraft & GPS jamming tables, indexes, and PG outbox triggers idempotently."""
|
||||
dialect = getattr(getattr(conn, "dialect", None), "name", "")
|
||||
if dialect == "postgresql":
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS aircraft_static (
|
||||
icao24 VARCHAR(12) PRIMARY KEY,
|
||||
registration VARCHAR(32),
|
||||
aircraft_type VARCHAR(16),
|
||||
type_description VARCHAR(128),
|
||||
operator VARCHAR(128),
|
||||
owner VARCHAR(128),
|
||||
origin_country VARCHAR(64),
|
||||
category VARCHAR(32),
|
||||
is_military BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
source VARCHAR(64) NOT NULL DEFAULT 'aircraft_registry',
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS aircraft_current_state (
|
||||
icao24 VARCHAR(12) PRIMARY KEY,
|
||||
callsign VARCHAR(16),
|
||||
lat DOUBLE PRECISION NOT NULL,
|
||||
lon DOUBLE PRECISION NOT NULL,
|
||||
baro_altitude_m DOUBLE PRECISION,
|
||||
geo_altitude_m DOUBLE PRECISION,
|
||||
ground_speed_ms DOUBLE PRECISION,
|
||||
track_deg DOUBLE PRECISION,
|
||||
vertical_rate_ms DOUBLE PRECISION,
|
||||
squawk VARCHAR(8),
|
||||
on_ground BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
category VARCHAR(32) NOT NULL DEFAULT 'other',
|
||||
is_military BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
is_emergency BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
emergency_code VARCHAR(8),
|
||||
source VARCHAR(64) NOT NULL,
|
||||
observed_at TIMESTAMPTZ NOT NULL,
|
||||
ingested_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE INDEX IF NOT EXISTS idx_aircraft_current_bbox
|
||||
ON aircraft_current_state (lon, lat)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE INDEX IF NOT EXISTS idx_aircraft_current_observed
|
||||
ON aircraft_current_state (observed_at DESC)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE INDEX IF NOT EXISTS idx_aircraft_current_category
|
||||
ON aircraft_current_state (category)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS aircraft_position (
|
||||
id SERIAL PRIMARY KEY,
|
||||
icao24 VARCHAR(12) NOT NULL,
|
||||
lat DOUBLE PRECISION NOT NULL,
|
||||
lon DOUBLE PRECISION NOT NULL,
|
||||
altitude_m DOUBLE PRECISION,
|
||||
ground_speed_ms DOUBLE PRECISION,
|
||||
track_deg DOUBLE PRECISION,
|
||||
observed_at TIMESTAMPTZ NOT NULL
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE INDEX IF NOT EXISTS idx_aircraft_pos_icao24_time
|
||||
ON aircraft_position (icao24, observed_at)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE INDEX IF NOT EXISTS idx_aircraft_pos_time
|
||||
ON aircraft_position (observed_at)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS adsb_source_health (
|
||||
source VARCHAR(64) PRIMARY KEY,
|
||||
connection_state VARCHAR(32) NOT NULL DEFAULT 'disconnected',
|
||||
active_count INTEGER NOT NULL DEFAULT 0,
|
||||
last_success_at TIMESTAMPTZ,
|
||||
last_error VARCHAR(500),
|
||||
cooldown_until TIMESTAMPTZ,
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS gps_jamming_cells (
|
||||
h3_index VARCHAR(32) NOT NULL,
|
||||
observed_date VARCHAR(10) NOT NULL,
|
||||
lat DOUBLE PRECISION NOT NULL,
|
||||
lon DOUBLE PRECISION NOT NULL,
|
||||
resolution INTEGER NOT NULL DEFAULT 4,
|
||||
level VARCHAR(16) NOT NULL,
|
||||
bad_ratio DOUBLE PRECISION NOT NULL DEFAULT 0.0,
|
||||
aircraft_count INTEGER NOT NULL DEFAULT 0,
|
||||
boundary JSONB NOT NULL DEFAULT '[]'::jsonb,
|
||||
source VARCHAR(64) NOT NULL DEFAULT 'gpsjam_interference',
|
||||
ingested_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
PRIMARY KEY (h3_index, observed_date)
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE INDEX IF NOT EXISTS idx_gps_jamming_date_level
|
||||
ON gps_jamming_cells (observed_date, level)
|
||||
"""
|
||||
)
|
||||
)
|
||||
|
||||
# Attach Earth outbox triggers when trigger helper already exists (migrator or session init).
|
||||
res = await conn.execute(
|
||||
text(
|
||||
"SELECT EXISTS (SELECT 1 FROM pg_proc WHERE proname = 'planet_notify_earth_table_changed_statement')"
|
||||
)
|
||||
)
|
||||
if bool(res.scalar()):
|
||||
for table_name in ("aircraft_current_state", "gps_jamming_cells"):
|
||||
for op, ref in (
|
||||
("insert", "REFERENCING NEW TABLE AS new_rows"),
|
||||
("update", "REFERENCING OLD TABLE AS old_rows NEW TABLE AS new_rows"),
|
||||
("delete", "REFERENCING OLD TABLE AS old_rows"),
|
||||
):
|
||||
await conn.execute(
|
||||
text(f"DROP TRIGGER IF EXISTS tr_planet_{table_name}_changed_{op} ON {table_name}")
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
f"""
|
||||
CREATE TRIGGER tr_planet_{table_name}_changed_{op}
|
||||
AFTER {op.upper()} ON {table_name}
|
||||
{ref}
|
||||
FOR EACH STATEMENT
|
||||
EXECUTE FUNCTION planet_notify_earth_table_changed_statement()
|
||||
"""
|
||||
)
|
||||
)
|
||||
return
|
||||
|
||||
# SQLite path
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS aircraft_static (
|
||||
icao24 VARCHAR(12) PRIMARY KEY,
|
||||
registration VARCHAR(32),
|
||||
aircraft_type VARCHAR(16),
|
||||
type_description VARCHAR(128),
|
||||
operator VARCHAR(128),
|
||||
owner VARCHAR(128),
|
||||
origin_country VARCHAR(64),
|
||||
category VARCHAR(32),
|
||||
is_military BOOLEAN NOT NULL DEFAULT 0,
|
||||
source VARCHAR(64) NOT NULL DEFAULT 'aircraft_registry',
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS aircraft_current_state (
|
||||
icao24 VARCHAR(12) PRIMARY KEY,
|
||||
callsign VARCHAR(16),
|
||||
lat FLOAT NOT NULL,
|
||||
lon FLOAT NOT NULL,
|
||||
baro_altitude_m FLOAT,
|
||||
geo_altitude_m FLOAT,
|
||||
ground_speed_ms FLOAT,
|
||||
track_deg FLOAT,
|
||||
vertical_rate_ms FLOAT,
|
||||
squawk VARCHAR(8),
|
||||
on_ground BOOLEAN NOT NULL DEFAULT 0,
|
||||
category VARCHAR(32) NOT NULL DEFAULT 'other',
|
||||
is_military BOOLEAN NOT NULL DEFAULT 0,
|
||||
is_emergency BOOLEAN NOT NULL DEFAULT 0,
|
||||
emergency_code VARCHAR(8),
|
||||
source VARCHAR(64) NOT NULL,
|
||||
observed_at TIMESTAMP NOT NULL,
|
||||
ingested_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE INDEX IF NOT EXISTS idx_aircraft_current_bbox
|
||||
ON aircraft_current_state (lon, lat)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE INDEX IF NOT EXISTS idx_aircraft_current_observed
|
||||
ON aircraft_current_state (observed_at)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS aircraft_position (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
icao24 VARCHAR(12) NOT NULL,
|
||||
lat FLOAT NOT NULL,
|
||||
lon FLOAT NOT NULL,
|
||||
altitude_m FLOAT,
|
||||
ground_speed_ms FLOAT,
|
||||
track_deg FLOAT,
|
||||
observed_at TIMESTAMP NOT NULL
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE INDEX IF NOT EXISTS idx_aircraft_pos_icao24_time
|
||||
ON aircraft_position (icao24, observed_at)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE INDEX IF NOT EXISTS idx_aircraft_pos_time
|
||||
ON aircraft_position (observed_at)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS adsb_source_health (
|
||||
source VARCHAR(64) PRIMARY KEY,
|
||||
connection_state VARCHAR(32) NOT NULL DEFAULT 'disconnected',
|
||||
active_count INTEGER NOT NULL DEFAULT 0,
|
||||
last_success_at TIMESTAMP,
|
||||
last_error VARCHAR(500),
|
||||
cooldown_until TIMESTAMP,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS gps_jamming_cells (
|
||||
h3_index VARCHAR(32) NOT NULL,
|
||||
observed_date VARCHAR(10) NOT NULL,
|
||||
lat FLOAT NOT NULL,
|
||||
lon FLOAT NOT NULL,
|
||||
resolution INTEGER NOT NULL DEFAULT 4,
|
||||
level VARCHAR(16) NOT NULL,
|
||||
bad_ratio FLOAT NOT NULL DEFAULT 0.0,
|
||||
aircraft_count INTEGER NOT NULL DEFAULT 0,
|
||||
boundary JSON NOT NULL DEFAULT '[]',
|
||||
source VARCHAR(64) NOT NULL DEFAULT 'gpsjam_interference',
|
||||
ingested_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (h3_index, observed_date)
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE INDEX IF NOT EXISTS idx_gps_jamming_date_level
|
||||
ON gps_jamming_cells (observed_date, level)
|
||||
"""
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,218 @@
|
||||
"""Create disaster_events, cable_advisories, and news credibility columns."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
VERSION = "0009"
|
||||
NAME = "add_disaster_and_maritime_intelligence"
|
||||
|
||||
|
||||
async def upgrade(conn) -> None:
|
||||
"""Create disaster_events, cable_advisories, and add news credibility/theater columns idempotently."""
|
||||
dialect = getattr(getattr(conn, "dialect", None), "name", "")
|
||||
if dialect == "postgresql":
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS disaster_events (
|
||||
id SERIAL PRIMARY KEY,
|
||||
source VARCHAR(64) NOT NULL,
|
||||
source_event_id VARCHAR(160) NOT NULL,
|
||||
event_type VARCHAR(32) NOT NULL,
|
||||
severity VARCHAR(24) NOT NULL DEFAULT 'medium',
|
||||
title VARCHAR(500) NOT NULL,
|
||||
lat DOUBLE PRECISION NOT NULL,
|
||||
lon DOUBLE PRECISION NOT NULL,
|
||||
magnitude DOUBLE PRECISION,
|
||||
started_at TIMESTAMPTZ,
|
||||
ended_at TIMESTAMPTZ,
|
||||
url TEXT,
|
||||
observed_at TIMESTAMPTZ NOT NULL,
|
||||
ingested_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
duplicate_of INTEGER,
|
||||
cluster_count INTEGER NOT NULL DEFAULT 1,
|
||||
max_brightness_k DOUBLE PRECISION,
|
||||
raw JSONB DEFAULT '{}'::jsonb,
|
||||
CONSTRAINT uq_disaster_source_event UNIQUE (source, source_event_id)
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"CREATE INDEX IF NOT EXISTS idx_disaster_source ON disaster_events (source)"
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"CREATE INDEX IF NOT EXISTS idx_disaster_type_observed ON disaster_events (event_type, observed_at)"
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"CREATE INDEX IF NOT EXISTS idx_disaster_geo ON disaster_events (lon, lat)"
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"CREATE INDEX IF NOT EXISTS idx_disaster_duplicate_of ON disaster_events (duplicate_of)"
|
||||
)
|
||||
)
|
||||
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS cable_advisories (
|
||||
id SERIAL PRIMARY KEY,
|
||||
source_warning_id VARCHAR(120) UNIQUE NOT NULL,
|
||||
text TEXT NOT NULL,
|
||||
lat DOUBLE PRECISION,
|
||||
lon DOUBLE PRECISION,
|
||||
polygon JSONB,
|
||||
issued_at TIMESTAMPTZ,
|
||||
cancelled_at TIMESTAMPTZ,
|
||||
matched_cable_ids JSONB NOT NULL DEFAULT '[]'::jsonb,
|
||||
match_method VARCHAR(64),
|
||||
ingested_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"CREATE INDEX IF NOT EXISTS idx_cable_advisories_issued ON cable_advisories (issued_at)"
|
||||
)
|
||||
)
|
||||
|
||||
# News credibility & theater columns (credibility_tier defaults NULL = unrated)
|
||||
await conn.execute(
|
||||
text(
|
||||
"ALTER TABLE earth_news_items ADD COLUMN IF NOT EXISTS credibility_tier INTEGER"
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"ALTER TABLE earth_news_items ADD COLUMN IF NOT EXISTS state_affiliated BOOLEAN NOT NULL DEFAULT FALSE"
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"ALTER TABLE earth_news_items ADD COLUMN IF NOT EXISTS theater_tags JSONB NOT NULL DEFAULT '[]'::jsonb"
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"CREATE INDEX IF NOT EXISTS idx_earth_news_credibility_tier ON earth_news_items (credibility_tier)"
|
||||
)
|
||||
)
|
||||
|
||||
# Register PG outbox notification triggers when helper function is present
|
||||
fn_exists = await conn.execute(
|
||||
text(
|
||||
"SELECT 1 FROM pg_proc WHERE proname = 'planet_notify_earth_table_changed_statement'"
|
||||
)
|
||||
)
|
||||
if fn_exists.scalar() is not None:
|
||||
for table_name in ("disaster_events", "cable_advisories"):
|
||||
for op, ref in (
|
||||
("insert", "REFERENCING NEW TABLE AS new_rows"),
|
||||
("update", "REFERENCING OLD TABLE AS old_rows NEW TABLE AS new_rows"),
|
||||
("delete", "REFERENCING OLD TABLE AS old_rows"),
|
||||
):
|
||||
await conn.execute(
|
||||
text(
|
||||
f"DROP TRIGGER IF EXISTS tr_planet_{table_name}_changed_{op} ON {table_name}"
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
f"""
|
||||
CREATE TRIGGER tr_planet_{table_name}_changed_{op}
|
||||
AFTER {op.upper()} ON {table_name}
|
||||
{ref}
|
||||
FOR EACH STATEMENT
|
||||
EXECUTE FUNCTION planet_notify_earth_table_changed_statement()
|
||||
"""
|
||||
)
|
||||
)
|
||||
return
|
||||
|
||||
# SQLite path
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS disaster_events (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
source VARCHAR(64) NOT NULL,
|
||||
source_event_id VARCHAR(160) NOT NULL,
|
||||
event_type VARCHAR(32) NOT NULL,
|
||||
severity VARCHAR(24) NOT NULL DEFAULT 'medium',
|
||||
title VARCHAR(500) NOT NULL,
|
||||
lat FLOAT NOT NULL,
|
||||
lon FLOAT NOT NULL,
|
||||
magnitude FLOAT,
|
||||
started_at TIMESTAMP,
|
||||
ended_at TIMESTAMP,
|
||||
url TEXT,
|
||||
observed_at TIMESTAMP NOT NULL,
|
||||
ingested_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
duplicate_of INTEGER,
|
||||
cluster_count INTEGER NOT NULL DEFAULT 1,
|
||||
max_brightness_k FLOAT,
|
||||
raw JSON DEFAULT '{}',
|
||||
UNIQUE (source, source_event_id)
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"CREATE INDEX IF NOT EXISTS idx_disaster_type_observed ON disaster_events (event_type, observed_at)"
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text("CREATE INDEX IF NOT EXISTS idx_disaster_geo ON disaster_events (lon, lat)")
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS cable_advisories (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
source_warning_id VARCHAR(120) UNIQUE NOT NULL,
|
||||
text TEXT NOT NULL,
|
||||
lat FLOAT,
|
||||
lon FLOAT,
|
||||
polygon JSON,
|
||||
issued_at TIMESTAMP,
|
||||
cancelled_at TIMESTAMP,
|
||||
matched_cable_ids JSON NOT NULL DEFAULT '[]',
|
||||
match_method VARCHAR(64),
|
||||
ingested_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
# Add earth_news_items columns if the table exists in this SQLite db
|
||||
tbl_check = await conn.execute(
|
||||
text("SELECT name FROM sqlite_master WHERE type='table' AND name='earth_news_items'")
|
||||
)
|
||||
if tbl_check.scalar() is not None:
|
||||
cols_res = await conn.execute(text("PRAGMA table_info(earth_news_items)"))
|
||||
existing_cols = {row[1] for row in cols_res.fetchall()}
|
||||
if "credibility_tier" not in existing_cols:
|
||||
await conn.execute(
|
||||
text("ALTER TABLE earth_news_items ADD COLUMN credibility_tier INTEGER")
|
||||
)
|
||||
if "state_affiliated" not in existing_cols:
|
||||
await conn.execute(
|
||||
text(
|
||||
"ALTER TABLE earth_news_items ADD COLUMN state_affiliated BOOLEAN NOT NULL DEFAULT 0"
|
||||
)
|
||||
)
|
||||
if "theater_tags" not in existing_cols:
|
||||
await conn.execute(
|
||||
text(
|
||||
"ALTER TABLE earth_news_items ADD COLUMN theater_tags JSON NOT NULL DEFAULT '[]'"
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,117 @@
|
||||
"""Create ontology_entity_aliases and analyst_links tables."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
VERSION = "0010"
|
||||
NAME = "add_ontology_curation"
|
||||
|
||||
|
||||
async def upgrade(conn) -> None:
|
||||
"""Create non-derivable ontology curation tables idempotently for PostgreSQL and SQLite."""
|
||||
dialect = getattr(getattr(conn, "dialect", None), "name", "")
|
||||
if dialect == "postgresql":
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS ontology_entity_aliases (
|
||||
id SERIAL PRIMARY KEY,
|
||||
alias VARCHAR(200) NOT NULL,
|
||||
object_id VARCHAR(160) NOT NULL,
|
||||
source VARCHAR(80) NOT NULL DEFAULT 'analyst',
|
||||
created_by VARCHAR(120) NOT NULL DEFAULT 'system',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
CONSTRAINT uq_ontology_alias_object UNIQUE (alias, object_id)
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"CREATE INDEX IF NOT EXISTS idx_ontology_alias_alias ON ontology_entity_aliases (alias)"
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"CREATE INDEX IF NOT EXISTS idx_ontology_alias_object_id ON ontology_entity_aliases (object_id)"
|
||||
)
|
||||
)
|
||||
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS analyst_links (
|
||||
id SERIAL PRIMARY KEY,
|
||||
from_object_id VARCHAR(160) NOT NULL,
|
||||
to_object_id VARCHAR(160) NOT NULL,
|
||||
relation_type VARCHAR(80) NOT NULL,
|
||||
note TEXT NOT NULL DEFAULT '',
|
||||
evidence_ids JSONB NOT NULL DEFAULT '[]'::jsonb,
|
||||
created_by VARCHAR(120) NOT NULL DEFAULT 'analyst',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
status VARCHAR(32) NOT NULL DEFAULT 'active'
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"CREATE INDEX IF NOT EXISTS idx_analyst_links_pair ON analyst_links (from_object_id, to_object_id, status)"
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"CREATE INDEX IF NOT EXISTS idx_analyst_links_to ON analyst_links (to_object_id)"
|
||||
)
|
||||
)
|
||||
return
|
||||
|
||||
# SQLite path
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS ontology_entity_aliases (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
alias VARCHAR(200) NOT NULL,
|
||||
object_id VARCHAR(160) NOT NULL,
|
||||
source VARCHAR(80) NOT NULL DEFAULT 'analyst',
|
||||
created_by VARCHAR(120) NOT NULL DEFAULT 'system',
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE (alias, object_id)
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"CREATE INDEX IF NOT EXISTS idx_ontology_alias_alias ON ontology_entity_aliases (alias)"
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"CREATE INDEX IF NOT EXISTS idx_ontology_alias_object_id ON ontology_entity_aliases (object_id)"
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS analyst_links (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
from_object_id VARCHAR(160) NOT NULL,
|
||||
to_object_id VARCHAR(160) NOT NULL,
|
||||
relation_type VARCHAR(80) NOT NULL,
|
||||
note TEXT NOT NULL DEFAULT '',
|
||||
evidence_ids JSON NOT NULL DEFAULT '[]',
|
||||
created_by VARCHAR(120) NOT NULL DEFAULT 'analyst',
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
status VARCHAR(32) NOT NULL DEFAULT 'active'
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"CREATE INDEX IF NOT EXISTS idx_analyst_links_pair ON analyst_links (from_object_id, to_object_id, status)"
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,155 @@
|
||||
"""Create geofences and situational_incidents tables (§3.8)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
VERSION = "0011"
|
||||
NAME = "add_geofences_and_incidents"
|
||||
|
||||
|
||||
async def upgrade(conn) -> None:
|
||||
"""Create geofences and situational_incidents idempotently for PostgreSQL and SQLite."""
|
||||
dialect = getattr(getattr(conn, "dialect", None), "name", "")
|
||||
if dialect == "postgresql":
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS geofences (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name VARCHAR(200) NOT NULL,
|
||||
kind VARCHAR(32) NOT NULL DEFAULT 'custom',
|
||||
geometry JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
rules JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
created_by VARCHAR(120) NOT NULL DEFAULT 'system',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text("CREATE INDEX IF NOT EXISTS idx_geofences_kind_enabled ON geofences (kind, enabled)")
|
||||
)
|
||||
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS situational_incidents (
|
||||
id SERIAL PRIMARY KEY,
|
||||
incident_type VARCHAR(80) NOT NULL,
|
||||
severity VARCHAR(24) NOT NULL DEFAULT 'medium',
|
||||
status VARCHAR(32) NOT NULL DEFAULT 'open',
|
||||
h3_index VARCHAR(32),
|
||||
window_start TIMESTAMPTZ,
|
||||
window_end TIMESTAMPTZ,
|
||||
object_ids JSONB NOT NULL DEFAULT '[]'::jsonb,
|
||||
signal_summary JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
evidence JSONB NOT NULL DEFAULT '[]'::jsonb,
|
||||
assessment_kind VARCHAR(48) NOT NULL DEFAULT 'rule_alert',
|
||||
title VARCHAR(320) NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_by VARCHAR(120),
|
||||
resolution_note TEXT
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"CREATE INDEX IF NOT EXISTS idx_situational_incidents_kind_status ON situational_incidents (assessment_kind, status, created_at)"
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"CREATE INDEX IF NOT EXISTS idx_situational_incidents_h3 ON situational_incidents (h3_index)"
|
||||
)
|
||||
)
|
||||
|
||||
fn_exists = await conn.execute(
|
||||
text(
|
||||
"SELECT 1 FROM pg_proc WHERE proname = 'planet_notify_earth_table_changed_statement'"
|
||||
)
|
||||
)
|
||||
if fn_exists.scalar() is not None:
|
||||
for table_name in ("geofences", "situational_incidents"):
|
||||
for op, ref in (
|
||||
("insert", "REFERENCING NEW TABLE AS new_rows"),
|
||||
("update", "REFERENCING OLD TABLE AS old_rows NEW TABLE AS new_rows"),
|
||||
("delete", "REFERENCING OLD TABLE AS old_rows"),
|
||||
):
|
||||
await conn.execute(
|
||||
text(
|
||||
f"DROP TRIGGER IF EXISTS tr_planet_{table_name}_changed_{op} ON {table_name}"
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
f"""
|
||||
CREATE TRIGGER tr_planet_{table_name}_changed_{op}
|
||||
AFTER {op.upper()} ON {table_name}
|
||||
{ref}
|
||||
FOR EACH STATEMENT
|
||||
EXECUTE FUNCTION planet_notify_earth_table_changed_statement()
|
||||
"""
|
||||
)
|
||||
)
|
||||
return
|
||||
|
||||
# SQLite path
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS geofences (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name VARCHAR(200) NOT NULL,
|
||||
kind VARCHAR(32) NOT NULL DEFAULT 'custom',
|
||||
geometry JSON NOT NULL DEFAULT '{}',
|
||||
rules JSON NOT NULL DEFAULT '{}',
|
||||
enabled BOOLEAN NOT NULL DEFAULT 1,
|
||||
created_by VARCHAR(120) NOT NULL DEFAULT 'system',
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text("CREATE INDEX IF NOT EXISTS idx_geofences_kind_enabled ON geofences (kind, enabled)")
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS situational_incidents (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
incident_type VARCHAR(80) NOT NULL,
|
||||
severity VARCHAR(24) NOT NULL DEFAULT 'medium',
|
||||
status VARCHAR(32) NOT NULL DEFAULT 'open',
|
||||
h3_index VARCHAR(32),
|
||||
window_start TIMESTAMP,
|
||||
window_end TIMESTAMP,
|
||||
object_ids JSON NOT NULL DEFAULT '[]',
|
||||
signal_summary JSON NOT NULL DEFAULT '{}',
|
||||
evidence JSON NOT NULL DEFAULT '[]',
|
||||
assessment_kind VARCHAR(48) NOT NULL DEFAULT 'rule_alert',
|
||||
title VARCHAR(320) NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_by VARCHAR(120),
|
||||
resolution_note TEXT
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"CREATE INDEX IF NOT EXISTS idx_situational_incidents_kind_status ON situational_incidents (assessment_kind, status, created_at)"
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"CREATE INDEX IF NOT EXISTS idx_situational_incidents_h3 ON situational_incidents (h3_index)"
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,117 @@
|
||||
"""Create investigation_cases, case_items, and case_versions tables (§4.3)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
VERSION = "0012"
|
||||
NAME = "add_investigation_cases"
|
||||
|
||||
|
||||
async def upgrade(conn) -> None:
|
||||
"""Create investigation case tables idempotently for PostgreSQL and SQLite."""
|
||||
dialect = getattr(getattr(conn, "dialect", None), "name", "")
|
||||
if dialect == "postgresql":
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS investigation_cases (
|
||||
id SERIAL PRIMARY KEY,
|
||||
title VARCHAR(240) NOT NULL,
|
||||
status VARCHAR(32) NOT NULL DEFAULT 'draft',
|
||||
owner_id INTEGER NOT NULL,
|
||||
owner_name VARCHAR(120) NOT NULL DEFAULT '',
|
||||
summary TEXT NOT NULL DEFAULT '',
|
||||
is_shared BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text("CREATE INDEX IF NOT EXISTS idx_cases_status ON investigation_cases (status, is_shared)")
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS case_items (
|
||||
id SERIAL PRIMARY KEY,
|
||||
case_id INTEGER NOT NULL REFERENCES investigation_cases(id) ON DELETE CASCADE,
|
||||
item_type VARCHAR(48) NOT NULL,
|
||||
ref_id VARCHAR(200) NOT NULL,
|
||||
payload JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
added_by VARCHAR(120) NOT NULL DEFAULT 'analyst',
|
||||
added_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(text("CREATE INDEX IF NOT EXISTS idx_case_items_case_id ON case_items (case_id)"))
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS case_versions (
|
||||
id SERIAL PRIMARY KEY,
|
||||
case_id INTEGER NOT NULL REFERENCES investigation_cases(id) ON DELETE CASCADE,
|
||||
version INTEGER NOT NULL,
|
||||
snapshot JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
content_sha256 VARCHAR(64) NOT NULL,
|
||||
frozen_by VARCHAR(120) NOT NULL,
|
||||
frozen_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
CONSTRAINT idx_case_versions_case_ver UNIQUE (case_id, version)
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
return
|
||||
|
||||
# SQLite path
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS investigation_cases (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
title VARCHAR(240) NOT NULL,
|
||||
status VARCHAR(32) NOT NULL DEFAULT 'draft',
|
||||
owner_id INTEGER NOT NULL,
|
||||
owner_name VARCHAR(120) NOT NULL DEFAULT '',
|
||||
summary TEXT NOT NULL DEFAULT '',
|
||||
is_shared BOOLEAN NOT NULL DEFAULT 1,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS case_items (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
case_id INTEGER NOT NULL REFERENCES investigation_cases(id) ON DELETE CASCADE,
|
||||
item_type VARCHAR(48) NOT NULL,
|
||||
ref_id VARCHAR(200) NOT NULL,
|
||||
payload JSON NOT NULL DEFAULT '{}',
|
||||
added_by VARCHAR(120) NOT NULL DEFAULT 'analyst',
|
||||
added_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS case_versions (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
case_id INTEGER NOT NULL REFERENCES investigation_cases(id) ON DELETE CASCADE,
|
||||
version INTEGER NOT NULL,
|
||||
snapshot JSON NOT NULL DEFAULT '{}',
|
||||
content_sha256 VARCHAR(64) NOT NULL,
|
||||
frozen_by VARCHAR(120) NOT NULL,
|
||||
frozen_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE (case_id, version)
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Create action_requests table (§4.5)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
VERSION = "0013"
|
||||
NAME = "add_action_requests"
|
||||
|
||||
|
||||
async def upgrade(conn) -> None:
|
||||
"""Create action_requests table idempotently for PostgreSQL and SQLite."""
|
||||
dialect = getattr(getattr(conn, "dialect", None), "name", "")
|
||||
if dialect == "postgresql":
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS action_requests (
|
||||
id SERIAL PRIMARY KEY,
|
||||
action_type VARCHAR(80) NOT NULL,
|
||||
target_object_ids JSONB NOT NULL DEFAULT '[]'::jsonb,
|
||||
params JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
risk_level VARCHAR(24) NOT NULL DEFAULT 'low',
|
||||
status VARCHAR(32) NOT NULL DEFAULT 'pending',
|
||||
requested_by VARCHAR(120) NOT NULL,
|
||||
requested_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
approved_by VARCHAR(120),
|
||||
approved_at TIMESTAMPTZ,
|
||||
decision_reason TEXT,
|
||||
execution_result JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
source_workflow_run_id VARCHAR(120)
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
await conn.execute(
|
||||
text("CREATE INDEX IF NOT EXISTS idx_action_requests_status ON action_requests (status, risk_level)")
|
||||
)
|
||||
return
|
||||
|
||||
# SQLite path
|
||||
await conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS action_requests (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
action_type VARCHAR(80) NOT NULL,
|
||||
target_object_ids JSON NOT NULL DEFAULT '[]',
|
||||
params JSON NOT NULL DEFAULT '{}',
|
||||
risk_level VARCHAR(24) NOT NULL DEFAULT 'low',
|
||||
status VARCHAR(32) NOT NULL DEFAULT 'pending',
|
||||
requested_by VARCHAR(120) NOT NULL,
|
||||
requested_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
approved_by VARCHAR(120),
|
||||
approved_at TIMESTAMP,
|
||||
decision_reason TEXT,
|
||||
execution_result JSON NOT NULL DEFAULT '{}',
|
||||
source_workflow_run_id VARCHAR(120)
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
@@ -50,7 +50,9 @@ BEGIN
|
||||
NULLIF(row_data->>'source_id', ''),
|
||||
NULLIF(row_data->>'incident_key', ''),
|
||||
NULLIF(row_data->>'id', ''),
|
||||
NULLIF(row_data->>'mmsi', '')
|
||||
NULLIF(row_data->>'mmsi', ''),
|
||||
NULLIF(row_data->>'icao24', ''),
|
||||
NULLIF(row_data->>'h3_index', '')
|
||||
)
|
||||
FROM (SELECT to_jsonb(t) AS row_data FROM new_rows AS t) rows_for_keys
|
||||
WHERE COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME) = change_source
|
||||
@@ -81,7 +83,9 @@ BEGIN
|
||||
NULLIF(row_data->>'source_id', ''),
|
||||
NULLIF(row_data->>'incident_key', ''),
|
||||
NULLIF(row_data->>'id', ''),
|
||||
NULLIF(row_data->>'mmsi', '')
|
||||
NULLIF(row_data->>'mmsi', ''),
|
||||
NULLIF(row_data->>'icao24', ''),
|
||||
NULLIF(row_data->>'h3_index', '')
|
||||
)
|
||||
FROM (SELECT to_jsonb(t) AS row_data FROM old_rows AS t) rows_for_keys
|
||||
WHERE COALESCE(NULLIF(row_data->>'source', ''), TG_TABLE_NAME) = change_source
|
||||
@@ -129,7 +133,9 @@ BEGIN
|
||||
NULLIF(row_data->>'source_id', ''),
|
||||
NULLIF(row_data->>'incident_key', ''),
|
||||
NULLIF(row_data->>'id', ''),
|
||||
NULLIF(row_data->>'mmsi', '')
|
||||
NULLIF(row_data->>'mmsi', ''),
|
||||
NULLIF(row_data->>'icao24', ''),
|
||||
NULLIF(row_data->>'h3_index', '')
|
||||
)
|
||||
FROM (
|
||||
SELECT to_jsonb(t) AS row_data FROM new_rows AS t
|
||||
@@ -825,6 +831,12 @@ async def _init_db_ddl_and_seed():
|
||||
"vessel_current_state",
|
||||
"ais_raw_observations",
|
||||
"ais_source_health",
|
||||
"aircraft_current_state",
|
||||
"gps_jamming_cells",
|
||||
"disaster_events",
|
||||
"cable_advisories",
|
||||
"geofences",
|
||||
"situational_incidents",
|
||||
"compute_center_locations",
|
||||
"earth_interactables",
|
||||
"earth_news_items",
|
||||
|
||||
+3
-1
@@ -90,7 +90,9 @@ async def lifespan(app: FastAPI):
|
||||
if settings.should_run_scheduler:
|
||||
if await acquire_scheduler_leader_lock():
|
||||
leader_lock_acquired = True
|
||||
await cleanup_stale_running_tasks()
|
||||
await cleanup_stale_running_tasks(
|
||||
include_all_running=(settings.normalized_role == "all")
|
||||
)
|
||||
start_scheduler()
|
||||
scheduler_started = True
|
||||
await sync_scheduler_with_datasources()
|
||||
|
||||
@@ -17,9 +17,22 @@ from app.models.playground_session import PlaygroundSession
|
||||
from app.models.playground_message import PlaygroundMessage
|
||||
from app.models.system_log import AuditLog, ObservabilityEvent, ObservabilityEventGroup, SystemLog
|
||||
from app.models.vessel import AISConflictRecord, AISRawObservation, AISSourceHealth, VesselPosition, VesselStatic
|
||||
from app.models.aircraft import (
|
||||
ADSBSourceHealth,
|
||||
AircraftCurrentState,
|
||||
AircraftPosition,
|
||||
AircraftStatic,
|
||||
)
|
||||
from app.models.gps_jamming import GPSJammingCell
|
||||
from app.models.disaster import DisasterEvent
|
||||
from app.models.maritime_advisory import CableAdvisory
|
||||
from app.models.datasource_mapping import DataSourceMappingTemplate
|
||||
from app.models.earth_news import EarthNewsItem
|
||||
from app.models.earth_interactable import EarthInteractable
|
||||
from app.models.ontology import AnalystLink, OntologyEntityAlias
|
||||
from app.models.geofence import Geofence, SituationalIncident
|
||||
from app.models.investigation_case import CaseItem, CaseVersion, InvestigationCase
|
||||
from app.models.action_request import ActionRequest
|
||||
from app.models.situational_assessment import (
|
||||
ComputeEvidenceCandidate,
|
||||
EvidenceRecord,
|
||||
@@ -61,9 +74,24 @@ __all__ = [
|
||||
"AISRawObservation",
|
||||
"AISConflictRecord",
|
||||
"AISSourceHealth",
|
||||
"AircraftStatic",
|
||||
"AircraftCurrentState",
|
||||
"AircraftPosition",
|
||||
"ADSBSourceHealth",
|
||||
"GPSJammingCell",
|
||||
"DisasterEvent",
|
||||
"CableAdvisory",
|
||||
"DataSourceMappingTemplate",
|
||||
"EarthNewsItem",
|
||||
"EarthInteractable",
|
||||
"OntologyEntityAlias",
|
||||
"AnalystLink",
|
||||
"Geofence",
|
||||
"SituationalIncident",
|
||||
"InvestigationCase",
|
||||
"CaseItem",
|
||||
"CaseVersion",
|
||||
"ActionRequest",
|
||||
"EvidenceRecord",
|
||||
"InvestigationSession",
|
||||
"SituationalAssessment",
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
"""Action Request model for human-in-the-loop operations & webhooks (§4.5)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import Column, DateTime, Integer, JSON, String, Text
|
||||
from sqlalchemy.sql import func
|
||||
|
||||
from app.core.time import to_iso8601_utc
|
||||
from app.db.session import Base
|
||||
|
||||
|
||||
class ActionRequest(Base):
|
||||
__tablename__ = "action_requests"
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True)
|
||||
action_type = Column(String(80), nullable=False, index=True)
|
||||
target_object_ids = Column(JSON, nullable=False, default=list)
|
||||
params = Column(JSON, nullable=False, default=dict)
|
||||
risk_level = Column(String(24), nullable=False, default="low", index=True)
|
||||
status = Column(String(32), nullable=False, default="pending", index=True)
|
||||
requested_by = Column(String(120), nullable=False, index=True)
|
||||
requested_at = Column(DateTime(timezone=True), nullable=False, server_default=func.now())
|
||||
approved_by = Column(String(120), nullable=True, index=True)
|
||||
approved_at = Column(DateTime(timezone=True), nullable=True)
|
||||
decision_reason = Column(Text, nullable=True)
|
||||
execution_result = Column(JSON, nullable=False, default=dict)
|
||||
source_workflow_run_id = Column(String(120), nullable=True, index=True)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"id": self.id,
|
||||
"action_type": self.action_type,
|
||||
"target_object_ids": list(self.target_object_ids or []),
|
||||
"params": dict(self.params or {}),
|
||||
"risk_level": self.risk_level,
|
||||
"status": self.status,
|
||||
"requested_by": self.requested_by,
|
||||
"requested_at": to_iso8601_utc(self.requested_at),
|
||||
"approved_by": self.approved_by,
|
||||
"approved_at": to_iso8601_utc(self.approved_at),
|
||||
"decision_reason": self.decision_reason,
|
||||
"execution_result": dict(self.execution_result or {}),
|
||||
"source_workflow_run_id": self.source_workflow_run_id,
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
"""Aircraft ADS-B and registry database models."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import Boolean, Column, DateTime, Float, Index, Integer, String
|
||||
from sqlalchemy.sql import func
|
||||
|
||||
from app.core.enums import ConnectionState
|
||||
from app.core.time import to_iso8601_utc
|
||||
from app.db.session import Base
|
||||
|
||||
|
||||
class AircraftStatic(Base):
|
||||
"""Reference aircraft metadata populated from open ICAO24 registries."""
|
||||
|
||||
__tablename__ = "aircraft_static"
|
||||
|
||||
icao24 = Column(String(12), primary_key=True)
|
||||
registration = Column(String(32), nullable=True, index=True)
|
||||
aircraft_type = Column(String(16), nullable=True, index=True)
|
||||
type_description = Column(String(128), nullable=True)
|
||||
operator = Column(String(128), nullable=True)
|
||||
owner = Column(String(128), nullable=True)
|
||||
origin_country = Column(String(64), nullable=True, index=True)
|
||||
category = Column(String(32), nullable=True, index=True)
|
||||
is_military = Column(Boolean, nullable=False, default=False, index=True)
|
||||
source = Column(String(64), nullable=False, default="aircraft_registry")
|
||||
updated_at = Column(DateTime(timezone=True), nullable=False, server_default=func.now())
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"icao24": self.icao24,
|
||||
"registration": self.registration,
|
||||
"aircraft_type": self.aircraft_type,
|
||||
"type_description": self.type_description,
|
||||
"operator": self.operator,
|
||||
"owner": self.owner,
|
||||
"origin_country": self.origin_country,
|
||||
"category": self.category,
|
||||
"is_military": bool(self.is_military),
|
||||
"source": self.source,
|
||||
"updated_at": to_iso8601_utc(self.updated_at),
|
||||
}
|
||||
|
||||
|
||||
class AircraftCurrentState(Base):
|
||||
"""Latest merged state per active aircraft for low-latency snapshot serving."""
|
||||
|
||||
__tablename__ = "aircraft_current_state"
|
||||
|
||||
icao24 = Column(String(12), primary_key=True)
|
||||
callsign = Column(String(16), nullable=True, index=True)
|
||||
lat = Column(Float, nullable=False)
|
||||
lon = Column(Float, nullable=False)
|
||||
baro_altitude_m = Column(Float, nullable=True)
|
||||
geo_altitude_m = Column(Float, nullable=True)
|
||||
ground_speed_ms = Column(Float, nullable=True)
|
||||
track_deg = Column(Float, nullable=True)
|
||||
vertical_rate_ms = Column(Float, nullable=True)
|
||||
squawk = Column(String(8), nullable=True, index=True)
|
||||
on_ground = Column(Boolean, nullable=False, default=False)
|
||||
category = Column(String(32), nullable=False, default="other", index=True)
|
||||
is_military = Column(Boolean, nullable=False, default=False, index=True)
|
||||
is_emergency = Column(Boolean, nullable=False, default=False, index=True)
|
||||
emergency_code = Column(String(8), nullable=True)
|
||||
source = Column(String(64), nullable=False, index=True)
|
||||
observed_at = Column(DateTime(timezone=True), nullable=False)
|
||||
ingested_at = Column(DateTime(timezone=True), nullable=False, server_default=func.now())
|
||||
|
||||
__table_args__ = (
|
||||
Index("idx_aircraft_current_bbox", "lon", "lat"),
|
||||
Index("idx_aircraft_current_observed", "observed_at"),
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"icao24": self.icao24,
|
||||
"callsign": self.callsign,
|
||||
"lat": self.lat,
|
||||
"lon": self.lon,
|
||||
"baro_altitude_m": self.baro_altitude_m,
|
||||
"geo_altitude_m": self.geo_altitude_m,
|
||||
"ground_speed_ms": self.ground_speed_ms,
|
||||
"track_deg": self.track_deg,
|
||||
"vertical_rate_ms": self.vertical_rate_ms,
|
||||
"squawk": self.squawk,
|
||||
"on_ground": bool(self.on_ground),
|
||||
"category": self.category,
|
||||
"is_military": bool(self.is_military),
|
||||
"is_emergency": bool(self.is_emergency),
|
||||
"emergency_code": self.emergency_code,
|
||||
"source": self.source,
|
||||
"observed_at": to_iso8601_utc(self.observed_at),
|
||||
"ingested_at": to_iso8601_utc(self.ingested_at),
|
||||
}
|
||||
|
||||
|
||||
class AircraftPosition(Base):
|
||||
"""Downsampled aircraft track points retained 24h for trails and 4D replay."""
|
||||
|
||||
__tablename__ = "aircraft_position"
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True)
|
||||
icao24 = Column(String(12), nullable=False)
|
||||
lat = Column(Float, nullable=False)
|
||||
lon = Column(Float, nullable=False)
|
||||
altitude_m = Column(Float, nullable=True)
|
||||
ground_speed_ms = Column(Float, nullable=True)
|
||||
track_deg = Column(Float, nullable=True)
|
||||
observed_at = Column(DateTime(timezone=True), nullable=False)
|
||||
|
||||
__table_args__ = (
|
||||
Index("idx_aircraft_pos_icao24_time", "icao24", "observed_at"),
|
||||
Index("idx_aircraft_pos_time", "observed_at"),
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"id": self.id,
|
||||
"icao24": self.icao24,
|
||||
"lat": self.lat,
|
||||
"lon": self.lon,
|
||||
"altitude_m": self.altitude_m,
|
||||
"ground_speed_ms": self.ground_speed_ms,
|
||||
"track_deg": self.track_deg,
|
||||
"observed_at": to_iso8601_utc(self.observed_at),
|
||||
}
|
||||
|
||||
|
||||
class ADSBSourceHealth(Base):
|
||||
"""Runtime health & cooldown state per aircraft ADS-B source."""
|
||||
|
||||
__tablename__ = "adsb_source_health"
|
||||
|
||||
source = Column(String(64), primary_key=True)
|
||||
connection_state = Column(String(32), nullable=False, default=ConnectionState.DISCONNECTED.value, index=True)
|
||||
active_count = Column(Integer, nullable=False, default=0)
|
||||
last_success_at = Column(DateTime(timezone=True), nullable=True, index=True)
|
||||
last_error = Column(String(500), nullable=True)
|
||||
cooldown_until = Column(DateTime(timezone=True), nullable=True, index=True)
|
||||
updated_at = Column(DateTime(timezone=True), nullable=False, server_default=func.now(), index=True)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"source": self.source,
|
||||
"connection_state": self.connection_state,
|
||||
"active_count": int(self.active_count or 0),
|
||||
"last_success_at": to_iso8601_utc(self.last_success_at),
|
||||
"last_error": self.last_error,
|
||||
"cooldown_until": to_iso8601_utc(self.cooldown_until),
|
||||
"updated_at": to_iso8601_utc(self.updated_at),
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
"""Natural disaster and hazard telemetry model."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import Column, DateTime, Float, Index, Integer, JSON, String, Text, UniqueConstraint
|
||||
from sqlalchemy.sql import func
|
||||
|
||||
from app.core.time import to_iso8601_utc
|
||||
from app.db.session import Base
|
||||
|
||||
|
||||
class DisasterEvent(Base):
|
||||
__tablename__ = "disaster_events"
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True)
|
||||
source = Column(String(64), nullable=False, index=True)
|
||||
source_event_id = Column(String(160), nullable=False)
|
||||
event_type = Column(String(32), nullable=False, index=True)
|
||||
severity = Column(String(24), nullable=False, default="medium", index=True)
|
||||
title = Column(String(500), nullable=False)
|
||||
lat = Column(Float, nullable=False)
|
||||
lon = Column(Float, nullable=False)
|
||||
magnitude = Column(Float, nullable=True)
|
||||
started_at = Column(DateTime(timezone=True), nullable=True)
|
||||
ended_at = Column(DateTime(timezone=True), nullable=True)
|
||||
url = Column(Text, nullable=True)
|
||||
observed_at = Column(DateTime(timezone=True), nullable=False, index=True)
|
||||
ingested_at = Column(DateTime(timezone=True), nullable=False, server_default=func.now())
|
||||
duplicate_of = Column(Integer, nullable=True, index=True)
|
||||
cluster_count = Column(Integer, nullable=False, default=1)
|
||||
max_brightness_k = Column(Float, nullable=True)
|
||||
raw = Column(JSON, nullable=True, default=dict)
|
||||
|
||||
__table_args__ = (
|
||||
UniqueConstraint("source", "source_event_id", name="uq_disaster_source_event"),
|
||||
Index("idx_disaster_type_observed", "event_type", "observed_at"),
|
||||
Index("idx_disaster_geo", "lon", "lat"),
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"id": self.id,
|
||||
"source": self.source,
|
||||
"source_event_id": self.source_event_id,
|
||||
"event_type": self.event_type,
|
||||
"severity": self.severity,
|
||||
"title": self.title,
|
||||
"lat": self.lat,
|
||||
"lon": self.lon,
|
||||
"magnitude": self.magnitude,
|
||||
"started_at": to_iso8601_utc(self.started_at),
|
||||
"ended_at": to_iso8601_utc(self.ended_at),
|
||||
"url": self.url,
|
||||
"observed_at": to_iso8601_utc(self.observed_at),
|
||||
"ingested_at": to_iso8601_utc(self.ingested_at),
|
||||
"duplicate_of": self.duplicate_of,
|
||||
"cluster_count": int(self.cluster_count or 1),
|
||||
"max_brightness_k": self.max_brightness_k,
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
from sqlalchemy import Boolean, Column, DateTime, Float, Index, JSON, String, Text
|
||||
from sqlalchemy import Boolean, Column, DateTime, Float, Index, Integer, JSON, String, Text
|
||||
from sqlalchemy.sql import func
|
||||
|
||||
from app.db.session import Base
|
||||
@@ -33,6 +33,9 @@ class EarthNewsItem(Base):
|
||||
enrichment_error = Column(Text, nullable=True)
|
||||
enriched_at = Column(DateTime(timezone=True), nullable=True, index=True)
|
||||
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
|
||||
credibility_tier = Column(Integer, nullable=True, index=True)
|
||||
state_affiliated = Column(Boolean, nullable=False, default=False)
|
||||
theater_tags = Column(JSON, nullable=False, default=list)
|
||||
|
||||
__table_args__ = (
|
||||
Index("idx_earth_news_region_published", "region", "published_at"),
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
"""Geofences and fused situational incident models (§3.8 & §3.9)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import Boolean, Column, DateTime, Index, Integer, JSON, String, Text
|
||||
from sqlalchemy.sql import func
|
||||
|
||||
from app.core.time import to_iso8601_utc
|
||||
from app.db.session import Base
|
||||
|
||||
|
||||
class Geofence(Base):
|
||||
"""Preset (chokepoint / cable corridor) or user-drawn geographic polygon geofence."""
|
||||
|
||||
__tablename__ = "geofences"
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True)
|
||||
name = Column(String(200), nullable=False, index=True)
|
||||
kind = Column(String(32), nullable=False, default="custom", index=True)
|
||||
geometry = Column(JSON, nullable=False, default=dict)
|
||||
rules = Column(JSON, nullable=False, default=dict)
|
||||
enabled = Column(Boolean, nullable=False, default=True, index=True)
|
||||
created_by = Column(String(120), nullable=False, default="system")
|
||||
created_at = Column(DateTime(timezone=True), nullable=False, server_default=func.now())
|
||||
updated_at = Column(DateTime(timezone=True), nullable=False, server_default=func.now(), onupdate=func.now())
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"id": self.id,
|
||||
"name": self.name,
|
||||
"kind": self.kind,
|
||||
"geometry": self.geometry or {},
|
||||
"rules": self.rules or {},
|
||||
"enabled": bool(self.enabled),
|
||||
"created_by": self.created_by,
|
||||
"created_at": to_iso8601_utc(self.created_at),
|
||||
"updated_at": to_iso8601_utc(self.updated_at),
|
||||
}
|
||||
|
||||
|
||||
class SituationalIncident(Base):
|
||||
"""Rule alerts, candidate correlations (待核查关联), and dependency-impact incidents."""
|
||||
|
||||
__tablename__ = "situational_incidents"
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True)
|
||||
incident_type = Column(String(80), nullable=False, index=True)
|
||||
severity = Column(String(24), nullable=False, default="medium", index=True)
|
||||
status = Column(String(32), nullable=False, default="open", index=True)
|
||||
h3_index = Column(String(32), nullable=True, index=True)
|
||||
window_start = Column(DateTime(timezone=True), nullable=True)
|
||||
window_end = Column(DateTime(timezone=True), nullable=True)
|
||||
object_ids = Column(JSON, nullable=False, default=list)
|
||||
signal_summary = Column(JSON, nullable=False, default=dict)
|
||||
evidence = Column(JSON, nullable=False, default=list)
|
||||
assessment_kind = Column(String(48), nullable=False, default="rule_alert", index=True)
|
||||
title = Column(String(320), nullable=False, default="")
|
||||
created_at = Column(DateTime(timezone=True), nullable=False, server_default=func.now(), index=True)
|
||||
updated_at = Column(DateTime(timezone=True), nullable=False, server_default=func.now(), onupdate=func.now())
|
||||
updated_by = Column(String(120), nullable=True)
|
||||
resolution_note = Column(Text, nullable=True)
|
||||
|
||||
__table_args__ = (
|
||||
Index("idx_situational_incidents_kind_status", "assessment_kind", "status", "created_at"),
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"id": self.id,
|
||||
"incident_type": self.incident_type,
|
||||
"severity": self.severity,
|
||||
"status": self.status,
|
||||
"h3_index": self.h3_index,
|
||||
"window_start": to_iso8601_utc(self.window_start),
|
||||
"window_end": to_iso8601_utc(self.window_end),
|
||||
"object_ids": list(self.object_ids or []),
|
||||
"signal_summary": dict(self.signal_summary or {}),
|
||||
"evidence": list(self.evidence or []),
|
||||
"assessment_kind": self.assessment_kind,
|
||||
"title": self.title,
|
||||
"created_at": to_iso8601_utc(self.created_at),
|
||||
"updated_at": to_iso8601_utc(self.updated_at),
|
||||
"updated_by": self.updated_by,
|
||||
"resolution_note": self.resolution_note,
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
"""GPS/GNSS interference cell model derived from H3 daily summaries."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import Column, DateTime, Float, Index, Integer, JSON, String
|
||||
from sqlalchemy.sql import func
|
||||
|
||||
from app.core.time import to_iso8601_utc
|
||||
from app.db.session import Base
|
||||
|
||||
|
||||
class GPSJammingCell(Base):
|
||||
"""Daily H3 hexagon summary of GPS/GNSS interference."""
|
||||
|
||||
__tablename__ = "gps_jamming_cells"
|
||||
|
||||
h3_index = Column(String(32), primary_key=True)
|
||||
observed_date = Column(String(10), primary_key=True)
|
||||
lat = Column(Float, nullable=False)
|
||||
lon = Column(Float, nullable=False)
|
||||
resolution = Column(Integer, nullable=False, default=4)
|
||||
level = Column(String(16), nullable=False, index=True)
|
||||
bad_ratio = Column(Float, nullable=False, default=0.0)
|
||||
aircraft_count = Column(Integer, nullable=False, default=0)
|
||||
boundary = Column(JSON, nullable=False, default=list)
|
||||
source = Column(String(64), nullable=False, default="gpsjam_interference")
|
||||
ingested_at = Column(DateTime(timezone=True), nullable=False, server_default=func.now())
|
||||
|
||||
__table_args__ = (
|
||||
Index("idx_gps_jamming_date_level", "observed_date", "level"),
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"h3_index": self.h3_index,
|
||||
"observed_date": self.observed_date,
|
||||
"lat": self.lat,
|
||||
"lon": self.lon,
|
||||
"resolution": int(self.resolution or 4),
|
||||
"level": self.level,
|
||||
"bad_ratio": float(self.bad_ratio or 0.0),
|
||||
"aircraft_count": int(self.aircraft_count or 0),
|
||||
"boundary": self.boundary or [],
|
||||
"source": self.source,
|
||||
"ingested_at": to_iso8601_utc(self.ingested_at),
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
"""Investigation Case Board, items, and immutable SHA-256 frozen versions (§4.3)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import Boolean, Column, DateTime, ForeignKey, Index, Integer, JSON, String, Text
|
||||
from sqlalchemy.sql import func
|
||||
|
||||
from app.core.time import to_iso8601_utc
|
||||
from app.db.session import Base
|
||||
|
||||
|
||||
class InvestigationCase(Base):
|
||||
__tablename__ = "investigation_cases"
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True)
|
||||
title = Column(String(240), nullable=False, index=True)
|
||||
status = Column(String(32), nullable=False, default="draft", index=True)
|
||||
owner_id = Column(Integer, nullable=False, index=True)
|
||||
owner_name = Column(String(120), nullable=False, default="")
|
||||
summary = Column(Text, nullable=False, default="")
|
||||
is_shared = Column(Boolean, nullable=False, default=True, index=True)
|
||||
created_at = Column(DateTime(timezone=True), nullable=False, server_default=func.now())
|
||||
updated_at = Column(DateTime(timezone=True), nullable=False, server_default=func.now(), onupdate=func.now())
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"id": self.id,
|
||||
"title": self.title,
|
||||
"status": self.status,
|
||||
"owner_id": self.owner_id,
|
||||
"owner_name": self.owner_name,
|
||||
"summary": self.summary,
|
||||
"is_shared": bool(self.is_shared),
|
||||
"created_at": to_iso8601_utc(self.created_at),
|
||||
"updated_at": to_iso8601_utc(self.updated_at),
|
||||
}
|
||||
|
||||
|
||||
class CaseItem(Base):
|
||||
__tablename__ = "case_items"
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True)
|
||||
case_id = Column(Integer, ForeignKey("investigation_cases.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||
item_type = Column(String(48), nullable=False, index=True)
|
||||
ref_id = Column(String(200), nullable=False)
|
||||
payload = Column(JSON, nullable=False, default=dict)
|
||||
added_by = Column(String(120), nullable=False, default="analyst")
|
||||
added_at = Column(DateTime(timezone=True), nullable=False, server_default=func.now())
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"id": self.id,
|
||||
"case_id": self.case_id,
|
||||
"item_type": self.item_type,
|
||||
"ref_id": self.ref_id,
|
||||
"payload": dict(self.payload or {}),
|
||||
"added_by": self.added_by,
|
||||
"added_at": to_iso8601_utc(self.added_at),
|
||||
}
|
||||
|
||||
|
||||
class CaseVersion(Base):
|
||||
__tablename__ = "case_versions"
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True)
|
||||
case_id = Column(Integer, ForeignKey("investigation_cases.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||
version = Column(Integer, nullable=False)
|
||||
snapshot = Column(JSON, nullable=False, default=dict)
|
||||
content_sha256 = Column(String(64), nullable=False, index=True)
|
||||
frozen_by = Column(String(120), nullable=False)
|
||||
frozen_at = Column(DateTime(timezone=True), nullable=False, server_default=func.now())
|
||||
|
||||
__table_args__ = (
|
||||
Index("idx_case_versions_case_ver", "case_id", "version", unique=True),
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"id": self.id,
|
||||
"case_id": self.case_id,
|
||||
"version": int(self.version),
|
||||
"snapshot": dict(self.snapshot or {}),
|
||||
"content_sha256": self.content_sha256,
|
||||
"frozen_by": self.frozen_by,
|
||||
"frozen_at": to_iso8601_utc(self.frozen_at),
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
"""NGA MSI maritime navigational warnings and submarine cable advisories model."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import Column, DateTime, Float, Integer, JSON, String, Text
|
||||
from sqlalchemy.sql import func
|
||||
|
||||
from app.core.time import to_iso8601_utc
|
||||
from app.db.session import Base
|
||||
|
||||
|
||||
class CableAdvisory(Base):
|
||||
__tablename__ = "cable_advisories"
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True)
|
||||
source_warning_id = Column(String(120), unique=True, nullable=False, index=True)
|
||||
text = Column(Text, nullable=False)
|
||||
lat = Column(Float, nullable=True)
|
||||
lon = Column(Float, nullable=True)
|
||||
polygon = Column(JSON, nullable=True)
|
||||
issued_at = Column(DateTime(timezone=True), nullable=True, index=True)
|
||||
cancelled_at = Column(DateTime(timezone=True), nullable=True, index=True)
|
||||
matched_cable_ids = Column(JSON, nullable=False, default=list)
|
||||
match_method = Column(String(64), nullable=True)
|
||||
ingested_at = Column(DateTime(timezone=True), nullable=False, server_default=func.now())
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"id": self.id,
|
||||
"source_warning_id": self.source_warning_id,
|
||||
"text": self.text,
|
||||
"lat": self.lat,
|
||||
"lon": self.lon,
|
||||
"polygon": list(self.polygon or []) if isinstance(self.polygon, list) else None,
|
||||
"issued_at": to_iso8601_utc(self.issued_at),
|
||||
"cancelled_at": to_iso8601_utc(self.cancelled_at),
|
||||
"matched_cable_ids": list(self.matched_cable_ids or []),
|
||||
"match_method": self.match_method,
|
||||
"ingested_at": to_iso8601_utc(self.ingested_at),
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
"""Ontology curation models storing only non-derivable aliases and analyst-asserted links."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import Column, DateTime, Index, Integer, JSON, String, Text, UniqueConstraint
|
||||
from sqlalchemy.sql import func
|
||||
|
||||
from app.core.time import to_iso8601_utc
|
||||
from app.db.session import Base
|
||||
|
||||
|
||||
class OntologyEntityAlias(Base):
|
||||
"""Confirmed external alias mapping (vessel/ship/cable/airline names) to `{type}:{id}`."""
|
||||
|
||||
__tablename__ = "ontology_entity_aliases"
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True)
|
||||
alias = Column(String(200), nullable=False, index=True)
|
||||
object_id = Column(String(160), nullable=False, index=True)
|
||||
source = Column(String(80), nullable=False, default="analyst")
|
||||
created_by = Column(String(120), nullable=False, default="system")
|
||||
created_at = Column(DateTime(timezone=True), nullable=False, server_default=func.now())
|
||||
|
||||
__table_args__ = (
|
||||
UniqueConstraint("alias", "object_id", name="uq_ontology_alias_object"),
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"id": self.id,
|
||||
"alias": self.alias,
|
||||
"object_id": self.object_id,
|
||||
"source": self.source,
|
||||
"created_by": self.created_by,
|
||||
"created_at": to_iso8601_utc(self.created_at),
|
||||
}
|
||||
|
||||
|
||||
class AnalystLink(Base):
|
||||
"""Non-derivable analyst-asserted relationship between two `{type}:{id}` objects."""
|
||||
|
||||
__tablename__ = "analyst_links"
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True)
|
||||
from_object_id = Column(String(160), nullable=False, index=True)
|
||||
to_object_id = Column(String(160), nullable=False, index=True)
|
||||
relation_type = Column(String(80), nullable=False, index=True)
|
||||
note = Column(Text, nullable=False, default="")
|
||||
evidence_ids = Column(JSON, nullable=False, default=list)
|
||||
created_by = Column(String(120), nullable=False, default="analyst")
|
||||
created_at = Column(DateTime(timezone=True), nullable=False, server_default=func.now())
|
||||
status = Column(String(32), nullable=False, default="active", index=True)
|
||||
|
||||
__table_args__ = (
|
||||
Index("idx_analyst_links_pair", "from_object_id", "to_object_id", "status"),
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"id": self.id,
|
||||
"from_object_id": self.from_object_id,
|
||||
"to_object_id": self.to_object_id,
|
||||
"relation_type": self.relation_type,
|
||||
"note": self.note,
|
||||
"evidence_ids": list(self.evidence_ids or []),
|
||||
"created_by": self.created_by,
|
||||
"created_at": to_iso8601_utc(self.created_at),
|
||||
"status": self.status,
|
||||
"relation_source": "analyst_asserted",
|
||||
}
|
||||
@@ -0,0 +1,369 @@
|
||||
"""Action registry, 3-role x risk approval matrix, SSRF-guarded webhook executor, and AuditLog (§4.5)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.enums import UserRole
|
||||
from app.core.logging import get_logger
|
||||
from app.models.action_request import ActionRequest
|
||||
from app.models.investigation_case import InvestigationCase
|
||||
from app.models.system_log import AuditLog
|
||||
from app.models.system_setting import SystemSetting
|
||||
from app.services.ai.tool_registry import SSRFBlockedError, validate_public_http_url
|
||||
|
||||
logger = get_logger(__name__, service="actions_service")
|
||||
|
||||
WEBHOOK_ALLOWLIST_CATEGORY = "actions"
|
||||
WEBHOOK_ALLOWLIST_KEY = "webhook_allowlist"
|
||||
WEBHOOK_SECRET_KEY = "webhook_signing_secret"
|
||||
|
||||
ACTION_TYPE_REGISTRY: dict[str, dict[str, Any]] = {
|
||||
"add_to_watchlist": {
|
||||
"action_type": "add_to_watchlist",
|
||||
"label": "加入持续关注清单",
|
||||
"label_en": "Add to Watchlist",
|
||||
"risk_level": "low",
|
||||
"description": "将目标对象纳入关注态势列表",
|
||||
},
|
||||
"create_case": {
|
||||
"action_type": "create_case",
|
||||
"label": "新建研判卷宗",
|
||||
"label_en": "Create Investigation Case",
|
||||
"risk_level": "low",
|
||||
"description": "基于目标对象自动初始化研判卷宗",
|
||||
},
|
||||
"create_ticket_webhook": {
|
||||
"action_type": "create_ticket_webhook",
|
||||
"label": "推送工单系统 Webhook",
|
||||
"label_en": "Dispatch Ticket Webhook",
|
||||
"risk_level": "high",
|
||||
"description": "向管理员白名单内的工单网关发送结构化处置请求",
|
||||
},
|
||||
"notify_webhook": {
|
||||
"action_type": "notify_webhook",
|
||||
"label": "推送协同群机器人通知",
|
||||
"label_en": "Notify Team Bot Webhook",
|
||||
"risk_level": "high",
|
||||
"description": "支持通用 JSON、企业微信、钉钉或飞书机器人消息格式推送告警",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
class ActionPermissionError(PermissionError):
|
||||
"""Raised when actor lacks RBAC permission or violates dual-person high-risk rule."""
|
||||
|
||||
|
||||
class ActionValidationError(ValueError):
|
||||
"""Raised on missing decision reason, unknown action type, allowlist miss, or SSRF block."""
|
||||
|
||||
|
||||
async def _write_audit(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
actor_id: int | None,
|
||||
actor_name: str,
|
||||
action: str,
|
||||
target_id: str,
|
||||
result: str,
|
||||
details: dict[str, Any],
|
||||
) -> None:
|
||||
db.add(
|
||||
AuditLog(
|
||||
actor_id=actor_id,
|
||||
actor_name=actor_name,
|
||||
action=action,
|
||||
target_type="action_request",
|
||||
target_id=target_id,
|
||||
result=result,
|
||||
details=details,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
async def get_webhook_allowlist(db: AsyncSession) -> list[str]:
|
||||
row = (
|
||||
await db.execute(
|
||||
select(SystemSetting).where(SystemSetting.category == WEBHOOK_ALLOWLIST_CATEGORY)
|
||||
)
|
||||
).scalars().first()
|
||||
if not row or not isinstance(row.payload, dict):
|
||||
return []
|
||||
raw = row.payload.get(WEBHOOK_ALLOWLIST_KEY)
|
||||
if isinstance(raw, list):
|
||||
return [str(u).strip() for u in raw if str(u).strip()]
|
||||
return []
|
||||
|
||||
|
||||
async def get_webhook_signing_secret(db: AsyncSession) -> str:
|
||||
row = (
|
||||
await db.execute(
|
||||
select(SystemSetting).where(SystemSetting.category == WEBHOOK_ALLOWLIST_CATEGORY)
|
||||
)
|
||||
).scalars().first()
|
||||
if not row or not isinstance(row.payload, dict):
|
||||
return ""
|
||||
return str(row.payload.get(WEBHOOK_SECRET_KEY) or "").strip()
|
||||
|
||||
|
||||
def format_webhook_payload(
|
||||
*,
|
||||
channel: str,
|
||||
title: str,
|
||||
summary: str,
|
||||
request_obj: ActionRequest,
|
||||
) -> dict[str, Any]:
|
||||
"""Build payload tailored for generic JSON, WeCom, DingTalk, or Feishu bot."""
|
||||
fmt = str(channel or "generic").strip().lower()
|
||||
if fmt == "wecom":
|
||||
return {
|
||||
"msgtype": "markdown",
|
||||
"markdown": {"content": f"### {title}\n{summary}\n> Targets: {', '.join(request_obj.target_object_ids or [])}"},
|
||||
}
|
||||
if fmt == "dingtalk":
|
||||
return {
|
||||
"msgtype": "markdown",
|
||||
"markdown": {"title": title, "text": f"### {title}\n\n{summary}"},
|
||||
}
|
||||
if fmt == "feishu":
|
||||
return {
|
||||
"msg_type": "text",
|
||||
"content": {"text": f"[{title}] {summary}"},
|
||||
}
|
||||
return {
|
||||
"event": "planet.action_request",
|
||||
"request_id": request_obj.id,
|
||||
"action_type": request_obj.action_type,
|
||||
"target_object_ids": list(request_obj.target_object_ids or []),
|
||||
"title": title,
|
||||
"summary": summary,
|
||||
"requested_by": request_obj.requested_by,
|
||||
"approved_by": request_obj.approved_by,
|
||||
}
|
||||
|
||||
|
||||
def validate_allowlisted_webhook_url(url: str, allowlist: list[str]) -> str:
|
||||
"""Ensure URL is in admin allowlist AND passes existing SSRF public HTTP check."""
|
||||
clean = str(url or "").strip()
|
||||
if not clean:
|
||||
raise ActionValidationError("Webhook target URL is required")
|
||||
try:
|
||||
validated = validate_public_http_url(clean, resolve_dns=True)
|
||||
except SSRFBlockedError as exc:
|
||||
raise ActionValidationError(f"SSRF check blocked webhook target: {exc}") from exc
|
||||
|
||||
allowed = False
|
||||
for prefix in allowlist:
|
||||
p = str(prefix or "").strip()
|
||||
if not p:
|
||||
continue
|
||||
if validated == p or validated.startswith(p.rstrip("/") + "/"):
|
||||
allowed = True
|
||||
break
|
||||
if not allowed:
|
||||
raise ActionValidationError("Webhook target URL is not in administrator allowlist")
|
||||
return validated
|
||||
|
||||
|
||||
async def _execute_action_request(
|
||||
db: AsyncSession,
|
||||
req: ActionRequest,
|
||||
*,
|
||||
actor_id: int | None,
|
||||
actor_name: str,
|
||||
http_post_fn=None,
|
||||
) -> ActionRequest:
|
||||
params = dict(req.params or {})
|
||||
if req.action_type == "add_to_watchlist":
|
||||
req.status = "executed"
|
||||
req.execution_result = {
|
||||
"watched_objects": list(req.target_object_ids or []),
|
||||
"executed_at": datetime.now(UTC).isoformat(),
|
||||
}
|
||||
elif req.action_type == "create_case":
|
||||
case = InvestigationCase(
|
||||
title=str(params.get("title") or f"Action Case #{req.id}"),
|
||||
summary=str(params.get("summary") or "Auto-created via approved action request"),
|
||||
status="draft",
|
||||
owner_id=int(actor_id or 0),
|
||||
owner_name=actor_name,
|
||||
is_shared=True,
|
||||
)
|
||||
db.add(case)
|
||||
await db.flush()
|
||||
req.status = "executed"
|
||||
req.execution_result = {"case_id": case.id, "title": case.title}
|
||||
elif req.action_type in {"create_ticket_webhook", "notify_webhook"}:
|
||||
target_url = str(params.get("webhook_url") or "")
|
||||
allowlist = await get_webhook_allowlist(db)
|
||||
validated_url = validate_allowlisted_webhook_url(target_url, allowlist)
|
||||
payload = format_webhook_payload(
|
||||
channel=str(params.get("channel") or "generic"),
|
||||
title=str(params.get("title") or f"Planet Action #{req.id}"),
|
||||
summary=str(params.get("summary") or ""),
|
||||
request_obj=req,
|
||||
)
|
||||
body_bytes = json.dumps(payload, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
|
||||
headers = {"Content-Type": "application/json"}
|
||||
secret = await get_webhook_signing_secret(db)
|
||||
if secret:
|
||||
sig = hmac.new(secret.encode("utf-8"), body_bytes, hashlib.sha256).hexdigest()
|
||||
headers["X-Planet-Signature"] = f"sha256={sig}"
|
||||
|
||||
attempts = 0
|
||||
last_err = ""
|
||||
status_code = 0
|
||||
while attempts < 2:
|
||||
attempts += 1
|
||||
try:
|
||||
if http_post_fn is not None:
|
||||
res = await http_post_fn(validated_url, body_bytes, headers)
|
||||
status_code = int(res.get("status_code", 200))
|
||||
else:
|
||||
async with httpx.AsyncClient(timeout=8.0) as client:
|
||||
resp = await client.post(validated_url, content=body_bytes, headers=headers)
|
||||
status_code = resp.status_code
|
||||
if 200 <= status_code < 300:
|
||||
req.status = "executed"
|
||||
req.execution_result = {
|
||||
"webhook_url": validated_url,
|
||||
"status_code": status_code,
|
||||
"attempts": attempts,
|
||||
"signed": bool(secret),
|
||||
}
|
||||
last_err = ""
|
||||
break
|
||||
last_err = f"HTTP {status_code}"
|
||||
except Exception as exc:
|
||||
last_err = str(exc)
|
||||
if last_err:
|
||||
req.status = "failed"
|
||||
req.execution_result = {"webhook_url": validated_url, "error": last_err, "attempts": attempts}
|
||||
await _write_audit(
|
||||
db,
|
||||
actor_id=actor_id,
|
||||
actor_name=actor_name,
|
||||
action=f"action.{req.action_type}.{req.status}",
|
||||
target_id=str(req.id),
|
||||
result=req.status,
|
||||
details={"risk_level": req.risk_level, "execution_result": req.execution_result},
|
||||
)
|
||||
return req
|
||||
|
||||
|
||||
async def submit_action_request(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
action_type: str,
|
||||
target_object_ids: list[str],
|
||||
params: dict[str, Any],
|
||||
actor_id: int | None,
|
||||
actor_name: str,
|
||||
actor_role: str,
|
||||
source_workflow_run_id: str | None = None,
|
||||
ai_suggested: bool = False,
|
||||
) -> ActionRequest:
|
||||
"""Create action request; low-risk admin submissions execute immediately unless `ai_suggested`."""
|
||||
role = str(actor_role or "").lower()
|
||||
if role == UserRole.VIEWER.value or role not in {UserRole.ADMIN.value, UserRole.SUPER_ADMIN.value}:
|
||||
raise ActionPermissionError("Viewer role cannot initiate action requests")
|
||||
|
||||
spec = ACTION_TYPE_REGISTRY.get(action_type)
|
||||
if spec is None:
|
||||
raise ActionValidationError(f"Unknown action_type: {action_type}")
|
||||
risk = spec["risk_level"]
|
||||
|
||||
req = ActionRequest(
|
||||
action_type=action_type,
|
||||
target_object_ids=list(target_object_ids or []),
|
||||
params=dict(params or {}),
|
||||
risk_level=risk,
|
||||
status="pending",
|
||||
requested_by=actor_name,
|
||||
requested_at=datetime.now(UTC),
|
||||
source_workflow_run_id=source_workflow_run_id,
|
||||
)
|
||||
db.add(req)
|
||||
await db.flush()
|
||||
|
||||
await _write_audit(
|
||||
db,
|
||||
actor_id=actor_id,
|
||||
actor_name=actor_name,
|
||||
action=f"action.{action_type}.requested",
|
||||
target_id=str(req.id),
|
||||
result="pending",
|
||||
details={"risk_level": risk, "ai_suggested": ai_suggested},
|
||||
)
|
||||
|
||||
if not ai_suggested and risk == "low":
|
||||
req.approved_by = actor_name
|
||||
req.approved_at = datetime.now(UTC)
|
||||
req.decision_reason = "Low-risk action executed directly by administrator"
|
||||
await _execute_action_request(db, req, actor_id=actor_id, actor_name=actor_name)
|
||||
|
||||
await db.commit()
|
||||
return req
|
||||
|
||||
|
||||
async def decide_action_request(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
req: ActionRequest,
|
||||
decision: str,
|
||||
decision_reason: str,
|
||||
actor_id: int | None,
|
||||
actor_name: str,
|
||||
actor_role: str,
|
||||
http_post_fn=None,
|
||||
) -> ActionRequest:
|
||||
"""Approve or reject a pending action request enforcing strict 3-role x risk matrix."""
|
||||
role = str(actor_role or "").lower()
|
||||
if role not in {UserRole.ADMIN.value, UserRole.SUPER_ADMIN.value}:
|
||||
raise ActionPermissionError("Insufficient permissions to decide action requests")
|
||||
|
||||
reason = str(decision_reason or "").strip()
|
||||
if not reason:
|
||||
raise ActionValidationError("Approval or rejection requires a non-empty decision_reason")
|
||||
|
||||
if req.status != "pending":
|
||||
raise ActionValidationError(f"Action request #{req.id} is already {req.status}")
|
||||
|
||||
if req.risk_level == "high":
|
||||
if role != UserRole.SUPER_ADMIN.value:
|
||||
raise ActionPermissionError("High-risk actions require super_admin approval")
|
||||
if actor_name == req.requested_by:
|
||||
raise ActionPermissionError("High-risk approver must differ from requester")
|
||||
|
||||
req.approved_by = actor_name
|
||||
req.approved_at = datetime.now(UTC)
|
||||
req.decision_reason = reason
|
||||
|
||||
if decision == "reject":
|
||||
req.status = "rejected"
|
||||
await _write_audit(
|
||||
db,
|
||||
actor_id=actor_id,
|
||||
actor_name=actor_name,
|
||||
action=f"action.{req.action_type}.rejected",
|
||||
target_id=str(req.id),
|
||||
result="rejected",
|
||||
details={"reason": reason},
|
||||
)
|
||||
await db.commit()
|
||||
return req
|
||||
|
||||
req.status = "approved"
|
||||
await _execute_action_request(
|
||||
db, req, actor_id=actor_id, actor_name=actor_name, http_post_fn=http_post_fn
|
||||
)
|
||||
await db.commit()
|
||||
return req
|
||||
@@ -22,11 +22,15 @@ from app.services.ai.thinking_sanitizer import strip_thinking_text
|
||||
from app.services.ai.tool_registry import (
|
||||
TimeBasis,
|
||||
isolate_untrusted_external_text,
|
||||
query_aircraft_posture_tool,
|
||||
query_bgp_incidents_tool,
|
||||
query_cable_posture_tool,
|
||||
query_cloud_posture_tool,
|
||||
query_compute_posture_tool,
|
||||
query_disaster_posture_tool,
|
||||
query_global_situational_tool,
|
||||
query_gps_jamming_posture_tool,
|
||||
query_ontology_neighborhood_tool,
|
||||
query_recent_earth_news_tool,
|
||||
query_satellite_posture_tool,
|
||||
query_vessel_posture_tool,
|
||||
@@ -163,6 +167,7 @@ _BGP_ENTITY_TYPES = frozenset({"bgp"})
|
||||
_CABLE_ENTITY_TYPES = frozenset({"cable", "landing_point"})
|
||||
_SATELLITE_ENTITY_TYPES = frozenset({"satellite"})
|
||||
_VESSEL_ENTITY_TYPES = frozenset({"vessel"})
|
||||
_AIRCRAFT_ENTITY_TYPES = frozenset({"aircraft"})
|
||||
_COMPUTE_FACILITY_TYPES = frozenset(
|
||||
{"supercomputer", "gpu_cluster", "data_center", "cloud_center", "edge_node", "compute_center_unresolved"}
|
||||
)
|
||||
@@ -295,6 +300,39 @@ async def _execute_tool(
|
||||
cutoff_at=cutoff_at,
|
||||
entity_id=_target_id_for_types(targets, _VESSEL_ENTITY_TYPES),
|
||||
)
|
||||
if tool_id == "query_aircraft_posture":
|
||||
return await query_aircraft_posture_tool(
|
||||
db,
|
||||
time_basis=time_basis,
|
||||
cutoff_at=cutoff_at,
|
||||
entity_id=_target_id_for_types(targets, _AIRCRAFT_ENTITY_TYPES),
|
||||
)
|
||||
if tool_id == "query_gps_jamming_posture":
|
||||
return await query_gps_jamming_posture_tool(
|
||||
db,
|
||||
time_basis=time_basis,
|
||||
cutoff_at=cutoff_at,
|
||||
)
|
||||
if tool_id == "query_disaster_posture":
|
||||
return await query_disaster_posture_tool(
|
||||
db,
|
||||
time_basis=time_basis,
|
||||
cutoff_at=cutoff_at,
|
||||
)
|
||||
if tool_id == "query_ontology_neighborhood":
|
||||
first = targets[0] if targets else {}
|
||||
oid = str(first.get("object_id") or "")
|
||||
if not oid and first.get("entity_type") and first.get("entity_id"):
|
||||
oid = f"{first['entity_type']}:{first['entity_id']}"
|
||||
if not oid:
|
||||
oid = "chokepoint:malacca_strait"
|
||||
return await query_ontology_neighborhood_tool(
|
||||
db,
|
||||
object_id=oid,
|
||||
depth=2,
|
||||
time_basis=time_basis,
|
||||
cutoff_at=cutoff_at,
|
||||
)
|
||||
if tool_id == "query_cloud_posture":
|
||||
first = targets[0] if targets else {}
|
||||
return await query_cloud_posture_tool(
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -71,6 +71,10 @@ class StageStepSpec(BaseModel):
|
||||
spotlight_Statistic_codes: list[str] = Field(default_factory=list)
|
||||
highlight_milestone_id: str | None = None
|
||||
enable_national_hubs: bool = False
|
||||
workflow_params: dict[str, Any] = Field(default_factory=dict)
|
||||
spotlight_card_keys: list[str] = Field(default_factory=list)
|
||||
overlays: list[str] = Field(default_factory=list)
|
||||
spatial_cards: list[dict[str, Any]] = Field(default_factory=list)
|
||||
logical_arcs: list[StageArcSpec] = Field(default_factory=list)
|
||||
measured_impact_regions: list[str] = Field(default_factory=list)
|
||||
evidence_ids: list[str] = Field(default_factory=list)
|
||||
|
||||
@@ -606,3 +606,101 @@ async def audit_situational_hygiene(db: AsyncSession) -> dict[str, Any]:
|
||||
"R1 write-on-GET feedback loop severed; SituationalAssessment & StagePresentation writes are now strictly content-fingerprint idempotent."
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
async def process_fusion_incident(
|
||||
db: AsyncSession,
|
||||
incident: Any,
|
||||
*,
|
||||
execute_workflow: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""Emit idempotent StagePresentation & workflow linkage for candidate_correlation / dependency_impact."""
|
||||
from app.services.ai.presentation_compiler import (
|
||||
StageCameraPose,
|
||||
StagePresentationContract,
|
||||
StageStepSpec,
|
||||
)
|
||||
|
||||
inc_id = getattr(incident, "id", None) or "adhoc"
|
||||
kind = str(getattr(incident, "assessment_kind", None) or "candidate_correlation")
|
||||
inc_type = str(getattr(incident, "incident_type", None) or "")
|
||||
title = str(getattr(incident, "title", None) or f"Fusion Incident #{inc_id}")
|
||||
summary = dict(getattr(incident, "signal_summary", None) or {})
|
||||
obj_ids = list(getattr(incident, "object_ids", None) or [])
|
||||
|
||||
is_cable_scenario = (
|
||||
kind == "dependency_impact"
|
||||
or "cable" in inc_type
|
||||
or any(str(oid).startswith("cable:") for oid in obj_ids)
|
||||
)
|
||||
workflow_id = "wargame.cable_protection" if is_cable_scenario else "wargame.air_sea_em"
|
||||
domain = "cable" if is_cable_scenario else "global"
|
||||
|
||||
lat = float(summary.get("lat")) if isinstance(summary.get("lat"), (int, float)) else 1.3
|
||||
lon = float(summary.get("lon")) if isinstance(summary.get("lon"), (int, float)) else 103.8
|
||||
|
||||
overlays = ["chokepoints", "geofences"]
|
||||
if kind == "dependency_impact":
|
||||
overlays.append("dependency_arcs")
|
||||
|
||||
spatial_cards = [
|
||||
{
|
||||
"key": f"fusion-{inc_id}",
|
||||
"title": title[:80],
|
||||
"title_en": f"{workflow_id} · #{inc_id}",
|
||||
"summary": summary.get("co_occurrence_note") or title,
|
||||
"anchor": {"latitude": lat, "longitude": lon},
|
||||
"side": "right",
|
||||
"blocks": [
|
||||
{
|
||||
"block_id": f"samples-{inc_id}",
|
||||
"block_type": "entity_samples",
|
||||
"data": {
|
||||
"title": "关联目标样本",
|
||||
"items": [{"object_id": oid, "label": oid} for oid in obj_ids[:6]],
|
||||
},
|
||||
}
|
||||
],
|
||||
}
|
||||
]
|
||||
|
||||
pres_key = f"fusion-incident:{inc_id}:{kind}"
|
||||
contract = StagePresentationContract(
|
||||
presentation_key=pres_key,
|
||||
domain=domain,
|
||||
time_basis="retrospective",
|
||||
title=title[:180],
|
||||
title_en=f"Situational Fusion · #{inc_id}",
|
||||
summary=str(summary.get("co_occurrence_note") or title)[:400],
|
||||
summary_en=f"Workflow {workflow_id} presentation for {kind}",
|
||||
steps=[
|
||||
StageStepSpec(
|
||||
step_id=f"fusion-{inc_id}-step-1",
|
||||
stage="discover" if kind == "candidate_correlation" else "impact",
|
||||
title="第一幕 · 多域信号叠加" if kind == "candidate_correlation" else "第一幕 · 独立证据与依赖影响",
|
||||
title_en="Act 1 · Multi-Domain Signals" if kind == "candidate_correlation" else "Act 1 · Grounded Dependency Impact",
|
||||
caption=title[:480],
|
||||
caption_en=title[:500],
|
||||
dwell_ms=5200,
|
||||
camera=StageCameraPose(lat=lat, lon=lon, zoom=1.35),
|
||||
workflow_params={"workflow_id": workflow_id, "incident_id": inc_id, "assessment_kind": kind},
|
||||
spotlight_card_keys=[f"fusion-{inc_id}"],
|
||||
overlays=overlays,
|
||||
spatial_cards=spatial_cards,
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
published_dict: dict[str, Any] | None = None
|
||||
if execute_workflow:
|
||||
published = await publish_stage_contract(db, contract)
|
||||
if published is not None:
|
||||
published_dict = published.to_dict()
|
||||
|
||||
return {
|
||||
"incident_id": inc_id,
|
||||
"assessment_kind": kind,
|
||||
"workflow_id": workflow_id,
|
||||
"presentation_key": pres_key,
|
||||
"published_presentation": published_dict,
|
||||
}
|
||||
@@ -74,6 +74,56 @@ def _parse_scene_json_candidate(raw_json: str) -> dict[str, Any] | None:
|
||||
return None
|
||||
|
||||
|
||||
def sanitize_spatial_cards(raw: Any) -> list[dict[str, Any]]:
|
||||
if not isinstance(raw, list):
|
||||
return []
|
||||
cleaned: list[dict[str, Any]] = []
|
||||
for item in raw[:8]:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
key = str(item.get("key") or "").strip()
|
||||
anchor = item.get("anchor")
|
||||
if not key or not isinstance(anchor, dict):
|
||||
continue
|
||||
lat = anchor.get("latitude")
|
||||
lon = anchor.get("longitude")
|
||||
if not isinstance(lat, (int, float)) or not isinstance(lon, (int, float)):
|
||||
continue
|
||||
blocks = item.get("blocks") if isinstance(item.get("blocks"), list) else []
|
||||
side = str(item.get("side") or "").strip().lower()
|
||||
cleaned.append(
|
||||
{
|
||||
"key": key,
|
||||
"title": str(item.get("title") or key),
|
||||
"title_en": str(item.get("title_en") or item.get("title") or key),
|
||||
"summary": str(item.get("summary") or "") or None,
|
||||
"anchor": {
|
||||
"latitude": float(lat),
|
||||
"longitude": float(lon),
|
||||
"label": str(anchor.get("label") or "") or None,
|
||||
},
|
||||
"side": side if side in {"left", "right"} else None,
|
||||
"partner_key": str(item.get("partner_key") or "") or None,
|
||||
"blocks": [b for b in blocks if isinstance(b, dict)],
|
||||
}
|
||||
)
|
||||
return cleaned
|
||||
|
||||
|
||||
_ALLOWED_SCENE_OVERLAYS = frozenset({"national_hubs", "chokepoints", "geofences", "dependency_arcs"})
|
||||
|
||||
|
||||
def sanitize_scene_overlays(raw: Any) -> list[str]:
|
||||
if not isinstance(raw, list):
|
||||
return []
|
||||
out: list[str] = []
|
||||
for item in raw:
|
||||
key = str(item or "").strip().lower()
|
||||
if key in _ALLOWED_SCENE_OVERLAYS and key not in out:
|
||||
out.append(key)
|
||||
return out
|
||||
|
||||
|
||||
def extract_planet_scene_from_text(text: str) -> tuple[str, dict[str, Any] | None]:
|
||||
"""Strip `<planet_scene>...</planet_scene>` blocks and return validated scene spec fields."""
|
||||
if not text:
|
||||
@@ -86,12 +136,18 @@ def extract_planet_scene_from_text(text: str) -> tuple[str, dict[str, Any] | Non
|
||||
continue
|
||||
zones = [z.model_dump(mode="json") for z in validate_influence_zones(payload.get("influence_zones"))]
|
||||
camera_hint = sanitize_camera_hint(payload.get("camera_hint"))
|
||||
if zones or camera_hint:
|
||||
spatial_cards = sanitize_spatial_cards(payload.get("spatial_cards"))
|
||||
overlays = sanitize_scene_overlays(payload.get("overlays"))
|
||||
if zones or camera_hint or spatial_cards or overlays:
|
||||
parsed_scene = {}
|
||||
if zones:
|
||||
parsed_scene["influence_zones"] = zones
|
||||
if camera_hint:
|
||||
parsed_scene["camera_hint"] = camera_hint
|
||||
if spatial_cards:
|
||||
parsed_scene["spatial_cards"] = spatial_cards
|
||||
if overlays:
|
||||
parsed_scene["overlays"] = overlays
|
||||
|
||||
if matches and parsed_scene is not None:
|
||||
extracted_zones = parsed_scene.get("influence_zones") or []
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, date, datetime
|
||||
from datetime import UTC, date, datetime, timedelta
|
||||
import hashlib
|
||||
import ipaddress
|
||||
import socket
|
||||
@@ -610,12 +610,27 @@ async def query_cable_posture_tool(
|
||||
if time_basis == "as_known_then":
|
||||
limitations.append("海缆资产库按当前目录快照读取,不具备历史逐日断缆回放快照,仅作当下资产基线参考。")
|
||||
|
||||
from app.services.nga_advisories import list_active_cable_advisories
|
||||
|
||||
advisories = await list_active_cable_advisories(db, limit=30)
|
||||
if advisories:
|
||||
base_evidence["ev-cable-nga-1"] = {
|
||||
"id": "ev-cable-nga-1",
|
||||
"title": "NGA MSI 航海通告与海缆安全告警(nga_navigation_warnings)",
|
||||
"publisher": "National Geospatial-Intelligence Agency (NGA MSI)",
|
||||
"url": "https://msi.nga.mil/NavWarnings",
|
||||
"published_at": datetime.now(UTC).date().isoformat(),
|
||||
"locator": "builtin:cable_advisories",
|
||||
}
|
||||
|
||||
return {
|
||||
"domain": "cable",
|
||||
"available": len(cable_features) > 0 or len(landing_features) > 0,
|
||||
"cables_total": len(cable_features),
|
||||
"landing_points_total": len(landing_features),
|
||||
"status_counts": status_counts,
|
||||
"advisory_count": len(advisories),
|
||||
"advisories": advisories,
|
||||
"top_longest_cables": cables_parsed[: max(1, min(limit, 12))],
|
||||
"top_landing_countries": top_countries,
|
||||
"top_landing_hubs": landing_hubs[: max(1, min(limit, 12))],
|
||||
@@ -786,18 +801,32 @@ async def query_recent_earth_news_tool(
|
||||
)
|
||||
if region:
|
||||
stmt = stmt.where(EarthNewsItem.region == region)
|
||||
rows = (await db.execute(stmt)).scalars().all()
|
||||
rows = list((await db.execute(stmt)).scalars().all())
|
||||
rows.sort(
|
||||
key=lambda r: (
|
||||
getattr(r, "credibility_tier", None) is None,
|
||||
int(getattr(r, "credibility_tier", None) or 99),
|
||||
-(r.published_at.timestamp() if r.published_at else (r.last_seen_at.timestamp() if r.last_seen_at else 0.0)),
|
||||
)
|
||||
)
|
||||
for row in rows:
|
||||
loc_meta = dict(row.location_meta or {})
|
||||
news_meta = loc_meta.get("news_meta") if isinstance(loc_meta.get("news_meta"), dict) else {}
|
||||
localizations = row.localizations if isinstance(row.localizations, dict) else {}
|
||||
zh_loc = localizations.get("zh-CN") if isinstance(localizations.get("zh-CN"), dict) else {}
|
||||
tier = getattr(row, "credibility_tier", None)
|
||||
state_aff = bool(getattr(row, "state_affiliated", False))
|
||||
items.append(
|
||||
{
|
||||
"id": row.id,
|
||||
"title": zh_loc.get("title") or row.title,
|
||||
"summary": (zh_loc.get("summary") or row.summary or "")[:400],
|
||||
"source": row.source or row.feed_name,
|
||||
"credibility_tier": tier,
|
||||
"credibility_label": f"Tier {tier}" if tier is not None else "未分级",
|
||||
"state_affiliated": state_aff,
|
||||
"state_affiliation_label": "国家背景媒体" if state_aff else None,
|
||||
"theater_tags": list(getattr(row, "theater_tags", None) or []),
|
||||
"region": row.region,
|
||||
"location_label": row.location_label,
|
||||
"category": news_meta.get("category") or "other",
|
||||
@@ -924,6 +953,13 @@ async def query_vessel_posture_tool(
|
||||
|
||||
parsed_vessels.sort(key=lambda r: (r["sog"] or -1.0, r["name"]), reverse=True)
|
||||
sorted_flags = dict(sorted(top_flags.items(), key=lambda kv: kv[1], reverse=True)[:8])
|
||||
|
||||
from app.services.maritime_geography import compute_chokepoint_vessel_summary
|
||||
|
||||
chokepoints = await compute_chokepoint_vessel_summary(db, features)
|
||||
warship_count = sum(1 for f in features if (f.get("properties") or {}).get("is_warship"))
|
||||
cable_ship_count = sum(1 for f in features if (f.get("properties") or {}).get("is_cable_ship"))
|
||||
|
||||
if time_basis == "as_known_then":
|
||||
limitations.append(f"AIS 船舶快照仅覆盖近 {since_minutes} 分钟滑动窗口,不支持历史截点静态重放。")
|
||||
|
||||
@@ -933,6 +969,9 @@ async def query_vessel_posture_tool(
|
||||
"vessels_total": int(stats.get("total") or len(features)),
|
||||
"underway": int(stats.get("underway") or 0),
|
||||
"anchored_or_moored": int(stats.get("anchored_or_moored") or 0),
|
||||
"warship_count": warship_count,
|
||||
"cable_ship_count": cable_ship_count,
|
||||
"chokepoints": chokepoints,
|
||||
"by_type": dict(stats.get("by_type") or {}),
|
||||
"top_flags": sorted_flags,
|
||||
"sample_vessels": parsed_vessels[:8],
|
||||
@@ -1180,9 +1219,16 @@ async def query_global_situational_tool(
|
||||
},
|
||||
]
|
||||
|
||||
from app.services.source_freshness import compute_domain_freshness
|
||||
|
||||
freshness_report = await compute_domain_freshness(db)
|
||||
blind_spots = list(freshness_report.get("blind_spots") or [])
|
||||
|
||||
limitations: list[str] = []
|
||||
if time_basis == "as_known_then":
|
||||
limitations.append("全局综合面板中算力与 BGP 遵循历史截点过滤,其余实时图层(海缆/卫星/AIS)按当前资产目录展示。")
|
||||
for spot in blind_spots[:5]:
|
||||
limitations.append(f"盲区提示:{spot.get('label')}({spot.get('status')})- {spot.get('reason')}")
|
||||
|
||||
return {
|
||||
"domain": "global",
|
||||
@@ -1190,6 +1236,8 @@ async def query_global_situational_tool(
|
||||
"selected_codes": codes,
|
||||
"visible_layers": vis,
|
||||
"domain_summaries": domain_summaries,
|
||||
"freshness": freshness_report.get("domains") or [],
|
||||
"blind_spots": blind_spots,
|
||||
"compute_summary": {
|
||||
"latest_year": latest_compute_year,
|
||||
"mode": compute_data.get("mode") or "global_share",
|
||||
@@ -1227,3 +1275,403 @@ async def query_global_situational_tool(
|
||||
"evidence": evidence,
|
||||
"limitations": limitations,
|
||||
}
|
||||
|
||||
|
||||
def _classify_airspace_corridor(lat: float, lon: float) -> str:
|
||||
if 30.0 <= lat <= 72.0 and -12.0 <= lon <= 45.0:
|
||||
return "europe_black_sea"
|
||||
if 10.0 <= lat <= 42.0 and 25.0 <= lon <= 65.0:
|
||||
return "middle_east_red_sea"
|
||||
if 0.0 <= lat <= 46.0 and 95.0 <= lon <= 150.0:
|
||||
return "indo_west_pacific"
|
||||
if 24.0 <= lat <= 60.0 and -130.0 <= lon <= -55.0:
|
||||
return "north_america"
|
||||
if 35.0 <= lat <= 65.0 and -55.0 <= lon < -12.0:
|
||||
return "north_atlantic"
|
||||
return "other_airspace"
|
||||
|
||||
|
||||
async def query_aircraft_posture_tool(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
time_basis: TimeBasis = "retrospective",
|
||||
cutoff_at: str | None = None,
|
||||
entity_id: str | None = None,
|
||||
limit: int = 800,
|
||||
since_minutes: int = 15,
|
||||
) -> dict[str, Any]:
|
||||
"""Read-only built-in telemetry summary for live ADS-B aircraft traffic."""
|
||||
base_ev_id = "ev-aircraft-1"
|
||||
base_evidence = {
|
||||
base_ev_id: {
|
||||
"id": base_ev_id,
|
||||
"title": "Planet 内置全球 ADS-B 空域态势快照(aircraft/snapshot)",
|
||||
"publisher": "adsb.lol (ODbL) & OpenSky Network",
|
||||
"url": "/api/v1/aircraft/snapshot",
|
||||
"published_at": datetime.now(UTC).date().isoformat(),
|
||||
"locator": f"builtin:aircraft:{entity_id or 'global'}:since={since_minutes}m",
|
||||
}
|
||||
}
|
||||
if not hasattr(db, "execute"):
|
||||
return {
|
||||
"domain": "aircraft",
|
||||
"available": False,
|
||||
"aircraft_total": 0,
|
||||
"military_count": 0,
|
||||
"emergency_count": 0,
|
||||
"by_category": {},
|
||||
"key_airspaces": {},
|
||||
"sample_aircraft": [],
|
||||
"focused_entity": None,
|
||||
"time_basis": time_basis,
|
||||
"cutoff_at": cutoff_at if time_basis == "as_known_then" else None,
|
||||
"evidence": base_evidence,
|
||||
"limitations": ["当前离线/无实时数据库会话,未读取 ADS-B 空域快照。"],
|
||||
}
|
||||
|
||||
from app.models.aircraft import AircraftCurrentState
|
||||
|
||||
cutoff = datetime.now(UTC) - timedelta(minutes=max(1, int(since_minutes)))
|
||||
safe_limit = max(50, min(int(limit or 800), 2000))
|
||||
rows: list[AircraftCurrentState] = []
|
||||
limitations: list[str] = []
|
||||
try:
|
||||
res = await db.execute(
|
||||
select(AircraftCurrentState)
|
||||
.where(AircraftCurrentState.observed_at >= cutoff)
|
||||
.order_by(
|
||||
desc(AircraftCurrentState.is_emergency),
|
||||
desc(AircraftCurrentState.is_military),
|
||||
desc(AircraftCurrentState.observed_at),
|
||||
)
|
||||
.limit(safe_limit)
|
||||
)
|
||||
rows = list(res.scalars().all())
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Aircraft posture query degraded",
|
||||
event="ai_tool.aircraft_posture.degraded",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
limitations.append("ADS-B 空域快照查询受限")
|
||||
|
||||
by_category: dict[str, int] = {}
|
||||
key_airspaces: dict[str, dict[str, int]] = {}
|
||||
military_count = 0
|
||||
emergency_count = 0
|
||||
focused_entity: dict[str, Any] | None = None
|
||||
query_norm = str(entity_id or "").strip().lower()
|
||||
sample_aircraft: list[dict[str, Any]] = []
|
||||
|
||||
for row in rows:
|
||||
cat = str(row.category or "other")
|
||||
by_category[cat] = by_category.get(cat, 0) + 1
|
||||
if row.is_military:
|
||||
military_count += 1
|
||||
if row.is_emergency:
|
||||
emergency_count += 1
|
||||
corridor = _classify_airspace_corridor(float(row.lat), float(row.lon))
|
||||
bucket = key_airspaces.setdefault(
|
||||
corridor,
|
||||
{"total": 0, "military": 0, "emergency": 0, "commercial": 0},
|
||||
)
|
||||
bucket["total"] += 1
|
||||
if row.is_military:
|
||||
bucket["military"] += 1
|
||||
if row.is_emergency:
|
||||
bucket["emergency"] += 1
|
||||
if cat == "commercial":
|
||||
bucket["commercial"] += 1
|
||||
|
||||
item = row.to_dict()
|
||||
if len(sample_aircraft) < 20:
|
||||
sample_aircraft.append(item)
|
||||
if query_norm and focused_entity is None and (
|
||||
query_norm == str(row.icao24).lower()
|
||||
or query_norm in str(row.callsign or "").lower()
|
||||
):
|
||||
focused_entity = {"kind": "aircraft", **item}
|
||||
|
||||
if time_basis == "as_known_then":
|
||||
limitations.append(f"实时空域快照仅覆盖近 {since_minutes} 分钟窗口。")
|
||||
|
||||
return {
|
||||
"domain": "aircraft",
|
||||
"available": bool(rows),
|
||||
"aircraft_total": len(rows),
|
||||
"military_count": military_count,
|
||||
"emergency_count": emergency_count,
|
||||
"by_category": by_category,
|
||||
"key_airspaces": key_airspaces,
|
||||
"sample_aircraft": sample_aircraft,
|
||||
"focused_entity": focused_entity,
|
||||
"time_basis": time_basis,
|
||||
"cutoff_at": cutoff_at if time_basis == "as_known_then" else None,
|
||||
"evidence": base_evidence,
|
||||
"limitations": limitations,
|
||||
}
|
||||
|
||||
|
||||
async def query_gps_jamming_posture_tool(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
time_basis: TimeBasis = "retrospective",
|
||||
cutoff_at: str | None = None,
|
||||
observed_date: str | None = None,
|
||||
limit: int = 200,
|
||||
) -> dict[str, Any]:
|
||||
"""Read-only built-in summary of daily H3 GNSS/GPS interference hotspots."""
|
||||
base_ev_id = "ev-gpsjam-1"
|
||||
base_evidence = {
|
||||
base_ev_id: {
|
||||
"id": base_ev_id,
|
||||
"title": "Planet 内置 GPS/GNSS 干扰监测快照(gpsjam.org H3-4)",
|
||||
"publisher": "gpsjam.org (airplanes.live / ADS-B Exchange)",
|
||||
"url": "/api/v1/gps-jamming/snapshot",
|
||||
"published_at": datetime.now(UTC).date().isoformat(),
|
||||
"locator": f"builtin:gps_jamming:{observed_date or 'latest'}",
|
||||
}
|
||||
}
|
||||
if not hasattr(db, "execute"):
|
||||
return {
|
||||
"domain": "gps_jamming",
|
||||
"available": False,
|
||||
"observed_date": None,
|
||||
"cells_total": 0,
|
||||
"high_count": 0,
|
||||
"medium_count": 0,
|
||||
"high_zones": [],
|
||||
"medium_zones": [],
|
||||
"time_basis": time_basis,
|
||||
"cutoff_at": cutoff_at if time_basis == "as_known_then" else None,
|
||||
"evidence": base_evidence,
|
||||
"limitations": ["当前离线/无实时数据库会话,未读取 GPS 干扰快照。"],
|
||||
}
|
||||
|
||||
from app.models.gps_jamming import GPSJammingCell
|
||||
|
||||
target_date = str(observed_date or "").strip() or None
|
||||
if not target_date:
|
||||
target_date = (
|
||||
await db.execute(
|
||||
select(GPSJammingCell.observed_date)
|
||||
.order_by(desc(GPSJammingCell.observed_date))
|
||||
.limit(1)
|
||||
)
|
||||
).scalar_one_or_none()
|
||||
|
||||
if not target_date:
|
||||
return {
|
||||
"domain": "gps_jamming",
|
||||
"available": False,
|
||||
"observed_date": None,
|
||||
"cells_total": 0,
|
||||
"high_count": 0,
|
||||
"medium_count": 0,
|
||||
"high_zones": [],
|
||||
"medium_zones": [],
|
||||
"time_basis": time_basis,
|
||||
"cutoff_at": cutoff_at if time_basis == "as_known_then" else None,
|
||||
"evidence": base_evidence,
|
||||
"limitations": ["暂无已采集的 gpsjam 日度干扰栅格。"],
|
||||
}
|
||||
|
||||
rows = list(
|
||||
(
|
||||
await db.execute(
|
||||
select(GPSJammingCell)
|
||||
.where(GPSJammingCell.observed_date == target_date)
|
||||
.where(GPSJammingCell.level.in_(["high", "medium"]))
|
||||
.order_by(desc(GPSJammingCell.bad_ratio))
|
||||
.limit(max(20, min(int(limit or 200), 1000)))
|
||||
)
|
||||
).scalars().all()
|
||||
)
|
||||
high_zones = [
|
||||
{
|
||||
"h3_index": r.h3_index,
|
||||
"lat": r.lat,
|
||||
"lon": r.lon,
|
||||
"bad_ratio": r.bad_ratio,
|
||||
"aircraft_count": r.aircraft_count,
|
||||
"region": _classify_airspace_corridor(float(r.lat), float(r.lon)),
|
||||
}
|
||||
for r in rows
|
||||
if r.level == "high"
|
||||
]
|
||||
medium_zones = [
|
||||
{
|
||||
"h3_index": r.h3_index,
|
||||
"lat": r.lat,
|
||||
"lon": r.lon,
|
||||
"bad_ratio": r.bad_ratio,
|
||||
"aircraft_count": r.aircraft_count,
|
||||
"region": _classify_airspace_corridor(float(r.lat), float(r.lon)),
|
||||
}
|
||||
for r in rows
|
||||
if r.level == "medium"
|
||||
]
|
||||
return {
|
||||
"domain": "gps_jamming",
|
||||
"available": bool(rows),
|
||||
"observed_date": target_date,
|
||||
"cells_total": len(rows),
|
||||
"high_count": len(high_zones),
|
||||
"medium_count": len(medium_zones),
|
||||
"high_zones": high_zones[:20],
|
||||
"medium_zones": medium_zones[:20],
|
||||
"time_basis": time_basis,
|
||||
"cutoff_at": cutoff_at if time_basis == "as_known_then" else None,
|
||||
"evidence": base_evidence,
|
||||
"limitations": [
|
||||
"gpsjam 反映高空航空器报告的 GNSS 导航精度下降指标,地面受影响范围可能与高空视线存在差异。"
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
async def query_disaster_posture_tool(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
time_basis: TimeBasis = "retrospective",
|
||||
cutoff_at: str | None = None,
|
||||
event_types: list[str] | None = None,
|
||||
since_hours: int = 72,
|
||||
limit: int = 200,
|
||||
) -> dict[str, Any]:
|
||||
"""Read-only built-in telemetry summary for recent natural disasters."""
|
||||
base_ev_id = "ev-disasters-1"
|
||||
base_evidence = {
|
||||
base_ev_id: {
|
||||
"id": base_ev_id,
|
||||
"title": "Planet 全球自然灾害快照(disasters/snapshot)",
|
||||
"publisher": "USGS / NASA FIRMS / GDACS / NASA EONET",
|
||||
"url": "/api/v1/disasters/snapshot",
|
||||
"published_at": datetime.now(UTC).date().isoformat(),
|
||||
"locator": f"builtin:disasters:since={since_hours}h",
|
||||
}
|
||||
}
|
||||
if not hasattr(db, "execute"):
|
||||
return {
|
||||
"domain": "disasters",
|
||||
"available": False,
|
||||
"count": 0,
|
||||
"high_count": 0,
|
||||
"by_type": {},
|
||||
"events": [],
|
||||
"time_basis": time_basis,
|
||||
"cutoff_at": cutoff_at if time_basis == "as_known_then" else None,
|
||||
"evidence": base_evidence,
|
||||
"limitations": ["当前离线/无实时数据库会话,未读取自然灾害库。"],
|
||||
}
|
||||
|
||||
from app.models.disaster import DisasterEvent
|
||||
|
||||
cutoff = datetime.now(UTC) - timedelta(hours=max(1, int(since_hours)))
|
||||
stmt = (
|
||||
select(DisasterEvent)
|
||||
.where(DisasterEvent.observed_at >= cutoff, DisasterEvent.duplicate_of.is_(None))
|
||||
.order_by(desc(DisasterEvent.observed_at))
|
||||
.limit(max(20, min(int(limit or 200), 1000)))
|
||||
)
|
||||
if event_types:
|
||||
stmt = stmt.where(DisasterEvent.event_type.in_(event_types))
|
||||
|
||||
rows: list[DisasterEvent] = []
|
||||
try:
|
||||
rows = list((await db.execute(stmt)).scalars().all())
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Disaster posture query degraded",
|
||||
event="ai_tool.disaster_posture.degraded",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
|
||||
by_type: dict[str, int] = {}
|
||||
high_count = 0
|
||||
samples: list[dict[str, Any]] = []
|
||||
for row in rows:
|
||||
ev_t = str(row.event_type or "other")
|
||||
by_type[ev_t] = by_type.get(ev_t, 0) + 1
|
||||
if str(row.severity or "").lower() == "high":
|
||||
high_count += 1
|
||||
if len(samples) < 25:
|
||||
samples.append(row.to_dict())
|
||||
|
||||
return {
|
||||
"domain": "disasters",
|
||||
"available": bool(rows),
|
||||
"count": len(rows),
|
||||
"high_count": high_count,
|
||||
"by_type": by_type,
|
||||
"events": samples,
|
||||
"time_basis": time_basis,
|
||||
"cutoff_at": cutoff_at if time_basis == "as_known_then" else None,
|
||||
"evidence": base_evidence,
|
||||
"limitations": [] if rows else ["近72小时内暂无已去重的自然灾害告警记录。"],
|
||||
}
|
||||
|
||||
|
||||
async def query_ontology_neighborhood_tool(
|
||||
db: Any,
|
||||
*,
|
||||
object_id: str,
|
||||
depth: int = 1,
|
||||
radius_km: float = 150.0,
|
||||
time_basis: TimeBasis = "current",
|
||||
cutoff_at: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Read-only built-in ontology object & 1-2 hop neighborhood lookup tool."""
|
||||
from app.services.ai.entity_resolver import resolve_ontology_neighborhood
|
||||
|
||||
base_ev_id = "ev-ontology-1"
|
||||
evidence = {
|
||||
base_ev_id: {
|
||||
"id": base_ev_id,
|
||||
"title": f"Planet 联邦本体邻域图谱 ({object_id})",
|
||||
"publisher": "Planet Ontology Read-Time Resolver",
|
||||
"url": f"/api/v1/ontology/objects/{object_id}/neighborhood?depth={depth}",
|
||||
"published_at": datetime.now(UTC).date().isoformat(),
|
||||
"locator": f"ontology:{object_id}:depth={depth}",
|
||||
}
|
||||
}
|
||||
if not hasattr(db, "execute"):
|
||||
return {
|
||||
"domain": "ontology",
|
||||
"available": False,
|
||||
"object_id": object_id,
|
||||
"root": None,
|
||||
"nodes": [],
|
||||
"edges": [],
|
||||
"time_basis": time_basis,
|
||||
"cutoff_at": cutoff_at if time_basis == "as_known_then" else None,
|
||||
"evidence": evidence,
|
||||
"limitations": ["当前离线/无实时数据库会话,未能查询本体邻域。"],
|
||||
}
|
||||
result = await resolve_ontology_neighborhood(db, object_id, depth=depth, radius_km=radius_km)
|
||||
if result is None:
|
||||
return {
|
||||
"domain": "ontology",
|
||||
"available": False,
|
||||
"object_id": object_id,
|
||||
"root": None,
|
||||
"nodes": [],
|
||||
"edges": [],
|
||||
"time_basis": time_basis,
|
||||
"cutoff_at": cutoff_at if time_basis == "as_known_then" else None,
|
||||
"evidence": evidence,
|
||||
"limitations": [f"未在本体库中解析到对象 {object_id}。"],
|
||||
}
|
||||
return {
|
||||
"domain": "ontology",
|
||||
"available": True,
|
||||
"object_id": result["root"]["object_id"],
|
||||
"root": result["root"],
|
||||
"depth": result["depth"],
|
||||
"nodes": result["nodes"],
|
||||
"edges": result["edges"],
|
||||
"relation_sources": result["relation_sources"],
|
||||
"time_basis": time_basis,
|
||||
"cutoff_at": cutoff_at if time_basis == "as_known_then" else None,
|
||||
"evidence": evidence,
|
||||
"limitations": [],
|
||||
}
|
||||
@@ -69,6 +69,27 @@ TOOL_CATALOG: list[dict[str, Any]] = [
|
||||
"category": "internal_read",
|
||||
"description": "查询航运密度、关键海峡通道船只态势。",
|
||||
},
|
||||
{
|
||||
"id": "query_aircraft_posture",
|
||||
"name": "全球 ADS-B 空域航班快照",
|
||||
"name_en": "ADS-B Aircraft Airspace Snapshot",
|
||||
"category": "internal_read",
|
||||
"description": "按区域统计军机、紧急应答机与民航数量及重点空域态势。",
|
||||
},
|
||||
{
|
||||
"id": "query_gps_jamming_posture",
|
||||
"name": "GPS/GNSS 电子干扰区域快照",
|
||||
"name_en": "GPS/GNSS Interference Zones Snapshot",
|
||||
"category": "internal_read",
|
||||
"description": "查询日度 H3 高/中干扰区域分布与覆盖范围。",
|
||||
},
|
||||
{
|
||||
"id": "query_disaster_posture",
|
||||
"name": "全球自然灾害态势快照",
|
||||
"name_en": "Global Natural Disaster Snapshot",
|
||||
"category": "internal_read",
|
||||
"description": "查询地震、林火热点簇、气旋、洪水与火山等已去重多源灾害告警。",
|
||||
},
|
||||
{
|
||||
"id": "query_cloud_posture",
|
||||
"name": "全球实时红外云图与强对流分析",
|
||||
@@ -90,6 +111,13 @@ TOOL_CATALOG: list[dict[str, Any]] = [
|
||||
"category": "internal_read",
|
||||
"description": "检索全球近期已入库/汉化新闻头条与地理锚点。",
|
||||
},
|
||||
{
|
||||
"id": "query_ontology_neighborhood",
|
||||
"name": "联邦本体邻域图谱检索",
|
||||
"name_en": "Ontology Neighborhood Lookup",
|
||||
"category": "internal_read",
|
||||
"description": "按 `{type}:{id}` 读取时推导对象 1–2 跳拓扑/空间邻域与人工关系。",
|
||||
},
|
||||
{
|
||||
"id": "builds_upon_inherit",
|
||||
"name": "Epoch builds_upon 父集群继承",
|
||||
@@ -217,6 +245,8 @@ EARTH_ENTITY_TYPES: list[dict[str, str]] = [
|
||||
{"id": "landing_point", "name": "海缆登陆站", "name_en": "Landing Point", "group": "infrastructure"},
|
||||
{"id": "satellite", "name": "在轨卫星", "name_en": "Satellite", "group": "infrastructure"},
|
||||
{"id": "vessel", "name": "AIS 船舶", "name_en": "AIS Vessel", "group": "infrastructure"},
|
||||
{"id": "aircraft", "name": "ADS-B 航空器", "name_en": "ADS-B Aircraft", "group": "infrastructure"},
|
||||
{"id": "gps_jamming_cell", "name": "GPS 干扰单元", "name_en": "GPS Jamming Cell", "group": "infrastructure"},
|
||||
{"id": "bgp", "name": "BGP 异常事件", "name_en": "BGP Incident", "group": "infrastructure"},
|
||||
{"id": "bgp_collector", "name": "BGP 观测站", "name_en": "BGP Collector", "group": "infrastructure"},
|
||||
{"id": "supercomputer", "name": "超级计算机", "name_en": "Supercomputer", "group": "compute"},
|
||||
@@ -415,6 +445,8 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [
|
||||
"landing_point",
|
||||
"satellite",
|
||||
"vessel",
|
||||
"aircraft",
|
||||
"gps_jamming_cell",
|
||||
"bgp",
|
||||
"bgp_collector",
|
||||
"supercomputer",
|
||||
@@ -459,9 +491,9 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [
|
||||
140,
|
||||
description="结合本地记忆与系统遥测输出结构化研判;区分事实与推演。",
|
||||
prompt_key="situational.copilot.reply",
|
||||
system_prompt="你是智能星球(Planet)首席态势参谋。仅基于传入事实与工具证据作答,严谨区分确认事实、概率推断与待核验缺口。",
|
||||
system_prompt="你是智能星球(Planet)首席态势参谋。仅基于传入事实与工具证据作答,严谨区分确认事实、概率推断与待核验缺口。回答中必须单独列出情报盲区(blind_spots);凡新鲜度状态不是 fresh 的业务域,严禁描述为“无事件”或“态势平静”。",
|
||||
prompt="结合用户聚焦的地球空间上下文、历史记忆与工具数据,给出清晰、可执行、引用可追溯的专业中文分析(若用户使用英文则用英文)。",
|
||||
tools=["query_global_situational", "query_compute_posture", "query_bgp_incidents", "query_recent_earth_news", "web_search"],
|
||||
tools=["query_global_situational", "query_compute_posture", "query_bgp_incidents", "query_aircraft_posture", "query_gps_jamming_posture", "query_recent_earth_news", "web_search"],
|
||||
thinking_enabled=True,
|
||||
max_steps=3,
|
||||
timeout_seconds=60,
|
||||
@@ -782,7 +814,7 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [
|
||||
"bindings": {
|
||||
"enabled": True,
|
||||
"surfaces": ["info_card", "multi_select", "copilot_quick"],
|
||||
"entity_types": ["cable", "landing_point", "bgp", "vessel", "satellite", "global"],
|
||||
"entity_types": ["cable", "landing_point", "bgp", "vessel", "aircraft", "gps_jamming_cell", "satellite", "global"],
|
||||
"action_label": "多域兵棋推演",
|
||||
"action_label_en": "Multi-Domain Wargame",
|
||||
"icon": "hub",
|
||||
@@ -798,7 +830,7 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [
|
||||
"Isolated Domain Snapshots",
|
||||
420,
|
||||
140,
|
||||
tools=["query_bgp_incidents", "query_cable_posture", "query_satellite_posture", "query_vessel_posture"],
|
||||
tools=["query_bgp_incidents", "query_cable_posture", "query_satellite_posture", "query_vessel_posture", "query_aircraft_posture", "query_gps_jamming_posture"],
|
||||
),
|
||||
_node(
|
||||
"wg_investigator",
|
||||
@@ -808,9 +840,9 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [
|
||||
800,
|
||||
140,
|
||||
prompt_key="incident.investigator.brief",
|
||||
system_prompt="你是全球互联网与海缆基础设施取证参谋。严格区分 confirmed_facts、candidate_explanations、counter_evidence 与 open_gaps;无独立海缆告警证据时严禁将地理邻近推断为物理断缆。",
|
||||
system_prompt="你是全球互联网与海缆基础设施取证参谋。严格区分 confirmed_facts、candidate_explanations、counter_evidence 与 open_gaps;无独立海缆告警证据时严禁将地理邻近推断为物理断缆。必须在 open_gaps 中列出当前情报盲区(blind_spots),任何新鲜度状态非 fresh 的域不得描述为“无事件”。",
|
||||
prompt="结合内部多域快照与受控外部取证槽位,生成结构化事件研判 JSON 与地球高亮实体。",
|
||||
tools=["query_bgp_incidents", "query_cable_posture", "query_satellite_posture", "query_vessel_posture", "web_search", "safe_web_fetch"],
|
||||
tools=["query_bgp_incidents", "query_cable_posture", "query_satellite_posture", "query_vessel_posture", "query_aircraft_posture", "query_gps_jamming_posture", "web_search", "safe_web_fetch"],
|
||||
thinking_enabled=True,
|
||||
max_steps=3,
|
||||
guardrails={"disallow_unverified_cable_cut": True},
|
||||
@@ -1028,6 +1060,109 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
"workflow_id": "wargame.cable_protection",
|
||||
"name": "海缆安全护卫兵棋工作流",
|
||||
"name_en": "Subsea Cable Protection Wargame",
|
||||
"category": "wargame",
|
||||
"description": "综合海缆路径、走廊船舶徘徊、NGA 航行警告、BGP 路由与本体拓扑,严格区分待核查关联与独立证据支撑的依赖影响链。",
|
||||
"description_en": "Correlates subsea cables, vessel loitering, NGA warnings, BGP events, and ontology topology to distinguish candidate correlations from corroborated dependency impact chains.",
|
||||
"is_default": False,
|
||||
"graph": {
|
||||
"nodes": [
|
||||
_node("cable_wg_trig", "trigger", "走廊告警入口", "Corridor Trigger", 40, 140),
|
||||
_node(
|
||||
"cable_wg_fetch",
|
||||
"deterministic",
|
||||
"读取海缆/船舶/NGA/BGP 与本体邻域",
|
||||
"Fetch Cable, Vessel, NGA, BGP & Ontology",
|
||||
380,
|
||||
140,
|
||||
tools=[
|
||||
"query_cable_posture",
|
||||
"query_vessel_posture",
|
||||
"query_bgp_incidents",
|
||||
"query_ontology_neighborhood",
|
||||
"query_global_situational",
|
||||
],
|
||||
),
|
||||
_node(
|
||||
"cable_wg_analyst",
|
||||
"llm_agent",
|
||||
"证据分级与影响链研判",
|
||||
"Evidence Tier & Impact Analysis",
|
||||
720,
|
||||
140,
|
||||
system_prompt=(
|
||||
"你是海缆安全护卫推演专家。规则:"
|
||||
"1) 只有邻近船舶与同时段异常、缺少独立 NGA 航行警告或运营方/直接 BGP 断链证据时,严格定性为“待核查关联”,严禁断言因果;"
|
||||
"2) 仅当存在独立 NGA 警告、运营方通告或直接 BGP 证据时才升级为“依赖影响”,并列出受影响国家、算力中心及备用海缆;"
|
||||
"3) 必须明确列出 `blind_spots` 情报盲区;结尾附 <planet_scene> 输出 spatial_cards 与 overlays。"
|
||||
),
|
||||
prompt="结合多域证据输出海缆护卫推演结论、影响清单、盲区及空间卡片。",
|
||||
thinking_enabled=True,
|
||||
),
|
||||
_node("cable_wg_out", "output", "推演结论与演播", "Briefing & Presentation", 1060, 140),
|
||||
],
|
||||
"edges": [
|
||||
_edge("cw-e1", "cable_wg_trig", "cable_wg_fetch"),
|
||||
_edge("cw-e2", "cable_wg_fetch", "cable_wg_analyst"),
|
||||
_edge("cw-e3", "cable_wg_analyst", "cable_wg_out"),
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
"workflow_id": "wargame.air_sea_em",
|
||||
"name": "空海电磁联合态势工作流",
|
||||
"name_en": "Air-Sea Electromagnetic Joint Posture",
|
||||
"category": "wargame",
|
||||
"description": "聚合空域军机/紧急应答机、GPS/GNSS 干扰热区、咽喉要道舰艇、自然灾害与分级新闻,生成无因果越界的多域空间对比卡片与盲区简报。",
|
||||
"description_en": "Aggregates military/emergency aircraft, GNSS jamming cells, chokepoint vessels, disasters, and tiered news into non-causal multi-domain spatial cards and blind-spot briefings.",
|
||||
"is_default": False,
|
||||
"graph": {
|
||||
"nodes": [
|
||||
_node("em_wg_trig", "trigger", "空海电磁网格触发", "H3 Convergence Trigger", 40, 140),
|
||||
_node(
|
||||
"em_wg_fetch",
|
||||
"deterministic",
|
||||
"采集空海电磁与本体上下文",
|
||||
"Collect Air-Sea-EM & Ontology Context",
|
||||
380,
|
||||
140,
|
||||
tools=[
|
||||
"query_aircraft_posture",
|
||||
"query_gps_jamming_posture",
|
||||
"query_vessel_posture",
|
||||
"query_disaster_posture",
|
||||
"query_recent_earth_news",
|
||||
"query_global_situational",
|
||||
],
|
||||
),
|
||||
_node(
|
||||
"em_wg_analyst",
|
||||
"llm_agent",
|
||||
"无因果约束联合简报生成",
|
||||
"Non-Causal Joint Briefing",
|
||||
720,
|
||||
140,
|
||||
system_prompt=(
|
||||
"你是空海电磁联合态势推演专家。必须严格遵守:"
|
||||
"1) 多域并存默认定性为“待核查关联”,严禁将空间巧合写成“导致/引发/袭击”;"
|
||||
"2) 必须显式列出所有非 fresh 数据域作为情报盲区(`blind_spots`),非 fresh 域不得称为无事件;"
|
||||
"3) 新闻引用按可信度分级排序并标注国家背景;结尾输出含 spatial_cards 与 overlays 的 <planet_scene>。"
|
||||
),
|
||||
prompt="汇总区域多域目标与盲区,输出对比卡片与空海电磁简报。",
|
||||
thinking_enabled=True,
|
||||
),
|
||||
_node("em_wg_out", "output", "态势输出", "Posture Output", 1060, 140),
|
||||
],
|
||||
"edges": [
|
||||
_edge("ew-e1", "em_wg_trig", "em_wg_fetch"),
|
||||
_edge("ew-e2", "em_wg_fetch", "em_wg_analyst"),
|
||||
_edge("ew-e3", "em_wg_analyst", "em_wg_out"),
|
||||
],
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
_BUILTIN_BY_ID: dict[str, dict[str, Any]] = {
|
||||
|
||||
@@ -0,0 +1,430 @@
|
||||
"""Multi-source aircraft state merge, downsampled 24h track logging, pruning, and health updates."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime, timedelta
|
||||
import math
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import delete, func, select
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.logging import get_logger
|
||||
from app.models.aircraft import (
|
||||
ADSBSourceHealth,
|
||||
AircraftCurrentState,
|
||||
AircraftPosition,
|
||||
AircraftStatic,
|
||||
)
|
||||
from app.services.aircraft_types import classify_aircraft, normalize_icao24
|
||||
|
||||
logger = get_logger(__name__, service="aircraft_aggregation")
|
||||
|
||||
DEFAULT_CURRENT_STALE_MINUTES = 15
|
||||
DEFAULT_POSITION_RETENTION_HOURS = 24
|
||||
TRACK_MIN_INTERVAL_SECONDS = 30.0
|
||||
TRACK_MIN_HEADING_DELTA_DEG = 10.0
|
||||
TRACK_MIN_ALTITUDE_DELTA_M = 300.0
|
||||
SQL_BATCH_SIZE = 500
|
||||
|
||||
|
||||
def coerce_utc_datetime(value: Any, fallback: datetime | None = None) -> datetime:
|
||||
"""Convert Unix seconds, ISO strings, or naive datetimes to aware UTC datetimes."""
|
||||
if isinstance(value, datetime):
|
||||
return value.astimezone(UTC) if value.tzinfo else value.replace(tzinfo=UTC)
|
||||
if isinstance(value, (int, float)) and math.isfinite(float(value)):
|
||||
return datetime.fromtimestamp(float(value), tz=UTC)
|
||||
if isinstance(value, str):
|
||||
raw = value.strip()
|
||||
if raw:
|
||||
try:
|
||||
return datetime.fromtimestamp(float(raw), tz=UTC)
|
||||
except ValueError:
|
||||
pass
|
||||
try:
|
||||
parsed = datetime.fromisoformat(raw.replace("Z", "+00:00"))
|
||||
return parsed.astimezone(UTC) if parsed.tzinfo else parsed.replace(tzinfo=UTC)
|
||||
except ValueError:
|
||||
pass
|
||||
return fallback or datetime.now(UTC)
|
||||
|
||||
|
||||
def wrapped_angle_diff_deg(a: float | None, b: float | None) -> float:
|
||||
"""Smallest angular difference on a 360-degree circle."""
|
||||
if a is None or b is None or not (math.isfinite(a) and math.isfinite(b)):
|
||||
return 0.0
|
||||
diff = abs(float(a) - float(b)) % 360.0
|
||||
return 360.0 - diff if diff > 180.0 else diff
|
||||
|
||||
|
||||
def should_record_aircraft_track_point(
|
||||
previous: dict[str, Any] | None,
|
||||
*,
|
||||
observed_at: datetime,
|
||||
altitude_m: float | None,
|
||||
track_deg: float | None,
|
||||
) -> bool:
|
||||
"""Return True if a track sample exceeds 30s, 10 deg heading change, or 300m altitude delta."""
|
||||
if previous is None:
|
||||
return True
|
||||
prev_time = coerce_utc_datetime(previous.get("observed_at"))
|
||||
if abs((observed_at - prev_time).total_seconds()) >= TRACK_MIN_INTERVAL_SECONDS:
|
||||
return True
|
||||
if wrapped_angle_diff_deg(track_deg, previous.get("track_deg")) > TRACK_MIN_HEADING_DELTA_DEG:
|
||||
return True
|
||||
prev_alt = previous.get("altitude_m")
|
||||
if altitude_m is not None and prev_alt is not None:
|
||||
if abs(float(altitude_m) - float(prev_alt)) > TRACK_MIN_ALTITUDE_DELTA_M:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _source_priority(source: str) -> int:
|
||||
normalized = str(source or "").strip().lower()
|
||||
if "adsb_lol" in normalized:
|
||||
return 2
|
||||
return 1
|
||||
|
||||
|
||||
def _should_replace_existing(
|
||||
existing: dict[str, Any],
|
||||
incoming: dict[str, Any],
|
||||
) -> bool:
|
||||
ext_obs = coerce_utc_datetime(existing["observed_at"])
|
||||
inc_obs = coerce_utc_datetime(incoming["observed_at"])
|
||||
if inc_obs > ext_obs:
|
||||
return True
|
||||
if inc_obs < ext_obs:
|
||||
return False
|
||||
return _source_priority(incoming["source"]) >= _source_priority(existing["source"])
|
||||
|
||||
|
||||
async def _load_static_metadata_map(
|
||||
db: AsyncSession,
|
||||
icao24s: list[str],
|
||||
) -> dict[str, AircraftStatic]:
|
||||
if not icao24s:
|
||||
return {}
|
||||
mapping: dict[str, AircraftStatic] = {}
|
||||
for offset in range(0, len(icao24s), SQL_BATCH_SIZE):
|
||||
chunk = icao24s[offset : offset + SQL_BATCH_SIZE]
|
||||
res = await db.execute(select(AircraftStatic).where(AircraftStatic.icao24.in_(chunk)))
|
||||
for row in res.scalars().all():
|
||||
mapping[row.icao24] = row
|
||||
return mapping
|
||||
|
||||
|
||||
async def _load_existing_current_map(
|
||||
db: AsyncSession,
|
||||
icao24s: list[str],
|
||||
) -> dict[str, dict[str, Any]]:
|
||||
if not icao24s:
|
||||
return {}
|
||||
mapping: dict[str, dict[str, Any]] = {}
|
||||
for offset in range(0, len(icao24s), SQL_BATCH_SIZE):
|
||||
chunk = icao24s[offset : offset + SQL_BATCH_SIZE]
|
||||
res = await db.execute(
|
||||
select(AircraftCurrentState).where(AircraftCurrentState.icao24.in_(chunk))
|
||||
)
|
||||
for row in res.scalars().all():
|
||||
mapping[row.icao24] = {
|
||||
"observed_at": coerce_utc_datetime(row.observed_at),
|
||||
"source": row.source,
|
||||
"is_military": bool(row.is_military),
|
||||
"category": row.category,
|
||||
}
|
||||
return mapping
|
||||
|
||||
|
||||
async def _load_latest_position_map(
|
||||
db: AsyncSession,
|
||||
icao24s: list[str],
|
||||
) -> dict[str, dict[str, Any]]:
|
||||
"""Fetch the most recent aircraft_position sample per icao24 for downsampling checks."""
|
||||
if not icao24s:
|
||||
return {}
|
||||
mapping: dict[str, dict[str, Any]] = {}
|
||||
for offset in range(0, len(icao24s), SQL_BATCH_SIZE):
|
||||
chunk = icao24s[offset : offset + SQL_BATCH_SIZE]
|
||||
subq = (
|
||||
select(
|
||||
AircraftPosition.icao24,
|
||||
func.max(AircraftPosition.observed_at).label("max_obs"),
|
||||
)
|
||||
.where(AircraftPosition.icao24.in_(chunk))
|
||||
.group_by(AircraftPosition.icao24)
|
||||
.subquery()
|
||||
)
|
||||
stmt = select(AircraftPosition).join(
|
||||
subq,
|
||||
(AircraftPosition.icao24 == subq.c.icao24)
|
||||
& (AircraftPosition.observed_at == subq.c.max_obs),
|
||||
)
|
||||
res = await db.execute(stmt)
|
||||
for row in res.scalars().all():
|
||||
mapping[row.icao24] = {
|
||||
"observed_at": coerce_utc_datetime(row.observed_at),
|
||||
"altitude_m": row.altitude_m,
|
||||
"track_deg": row.track_deg,
|
||||
}
|
||||
return mapping
|
||||
|
||||
|
||||
async def upsert_aircraft_observations(
|
||||
db: AsyncSession,
|
||||
observations: list[dict[str, Any]],
|
||||
*,
|
||||
default_source: str,
|
||||
ingested_at: datetime | None = None,
|
||||
) -> dict[str, int]:
|
||||
"""Merge multi-source aircraft observations into aircraft_current_state and downsampled aircraft_position."""
|
||||
if not observations:
|
||||
return {"states_upserted": 0, "positions_inserted": 0}
|
||||
|
||||
now = coerce_utc_datetime(ingested_at) if ingested_at else datetime.now(UTC)
|
||||
deduped: dict[str, dict[str, Any]] = {}
|
||||
for raw in observations:
|
||||
icao24 = normalize_icao24(raw.get("icao24"))
|
||||
lat = raw.get("lat")
|
||||
lon = raw.get("lon")
|
||||
if len(icao24) != 6 or lat is None or lon is None:
|
||||
continue
|
||||
try:
|
||||
lat_f = float(lat)
|
||||
lon_f = float(lon)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if not (-90.0 <= lat_f <= 90.0 and -180.0 <= lon_f <= 180.0):
|
||||
continue
|
||||
|
||||
src = str(raw.get("source") or default_source).strip() or default_source
|
||||
obs_at = coerce_utc_datetime(raw.get("observed_at"), fallback=now)
|
||||
candidate = {
|
||||
"icao24": icao24,
|
||||
"callsign": (str(raw.get("callsign") or "").strip().upper()[:16] or None),
|
||||
"lat": lat_f,
|
||||
"lon": lon_f,
|
||||
"baro_altitude_m": raw.get("baro_altitude_m"),
|
||||
"geo_altitude_m": raw.get("geo_altitude_m"),
|
||||
"ground_speed_ms": raw.get("ground_speed_ms"),
|
||||
"track_deg": raw.get("track_deg"),
|
||||
"vertical_rate_ms": raw.get("vertical_rate_ms"),
|
||||
"squawk": (str(raw.get("squawk") or "").strip()[:8] or None),
|
||||
"on_ground": bool(raw.get("on_ground", False)),
|
||||
"adsb_category": raw.get("adsb_category"),
|
||||
"aircraft_type": raw.get("aircraft_type"),
|
||||
"db_flags": raw.get("db_flags"),
|
||||
"source_is_military": bool(raw.get("source_is_military", False)),
|
||||
"source": src,
|
||||
"observed_at": obs_at,
|
||||
}
|
||||
prior = deduped.get(icao24)
|
||||
if prior is None:
|
||||
deduped[icao24] = candidate
|
||||
else:
|
||||
if _should_replace_existing(prior, candidate):
|
||||
candidate["source_is_military"] = bool(
|
||||
candidate["source_is_military"] or prior["source_is_military"]
|
||||
)
|
||||
deduped[icao24] = candidate
|
||||
else:
|
||||
prior["source_is_military"] = bool(
|
||||
prior["source_is_military"] or candidate["source_is_military"]
|
||||
)
|
||||
|
||||
if not deduped:
|
||||
return {"states_upserted": 0, "positions_inserted": 0}
|
||||
|
||||
icao_list = list(deduped.keys())
|
||||
static_map = await _load_static_metadata_map(db, icao_list)
|
||||
existing_map = await _load_existing_current_map(db, icao_list)
|
||||
latest_pos_map = await _load_latest_position_map(db, icao_list)
|
||||
|
||||
upsert_rows: list[dict[str, Any]] = []
|
||||
position_rows: list[dict[str, Any]] = []
|
||||
|
||||
for icao24, item in deduped.items():
|
||||
static_rec = static_map.get(icao24)
|
||||
existing = existing_map.get(icao24)
|
||||
preserved_mil = bool(existing and existing.get("is_military"))
|
||||
cls = classify_aircraft(
|
||||
icao24=icao24,
|
||||
callsign=item["callsign"],
|
||||
squawk=item["squawk"],
|
||||
aircraft_type=item.get("aircraft_type") or (static_rec.aircraft_type if static_rec else None),
|
||||
adsb_category=item.get("adsb_category"),
|
||||
db_flags=item.get("db_flags"),
|
||||
static_is_military=bool(static_rec and static_rec.is_military) or preserved_mil,
|
||||
static_category=static_rec.category if static_rec else None,
|
||||
source_is_military_feed=bool(item.get("source_is_military")),
|
||||
)
|
||||
|
||||
# Even if DB has newer observed_at from another source, never lose military marker from adsb.lol.
|
||||
if existing and not _should_replace_existing(existing, item):
|
||||
continue
|
||||
|
||||
row_payload = {
|
||||
"icao24": icao24,
|
||||
"callsign": item["callsign"],
|
||||
"lat": item["lat"],
|
||||
"lon": item["lon"],
|
||||
"baro_altitude_m": item["baro_altitude_m"],
|
||||
"geo_altitude_m": item["geo_altitude_m"],
|
||||
"ground_speed_ms": item["ground_speed_ms"],
|
||||
"track_deg": item["track_deg"],
|
||||
"vertical_rate_ms": item["vertical_rate_ms"],
|
||||
"squawk": item["squawk"],
|
||||
"on_ground": item["on_ground"],
|
||||
"category": str(cls["category"]),
|
||||
"is_military": bool(cls["is_military"]),
|
||||
"is_emergency": bool(cls["is_emergency"]),
|
||||
"emergency_code": cls["emergency_code"],
|
||||
"source": item["source"],
|
||||
"observed_at": item["observed_at"],
|
||||
"ingested_at": now,
|
||||
}
|
||||
upsert_rows.append(row_payload)
|
||||
|
||||
alt_m = (
|
||||
item["geo_altitude_m"]
|
||||
if item["geo_altitude_m"] is not None
|
||||
else item["baro_altitude_m"]
|
||||
)
|
||||
prev_pos = latest_pos_map.get(icao24)
|
||||
if should_record_aircraft_track_point(
|
||||
prev_pos,
|
||||
observed_at=item["observed_at"],
|
||||
altitude_m=alt_m,
|
||||
track_deg=item["track_deg"],
|
||||
):
|
||||
position_rows.append(
|
||||
{
|
||||
"icao24": icao24,
|
||||
"lat": item["lat"],
|
||||
"lon": item["lon"],
|
||||
"altitude_m": alt_m,
|
||||
"ground_speed_ms": item["ground_speed_ms"],
|
||||
"track_deg": item["track_deg"],
|
||||
"observed_at": item["observed_at"],
|
||||
}
|
||||
)
|
||||
|
||||
dialect = getattr(getattr(db.get_bind(), "dialect", None), "name", "sqlite")
|
||||
for offset in range(0, len(upsert_rows), SQL_BATCH_SIZE):
|
||||
batch = upsert_rows[offset : offset + SQL_BATCH_SIZE]
|
||||
if dialect == "postgresql":
|
||||
stmt = pg_insert(AircraftCurrentState).values(batch)
|
||||
stmt = stmt.on_conflict_do_update(
|
||||
index_elements=[AircraftCurrentState.icao24],
|
||||
set_={
|
||||
"callsign": stmt.excluded.callsign,
|
||||
"lat": stmt.excluded.lat,
|
||||
"lon": stmt.excluded.lon,
|
||||
"baro_altitude_m": stmt.excluded.baro_altitude_m,
|
||||
"geo_altitude_m": stmt.excluded.geo_altitude_m,
|
||||
"ground_speed_ms": stmt.excluded.ground_speed_ms,
|
||||
"track_deg": stmt.excluded.track_deg,
|
||||
"vertical_rate_ms": stmt.excluded.vertical_rate_ms,
|
||||
"squawk": stmt.excluded.squawk,
|
||||
"on_ground": stmt.excluded.on_ground,
|
||||
"category": stmt.excluded.category,
|
||||
"is_military": stmt.excluded.is_military,
|
||||
"is_emergency": stmt.excluded.is_emergency,
|
||||
"emergency_code": stmt.excluded.emergency_code,
|
||||
"source": stmt.excluded.source,
|
||||
"observed_at": stmt.excluded.observed_at,
|
||||
"ingested_at": stmt.excluded.ingested_at,
|
||||
},
|
||||
)
|
||||
await db.execute(stmt)
|
||||
else:
|
||||
stmt_sq = sqlite_insert(AircraftCurrentState).values(batch)
|
||||
stmt_sq = stmt_sq.on_conflict_do_update(
|
||||
index_elements=[AircraftCurrentState.icao24],
|
||||
set_={
|
||||
"callsign": stmt_sq.excluded.callsign,
|
||||
"lat": stmt_sq.excluded.lat,
|
||||
"lon": stmt_sq.excluded.lon,
|
||||
"baro_altitude_m": stmt_sq.excluded.baro_altitude_m,
|
||||
"geo_altitude_m": stmt_sq.excluded.geo_altitude_m,
|
||||
"ground_speed_ms": stmt_sq.excluded.ground_speed_ms,
|
||||
"track_deg": stmt_sq.excluded.track_deg,
|
||||
"vertical_rate_ms": stmt_sq.excluded.vertical_rate_ms,
|
||||
"squawk": stmt_sq.excluded.squawk,
|
||||
"on_ground": stmt_sq.excluded.on_ground,
|
||||
"category": stmt_sq.excluded.category,
|
||||
"is_military": stmt_sq.excluded.is_military,
|
||||
"is_emergency": stmt_sq.excluded.is_emergency,
|
||||
"emergency_code": stmt_sq.excluded.emergency_code,
|
||||
"source": stmt_sq.excluded.source,
|
||||
"observed_at": stmt_sq.excluded.observed_at,
|
||||
"ingested_at": stmt_sq.excluded.ingested_at,
|
||||
},
|
||||
)
|
||||
await db.execute(stmt_sq)
|
||||
|
||||
for offset in range(0, len(position_rows), SQL_BATCH_SIZE):
|
||||
batch = position_rows[offset : offset + SQL_BATCH_SIZE]
|
||||
await db.execute(AircraftPosition.__table__.insert().values(batch))
|
||||
|
||||
return {
|
||||
"states_upserted": len(upsert_rows),
|
||||
"positions_inserted": len(position_rows),
|
||||
}
|
||||
|
||||
|
||||
async def prune_aircraft_tables(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
current_stale_minutes: int = DEFAULT_CURRENT_STALE_MINUTES,
|
||||
position_retention_hours: int = DEFAULT_POSITION_RETENTION_HOURS,
|
||||
now: datetime | None = None,
|
||||
) -> dict[str, int]:
|
||||
"""Delete expired current aircraft (>15m) and expired track history (>24h default)."""
|
||||
ref = coerce_utc_datetime(now) if now else datetime.now(UTC)
|
||||
current_cutoff = ref - timedelta(minutes=max(1, int(current_stale_minutes)))
|
||||
pos_cutoff = ref - timedelta(hours=max(1, int(position_retention_hours)))
|
||||
|
||||
curr_res = await db.execute(
|
||||
delete(AircraftCurrentState).where(AircraftCurrentState.observed_at < current_cutoff)
|
||||
)
|
||||
pos_res = await db.execute(
|
||||
delete(AircraftPosition).where(AircraftPosition.observed_at < pos_cutoff)
|
||||
)
|
||||
return {
|
||||
"current_deleted": int(curr_res.rowcount or 0),
|
||||
"positions_deleted": int(pos_res.rowcount or 0),
|
||||
}
|
||||
|
||||
|
||||
async def update_adsb_source_health(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
source: str,
|
||||
connection_state: str,
|
||||
active_count: int = 0,
|
||||
last_success_at: datetime | None = None,
|
||||
last_error: str | None = None,
|
||||
cooldown_until: datetime | None = None,
|
||||
clear_cooldown: bool = False,
|
||||
) -> ADSBSourceHealth:
|
||||
"""Upsert runtime ADS-B health status and optional cooldown timestamp."""
|
||||
now = datetime.now(UTC)
|
||||
record = await db.get(ADSBSourceHealth, source)
|
||||
if record is None:
|
||||
record = ADSBSourceHealth(source=source)
|
||||
db.add(record)
|
||||
|
||||
record.connection_state = connection_state
|
||||
record.active_count = max(0, int(active_count))
|
||||
if last_success_at is not None:
|
||||
record.last_success_at = coerce_utc_datetime(last_success_at)
|
||||
record.last_error = last_error[:500] if last_error else None
|
||||
if clear_cooldown:
|
||||
record.cooldown_until = None
|
||||
elif cooldown_until is not None:
|
||||
record.cooldown_until = coerce_utc_datetime(cooldown_until)
|
||||
record.updated_at = now
|
||||
return record
|
||||
@@ -0,0 +1,319 @@
|
||||
"""Open ICAO24 aircraft registry downloader, parser, and offline cache manager (Source 42)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import csv
|
||||
from datetime import UTC, datetime
|
||||
import gzip
|
||||
import io
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.config import ROOT_DIR
|
||||
from app.core.data_sources import get_data_sources_config
|
||||
from app.core.logging import get_logger
|
||||
from app.models.aircraft import AircraftStatic
|
||||
from app.services.aircraft_types import classify_aircraft, normalize_icao24
|
||||
|
||||
logger = get_logger(__name__, service="aircraft_registry")
|
||||
|
||||
MAX_REGISTRY_BYTES = 200 * 1024 * 1024 # safety ceiling for remote CSV/CSV.GZ downloads
|
||||
UPSERT_BATCH_SIZE = 1000
|
||||
|
||||
|
||||
def get_aircraft_registry_cache_dir(configured_dir: str | None = None) -> Path:
|
||||
"""Resolve configurable local directory for cached ICAO24 registry CSVs."""
|
||||
raw = str(configured_dir or os.getenv("PLANET_AIRCRAFT_REGISTRY_DIR") or "").strip()
|
||||
if raw:
|
||||
path = Path(raw)
|
||||
else:
|
||||
path = ROOT_DIR / "data" / "aircraft_registry"
|
||||
return path
|
||||
|
||||
|
||||
def _clean_text(value: Any, max_len: int) -> str | None:
|
||||
text = str(value or "").strip()
|
||||
if not text or text.lower() in {"nan", "null", "none", "n/a"}:
|
||||
return None
|
||||
return text[:max_len]
|
||||
|
||||
|
||||
def _pick_header(fieldnames: list[str], *candidates: str) -> str | None:
|
||||
lowered = {name.strip().lower(): name for name in fieldnames if name}
|
||||
for cand in candidates:
|
||||
matched = lowered.get(cand.lower())
|
||||
if matched:
|
||||
return matched
|
||||
return None
|
||||
|
||||
|
||||
def parse_aircraft_registry_csv(text: str, *, max_rows: int | None = None) -> list[dict[str, Any]]:
|
||||
"""Parse OpenSky aircraft database CSV or tar1090 semicolon CSV into normalized records."""
|
||||
cleaned = text.lstrip("\ufeff")
|
||||
if not cleaned.strip():
|
||||
return []
|
||||
|
||||
first_line = next((line for line in cleaned.splitlines() if line.strip()), "")
|
||||
delimiter = ";" if first_line.count(";") > first_line.count(",") else ","
|
||||
records: list[dict[str, Any]] = []
|
||||
|
||||
if delimiter == ";" and "icao" not in first_line.lower():
|
||||
# Headerless tar1090 CSV format: icao24;reg;typecode;flags;description;year;...
|
||||
reader = csv.reader(io.StringIO(cleaned), delimiter=";")
|
||||
for row in reader:
|
||||
if not row or len(row) < 3:
|
||||
continue
|
||||
icao24 = normalize_icao24(row[0])
|
||||
if len(icao24) != 6:
|
||||
continue
|
||||
reg = _clean_text(row[1] if len(row) > 1 else None, 32)
|
||||
typecode = _clean_text(row[2] if len(row) > 2 else None, 16)
|
||||
flags_raw = row[3].strip() if len(row) > 3 else ""
|
||||
try:
|
||||
db_flags = int(flags_raw) if flags_raw else 0
|
||||
except ValueError:
|
||||
db_flags = 0
|
||||
desc = _clean_text(row[4] if len(row) > 4 else None, 128)
|
||||
cls = classify_aircraft(icao24=icao24, aircraft_type=typecode, db_flags=db_flags)
|
||||
records.append(
|
||||
{
|
||||
"icao24": icao24,
|
||||
"registration": reg,
|
||||
"aircraft_type": typecode,
|
||||
"type_description": desc,
|
||||
"operator": None,
|
||||
"owner": None,
|
||||
"origin_country": None,
|
||||
"category": cls["category"],
|
||||
"is_military": bool(cls["is_military"]),
|
||||
"source": "aircraft_registry",
|
||||
}
|
||||
)
|
||||
if max_rows is not None and len(records) >= max_rows:
|
||||
break
|
||||
return records
|
||||
|
||||
dict_reader = csv.DictReader(io.StringIO(cleaned), delimiter=delimiter)
|
||||
fieldnames = list(dict_reader.fieldnames or [])
|
||||
if not fieldnames:
|
||||
return []
|
||||
|
||||
col_icao = _pick_header(fieldnames, "icao24", "icao", "hex")
|
||||
if not col_icao:
|
||||
return []
|
||||
col_reg = _pick_header(fieldnames, "registration", "reg")
|
||||
col_type = _pick_header(fieldnames, "typecode", "aircraft_type", "icaoaircrafttype", "t")
|
||||
col_desc = _pick_header(fieldnames, "model", "type_description", "desc", "categorydescription")
|
||||
col_op = _pick_header(fieldnames, "operator", "operatoricao", "operatorcallsign", "ownop")
|
||||
col_owner = _pick_header(fieldnames, "owner", "registeredowners")
|
||||
col_country = _pick_header(fieldnames, "country", "origin_country")
|
||||
col_flags = _pick_header(fieldnames, "dbflags", "flags", "mil")
|
||||
|
||||
for row in dict_reader:
|
||||
icao24 = normalize_icao24(row.get(col_icao))
|
||||
if len(icao24) != 6:
|
||||
continue
|
||||
typecode = _clean_text(row.get(col_type) if col_type else None, 16)
|
||||
raw_flags = str(row.get(col_flags) or "").strip() if col_flags else ""
|
||||
try:
|
||||
db_flags = int(raw_flags) if raw_flags else 0
|
||||
except ValueError:
|
||||
db_flags = 1 if raw_flags.lower() in {"true", "yes", "mil", "military"} else 0
|
||||
|
||||
cls = classify_aircraft(icao24=icao24, aircraft_type=typecode, db_flags=db_flags)
|
||||
records.append(
|
||||
{
|
||||
"icao24": icao24,
|
||||
"registration": _clean_text(row.get(col_reg) if col_reg else None, 32),
|
||||
"aircraft_type": typecode,
|
||||
"type_description": _clean_text(row.get(col_desc) if col_desc else None, 128),
|
||||
"operator": _clean_text(row.get(col_op) if col_op else None, 128),
|
||||
"owner": _clean_text(row.get(col_owner) if col_owner else None, 128),
|
||||
"origin_country": _clean_text(row.get(col_country) if col_country else None, 64),
|
||||
"category": cls["category"],
|
||||
"is_military": bool(cls["is_military"]),
|
||||
"source": "aircraft_registry",
|
||||
}
|
||||
)
|
||||
if max_rows is not None and len(records) >= max_rows:
|
||||
break
|
||||
return records
|
||||
|
||||
|
||||
def decode_registry_payload(raw_bytes: bytes, source_url: str = "") -> str:
|
||||
"""Decompress gzipped CSV when applicable and decode UTF-8 safely."""
|
||||
if source_url.lower().endswith(".gz") or raw_bytes[:2] == b"\x1f\x8b":
|
||||
raw_bytes = gzip.decompress(raw_bytes)
|
||||
return raw_bytes.decode("utf-8", errors="replace")
|
||||
|
||||
|
||||
async def upsert_aircraft_static_records(
|
||||
db: AsyncSession,
|
||||
records: list[dict[str, Any]],
|
||||
) -> int:
|
||||
"""Upsert parsed aircraft_static metadata rows in batches."""
|
||||
if not records:
|
||||
return 0
|
||||
|
||||
now = datetime.now(UTC)
|
||||
dialect = getattr(getattr(db.get_bind(), "dialect", None), "name", "sqlite")
|
||||
written = 0
|
||||
|
||||
for offset in range(0, len(records), UPSERT_BATCH_SIZE):
|
||||
batch = []
|
||||
for item in records[offset : offset + UPSERT_BATCH_SIZE]:
|
||||
batch.append(
|
||||
{
|
||||
"icao24": item["icao24"],
|
||||
"registration": item.get("registration"),
|
||||
"aircraft_type": item.get("aircraft_type"),
|
||||
"type_description": item.get("type_description"),
|
||||
"operator": item.get("operator"),
|
||||
"owner": item.get("owner"),
|
||||
"origin_country": item.get("origin_country"),
|
||||
"category": item.get("category") or "other",
|
||||
"is_military": bool(item.get("is_military", False)),
|
||||
"source": item.get("source") or "aircraft_registry",
|
||||
"updated_at": now,
|
||||
}
|
||||
)
|
||||
if not batch:
|
||||
continue
|
||||
if dialect == "postgresql":
|
||||
stmt = pg_insert(AircraftStatic).values(batch)
|
||||
stmt = stmt.on_conflict_do_update(
|
||||
index_elements=[AircraftStatic.icao24],
|
||||
set_={
|
||||
"registration": stmt.excluded.registration,
|
||||
"aircraft_type": stmt.excluded.aircraft_type,
|
||||
"type_description": stmt.excluded.type_description,
|
||||
"operator": stmt.excluded.operator,
|
||||
"owner": stmt.excluded.owner,
|
||||
"origin_country": stmt.excluded.origin_country,
|
||||
"category": stmt.excluded.category,
|
||||
"is_military": stmt.excluded.is_military,
|
||||
"source": stmt.excluded.source,
|
||||
"updated_at": stmt.excluded.updated_at,
|
||||
},
|
||||
)
|
||||
await db.execute(stmt)
|
||||
else:
|
||||
stmt_sq = sqlite_insert(AircraftStatic).values(batch)
|
||||
stmt_sq = stmt_sq.on_conflict_do_update(
|
||||
index_elements=[AircraftStatic.icao24],
|
||||
set_={
|
||||
"registration": stmt_sq.excluded.registration,
|
||||
"aircraft_type": stmt_sq.excluded.aircraft_type,
|
||||
"type_description": stmt_sq.excluded.type_description,
|
||||
"operator": stmt_sq.excluded.operator,
|
||||
"owner": stmt_sq.excluded.owner,
|
||||
"origin_country": stmt_sq.excluded.origin_country,
|
||||
"category": stmt_sq.excluded.category,
|
||||
"is_military": stmt_sq.excluded.is_military,
|
||||
"source": stmt_sq.excluded.source,
|
||||
"updated_at": stmt_sq.excluded.updated_at,
|
||||
},
|
||||
)
|
||||
await db.execute(stmt_sq)
|
||||
written += len(batch)
|
||||
return written
|
||||
|
||||
|
||||
async def sync_aircraft_registry(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
primary_url: str | None = None,
|
||||
fallback_url: str | None = None,
|
||||
cache_dir: str | None = None,
|
||||
max_rows: int | None = None,
|
||||
timeout_seconds: float = 60.0,
|
||||
) -> dict[str, Any]:
|
||||
"""Download open ICAO24 registry CSV (or use cached/existing DB on failure offline)."""
|
||||
cfg = get_data_sources_config()
|
||||
primary_resolved = primary_url if primary_url is not None else cfg.get_yaml_url("aircraft_registry")
|
||||
fallback_resolved = (
|
||||
fallback_url
|
||||
if fallback_url is not None
|
||||
else cfg.get_yaml_value("aircraft_registry.fallback_url")
|
||||
)
|
||||
urls = [
|
||||
url
|
||||
for url in (primary_resolved, fallback_resolved)
|
||||
if isinstance(url, str) and url.strip()
|
||||
]
|
||||
target_dir = get_aircraft_registry_cache_dir(cache_dir)
|
||||
target_dir.mkdir(parents=True, exist_ok=True)
|
||||
cached_csv_path = target_dir / "aircraft_registry.csv"
|
||||
|
||||
downloaded_text: str | None = None
|
||||
used_url: str | None = None
|
||||
last_error: str | None = None
|
||||
|
||||
for candidate_url in urls:
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=timeout_seconds, follow_redirects=True) as client:
|
||||
response = await client.get(
|
||||
candidate_url,
|
||||
headers={"User-Agent": "Planet-Intelligence-System/1.0 (aircraft-registry)"},
|
||||
)
|
||||
response.raise_for_status()
|
||||
if len(response.content) > MAX_REGISTRY_BYTES:
|
||||
raise ValueError(f"Registry file exceeds {MAX_REGISTRY_BYTES} bytes limit")
|
||||
downloaded_text = decode_registry_payload(response.content, candidate_url)
|
||||
tmp_path = target_dir / "aircraft_registry.csv.tmp"
|
||||
tmp_path.write_text(downloaded_text, encoding="utf-8")
|
||||
tmp_path.replace(cached_csv_path)
|
||||
used_url = candidate_url
|
||||
break
|
||||
except Exception as exc:
|
||||
last_error = f"{exc.__class__.__name__}: {exc}"
|
||||
logger.warning_event(
|
||||
"Aircraft registry download failed; trying fallback or offline cache",
|
||||
event="aircraft_registry.download_failed",
|
||||
context={"url": candidate_url, "error": last_error},
|
||||
)
|
||||
|
||||
if downloaded_text is None and cached_csv_path.exists():
|
||||
try:
|
||||
downloaded_text = cached_csv_path.read_text(encoding="utf-8", errors="replace")
|
||||
used_url = f"file://{cached_csv_path}"
|
||||
except OSError as exc:
|
||||
last_error = f"{exc.__class__.__name__}: {exc}"
|
||||
|
||||
if downloaded_text is None:
|
||||
existing_count = int((await db.execute(select(func.count(AircraftStatic.icao24)))).scalar() or 0)
|
||||
return {
|
||||
"status": "offline_retained",
|
||||
"upserted": 0,
|
||||
"existing_count": existing_count,
|
||||
"source_url": None,
|
||||
"error": last_error,
|
||||
}
|
||||
|
||||
records = parse_aircraft_registry_csv(downloaded_text, max_rows=max_rows)
|
||||
if not records:
|
||||
existing_count = int((await db.execute(select(func.count(AircraftStatic.icao24)))).scalar() or 0)
|
||||
return {
|
||||
"status": "empty_retained",
|
||||
"upserted": 0,
|
||||
"existing_count": existing_count,
|
||||
"source_url": used_url,
|
||||
"error": last_error,
|
||||
}
|
||||
|
||||
upserted = await upsert_aircraft_static_records(db, records)
|
||||
await db.commit()
|
||||
return {
|
||||
"status": "updated" if not str(used_url or "").startswith("file://") else "cache_loaded",
|
||||
"upserted": upserted,
|
||||
"existing_count": upserted,
|
||||
"source_url": used_url,
|
||||
"error": last_error,
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
"""Aircraft ICAO24 military allocation table, callsign heuristics, and category classification."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Final
|
||||
|
||||
AIRCRAFT_CATEGORIES: Final[frozenset[str]] = frozenset(
|
||||
{
|
||||
"commercial",
|
||||
"cargo",
|
||||
"military",
|
||||
"emergency",
|
||||
"general",
|
||||
"helicopter",
|
||||
"other",
|
||||
}
|
||||
)
|
||||
|
||||
EMERGENCY_SQUAWKS: Final[dict[str, str]] = {
|
||||
"7500": "hijack",
|
||||
"7600": "radio_failure",
|
||||
"7700": "emergency",
|
||||
}
|
||||
|
||||
# ICAO 24-bit military address blocks compiled from published ICAO Annex 10 national
|
||||
# allocations and community ADS-B reference registries (tar1090 / mictronics / adsbexchange docs).
|
||||
MILITARY_ICAO24_HEX_RANGES: Final[tuple[tuple[int, int, str], ...]] = (
|
||||
(0xADF7C8, 0xAFFFFF, "US Military (DoD/USAF/USN/USCG)"),
|
||||
(0x43C000, 0x43CFFF, "UK Ministry of Defence (RAF/RN)"),
|
||||
(0x3AA000, 0x3AFFFF, "French Military (Armée de l'Air/Marine)"),
|
||||
(0x3B0000, 0x3BFFFF, "French State/Military"),
|
||||
(0x3EA000, 0x3EBFFF, "German Armed Forces (Bundeswehr)"),
|
||||
(0x3F4000, 0x3F7FFF, "German Military Tactical"),
|
||||
(0x33FF00, 0x33FFFF, "Italian Air Force"),
|
||||
(0x44F000, 0x44FFFF, "Belgian Air Component"),
|
||||
(0x480000, 0x480FFF, "Royal Netherlands Air Force"),
|
||||
(0x478100, 0x4781FF, "Royal Norwegian Air Force"),
|
||||
(0x48D800, 0x48DFFF, "Polish Air Force"),
|
||||
(0x4B8200, 0x4B82FF, "Turkish Air Force"),
|
||||
(0x4D0000, 0x4D03FF, "NATO Airborne Early Warning (Luxembourg)"),
|
||||
(0x71BC00, 0x71BFFF, "Republic of Korea Air Force"),
|
||||
(0x738A00, 0x738BFF, "Israeli Air Force"),
|
||||
(0x7CF800, 0x7CFFFF, "Royal Australian Air Force"),
|
||||
(0x800200, 0x8002FF, "Indian Air Force"),
|
||||
(0x840000, 0x840FFF, "Japan Self-Defense Forces"),
|
||||
(0x87F000, 0x87FFFF, "Japan Self-Defense Forces (Secondary)"),
|
||||
(0xC2B300, 0xC2C3FF, "Royal Canadian Air Force"),
|
||||
(0xE40000, 0xE400FF, "Brazilian Air Force"),
|
||||
)
|
||||
|
||||
MILITARY_CALLSIGN_PREFIXES: Final[tuple[str, ...]] = (
|
||||
"RCH",
|
||||
"REACH",
|
||||
"CNV",
|
||||
"CONVOY",
|
||||
"ASY",
|
||||
"ASCOT",
|
||||
"RRR",
|
||||
"GAF",
|
||||
"CTM",
|
||||
"FAF",
|
||||
"IAM",
|
||||
"NATO",
|
||||
"MMF",
|
||||
"SAM",
|
||||
"EXEC",
|
||||
"SPAR",
|
||||
"PAT",
|
||||
"NAVY",
|
||||
"USAF",
|
||||
"USMC",
|
||||
"CFC",
|
||||
"CANF",
|
||||
"KIWI",
|
||||
"AUSSIE",
|
||||
"ASY",
|
||||
"PLF",
|
||||
"BAF",
|
||||
"HVK",
|
||||
"JASDF",
|
||||
"KAF",
|
||||
"IAF",
|
||||
)
|
||||
|
||||
CARGO_CALLSIGN_PREFIXES: Final[tuple[str, ...]] = (
|
||||
"FDX",
|
||||
"UPS",
|
||||
"GTI",
|
||||
"CLX",
|
||||
"ABX",
|
||||
"ATN",
|
||||
"BOX",
|
||||
"CKK",
|
||||
"CSS",
|
||||
"PAC",
|
||||
"BCS",
|
||||
"GEC",
|
||||
"DHK",
|
||||
"SOO",
|
||||
"KFS",
|
||||
"CJT",
|
||||
)
|
||||
|
||||
HELICOPTER_TYPE_CODES: Final[frozenset[str]] = frozenset(
|
||||
{
|
||||
"EC35",
|
||||
"EC45",
|
||||
"EC55",
|
||||
"H125",
|
||||
"H135",
|
||||
"H145",
|
||||
"H160",
|
||||
"H175",
|
||||
"S76",
|
||||
"S92",
|
||||
"UH60",
|
||||
"H60",
|
||||
"CH47",
|
||||
"H47",
|
||||
"AH64",
|
||||
"H64",
|
||||
"B06",
|
||||
"B407",
|
||||
"B412",
|
||||
"B429",
|
||||
"AS32",
|
||||
"AS50",
|
||||
"AS65",
|
||||
"MI8",
|
||||
"MI24",
|
||||
"NH90",
|
||||
"A109",
|
||||
"A139",
|
||||
"AW139",
|
||||
"AW189",
|
||||
"R22",
|
||||
"R44",
|
||||
"R66",
|
||||
"V22",
|
||||
}
|
||||
)
|
||||
|
||||
_COMMERCIAL_CALLSIGN_RE = re.compile(r"^[A-Z]{3}[0-9]{1,4}[A-Z]{0,2}$")
|
||||
|
||||
|
||||
def normalize_icao24(value: str | None) -> str:
|
||||
"""Normalize an ICAO 24-bit hex identifier to lowercase 6-char hex when valid."""
|
||||
cleaned = str(value or "").strip().lower().lstrip("~")
|
||||
return cleaned
|
||||
|
||||
|
||||
def is_military_icao24(icao24: str | None) -> bool:
|
||||
"""Return True if the 24-bit ICAO hex address falls within a known military block."""
|
||||
normalized = normalize_icao24(icao24)
|
||||
if len(normalized) != 6:
|
||||
return False
|
||||
try:
|
||||
addr = int(normalized, 16)
|
||||
except ValueError:
|
||||
return False
|
||||
return any(low <= addr <= high for low, high, _label in MILITARY_ICAO24_HEX_RANGES)
|
||||
|
||||
|
||||
def is_military_callsign(callsign: str | None) -> bool:
|
||||
"""Return True when the trimmed flight callsign starts with a known military designator."""
|
||||
cs = str(callsign or "").strip().upper()
|
||||
if not cs:
|
||||
return False
|
||||
for prefix in MILITARY_CALLSIGN_PREFIXES:
|
||||
if cs == prefix or (cs.startswith(prefix) and len(cs) > len(prefix) and cs[len(prefix)].isdigit()):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def classify_aircraft(
|
||||
*,
|
||||
icao24: str | None,
|
||||
callsign: str | None = None,
|
||||
squawk: str | None = None,
|
||||
aircraft_type: str | None = None,
|
||||
adsb_category: str | None = None,
|
||||
db_flags: int | None = None,
|
||||
static_is_military: bool = False,
|
||||
static_category: str | None = None,
|
||||
source_is_military_feed: bool = False,
|
||||
) -> dict[str, object]:
|
||||
"""Classify aircraft operational category, military flag, and emergency status."""
|
||||
norm_squawk = str(squawk or "").strip()
|
||||
is_emergency = norm_squawk in EMERGENCY_SQUAWKS
|
||||
emergency_code = norm_squawk if is_emergency else None
|
||||
|
||||
db_mil = bool(db_flags is not None and (int(db_flags) & 1))
|
||||
is_military = bool(
|
||||
static_is_military
|
||||
or db_mil
|
||||
or source_is_military_feed
|
||||
or is_military_icao24(icao24)
|
||||
or is_military_callsign(callsign)
|
||||
)
|
||||
|
||||
cs = str(callsign or "").strip().upper()
|
||||
type_upper = str(aircraft_type or "").strip().upper()
|
||||
emitter = str(adsb_category or "").strip().upper()
|
||||
static_cat = str(static_category or "").strip().lower()
|
||||
|
||||
is_helicopter = (
|
||||
emitter == "A7"
|
||||
or type_upper in HELICOPTER_TYPE_CODES
|
||||
or static_cat == "helicopter"
|
||||
)
|
||||
is_cargo = bool(
|
||||
cs and any(cs.startswith(p) and len(cs) > len(p) and cs[len(p)].isdigit() for p in CARGO_CALLSIGN_PREFIXES)
|
||||
) or static_cat == "cargo"
|
||||
|
||||
if is_emergency:
|
||||
category = "emergency"
|
||||
elif is_military:
|
||||
category = "military"
|
||||
elif is_helicopter:
|
||||
category = "helicopter"
|
||||
elif is_cargo:
|
||||
category = "cargo"
|
||||
elif emitter in {"A3", "A4", "A5"} or (_COMMERCIAL_CALLSIGN_RE.match(cs) is not None):
|
||||
category = "commercial"
|
||||
elif emitter in {"A1", "A2"} or static_cat == "general":
|
||||
category = "general"
|
||||
elif static_cat in AIRCRAFT_CATEGORIES:
|
||||
category = static_cat
|
||||
elif cs:
|
||||
category = "general"
|
||||
else:
|
||||
category = "other"
|
||||
|
||||
return {
|
||||
"category": category,
|
||||
"is_military": is_military,
|
||||
"is_emergency": is_emergency,
|
||||
"emergency_code": emergency_code,
|
||||
}
|
||||
@@ -29,6 +29,8 @@ EARTH_READ_SCOPES: frozenset[str] = frozenset(
|
||||
"visualization:read",
|
||||
"layers:read",
|
||||
"vessels:read",
|
||||
"aircraft:read",
|
||||
"gps_jamming:read",
|
||||
"news:read",
|
||||
"data_products:read",
|
||||
"situational:read",
|
||||
|
||||
@@ -46,6 +46,17 @@ from app.services.collectors.earth_tiles import (
|
||||
)
|
||||
from app.services.collectors.vessel_ais import VesselAISCollector
|
||||
from app.services.collectors.wind_gfs import EarthWindGFSCollector
|
||||
from app.services.collectors.adsb_lol import ADSBLolCollector
|
||||
from app.services.collectors.opensky import OpenSkyAircraftCollector
|
||||
from app.services.collectors.gps_jamming import GPSJammingCollector
|
||||
from app.services.collectors.aircraft_registry import AircraftRegistryCollector
|
||||
from app.services.collectors.disasters import (
|
||||
GDACSDisasterCollector,
|
||||
NASAEonetCollector,
|
||||
NASAFirmsWildfireCollector,
|
||||
USGSEarthquakeCollector,
|
||||
)
|
||||
from app.services.collectors.nga_warnings import NGANavigationWarningsCollector
|
||||
|
||||
collector_registry.register(TOP500Collector())
|
||||
collector_registry.register(EpochAIGPUCollector())
|
||||
@@ -81,6 +92,15 @@ collector_registry.register(CloudHDTilesCollector())
|
||||
collector_registry.register(Sentinel2ImageryCollector())
|
||||
collector_registry.register(VIIRSDailyImageryCollector())
|
||||
collector_registry.register(EarthWindGFSCollector())
|
||||
collector_registry.register(ADSBLolCollector())
|
||||
collector_registry.register(OpenSkyAircraftCollector())
|
||||
collector_registry.register(GPSJammingCollector())
|
||||
collector_registry.register(AircraftRegistryCollector())
|
||||
collector_registry.register(USGSEarthquakeCollector())
|
||||
collector_registry.register(NASAFirmsWildfireCollector())
|
||||
collector_registry.register(GDACSDisasterCollector())
|
||||
collector_registry.register(NASAEonetCollector())
|
||||
collector_registry.register(NGANavigationWarningsCollector())
|
||||
|
||||
__all__ = [
|
||||
"BaseCollector",
|
||||
@@ -122,4 +142,13 @@ __all__ = [
|
||||
"Sentinel2ImageryCollector",
|
||||
"VIIRSDailyImageryCollector",
|
||||
"EarthWindGFSCollector",
|
||||
"ADSBLolCollector",
|
||||
"OpenSkyAircraftCollector",
|
||||
"GPSJammingCollector",
|
||||
"AircraftRegistryCollector",
|
||||
"USGSEarthquakeCollector",
|
||||
"NASAFirmsWildfireCollector",
|
||||
"GDACSDisasterCollector",
|
||||
"NASAEonetCollector",
|
||||
"NGANavigationWarningsCollector",
|
||||
]
|
||||
@@ -0,0 +1,324 @@
|
||||
"""adsb.lol ADS-B collector (Source 39) with optional opt-in non-commercial gap-fill."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.data_sources import get_data_sources_config
|
||||
from app.core.enums import ConnectionState, SnapshotStatus
|
||||
from app.core.logging import get_logger
|
||||
from app.core.websocket.broadcaster import broadcaster
|
||||
from app.models.data_snapshot import DataSnapshot
|
||||
from app.models.datasource_config import DataSourceConfig
|
||||
from app.services.aircraft_aggregation import (
|
||||
DEFAULT_CURRENT_STALE_MINUTES,
|
||||
DEFAULT_POSITION_RETENTION_HOURS,
|
||||
prune_aircraft_tables,
|
||||
update_adsb_source_health,
|
||||
upsert_aircraft_observations,
|
||||
)
|
||||
from app.services.collectors.base import BaseCollector
|
||||
|
||||
logger = get_logger(__name__, service="collector.adsb_lol")
|
||||
|
||||
ADSB_LOL_DEFAULT_BASE_URL = "https://api.adsb.lol"
|
||||
AIRPLANES_LIVE_BASE_URL = "https://api.airplanes.live"
|
||||
ADSB_FI_BASE_URL = "https://opendata.adsb.fi/api"
|
||||
|
||||
FEET_TO_METERS = 0.3048
|
||||
KNOTS_TO_MS = 0.514444
|
||||
FTMIN_TO_MS = 0.00508
|
||||
MAX_ENDPOINT_RETRIES = 2
|
||||
|
||||
|
||||
def _as_float(val: Any) -> float | None:
|
||||
if val in (None, "", "ground"):
|
||||
return None
|
||||
try:
|
||||
return float(val)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _as_int(val: Any) -> int | None:
|
||||
if val in (None, ""):
|
||||
return None
|
||||
try:
|
||||
return int(val)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def parse_adsb_lol_payload(
|
||||
payload: dict[str, Any] | list[Any],
|
||||
*,
|
||||
source: str = "adsb_lol_aircraft",
|
||||
is_military_endpoint: bool = False,
|
||||
squawk_hint: str | None = None,
|
||||
fallback_time: datetime | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Parse an adsb.lol v2 API JSON payload into normalized aircraft observations."""
|
||||
ref_now = fallback_time or datetime.now(UTC)
|
||||
if isinstance(payload, dict) and payload.get("now") is not None:
|
||||
raw_now = _as_float(payload.get("now"))
|
||||
if raw_now is not None:
|
||||
if raw_now > 10_000_000_000:
|
||||
raw_now /= 1000.0
|
||||
ref_now = datetime.fromtimestamp(raw_now, tz=UTC)
|
||||
|
||||
items = payload.get("ac") if isinstance(payload, dict) else payload
|
||||
if not isinstance(items, list):
|
||||
return []
|
||||
|
||||
records: list[dict[str, Any]] = []
|
||||
for item in items:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
icao24 = str(item.get("hex") or "").strip().lower().lstrip("~")
|
||||
lat = _as_float(item.get("lat"))
|
||||
lon = _as_float(item.get("lon"))
|
||||
if len(icao24) != 6 or lat is None or lon is None:
|
||||
continue
|
||||
|
||||
raw_baro = item.get("alt_baro")
|
||||
on_ground = raw_baro == "ground"
|
||||
baro_ft = _as_float(raw_baro)
|
||||
geom_ft = _as_float(item.get("alt_geom"))
|
||||
baro_m = 0.0 if on_ground else (baro_ft * FEET_TO_METERS if baro_ft is not None else None)
|
||||
geom_m = geom_ft * FEET_TO_METERS if geom_ft is not None else None
|
||||
|
||||
gs_knots = _as_float(item.get("gs"))
|
||||
speed_ms = gs_knots * KNOTS_TO_MS if gs_knots is not None else None
|
||||
track_deg = _as_float(item.get("track"))
|
||||
vrate_fpm = _as_float(item.get("baro_rate") if item.get("baro_rate") is not None else item.get("geom_rate"))
|
||||
vrate_ms = vrate_fpm * FTMIN_TO_MS if vrate_fpm is not None else None
|
||||
|
||||
seen_pos = _as_float(item.get("seen_pos") if item.get("seen_pos") is not None else item.get("seen"))
|
||||
obs_at = ref_now - timedelta(seconds=max(0.0, seen_pos or 0.0))
|
||||
|
||||
squawk = str(item.get("squawk") or squawk_hint or "").strip()[:8] or None
|
||||
db_flags = _as_int(item.get("dbFlags"))
|
||||
|
||||
records.append(
|
||||
{
|
||||
"icao24": icao24,
|
||||
"callsign": str(item.get("flight") or "").strip()[:16] or None,
|
||||
"lat": lat,
|
||||
"lon": lon,
|
||||
"baro_altitude_m": baro_m,
|
||||
"geo_altitude_m": geom_m,
|
||||
"ground_speed_ms": speed_ms,
|
||||
"track_deg": track_deg,
|
||||
"vertical_rate_ms": vrate_ms,
|
||||
"squawk": squawk,
|
||||
"on_ground": on_ground,
|
||||
"aircraft_type": str(item.get("t") or "").strip()[:16] or None,
|
||||
"adsb_category": str(item.get("category") or "").strip()[:8] or None,
|
||||
"db_flags": db_flags,
|
||||
"source_is_military": bool(is_military_endpoint or (db_flags is not None and (db_flags & 1))),
|
||||
"source": source,
|
||||
"observed_at": obs_at,
|
||||
}
|
||||
)
|
||||
return records
|
||||
|
||||
|
||||
class ADSBLolCollector(BaseCollector):
|
||||
"""Collect military, emergency squawk, and configured focus-area ADS-B traffic from adsb.lol."""
|
||||
|
||||
name = "adsb_lol_aircraft"
|
||||
priority = "P1"
|
||||
module = "L4"
|
||||
frequency_hours = 1
|
||||
data_type = "aircraft_adsb"
|
||||
fail_on_empty = False
|
||||
preserve_snapshot_on_failure = True
|
||||
|
||||
@property
|
||||
def base_url(self) -> str:
|
||||
raw = self._resolved_url or get_data_sources_config().get_yaml_url(self.name) or ADSB_LOL_DEFAULT_BASE_URL
|
||||
return raw.rstrip("/")
|
||||
|
||||
async def _load_runtime_config(self) -> dict[str, Any]:
|
||||
db = getattr(self, "_db_session", None)
|
||||
if db is None or not callable(getattr(db, "execute", None)):
|
||||
return {}
|
||||
try:
|
||||
res = await db.execute(
|
||||
select(DataSourceConfig)
|
||||
.where(DataSourceConfig.name == self.name)
|
||||
.where(DataSourceConfig.is_active.is_(True))
|
||||
)
|
||||
rec = res.scalar_one_or_none()
|
||||
return dict(rec.config or {}) if rec and isinstance(rec.config, dict) else {}
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Could not load adsb_lol_aircraft runtime config; using defaults",
|
||||
event="adsb_lol.config_load_failed",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
return {}
|
||||
|
||||
async def _get_with_retry(
|
||||
self,
|
||||
client: httpx.AsyncClient,
|
||||
url: str,
|
||||
) -> dict[str, Any] | None:
|
||||
last_exc: Exception | None = None
|
||||
for attempt in range(MAX_ENDPOINT_RETRIES + 1):
|
||||
try:
|
||||
resp = await client.get(
|
||||
url,
|
||||
headers={"User-Agent": "Planet-Intelligence-System/1.0 (adsb.lol ODbL)"},
|
||||
)
|
||||
resp.raise_for_status()
|
||||
payload = resp.json()
|
||||
return payload if isinstance(payload, dict) else None
|
||||
except Exception as exc:
|
||||
last_exc = exc
|
||||
if attempt < MAX_ENDPOINT_RETRIES:
|
||||
await asyncio.sleep(0.5 * (2**attempt))
|
||||
logger.warning_event(
|
||||
"adsb.lol endpoint failed after retries",
|
||||
event="adsb_lol.endpoint_failed",
|
||||
context={"url": url, "error": str(last_exc) if last_exc else "unknown"},
|
||||
)
|
||||
return None
|
||||
|
||||
async def fetch(self) -> list[dict[str, Any]]:
|
||||
cfg = await self._load_runtime_config()
|
||||
focus_points = cfg.get("focus_points") if isinstance(cfg.get("focus_points"), list) else []
|
||||
gap_fill_enabled = bool(cfg.get("gap_fill_noncommercial_enabled", False))
|
||||
gap_fill_provider = str(cfg.get("gap_fill_provider") or "airplanes_live").strip().lower()
|
||||
|
||||
endpoints: list[tuple[str, bool, str | None, str]] = [
|
||||
(f"{self.base_url}/v2/mil", True, None, self.name),
|
||||
(f"{self.base_url}/v2/sqk/7500", False, "7500", self.name),
|
||||
(f"{self.base_url}/v2/sqk/7600", False, "7600", self.name),
|
||||
(f"{self.base_url}/v2/sqk/7700", False, "7700", self.name),
|
||||
]
|
||||
|
||||
for pt in focus_points[:8]:
|
||||
if not isinstance(pt, dict):
|
||||
continue
|
||||
lat = _as_float(pt.get("lat"))
|
||||
lon = _as_float(pt.get("lon"))
|
||||
radius = max(10, min(int(_as_float(pt.get("radius_nm")) or 250), 250))
|
||||
if lat is not None and lon is not None:
|
||||
endpoints.append((f"{self.base_url}/v2/point/{lat}/{lon}/{radius}", False, None, self.name))
|
||||
if gap_fill_enabled:
|
||||
if gap_fill_provider == "adsb_fi":
|
||||
endpoints.append(
|
||||
(f"{ADSB_FI_BASE_URL}/v2/lat/{lat}/lon/{lon}/dist/{radius}", False, None, "adsb_fi")
|
||||
)
|
||||
else:
|
||||
endpoints.append(
|
||||
(f"{AIRPLANES_LIVE_BASE_URL}/v2/point/{lat}/{lon}/{radius}", False, None, "airplanes_live")
|
||||
)
|
||||
|
||||
all_records: list[dict[str, Any]] = []
|
||||
any_succeeded = False
|
||||
async with httpx.AsyncClient(timeout=20.0, follow_redirects=True) as client:
|
||||
for url, is_mil, squawk_hint, src in endpoints:
|
||||
payload = await self._get_with_retry(client, url)
|
||||
if payload is not None:
|
||||
any_succeeded = True
|
||||
all_records.extend(
|
||||
parse_adsb_lol_payload(
|
||||
payload,
|
||||
source=src,
|
||||
is_military_endpoint=is_mil,
|
||||
squawk_hint=squawk_hint,
|
||||
)
|
||||
)
|
||||
|
||||
self._last_fetch_succeeded = any_succeeded
|
||||
return all_records
|
||||
|
||||
def transform(self, raw_data: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
return [item for item in raw_data if isinstance(item, dict) and item.get("icao24")]
|
||||
|
||||
async def _save_data(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
data: list[dict[str, Any]],
|
||||
task_id: int | None = None,
|
||||
snapshot_id: int | None = None,
|
||||
) -> int:
|
||||
now = datetime.now(UTC)
|
||||
cfg = await self._load_runtime_config()
|
||||
stale_minutes = int(cfg.get("current_stale_minutes") or DEFAULT_CURRENT_STALE_MINUTES)
|
||||
retention_hours = int(cfg.get("position_retention_hours") or DEFAULT_POSITION_RETENTION_HOURS)
|
||||
|
||||
fetch_ok = getattr(self, "_last_fetch_succeeded", True)
|
||||
if not fetch_ok and not data:
|
||||
await update_adsb_source_health(
|
||||
db,
|
||||
source=self.name,
|
||||
connection_state=ConnectionState.DISCONNECTED.value,
|
||||
active_count=0,
|
||||
last_error="All adsb.lol endpoints failed; retaining previous state until expiry",
|
||||
)
|
||||
await db.commit()
|
||||
return 0
|
||||
|
||||
summary = await upsert_aircraft_observations(
|
||||
db,
|
||||
data,
|
||||
default_source=self.name,
|
||||
ingested_at=now,
|
||||
)
|
||||
await prune_aircraft_tables(
|
||||
db,
|
||||
current_stale_minutes=stale_minutes,
|
||||
position_retention_hours=retention_hours,
|
||||
now=now,
|
||||
)
|
||||
await update_adsb_source_health(
|
||||
db,
|
||||
source=self.name,
|
||||
connection_state=ConnectionState.CONNECTED.value,
|
||||
active_count=summary["states_upserted"],
|
||||
last_success_at=now,
|
||||
last_error=None,
|
||||
clear_cooldown=True,
|
||||
)
|
||||
|
||||
if snapshot_id is not None:
|
||||
snapshot = await db.get(DataSnapshot, snapshot_id)
|
||||
if snapshot:
|
||||
snapshot.record_count = summary["states_upserted"]
|
||||
snapshot.status = SnapshotStatus.SUCCESS.value
|
||||
snapshot.completed_at = now
|
||||
snapshot.summary = {
|
||||
"created": summary["states_upserted"],
|
||||
"positions_inserted": summary["positions_inserted"],
|
||||
"storage": "aircraft_current_state_and_24h_position",
|
||||
}
|
||||
await db.commit()
|
||||
|
||||
if summary["states_upserted"] > 0:
|
||||
try:
|
||||
await broadcaster.broadcast_earth_update(
|
||||
{
|
||||
"event": "earth.layer.changed",
|
||||
"action": "database_changed",
|
||||
"source": self.name,
|
||||
"layers": ["aircraft"],
|
||||
"refresh_strategy": "reload",
|
||||
"records_processed": summary["states_upserted"],
|
||||
}
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed to broadcast aircraft update after adsb.lol ingestion",
|
||||
event="adsb_lol.broadcast_failed",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
return summary["states_upserted"]
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Collector entrypoint for open ICAO24 aircraft registry synchronization (Source 42)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.enums import SnapshotStatus
|
||||
from app.models.data_snapshot import DataSnapshot
|
||||
from app.services.aircraft_registry import sync_aircraft_registry
|
||||
from app.services.collectors.base import BaseCollector
|
||||
|
||||
|
||||
class AircraftRegistryCollector(BaseCollector):
|
||||
"""Download/update local ICAO24 aircraft_static metadata with offline graceful retention."""
|
||||
|
||||
name = "aircraft_registry"
|
||||
priority = "P2"
|
||||
module = "L4"
|
||||
frequency_hours = 168
|
||||
data_type = "aircraft_registry"
|
||||
fail_on_empty = False
|
||||
preserve_snapshot_on_failure = True
|
||||
|
||||
async def fetch(self) -> list[dict[str, Any]]:
|
||||
db = getattr(self, "_db_session", None)
|
||||
if db is None:
|
||||
return []
|
||||
result = await sync_aircraft_registry(db, primary_url=self._resolved_url)
|
||||
return [result]
|
||||
|
||||
async def _save_data(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
data: list[dict[str, Any]],
|
||||
task_id: int | None = None,
|
||||
snapshot_id: int | None = None,
|
||||
) -> int:
|
||||
now = datetime.now(UTC)
|
||||
summary = data[0] if data and isinstance(data[0], dict) else {}
|
||||
written = int(summary.get("upserted") or 0)
|
||||
if snapshot_id is not None:
|
||||
snapshot = await db.get(DataSnapshot, snapshot_id)
|
||||
if snapshot:
|
||||
snapshot.record_count = written
|
||||
snapshot.status = SnapshotStatus.SUCCESS.value
|
||||
snapshot.completed_at = now
|
||||
snapshot.summary = summary
|
||||
await db.commit()
|
||||
return written
|
||||
@@ -0,0 +1,279 @@
|
||||
"""Natural disaster collectors: USGS (43), NASA FIRMS (44), GDACS (45), NASA EONET (46)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from sqlalchemy import update
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.data_sources import get_data_sources_config
|
||||
from app.core.enums import SnapshotStatus
|
||||
from app.core.logging import get_logger
|
||||
from app.core.websocket.broadcaster import broadcaster
|
||||
from app.models.data_snapshot import DataSnapshot
|
||||
from app.models.datasource import DataSource
|
||||
from app.services.collectors.base import BaseCollector
|
||||
from app.services.datasource_connectivity import resolve_nasa_firms_map_key
|
||||
from app.services.disaster_aggregation import (
|
||||
parse_gdacs_events,
|
||||
parse_nasa_eonet_events,
|
||||
parse_nasa_firms_csv,
|
||||
parse_usgs_earthquakes,
|
||||
upsert_disaster_events,
|
||||
)
|
||||
|
||||
logger = get_logger(__name__, service="collector.disasters")
|
||||
|
||||
USGS_URL_DEFAULT = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_day.geojson"
|
||||
NASA_FIRMS_BASE_DEFAULT = "https://firms.modaps.eosdis.nasa.gov/api/area/csv"
|
||||
GDACS_URL_DEFAULT = "https://www.gdacs.org/gdacsapi/api/events/geteventlist/SEARCH"
|
||||
NASA_EONET_URL_DEFAULT = "https://eonet.gsfc.nasa.gov/api/v3/events?status=open&limit=100"
|
||||
|
||||
|
||||
async def _mark_source_status(db: AsyncSession, source_name: str, status_val: str) -> None:
|
||||
try:
|
||||
await db.execute(
|
||||
update(DataSource)
|
||||
.where(DataSource.source == source_name)
|
||||
.values(last_status=status_val, last_run_at=datetime.now(UTC))
|
||||
)
|
||||
await db.commit()
|
||||
except Exception as exc:
|
||||
logger.debug_event(
|
||||
"Skipped datasource status update",
|
||||
event="disaster_collector.status_update_skipped",
|
||||
context={"source": source_name, "error_type": type(exc).__name__},
|
||||
)
|
||||
|
||||
|
||||
async def _persist_disaster_batch(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
source_name: str,
|
||||
records: list[dict[str, Any]],
|
||||
snapshot_id: int | None = None,
|
||||
) -> int:
|
||||
saved = await upsert_disaster_events(db, records)
|
||||
now = datetime.now(UTC)
|
||||
if snapshot_id is not None:
|
||||
snap = await db.get(DataSnapshot, snapshot_id)
|
||||
if snap is not None:
|
||||
snap.record_count = saved
|
||||
snap.status = SnapshotStatus.SUCCESS.value
|
||||
snap.completed_at = now
|
||||
snap.summary = {"created": saved, "storage": "disaster_events"}
|
||||
await db.commit()
|
||||
if saved > 0:
|
||||
try:
|
||||
await broadcaster.broadcast_earth_update(
|
||||
{
|
||||
"event": "earth.layer.changed",
|
||||
"action": "database_changed",
|
||||
"source": source_name,
|
||||
"layers": ["disasters"],
|
||||
"refresh_strategy": "reload",
|
||||
"records_processed": saved,
|
||||
}
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed to broadcast disasters update",
|
||||
event="disasters.broadcast_failed",
|
||||
context={"source": source_name, "error": str(exc)},
|
||||
)
|
||||
return saved
|
||||
|
||||
|
||||
class USGSEarthquakeCollector(BaseCollector):
|
||||
"""Collector 43: USGS M4.5+ global earthquakes."""
|
||||
|
||||
name = "usgs_earthquakes"
|
||||
priority = "P1"
|
||||
module = "L4"
|
||||
frequency_hours = 1
|
||||
data_type = "disasters"
|
||||
fail_on_empty = False
|
||||
preserve_snapshot_on_failure = True
|
||||
|
||||
def _resolve_url(self) -> str:
|
||||
val = self._resolved_url or get_data_sources_config().get_yaml_value("usgs_earthquakes.url")
|
||||
return str(val or USGS_URL_DEFAULT)
|
||||
|
||||
async def fetch(self) -> list[dict[str, Any]]:
|
||||
url = self._resolve_url()
|
||||
async with httpx.AsyncClient(timeout=20.0, follow_redirects=True) as client:
|
||||
resp = await client.get(url, headers={"User-Agent": "Planet-Intelligence-System/1.0"})
|
||||
resp.raise_for_status()
|
||||
payload = resp.json()
|
||||
return parse_usgs_earthquakes(payload, source=self.name)
|
||||
|
||||
def transform(self, raw_data: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
return [r for r in raw_data if isinstance(r, dict) and r.get("source_event_id")]
|
||||
|
||||
async def _save_data(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
data: list[dict[str, Any]],
|
||||
task_id: int | None = None,
|
||||
snapshot_id: int | None = None,
|
||||
) -> int:
|
||||
return await _persist_disaster_batch(db, source_name=self.name, records=data, snapshot_id=snapshot_id)
|
||||
|
||||
async def collect(self, db: AsyncSession, **kwargs) -> dict[str, Any]:
|
||||
records = self.transform(await self.fetch())
|
||||
saved = await self._save_data(db, records)
|
||||
await _mark_source_status(db, self.name, "success")
|
||||
return {"source": self.name, "status": "success", "records_saved": saved}
|
||||
|
||||
|
||||
class NASAFirmsWildfireCollector(BaseCollector):
|
||||
"""Collector 44: NASA FIRMS VIIRS active fires (requires free MAP_KEY)."""
|
||||
|
||||
name = "nasa_firms_wildfires"
|
||||
priority = "P1"
|
||||
module = "L4"
|
||||
frequency_hours = 1
|
||||
data_type = "disasters"
|
||||
fail_on_empty = False
|
||||
preserve_snapshot_on_failure = True
|
||||
|
||||
def _resolve_base_url(self) -> str:
|
||||
val = self._resolved_url or get_data_sources_config().get_yaml_value("nasa_firms_wildfires.url")
|
||||
return str(val or NASA_FIRMS_BASE_DEFAULT).rstrip("/")
|
||||
|
||||
async def fetch_with_db(self, db: AsyncSession | None = None) -> tuple[list[dict[str, Any]], str]:
|
||||
map_key, _cred_source = await resolve_nasa_firms_map_key(db)
|
||||
if not map_key:
|
||||
return [], "not_configured"
|
||||
cfg = get_data_sources_config()
|
||||
sensor = str(cfg.get_yaml_value("nasa_firms_wildfires.sensor") or "VIIRS_SNPP_NRT")
|
||||
days = int(cfg.get_yaml_value("nasa_firms_wildfires.days") or 1)
|
||||
url = f"{self._resolve_base_url()}/{map_key}/{sensor}/world/{days}"
|
||||
async with httpx.AsyncClient(timeout=30.0, follow_redirects=True) as client:
|
||||
resp = await client.get(url, headers={"User-Agent": "Planet-Intelligence-System/1.0"})
|
||||
resp.raise_for_status()
|
||||
csv_text = resp.text
|
||||
return parse_nasa_firms_csv(csv_text, source=self.name), "success"
|
||||
|
||||
async def fetch(self) -> list[dict[str, Any]]:
|
||||
records, _ = await self.fetch_with_db(self._db_session)
|
||||
return records
|
||||
|
||||
def transform(self, raw_data: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
return [r for r in raw_data if isinstance(r, dict) and r.get("source_event_id")]
|
||||
|
||||
async def _save_data(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
data: list[dict[str, Any]],
|
||||
task_id: int | None = None,
|
||||
snapshot_id: int | None = None,
|
||||
) -> int:
|
||||
return await _persist_disaster_batch(db, source_name=self.name, records=data, snapshot_id=snapshot_id)
|
||||
|
||||
async def collect(self, db: AsyncSession, **kwargs) -> dict[str, Any]:
|
||||
records, status_val = await self.fetch_with_db(db)
|
||||
if status_val == "not_configured":
|
||||
await _mark_source_status(db, self.name, "not_configured")
|
||||
logger.info_event(
|
||||
"NASA FIRMS MAP_KEY missing; skipping cleanly",
|
||||
event="nasa_firms.not_configured",
|
||||
)
|
||||
return {"source": self.name, "status": "not_configured", "records_saved": 0}
|
||||
saved = await self._save_data(db, self.transform(records))
|
||||
await _mark_source_status(db, self.name, "success")
|
||||
return {"source": self.name, "status": "success", "records_saved": saved}
|
||||
|
||||
|
||||
class GDACSDisasterCollector(BaseCollector):
|
||||
"""Collector 45: GDACS Orange/Red global disaster alerts."""
|
||||
|
||||
name = "gdacs_disasters"
|
||||
priority = "P1"
|
||||
module = "L4"
|
||||
frequency_hours = 1
|
||||
data_type = "disasters"
|
||||
fail_on_empty = False
|
||||
preserve_snapshot_on_failure = True
|
||||
|
||||
def _resolve_url(self) -> str:
|
||||
val = self._resolved_url or get_data_sources_config().get_yaml_value("gdacs_disasters.url")
|
||||
return str(val or GDACS_URL_DEFAULT)
|
||||
|
||||
async def fetch(self) -> list[dict[str, Any]]:
|
||||
url = self._resolve_url()
|
||||
async with httpx.AsyncClient(timeout=20.0, follow_redirects=True) as client:
|
||||
resp = await client.get(
|
||||
url,
|
||||
headers={
|
||||
"User-Agent": "Planet-Intelligence-System/1.0",
|
||||
"Accept": "application/json, application/xml, text/xml",
|
||||
},
|
||||
)
|
||||
resp.raise_for_status()
|
||||
content_type = str(resp.headers.get("content-type") or "").lower()
|
||||
raw: dict[str, Any] | str = resp.json() if "json" in content_type else resp.text
|
||||
return parse_gdacs_events(raw, source=self.name)
|
||||
|
||||
def transform(self, raw_data: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
return [r for r in raw_data if isinstance(r, dict) and r.get("source_event_id")]
|
||||
|
||||
async def _save_data(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
data: list[dict[str, Any]],
|
||||
task_id: int | None = None,
|
||||
snapshot_id: int | None = None,
|
||||
) -> int:
|
||||
return await _persist_disaster_batch(db, source_name=self.name, records=data, snapshot_id=snapshot_id)
|
||||
|
||||
async def collect(self, db: AsyncSession, **kwargs) -> dict[str, Any]:
|
||||
records = self.transform(await self.fetch())
|
||||
saved = await self._save_data(db, records)
|
||||
await _mark_source_status(db, self.name, "success")
|
||||
return {"source": self.name, "status": "success", "records_saved": saved}
|
||||
|
||||
|
||||
class NASAEonetCollector(BaseCollector):
|
||||
"""Collector 46: NASA EONET natural events (excluding earthquakes)."""
|
||||
|
||||
name = "nasa_eonet_events"
|
||||
priority = "P2"
|
||||
module = "L4"
|
||||
frequency_hours = 1
|
||||
data_type = "disasters"
|
||||
fail_on_empty = False
|
||||
preserve_snapshot_on_failure = True
|
||||
|
||||
def _resolve_url(self) -> str:
|
||||
val = self._resolved_url or get_data_sources_config().get_yaml_value("nasa_eonet_events.url")
|
||||
return str(val or NASA_EONET_URL_DEFAULT)
|
||||
|
||||
async def fetch(self) -> list[dict[str, Any]]:
|
||||
url = self._resolve_url()
|
||||
async with httpx.AsyncClient(timeout=20.0, follow_redirects=True) as client:
|
||||
resp = await client.get(url, headers={"User-Agent": "Planet-Intelligence-System/1.0"})
|
||||
resp.raise_for_status()
|
||||
payload = resp.json()
|
||||
return parse_nasa_eonet_events(payload, source=self.name)
|
||||
|
||||
def transform(self, raw_data: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
return [r for r in raw_data if isinstance(r, dict) and r.get("source_event_id")]
|
||||
|
||||
async def _save_data(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
data: list[dict[str, Any]],
|
||||
task_id: int | None = None,
|
||||
snapshot_id: int | None = None,
|
||||
) -> int:
|
||||
return await _persist_disaster_batch(db, source_name=self.name, records=data, snapshot_id=snapshot_id)
|
||||
|
||||
async def collect(self, db: AsyncSession, **kwargs) -> dict[str, Any]:
|
||||
records = self.transform(await self.fetch())
|
||||
saved = await self._save_data(db, records)
|
||||
await _mark_source_status(db, self.name, "success")
|
||||
return {"source": self.name, "status": "success", "records_saved": saved}
|
||||
@@ -0,0 +1,246 @@
|
||||
"""gpsjam.org daily H3 GNSS interference collector (Source 41)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import csv
|
||||
from datetime import UTC, datetime
|
||||
import io
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
import h3
|
||||
import httpx
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.data_sources import get_data_sources_config
|
||||
from app.core.enums import SnapshotStatus
|
||||
from app.core.logging import get_logger
|
||||
from app.core.websocket.broadcaster import broadcaster
|
||||
from app.models.data_snapshot import DataSnapshot
|
||||
from app.models.gps_jamming import GPSJammingCell
|
||||
from app.services.collectors.base import BaseCollector
|
||||
|
||||
logger = get_logger(__name__, service="collector.gps_jamming")
|
||||
|
||||
GPSJAM_MANIFEST_URL = "https://gpsjam.org/data/manifest.csv"
|
||||
GPSJAM_DATA_BASE_URL = "https://gpsjam.org/data"
|
||||
_DATE_RE = re.compile(r"\b(\d{4}-\d{2}-\d{2})\b")
|
||||
|
||||
|
||||
def parse_manifest_latest_date(manifest_text: str) -> str | None:
|
||||
"""Return the latest YYYY-MM-DD entry found in gpsjam manifest.csv."""
|
||||
dates = _DATE_RE.findall(manifest_text or "")
|
||||
return max(dates) if dates else None
|
||||
|
||||
|
||||
def classify_jamming_level(bad_ratio: float) -> str:
|
||||
"""Classify GNSS interference level from bad_ratio into low/medium/high."""
|
||||
if bad_ratio > 0.10:
|
||||
return "high"
|
||||
if bad_ratio >= 0.02:
|
||||
return "medium"
|
||||
return "low"
|
||||
|
||||
|
||||
def _pick_col(fieldnames: list[str], *candidates: str) -> str | None:
|
||||
lowered = {f.strip().lower(): f for f in fieldnames if f}
|
||||
for cand in candidates:
|
||||
if cand.lower() in lowered:
|
||||
return lowered[cand.lower()]
|
||||
return None
|
||||
|
||||
|
||||
def parse_gpsjam_csv(
|
||||
csv_text: str,
|
||||
*,
|
||||
observed_date: str,
|
||||
source: str = "gpsjam_interference",
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Parse gpsjam `{date}-h3_4.csv` text and generate H3 center & boundary polygons."""
|
||||
cleaned = str(csv_text or "").lstrip("\ufeff").strip()
|
||||
if not cleaned:
|
||||
return []
|
||||
|
||||
reader = csv.DictReader(io.StringIO(cleaned))
|
||||
fieldnames = list(reader.fieldnames or [])
|
||||
col_hex = _pick_col(fieldnames, "hex", "h3", "h3_index", "gnssCellKey")
|
||||
if not col_hex:
|
||||
return []
|
||||
col_good = _pick_col(fieldnames, "count_good_aircraft", "good", "good_count")
|
||||
col_bad = _pick_col(fieldnames, "count_bad_aircraft", "bad", "bad_count")
|
||||
col_total = _pick_col(fieldnames, "aircraft_count", "total")
|
||||
col_ratio = _pick_col(fieldnames, "bad_ratio", "ratio")
|
||||
|
||||
cells: dict[str, dict[str, Any]] = {}
|
||||
for row in reader:
|
||||
h3_index = str(row.get(col_hex) or "").strip()
|
||||
if not h3_index or not h3.is_valid_cell(h3_index):
|
||||
continue
|
||||
|
||||
good = int(float(row.get(col_good) or 0)) if col_good and row.get(col_good) not in (None, "") else 0
|
||||
bad = int(float(row.get(col_bad) or 0)) if col_bad and row.get(col_bad) not in (None, "") else 0
|
||||
total = (
|
||||
int(float(row.get(col_total)))
|
||||
if col_total and row.get(col_total) not in (None, "")
|
||||
else (good + bad)
|
||||
)
|
||||
if total <= 0 and bad <= 0:
|
||||
continue
|
||||
|
||||
if col_ratio and row.get(col_ratio) not in (None, ""):
|
||||
bad_ratio = max(0.0, min(1.0, float(row[col_ratio])))
|
||||
else:
|
||||
bad_ratio = (bad / total) if total > 0 else 0.0
|
||||
|
||||
if bad_ratio <= 0.0:
|
||||
continue
|
||||
|
||||
lat, lon = h3.cell_to_latlng(h3_index)
|
||||
boundary = [
|
||||
[round(float(b_lat), 5), round(float(b_lon), 5)]
|
||||
for b_lat, b_lon in h3.cell_to_boundary(h3_index)
|
||||
]
|
||||
cells[h3_index] = {
|
||||
"h3_index": h3_index,
|
||||
"observed_date": observed_date,
|
||||
"lat": round(float(lat), 5),
|
||||
"lon": round(float(lon), 5),
|
||||
"resolution": int(h3.get_resolution(h3_index)),
|
||||
"level": classify_jamming_level(bad_ratio),
|
||||
"bad_ratio": round(float(bad_ratio), 6),
|
||||
"aircraft_count": total,
|
||||
"boundary": boundary,
|
||||
"source": source,
|
||||
}
|
||||
return list(cells.values())
|
||||
|
||||
|
||||
class GPSJammingCollector(BaseCollector):
|
||||
"""Collect daily GPS/GNSS interference hexagons from gpsjam.org."""
|
||||
|
||||
name = "gpsjam_interference"
|
||||
priority = "P2"
|
||||
module = "L4"
|
||||
frequency_hours = 6
|
||||
data_type = "gps_jamming"
|
||||
fail_on_empty = False
|
||||
preserve_snapshot_on_failure = True
|
||||
|
||||
@property
|
||||
def manifest_url(self) -> str:
|
||||
return (
|
||||
self._resolved_url
|
||||
or get_data_sources_config().get_yaml_url(self.name)
|
||||
or GPSJAM_MANIFEST_URL
|
||||
)
|
||||
|
||||
@property
|
||||
def base_data_url(self) -> str:
|
||||
val = get_data_sources_config().get_yaml_value("gpsjam_interference.base_data_url")
|
||||
return str(val or GPSJAM_DATA_BASE_URL).rstrip("/")
|
||||
|
||||
async def fetch(self) -> list[dict[str, Any]]:
|
||||
async with httpx.AsyncClient(timeout=30.0, follow_redirects=True) as client:
|
||||
manifest_resp = await client.get(
|
||||
self.manifest_url,
|
||||
headers={"User-Agent": "Planet-Intelligence-System/1.0 (gpsjam)"},
|
||||
)
|
||||
manifest_resp.raise_for_status()
|
||||
latest_date = parse_manifest_latest_date(manifest_resp.text)
|
||||
if not latest_date:
|
||||
return []
|
||||
csv_url = f"{self.base_data_url}/{latest_date}-h3_4.csv"
|
||||
data_resp = await client.get(
|
||||
csv_url,
|
||||
headers={"User-Agent": "Planet-Intelligence-System/1.0 (gpsjam)"},
|
||||
)
|
||||
data_resp.raise_for_status()
|
||||
return parse_gpsjam_csv(data_resp.text, observed_date=latest_date, source=self.name)
|
||||
|
||||
def transform(self, raw_data: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
return [item for item in raw_data if isinstance(item, dict) and item.get("h3_index")]
|
||||
|
||||
async def _save_data(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
data: list[dict[str, Any]],
|
||||
task_id: int | None = None,
|
||||
snapshot_id: int | None = None,
|
||||
) -> int:
|
||||
now = datetime.now(UTC)
|
||||
dialect = getattr(getattr(db.get_bind(), "dialect", None), "name", "sqlite")
|
||||
written = 0
|
||||
|
||||
for offset in range(0, len(data), 500):
|
||||
batch = [{**row, "ingested_at": now} for row in data[offset : offset + 500]]
|
||||
if not batch:
|
||||
continue
|
||||
if dialect == "postgresql":
|
||||
stmt = pg_insert(GPSJammingCell).values(batch)
|
||||
stmt = stmt.on_conflict_do_update(
|
||||
index_elements=[GPSJammingCell.h3_index, GPSJammingCell.observed_date],
|
||||
set_={
|
||||
"lat": stmt.excluded.lat,
|
||||
"lon": stmt.excluded.lon,
|
||||
"resolution": stmt.excluded.resolution,
|
||||
"level": stmt.excluded.level,
|
||||
"bad_ratio": stmt.excluded.bad_ratio,
|
||||
"aircraft_count": stmt.excluded.aircraft_count,
|
||||
"boundary": stmt.excluded.boundary,
|
||||
"source": stmt.excluded.source,
|
||||
"ingested_at": stmt.excluded.ingested_at,
|
||||
},
|
||||
)
|
||||
await db.execute(stmt)
|
||||
else:
|
||||
stmt_sq = sqlite_insert(GPSJammingCell).values(batch)
|
||||
stmt_sq = stmt_sq.on_conflict_do_update(
|
||||
index_elements=[GPSJammingCell.h3_index, GPSJammingCell.observed_date],
|
||||
set_={
|
||||
"lat": stmt_sq.excluded.lat,
|
||||
"lon": stmt_sq.excluded.lon,
|
||||
"resolution": stmt_sq.excluded.resolution,
|
||||
"level": stmt_sq.excluded.level,
|
||||
"bad_ratio": stmt_sq.excluded.bad_ratio,
|
||||
"aircraft_count": stmt_sq.excluded.aircraft_count,
|
||||
"boundary": stmt_sq.excluded.boundary,
|
||||
"source": stmt_sq.excluded.source,
|
||||
"ingested_at": stmt_sq.excluded.ingested_at,
|
||||
},
|
||||
)
|
||||
await db.execute(stmt_sq)
|
||||
written += len(batch)
|
||||
|
||||
if snapshot_id is not None:
|
||||
snapshot = await db.get(DataSnapshot, snapshot_id)
|
||||
if snapshot:
|
||||
snapshot.record_count = written
|
||||
snapshot.status = SnapshotStatus.SUCCESS.value
|
||||
snapshot.completed_at = now
|
||||
snapshot.summary = {
|
||||
"created": written,
|
||||
"storage": "gps_jamming_cells",
|
||||
}
|
||||
await db.commit()
|
||||
|
||||
if written > 0:
|
||||
try:
|
||||
await broadcaster.broadcast_earth_update(
|
||||
{
|
||||
"event": "earth.layer.changed",
|
||||
"action": "database_changed",
|
||||
"source": self.name,
|
||||
"layers": ["gpsJamming"],
|
||||
"refresh_strategy": "reload",
|
||||
"records_processed": written,
|
||||
}
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed to broadcast gpsJamming update",
|
||||
event="gpsjam.broadcast_failed",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
return written
|
||||
@@ -0,0 +1,106 @@
|
||||
"""NGA MSI Maritime Navigation Warnings collector (Source 47)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from sqlalchemy import update
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.data_sources import get_data_sources_config
|
||||
from app.core.enums import SnapshotStatus
|
||||
from app.core.logging import get_logger
|
||||
from app.core.websocket.broadcaster import broadcaster
|
||||
from app.models.data_snapshot import DataSnapshot
|
||||
from app.models.datasource import DataSource
|
||||
from app.services.collectors.base import BaseCollector
|
||||
from app.services.nga_advisories import parse_nga_broadcast_warnings, upsert_cable_advisories
|
||||
|
||||
logger = get_logger(__name__, service="collector.nga_warnings")
|
||||
|
||||
NGA_WARNINGS_URL_DEFAULT = "https://msi.nga.mil/api/publications/broadcast-warn?output=json"
|
||||
|
||||
|
||||
class NGANavigationWarningsCollector(BaseCollector):
|
||||
"""Collector 47: NGA MSI maritime warnings filtered for submarine cable advisories."""
|
||||
|
||||
name = "nga_navigation_warnings"
|
||||
priority = "P1"
|
||||
module = "L4"
|
||||
frequency_hours = 6
|
||||
data_type = "cables"
|
||||
fail_on_empty = False
|
||||
preserve_snapshot_on_failure = True
|
||||
|
||||
def _resolve_url(self) -> str:
|
||||
val = self._resolved_url or get_data_sources_config().get_yaml_value(
|
||||
"nga_navigation_warnings.url"
|
||||
)
|
||||
return str(val or NGA_WARNINGS_URL_DEFAULT)
|
||||
|
||||
async def fetch(self) -> list[dict[str, Any]]:
|
||||
url = self._resolve_url()
|
||||
async with httpx.AsyncClient(timeout=25.0, follow_redirects=True) as client:
|
||||
resp = await client.get(url, headers={"User-Agent": "Planet-Intelligence-System/1.0"})
|
||||
resp.raise_for_status()
|
||||
payload = resp.json()
|
||||
return parse_nga_broadcast_warnings(payload)
|
||||
|
||||
def transform(self, raw_data: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
return [w for w in raw_data if isinstance(w, dict) and w.get("source_warning_id")]
|
||||
|
||||
async def _save_data(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
data: list[dict[str, Any]],
|
||||
task_id: int | None = None,
|
||||
snapshot_id: int | None = None,
|
||||
) -> int:
|
||||
saved = await upsert_cable_advisories(db, data)
|
||||
if snapshot_id is not None:
|
||||
snap = await db.get(DataSnapshot, snapshot_id)
|
||||
if snap is not None:
|
||||
snap.record_count = saved
|
||||
snap.status = SnapshotStatus.SUCCESS.value
|
||||
snap.completed_at = datetime.now(UTC)
|
||||
snap.summary = {"created": saved, "storage": "cable_advisories"}
|
||||
await db.commit()
|
||||
if saved > 0:
|
||||
try:
|
||||
await broadcaster.broadcast_earth_update(
|
||||
{
|
||||
"event": "earth.layer.changed",
|
||||
"action": "database_changed",
|
||||
"source": self.name,
|
||||
"layers": ["cables"],
|
||||
"refresh_strategy": "reload",
|
||||
"records_processed": saved,
|
||||
}
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed to broadcast NGA cable advisory update",
|
||||
event="nga_advisories.broadcast_failed",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
return saved
|
||||
|
||||
async def collect(self, db: AsyncSession, **kwargs) -> dict[str, Any]:
|
||||
records = self.transform(await self.fetch())
|
||||
saved = await self._save_data(db, records)
|
||||
try:
|
||||
await db.execute(
|
||||
update(DataSource)
|
||||
.where(DataSource.source == self.name)
|
||||
.values(last_status="success", last_run_at=datetime.now(UTC))
|
||||
)
|
||||
await db.commit()
|
||||
except Exception as exc:
|
||||
logger.debug_event(
|
||||
"Skipped datasource status update for NGA warnings",
|
||||
event="nga_advisories.status_update_skipped",
|
||||
context={"error_type": type(exc).__name__},
|
||||
)
|
||||
return {"source": self.name, "status": "success", "records_saved": saved}
|
||||
@@ -0,0 +1,403 @@
|
||||
"""OpenSky Network REST API ADS-B collector (Source 40) with OAuth2 client credentials & 429 cooldown."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from datetime import UTC, datetime, timedelta
|
||||
import os
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.data_sources import get_data_sources_config
|
||||
from app.core.enums import ConnectionState, SnapshotStatus
|
||||
from app.core.logging import get_logger
|
||||
from app.core.websocket.broadcaster import broadcaster
|
||||
from app.models.aircraft import ADSBSourceHealth
|
||||
from app.models.data_snapshot import DataSnapshot
|
||||
from app.models.datasource_config import DataSourceConfig
|
||||
from app.services.aircraft_aggregation import (
|
||||
DEFAULT_CURRENT_STALE_MINUTES,
|
||||
DEFAULT_POSITION_RETENTION_HOURS,
|
||||
coerce_utc_datetime,
|
||||
prune_aircraft_tables,
|
||||
update_adsb_source_health,
|
||||
upsert_aircraft_observations,
|
||||
)
|
||||
from app.services.barentswatch import _read_zshrc_env
|
||||
from app.services.collectors.base import BaseCollector
|
||||
|
||||
logger = get_logger(__name__, service="collector.opensky")
|
||||
|
||||
OPENSKY_STATES_URL = "https://opensky-network.org/api/states/all"
|
||||
OPENSKY_TOKEN_URL = "https://auth.opensky-network.org/auth/realms/opensky-network/protocol/openid-connect/token"
|
||||
TOKEN_REFRESH_BUFFER_SECONDS = 60
|
||||
DEFAULT_COOLDOWN_SECONDS = 900
|
||||
|
||||
# Mapping from OpenSky state vector category index (index 17) to ADS-B emitter categories
|
||||
_OPENSKY_CAT_TO_EMITTER: dict[int, str] = {
|
||||
2: "A1",
|
||||
3: "A2",
|
||||
4: "A3",
|
||||
5: "A4",
|
||||
6: "A5",
|
||||
8: "A7",
|
||||
}
|
||||
|
||||
_TOKEN_CACHE: dict[tuple[str, str], tuple[str, datetime]] = {}
|
||||
|
||||
|
||||
def clear_opensky_token_cache() -> None:
|
||||
"""Clear in-memory OAuth2 access token cache (mainly for testing)."""
|
||||
_TOKEN_CACHE.clear()
|
||||
|
||||
|
||||
async def resolve_opensky_credentials(
|
||||
db: AsyncSession | None = None,
|
||||
credential_override: dict[str, str] | None = None,
|
||||
) -> tuple[str, str, str, dict[str, Any]]:
|
||||
"""Resolve OpenSky OAuth2 client_id & client_secret plus runtime config."""
|
||||
runtime_cfg: dict[str, Any] = {}
|
||||
db_id = ""
|
||||
db_secret = ""
|
||||
if db is not None and callable(getattr(db, "execute", None)):
|
||||
try:
|
||||
res = await db.execute(
|
||||
select(DataSourceConfig)
|
||||
.where(DataSourceConfig.name == "opensky_aircraft")
|
||||
.where(DataSourceConfig.is_active.is_(True))
|
||||
)
|
||||
record = res.scalar_one_or_none()
|
||||
if record is not None:
|
||||
auth_cfg = record.auth_config or {}
|
||||
runtime_cfg = dict(record.config or {}) if isinstance(record.config, dict) else {}
|
||||
db_id = str(auth_cfg.get("client_id") or runtime_cfg.get("client_id") or "").strip()
|
||||
db_secret = str(auth_cfg.get("client_secret") or runtime_cfg.get("client_secret") or "").strip()
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Could not read OpenSky DataSourceConfig",
|
||||
event="opensky.config_read_failed",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
|
||||
zshrc_env = _read_zshrc_env()
|
||||
env_id = str(os.getenv("OPENSKY_CLIENT_ID") or zshrc_env.get("OPENSKY_CLIENT_ID") or "").strip()
|
||||
env_secret = str(os.getenv("OPENSKY_CLIENT_SECRET") or zshrc_env.get("OPENSKY_CLIENT_SECRET") or "").strip()
|
||||
|
||||
ov_id = str((credential_override or {}).get("client_id") or "").strip()
|
||||
ov_secret = str((credential_override or {}).get("client_secret") or "").strip()
|
||||
|
||||
if ov_id or ov_secret:
|
||||
return ov_id or db_id or env_id, ov_secret or db_secret or env_secret, "draft", runtime_cfg
|
||||
if db_id or db_secret:
|
||||
return db_id, db_secret, "datasource_config", runtime_cfg
|
||||
if env_id or env_secret:
|
||||
cred_source = "environment" if os.getenv("OPENSKY_CLIENT_ID") else "~/.zshrc"
|
||||
return env_id, env_secret, cred_source, runtime_cfg
|
||||
return "", "", "missing", runtime_cfg
|
||||
|
||||
|
||||
async def fetch_opensky_access_token(
|
||||
client: httpx.AsyncClient,
|
||||
*,
|
||||
client_id: str,
|
||||
client_secret: str,
|
||||
token_url: str = OPENSKY_TOKEN_URL,
|
||||
now: datetime | None = None,
|
||||
) -> str | None:
|
||||
"""Obtain and cache an OpenSky OAuth2 token until 60s before expiry."""
|
||||
if not client_id or not client_secret:
|
||||
return None
|
||||
ref_now = coerce_utc_datetime(now) if now else datetime.now(UTC)
|
||||
cache_key = (client_id, client_secret)
|
||||
cached = _TOKEN_CACHE.get(cache_key)
|
||||
if cached is not None:
|
||||
token, expires_at = cached
|
||||
if ref_now + timedelta(seconds=TOKEN_REFRESH_BUFFER_SECONDS) < expires_at:
|
||||
return token
|
||||
|
||||
response = await client.post(
|
||||
token_url,
|
||||
data={
|
||||
"grant_type": "client_credentials",
|
||||
"client_id": client_id,
|
||||
"client_secret": client_secret,
|
||||
},
|
||||
headers={"Content-Type": "application/x-www-form-urlencoded"},
|
||||
)
|
||||
response.raise_for_status()
|
||||
payload = response.json()
|
||||
token = str(payload.get("access_token") or "").strip()
|
||||
expires_in = int(payload.get("expires_in") or 1800)
|
||||
if not token:
|
||||
return None
|
||||
_TOKEN_CACHE[cache_key] = (token, ref_now + timedelta(seconds=max(expires_in, 120)))
|
||||
return token
|
||||
|
||||
|
||||
def parse_opensky_states_payload(
|
||||
payload: dict[str, Any],
|
||||
*,
|
||||
source: str = "opensky_aircraft",
|
||||
fallback_time: datetime | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Parse OpenSky `/api/states/all` response vectors into normalized aircraft observations."""
|
||||
ref_now = fallback_time or datetime.now(UTC)
|
||||
if payload.get("time") is not None:
|
||||
try:
|
||||
ref_now = datetime.fromtimestamp(float(payload["time"]), tz=UTC)
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
|
||||
states = payload.get("states")
|
||||
if not isinstance(states, list):
|
||||
return []
|
||||
|
||||
records: list[dict[str, Any]] = []
|
||||
for vec in states:
|
||||
if not isinstance(vec, (list, tuple)) or len(vec) < 11:
|
||||
continue
|
||||
icao24 = str(vec[0] or "").strip().lower()
|
||||
lon = vec[5]
|
||||
lat = vec[6]
|
||||
if len(icao24) != 6 or lat is None or lon is None:
|
||||
continue
|
||||
try:
|
||||
lat_f = float(lat)
|
||||
lon_f = float(lon)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
|
||||
pos_ts = vec[3] if vec[3] is not None else vec[4]
|
||||
obs_at = coerce_utc_datetime(pos_ts, fallback=ref_now) if pos_ts is not None else ref_now
|
||||
cat_num = vec[17] if len(vec) > 17 and vec[17] is not None else None
|
||||
emitter = _OPENSKY_CAT_TO_EMITTER.get(int(cat_num)) if isinstance(cat_num, (int, float)) else None
|
||||
squawk = str(vec[14] or "").strip()[:8] if len(vec) > 14 and vec[14] else None
|
||||
|
||||
records.append(
|
||||
{
|
||||
"icao24": icao24,
|
||||
"callsign": str(vec[1] or "").strip()[:16] or None,
|
||||
"lat": lat_f,
|
||||
"lon": lon_f,
|
||||
"baro_altitude_m": float(vec[7]) if vec[7] is not None else None,
|
||||
"geo_altitude_m": float(vec[13]) if len(vec) > 13 and vec[13] is not None else None,
|
||||
"ground_speed_ms": float(vec[9]) if vec[9] is not None else None,
|
||||
"track_deg": float(vec[10]) if vec[10] is not None else None,
|
||||
"vertical_rate_ms": float(vec[11]) if len(vec) > 11 and vec[11] is not None else None,
|
||||
"squawk": squawk,
|
||||
"on_ground": bool(vec[8]) if vec[8] is not None else False,
|
||||
"adsb_category": emitter,
|
||||
"source_is_military": False,
|
||||
"source": source,
|
||||
"observed_at": obs_at,
|
||||
}
|
||||
)
|
||||
return records
|
||||
|
||||
|
||||
class OpenSkyAircraftCollector(BaseCollector):
|
||||
"""Collect global/bbox aircraft states via OpenSky OAuth2 client credentials."""
|
||||
|
||||
name = "opensky_aircraft"
|
||||
priority = "P1"
|
||||
module = "L4"
|
||||
frequency_hours = 1
|
||||
data_type = "aircraft_adsb"
|
||||
fail_on_empty = False
|
||||
preserve_snapshot_on_failure = True
|
||||
|
||||
@property
|
||||
def states_url(self) -> str:
|
||||
return (
|
||||
self._resolved_url
|
||||
or get_data_sources_config().get_yaml_url(self.name)
|
||||
or OPENSKY_STATES_URL
|
||||
)
|
||||
|
||||
@property
|
||||
def token_url(self) -> str:
|
||||
val = get_data_sources_config().get_yaml_value("opensky_aircraft.token_url")
|
||||
return str(val or OPENSKY_TOKEN_URL)
|
||||
|
||||
async def _is_in_cooldown(self, now: datetime) -> bool:
|
||||
db = getattr(self, "_db_session", None)
|
||||
if db is None or not callable(getattr(db, "get", None)):
|
||||
return False
|
||||
health = await db.get(ADSBSourceHealth, self.name)
|
||||
if health and health.cooldown_until is not None:
|
||||
cooldown_dt = coerce_utc_datetime(health.cooldown_until)
|
||||
if cooldown_dt > now:
|
||||
return True
|
||||
return False
|
||||
|
||||
async def fetch(self) -> list[dict[str, Any]]:
|
||||
self._skip_reason: str | None = None
|
||||
self._cooldown_until: datetime | None = None
|
||||
now = datetime.now(UTC)
|
||||
|
||||
client_id, client_secret, _cred_src, runtime_cfg = await resolve_opensky_credentials(
|
||||
getattr(self, "_db_session", None)
|
||||
)
|
||||
if not client_id or not client_secret:
|
||||
self._skip_reason = "not_configured"
|
||||
return []
|
||||
|
||||
if await self._is_in_cooldown(now):
|
||||
self._skip_reason = "cooldown"
|
||||
return []
|
||||
|
||||
bboxes = runtime_cfg.get("bboxes") if isinstance(runtime_cfg.get("bboxes"), list) else []
|
||||
request_interval = float(runtime_cfg.get("request_interval_seconds") or 1.5)
|
||||
targets = bboxes[:6] if bboxes else [None]
|
||||
|
||||
records: list[dict[str, Any]] = []
|
||||
async with httpx.AsyncClient(timeout=30.0, follow_redirects=True) as client:
|
||||
token = await fetch_opensky_access_token(
|
||||
client,
|
||||
client_id=client_id,
|
||||
client_secret=client_secret,
|
||||
token_url=self.token_url,
|
||||
now=now,
|
||||
)
|
||||
if not token:
|
||||
self._skip_reason = "token_empty"
|
||||
return []
|
||||
|
||||
headers = {
|
||||
"Authorization": f"Bearer {token}",
|
||||
"User-Agent": "Planet-Intelligence-System/1.0 (opensky research)",
|
||||
}
|
||||
for idx, bbox in enumerate(targets):
|
||||
if idx > 0 and request_interval > 0:
|
||||
await asyncio.sleep(request_interval)
|
||||
params: dict[str, Any] = {"extended": "1"}
|
||||
if isinstance(bbox, dict):
|
||||
for key in ("lamin", "lomin", "lamax", "lomax"):
|
||||
if bbox.get(key) is not None:
|
||||
params[key] = bbox[key]
|
||||
elif isinstance(bbox, (list, tuple)) and len(bbox) == 4:
|
||||
params.update(
|
||||
{
|
||||
"lamin": bbox[0],
|
||||
"lomin": bbox[1],
|
||||
"lamax": bbox[2],
|
||||
"lomax": bbox[3],
|
||||
}
|
||||
)
|
||||
resp = await client.get(self.states_url, params=params, headers=headers)
|
||||
if resp.status_code == 429:
|
||||
retry_after = resp.headers.get("Retry-After") or resp.headers.get("X-Rate-Limit-Retry-After-Seconds")
|
||||
try:
|
||||
cooldown_sec = max(60, int(float(retry_after))) if retry_after else DEFAULT_COOLDOWN_SECONDS
|
||||
except ValueError:
|
||||
cooldown_sec = DEFAULT_COOLDOWN_SECONDS
|
||||
self._skip_reason = "rate_limited"
|
||||
self._cooldown_until = now + timedelta(seconds=cooldown_sec)
|
||||
break
|
||||
resp.raise_for_status()
|
||||
payload = resp.json()
|
||||
if isinstance(payload, dict):
|
||||
records.extend(parse_opensky_states_payload(payload, source=self.name))
|
||||
return records
|
||||
|
||||
def transform(self, raw_data: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
return [item for item in raw_data if isinstance(item, dict) and item.get("icao24")]
|
||||
|
||||
async def _save_data(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
data: list[dict[str, Any]],
|
||||
task_id: int | None = None,
|
||||
snapshot_id: int | None = None,
|
||||
) -> int:
|
||||
now = datetime.now(UTC)
|
||||
skip_reason = getattr(self, "_skip_reason", None)
|
||||
cooldown_until = getattr(self, "_cooldown_until", None)
|
||||
|
||||
if skip_reason == "not_configured":
|
||||
await update_adsb_source_health(
|
||||
db,
|
||||
source=self.name,
|
||||
connection_state="not_configured",
|
||||
active_count=0,
|
||||
last_error="OpenSky credentials not configured",
|
||||
)
|
||||
await db.commit()
|
||||
return 0
|
||||
|
||||
if skip_reason == "rate_limited" and cooldown_until is not None:
|
||||
await update_adsb_source_health(
|
||||
db,
|
||||
source=self.name,
|
||||
connection_state="cooldown",
|
||||
active_count=0,
|
||||
last_error="HTTP 429 Too Many Requests",
|
||||
cooldown_until=cooldown_until,
|
||||
)
|
||||
await db.commit()
|
||||
return 0
|
||||
|
||||
if skip_reason == "cooldown":
|
||||
return 0
|
||||
|
||||
_, _, _, runtime_cfg = await resolve_opensky_credentials(db)
|
||||
stale_minutes = int(runtime_cfg.get("current_stale_minutes") or DEFAULT_CURRENT_STALE_MINUTES)
|
||||
retention_hours = int(runtime_cfg.get("position_retention_hours") or DEFAULT_POSITION_RETENTION_HOURS)
|
||||
|
||||
summary = await upsert_aircraft_observations(
|
||||
db,
|
||||
data,
|
||||
default_source=self.name,
|
||||
ingested_at=now,
|
||||
)
|
||||
await prune_aircraft_tables(
|
||||
db,
|
||||
current_stale_minutes=stale_minutes,
|
||||
position_retention_hours=retention_hours,
|
||||
now=now,
|
||||
)
|
||||
await update_adsb_source_health(
|
||||
db,
|
||||
source=self.name,
|
||||
connection_state=ConnectionState.CONNECTED.value,
|
||||
active_count=summary["states_upserted"],
|
||||
last_success_at=now,
|
||||
last_error=None,
|
||||
clear_cooldown=True,
|
||||
)
|
||||
|
||||
if snapshot_id is not None:
|
||||
snapshot = await db.get(DataSnapshot, snapshot_id)
|
||||
if snapshot:
|
||||
snapshot.record_count = summary["states_upserted"]
|
||||
snapshot.status = SnapshotStatus.SUCCESS.value
|
||||
snapshot.completed_at = now
|
||||
snapshot.summary = {
|
||||
"created": summary["states_upserted"],
|
||||
"positions_inserted": summary["positions_inserted"],
|
||||
"storage": "aircraft_current_state_and_24h_position",
|
||||
}
|
||||
await db.commit()
|
||||
|
||||
if summary["states_upserted"] > 0:
|
||||
try:
|
||||
await broadcaster.broadcast_earth_update(
|
||||
{
|
||||
"event": "earth.layer.changed",
|
||||
"action": "database_changed",
|
||||
"source": self.name,
|
||||
"layers": ["aircraft"],
|
||||
"refresh_strategy": "reload",
|
||||
"records_processed": summary["states_upserted"],
|
||||
}
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed to broadcast aircraft update after OpenSky ingestion",
|
||||
event="opensky.broadcast_failed",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
return summary["states_upserted"]
|
||||
@@ -156,11 +156,65 @@ SPACETRACK_DEFAULT_GUIDE = CredentialGuideDefault(
|
||||
""",
|
||||
)
|
||||
|
||||
OPENSKY_DEFAULT_GUIDE = CredentialGuideDefault(
|
||||
provider="opensky",
|
||||
title="OpenSky Network OAuth2 凭证获取教程",
|
||||
prompt=(
|
||||
"请生成一份中文教程,指导开发者为 OpenSky Network REST API 申请 OAuth2 Client Credentials 并配置到 Planet。"
|
||||
"包含注册/登录 OpenSky、创建 API client 获取 Client ID 与 Client Secret、仅限非商业/研究用途的使用条款、"
|
||||
"在 Planet 采集器配置页填写并配置 bbox、连接测试与 429 冷却机制。"
|
||||
),
|
||||
markdown="""## OpenSky Network OAuth2 凭证获取
|
||||
|
||||
官方入口:https://opensky-network.org/
|
||||
|
||||
> **许可与合规提示**:OpenSky 实时空域数据**仅限非商业 / 研究用途**,请勿用于商业分发或高频无节制抓取。
|
||||
|
||||
1. 前往 OpenSky Network 官网注册或登录账号。
|
||||
2. 在账号安全 / API Client 管理页面创建一个新的 `OAuth2 Client`(`client_credentials` 模式)。
|
||||
3. 复制生成的 `Client ID` 与 `Client Secret`。
|
||||
4. 回到 Planet 的 `设置 / 资源配置 -> opensky_aircraft`,填入 `Client ID` 和 `Client Secret`(或通过环境变量 `OPENSKY_CLIENT_ID` / `OPENSKY_CLIENT_SECRET` 注入)。
|
||||
5. 建议先配置 1–3 个关注区域的 `Bounding Boxes`,降低额度消耗并提高刷新稳定性。
|
||||
6. 点击「连接测试」验证 Token 获取与 `/api/states/all` 连通性后保存。
|
||||
|
||||
### 常见排查
|
||||
|
||||
- 未配置凭证时,采集器会安静跳过并显示“未配置”。
|
||||
- 遇到上游 `HTTP 429` 限流时,采集器会自动写入 `cooldown_until` 并暂停请求直到冷却结束。
|
||||
""",
|
||||
)
|
||||
|
||||
|
||||
NASA_FIRMS_DEFAULT_GUIDE = CredentialGuideDefault(
|
||||
provider="nasa_firms",
|
||||
title="NASA FIRMS MAP_KEY 凭证获取教程",
|
||||
prompt=(
|
||||
"请生成一份中文教程,指导开发者申请 NASA FIRMS MAP_KEY 并在 Planet 中配置 `nasa_firms_wildfires`。"
|
||||
"包含官方入口 `https://firms.modaps.eosdis.nasa.gov/api/map_key/`、邮箱申请步骤、环境变量 `NASA_FIRMS_MAP_KEY` "
|
||||
"与采集器配置页面填写位置、速率配额提示。"
|
||||
),
|
||||
markdown="""## NASA FIRMS MAP_KEY 获取教程
|
||||
|
||||
官方申请入口:https://firms.modaps.eosdis.nasa.gov/api/map_key/
|
||||
|
||||
1. 打开 NASA FIRMS API MAP_KEY 页面,填写个人或机构邮箱申请免费的 `MAP_KEY`。
|
||||
2. 查收确认邮件,复制系统发放的 32 位 `MAP_KEY`。
|
||||
3. 回到 Planet 的「设置 / 资源配置 -> `nasa_firms_wildfires`」,在 `API Key / MAP_KEY` 中填入密钥(或通过环境变量 `NASA_FIRMS_MAP_KEY` 注入)。
|
||||
4. 保存后点击「连接测试」验证 VIIRS 近实时热点接口连通性。
|
||||
|
||||
### 说明与限制
|
||||
|
||||
- 未配置 `MAP_KEY` 时,采集器会保持 `not_configured` 状态,不影响其他自然灾害源(USGS、GDACS、EONET)采集。
|
||||
- VIIRS 热点按 `0.25°` 空间网格聚合成热点簇存储,单次全量采集遵守 NASA FIRMS 10 分钟交易配额限制。
|
||||
""",
|
||||
)
|
||||
|
||||
DEFAULT_CREDENTIAL_GUIDES = {
|
||||
BARENTSWATCH_DEFAULT_GUIDE.provider: BARENTSWATCH_DEFAULT_GUIDE,
|
||||
AISSTREAM_DEFAULT_GUIDE.provider: AISSTREAM_DEFAULT_GUIDE,
|
||||
SPACETRACK_DEFAULT_GUIDE.provider: SPACETRACK_DEFAULT_GUIDE,
|
||||
OPENSKY_DEFAULT_GUIDE.provider: OPENSKY_DEFAULT_GUIDE,
|
||||
NASA_FIRMS_DEFAULT_GUIDE.provider: NASA_FIRMS_DEFAULT_GUIDE,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -628,6 +628,42 @@ async def _clear_derived_datasource_data_in_batches(
|
||||
progress_offset=progress_offset + sum(deleted_counts.values()),
|
||||
)
|
||||
return deleted_counts
|
||||
if source in {"adsb_lol_aircraft", "opensky_aircraft"}:
|
||||
from app.models.aircraft import ADSBSourceHealth, AircraftCurrentState
|
||||
|
||||
res_curr = await db.execute(
|
||||
AircraftCurrentState.__table__.delete().where(AircraftCurrentState.source == source)
|
||||
)
|
||||
res_health = await db.execute(
|
||||
ADSBSourceHealth.__table__.delete().where(ADSBSourceHealth.source == source)
|
||||
)
|
||||
await db.commit()
|
||||
return {
|
||||
"aircraft_current_state": int(res_curr.rowcount or 0),
|
||||
"adsb_source_health": int(res_health.rowcount or 0),
|
||||
}
|
||||
if source == "gpsjam_interference":
|
||||
from app.models.gps_jamming import GPSJammingCell
|
||||
|
||||
res_cells = await db.execute(
|
||||
GPSJammingCell.__table__.delete().where(GPSJammingCell.source == source)
|
||||
)
|
||||
await db.commit()
|
||||
return {"gps_jamming_cells": int(res_cells.rowcount or 0)}
|
||||
if source in {"usgs_earthquakes", "nasa_firms_wildfires", "gdacs_disasters", "nasa_eonet_events"}:
|
||||
from app.models.disaster import DisasterEvent
|
||||
|
||||
res_ev = await db.execute(
|
||||
DisasterEvent.__table__.delete().where(DisasterEvent.source == source)
|
||||
)
|
||||
await db.commit()
|
||||
return {"disaster_events": int(res_ev.rowcount or 0)}
|
||||
if source == "nga_navigation_warnings":
|
||||
from app.models.maritime_advisory import CableAdvisory
|
||||
|
||||
res_adv = await db.execute(CableAdvisory.__table__.delete())
|
||||
await db.commit()
|
||||
return {"cable_advisories": int(res_adv.rowcount or 0)}
|
||||
if source == "global_cloud_map":
|
||||
from app.services.earth_clouds import clear_all_cloud_map_artifacts
|
||||
|
||||
|
||||
@@ -28,11 +28,16 @@ from app.services.barentswatch import (
|
||||
fetch_barentswatch_access_token,
|
||||
resolve_barentswatch_config,
|
||||
)
|
||||
from app.services.collectors.opensky import (
|
||||
OPENSKY_TOKEN_URL,
|
||||
fetch_opensky_access_token,
|
||||
resolve_opensky_credentials,
|
||||
)
|
||||
|
||||
|
||||
CONNECTIVITY_VALIDATION_KEY = "connectivity_validation"
|
||||
CONNECTIVITY_STORE_CATEGORY = "datasource_connectivity_validations"
|
||||
SUPPORTED_CREDENTIAL_PROVIDERS = {"barentswatch", "spacetrack", "aisstream"}
|
||||
SUPPORTED_CREDENTIAL_PROVIDERS = {"barentswatch", "spacetrack", "aisstream", "opensky", "nasa_firms"}
|
||||
_ARCGIS_SOURCES = frozenset(
|
||||
{"arcgis_cables", "arcgis_landing_points", "arcgis_cable_landing_relation"}
|
||||
)
|
||||
@@ -156,6 +161,45 @@ async def _resolve_aisstream_api_key(
|
||||
return "", "missing"
|
||||
|
||||
|
||||
async def resolve_nasa_firms_map_key(
|
||||
db=None,
|
||||
credential_override: dict[str, str] | None = None,
|
||||
) -> tuple[str, str]:
|
||||
ov_key = _clean_override_value(credential_override, "api_key", secret=True)
|
||||
if ov_key:
|
||||
return ov_key, "draft"
|
||||
|
||||
if db is not None:
|
||||
try:
|
||||
result = await db.execute(
|
||||
select(DataSourceConfig)
|
||||
.where(DataSourceConfig.name == "nasa_firms_wildfires")
|
||||
.where(DataSourceConfig.is_active.is_(True))
|
||||
)
|
||||
record = result.scalar_one_or_none()
|
||||
if record is not None:
|
||||
auth_config = record.auth_config or {}
|
||||
runtime_config = record.config or {}
|
||||
map_key = str(
|
||||
auth_config.get("api_key")
|
||||
or auth_config.get("map_key")
|
||||
or runtime_config.get("map_key")
|
||||
or ""
|
||||
).strip()
|
||||
if map_key:
|
||||
return map_key, "datasource_config"
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
env_key = os.getenv("NASA_FIRMS_MAP_KEY")
|
||||
if env_key and str(env_key).strip():
|
||||
return str(env_key).strip(), "environment"
|
||||
zshrc_key = _read_zshrc_env().get("NASA_FIRMS_MAP_KEY")
|
||||
if zshrc_key and str(zshrc_key).strip():
|
||||
return str(zshrc_key).strip(), "~/.zshrc"
|
||||
return "", "missing"
|
||||
|
||||
|
||||
def strip_connectivity_validation(config: dict | None) -> dict:
|
||||
cleaned = dict(config or {})
|
||||
cleaned.pop(CONNECTIVITY_VALIDATION_KEY, None)
|
||||
@@ -219,6 +263,20 @@ async def build_builtin_connectivity_checksum(
|
||||
api_key, credential_source = await _resolve_aisstream_api_key(db, credential_override)
|
||||
has_credentials = bool(api_key)
|
||||
credential_fingerprint = _sha256_json({"api_key": api_key})
|
||||
elif credential_provider == "opensky":
|
||||
client_id, client_secret, credential_source, _cfg = await resolve_opensky_credentials(
|
||||
db, credential_override
|
||||
)
|
||||
has_credentials = bool(client_id and client_secret)
|
||||
credential_fingerprint = _sha256_json(
|
||||
{"client_id": client_id, "client_secret": client_secret}
|
||||
)
|
||||
elif credential_provider == "nasa_firms":
|
||||
map_key, credential_source = await resolve_nasa_firms_map_key(
|
||||
db, credential_override
|
||||
)
|
||||
has_credentials = bool(map_key)
|
||||
credential_fingerprint = _sha256_json({"api_key": map_key})
|
||||
elif defaults.get("requires_credentials"):
|
||||
credential_source = str(credential_provider or "unsupported")
|
||||
|
||||
@@ -307,6 +365,18 @@ def _prepare_builtin_http_probe(
|
||||
"vgrd10m[(last)][(-10):10:(10)][(0):10:(10)]"
|
||||
)
|
||||
probe_headers.setdefault("User-Agent", "Planet-Intelligence-System/1.0 (Python/collector)")
|
||||
elif source == "adsb_lol_aircraft":
|
||||
base = probe_url.rstrip("/")
|
||||
probe_url = f"{base}/v2/sqk/7700" if not base.endswith("/7700") else base
|
||||
probe_headers.setdefault("User-Agent", "Planet-Intelligence-System/1.0 (adsb.lol ODbL)")
|
||||
elif source == "opensky_aircraft":
|
||||
if "?" not in probe_url:
|
||||
probe_params = {"lamin": 45.8, "lomin": 5.9, "lamax": 47.8, "lomax": 10.5}
|
||||
probe_headers.setdefault("User-Agent", "Planet-Intelligence-System/1.0 (opensky research)")
|
||||
elif source in {"gpsjam_interference", "aircraft_registry"}:
|
||||
probe_headers.setdefault("User-Agent", "Planet-Intelligence-System/1.0 (Python/collector)")
|
||||
elif source in {"usgs_earthquakes", "gdacs_disasters", "nasa_eonet_events", "nga_navigation_warnings"}:
|
||||
probe_headers.setdefault("User-Agent", "Planet-Intelligence-System/1.0 (Python/collector)")
|
||||
return probe_url, probe_params, probe_headers
|
||||
|
||||
|
||||
@@ -516,6 +586,11 @@ async def test_builtin_connectivity(
|
||||
**credential_context,
|
||||
}
|
||||
request_headers["Authorization"] = f"Bearer {token}"
|
||||
elif credential_context["credential_provider"] == "nasa_firms":
|
||||
map_key, _src = await resolve_nasa_firms_map_key(db, credential_override)
|
||||
base_csv = probe_url.rstrip("/")
|
||||
probe_url = f"{base_csv}/{map_key}/VIIRS_SNPP_NRT/-10,-10,10,10/1"
|
||||
request_headers.setdefault("User-Agent", "Planet-Intelligence-System/1.0 (NASA FIRMS client)")
|
||||
elif credential_context["credential_provider"] == "spacetrack":
|
||||
username, password, _source = await resolve_spacetrack_credentials(
|
||||
db, credential_override
|
||||
@@ -529,6 +604,30 @@ async def test_builtin_connectivity(
|
||||
},
|
||||
)
|
||||
login_response.raise_for_status()
|
||||
elif credential_context["credential_provider"] == "opensky":
|
||||
client_id, client_secret, _src, _cfg = await resolve_opensky_credentials(
|
||||
db, credential_override
|
||||
)
|
||||
token_url = str(
|
||||
get_data_sources_config().get_yaml_value("opensky_aircraft.token_url")
|
||||
or OPENSKY_TOKEN_URL
|
||||
)
|
||||
token = await fetch_opensky_access_token(
|
||||
client,
|
||||
client_id=client_id,
|
||||
client_secret=client_secret,
|
||||
token_url=token_url,
|
||||
)
|
||||
if not token:
|
||||
return {
|
||||
"success": False,
|
||||
"checksum": checksum,
|
||||
"stage": "token",
|
||||
"message": "OpenSky OAuth2 响应未包含 access_token。",
|
||||
"settings_tab": "collector_credentials",
|
||||
**credential_context,
|
||||
}
|
||||
request_headers["Authorization"] = f"Bearer {token}"
|
||||
|
||||
started = datetime.now(UTC)
|
||||
async with client.stream(
|
||||
|
||||
@@ -0,0 +1,533 @@
|
||||
"""Natural disaster parsing, wildfire 0.25-deg clustering, and 0.1-deg cross-source dedup."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import csv
|
||||
from datetime import UTC, datetime, timedelta
|
||||
import io
|
||||
import math
|
||||
import re
|
||||
from typing import Any
|
||||
from urllib.parse import urlsplit
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.logging import get_logger
|
||||
from app.models.disaster import DisasterEvent
|
||||
|
||||
logger = get_logger(__name__, service="disaster_aggregation")
|
||||
|
||||
DISASTER_TYPES = (
|
||||
"earthquake",
|
||||
"wildfire",
|
||||
"cyclone",
|
||||
"flood",
|
||||
"volcano",
|
||||
"drought",
|
||||
"other",
|
||||
)
|
||||
|
||||
SOURCE_DEDUP_PRIORITY = {
|
||||
"usgs_earthquakes": 1,
|
||||
"gdacs_disasters": 2,
|
||||
"nasa_eonet_events": 3,
|
||||
"nasa_firms_wildfires": 4,
|
||||
}
|
||||
|
||||
|
||||
def _coerce_utc(value: Any, fallback: datetime | None = None) -> datetime:
|
||||
if isinstance(value, datetime):
|
||||
return value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
|
||||
if isinstance(value, (int, float)):
|
||||
num = float(value)
|
||||
if num > 1e11: # epoch ms (USGS)
|
||||
num /= 1000.0
|
||||
try:
|
||||
return datetime.fromtimestamp(num, tz=UTC)
|
||||
except (OverflowError, OSError, ValueError):
|
||||
pass
|
||||
if isinstance(value, str):
|
||||
text = value.strip()
|
||||
if text:
|
||||
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:
|
||||
pass
|
||||
for fmt in ("%a, %d %b %Y %H:%M:%S %Z", "%Y-%m-%d %H:%M:%S"):
|
||||
try:
|
||||
return datetime.strptime(text, fmt).replace(tzinfo=UTC)
|
||||
except ValueError:
|
||||
continue
|
||||
return fallback or datetime.now(UTC)
|
||||
|
||||
|
||||
def _safe_float(val: Any) -> float | None:
|
||||
if val is None or val == "":
|
||||
return None
|
||||
try:
|
||||
f = float(val)
|
||||
return f if math.isfinite(f) else None
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _sanitize_url(url: Any) -> str | None:
|
||||
text = str(url or "").strip()
|
||||
if not text:
|
||||
return None
|
||||
parts = urlsplit(text)
|
||||
if parts.scheme in {"http", "https"} and parts.netloc:
|
||||
return text
|
||||
return None
|
||||
|
||||
|
||||
def _map_gdacs_type(raw_type: str) -> str:
|
||||
code = str(raw_type or "").strip().upper()
|
||||
mapping = {
|
||||
"EQ": "earthquake",
|
||||
"TC": "cyclone",
|
||||
"FL": "flood",
|
||||
"VO": "volcano",
|
||||
"DR": "drought",
|
||||
"WF": "wildfire",
|
||||
}
|
||||
return mapping.get(code, "other")
|
||||
|
||||
|
||||
def _map_eonet_category(categories: list[dict[str, Any]]) -> tuple[str, bool]:
|
||||
"""Return `(normalized_event_type, is_excluded_earthquake)`."""
|
||||
for cat in categories or []:
|
||||
cid = str(cat.get("id") or "").strip().lower()
|
||||
ctitle = str(cat.get("title") or "").strip().lower()
|
||||
if cid == "earthquakes" or "earthquake" in ctitle:
|
||||
return "earthquake", True
|
||||
if cid == "wildfires" or "wildfire" in ctitle or "fire" in ctitle:
|
||||
return "wildfire", False
|
||||
if cid in {"severestorms", "severe storms", "storms"} or "cyclone" in ctitle or "storm" in ctitle:
|
||||
return "cyclone", False
|
||||
if cid == "floods" or "flood" in ctitle:
|
||||
return "flood", False
|
||||
if cid == "volcanoes" or "volcan" in ctitle:
|
||||
return "volcano", False
|
||||
if cid == "drought" or "drought" in ctitle:
|
||||
return "drought", False
|
||||
return "other", False
|
||||
|
||||
|
||||
def _extract_centroid(geometry: dict[str, Any] | None) -> tuple[float, float] | None:
|
||||
if not isinstance(geometry, dict):
|
||||
return None
|
||||
gtype = str(geometry.get("type") or "").strip()
|
||||
coords = geometry.get("coordinates")
|
||||
if gtype == "Point" and isinstance(coords, (list, tuple)) and len(coords) >= 2:
|
||||
lon, lat = _safe_float(coords[0]), _safe_float(coords[1])
|
||||
if lat is not None and lon is not None and -90 <= lat <= 90 and -180 <= lon <= 180:
|
||||
return lat, lon
|
||||
if gtype == "Polygon" and isinstance(coords, list) and coords and isinstance(coords[0], list):
|
||||
ring = [pt for pt in coords[0] if isinstance(pt, (list, tuple)) and len(pt) >= 2]
|
||||
if ring:
|
||||
lons = [_safe_float(pt[0]) for pt in ring]
|
||||
lats = [_safe_float(pt[1]) for pt in ring]
|
||||
valid_lons = [x for x in lons if x is not None]
|
||||
valid_lats = [y for y in lats if y is not None]
|
||||
if valid_lons and valid_lats:
|
||||
return sum(valid_lats) / len(valid_lats), sum(valid_lons) / len(valid_lons)
|
||||
return None
|
||||
|
||||
|
||||
def parse_usgs_earthquakes(payload: dict[str, Any], *, source: str = "usgs_earthquakes") -> list[dict[str, Any]]:
|
||||
"""Parse USGS M4.5+ GeoJSON feed into normalized disaster records."""
|
||||
if not isinstance(payload, dict):
|
||||
return []
|
||||
now = datetime.now(UTC)
|
||||
items: list[dict[str, Any]] = []
|
||||
for feat in payload.get("features") or []:
|
||||
if not isinstance(feat, dict):
|
||||
continue
|
||||
props = feat.get("properties") or {}
|
||||
centroid = _extract_centroid(feat.get("geometry"))
|
||||
if centroid is None:
|
||||
continue
|
||||
lat, lon = centroid
|
||||
mag = _safe_float(props.get("mag"))
|
||||
event_id = str(feat.get("id") or props.get("code") or f"{lat:.3f}:{lon:.3f}").strip()
|
||||
if not event_id:
|
||||
continue
|
||||
alert = str(props.get("alert") or "").strip().lower()
|
||||
if (mag is not None and mag >= 6.5) or alert in {"red", "orange"}:
|
||||
severity = "high"
|
||||
elif mag is not None and mag >= 5.2:
|
||||
severity = "medium"
|
||||
else:
|
||||
severity = "low"
|
||||
obs = _coerce_utc(props.get("time"), fallback=now)
|
||||
items.append(
|
||||
{
|
||||
"source": source,
|
||||
"source_event_id": event_id[:160],
|
||||
"event_type": "earthquake",
|
||||
"severity": severity,
|
||||
"title": str(props.get("title") or props.get("place") or f"M{mag or '?'} Earthquake")[:500],
|
||||
"lat": round(lat, 5),
|
||||
"lon": round(lon, 5),
|
||||
"magnitude": mag,
|
||||
"started_at": obs,
|
||||
"ended_at": None,
|
||||
"url": _sanitize_url(props.get("url")),
|
||||
"observed_at": obs,
|
||||
"cluster_count": 1,
|
||||
"max_brightness_k": None,
|
||||
"raw": {"mag": mag, "place": props.get("place"), "alert": props.get("alert")},
|
||||
}
|
||||
)
|
||||
return items
|
||||
|
||||
|
||||
def parse_nasa_firms_csv(
|
||||
csv_text: str,
|
||||
*,
|
||||
source: str = "nasa_firms_wildfires",
|
||||
grid_deg: float = 0.25,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Aggregate NASA FIRMS VIIRS hotspots into 0.25-degree grid clusters."""
|
||||
cleaned = str(csv_text or "").lstrip("\ufeff").strip()
|
||||
if not cleaned:
|
||||
return []
|
||||
reader = csv.DictReader(io.StringIO(cleaned))
|
||||
if not reader.fieldnames:
|
||||
return []
|
||||
|
||||
buckets: dict[tuple[str, int, int], dict[str, Any]] = {}
|
||||
now = datetime.now(UTC)
|
||||
|
||||
for row in reader:
|
||||
lat = _safe_float(row.get("latitude") or row.get("lat"))
|
||||
lon = _safe_float(row.get("longitude") or row.get("lon"))
|
||||
if lat is None or lon is None or not (-90 <= lat <= 90 and -180 <= lon <= 180):
|
||||
continue
|
||||
brightness = _safe_float(row.get("bright_ti4") or row.get("brightness"))
|
||||
acq_date = str(row.get("acq_date") or now.date().isoformat()).strip()
|
||||
acq_time = str(row.get("acq_time") or "0000").strip().zfill(4)
|
||||
hh = acq_time[:2] if acq_time[:2].isdigit() else "00"
|
||||
mm = acq_time[2:4] if acq_time[2:4].isdigit() else "00"
|
||||
obs = _coerce_utc(f"{acq_date}T{hh}:{mm}:00+00:00", fallback=now)
|
||||
|
||||
lat_bin = int(math.floor((lat + 90.0) / grid_deg))
|
||||
lon_bin = int(math.floor((lon + 180.0) / grid_deg))
|
||||
key = (acq_date, lat_bin, lon_bin)
|
||||
bucket = buckets.get(key)
|
||||
if bucket is None:
|
||||
buckets[key] = {
|
||||
"lat_sum": lat,
|
||||
"lon_sum": lon,
|
||||
"count": 1,
|
||||
"max_k": brightness,
|
||||
"max_obs": obs,
|
||||
"acq_date": acq_date,
|
||||
"lat_bin": lat_bin,
|
||||
"lon_bin": lon_bin,
|
||||
}
|
||||
else:
|
||||
bucket["lat_sum"] += lat
|
||||
bucket["lon_sum"] += lon
|
||||
bucket["count"] += 1
|
||||
if brightness is not None and (bucket["max_k"] is None or brightness > bucket["max_k"]):
|
||||
bucket["max_k"] = brightness
|
||||
if obs > bucket["max_obs"]:
|
||||
bucket["max_obs"] = obs
|
||||
|
||||
results: list[dict[str, Any]] = []
|
||||
for bucket in buckets.values():
|
||||
cnt = bucket["count"]
|
||||
avg_lat = round(bucket["lat_sum"] / cnt, 4)
|
||||
avg_lon = round(bucket["lon_sum"] / cnt, 4)
|
||||
max_k = bucket["max_k"]
|
||||
if cnt >= 10 or (max_k is not None and max_k >= 360.0):
|
||||
severity = "high"
|
||||
elif cnt >= 3 or (max_k is not None and max_k >= 330.0):
|
||||
severity = "medium"
|
||||
else:
|
||||
severity = "low"
|
||||
temp_label = f" · 最高 {max_k:.1f}K" if max_k is not None else ""
|
||||
results.append(
|
||||
{
|
||||
"source": source,
|
||||
"source_event_id": f"firms:{bucket['acq_date']}:{bucket['lat_bin']}:{bucket['lon_bin']}",
|
||||
"event_type": "wildfire",
|
||||
"severity": severity,
|
||||
"title": f"NASA FIRMS 林火热点簇({cnt} 热点{temp_label})",
|
||||
"lat": avg_lat,
|
||||
"lon": avg_lon,
|
||||
"magnitude": max_k,
|
||||
"started_at": bucket["max_obs"],
|
||||
"ended_at": None,
|
||||
"url": "https://firms.modaps.eosdis.nasa.gov/map/",
|
||||
"observed_at": bucket["max_obs"],
|
||||
"cluster_count": cnt,
|
||||
"max_brightness_k": max_k,
|
||||
"raw": {"grid_deg": grid_deg, "acq_date": bucket["acq_date"], "cluster_count": cnt},
|
||||
}
|
||||
)
|
||||
return results
|
||||
|
||||
|
||||
def parse_gdacs_events(raw_body: dict[str, Any] | str, *, source: str = "gdacs_disasters") -> list[dict[str, Any]]:
|
||||
"""Parse GDACS GeoJSON or XML feed, excluding Green-level alerts."""
|
||||
now = datetime.now(UTC)
|
||||
items: list[dict[str, Any]] = []
|
||||
|
||||
if isinstance(raw_body, dict):
|
||||
for feat in raw_body.get("features") or []:
|
||||
if not isinstance(feat, dict):
|
||||
continue
|
||||
props = feat.get("properties") or {}
|
||||
alert = str(props.get("alertlevel") or "").strip().lower()
|
||||
if alert == "green":
|
||||
continue
|
||||
centroid = _extract_centroid(feat.get("geometry"))
|
||||
if centroid is None:
|
||||
continue
|
||||
lat, lon = centroid
|
||||
ev_type = _map_gdacs_type(props.get("eventtype") or "")
|
||||
severity = "high" if alert == "red" else "medium"
|
||||
obs = _coerce_utc(props.get("todate") or props.get("fromdate"), fallback=now)
|
||||
started = _coerce_utc(props.get("fromdate"), fallback=obs)
|
||||
ev_id = str(props.get("eventid") or feat.get("id") or f"gdacs:{ev_type}:{lat:.2f}:{lon:.2f}")
|
||||
items.append(
|
||||
{
|
||||
"source": source,
|
||||
"source_event_id": ev_id[:160],
|
||||
"event_type": ev_type,
|
||||
"severity": severity,
|
||||
"title": str(props.get("name") or props.get("description") or f"GDACS {ev_type}")[:500],
|
||||
"lat": round(lat, 5),
|
||||
"lon": round(lon, 5),
|
||||
"magnitude": _safe_float((props.get("severitydata") or {}).get("severity") if isinstance(props.get("severitydata"), dict) else props.get("alertscore")),
|
||||
"started_at": started,
|
||||
"ended_at": None,
|
||||
"url": _sanitize_url((props.get("url") or {}).get("report") if isinstance(props.get("url"), dict) else props.get("url")),
|
||||
"observed_at": obs,
|
||||
"cluster_count": 1,
|
||||
"max_brightness_k": None,
|
||||
"raw": {"alertlevel": alert, "eventtype": props.get("eventtype"), "country": props.get("country")},
|
||||
}
|
||||
)
|
||||
return items
|
||||
|
||||
if isinstance(raw_body, str) and "<" in raw_body:
|
||||
try:
|
||||
root = ET.fromstring(raw_body)
|
||||
except ET.ParseError:
|
||||
return []
|
||||
for elem in root.iter():
|
||||
if elem.tag.split("}")[-1] != "item":
|
||||
continue
|
||||
child_map = {ch.tag.split("}")[-1]: (ch.text or "").strip() for ch in elem}
|
||||
alert = child_map.get("alertlevel", "").lower()
|
||||
if alert == "green":
|
||||
continue
|
||||
lat = _safe_float(child_map.get("lat"))
|
||||
lon = _safe_float(child_map.get("long"))
|
||||
if (lat is None or lon is None) and child_map.get("point"):
|
||||
parts = re.split(r"[\s,]+", child_map["point"].strip())
|
||||
if len(parts) >= 2:
|
||||
lat = _safe_float(parts[0])
|
||||
lon = _safe_float(parts[1])
|
||||
if lat is None or lon is None:
|
||||
continue
|
||||
ev_type = _map_gdacs_type(child_map.get("eventtype", ""))
|
||||
ev_id = child_map.get("eventid") or child_map.get("guid") or f"gdacs:{ev_type}:{lat:.2f}:{lon:.2f}"
|
||||
obs = _coerce_utc(child_map.get("pubDate") or child_map.get("todate"), fallback=now)
|
||||
items.append(
|
||||
{
|
||||
"source": source,
|
||||
"source_event_id": ev_id[:160],
|
||||
"event_type": ev_type,
|
||||
"severity": "high" if alert == "red" else "medium",
|
||||
"title": (child_map.get("title") or f"GDACS {ev_type}")[:500],
|
||||
"lat": round(lat, 5),
|
||||
"lon": round(lon, 5),
|
||||
"magnitude": _safe_float(child_map.get("severity")),
|
||||
"started_at": _coerce_utc(child_map.get("fromdate"), fallback=obs),
|
||||
"ended_at": None,
|
||||
"url": _sanitize_url(child_map.get("link")),
|
||||
"observed_at": obs,
|
||||
"cluster_count": 1,
|
||||
"max_brightness_k": None,
|
||||
"raw": {"alertlevel": alert, "eventtype": child_map.get("eventtype")},
|
||||
}
|
||||
)
|
||||
return items
|
||||
|
||||
|
||||
def parse_nasa_eonet_events(payload: dict[str, Any], *, source: str = "nasa_eonet_events") -> list[dict[str, Any]]:
|
||||
"""Parse NASA EONET v3 events excluding earthquakes (handled by USGS)."""
|
||||
if not isinstance(payload, dict):
|
||||
return []
|
||||
now = datetime.now(UTC)
|
||||
items: list[dict[str, Any]] = []
|
||||
for ev in payload.get("events") or []:
|
||||
if not isinstance(ev, dict):
|
||||
continue
|
||||
ev_type, is_excluded = _map_eonet_category(ev.get("categories") or [])
|
||||
if is_excluded:
|
||||
continue
|
||||
geoms = ev.get("geometry") or []
|
||||
if not geoms or not isinstance(geoms, list):
|
||||
continue
|
||||
latest = geoms[-1]
|
||||
centroid = _extract_centroid(latest)
|
||||
if centroid is None:
|
||||
continue
|
||||
lat, lon = centroid
|
||||
ev_id = str(ev.get("id") or "").strip()
|
||||
if not ev_id:
|
||||
continue
|
||||
obs = _coerce_utc(latest.get("date"), fallback=now)
|
||||
started = _coerce_utc(geoms[0].get("date") if geoms else None, fallback=obs)
|
||||
src_url = None
|
||||
for src_entry in ev.get("sources") or []:
|
||||
if isinstance(src_entry, dict) and src_entry.get("url"):
|
||||
src_url = _sanitize_url(src_entry.get("url"))
|
||||
if src_url:
|
||||
break
|
||||
items.append(
|
||||
{
|
||||
"source": source,
|
||||
"source_event_id": ev_id[:160],
|
||||
"event_type": ev_type,
|
||||
"severity": "medium",
|
||||
"title": str(ev.get("title") or f"EONET {ev_type}")[:500],
|
||||
"lat": round(lat, 5),
|
||||
"lon": round(lon, 5),
|
||||
"magnitude": _safe_float(latest.get("magnitudeValue")),
|
||||
"started_at": started,
|
||||
"ended_at": _coerce_utc(ev.get("closed")) if ev.get("closed") else None,
|
||||
"url": src_url or _sanitize_url(ev.get("link")),
|
||||
"observed_at": obs,
|
||||
"cluster_count": 1,
|
||||
"max_brightness_k": None,
|
||||
"raw": {"categories": ev.get("categories"), "magnitudeUnit": latest.get("magnitudeUnit")},
|
||||
}
|
||||
)
|
||||
return items
|
||||
|
||||
|
||||
async def mark_cross_source_duplicates(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
window_hours: int = 6,
|
||||
grid_deg: float = 0.1,
|
||||
) -> int:
|
||||
"""Annotate `duplicate_of` across recent disaster events within 0.1-deg & +-6h window."""
|
||||
cutoff = datetime.now(UTC) - timedelta(hours=max(24, window_hours * 4))
|
||||
res = await db.execute(
|
||||
select(DisasterEvent)
|
||||
.where(DisasterEvent.observed_at >= cutoff)
|
||||
.order_by(DisasterEvent.observed_at.asc(), DisasterEvent.id.asc())
|
||||
)
|
||||
rows = list(res.scalars().all())
|
||||
if len(rows) <= 1:
|
||||
return 0
|
||||
|
||||
rows_sorted = sorted(
|
||||
rows,
|
||||
key=lambda r: (
|
||||
SOURCE_DEDUP_PRIORITY.get(str(r.source), 99),
|
||||
_coerce_utc(r.observed_at),
|
||||
int(r.id or 0),
|
||||
),
|
||||
)
|
||||
|
||||
updated = 0
|
||||
canonicals: list[DisasterEvent] = []
|
||||
window_sec = window_hours * 3600
|
||||
for row in rows_sorted:
|
||||
matched_canon: DisasterEvent | None = None
|
||||
row_obs = _coerce_utc(row.observed_at)
|
||||
for canon in canonicals:
|
||||
if canon.event_type != row.event_type or canon.source == row.source:
|
||||
continue
|
||||
if abs(float(canon.lat) - float(row.lat)) > grid_deg:
|
||||
continue
|
||||
if abs(float(canon.lon) - float(row.lon)) > grid_deg:
|
||||
continue
|
||||
if abs((_coerce_utc(canon.observed_at) - row_obs).total_seconds()) <= window_sec:
|
||||
matched_canon = canon
|
||||
break
|
||||
if matched_canon is not None:
|
||||
if row.duplicate_of != matched_canon.id:
|
||||
row.duplicate_of = matched_canon.id
|
||||
updated += 1
|
||||
else:
|
||||
if row.duplicate_of is not None:
|
||||
row.duplicate_of = None
|
||||
updated += 1
|
||||
canonicals.append(row)
|
||||
|
||||
if updated:
|
||||
await db.flush()
|
||||
return updated
|
||||
|
||||
|
||||
async def upsert_disaster_events(db: AsyncSession, records: list[dict[str, Any]]) -> int:
|
||||
"""Idempotently upsert normalized disaster records and run 0.1-deg cross-source dedup."""
|
||||
if not records:
|
||||
return 0
|
||||
dialect = getattr(getattr(db.get_bind(), "dialect", None), "name", "")
|
||||
insert_fn = pg_insert if dialect == "postgresql" else sqlite_insert
|
||||
now = datetime.now(UTC)
|
||||
|
||||
rows = []
|
||||
for item in records:
|
||||
rows.append(
|
||||
{
|
||||
"source": str(item["source"])[:64],
|
||||
"source_event_id": str(item["source_event_id"])[:160],
|
||||
"event_type": str(item.get("event_type") or "other")[:32],
|
||||
"severity": str(item.get("severity") or "medium")[:24],
|
||||
"title": str(item.get("title") or "Disaster Event")[:500],
|
||||
"lat": float(item["lat"]),
|
||||
"lon": float(item["lon"]),
|
||||
"magnitude": item.get("magnitude"),
|
||||
"started_at": item.get("started_at"),
|
||||
"ended_at": item.get("ended_at"),
|
||||
"url": item.get("url"),
|
||||
"observed_at": item.get("observed_at") or now,
|
||||
"ingested_at": now,
|
||||
"cluster_count": int(item.get("cluster_count") or 1),
|
||||
"max_brightness_k": item.get("max_brightness_k"),
|
||||
"raw": item.get("raw") or {},
|
||||
}
|
||||
)
|
||||
|
||||
stmt = insert_fn(DisasterEvent).values(rows)
|
||||
stmt = stmt.on_conflict_do_update(
|
||||
index_elements=["source", "source_event_id"],
|
||||
set_={
|
||||
"event_type": stmt.excluded.event_type,
|
||||
"severity": stmt.excluded.severity,
|
||||
"title": stmt.excluded.title,
|
||||
"lat": stmt.excluded.lat,
|
||||
"lon": stmt.excluded.lon,
|
||||
"magnitude": stmt.excluded.magnitude,
|
||||
"started_at": stmt.excluded.started_at,
|
||||
"ended_at": stmt.excluded.ended_at,
|
||||
"url": stmt.excluded.url,
|
||||
"observed_at": stmt.excluded.observed_at,
|
||||
"ingested_at": stmt.excluded.ingested_at,
|
||||
"cluster_count": stmt.excluded.cluster_count,
|
||||
"max_brightness_k": stmt.excluded.max_brightness_k,
|
||||
"raw": stmt.excluded.raw,
|
||||
},
|
||||
)
|
||||
await db.execute(stmt)
|
||||
await db.flush()
|
||||
await mark_cross_source_duplicates(db)
|
||||
await db.commit()
|
||||
return len(rows)
|
||||
@@ -3,14 +3,15 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from datetime import UTC, datetime
|
||||
import gc
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from time import perf_counter
|
||||
from typing import Any
|
||||
from urllib.parse import urlparse
|
||||
@@ -43,6 +44,7 @@ CLOUD_CONFIG_CATEGORY = "earth_cloud_map"
|
||||
DEFAULT_STATIC_CLOUD_URL = "./assets/earth_clouds_2048.png"
|
||||
ANALYSIS_GRID_WIDTH = 720
|
||||
ANALYSIS_GRID_HEIGHT = 360
|
||||
LOW_MEMORY_CGROUP_THRESHOLD_MB = 1024
|
||||
VERSION_PATTERN = re.compile(r"^[A-Za-z0-9._-]{4,64}$")
|
||||
|
||||
NASA_GIBS_WMS_URL = "https://gibs.earthdata.nasa.gov/wms/epsg4326/best/wms.cgi"
|
||||
@@ -377,6 +379,49 @@ def parse_resolution(resolution: str) -> tuple[int, int]:
|
||||
return (4096, 2048) if resolution == "4096x2048" else (2048, 1024)
|
||||
|
||||
|
||||
def detect_container_memory_limit_mb() -> int | None:
|
||||
"""Return cgroup memory limit in MiB when bounded inside a container, else None."""
|
||||
for path in (
|
||||
Path("/sys/fs/cgroup/memory.max"),
|
||||
Path("/sys/fs/cgroup/memory/memory.limit_in_bytes"),
|
||||
):
|
||||
try:
|
||||
raw = path.read_text(encoding="utf-8").strip()
|
||||
except OSError:
|
||||
continue
|
||||
if not raw or raw == "max":
|
||||
continue
|
||||
try:
|
||||
limit_bytes = int(raw)
|
||||
except ValueError:
|
||||
continue
|
||||
if limit_bytes <= 0 or limit_bytes >= (1 << 50):
|
||||
continue
|
||||
return int(limit_bytes // (1024 * 1024))
|
||||
return None
|
||||
|
||||
|
||||
def resolve_effective_cloud_config(config: CloudMapConfig) -> CloudMapConfig:
|
||||
"""Clamp working resolution to 2048x1024 in bounded low-memory containers."""
|
||||
env_max = str(os.environ.get("PLANET_CLOUD_MAX_RESOLUTION") or "").strip().lower()
|
||||
mem_limit_mb = detect_container_memory_limit_mb()
|
||||
if config.resolution == "4096x2048" and (
|
||||
env_max == "2048x1024"
|
||||
or (mem_limit_mb is not None and mem_limit_mb <= LOW_MEMORY_CGROUP_THRESHOLD_MB)
|
||||
):
|
||||
logger.warning_event(
|
||||
"Clamped cloud map working resolution to 2048x1024 for low-memory environment",
|
||||
event="earth.cloud_map.resolution_clamped_low_memory",
|
||||
context={
|
||||
"configured_resolution": config.resolution,
|
||||
"effective_resolution": "2048x1024",
|
||||
"container_memory_limit_mb": mem_limit_mb,
|
||||
},
|
||||
)
|
||||
return config.model_copy(update={"resolution": "2048x1024"})
|
||||
return config
|
||||
|
||||
|
||||
def _get_gibs_3d_lut() -> np.ndarray:
|
||||
"""Build a quantized 5-bit/channel RGB -> Brightness Temperature (°C) lookup table."""
|
||||
global _GIBS_3D_LUT
|
||||
@@ -460,29 +505,33 @@ def _disambiguate_dvorak_cold_gray(
|
||||
if np.any(ultra_wrap):
|
||||
result[ultra_wrap] = -91.5
|
||||
|
||||
del not_ring, labels, stats
|
||||
return result, updated_valid
|
||||
|
||||
|
||||
def decode_gibs_band13_to_temp_and_valid(rgba_arr: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""Invert GIBS Band13 Clean IR RGBA pixels into Brightness Temperature (°C) and valid mask."""
|
||||
rgb = rgba_arr[:, :, :3].astype(np.int32)
|
||||
r_u8 = rgba_arr[:, :, 0]
|
||||
g_u8 = rgba_arr[:, :, 1]
|
||||
b_u8 = rgba_arr[:, :, 2]
|
||||
alpha = rgba_arr[:, :, 3]
|
||||
valid = alpha > 12
|
||||
|
||||
r_ch = rgb[:, :, 0]
|
||||
g_ch = rgb[:, :, 1]
|
||||
b_ch = rgb[:, :, 2]
|
||||
chroma = np.maximum(np.maximum(r_ch, g_ch), b_ch) - np.minimum(np.minimum(r_ch, g_ch), b_ch)
|
||||
gray = ((r_ch + g_ch + b_ch) // 3).astype(np.float32)
|
||||
chroma = np.maximum(np.maximum(r_u8, g_u8), b_u8) - np.minimum(np.minimum(r_u8, g_u8), b_u8)
|
||||
gray_sum = r_u8.astype(np.uint16)
|
||||
gray_sum += g_u8
|
||||
gray_sum += b_u8
|
||||
gray = (gray_sum // 3).astype(np.float32)
|
||||
del gray_sum
|
||||
|
||||
temp_c = 57.3 - (np.clip(gray, 0.0, 197.0) / 197.0) * 76.4
|
||||
temp_c = (57.3 - (np.clip(gray, 0.0, 197.0) / 197.0) * 76.4).astype(np.float32)
|
||||
color_mask = valid & (chroma >= 12)
|
||||
if np.any(color_mask):
|
||||
lut = _get_gibs_3d_lut()
|
||||
temp_c[color_mask] = lut[
|
||||
r_ch[color_mask] >> 3,
|
||||
g_ch[color_mask] >> 3,
|
||||
b_ch[color_mask] >> 3,
|
||||
r_u8[color_mask] >> 3,
|
||||
g_u8[color_mask] >> 3,
|
||||
b_u8[color_mask] >> 3,
|
||||
]
|
||||
|
||||
temp_c, valid = _disambiguate_dvorak_cold_gray(valid, gray, chroma, temp_c)
|
||||
@@ -599,6 +648,7 @@ def synthesize_multi_sat_ir(
|
||||
temp_accum += safe_temp * pixel_weight
|
||||
weight_accum += pixel_weight
|
||||
active_satellites.append(str(sat["id"]))
|
||||
del rgba_arr, sat_temp, valid, pixel_weight, safe_temp
|
||||
|
||||
if not active_satellites or not np.any(weight_accum > 0.0):
|
||||
raise RuntimeError("No valid geostationary IR satellite frames could be decoded")
|
||||
@@ -1190,6 +1240,7 @@ async def collect_latest_cloud_frame(
|
||||
envelope = await read_cloud_map_configuration(db)
|
||||
merged_cfg = {**envelope["config"], **(override_config or {})}
|
||||
config = CloudMapConfig.model_validate(merged_cfg)
|
||||
effective_config = resolve_effective_cloud_config(config)
|
||||
|
||||
manifest = _read_manifest()
|
||||
prev_frames = manifest.get("frames", [])
|
||||
@@ -1207,42 +1258,43 @@ async def collect_latest_cloud_frame(
|
||||
density: np.ndarray | None = None
|
||||
temp_c: np.ndarray | None = None
|
||||
visual_payloads: list[tuple[dict[str, Any], bytes]] = []
|
||||
source_used = config.primary_source
|
||||
source_used = effective_config.primary_source
|
||||
satellites: list[str] = []
|
||||
degraded = False
|
||||
|
||||
if config.primary_source == "multi_sat_ir":
|
||||
if config.geocolor_enabled:
|
||||
payloads, visual_payloads = await asyncio.gather(
|
||||
_fetch_multi_sat_payloads(config, layer_field="layer"),
|
||||
_fetch_multi_sat_payloads(config, layer_field="visual_layer"),
|
||||
)
|
||||
else:
|
||||
payloads = await _fetch_multi_sat_payloads(config, layer_field="layer")
|
||||
if effective_config.primary_source == "multi_sat_ir":
|
||||
payloads = await _fetch_multi_sat_payloads(effective_config, layer_field="layer")
|
||||
if payloads:
|
||||
density, temp_c, satellites = await asyncio.to_thread(
|
||||
synthesize_multi_sat_ir,
|
||||
payloads,
|
||||
config=config,
|
||||
config=effective_config,
|
||||
)
|
||||
payloads.clear()
|
||||
del payloads
|
||||
if len(satellites) < len(SATELLITE_SOURCES):
|
||||
degraded = True
|
||||
elif config.fallback_source == "matteason_live":
|
||||
raw = await _fetch_matteason_bytes(config)
|
||||
if effective_config.geocolor_enabled:
|
||||
visual_payloads = await _fetch_multi_sat_payloads(
|
||||
effective_config,
|
||||
layer_field="visual_layer",
|
||||
)
|
||||
elif effective_config.fallback_source == "matteason_live":
|
||||
raw = await _fetch_matteason_bytes(effective_config)
|
||||
density, temp_c = await asyncio.to_thread(
|
||||
decode_matteason_cloud_bytes,
|
||||
raw,
|
||||
config=config,
|
||||
config=effective_config,
|
||||
)
|
||||
source_used = "matteason_live"
|
||||
satellites = ["eumetsat_nasa_mosaic"]
|
||||
degraded = True
|
||||
else:
|
||||
raw = await _fetch_matteason_bytes(config)
|
||||
raw = await _fetch_matteason_bytes(effective_config)
|
||||
density, temp_c = await asyncio.to_thread(
|
||||
decode_matteason_cloud_bytes,
|
||||
raw,
|
||||
config=config,
|
||||
config=effective_config,
|
||||
)
|
||||
source_used = "matteason_live"
|
||||
satellites = ["eumetsat_nasa_mosaic"]
|
||||
@@ -1257,88 +1309,80 @@ async def collect_latest_cloud_frame(
|
||||
def _finalize() -> tuple[dict[str, Any], dict[str, Any]]:
|
||||
from app.services.earth_clouds_fx import (
|
||||
compute_dis_optical_flow_webp,
|
||||
decode_visual_payloads,
|
||||
fuse_daytime_visible_into_density,
|
||||
synthesize_geocolor_visual_webp,
|
||||
fuse_and_synthesize_visual_layers,
|
||||
)
|
||||
|
||||
width, height = parse_resolution(config.resolution)
|
||||
decoded_visuals = (
|
||||
decode_visual_payloads(visual_payloads, width, height)
|
||||
if (config.geocolor_enabled and visual_payloads)
|
||||
else []
|
||||
)
|
||||
fused_density = (
|
||||
fuse_daytime_visible_into_density(
|
||||
density,
|
||||
temp_c,
|
||||
decoded_visuals,
|
||||
width=width,
|
||||
height=height,
|
||||
now_utc=now_utc,
|
||||
)
|
||||
if decoded_visuals
|
||||
else density
|
||||
)
|
||||
try:
|
||||
width, height = parse_resolution(effective_config.resolution)
|
||||
if effective_config.geocolor_enabled and visual_payloads:
|
||||
fused_density, visual_webp_bytes = fuse_and_synthesize_visual_layers(
|
||||
density,
|
||||
temp_c,
|
||||
visual_payloads,
|
||||
width=width,
|
||||
height=height,
|
||||
now_utc=now_utc,
|
||||
)
|
||||
else:
|
||||
fused_density, visual_webp_bytes = density, None
|
||||
visual_payloads.clear()
|
||||
|
||||
analysis = analyze_cloud_density_grid(
|
||||
fused_density,
|
||||
temp_c,
|
||||
config=config,
|
||||
previous_snapshot=prev_snapshot,
|
||||
previous_regions=prev_regions,
|
||||
)
|
||||
webp_bytes = _encode_cloud_webp(fused_density)
|
||||
visual_webp_bytes = (
|
||||
synthesize_geocolor_visual_webp(
|
||||
decoded_visuals,
|
||||
analysis = analyze_cloud_density_grid(
|
||||
fused_density,
|
||||
width=width,
|
||||
height=height,
|
||||
temp_c,
|
||||
config=effective_config,
|
||||
previous_snapshot=prev_snapshot,
|
||||
previous_regions=prev_regions,
|
||||
)
|
||||
if decoded_visuals
|
||||
else None
|
||||
)
|
||||
flow_webp_bytes: bytes | None = None
|
||||
flow_prev_version: str | None = None
|
||||
flow_max_uv = 0.0
|
||||
if config.optical_flow_enabled and isinstance(prev_entry, dict) and prev_entry.get("version"):
|
||||
prev_ver = str(prev_entry["version"])
|
||||
prev_frame_file = _frames_dir() / f"{prev_ver}.webp"
|
||||
if prev_ver != version and prev_frame_file.exists():
|
||||
try:
|
||||
prev_rgba = _decode_image_bytes(prev_frame_file.read_bytes(), width, height)
|
||||
prev_density = prev_rgba[:, :, 3]
|
||||
flow_res = compute_dis_optical_flow_webp(prev_density, fused_density)
|
||||
if flow_res is not None:
|
||||
flow_webp_bytes, flow_max_uv = flow_res
|
||||
flow_prev_version = prev_ver
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Cloud optical flow calculation failed",
|
||||
event="earth.cloud_map.optical_flow_failed",
|
||||
context={"prev_version": prev_ver, "error": str(exc)},
|
||||
)
|
||||
webp_bytes = _encode_cloud_webp(fused_density)
|
||||
flow_webp_bytes: bytes | None = None
|
||||
flow_prev_version: str | None = None
|
||||
flow_max_uv = 0.0
|
||||
if (
|
||||
effective_config.optical_flow_enabled
|
||||
and isinstance(prev_entry, dict)
|
||||
and prev_entry.get("version")
|
||||
):
|
||||
prev_ver = str(prev_entry["version"])
|
||||
prev_frame_file = _frames_dir() / f"{prev_ver}.webp"
|
||||
if prev_ver != version and prev_frame_file.exists():
|
||||
try:
|
||||
prev_rgba = _decode_image_bytes(prev_frame_file.read_bytes(), width, height)
|
||||
prev_density = prev_rgba[:, :, 3]
|
||||
flow_res = compute_dis_optical_flow_webp(prev_density, fused_density)
|
||||
del prev_rgba, prev_density
|
||||
if flow_res is not None:
|
||||
flow_webp_bytes, flow_max_uv = flow_res
|
||||
flow_prev_version = prev_ver
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Cloud optical flow calculation failed",
|
||||
event="earth.cloud_map.optical_flow_failed",
|
||||
context={"prev_version": prev_ver, "error": str(exc)},
|
||||
)
|
||||
|
||||
entry = _save_frame_artifacts_sync(
|
||||
version=version,
|
||||
captured_at=captured_at,
|
||||
source_used=source_used,
|
||||
satellites=satellites,
|
||||
degraded=degraded,
|
||||
config=config,
|
||||
webp_bytes=webp_bytes,
|
||||
visual_webp_bytes=visual_webp_bytes,
|
||||
flow_webp_bytes=flow_webp_bytes,
|
||||
flow_prev_version=flow_prev_version,
|
||||
flow_max_uv=flow_max_uv,
|
||||
grid_density=analysis["grid_density"],
|
||||
grid_temp_i8=analysis["grid_temp_i8"],
|
||||
global_summary=analysis["global_summary"],
|
||||
regions=analysis["regions"],
|
||||
clusters=analysis["convective_clusters"],
|
||||
)
|
||||
return entry, analysis
|
||||
entry = _save_frame_artifacts_sync(
|
||||
version=version,
|
||||
captured_at=captured_at,
|
||||
source_used=source_used,
|
||||
satellites=satellites,
|
||||
degraded=degraded,
|
||||
config=effective_config,
|
||||
webp_bytes=webp_bytes,
|
||||
visual_webp_bytes=visual_webp_bytes,
|
||||
flow_webp_bytes=flow_webp_bytes,
|
||||
flow_prev_version=flow_prev_version,
|
||||
flow_max_uv=flow_max_uv,
|
||||
grid_density=analysis["grid_density"],
|
||||
grid_temp_i8=analysis["grid_temp_i8"],
|
||||
global_summary=analysis["global_summary"],
|
||||
regions=analysis["regions"],
|
||||
clusters=analysis["convective_clusters"],
|
||||
)
|
||||
return entry, analysis
|
||||
finally:
|
||||
visual_payloads.clear()
|
||||
gc.collect()
|
||||
|
||||
async with _CLOUD_WRITE_LOCK:
|
||||
frame_entry, analysis = await asyncio.to_thread(_finalize)
|
||||
@@ -1348,7 +1392,7 @@ async def collect_latest_cloud_frame(
|
||||
"global_summary": analysis["global_summary"],
|
||||
"regions": analysis["regions"],
|
||||
"convective_clusters": analysis["convective_clusters"],
|
||||
"config": config.model_dump(mode="json"),
|
||||
"config": effective_config.model_dump(mode="json"),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -2,10 +2,11 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
import gc
|
||||
import io
|
||||
import math
|
||||
from typing import Any, Sequence
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any, Iterator, Sequence
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
@@ -35,18 +36,40 @@ def decode_visual_payloads(
|
||||
height: int,
|
||||
) -> list[tuple[dict[str, Any], np.ndarray]]:
|
||||
"""Decode and resize visible satellite payloads once so density & GeoColor share buffers."""
|
||||
decoded: list[tuple[dict[str, Any], np.ndarray]] = []
|
||||
return list(_iter_decoded_visuals(visual_payloads, width, height))
|
||||
|
||||
|
||||
def _iter_decoded_visuals(
|
||||
visual_payloads: Sequence[tuple[dict[str, Any], bytes | np.ndarray]],
|
||||
width: int,
|
||||
height: int,
|
||||
) -> Iterator[tuple[dict[str, Any], np.ndarray]]:
|
||||
"""Yield one decoded RGBA visual frame at a time to bound peak heap usage."""
|
||||
for sat, payload in visual_payloads:
|
||||
if isinstance(payload, np.ndarray):
|
||||
if payload.shape[:2] == (height, width) and payload.shape[2] == 4:
|
||||
decoded.append((sat, payload))
|
||||
yield sat, payload
|
||||
continue
|
||||
try:
|
||||
rgba = _decode_rgba_resized(payload, width, height)
|
||||
decoded.append((sat, rgba))
|
||||
yield sat, rgba
|
||||
except Exception:
|
||||
continue
|
||||
return decoded
|
||||
|
||||
|
||||
def _rgba_channels_and_luma(
|
||||
rgba: np.ndarray,
|
||||
) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
|
||||
red = rgba[:, :, 0]
|
||||
green = rgba[:, :, 1]
|
||||
blue = rgba[:, :, 2]
|
||||
alpha = rgba[:, :, 3]
|
||||
luma = (
|
||||
0.299 * red.astype(np.float32)
|
||||
+ 0.587 * green.astype(np.float32)
|
||||
+ 0.114 * blue.astype(np.float32)
|
||||
)
|
||||
return red, green, blue, alpha, luma
|
||||
|
||||
|
||||
def _solar_cosine_grid(width: int, height: int, now_utc: datetime) -> tuple[np.ndarray, np.ndarray]:
|
||||
@@ -87,10 +110,6 @@ def fuse_daytime_visible_into_density(
|
||||
if not np.any(day_weight > 0.01):
|
||||
return density_u8
|
||||
|
||||
decoded_visuals = decode_visual_payloads(visual_payloads, width, height)
|
||||
if not decoded_visuals:
|
||||
return density_u8
|
||||
|
||||
cos_safe = np.clip(cos_sza, 0.30, 1.0)
|
||||
safe_temp = np.where(np.isfinite(temp_c), temp_c, 15.0).astype(np.float32)
|
||||
# Band-pass gate: peaks on -2C..+16C warm low clouds while suppressing hot deserts (>+24C) and sub-zero snow (<-8C).
|
||||
@@ -102,25 +121,24 @@ def fuse_daytime_visible_into_density(
|
||||
vis_accum = np.zeros((height, width), dtype=np.float32)
|
||||
weight_accum = np.zeros((height, width), dtype=np.float32)
|
||||
|
||||
for sat, rgba in decoded_visuals:
|
||||
rgb = rgba[:, :, :3].astype(np.float32)
|
||||
alpha = rgba[:, :, 3].astype(np.float32)
|
||||
luma = 0.299 * rgb[:, :, 0] + 0.587 * rgb[:, :, 1] + 0.114 * rgb[:, :, 2]
|
||||
for sat, rgba in _iter_decoded_visuals(visual_payloads, width, height):
|
||||
r_u8, g_u8, b_u8, alpha_u8, luma = _rgba_channels_and_luma(rgba)
|
||||
not_clipped = ~(
|
||||
(rgb[:, :, 0] >= 254.0)
|
||||
& (rgb[:, :, 1] >= 254.0)
|
||||
& (rgb[:, :, 2] >= 254.0)
|
||||
(r_u8 >= 254)
|
||||
& (g_u8 >= 254)
|
||||
& (b_u8 >= 254)
|
||||
& (safe_temp > -10.0)
|
||||
)
|
||||
valid = (alpha > 12.0) & (luma > 8.0) & not_clipped
|
||||
valid = (alpha_u8 > 12) & (luma > 8.0) & not_clipped
|
||||
if not np.any(valid):
|
||||
continue
|
||||
|
||||
chroma = (np.max(rgb, axis=2) - np.min(rgb, axis=2)) / 255.0
|
||||
max_u8 = np.maximum(np.maximum(r_u8, g_u8), b_u8)
|
||||
min_u8 = np.minimum(np.minimum(r_u8, g_u8), b_u8)
|
||||
chroma = (max_u8 - min_u8).astype(np.float32) / 255.0
|
||||
is_color = float(np.nanpercentile(chroma[valid], 95)) > 0.08
|
||||
if is_color:
|
||||
min_rgb = np.min(rgb, axis=2)
|
||||
albedo = min_rgb / cos_safe
|
||||
albedo = min_u8.astype(np.float32) / cos_safe
|
||||
whiteness = np.clip(1.0 - chroma / 0.36, 0.0, 1.0)
|
||||
sat_cloud = np.clip((albedo - 85.0) / 135.0, 0.0, 1.0) * whiteness * warm_low_cloud_gate
|
||||
else:
|
||||
@@ -131,6 +149,7 @@ def fuse_daytime_visible_into_density(
|
||||
pix_w = np.where(valid, lon_w[None, :], 0.0)
|
||||
vis_accum += sat_cloud * pix_w
|
||||
weight_accum += pix_w
|
||||
del rgba, luma, chroma, sat_cloud, pix_w
|
||||
|
||||
covered = weight_accum > 0.0
|
||||
if not np.any(covered):
|
||||
@@ -156,37 +175,33 @@ def synthesize_geocolor_visual_webp(
|
||||
if not visual_payloads or density_u8.shape != (height, width):
|
||||
return None
|
||||
|
||||
decoded_visuals = decode_visual_payloads(visual_payloads, width, height)
|
||||
if not decoded_visuals:
|
||||
return None
|
||||
|
||||
rgb_accum = np.zeros((height, width, 3), dtype=np.float32)
|
||||
weight_accum = np.zeros((height, width), dtype=np.float32)
|
||||
valid_sources = 0
|
||||
|
||||
for sat, rgba in decoded_visuals:
|
||||
rgb = rgba[:, :, :3].astype(np.float32)
|
||||
alpha = rgba[:, :, 3].astype(np.float32)
|
||||
luma = 0.299 * rgb[:, :, 0] + 0.587 * rgb[:, :, 1] + 0.114 * rgb[:, :, 2]
|
||||
for sat, rgba in _iter_decoded_visuals(visual_payloads, width, height):
|
||||
r_u8, g_u8, b_u8, alpha_u8, luma = _rgba_channels_and_luma(rgba)
|
||||
|
||||
# EUMETView/GIBS return opaque black over night hemispheres or pure-white clipped wedges.
|
||||
# Mask out dark night pixels and non-dense pure-white [255,255,255] fill artifacts.
|
||||
not_clipped = ~(
|
||||
(rgb[:, :, 0] >= 254.0)
|
||||
& (rgb[:, :, 1] >= 254.0)
|
||||
& (rgb[:, :, 2] >= 254.0)
|
||||
(r_u8 >= 254)
|
||||
& (g_u8 >= 254)
|
||||
& (b_u8 >= 254)
|
||||
& (density_u8 < 180)
|
||||
)
|
||||
valid = (alpha > 12.0) & (luma > 22.0) & not_clipped
|
||||
valid = (alpha_u8 > 12) & (luma > 22.0) & not_clipped
|
||||
if not np.any(valid):
|
||||
continue
|
||||
|
||||
lon_w = _longitude_weight_vector(width, float(sat.get("sub_lon", 0.0)))
|
||||
# Emphasize cloud-rich pixels from daytime channels so dark ocean reflectance doesn't darken clouds.
|
||||
pix_w = np.where(valid, lon_w[None, :], 0.0)
|
||||
rgb_accum += rgb * pix_w[:, :, None]
|
||||
for ch in range(3):
|
||||
rgb_accum[:, :, ch] += rgba[:, :, ch].astype(np.float32) * pix_w
|
||||
weight_accum += pix_w
|
||||
valid_sources += 1
|
||||
del rgba, luma, pix_w
|
||||
|
||||
if valid_sources == 0 or not np.any(weight_accum > 0.0):
|
||||
return None
|
||||
@@ -274,3 +289,34 @@ def compute_dis_optical_flow_webp(
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, format="WEBP", quality=92, method=1)
|
||||
return buf.getvalue(), round(float(max_uv), 6)
|
||||
|
||||
|
||||
def fuse_and_synthesize_visual_layers(
|
||||
density_u8: np.ndarray,
|
||||
temp_c: np.ndarray,
|
||||
visual_payloads: Sequence[tuple[dict[str, Any], bytes | np.ndarray]],
|
||||
*,
|
||||
width: int,
|
||||
height: int,
|
||||
now_utc: datetime | None = None,
|
||||
) -> tuple[np.ndarray, bytes | None]:
|
||||
"""Stream visible payloads one at a time for low-cloud density fusion and GeoColor WebP."""
|
||||
if not visual_payloads:
|
||||
return density_u8, None
|
||||
fused_density = fuse_daytime_visible_into_density(
|
||||
density_u8,
|
||||
temp_c,
|
||||
visual_payloads,
|
||||
width=width,
|
||||
height=height,
|
||||
now_utc=now_utc,
|
||||
)
|
||||
gc.collect()
|
||||
visual_webp_bytes = synthesize_geocolor_visual_webp(
|
||||
visual_payloads,
|
||||
fused_density,
|
||||
width=width,
|
||||
height=height,
|
||||
)
|
||||
gc.collect()
|
||||
return fused_density, visual_webp_bytes
|
||||
@@ -40,11 +40,14 @@ EARTH_LAYER_ADAPTERS: tuple[EarthLayerAdapter, ...] = (
|
||||
"arcgis_cable_landing_relation",
|
||||
"arcgis_cable_landing_relations",
|
||||
"fao_landing_points",
|
||||
"nga_navigation_warnings",
|
||||
"cable_advisories",
|
||||
}
|
||||
),
|
||||
tables=frozenset({"collected_data"}),
|
||||
tables=frozenset({"collected_data", "cable_advisories"}),
|
||||
layers=("cables",),
|
||||
cache_patterns=("cables*", "landing-points*", "summary*"),
|
||||
derived_models=("cable_advisories",),
|
||||
),
|
||||
EarthLayerAdapter(
|
||||
sources=frozenset({"celestrak_tle", "spacetrack_tle"}),
|
||||
@@ -137,6 +140,54 @@ EARTH_LAYER_ADAPTERS: tuple[EarthLayerAdapter, ...] = (
|
||||
cache_patterns=(),
|
||||
refresh_strategy="reload",
|
||||
),
|
||||
EarthLayerAdapter(
|
||||
sources=frozenset(
|
||||
{
|
||||
"adsb_lol_aircraft",
|
||||
"opensky_aircraft",
|
||||
"aircraft_static",
|
||||
"aircraft_current_state",
|
||||
"aircraft_position",
|
||||
"adsb_source_health",
|
||||
}
|
||||
),
|
||||
tables=frozenset(
|
||||
{
|
||||
"aircraft_static",
|
||||
"aircraft_current_state",
|
||||
"aircraft_position",
|
||||
"adsb_source_health",
|
||||
}
|
||||
),
|
||||
layers=("aircraft",),
|
||||
cache_patterns=("aircraft*", "summary*"),
|
||||
derived_models=("aircraft_current_state", "adsb_source_health"),
|
||||
refresh_strategy="reload",
|
||||
),
|
||||
EarthLayerAdapter(
|
||||
sources=frozenset({"gpsjam_interference", "gps_jamming_cells"}),
|
||||
tables=frozenset({"gps_jamming_cells"}),
|
||||
layers=("gpsJamming",),
|
||||
cache_patterns=("gps-jamming*", "summary*"),
|
||||
derived_models=("gps_jamming_cells",),
|
||||
refresh_strategy="reload",
|
||||
),
|
||||
EarthLayerAdapter(
|
||||
sources=frozenset(
|
||||
{
|
||||
"usgs_earthquakes",
|
||||
"nasa_firms_wildfires",
|
||||
"gdacs_disasters",
|
||||
"nasa_eonet_events",
|
||||
"disaster_events",
|
||||
}
|
||||
),
|
||||
tables=frozenset({"disaster_events"}),
|
||||
layers=("disasters",),
|
||||
cache_patterns=("disasters*", "summary*"),
|
||||
derived_models=("disaster_events",),
|
||||
refresh_strategy="reload",
|
||||
),
|
||||
)
|
||||
|
||||
_ADAPTERS_BY_SOURCE = {
|
||||
@@ -199,6 +250,8 @@ async def clear_derived_datasource_data(db: AsyncSession, source: str) -> dict[s
|
||||
AISSourceHealth,
|
||||
VesselCurrentState,
|
||||
)
|
||||
from app.models.aircraft import ADSBSourceHealth, AircraftCurrentState
|
||||
from app.models.gps_jamming import GPSJammingCell
|
||||
|
||||
model_by_key: dict[str, Any] = {
|
||||
"bgp_observations": BGPObservation,
|
||||
@@ -208,6 +261,9 @@ async def clear_derived_datasource_data(db: AsyncSession, source: str) -> dict[s
|
||||
"vessel_current_state": VesselCurrentState,
|
||||
"ais_conflict_records": AISConflictRecord,
|
||||
"ais_source_health": AISSourceHealth,
|
||||
"aircraft_current_state": AircraftCurrentState,
|
||||
"adsb_source_health": ADSBSourceHealth,
|
||||
"gps_jamming_cells": GPSJammingCell,
|
||||
}
|
||||
deleted_counts: dict[str, int] = {}
|
||||
keys_to_clear = list(adapter.derived_models)
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections import OrderedDict
|
||||
from collections.abc import Awaitable, Callable
|
||||
from contextlib import suppress
|
||||
from dataclasses import dataclass, replace
|
||||
@@ -30,6 +29,7 @@ DEFAULT_MAX_BYTES = 5 * 1024 * 1024
|
||||
DEFAULT_BBOX_PRECISION_DEGREES = 0.1
|
||||
DEV_CACHE_KEY_HEADER = {"development", "dev", "test", "testing", "local"}
|
||||
ENCODED_ARTIFACT_CACHE_MAX_ENTRIES = 8
|
||||
ENCODED_ARTIFACT_CACHE_MAX_BYTES = 8 * 1024 * 1024
|
||||
GZIP_COMPRESS_LEVEL = 5
|
||||
|
||||
|
||||
@@ -55,7 +55,6 @@ class EarthLayerCacheResult:
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _EncodedLayerArtifact:
|
||||
raw_bytes: bytes
|
||||
gzip_bytes: bytes
|
||||
etag: str
|
||||
features: int
|
||||
@@ -69,7 +68,7 @@ class EarthLayerEncodedResult:
|
||||
key: str
|
||||
|
||||
|
||||
_ENCODED_ARTIFACT_CACHE: OrderedDict[tuple[str, str], _EncodedLayerArtifact] = OrderedDict()
|
||||
_ENCODED_ARTIFACT_CACHE: dict[tuple[str, str], _EncodedLayerArtifact] = {}
|
||||
|
||||
|
||||
class EarthLayerCache:
|
||||
@@ -277,7 +276,9 @@ def _encode_layer_bytes(
|
||||
cache_key = (key, etag)
|
||||
cached = _ENCODED_ARTIFACT_CACHE.get(cache_key)
|
||||
if cached is not None:
|
||||
_ENCODED_ARTIFACT_CACHE.move_to_end(cache_key)
|
||||
# Refresh insertion order on hit so eviction removes least recently used entries.
|
||||
_ENCODED_ARTIFACT_CACHE.pop(cache_key, None)
|
||||
_ENCODED_ARTIFACT_CACHE[cache_key] = cached
|
||||
return cached
|
||||
|
||||
resolved_features = features
|
||||
@@ -289,15 +290,20 @@ def _encode_layer_bytes(
|
||||
|
||||
gzip_bytes = gzip.compress(raw_bytes, compresslevel=GZIP_COMPRESS_LEVEL)
|
||||
artifact = _EncodedLayerArtifact(
|
||||
raw_bytes=raw_bytes,
|
||||
gzip_bytes=gzip_bytes,
|
||||
etag=etag,
|
||||
features=resolved_features,
|
||||
byte_length=len(raw_bytes),
|
||||
)
|
||||
_ENCODED_ARTIFACT_CACHE[cache_key] = artifact
|
||||
while len(_ENCODED_ARTIFACT_CACHE) > ENCODED_ARTIFACT_CACHE_MAX_ENTRIES:
|
||||
_ENCODED_ARTIFACT_CACHE.popitem(last=False)
|
||||
if len(gzip_bytes) <= ENCODED_ARTIFACT_CACHE_MAX_BYTES:
|
||||
_ENCODED_ARTIFACT_CACHE[cache_key] = artifact
|
||||
while (
|
||||
len(_ENCODED_ARTIFACT_CACHE) > ENCODED_ARTIFACT_CACHE_MAX_ENTRIES
|
||||
or sum(len(item.gzip_bytes) for item in _ENCODED_ARTIFACT_CACHE.values())
|
||||
> ENCODED_ARTIFACT_CACHE_MAX_BYTES
|
||||
):
|
||||
oldest_key = next(iter(_ENCODED_ARTIFACT_CACHE))
|
||||
_ENCODED_ARTIFACT_CACHE.pop(oldest_key, None)
|
||||
return artifact
|
||||
|
||||
|
||||
@@ -357,7 +363,7 @@ async def get_or_build_layer_response(
|
||||
headers={**headers, "Content-Encoding": "gzip"},
|
||||
)
|
||||
return Response(
|
||||
content=result.artifact.raw_bytes,
|
||||
content=gzip.decompress(result.artifact.gzip_bytes),
|
||||
media_type="application/json",
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
@@ -95,6 +95,34 @@ class NewsFeedEndpoint:
|
||||
priority: int = 100
|
||||
|
||||
|
||||
THEATER_PRESETS = ("global", "russo_ukrainian", "middle_east", "indo_pacific", "europe")
|
||||
|
||||
|
||||
def normalize_credibility_tier(value: Any) -> int | None:
|
||||
"""Parse credibility tier 1..4 preserving NULL ('unrated') when missing."""
|
||||
if value is None or value == "":
|
||||
return None
|
||||
try:
|
||||
tier = int(value)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return tier if 1 <= tier <= 4 else None
|
||||
|
||||
|
||||
def normalize_theater_tags(raw: Any) -> list[str]:
|
||||
if isinstance(raw, str):
|
||||
tokens = [t.strip().lower() for t in re.split(r"[,,\s]+", raw) if t.strip()]
|
||||
elif isinstance(raw, (list, tuple, set)):
|
||||
tokens = [str(t).strip().lower() for t in raw if str(t).strip()]
|
||||
else:
|
||||
return []
|
||||
seen: list[str] = []
|
||||
for tok in tokens:
|
||||
if tok not in seen:
|
||||
seen.append(tok)
|
||||
return seen
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class NewsFeedSource:
|
||||
id: str
|
||||
@@ -112,6 +140,9 @@ class NewsFeedSource:
|
||||
default_category: str = "other"
|
||||
importance_weight: int = 0
|
||||
health_policy: dict[str, Any] = field(default_factory=dict)
|
||||
credibility_tier: int | None = None
|
||||
state_affiliated: bool = False
|
||||
theater_tags: tuple[str, ...] = ()
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -166,6 +197,9 @@ class ParsedNewsItem:
|
||||
breaking_source: str = BreakingSource.RULES.value
|
||||
breaking_confidence: float = 0.0
|
||||
breaking_expires_at: datetime | None = None
|
||||
credibility_tier: int | None = None
|
||||
state_affiliated: bool = False
|
||||
theater_tags: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -1434,6 +1468,9 @@ def serialize_news_source_config(source: NewsFeedSource) -> dict[str, Any]:
|
||||
"source_tags": list(source.source_tags),
|
||||
"default_category": source.default_category,
|
||||
"importance_weight": source.importance_weight,
|
||||
"credibility_tier": source.credibility_tier,
|
||||
"state_affiliated": bool(source.state_affiliated),
|
||||
"theater_tags": list(source.theater_tags),
|
||||
"health_policy": dict(source.health_policy or DEFAULT_NEWS_HEALTH_POLICY),
|
||||
}
|
||||
|
||||
@@ -1502,6 +1539,19 @@ def _source_from_config(payload: dict[str, Any]) -> NewsFeedSource | None:
|
||||
default_category=str(payload.get("default_category") or (default_source.default_category if default_source else "other") or "other").strip() or "other",
|
||||
importance_weight=importance_weight,
|
||||
health_policy={**DEFAULT_NEWS_HEALTH_POLICY, **health_policy},
|
||||
credibility_tier=normalize_credibility_tier(
|
||||
payload.get("credibility_tier", default_source.credibility_tier if default_source else None)
|
||||
),
|
||||
state_affiliated=bool(
|
||||
payload.get("state_affiliated", default_source.state_affiliated if default_source else False)
|
||||
),
|
||||
theater_tags=tuple(
|
||||
normalize_theater_tags(
|
||||
payload.get("theater_tags")
|
||||
if "theater_tags" in payload
|
||||
else (default_source.theater_tags if default_source else ())
|
||||
)
|
||||
),
|
||||
)
|
||||
feeds = tuple(
|
||||
feed
|
||||
@@ -1909,6 +1959,9 @@ def _parse_feed_entries(
|
||||
feed_type=feed_type,
|
||||
feed_default_category=(feed.default_category if feed else source.default_category) or "other",
|
||||
source_tags=list(source.source_tags),
|
||||
credibility_tier=source.credibility_tier,
|
||||
state_affiliated=bool(source.state_affiliated),
|
||||
theater_tags=list(source.theater_tags),
|
||||
)
|
||||
apply_news_classification(item, source, feed=feed, config_payload=config_payload)
|
||||
items.append(item)
|
||||
@@ -2021,6 +2074,10 @@ def _news_meta_patch(item: ParsedNewsItem) -> dict[str, Any]:
|
||||
"breaking_source": item.breaking_source,
|
||||
"breaking_confidence": item.breaking_confidence,
|
||||
"breaking_expires_at": _serialize_breaking_expires_at(item.breaking_expires_at),
|
||||
"credibility_tier": normalize_credibility_tier(item.credibility_tier),
|
||||
"credibility_label": f"T{item.credibility_tier}" if normalize_credibility_tier(item.credibility_tier) is not None else "未分级",
|
||||
"state_affiliated": bool(item.state_affiliated),
|
||||
"theater_tags": list(item.theater_tags or []),
|
||||
}
|
||||
|
||||
|
||||
@@ -2122,6 +2179,10 @@ def build_target_location_job_payload(item: ParsedNewsItem) -> dict[str, Any]:
|
||||
"breaking_source": item.breaking_source,
|
||||
"breaking_confidence": item.breaking_confidence,
|
||||
"breaking_expires_at": _serialize_breaking_expires_at(item.breaking_expires_at),
|
||||
"credibility_tier": normalize_credibility_tier(item.credibility_tier),
|
||||
"credibility_label": f"T{item.credibility_tier}" if normalize_credibility_tier(item.credibility_tier) is not None else "未分级",
|
||||
"state_affiliated": bool(item.state_affiliated),
|
||||
"theater_tags": list(item.theater_tags or []),
|
||||
}
|
||||
|
||||
|
||||
@@ -2159,6 +2220,9 @@ def parsed_news_item_from_job_payload(payload: dict[str, Any]) -> ParsedNewsItem
|
||||
breaking_source=str(payload.get("breaking_source") or "rules"),
|
||||
breaking_confidence=float(payload.get("breaking_confidence") or 0),
|
||||
breaking_expires_at=_parse_datetime(_coerce_str(payload.get("breaking_expires_at"))),
|
||||
credibility_tier=normalize_credibility_tier(payload.get("credibility_tier")),
|
||||
state_affiliated=bool(payload.get("state_affiliated", False)),
|
||||
theater_tags=normalize_theater_tags(payload.get("theater_tags")),
|
||||
)
|
||||
|
||||
|
||||
@@ -2210,6 +2274,10 @@ def _serialize_item(item: ParsedNewsItem, *, active_region: str, locale: str = D
|
||||
"breaking_source": item.breaking_source,
|
||||
"breaking_confidence": item.breaking_confidence,
|
||||
"breaking_expires_at": _serialize_breaking_expires_at(item.breaking_expires_at),
|
||||
"credibility_tier": normalize_credibility_tier(item.credibility_tier),
|
||||
"credibility_label": f"T{item.credibility_tier}" if normalize_credibility_tier(item.credibility_tier) is not None else "未分级",
|
||||
"state_affiliated": bool(item.state_affiliated),
|
||||
"theater_tags": list(item.theater_tags or []),
|
||||
}
|
||||
|
||||
|
||||
@@ -2360,14 +2428,21 @@ def _diversify_news_items_for_locale(
|
||||
|
||||
|
||||
async def _call_store_list_items(list_fn, db: AsyncSession, **kwargs):
|
||||
try:
|
||||
return await list_fn(db, **kwargs)
|
||||
except TypeError as error:
|
||||
if "source_ids" not in str(error):
|
||||
raise
|
||||
legacy_kwargs = dict(kwargs)
|
||||
legacy_kwargs.pop("source_ids", None)
|
||||
return await list_fn(db, **legacy_kwargs)
|
||||
attempt_kwargs = dict(kwargs)
|
||||
for _ in range(3):
|
||||
try:
|
||||
return await list_fn(db, **attempt_kwargs)
|
||||
except TypeError as error:
|
||||
msg = str(error)
|
||||
removed = False
|
||||
for optional_kw in ("source_ids", "theater"):
|
||||
if optional_kw in msg and optional_kw in attempt_kwargs:
|
||||
attempt_kwargs.pop(optional_kw, None)
|
||||
removed = True
|
||||
break
|
||||
if not removed:
|
||||
raise
|
||||
return await list_fn(db, **attempt_kwargs)
|
||||
|
||||
|
||||
def _get_cached_region_feed(region: str) -> CachedRegionFeed | None:
|
||||
@@ -2728,6 +2803,7 @@ async def get_earth_news_payload(
|
||||
region: str | None = None,
|
||||
categories: set[str] | None = None,
|
||||
source_ids: set[str] | None = None,
|
||||
theater: str | None = None,
|
||||
limit: int = MAX_ITEMS_TOTAL,
|
||||
locale: str = DEFAULT_NEWS_LOCALE,
|
||||
provider_client: AIProviderClient | None = None,
|
||||
@@ -2742,8 +2818,12 @@ async def get_earth_news_payload(
|
||||
else get_sources_for_region(active_region)
|
||||
)
|
||||
|
||||
normalized_theater = str(theater or "").strip().lower() or None
|
||||
if normalized_theater == "global":
|
||||
normalized_theater = None
|
||||
|
||||
if db is None:
|
||||
return await _get_earth_news_payload_from_rss_only(
|
||||
rss_payload = await _get_earth_news_payload_from_rss_only(
|
||||
lat=lat,
|
||||
lon=lon,
|
||||
active_region=active_region,
|
||||
@@ -2753,6 +2833,12 @@ async def get_earth_news_payload(
|
||||
limit=limit,
|
||||
locale=locale,
|
||||
)
|
||||
if normalized_theater:
|
||||
rss_payload["items"] = [
|
||||
it for it in rss_payload.get("items") or []
|
||||
if normalized_theater in (it.get("theater_tags") or [])
|
||||
]
|
||||
return rss_payload
|
||||
|
||||
from app.services.earth_news_store import list_earth_news_cruise_items, list_earth_news_items
|
||||
|
||||
@@ -2763,6 +2849,7 @@ async def get_earth_news_payload(
|
||||
limit=limit,
|
||||
categories=categories,
|
||||
source_ids=source_ids,
|
||||
theater=normalized_theater,
|
||||
)
|
||||
if items and not source_ids:
|
||||
ready_sources = {
|
||||
|
||||
@@ -97,6 +97,9 @@ def record_to_parsed_news_item(record: EarthNewsItem) -> ParsedNewsItem:
|
||||
breaking_source=str(news_meta.get("breaking_source") or "rules"),
|
||||
breaking_confidence=float(news_meta.get("breaking_confidence") or 0),
|
||||
breaking_expires_at=_coerce_meta_datetime(news_meta.get("breaking_expires_at")),
|
||||
credibility_tier=record.credibility_tier,
|
||||
state_affiliated=bool(record.state_affiliated),
|
||||
theater_tags=list(record.theater_tags or []) if isinstance(record.theater_tags, list) else [],
|
||||
)
|
||||
return apply_enrichment_patch_to_item(item, _location_patch_from_record(record))
|
||||
|
||||
@@ -186,6 +189,7 @@ async def list_earth_news_items(
|
||||
limit: int,
|
||||
categories: set[str] | None = None,
|
||||
source_ids: set[str] | None = None,
|
||||
theater: str | None = None,
|
||||
) -> list[ParsedNewsItem]:
|
||||
query_limit = limit if source_ids else min(max(limit * 20, limit), 500)
|
||||
query = (
|
||||
@@ -213,6 +217,9 @@ async def list_earth_news_items(
|
||||
[record_to_parsed_news_item(record) for record in records],
|
||||
active_region=active_region,
|
||||
)
|
||||
if theater and theater != "global":
|
||||
t_norm = str(theater).strip().lower()
|
||||
items = [it for it in items if t_norm in [str(tag).strip().lower() for tag in (it.theater_tags or [])]]
|
||||
if active_region == "global" and not source_ids:
|
||||
return _diversify_parsed_news_items_by_region(items, limit=limit)
|
||||
return items[:limit]
|
||||
@@ -338,6 +345,9 @@ async def upsert_earth_news_items(db: AsyncSession, items: list[ParsedNewsItem])
|
||||
enrichment_status=item.enrichment_status,
|
||||
enrichment_error=item.enrichment_error,
|
||||
enriched_at=item.enriched_at,
|
||||
credibility_tier=item.credibility_tier,
|
||||
state_affiliated=bool(item.state_affiliated),
|
||||
theater_tags=list(item.theater_tags or []),
|
||||
)
|
||||
db.add(record)
|
||||
changed += 1
|
||||
@@ -353,6 +363,9 @@ async def upsert_earth_news_items(db: AsyncSession, items: list[ParsedNewsItem])
|
||||
("region", item.feed_region),
|
||||
("homepage_url", item.homepage_url),
|
||||
("published_at", item.published_at),
|
||||
("credibility_tier", item.credibility_tier),
|
||||
("state_affiliated", bool(item.state_affiliated)),
|
||||
("theater_tags", list(item.theater_tags or [])),
|
||||
):
|
||||
if getattr(record, field_name) != value:
|
||||
setattr(record, field_name, value)
|
||||
|
||||
@@ -3,13 +3,14 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from datetime import UTC, datetime
|
||||
import hashlib
|
||||
import io
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import time
|
||||
import weakref
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
@@ -57,6 +58,41 @@ BASEMAP_TILE_SOURCES: tuple[str, ...] = (
|
||||
"earth_imagery_viirs_daily",
|
||||
)
|
||||
|
||||
# A contended semaphore holds its event loop, so the cache also keeps values weakly.
|
||||
_TILE_ENCODE_SEMAPHORES: weakref.WeakKeyDictionary[
|
||||
asyncio.AbstractEventLoop, weakref.ReferenceType[asyncio.Semaphore]
|
||||
] = weakref.WeakKeyDictionary()
|
||||
_INFLIGHT_TILE_FETCHES: weakref.WeakKeyDictionary[
|
||||
asyncio.AbstractEventLoop, dict[tuple[str, int, int, int], asyncio.Task[bytes | None]]
|
||||
] = weakref.WeakKeyDictionary()
|
||||
|
||||
|
||||
def _tile_encode_concurrency() -> int:
|
||||
raw = str(os.environ.get("PLANET_TILE_ENCODE_CONCURRENCY") or "2").strip()
|
||||
try:
|
||||
return max(1, min(8, int(raw)))
|
||||
except ValueError:
|
||||
return 2
|
||||
|
||||
|
||||
def _get_tile_encode_semaphore() -> asyncio.Semaphore:
|
||||
loop = asyncio.get_running_loop()
|
||||
semaphore_ref = _TILE_ENCODE_SEMAPHORES.get(loop)
|
||||
semaphore = semaphore_ref() if semaphore_ref is not None else None
|
||||
if semaphore is None:
|
||||
semaphore = asyncio.Semaphore(_tile_encode_concurrency())
|
||||
_TILE_ENCODE_SEMAPHORES[loop] = weakref.ref(semaphore)
|
||||
return semaphore
|
||||
|
||||
|
||||
def _get_inflight_tile_fetches() -> dict[tuple[str, int, int, int], asyncio.Task[bytes | None]]:
|
||||
loop = asyncio.get_running_loop()
|
||||
inflight = _INFLIGHT_TILE_FETCHES.get(loop)
|
||||
if inflight is None:
|
||||
inflight = {}
|
||||
_INFLIGHT_TILE_FETCHES[loop] = inflight
|
||||
return inflight
|
||||
|
||||
DEFAULT_TILE_TEMPLATES: dict[str, str] = {
|
||||
"cloud_hd_tiles": (
|
||||
"https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/"
|
||||
@@ -589,29 +625,31 @@ async def _fetch_and_encode_tile(
|
||||
)
|
||||
ir_bytes = ir_res.content if _is_valid_image_response(ir_res) else None
|
||||
if _is_valid_image_response(primary_res):
|
||||
return await asyncio.to_thread(
|
||||
_encode_tile_webp,
|
||||
source_key,
|
||||
primary_res.content,
|
||||
provider=provider,
|
||||
ir_bytes=ir_bytes,
|
||||
ir_provider=ir_provider,
|
||||
cos_sza=cos_sza,
|
||||
z=z,
|
||||
x=x,
|
||||
y=y,
|
||||
ir_z_src=ir_z_src,
|
||||
)
|
||||
async with _get_tile_encode_semaphore():
|
||||
return await asyncio.to_thread(
|
||||
_encode_tile_webp,
|
||||
source_key,
|
||||
primary_res.content,
|
||||
provider=provider,
|
||||
ir_bytes=ir_bytes,
|
||||
ir_provider=ir_provider,
|
||||
cos_sza=cos_sza,
|
||||
z=z,
|
||||
x=x,
|
||||
y=y,
|
||||
ir_z_src=ir_z_src,
|
||||
)
|
||||
if ir_bytes is not None:
|
||||
return await asyncio.to_thread(
|
||||
_encode_tile_webp,
|
||||
source_key,
|
||||
ir_bytes,
|
||||
provider=ir_provider,
|
||||
z=z,
|
||||
x=x,
|
||||
y=y,
|
||||
)
|
||||
async with _get_tile_encode_semaphore():
|
||||
return await asyncio.to_thread(
|
||||
_encode_tile_webp,
|
||||
source_key,
|
||||
ir_bytes,
|
||||
provider=ir_provider,
|
||||
z=z,
|
||||
x=x,
|
||||
y=y,
|
||||
)
|
||||
if isinstance(primary_res, Exception) and raise_on_error:
|
||||
raise primary_res
|
||||
if isinstance(primary_res, httpx.Response) and primary_res.status_code not in (200, 404) and raise_on_error:
|
||||
@@ -632,15 +670,16 @@ async def _fetch_and_encode_tile(
|
||||
response.raise_for_status()
|
||||
if not _is_valid_image_response(response):
|
||||
return None
|
||||
return await asyncio.to_thread(
|
||||
_encode_tile_webp,
|
||||
source_key,
|
||||
response.content,
|
||||
provider=provider,
|
||||
z=z,
|
||||
x=x,
|
||||
y=y,
|
||||
)
|
||||
async with _get_tile_encode_semaphore():
|
||||
return await asyncio.to_thread(
|
||||
_encode_tile_webp,
|
||||
source_key,
|
||||
response.content,
|
||||
provider=provider,
|
||||
z=z,
|
||||
x=x,
|
||||
y=y,
|
||||
)
|
||||
|
||||
|
||||
async def get_or_fetch_tile(
|
||||
@@ -667,15 +706,39 @@ async def get_or_fetch_tile(
|
||||
pass
|
||||
return target.read_bytes(), True
|
||||
|
||||
timeout = httpx.Timeout(float(cfg.get("request_timeout_seconds") or 15))
|
||||
headers = {"User-Agent": "Planet-Intelligence-System/1.0 (EarthTileProxy)"}
|
||||
async with httpx.AsyncClient(timeout=timeout, follow_redirects=True, headers=headers) as client:
|
||||
webp_bytes = await _fetch_and_encode_tile(client, source_key, template, z, x, y)
|
||||
tile_key = (source_key, int(z), int(x), int(y))
|
||||
inflight = _get_inflight_tile_fetches()
|
||||
existing_task = inflight.get(tile_key)
|
||||
if existing_task is None or existing_task.done():
|
||||
timeout = httpx.Timeout(float(cfg.get("request_timeout_seconds") or 15))
|
||||
headers = {"User-Agent": "Planet-Intelligence-System/1.0 (EarthTileProxy)"}
|
||||
|
||||
async def _load_and_persist() -> bytes | None:
|
||||
async with httpx.AsyncClient(
|
||||
timeout=timeout,
|
||||
follow_redirects=True,
|
||||
headers=headers,
|
||||
) as client:
|
||||
loaded = await _fetch_and_encode_tile(
|
||||
client, source_key, template, z, x, y
|
||||
)
|
||||
if loaded is not None:
|
||||
await asyncio.to_thread(_atomic_write_bytes, target, loaded)
|
||||
return loaded
|
||||
|
||||
existing_task = asyncio.create_task(_load_and_persist())
|
||||
inflight[tile_key] = existing_task
|
||||
existing_task.add_done_callback(
|
||||
lambda done_task: (
|
||||
inflight.pop(tile_key, None)
|
||||
if inflight.get(tile_key) is done_task
|
||||
else None
|
||||
)
|
||||
)
|
||||
|
||||
webp_bytes = await asyncio.shield(existing_task)
|
||||
if webp_bytes is None:
|
||||
return None, True
|
||||
|
||||
await asyncio.to_thread(_atomic_write_bytes, target, webp_bytes)
|
||||
return webp_bytes, True
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
"""Multi-domain situational fusion services (§3.8–§3.10)."""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -0,0 +1,641 @@
|
||||
"""Deterministic geofence rule-alert engine (§3.8)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime, timedelta
|
||||
import math
|
||||
import os
|
||||
from typing import Any
|
||||
|
||||
import h3
|
||||
from sqlalchemy import desc, 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 AircraftCurrentState, AircraftPosition
|
||||
from app.models.collected_data import CollectedData
|
||||
from app.models.earth_interactable import EarthInteractable
|
||||
from app.models.geofence import Geofence, SituationalIncident
|
||||
from app.models.vessel import VesselCurrentState, VesselPosition
|
||||
from app.services.maritime_geography import load_chokepoints, point_in_polygon
|
||||
|
||||
logger = get_logger(__name__, service="fusion_anomaly")
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
def get_cable_corridor_half_width_km() -> float:
|
||||
raw = str(os.getenv("GEOFENCE_CABLE_CORRIDOR_KM", "15.0")).strip()
|
||||
try:
|
||||
return max(2.0, min(float(raw), 100.0))
|
||||
except ValueError:
|
||||
return 15.0
|
||||
|
||||
|
||||
def _ring_from_geojson(geometry: dict[str, Any]) -> list[list[list[float]]]:
|
||||
if not isinstance(geometry, dict):
|
||||
return []
|
||||
gtype = str(geometry.get("type") or "")
|
||||
coords = geometry.get("coordinates") or []
|
||||
if gtype == "Polygon" and isinstance(coords, list) and coords:
|
||||
return [coords[0]] if isinstance(coords[0], list) else []
|
||||
if gtype == "MultiPolygon" and isinstance(coords, list):
|
||||
return [poly[0] for poly in coords if isinstance(poly, list) and poly and isinstance(poly[0], list)]
|
||||
return []
|
||||
|
||||
|
||||
def point_in_geofence(lat: float, lon: float, geofence: Geofence | dict[str, Any]) -> bool:
|
||||
geom = geofence.geometry if isinstance(geofence, Geofence) else (geofence.get("geometry") or {})
|
||||
for ring in _ring_from_geojson(geom):
|
||||
if point_in_polygon(lat, lon, ring):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _geofence_centroid(geofence: Geofence) -> tuple[float | None, float | None]:
|
||||
rings = _ring_from_geojson(geofence.geometry or {})
|
||||
if not rings or not rings[0]:
|
||||
return None, None
|
||||
pts = [pt for pt in rings[0] if isinstance(pt, (list, tuple)) and len(pt) >= 2]
|
||||
if not pts:
|
||||
return None, None
|
||||
return (
|
||||
sum(float(p[1]) for p in pts) / len(pts),
|
||||
sum(float(p[0]) for p in pts) / len(pts),
|
||||
)
|
||||
|
||||
|
||||
def build_corridor_polygon_from_line(
|
||||
coords: list[list[float]],
|
||||
*,
|
||||
half_width_km: float = 15.0,
|
||||
) -> dict[str, Any] | None:
|
||||
"""Build a lightweight WGS-84 corridor buffer polygon from a LineString's bounding corridor."""
|
||||
pts = [
|
||||
(float(pt[0]), float(pt[1]))
|
||||
for pt in (coords or [])
|
||||
if isinstance(pt, (list, tuple)) and len(pt) >= 2
|
||||
]
|
||||
if len(pts) < 2:
|
||||
return None
|
||||
sample = pts if len(pts) <= 12 else [pts[i] for i in range(0, len(pts), max(1, len(pts) // 10))] + [pts[-1]]
|
||||
avg_lat = sum(p[1] for p in sample) / len(sample)
|
||||
d_lat = half_width_km / 111.32
|
||||
cos_lat = max(0.25, math.cos(math.radians(avg_lat)))
|
||||
d_lon = half_width_km / (111.32 * cos_lat)
|
||||
|
||||
left_side: list[list[float]] = []
|
||||
right_side: list[list[float]] = []
|
||||
for idx in range(len(sample)):
|
||||
p_prev = sample[max(0, idx - 1)]
|
||||
p_next = sample[min(len(sample) - 1, idx + 1)]
|
||||
dx = p_next[0] - p_prev[0]
|
||||
dy = p_next[1] - p_prev[1]
|
||||
norm = math.hypot(dx, dy) or 1.0
|
||||
nx = -dy / norm
|
||||
ny = dx / norm
|
||||
lon, lat = sample[idx]
|
||||
left_side.append([round(lon + nx * d_lon, 5), round(lat + ny * d_lat, 5)])
|
||||
right_side.append([round(lon - nx * d_lon, 5), round(lat - ny * d_lat, 5)])
|
||||
|
||||
ring = left_side + list(reversed(right_side)) + [left_side[0]]
|
||||
return {"type": "Polygon", "coordinates": [ring]}
|
||||
|
||||
|
||||
async def ensure_preset_geofences(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
corridor_half_width_km: float | None = None,
|
||||
max_cable_corridors: int = 24,
|
||||
) -> int:
|
||||
"""Idempotently seed preset chokepoint and submarine-cable corridor geofences."""
|
||||
existing_rows = list(
|
||||
(await db.execute(select(Geofence).where(Geofence.kind == "preset"))).scalars().all()
|
||||
)
|
||||
existing_names = {str(g.name): g for g in existing_rows}
|
||||
created = 0
|
||||
width_km = float(corridor_half_width_km) if corridor_half_width_km is not None else get_cable_corridor_half_width_km()
|
||||
|
||||
for cp in load_chokepoints():
|
||||
ring = cp.get("polygon") or []
|
||||
if len(ring) < 3:
|
||||
continue
|
||||
name = f"咽喉要道 · {cp.get('name') or cp['id']}"
|
||||
if name in existing_names:
|
||||
continue
|
||||
db.add(
|
||||
Geofence(
|
||||
name=name,
|
||||
kind="preset",
|
||||
geometry={"type": "Polygon", "coordinates": [ring]},
|
||||
rules={
|
||||
"corridor_type": "chokepoint",
|
||||
"chokepoint_id": cp["id"],
|
||||
"enable_loitering": True,
|
||||
"loitering_sog_kn": 3.0,
|
||||
"loitering_minutes": 30,
|
||||
"enable_dark_target": True,
|
||||
"dark_threshold_minutes": 45,
|
||||
"enable_surge": True,
|
||||
"surge_sigma": 2.0,
|
||||
},
|
||||
enabled=True,
|
||||
created_by="system",
|
||||
)
|
||||
)
|
||||
created += 1
|
||||
|
||||
try:
|
||||
cable_rows = list(
|
||||
(
|
||||
await db.execute(
|
||||
select(CollectedData)
|
||||
.where(
|
||||
CollectedData.source == "arcgis_cables",
|
||||
CollectedData.is_current.is_(True),
|
||||
)
|
||||
.limit(max_cable_corridors * 2)
|
||||
)
|
||||
)
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
except Exception:
|
||||
cable_rows = []
|
||||
|
||||
cable_seeded = 0
|
||||
for row in cable_rows:
|
||||
if cable_seeded >= max_cable_corridors:
|
||||
break
|
||||
extra = row.extra_data or {}
|
||||
geom = extra.get("geometry") or {}
|
||||
coords = extra.get("coordinates") or geom.get("coordinates")
|
||||
if not isinstance(coords, list) or not coords:
|
||||
continue
|
||||
line_coords = coords
|
||||
if isinstance(coords[0], list) and coords[0] and isinstance(coords[0][0], list):
|
||||
line_coords = coords[0]
|
||||
poly = build_corridor_polygon_from_line(line_coords, half_width_km=width_km)
|
||||
if poly is None:
|
||||
continue
|
||||
cid = str(extra.get("cable_id") or row.source_id or row.name or row.id)
|
||||
cname = str(row.name or cid)
|
||||
gf_name = f"海缆走廊 · {cname}"
|
||||
if gf_name in existing_names:
|
||||
cable_seeded += 1
|
||||
continue
|
||||
db.add(
|
||||
Geofence(
|
||||
name=gf_name,
|
||||
kind="preset",
|
||||
geometry=poly,
|
||||
rules={
|
||||
"corridor_type": "cable_corridor",
|
||||
"cable_id": cid,
|
||||
"cable_name": cname,
|
||||
"buffer_km": width_km,
|
||||
"enable_loitering": True,
|
||||
"loitering_sog_kn": 3.0,
|
||||
"loitering_minutes": 30,
|
||||
"enable_dark_target": True,
|
||||
"dark_threshold_minutes": 45,
|
||||
"enable_surge": True,
|
||||
"surge_sigma": 2.0,
|
||||
},
|
||||
enabled=True,
|
||||
created_by="system",
|
||||
)
|
||||
)
|
||||
created += 1
|
||||
cable_seeded += 1
|
||||
|
||||
if created:
|
||||
await db.commit()
|
||||
return created
|
||||
|
||||
|
||||
async def _in_cooldown(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
incident_type: str,
|
||||
dedup_key: str,
|
||||
now: datetime,
|
||||
cooldown_minutes: int,
|
||||
) -> bool:
|
||||
cutoff = now - timedelta(minutes=max(1, cooldown_minutes))
|
||||
stmt = (
|
||||
select(SituationalIncident)
|
||||
.where(
|
||||
SituationalIncident.incident_type == incident_type,
|
||||
SituationalIncident.created_at >= cutoff,
|
||||
)
|
||||
.order_by(desc(SituationalIncident.created_at))
|
||||
.limit(100)
|
||||
)
|
||||
for row in list((await db.execute(stmt)).scalars().all()):
|
||||
summary = row.signal_summary or {}
|
||||
if str(summary.get("dedup_key") or "") == dedup_key:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _h3_or_none(lat: float | None, lon: float | None) -> str | None:
|
||||
if lat is None or lon is None:
|
||||
return None
|
||||
try:
|
||||
return h3.latlng_to_cell(float(lat), float(lon), 4)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
async def detect_cable_corridor_loitering(
|
||||
db: AsyncSession,
|
||||
geofences: list[Geofence],
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
cooldown_minutes: int = 60,
|
||||
) -> list[SituationalIncident]:
|
||||
"""Rule 1: vessel in cable corridor with SOG < 3 kn and dwell > 30 min."""
|
||||
ref_now = now or datetime.now(UTC)
|
||||
corridors = [
|
||||
gf
|
||||
for gf in geofences
|
||||
if gf.enabled and (gf.rules or {}).get("enable_loitering", False)
|
||||
]
|
||||
if not corridors:
|
||||
return []
|
||||
|
||||
vessels = list((await db.execute(select(VesselCurrentState).limit(2000))).scalars().all())
|
||||
created: list[SituationalIncident] = []
|
||||
hist_cutoff = ref_now - timedelta(hours=6)
|
||||
|
||||
for vessel in vessels:
|
||||
if vessel.sog is None:
|
||||
continue
|
||||
obs = _coerce_utc(vessel.observed_at)
|
||||
if obs is None or (ref_now - obs).total_seconds() > 6 * 3600:
|
||||
continue
|
||||
for gf in corridors:
|
||||
rules = gf.rules or {}
|
||||
corridor_type = str(rules.get("corridor_type") or "")
|
||||
if corridor_type != "cable_corridor" and "cable" not in str(gf.name).lower() and not rules.get("cable_id"):
|
||||
continue
|
||||
max_sog = float(rules.get("loitering_sog_kn", 3.0))
|
||||
min_dwell = float(rules.get("loitering_minutes", 30))
|
||||
if float(vessel.sog) >= max_sog:
|
||||
continue
|
||||
if not point_in_geofence(float(vessel.lat), float(vessel.lon), gf):
|
||||
continue
|
||||
|
||||
track = list(
|
||||
(
|
||||
await db.execute(
|
||||
select(VesselPosition)
|
||||
.where(
|
||||
VesselPosition.mmsi == vessel.mmsi,
|
||||
VesselPosition.received_at >= hist_cutoff,
|
||||
VesselPosition.received_at <= ref_now,
|
||||
)
|
||||
.order_by(VesselPosition.received_at.asc())
|
||||
)
|
||||
)
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
in_zone_times = [
|
||||
_coerce_utc(pt.received_at)
|
||||
for pt in track
|
||||
if point_in_geofence(float(pt.lat), float(pt.lon), gf)
|
||||
and (pt.sog is None or float(pt.sog) < max_sog)
|
||||
]
|
||||
in_zone_times = [t for t in in_zone_times if t is not None]
|
||||
if not in_zone_times:
|
||||
continue
|
||||
earliest = min(in_zone_times)
|
||||
latest = max([obs, max(in_zone_times)])
|
||||
dwell_min = (latest - earliest).total_seconds() / 60.0
|
||||
if dwell_min <= min_dwell:
|
||||
continue
|
||||
|
||||
dedup_key = f"loiter:gf:{gf.id}:vessel:{vessel.mmsi}"
|
||||
if await _in_cooldown(
|
||||
db,
|
||||
incident_type="cable_corridor_loitering",
|
||||
dedup_key=dedup_key,
|
||||
now=ref_now,
|
||||
cooldown_minutes=cooldown_minutes,
|
||||
):
|
||||
continue
|
||||
|
||||
cable_id = rules.get("cable_id")
|
||||
obj_ids = [f"vessel:{vessel.mmsi}"]
|
||||
if cable_id:
|
||||
obj_ids.append(f"cable:{cable_id}")
|
||||
inc = SituationalIncident(
|
||||
incident_type="cable_corridor_loitering",
|
||||
severity="high",
|
||||
status="open",
|
||||
h3_index=_h3_or_none(float(vessel.lat), float(vessel.lon)),
|
||||
window_start=earliest,
|
||||
window_end=latest,
|
||||
object_ids=obj_ids,
|
||||
signal_summary={
|
||||
"dedup_key": dedup_key,
|
||||
"geofence_id": gf.id,
|
||||
"geofence_name": gf.name,
|
||||
"mmsi": vessel.mmsi,
|
||||
"vessel_name": vessel.name,
|
||||
"sog_kn": round(float(vessel.sog), 2),
|
||||
"dwell_minutes": round(dwell_min, 1),
|
||||
"lat": float(vessel.lat),
|
||||
"lon": float(vessel.lon),
|
||||
},
|
||||
evidence=[
|
||||
{
|
||||
"source": vessel.source,
|
||||
"observed_at": to_iso8601_utc(obs),
|
||||
"detail": f"SOG {float(vessel.sog):.1f} kn 在围栏内连续停留 {dwell_min:.1f} 分钟",
|
||||
}
|
||||
],
|
||||
assessment_kind="rule_alert",
|
||||
title=f"规则告警:海缆走廊低速徘徊 ({vessel.name or vessel.mmsi} · {gf.name})",
|
||||
created_at=ref_now,
|
||||
)
|
||||
db.add(inc)
|
||||
created.append(inc)
|
||||
if created:
|
||||
await db.commit()
|
||||
return created
|
||||
|
||||
|
||||
async def detect_dark_target_blackout(
|
||||
db: AsyncSession,
|
||||
geofences: list[Geofence],
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
max_lookback_hours: int = 12,
|
||||
cooldown_minutes: int = 60,
|
||||
) -> list[SituationalIncident]:
|
||||
"""Rule 2: vessel or aircraft signal blackout inside priority geofence beyond threshold."""
|
||||
ref_now = now or datetime.now(UTC)
|
||||
monitored = [
|
||||
gf
|
||||
for gf in geofences
|
||||
if gf.enabled and (gf.rules or {}).get("enable_dark_target", True)
|
||||
]
|
||||
if not monitored:
|
||||
return []
|
||||
|
||||
vessels = list((await db.execute(select(VesselCurrentState).limit(2000))).scalars().all())
|
||||
aircraft = list((await db.execute(select(AircraftCurrentState).limit(2000))).scalars().all())
|
||||
created: list[SituationalIncident] = []
|
||||
|
||||
candidates: list[tuple[str, str, str, float, float, datetime | None, str]] = []
|
||||
for v in vessels:
|
||||
candidates.append(
|
||||
(
|
||||
f"vessel:{v.mmsi}",
|
||||
"AIS",
|
||||
str(v.name or v.mmsi),
|
||||
float(v.lat),
|
||||
float(v.lon),
|
||||
_coerce_utc(v.observed_at),
|
||||
str(v.source),
|
||||
)
|
||||
)
|
||||
for a in aircraft:
|
||||
candidates.append(
|
||||
(
|
||||
f"aircraft:{a.icao24}",
|
||||
"ADS-B",
|
||||
str(a.callsign or a.icao24),
|
||||
float(a.lat),
|
||||
float(a.lon),
|
||||
_coerce_utc(a.observed_at),
|
||||
str(a.source),
|
||||
)
|
||||
)
|
||||
|
||||
for obj_id, channel, label, lat, lon, obs, src in candidates:
|
||||
if obs is None:
|
||||
continue
|
||||
silent_min = (ref_now - obs).total_seconds() / 60.0
|
||||
if silent_min > max_lookback_hours * 60:
|
||||
continue
|
||||
for gf in monitored:
|
||||
thresh_min = float((gf.rules or {}).get("dark_threshold_minutes", 45))
|
||||
if silent_min <= thresh_min:
|
||||
continue
|
||||
if not point_in_geofence(lat, lon, gf):
|
||||
continue
|
||||
dedup_key = f"dark:gf:{gf.id}:{obj_id}"
|
||||
if await _in_cooldown(
|
||||
db,
|
||||
incident_type="dark_target_blackout",
|
||||
dedup_key=dedup_key,
|
||||
now=ref_now,
|
||||
cooldown_minutes=cooldown_minutes,
|
||||
):
|
||||
continue
|
||||
|
||||
inc = SituationalIncident(
|
||||
incident_type="dark_target_blackout",
|
||||
severity="high",
|
||||
status="open",
|
||||
h3_index=_h3_or_none(lat, lon),
|
||||
window_start=obs,
|
||||
window_end=ref_now,
|
||||
object_ids=[obj_id],
|
||||
signal_summary={
|
||||
"dedup_key": dedup_key,
|
||||
"geofence_id": gf.id,
|
||||
"geofence_name": gf.name,
|
||||
"channel": channel,
|
||||
"label": label,
|
||||
"silent_minutes": round(silent_min, 1),
|
||||
"threshold_minutes": thresh_min,
|
||||
"lat": lat,
|
||||
"lon": lon,
|
||||
},
|
||||
evidence=[
|
||||
{
|
||||
"source": src,
|
||||
"observed_at": to_iso8601_utc(obs),
|
||||
"detail": f"{channel} 信号在围栏 {gf.name} 内中断 {silent_min:.1f} 分钟 (阈值 {thresh_min:.0f} 分钟)",
|
||||
}
|
||||
],
|
||||
assessment_kind="rule_alert",
|
||||
title=f"规则告警:暗目标信号中断 ({label} · {gf.name})",
|
||||
created_at=ref_now,
|
||||
)
|
||||
db.add(inc)
|
||||
created.append(inc)
|
||||
if created:
|
||||
await db.commit()
|
||||
return created
|
||||
|
||||
|
||||
async def detect_geofence_traffic_surge(
|
||||
db: AsyncSession,
|
||||
geofences: list[Geofence],
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
min_baseline_days: int = 3,
|
||||
cooldown_minutes: int = 60,
|
||||
) -> list[SituationalIncident]:
|
||||
"""Rule 3: current target count inside geofence > 14-day same-hour baseline + 2*sigma."""
|
||||
ref_now = now or datetime.now(UTC)
|
||||
monitored = [
|
||||
gf for gf in geofences if gf.enabled and (gf.rules or {}).get("enable_surge", True)
|
||||
]
|
||||
if not monitored:
|
||||
return []
|
||||
|
||||
vessels = list((await db.execute(select(VesselCurrentState).limit(3000))).scalars().all())
|
||||
aircraft = list((await db.execute(select(AircraftCurrentState).limit(3000))).scalars().all())
|
||||
interactables = list(
|
||||
(await db.execute(select(EarthInteractable).where(EarthInteractable.is_deleted.is_(False)).limit(2000)))
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
|
||||
cutoff_14d = ref_now - timedelta(days=14)
|
||||
yesterday_cutoff = ref_now - timedelta(hours=12)
|
||||
vessel_hist = list(
|
||||
(
|
||||
await db.execute(
|
||||
select(VesselPosition).where(
|
||||
VesselPosition.received_at >= cutoff_14d,
|
||||
VesselPosition.received_at < yesterday_cutoff,
|
||||
)
|
||||
)
|
||||
)
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
air_hist = list(
|
||||
(
|
||||
await db.execute(
|
||||
select(AircraftPosition).where(
|
||||
AircraftPosition.observed_at >= cutoff_14d,
|
||||
AircraftPosition.observed_at < yesterday_cutoff,
|
||||
)
|
||||
)
|
||||
)
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
|
||||
target_hour = ref_now.hour
|
||||
created: list[SituationalIncident] = []
|
||||
|
||||
for gf in monitored:
|
||||
current_ids: list[str] = []
|
||||
for v in vessels:
|
||||
obs = _coerce_utc(v.observed_at)
|
||||
if obs and (ref_now - obs).total_seconds() <= 3600 and point_in_geofence(float(v.lat), float(v.lon), gf):
|
||||
current_ids.append(f"vessel:{v.mmsi}")
|
||||
for a in aircraft:
|
||||
obs = _coerce_utc(a.observed_at)
|
||||
if obs and (ref_now - obs).total_seconds() <= 3600 and point_in_geofence(float(a.lat), float(a.lon), gf):
|
||||
current_ids.append(f"aircraft:{a.icao24}")
|
||||
for obj in interactables:
|
||||
if point_in_geofence(float(obj.latitude), float(obj.longitude), gf):
|
||||
current_ids.append(f"interactable:{obj.id}")
|
||||
|
||||
if len(current_ids) < 2:
|
||||
continue
|
||||
|
||||
by_day: dict[str, set[str]] = {}
|
||||
for pt in vessel_hist:
|
||||
obs = _coerce_utc(pt.received_at)
|
||||
if obs and obs.hour == target_hour and point_in_geofence(float(pt.lat), float(pt.lon), gf):
|
||||
by_day.setdefault(obs.date().isoformat(), set()).add(f"vessel:{pt.mmsi}")
|
||||
for pt in air_hist:
|
||||
obs = _coerce_utc(pt.observed_at)
|
||||
if obs and obs.hour == target_hour and point_in_geofence(float(pt.lat), float(pt.lon), gf):
|
||||
by_day.setdefault(obs.date().isoformat(), set()).add(f"aircraft:{pt.icao24}")
|
||||
|
||||
counts = [len(s) for s in by_day.values()]
|
||||
if len(counts) < min_baseline_days:
|
||||
continue
|
||||
mean = sum(counts) / len(counts)
|
||||
variance = sum((c - mean) ** 2 for c in counts) / len(counts)
|
||||
std = math.sqrt(variance)
|
||||
sigma = float((gf.rules or {}).get("surge_sigma", 2.0))
|
||||
threshold = mean + sigma * std
|
||||
# Guard against degenerate zero-std singletons
|
||||
if len(current_ids) <= threshold or len(current_ids) < max(3.0, mean + 2.0):
|
||||
continue
|
||||
|
||||
dedup_key = f"surge:gf:{gf.id}:hour:{target_hour}"
|
||||
if await _in_cooldown(
|
||||
db,
|
||||
incident_type="geofence_traffic_surge",
|
||||
dedup_key=dedup_key,
|
||||
now=ref_now,
|
||||
cooldown_minutes=cooldown_minutes,
|
||||
):
|
||||
continue
|
||||
|
||||
clat, clon = _geofence_centroid(gf)
|
||||
inc = SituationalIncident(
|
||||
incident_type="geofence_traffic_surge",
|
||||
severity="medium",
|
||||
status="open",
|
||||
h3_index=_h3_or_none(clat, clon),
|
||||
window_start=ref_now - timedelta(hours=1),
|
||||
window_end=ref_now,
|
||||
object_ids=current_ids[:40],
|
||||
signal_summary={
|
||||
"dedup_key": dedup_key,
|
||||
"geofence_id": gf.id,
|
||||
"geofence_name": gf.name,
|
||||
"current_count": len(current_ids),
|
||||
"baseline_mean": round(mean, 2),
|
||||
"baseline_std": round(std, 2),
|
||||
"sample_days": len(counts),
|
||||
"threshold": round(threshold, 2),
|
||||
"lat": clat,
|
||||
"lon": clon,
|
||||
},
|
||||
evidence=[
|
||||
{
|
||||
"source": "14d_hourly_baseline",
|
||||
"observed_at": to_iso8601_utc(ref_now),
|
||||
"detail": f"当前目标数 {len(current_ids)} 超过 14 天同时段基线均值 {mean:.1f} + {sigma:.1f}σ (阈值 {threshold:.1f})",
|
||||
}
|
||||
],
|
||||
assessment_kind="rule_alert",
|
||||
title=f"规则告警:围栏目标激增 ({gf.name} · 当前 {len(current_ids)} vs 基线 {mean:.1f})",
|
||||
created_at=ref_now,
|
||||
)
|
||||
db.add(inc)
|
||||
created.append(inc)
|
||||
if created:
|
||||
await db.commit()
|
||||
return created
|
||||
|
||||
|
||||
async def run_anomaly_cycle(db: AsyncSession, *, now: datetime | None = None) -> dict[str, Any]:
|
||||
"""Ensure preset geofences exist and run all three deterministic anomaly rules."""
|
||||
ref_now = now or datetime.now(UTC)
|
||||
seeded = await ensure_preset_geofences(db)
|
||||
geofences = list((await db.execute(select(Geofence).where(Geofence.enabled.is_(True)))).scalars().all())
|
||||
|
||||
loitering = await detect_cable_corridor_loitering(db, geofences, now=ref_now)
|
||||
dark = await detect_dark_target_blackout(db, geofences, now=ref_now)
|
||||
surge = await detect_geofence_traffic_surge(db, geofences, now=ref_now)
|
||||
|
||||
return {
|
||||
"seeded_presets": seeded,
|
||||
"evaluated_geofences": len(geofences),
|
||||
"loitering_alerts": len(loitering),
|
||||
"dark_target_alerts": len(dark),
|
||||
"surge_alerts": len(surge),
|
||||
}
|
||||
@@ -0,0 +1,398 @@
|
||||
"""Multi-domain H3 resolution-4 spatial-temporal convergence scanner (§3.9)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
import h3
|
||||
from sqlalchemy import 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 AircraftCurrentState
|
||||
from app.models.bgp_incident import BGPIncident
|
||||
from app.models.collected_data import CollectedData
|
||||
from app.models.disaster import DisasterEvent
|
||||
from app.models.earth_news import EarthNewsItem
|
||||
from app.models.geofence import SituationalIncident
|
||||
from app.models.gps_jamming import GPSJammingCell
|
||||
from app.models.maritime_advisory import CableAdvisory
|
||||
from app.services.ai.entity_resolver import _cable_centroid
|
||||
|
||||
logger = get_logger(__name__, service="fusion_convergence")
|
||||
|
||||
CAUSAL_FORBIDDEN_PHRASES: tuple[str, ...] = (
|
||||
"导致",
|
||||
"引发",
|
||||
"造成",
|
||||
"袭击",
|
||||
"破坏确认",
|
||||
"破坏导致",
|
||||
"系因",
|
||||
"caused by",
|
||||
"sabotage confirmed",
|
||||
"confirmed attack",
|
||||
)
|
||||
|
||||
|
||||
def contains_causal_assertion(text: str) -> bool:
|
||||
"""Return True if text asserts unverified causation rather than co-occurrence."""
|
||||
lowered = str(text or "").lower()
|
||||
return any(phrase.lower() in lowered for phrase in CAUSAL_FORBIDDEN_PHRASES)
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
def _cell_for(lat: Any, lon: Any) -> str | None:
|
||||
if lat is None or lon is None:
|
||||
return None
|
||||
try:
|
||||
return h3.latlng_to_cell(float(lat), float(lon), 4)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
async def _scan_domain_signals_by_cell(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
cutoff: datetime,
|
||||
now: datetime,
|
||||
) -> dict[str, dict[str, list[dict[str, Any]]]]:
|
||||
"""Collect multi-domain signals grouped as `{h3_index: {domain_key: [signal_items...]}}`."""
|
||||
buckets: dict[str, dict[str, list[dict[str, Any]]]] = {}
|
||||
|
||||
def _add(cell: str | None, domain: str, item: dict[str, Any]) -> None:
|
||||
if not cell:
|
||||
return
|
||||
buckets.setdefault(cell, {}).setdefault(domain, []).append(item)
|
||||
|
||||
# 1. §3.8 Rule alerts
|
||||
rule_rows = list(
|
||||
(
|
||||
await db.execute(
|
||||
select(SituationalIncident).where(
|
||||
SituationalIncident.assessment_kind == "rule_alert",
|
||||
SituationalIncident.status.in_(["open", "acknowledged"]),
|
||||
SituationalIncident.created_at >= cutoff,
|
||||
)
|
||||
)
|
||||
)
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
for row in rule_rows:
|
||||
summary = row.signal_summary or {}
|
||||
cell = row.h3_index or _cell_for(summary.get("lat"), summary.get("lon"))
|
||||
_add(
|
||||
cell,
|
||||
"rule_alert",
|
||||
{
|
||||
"object_ids": list(row.object_ids or []),
|
||||
"title": row.title,
|
||||
"incident_id": row.id,
|
||||
"observed_at": to_iso8601_utc(row.created_at),
|
||||
"lat": summary.get("lat"),
|
||||
"lon": summary.get("lon"),
|
||||
},
|
||||
)
|
||||
|
||||
# 2. Emergency aircraft
|
||||
ac_rows = list(
|
||||
(
|
||||
await db.execute(
|
||||
select(AircraftCurrentState).where(
|
||||
AircraftCurrentState.is_emergency.is_(True),
|
||||
AircraftCurrentState.observed_at >= cutoff,
|
||||
)
|
||||
)
|
||||
)
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
for ac in ac_rows:
|
||||
_add(
|
||||
_cell_for(ac.lat, ac.lon),
|
||||
"emergency_aircraft",
|
||||
{
|
||||
"object_ids": [f"aircraft:{ac.icao24}"],
|
||||
"title": f"紧急应答机 {ac.callsign or ac.icao24} ({ac.squawk or 'EMG'})",
|
||||
"observed_at": to_iso8601_utc(ac.observed_at),
|
||||
"lat": float(ac.lat),
|
||||
"lon": float(ac.lon),
|
||||
},
|
||||
)
|
||||
|
||||
# 3. High GPS jamming cells
|
||||
cutoff_date = cutoff.date().isoformat()
|
||||
gps_rows = list(
|
||||
(
|
||||
await db.execute(
|
||||
select(GPSJammingCell).where(
|
||||
GPSJammingCell.level == "high",
|
||||
GPSJammingCell.observed_date >= cutoff_date,
|
||||
)
|
||||
)
|
||||
)
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
for cell_row in gps_rows:
|
||||
h3_id = cell_row.h3_index if (cell_row.h3_index and h3.is_valid_cell(cell_row.h3_index)) else _cell_for(cell_row.lat, cell_row.lon)
|
||||
try:
|
||||
if h3_id and h3.get_resolution(h3_id) != 4:
|
||||
h3_id = h3.cell_to_parent(h3_id, 4)
|
||||
except Exception:
|
||||
h3_id = _cell_for(cell_row.lat, cell_row.lon)
|
||||
_add(
|
||||
h3_id,
|
||||
"gps_jamming",
|
||||
{
|
||||
"object_ids": [f"gps_jamming_cell:{cell_row.h3_index}"],
|
||||
"title": f"高强度 GNSS 干扰 ({cell_row.bad_ratio:.0%})",
|
||||
"observed_at": cell_row.observed_date,
|
||||
"lat": float(cell_row.lat),
|
||||
"lon": float(cell_row.lon),
|
||||
},
|
||||
)
|
||||
|
||||
# 4. Natural disasters
|
||||
dis_rows = list(
|
||||
(
|
||||
await db.execute(
|
||||
select(DisasterEvent).where(
|
||||
DisasterEvent.duplicate_of.is_(None),
|
||||
DisasterEvent.observed_at >= cutoff,
|
||||
)
|
||||
)
|
||||
)
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
for dis in dis_rows:
|
||||
_add(
|
||||
_cell_for(dis.lat, dis.lon),
|
||||
"disaster",
|
||||
{
|
||||
"object_ids": [f"disaster_event:{dis.id}"],
|
||||
"title": dis.title,
|
||||
"observed_at": to_iso8601_utc(dis.observed_at),
|
||||
"lat": float(dis.lat),
|
||||
"lon": float(dis.lon),
|
||||
},
|
||||
)
|
||||
|
||||
# 5. Cable advisories (NGA MSI)
|
||||
adv_rows = list(
|
||||
(
|
||||
await db.execute(
|
||||
select(CableAdvisory).where(
|
||||
CableAdvisory.cancelled_at.is_(None),
|
||||
CableAdvisory.ingested_at >= cutoff,
|
||||
)
|
||||
)
|
||||
)
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
for adv in adv_rows:
|
||||
cell = _cell_for(adv.lat, adv.lon)
|
||||
_add(
|
||||
cell,
|
||||
"cable_advisory",
|
||||
{
|
||||
"object_ids": [f"cable:{cid}" for cid in (adv.matched_cable_ids or [])[:3]],
|
||||
"title": f"NGA 航行警告 {adv.source_warning_id}",
|
||||
"observed_at": to_iso8601_utc(adv.issued_at or adv.ingested_at),
|
||||
"lat": adv.lat,
|
||||
"lon": adv.lon,
|
||||
},
|
||||
)
|
||||
|
||||
# 6. BGP incidents (using geo hints or linked cable coordinates)
|
||||
bgp_rows = list(
|
||||
(
|
||||
await db.execute(
|
||||
select(BGPIncident).where(BGPIncident.started_at >= cutoff).limit(200)
|
||||
)
|
||||
)
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
cable_coords_cache: dict[str, tuple[float, float]] | None = None
|
||||
for inc in bgp_rows:
|
||||
pts: list[tuple[float, float]] = []
|
||||
for entry in inc.related_cables or []:
|
||||
if isinstance(entry, dict) and entry.get("lat") is not None and entry.get("lon") is not None:
|
||||
pts.append((float(entry["lat"]), float(entry["lon"])))
|
||||
elif isinstance(entry, dict) and (entry.get("cable_id") or entry.get("cable_names")):
|
||||
if cable_coords_cache is None:
|
||||
cable_coords_cache = {}
|
||||
c_rows = list(
|
||||
(
|
||||
await db.execute(
|
||||
select(CollectedData).where(
|
||||
CollectedData.source == "arcgis_cables",
|
||||
CollectedData.is_current.is_(True),
|
||||
)
|
||||
)
|
||||
)
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
for cr in c_rows:
|
||||
ex = cr.extra_data or {}
|
||||
clat, clon = _cable_centroid(ex)
|
||||
if clat is not None and clon is not None:
|
||||
for key in (ex.get("cable_id"), cr.source_id, cr.name):
|
||||
if key:
|
||||
cable_coords_cache[str(key).lower()] = (clat, clon)
|
||||
cid = str(entry.get("cable_id") or "").lower()
|
||||
if cid in cable_coords_cache:
|
||||
pts.append(cable_coords_cache[cid])
|
||||
for cname in entry.get("cable_names") or []:
|
||||
if str(cname).lower() in cable_coords_cache:
|
||||
pts.append(cable_coords_cache[str(cname).lower()])
|
||||
for reg in inc.affected_regions or []:
|
||||
if isinstance(reg, dict) and reg.get("lat") is not None and reg.get("lon") is not None:
|
||||
pts.append((float(reg["lat"]), float(reg["lon"])))
|
||||
asns = [f"asn:AS{str(a).upper().removeprefix('AS')}" for a in (inc.affected_asns or [])[:3]]
|
||||
for pt_lat, pt_lon in pts:
|
||||
_add(
|
||||
_cell_for(pt_lat, pt_lon),
|
||||
"bgp",
|
||||
{
|
||||
"object_ids": asns,
|
||||
"title": inc.title,
|
||||
"incident_key": inc.incident_key,
|
||||
"observed_at": to_iso8601_utc(inc.started_at),
|
||||
"lat": pt_lat,
|
||||
"lon": pt_lon,
|
||||
},
|
||||
)
|
||||
|
||||
# 7. News hotspots
|
||||
news_rows = list(
|
||||
(
|
||||
await db.execute(
|
||||
select(EarthNewsItem).where(
|
||||
EarthNewsItem.resolved_at.is_(None),
|
||||
EarthNewsItem.last_seen_at >= cutoff,
|
||||
).limit(500)
|
||||
)
|
||||
)
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
for news in news_rows:
|
||||
_add(
|
||||
_cell_for(news.latitude, news.longitude),
|
||||
"news_hotspot",
|
||||
{
|
||||
"object_ids": [],
|
||||
"title": news.title,
|
||||
"observed_at": to_iso8601_utc(news.published_at or news.last_seen_at),
|
||||
"lat": float(news.latitude),
|
||||
"lon": float(news.longitude),
|
||||
},
|
||||
)
|
||||
|
||||
return buckets
|
||||
|
||||
|
||||
async def run_convergence_cycle(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
windows_hours: tuple[int, ...] = (6, 24),
|
||||
cooldown_minutes: int = 120,
|
||||
) -> list[SituationalIncident]:
|
||||
"""Emit `candidate_correlation` incidents strictly when >=2 distinct domains share an H3 res-4 cell."""
|
||||
ref_now = now or datetime.now(UTC)
|
||||
created: list[SituationalIncident] = []
|
||||
cooldown_cutoff = ref_now - timedelta(minutes=max(1, cooldown_minutes))
|
||||
|
||||
existing_recent = list(
|
||||
(
|
||||
await db.execute(
|
||||
select(SituationalIncident).where(
|
||||
SituationalIncident.assessment_kind == "candidate_correlation",
|
||||
SituationalIncident.created_at >= cooldown_cutoff,
|
||||
)
|
||||
)
|
||||
)
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
existing_keys = {
|
||||
str((row.signal_summary or {}).get("dedup_key") or "")
|
||||
for row in existing_recent
|
||||
}
|
||||
|
||||
for window_h in windows_hours:
|
||||
cutoff = ref_now - timedelta(hours=window_h)
|
||||
buckets = await _scan_domain_signals_by_cell(db, cutoff=cutoff, now=ref_now)
|
||||
for h3_cell, domains_map in buckets.items():
|
||||
distinct_domains = sorted(d for d, items in domains_map.items() if items)
|
||||
if len(distinct_domains) < 2:
|
||||
continue
|
||||
|
||||
dedup_key = f"corr:h3:{h3_cell}:w:{window_h}h"
|
||||
if dedup_key in existing_keys:
|
||||
continue
|
||||
|
||||
center_lat, center_lon = h3.cell_to_latlng(h3_cell)
|
||||
all_object_ids: list[str] = []
|
||||
evidence: list[dict[str, Any]] = []
|
||||
for dom in distinct_domains:
|
||||
for item in domains_map[dom][:3]:
|
||||
for oid in item.get("object_ids") or []:
|
||||
if oid not in all_object_ids:
|
||||
all_object_ids.append(oid)
|
||||
evidence.append(
|
||||
{
|
||||
"domain": dom,
|
||||
"title": item.get("title"),
|
||||
"observed_at": item.get("observed_at"),
|
||||
}
|
||||
)
|
||||
|
||||
title = (
|
||||
f"待核查关联:H3 {h3_cell} 在 {window_h} 小时内并存 "
|
||||
f"{len(distinct_domains)} 类信号({', '.join(distinct_domains)})"
|
||||
)
|
||||
severity = "high" if len(distinct_domains) >= 3 else "medium"
|
||||
inc = SituationalIncident(
|
||||
incident_type=f"multi_domain_convergence_{window_h}h",
|
||||
severity=severity,
|
||||
status="open",
|
||||
h3_index=h3_cell,
|
||||
window_start=cutoff,
|
||||
window_end=ref_now,
|
||||
object_ids=all_object_ids[:30],
|
||||
signal_summary={
|
||||
"dedup_key": dedup_key,
|
||||
"window_hours": window_h,
|
||||
"signal_types": distinct_domains,
|
||||
"signal_counts": {d: len(domains_map[d]) for d in distinct_domains},
|
||||
"lat": round(float(center_lat), 5),
|
||||
"lon": round(float(center_lon), 5),
|
||||
"co_occurrence_note": "仅记录同一时空网格内多域信号并存,需人工或独立证据进一步核查,不构成因果定论。",
|
||||
},
|
||||
evidence=evidence[:15],
|
||||
assessment_kind="candidate_correlation",
|
||||
title=title,
|
||||
created_at=ref_now,
|
||||
)
|
||||
db.add(inc)
|
||||
created.append(inc)
|
||||
existing_keys.add(dedup_key)
|
||||
|
||||
if created:
|
||||
await db.commit()
|
||||
return created
|
||||
@@ -0,0 +1,302 @@
|
||||
"""Grounded physical-to-logical dependency impact chain resolver (§3.9)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
import h3
|
||||
from sqlalchemy import desc, 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.bgp_incident import BGPIncident
|
||||
from app.models.collected_data import CollectedData
|
||||
from app.models.geofence import SituationalIncident
|
||||
from app.models.maritime_advisory import CableAdvisory
|
||||
from app.services.ai.entity_resolver import (
|
||||
_country_code_from_name,
|
||||
resolve_ontology_neighborhood,
|
||||
)
|
||||
|
||||
logger = get_logger(__name__, service="fusion_dependency")
|
||||
|
||||
|
||||
async def _find_corroborating_evidence(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
cable_id: str,
|
||||
cable_name: str,
|
||||
linked_asns: list[str],
|
||||
explicit_evidence: list[dict[str, Any]] | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Collect independent corroborating evidence (NGA advisory, operator notice, or grounded BGP)."""
|
||||
corroborating: list[dict[str, Any]] = []
|
||||
seen: set[str] = set()
|
||||
|
||||
for ev in explicit_evidence or []:
|
||||
ev_type = str(ev.get("evidence_type") or ev.get("source") or "").lower()
|
||||
if any(k in ev_type for k in ("nga", "advisory", "operator", "cable_notice", "bgp")):
|
||||
key = f"explicit:{ev.get('id') or ev.get('detail') or ev_type}"
|
||||
if key not in seen:
|
||||
seen.add(key)
|
||||
corroborating.append(dict(ev))
|
||||
|
||||
# 1. NGA CableAdvisory referencing this cable
|
||||
adv_rows = list(
|
||||
(
|
||||
await db.execute(
|
||||
select(CableAdvisory)
|
||||
.where(CableAdvisory.cancelled_at.is_(None))
|
||||
.order_by(desc(CableAdvisory.issued_at))
|
||||
.limit(100)
|
||||
)
|
||||
)
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
target_tokens = {cable_id.lower(), cable_name.lower()} - {""}
|
||||
for adv in adv_rows:
|
||||
matched = {str(cid).lower() for cid in (adv.matched_cable_ids or [])}
|
||||
text_low = str(adv.text or "").lower()
|
||||
if matched.intersection(target_tokens) or (cable_name and cable_name.lower() in text_low):
|
||||
key = f"nga:{adv.source_warning_id}"
|
||||
if key not in seen:
|
||||
seen.add(key)
|
||||
corroborating.append(
|
||||
{
|
||||
"evidence_type": "nga_advisory",
|
||||
"source": "nga_navigation_warnings",
|
||||
"warning_id": adv.source_warning_id,
|
||||
"observed_at": to_iso8601_utc(adv.issued_at or adv.ingested_at),
|
||||
"detail": adv.text[:240],
|
||||
}
|
||||
)
|
||||
|
||||
# 2. Grounded BGPIncident affecting linked ASNs or explicitly naming the cable
|
||||
clean_asns = {a.upper().removeprefix("AS") for a in linked_asns}
|
||||
bgp_rows = list(
|
||||
(
|
||||
await db.execute(
|
||||
select(BGPIncident).order_by(desc(BGPIncident.started_at)).limit(100)
|
||||
)
|
||||
)
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
for inc in bgp_rows:
|
||||
inc_asns = {str(a).upper().removeprefix("AS") for a in (inc.affected_asns or [])}
|
||||
rel_cables_str = str(inc.related_cables or "").lower()
|
||||
if inc_asns.intersection(clean_asns) or any(tok in rel_cables_str for tok in target_tokens):
|
||||
key = f"bgp:{inc.incident_key}"
|
||||
if key not in seen:
|
||||
seen.add(key)
|
||||
corroborating.append(
|
||||
{
|
||||
"evidence_type": "bgp_evidence",
|
||||
"source": inc.source,
|
||||
"incident_key": inc.incident_key,
|
||||
"observed_at": to_iso8601_utc(inc.started_at),
|
||||
"detail": inc.title,
|
||||
}
|
||||
)
|
||||
|
||||
return corroborating
|
||||
|
||||
|
||||
async def _find_backup_cables(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
exclude_cable_id: str,
|
||||
landing_point_ids: set[str],
|
||||
country_codes: set[str],
|
||||
) -> list[dict[str, str]]:
|
||||
"""Find alternative submarine cables sharing the affected landing points or countries."""
|
||||
backups: list[dict[str, str]] = []
|
||||
if not landing_point_ids and not country_codes:
|
||||
return backups
|
||||
|
||||
rel_rows = list(
|
||||
(
|
||||
await db.execute(
|
||||
select(CollectedData).where(
|
||||
CollectedData.source == "arcgis_cable_landing_relation",
|
||||
CollectedData.is_current.is_(True),
|
||||
)
|
||||
)
|
||||
)
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
lp_rows = list(
|
||||
(
|
||||
await db.execute(
|
||||
select(CollectedData).where(
|
||||
CollectedData.source == "arcgis_landing_points",
|
||||
CollectedData.is_current.is_(True),
|
||||
)
|
||||
)
|
||||
)
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
matching_city_ids = set(landing_point_ids)
|
||||
for lp in lp_rows:
|
||||
extra = lp.extra_data or {}
|
||||
if _country_code_from_name(extra.get("country")) in country_codes:
|
||||
cid = str(extra.get("city_id") or "")
|
||||
if cid:
|
||||
matching_city_ids.add(cid)
|
||||
|
||||
alt_cable_ids: set[str] = set()
|
||||
for rel in rel_rows:
|
||||
extra = rel.extra_data or {}
|
||||
if str(extra.get("city_id") or "") in matching_city_ids:
|
||||
cand = str(extra.get("cable_id") or "").strip()
|
||||
if cand and cand != exclude_cable_id:
|
||||
alt_cable_ids.add(cand)
|
||||
|
||||
if not alt_cable_ids:
|
||||
return backups
|
||||
|
||||
cable_rows = list(
|
||||
(
|
||||
await db.execute(
|
||||
select(CollectedData).where(
|
||||
CollectedData.source == "arcgis_cables",
|
||||
CollectedData.is_current.is_(True),
|
||||
)
|
||||
)
|
||||
)
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
seen_ids: set[str] = set()
|
||||
for cr in cable_rows:
|
||||
ex = cr.extra_data or {}
|
||||
cid = str(ex.get("cable_id") or cr.source_id or "").strip()
|
||||
if cid in alt_cable_ids and cid not in seen_ids:
|
||||
seen_ids.add(cid)
|
||||
backups.append({"cable_id": cid, "name": str(cr.name or cid)})
|
||||
return backups[:10]
|
||||
|
||||
|
||||
async def evaluate_cable_dependency_impact(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
cable_id: str,
|
||||
suspect_object_ids: list[str] | None = None,
|
||||
explicit_evidence: list[dict[str, Any]] | None = None,
|
||||
now: datetime | None = None,
|
||||
) -> SituationalIncident | None:
|
||||
"""Compute grounded physical->logical dependency impact + backup paths, gated on independent evidence."""
|
||||
ref_now = now or datetime.now(UTC)
|
||||
canonical_cable_id = cable_id if cable_id.startswith("cable:") else f"cable:{cable_id}"
|
||||
raw_cid = canonical_cable_id.split(":", 1)[1]
|
||||
|
||||
hood = await resolve_ontology_neighborhood(db, canonical_cable_id, depth=2, radius_km=160.0)
|
||||
if hood is None:
|
||||
return None
|
||||
|
||||
root = hood["root"]
|
||||
cable_name = str(root.get("label") or raw_cid)
|
||||
nodes = hood["nodes"]
|
||||
|
||||
# Collect grounded topology nodes (`derived_topology` or `analyst_asserted` — NOT proximity alone)
|
||||
topology_ids: set[str] = {canonical_cable_id}
|
||||
for edge in hood["edges"]:
|
||||
if edge["relation_source"] in {"derived_topology", "analyst_asserted"}:
|
||||
topology_ids.add(edge["from_object_id"])
|
||||
topology_ids.add(edge["to_object_id"])
|
||||
|
||||
landing_pts = [n for n in nodes if n["object_type"] == "landing_point" and n["object_id"] in topology_ids]
|
||||
countries = [n for n in nodes if n["object_type"] == "country" and n["object_id"] in topology_ids]
|
||||
compute_centers = [n for n in nodes if n["object_type"] == "compute_center" and n["object_id"] in topology_ids]
|
||||
asns = [n for n in nodes if n["object_type"] == "asn" and n["object_id"] in topology_ids]
|
||||
|
||||
corroborating = await _find_corroborating_evidence(
|
||||
db,
|
||||
cable_id=raw_cid,
|
||||
cable_name=cable_name,
|
||||
linked_asns=[n["object_id"].split(":", 1)[1] for n in asns],
|
||||
explicit_evidence=explicit_evidence,
|
||||
)
|
||||
# Require either NGA/operator notice (standalone physical evidence) OR explicit BGP evidence tied to the cable
|
||||
has_independent_evidence = any(
|
||||
ev.get("evidence_type") in {"nga_advisory", "operator_notice", "cable_notice", "bgp_evidence"}
|
||||
for ev in corroborating
|
||||
)
|
||||
if not has_independent_evidence:
|
||||
return None
|
||||
|
||||
landing_ids = {str((lp.get("attributes") or {}).get("city_id") or lp["object_id"].split(":", 1)[1]) for lp in landing_pts}
|
||||
country_codes = {str(c["object_id"].split(":", 1)[1]).upper() for c in countries}
|
||||
backup_cables = await _find_backup_cables(
|
||||
db,
|
||||
exclude_cable_id=raw_cid,
|
||||
landing_point_ids=landing_ids,
|
||||
country_codes=country_codes,
|
||||
)
|
||||
|
||||
c_lat = root.get("lat")
|
||||
c_lon = root.get("lon")
|
||||
impact_arcs: list[dict[str, Any]] = []
|
||||
if c_lat is not None and c_lon is not None:
|
||||
for target in landing_pts + compute_centers + countries:
|
||||
t_lat = target.get("lat")
|
||||
t_lon = target.get("lon")
|
||||
if isinstance(t_lat, (int, float)) and isinstance(t_lon, (int, float)):
|
||||
impact_arcs.append(
|
||||
{
|
||||
"from_object_id": canonical_cable_id,
|
||||
"to_object_id": target["object_id"],
|
||||
"from_lat": float(c_lat),
|
||||
"from_lon": float(c_lon),
|
||||
"to_lat": float(t_lat),
|
||||
"to_lon": float(t_lon),
|
||||
"label": f"{cable_name} → {target['label']}",
|
||||
"kind": "dependency_impact",
|
||||
}
|
||||
)
|
||||
|
||||
object_ids = [canonical_cable_id] + [n["object_id"] for n in landing_pts + countries + compute_centers + asns]
|
||||
for oid in suspect_object_ids or []:
|
||||
if oid not in object_ids:
|
||||
object_ids.append(oid)
|
||||
|
||||
h3_cell = None
|
||||
if c_lat is not None and c_lon is not None:
|
||||
try:
|
||||
h3_cell = h3.latlng_to_cell(float(c_lat), float(c_lon), 4)
|
||||
except Exception:
|
||||
h3_cell = None
|
||||
|
||||
inc = SituationalIncident(
|
||||
incident_type="cable_dependency_impact",
|
||||
severity="high",
|
||||
status="open",
|
||||
h3_index=h3_cell,
|
||||
window_start=ref_now - timedelta(hours=6),
|
||||
window_end=ref_now,
|
||||
object_ids=object_ids[:40],
|
||||
signal_summary={
|
||||
"cable_id": raw_cid,
|
||||
"cable_name": cable_name,
|
||||
"impacted_landing_points": [lp["object_id"] for lp in landing_pts],
|
||||
"impacted_countries": sorted(country_codes),
|
||||
"impacted_compute_centers": [cc["object_id"] for cc in compute_centers],
|
||||
"impacted_asns": [a["object_id"] for a in asns],
|
||||
"backup_cables": backup_cables,
|
||||
"impact_arcs": impact_arcs,
|
||||
"lat": c_lat,
|
||||
"lon": c_lon,
|
||||
},
|
||||
evidence=corroborating,
|
||||
assessment_kind="dependency_impact",
|
||||
title=f"依赖影响:{cable_name} 物理-逻辑影响链(受影响 {len(countries)} 国 · {len(backup_cables)} 条备用海缆)",
|
||||
created_at=ref_now,
|
||||
)
|
||||
db.add(inc)
|
||||
await db.commit()
|
||||
return inc
|
||||
@@ -0,0 +1,512 @@
|
||||
"""Deterministic end-to-end wargame scenario pipelines (§3.10)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
import h3
|
||||
from sqlalchemy import desc, 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 AircraftCurrentState
|
||||
from app.models.bgp_incident import BGPIncident
|
||||
from app.models.disaster import DisasterEvent
|
||||
from app.models.earth_news import EarthNewsItem
|
||||
from app.models.geofence import SituationalIncident
|
||||
from app.models.gps_jamming import GPSJammingCell
|
||||
from app.models.maritime_advisory import CableAdvisory
|
||||
from app.models.vessel import VesselCurrentState
|
||||
from app.services.ai.entity_resolver import resolve_ontology_neighborhood, resolve_ontology_object
|
||||
from app.services.ai.presentation_compiler import (
|
||||
StageCameraPose,
|
||||
StagePresentationContract,
|
||||
StageStepSpec,
|
||||
publish_stage_contract,
|
||||
)
|
||||
from app.services.fusion.convergence import contains_causal_assertion
|
||||
from app.services.fusion.dependency_impact import evaluate_cable_dependency_impact
|
||||
from app.services.nga_advisories import haversine_km
|
||||
from app.services.source_freshness import compute_domain_freshness
|
||||
|
||||
logger = get_logger(__name__, service="fusion_wargame")
|
||||
|
||||
|
||||
async def run_cable_protection_scenario(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
cable_id: str,
|
||||
suspect_vessel_mmsi: int | None = None,
|
||||
now: datetime | None = None,
|
||||
persist_incident: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""Execute §3.10 Scenario 1 (`wargame.cable_protection`).
|
||||
|
||||
Upgrades to `dependency_impact` ONLY when independent NGA / operator / direct BGP
|
||||
evidence exists; proximity + concurrent BGP without independent cable evidence stays
|
||||
strictly `candidate_correlation` ("待核查关联").
|
||||
"""
|
||||
ref_now = now or datetime.now(UTC)
|
||||
freshness = await compute_domain_freshness(db, now=ref_now)
|
||||
blind_spots = list(freshness.get("blind_spots") or [])
|
||||
|
||||
canonical_cable = cable_id if str(cable_id).startswith("cable:") else f"cable:{cable_id}"
|
||||
raw_cid = canonical_cable.split(":", 1)[1]
|
||||
cable_obj = await resolve_ontology_object(db, canonical_cable)
|
||||
lat = float(cable_obj["lat"]) if cable_obj and cable_obj.get("lat") is not None else 1.28
|
||||
lon = float(cable_obj["lon"]) if cable_obj and cable_obj.get("lon") is not None else 103.8
|
||||
|
||||
vessels = list((await db.execute(select(VesselCurrentState).limit(500))).scalars().all())
|
||||
nearby_vessels: list[dict[str, Any]] = []
|
||||
for v in vessels:
|
||||
dist = haversine_km(lat, lon, float(v.lat), float(v.lon))
|
||||
if (suspect_vessel_mmsi and v.mmsi == suspect_vessel_mmsi) or dist <= 120.0:
|
||||
nearby_vessels.append(
|
||||
{
|
||||
"object_id": f"vessel:{v.mmsi}",
|
||||
"label": f"{v.name or v.mmsi} ({float(v.sog or 0.0):.1f} kn)",
|
||||
"mmsi": v.mmsi,
|
||||
"sog": v.sog,
|
||||
"distance_km": round(dist, 1),
|
||||
"lat": float(v.lat),
|
||||
"lon": float(v.lon),
|
||||
}
|
||||
)
|
||||
|
||||
# Check direct CableAdvisory or explicit cable_id linkage
|
||||
adv_rows = list(
|
||||
(
|
||||
await db.execute(
|
||||
select(CableAdvisory)
|
||||
.where(CableAdvisory.cancelled_at.is_(None))
|
||||
.order_by(desc(CableAdvisory.issued_at))
|
||||
.limit(50)
|
||||
)
|
||||
)
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
matching_advisories = [
|
||||
adv.to_dict()
|
||||
for adv in adv_rows
|
||||
if raw_cid.lower() in {str(x).lower() for x in (adv.matched_cable_ids or [])}
|
||||
or (cable_obj and str(cable_obj.get("label") or "").lower() in str(adv.text or "").lower())
|
||||
]
|
||||
|
||||
bgp_rows = list(
|
||||
(await db.execute(select(BGPIncident).order_by(desc(BGPIncident.started_at)).limit(50)))
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
recent_bgp = [
|
||||
b.to_dict()
|
||||
for b in bgp_rows
|
||||
if any(
|
||||
raw_cid.lower() in str(rc).lower()
|
||||
for rc in (b.related_cables or [])
|
||||
)
|
||||
or len(bgp_rows) > 0
|
||||
][:5]
|
||||
|
||||
suspect_ids = [v["object_id"] for v in nearby_vessels[:5]]
|
||||
impact_inc: SituationalIncident | None = None
|
||||
if matching_advisories:
|
||||
impact_inc = await evaluate_cable_dependency_impact(
|
||||
db,
|
||||
cable_id=raw_cid,
|
||||
suspect_object_ids=suspect_ids,
|
||||
now=ref_now,
|
||||
)
|
||||
|
||||
h3_cell = h3.latlng_to_cell(lat, lon, 4)
|
||||
if impact_inc is not None:
|
||||
assessment_kind = "dependency_impact"
|
||||
verdict_label = "依赖影响"
|
||||
incident = impact_inc
|
||||
impacted_countries = impact_inc.signal_summary.get("impacted_countries") or []
|
||||
impacted_compute = impact_inc.signal_summary.get("impacted_compute_centers") or []
|
||||
backup_cables = impact_inc.signal_summary.get("backup_cables") or []
|
||||
impact_arcs = impact_inc.signal_summary.get("impact_arcs") or []
|
||||
briefing_text = (
|
||||
f"【海缆安全护卫 · 依赖影响】海缆 {raw_cid} 命中独立 NGA 航行警告({len(matching_advisories)} 条),"
|
||||
f"已基于本体拓扑生成物理-逻辑影响链:受影响国家 {', '.join(impacted_countries) or '暂无'},"
|
||||
f"备用海缆 {len(backup_cables)} 条。周边监测船舶 {len(nearby_vessels)} 艘(作为核查对象附列)。"
|
||||
)
|
||||
else:
|
||||
assessment_kind = "candidate_correlation"
|
||||
verdict_label = "待核查关联"
|
||||
hood = await resolve_ontology_neighborhood(db, canonical_cable, depth=2, radius_km=120.0)
|
||||
nodes = (hood or {}).get("nodes") or []
|
||||
impacted_countries = [n["object_id"].split(":", 1)[1] for n in nodes if n["object_type"] == "country"]
|
||||
impacted_compute = [n["object_id"] for n in nodes if n["object_type"] == "compute_center"]
|
||||
backup_cables = []
|
||||
impact_arcs = []
|
||||
|
||||
incident = SituationalIncident(
|
||||
incident_type="wargame_cable_protection",
|
||||
severity="medium",
|
||||
status="open",
|
||||
h3_index=h3_cell,
|
||||
window_start=ref_now - timedelta(hours=6),
|
||||
window_end=ref_now,
|
||||
object_ids=[canonical_cable] + suspect_ids,
|
||||
signal_summary={
|
||||
"dedup_key": f"wg:cable:{raw_cid}:{h3_cell}",
|
||||
"cable_id": raw_cid,
|
||||
"signal_types": ["vessel_loitering", "bgp"] if recent_bgp else ["vessel_loitering"],
|
||||
"lat": lat,
|
||||
"lon": lon,
|
||||
},
|
||||
evidence=[
|
||||
{
|
||||
"domain": "vessels",
|
||||
"detail": f"走廊附近存在 {len(nearby_vessels)} 艘目标船舶",
|
||||
"observed_at": to_iso8601_utc(ref_now),
|
||||
}
|
||||
],
|
||||
assessment_kind="candidate_correlation",
|
||||
title=f"待核查关联:{raw_cid} 走廊附近船舶徘徊与同时段异常并存(尚无独立断缆证据)",
|
||||
created_at=ref_now,
|
||||
)
|
||||
if persist_incident:
|
||||
db.add(incident)
|
||||
await db.commit()
|
||||
|
||||
briefing_text = (
|
||||
f"【海缆安全护卫 · 待核查关联】在海缆 {raw_cid}(H3 {h3_cell})周边观测到低速船舶与同时段异常信号并存,"
|
||||
f"但尚未发现独立 NGA 海缆告警或运营方公告确认物理受损,当前仅记为待核查关联,不作因果判断。"
|
||||
)
|
||||
|
||||
if blind_spots:
|
||||
briefing_text += f"\n情报盲区:{'; '.join(item['domain'] + '(' + item['status'] + ')' for item in blind_spots)}。"
|
||||
|
||||
spatial_cards = [
|
||||
{
|
||||
"key": f"cable-status-{raw_cid}",
|
||||
"title": f"海缆态势 · {cable_obj['label'] if cable_obj else raw_cid}",
|
||||
"title_en": f"Cable Posture · {raw_cid}",
|
||||
"summary": f"判定等级:{verdict_label} · NGA 告警 {len(matching_advisories)} 条",
|
||||
"anchor": {"latitude": lat, "longitude": lon},
|
||||
"side": "left",
|
||||
"partner_key": f"suspect-vessels-{raw_cid}",
|
||||
"blocks": [
|
||||
{
|
||||
"block_id": "cable-samples",
|
||||
"block_type": "entity_samples",
|
||||
"data": {
|
||||
"title": "周边疑似船舶",
|
||||
"items": nearby_vessels[:5],
|
||||
},
|
||||
}
|
||||
],
|
||||
},
|
||||
{
|
||||
"key": f"suspect-vessels-{raw_cid}",
|
||||
"title": "受影响国家与算力资产",
|
||||
"title_en": "Impacted Countries & Compute",
|
||||
"summary": f"影响国家:{', '.join(impacted_countries) or '待定'} · 备用路径 {len(backup_cables)} 条",
|
||||
"anchor": {"latitude": lat + 0.15, "longitude": lon + 0.25},
|
||||
"side": "right",
|
||||
"partner_key": f"cable-status-{raw_cid}",
|
||||
"blocks": [
|
||||
{
|
||||
"block_id": "impact-samples",
|
||||
"block_type": "entity_samples",
|
||||
"data": {
|
||||
"title": "关联算力与海缆",
|
||||
"items": [{"object_id": cid, "label": cid} for cid in impacted_compute[:4]],
|
||||
},
|
||||
}
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
overlays = ["geofences", "chokepoints"]
|
||||
if assessment_kind == "dependency_impact":
|
||||
overlays.append("dependency_arcs")
|
||||
|
||||
contract = StagePresentationContract(
|
||||
presentation_key=f"wargame-cable-{raw_cid}-{assessment_kind}",
|
||||
domain="cable",
|
||||
time_basis="retrospective",
|
||||
title=f"海缆安全护卫 · {raw_cid} ({verdict_label})",
|
||||
title_en=f"Cable Protection · {raw_cid}",
|
||||
summary=briefing_text[:400],
|
||||
summary_en=briefing_text[:400],
|
||||
steps=[
|
||||
StageStepSpec(
|
||||
step_id="cable-wg-1",
|
||||
stage="discover",
|
||||
title="第一幕 · 海缆走廊目标检索",
|
||||
title_en="Act 1 · Cable Corridor Discovery",
|
||||
caption=briefing_text[:420],
|
||||
caption_en=briefing_text[:420],
|
||||
camera=StageCameraPose(lat=lat, lon=lon, zoom=1.42),
|
||||
overlays=overlays,
|
||||
spatial_cards=spatial_cards,
|
||||
spotlight_card_keys=[c["key"] for c in spatial_cards],
|
||||
workflow_params={"workflow_id": "wargame.cable_protection", "cable_id": raw_cid},
|
||||
),
|
||||
StageStepSpec(
|
||||
step_id="cable-wg-2",
|
||||
stage="impact" if assessment_kind == "dependency_impact" else "explain",
|
||||
title="第二幕 · 证据分级与备用路径",
|
||||
title_en="Act 2 · Corroboration & Backup Paths",
|
||||
caption=f"{verdict_label} · 备用海缆 {len(backup_cables)} 条",
|
||||
caption_en=f"{assessment_kind} · {len(backup_cables)} backup cables",
|
||||
camera=StageCameraPose(lat=lat, lon=lon, zoom=1.22),
|
||||
overlays=overlays,
|
||||
spatial_cards=spatial_cards,
|
||||
spotlight_card_keys=[c["key"] for c in spatial_cards],
|
||||
),
|
||||
],
|
||||
)
|
||||
if persist_incident:
|
||||
await publish_stage_contract(db, contract)
|
||||
|
||||
return {
|
||||
"workflow_id": "wargame.cable_protection",
|
||||
"assessment_kind": assessment_kind,
|
||||
"verdict_label": verdict_label,
|
||||
"incident": incident.to_dict(),
|
||||
"impacted_countries": impacted_countries,
|
||||
"impacted_compute": impacted_compute,
|
||||
"backup_cables": backup_cables,
|
||||
"impact_arcs": impact_arcs,
|
||||
"blind_spots": blind_spots,
|
||||
"spatial_cards": spatial_cards,
|
||||
"overlays": overlays,
|
||||
"briefing": briefing_text,
|
||||
"contains_causal_assertion": contains_causal_assertion(briefing_text),
|
||||
"presentation": contract.model_dump(),
|
||||
}
|
||||
|
||||
|
||||
async def run_air_sea_em_scenario(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
center_lat: float = 2.0,
|
||||
center_lon: float = 102.0,
|
||||
radius_km: float = 350.0,
|
||||
now: datetime | None = None,
|
||||
persist_incident: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""Execute §3.10 Scenario 2 (`wargame.air_sea_em`) across aircraft, GPS jamming, vessels, disasters, and news."""
|
||||
ref_now = now or datetime.now(UTC)
|
||||
freshness = await compute_domain_freshness(db, now=ref_now)
|
||||
blind_spots = list(freshness.get("blind_spots") or [])
|
||||
|
||||
aircraft = list((await db.execute(select(AircraftCurrentState).limit(1000))).scalars().all())
|
||||
local_air = [
|
||||
a
|
||||
for a in aircraft
|
||||
if haversine_km(center_lat, center_lon, float(a.lat), float(a.lon)) <= radius_km
|
||||
]
|
||||
mil_or_emg_air = [a for a in local_air if a.is_military or a.is_emergency]
|
||||
|
||||
gps_cells = list(
|
||||
(await db.execute(select(GPSJammingCell).where(GPSJammingCell.level == "high").limit(300)))
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
local_gps = [
|
||||
g
|
||||
for g in gps_cells
|
||||
if haversine_km(center_lat, center_lon, float(g.lat), float(g.lon)) <= radius_km
|
||||
]
|
||||
|
||||
vessels = list((await db.execute(select(VesselCurrentState).limit(1000))).scalars().all())
|
||||
local_vessels = [
|
||||
v
|
||||
for v in vessels
|
||||
if haversine_km(center_lat, center_lon, float(v.lat), float(v.lon)) <= radius_km
|
||||
]
|
||||
warships = [v for v in local_vessels if v.vessel_type == 35 or "uss" in str(v.name or "").lower()]
|
||||
|
||||
disasters = list(
|
||||
(await db.execute(select(DisasterEvent).where(DisasterEvent.duplicate_of.is_(None)).limit(300)))
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
local_disasters = [
|
||||
d
|
||||
for d in disasters
|
||||
if haversine_km(center_lat, center_lon, float(d.lat), float(d.lon)) <= radius_km
|
||||
]
|
||||
|
||||
news_rows = list(
|
||||
(await db.execute(select(EarthNewsItem).where(EarthNewsItem.resolved_at.is_(None)).limit(200)))
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
local_news = sorted(
|
||||
[
|
||||
n
|
||||
for n in news_rows
|
||||
if haversine_km(center_lat, center_lon, float(n.latitude), float(n.longitude)) <= max(radius_km, 800.0)
|
||||
],
|
||||
key=lambda x: (x.credibility_tier if x.credibility_tier is not None else 99),
|
||||
)[:5]
|
||||
|
||||
signal_domains: list[str] = []
|
||||
if local_gps:
|
||||
signal_domains.append("gps_jamming")
|
||||
if mil_or_emg_air:
|
||||
signal_domains.append("military_emergency_aircraft")
|
||||
if warships or local_vessels:
|
||||
signal_domains.append("chokepoint_vessels")
|
||||
if local_disasters:
|
||||
signal_domains.append("disasters")
|
||||
if local_news:
|
||||
signal_domains.append("news")
|
||||
|
||||
h3_cell = h3.latlng_to_cell(center_lat, center_lon, 4)
|
||||
obj_ids = (
|
||||
[f"aircraft:{a.icao24}" for a in mil_or_emg_air[:6]]
|
||||
+ [f"vessel:{v.mmsi}" for v in warships[:6]]
|
||||
+ [f"gps_jamming_cell:{g.h3_index}" for g in local_gps[:4]]
|
||||
)
|
||||
|
||||
incident = SituationalIncident(
|
||||
incident_type="wargame_air_sea_em",
|
||||
severity="high" if len(signal_domains) >= 3 else "medium",
|
||||
status="open",
|
||||
h3_index=h3_cell,
|
||||
window_start=ref_now - timedelta(hours=6),
|
||||
window_end=ref_now,
|
||||
object_ids=obj_ids,
|
||||
signal_summary={
|
||||
"dedup_key": f"wg:em:{h3_cell}",
|
||||
"signal_types": signal_domains,
|
||||
"lat": center_lat,
|
||||
"lon": center_lon,
|
||||
"aircraft_count": len(mil_or_emg_air),
|
||||
"gps_high_count": len(local_gps),
|
||||
"warship_count": len(warships),
|
||||
"disaster_count": len(local_disasters),
|
||||
},
|
||||
evidence=[
|
||||
{
|
||||
"domain": "multi_domain_em",
|
||||
"detail": (
|
||||
f"区域内高 GNSS 干扰 {len(local_gps)} 格,军机/紧急机 {len(mil_or_emg_air)} 架,"
|
||||
f"咽喉军舰 {len(warships)} 艘,自然灾害 {len(local_disasters)} 起。"
|
||||
),
|
||||
"observed_at": to_iso8601_utc(ref_now),
|
||||
}
|
||||
],
|
||||
assessment_kind="candidate_correlation",
|
||||
title=f"待核查关联:空海电磁多域信号集中(H3 {h3_cell} · 军机/GNSS/军舰并存)",
|
||||
created_at=ref_now,
|
||||
)
|
||||
if persist_incident:
|
||||
db.add(incident)
|
||||
await db.commit()
|
||||
|
||||
blind_spot_text = (
|
||||
"; ".join(f"{b['domain']}({b['status']})" for b in blind_spots)
|
||||
if blind_spots
|
||||
else "暂无过期域"
|
||||
)
|
||||
briefing = (
|
||||
f"【空海电磁联合态势 · 待核查关联】在 H3 {h3_cell} 半径 {int(radius_km)} km 内汇总观测到:"
|
||||
f"高 GNSS 干扰区 {len(local_gps)} 个,军用或紧急航空器 {len(mil_or_emg_air)} 架,"
|
||||
f"舰艇目标 {len(warships)} 艘,自然灾害 {len(local_disasters)} 起。"
|
||||
f"上述信号属于同一空域时段内的并存观测,作为待核查关联呈现,不代表已确认军事或技术因果关系。"
|
||||
f"\n情报盲区:{blind_spot_text}。"
|
||||
)
|
||||
|
||||
spatial_cards = [
|
||||
{
|
||||
"key": "em-signal-duel",
|
||||
"title": "空海电磁多域信号对比",
|
||||
"title_en": "Air-Sea EM Multi-Domain Posture",
|
||||
"summary": f"军机/紧急 {len(mil_or_emg_air)} vs GNSS 高干扰 {len(local_gps)} vs 舰艇 {len(warships)}",
|
||||
"anchor": {"latitude": center_lat, "longitude": center_lon},
|
||||
"side": "left",
|
||||
"partner_key": "em-linked-objects",
|
||||
"blocks": [
|
||||
{
|
||||
"block_id": "em-duel-1",
|
||||
"block_type": "bilateral_duel",
|
||||
"data": {
|
||||
"title": "空中集群与海面舰艇密度对照",
|
||||
"left_label": "军机/紧急",
|
||||
"right_label": "海面舰艇",
|
||||
"left_value": len(mil_or_emg_air),
|
||||
"right_value": max(1, len(warships)),
|
||||
"metric_label": "比值",
|
||||
"metric_value": round((len(mil_or_emg_air) / max(1, len(warships))) * 100.0, 1),
|
||||
"unit": "",
|
||||
},
|
||||
}
|
||||
],
|
||||
},
|
||||
{
|
||||
"key": "em-linked-objects",
|
||||
"title": "区域联合采样对象",
|
||||
"title_en": "Correlated Area Targets",
|
||||
"summary": f"盲区域数:{len(blind_spots)} · 关联新闻 {len(local_news)} 条",
|
||||
"anchor": {"latitude": center_lat + 0.3, "longitude": center_lon + 0.4},
|
||||
"side": "right",
|
||||
"partner_key": "em-signal-duel",
|
||||
"blocks": [
|
||||
{
|
||||
"block_id": "em-samples-1",
|
||||
"block_type": "entity_samples",
|
||||
"data": {
|
||||
"title": "重点空海目标",
|
||||
"items": [{"object_id": oid, "label": oid} for oid in obj_ids[:6]],
|
||||
},
|
||||
}
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
overlays = ["chokepoints", "geofences"]
|
||||
contract = StagePresentationContract(
|
||||
presentation_key=f"wargame-em-{h3_cell}",
|
||||
domain="global",
|
||||
time_basis="retrospective",
|
||||
title="空海电磁联合态势(待核查关联)",
|
||||
title_en="Air-Sea Electromagnetic Joint Posture",
|
||||
summary=briefing[:400],
|
||||
summary_en="Joint air, naval, and GNSS jamming co-occurrence summary.",
|
||||
steps=[
|
||||
StageStepSpec(
|
||||
step_id="em-wg-1",
|
||||
stage="discover",
|
||||
title="第一幕 · 空海电磁多域叠加",
|
||||
title_en="Act 1 · Multi-Domain Co-occurrence",
|
||||
caption=briefing[:420],
|
||||
caption_en=briefing[:420],
|
||||
camera=StageCameraPose(lat=center_lat, lon=center_lon, zoom=1.35),
|
||||
overlays=overlays,
|
||||
spatial_cards=spatial_cards,
|
||||
spotlight_card_keys=[c["key"] for c in spatial_cards],
|
||||
workflow_params={"workflow_id": "wargame.air_sea_em", "h3_index": h3_cell},
|
||||
)
|
||||
],
|
||||
)
|
||||
if persist_incident:
|
||||
await publish_stage_contract(db, contract)
|
||||
|
||||
return {
|
||||
"workflow_id": "wargame.air_sea_em",
|
||||
"assessment_kind": "candidate_correlation",
|
||||
"incident": incident.to_dict(),
|
||||
"signal_domains": signal_domains,
|
||||
"aircraft_count": len(mil_or_emg_air),
|
||||
"gps_jamming_count": len(local_gps),
|
||||
"warship_count": len(warships),
|
||||
"disaster_count": len(local_disasters),
|
||||
"news_count": len(local_news),
|
||||
"blind_spots": blind_spots,
|
||||
"spatial_cards": spatial_cards,
|
||||
"overlays": overlays,
|
||||
"briefing": briefing,
|
||||
"contains_causal_assertion": contains_causal_assertion(briefing),
|
||||
"presentation": contract.model_dump(),
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
"""Investigation Case Board service: immutable SHA-256 freeze snapshots and Markdown export (§4.3)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from sqlalchemy import desc, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.time import to_iso8601_utc
|
||||
from app.models.investigation_case import CaseItem, CaseVersion, InvestigationCase
|
||||
from app.services.storage_policy import compute_record_content_hash
|
||||
|
||||
|
||||
async def freeze_investigation_case(
|
||||
db: AsyncSession,
|
||||
case: InvestigationCase,
|
||||
*,
|
||||
frozen_by: str,
|
||||
) -> CaseVersion:
|
||||
"""Create an immutable `CaseVersion` snapshot with deterministic SHA-256 and mark case frozen."""
|
||||
items = list(
|
||||
(
|
||||
await db.execute(
|
||||
select(CaseItem)
|
||||
.where(CaseItem.case_id == case.id)
|
||||
.order_by(CaseItem.id.asc())
|
||||
)
|
||||
)
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
latest_ver = (
|
||||
await db.execute(
|
||||
select(CaseVersion)
|
||||
.where(CaseVersion.case_id == case.id)
|
||||
.order_by(desc(CaseVersion.version))
|
||||
.limit(1)
|
||||
)
|
||||
).scalars().first()
|
||||
next_version = int(latest_ver.version) + 1 if latest_ver else 1
|
||||
|
||||
snapshot = {
|
||||
"case_id": case.id,
|
||||
"title": case.title,
|
||||
"summary": case.summary,
|
||||
"owner_id": case.owner_id,
|
||||
"owner_name": case.owner_name,
|
||||
"version": next_version,
|
||||
"items": [
|
||||
{
|
||||
"id": it.id,
|
||||
"item_type": it.item_type,
|
||||
"ref_id": it.ref_id,
|
||||
"payload": it.payload or {},
|
||||
"added_by": it.added_by,
|
||||
"added_at": to_iso8601_utc(it.added_at),
|
||||
}
|
||||
for it in items
|
||||
],
|
||||
}
|
||||
sha = compute_record_content_hash(snapshot)
|
||||
ver = CaseVersion(
|
||||
case_id=case.id,
|
||||
version=next_version,
|
||||
snapshot=snapshot,
|
||||
content_sha256=sha,
|
||||
frozen_by=frozen_by,
|
||||
frozen_at=datetime.now(UTC),
|
||||
)
|
||||
case.status = "frozen"
|
||||
db.add(ver)
|
||||
await db.commit()
|
||||
await db.refresh(case)
|
||||
await db.refresh(ver)
|
||||
return ver
|
||||
|
||||
|
||||
def export_case_markdown(
|
||||
case: InvestigationCase,
|
||||
items: list[CaseItem],
|
||||
versions: list[CaseVersion],
|
||||
) -> str:
|
||||
"""Render revision/freeze-bound Markdown dossier citing provenance and SHA-256 hashes."""
|
||||
latest = versions[0] if versions else None
|
||||
lines: list[str] = [
|
||||
f"# 研判卷宗 · {case.title}",
|
||||
"",
|
||||
f"- **卷宗编号**: CASE-{case.id}",
|
||||
f"- **状态**: {case.status}",
|
||||
f"- **责任人**: {case.owner_name or case.owner_id}",
|
||||
f"- **共享只读可见**: {'是' if case.is_shared else '否'}",
|
||||
f"- **创建时间**: {to_iso8601_utc(case.created_at) or '-'}",
|
||||
]
|
||||
if latest:
|
||||
lines.extend(
|
||||
[
|
||||
f"- **最新冻结版本**: v{latest.version}",
|
||||
f"- **冻结 SHA-256 摘要**: `{latest.content_sha256}`",
|
||||
f"- **冻结人 / 时间**: {latest.frozen_by} @ {to_iso8601_utc(latest.frozen_at) or '-'}",
|
||||
]
|
||||
)
|
||||
lines.extend(["", "## 卷宗摘要", "", case.summary or "暂无摘要。", "", "## 关联证据与条目清单", ""])
|
||||
|
||||
if not items:
|
||||
lines.append("_当前卷宗暂无绑定条目。_")
|
||||
else:
|
||||
for idx, it in enumerate(items, start=1):
|
||||
payload = dict(it.payload or {})
|
||||
item_hash = compute_record_content_hash(
|
||||
{"item_type": it.item_type, "ref_id": it.ref_id, "payload": payload}
|
||||
)
|
||||
prov = payload.get("provenance") or payload.get("source") or it.added_by
|
||||
lines.append(f"### {idx}. [{it.item_type}] `{it.ref_id}`")
|
||||
lines.append(f"- **条目摘要哈希**: `{item_hash}`")
|
||||
lines.append(f"- **出处 / 提交人**: {prov} ({it.added_by} @ {to_iso8601_utc(it.added_at) or '-'})")
|
||||
if payload.get("title"):
|
||||
lines.append(f"- **标题**: {payload['title']}")
|
||||
if payload.get("note") or payload.get("summary"):
|
||||
lines.append(f"- **研判说明**: {payload.get('note') or payload.get('summary')}")
|
||||
if payload.get("publish_id"):
|
||||
lines.append(f"- **关联发布版本 (`publish_id`)**: `{payload['publish_id']}`")
|
||||
lines.append("")
|
||||
|
||||
if versions:
|
||||
lines.extend(["## 不可变冻结历史", ""])
|
||||
for ver in versions:
|
||||
lines.append(
|
||||
f"- `v{ver.version}` · `{ver.content_sha256}` · {ver.frozen_by} · {to_iso8601_utc(ver.frozen_at) or '-'}"
|
||||
)
|
||||
lines.append("")
|
||||
|
||||
return "\n".join(lines)
|
||||
@@ -0,0 +1,227 @@
|
||||
"""Maritime chokepoint polygons, strategic ports registry, and rolling-baseline vessel analytics."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from functools import lru_cache
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.logging import get_logger
|
||||
from app.models.vessel import VesselCurrentState, VesselPosition
|
||||
from app.services.vessel_types import classify_military_vessel, is_cable_repair_vessel
|
||||
|
||||
logger = get_logger(__name__, service="maritime_geography")
|
||||
|
||||
_DATA_DIR = Path(__file__).resolve().parents[1] / "data"
|
||||
_CHOKEPOINTS_PATH = _DATA_DIR / "maritime_chokepoints.json"
|
||||
_PORTS_PATH = _DATA_DIR / "strategic_ports.json"
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def load_chokepoints() -> list[dict[str, Any]]:
|
||||
"""Return cited maritime chokepoint definitions."""
|
||||
if not _CHOKEPOINTS_PATH.exists():
|
||||
return []
|
||||
data = json.loads(_CHOKEPOINTS_PATH.read_text(encoding="utf-8"))
|
||||
return list(data) if isinstance(data, list) else []
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def load_strategic_ports() -> list[dict[str, Any]]:
|
||||
"""Return cited strategic ports directory."""
|
||||
if not _PORTS_PATH.exists():
|
||||
return []
|
||||
data = json.loads(_PORTS_PATH.read_text(encoding="utf-8"))
|
||||
return list(data) if isinstance(data, list) else []
|
||||
|
||||
|
||||
def point_in_polygon(lat: float, lon: float, polygon: list[list[float]]) -> bool:
|
||||
"""Ray-casting check for `[lon, lat]` polygon ring."""
|
||||
if not polygon or len(polygon) < 3:
|
||||
return False
|
||||
inside = False
|
||||
n = len(polygon)
|
||||
j = n - 1
|
||||
for i in range(n):
|
||||
xi, yi = float(polygon[i][0]), float(polygon[i][1])
|
||||
xj, yj = float(polygon[j][0]), float(polygon[j][1])
|
||||
intersects = ((yi > lat) != (yj > lat)) and (
|
||||
lon < (xj - xi) * (lat - yi) / ((yj - yi) or 1e-12) + xi
|
||||
)
|
||||
if intersects:
|
||||
inside = not inside
|
||||
j = i
|
||||
return inside
|
||||
|
||||
|
||||
def find_chokepoint_for_point(lat: float, lon: float) -> dict[str, Any] | None:
|
||||
"""Return the first chokepoint containing `(lat, lon)` or None."""
|
||||
for cp in load_chokepoints():
|
||||
if point_in_polygon(lat, lon, cp.get("polygon") or []):
|
||||
return cp
|
||||
return None
|
||||
|
||||
|
||||
def enrich_vessel_feature_roles(feature: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Attach `military_role`, `is_warship`, `is_cable_ship`, and `chokepoint_id` on a vessel GeoJSON feature."""
|
||||
props = feature.get("properties")
|
||||
if not isinstance(props, dict):
|
||||
return feature
|
||||
m_role, m_src = classify_military_vessel(
|
||||
vessel_type=props.get("vessel_type") or props.get("vessel_type_name"),
|
||||
name=props.get("name"),
|
||||
callsign=props.get("callsign"),
|
||||
)
|
||||
cable_ship, cable_src = is_cable_repair_vessel(
|
||||
vessel_type=props.get("vessel_type"),
|
||||
name=props.get("name"),
|
||||
)
|
||||
props["military_role"] = m_role
|
||||
props["military_source"] = m_src
|
||||
props["is_warship"] = m_role is not None
|
||||
props["is_cable_ship"] = bool(cable_ship)
|
||||
props["cable_ship_source"] = cable_src
|
||||
if m_role is not None and not props.get("vessel_type_name"):
|
||||
props["vessel_type_name"] = "Military"
|
||||
|
||||
coords = (feature.get("geometry") or {}).get("coordinates") or []
|
||||
if len(coords) >= 2:
|
||||
try:
|
||||
cp = find_chokepoint_for_point(float(coords[1]), float(coords[0]))
|
||||
props["chokepoint_id"] = cp["id"] if cp else None
|
||||
props["chokepoint_name"] = cp["name"] if cp else None
|
||||
except (TypeError, ValueError):
|
||||
props["chokepoint_id"] = None
|
||||
return feature
|
||||
|
||||
|
||||
async def compute_chokepoint_vessel_summary(
|
||||
db: AsyncSession | None,
|
||||
features: list[dict[str, Any]] | None = None,
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Compute per-chokepoint vessel, warship, cable-ship counts vs 7-day rolling baseline."""
|
||||
current_now = now.astimezone(UTC) if now is not None else datetime.now(UTC)
|
||||
chokepoints = load_chokepoints()
|
||||
if not chokepoints:
|
||||
return []
|
||||
|
||||
current_rows: list[tuple[float, float, Any, Any, Any]] = []
|
||||
if features is not None:
|
||||
for feat in features:
|
||||
enrich_vessel_feature_roles(feat)
|
||||
coords = (feat.get("geometry") or {}).get("coordinates") or []
|
||||
if len(coords) < 2:
|
||||
continue
|
||||
props = feat.get("properties") or {}
|
||||
current_rows.append(
|
||||
(
|
||||
float(coords[1]),
|
||||
float(coords[0]),
|
||||
props.get("vessel_type") or props.get("vessel_type_name"),
|
||||
props.get("name"),
|
||||
props.get("callsign"),
|
||||
)
|
||||
)
|
||||
elif db is not None and hasattr(db, "execute"):
|
||||
try:
|
||||
cutoff = current_now - timedelta(minutes=60)
|
||||
res = await db.execute(
|
||||
select(
|
||||
VesselCurrentState.lat,
|
||||
VesselCurrentState.lon,
|
||||
VesselCurrentState.vessel_type,
|
||||
VesselCurrentState.name,
|
||||
VesselCurrentState.callsign,
|
||||
).where(VesselCurrentState.observed_at >= cutoff)
|
||||
)
|
||||
current_rows = list(res.all())
|
||||
except Exception as exc:
|
||||
logger.debug_event(
|
||||
"Skipped live chokepoint vessel query",
|
||||
event="maritime.chokepoint_query_skipped",
|
||||
context={"error_type": type(exc).__name__},
|
||||
)
|
||||
|
||||
# 7-day rolling daily baseline from vessel_position history
|
||||
baseline_days: dict[str, dict[str, set[str]]] = {cp["id"]: {} for cp in chokepoints}
|
||||
if db is not None and hasattr(db, "execute"):
|
||||
try:
|
||||
b_start = current_now - timedelta(days=7)
|
||||
b_end = current_now - timedelta(hours=1)
|
||||
pos_res = await db.execute(
|
||||
select(
|
||||
VesselPosition.mmsi,
|
||||
VesselPosition.lat,
|
||||
VesselPosition.lon,
|
||||
VesselPosition.received_at,
|
||||
)
|
||||
.where(VesselPosition.received_at >= b_start, VesselPosition.received_at < b_end)
|
||||
.limit(20000)
|
||||
)
|
||||
for mmsi, lat, lon, r_at in pos_res.all():
|
||||
if lat is None or lon is None or r_at is None:
|
||||
continue
|
||||
cp = find_chokepoint_for_point(float(lat), float(lon))
|
||||
if cp is None:
|
||||
continue
|
||||
day_key = (r_at.date().isoformat() if hasattr(r_at, "date") else str(r_at)[:10])
|
||||
baseline_days[cp["id"]].setdefault(day_key, set()).add(str(mmsi))
|
||||
except Exception as exc:
|
||||
logger.debug_event(
|
||||
"Skipped 7d rolling baseline query",
|
||||
event="maritime.baseline_query_skipped",
|
||||
context={"error_type": type(exc).__name__},
|
||||
)
|
||||
|
||||
summary: list[dict[str, Any]] = []
|
||||
for cp in chokepoints:
|
||||
poly = cp.get("polygon") or []
|
||||
v_count = 0
|
||||
w_count = 0
|
||||
c_count = 0
|
||||
for lat, lon, vtype, vname, csign in current_rows:
|
||||
if not point_in_polygon(lat, lon, poly):
|
||||
continue
|
||||
v_count += 1
|
||||
m_role, _ = classify_military_vessel(vessel_type=vtype, name=vname, callsign=csign)
|
||||
if m_role is not None:
|
||||
w_count += 1
|
||||
is_cable, _ = is_cable_repair_vessel(vessel_type=vtype, name=vname)
|
||||
if is_cable:
|
||||
c_count += 1
|
||||
|
||||
day_sets = baseline_days.get(cp["id"]) or {}
|
||||
if day_sets:
|
||||
baseline_avg = round(sum(len(s) for s in day_sets.values()) / len(day_sets), 2)
|
||||
delta = round(v_count - baseline_avg, 2)
|
||||
delta_pct = round(((v_count - baseline_avg) / baseline_avg) * 100.0, 1) if baseline_avg > 0 else None
|
||||
else:
|
||||
baseline_avg = None
|
||||
delta = None
|
||||
delta_pct = None
|
||||
|
||||
summary.append(
|
||||
{
|
||||
"id": cp["id"],
|
||||
"name": cp["name"],
|
||||
"name_en": cp["name_en"],
|
||||
"category": cp.get("category"),
|
||||
"center": cp.get("center"),
|
||||
"polygon": poly,
|
||||
"vessel_count": v_count,
|
||||
"warship_count": w_count,
|
||||
"cable_ship_count": c_count,
|
||||
"baseline_7d_avg": baseline_avg,
|
||||
"delta_vs_7d": delta,
|
||||
"delta_pct": delta_pct,
|
||||
"source_citation": cp.get("source_citation"),
|
||||
}
|
||||
)
|
||||
return summary
|
||||
@@ -0,0 +1,389 @@
|
||||
"""NGA MSI maritime navigational warnings parser and submarine cable advisory matcher."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import desc, select
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.logging import get_logger
|
||||
from app.models.maritime_advisory import CableAdvisory
|
||||
|
||||
logger = get_logger(__name__, service="nga_advisories")
|
||||
|
||||
CABLE_WARNING_KEYWORDS = (
|
||||
"submarine cable",
|
||||
"cable repair",
|
||||
"cable ship",
|
||||
"cable laying",
|
||||
"cable-laying",
|
||||
"undersea cable",
|
||||
"fiber optic cable",
|
||||
"subsea cable",
|
||||
"cable operations",
|
||||
"cable ",
|
||||
"cables",
|
||||
)
|
||||
|
||||
# Matches:
|
||||
# - DMS/DM with hyphen or symbols: 24-12.5N 121-45.2E, 24°12'30"N 121°45'15"E, 24-12-30N 121-45-15E
|
||||
# - Space-separated DM: 24 12.5N 121 45.2E
|
||||
# - Signed or hemisphere decimal: 24.208N 121.750E
|
||||
_DMS_DM_PAIR_RE = re.compile(
|
||||
r"(?P<lat_d>\d{1,2})[-°\s]+(?P<lat_m>\d{1,2}(?:\.\d+)?)(?:[-'′\s]+(?P<lat_s>\d{1,2}(?:\.\d+)?))?[\"″]?\s*(?P<lat_h>[NS])\b"
|
||||
r"[\s,;:/]+"
|
||||
r"(?P<lon_d>\d{1,3})[-°\s]+(?P<lon_m>\d{1,2}(?:\.\d+)?)(?:[-'′\s]+(?P<lon_s>\d{1,2}(?:\.\d+)?))?[\"″]?\s*(?P<lon_h>[EW])\b",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
_DD_HEMI_PAIR_RE = re.compile(
|
||||
r"(?P<lat>\d{1,2}\.\d+)\s*°?\s*(?P<lat_h>[NS])\b[\s,;:/]+(?P<lon>\d{1,3}\.\d+)\s*°?\s*(?P<lon_h>[EW])\b",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
_DD_SIGNED_PAIR_RE = re.compile(
|
||||
r"(?P<lat>-?\d{1,2}\.\d{2,})\s*,\s*(?P<lon>-?\d{1,3}\.\d{2,})"
|
||||
)
|
||||
|
||||
|
||||
def is_cable_related_warning(text: str) -> bool:
|
||||
"""Return True if a navigation warning relates to submarine cables or repair ops."""
|
||||
lower = str(text or "").lower()
|
||||
if not lower:
|
||||
return False
|
||||
return any(kw in lower for kw in CABLE_WARNING_KEYWORDS)
|
||||
|
||||
|
||||
def _dms_to_decimal(deg: float, minutes: float, seconds: float, hemi: str) -> float | None:
|
||||
if minutes < 0 or minutes >= 60 or seconds < 0 or seconds >= 60:
|
||||
return None
|
||||
val = deg + minutes / 60.0 + seconds / 3600.0
|
||||
if hemi.upper() in {"S", "W"}:
|
||||
val = -val
|
||||
return round(val, 6)
|
||||
|
||||
|
||||
def extract_warning_coordinates(
|
||||
text: str,
|
||||
) -> tuple[float | None, float | None, list[list[float]] | None]:
|
||||
"""Extract centroid `(lat, lon)` and optional polygon `[[lat, lon], ...]` from NGA warning text."""
|
||||
src = str(text or "")
|
||||
points: list[list[float]] = []
|
||||
|
||||
for m in _DMS_DM_PAIR_RE.finditer(src):
|
||||
lat = _dms_to_decimal(
|
||||
float(m.group("lat_d")),
|
||||
float(m.group("lat_m")),
|
||||
float(m.group("lat_s") or 0.0),
|
||||
m.group("lat_h"),
|
||||
)
|
||||
lon = _dms_to_decimal(
|
||||
float(m.group("lon_d")),
|
||||
float(m.group("lon_m")),
|
||||
float(m.group("lon_s") or 0.0),
|
||||
m.group("lon_h"),
|
||||
)
|
||||
if lat is not None and lon is not None and -90 <= lat <= 90 and -180 <= lon <= 180:
|
||||
points.append([lat, lon])
|
||||
|
||||
if not points:
|
||||
for m in _DD_HEMI_PAIR_RE.finditer(src):
|
||||
lat = float(m.group("lat")) * (-1.0 if m.group("lat_h").upper() == "S" else 1.0)
|
||||
lon = float(m.group("lon")) * (-1.0 if m.group("lon_h").upper() == "W" else 1.0)
|
||||
if -90 <= lat <= 90 and -180 <= lon <= 180:
|
||||
points.append([round(lat, 6), round(lon, 6)])
|
||||
|
||||
if not points:
|
||||
for m in _DD_SIGNED_PAIR_RE.finditer(src):
|
||||
lat = float(m.group("lat"))
|
||||
lon = float(m.group("lon"))
|
||||
if -90 <= lat <= 90 and -180 <= lon <= 180:
|
||||
points.append([round(lat, 6), round(lon, 6)])
|
||||
|
||||
if not points:
|
||||
return None, None, None
|
||||
|
||||
centroid_lat = round(sum(pt[0] for pt in points) / len(points), 6)
|
||||
centroid_lon = round(sum(pt[1] for pt in points) / len(points), 6)
|
||||
polygon = points if len(points) >= 3 else None
|
||||
return centroid_lat, centroid_lon, polygon
|
||||
|
||||
|
||||
def haversine_km(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
|
||||
"""Great-circle distance in kilometers between two WGS-84 coordinates."""
|
||||
r = 6371.0088
|
||||
p1 = math.radians(lat1)
|
||||
p2 = math.radians(lat2)
|
||||
dp = p2 - p1
|
||||
dl = math.radians(lon2 - lon1)
|
||||
a = math.sin(dp / 2.0) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2.0) ** 2
|
||||
return r * 2.0 * math.atan2(math.sqrt(a), math.sqrt(max(0.0, 1.0 - a)))
|
||||
|
||||
|
||||
def _iter_cable_vertices(geometry: dict[str, Any]) -> list[tuple[float, float]]:
|
||||
if not isinstance(geometry, dict):
|
||||
return []
|
||||
gtype = str(geometry.get("type") or "")
|
||||
coords = geometry.get("coordinates")
|
||||
verts: list[tuple[float, float]] = []
|
||||
if gtype == "LineString" and isinstance(coords, list):
|
||||
for pt in coords:
|
||||
if isinstance(pt, (list, tuple)) and len(pt) >= 2:
|
||||
verts.append((float(pt[1]), float(pt[0])))
|
||||
elif gtype == "MultiLineString" and isinstance(coords, list):
|
||||
for line in coords:
|
||||
if isinstance(line, list):
|
||||
for pt in line:
|
||||
if isinstance(pt, (list, tuple)) and len(pt) >= 2:
|
||||
verts.append((float(pt[1]), float(pt[0])))
|
||||
return verts
|
||||
|
||||
|
||||
def get_cable_match_threshold_km() -> float:
|
||||
raw = str(os.getenv("NGA_CABLE_MATCH_THRESHOLD_KM", "50.0")).strip()
|
||||
try:
|
||||
return max(1.0, min(float(raw), 500.0))
|
||||
except ValueError:
|
||||
return 50.0
|
||||
|
||||
|
||||
def match_warning_to_cables(
|
||||
lat: float | None,
|
||||
lon: float | None,
|
||||
polygon: list[list[float]] | None,
|
||||
cable_features: list[dict[str, Any]],
|
||||
*,
|
||||
threshold_km: float | None = None,
|
||||
) -> tuple[list[str], str]:
|
||||
"""Match an advisory point/polygon against submarine cable GeoJSON features within `threshold_km`."""
|
||||
query_pts: list[tuple[float, float]] = []
|
||||
if polygon:
|
||||
for pt in polygon:
|
||||
if isinstance(pt, (list, tuple)) and len(pt) >= 2:
|
||||
query_pts.append((float(pt[0]), float(pt[1])))
|
||||
if lat is not None and lon is not None:
|
||||
query_pts.append((float(lat), float(lon)))
|
||||
if not query_pts or not cable_features:
|
||||
return [], "none"
|
||||
|
||||
limit_km = float(threshold_km) if threshold_km is not None else get_cable_match_threshold_km()
|
||||
matched: list[tuple[float, str]] = []
|
||||
seen_ids: set[str] = set()
|
||||
|
||||
for feat in cable_features:
|
||||
props = feat.get("properties") or {}
|
||||
cid = str(
|
||||
props.get("cable_id")
|
||||
or props.get("id")
|
||||
or props.get("Name")
|
||||
or props.get("name")
|
||||
or ""
|
||||
).strip()
|
||||
if not cid or cid in seen_ids:
|
||||
continue
|
||||
verts = _iter_cable_vertices(feat.get("geometry") or {})
|
||||
if not verts:
|
||||
continue
|
||||
best_dist = min(haversine_km(qlat, qlon, vlat, vlon) for qlat, qlon in query_pts for vlat, vlon in verts)
|
||||
if best_dist <= limit_km:
|
||||
seen_ids.add(cid)
|
||||
matched.append((best_dist, cid))
|
||||
|
||||
matched.sort(key=lambda pair: pair[0])
|
||||
method = f"haversine_{int(round(limit_km))}km"
|
||||
return [cid for _, cid in matched], method
|
||||
|
||||
|
||||
def _coerce_utc(val: Any) -> datetime | None:
|
||||
if isinstance(val, datetime):
|
||||
return val.replace(tzinfo=UTC) if val.tzinfo is None else val.astimezone(UTC)
|
||||
if isinstance(val, str) and val.strip():
|
||||
try:
|
||||
parsed = datetime.fromisoformat(val.strip().replace("Z", "+00:00"))
|
||||
return parsed.replace(tzinfo=UTC) if parsed.tzinfo is None else parsed.astimezone(UTC)
|
||||
except ValueError:
|
||||
pass
|
||||
for fmt in ("%d%H%MZ %b %y", "%Y-%m-%d %H:%M:%S", "%Y-%m-%d"):
|
||||
try:
|
||||
return datetime.strptime(val.strip().upper(), fmt).replace(tzinfo=UTC)
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def parse_nga_broadcast_warnings(
|
||||
payload: dict[str, Any] | list[dict[str, Any]],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Parse NGA MSI broadcast-warn JSON output keeping cable-related navigational warnings."""
|
||||
if isinstance(payload, list):
|
||||
raw_list = payload
|
||||
elif isinstance(payload, dict):
|
||||
raw_list = (
|
||||
payload.get("broadcast-warn")
|
||||
or payload.get("broadcastWarn")
|
||||
or payload.get("warnings")
|
||||
or payload.get("items")
|
||||
or []
|
||||
)
|
||||
else:
|
||||
return []
|
||||
|
||||
parsed: list[dict[str, Any]] = []
|
||||
for item in raw_list:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
text = str(item.get("text") or item.get("msgText") or item.get("message") or "").strip()
|
||||
if not is_cable_related_warning(text):
|
||||
continue
|
||||
nav_area = str(item.get("navArea") or item.get("nav_area") or "").strip()
|
||||
msg_year = str(item.get("msgYear") or "").strip()
|
||||
msg_num = str(item.get("msgNumber") or item.get("number") or "").strip()
|
||||
warning_id = str(
|
||||
item.get("source_warning_id")
|
||||
or item.get("msgId")
|
||||
or (f"NGA-{nav_area}-{msg_year}-{msg_num}" if (nav_area or msg_num) else "")
|
||||
).strip()
|
||||
if not warning_id:
|
||||
warning_id = f"NGA-TXT-{abs(hash(text))}"
|
||||
lat, lon, polygon = extract_warning_coordinates(text)
|
||||
status_str = str(item.get("status") or "A").strip().upper()
|
||||
cancelled_at = _coerce_utc(item.get("cancelDate"))
|
||||
if status_str in {"C", "CANCELLED"} and cancelled_at is None:
|
||||
cancelled_at = datetime.now(UTC)
|
||||
parsed.append(
|
||||
{
|
||||
"source_warning_id": warning_id[:120],
|
||||
"text": text,
|
||||
"lat": lat,
|
||||
"lon": lon,
|
||||
"polygon": polygon,
|
||||
"issued_at": _coerce_utc(item.get("issueDate") or item.get("issued_at")),
|
||||
"cancelled_at": cancelled_at,
|
||||
}
|
||||
)
|
||||
return parsed
|
||||
|
||||
|
||||
async def upsert_cable_advisories(
|
||||
db: AsyncSession,
|
||||
warnings: list[dict[str, Any]],
|
||||
*,
|
||||
cable_features: list[dict[str, Any]] | None = None,
|
||||
threshold_km: float | None = None,
|
||||
) -> int:
|
||||
"""Persist NGA cable advisories and link them to cables within distance threshold."""
|
||||
if not warnings:
|
||||
return 0
|
||||
|
||||
if cable_features is None:
|
||||
cable_features = []
|
||||
try:
|
||||
from app.api.v1.visualization import _build_cables_geojson
|
||||
|
||||
fc = await _build_cables_geojson(db)
|
||||
cable_features = list(fc.get("features") or [])
|
||||
except Exception as exc:
|
||||
logger.debug_event(
|
||||
"Skipped cable GeoJSON load during NGA matching",
|
||||
event="nga_advisories.cable_load_skipped",
|
||||
context={"error_type": type(exc).__name__},
|
||||
)
|
||||
|
||||
now = datetime.now(UTC)
|
||||
dialect = getattr(getattr(db.get_bind(), "dialect", None), "name", "sqlite")
|
||||
insert_fn = pg_insert if dialect == "postgresql" else sqlite_insert
|
||||
|
||||
rows = []
|
||||
for warn in warnings:
|
||||
matched_ids, method = match_warning_to_cables(
|
||||
warn.get("lat"),
|
||||
warn.get("lon"),
|
||||
warn.get("polygon"),
|
||||
cable_features,
|
||||
threshold_km=threshold_km,
|
||||
)
|
||||
rows.append(
|
||||
{
|
||||
"source_warning_id": str(warn["source_warning_id"])[:120],
|
||||
"text": str(warn["text"]),
|
||||
"lat": warn.get("lat"),
|
||||
"lon": warn.get("lon"),
|
||||
"polygon": warn.get("polygon"),
|
||||
"issued_at": warn.get("issued_at"),
|
||||
"cancelled_at": warn.get("cancelled_at"),
|
||||
"matched_cable_ids": matched_ids,
|
||||
"match_method": method,
|
||||
"ingested_at": now,
|
||||
}
|
||||
)
|
||||
|
||||
stmt = insert_fn(CableAdvisory).values(rows)
|
||||
stmt = stmt.on_conflict_do_update(
|
||||
index_elements=["source_warning_id"],
|
||||
set_={
|
||||
"text": stmt.excluded.text,
|
||||
"lat": stmt.excluded.lat,
|
||||
"lon": stmt.excluded.lon,
|
||||
"polygon": stmt.excluded.polygon,
|
||||
"issued_at": stmt.excluded.issued_at,
|
||||
"cancelled_at": stmt.excluded.cancelled_at,
|
||||
"matched_cable_ids": stmt.excluded.matched_cable_ids,
|
||||
"match_method": stmt.excluded.match_method,
|
||||
"ingested_at": stmt.excluded.ingested_at,
|
||||
},
|
||||
)
|
||||
await db.execute(stmt)
|
||||
await db.commit()
|
||||
return len(rows)
|
||||
|
||||
|
||||
async def list_active_cable_advisories(db: AsyncSession, limit: int = 200) -> list[dict[str, Any]]:
|
||||
"""Return uncancelled cable advisories ordered newest first."""
|
||||
if not hasattr(db, "execute"):
|
||||
return []
|
||||
try:
|
||||
rows = list(
|
||||
(
|
||||
await db.execute(
|
||||
select(CableAdvisory)
|
||||
.where(CableAdvisory.cancelled_at.is_(None))
|
||||
.order_by(desc(CableAdvisory.issued_at), desc(CableAdvisory.id))
|
||||
.limit(limit)
|
||||
)
|
||||
)
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
return [
|
||||
{
|
||||
**row.to_dict(),
|
||||
"source": "NGA MSI (nga_navigation_warnings)",
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
except Exception as exc:
|
||||
logger.debug_event(
|
||||
"Skipped cable advisory query on unavailable schema",
|
||||
event="nga_advisories.query_skipped",
|
||||
context={"error_type": type(exc).__name__},
|
||||
)
|
||||
return []
|
||||
|
||||
|
||||
async def map_advisories_by_cable_id(db: AsyncSession) -> dict[str, list[dict[str, Any]]]:
|
||||
"""Group active advisories by matched cable ID."""
|
||||
advisories = await list_active_cable_advisories(db)
|
||||
mapping: dict[str, list[dict[str, Any]]] = {}
|
||||
for adv in advisories:
|
||||
for cid in adv.get("matched_cable_ids") or []:
|
||||
key = str(cid).strip()
|
||||
if key:
|
||||
mapping.setdefault(key, []).append(adv)
|
||||
return mapping
|
||||
@@ -0,0 +1,297 @@
|
||||
"""Private CSV/JSON/REST upload-to-globe ingestion reusing mapping DSL (§4.4)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import csv
|
||||
from datetime import UTC, datetime
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.logging import get_logger
|
||||
from app.models.earth_interactable import EarthInteractable
|
||||
from app.services.datasource_mapping import build_heuristic_mapping, execute_mapping
|
||||
|
||||
logger = get_logger(__name__, service="private_data_ingest")
|
||||
|
||||
|
||||
def get_private_upload_limits() -> tuple[int, int]:
|
||||
"""Return `(max_bytes, max_rows)` (defaults: 20 MB / 100,000 rows)."""
|
||||
max_mb = int(os.getenv("PRIVATE_UPLOAD_MAX_MB", "20") or "20")
|
||||
max_rows = int(os.getenv("PRIVATE_UPLOAD_MAX_ROWS", "100000") or "100000")
|
||||
return max(1024, max_mb * 1024 * 1024), max(1, max_rows)
|
||||
|
||||
|
||||
def parse_tabular_or_json_bytes(
|
||||
raw_bytes: bytes,
|
||||
*,
|
||||
fmt: str,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Parse CSV or JSON bytes into a list of flat dicts, enforcing size and row caps."""
|
||||
max_bytes, max_rows = get_private_upload_limits()
|
||||
if len(raw_bytes) > max_bytes:
|
||||
raise ValueError(
|
||||
f"文件体积超出上限 ({len(raw_bytes)} bytes > {max_bytes} bytes),请分批上传"
|
||||
)
|
||||
|
||||
fmt_clean = str(fmt or "json").strip().lower()
|
||||
records: list[dict[str, Any]] = []
|
||||
if fmt_clean == "csv":
|
||||
text_content = raw_bytes.decode("utf-8-sig", errors="replace")
|
||||
reader = csv.DictReader(io.StringIO(text_content))
|
||||
for row in reader:
|
||||
records.append(dict(row))
|
||||
if len(records) > max_rows:
|
||||
raise ValueError(
|
||||
f"数据行数超出上限 ({max_rows} 行),请拆分为多个批次导入"
|
||||
)
|
||||
elif fmt_clean == "json":
|
||||
parsed = json.loads(raw_bytes.decode("utf-8-sig", errors="replace"))
|
||||
if isinstance(parsed, list):
|
||||
items = parsed
|
||||
elif isinstance(parsed, dict):
|
||||
items = (
|
||||
parsed.get("items")
|
||||
or parsed.get("records")
|
||||
or parsed.get("features")
|
||||
or parsed.get("data")
|
||||
or [parsed]
|
||||
)
|
||||
else:
|
||||
raise ValueError("JSON 必须为对象数组或包含 records/items 的对象")
|
||||
if len(items) > max_rows:
|
||||
raise ValueError(f"数据行数超出上限 ({max_rows} 行),请拆分为多个批次导入")
|
||||
records = [dict(it) for it in items if isinstance(it, dict)]
|
||||
else:
|
||||
raise ValueError(f"Unsupported upload format: {fmt}")
|
||||
|
||||
return records
|
||||
|
||||
|
||||
async def fetch_rest_records_for_upload(url: str, *, root_path: str | None = None) -> list[dict[str, Any]]:
|
||||
"""Fetch a JSON REST endpoint into normalized candidate dicts within upload limits."""
|
||||
max_bytes, max_rows = get_private_upload_limits()
|
||||
async with httpx.AsyncClient(timeout=15.0) as client:
|
||||
resp = await client.get(url)
|
||||
resp.raise_for_status()
|
||||
raw = resp.content
|
||||
if len(raw) > max_bytes:
|
||||
raise ValueError(f"REST 响应体超出上限 ({max_bytes} bytes),请分页读取")
|
||||
payload = json.loads(raw.decode("utf-8-sig", errors="replace"))
|
||||
if root_path and isinstance(payload, dict):
|
||||
for seg in root_path.split("."):
|
||||
if isinstance(payload, dict):
|
||||
payload = payload.get(seg)
|
||||
if isinstance(payload, list):
|
||||
items = payload
|
||||
elif isinstance(payload, dict):
|
||||
items = payload.get("items") or payload.get("records") or payload.get("data") or [payload]
|
||||
else:
|
||||
items = []
|
||||
if len(items) > max_rows:
|
||||
raise ValueError(f"REST 数据行数超出上限 ({max_rows} 行),请分页读取")
|
||||
return [dict(it) for it in items if isinstance(it, dict)]
|
||||
|
||||
|
||||
_ALIAS_FIELD_MAP = {
|
||||
"latitude": ("lat", "float"),
|
||||
"lat": ("lat", "float"),
|
||||
"longitude": ("lon", "float"),
|
||||
"lon": ("lon", "float"),
|
||||
"name": ("name", "string"),
|
||||
"label": ("name", "string"),
|
||||
"id": ("source_id", "string"),
|
||||
"source_id": ("source_id", "string"),
|
||||
"kind": ("type", "string"),
|
||||
"type": ("type", "string"),
|
||||
"category": ("type", "string"),
|
||||
"observed_at": ("observed_at", "string"),
|
||||
}
|
||||
|
||||
|
||||
def _normalize_geo_mapping_json(custom_mapping: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Convert flat field_mapping or full DSL dict into `execute_mapping(..., 'geo_points')` format."""
|
||||
if isinstance(custom_mapping.get("fields"), dict) and custom_mapping["fields"]:
|
||||
return custom_mapping
|
||||
raw_fields = (
|
||||
custom_mapping.get("field_mapping")
|
||||
if isinstance(custom_mapping.get("field_mapping"), dict)
|
||||
else custom_mapping
|
||||
)
|
||||
fields: dict[str, Any] = {}
|
||||
for src_key, spec in raw_fields.items():
|
||||
if src_key in ("source", "items_path", "meta"):
|
||||
continue
|
||||
target_name, default_type = _ALIAS_FIELD_MAP.get(str(src_key), (str(src_key), "string"))
|
||||
if isinstance(spec, dict) and spec.get("path"):
|
||||
fields[target_name] = dict(spec)
|
||||
elif isinstance(spec, str) and spec.strip():
|
||||
col = spec.strip()
|
||||
path = col if col.startswith("$") else f"$.{col}"
|
||||
fields[target_name] = {"path": path, "type": default_type}
|
||||
return {"source": {"items_path": "$"}, "fields": fields}
|
||||
|
||||
|
||||
def preview_private_mapping(records: list[dict[str, Any]], *, custom_mapping: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
"""Generate heuristic field mapping & preview mapped globe coordinates."""
|
||||
sample = records[:5]
|
||||
suggested = build_heuristic_mapping(sample, target_schema_key="geo_points")
|
||||
if custom_mapping:
|
||||
mapping_json = _normalize_geo_mapping_json(custom_mapping)
|
||||
else:
|
||||
mapping_json = suggested
|
||||
fields = dict(mapping_json.get("fields") or {})
|
||||
cols = list(sample[0].keys()) if sample else []
|
||||
for target_name, default_type, candidates in (
|
||||
("source_id", "string", ("source_id", "id", "uid", "code", "object_id", "asset_id")),
|
||||
("name", "string", ("name", "title", "label", "facility")),
|
||||
("type", "string", ("type", "kind", "category")),
|
||||
("lat", "float", ("lat", "latitude", "y")),
|
||||
("lon", "float", ("lon", "lng", "longitude", "x")),
|
||||
):
|
||||
existing = fields.get(target_name)
|
||||
existing_col = (
|
||||
existing.get("path", "").removeprefix("$.")
|
||||
if isinstance(existing, dict)
|
||||
else ""
|
||||
)
|
||||
if not existing_col or existing_col not in cols:
|
||||
for col in cols:
|
||||
if col.lower() in candidates:
|
||||
fields[target_name] = {"path": f"$.{col}", "type": default_type}
|
||||
break
|
||||
mapping_json = {"source": mapping_json.get("source") or {"items_path": "$"}, "fields": fields}
|
||||
preview_items = (
|
||||
execute_mapping(sample, mapping_json, "geo_points")
|
||||
if mapping_json.get("fields")
|
||||
else {"records": sample, "errors": []}
|
||||
)
|
||||
columns = list(sample[0].keys()) if sample else []
|
||||
flat_mapping = {
|
||||
k: (v.get("path", "").removeprefix("$.") if isinstance(v, dict) else v)
|
||||
for k, v in (mapping_json.get("fields") or {}).items()
|
||||
}
|
||||
return {
|
||||
"total_records": len(records),
|
||||
"columns": columns,
|
||||
"field_mapping": flat_mapping,
|
||||
"mapping_json": mapping_json,
|
||||
"preview": preview_items.get("records") or sample,
|
||||
"errors": preview_items.get("errors") or [],
|
||||
}
|
||||
|
||||
|
||||
async def commit_private_records_to_globe(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
records: list[dict[str, Any]],
|
||||
field_mapping: dict[str, Any],
|
||||
default_kind: str = "private_asset",
|
||||
layer_name: str = "interactables",
|
||||
source_label: str = "private_upload",
|
||||
) -> dict[str, Any]:
|
||||
"""Map records via DSL and upsert into `earth_interactables` (`interactable:{id}`)."""
|
||||
mapping_json = _normalize_geo_mapping_json(field_mapping or {})
|
||||
mapped_res = (
|
||||
execute_mapping(records, mapping_json, "geo_points")
|
||||
if mapping_json.get("fields")
|
||||
else {"records": records, "errors": []}
|
||||
)
|
||||
mapped_rows = mapped_res.get("records") or []
|
||||
dialect = getattr(getattr(db.get_bind(), "dialect", None), "name", "")
|
||||
now = datetime.now(UTC)
|
||||
upserted = 0
|
||||
skipped = 0
|
||||
created_ids: list[str] = []
|
||||
|
||||
for idx, row in enumerate(mapped_rows):
|
||||
raw_src = records[idx] if idx < len(records) else {}
|
||||
lat_val = row.get("lat") if row.get("lat") is not None else row.get("latitude")
|
||||
lon_val = row.get("lon") if row.get("lon") is not None else row.get("longitude")
|
||||
try:
|
||||
lat = float(lat_val)
|
||||
lon = float(lon_val)
|
||||
except (TypeError, ValueError):
|
||||
skipped += 1
|
||||
continue
|
||||
if not (-90 <= lat <= 90 and -180 <= lon <= 180):
|
||||
skipped += 1
|
||||
continue
|
||||
|
||||
obj_id = str(row.get("source_id") or row.get("id") or raw_src.get("id") or f"{default_kind}-{idx+1}").strip()[:160]
|
||||
label = str(row.get("name") or row.get("label") or obj_id).strip()[:255]
|
||||
kind = str(row.get("type") or row.get("kind") or row.get("category") or default_kind).strip()[:80]
|
||||
props = {
|
||||
**raw_src,
|
||||
"source": source_label,
|
||||
"observed_at": row.get("observed_at") or raw_src.get("observed_at") or now.isoformat(),
|
||||
"category": row.get("category") or kind,
|
||||
}
|
||||
values = {
|
||||
"id": obj_id,
|
||||
"layer": layer_name,
|
||||
"kind": kind,
|
||||
"label": label,
|
||||
"description": str(row.get("description") or raw_src.get("description") or ""),
|
||||
"latitude": lat,
|
||||
"longitude": lon,
|
||||
"altitude": float(row["altitude"]) if row.get("altitude") is not None else None,
|
||||
"revision": 1,
|
||||
"properties": props,
|
||||
"is_deleted": False,
|
||||
}
|
||||
|
||||
if dialect == "postgresql":
|
||||
stmt = pg_insert(EarthInteractable).values(**values)
|
||||
stmt = stmt.on_conflict_do_update(
|
||||
index_elements=["id"],
|
||||
set_={
|
||||
"layer": stmt.excluded.layer,
|
||||
"kind": stmt.excluded.kind,
|
||||
"label": stmt.excluded.label,
|
||||
"description": stmt.excluded.description,
|
||||
"latitude": stmt.excluded.latitude,
|
||||
"longitude": stmt.excluded.longitude,
|
||||
"altitude": stmt.excluded.altitude,
|
||||
"properties": stmt.excluded.properties,
|
||||
"is_deleted": False,
|
||||
"deleted_at": None,
|
||||
"updated_at": now,
|
||||
},
|
||||
)
|
||||
await db.execute(stmt)
|
||||
else:
|
||||
stmt = sqlite_insert(EarthInteractable).values(**values)
|
||||
stmt = stmt.on_conflict_do_update(
|
||||
index_elements=["id"],
|
||||
set_={
|
||||
"layer": stmt.excluded.layer,
|
||||
"kind": stmt.excluded.kind,
|
||||
"label": stmt.excluded.label,
|
||||
"description": stmt.excluded.description,
|
||||
"latitude": stmt.excluded.latitude,
|
||||
"longitude": stmt.excluded.longitude,
|
||||
"altitude": stmt.excluded.altitude,
|
||||
"properties": stmt.excluded.properties,
|
||||
"is_deleted": False,
|
||||
"deleted_at": None,
|
||||
},
|
||||
)
|
||||
await db.execute(stmt)
|
||||
|
||||
upserted += 1
|
||||
created_ids.append(f"interactable:{obj_id}")
|
||||
|
||||
await db.commit()
|
||||
return {
|
||||
"upserted": upserted,
|
||||
"skipped": skipped,
|
||||
"object_ids": created_ids,
|
||||
"mapping_errors": mapped_res.get("errors") or [],
|
||||
}
|
||||
@@ -62,6 +62,10 @@ STORAGE_RETENTION_JOB_ID = "storage_retention_maintenance"
|
||||
STORAGE_RETENTION_INTERVAL_HOURS = 6
|
||||
COMPUTE_PRESENTATION_RETRY_JOB_ID = "compute_revision_presentation_retry"
|
||||
COMPUTE_PRESENTATION_RETRY_INTERVAL_MINUTES = 5
|
||||
AIRCRAFT_PRUNE_JOB_ID = "aircraft_state_position_prune"
|
||||
AIRCRAFT_PRUNE_INTERVAL_MINUTES = 15
|
||||
FUSION_ANOMALY_JOB_ID = "fusion_geofence_anomaly_scan"
|
||||
FUSION_ANOMALY_INTERVAL_MINUTES = 5
|
||||
SCHEDULER_LEADER_LOCK_KEY = (17001613, 3)
|
||||
_leader_lock_conn: Optional[asyncpg.Connection] = None
|
||||
_pending_earth_news_refreshes: dict[str, dict[str, Any]] = {}
|
||||
@@ -444,26 +448,36 @@ async def run_collector_task(collector_name: str):
|
||||
)
|
||||
|
||||
|
||||
async def cleanup_stale_running_tasks(max_age_hours: int = 2) -> int:
|
||||
async def cleanup_stale_running_tasks(
|
||||
max_age_hours: int = 2,
|
||||
*,
|
||||
include_all_running: bool = False,
|
||||
) -> int:
|
||||
"""Mark stale running tasks as failed after restarts or collector hangs."""
|
||||
cutoff = datetime.now(UTC) - timedelta(hours=max_age_hours)
|
||||
|
||||
async with async_session_factory() as db:
|
||||
result = await db.execute(
|
||||
select(CollectionTask).where(
|
||||
CollectionTask.status == JobStatus.RUNNING.value,
|
||||
conditions = [CollectionTask.status == JobStatus.RUNNING.value]
|
||||
if not include_all_running:
|
||||
conditions.extend(
|
||||
[
|
||||
CollectionTask.started_at.is_not(None),
|
||||
CollectionTask.started_at < cutoff,
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
async with async_session_factory() as db:
|
||||
result = await db.execute(select(CollectionTask).where(*conditions))
|
||||
stale_tasks = result.scalars().all()
|
||||
|
||||
cleanup_error = (
|
||||
"Marked failed automatically after backend restart"
|
||||
if include_all_running
|
||||
else "Marked failed automatically after stale running task cleanup"
|
||||
)
|
||||
for task in stale_tasks:
|
||||
task.status = JobStatus.FAILED.value
|
||||
task.phase = "failed"
|
||||
task.completed_at = datetime.now(UTC)
|
||||
existing_error = (task.error_message or "").strip()
|
||||
cleanup_error = "Marked failed automatically after stale running task cleanup"
|
||||
task.error_message = (
|
||||
f"{existing_error}\n{cleanup_error}".strip() if existing_error else cleanup_error
|
||||
)
|
||||
@@ -473,7 +487,10 @@ async def cleanup_stale_running_tasks(max_age_hours: int = 2) -> int:
|
||||
logger.warning_event(
|
||||
"Cleaned up stale running collection tasks",
|
||||
event="collector.cleanup.stale_tasks_cleaned",
|
||||
context={"count": len(stale_tasks)},
|
||||
context={
|
||||
"count": len(stale_tasks),
|
||||
"include_all_running": include_all_running,
|
||||
},
|
||||
)
|
||||
|
||||
return len(stale_tasks)
|
||||
@@ -550,6 +567,42 @@ async def run_compute_presentation_retry_job() -> None:
|
||||
)
|
||||
|
||||
|
||||
async def run_aircraft_prune_job() -> None:
|
||||
"""Periodically prune expired aircraft_current_state (>15m) and 24h aircraft_position history."""
|
||||
from app.services.aircraft_aggregation import prune_aircraft_tables
|
||||
|
||||
async with async_session_factory() as db:
|
||||
try:
|
||||
await prune_aircraft_tables(db)
|
||||
await db.commit()
|
||||
except Exception as exc:
|
||||
await db.rollback()
|
||||
logger.warning_event(
|
||||
"Scheduled aircraft prune job failed",
|
||||
event="aircraft.prune.failed",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
|
||||
|
||||
async def run_fusion_anomaly_job() -> None:
|
||||
"""Periodically run geofence deterministic anomaly rules (§3.8) and H3 convergence (§3.9)."""
|
||||
from app.services.fusion.anomaly_engine import run_anomaly_cycle
|
||||
from app.services.fusion.convergence import run_convergence_cycle
|
||||
|
||||
async with async_session_factory() as db:
|
||||
try:
|
||||
await run_anomaly_cycle(db)
|
||||
await run_convergence_cycle(db)
|
||||
await db.commit()
|
||||
except Exception as exc:
|
||||
await db.rollback()
|
||||
logger.warning_event(
|
||||
"Scheduled fusion anomaly job failed",
|
||||
event="fusion.anomaly_cycle.failed",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
|
||||
|
||||
def start_scheduler() -> None:
|
||||
"""Start the scheduler."""
|
||||
if not scheduler.running:
|
||||
@@ -584,6 +637,26 @@ def start_scheduler() -> None:
|
||||
coalesce=True,
|
||||
misfire_grace_time=120,
|
||||
)
|
||||
scheduler.add_job(
|
||||
run_aircraft_prune_job,
|
||||
trigger=IntervalTrigger(minutes=AIRCRAFT_PRUNE_INTERVAL_MINUTES),
|
||||
id=AIRCRAFT_PRUNE_JOB_ID,
|
||||
name="Aircraft state and 24h position prune",
|
||||
replace_existing=True,
|
||||
max_instances=1,
|
||||
coalesce=True,
|
||||
misfire_grace_time=120,
|
||||
)
|
||||
scheduler.add_job(
|
||||
run_fusion_anomaly_job,
|
||||
trigger=IntervalTrigger(minutes=FUSION_ANOMALY_INTERVAL_MINUTES),
|
||||
id=FUSION_ANOMALY_JOB_ID,
|
||||
name="Geofence anomaly and convergence cycle",
|
||||
replace_existing=True,
|
||||
max_instances=1,
|
||||
coalesce=True,
|
||||
misfire_grace_time=120,
|
||||
)
|
||||
scheduler.start()
|
||||
logger.info_event("Scheduler started", event="scheduler.started")
|
||||
|
||||
|
||||
@@ -0,0 +1,535 @@
|
||||
"""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,
|
||||
}
|
||||
@@ -302,10 +302,17 @@ async def _run_maintenance_with_session(
|
||||
where_clause=[ObservabilityEvent.occurred_at < history_cutoff],
|
||||
batch_size=batch_size,
|
||||
)
|
||||
from app.services.aircraft_aggregation import prune_aircraft_tables
|
||||
from app.services.earth_clouds import prune_cloud_map_artifacts, read_cloud_map_configuration
|
||||
from app.services.earth_tiles import prune_all_tile_caches
|
||||
from app.services.earth_wind import prune_wind_artifacts, read_wind_configuration
|
||||
|
||||
aircraft_retention_hours = int(policy.get("aircraft_position_retention_hours") or 24)
|
||||
aircraft_pruned = await prune_aircraft_tables(
|
||||
db,
|
||||
position_retention_hours=aircraft_retention_hours,
|
||||
now=ref_now,
|
||||
)
|
||||
cloud_env = await read_cloud_map_configuration(db)
|
||||
max_cloud_frames = int((cloud_env.get("config") or {}).get("max_history_frames") or 24)
|
||||
pruned_cloud_artifacts = prune_cloud_map_artifacts(max_frames=max_cloud_frames)
|
||||
@@ -320,6 +327,8 @@ async def _run_maintenance_with_session(
|
||||
"bgp_observations": deleted_bgp_observations,
|
||||
"ais_raw_observations": deleted_ais_raw,
|
||||
"vessel_positions": deleted_vessel_positions,
|
||||
"aircraft_current_state": aircraft_pruned["current_deleted"],
|
||||
"aircraft_positions": aircraft_pruned["positions_deleted"],
|
||||
"earth_news_items": deleted_news_items,
|
||||
"system_logs": deleted_system_logs,
|
||||
"observability_events": deleted_observability_events,
|
||||
|
||||
@@ -45,6 +45,14 @@ HIGH_VOLUME_SOURCES: dict[str, dict[str, str]] = {
|
||||
"estimated_monthly_growth": "~15 GB / 月",
|
||||
"note": "WebSocket 高频 AIS 报文流,开启历史快照将高频写入 ais_raw_observations",
|
||||
},
|
||||
"adsb_lol_aircraft": {
|
||||
"estimated_monthly_growth": "~8 GB / 月",
|
||||
"note": "每分钟采集军机与紧急航班 ADS-B 状态,建议保持默认 single 模式并由 aircraft_position 24 小时降采样策略保留轨迹",
|
||||
},
|
||||
"opensky_aircraft": {
|
||||
"estimated_monthly_growth": "~18 GB / 月",
|
||||
"note": "每 2 分钟采集全球重点空域状态,开启历史快照会导致快照快速膨胀",
|
||||
},
|
||||
}
|
||||
|
||||
DEFAULT_RECOMMENDED_OVERRIDES: dict[str, SnapshotMode] = {
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
"""Shared AIS vessel type helpers."""
|
||||
"""Shared AIS vessel type, military warship, and cable-repair vessel classification helpers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
VESSEL_TYPE_NAMES = {
|
||||
@@ -10,13 +13,88 @@ VESSEL_TYPE_NAMES = {
|
||||
80: "Tanker",
|
||||
}
|
||||
|
||||
# Cited naval vessel prefixes (NATO / Jane's Fighting Ships / USNI Naval Vessel Register)
|
||||
WARSHIP_PREFIXES = (
|
||||
"USS ",
|
||||
"HMS ",
|
||||
"HMCS ",
|
||||
"HMAS ",
|
||||
"HMNZS ",
|
||||
"INS ",
|
||||
"JS ",
|
||||
"ROKS ",
|
||||
"TCG ",
|
||||
"FS ",
|
||||
"FGS ",
|
||||
"ITS ",
|
||||
"HNLMS ",
|
||||
"SPS ",
|
||||
"SNS ",
|
||||
"USNS ",
|
||||
"RFA ",
|
||||
"USCGC ",
|
||||
"PLA NAVY ",
|
||||
"CNS ",
|
||||
)
|
||||
|
||||
# Cited named warships / naval auxiliaries verified from public open-source registers
|
||||
# Source: USNI Naval Vessel Register / Royal Navy Fleet List / Wikipedia Order of Battle
|
||||
KNOWN_WARSHIP_WHITELIST: dict[str, dict[str, str]] = {
|
||||
"USS GERALD R FORD": {"role": "aircraft_carrier", "source": "USNI Naval Vessel Register"},
|
||||
"USS NIMITZ": {"role": "aircraft_carrier", "source": "USNI Naval Vessel Register"},
|
||||
"USS RONALD REAGAN": {"role": "aircraft_carrier", "source": "USNI Naval Vessel Register"},
|
||||
"USS DWIGHT D EISENHOWER": {"role": "aircraft_carrier", "source": "USNI Naval Vessel Register"},
|
||||
"USS ABRAHAM LINCOLN": {"role": "aircraft_carrier", "source": "USNI Naval Vessel Register"},
|
||||
"USS ARLEIGH BURKE": {"role": "destroyer", "source": "USNI Naval Vessel Register"},
|
||||
"HMS QUEEN ELIZABETH": {"role": "aircraft_carrier", "source": "Royal Navy Fleet Registry"},
|
||||
"HMS PRINCE OF WALES": {"role": "aircraft_carrier", "source": "Royal Navy Fleet Registry"},
|
||||
"HMS DIAMOND": {"role": "destroyer", "source": "Royal Navy Fleet Registry"},
|
||||
"FS CHARLES DE GAULLE": {"role": "aircraft_carrier", "source": "Marine Nationale"},
|
||||
"JS IZUMO": {"role": "helicopter_destroyer", "source": "JMSDF Fleet Register"},
|
||||
"JS KAGA": {"role": "helicopter_destroyer", "source": "JMSDF Fleet Register"},
|
||||
"INS VIKRANT": {"role": "aircraft_carrier", "source": "Indian Navy Fleet Register"},
|
||||
"ITS CAVOUR": {"role": "aircraft_carrier", "source": "Marina Militare"},
|
||||
}
|
||||
|
||||
# Known subsea telecom cable repair / laying ships
|
||||
# Source: ICPC Cable Ship Fleet Registry & SubTel Forum Cable Vessels Directory
|
||||
KNOWN_CABLE_SHIP_WHITELIST: dict[str, str] = {
|
||||
"CS SOVEREIGN": "Global Marine / SubTel Forum Fleet Directory",
|
||||
"CS RESOLUTE": "Orange Marine / ICPC Fleet Registry",
|
||||
"CS RELIANCE": "SubCom / ICPC Fleet Registry",
|
||||
"CS DEPENDABLE": "SubCom / ICPC Fleet Registry",
|
||||
"CS DECISIVE": "SubCom / ICPC Fleet Registry",
|
||||
"CS DURABLE": "SubCom / ICPC Fleet Registry",
|
||||
"CS GLOBAL SENTINEL": "SubCom / ICPC Fleet Registry",
|
||||
"CABLE INNOVATOR": "Global Marine / ICPC Fleet Registry",
|
||||
"WAVE SENTINEL": "Global Marine / ICPC Fleet Registry",
|
||||
"ILE DE BREHAT": "Alcatel Submarine Networks (ASN) Fleet",
|
||||
"ILE DE SEIN": "Alcatel Submarine Networks (ASN) Fleet",
|
||||
"ILE DE BATZ": "Alcatel Submarine Networks (ASN) Fleet",
|
||||
"RENE DESCARTES": "Orange Marine Fleet Registry",
|
||||
"PIERRE DE FERMAT": "Orange Marine Fleet Registry",
|
||||
"SOPHIE GERMAIN": "Orange Marine Fleet Registry",
|
||||
"CS FU HAI": "SBSS / China Telecom Marine Fleet",
|
||||
"CS BOLD MAVERICK": "SBSS Fleet Registry",
|
||||
"KDDI CABLE INFINITY": "Kokusai Cable Ship Co. Fleet",
|
||||
"SUBARU": "NTT World Engineering Marine Fleet",
|
||||
"ASEAN EXPLORER": "ASEAN Cableship Pte Ltd",
|
||||
"ASEAN RESTORER": "ASEAN Cableship Pte Ltd",
|
||||
}
|
||||
|
||||
_PREFIX_RE = re.compile(
|
||||
r"^(?:" + "|".join(re.escape(p.strip()) for p in WARSHIP_PREFIXES) + r")(?:\s+|[-_])",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
def normalize_vessel_type_name(vessel_type: Any) -> str:
|
||||
"""Map AIS numeric vessel type codes to display buckets."""
|
||||
|
||||
try:
|
||||
type_code = int(float(vessel_type))
|
||||
except (TypeError, ValueError):
|
||||
if isinstance(vessel_type, str) and "military" in vessel_type.lower():
|
||||
return "Military"
|
||||
return "Other"
|
||||
if 70 <= type_code <= 79:
|
||||
return "Cargo"
|
||||
@@ -26,6 +104,72 @@ def normalize_vessel_type_name(vessel_type: Any) -> str:
|
||||
return "Passenger"
|
||||
if type_code == 30:
|
||||
return "Fishing"
|
||||
if type_code == 35:
|
||||
if type_code == 35 or 350 <= type_code <= 359:
|
||||
return "Military"
|
||||
return VESSEL_TYPE_NAMES.get(type_code, "Other")
|
||||
|
||||
|
||||
def _clean_name(value: Any) -> str:
|
||||
return re.sub(r"\s+", " ", str(value or "").strip().upper())
|
||||
|
||||
|
||||
def classify_military_vessel(
|
||||
vessel_type: Any = None,
|
||||
name: Any = None,
|
||||
callsign: Any = None,
|
||||
) -> tuple[str | None, str | None]:
|
||||
"""Return `(military_role, match_source)` when a vessel matches AIS military type, naval prefix, or whitelist."""
|
||||
cleaned_name = _clean_name(name)
|
||||
cleaned_call = _clean_name(callsign)
|
||||
|
||||
if cleaned_name in KNOWN_WARSHIP_WHITELIST:
|
||||
meta = KNOWN_WARSHIP_WHITELIST[cleaned_name]
|
||||
return meta["role"], meta["source"]
|
||||
|
||||
try:
|
||||
code = int(float(vessel_type)) if vessel_type not in (None, "") else None
|
||||
except (TypeError, ValueError):
|
||||
code = None
|
||||
if code == 35 or (code is not None and 350 <= code <= 359):
|
||||
if cleaned_name.startswith(("USNS ", "RFA ")):
|
||||
return "naval_auxiliary", "AIS Type 35 + Naval Auxiliary Prefix"
|
||||
if cleaned_name.startswith("USCGC "):
|
||||
return "coast_guard", "AIS Type 35 + Coast Guard Prefix"
|
||||
return "warship", "AIS Vessel Type 35 (Military Ops)"
|
||||
|
||||
for candidate in (cleaned_name, cleaned_call):
|
||||
if candidate and _PREFIX_RE.match(candidate):
|
||||
if candidate.startswith(("USNS ", "RFA ")):
|
||||
return "naval_auxiliary", "Naval Auxiliary Callsign/Name Prefix"
|
||||
if candidate.startswith("USCGC "):
|
||||
return "coast_guard", "Coast Guard Prefix"
|
||||
return "warship", "Naval Vessel Prefix (USS/HMS/HMCS/HMAS/INS/JS/ROKS/TCG)"
|
||||
|
||||
if isinstance(vessel_type, str) and "military" in vessel_type.lower():
|
||||
return "warship", "AIS Reported Military Category"
|
||||
|
||||
return None, None
|
||||
|
||||
|
||||
def is_cable_repair_vessel(
|
||||
vessel_type: Any = None,
|
||||
name: Any = None,
|
||||
) -> tuple[bool, str | None]:
|
||||
"""Return `(is_cable_ship, match_source)` for known or AIS-indicated subsea cable ships."""
|
||||
cleaned = _clean_name(name)
|
||||
if cleaned in KNOWN_CABLE_SHIP_WHITELIST:
|
||||
return True, KNOWN_CABLE_SHIP_WHITELIST[cleaned]
|
||||
if cleaned and any(tok in cleaned for tok in ("CABLE SHIP", "CABLE LAYER", "CABLESHIP", "C/S ")):
|
||||
return True, "Vessel Name Cable-Operations Indicator"
|
||||
if cleaned.startswith("CS ") and any(
|
||||
w in KNOWN_CABLE_SHIP_WHITELIST for w in (cleaned,)
|
||||
):
|
||||
return True, KNOWN_CABLE_SHIP_WHITELIST[cleaned]
|
||||
# AIS special ops / dredging or underwater ops (33 / 34 / 52) combined with CABLE keyword
|
||||
try:
|
||||
code = int(float(vessel_type)) if vessel_type not in (None, "") else None
|
||||
except (TypeError, ValueError):
|
||||
code = None
|
||||
if code in {33, 34, 52} and cleaned and "CABLE" in cleaned:
|
||||
return True, f"AIS Type {code} + Cable Ship Keyword"
|
||||
return False, None
|
||||
@@ -0,0 +1,247 @@
|
||||
"""Tests for §4.5 action request matrix, SSRF/allowlist guards, webhook formats, and AuditLog."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import asynccontextmanager
|
||||
from types import SimpleNamespace
|
||||
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.access_gate import get_current_user, require_admin_user
|
||||
from app.core.enums import UserRole
|
||||
from app.db.migrations import discover_migrations
|
||||
from app.db.session import Base, get_db
|
||||
from app.main import app
|
||||
from app.models.action_request import ActionRequest
|
||||
from app.models.system_log import AuditLog
|
||||
from app.models.system_setting import SystemSetting
|
||||
from app.services.actions import (
|
||||
ActionValidationError,
|
||||
decide_action_request,
|
||||
format_webhook_payload,
|
||||
validate_allowlisted_webhook_url,
|
||||
)
|
||||
|
||||
|
||||
class _AsyncSQLiteSession:
|
||||
def __init__(self, session: Session):
|
||||
self._session = session
|
||||
|
||||
def get_bind(self):
|
||||
return self._session.get_bind()
|
||||
|
||||
def add(self, instance) -> None:
|
||||
self._session.add(instance)
|
||||
|
||||
async def get(self, entity, ident):
|
||||
return self._session.get(entity, ident)
|
||||
|
||||
async def execute(self, statement, params=None):
|
||||
return (
|
||||
self._session.execute(statement, params)
|
||||
if params is not None
|
||||
else self._session.execute(statement)
|
||||
)
|
||||
|
||||
async def flush(self) -> None:
|
||||
self._session.flush()
|
||||
|
||||
async def commit(self) -> None:
|
||||
self._session.commit()
|
||||
|
||||
|
||||
class _AsyncConnShim:
|
||||
def __init__(self, conn):
|
||||
self._conn = conn
|
||||
self.dialect = conn.dialect
|
||||
|
||||
async def execute(self, stmt, params=None):
|
||||
return (
|
||||
self._conn.execute(stmt, params)
|
||||
if params is not None
|
||||
else self._conn.execute(stmt)
|
||||
)
|
||||
|
||||
|
||||
async def _make_sqlite_session():
|
||||
engine = create_engine("sqlite:///:memory:")
|
||||
with engine.begin() as raw_conn:
|
||||
shim = _AsyncConnShim(raw_conn)
|
||||
for step in discover_migrations():
|
||||
if step.version in {"0012", "0013"}:
|
||||
await step.upgrade(shim)
|
||||
Base.metadata.create_all(raw_conn, checkfirst=True)
|
||||
for step in discover_migrations():
|
||||
if step.version == "0013":
|
||||
await step.upgrade(shim)
|
||||
|
||||
@asynccontextmanager
|
||||
async def _factory():
|
||||
with Session(engine) as session:
|
||||
yield _AsyncSQLiteSession(session)
|
||||
|
||||
return engine, _factory
|
||||
|
||||
|
||||
def test_webhook_allowlist_ssrf_and_bot_formats(monkeypatch) -> None:
|
||||
allowlist = ["https://hooks.example.com/planet"]
|
||||
# SSRF private/loopback IP must always be blocked even if allowlisted!
|
||||
with pytest.raises(ActionValidationError):
|
||||
validate_allowlisted_webhook_url("http://127.0.0.1:8080/hook", ["http://127.0.0.1:8080"])
|
||||
with pytest.raises(ActionValidationError):
|
||||
validate_allowlisted_webhook_url("http://169.254.169.254/latest", ["http://169.254.169.254"])
|
||||
# Non-allowlisted external host must be blocked
|
||||
with pytest.raises(ActionValidationError):
|
||||
validate_allowlisted_webhook_url("https://evil.example.org/leak", allowlist)
|
||||
|
||||
# Mock DNS resolution for public allowlisted domain
|
||||
monkeypatch.setattr(
|
||||
"app.services.ai.tool_registry.socket.getaddrinfo",
|
||||
lambda *_a, **_kw: [(2, 1, 6, "", ("93.184.216.34", 443))],
|
||||
)
|
||||
ok_url = validate_allowlisted_webhook_url("https://hooks.example.com/planet/bot1", allowlist)
|
||||
assert ok_url == "https://hooks.example.com/planet/bot1"
|
||||
|
||||
req = ActionRequest(id=9, action_type="notify_webhook", target_object_ids=["cable:apg-1"], requested_by="admin1")
|
||||
assert format_webhook_payload(channel="wecom", title="T", summary="S", request_obj=req)["msgtype"] == "markdown"
|
||||
assert format_webhook_payload(channel="dingtalk", title="T", summary="S", request_obj=req)["markdown"]["title"] == "T"
|
||||
assert format_webhook_payload(channel="feishu", title="T", summary="S", request_obj=req)["msg_type"] == "text"
|
||||
assert format_webhook_payload(channel="generic", title="T", summary="S", request_obj=req)["event"] == "planet.action_request"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_action_approval_matrix_ai_pending_and_audit_log(monkeypatch) -> None:
|
||||
_engine, session_factory = await _make_sqlite_session()
|
||||
actor = {"id": 1, "username": "viewer1", "role": UserRole.VIEWER.value}
|
||||
|
||||
async with session_factory() as db:
|
||||
db.add(
|
||||
SystemSetting(
|
||||
category="actions",
|
||||
payload={"webhook_allowlist": ["https://hooks.example.com/planet"]},
|
||||
)
|
||||
)
|
||||
await db.commit()
|
||||
|
||||
async def _override_db():
|
||||
async with session_factory() as session:
|
||||
yield session
|
||||
|
||||
async def _override_read():
|
||||
return SimpleNamespace(**actor)
|
||||
|
||||
async def _override_admin():
|
||||
return SimpleNamespace(**actor)
|
||||
|
||||
app.dependency_overrides[get_db] = _override_db
|
||||
app.dependency_overrides[get_current_user] = _override_read
|
||||
app.dependency_overrides[require_admin_user] = _override_admin
|
||||
|
||||
try:
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
# 1. Viewer cannot submit
|
||||
r_v = await client.post(
|
||||
"/api/v1/actions",
|
||||
json={"action_type": "add_to_watchlist", "target_object_ids": ["cable:apg-1"]},
|
||||
)
|
||||
assert r_v.status_code == 403
|
||||
|
||||
# 2. Admin can directly execute low-risk action
|
||||
actor.update({"id": 2, "username": "admin1", "role": UserRole.ADMIN.value})
|
||||
r_low = await client.post(
|
||||
"/api/v1/actions",
|
||||
json={"action_type": "add_to_watchlist", "target_object_ids": ["cable:apg-1"]},
|
||||
)
|
||||
assert r_low.status_code == 200
|
||||
assert r_low.json()["status"] == "executed"
|
||||
|
||||
# 3. AI-suggested low-risk stays strictly pending
|
||||
r_ai = await client.post(
|
||||
"/api/v1/actions",
|
||||
json={
|
||||
"action_type": "add_to_watchlist",
|
||||
"target_object_ids": ["cable:apg-1"],
|
||||
"ai_suggested": True,
|
||||
},
|
||||
)
|
||||
assert r_ai.status_code == 200
|
||||
assert r_ai.json()["status"] == "pending"
|
||||
|
||||
# 4. Super_admin submits high-risk webhook -> stays pending
|
||||
actor.update({"id": 3, "username": "super1", "role": UserRole.SUPER_ADMIN.value})
|
||||
r_high = await client.post(
|
||||
"/api/v1/actions",
|
||||
json={
|
||||
"action_type": "notify_webhook",
|
||||
"target_object_ids": ["cable:apg-1"],
|
||||
"params": {
|
||||
"webhook_url": "https://hooks.example.com/planet/alert",
|
||||
"channel": "wecom",
|
||||
"title": "Cable Alert",
|
||||
"summary": "Review requested",
|
||||
},
|
||||
},
|
||||
)
|
||||
assert r_high.status_code == 200
|
||||
high_id = r_high.json()["id"]
|
||||
assert r_high.json()["status"] == "pending"
|
||||
|
||||
# 5. Admin cannot approve high risk (403)
|
||||
actor.update({"id": 2, "username": "admin1", "role": UserRole.ADMIN.value})
|
||||
assert (
|
||||
await client.post(
|
||||
f"/api/v1/actions/{high_id}/approve",
|
||||
json={"decision_reason": "Try approve"},
|
||||
)
|
||||
).status_code == 403
|
||||
|
||||
# 6. Same super1 cannot approve own high-risk request (403)
|
||||
actor.update({"id": 3, "username": "super1", "role": UserRole.SUPER_ADMIN.value})
|
||||
assert (
|
||||
await client.post(
|
||||
f"/api/v1/actions/{high_id}/approve",
|
||||
json={"decision_reason": "Self approval forbidden"},
|
||||
)
|
||||
).status_code == 403
|
||||
|
||||
# 7. Empty reason rejected (422)
|
||||
actor.update({"id": 4, "username": "super2", "role": UserRole.SUPER_ADMIN.value})
|
||||
assert (
|
||||
await client.post(
|
||||
f"/api/v1/actions/{high_id}/approve",
|
||||
json={"decision_reason": " "},
|
||||
)
|
||||
).status_code == 422
|
||||
|
||||
# 8. Distinct super2 approves high risk with reason -> executes allowlisted webhook + writes AuditLog
|
||||
monkeypatch.setattr(
|
||||
"app.services.ai.tool_registry.socket.getaddrinfo",
|
||||
lambda *_a, **_kw: [(2, 1, 6, "", ("93.184.216.34", 443))],
|
||||
)
|
||||
sent_payloads = []
|
||||
|
||||
async def _mock_post(url, body_bytes, headers):
|
||||
sent_payloads.append((url, body_bytes, headers))
|
||||
return {"status_code": 200}
|
||||
|
||||
async with session_factory() as db:
|
||||
req_obj = await db.get(ActionRequest, high_id)
|
||||
done = await decide_action_request(
|
||||
db,
|
||||
req=req_obj,
|
||||
decision="approve",
|
||||
decision_reason="Verified independent evidence",
|
||||
actor_id=4,
|
||||
actor_name="super2",
|
||||
actor_role=UserRole.SUPER_ADMIN.value,
|
||||
http_post_fn=_mock_post,
|
||||
)
|
||||
assert done.status == "executed"
|
||||
assert len(sent_payloads) == 1
|
||||
audits = list((await db.execute(select(AuditLog))).scalars().all())
|
||||
assert any(a.target_id == str(high_id) and a.result == "executed" for a in audits)
|
||||
finally:
|
||||
app.dependency_overrides.clear()
|
||||
@@ -0,0 +1,193 @@
|
||||
"""Phase 2 aircraft columnar snapshot, detail, track, and permission API tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
import pytest
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.db.migrations import discover_migrations
|
||||
from app.db.session import get_db
|
||||
from app.main import app
|
||||
from app.models.aircraft import AircraftCurrentState, AircraftPosition, AircraftStatic
|
||||
|
||||
|
||||
class _AsyncSQLiteSession:
|
||||
def __init__(self, session: Session):
|
||||
self._session = session
|
||||
|
||||
def get_bind(self):
|
||||
return self._session.get_bind()
|
||||
|
||||
def add(self, instance) -> None:
|
||||
self._session.add(instance)
|
||||
|
||||
def add_all(self, instances) -> None:
|
||||
self._session.add_all(instances)
|
||||
|
||||
async def get(self, entity, ident):
|
||||
return self._session.get(entity, ident)
|
||||
|
||||
async def execute(self, statement, params=None):
|
||||
return self._session.execute(statement, params) if params is not None else self._session.execute(statement)
|
||||
|
||||
async def commit(self) -> None:
|
||||
self._session.commit()
|
||||
|
||||
|
||||
class _AsyncConnShim:
|
||||
def __init__(self, conn):
|
||||
self._conn = conn
|
||||
self.dialect = conn.dialect
|
||||
|
||||
async def execute(self, stmt, params=None):
|
||||
return self._conn.execute(stmt, params) if params is not None else self._conn.execute(stmt)
|
||||
|
||||
|
||||
async def _make_sqlite_session():
|
||||
engine = create_engine("sqlite:///:memory:")
|
||||
with engine.begin() as raw_conn:
|
||||
shim = _AsyncConnShim(raw_conn)
|
||||
for step in discover_migrations():
|
||||
if step.version == "0008":
|
||||
await step.upgrade(shim)
|
||||
|
||||
@asynccontextmanager
|
||||
async def _factory():
|
||||
with Session(engine) as session:
|
||||
yield _AsyncSQLiteSession(session)
|
||||
|
||||
return engine, _factory
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_aircraft_snapshot_columnar_empty_filter_and_detail(monkeypatch):
|
||||
engine, factory = await _make_sqlite_session()
|
||||
|
||||
async def _override_db():
|
||||
async with factory() as session:
|
||||
yield session
|
||||
|
||||
app.dependency_overrides[get_db] = _override_db
|
||||
try:
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
# 1) Empty database -> HTTP 200 columnar empty rows
|
||||
resp_empty = await client.get("/api/v1/aircraft/snapshot")
|
||||
assert resp_empty.status_code == 200
|
||||
body = resp_empty.json()
|
||||
assert body["fields"][:5] == ["icao24", "callsign", "lat", "lon", "altitude_m"]
|
||||
assert body["rows"] == []
|
||||
|
||||
now = datetime.now(UTC)
|
||||
async with factory() as db:
|
||||
db.add_all(
|
||||
[
|
||||
AircraftStatic(
|
||||
icao24="ae1234",
|
||||
registration="08-8190",
|
||||
aircraft_type="C17",
|
||||
type_description="Boeing C-17A Globemaster III",
|
||||
operator="USAF AMC",
|
||||
category="military",
|
||||
is_military=True,
|
||||
source="aircraft_registry",
|
||||
),
|
||||
AircraftCurrentState(
|
||||
icao24="ae1234",
|
||||
callsign="RCH401",
|
||||
lat=35.12,
|
||||
lon=139.45,
|
||||
baro_altitude_m=9500.0,
|
||||
ground_speed_ms=230.0,
|
||||
track_deg=88.0,
|
||||
vertical_rate_ms=1.5,
|
||||
squawk="1200",
|
||||
on_ground=False,
|
||||
category="military",
|
||||
is_military=True,
|
||||
is_emergency=False,
|
||||
source="adsb_lol_aircraft",
|
||||
observed_at=now - timedelta(seconds=20),
|
||||
ingested_at=now,
|
||||
),
|
||||
AircraftCurrentState(
|
||||
icao24="4ca777",
|
||||
callsign="RYR777",
|
||||
lat=51.50,
|
||||
lon=-0.12,
|
||||
baro_altitude_m=4200.0,
|
||||
ground_speed_ms=175.0,
|
||||
track_deg=260.0,
|
||||
squawk="7700",
|
||||
on_ground=False,
|
||||
category="emergency",
|
||||
is_military=False,
|
||||
is_emergency=True,
|
||||
emergency_code="7700",
|
||||
source="adsb_lol_aircraft",
|
||||
observed_at=now - timedelta(seconds=10),
|
||||
ingested_at=now,
|
||||
),
|
||||
AircraftPosition(
|
||||
icao24="ae1234",
|
||||
lat=34.9,
|
||||
lon=139.1,
|
||||
altitude_m=9100.0,
|
||||
ground_speed_ms=228.0,
|
||||
track_deg=87.0,
|
||||
observed_at=now - timedelta(minutes=25),
|
||||
),
|
||||
AircraftPosition(
|
||||
icao24="ae1234",
|
||||
lat=35.12,
|
||||
lon=139.45,
|
||||
altitude_m=9500.0,
|
||||
ground_speed_ms=230.0,
|
||||
track_deg=88.0,
|
||||
observed_at=now - timedelta(seconds=20),
|
||||
),
|
||||
]
|
||||
)
|
||||
await db.commit()
|
||||
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
# 2) Filter by bbox & category
|
||||
resp_mil = await client.get(
|
||||
"/api/v1/aircraft/snapshot",
|
||||
params={"bbox": "135,30,145,40", "category": "military"},
|
||||
)
|
||||
assert resp_mil.status_code == 200
|
||||
data_mil = resp_mil.json()
|
||||
assert len(data_mil["rows"]) == 1
|
||||
assert data_mil["rows"][0][0] == "ae1234"
|
||||
assert "adsb.lol" in data_mil["attribution"]
|
||||
|
||||
# 3) Detail endpoint provenance & freshness
|
||||
resp_detail = await client.get("/api/v1/aircraft/ae1234")
|
||||
assert resp_detail.status_code == 200
|
||||
detail = resp_detail.json()
|
||||
assert detail["source"] == "adsb_lol_aircraft"
|
||||
assert detail["is_stale"] is False
|
||||
assert detail["static"]["aircraft_type"] == "C17"
|
||||
assert detail["current"]["callsign"] == "RCH401"
|
||||
|
||||
# 4) Track endpoint
|
||||
resp_track = await client.get("/api/v1/aircraft/ae1234/track", params={"hours": 3})
|
||||
assert resp_track.status_code == 200
|
||||
track = resp_track.json()
|
||||
assert len(track["points"]) == 2
|
||||
assert track["points"][0]["lat"] == pytest.approx(34.9, rel=1e-4)
|
||||
|
||||
# 5) Enforce API scope when EARTH_API_AUTH_MODE=enforce
|
||||
from app.core.config import settings
|
||||
|
||||
monkeypatch.setattr(settings, "EARTH_API_AUTH_MODE", "enforce")
|
||||
unauth = await client.get("/api/v1/aircraft/snapshot")
|
||||
assert unauth.status_code == 401
|
||||
finally:
|
||||
app.dependency_overrides.pop(get_db, None)
|
||||
engine.dispose()
|
||||
@@ -0,0 +1,411 @@
|
||||
"""Phase 2 aircraft collectors, classification, registry offline resilience, and aggregation tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import UTC, datetime, timedelta
|
||||
import httpx
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.datasource_defaults import DEFAULT_DATASOURCES
|
||||
from app.db.migrations import discover_migrations
|
||||
from app.models.aircraft import (
|
||||
ADSBSourceHealth,
|
||||
AircraftCurrentState,
|
||||
AircraftPosition,
|
||||
AircraftStatic,
|
||||
)
|
||||
from app.models.datasource_config import DataSourceConfig
|
||||
from app.services.aircraft_aggregation import (
|
||||
prune_aircraft_tables,
|
||||
should_record_aircraft_track_point,
|
||||
upsert_aircraft_observations,
|
||||
)
|
||||
from app.services.aircraft_registry import parse_aircraft_registry_csv, sync_aircraft_registry
|
||||
from app.services.aircraft_types import classify_aircraft, is_military_callsign, is_military_icao24
|
||||
from app.services.collectors.adsb_lol import parse_adsb_lol_payload
|
||||
from app.services.collectors.opensky import (
|
||||
OpenSkyAircraftCollector,
|
||||
clear_opensky_token_cache,
|
||||
fetch_opensky_access_token,
|
||||
parse_opensky_states_payload,
|
||||
)
|
||||
from app.services.credential_guides import DEFAULT_CREDENTIAL_GUIDES
|
||||
from app.services.datasource_connectivity import SUPPORTED_CREDENTIAL_PROVIDERS
|
||||
|
||||
|
||||
class _AsyncSQLiteSession:
|
||||
def __init__(self, session: Session):
|
||||
self._session = session
|
||||
|
||||
def get_bind(self):
|
||||
return self._session.get_bind()
|
||||
|
||||
def add(self, instance) -> None:
|
||||
self._session.add(instance)
|
||||
|
||||
def add_all(self, instances) -> None:
|
||||
self._session.add_all(instances)
|
||||
|
||||
async def delete(self, instance) -> None:
|
||||
self._session.delete(instance)
|
||||
|
||||
async def get(self, entity, ident):
|
||||
return self._session.get(entity, ident)
|
||||
|
||||
async def execute(self, statement, params=None):
|
||||
return self._session.execute(statement, params) if params is not None else self._session.execute(statement)
|
||||
|
||||
async def scalar(self, statement):
|
||||
return self._session.scalar(statement)
|
||||
|
||||
async def scalars(self, statement):
|
||||
return self._session.scalars(statement)
|
||||
|
||||
async def flush(self) -> None:
|
||||
self._session.flush()
|
||||
|
||||
async def commit(self) -> None:
|
||||
self._session.commit()
|
||||
|
||||
async def rollback(self) -> None:
|
||||
self._session.rollback()
|
||||
|
||||
|
||||
class _AsyncConnShim:
|
||||
def __init__(self, conn):
|
||||
self._conn = conn
|
||||
self.dialect = conn.dialect
|
||||
|
||||
async def execute(self, stmt, params=None):
|
||||
return self._conn.execute(stmt, params) if params is not None else self._conn.execute(stmt)
|
||||
|
||||
|
||||
async def _make_sqlite_session():
|
||||
engine = create_engine("sqlite:///:memory:")
|
||||
with engine.begin() as raw_conn:
|
||||
shim = _AsyncConnShim(raw_conn)
|
||||
DataSourceConfig.__table__.create(raw_conn, checkfirst=True)
|
||||
for step in discover_migrations():
|
||||
if step.version == "0008":
|
||||
await step.upgrade(shim)
|
||||
|
||||
@asynccontextmanager
|
||||
async def _factory():
|
||||
with Session(engine) as session:
|
||||
yield _AsyncSQLiteSession(session)
|
||||
|
||||
return engine, _factory
|
||||
|
||||
|
||||
def test_adsb_lol_fixture_parsing_military_and_emergency():
|
||||
fixture = {
|
||||
"now": 1733500000.0,
|
||||
"ac": [
|
||||
{
|
||||
"hex": "ae1234",
|
||||
"flight": "RCH401 ",
|
||||
"t": "C17",
|
||||
"lat": 35.12,
|
||||
"lon": 139.45,
|
||||
"alt_baro": 32000,
|
||||
"alt_geom": 32150,
|
||||
"gs": 450.0,
|
||||
"track": 95.5,
|
||||
"baro_rate": -100,
|
||||
"squawk": "1200",
|
||||
"category": "A5",
|
||||
"dbFlags": 1,
|
||||
"seen_pos": 4.0,
|
||||
},
|
||||
{
|
||||
"hex": "4ca123",
|
||||
"flight": "RYR102",
|
||||
"t": "B738",
|
||||
"lat": 51.47,
|
||||
"lon": -0.45,
|
||||
"alt_baro": "ground",
|
||||
"gs": 15.0,
|
||||
"track": 270.0,
|
||||
"squawk": "7700",
|
||||
"category": "A3",
|
||||
"seen_pos": 1.0,
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
parsed = parse_adsb_lol_payload(fixture, is_military_endpoint=False)
|
||||
assert len(parsed) == 2
|
||||
|
||||
mil = parsed[0]
|
||||
assert mil["icao24"] == "ae1234"
|
||||
assert mil["callsign"] == "RCH401"
|
||||
assert mil["on_ground"] is False
|
||||
assert mil["baro_altitude_m"] == pytest.approx(32000 * 0.3048, rel=1e-4)
|
||||
assert mil["ground_speed_ms"] == pytest.approx(450.0 * 0.514444, rel=1e-4)
|
||||
assert mil["source_is_military"] is True
|
||||
|
||||
emg = parsed[1]
|
||||
assert emg["icao24"] == "4ca123"
|
||||
assert emg["on_ground"] is True
|
||||
assert emg["baro_altitude_m"] == 0.0
|
||||
assert emg["squawk"] == "7700"
|
||||
|
||||
|
||||
def test_military_icao_hex_and_callsign_classification():
|
||||
assert is_military_icao24("AE0001") is True
|
||||
assert is_military_icao24("43c100") is True
|
||||
assert is_military_icao24("a01234") is False
|
||||
assert is_military_callsign("REACH12") is True
|
||||
assert is_military_callsign("NATO07") is True
|
||||
assert is_military_callsign("CCA981") is False
|
||||
|
||||
# Emergency squawk wins category while keeping is_military=True!
|
||||
res = classify_aircraft(
|
||||
icao24="ae1111",
|
||||
callsign="RCH900",
|
||||
squawk="7700",
|
||||
aircraft_type="C17",
|
||||
)
|
||||
assert res["category"] == "emergency"
|
||||
assert res["is_military"] is True
|
||||
assert res["is_emergency"] is True
|
||||
assert res["emergency_code"] == "7700"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_opensky_token_cache_429_cooldown_and_unconfigured_skip(monkeypatch):
|
||||
clear_opensky_token_cache()
|
||||
token_calls = 0
|
||||
|
||||
def _handler(request: httpx.Request) -> httpx.Response:
|
||||
nonlocal token_calls
|
||||
if "openid-connect/token" in str(request.url):
|
||||
token_calls += 1
|
||||
return httpx.Response(200, json={"access_token": f"tok-{token_calls}", "expires_in": 600})
|
||||
return httpx.Response(429, headers={"Retry-After": "120"})
|
||||
|
||||
transport = httpx.MockTransport(_handler)
|
||||
t0 = datetime(2026, 12, 6, 10, 0, tzinfo=UTC)
|
||||
async with httpx.AsyncClient(transport=transport) as client:
|
||||
tok1 = await fetch_opensky_access_token(client, client_id="cid", client_secret="sec", now=t0)
|
||||
tok2 = await fetch_opensky_access_token(
|
||||
client, client_id="cid", client_secret="sec", now=t0 + timedelta(seconds=300)
|
||||
)
|
||||
# Inside 60s refresh window -> refreshes cleanly
|
||||
tok3 = await fetch_opensky_access_token(
|
||||
client, client_id="cid", client_secret="sec", now=t0 + timedelta(seconds=550)
|
||||
)
|
||||
|
||||
assert tok1 == "tok-1"
|
||||
assert tok2 == "tok-1"
|
||||
assert tok3 == "tok-2"
|
||||
assert token_calls == 2
|
||||
|
||||
# Unconfigured collector skips quietly and updates status cleanly
|
||||
engine, factory = await _make_sqlite_session()
|
||||
try:
|
||||
async with factory() as db:
|
||||
collector = OpenSkyAircraftCollector()
|
||||
collector._db_session = db
|
||||
monkeypatch.delenv("OPENSKY_CLIENT_ID", raising=False)
|
||||
monkeypatch.delenv("OPENSKY_CLIENT_SECRET", raising=False)
|
||||
rows = await collector.fetch()
|
||||
assert rows == []
|
||||
assert getattr(collector, "_skip_reason", None) == "not_configured"
|
||||
await collector._save_data(db, rows)
|
||||
health = await db.get(ADSBSourceHealth, "opensky_aircraft")
|
||||
assert health is not None
|
||||
assert health.connection_state == "not_configured"
|
||||
|
||||
# Simulate 429 cooldown written + respected
|
||||
collector._skip_reason = "rate_limited"
|
||||
collector._cooldown_until = datetime.now(UTC) + timedelta(minutes=10)
|
||||
await collector._save_data(db, [])
|
||||
health = await db.get(ADSBSourceHealth, "opensky_aircraft")
|
||||
assert health.connection_state == "cooldown"
|
||||
assert await collector._is_in_cooldown(datetime.now(UTC)) is True
|
||||
finally:
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_opensky_states_vector_parsing():
|
||||
payload = {
|
||||
"time": 1733500100,
|
||||
"states": [
|
||||
["780a1b", "CCA101 ", "China", 1733500095, 1733500098, 116.58, 40.08, 10500.0, False, 240.5, 180.0, 2.5, None, 10600.0, "2000", False, 0, 5]
|
||||
],
|
||||
}
|
||||
parsed = parse_opensky_states_payload(payload)
|
||||
assert len(parsed) == 1
|
||||
assert parsed[0]["icao24"] == "780a1b"
|
||||
assert parsed[0]["callsign"] == "CCA101"
|
||||
assert parsed[0]["baro_altitude_m"] == 10500.0
|
||||
assert parsed[0]["adsb_category"] == "A4"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_multi_source_merge_track_downsampling_and_prune():
|
||||
assert should_record_aircraft_track_point(
|
||||
None,
|
||||
observed_at=datetime.now(UTC),
|
||||
altitude_m=10000,
|
||||
track_deg=90,
|
||||
) is True
|
||||
base_time = datetime(2026, 12, 6, 12, 0, 0, tzinfo=UTC)
|
||||
prev = {"observed_at": base_time, "altitude_m": 10000.0, "track_deg": 90.0}
|
||||
# Small delta (<30s, <=10deg, <=300m) -> skip
|
||||
assert should_record_aircraft_track_point(
|
||||
prev,
|
||||
observed_at=base_time + timedelta(seconds=10),
|
||||
altitude_m=10100.0,
|
||||
track_deg=95.0,
|
||||
) is False
|
||||
# Heading jump across 360/0 boundary (358 -> 12 deg = 14 deg) -> record
|
||||
assert should_record_aircraft_track_point(
|
||||
{"observed_at": base_time, "altitude_m": 10000.0, "track_deg": 358.0},
|
||||
observed_at=base_time + timedelta(seconds=10),
|
||||
altitude_m=10000.0,
|
||||
track_deg=12.0,
|
||||
) is True
|
||||
# Altitude delta > 300m -> record
|
||||
assert should_record_aircraft_track_point(
|
||||
prev,
|
||||
observed_at=base_time + timedelta(seconds=5),
|
||||
altitude_m=10400.0,
|
||||
track_deg=90.0,
|
||||
) is True
|
||||
|
||||
engine, factory = await _make_sqlite_session()
|
||||
try:
|
||||
async with factory() as db:
|
||||
# 1) Same timestamp from opensky vs adsb_lol -> adsb_lol wins & military flag sticks
|
||||
await upsert_aircraft_observations(
|
||||
db,
|
||||
[
|
||||
{
|
||||
"icao24": "4b1234",
|
||||
"callsign": "SWR101",
|
||||
"lat": 47.0,
|
||||
"lon": 8.0,
|
||||
"baro_altitude_m": 9000.0,
|
||||
"ground_speed_ms": 210.0,
|
||||
"track_deg": 45.0,
|
||||
"source": "opensky_aircraft",
|
||||
"observed_at": base_time,
|
||||
}
|
||||
],
|
||||
default_source="opensky_aircraft",
|
||||
ingested_at=base_time,
|
||||
)
|
||||
await upsert_aircraft_observations(
|
||||
db,
|
||||
[
|
||||
{
|
||||
"icao24": "4b1234",
|
||||
"callsign": "SWR101",
|
||||
"lat": 47.05,
|
||||
"lon": 8.05,
|
||||
"baro_altitude_m": 9100.0,
|
||||
"ground_speed_ms": 215.0,
|
||||
"track_deg": 46.0,
|
||||
"source": "adsb_lol_aircraft",
|
||||
"source_is_military": True,
|
||||
"observed_at": base_time,
|
||||
}
|
||||
],
|
||||
default_source="adsb_lol_aircraft",
|
||||
ingested_at=base_time,
|
||||
)
|
||||
await db.commit()
|
||||
|
||||
curr = await db.get(AircraftCurrentState, "4b1234")
|
||||
assert curr is not None
|
||||
assert curr.source == "adsb_lol_aircraft"
|
||||
assert curr.is_military is True
|
||||
|
||||
# Insert an expired record (>20m ago) and expired track (>25h ago) and verify prune
|
||||
old_curr_time = base_time - timedelta(minutes=20)
|
||||
old_pos_time = base_time - timedelta(hours=25)
|
||||
db.add(
|
||||
AircraftCurrentState(
|
||||
icao24="dead01",
|
||||
lat=10.0,
|
||||
lon=20.0,
|
||||
category="other",
|
||||
source="opensky_aircraft",
|
||||
observed_at=old_curr_time,
|
||||
ingested_at=old_curr_time,
|
||||
)
|
||||
)
|
||||
db.add(
|
||||
AircraftPosition(
|
||||
icao24="dead01",
|
||||
lat=10.0,
|
||||
lon=20.0,
|
||||
observed_at=old_pos_time,
|
||||
)
|
||||
)
|
||||
await db.commit()
|
||||
|
||||
pruned = await prune_aircraft_tables(db, now=base_time)
|
||||
await db.commit()
|
||||
assert pruned["current_deleted"] >= 1
|
||||
assert pruned["positions_deleted"] >= 1
|
||||
assert await db.get(AircraftCurrentState, "4b1234") is not None
|
||||
assert await db.get(AircraftCurrentState, "dead01") is None
|
||||
pos_rows = (
|
||||
await db.execute(select(AircraftPosition).where(AircraftPosition.icao24 == "4b1234"))
|
||||
).scalars().all()
|
||||
assert len(pos_rows) == 1
|
||||
finally:
|
||||
engine.dispose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_aircraft_registry_offline_graceful_degradation(tmp_path):
|
||||
csv_sample = "icao24,registration,typecode,model,operator,owner,country,dbFlags\nae1234,07-7171,C17,Boeing C-17A,USAF AMC,USAF,United States,1\n"
|
||||
parsed = parse_aircraft_registry_csv(csv_sample)
|
||||
assert len(parsed) == 1
|
||||
assert parsed[0]["is_military"] is True
|
||||
|
||||
engine, factory = await _make_sqlite_session()
|
||||
try:
|
||||
async with factory() as db:
|
||||
db.add(
|
||||
AircraftStatic(
|
||||
icao24="780111",
|
||||
registration="B-1234",
|
||||
aircraft_type="B738",
|
||||
category="commercial",
|
||||
is_military=False,
|
||||
source="aircraft_registry",
|
||||
)
|
||||
)
|
||||
await db.commit()
|
||||
|
||||
# Point to unreachable URL -> must NOT crash & must retain existing rows
|
||||
res = await sync_aircraft_registry(
|
||||
db,
|
||||
primary_url="http://127.0.0.1:9/nonexistent.csv",
|
||||
fallback_url="",
|
||||
cache_dir=str(tmp_path / "empty_cache"),
|
||||
timeout_seconds=0.5,
|
||||
)
|
||||
assert res["status"] == "offline_retained"
|
||||
assert res["existing_count"] == 1
|
||||
assert await db.get(AircraftStatic, "780111") is not None
|
||||
finally:
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_opensky_credential_collector_contract_complete():
|
||||
info = DEFAULT_DATASOURCES["opensky_aircraft"]
|
||||
assert info["id"] == 40
|
||||
assert info["requires_credentials"] is True
|
||||
assert info["credential_status"] == "supported"
|
||||
assert info["credential_provider"] == "opensky"
|
||||
assert "opensky" in DEFAULT_CREDENTIAL_GUIDES
|
||||
assert "opensky" in SUPPORTED_CREDENTIAL_PROVIDERS
|
||||
@@ -331,3 +331,62 @@ def test_old_gpu_preview_urls_are_replaced_with_latest_variants():
|
||||
latest = next(a for a in bundled_configuration()[0].assets if a.id == old.id)
|
||||
assert upgraded["variants"] == latest.variants
|
||||
assert upgraded["url"] == latest.url
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fingerprint_resolve_etag_and_head_file(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(card_image_files, "ASSET_DIR", tmp_path)
|
||||
defaults, _ = bundled_configuration()
|
||||
payload = {
|
||||
"revision": "rev-one",
|
||||
"config": defaults.model_dump(mode="json"),
|
||||
"known_assets": [],
|
||||
"known_rules": [],
|
||||
}
|
||||
db, _record = fake_db(payload)
|
||||
app = FastAPI()
|
||||
app.include_router(router)
|
||||
app.dependency_overrides[get_db] = lambda: db
|
||||
app.dependency_overrides[get_current_user] = lambda: SimpleNamespace(
|
||||
role="admin", id=1, username="admin"
|
||||
)
|
||||
|
||||
buffer = io.BytesIO()
|
||||
Image.new("RGB", (640, 480), "navy").save(buffer, "PNG")
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
fp1 = await client.get("/fingerprint")
|
||||
assert fp1.status_code == 200
|
||||
fp_etag = fp1.headers["etag"]
|
||||
assert fp1.json()["revision"].endswith(":rev-one")
|
||||
|
||||
fp_304 = await client.get("/fingerprint", headers={"If-None-Match": fp_etag})
|
||||
assert fp_304.status_code == 304 and fp_304.content == b""
|
||||
|
||||
res1 = await client.get("/resolve", params={"entity_type": "satellite", "entity_id": "123"})
|
||||
assert res1.status_code == 200
|
||||
body = res1.json()
|
||||
assert body["fingerprint"] and res1.headers["etag"] == f'"{body["fingerprint"]}"'
|
||||
|
||||
res_304 = await client.get(
|
||||
"/resolve",
|
||||
params={"entity_type": "satellite", "entity_id": "123"},
|
||||
headers={"If-None-Match": res1.headers["etag"]},
|
||||
)
|
||||
assert res_304.status_code == 304 and res_304.content == b""
|
||||
|
||||
payload["revision"] = "rev-two"
|
||||
res2 = await client.get(
|
||||
"/resolve",
|
||||
params={"entity_type": "satellite", "entity_id": "123"},
|
||||
headers={"If-None-Match": res1.headers["etag"]},
|
||||
)
|
||||
assert res2.status_code == 200
|
||||
assert res2.json()["fingerprint"] != body["fingerprint"]
|
||||
|
||||
upload_res = await client.post(
|
||||
"/upload", files={"file": ("head-test.png", buffer.getvalue(), "image/png")}
|
||||
)
|
||||
filename = upload_res.json()["variants"]["640"].rsplit("/", 1)[1]
|
||||
head_res = await client.head(f"/files/{filename}")
|
||||
assert head_res.status_code == 200
|
||||
assert "immutable" in head_res.headers["cache-control"]
|
||||
@@ -0,0 +1,251 @@
|
||||
"""Phase 3.2 natural disaster collector parsers, dedup, wildfire clustering, FIRMS contract, and API tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.datasource_defaults import DEFAULT_DATASOURCES
|
||||
from app.db.migrations import discover_migrations
|
||||
from app.db.session import get_db
|
||||
from app.main import app
|
||||
from app.models.disaster import DisasterEvent
|
||||
from app.services.ai.tool_registry import query_disaster_posture_tool
|
||||
from app.services.collectors.disasters import NASAFirmsWildfireCollector
|
||||
from app.services.credential_guides import DEFAULT_CREDENTIAL_GUIDES
|
||||
from app.services.datasource_connectivity import SUPPORTED_CREDENTIAL_PROVIDERS
|
||||
from app.services.disaster_aggregation import (
|
||||
parse_gdacs_events,
|
||||
parse_nasa_eonet_events,
|
||||
parse_nasa_firms_csv,
|
||||
parse_usgs_earthquakes,
|
||||
upsert_disaster_events,
|
||||
)
|
||||
|
||||
|
||||
class _AsyncSQLiteSession:
|
||||
def __init__(self, session: Session):
|
||||
self._session = session
|
||||
|
||||
def get_bind(self):
|
||||
return self._session.get_bind()
|
||||
|
||||
def add(self, instance) -> None:
|
||||
self._session.add(instance)
|
||||
|
||||
def add_all(self, instances) -> None:
|
||||
self._session.add_all(instances)
|
||||
|
||||
async def get(self, entity, ident):
|
||||
return self._session.get(entity, ident)
|
||||
|
||||
async def execute(self, statement, params=None):
|
||||
return self._session.execute(statement, params) if params is not None else self._session.execute(statement)
|
||||
|
||||
async def flush(self) -> None:
|
||||
self._session.flush()
|
||||
|
||||
async def commit(self) -> None:
|
||||
self._session.commit()
|
||||
|
||||
|
||||
class _AsyncConnShim:
|
||||
def __init__(self, conn):
|
||||
self._conn = conn
|
||||
self.dialect = conn.dialect
|
||||
|
||||
async def execute(self, stmt, params=None):
|
||||
return self._conn.execute(stmt, params) if params is not None else self._conn.execute(stmt)
|
||||
|
||||
|
||||
async def _make_sqlite_session():
|
||||
engine = create_engine("sqlite:///:memory:")
|
||||
with engine.begin() as raw_conn:
|
||||
shim = _AsyncConnShim(raw_conn)
|
||||
for step in discover_migrations():
|
||||
if step.version == "0009":
|
||||
await step.upgrade(shim)
|
||||
|
||||
@asynccontextmanager
|
||||
async def _factory():
|
||||
with Session(engine) as session:
|
||||
yield _AsyncSQLiteSession(session)
|
||||
|
||||
return engine, _factory
|
||||
|
||||
|
||||
def test_usgs_gdacs_eonet_and_firms_parsers():
|
||||
usgs = parse_usgs_earthquakes(
|
||||
{
|
||||
"features": [
|
||||
{
|
||||
"id": "us7000eq01",
|
||||
"geometry": {"type": "Point", "coordinates": [121.55, 23.85, 10.0]},
|
||||
"properties": {"mag": 6.6, "title": "M 6.6 - Hualien", "time": 1733486400000, "url": "https://earthquake.usgs.gov/earthquakes/eventpage/us7000eq01"},
|
||||
}
|
||||
]
|
||||
}
|
||||
)
|
||||
assert len(usgs) == 1
|
||||
assert usgs[0]["event_type"] == "earthquake"
|
||||
assert usgs[0]["severity"] == "high"
|
||||
assert usgs[0]["magnitude"] == 6.6
|
||||
|
||||
# GDACS must filter out Green alertlevel
|
||||
gdacs = parse_gdacs_events(
|
||||
{
|
||||
"features": [
|
||||
{
|
||||
"id": "gd1",
|
||||
"geometry": {"type": "Point", "coordinates": [121.58, 23.87]},
|
||||
"properties": {"eventid": "gdacs-eq-1", "eventtype": "EQ", "alertlevel": "Orange", "name": "Taiwan EQ", "fromdate": "2024-12-06T11:30:00Z"},
|
||||
},
|
||||
{
|
||||
"id": "gd2",
|
||||
"geometry": {"type": "Point", "coordinates": [10.0, 10.0]},
|
||||
"properties": {"eventid": "gdacs-green", "eventtype": "FL", "alertlevel": "Green", "name": "Minor flood", "fromdate": "2024-12-06T11:30:00Z"},
|
||||
},
|
||||
]
|
||||
}
|
||||
)
|
||||
assert len(gdacs) == 1
|
||||
assert gdacs[0]["source_event_id"] == "gdacs-eq-1"
|
||||
assert gdacs[0]["severity"] == "medium"
|
||||
|
||||
# NASA EONET must exclude earthquakes
|
||||
eonet = parse_nasa_eonet_events(
|
||||
{
|
||||
"events": [
|
||||
{
|
||||
"id": "EONET_EQ",
|
||||
"title": "Quake dup",
|
||||
"categories": [{"id": "earthquakes", "title": "Earthquakes"}],
|
||||
"geometry": [{"date": "2024-12-06T10:00:00Z", "type": "Point", "coordinates": [120.0, 24.0]}],
|
||||
},
|
||||
{
|
||||
"id": "EONET_VOLC",
|
||||
"title": "Etna Eruption",
|
||||
"categories": [{"id": "volcanoes", "title": "Volcanoes"}],
|
||||
"geometry": [{"date": "2024-12-06T10:00:00Z", "type": "Point", "coordinates": [15.0, 37.75]}],
|
||||
},
|
||||
]
|
||||
}
|
||||
)
|
||||
assert len(eonet) == 1
|
||||
assert eonet[0]["event_type"] == "volcano"
|
||||
|
||||
# FIRMS 0.25-deg hotspot clustering
|
||||
csv_text = (
|
||||
"latitude,longitude,bright_ti4,acq_date,acq_time\n"
|
||||
"34.10,118.10,335.2,2026-12-06,0100\n"
|
||||
"34.15,118.12,368.5,2026-12-06,0105\n"
|
||||
"34.18,118.20,342.0,2026-12-06,0110\n"
|
||||
)
|
||||
firms = parse_nasa_firms_csv(csv_text)
|
||||
assert len(firms) == 1
|
||||
assert firms[0]["cluster_count"] == 3
|
||||
assert firms[0]["max_brightness_k"] == 368.5
|
||||
assert firms[0]["severity"] == "high"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_disaster_cross_source_dedup_snapshot_and_ai_tool():
|
||||
engine, factory = await _make_sqlite_session()
|
||||
now = datetime.now(UTC)
|
||||
|
||||
records = [
|
||||
{
|
||||
"source": "usgs_earthquakes",
|
||||
"source_event_id": "us-tw-1",
|
||||
"event_type": "earthquake",
|
||||
"severity": "high",
|
||||
"title": "M6.4 Taiwan Offshore",
|
||||
"lat": 23.85,
|
||||
"lon": 121.55,
|
||||
"magnitude": 6.4,
|
||||
"observed_at": now - timedelta(minutes=20),
|
||||
},
|
||||
{
|
||||
"source": "gdacs_disasters",
|
||||
"source_event_id": "gdacs-tw-1",
|
||||
"event_type": "earthquake",
|
||||
"severity": "medium",
|
||||
"title": "GDACS Earthquake Taiwan",
|
||||
"lat": 23.89,
|
||||
"lon": 121.58,
|
||||
"magnitude": 6.3,
|
||||
"observed_at": now - timedelta(minutes=10),
|
||||
},
|
||||
{
|
||||
"source": "nasa_eonet_events",
|
||||
"source_event_id": "eonet-etna",
|
||||
"event_type": "volcano",
|
||||
"severity": "medium",
|
||||
"title": "Mount Etna Activity",
|
||||
"lat": 37.75,
|
||||
"lon": 15.00,
|
||||
"observed_at": now - timedelta(minutes=5),
|
||||
},
|
||||
]
|
||||
|
||||
async def _override_db():
|
||||
async with factory() as session:
|
||||
yield session
|
||||
|
||||
app.dependency_overrides[get_db] = _override_db
|
||||
try:
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
empty_resp = await client.get("/api/v1/disasters/snapshot")
|
||||
assert empty_resp.status_code == 200
|
||||
assert empty_resp.json()["count"] == 0
|
||||
|
||||
async with factory() as db:
|
||||
await upsert_disaster_events(db, records)
|
||||
rows = list((await db.execute(select(DisasterEvent).order_by(DisasterEvent.id))).scalars().all())
|
||||
by_src_id = {r.source_event_id: r for r in rows}
|
||||
assert by_src_id["us-tw-1"].duplicate_of is None
|
||||
assert by_src_id["gdacs-tw-1"].duplicate_of == by_src_id["us-tw-1"].id
|
||||
|
||||
tool_res = await query_disaster_posture_tool(db)
|
||||
assert tool_res["count"] == 2
|
||||
assert tool_res["high_count"] == 1
|
||||
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
resp = await client.get("/api/v1/disasters/snapshot?types=volcano")
|
||||
assert resp.status_code == 200
|
||||
body = resp.json()
|
||||
assert body["count"] == 1
|
||||
item = body["items"][0]
|
||||
assert item["source"] == "nasa_eonet_events"
|
||||
assert "observed_at" in item
|
||||
assert "ingested_at" in item
|
||||
assert "is_stale" in item
|
||||
finally:
|
||||
app.dependency_overrides.clear()
|
||||
engine.dispose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_nasa_firms_credential_collector_contract_and_missing_key(monkeypatch):
|
||||
info = DEFAULT_DATASOURCES["nasa_firms_wildfires"]
|
||||
assert info["id"] == 44
|
||||
assert info["requires_credentials"] is True
|
||||
assert info["credential_status"] == "supported"
|
||||
assert info["credential_provider"] == "nasa_firms"
|
||||
assert "nasa_firms" in DEFAULT_CREDENTIAL_GUIDES
|
||||
assert "nasa_firms" in SUPPORTED_CREDENTIAL_PROVIDERS
|
||||
|
||||
monkeypatch.delenv("NASA_FIRMS_MAP_KEY", raising=False)
|
||||
engine, factory = await _make_sqlite_session()
|
||||
try:
|
||||
async with factory() as db:
|
||||
collector = NASAFirmsWildfireCollector()
|
||||
result = await collector.collect(db)
|
||||
assert result["status"] == "not_configured"
|
||||
assert result["records_saved"] == 0
|
||||
finally:
|
||||
engine.dispose()
|
||||
@@ -434,3 +434,40 @@ async def test_cloud_apis_rbac_optimistic_lock_and_analytics(monkeypatch):
|
||||
assert r_clear.json()["meta"]["mode"] == "fallback_static"
|
||||
finally:
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
def test_resolve_effective_cloud_config_clamps_on_low_memory(monkeypatch):
|
||||
cfg = earth_clouds.CloudMapConfig(resolution="4096x2048")
|
||||
|
||||
monkeypatch.setattr(earth_clouds, "detect_container_memory_limit_mb", lambda: 500)
|
||||
clamped = earth_clouds.resolve_effective_cloud_config(cfg)
|
||||
assert clamped.resolution == "2048x1024"
|
||||
|
||||
monkeypatch.setattr(earth_clouds, "detect_container_memory_limit_mb", lambda: 2048)
|
||||
assert earth_clouds.resolve_effective_cloud_config(cfg).resolution == "4096x2048"
|
||||
|
||||
monkeypatch.setattr(earth_clouds, "detect_container_memory_limit_mb", lambda: None)
|
||||
assert earth_clouds.resolve_effective_cloud_config(cfg).resolution == "4096x2048"
|
||||
|
||||
|
||||
def test_fuse_and_synthesize_visual_layers_streams_png_payloads():
|
||||
from datetime import UTC, datetime
|
||||
from app.services.earth_clouds_fx import fuse_and_synthesize_visual_layers
|
||||
|
||||
ir_zero = np.zeros((32, 64), dtype=np.uint8)
|
||||
temp_grid = np.full((32, 64), 16.0, dtype=np.float32)
|
||||
temp_grid[9:13, 50:56] = 8.0
|
||||
vis_arr = np.zeros((32, 64, 4), dtype=np.uint8)
|
||||
vis_arr[:, :, 3] = 255
|
||||
vis_arr[9:13, 50:56, :3] = [215, 215, 215]
|
||||
|
||||
fused, webp = fuse_and_synthesize_visual_layers(
|
||||
ir_zero,
|
||||
temp_grid,
|
||||
[({"id": "himawari", "sub_lon": 140.7}, _make_png_bytes(vis_arr))],
|
||||
width=64,
|
||||
height=32,
|
||||
now_utc=datetime(2026, 12, 3, 5, 0, 0, tzinfo=UTC),
|
||||
)
|
||||
assert int(fused[11, 53]) >= 120
|
||||
assert webp is not None and len(webp) > 20
|
||||
@@ -665,4 +665,109 @@ async def test_satellites_endpoint_supports_compact_gzip_and_etag_304(
|
||||
assert json.loads(raw_cached)["count"] == 1
|
||||
assert second_compact.json()["count"] == 1
|
||||
artifact = next(iter(_ENCODED_ARTIFACT_CACHE.values()))
|
||||
assert gzip.decompress(artifact.gzip_bytes) == artifact.raw_bytes
|
||||
assert not hasattr(artifact, "raw_bytes")
|
||||
assert json.loads(gzip.decompress(artifact.gzip_bytes)) == json.loads(raw_cached)
|
||||
|
||||
|
||||
def test_encoded_artifact_cache_evicts_by_total_byte_budget(monkeypatch):
|
||||
from app.services import earth_layer_cache as cache_mod
|
||||
|
||||
monkeypatch.setattr(cache_mod, "ENCODED_ARTIFACT_CACHE_MAX_BYTES", 512)
|
||||
monkeypatch.setattr(cache_mod, "ENCODED_ARTIFACT_CACHE_MAX_ENTRIES", 16)
|
||||
_ENCODED_ARTIFACT_CACHE.clear()
|
||||
|
||||
# Craft high-entropy JSON payloads whose compressed size is ~200-300 bytes each.
|
||||
for idx in range(5):
|
||||
token = f"{idx}-" + ("abcdefghij1234567890" * 12)
|
||||
payload = {"type": "FeatureCollection", "features": [], "blob": f"{idx}:{hash(idx)}:{token}"}
|
||||
raw = json.dumps(payload).encode("utf-8")
|
||||
cache_mod._encode_layer_bytes(f"layer:{idx}", raw, features=0)
|
||||
|
||||
total_gzip_bytes = sum(len(item.gzip_bytes) for item in _ENCODED_ARTIFACT_CACHE.values())
|
||||
assert total_gzip_bytes <= 512
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_terrarium_tile_uses_bounded_disk_lru_and_304(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("PLANET_TERRAIN_CACHE_DIR", str(tmp_path))
|
||||
monkeypatch.setenv("PLANET_TERRAIN_CACHE_MAX_BYTES", "1600")
|
||||
|
||||
fetches = []
|
||||
|
||||
real_async_client = httpx.AsyncClient
|
||||
|
||||
class FakeUpstreamResponse:
|
||||
def __init__(self, body: bytes):
|
||||
self.content = body
|
||||
self.headers = {"content-type": "image/png", "cache-control": "public, max-age=86400"}
|
||||
|
||||
def raise_for_status(self):
|
||||
return None
|
||||
|
||||
class FakeAsyncClient:
|
||||
def __new__(cls, *args, **kwargs):
|
||||
if "transport" in kwargs:
|
||||
return real_async_client(*args, **kwargs)
|
||||
return super().__new__(cls)
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *args):
|
||||
return None
|
||||
|
||||
async def get(self, url: str):
|
||||
fetches.append(url)
|
||||
return FakeUpstreamResponse((url.encode("utf-8") * 40)[:700])
|
||||
|
||||
monkeypatch.setattr(visualization.httpx, "AsyncClient", FakeAsyncClient)
|
||||
|
||||
app = FastAPI()
|
||||
app.include_router(visualization.router, prefix="/api/v1/visualization")
|
||||
|
||||
async with real_async_client(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:
|
||||
first = await client.get("/api/v1/visualization/terrain/terrarium/1/0/0.png")
|
||||
assert first.status_code == 200
|
||||
etag = first.headers["etag"]
|
||||
|
||||
not_modified = await client.get(
|
||||
"/api/v1/visualization/terrain/terrarium/1/0/0.png",
|
||||
headers={"If-None-Match": etag},
|
||||
)
|
||||
assert not_modified.status_code == 304 and not_modified.content == b""
|
||||
assert len(fetches) == 1
|
||||
|
||||
head_res = await client.head("/api/v1/visualization/terrain/terrarium/1/0/0.png")
|
||||
assert head_res.status_code == 200 and head_res.headers["etag"] == etag
|
||||
|
||||
await client.get("/api/v1/visualization/terrain/terrarium/1/0/1.png")
|
||||
await client.get("/api/v1/visualization/terrain/terrarium/1/1/0.png")
|
||||
|
||||
total_disk_bytes = sum(p.stat().st_size for p in tmp_path.glob("*.png"))
|
||||
assert total_disk_bytes <= 1600
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_earth_brand_and_about_support_etag_304(monkeypatch):
|
||||
from app.api.v1 import earth as earth_api
|
||||
|
||||
async def fake_brand(_db):
|
||||
return {"brand": {"title_text": "Planet"}, "is_default": True}
|
||||
|
||||
async def fake_about(_db):
|
||||
return {"about": {"title": "Planet"}, "is_default": True}
|
||||
|
||||
monkeypatch.setattr(earth_api, "_get_earth_brand_payload", fake_brand)
|
||||
monkeypatch.setattr(earth_api, "_get_earth_about_payload", fake_about)
|
||||
|
||||
app = FastAPI()
|
||||
app.include_router(earth_api.router, prefix="/api/v1/earth")
|
||||
app.dependency_overrides[earth_api.get_db] = lambda: object()
|
||||
|
||||
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:
|
||||
for ep in ("/api/v1/earth/brand", "/api/v1/earth/about"):
|
||||
r1 = await client.get(ep)
|
||||
assert r1.status_code == 200
|
||||
etag = r1.headers["etag"]
|
||||
r2 = await client.get(ep, headers={"If-None-Match": etag})
|
||||
assert r2.status_code == 304 and r2.content == b""
|
||||
@@ -2,7 +2,10 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import gc
|
||||
import io
|
||||
import weakref
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
import httpx
|
||||
@@ -367,3 +370,101 @@ async def test_tile_proxy_gating_cache_lru_and_basemap_api(tmp_path, monkeypatch
|
||||
assert wind_tool["domain"] == "wind"
|
||||
finally:
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_or_fetch_tile_coalesces_concurrent_requests(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(earth_tiles, "TILES_DATA_DIR", tmp_path / "tiles")
|
||||
monkeypatch.setattr(
|
||||
earth_tiles,
|
||||
"_get_source_runtime_settings",
|
||||
AsyncMock(
|
||||
return_value=(
|
||||
True,
|
||||
earth_tiles.DEFAULT_TILE_TEMPLATES["earth_imagery_sentinel2"],
|
||||
{"max_zoom": 8, "request_timeout_seconds": 10},
|
||||
)
|
||||
),
|
||||
)
|
||||
calls = 0
|
||||
|
||||
async def slow_fetch(*_args, **_kwargs):
|
||||
nonlocal calls
|
||||
calls += 1
|
||||
await asyncio.sleep(0.05)
|
||||
return b"RIFFcoalescedWEBP"
|
||||
|
||||
monkeypatch.setattr(earth_tiles, "_fetch_and_encode_tile", slow_fetch)
|
||||
results = await asyncio.gather(
|
||||
*(
|
||||
earth_tiles.get_or_fetch_tile("earth_imagery_sentinel2", 2, 1, 1)
|
||||
for _ in range(4)
|
||||
)
|
||||
)
|
||||
assert calls == 1
|
||||
assert results == [(b"RIFFcoalescedWEBP", True)] * 4
|
||||
|
||||
|
||||
def test_tile_encode_semaphore_limits_concurrency_without_retaining_closed_loop(monkeypatch):
|
||||
monkeypatch.setenv("PLANET_TILE_ENCODE_CONCURRENCY", "1")
|
||||
|
||||
async def contend_for_semaphore():
|
||||
waiting = asyncio.Event()
|
||||
entered = asyncio.Event()
|
||||
|
||||
async def acquire():
|
||||
waiting.set()
|
||||
async with earth_tiles._get_tile_encode_semaphore():
|
||||
entered.set()
|
||||
|
||||
async with earth_tiles._get_tile_encode_semaphore():
|
||||
contender = asyncio.create_task(acquire())
|
||||
await waiting.wait()
|
||||
assert not entered.is_set()
|
||||
|
||||
await contender
|
||||
assert entered.is_set()
|
||||
return weakref.ref(asyncio.get_running_loop())
|
||||
|
||||
loop_ref = asyncio.run(contend_for_semaphore())
|
||||
gc.collect()
|
||||
assert loop_ref() is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cleanup_stale_running_tasks_include_all_running(monkeypatch):
|
||||
from datetime import UTC, datetime
|
||||
from types import SimpleNamespace
|
||||
from contextlib import asynccontextmanager
|
||||
from app.services import scheduler
|
||||
|
||||
fresh_task = SimpleNamespace(
|
||||
id=111,
|
||||
status="running",
|
||||
phase="fetching",
|
||||
started_at=datetime.now(UTC),
|
||||
completed_at=None,
|
||||
error_message="",
|
||||
)
|
||||
committed = False
|
||||
|
||||
class _FakeDb:
|
||||
async def execute(self, _stmt):
|
||||
return SimpleNamespace(scalars=lambda: SimpleNamespace(all=lambda: [fresh_task]))
|
||||
|
||||
async def commit(self):
|
||||
nonlocal committed
|
||||
committed = True
|
||||
|
||||
@asynccontextmanager
|
||||
async def _fake_session_factory():
|
||||
yield _FakeDb()
|
||||
|
||||
monkeypatch.setattr(scheduler, "async_session_factory", _fake_session_factory)
|
||||
cleaned = await scheduler.cleanup_stale_running_tasks(include_all_running=True)
|
||||
assert cleaned == 1
|
||||
assert committed is True
|
||||
assert fresh_task.status == "failed"
|
||||
assert fresh_task.phase == "failed"
|
||||
assert fresh_task.completed_at is not None
|
||||
assert "backend restart" in fresh_task.error_message
|
||||
Loaded 100 of 282 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user