From 1c0066edc6ee13d66d75a2e44fc362ef2f17d6c7 Mon Sep 17 00:00:00 2001 From: linkong Date: Sun, 6 Dec 2026 22:47:23 +0800 Subject: [PATCH] release: bump version to 0.85.0 --- .gitignore | 2 + VERSION | 2 +- backend/app/api/main.py | 18 + backend/app/api/v1/actions.py | 182 +++ backend/app/api/v1/aircraft.py | 226 ++++ backend/app/api/v1/card_images.py | 79 +- backend/app/api/v1/cases.py | 209 +++ backend/app/api/v1/data_products.py | 23 + backend/app/api/v1/datasource_config.py | 15 + backend/app/api/v1/datasources.py | 3 +- backend/app/api/v1/disasters.py | 80 ++ backend/app/api/v1/earth.py | 44 +- backend/app/api/v1/geofences.py | 127 ++ backend/app/api/v1/gps_jamming.py | 88 ++ backend/app/api/v1/incidents.py | 203 +++ backend/app/api/v1/interactables.py | 94 +- backend/app/api/v1/news.py | 2 + backend/app/api/v1/ontology.py | 185 +++ backend/app/api/v1/replay.py | 421 ++++++ backend/app/api/v1/settings.py | 19 +- backend/app/api/v1/system_control.py | 11 + backend/app/api/v1/vessels.py | 19 + backend/app/api/v1/visualization.py | 294 ++++- backend/app/core/data_sources.py | 9 + backend/app/core/data_sources.yaml | 41 + backend/app/core/datasource_defaults.py | 94 ++ backend/app/data/maritime_chokepoints.json | 83 ++ backend/app/data/strategic_ports.json | 26 + .../0008_add_aircraft_and_gps_jamming.py | 325 +++++ ..._add_disaster_and_maritime_intelligence.py | 218 +++ .../0010_add_ontology_curation.py | 117 ++ .../0011_add_geofences_and_incidents.py | 155 +++ .../0012_add_investigation_cases.py | 117 ++ .../0013_add_action_requests.py | 62 + backend/app/db/session.py | 18 +- backend/app/models/__init__.py | 28 + backend/app/models/action_request.py | 44 + backend/app/models/aircraft.py | 152 +++ backend/app/models/disaster.py | 59 + backend/app/models/earth_news.py | 5 +- backend/app/models/geofence.py | 85 ++ backend/app/models/gps_jamming.py | 46 + backend/app/models/investigation_case.py | 86 ++ backend/app/models/maritime_advisory.py | 40 + backend/app/models/ontology.py | 70 + backend/app/services/actions.py | 369 ++++++ backend/app/services/ai/dag_executor.py | 38 + backend/app/services/ai/entity_resolver.py | 1176 +++++++++++++++++ .../app/services/ai/presentation_compiler.py | 4 + backend/app/services/ai/proactive_pipeline.py | 98 ++ backend/app/services/ai/scene_directives.py | 58 +- backend/app/services/ai/tool_registry.py | 452 ++++++- backend/app/services/ai/workflow_registry.py | 147 ++- backend/app/services/aircraft_aggregation.py | 430 ++++++ backend/app/services/aircraft_registry.py | 319 +++++ backend/app/services/aircraft_types.py | 240 ++++ backend/app/services/api_keys.py | 2 + backend/app/services/collectors/__init__.py | 29 + backend/app/services/collectors/adsb_lol.py | 324 +++++ .../services/collectors/aircraft_registry.py | 52 + backend/app/services/collectors/disasters.py | 279 ++++ .../app/services/collectors/gps_jamming.py | 246 ++++ .../app/services/collectors/nga_warnings.py | 106 ++ backend/app/services/collectors/opensky.py | 403 ++++++ backend/app/services/credential_guides.py | 54 + backend/app/services/data_jobs.py | 36 + .../app/services/datasource_connectivity.py | 101 +- backend/app/services/disaster_aggregation.py | 533 ++++++++ backend/app/services/earth_layer_adapters.py | 58 +- backend/app/services/earth_layer_cache.py | 24 +- backend/app/services/earth_news.py | 105 +- backend/app/services/earth_news_store.py | 13 + backend/app/services/fusion/__init__.py | 3 + backend/app/services/fusion/anomaly_engine.py | 641 +++++++++ backend/app/services/fusion/convergence.py | 398 ++++++ .../app/services/fusion/dependency_impact.py | 302 +++++ .../app/services/fusion/wargame_scenarios.py | 512 +++++++ backend/app/services/investigation_cases.py | 133 ++ backend/app/services/maritime_geography.py | 227 ++++ backend/app/services/nga_advisories.py | 389 ++++++ backend/app/services/private_data_ingest.py | 297 +++++ backend/app/services/scheduler.py | 60 + backend/app/services/source_freshness.py | 535 ++++++++ backend/app/services/storage_maintenance.py | 9 + backend/app/services/storage_policy.py | 8 + backend/app/services/vessel_types.py | 150 ++- backend/tests/test_actions_approval.py | 247 ++++ backend/tests/test_aircraft_api.py | 193 +++ backend/tests/test_aircraft_collectors.py | 411 ++++++ backend/tests/test_card_images.py | 59 + backend/tests/test_disasters.py | 251 ++++ backend/tests/test_earth_layer_cache.py | 107 +- backend/tests/test_fusion_convergence.py | 251 ++++ backend/tests/test_geofences_anomalies.py | 300 +++++ backend/tests/test_gps_jamming.py | 131 ++ backend/tests/test_ha_and_migrations.py | 3 +- backend/tests/test_investigation_cases.py | 154 +++ backend/tests/test_maritime_intelligence.py | 126 ++ backend/tests/test_news_credibility.py | 152 +++ backend/tests/test_nga_advisories.py | 173 +++ backend/tests/test_offline_mode.py | 77 ++ backend/tests/test_ontology.py | 368 ++++++ backend/tests/test_private_data_ingest.py | 184 +++ backend/tests/test_replay.py | 191 +++ backend/tests/test_source_freshness.py | 180 +++ backend/tests/test_spatial_cards_and_scene.py | 56 + backend/tests/test_storage_policy.py | 8 + .../test_visualization_satellite_streaming.py | 20 +- backend/tests/test_wargame_scenarios.py | 303 +++++ client/package.json | 2 +- client/scripts/build-earth-bundle.mjs | 42 +- client/src/main/config.ts | 29 + client/src/main/index.ts | 38 +- client/src/main/menu.ts | 31 + client/src/main/protocol-core.ts | 219 ++- client/src/main/protocol.ts | 2 + client/src/main/recording-core.ts | 17 +- client/src/main/recording-cursor-overlay.ts | 21 + client/src/main/recording-indicator.ts | 23 +- client/src/main/screen-recorder.ts | 7 + client/src/main/ui-scale.ts | 131 ++ client/src/main/window.ts | 153 ++- client/src/preload/index.ts | 2 + client/tests/protocol.test.ts | 58 + client/tests/recording-core.test.ts | 9 + client/tests/ui-scale.test.ts | 154 +++ docs/CHANGELOG.md | 15 + docs/plans/phase2-4-continuous-plan.md | 423 ++++++ docs/technical/en/backend-collectors.md | 9 + ...asource-collector-settings-connectivity.md | 9 + docs/technical/en/earth-frontend-context.md | 9 + .../en/earth-layer-style-reference.md | 2 +- .../en/earth-performance-baseline.md | 89 ++ docs/technical/en/earth-render-layer-order.md | 7 + docs/technical/en/manual.md | 10 +- docs/technical/en/ops-runbook.md | 25 + docs/technical/en/platform-data-flows.md | 2 + docs/technical/zh/backend-collectors.md | 9 + ...asource-collector-settings-connectivity.md | 9 + docs/technical/zh/earth-frontend-context.md | 9 + .../zh/earth-layer-style-reference.md | 2 +- .../zh/earth-performance-baseline.md | 89 ++ docs/technical/zh/earth-render-layer-order.md | 7 + docs/technical/zh/manual.md | 10 +- docs/technical/zh/ops-runbook.md | 25 + docs/technical/zh/platform-data-flows.md | 2 + docs/version-history.md | 3 +- frontend/bun.lock | 47 + frontend/package.json | 3 +- frontend/public/earth/css/hud.css | 639 ++++++++- frontend/public/earth/css/news-panel.css | 39 + frontend/public/earth/css/toolbar.css | 111 +- frontend/public/earth/index.html | 146 +- frontend/public/earth/js/about.js | 15 +- frontend/public/earth/js/actions-hud.js | 212 +++ .../earth/js/aircraft-gps-jamming.test.js | 134 ++ frontend/public/earth/js/aircraft-math.js | 259 ++++ frontend/public/earth/js/aircraft-worker.js | 35 + frontend/public/earth/js/aircraft.js | 715 ++++++++++ frontend/public/earth/js/asset-swr-cache.js | 512 +++++++ .../public/earth/js/asset-swr-cache.test.js | 144 ++ frontend/public/earth/js/bgp.js | 26 +- frontend/public/earth/js/brand.js | 19 +- frontend/public/earth/js/cables.js | 49 +- frontend/public/earth/js/card-images.js | 393 +++++- frontend/public/earth/js/card-images.test.js | 53 +- frontend/public/earth/js/cases-hud.js | 270 ++++ frontend/public/earth/js/cloud-map.js | 47 +- frontend/public/earth/js/compute-centers.js | 72 +- frontend/public/earth/js/compute-topic.js | 10 + frontend/public/earth/js/constants.js | 25 +- frontend/public/earth/js/controls.js | 284 ++++ .../public/earth/js/country-boundaries.js | 324 ++++- .../earth/js/country-boundaries.test.js | 19 +- frontend/public/earth/js/disasters.js | 264 ++++ frontend/public/earth/js/disasters.test.js | 24 + .../public/earth/js/earth-interactables.js | 30 + .../public/earth/js/earth-texture-image.js | 48 +- frontend/public/earth/js/earth.js | 13 + frontend/public/earth/js/fusion-overlays.js | 183 +++ .../public/earth/js/fusion-overlays.test.js | 50 + frontend/public/earth/js/geo-labels.js | 10 + frontend/public/earth/js/geofence-editor.js | 318 +++++ .../public/earth/js/geofence-editor.test.js | 52 + frontend/public/earth/js/gps-jamming-math.js | 102 ++ .../public/earth/js/gps-jamming-worker.js | 27 + frontend/public/earth/js/gps-jamming.js | 241 ++++ frontend/public/earth/js/hud-focus-stack.js | 1 + frontend/public/earth/js/i18n.js | 194 +++ frontend/public/earth/js/incidents-hud.js | 269 ++++ frontend/public/earth/js/info-card.js | 120 +- .../public/earth/js/layer-startup-tasks.js | 88 ++ frontend/public/earth/js/legend-filters.js | 1 + frontend/public/earth/js/legend.js | 10 + frontend/public/earth/js/main.js | 1138 +++++++++++++++- frontend/public/earth/js/map-2d.js | 824 ++++++++++++ .../public/earth/js/map-view-controller.js | 200 +++ .../earth/js/map-view-controller.test.js | 107 ++ frontend/public/earth/js/maritime-context.js | 97 ++ frontend/public/earth/js/news.js | 67 +- frontend/public/earth/js/ontology-graph.js | 242 ++++ .../public/earth/js/ontology-graph.test.js | 32 + frontend/public/earth/js/ontology-hud.js | 132 ++ frontend/public/earth/js/replay-timeline.js | 418 ++++++ frontend/public/earth/js/replay-worker.js | 104 ++ .../public/earth/js/replay-worker.test.js | 34 + frontend/public/earth/js/source-freshness.js | 262 ++++ .../public/earth/js/spatial-workflow-cards.js | 135 ++ .../earth/js/spatial-workflow-cards.test.js | 94 ++ frontend/public/earth/js/surface-ribbon.js | 116 ++ frontend/public/earth/js/terrain.js | 37 +- frontend/public/earth/js/wind-layer.js | 67 +- frontend/public/earth/js/workbench-blocks.js | 109 ++ frontend/scripts/earth-runtime-plugin.mjs | 28 +- .../datasources/PrivateUploadWizard.tsx | 242 ++++ frontend/src/admin/pages/ApiKeySettings.tsx | 2 + .../src/admin/pages/PlainResourcePages.tsx | 66 +- .../admin/pages/datasourceConfigHelpers.ts | 53 +- frontend/src/i18n/legacy-ui.ts | 39 + frontend/tests/private-upload-wizard.test.tsx | 22 + pyproject.toml | 3 +- scripts/harness/client-smoke.mjs | 30 +- uv.lock | 36 +- 223 files changed, 30277 insertions(+), 340 deletions(-) create mode 100644 backend/app/api/v1/actions.py create mode 100644 backend/app/api/v1/aircraft.py create mode 100644 backend/app/api/v1/cases.py create mode 100644 backend/app/api/v1/disasters.py create mode 100644 backend/app/api/v1/geofences.py create mode 100644 backend/app/api/v1/gps_jamming.py create mode 100644 backend/app/api/v1/incidents.py create mode 100644 backend/app/api/v1/ontology.py create mode 100644 backend/app/api/v1/replay.py create mode 100644 backend/app/data/maritime_chokepoints.json create mode 100644 backend/app/data/strategic_ports.json create mode 100644 backend/app/db/migration_steps/0008_add_aircraft_and_gps_jamming.py create mode 100644 backend/app/db/migration_steps/0009_add_disaster_and_maritime_intelligence.py create mode 100644 backend/app/db/migration_steps/0010_add_ontology_curation.py create mode 100644 backend/app/db/migration_steps/0011_add_geofences_and_incidents.py create mode 100644 backend/app/db/migration_steps/0012_add_investigation_cases.py create mode 100644 backend/app/db/migration_steps/0013_add_action_requests.py create mode 100644 backend/app/models/action_request.py create mode 100644 backend/app/models/aircraft.py create mode 100644 backend/app/models/disaster.py create mode 100644 backend/app/models/geofence.py create mode 100644 backend/app/models/gps_jamming.py create mode 100644 backend/app/models/investigation_case.py create mode 100644 backend/app/models/maritime_advisory.py create mode 100644 backend/app/models/ontology.py create mode 100644 backend/app/services/actions.py create mode 100644 backend/app/services/aircraft_aggregation.py create mode 100644 backend/app/services/aircraft_registry.py create mode 100644 backend/app/services/aircraft_types.py create mode 100644 backend/app/services/collectors/adsb_lol.py create mode 100644 backend/app/services/collectors/aircraft_registry.py create mode 100644 backend/app/services/collectors/disasters.py create mode 100644 backend/app/services/collectors/gps_jamming.py create mode 100644 backend/app/services/collectors/nga_warnings.py create mode 100644 backend/app/services/collectors/opensky.py create mode 100644 backend/app/services/disaster_aggregation.py create mode 100644 backend/app/services/fusion/__init__.py create mode 100644 backend/app/services/fusion/anomaly_engine.py create mode 100644 backend/app/services/fusion/convergence.py create mode 100644 backend/app/services/fusion/dependency_impact.py create mode 100644 backend/app/services/fusion/wargame_scenarios.py create mode 100644 backend/app/services/investigation_cases.py create mode 100644 backend/app/services/maritime_geography.py create mode 100644 backend/app/services/nga_advisories.py create mode 100644 backend/app/services/private_data_ingest.py create mode 100644 backend/app/services/source_freshness.py create mode 100644 backend/tests/test_actions_approval.py create mode 100644 backend/tests/test_aircraft_api.py create mode 100644 backend/tests/test_aircraft_collectors.py create mode 100644 backend/tests/test_disasters.py create mode 100644 backend/tests/test_fusion_convergence.py create mode 100644 backend/tests/test_geofences_anomalies.py create mode 100644 backend/tests/test_gps_jamming.py create mode 100644 backend/tests/test_investigation_cases.py create mode 100644 backend/tests/test_maritime_intelligence.py create mode 100644 backend/tests/test_news_credibility.py create mode 100644 backend/tests/test_nga_advisories.py create mode 100644 backend/tests/test_offline_mode.py create mode 100644 backend/tests/test_ontology.py create mode 100644 backend/tests/test_private_data_ingest.py create mode 100644 backend/tests/test_replay.py create mode 100644 backend/tests/test_source_freshness.py create mode 100644 backend/tests/test_spatial_cards_and_scene.py create mode 100644 backend/tests/test_wargame_scenarios.py create mode 100644 client/src/main/ui-scale.ts create mode 100644 client/tests/ui-scale.test.ts create mode 100755 docs/plans/phase2-4-continuous-plan.md create mode 100644 docs/technical/en/earth-performance-baseline.md create mode 100644 docs/technical/zh/earth-performance-baseline.md create mode 100644 frontend/public/earth/js/actions-hud.js create mode 100644 frontend/public/earth/js/aircraft-gps-jamming.test.js create mode 100644 frontend/public/earth/js/aircraft-math.js create mode 100644 frontend/public/earth/js/aircraft-worker.js create mode 100644 frontend/public/earth/js/aircraft.js create mode 100644 frontend/public/earth/js/asset-swr-cache.js create mode 100644 frontend/public/earth/js/asset-swr-cache.test.js create mode 100644 frontend/public/earth/js/cases-hud.js create mode 100644 frontend/public/earth/js/disasters.js create mode 100644 frontend/public/earth/js/disasters.test.js create mode 100644 frontend/public/earth/js/fusion-overlays.js create mode 100644 frontend/public/earth/js/fusion-overlays.test.js create mode 100644 frontend/public/earth/js/geofence-editor.js create mode 100644 frontend/public/earth/js/geofence-editor.test.js create mode 100644 frontend/public/earth/js/gps-jamming-math.js create mode 100644 frontend/public/earth/js/gps-jamming-worker.js create mode 100644 frontend/public/earth/js/gps-jamming.js create mode 100644 frontend/public/earth/js/incidents-hud.js create mode 100644 frontend/public/earth/js/map-2d.js create mode 100644 frontend/public/earth/js/map-view-controller.js create mode 100644 frontend/public/earth/js/map-view-controller.test.js create mode 100644 frontend/public/earth/js/maritime-context.js create mode 100644 frontend/public/earth/js/ontology-graph.js create mode 100644 frontend/public/earth/js/ontology-graph.test.js create mode 100644 frontend/public/earth/js/ontology-hud.js create mode 100644 frontend/public/earth/js/replay-timeline.js create mode 100644 frontend/public/earth/js/replay-worker.js create mode 100644 frontend/public/earth/js/replay-worker.test.js create mode 100644 frontend/public/earth/js/source-freshness.js create mode 100644 frontend/public/earth/js/spatial-workflow-cards.js create mode 100644 frontend/public/earth/js/spatial-workflow-cards.test.js create mode 100644 frontend/src/admin/components/datasources/PrivateUploadWizard.tsx create mode 100644 frontend/tests/private-upload-wizard.test.tsx diff --git a/.gitignore b/.gitignore index f7ef8d67..cd96e696 100644 --- a/.gitignore +++ b/.gitignore @@ -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 diff --git a/VERSION b/VERSION index 7a10a81e..137c1281 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.84.2 +0.85.0 diff --git a/backend/app/api/main.py b/backend/app/api/main.py index 6630bd0e..841593c8 100644 --- a/backend/app/api/main.py +++ b/backend/app/api/main.py @@ -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"]) diff --git a/backend/app/api/v1/actions.py b/backend/app/api/v1/actions.py new file mode 100644 index 00000000..1251e995 --- /dev/null +++ b/backend/app/api/v1/actions.py @@ -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 diff --git a/backend/app/api/v1/aircraft.py b/backend/app/api/v1/aircraft.py new file mode 100644 index 00000000..76391fef --- /dev/null +++ b/backend/app/api/v1/aircraft.py @@ -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, + } diff --git a/backend/app/api/v1/card_images.py b/backend/app/api/v1/card_images.py index 75029f8f..c5a892f1 100644 --- a/backend/app/api/v1/card_images.py +++ b/backend/app/api/v1/card_images.py @@ -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") diff --git a/backend/app/api/v1/cases.py b/backend/app/api/v1/cases.py new file mode 100644 index 00000000..844df65e --- /dev/null +++ b/backend/app/api/v1/cases.py @@ -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"'}, + ) diff --git a/backend/app/api/v1/data_products.py b/backend/app/api/v1/data_products.py index 34d0190e..a3b6b0e8 100644 --- a/backend/app/api/v1/data_products.py +++ b/backend/app/api/v1/data_products.py @@ -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"], + }, } diff --git a/backend/app/api/v1/datasource_config.py b/backend/app/api/v1/datasource_config.py index 62e4da8a..5f0cbcd8 100644 --- a/backend/app/api/v1/datasource_config.py +++ b/backend/app/api/v1/datasource_config.py @@ -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: diff --git a/backend/app/api/v1/datasources.py b/backend/app/api/v1/datasources.py index c7ebfa04..d972354d 100644 --- a/backend/app/api/v1/datasources.py +++ b/backend/app/api/v1/datasources.py @@ -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")), diff --git a/backend/app/api/v1/disasters.py b/backend/app/api/v1/disasters.py new file mode 100644 index 00000000..e0437d23 --- /dev/null +++ b/backend/app/api/v1/disasters.py @@ -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, + } diff --git a/backend/app/api/v1/earth.py b/backend/app/api/v1/earth.py index 15801a8f..9effd3fc 100644 --- a/backend/app/api/v1/earth.py +++ b/backend/app/api/v1/earth.py @@ -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") diff --git a/backend/app/api/v1/geofences.py b/backend/app/api/v1/geofences.py new file mode 100644 index 00000000..b07d39a6 --- /dev/null +++ b/backend/app/api/v1/geofences.py @@ -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} diff --git a/backend/app/api/v1/gps_jamming.py b/backend/app/api/v1/gps_jamming.py new file mode 100644 index 00000000..7d2102ed --- /dev/null +++ b/backend/app/api/v1/gps_jamming.py @@ -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, + } diff --git a/backend/app/api/v1/incidents.py b/backend/app/api/v1/incidents.py new file mode 100644 index 00000000..ea7844af --- /dev/null +++ b/backend/app/api/v1/incidents.py @@ -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}") diff --git a/backend/app/api/v1/interactables.py b/backend/app/api/v1/interactables.py index 30987971..512ee261 100644 --- a/backend/app/api/v1/interactables.py +++ b/backend/app/api/v1/interactables.py @@ -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, diff --git a/backend/app/api/v1/news.py b/backend/app/api/v1/news.py index 96638207..a3a0f0ee 100644 --- a/backend/app/api/v1/news.py +++ b/backend/app/api/v1/news.py @@ -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, diff --git a/backend/app/api/v1/ontology.py b/backend/app/api/v1/ontology.py new file mode 100644 index 00000000..d0cf2bcd --- /dev/null +++ b/backend/app/api/v1/ontology.py @@ -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() diff --git a/backend/app/api/v1/replay.py b/backend/app/api/v1/replay.py new file mode 100644 index 00000000..c487bc35 --- /dev/null +++ b/backend/app/api/v1/replay.py @@ -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, + } diff --git a/backend/app/api/v1/settings.py b/backend/app/api/v1/settings.py index 194cdf06..b49a2a46 100644 --- a/backend/app/api/v1/settings.py +++ b/backend/app/api/v1/settings.py @@ -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], diff --git a/backend/app/api/v1/system_control.py b/backend/app/api/v1/system_control.py index 2ec89f2d..b34eccee 100644 --- a/backend/app/api/v1/system_control.py +++ b/backend/app/api/v1/system_control.py @@ -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) diff --git a/backend/app/api/v1/vessels.py b/backend/app/api/v1/vessels.py index 461eb5f1..8906fc0a 100644 --- a/backend/app/api/v1/vessels.py +++ b/backend/app/api/v1/vessels.py @@ -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, + } diff --git a/backend/app/api/v1/visualization.py b/backend/app/api/v1/visualization.py index 51e22b37..b5b5f8a9 100644 --- a/backend/app/api/v1/visualization.py +++ b/backend/app/api/v1/visualization.py @@ -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, diff --git a/backend/app/core/data_sources.py b/backend/app/core/data_sources.py index 8c3da868..c1a4fb5f 100644 --- a/backend/app/core/data_sources.py +++ b/backend/app/core/data_sources.py @@ -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", } diff --git a/backend/app/core/data_sources.yaml b/backend/app/core/data_sources.yaml index 0e968c52..54a0536a 100644 --- a/backend/app/core/data_sources.yaml +++ b/backend/app/core/data_sources.yaml @@ -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" diff --git a/backend/app/core/datasource_defaults.py b/backend/app/core/datasource_defaults.py index 460eeffb..cc32a20c 100644 --- a/backend/app/core/datasource_defaults.py +++ b/backend/app/core/datasource_defaults.py @@ -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()} diff --git a/backend/app/data/maritime_chokepoints.json b/backend/app/data/maritime_chokepoints.json new file mode 100644 index 00000000..be275ef4 --- /dev/null +++ b/backend/app/data/maritime_chokepoints.json @@ -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" + } +] diff --git a/backend/app/data/strategic_ports.json b/backend/app/data/strategic_ports.json new file mode 100644 index 00000000..7e93a890 --- /dev/null +++ b/backend/app/data/strategic_ports.json @@ -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"} +] diff --git a/backend/app/db/migration_steps/0008_add_aircraft_and_gps_jamming.py b/backend/app/db/migration_steps/0008_add_aircraft_and_gps_jamming.py new file mode 100644 index 00000000..a66ec03a --- /dev/null +++ b/backend/app/db/migration_steps/0008_add_aircraft_and_gps_jamming.py @@ -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) + """ + ) + ) diff --git a/backend/app/db/migration_steps/0009_add_disaster_and_maritime_intelligence.py b/backend/app/db/migration_steps/0009_add_disaster_and_maritime_intelligence.py new file mode 100644 index 00000000..d135053a --- /dev/null +++ b/backend/app/db/migration_steps/0009_add_disaster_and_maritime_intelligence.py @@ -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 '[]'" + ) + ) diff --git a/backend/app/db/migration_steps/0010_add_ontology_curation.py b/backend/app/db/migration_steps/0010_add_ontology_curation.py new file mode 100644 index 00000000..3c75bc3a --- /dev/null +++ b/backend/app/db/migration_steps/0010_add_ontology_curation.py @@ -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)" + ) + ) diff --git a/backend/app/db/migration_steps/0011_add_geofences_and_incidents.py b/backend/app/db/migration_steps/0011_add_geofences_and_incidents.py new file mode 100644 index 00000000..3ddf289c --- /dev/null +++ b/backend/app/db/migration_steps/0011_add_geofences_and_incidents.py @@ -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)" + ) + ) diff --git a/backend/app/db/migration_steps/0012_add_investigation_cases.py b/backend/app/db/migration_steps/0012_add_investigation_cases.py new file mode 100644 index 00000000..eaf493a4 --- /dev/null +++ b/backend/app/db/migration_steps/0012_add_investigation_cases.py @@ -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) + ) + """ + ) + ) diff --git a/backend/app/db/migration_steps/0013_add_action_requests.py b/backend/app/db/migration_steps/0013_add_action_requests.py new file mode 100644 index 00000000..a4f056d9 --- /dev/null +++ b/backend/app/db/migration_steps/0013_add_action_requests.py @@ -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) + ) + """ + ) + ) diff --git a/backend/app/db/session.py b/backend/app/db/session.py index 671d6e57..b4627c8a 100644 --- a/backend/app/db/session.py +++ b/backend/app/db/session.py @@ -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", diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index d9a1fe77..d82b36ab 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -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", diff --git a/backend/app/models/action_request.py b/backend/app/models/action_request.py new file mode 100644 index 00000000..a70620ae --- /dev/null +++ b/backend/app/models/action_request.py @@ -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, + } diff --git a/backend/app/models/aircraft.py b/backend/app/models/aircraft.py new file mode 100644 index 00000000..22c2533a --- /dev/null +++ b/backend/app/models/aircraft.py @@ -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), + } diff --git a/backend/app/models/disaster.py b/backend/app/models/disaster.py new file mode 100644 index 00000000..8ebdca20 --- /dev/null +++ b/backend/app/models/disaster.py @@ -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, + } diff --git a/backend/app/models/earth_news.py b/backend/app/models/earth_news.py index 763fbc04..e0369a50 100644 --- a/backend/app/models/earth_news.py +++ b/backend/app/models/earth_news.py @@ -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"), diff --git a/backend/app/models/geofence.py b/backend/app/models/geofence.py new file mode 100644 index 00000000..7c04538f --- /dev/null +++ b/backend/app/models/geofence.py @@ -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, + } diff --git a/backend/app/models/gps_jamming.py b/backend/app/models/gps_jamming.py new file mode 100644 index 00000000..88072fd8 --- /dev/null +++ b/backend/app/models/gps_jamming.py @@ -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), + } diff --git a/backend/app/models/investigation_case.py b/backend/app/models/investigation_case.py new file mode 100644 index 00000000..6ac86756 --- /dev/null +++ b/backend/app/models/investigation_case.py @@ -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), + } diff --git a/backend/app/models/maritime_advisory.py b/backend/app/models/maritime_advisory.py new file mode 100644 index 00000000..ba5aa211 --- /dev/null +++ b/backend/app/models/maritime_advisory.py @@ -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), + } diff --git a/backend/app/models/ontology.py b/backend/app/models/ontology.py new file mode 100644 index 00000000..50441fa1 --- /dev/null +++ b/backend/app/models/ontology.py @@ -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", + } diff --git a/backend/app/services/actions.py b/backend/app/services/actions.py new file mode 100644 index 00000000..d73786f8 --- /dev/null +++ b/backend/app/services/actions.py @@ -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 diff --git a/backend/app/services/ai/dag_executor.py b/backend/app/services/ai/dag_executor.py index 81a495c3..90f236aa 100644 --- a/backend/app/services/ai/dag_executor.py +++ b/backend/app/services/ai/dag_executor.py @@ -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( diff --git a/backend/app/services/ai/entity_resolver.py b/backend/app/services/ai/entity_resolver.py index 740cadcf..868bdfa8 100644 --- a/backend/app/services/ai/entity_resolver.py +++ b/backend/app/services/ai/entity_resolver.py @@ -2,12 +2,16 @@ from __future__ import annotations +from datetime import UTC, datetime from typing import Any, Literal from pydantic import BaseModel, ConfigDict, Field +from app.core.logging import get_logger from app.services.compute_catalog import PARTICIPANTS +logger = get_logger(__name__, service="ontology_resolver") + class EntityRef(BaseModel): model_config = ConfigDict(extra="forbid") @@ -25,6 +29,8 @@ class EntityRef(BaseModel): "cable_landing_point", "satellite", "vessel", + "aircraft", + "gps_jamming_cell", "earth_layer", ] label: str @@ -227,3 +233,1173 @@ def resolve_incident_entities( ) return entities, relations + + +# --------------------------------------------------------------------------- +# §3.7 Federated Read-Time Ontology Resolver (`{type}:{id}` across 12 domains) +# --------------------------------------------------------------------------- + +SUPPORTED_ONTOLOGY_TYPES: tuple[str, ...] = ( + "aircraft", + "vessel", + "cable", + "landing_point", + "asn", + "gps_jamming_cell", + "disaster_event", + "chokepoint", + "port", + "compute_center", + "country", + "interactable", +) + +_TYPE_TO_FRESHNESS_DOMAIN: dict[str, str] = { + "aircraft": "aircraft", + "vessel": "vessels", + "cable": "cables", + "landing_point": "cables", + "asn": "bgp", + "gps_jamming_cell": "gps_jamming", + "disaster_event": "disasters", + "compute_center": "compute", + "chokepoint": "vessels", + "port": "vessels", +} + +_STATIC_COUNTRIES: dict[str, dict[str, Any]] = { + "CN": {"name": "中国", "name_en": "China", "lat": 35.86, "lon": 104.19}, + "US": {"name": "美国", "name_en": "United States", "lat": 39.83, "lon": -98.58}, + "JP": {"name": "日本", "name_en": "Japan", "lat": 36.20, "lon": 138.25}, + "KR": {"name": "韩国", "name_en": "South Korea", "lat": 35.91, "lon": 127.77}, + "SG": {"name": "新加坡", "name_en": "Singapore", "lat": 1.35, "lon": 103.82}, + "GB": {"name": "英国", "name_en": "United Kingdom", "lat": 55.38, "lon": -3.44}, + "DE": {"name": "德国", "name_en": "Germany", "lat": 51.16, "lon": 10.45}, + "FR": {"name": "法国", "name_en": "France", "lat": 46.23, "lon": 2.21}, + "AE": {"name": "阿联酋", "name_en": "United Arab Emirates", "lat": 23.42, "lon": 53.85}, + "EG": {"name": "埃及", "name_en": "Egypt", "lat": 26.82, "lon": 30.80}, + "MY": {"name": "马来西亚", "name_en": "Malaysia", "lat": 4.21, "lon": 101.98}, + "ID": {"name": "印度尼西亚", "name_en": "Indonesia", "lat": -0.79, "lon": 113.92}, + "IN": {"name": "印度", "name_en": "India", "lat": 20.59, "lon": 78.96}, + "TW": {"name": "中国台湾", "name_en": "Taiwan", "lat": 23.70, "lon": 120.96}, + "SA": {"name": "沙特阿拉伯", "name_en": "Saudi Arabia", "lat": 23.89, "lon": 45.08}, + "OM": {"name": "阿曼", "name_en": "Oman", "lat": 21.47, "lon": 55.98}, + "TR": {"name": "土耳其", "name_en": "Turkey", "lat": 38.96, "lon": 35.24}, + "ES": {"name": "西班牙", "name_en": "Spain", "lat": 40.46, "lon": -3.75}, + "PA": {"name": "巴拿马", "name_en": "Panama", "lat": 8.54, "lon": -80.78}, + "DJ": {"name": "吉布提", "name_en": "Djibouti", "lat": 11.83, "lon": 42.59}, + "YE": {"name": "也门", "name_en": "Yemen", "lat": 15.55, "lon": 48.52}, + "IR": {"name": "伊朗", "name_en": "Iran", "lat": 32.43, "lon": 53.69}, +} + + +def format_object_id(object_type: str, raw_id: Any) -> str: + otype = str(object_type or "").strip().lower() + if otype not in SUPPORTED_ONTOLOGY_TYPES: + raise ValueError(f"Unsupported ontology object type: {object_type}") + ident = str(raw_id or "").strip() + if not ident: + raise ValueError("Ontology object identifier is required") + return f"{otype}:{ident}" + + +def parse_object_id(object_id: str) -> tuple[str, str]: + raw = str(object_id or "").strip() + if ":" not in raw: + raise ValueError(f"Ontology object_id must follow '{{type}}:{{id}}': {object_id}") + otype, ident = raw.split(":", 1) + otype = otype.strip().lower() + ident = ident.strip() + if otype not in SUPPORTED_ONTOLOGY_TYPES or not ident: + raise ValueError(f"Unsupported ontology object_id: {object_id}") + return otype, ident + + +def _coerce_utc_dt(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) + if isinstance(value, str) and value.strip(): + try: + parsed = datetime.fromisoformat(value.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 _compute_item_freshness( + object_type: str, + observed_at: Any, + ingested_at: Any = None, +) -> dict[str, Any]: + from app.core.time import to_iso8601_utc + from app.services.source_freshness import DOMAIN_SPEC_BY_KEY + + domain = _TYPE_TO_FRESHNESS_DOMAIN.get(object_type) + spec = DOMAIN_SPEC_BY_KEY.get(domain) if domain else None + threshold = spec.threshold_seconds if spec else None + obs_dt = _coerce_utc_dt(observed_at) + ing_dt = _coerce_utc_dt(ingested_at) + now = datetime.now(UTC) + + if object_type in {"chokepoint", "port", "country"}: + return { + "domain": domain or "static_reference", + "state": "fresh", + "is_stale": False, + "age_seconds": 0, + "threshold_seconds": threshold, + "observed_at": to_iso8601_utc(obs_dt) if obs_dt else None, + "ingested_at": to_iso8601_utc(ing_dt) if ing_dt else None, + } + + ref_dt = obs_dt or ing_dt + if ref_dt is None: + return { + "domain": domain, + "state": "offline", + "is_stale": True, + "age_seconds": None, + "threshold_seconds": threshold, + "observed_at": None, + "ingested_at": None, + } + + age = max(0, int((now - ref_dt).total_seconds())) + if threshold is None: + state = "fresh" + is_stale = False + elif age <= threshold: + state = "fresh" + is_stale = False + elif age <= threshold * 4: + state = "stale" + is_stale = True + else: + state = "very_stale" + is_stale = True + + return { + "domain": domain, + "state": state, + "is_stale": is_stale, + "age_seconds": age, + "threshold_seconds": threshold, + "observed_at": to_iso8601_utc(obs_dt) if obs_dt else None, + "ingested_at": to_iso8601_utc(ing_dt) if ing_dt else None, + } + + +def _polygon_centroid(ring: list[list[float]]) -> tuple[float | None, float | None]: + pts = [pt for pt in (ring or []) if isinstance(pt, (list, tuple)) and len(pt) >= 2] + if not pts: + return None, None + lon = sum(float(pt[0]) for pt in pts) / len(pts) + lat = sum(float(pt[1]) for pt in pts) / len(pts) + return round(lat, 5), round(lon, 5) + + +def _cable_centroid(extra: dict[str, Any]) -> tuple[float | None, float | None]: + coords = extra.get("coordinates") or (extra.get("geometry") or {}).get("coordinates") + pts: list[tuple[float, float]] = [] + if isinstance(coords, list) and coords: + if isinstance(coords[0], (list, tuple)) and coords[0] and isinstance(coords[0][0], (int, float)): + for pt in coords: + if isinstance(pt, (list, tuple)) and len(pt) >= 2: + pts.append((float(pt[1]), float(pt[0]))) + else: + for line in coords: + if isinstance(line, list): + for pt in line: + if isinstance(pt, (list, tuple)) and len(pt) >= 2: + pts.append((float(pt[1]), float(pt[0]))) + if not pts: + return None, None + mid = pts[len(pts) // 2] + return round(mid[0], 5), round(mid[1], 5) + + +def _country_code_from_name(country_val: str | None) -> str | None: + if not country_val: + return None + val = str(country_val).strip() + upper = val.upper() + if upper in _STATIC_COUNTRIES or upper in PARTICIPANTS: + return upper + low = val.lower() + for code, meta in PARTICIPANTS.items(): + if len(code) <= 3 and ( + str(meta.get("name_zh") or "").lower() == low + or str(meta.get("name_en") or "").lower() == low + ): + return code + for code, meta in _STATIC_COUNTRIES.items(): + if meta["name"].lower() == low or meta["name_en"].lower() == low: + return code + return None + + +async def _load_aliases_for_object(db: Any, object_id: str) -> list[dict[str, Any]]: + if not hasattr(db, "execute"): + return [] + from sqlalchemy import select + from app.models.ontology import OntologyEntityAlias + + try: + rows = list( + ( + await db.execute( + select(OntologyEntityAlias).where(OntologyEntityAlias.object_id == object_id) + ) + ) + .scalars() + .all() + ) + return [r.to_dict() for r in rows] + except Exception: + return [] + + +async def resolve_alias_to_object_ids(db: Any, alias_text: str) -> list[str]: + """Look up canonical `{type}:{id}` identifiers associated with a curated alias.""" + if not hasattr(db, "execute"): + return [] + from sqlalchemy import func as sql_func, select + from app.models.ontology import OntologyEntityAlias + + cleaned = str(alias_text or "").strip().lower() + if not cleaned: + return [] + try: + rows = list( + ( + await db.execute( + select(OntologyEntityAlias.object_id).where( + sql_func.lower(OntologyEntityAlias.alias) == cleaned + ) + ) + ) + .scalars() + .all() + ) + return list(dict.fromkeys(str(r) for r in rows if r)) + except Exception: + return [] + + +async def resolve_ontology_object(db: Any, object_id: str) -> dict[str, Any] | None: + """Resolve a canonical `{type}:{id}` (or curated alias) on the fly across 12 domains.""" + from sqlalchemy import desc, select + + raw = str(object_id or "").strip() + if ":" not in raw: + aliased = await resolve_alias_to_object_ids(db, raw) + if not aliased: + return None + raw = aliased[0] + + otype, ident = parse_object_id(raw) + resolved: dict[str, Any] | None = None + + if otype == "aircraft" and hasattr(db, "execute"): + from app.models.aircraft import AircraftCurrentState + + row = ( + await db.execute( + select(AircraftCurrentState).where(AircraftCurrentState.icao24 == ident.lower()) + ) + ).scalars().first() or ( + await db.execute( + select(AircraftCurrentState).where(AircraftCurrentState.icao24 == ident) + ) + ).scalars().first() + if row: + data = row.to_dict() + resolved = { + "object_id": format_object_id("aircraft", row.icao24), + "object_type": "aircraft", + "label": str(row.callsign or row.icao24), + "label_en": str(row.callsign or row.icao24), + "lat": float(row.lat), + "lon": float(row.lon), + "attributes": data, + "provenance": { + "source": row.source, + "observed_at": data["observed_at"], + "ingested_at": data["ingested_at"], + }, + "freshness": _compute_item_freshness("aircraft", row.observed_at, row.ingested_at), + } + + elif otype == "vessel" and hasattr(db, "execute"): + from app.models.vessel import VesselCurrentState + from app.services.maritime_geography import find_chokepoint_for_point + from app.services.vessel_types import classify_military_vessel, is_cable_repair_vessel + + try: + mmsi_val = int(ident) + except ValueError: + mmsi_val = None + if mmsi_val is not None: + row = ( + await db.execute(select(VesselCurrentState).where(VesselCurrentState.mmsi == mmsi_val)) + ).scalars().first() + if row: + from app.core.time import to_iso8601_utc + + m_role, m_src = classify_military_vessel( + vessel_type=row.vessel_type_name or row.vessel_type, + name=row.name, + callsign=row.callsign, + ) + is_cs, cs_src = is_cable_repair_vessel(vessel_type=row.vessel_type, name=row.name) + cp = find_chokepoint_for_point(float(row.lat), float(row.lon)) + attrs = row.to_dict() + attrs["received_at"] = to_iso8601_utc(row.observed_at) + attrs["observed_at"] = attrs["received_at"] + attrs["military_role"] = m_role + attrs["military_source"] = m_src + attrs["is_warship"] = m_role is not None + attrs["is_cable_ship"] = bool(is_cs) + attrs["cable_ship_source"] = cs_src + attrs["chokepoint_id"] = cp["id"] if cp else None + resolved = { + "object_id": format_object_id("vessel", row.mmsi), + "object_type": "vessel", + "label": str(row.name or row.mmsi), + "label_en": str(row.name or row.mmsi), + "lat": float(row.lat), + "lon": float(row.lon), + "attributes": attrs, + "provenance": { + "source": row.source, + "observed_at": attrs["observed_at"], + "ingested_at": to_iso8601_utc(row.updated_at), + }, + "freshness": _compute_item_freshness("vessel", row.observed_at, row.updated_at), + } + + elif otype == "cable" and hasattr(db, "execute"): + from app.core.time import to_iso8601_utc + from app.models.collected_data import CollectedData + + rows = list( + ( + await db.execute( + select(CollectedData) + .where(CollectedData.source == "arcgis_cables", CollectedData.is_current.is_(True)) + .limit(1500) + ) + ) + .scalars() + .all() + ) + matched_row = None + for r in rows: + extra = r.extra_data or {} + cand_ids = { + str(extra.get("cable_id") or "").strip(), + str(extra.get("id") or "").strip(), + str(r.source_id or "").strip(), + str(r.name or "").strip(), + } + if ident in cand_ids or ident.lower() in {c.lower() for c in cand_ids if c}: + matched_row = r + break + if matched_row: + extra = matched_row.extra_data or {} + lat, lon = _cable_centroid(extra) + cid = str(extra.get("cable_id") or matched_row.source_id or matched_row.name or ident) + resolved = { + "object_id": format_object_id("cable", cid), + "object_type": "cable", + "label": str(matched_row.name or cid), + "label_en": str(matched_row.name or cid), + "lat": lat, + "lon": lon, + "attributes": { + "cable_id": cid, + "name": matched_row.name, + "owners": extra.get("owners"), + "rfs": extra.get("rfs"), + "length": extra.get("length"), + "is_planned": extra.get("is_planned"), + "geometry_type": (extra.get("geometry") or {}).get("type"), + }, + "provenance": { + "source": matched_row.source, + "observed_at": to_iso8601_utc(matched_row.reference_date or matched_row.collected_at), + "ingested_at": to_iso8601_utc(matched_row.collected_at), + }, + "freshness": _compute_item_freshness("cable", matched_row.reference_date or matched_row.collected_at, matched_row.collected_at), + } + + elif otype == "landing_point" and hasattr(db, "execute"): + from app.core.time import to_iso8601_utc + from app.models.collected_data import CollectedData + + rows = list( + ( + await db.execute( + select(CollectedData) + .where(CollectedData.source == "arcgis_landing_points", CollectedData.is_current.is_(True)) + .limit(2500) + ) + ) + .scalars() + .all() + ) + matched_row = None + for r in rows: + extra = r.extra_data or {} + cand_ids = { + str(extra.get("city_id") or "").strip(), + str(extra.get("id") or "").strip(), + str(r.source_id or "").strip(), + str(r.name or "").strip(), + } + if ident in cand_ids or ident.lower() in {c.lower() for c in cand_ids if c}: + matched_row = r + break + if matched_row: + extra = matched_row.extra_data or {} + lat = float(extra["latitude"]) if extra.get("latitude") is not None else None + lon = float(extra["longitude"]) if extra.get("longitude") is not None else None + lid = str(extra.get("city_id") or matched_row.source_id or matched_row.name or ident) + resolved = { + "object_id": format_object_id("landing_point", lid), + "object_type": "landing_point", + "label": str(matched_row.name or lid), + "label_en": str(matched_row.name or lid), + "lat": lat, + "lon": lon, + "attributes": { + "city_id": extra.get("city_id"), + "country": extra.get("country"), + "city_name": matched_row.name, + }, + "provenance": { + "source": matched_row.source, + "observed_at": to_iso8601_utc(matched_row.collected_at), + "ingested_at": to_iso8601_utc(matched_row.collected_at), + }, + "freshness": _compute_item_freshness("landing_point", matched_row.collected_at, matched_row.collected_at), + } + + elif otype == "asn" and hasattr(db, "execute"): + from app.core.time import to_iso8601_utc + from app.models.bgp_incident import BGPIncident + from app.models.collected_data import CollectedData + + clean_num = ident.upper().removeprefix("AS").strip() + canonical_asn = f"AS{clean_num}" + incidents = list( + (await db.execute(select(BGPIncident).order_by(desc(BGPIncident.started_at)).limit(100))) + .scalars() + .all() + ) + matched_incidents = [ + inc + for inc in incidents + if clean_num in [str(a).upper().removeprefix("AS") for a in (inc.affected_asns or [])] + ] + geo_rows = list( + ( + await db.execute( + select(CollectedData) + .where( + CollectedData.source == "iptoasn_prefix_geo", + CollectedData.is_current.is_(True), + ) + .limit(500) + ) + ) + .scalars() + .all() + ) + matched_geo = [ + r for r in geo_rows + if str((r.extra_data or {}).get("asn") or r.source_id or "").upper().removeprefix("AS") == clean_num + ] + if matched_incidents or matched_geo: + first_inc = matched_incidents[0] if matched_incidents else None + first_geo = matched_geo[0] if matched_geo else None + obs_ts = first_inc.started_at if first_inc else (first_geo.collected_at if first_geo else None) + extra = first_geo.extra_data or {} if first_geo else {} + resolved = { + "object_id": format_object_id("asn", canonical_asn), + "object_type": "asn", + "label": str(extra.get("as_name") or canonical_asn), + "label_en": str(extra.get("as_name") or canonical_asn), + "lat": float(extra["latitude"]) if extra.get("latitude") is not None else None, + "lon": float(extra["longitude"]) if extra.get("longitude") is not None else None, + "attributes": { + "asn": canonical_asn, + "country": extra.get("country"), + "incident_count": len(matched_incidents), + "latest_incident_key": first_inc.incident_key if first_inc else None, + }, + "provenance": { + "source": "bgp_incidents" if first_inc else "iptoasn_prefix_geo", + "observed_at": to_iso8601_utc(obs_ts), + "ingested_at": to_iso8601_utc(first_inc.created_at if first_inc else (first_geo.collected_at if first_geo else None)), + }, + "freshness": _compute_item_freshness("asn", obs_ts, obs_ts), + } + + elif otype == "gps_jamming_cell" and hasattr(db, "execute"): + from app.models.gps_jamming import GPSJammingCell + + row = ( + await db.execute( + select(GPSJammingCell) + .where(GPSJammingCell.h3_index == ident) + .order_by(desc(GPSJammingCell.observed_date)) + .limit(1) + ) + ).scalars().first() + if row: + data = row.to_dict() + resolved = { + "object_id": format_object_id("gps_jamming_cell", row.h3_index), + "object_type": "gps_jamming_cell", + "label": f"GNSS Jamming {row.h3_index} ({row.level})", + "label_en": f"GNSS Jamming {row.h3_index} ({row.level})", + "lat": float(row.lat), + "lon": float(row.lon), + "attributes": data, + "provenance": { + "source": row.source, + "observed_at": row.observed_date, + "ingested_at": data["ingested_at"], + }, + "freshness": _compute_item_freshness("gps_jamming_cell", row.ingested_at, row.ingested_at), + } + + elif otype == "disaster_event" and hasattr(db, "execute"): + from app.models.disaster import DisasterEvent + + row = None + if ident.isdigit(): + row = ( + await db.execute(select(DisasterEvent).where(DisasterEvent.id == int(ident))) + ).scalars().first() + if row is None: + row = ( + await db.execute( + select(DisasterEvent).where(DisasterEvent.source_event_id == ident) + ) + ).scalars().first() + if row: + data = row.to_dict() + resolved = { + "object_id": format_object_id("disaster_event", row.id), + "object_type": "disaster_event", + "label": row.title, + "label_en": row.title, + "lat": float(row.lat), + "lon": float(row.lon), + "attributes": data, + "provenance": { + "source": row.source, + "observed_at": data["observed_at"], + "ingested_at": data["ingested_at"], + }, + "freshness": _compute_item_freshness("disaster_event", row.observed_at, row.ingested_at), + } + + elif otype == "chokepoint": + from app.services.maritime_geography import load_chokepoints + + for cp in load_chokepoints(): + if ( + str(cp.get("id") or "").lower() == ident.lower() + or str(cp.get("name") or "").lower() == ident.lower() + or str(cp.get("name_en") or "").lower() == ident.lower() + ): + lat, lon = _polygon_centroid(cp.get("polygon") or []) + resolved = { + "object_id": format_object_id("chokepoint", cp["id"]), + "object_type": "chokepoint", + "label": str(cp.get("name_zh") or cp.get("name") or cp["id"]), + "label_en": str(cp.get("name") or cp["id"]), + "lat": lat, + "lon": lon, + "attributes": cp, + "provenance": { + "source": str(cp.get("source") or "maritime_chokepoints"), + "observed_at": None, + "ingested_at": None, + }, + "freshness": _compute_item_freshness("chokepoint", None, None), + } + break + + elif otype == "port": + from app.services.maritime_geography import load_strategic_ports + + for port in load_strategic_ports(): + if ( + str(port.get("id") or "").lower() == ident.lower() + or str(port.get("name") or "").lower() == ident.lower() + or str(port.get("name_en") or "").lower() == ident.lower() + ): + resolved = { + "object_id": format_object_id("port", port["id"]), + "object_type": "port", + "label": str(port.get("name_zh") or port.get("name") or port["id"]), + "label_en": str(port.get("name") or port["id"]), + "lat": float(port["lat"]), + "lon": float(port["lon"]), + "attributes": port, + "provenance": { + "source": str(port.get("source") or "strategic_ports"), + "observed_at": None, + "ingested_at": None, + }, + "freshness": _compute_item_freshness("port", None, None), + } + break + + elif otype == "compute_center" and hasattr(db, "execute"): + from app.core.time import to_iso8601_utc + from app.models.compute_center_location import ComputeCenterLocationRecord + + row = None + if ident.isdigit(): + row = ( + await db.execute( + select(ComputeCenterLocationRecord).where( + ComputeCenterLocationRecord.id == int(ident) + ) + ) + ).scalars().first() + if row is None: + row = ( + await db.execute( + select(ComputeCenterLocationRecord) + .where(ComputeCenterLocationRecord.source_id == ident) + .limit(1) + ) + ).scalars().first() + if row: + attrs = row.to_location_dict() + resolved = { + "object_id": format_object_id("compute_center", row.id), + "object_type": "compute_center", + "label": str(row.name or row.source_id), + "label_en": str(row.name or row.source_id), + "lat": float(row.latitude) if row.latitude is not None else None, + "lon": float(row.longitude) if row.longitude is not None else None, + "attributes": attrs, + "provenance": { + "source": row.source, + "observed_at": to_iso8601_utc(row.verified_at or row.updated_at), + "ingested_at": to_iso8601_utc(row.updated_at or row.created_at), + }, + "freshness": _compute_item_freshness("compute_center", row.verified_at or row.updated_at, row.updated_at), + } + + elif otype == "country": + code = ident.upper() + part = PARTICIPANTS.get(code) + static = _STATIC_COUNTRIES.get(code) + if part or static: + resolved = { + "object_id": format_object_id("country", code), + "object_type": "country", + "label": str((part or {}).get("name_zh") or (static or {}).get("name") or code), + "label_en": str((part or {}).get("name_en") or (static or {}).get("name_en") or code), + "lat": (static or {}).get("lat"), + "lon": (static or {}).get("lon"), + "attributes": {"country_code": code, **(part or {}), **(static or {})}, + "provenance": { + "source": "compute_catalog_participants" if part else "country_reference", + "observed_at": None, + "ingested_at": None, + }, + "freshness": _compute_item_freshness("country", None, None), + } + + elif otype == "interactable" and hasattr(db, "execute"): + from app.core.time import to_iso8601_utc + from app.models.earth_interactable import EarthInteractable + + row = ( + await db.execute( + select(EarthInteractable).where( + EarthInteractable.id == ident, + EarthInteractable.is_deleted.is_(False), + ) + ) + ).scalars().first() + if row: + resolved = { + "object_id": format_object_id("interactable", row.id), + "object_type": "interactable", + "label": str(row.label or row.id), + "label_en": str(row.label or row.id), + "lat": float(row.latitude), + "lon": float(row.longitude), + "attributes": { + "id": row.id, + "layer": row.layer, + "kind": row.kind, + "description": row.description, + "altitude": row.altitude, + "properties": row.properties or {}, + "revision": row.revision, + }, + "provenance": { + "source": str((row.properties or {}).get("source") or f"earth_interactable:{row.kind}"), + "observed_at": to_iso8601_utc(row.updated_at or row.created_at), + "ingested_at": to_iso8601_utc(row.created_at), + }, + "freshness": _compute_item_freshness("interactable", row.updated_at or row.created_at, row.created_at), + } + + if resolved is None: + return None + resolved["aliases"] = await _load_aliases_for_object(db, resolved["object_id"]) + return resolved + + +async def _derive_one_hop( + db: Any, + node: dict[str, Any], + *, + radius_km: float, + limit: int, +) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + """Derive 1-hop topology, spatial, and analyst-asserted neighbors for a resolved node.""" + from sqlalchemy import or_, select + from app.models.aircraft import AircraftCurrentState + from app.models.collected_data import CollectedData + from app.models.compute_center_location import ComputeCenterLocationRecord + from app.models.disaster import DisasterEvent + from app.models.earth_interactable import EarthInteractable + from app.models.gps_jamming import GPSJammingCell + from app.models.ontology import AnalystLink + from app.models.vessel import VesselCurrentState + from app.services.maritime_geography import ( + load_chokepoints, + load_strategic_ports, + point_in_polygon, + ) + from app.services.nga_advisories import haversine_km + + oid = str(node["object_id"]) + otype = str(node["object_type"]) + lat = node.get("lat") + lon = node.get("lon") + attrs = node.get("attributes") or {} + + neighbors: dict[str, dict[str, Any]] = {} + edges: list[dict[str, Any]] = [] + seen_edges: set[tuple[str, str, str, str]] = set() + + async def _attach(target_id: str, rel_type: str, rel_source: str, note: str, evidence_ids: list[str] | None = None) -> None: + if len(edges) >= limit or target_id == oid: + return + sig = (oid, target_id, rel_type, rel_source) + if sig in seen_edges: + return + if target_id not in neighbors: + target_obj = await resolve_ontology_object(db, target_id) + if not target_obj: + return + neighbors[target_id] = target_obj + seen_edges.add(sig) + edges.append( + { + "from_object_id": oid, + "to_object_id": target_id, + "relation_type": rel_type, + "relation_source": rel_source, + "note": note, + "evidence_ids": evidence_ids or [], + } + ) + + # 1. Analyst-asserted links (always merged cleanly) + if hasattr(db, "execute"): + try: + analyst_rows = list( + ( + await db.execute( + select(AnalystLink).where( + AnalystLink.status == "active", + or_( + AnalystLink.from_object_id == oid, + AnalystLink.to_object_id == oid, + ), + ) + ) + ) + .scalars() + .all() + ) + for link in analyst_rows: + other_id = link.to_object_id if link.from_object_id == oid else link.from_object_id + if other_id not in neighbors: + resolved_other = await resolve_ontology_object(db, other_id) + if not resolved_other: + # Preserve curated reference placeholder if underlying external entity isn't in local DB + parsed_type = other_id.split(":", 1)[0] if ":" in other_id else "interactable" + resolved_other = { + "object_id": other_id, + "object_type": parsed_type, + "label": other_id, + "label_en": other_id, + "lat": None, + "lon": None, + "attributes": {}, + "aliases": [], + "provenance": {"source": "analyst_link", "observed_at": None, "ingested_at": None}, + "freshness": _compute_item_freshness(parsed_type, None, None), + } + neighbors[other_id] = resolved_other + edges.append( + { + "id": f"analyst:{link.id}", + "from_object_id": link.from_object_id, + "to_object_id": link.to_object_id, + "relation_type": link.relation_type, + "relation_source": "analyst_asserted", + "note": link.note, + "evidence_ids": list(link.evidence_ids or []), + } + ) + except Exception as exc: + logger.debug_event( + "Skipped analyst link lookup", + event="ontology.analyst_links.skipped", + context={"object_id": oid, "error": str(exc)}, + ) + + # 2. Derived topology edges (cable <-> landing_point <-> country <-> compute_center / asn) + if otype == "cable" and hasattr(db, "execute"): + cable_id = str(attrs.get("cable_id") or oid.split(":", 1)[1]) + rel_rows = list( + ( + await db.execute( + select(CollectedData).where( + CollectedData.source == "arcgis_cable_landing_relation", + CollectedData.is_current.is_(True), + ) + ) + ) + .scalars() + .all() + ) + for rel in rel_rows: + extra = rel.extra_data or {} + if str(extra.get("cable_id") or "") == cable_id and extra.get("city_id") is not None: + await _attach( + format_object_id("landing_point", extra["city_id"]), + "cable_lands_at", + "derived_topology", + "海底光缆-登陆站拓扑关系", + ) + + elif otype == "landing_point": + country_code = _country_code_from_name(attrs.get("country")) + if country_code: + await _attach( + format_object_id("country", country_code), + "located_in_country", + "derived_topology", + "登陆站所属国家/地区", + ) + city_id = str(attrs.get("city_id") or oid.split(":", 1)[1]) + if hasattr(db, "execute"): + rel_rows = list( + ( + await db.execute( + select(CollectedData).where( + CollectedData.source == "arcgis_cable_landing_relation", + CollectedData.is_current.is_(True), + ) + ) + ) + .scalars() + .all() + ) + for rel in rel_rows: + extra = rel.extra_data or {} + if str(extra.get("city_id") or "") == city_id and extra.get("cable_id") is not None: + await _attach( + format_object_id("cable", extra["cable_id"]), + "cable_lands_at", + "derived_topology", + "登陆站承载海底光缆", + ) + + elif otype == "compute_center": + cc = _country_code_from_name(attrs.get("country")) + if cc: + await _attach( + format_object_id("country", cc), + "hosted_in_country", + "derived_topology", + "算力中心所属国家/地区", + ) + + elif otype == "asn": + cc = _country_code_from_name(attrs.get("country")) + if cc: + await _attach( + format_object_id("country", cc), + "asn_registered_in_country", + "derived_topology", + "自治系统注册国家/地区", + ) + + elif otype == "country" and hasattr(db, "execute"): + cc = oid.split(":", 1)[1].upper() + lp_rows = list( + ( + await db.execute( + select(CollectedData).where( + CollectedData.source == "arcgis_landing_points", + CollectedData.is_current.is_(True), + ).limit(500) + ) + ) + .scalars() + .all() + ) + for lp in lp_rows: + extra = lp.extra_data or {} + if _country_code_from_name(extra.get("country")) == cc: + lid = str(extra.get("city_id") or lp.source_id or lp.name or "") + if lid: + await _attach( + format_object_id("landing_point", lid), + "located_in_country", + "derived_topology", + "境内海缆登陆站", + ) + comp_rows = list( + (await db.execute(select(ComputeCenterLocationRecord).limit(300))).scalars().all() + ) + for comp in comp_rows: + if _country_code_from_name(comp.country) == cc: + await _attach( + format_object_id("compute_center", comp.id), + "hosted_in_country", + "derived_topology", + "境内算力中心", + ) + for port in load_strategic_ports(): + if str(port.get("country") or "").upper() == cc: + await _attach( + format_object_id("port", port["id"]), + "port_in_country", + "derived_topology", + "境内战略港口", + ) + geo_rows = list( + ( + await db.execute( + select(CollectedData) + .where( + CollectedData.source == "iptoasn_prefix_geo", + CollectedData.is_current.is_(True), + ) + .limit(400) + ) + ) + .scalars() + .all() + ) + seen_asns: set[str] = set() + for gr in geo_rows: + extra = gr.extra_data or {} + if _country_code_from_name(extra.get("country")) == cc: + raw_asn = str(extra.get("asn") or gr.source_id or "").upper().removeprefix("AS").strip() + if raw_asn and raw_asn not in seen_asns: + seen_asns.add(raw_asn) + await _attach( + format_object_id("asn", f"AS{raw_asn}"), + "asn_registered_in_country", + "derived_topology", + "境内注册自治系统", + ) + + elif otype == "port": + cc = _country_code_from_name(attrs.get("country")) + if cc: + await _attach( + format_object_id("country", cc), + "port_in_country", + "derived_topology", + "港口所属国家", + ) + + # 3. Derived spatial edges when object has coordinates + if isinstance(lat, (int, float)) and isinstance(lon, (int, float)): + for cp in load_chokepoints(): + cp_id = str(cp.get("id") or "") + if not cp_id or (otype == "chokepoint" and oid == f"chokepoint:{cp_id}"): + continue + if point_in_polygon(float(lat), float(lon), cp.get("polygon") or []): + await _attach( + format_object_id("chokepoint", cp_id), + "inside_chokepoint", + "derived_spatial", + "位于咽喉要道多边形范围内", + ) + else: + cp_lat, cp_lon = _polygon_centroid(cp.get("polygon") or []) + if cp_lat is not None and cp_lon is not None and haversine_km(float(lat), float(lon), cp_lat, cp_lon) <= radius_km: + await _attach( + format_object_id("chokepoint", cp_id), + "near_chokepoint", + "derived_spatial", + f"距离咽喉要道 <= {int(radius_km)} km", + ) + + for port in load_strategic_ports(): + if haversine_km(float(lat), float(lon), float(port["lat"]), float(port["lon"])) <= radius_km: + await _attach( + format_object_id("port", port["id"]), + "near_port", + "derived_spatial", + f"距离战略港口 <= {int(radius_km)} km", + ) + + if hasattr(db, "execute"): + for ac in list((await db.execute(select(AircraftCurrentState).limit(250))).scalars().all()): + if haversine_km(float(lat), float(lon), float(ac.lat), float(ac.lon)) <= radius_km: + await _attach( + format_object_id("aircraft", ac.icao24), + "spatial_co_location", + "derived_spatial", + f"空间邻近飞行器 (<= {int(radius_km)} km)", + ) + for vs in list((await db.execute(select(VesselCurrentState).limit(250))).scalars().all()): + if haversine_km(float(lat), float(lon), float(vs.lat), float(vs.lon)) <= radius_km: + await _attach( + format_object_id("vessel", vs.mmsi), + "spatial_co_location", + "derived_spatial", + f"空间邻近船舶 (<= {int(radius_km)} km)", + ) + for gz in list((await db.execute(select(GPSJammingCell).limit(150))).scalars().all()): + if haversine_km(float(lat), float(lon), float(gz.lat), float(gz.lon)) <= radius_km: + await _attach( + format_object_id("gps_jamming_cell", gz.h3_index), + "spatial_co_location", + "derived_spatial", + f"邻近 GNSS 干扰网格 (<= {int(radius_km)} km)", + ) + for ds in list((await db.execute(select(DisasterEvent).where(DisasterEvent.duplicate_of.is_(None)).limit(150))).scalars().all()): + if haversine_km(float(lat), float(lon), float(ds.lat), float(ds.lon)) <= radius_km: + await _attach( + format_object_id("disaster_event", ds.id), + "spatial_co_location", + "derived_spatial", + f"邻近自然灾害事件 (<= {int(radius_km)} km)", + ) + for comp in list((await db.execute(select(ComputeCenterLocationRecord).limit(150))).scalars().all()): + if comp.latitude is not None and comp.longitude is not None: + if haversine_km(float(lat), float(lon), float(comp.latitude), float(comp.longitude)) <= radius_km: + await _attach( + format_object_id("compute_center", comp.id), + "spatial_co_location", + "derived_spatial", + f"邻近算力中心 (<= {int(radius_km)} km)", + ) + for obj in list((await db.execute(select(EarthInteractable).where(EarthInteractable.is_deleted.is_(False)).limit(150))).scalars().all()): + if haversine_km(float(lat), float(lon), float(obj.latitude), float(obj.longitude)) <= radius_km: + await _attach( + format_object_id("interactable", obj.id), + "spatial_co_location", + "derived_spatial", + f"邻近地球标绘对象 (<= {int(radius_km)} km)", + ) + if otype != "cable": + cable_rows = list( + ( + await db.execute( + select(CollectedData) + .where(CollectedData.source == "arcgis_cables", CollectedData.is_current.is_(True)) + .limit(300) + ) + ) + .scalars() + .all() + ) + for c_row in cable_rows: + extra = c_row.extra_data or {} + clat, clon = _cable_centroid(extra) + if clat is not None and clon is not None and haversine_km(float(lat), float(lon), clat, clon) <= max(radius_km, 250.0): + cid = str(extra.get("cable_id") or c_row.source_id or c_row.name or "") + if cid: + await _attach( + format_object_id("cable", cid), + "near_submarine_cable", + "derived_spatial", + "邻近海底光缆路径(仅空间邻近线索)", + ) + + return list(neighbors.values()), edges + + +async def resolve_ontology_neighborhood( + db: Any, + object_id: str, + *, + depth: int = 1, + radius_km: float = 150.0, + limit: int = 40, +) -> dict[str, Any] | None: + """Resolve 1-to-2 hop ontology neighborhood with explicit `relation_source` tags.""" + root = await resolve_ontology_object(db, object_id) + if root is None: + return None + + clamped_depth = max(1, min(int(depth or 1), 2)) + nodes_map: dict[str, dict[str, Any]] = {root["object_id"]: root} + all_edges: list[dict[str, Any]] = [] + seen_edge_keys: set[tuple[str, str, str, str]] = set() + frontier: list[dict[str, Any]] = [root] + visited: set[str] = {root["object_id"]} + + for _hop in range(clamped_depth): + next_frontier: list[dict[str, Any]] = [] + for current in frontier: + hop_nodes, hop_edges = await _derive_one_hop( + db, current, radius_km=radius_km, limit=limit + ) + for node in hop_nodes: + nid = str(node["object_id"]) + if nid not in nodes_map: + nodes_map[nid] = node + if nid not in visited: + visited.add(nid) + next_frontier.append(node) + for edge in hop_edges: + key = ( + str(edge["from_object_id"]), + str(edge["to_object_id"]), + str(edge["relation_type"]), + str(edge["relation_source"]), + ) + if key not in seen_edge_keys: + seen_edge_keys.add(key) + all_edges.append(edge) + frontier = next_frontier[:15] + if not frontier: + break + + return { + "root": root, + "depth": clamped_depth, + "nodes": list(nodes_map.values()), + "edges": all_edges, + "relation_sources": sorted({e["relation_source"] for e in all_edges}), + } diff --git a/backend/app/services/ai/presentation_compiler.py b/backend/app/services/ai/presentation_compiler.py index 9569c0f0..1d1ea6c1 100644 --- a/backend/app/services/ai/presentation_compiler.py +++ b/backend/app/services/ai/presentation_compiler.py @@ -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) diff --git a/backend/app/services/ai/proactive_pipeline.py b/backend/app/services/ai/proactive_pipeline.py index e0b9c867..347eaeb3 100644 --- a/backend/app/services/ai/proactive_pipeline.py +++ b/backend/app/services/ai/proactive_pipeline.py @@ -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, + } diff --git a/backend/app/services/ai/scene_directives.py b/backend/app/services/ai/scene_directives.py index 5b6e87ed..a40673fc 100644 --- a/backend/app/services/ai/scene_directives.py +++ b/backend/app/services/ai/scene_directives.py @@ -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 `...` 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 [] diff --git a/backend/app/services/ai/tool_registry.py b/backend/app/services/ai/tool_registry.py index 1837f337..caea234c 100644 --- a/backend/app/services/ai/tool_registry.py +++ b/backend/app/services/ai/tool_registry.py @@ -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": [], + } diff --git a/backend/app/services/ai/workflow_registry.py b/backend/app/services/ai/workflow_registry.py index 422f8dd2..58464a48 100644 --- a/backend/app/services/ai/workflow_registry.py +++ b/backend/app/services/ai/workflow_registry.py @@ -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` 情报盲区;结尾附 输出 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 的 。" + ), + 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]] = { diff --git a/backend/app/services/aircraft_aggregation.py b/backend/app/services/aircraft_aggregation.py new file mode 100644 index 00000000..225bf55a --- /dev/null +++ b/backend/app/services/aircraft_aggregation.py @@ -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 diff --git a/backend/app/services/aircraft_registry.py b/backend/app/services/aircraft_registry.py new file mode 100644 index 00000000..e4cdb4be --- /dev/null +++ b/backend/app/services/aircraft_registry.py @@ -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, + } diff --git a/backend/app/services/aircraft_types.py b/backend/app/services/aircraft_types.py new file mode 100644 index 00000000..9440256f --- /dev/null +++ b/backend/app/services/aircraft_types.py @@ -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, + } diff --git a/backend/app/services/api_keys.py b/backend/app/services/api_keys.py index cffaa151..9d6bd3ae 100644 --- a/backend/app/services/api_keys.py +++ b/backend/app/services/api_keys.py @@ -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", diff --git a/backend/app/services/collectors/__init__.py b/backend/app/services/collectors/__init__.py index f2ce6a52..2b710a8d 100644 --- a/backend/app/services/collectors/__init__.py +++ b/backend/app/services/collectors/__init__.py @@ -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", ] diff --git a/backend/app/services/collectors/adsb_lol.py b/backend/app/services/collectors/adsb_lol.py new file mode 100644 index 00000000..0d2524d2 --- /dev/null +++ b/backend/app/services/collectors/adsb_lol.py @@ -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"] diff --git a/backend/app/services/collectors/aircraft_registry.py b/backend/app/services/collectors/aircraft_registry.py new file mode 100644 index 00000000..2f98a0f4 --- /dev/null +++ b/backend/app/services/collectors/aircraft_registry.py @@ -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 diff --git a/backend/app/services/collectors/disasters.py b/backend/app/services/collectors/disasters.py new file mode 100644 index 00000000..0039129a --- /dev/null +++ b/backend/app/services/collectors/disasters.py @@ -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} diff --git a/backend/app/services/collectors/gps_jamming.py b/backend/app/services/collectors/gps_jamming.py new file mode 100644 index 00000000..17e19150 --- /dev/null +++ b/backend/app/services/collectors/gps_jamming.py @@ -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 diff --git a/backend/app/services/collectors/nga_warnings.py b/backend/app/services/collectors/nga_warnings.py new file mode 100644 index 00000000..9831013b --- /dev/null +++ b/backend/app/services/collectors/nga_warnings.py @@ -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} diff --git a/backend/app/services/collectors/opensky.py b/backend/app/services/collectors/opensky.py new file mode 100644 index 00000000..18520771 --- /dev/null +++ b/backend/app/services/collectors/opensky.py @@ -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"] diff --git a/backend/app/services/credential_guides.py b/backend/app/services/credential_guides.py index eddc208d..adb2b6cd 100644 --- a/backend/app/services/credential_guides.py +++ b/backend/app/services/credential_guides.py @@ -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, } diff --git a/backend/app/services/data_jobs.py b/backend/app/services/data_jobs.py index ff5f5483..af2d95f0 100644 --- a/backend/app/services/data_jobs.py +++ b/backend/app/services/data_jobs.py @@ -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 diff --git a/backend/app/services/datasource_connectivity.py b/backend/app/services/datasource_connectivity.py index 6ade43aa..d97b2ee0 100644 --- a/backend/app/services/datasource_connectivity.py +++ b/backend/app/services/datasource_connectivity.py @@ -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( diff --git a/backend/app/services/disaster_aggregation.py b/backend/app/services/disaster_aggregation.py new file mode 100644 index 00000000..283bd799 --- /dev/null +++ b/backend/app/services/disaster_aggregation.py @@ -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) diff --git a/backend/app/services/earth_layer_adapters.py b/backend/app/services/earth_layer_adapters.py index f2ec15b7..92f4ac5f 100644 --- a/backend/app/services/earth_layer_adapters.py +++ b/backend/app/services/earth_layer_adapters.py @@ -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) diff --git a/backend/app/services/earth_layer_cache.py b/backend/app/services/earth_layer_cache.py index 72a2904c..73d087a3 100644 --- a/backend/app/services/earth_layer_cache.py +++ b/backend/app/services/earth_layer_cache.py @@ -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, ) diff --git a/backend/app/services/earth_news.py b/backend/app/services/earth_news.py index cdf4d117..2664fd89 100644 --- a/backend/app/services/earth_news.py +++ b/backend/app/services/earth_news.py @@ -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 = { diff --git a/backend/app/services/earth_news_store.py b/backend/app/services/earth_news_store.py index 91fccbee..447b9284 100644 --- a/backend/app/services/earth_news_store.py +++ b/backend/app/services/earth_news_store.py @@ -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) diff --git a/backend/app/services/fusion/__init__.py b/backend/app/services/fusion/__init__.py new file mode 100644 index 00000000..6786da99 --- /dev/null +++ b/backend/app/services/fusion/__init__.py @@ -0,0 +1,3 @@ +"""Multi-domain situational fusion services (§3.8–§3.10).""" + +from __future__ import annotations diff --git a/backend/app/services/fusion/anomaly_engine.py b/backend/app/services/fusion/anomaly_engine.py new file mode 100644 index 00000000..084d4c67 --- /dev/null +++ b/backend/app/services/fusion/anomaly_engine.py @@ -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), + } diff --git a/backend/app/services/fusion/convergence.py b/backend/app/services/fusion/convergence.py new file mode 100644 index 00000000..08543e32 --- /dev/null +++ b/backend/app/services/fusion/convergence.py @@ -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 diff --git a/backend/app/services/fusion/dependency_impact.py b/backend/app/services/fusion/dependency_impact.py new file mode 100644 index 00000000..b80fd1da --- /dev/null +++ b/backend/app/services/fusion/dependency_impact.py @@ -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 diff --git a/backend/app/services/fusion/wargame_scenarios.py b/backend/app/services/fusion/wargame_scenarios.py new file mode 100644 index 00000000..300538f8 --- /dev/null +++ b/backend/app/services/fusion/wargame_scenarios.py @@ -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(), + } diff --git a/backend/app/services/investigation_cases.py b/backend/app/services/investigation_cases.py new file mode 100644 index 00000000..3c2997b2 --- /dev/null +++ b/backend/app/services/investigation_cases.py @@ -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) diff --git a/backend/app/services/maritime_geography.py b/backend/app/services/maritime_geography.py new file mode 100644 index 00000000..9ca4d6d9 --- /dev/null +++ b/backend/app/services/maritime_geography.py @@ -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 diff --git a/backend/app/services/nga_advisories.py b/backend/app/services/nga_advisories.py new file mode 100644 index 00000000..824083ba --- /dev/null +++ b/backend/app/services/nga_advisories.py @@ -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\d{1,2})[-°\s]+(?P\d{1,2}(?:\.\d+)?)(?:[-'′\s]+(?P\d{1,2}(?:\.\d+)?))?[\"″]?\s*(?P[NS])\b" + r"[\s,;:/]+" + r"(?P\d{1,3})[-°\s]+(?P\d{1,2}(?:\.\d+)?)(?:[-'′\s]+(?P\d{1,2}(?:\.\d+)?))?[\"″]?\s*(?P[EW])\b", + re.IGNORECASE, +) + +_DD_HEMI_PAIR_RE = re.compile( + r"(?P\d{1,2}\.\d+)\s*°?\s*(?P[NS])\b[\s,;:/]+(?P\d{1,3}\.\d+)\s*°?\s*(?P[EW])\b", + re.IGNORECASE, +) + +_DD_SIGNED_PAIR_RE = re.compile( + r"(?P-?\d{1,2}\.\d{2,})\s*,\s*(?P-?\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 diff --git a/backend/app/services/private_data_ingest.py b/backend/app/services/private_data_ingest.py new file mode 100644 index 00000000..2f71ebd9 --- /dev/null +++ b/backend/app/services/private_data_ingest.py @@ -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 [], + } diff --git a/backend/app/services/scheduler.py b/backend/app/services/scheduler.py index d7f83349..1511f613 100644 --- a/backend/app/services/scheduler.py +++ b/backend/app/services/scheduler.py @@ -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]] = {} @@ -563,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: @@ -597,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") diff --git a/backend/app/services/source_freshness.py b/backend/app/services/source_freshness.py new file mode 100644 index 00000000..0da5dc4d --- /dev/null +++ b/backend/app/services/source_freshness.py @@ -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, + } diff --git a/backend/app/services/storage_maintenance.py b/backend/app/services/storage_maintenance.py index ddbe5cbd..635adf91 100644 --- a/backend/app/services/storage_maintenance.py +++ b/backend/app/services/storage_maintenance.py @@ -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, diff --git a/backend/app/services/storage_policy.py b/backend/app/services/storage_policy.py index a2ee4abd..1e8ec951 100644 --- a/backend/app/services/storage_policy.py +++ b/backend/app/services/storage_policy.py @@ -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] = { diff --git a/backend/app/services/vessel_types.py b/backend/app/services/vessel_types.py index 156cb183..b1eb53ba 100644 --- a/backend/app/services/vessel_types.py +++ b/backend/app/services/vessel_types.py @@ -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 diff --git a/backend/tests/test_actions_approval.py b/backend/tests/test_actions_approval.py new file mode 100644 index 00000000..7f1cfdde --- /dev/null +++ b/backend/tests/test_actions_approval.py @@ -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() diff --git a/backend/tests/test_aircraft_api.py b/backend/tests/test_aircraft_api.py new file mode 100644 index 00000000..8768301b --- /dev/null +++ b/backend/tests/test_aircraft_api.py @@ -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() diff --git a/backend/tests/test_aircraft_collectors.py b/backend/tests/test_aircraft_collectors.py new file mode 100644 index 00000000..4fde8f95 --- /dev/null +++ b/backend/tests/test_aircraft_collectors.py @@ -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 diff --git a/backend/tests/test_card_images.py b/backend/tests/test_card_images.py index ab57c49c..abe2078f 100644 --- a/backend/tests/test_card_images.py +++ b/backend/tests/test_card_images.py @@ -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"] diff --git a/backend/tests/test_disasters.py b/backend/tests/test_disasters.py new file mode 100644 index 00000000..0695ac06 --- /dev/null +++ b/backend/tests/test_disasters.py @@ -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() diff --git a/backend/tests/test_earth_layer_cache.py b/backend/tests/test_earth_layer_cache.py index dd572cc1..4fe9df31 100644 --- a/backend/tests/test_earth_layer_cache.py +++ b/backend/tests/test_earth_layer_cache.py @@ -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"" diff --git a/backend/tests/test_fusion_convergence.py b/backend/tests/test_fusion_convergence.py new file mode 100644 index 00000000..4a198f7e --- /dev/null +++ b/backend/tests/test_fusion_convergence.py @@ -0,0 +1,251 @@ +"""Tests for §3.9 H3 convergence, dependency impact gating, and proactive pipeline isolation.""" + +from __future__ import annotations + +from contextlib import asynccontextmanager +from datetime import UTC, datetime, timedelta + +import h3 +import pytest +from sqlalchemy import create_engine, select +from sqlalchemy.orm import Session + +from app.db.migrations import discover_migrations +from app.db.session import Base +from app.models.aircraft import AircraftCurrentState +from app.models.collected_data import CollectedData +from app.models.compute_center_location import ComputeCenterLocationRecord +from app.models.gps_jamming import GPSJammingCell +from app.models.maritime_advisory import CableAdvisory +from app.models.situational_assessment import StagePresentation +from app.services.ai.proactive_pipeline import process_fusion_incident +from app.services.fusion.convergence import contains_causal_assertion, run_convergence_cycle +from app.services.fusion.dependency_impact import evaluate_cable_dependency_impact + + +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 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 {"0009", "0010", "0011"}: + await step.upgrade(shim) + Base.metadata.create_all(raw_conn, checkfirst=True) + + @asynccontextmanager + async def _factory(): + with Session(engine) as session: + yield _AsyncSQLiteSession(session) + + return engine, _factory + + +@pytest.mark.asyncio +async def test_convergence_requires_two_domains_and_avoids_causality() -> None: + _engine, session_factory = await _make_sqlite_session() + now = datetime(2026, 6, 15, 12, 0, tzinfo=UTC) + + async with session_factory() as db: + sg_h3 = h3.latlng_to_cell(1.30, 103.85, 4) + # Single domain only -> should NOT generate candidate_correlation + db.add( + GPSJammingCell( + h3_index=sg_h3, + observed_date=now.date().isoformat(), + lat=1.30, + lon=103.85, + resolution=4, + level="high", + bad_ratio=0.55, + aircraft_count=12, + boundary=[[1.2, 103.7], [1.4, 103.9]], + source="gpsjam_interference", + ingested_at=now, + ) + ) + await db.commit() + res_single = await run_convergence_cycle(db, now=now) + assert res_single == [] + + # Add a second distinct domain (emergency aircraft) in the same coordinates + db.add( + AircraftCurrentState( + icao24="ae9991", + callsign="RCH123", + lat=1.30, + lon=103.85, + squawk="7700", + on_ground=False, + is_military=True, + is_emergency=True, + source="adsb_lol_aircraft", + observed_at=now - timedelta(minutes=15), + ingested_at=now, + ) + ) + await db.commit() + + res_multi = await run_convergence_cycle(db, now=now) + assert len(res_multi) == 2 # 6h + 24h windows + for inc in res_multi: + assert inc.assessment_kind == "candidate_correlation" + assert "待核查关联" in inc.title + assert not contains_causal_assertion(inc.title) + assert not contains_causal_assertion(inc.signal_summary.get("co_occurrence_note", "")) + + +@pytest.mark.asyncio +async def test_dependency_impact_gates_on_independent_evidence_and_proactive_pipeline() -> None: + _engine, session_factory = await _make_sqlite_session() + now = datetime(2026, 6, 15, 12, 0, tzinfo=UTC) + + async with session_factory() as db: + # Topology: apg-1 + backup sea-me-we-6 both land in city 901 (Singapore -> compute center 77) + db.add_all( + [ + CollectedData( + source="arcgis_cables", + source_id="apg-1", + data_type="cable", + name="APG Cable", + extra_data={"cable_id": "apg-1", "coordinates": [[103.6, 1.25], [103.8, 1.3]]}, + is_current=True, + collected_at=now, + ), + CollectedData( + source="arcgis_cables", + source_id="smw6", + data_type="cable", + name="SEA-ME-WE 6", + extra_data={"cable_id": "smw6", "coordinates": [[103.5, 1.22], [103.9, 1.31]]}, + is_current=True, + collected_at=now, + ), + CollectedData( + source="arcgis_landing_points", + source_id="tuas", + data_type="landing_point", + name="Tuas", + extra_data={"city_id": 901, "country": "Singapore", "latitude": 1.32, "longitude": 103.64}, + is_current=True, + collected_at=now, + ), + CollectedData( + source="arcgis_cable_landing_relation", + source_id="r1", + data_type="relation", + name="apg-tuas", + extra_data={"cable_id": "apg-1", "city_id": 901}, + is_current=True, + collected_at=now, + ), + CollectedData( + source="arcgis_cable_landing_relation", + source_id="r2", + data_type="relation", + name="smw6-tuas", + extra_data={"cable_id": "smw6", "city_id": 901}, + is_current=True, + collected_at=now, + ), + ComputeCenterLocationRecord( + id=77, + source="top500", + source_id="sg-77", + name="SG National HPC", + country="SG", + latitude=1.34, + longitude=103.81, + verified_at=now, + ), + ] + ) + await db.commit() + + # Without independent NGA/operator/BGP evidence -> strictly None + no_ev = await evaluate_cable_dependency_impact( + db, + cable_id="apg-1", + suspect_object_ids=["vessel:412111222"], + now=now, + ) + assert no_ev is None + + # Add matching NGA CableAdvisory -> upgrades to dependency_impact with backup cables & arcs + db.add( + CableAdvisory( + source_warning_id="HYDROPAC 111/26", + text="APG SUBMARINE CABLE REPAIR OPERATIONS IN PROGRESS", + lat=1.28, + lon=103.72, + issued_at=now - timedelta(hours=1), + matched_cable_ids=["apg-1"], + match_method="haversine_50km", + ingested_at=now, + ) + ) + await db.commit() + + impact_inc = await evaluate_cable_dependency_impact( + db, + cable_id="apg-1", + suspect_object_ids=["vessel:412111222"], + now=now, + ) + assert impact_inc is not None + assert impact_inc.assessment_kind == "dependency_impact" + assert "SG" in impact_inc.signal_summary["impacted_countries"] + assert any(b["cable_id"] == "smw6" for b in impact_inc.signal_summary["backup_cables"]) + assert len(impact_inc.signal_summary["impact_arcs"]) >= 1 + + pro_res = await process_fusion_incident(db, impact_inc) + assert pro_res["workflow_id"] == "wargame.cable_protection" + assert pro_res["published_presentation"] is not None + persisted = ( + await db.execute( + select(StagePresentation).where( + StagePresentation.presentation_key == pro_res["presentation_key"] + ) + ) + ).scalars().first() + assert persisted is not None diff --git a/backend/tests/test_geofences_anomalies.py b/backend/tests/test_geofences_anomalies.py new file mode 100644 index 00000000..8d211bc9 --- /dev/null +++ b/backend/tests/test_geofences_anomalies.py @@ -0,0 +1,300 @@ +"""Tests for §3.8 geofences, deterministic anomaly rules, cooldown dedup, and incident triage RBAC.""" + +from __future__ import annotations + +from contextlib import asynccontextmanager +from datetime import UTC, datetime, timedelta +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_earth_or_api_access +from app.core.enums import UserRole +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 +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.fusion.anomaly_engine import ( + detect_cable_corridor_loitering, + detect_dark_target_blackout, + detect_geofence_traffic_surge, + ensure_preset_geofences, +) + + +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 delete(self, instance) -> None: + self._session.delete(instance) + + 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() + + 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) + for step in discover_migrations(): + if step.version in {"0009", "0010", "0011"}: + await step.upgrade(shim) + VesselCurrentState.__table__.create(raw_conn, checkfirst=True) + VesselPosition.__table__.create(raw_conn, checkfirst=True) + AircraftCurrentState.__table__.create(raw_conn, checkfirst=True) + AircraftPosition.__table__.create(raw_conn, checkfirst=True) + CollectedData.__table__.create(raw_conn, checkfirst=True) + EarthInteractable.__table__.create(raw_conn, checkfirst=True) + for step in discover_migrations(): + if step.version == "0011": + 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_preset_seeding_and_three_anomaly_rules_with_cooldown() -> None: + _engine, session_factory = await _make_sqlite_session() + now = datetime(2026, 6, 15, 12, 0, tzinfo=UTC) + + async with session_factory() as db: + # 1 cable record to seed cable corridor preset + db.add( + CollectedData( + source="arcgis_cables", + source_id="apg-1", + data_type="cable", + name="APG Cable", + extra_data={"cable_id": "apg-1", "coordinates": [[103.5, 1.2], [104.2, 1.2]]}, + is_current=True, + collected_at=now, + ) + ) + await db.commit() + + seeded = await ensure_preset_geofences(db, corridor_half_width_km=18.0) + assert seeded >= 10 # 9 chokepoints + 1 cable corridor + assert await ensure_preset_geofences(db, corridor_half_width_km=18.0) == 0 + + geofences = list((await db.execute(select(Geofence))).scalars().all()) + cable_gf = next(g for g in geofences if (g.rules or {}).get("corridor_type") == "cable_corridor") + + # Rule 1 fixture: vessel loitering > 30 min at SOG 1.2 kn inside cable corridor + db.add( + VesselCurrentState( + mmsi=412111222, + lat=1.20, + lon=103.85, + sog=1.2, + name="LOITER SHIP", + source="aisstream_vessels", + observed_at=now - timedelta(minutes=2), + ) + ) + db.add( + VesselPosition( + mmsi=412111222, + lat=1.20, + lon=103.84, + sog=1.1, + received_at=now - timedelta(minutes=45), + ) + ) + db.add( + VesselPosition( + mmsi=412111222, + lat=1.20, + lon=103.85, + sog=1.2, + received_at=now - timedelta(minutes=2), + ) + ) + + # Rule 2 fixture: dark target silent > 45 min inside Malacca chokepoint + db.add( + VesselCurrentState( + mmsi=412999000, + lat=2.0, + lon=102.0, + sog=11.0, + name="DARK RUNNER", + source="aisstream_vessels", + observed_at=now - timedelta(minutes=75), + ) + ) + + # Rule 3 fixture: surge in Malacca (> 14-day same-hour mean + 2*sigma) + # Seed 5 historical days with [1, 2, 1, 2, 1] vessels at hour=12 (mean=1.4, std=0.49, thresh~2.38) + for day_offset, cnt in [(2, 1), (3, 2), (4, 1), (5, 2), (6, 1)]: + for idx in range(cnt): + db.add( + VesselPosition( + mmsi=500000 + day_offset * 10 + idx, + lat=2.05, + lon=102.05, + sog=10.0, + received_at=now - timedelta(days=day_offset), + ) + ) + # Seed 5 active vessels in Malacca right now + for idx in range(5): + db.add( + VesselCurrentState( + mmsi=700000 + idx, + lat=2.02, + lon=102.02, + sog=12.0, + name=f"SURGE-{idx}", + source="aisstream_vessels", + observed_at=now - timedelta(minutes=5), + ) + ) + await db.commit() + + loiter_1 = await detect_cable_corridor_loitering(db, [cable_gf], now=now) + assert len(loiter_1) == 1 + assert loiter_1[0].assessment_kind == "rule_alert" + assert "vessel:412111222" in loiter_1[0].object_ids + # Cooldown suppresses duplicate + assert await detect_cable_corridor_loitering(db, [cable_gf], now=now + timedelta(minutes=10)) == [] + + dark_1 = await detect_dark_target_blackout(db, geofences, now=now) + assert any(i.object_ids == ["vessel:412999000"] for i in dark_1) + assert await detect_dark_target_blackout(db, geofences, now=now + timedelta(minutes=10)) == [] + + surge_1 = await detect_geofence_traffic_surge(db, geofences, now=now) + assert any(i.incident_type == "geofence_traffic_surge" for i in surge_1) + + +@pytest.mark.asyncio +async def test_geofences_and_incidents_api_rbac_and_dismiss_reason() -> None: + _engine, session_factory = await _make_sqlite_session() + async with session_factory() as db: + inc = SituationalIncident( + incident_type="cable_corridor_loitering", + severity="high", + status="open", + object_ids=["vessel:123456"], + signal_summary={"lat": 1.2, "lon": 103.8}, + evidence=[], + assessment_kind="rule_alert", + title="Test Loitering", + ) + db.add(inc) + await db.commit() + inc_id = inc.id + + current_role = {"role": UserRole.VIEWER.value, "username": "viewer1"} + + async def _override_db(): + async with session_factory() as session: + yield session + + async def _override_read(): + return SimpleNamespace(id=1, username=current_role["username"], role=current_role["role"]) + + async def _override_user(): + return SimpleNamespace(id=1, username=current_role["username"], role=current_role["role"]) + + app.dependency_overrides[get_db] = _override_db + app.dependency_overrides[require_earth_or_api_access("visualization:read")] = _override_read + app.dependency_overrides[get_current_user] = _override_user + + try: + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: + # Viewer cannot create custom geofence or dismiss incident + r_deny = await client.post( + "/api/v1/geofences", + json={ + "name": "Custom Watch", + "geometry": { + "type": "Polygon", + "coordinates": [[[103.0, 1.0], [104.0, 1.0], [104.0, 2.0], [103.0, 2.0], [103.0, 1.0]]], + }, + }, + ) + assert r_deny.status_code == 403 + + # Admin can create custom geofence + current_role["role"] = UserRole.ADMIN.value + current_role["username"] = "admin1" + r_ok = await client.post( + "/api/v1/geofences", + json={ + "name": "Custom Watch", + "geometry": { + "type": "Polygon", + "coordinates": [[[103.0, 1.0], [104.0, 1.0], [104.0, 2.0], [103.0, 2.0], [103.0, 1.0]]], + }, + }, + ) + assert r_ok.status_code == 200 + assert r_ok.json()["kind"] == "custom" + + # Acknowledge works + r_ack = await client.post(f"/api/v1/incidents/{inc_id}/acknowledge", json={}) + assert r_ack.status_code == 200 + assert r_ack.json()["status"] == "acknowledged" + + # Dismiss rejects empty reason + r_bad = await client.post(f"/api/v1/incidents/{inc_id}/dismiss", json={"resolution_note": " "}) + assert r_bad.status_code == 422 + + # Dismiss succeeds with mandatory reason + r_dis = await client.post( + f"/api/v1/incidents/{inc_id}/dismiss", + json={"resolution_note": "False positive anchored tugboat"}, + ) + assert r_dis.status_code == 200 + assert r_dis.json()["status"] == "dismissed" + assert r_dis.json()["resolution_note"] == "False positive anchored tugboat" + finally: + app.dependency_overrides.clear() diff --git a/backend/tests/test_gps_jamming.py b/backend/tests/test_gps_jamming.py new file mode 100644 index 00000000..75a03c69 --- /dev/null +++ b/backend/tests/test_gps_jamming.py @@ -0,0 +1,131 @@ +"""Phase 2 GPS/GNSS interference H3 parsing, cell generation, and API tests.""" + +from __future__ import annotations + +from contextlib import asynccontextmanager + +import h3 +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.gps_jamming import GPSJammingCell +from app.services.collectors.gps_jamming import ( + classify_jamming_level, + parse_gpsjam_csv, + parse_manifest_latest_date, +) + + +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 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 + + +def test_gpsjam_manifest_and_h3_cell_parsing(): + manifest = "date,url\n2026-12-04,2026-12-04-h3_4.csv\n2026-12-05,2026-12-05-h3_4.csv\n" + assert parse_manifest_latest_date(manifest) == "2026-12-05" + + cell_high = h3.latlng_to_cell(35.0, 33.0, 4) + cell_med = h3.latlng_to_cell(54.7, 20.5, 4) + cell_clean = h3.latlng_to_cell(48.8, 2.3, 4) + + csv_text = ( + "hex,count_good_aircraft,count_bad_aircraft\n" + f"{cell_high},80,25\n" + f"{cell_med},95,5\n" + f"{cell_clean},100,0\n" + ) + cells = parse_gpsjam_csv(csv_text, observed_date="2026-12-05") + assert len(cells) == 2 + by_hex = {c["h3_index"]: c for c in cells} + + assert by_hex[cell_high]["level"] == "high" + assert by_hex[cell_high]["resolution"] == 4 + assert len(by_hex[cell_high]["boundary"]) >= 5 + assert by_hex[cell_med]["level"] == "medium" + assert classify_jamming_level(0.01) == "low" + + +@pytest.mark.asyncio +async def test_gps_jamming_snapshot_api(): + 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: + cell_high = h3.latlng_to_cell(35.0, 33.0, 4) + async with factory() as db: + db.add( + GPSJammingCell( + h3_index=cell_high, + observed_date="2026-12-05", + lat=35.0, + lon=33.0, + resolution=4, + level="high", + bad_ratio=0.238, + aircraft_count=105, + boundary=[[lat, lon] for lat, lon in h3.cell_to_boundary(cell_high)], + source="gpsjam_interference", + ) + ) + await db.commit() + + transport = ASGITransport(app=app) + async with AsyncClient(transport=transport, base_url="http://test") as client: + resp = await client.get("/api/v1/gps-jamming/snapshot") + assert resp.status_code == 200 + data = resp.json() + assert data["date"] == "2026-12-05" + assert data["stats"]["high"] == 1 + assert len(data["cells"]) == 1 + assert data["cells"][0]["h3_index"] == cell_high + assert "gpsjam.org" in data["attribution"] + finally: + app.dependency_overrides.pop(get_db, None) + engine.dispose() diff --git a/backend/tests/test_ha_and_migrations.py b/backend/tests/test_ha_and_migrations.py index fce521c9..7dcc4d90 100644 --- a/backend/tests/test_ha_and_migrations.py +++ b/backend/tests/test_ha_and_migrations.py @@ -4,7 +4,6 @@ from __future__ import annotations import asyncio from contextlib import asynccontextmanager -import json from pathlib import Path from fastapi import FastAPI @@ -79,7 +78,7 @@ async def test_lifespan_respects_planet_role_and_leader_lock(monkeypatch): return False monkeypatch.setattr(main_module, "init_db", noop_async) - monkeypatch.setattr(main_module, "cleanup_stale_running_tasks", lambda: noop_async()) + monkeypatch.setattr(main_module, "cleanup_stale_running_tasks", noop_async) monkeypatch.setattr(main_module, "sync_scheduler_with_datasources", lambda: noop_async()) monkeypatch.setattr(main_module, "release_scheduler_leader_lock", lambda: noop_async()) monkeypatch.setattr(main_module, "start_scheduler", lambda: calls.append("start_scheduler")) diff --git a/backend/tests/test_investigation_cases.py b/backend/tests/test_investigation_cases.py new file mode 100644 index 00000000..d79af49e --- /dev/null +++ b/backend/tests/test_investigation_cases.py @@ -0,0 +1,154 @@ +"""Tests for §4.3 Investigation Case Board, SHA-256 freeze stability, Markdown export, and RBAC.""" + +from __future__ import annotations + +from contextlib import asynccontextmanager +from types import SimpleNamespace + +from httpx import ASGITransport, AsyncClient +import pytest +from sqlalchemy import create_engine +from sqlalchemy.orm import Session + +from app.core.access_gate import get_current_user, require_earth_or_api_access +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 + + +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 commit(self) -> None: + self._session.commit() + + async def refresh(self, instance) -> None: + self._session.refresh(instance) + + +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"}: + await step.upgrade(shim) + Base.metadata.create_all(raw_conn, checkfirst=True) + for step in discover_migrations(): + if step.version == "0012": + 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_investigation_case_freeze_sha256_markdown_export_and_rbac() -> None: + _engine, session_factory = await _make_sqlite_session() + actor = {"id": 10, "username": "admin1", "role": UserRole.ADMIN.value} + + async def _override_db(): + async with session_factory() as session: + yield session + + async def _override_user(): + return SimpleNamespace(**actor) + + async def _override_read(): + return SimpleNamespace(**actor) + + app.dependency_overrides[get_db] = _override_db + app.dependency_overrides[get_current_user] = _override_user + app.dependency_overrides[require_earth_or_api_access("visualization:read")] = _override_read + + try: + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: + r_create = await client.post( + "/api/v1/cases", + json={"title": "SEA-ME-WE 6 Cable Anomaly", "summary": "Joint dossier", "is_shared": True}, + ) + assert r_create.status_code == 200 + case_id = r_create.json()["id"] + + r_priv = await client.post( + "/api/v1/cases", + json={"title": "Private Draft", "summary": "Internal", "is_shared": False}, + ) + assert r_priv.status_code == 200 + priv_id = r_priv.json()["id"] + + r_item = await client.post( + f"/api/v1/cases/{case_id}/items", + json={ + "item_type": "object", + "ref_id": "cable:smw6", + "payload": {"title": "SEA-ME-WE 6", "provenance": "arcgis_cables", "publish_id": "pub-1"}, + }, + ) + assert r_item.status_code == 200 + + r_freeze_1 = await client.post(f"/api/v1/cases/{case_id}/freeze") + assert r_freeze_1.status_code == 200 + sha1 = r_freeze_1.json()["version"]["content_sha256"] + assert len(sha1) == 64 + assert r_freeze_1.json()["case"]["status"] == "frozen" + + # Verify Markdown export contains provenance, publish_id, and SHA-256 + r_md = await client.get(f"/api/v1/cases/{case_id}/export/markdown") + assert r_md.status_code == 200 + md_text = r_md.text + assert sha1 in md_text + assert "arcgis_cables" in md_text + assert "pub-1" in md_text + + # Viewer RBAC: can read & export shared case, blocked on write or unshared draft + actor.update({"id": 20, "username": "viewer1", "role": UserRole.VIEWER.value}) + assert (await client.get(f"/api/v1/cases/{case_id}")).status_code == 200 + assert (await client.get(f"/api/v1/cases/{case_id}/export/markdown")).status_code == 200 + assert (await client.get(f"/api/v1/cases/{priv_id}")).status_code == 403 + assert ( + await client.post("/api/v1/cases", json={"title": "Blocked"}) + ).status_code == 403 + assert ( + await client.post( + f"/api/v1/cases/{case_id}/items", + json={"item_type": "note", "ref_id": "n1", "payload": {}}, + ) + ).status_code == 403 + finally: + app.dependency_overrides.clear() diff --git a/backend/tests/test_maritime_intelligence.py b/backend/tests/test_maritime_intelligence.py new file mode 100644 index 00000000..35206c66 --- /dev/null +++ b/backend/tests/test_maritime_intelligence.py @@ -0,0 +1,126 @@ +"""Phase 3.4 strategic ports, maritime chokepoints, warship/cable-ship recognition, and baseline tests.""" + +from __future__ import annotations + +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.session import Base, get_db +from app.main import app +from app.models.vessel import VesselCurrentState, VesselPosition +from app.services.maritime_geography import ( + compute_chokepoint_vessel_summary, + enrich_vessel_feature_roles, + find_chokepoint_for_point, + load_chokepoints, + load_strategic_ports, +) +from app.services.vessel_types import classify_military_vessel, is_cable_repair_vessel + + +class _AsyncSQLiteSession: + def __init__(self, session: Session): + self._session = session + + def get_bind(self): + return self._session.get_bind() + + 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() + + +def test_cited_dictionaries_and_warship_cable_ship_recognition(): + chokepoints = load_chokepoints() + ports = load_strategic_ports() + cp_ids = {c["id"] for c in chokepoints} + assert {"malacca_strait", "strait_of_hormuz", "bab_el_mandeb", "suez_canal", "panama_canal", "strait_of_gibraltar", "bosphorus_strait", "taiwan_strait", "korea_strait"}.issubset(cp_ids) + assert all(c.get("source_citation") for c in chokepoints) + assert len(ports) >= 20 + assert all(p.get("source_citation") and p.get("port_type") for p in ports) + + # Warship classification + role1, src1 = classify_military_vessel(vessel_type=35, name="UNKNOWN VESSEL") + assert role1 == "warship" and "35" in src1 + role2, _ = classify_military_vessel(vessel_type=70, name="USS ARLEIGH BURKE") + assert role2 == "destroyer" + role3, _ = classify_military_vessel(vessel_type=0, name="HMS DIAMOND") + assert role3 == "destroyer" + role4, _ = classify_military_vessel(vessel_type=0, name="ROKS SEJONG") + assert role4 == "warship" + role_civ, _ = classify_military_vessel(vessel_type=70, name="COSCO SHIPPING UNIVERSE") + assert role_civ is None + + # Cable repair ship classification + is_cs, cs_src = is_cable_repair_vessel(vessel_type=33, name="CS RESOLUTE") + assert is_cs is True and "ICPC" in cs_src + is_cs2, _ = is_cable_repair_vessel(vessel_type=70, name="C/S ORANGE PACIFIC") + assert is_cs2 is True + assert is_cable_repair_vessel(vessel_type=70, name="EVER GIVEN")[0] is False + + +@pytest.mark.asyncio +async def test_chokepoint_counting_rolling_baseline_api_and_ai_tool(): + engine = create_engine("sqlite:///:memory:") + Base.metadata.create_all(bind=engine) + now = datetime.now(UTC) + + with Session(engine) as s: + # 2 current vessels in Strait of Hormuz (26.55N, 56.35E), 1 warship + s.add_all( + [ + VesselCurrentState(mmsi="999000111", name="USS NIMITZ", vessel_type=35, lat=26.55, lon=56.35, source="aisstream_vessels", observed_at=now - timedelta(minutes=5)), + VesselCurrentState(mmsi="999000222", name="CS RESOLUTE", vessel_type=33, lat=26.50, lon=56.40, source="aisstream_vessels", observed_at=now - timedelta(minutes=5)), + ] + ) + # 7d history baseline inside Strait of Hormuz: 1 ship on day -2, 1 ship on day -3 -> avg 1.0/day + s.add_all( + [ + VesselPosition(mmsi="888000111", lat=26.55, lon=56.35, received_at=now - timedelta(days=2)), + VesselPosition(mmsi="888000222", lat=26.52, lon=56.30, received_at=now - timedelta(days=3)), + ] + ) + s.commit() + + async def _override_db(): + with Session(engine) as s: + yield _AsyncSQLiteSession(s) + + app.dependency_overrides[get_db] = _override_db + try: + assert find_chokepoint_for_point(26.55, 56.35)["id"] == "strait_of_hormuz" + + sample_feat = { + "type": "Feature", + "geometry": {"type": "Point", "coordinates": [56.35, 26.55]}, + "properties": {"mmsi": "999000111", "name": "USS NIMITZ", "vessel_type": 35}, + } + enrich_vessel_feature_roles(sample_feat) + assert sample_feat["properties"]["is_warship"] is True + assert sample_feat["properties"]["chokepoint_id"] == "strait_of_hormuz" + + with Session(engine) as s: + summary = await compute_chokepoint_vessel_summary(_AsyncSQLiteSession(s), now=now) + hormuz = next(c for c in summary if c["id"] == "strait_of_hormuz") + assert hormuz["vessel_count"] == 2 + assert hormuz["warship_count"] == 1 + assert hormuz["cable_ship_count"] == 1 + assert hormuz["baseline_7d_avg"] == 1.0 + assert hormuz["delta_vs_7d"] == 1.0 + + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: + resp = await client.get("/api/v1/vessels/maritime-context") + assert resp.status_code == 200 + body = resp.json() + assert body["chokepoint_count"] >= 9 + assert body["port_count"] >= 20 + hormuz_api = next(c for c in body["chokepoints"] if c["id"] == "strait_of_hormuz") + assert hormuz_api["vessel_count"] == 2 + finally: + app.dependency_overrides.clear() + engine.dispose() diff --git a/backend/tests/test_news_credibility.py b/backend/tests/test_news_credibility.py new file mode 100644 index 00000000..b9dc14be --- /dev/null +++ b/backend/tests/test_news_credibility.py @@ -0,0 +1,152 @@ +"""Phase 3.5 news source credibility tier, state-affiliation labeling, and theater filter tests.""" + +from __future__ import annotations + +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.session import Base, get_db +from app.main import app +from app.models.earth_news import EarthNewsItem +from app.services.ai.tool_registry import query_recent_earth_news_tool +from app.services.earth_news import normalize_earth_news_sources_payload + + +class _AsyncSQLiteSession: + def __init__(self, session: Session): + self._session = session + + def get_bind(self): + return self._session.get_bind() + + 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() + + +def test_news_source_config_preserves_unrated_null_tier_and_metadata(): + normalized = normalize_earth_news_sources_payload( + { + "sources": [ + { + "id": "src_rated", + "name": "Rated Source", + "region": "europe", + "feed_url": "https://example.com/rss.xml", + "homepage_url": "https://example.com", + "source_type": "rss", + "credibility_tier": 1, + "state_affiliated": False, + "theater_tags": ["europe", "russo_ukrainian"], + }, + { + "id": "src_unrated", + "name": "Legacy Source", + "region": "global", + "feed_url": "https://example.org/rss.xml", + "homepage_url": "https://example.org", + "source_type": "rss", + }, + ] + } + ) + by_id = {s["id"]: s for s in normalized["sources"]} + assert by_id["src_rated"]["credibility_tier"] == 1 + assert by_id["src_rated"]["theater_tags"] == ["europe", "russo_ukrainian"] + # Existing/unconfigured rows MUST remain None ('未分级'), NEVER defaulted to 4 + assert by_id["src_unrated"]["credibility_tier"] is None + assert by_id["src_unrated"]["state_affiliated"] is False + + +@pytest.mark.asyncio +async def test_news_theater_filter_and_ai_credibility_sorting(): + engine = create_engine("sqlite:///:memory:") + Base.metadata.create_all(bind=engine) + now = datetime.now(UTC) + + with Session(engine) as s: + s.add_all( + [ + EarthNewsItem( + id="n1", + title="Unrated rumor", + summary="No tier yet", + url="https://example.com/1", + source="RumorFeed", + feed_name="RumorFeed", + region="global", + published_at=now - timedelta(minutes=5), + latitude=1.0, + longitude=1.0, + location_label="Global", + credibility_tier=None, + state_affiliated=False, + theater_tags=["indo_pacific"], + ), + EarthNewsItem( + id="n2", + title="Tier 2 State Broadcast", + summary="Official bulletin", + url="https://example.com/2", + source="StateWire", + feed_name="StateWire", + region="global", + published_at=now - timedelta(minutes=15), + latitude=25.0, + longitude=55.0, + location_label="Middle East", + credibility_tier=2, + state_affiliated=True, + theater_tags=["middle_east"], + ), + EarthNewsItem( + id="n3", + title="Tier 1 Primary Dispatch", + summary="Confirmed port notice", + url="https://example.com/3", + source="PrimaryPress", + feed_name="PrimaryPress", + region="global", + published_at=now - timedelta(minutes=30), + latitude=24.0, + longitude=120.0, + location_label="Taiwan Strait", + credibility_tier=1, + state_affiliated=False, + theater_tags=["indo_pacific"], + ), + ] + ) + s.commit() + + async def _override_db(): + with Session(engine) as s: + yield _AsyncSQLiteSession(s) + + app.dependency_overrides[get_db] = _override_db + try: + with Session(engine) as s: + ai_res = await query_recent_earth_news_tool(_AsyncSQLiteSession(s), limit=10) + assert [it["id"] for it in ai_res["items"]] == ["n3", "n2", "n1"] + assert ai_res["items"][0]["credibility_label"] == "Tier 1" + assert ai_res["items"][1]["state_affiliation_label"] == "国家背景媒体" + assert ai_res["items"][2]["credibility_tier"] is None + assert ai_res["items"][2]["credibility_label"] == "未分级" + + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: + resp = await client.get("/api/v1/news/earth-feed?theater=indo_pacific") + assert resp.status_code == 200 + body = resp.json() + ids = {it["id"] for it in body["items"]} + assert ids == {"n1", "n3"} + by_id = {it["id"]: it for it in body["items"]} + assert by_id["n1"]["credibility_tier"] is None + assert by_id["n1"]["credibility_label"] == "未分级" + finally: + app.dependency_overrides.clear() + engine.dispose() diff --git a/backend/tests/test_nga_advisories.py b/backend/tests/test_nga_advisories.py new file mode 100644 index 00000000..d5ed00ab --- /dev/null +++ b/backend/tests/test_nga_advisories.py @@ -0,0 +1,173 @@ +"""Phase 3.3 NGA MSI coordinate parser, cable matching, and AI tool advisory tests.""" + +from __future__ import annotations + +from contextlib import asynccontextmanager +import pytest +from sqlalchemy import create_engine +from sqlalchemy.orm import Session + +from app.db.migrations import discover_migrations +from app.services.ai.tool_registry import query_cable_posture_tool +from app.services.nga_advisories import ( + extract_warning_coordinates, + match_warning_to_cables, + parse_nga_broadcast_warnings, + upsert_cable_advisories, +) + + +class _AsyncSQLiteSession: + def __init__(self, session: Session): + self._session = session + + def get_bind(self): + return self._session.get_bind() + + 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 == "0009": + await step.upgrade(shim) + + @asynccontextmanager + async def _factory(): + with Session(engine) as session: + yield _AsyncSQLiteSession(session) + + return engine, _factory + + +def test_nga_dms_dm_dd_and_polygon_coordinate_parsing(): + # DMS + lat, lon, poly = extract_warning_coordinates("SUBMARINE CABLE REPAIR IN 24-30-00N 121-45-00E.") + assert poly is None + assert lat == pytest.approx(24.5, abs=1e-4) + assert lon == pytest.approx(121.75, abs=1e-4) + + # DM + lat_dm, lon_dm, _ = extract_warning_coordinates("CABLE SHIP OPS 55-15.0N 015-30.0E WIDE BERTH.") + assert lat_dm == pytest.approx(55.25, abs=1e-4) + assert lon_dm == pytest.approx(15.5, abs=1e-4) + + # DD + lat_dd, lon_dd, _ = extract_warning_coordinates("CABLE LAYING NEAR 12.500N 043.250E.") + assert lat_dd == pytest.approx(12.5, abs=1e-4) + assert lon_dd == pytest.approx(43.25, abs=1e-4) + + # Polygon (>=3 points) + lat_p, lon_p, poly_pts = extract_warning_coordinates( + "SUBMARINE CABLE OPERATIONS IN AREA BOUND BY " + "10-00.0N 100-00.0E, 10-00.0N 101-00.0E, 11-00.0N 101-00.0E, 11-00.0N 100-00.0E." + ) + assert poly_pts is not None and len(poly_pts) == 4 + assert lat_p == pytest.approx(10.5, abs=1e-4) + assert lon_p == pytest.approx(100.5, abs=1e-4) + + +def test_nga_keyword_filter_and_50km_cable_matching(): + warnings = parse_nga_broadcast_warnings( + { + "broadcast-warn": [ + { + "navArea": "XI", + "msgYear": "2026", + "msgNumber": "101", + "text": "TAIWAN STRAIT. SUBMARINE CABLE REPAIR OPERATIONS NEAR 24-30.0N 121-45.0E.", + "issueDate": "2026-12-06T06:00:00Z", + "status": "A", + }, + { + "navArea": "XI", + "msgYear": "2026", + "msgNumber": "102", + "text": "GUNNERY EXERCISES NEAR 20-00.0N 120-00.0E.", + "status": "A", + }, + ] + } + ) + assert len(warnings) == 1 + assert warnings[0]["source_warning_id"] == "NGA-XI-2026-101" + + sample_cables = [ + { + "geometry": {"type": "LineString", "coordinates": [[121.6, 24.4], [122.0, 24.6]]}, + "properties": {"cable_id": "apcn-2", "name": "APCN-2"}, + }, + { + "geometry": {"type": "LineString", "coordinates": [[-5.0, 36.0], [-4.0, 36.0]]}, + "properties": {"cable_id": "far-cable", "name": "Far Atlantic"}, + }, + ] + matched, method = match_warning_to_cables( + warnings[0]["lat"], + warnings[0]["lon"], + warnings[0]["polygon"], + sample_cables, + threshold_km=50.0, + ) + assert matched == ["apcn-2"] + assert "50km" in method + + +@pytest.mark.asyncio +async def test_nga_upsert_and_cable_posture_includes_advisories(monkeypatch): + engine, factory = await _make_sqlite_session() + + async def _fake_cables(db): + return { + "type": "FeatureCollection", + "features": [ + { + "geometry": {"type": "LineString", "coordinates": [[121.6, 24.4], [122.0, 24.6]]}, + "properties": {"cable_id": "apcn-2", "Name": "APCN-2", "length": "19000 km"}, + } + ], + } + + async def _fake_lps(db): + return {"type": "FeatureCollection", "features": []} + + monkeypatch.setattr("app.api.v1.visualization._build_cables_geojson", _fake_cables) + monkeypatch.setattr("app.api.v1.visualization._build_landing_points_geojson", _fake_lps) + + try: + async with factory() as db: + parsed = parse_nga_broadcast_warnings( + [ + { + "source_warning_id": "HYDROPAC-412-26", + "text": "SUBMARINE CABLE REPAIR IN 24-30.0N 121-45.0E", + "issueDate": "2026-12-06T08:00:00Z", + } + ] + ) + written = await upsert_cable_advisories(db, parsed) + assert written == 1 + + # Note query_cable_posture_tool checks hasattr(db, "execute") + posture = await query_cable_posture_tool(db) + assert posture["advisory_count"] == 1 + assert posture["advisories"][0]["source_warning_id"] == "HYDROPAC-412-26" + assert "apcn-2" in posture["advisories"][0]["matched_cable_ids"] + finally: + engine.dispose() diff --git a/backend/tests/test_offline_mode.py b/backend/tests/test_offline_mode.py new file mode 100644 index 00000000..bb577be1 --- /dev/null +++ b/backend/tests/test_offline_mode.py @@ -0,0 +1,77 @@ +"""Tests for §4.6 offline / disconnected degradation without unhandled errors.""" + +from __future__ import annotations + +from datetime import UTC, datetime + +import pytest +from sqlalchemy import create_engine +from sqlalchemy.orm import Session + +from app.db.migrations import discover_migrations +from app.db.session import Base +from app.models.datasource import DataSource +from app.services.source_freshness import compute_domain_freshness + + +class _AsyncSQLiteSession: + def __init__(self, session: Session): + self._session = session + + def add(self, instance) -> None: + self._session.add(instance) + + 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) + ) + + +@pytest.mark.asyncio +async def test_offline_mode_marks_domains_offline_and_never_raises(monkeypatch) -> None: + engine = create_engine("sqlite:///:memory:") + with engine.begin() as raw_conn: + shim = _AsyncConnShim(raw_conn) + for step in discover_migrations(): + if step.version in {"0009", "0010", "0011"}: + await step.upgrade(shim) + Base.metadata.create_all(raw_conn, checkfirst=True) + + monkeypatch.setenv("PLANET_OFFLINE_MODE", "1") + with Session(engine) as sync_sess: + db = _AsyncSQLiteSession(sync_sess) + db.add( + DataSource( + name="USGS Earthquakes", + source="usgs_earthquakes", + module="L2", + collector_class="USGSEarthquakeCollector", + is_active=True, + last_status="offline", + ) + ) + await db.commit() + + summary = await compute_domain_freshness(db, now=datetime.now(UTC)) + assert summary["offline_mode"] is True + dis = next(d for d in summary["domains"] if d["domain"] == "disasters") + assert dis["status"] == "offline" + assert dis["is_blind_spot"] is True diff --git a/backend/tests/test_ontology.py b/backend/tests/test_ontology.py new file mode 100644 index 00000000..b67e4ab3 --- /dev/null +++ b/backend/tests/test_ontology.py @@ -0,0 +1,368 @@ +"""Tests for §3.7 federated ontology read-time resolution, curation tables, and RBAC.""" + +from __future__ import annotations + +from contextlib import asynccontextmanager +from datetime import UTC, datetime, timedelta +from types import SimpleNamespace + +from httpx import ASGITransport, AsyncClient +import pytest +from sqlalchemy import create_engine +from sqlalchemy.orm import Session + +from app.core.access_gate import get_current_user, require_earth_or_api_access +from app.core.enums import UserRole +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 +from app.models.bgp_incident import BGPIncident +from app.models.collected_data import CollectedData +from app.models.compute_center_location import ComputeCenterLocationRecord +from app.models.disaster import DisasterEvent +from app.models.earth_interactable import EarthInteractable +from app.models.gps_jamming import GPSJammingCell +from app.models.vessel import VesselCurrentState +from app.services.ai.entity_resolver import ( + resolve_alias_to_object_ids, + resolve_ontology_neighborhood, + resolve_ontology_object, +) + + +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 delete(self, instance) -> None: + self._session.delete(instance) + + 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() + + 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) + for step in discover_migrations(): + if step.version in {"0009", "0010"}: + await step.upgrade(shim) + # Ensure base tables used by read-time resolvers exist in sqlite test DB + AircraftCurrentState.__table__.create(raw_conn, checkfirst=True) + VesselCurrentState.__table__.create(raw_conn, checkfirst=True) + GPSJammingCell.__table__.create(raw_conn, checkfirst=True) + ComputeCenterLocationRecord.__table__.create(raw_conn, checkfirst=True) + EarthInteractable.__table__.create(raw_conn, checkfirst=True) + CollectedData.__table__.create(raw_conn, checkfirst=True) + BGPIncident.__table__.create(raw_conn, checkfirst=True) + # Re-run 0010 idempotently to ensure zero errors on repeated upgrade + for step in discover_migrations(): + if step.version == "0010": + 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_ontology_resolve_all_domains_and_neighborhood() -> None: + _engine, session_factory = await _make_sqlite_session() + now = datetime.now(UTC) + + async with session_factory() as db: + db.add( + AircraftCurrentState( + icao24="ae1234", + callsign="FORTE11", + lat=1.28, + lon=103.85, + squawk="7700", + on_ground=False, + is_military=True, + is_emergency=True, + source="adsb_lol_aircraft", + observed_at=now - timedelta(seconds=30), + ingested_at=now, + ) + ) + db.add( + VesselCurrentState( + mmsi=563000111, + lat=1.25, + lon=103.82, + sog=2.1, + name="USS TEST SHIP", + vessel_type=35, + source="aisstream_vessels", + observed_at=now - timedelta(hours=2), + ) + ) + db.add( + GPSJammingCell( + h3_index="8465285ffffffff", + observed_date=now.date().isoformat(), + lat=1.30, + lon=103.85, + resolution=4, + level="high", + bad_ratio=0.42, + aircraft_count=18, + boundary=[[1.2, 103.7], [1.4, 103.9]], + source="gpsjam_interference", + ingested_at=now, + ) + ) + db.add( + DisasterEvent( + source="usgs_earthquakes", + source_event_id="us9991", + event_type="earthquake", + severity="high", + title="Sumatra M6.2 Offshore", + lat=1.40, + lon=103.60, + magnitude=6.2, + observed_at=now - timedelta(minutes=10), + ingested_at=now, + ) + ) + db.add( + ComputeCenterLocationRecord( + id=77, + source="top500", + source_id="sg-hpc-77", + name="Singapore Supercomputer", + country="SG", + latitude=1.34, + longitude=103.81, + verified_at=now, + ) + ) + db.add( + EarthInteractable( + id="sensor-sg-1", + layer="interactables", + kind="subsea_sensor", + label="SG Buoy 1", + description="Private acoustic monitor", + latitude=1.24, + longitude=103.84, + ) + ) + db.add( + CollectedData( + source="arcgis_cables", + source_id="sea-me-we-6", + data_type="cable", + name="SEA-ME-WE 6", + extra_data={"cable_id": "smw6", "coordinates": [[103.8, 1.2], [103.9, 1.3]]}, + is_current=True, + collected_at=now, + ) + ) + db.add( + CollectedData( + source="arcgis_landing_points", + source_id="tuas-lp", + data_type="landing_point", + name="Tuas", + extra_data={"city_id": 901, "country": "Singapore", "latitude": 1.32, "longitude": 103.64}, + is_current=True, + collected_at=now, + ) + ) + db.add( + CollectedData( + source="arcgis_cable_landing_relation", + source_id="rel-1", + data_type="relation", + name="smw6-tuas", + extra_data={"cable_id": "smw6", "city_id": 901}, + is_current=True, + collected_at=now, + ) + ) + db.add( + CollectedData( + source="iptoasn_prefix_geo", + source_id="64512", + data_type="asn_prefix", + name="AS64512 SG Backbone", + extra_data={"asn": "AS64512", "as_name": "SG Backbone", "country": "SG", "latitude": 1.35, "longitude": 103.82}, + is_current=True, + collected_at=now, + ) + ) + await db.commit() + + for oid, expected_stale in [ + ("aircraft:ae1234", False), + ("vessel:563000111", True), + ("cable:smw6", False), + ("landing_point:901", False), + ("asn:AS64512", False), + ("gps_jamming_cell:8465285ffffffff", False), + ("disaster_event:us9991", False), + ("chokepoint:malacca_strait", False), + ("port:port_singapore", False), + ("compute_center:77", False), + ("country:SG", False), + ("interactable:sensor-sg-1", False), + ]: + obj = await resolve_ontology_object(db, oid) + assert obj is not None, f"Failed to resolve {oid}" + assert obj["freshness"]["is_stale"] is expected_stale + assert obj["provenance"]["source"] + + hood = await resolve_ontology_neighborhood(db, "cable:smw6", depth=2, radius_km=120.0) + assert hood is not None + node_ids = {n["object_id"] for n in hood["nodes"]} + assert "landing_point:901" in node_ids + assert "country:SG" in node_ids + assert "compute_center:77" in node_ids + sources = {e["relation_source"] for e in hood["edges"]} + assert "derived_topology" in sources + + lp_hood = await resolve_ontology_neighborhood(db, "landing_point:901", depth=2, radius_km=120.0) + assert lp_hood is not None + assert "asn:AS64512" in {n["object_id"] for n in lp_hood["nodes"]} + + +@pytest.mark.asyncio +async def test_ontology_api_aliases_analyst_links_and_rbac() -> None: + _engine, session_factory = await _make_sqlite_session() + now = datetime.now(UTC) + + async with session_factory() as db: + db.add( + VesselCurrentState( + mmsi=412000999, + lat=1.26, + lon=103.85, + sog=4.0, + name="MV HAIYANG", + source="aisstream_vessels", + observed_at=now, + ) + ) + await db.commit() + + current_role = {"role": UserRole.VIEWER.value, "username": "viewer1"} + + async def _override_db(): + async with session_factory() as session: + yield session + + async def _override_read(): + return SimpleNamespace(id=1, username=current_role["username"], role=current_role["role"]) + + async def _override_user(): + return SimpleNamespace(id=1, username=current_role["username"], role=current_role["role"]) + + app.dependency_overrides[get_db] = _override_db + app.dependency_overrides[require_earth_or_api_access("visualization:read")] = _override_read + app.dependency_overrides[get_current_user] = _override_user + + try: + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: + # Viewer cannot create aliases or analyst links + r_alias_deny = await client.post( + "/api/v1/ontology/aliases", + json={"alias": "Haiyang Vessel", "object_id": "vessel:412000999"}, + ) + assert r_alias_deny.status_code == 403 + r_link_deny = await client.post( + "/api/v1/ontology/links", + json={ + "from_object_id": "vessel:412000999", + "to_object_id": "chokepoint:malacca_strait", + "relation_type": "suspected_escort", + }, + ) + assert r_link_deny.status_code == 403 + + # Admin can create alias & analyst link + current_role["role"] = UserRole.ADMIN.value + current_role["username"] = "admin1" + r_alias_ok = await client.post( + "/api/v1/ontology/aliases", + json={"alias": "Haiyang Vessel", "object_id": "vessel:412000999"}, + ) + assert r_alias_ok.status_code == 200 + assert r_alias_ok.json()["object_id"] == "vessel:412000999" + + r_link_ok = await client.post( + "/api/v1/ontology/links", + json={ + "from_object_id": "vessel:412000999", + "to_object_id": "chokepoint:malacca_strait", + "relation_type": "analyst_corroborated_transit", + "note": "Verified against port log", + "evidence_ids": ["ev-port-1"], + }, + ) + assert r_link_ok.status_code == 200 + assert r_link_ok.json()["relation_source"] == "analyst_asserted" + + # Object GET works for viewer and includes aliases + current_role["role"] = UserRole.VIEWER.value + r_obj = await client.get("/api/v1/ontology/objects/vessel:412000999") + assert r_obj.status_code == 200 + assert r_obj.json()["aliases"][0]["alias"] == "Haiyang Vessel" + + # Neighborhood returns derived + analyst_asserted + r_hood = await client.get("/api/v1/ontology/objects/vessel:412000999/neighborhood?depth=1") + assert r_hood.status_code == 200 + hood = r_hood.json() + assert "analyst_asserted" in hood["relation_sources"] + assert any( + e["relation_type"] == "analyst_corroborated_transit" + for e in hood["edges"] + ) + + async with session_factory() as db: + found = await resolve_alias_to_object_ids(db, "haiyang vessel") + assert found == ["vessel:412000999"] + finally: + app.dependency_overrides.clear() diff --git a/backend/tests/test_private_data_ingest.py b/backend/tests/test_private_data_ingest.py new file mode 100644 index 00000000..5096fc8b --- /dev/null +++ b/backend/tests/test_private_data_ingest.py @@ -0,0 +1,184 @@ +"""Tests for §4.4 private CSV/JSON/REST upload-to-globe, size caps, and ontology/geofence linkage.""" + +from __future__ import annotations + +from contextlib import asynccontextmanager +from types import SimpleNamespace +from unittest.mock import patch + +from httpx import ASGITransport, AsyncClient +import pytest +from sqlalchemy import create_engine +from sqlalchemy.orm import Session + +from app.core.access_gate import 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.geofence import Geofence +from app.services.ai.entity_resolver import resolve_ontology_neighborhood, resolve_ontology_object +from app.services.fusion.anomaly_engine import point_in_geofence + + +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 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 in {"0011"}: + await step.upgrade(shim) + Base.metadata.create_all(raw_conn, checkfirst=True) + + @asynccontextmanager + async def _factory(): + with Session(engine) as session: + yield _AsyncSQLiteSession(session) + + return engine, _factory + + +@pytest.mark.asyncio +async def test_private_upload_csv_json_rest_and_ontology_geofence_linkage(monkeypatch) -> None: + _engine, session_factory = await _make_sqlite_session() + + async def _override_db(): + async with session_factory() as session: + yield session + + async def _override_admin(): + return SimpleNamespace(id=1, username="admin1", role=UserRole.ADMIN.value) + + app.dependency_overrides[get_db] = _override_db + app.dependency_overrides[require_admin_user] = _override_admin + + async with session_factory() as db: + db.add( + Geofence( + name="SG Private Asset Watch", + kind="custom", + geometry={ + "type": "Polygon", + "coordinates": [[[103.5, 1.0], [104.2, 1.0], [104.2, 1.6], [103.5, 1.6], [103.5, 1.0]]], + }, + rules={}, + enabled=True, + created_by="admin1", + ) + ) + await db.commit() + + try: + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: + # 1. CSV E2E + csv_bytes = b"id,name,latitude,longitude,kind\nbuoy-1,SG Acoustic Buoy,1.25,103.85,buoy\n" + r_csv_prev = await client.post( + "/api/v1/interactables/upload/preview", + data={"fmt": "csv"}, + files={"file": ("assets.csv", csv_bytes, "text/csv")}, + ) + assert r_csv_prev.status_code == 200 + prev_csv = r_csv_prev.json() + assert "lat" in prev_csv["field_mapping"] + r_csv_commit = await client.post( + "/api/v1/interactables/upload/commit", + json={ + "records": prev_csv["records"], + "field_mapping": prev_csv["field_mapping"], + "default_kind": "buoy", + }, + ) + assert r_csv_commit.status_code == 200 + assert r_csv_commit.json()["object_ids"] == ["interactable:buoy-1"] + + # 2. JSON E2E + json_bytes = b'[{"uid":"radar-2","title":"Coastal Radar","lat":1.35,"lon":103.90,"type":"radar"}]' + r_json_prev = await client.post( + "/api/v1/interactables/upload/preview", + data={"fmt": "json"}, + files={"file": ("radars.json", json_bytes, "application/json")}, + ) + assert r_json_prev.status_code == 200 + pj = r_json_prev.json() + r_json_commit = await client.post( + "/api/v1/interactables/upload/commit", + json={"records": pj["records"], "field_mapping": pj["field_mapping"], "default_kind": "radar"}, + ) + assert r_json_commit.json()["object_ids"] == ["interactable:radar-2"] + + # 3. REST E2E (mocked fetch) + with patch( + "app.services.private_data_ingest.fetch_rest_records_for_upload", + return_value=[{"code": "sub-3", "label": "Subsea Repeater", "y": 1.30, "x": 103.80}], + ): + r_rest_prev = await client.post( + "/api/v1/interactables/upload/preview", + data={"rest_url": "https://example.invalid/assets.json"}, + ) + assert r_rest_prev.status_code == 200 + pr = r_rest_prev.json() + r_rest_commit = await client.post( + "/api/v1/interactables/upload/commit", + json={"records": pr["records"], "field_mapping": pr["field_mapping"], "default_kind": "repeater"}, + ) + assert r_rest_commit.json()["object_ids"] == ["interactable:sub-3"] + + # 4. Upload row cap enforcement + monkeypatch.setenv("PRIVATE_UPLOAD_MAX_ROWS", "2") + too_many = b"id,name,latitude,longitude\na,A,1,1\nb,B,2,2\nc,C,3,3\n" + r_cap = await client.post( + "/api/v1/interactables/upload/preview", + data={"fmt": "csv"}, + files={"file": ("big.csv", too_many, "text/csv")}, + ) + assert r_cap.status_code == 413 + + # Verify uploaded object resolves into ontology & geofence containment + async with session_factory() as db: + obj = await resolve_ontology_object(db, "interactable:buoy-1") + assert obj is not None + assert obj["attributes"]["kind"] == "buoy" + hood = await resolve_ontology_neighborhood(db, "interactable:buoy-1", depth=1, radius_km=120.0) + assert hood is not None + assert point_in_geofence(obj["lat"], obj["lon"], { + "geometry": { + "type": "Polygon", + "coordinates": [[[103.5, 1.0], [104.2, 1.0], [104.2, 1.6], [103.5, 1.6], [103.5, 1.0]]], + } + }) is True + finally: + app.dependency_overrides.clear() diff --git a/backend/tests/test_replay.py b/backend/tests/test_replay.py new file mode 100644 index 00000000..17c18aa3 --- /dev/null +++ b/backend/tests/test_replay.py @@ -0,0 +1,191 @@ +"""Tests for §4.1 4D replay chunking, out-of-retention unavailable markers, and compute as_of linkage.""" + +from __future__ import annotations + +from contextlib import asynccontextmanager +from datetime import UTC, datetime, timedelta +from types import SimpleNamespace + +from httpx import ASGITransport, AsyncClient +import pytest +from sqlalchemy import create_engine +from sqlalchemy.orm import Session + +from app.core.access_gate import require_earth_or_api_access +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.aircraft import AircraftPosition +from app.models.compute_configuration_revision import ComputeConfigurationRevision +from app.models.vessel import VesselPosition + + +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 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 in {"0009", "0010", "0011"}: + await step.upgrade(shim) + Base.metadata.create_all(raw_conn, checkfirst=True) + + @asynccontextmanager + async def _factory(): + with Session(engine) as session: + yield _AsyncSQLiteSession(session) + + return engine, _factory + + +@pytest.mark.asyncio +async def test_replay_chunk_limit_retention_unavailable_and_compute_as_of() -> None: + _engine, session_factory = await _make_sqlite_session() + now = datetime.now(UTC) + t_mid = now - timedelta(hours=1) + t_start = now - timedelta(hours=2) + + async with session_factory() as db: + db.add_all( + [ + AircraftPosition( + icao24="ae0001", + lat=1.25, + lon=103.80, + altitude_m=9500.0, + ground_speed_ms=220.0, + track_deg=90.0, + observed_at=t_start + timedelta(minutes=1), + ), + AircraftPosition( + icao24="ae0001", + lat=1.35, + lon=103.95, + altitude_m=9600.0, + ground_speed_ms=220.0, + track_deg=85.0, + observed_at=t_mid, + ), + VesselPosition( + mmsi=412000111, + lat=1.22, + lon=103.75, + sog=12.0, + cog=110.0, + received_at=t_start + timedelta(minutes=2), + ), + ComputeConfigurationRevision( + publish_id="pub-rev-1", + action="publish", + content_fingerprint="fp1", + config_payload={}, + published_at=t_start - timedelta(minutes=30), + ), + ComputeConfigurationRevision( + publish_id="pub-rev-2", + action="publish", + content_fingerprint="fp2", + config_payload={}, + published_at=t_mid - timedelta(seconds=30), + ), + ] + ) + await db.commit() + + async def _override_db(): + async with session_factory() as session: + yield session + + async def _override_read(): + return SimpleNamespace(id=1, username="viewer1", role=UserRole.VIEWER.value) + + app.dependency_overrides[get_db] = _override_db + app.dependency_overrides[require_earth_or_api_access("visualization:read")] = _override_read + + try: + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: + r_avail = await client.get("/api/v1/replay/availability") + assert r_avail.status_code == 200 + avail = r_avail.json() + assert avail["layers"]["aircraft"]["retention_hours"] == 24 + assert avail["layers"]["vessels"]["retention_hours"] == 24 + + # Reject > 6h span + r_too_long = await client.get( + "/api/v1/replay/frames", + params={ + "start": (now - timedelta(hours=8)).isoformat(), + "end": now.isoformat(), + }, + ) + assert r_too_long.status_code == 400 + + # Outside 24h retention -> unavailable marker + r_old = await client.get( + "/api/v1/replay/frames", + params={ + "start": (now - timedelta(hours=36)).isoformat(), + "end": (now - timedelta(hours=34)).isoformat(), + "layers": "aircraft,vessels", + }, + ) + assert r_old.status_code == 200 + old_data = r_old.json() + assert old_data["layers"]["aircraft"]["status"] == "unavailable" + assert old_data["layers"]["vessels"]["status"] == "unavailable" + + # Valid window -> columnar frames + compute_as_of switches at t_mid + r_ok = await client.get( + "/api/v1/replay/frames", + params={ + "start": t_start.isoformat(), + "end": now.isoformat(), + "step_sec": 600, + "layers": "aircraft,vessels,satellites,compute", + }, + ) + assert r_ok.status_code == 200 + ok = r_ok.json() + assert ok["layers"]["aircraft"]["status"] == "ok" + assert ok["compute_as_of"][0]["publish_id"] == "pub-rev-1" + assert ok["compute_as_of"][-1]["publish_id"] == "pub-rev-2" + assert ok["layers"]["satellites"]["mode"] == "tle_live_propagation" + finally: + app.dependency_overrides.clear() diff --git a/backend/tests/test_source_freshness.py b/backend/tests/test_source_freshness.py new file mode 100644 index 00000000..700f4d5a --- /dev/null +++ b/backend/tests/test_source_freshness.py @@ -0,0 +1,180 @@ +"""Phase 3.1 domain freshness, sanitization, blind-spot injection, and endpoint tests.""" + +from __future__ import annotations + +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.session import Base, get_db +from app.main import app +from app.models.aircraft import AircraftCurrentState +from app.models.compute_configuration_revision import ComputeConfigurationRevision +from app.models.datasource import DataSource +from app.models.task import CollectionTask +from app.services.ai.tool_registry import query_global_situational_tool +from app.services.ai.workflow_registry import BUILTIN_WORKFLOWS +from app.services.source_freshness import ( + DOMAIN_SPEC_BY_KEY, + VALID_FRESHNESS_STATUSES, + classify_domain_freshness, + compute_domain_freshness, +) + + +class _AsyncSQLiteSession: + def __init__(self, session: Session): + self._session = session + + def get_bind(self): + return self._session.get_bind() + + 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() + + +def _create_sqlite_session() -> Session: + engine = create_engine("sqlite:///:memory:") + Base.metadata.create_all(bind=engine) + return Session(engine) + + +def test_classify_domain_freshness_covers_all_seven_statuses(): + now = datetime(2026, 12, 6, 12, 0, tzinfo=UTC) + spec = DOMAIN_SPEC_BY_KEY["aircraft"] # 300s threshold + + cases = { + "fresh": dict(last_success_at=now - timedelta(minutes=2), has_active_source=True, has_any_source=True, all_disabled=False, has_unconfigured_only=False, has_recent_failure=False, all_failed_offline=False), + "stale": dict(last_success_at=now - timedelta(minutes=8), has_active_source=True, has_any_source=True, all_disabled=False, has_unconfigured_only=False, has_recent_failure=False, all_failed_offline=False), + "very_stale": dict(last_success_at=now - timedelta(minutes=30), has_active_source=True, has_any_source=True, all_disabled=False, has_unconfigured_only=False, has_recent_failure=False, all_failed_offline=False), + "degraded": dict(last_success_at=now - timedelta(minutes=1), has_active_source=True, has_any_source=True, all_disabled=False, has_unconfigured_only=False, has_recent_failure=True, all_failed_offline=False), + "offline": dict(last_success_at=now - timedelta(minutes=1), has_active_source=True, has_any_source=True, all_disabled=False, has_unconfigured_only=False, has_recent_failure=True, all_failed_offline=True), + "disabled": dict(last_success_at=now - timedelta(minutes=1), has_active_source=False, has_any_source=True, all_disabled=True, has_unconfigured_only=False, has_recent_failure=False, all_failed_offline=False), + "not_configured": dict(last_success_at=None, has_active_source=False, has_any_source=True, all_disabled=False, has_unconfigured_only=True, has_recent_failure=False, all_failed_offline=False), + } + + for expected_status, kwargs in cases.items(): + res = classify_domain_freshness(spec, now=now, **kwargs) + assert res["status"] == expected_status + assert res["status"] in VALID_FRESHNESS_STATUSES + assert res["is_blind_spot"] is (expected_status != "fresh") + + +@pytest.mark.asyncio +async def test_freshness_endpoint_sanitizes_internal_errors_and_computes_blind_spots(): + sync_session = _create_sqlite_session() + now = datetime.now(UTC) + + sync_session.add( + DataSource( + id=39, + name="adsb.lol", + source="adsb_lol_aircraft", + module="L4", + priority="P1", + frequency_minutes=1, + collector_class="ADSBCollector", + is_active=True, + last_run_at=now - timedelta(minutes=1), + last_status="success", + ) + ) + sync_session.add( + AircraftCurrentState( + icao24="ae0001", + lat=25.0, + lon=121.5, + source="adsb_lol_aircraft", + observed_at=now - timedelta(minutes=1), + ingested_at=now, + ) + ) + sync_session.add( + DataSource( + id=27, + name="barentswatch", + source="barentswatch_vessels", + module="L4", + priority="P1", + frequency_minutes=1, + collector_class="VesselCollector", + is_active=True, + last_run_at=now - timedelta(hours=2), + last_status="failed", + ) + ) + secret_url = "https://internal-secret.corp/token=TOP_SECRET_12345" + sync_session.add( + CollectionTask( + datasource_id=27, + source="barentswatch_vessels", + task_type="collect", + status="failed", + error_message=f"Traceback: ConnectError while dialing {secret_url}", + created_at=now, + ) + ) + sync_session.add( + ComputeConfigurationRevision( + publish_id="rev-fresh-001", + action="publish", + content_fingerprint="abc123", + is_default_content=False, + config_payload={}, + published_at=now, + ) + ) + sync_session.commit() + + async_db = _AsyncSQLiteSession(sync_session) + + async def _override_get_db(): + yield async_db + + app.dependency_overrides[get_db] = _override_get_db + try: + report = await compute_domain_freshness(async_db, now=now) + serialized = str(report) + assert "TOP_SECRET_12345" not in serialized + assert "internal-secret.corp" not in serialized + assert "Traceback" not in serialized + + by_domain = {d["domain"]: d for d in report["domains"]} + assert by_domain["aircraft"]["status"] == "fresh" + assert by_domain["compute"]["status"] == "fresh" + assert by_domain["vessels"]["status"] in {"stale", "offline", "degraded"} + assert any(b["domain"] == "vessels" for b in report["blind_spots"]) + + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: + resp = await client.get("/api/v1/system/freshness") + assert resp.status_code == 200 + payload = resp.json() + assert payload["blind_spot_count"] >= 1 + assert "TOP_SECRET_12345" not in resp.text + assert "Traceback" not in resp.text + finally: + app.dependency_overrides.clear() + + +@pytest.mark.asyncio +async def test_global_situational_tool_injects_blind_spots_and_workflow_prompts_enforce_rule(): + sync_session = _create_sqlite_session() + async_db = _AsyncSQLiteSession(sync_session) + result = await query_global_situational_tool(async_db) + assert "blind_spots" in result + assert "freshness" in result + assert isinstance(result["blind_spots"], list) + assert len(result["blind_spots"]) >= 1 + + wf_map = {w["workflow_id"]: w for w in BUILTIN_WORKFLOWS} + for wf_id in ("default.general", "wargame.infrastructure"): + llm_nodes = [n for n in wf_map[wf_id]["graph"]["nodes"] if n.get("node_type") == "llm_agent"] + assert llm_nodes + prompt = llm_nodes[0]["system_prompt"] + assert "blind_spots" in prompt + assert "无事件" in prompt diff --git a/backend/tests/test_spatial_cards_and_scene.py b/backend/tests/test_spatial_cards_and_scene.py new file mode 100644 index 00000000..3642b115 --- /dev/null +++ b/backend/tests/test_spatial_cards_and_scene.py @@ -0,0 +1,56 @@ +"""Tests for §3.6 universal spatial workflow cards and StageStepSpec scene schema.""" + +from __future__ import annotations + +from app.services.ai.presentation_compiler import StageCameraPose, StageStepSpec +from app.services.ai.scene_directives import extract_planet_scene_from_text + + +def test_extract_planet_scene_supports_spatial_cards_and_overlays() -> None: + text = ( + "结论摘要。\n" + '{"influence_zones":[],"spatial_cards":[{"key":"malacca","title":"马六甲监视","anchor":{"latitude":2.5,"longitude":101.2},"side":"left","blocks":[{"block_type":"entity_samples","data":{"items":[{"object_id":"chokepoint:malacca","label":"Malacca Strait"}]}}]}],"overlays":["chokepoints","geofences"]}' + ) + cleaned, scene = extract_planet_scene_from_text(text) + assert cleaned == "结论摘要。" + assert scene is not None + assert len(scene["spatial_cards"]) == 1 + assert scene["spatial_cards"][0]["key"] == "malacca" + assert scene["spatial_cards"][0]["anchor"]["latitude"] == 2.5 + assert scene["overlays"] == ["chokepoints", "geofences"] + + +def test_stage_step_spec_preserves_compute_fields_and_accepts_workflow_fields() -> None: + step = StageStepSpec( + step_id="step-1", + stage="discover", + title="发现关联", + title_en="Discover Correlation", + caption="定位目标走廊", + caption_en="Locate target corridor", + camera=StageCameraPose(lat=1.2, lon=103.8, zoom=1.1), + workflow_params={"chokepoint": "malacca"}, + spotlight_card_keys=["malacca"], + overlays=["chokepoints", "dependency_arcs"], + spatial_cards=[{"key": "malacca", "anchor": {"latitude": 1.2, "longitude": 103.8}}], + ) + assert step.workflow_params == {"chokepoint": "malacca"} + assert step.overlays == ["chokepoints", "dependency_arcs"] + assert step.spotlight_card_keys == ["malacca"] + + legacy = StageStepSpec( + step_id="compute-step", + stage="divergence", + title="结构差异", + title_en="Divergence", + caption="基线比较", + caption_en="Baseline compare", + camera=StageCameraPose(lat=35.0, lon=104.0), + compute_mode="global_share", + focus_year=2025, + spotlight_Statistic_codes=["CN", "US"], + enable_national_hubs=True, + ) + assert legacy.compute_mode == "global_share" + assert legacy.enable_national_hubs is True + assert legacy.overlays == [] diff --git a/backend/tests/test_storage_policy.py b/backend/tests/test_storage_policy.py index 1414ec9d..7af9a2ad 100644 --- a/backend/tests/test_storage_policy.py +++ b/backend/tests/test_storage_policy.py @@ -34,6 +34,11 @@ from app.models.system_log import ObservabilityEvent, SystemLog from app.models.system_setting import SystemSetting from app.models.task import CollectionTask from app.models.user import User +from app.models.aircraft import ( + ADSBSourceHealth, + AircraftCurrentState, + AircraftPosition, +) from app.models.vessel import ( AISRawObservation, AISSourceHealth, @@ -131,6 +136,9 @@ def sqlite_db(): AISSourceHealth.__table__, VesselCurrentState.__table__, VesselPosition.__table__, + ADSBSourceHealth.__table__, + AircraftCurrentState.__table__, + AircraftPosition.__table__, BGPObservation.__table__, BGPAnomaly.__table__, BGPIncident.__table__, diff --git a/backend/tests/test_visualization_satellite_streaming.py b/backend/tests/test_visualization_satellite_streaming.py index 3b19f243..a53b0c1e 100644 --- a/backend/tests/test_visualization_satellite_streaming.py +++ b/backend/tests/test_visualization_satellite_streaming.py @@ -49,6 +49,18 @@ def satellite_db() -> Iterator[SatelliteSession]: engine.dispose() +def _tle1(record_id: int) -> str: + line = f"1 {record_id + 40000:05d}U 24001A 26001.00000000 .00001000 00000-0 10000-3 0 999{record_id % 10}" + assert len(line) == 69 + return line + + +def _tle2(record_id: int) -> str: + line = f"2 {record_id + 40000:05d} 53.0000 120.0000 0001000 90.0000 45.0000 15.0000000000000{record_id % 10}" + assert len(line) == 69 + return line + + def satellite( record_id: int, *, current: bool = True, task_id: int = 1, name: str | None = None, source: str = "celestrak_tle", @@ -64,8 +76,8 @@ def satellite( collected_at=datetime(2026, 1, 1, tzinfo=UTC) + timedelta(days=task_id), extra_data={ "norad_cat_id": record_id + 40000, - "tle_line1": f"line-1-{record_id}", - "tle_line2": f"line-2-{record_id}", + "tle_line1": _tle1(record_id), + "tle_line2": _tle2(record_id), }, ) @@ -89,7 +101,7 @@ async def test_streamed_satellites_preserve_all_rows_order_tle_and_limit( assert payload["count"] == len(expected_ids) assert [feature["properties"]["id"] for feature in payload["features"]] == expected_ids assert [feature["properties"]["tle_line1"] for feature in payload["features"]] == [ - f"line-1-{record_id}" for record_id in expected_ids + _tle1(record_id) for record_id in expected_ids ] assert len(satellite_db.streams) == 1 assert satellite_db.streams[0].closed @@ -194,7 +206,7 @@ async def test_compact_satellite_builder_emits_compact_rows_and_fallback_element rows_by_id = {row[0]: row for row in payload["satellites"]} assert len(rows_by_id[10]) == 6 assert rows_by_id[10][:4] == [10, 40010, "SAT-10", None] - assert rows_by_id[10][4:6] == ["line-1-10", "line-2-10"] + assert rows_by_id[10][4:6] == [_tle1(10), _tle2(10)] assert rows_by_id[12][:4] == [12, 40012, "STARLINK-1234", "starlink"] assert len(rows_by_id[11]) == 7 assert rows_by_id[11][4] is None diff --git a/backend/tests/test_wargame_scenarios.py b/backend/tests/test_wargame_scenarios.py new file mode 100644 index 00000000..8a146227 --- /dev/null +++ b/backend/tests/test_wargame_scenarios.py @@ -0,0 +1,303 @@ +"""End-to-end recorded-fixture tests for §3.10 wargame scenarios & incident resolution.""" + +from __future__ import annotations + +from contextlib import asynccontextmanager +from datetime import UTC, datetime, timedelta +from types import SimpleNamespace + +from httpx import ASGITransport, AsyncClient +import pytest +from sqlalchemy import create_engine +from sqlalchemy.orm import Session + +from app.core.access_gate import get_current_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.aircraft import AircraftCurrentState +from app.models.bgp_incident import BGPIncident +from app.models.collected_data import CollectedData +from app.models.compute_center_location import ComputeCenterLocationRecord +from app.models.gps_jamming import GPSJammingCell +from app.models.maritime_advisory import CableAdvisory +from app.models.vessel import VesselCurrentState +from app.services.ai.workflow_registry import BUILTIN_WORKFLOWS +from app.services.fusion.wargame_scenarios import ( + run_air_sea_em_scenario, + run_cable_protection_scenario, +) + + +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 in {"0009", "0010", "0011"}: + await step.upgrade(shim) + Base.metadata.create_all(raw_conn, checkfirst=True) + + @asynccontextmanager + async def _factory(): + with Session(engine) as session: + yield _AsyncSQLiteSession(session) + + return engine, _factory + + +def test_wargame_workflows_registered_in_builtin_catalog() -> None: + ids = {wf["workflow_id"] for wf in BUILTIN_WORKFLOWS} + assert "wargame.cable_protection" in ids + assert "wargame.air_sea_em" in ids + + +@pytest.mark.asyncio +async def test_cable_protection_scenario_upgrades_only_with_nga_evidence_and_triage_roundtrip() -> None: + _engine, session_factory = await _make_sqlite_session() + now = datetime.now(UTC) + + async with session_factory() as db: + db.add_all( + [ + CollectedData( + source="arcgis_cables", + source_id="apg-1", + data_type="cable", + name="APG Cable", + extra_data={"cable_id": "apg-1", "coordinates": [[103.6, 1.25], [103.85, 1.28]]}, + is_current=True, + collected_at=now, + ), + CollectedData( + source="arcgis_cables", + source_id="smw6", + data_type="cable", + name="SEA-ME-WE 6", + extra_data={"cable_id": "smw6", "coordinates": [[103.5, 1.22], [103.9, 1.31]]}, + is_current=True, + collected_at=now, + ), + CollectedData( + source="arcgis_landing_points", + source_id="tuas", + data_type="landing_point", + name="Tuas", + extra_data={"city_id": 901, "country": "Singapore", "latitude": 1.32, "longitude": 103.64}, + is_current=True, + collected_at=now, + ), + CollectedData( + source="arcgis_cable_landing_relation", + source_id="r1", + data_type="relation", + name="apg-tuas", + extra_data={"cable_id": "apg-1", "city_id": 901}, + is_current=True, + collected_at=now, + ), + CollectedData( + source="arcgis_cable_landing_relation", + source_id="r2", + data_type="relation", + name="smw6-tuas", + extra_data={"cable_id": "smw6", "city_id": 901}, + is_current=True, + collected_at=now, + ), + ComputeCenterLocationRecord( + id=77, + source="top500", + source_id="sg-77", + name="SG National HPC", + country="SG", + latitude=1.34, + longitude=103.81, + verified_at=now, + ), + VesselCurrentState( + mmsi=412111222, + lat=1.27, + lon=103.75, + sog=1.4, + name="LOITERING WORKBOAT", + source="aisstream_vessels", + observed_at=now - timedelta(minutes=2), + ), + BGPIncident( + source="ris_live_bgp", + incident_key="bgp-sg-1", + incident_type="outage", + title="SG Transit Flap", + summary="Transient BGP flap in AS4657", + severity="medium", + affected_asns=[4657], + started_at=now - timedelta(minutes=10), + ), + ] + ) + await db.commit() + + # Step 1: Without matching NGA advisory -> strictly candidate_correlation ("待核查关联") + res1 = await run_cable_protection_scenario( + db, cable_id="apg-1", suspect_vessel_mmsi=412111222, now=now + ) + assert res1["assessment_kind"] == "candidate_correlation" + assert res1["verdict_label"] == "待核查关联" + assert res1["contains_causal_assertion"] is False + assert "待核查关联" in res1["incident"]["title"] + assert len(res1["spatial_cards"]) == 2 + assert "dependency_arcs" not in res1["overlays"] + + # Step 2: Add matching NGA CableAdvisory -> upgrades to dependency_impact with arcs + db.add( + CableAdvisory( + source_warning_id="HYDROPAC 202/26", + text="APG CABLE REPAIR OPS AT 01-16N 103-45E", + lat=1.27, + lon=103.75, + issued_at=now - timedelta(minutes=30), + matched_cable_ids=["apg-1"], + match_method="haversine_50km", + ingested_at=now, + ) + ) + await db.commit() + + res2 = await run_cable_protection_scenario( + db, cable_id="apg-1", suspect_vessel_mmsi=412111222, now=now + ) + assert res2["assessment_kind"] == "dependency_impact" + assert res2["verdict_label"] == "依赖影响" + assert "dependency_arcs" in res2["overlays"] + assert len(res2["impact_arcs"]) >= 1 + assert "SG" in res2["impacted_countries"] + assert any(b["cable_id"] == "smw6" for b in res2["backup_cables"]) + impact_id = res2["incident"]["id"] + + async def _override_db(): + async with session_factory() as session: + yield session + + async def _override_user(): + return SimpleNamespace(id=1, username="admin1", role=UserRole.ADMIN.value) + + app.dependency_overrides[get_db] = _override_db + app.dependency_overrides[get_current_user] = _override_user + try: + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: + r_ack = await client.post(f"/api/v1/incidents/{impact_id}/acknowledge", json={}) + assert r_ack.status_code == 200 + assert r_ack.json()["status"] == "acknowledged" + r_dis = await client.post( + f"/api/v1/incidents/{impact_id}/dismiss", + json={"resolution_note": "Scheduled maintenance confirmed by operator"}, + ) + assert r_dis.status_code == 200 + assert r_dis.json()["status"] == "dismissed" + finally: + app.dependency_overrides.clear() + + +@pytest.mark.asyncio +async def test_air_sea_em_scenario_lists_blind_spots_without_causality() -> None: + _engine, session_factory = await _make_sqlite_session() + now = datetime.now(UTC) + + async with session_factory() as db: + db.add_all( + [ + GPSJammingCell( + h3_index="8465285ffffffff", + observed_date=now.date().isoformat(), + lat=2.0, + lon=102.0, + resolution=4, + level="high", + bad_ratio=0.48, + aircraft_count=22, + boundary=[[1.9, 101.9], [2.1, 102.1]], + source="gpsjam_interference", + ingested_at=now, + ), + AircraftCurrentState( + icao24="ae8881", + callsign="FORTE12", + lat=2.05, + lon=102.05, + squawk="7700", + on_ground=False, + is_military=True, + is_emergency=True, + source="adsb_lol_aircraft", + observed_at=now - timedelta(minutes=1), + ingested_at=now, + ), + VesselCurrentState( + mmsi=338000111, + lat=2.01, + lon=101.95, + sog=14.0, + name="USS PATROL", + vessel_type=35, + source="aisstream_vessels", + observed_at=now - timedelta(minutes=3), + ), + ] + ) + await db.commit() + + res = await run_air_sea_em_scenario(db, center_lat=2.0, center_lon=102.0, now=now) + assert res["assessment_kind"] == "candidate_correlation" + assert res["aircraft_count"] == 1 + assert res["gps_jamming_count"] == 1 + assert res["warship_count"] == 1 + assert res["contains_causal_assertion"] is False + assert "待核查关联" in res["incident"]["title"] + assert len(res["blind_spots"]) > 0 + assert "情报盲区" in res["briefing"] + assert len(res["spatial_cards"]) == 2 diff --git a/client/package.json b/client/package.json index 8286b8ea..7e517db0 100644 --- a/client/package.json +++ b/client/package.json @@ -1,6 +1,6 @@ { "name": "planet-client", - "version": "0.84.2", + "version": "0.85.0", "description": "Intelligent Planet Program - Native Electron Earth Viewer", "private": true, "packageManager": "bun@1", diff --git a/client/scripts/build-earth-bundle.mjs b/client/scripts/build-earth-bundle.mjs index 6f2eeec5..272f0c80 100644 --- a/client/scripts/build-earth-bundle.mjs +++ b/client/scripts/build-earth-bundle.mjs @@ -14,6 +14,9 @@ const earthSourceDir = join(repoRoot, 'frontend/public/earth') const bundleEarthDir = join(desktopRoot, '.earth-bundle/earth') const require = createRequire(join(desktopRoot, 'package.json')) +const desktopRequire = createRequire(join(desktopRoot, 'package.json')) +const frontendRequire = createRequire(join(repoRoot, 'frontend/package.json')) + const VENDOR_PACKAGES = [ { id: 'three', outFile: 'three.mjs' }, { id: 'pmtiles', outFile: 'pmtiles.mjs' }, @@ -47,6 +50,16 @@ for (const pkg of VENDOR_PACKAGES) { importMapOverrides[pkg.id] = `./vendor/${pkg.outFile}` } +const maplibreDistDir = join(dirname(frontendRequire.resolve('maplibre-gl/package.json')), 'dist') +for (const fileName of ['maplibre-gl.mjs', 'maplibre-gl-worker.mjs', 'maplibre-gl.css']) { + const src = join(maplibreDistDir, fileName) + if (existsSync(src)) { + cpSync(src, join(bundleEarthDir, 'vendor', fileName)) + } +} +importMapOverrides['maplibre-gl'] = './vendor/maplibre-gl.mjs' +void desktopRequire + const { assets, html } = await compileEarthRuntime({ earthDir: earthSourceDir, importMapOverrides, @@ -76,14 +89,39 @@ if (!workerBuild.success) { // Earth boundary PMTiles artifacts are served by the backend API // (/api/v1/earth/boundaries/...); legacy local builds must never ship in the -// desktop installer. +// desktop installer. Large card original images whose 640/1280 WebP variants +// already live in previews/ are also omitted so the installer stays slim. const legacyBoundaryArtifacts = join(earthSourceDir, 'data', 'boundaries') +const cardsDir = join(earthSourceDir, 'assets', 'cards') +const skippedCardOriginals = new Set() +try { + const manifestPath = join(cardsDir, 'manifest.json') + if (existsSync(manifestPath)) { + const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) + for (const item of manifest.assets || []) { + const has640 = Boolean(item?.variants?.['640']) + const has1280 = Boolean(item?.variants?.['1280']) + if (has640 && has1280 && item?.file) { + const preview640 = join(earthSourceDir, item.variants['640'].replace(/^\/earth\//, '')) + const preview1280 = join(earthSourceDir, item.variants['1280'].replace(/^\/earth\//, '')) + if (existsSync(preview640) && existsSync(preview1280)) { + skippedCardOriginals.add(join(cardsDir, item.file)) + } + } + } + } +} catch { + // Fall back to copying all card assets if manifest inspection fails. +} for (const folder of ['css', 'assets', 'data']) { const srcFolder = join(earthSourceDir, folder) if (existsSync(srcFolder)) { cpSync(srcFolder, join(bundleEarthDir, folder), { recursive: true, - filter: (src) => src !== legacyBoundaryArtifacts && !src.startsWith(`${legacyBoundaryArtifacts}${sep}`), + filter: (src) => + src !== legacyBoundaryArtifacts && + !src.startsWith(`${legacyBoundaryArtifacts}${sep}`) && + !skippedCardOriginals.has(src), }) } } diff --git a/client/src/main/config.ts b/client/src/main/config.ts index 1ede16d6..c21e4118 100644 --- a/client/src/main/config.ts +++ b/client/src/main/config.ts @@ -1,6 +1,10 @@ import fs from 'node:fs' import path from 'node:path' +import { DEFAULT_UI_SCALE_MODE, normalizeUiScaleMode, type UiScaleMode } from './ui-scale' + +export type { UiScaleMode } + export type SplashTheme = 'singularity' | 'off' export type GpuRenderMode = 'auto' | 'high-performance' | 'low-power' | 'software' @@ -13,6 +17,7 @@ export interface ServerEndpoints { export interface PersistedUserConfig extends Partial { splashTheme?: SplashTheme gpuMode?: GpuRenderMode + uiScale?: UiScaleMode recordAudio?: boolean recordHideCursor?: boolean } @@ -43,6 +48,7 @@ export interface DesktopLaunchFlags { deepLinkUrl: string | null splashThemeOverride?: SplashTheme gpuModeOverride?: GpuRenderMode + uiScaleOverride?: UiScaleMode gpuHandoff: boolean gpuHandoffTarget?: GpuHandoffTarget } @@ -51,6 +57,7 @@ export interface DesktopRuntimeConfig extends ServerEndpoints, DesktopLaunchFlag wsUrl: string splashTheme: SplashTheme gpuMode: GpuRenderMode + uiScale: UiScaleMode recordAudio: boolean recordHideCursor: boolean } @@ -206,6 +213,10 @@ export function parseLaunchArgs(argv: string[]): { flags.gpuModeOverride = normalizeGpuMode(arg.slice('--gpu-mode='.length)) } else if (arg === '--gpu-mode' && argv[i + 1]) { flags.gpuModeOverride = normalizeGpuMode(argv[++i]) + } else if (arg.startsWith('--ui-scale=')) { + flags.uiScaleOverride = normalizeUiScaleMode(arg.slice('--ui-scale='.length)) + } else if (arg === '--ui-scale' && argv[i + 1]) { + flags.uiScaleOverride = normalizeUiScaleMode(argv[++i]) } else if (arg === '--software-gl') { flags.gpuModeOverride = 'software' } else if (arg === '--low-power-gpu') { @@ -340,6 +351,13 @@ export class DesktopConfigStore { userSaved.gpuMode, 'auto', ) + const uiScale = normalizeUiScaleMode( + this.launchFlags.uiScaleOverride ?? + env.PLANET_UI_SCALE ?? + portable.uiScale ?? + userSaved.uiScale, + DEFAULT_UI_SCALE_MODE, + ) const recordAudio = normalizeBooleanFlag(portable.recordAudio ?? userSaved.recordAudio, false) const recordHideCursor = normalizeBooleanFlag( portable.recordHideCursor ?? userSaved.recordHideCursor, @@ -353,6 +371,7 @@ export class DesktopConfigStore { wsUrl: deriveBackendWsUrl(backendUrl), splashTheme, gpuMode, + uiScale, recordAudio, recordHideCursor, ...this.launchFlags, @@ -407,6 +426,16 @@ export class DesktopConfigStore { return this.get() } + updateUiScale(rawScale: unknown): DesktopRuntimeConfig { + const nextScale = normalizeUiScaleMode(rawScale, this.current.uiScale) + this.writeUserConfig({ uiScale: nextScale }) + this.current = { + ...this.current, + uiScale: nextScale, + } + return this.get() + } + updateRecordAudio(enabled: unknown): DesktopRuntimeConfig { const nextRecordAudio = normalizeBooleanFlag(enabled, this.current.recordAudio) this.writeUserConfig({ recordAudio: nextRecordAudio }) diff --git a/client/src/main/index.ts b/client/src/main/index.ts index 97abc072..e8601f4a 100644 --- a/client/src/main/index.ts +++ b/client/src/main/index.ts @@ -3,7 +3,7 @@ import path from 'node:path' import { app, BrowserWindow, dialog, ipcMain, Menu, net, session, shell } from 'electron' -import { DesktopConfigStore, normalizeSplashTheme, readPreReadyGpuHandoff, readPreReadyGpuMode, type GpuRenderMode, type ServerEndpoints } from './config' +import { DesktopConfigStore, normalizeSplashTheme, readPreReadyGpuHandoff, readPreReadyGpuMode, type GpuRenderMode, type ServerEndpoints, type UiScaleMode } from './config' import { DESKTOP_SCHEME, registerDesktopLink } from './desktop-link' import { createEarthDesktopAuth } from './earth-auth' import { createAdaptiveGpuMonitor, probeWindowsGpuEnvironmentSync } from './gpu-monitor' @@ -13,8 +13,9 @@ import { createHotUpdateController } from './hot-updater' import { tClient } from './i18n' import { buildApplicationMenu } from './menu' import { EARTH_ORIGIN, installEarthSessionHandlers, registerEarthScheme } from './protocol' +import { clearDiskAssetCache, getDiskAssetCacheStats } from './protocol-core' import { createScreenRecorderController } from './screen-recorder' -import { createMainWindow, dismissMenuBarOnPointerDown, flushWindowState, toggleWindowOrientation } from './window' +import { createMainWindow, dismissMenuBarOnPointerDown, flushWindowState, getWindowUiZoomFactor, syncWindowUiZoom, toggleWindowOrientation } from './window' registerEarthScheme() @@ -236,6 +237,7 @@ if (!singleInstanceLock) { const refreshApplicationMenu = () => { if (!mainWindow || mainWindow.isDestroyed()) return + const menuWasVisible = process.platform === 'darwin' ? true : mainWindow.isMenuBarVisible() Menu.setApplicationMenu( buildApplicationMenu({ mainWindow, @@ -286,8 +288,18 @@ if (!singleInstanceLock) { onOpenRecordingsFolder: () => { void screenRecorder?.openRecordingsFolder() }, + getEffectiveUiZoomFactor: () => getWindowUiZoomFactor(mainWindow), + onSelectUiScale: (nextScale: UiScaleMode) => { + configStore.updateUiScale(nextScale) + syncWindowUiZoom(mainWindow) + screenRecorder?.syncUiZoom() + refreshApplicationMenu() + }, }), ) + if (process.platform !== 'darwin' && !menuWasVisible && !mainWindow.isDestroyed()) { + mainWindow.setMenuBarVisibility(false) + } } screenRecorder = createScreenRecorderController({ @@ -312,14 +324,21 @@ if (!singleInstanceLock) { fetchImpl: (input, init) => net.fetch(input as string, init), }) + const assetCacheDir = path.join(app.getPath('userData'), 'asset-cache') installEarthSessionHandlers(session.defaultSession, { earthBundleRoot, getEarthOverlayRoot: () => hotUpdater.getOverlayRoot(), - boundaryCacheDir: path.join(app.getPath('userData'), 'earth-cache', 'boundaries'), + assetCacheDir, getBackendUrl: () => configStore.get().backendUrl, getEarthAuthToken: (opts) => earthAuth.getToken(opts), }) + ipcMain.handle('planet:get-asset-cache-stats', () => getDiskAssetCacheStats(assetCacheDir)) + ipcMain.handle('planet:clear-asset-cache', (_event, buckets: unknown) => { + clearDiskAssetCache(assetCacheDir, Array.isArray(buckets) ? buckets.map(String) : undefined) + return getDiskAssetCacheStats(assetCacheDir) + }) + ipcMain.handle('planet:get-earth-session-token', (_event, opts: unknown) => { const forceRefresh = Boolean( opts && typeof opts === 'object' && (opts as { forceRefresh?: unknown }).forceRefresh, @@ -363,6 +382,7 @@ if (!singleInstanceLock) { gpuMode: cfg.gpuMode, gpuTarget: startupGpuDecision.target, gpuHandoff: cfg.gpuHandoff, + uiScale: cfg.uiScale, headlessSmoke: cfg.headlessSmoke, isElectron: true, platform: process.platform, @@ -442,6 +462,10 @@ if (!singleInstanceLock) { onToggleRecording: () => { void screenRecorder?.toggleRecording({ fromMenu: false }) }, + onUiZoomChanged: () => { + screenRecorder?.syncUiZoom() + refreshApplicationMenu() + }, }) mainWindow.on('close', (event) => { @@ -495,12 +519,12 @@ if (!singleInstanceLock) { if (isHeadlessSmoke) { const smokeTimeout = setTimeout(() => { app.exit(1) - }, 25000) + }, 30000) mainWindow.webContents.once('did-finish-load', async () => { try { const earthStartup = await mainWindow!.webContents.executeJavaScript(`new Promise((resolve) => { - const deadline = performance.now() + 14000; + const deadline = performance.now() + 18000; const poll = () => { const ready = document.documentElement.dataset.earthStartupReady === '1'; const progress = document.documentElement.dataset.earthStartupProgress || ''; @@ -581,12 +605,15 @@ if (!singleInstanceLock) { }); })`) + const cfg = configStore.get() const enrichedReport = { ...report, earthStartupReady: earthStartup.ready, earthStartupProgress: earthStartup.progress, hasApplicationMenu, menuBarInitiallyHidden, + uiScaleMode: cfg.uiScale, + uiZoomFactor: getWindowUiZoomFactor(mainWindow), afterPortraitToggle, portraitBounds, portraitLayoutMode: portraitDom.mode, @@ -596,7 +623,6 @@ if (!singleInstanceLock) { restoredInnerWidth: landscapeDom.width, splashCheck, } - const cfg = configStore.get() if (cfg.smokeOutputPath) { fs.mkdirSync(path.dirname(cfg.smokeOutputPath), { recursive: true }) fs.writeFileSync(cfg.smokeOutputPath, JSON.stringify(enrichedReport, null, 2), 'utf8') diff --git a/client/src/main/menu.ts b/client/src/main/menu.ts index df7375b8..7ac584fe 100644 --- a/client/src/main/menu.ts +++ b/client/src/main/menu.ts @@ -5,6 +5,7 @@ import type { GpuRuntimeSummary } from './gpu-monitor' import type { HotUpdateVersionInfo } from './hot-updater' import { tClient } from './i18n' import type { RecordingStatusSnapshot } from './recording-core' +import { formatUiScalePercent, UI_SCALE_PRESETS, type UiScaleMode } from './ui-scale' import { openServerSettingsDialog, toggleWindowOrientation } from './window' function formatGpuSummaryLabel(summary: GpuRuntimeSummary): string { @@ -38,6 +39,8 @@ export function buildApplicationMenu(options: { onToggleRecordAudio?: (enabled: boolean) => void onToggleRecordHideCursor?: (enabled: boolean) => void onOpenRecordingsFolder?: () => void + getEffectiveUiZoomFactor?: () => number + onSelectUiScale?: (mode: UiScaleMode) => void }): Menu { const sendAction = (action: string) => { if (!options.mainWindow.isDestroyed()) { @@ -52,6 +55,8 @@ export function buildApplicationMenu(options: { const currentSplashTheme = options.configStore.get().splashTheme const currentGpuMode = options.configStore.get().gpuMode + const currentUiScale = options.configStore.get().uiScale + const effectiveUiZoom = options.getEffectiveUiZoomFactor?.() ?? (currentUiScale === 'auto' ? 1 : currentUiScale) const currentRecordAudio = options.configStore.get().recordAudio const currentRecordHideCursor = options.configStore.get().recordHideCursor const gpuSummary = options.getGpuStatus?.() @@ -271,6 +276,32 @@ export function buildApplicationMenu(options: { click: () => sendAction('reset-view'), }, { type: 'separator' }, + { + label: tClient('界面缩放', 'Interface Scale'), + submenu: [ + { + label: tClient( + `自动(当前 ${formatUiScalePercent(effectiveUiZoom)})`, + `Auto (${formatUiScalePercent(effectiveUiZoom)})`, + ), + type: 'radio', + checked: currentUiScale === 'auto', + click: () => { + options.onSelectUiScale?.('auto') + }, + }, + { type: 'separator' }, + ...UI_SCALE_PRESETS.map((preset) => ({ + label: formatUiScalePercent(preset), + type: 'radio' as const, + checked: currentUiScale === preset, + click: () => { + options.onSelectUiScale?.(preset) + }, + })), + ], + }, + { type: 'separator' }, { label: tClient('切换横竖屏', 'Toggle Portrait & Landscape'), accelerator: 'CmdOrCtrl+Shift+M', diff --git a/client/src/main/protocol-core.ts b/client/src/main/protocol-core.ts index 3cdd2cba..327d9639 100644 --- a/client/src/main/protocol-core.ts +++ b/client/src/main/protocol-core.ts @@ -166,6 +166,185 @@ export function createStaticFileResponse( const BOUNDARY_FILES_PREFIX = '/api/v1/earth/boundaries/files/' const BOUNDARY_ARTIFACT_NAME_RE = /^[A-Za-z0-9._-]+\.(pmtiles|json)$/ const BOUNDARY_PREFIX_GROUPS = ['earth-boundaries.', 'hover-index.', 'hover-borders.', 'geo-labels.'] +const CARD_IMAGE_FILES_PREFIX = '/api/v1/earth/card-images/files/' +const SAFE_SINGLE_FILE_RE = /^[A-Za-z0-9._-]+\.(?:png|jpe?g|webp|svg)$/i +const TILE_FILE_RE = /^\/api\/v1\/earth\/tiles\/([A-Za-z0-9_-]+)\/(\d+)\/(\d+)\/(\d+)\.(webp|png|jpg|jpeg)$/ +const TERRAIN_FILE_RE = /^\/api\/v1\/visualization\/terrain\/terrarium\/(\d+)\/(\d+)\/(\d+)\.png$/ +const CLOUD_FILE_RE = /^\/api\/v1\/earth\/clouds\/([A-Za-z0-9._-]+\.(?:webp|png|jpg|jpeg))$/i + +export type DiskAssetBucket = 'boundaries' | 'card-images' | 'brand' | 'tiles' | 'terrain' | 'clouds' + +const DISK_BUCKET_MAX_BYTES: Record = { + boundaries: 256 * 1024 * 1024, + 'card-images': 128 * 1024 * 1024, + brand: 32 * 1024 * 1024, + tiles: 512 * 1024 * 1024, + terrain: 128 * 1024 * 1024, + clouds: 64 * 1024 * 1024, +} + +const ALL_DISK_BUCKETS = Object.keys(DISK_BUCKET_MAX_BYTES) as DiskAssetBucket[] + +export function getDiskAssetCacheStats(assetCacheDir: string): { + totalBytes: number + totalCount: number + buckets: Record +} { + const buckets: Record = {} + let totalBytes = 0 + let totalCount = 0 + for (const bucket of ALL_DISK_BUCKETS) { + const dir = path.join(assetCacheDir, bucket) + let bytes = 0 + let count = 0 + if (fs.existsSync(dir)) { + const walk = (target: string) => { + for (const entry of fs.readdirSync(target, { withFileTypes: true })) { + const full = path.join(target, entry.name) + if (entry.isDirectory()) { + walk(full) + } else if (entry.isFile() && !entry.name.endsWith('.tmp')) { + try { + bytes += fs.statSync(full).size + count += 1 + } catch { + // Ignore concurrent file removal. + } + } + } + } + try { + walk(dir) + } catch { + // Ignore unreadable bucket dir. + } + } + buckets[bucket] = { bytes, count } + totalBytes += bytes + totalCount += count + } + return { totalBytes, totalCount, buckets } +} + +export function clearDiskAssetCache(assetCacheDir: string, targetBuckets?: string[]): void { + const allowed = targetBuckets?.length + ? ALL_DISK_BUCKETS.filter((bucket) => targetBuckets.includes(bucket)) + : ALL_DISK_BUCKETS + for (const bucket of allowed) { + const dir = path.join(assetCacheDir, bucket) + try { + fs.rmSync(dir, { recursive: true, force: true }) + } catch { + // Ignore cleanup errors. + } + } +} + +function resolveSimpleBucketTarget( + assetCacheDir: string, + pathname: string, +): { bucket: Exclude; filePath: string; cacheControl: string; maxBytes: number } | null { + let decodedPath = pathname + try { + decodedPath = decodeURIComponent(pathname) + } catch { + return null + } + if (decodedPath.includes('..') || pathname.toLowerCase().includes('%2e%2e')) return null + + if (pathname.startsWith(CARD_IMAGE_FILES_PREFIX)) { + const raw = decodedPath.slice(CARD_IMAGE_FILES_PREFIX.length) + if (!raw || raw.includes('/') || !SAFE_SINGLE_FILE_RE.test(raw)) return null + return { + bucket: 'card-images', + filePath: path.join(assetCacheDir, 'card-images', raw), + cacheControl: 'public, max-age=31536000, immutable', + maxBytes: DISK_BUCKET_MAX_BYTES['card-images'], + } + } + + if (pathname.startsWith('/earth-brand-assets/')) { + const raw = decodedPath.slice('/earth-brand-assets/'.length) + if (!raw || raw.includes('/') || !SAFE_SINGLE_FILE_RE.test(raw)) return null + return { + bucket: 'brand', + filePath: path.join(assetCacheDir, 'brand', raw), + cacheControl: 'public, max-age=86400', + maxBytes: DISK_BUCKET_MAX_BYTES.brand, + } + } + + const tileMatch = TILE_FILE_RE.exec(decodedPath) + if (tileMatch) { + const [, sourceKey, z, x, y, ext] = tileMatch + return { + bucket: 'tiles', + filePath: path.join(assetCacheDir, 'tiles', `${sourceKey}_${z}_${x}_${y}.${ext}`), + cacheControl: 'public, max-age=86400', + maxBytes: DISK_BUCKET_MAX_BYTES.tiles, + } + } + + const terrainMatch = TERRAIN_FILE_RE.exec(decodedPath) + if (terrainMatch) { + const [, z, x, y] = terrainMatch + return { + bucket: 'terrain', + filePath: path.join(assetCacheDir, 'terrain', `${z}_${x}_${y}.png`), + cacheControl: 'public, max-age=86400', + maxBytes: DISK_BUCKET_MAX_BYTES.terrain, + } + } + + const cloudMatch = CLOUD_FILE_RE.exec(decodedPath) + if (cloudMatch) { + return { + bucket: 'clouds', + filePath: path.join(assetCacheDir, 'clouds', cloudMatch[1]), + cacheControl: 'public, max-age=3600', + maxBytes: DISK_BUCKET_MAX_BYTES.clouds, + } + } + + return null +} + +function pruneBucketDir(bucketDir: string, maxBytes: number): void { + try { + const entries: Array<{ mtimeMs: number; size: number; filePath: string }> = [] + let total = 0 + for (const name of fs.readdirSync(bucketDir)) { + if (name.endsWith('.tmp')) continue + const full = path.join(bucketDir, name) + const stat = fs.statSync(full) + if (!stat.isFile()) continue + total += stat.size + entries.push({ mtimeMs: stat.mtimeMs, size: stat.size, filePath: full }) + } + if (total <= maxBytes) return + const target = Math.floor(maxBytes * 0.85) + entries.sort((a, b) => a.mtimeMs - b.mtimeMs) + for (const entry of entries) { + if (total <= target) break + fs.rmSync(entry.filePath, { force: true }) + total -= entry.size + } + } catch { + // Prune failures never break asset responses. + } +} + +function writeBucketCacheAtomic(bucketDir: string, filePath: string, data: Uint8Array, maxBytes: number): void { + try { + fs.mkdirSync(bucketDir, { recursive: true }) + const tmpPath = `${filePath}.${Date.now().toString(36)}.tmp` + fs.writeFileSync(tmpPath, data) + fs.renameSync(tmpPath, filePath) + pruneBucketDir(bucketDir, maxBytes) + } catch { + // Disk write failures stay non-fatal. + } +} function resolveBoundaryCacheName(pathname: string): string | null { if (!pathname.startsWith(BOUNDARY_FILES_PREFIX)) return null @@ -202,12 +381,16 @@ export function createEarthProtocolHandler(options: { earthBundleRoot: string getEarthOverlayRoot?: () => string | null boundaryCacheDir?: string + assetCacheDir?: string + bucketMaxBytes?: Partial> getBackendUrl: () => string getEarthAuthToken?: (opts?: { forceRefresh?: boolean }) => Promise fetchImpl?: typeof fetch }): (request: Request) => Promise { const fetchImpl = options.fetchImpl ?? fetch - const boundaryCacheDir = options.boundaryCacheDir + const assetCacheDir = options.assetCacheDir + const boundaryCacheDir = + options.boundaryCacheDir || (assetCacheDir ? path.join(assetCacheDir, 'boundaries') : undefined) const inFlightBoundaryDownloads = new Map>() const scheduleBoundaryDownload = ( @@ -372,6 +555,30 @@ export function createEarthProtocolHandler(options: { scheduleBoundaryDownload(boundaryFileName, targetUrl, buildForwardHeaders) } } + + const bucketTarget = + assetCacheDir && (method === 'GET' || method === 'HEAD') + ? resolveSimpleBucketTarget(assetCacheDir, parsedUrl.pathname) + : null + if (bucketTarget) { + try { + const stat = fs.statSync(bucketTarget.filePath) + if (stat.isFile()) { + const now = new Date() + try { + fs.utimesSync(bucketTarget.filePath, now, now) + } catch { + // Ignore mtime touch error. + } + return createStaticFileResponse(bucketTarget.filePath, request.headers, { + method, + cacheControl: bucketTarget.cacheControl, + }) + } + } catch { + // Cache miss: proxy upstream and populate disk cache on 200 GET. + } + } const hasBody = method !== 'GET' && method !== 'HEAD' try { const makeInit = (headers: Headers): RequestInit & { duplex?: 'half' } => { @@ -406,6 +613,16 @@ export function createEarthProtocolHandler(options: { const responseHeaders = new Headers(upstream.headers) responseHeaders.delete('content-encoding') responseHeaders.delete('content-length') + if (bucketTarget && method === 'GET' && upstream.status === 200 && upstream.body) { + const buf = new Uint8Array(await upstream.arrayBuffer()) + const maxBytes = options.bucketMaxBytes?.[bucketTarget.bucket] ?? bucketTarget.maxBytes + writeBucketCacheAtomic(path.dirname(bucketTarget.filePath), bucketTarget.filePath, buf, maxBytes) + return new Response(buf, { + status: upstream.status, + statusText: upstream.statusText, + headers: responseHeaders, + }) + } const isNullBodyStatus = upstream.status === 204 || upstream.status === 205 || upstream.status === 304 return new Response(isNullBodyStatus ? null : upstream.body, { status: upstream.status, diff --git a/client/src/main/protocol.ts b/client/src/main/protocol.ts index bd21be0b..56cc0121 100644 --- a/client/src/main/protocol.ts +++ b/client/src/main/protocol.ts @@ -31,6 +31,7 @@ export function installEarthSessionHandlers( earthBundleRoot: string getEarthOverlayRoot?: () => string | null boundaryCacheDir?: string + assetCacheDir?: string getBackendUrl: () => string getEarthAuthToken?: (opts?: { forceRefresh?: boolean }) => Promise }, @@ -39,6 +40,7 @@ export function installEarthSessionHandlers( earthBundleRoot: options.earthBundleRoot, getEarthOverlayRoot: options.getEarthOverlayRoot, boundaryCacheDir: options.boundaryCacheDir, + assetCacheDir: options.assetCacheDir, getBackendUrl: options.getBackendUrl, getEarthAuthToken: options.getEarthAuthToken, fetchImpl: (input, init) => net.fetch(input as string, init), diff --git a/client/src/main/recording-core.ts b/client/src/main/recording-core.ts index 4117de63..9d16ca6b 100644 --- a/client/src/main/recording-core.ts +++ b/client/src/main/recording-core.ts @@ -98,13 +98,20 @@ export function pickSupportedRecordingMimeTypes(includeAudio: boolean): string[] export function computeIndicatorBounds(options: { contentBounds: RectBounds elapsedMs: number + zoomFactor?: number }): RectBounds { - const { contentBounds, elapsedMs } = options - const desiredWidth = elapsedMs >= 3_600_000 ? INDICATOR_LONG_WIDTH : INDICATOR_BASE_WIDTH - const width = Math.max(60, Math.min(desiredWidth, Math.max(60, contentBounds.width - 16))) - const height = Math.min(INDICATOR_HEIGHT, Math.max(24, contentBounds.height - 8)) + const { contentBounds, elapsedMs, zoomFactor = 1 } = options + const safeZoom = Number.isFinite(zoomFactor) ? Math.min(2.5, Math.max(0.5, zoomFactor)) : 1 + const desiredWidth = Math.round((elapsedMs >= 3_600_000 ? INDICATOR_LONG_WIDTH : INDICATOR_BASE_WIDTH) * safeZoom) + const desiredHeight = Math.round(INDICATOR_HEIGHT * safeZoom) + const minMargin = Math.round(8 * safeZoom) + const width = Math.max(60, Math.min(desiredWidth, Math.max(60, contentBounds.width - minMargin * 2))) + const height = Math.min(desiredHeight, Math.max(24, contentBounds.height - minMargin)) const rawX = contentBounds.x + Math.round((contentBounds.width - width) / 2) - const topOffset = Math.min(56, Math.max(10, Math.round(contentBounds.height * 0.08))) + const topOffset = Math.min( + Math.round(56 * safeZoom), + Math.max(Math.round(10 * safeZoom), Math.round(contentBounds.height * 0.08)), + ) const rawY = contentBounds.y + topOffset const maxX = contentBounds.x + Math.max(0, contentBounds.width - width) const maxY = contentBounds.y + Math.max(0, contentBounds.height - height) diff --git a/client/src/main/recording-cursor-overlay.ts b/client/src/main/recording-cursor-overlay.ts index d5bbf69b..c015c1ac 100644 --- a/client/src/main/recording-cursor-overlay.ts +++ b/client/src/main/recording-cursor-overlay.ts @@ -5,6 +5,7 @@ import { buildCursorOverlayHtml, type RecordingCursorPayload } from './recording export interface RecordingCursorOverlayController { show: () => void updateCursor: (payload: RecordingCursorPayload) => void + syncZoom: () => void hide: () => void destroy: () => void } @@ -43,6 +44,11 @@ export function createRecordingCursorOverlayController(options: { overlayWin.webContents.send('planet:recording-cursor-update', payload) } + const resolveMainZoomFactor = (mainWin: BrowserWindow): number => { + const raw = mainWin.webContents.isDestroyed() ? 1 : mainWin.webContents.getZoomFactor() + return Number.isFinite(raw) && raw > 0 ? raw : 1 + } + const syncBoundsAndLevel = () => { const mainWin = options.getMainWindow() if ( @@ -63,6 +69,11 @@ export function createRecordingCursorOverlayController(options: { return } + const zoomFactor = resolveMainZoomFactor(mainWin) + if (!overlayWin.webContents.isDestroyed() && Math.abs(overlayWin.webContents.getZoomFactor() - zoomFactor) > 0.001) { + overlayWin.webContents.setZoomFactor(zoomFactor) + } + const contentBounds = mainWin.getContentBounds() if (contentBounds.width > 0 && contentBounds.height > 0) { overlayWin.setBounds(contentBounds) @@ -140,6 +151,7 @@ export function createRecordingCursorOverlayController(options: { } readyToShow = false const contentBounds = mainWin.getContentBounds() + const zoomFactor = resolveMainZoomFactor(mainWin) overlayWin = new BrowserWindow({ x: contentBounds.x, y: contentBounds.y, @@ -164,6 +176,7 @@ export function createRecordingCursorOverlayController(options: { contextIsolation: true, nodeIntegration: false, sandbox: true, + zoomFactor, }, }) overlayWin.setMenuBarVisibility(false) @@ -171,6 +184,9 @@ export function createRecordingCursorOverlayController(options: { overlayWin.webContents.once('did-finish-load', () => { if (!overlayWin || overlayWin.isDestroyed()) return void overlayWin.webContents.setVisualZoomLevelLimits(1, 1) + const currentMain = options.getMainWindow() + const currentZoom = currentMain && !currentMain.isDestroyed() ? resolveMainZoomFactor(currentMain) : zoomFactor + overlayWin.webContents.setZoomFactor(currentZoom) readyToShow = true pushCursor(HIDDEN_CURSOR_PAYLOAD) if (visible) { @@ -216,9 +232,14 @@ export function createRecordingCursorOverlayController(options: { overlayWin = null } + const syncZoom = () => { + syncBoundsAndLevel() + } + return { show, updateCursor, + syncZoom, hide, destroy, } diff --git a/client/src/main/recording-indicator.ts b/client/src/main/recording-indicator.ts index fa71f5d4..8683af76 100644 --- a/client/src/main/recording-indicator.ts +++ b/client/src/main/recording-indicator.ts @@ -6,6 +6,7 @@ import { buildRecordingIndicatorHtml, computeIndicatorBounds, formatRecordingDur export interface RecordingIndicatorController { show: (elapsedMs?: number) => void updateElapsed: (elapsedMs: number) => void + syncZoom: () => void hide: () => void destroy: () => void } @@ -29,6 +30,11 @@ export function createRecordingIndicatorController(options: { } } + const resolveMainZoomFactor = (mainWin: BrowserWindow): number => { + const raw = mainWin.webContents.isDestroyed() ? 1 : mainWin.webContents.getZoomFactor() + return Number.isFinite(raw) && raw > 0 ? raw : 1 + } + const syncBoundsAndLevel = () => { const mainWin = options.getMainWindow() if ( @@ -47,8 +53,12 @@ export function createRecordingIndicatorController(options: { } return } + const zoomFactor = resolveMainZoomFactor(mainWin) + if (!indicatorWin.webContents.isDestroyed() && Math.abs(indicatorWin.webContents.getZoomFactor() - zoomFactor) > 0.001) { + indicatorWin.webContents.setZoomFactor(zoomFactor) + } const contentBounds = mainWin.getContentBounds() - const nextBounds = computeIndicatorBounds({ contentBounds, elapsedMs: lastElapsedMs }) + const nextBounds = computeIndicatorBounds({ contentBounds, elapsedMs: lastElapsedMs, zoomFactor }) indicatorWin.setBounds(nextBounds) indicatorWin.setAlwaysOnTop(true, mainWin.isFullScreen() ? 'screen-saver' : 'pop-up-menu') @@ -126,9 +136,11 @@ export function createRecordingIndicatorController(options: { return indicatorWin } readyToShow = false + const zoomFactor = resolveMainZoomFactor(mainWin) const initialBounds = computeIndicatorBounds({ contentBounds: mainWin.getContentBounds(), elapsedMs: lastElapsedMs, + zoomFactor, }) indicatorWin = new BrowserWindow({ ...initialBounds, @@ -151,12 +163,16 @@ export function createRecordingIndicatorController(options: { contextIsolation: true, nodeIntegration: false, sandbox: true, + zoomFactor, }, }) indicatorWin.setMenuBarVisibility(false) indicatorWin.webContents.once('did-finish-load', () => { if (!indicatorWin || indicatorWin.isDestroyed()) return void indicatorWin.webContents.setVisualZoomLevelLimits(1, 1) + const currentMain = options.getMainWindow() + const currentZoom = currentMain && !currentMain.isDestroyed() ? resolveMainZoomFactor(currentMain) : zoomFactor + indicatorWin.webContents.setZoomFactor(currentZoom) readyToShow = true pushTick(lastElapsedMs) if (visible) { @@ -207,9 +223,14 @@ export function createRecordingIndicatorController(options: { indicatorWin = null } + const syncZoom = () => { + syncBoundsAndLevel() + } + return { show, updateElapsed, + syncZoom, hide, destroy, } diff --git a/client/src/main/screen-recorder.ts b/client/src/main/screen-recorder.ts index f326437a..5889f605 100644 --- a/client/src/main/screen-recorder.ts +++ b/client/src/main/screen-recorder.ts @@ -36,6 +36,7 @@ const VALID_CURSOR_SHAPES = new Set(['default', 'pointer', export interface ScreenRecorderController { getState: () => RecordingStatusSnapshot isActive: () => boolean + syncUiZoom: () => void startRecording: (options?: { fromMenu?: boolean }) => Promise stopRecording: (options?: { timeoutMs?: number }) => Promise toggleRecording: (options?: { fromMenu?: boolean }) => Promise @@ -453,9 +454,15 @@ export function createScreenRecorderController(options: { resolvePendingFinish() } + const syncUiZoom = () => { + indicator.syncZoom() + cursorOverlay.syncZoom() + } + return { getState, isActive, + syncUiZoom, startRecording, stopRecording, toggleRecording, diff --git a/client/src/main/ui-scale.ts b/client/src/main/ui-scale.ts new file mode 100644 index 00000000..b3da52d4 --- /dev/null +++ b/client/src/main/ui-scale.ts @@ -0,0 +1,131 @@ +export type UiScalePreset = 1 | 1.25 | 1.5 | 1.75 | 2 +export type UiScaleMode = 'auto' | UiScalePreset + +export const UI_SCALE_PRESETS: readonly UiScalePreset[] = [1, 1.25, 1.5, 1.75, 2] as const +export const DEFAULT_UI_SCALE_MODE: UiScaleMode = 'auto' + +export const REFERENCE_LOGICAL_WIDTH = 1920 +export const REFERENCE_LOGICAL_HEIGHT = 1080 +export const MIN_POST_ZOOM_LOGICAL_WIDTH = 1180 +export const MIN_POST_ZOOM_LOGICAL_HEIGHT = 660 + +export interface AutoUiScaleInput { + displayWidth: number + displayHeight: number + displayScaleFactor?: number + windowWidth?: number + windowHeight?: number + isPortrait?: boolean +} + +/** + * Parse and constrain a persisted/CLI/menu UI scale value to `'auto'` or a supported preset. + */ +export function normalizeUiScaleMode( + raw: unknown, + fallback: UiScaleMode = DEFAULT_UI_SCALE_MODE, +): UiScaleMode { + let numericCandidate: number | null = null + if (typeof raw === 'number') { + numericCandidate = raw + } else if (typeof raw === 'string') { + const trimmed = raw.trim().toLowerCase() + if (!trimmed) return fallback + if (trimmed === 'auto') return 'auto' + if (trimmed.endsWith('%')) { + const pct = Number(trimmed.slice(0, -1).trim()) + numericCandidate = Number.isFinite(pct) ? pct / 100 : null + } else { + const parsed = Number(trimmed) + numericCandidate = Number.isFinite(parsed) ? parsed : null + } + } + + if (numericCandidate !== null && Number.isFinite(numericCandidate)) { + const matched = UI_SCALE_PRESETS.find((preset) => Math.abs(preset - numericCandidate!) <= 0.01) + if (matched !== undefined) { + return matched + } + } + return fallback +} + +/** + * Pick the automatic Electron UI zoom preset for a display's DIP dimensions and OS scaleFactor. + * Targets 1.5x on 4K@100% low-DPI screens while avoiding double-scaling at 150%/200% OS DPI. + */ +export function computeDisplayAutoUiZoomFactor( + displayWidth: number, + displayHeight: number, + displayScaleFactor = 1, +): UiScalePreset { + const safeW = Number.isFinite(displayWidth) && displayWidth > 0 ? displayWidth : REFERENCE_LOGICAL_WIDTH + const safeH = Number.isFinite(displayHeight) && displayHeight > 0 ? displayHeight : REFERENCE_LOGICAL_HEIGHT + const osScale = Number.isFinite(displayScaleFactor) && displayScaleFactor > 0 + ? Math.max(0.5, displayScaleFactor) + : 1 + const ratio = Math.min(safeW / REFERENCE_LOGICAL_WIDTH, safeH / REFERENCE_LOGICAL_HEIGHT) + + if (ratio >= 2.4) return 2 + if (ratio >= 1.75) return 1.5 + if (ratio >= 1.45) return 1.25 + if (ratio >= 1.25 && osScale < 1.25) return 1.25 + return 1 +} + +/** + * Compute automatic UI zoom factor constrained by current window orientation and dimensions + * so zoomed-in floating windows never collapse into narrow/mobile breakpoints. + */ +export function computeAutoUiZoomFactor(input: AutoUiScaleInput): UiScalePreset { + const hasWinDims = + typeof input.windowWidth === 'number' && + typeof input.windowHeight === 'number' && + Number.isFinite(input.windowWidth) && + Number.isFinite(input.windowHeight) && + input.windowWidth > 0 && + input.windowHeight > 0 + + if (input.isPortrait || (hasWinDims && (input.windowHeight as number) > (input.windowWidth as number))) { + return 1 + } + + const desired = computeDisplayAutoUiZoomFactor( + input.displayWidth, + input.displayHeight, + input.displayScaleFactor, + ) + + if (!hasWinDims) { + return desired + } + + const winW = input.windowWidth as number + const winH = input.windowHeight as number + const startIdx = UI_SCALE_PRESETS.indexOf(desired) + for (let i = startIdx; i >= 0; i -= 1) { + const candidate = UI_SCALE_PRESETS[i] + if ( + winW / candidate >= MIN_POST_ZOOM_LOGICAL_WIDTH && + winH / candidate >= MIN_POST_ZOOM_LOGICAL_HEIGHT + ) { + return candidate + } + } + return 1 +} + +/** + * Resolve final webContents zoomFactor for the active `'auto'` or manual preset mode. + */ +export function resolveEffectiveUiZoomFactor(mode: UiScaleMode, input: AutoUiScaleInput): UiScalePreset { + return mode === 'auto' ? computeAutoUiZoomFactor(input) : mode +} + +/** + * Format a zoomFactor (e.g. 1.5) as a human-readable percentage label ("150%"). + */ +export function formatUiScalePercent(factor: number): string { + const safe = Number.isFinite(factor) && factor > 0 ? factor : 1 + return `${Math.round(safe * 100)}%` +} diff --git a/client/src/main/window.ts b/client/src/main/window.ts index b3c2966f..96acecc4 100644 --- a/client/src/main/window.ts +++ b/client/src/main/window.ts @@ -8,6 +8,7 @@ import { DEFAULT_ENDPOINTS, type DesktopConfigStore, type DesktopRuntimeConfig } import { resolveExternalTargetUrl } from './external-links' import { getClientLocale, tClient } from './i18n' import { createWindowShowGate } from './show-gate' +import { computeDisplayAutoUiZoomFactor, resolveEffectiveUiZoomFactor } from './ui-scale' import { clampBoundsToWorkArea, computeLandscapeBounds, @@ -27,6 +28,23 @@ const resetAltMenuTrackers = new WeakMap void>() const windowStateFlushers = new WeakMap void>() const cancelInitialUnmaximizeRestore = new WeakMap void>() +interface WindowUiZoomController { + zoomFactor: number + sync: (notify?: boolean) => number +} + +const windowUiZoomControllers = new WeakMap() + +export function getWindowUiZoomFactor(win: BrowserWindow | null): number { + if (!win || win.isDestroyed()) return 1 + return windowUiZoomControllers.get(win)?.zoomFactor ?? 1 +} + +export function syncWindowUiZoom(win: BrowserWindow | null): number { + if (!win || win.isDestroyed()) return 1 + return windowUiZoomControllers.get(win)?.sync(false) ?? 1 +} + export function flushWindowState(win: BrowserWindow | null): void { if (!win || win.isDestroyed()) return windowStateFlushers.get(win)?.() @@ -88,6 +106,7 @@ export function toggleWindowOrientation(win: BrowserWindow): WindowOrientation { }) win.setBounds(portraitBounds) state.lastPortraitBounds = portraitBounds + windowUiZoomControllers.get(win)?.sync(true) return 'portrait' } @@ -107,6 +126,7 @@ export function toggleWindowOrientation(win: BrowserWindow): WindowOrientation { } state.restoreMaximizedOnLandscape = false state.restoreFullScreenOnLandscape = false + windowUiZoomControllers.get(win)?.sync(true) return 'landscape' } @@ -120,10 +140,18 @@ export interface SavedWindowState { } function loadWindowState(statePath: string, ignoreSaved = false): SavedWindowState { - const workArea = screen.getPrimaryDisplay().workAreaSize + const primaryDisplay = screen.getPrimaryDisplay() + const workArea = primaryDisplay.workAreaSize + const defaultZoom = ignoreSaved + ? 1 + : computeDisplayAutoUiZoomFactor( + primaryDisplay.bounds.width, + primaryDisplay.bounds.height, + primaryDisplay.scaleFactor, + ) const fallback: SavedWindowState = { - width: Math.min(DEFAULT_LANDSCAPE_WIDTH, workArea.width), - height: Math.min(DEFAULT_LANDSCAPE_HEIGHT, workArea.height), + width: Math.min(Math.round(DEFAULT_LANDSCAPE_WIDTH * defaultZoom), workArea.width), + height: Math.min(Math.round(DEFAULT_LANDSCAPE_HEIGHT * defaultZoom), workArea.height), isMaximized: false, isFullScreen: false, } @@ -182,6 +210,7 @@ export function createMainWindow(options: { userDataDir: string configStore: DesktopConfigStore onToggleRecording?: () => void + onUiZoomChanged?: (zoomFactor: number) => void }): BrowserWindow { nativeTheme.themeSource = 'dark' @@ -192,13 +221,35 @@ export function createMainWindow(options: { saved.x !== undefined && saved.y !== undefined ? screen.getDisplayMatching({ x: saved.x, y: saved.y, width: saved.width, height: saved.height }) : screen.getPrimaryDisplay() + const launchFullScreen = Boolean(runtimeConfig.fullscreen || runtimeConfig.kiosk) const { initialBounds, shouldRestoreNormalBoundsOnUnmaximize } = resolveInitialWindowBounds({ saved, - launchFullScreen: Boolean(runtimeConfig.fullscreen || runtimeConfig.kiosk), + launchFullScreen, headlessSmoke: runtimeConfig.headlessSmoke, displayWorkArea: targetDisplay.workArea, displayBounds: targetDisplay.bounds, }) + const launchMaximizedOrFull = Boolean(saved.isMaximized || saved.isFullScreen || launchFullScreen) + const launchEffectiveW = + saved.isFullScreen || launchFullScreen + ? targetDisplay.bounds.width + : saved.isMaximized + ? targetDisplay.workArea.width + : initialBounds.width + const launchEffectiveH = + saved.isFullScreen || launchFullScreen + ? targetDisplay.bounds.height + : saved.isMaximized + ? targetDisplay.workArea.height + : initialBounds.height + const initialZoomFactor = resolveEffectiveUiZoomFactor(runtimeConfig.uiScale, { + displayWidth: targetDisplay.bounds.width, + displayHeight: targetDisplay.bounds.height, + displayScaleFactor: targetDisplay.scaleFactor, + windowWidth: launchEffectiveW, + windowHeight: launchEffectiveH, + isPortrait: !launchMaximizedOrFull && launchEffectiveH > launchEffectiveW, + }) const win = new BrowserWindow({ x: initialBounds.x, @@ -219,6 +270,7 @@ export function createMainWindow(options: { sandbox: true, backgroundThrottling: false, webgl: true, + zoomFactor: initialZoomFactor, }, }) @@ -352,10 +404,79 @@ export function createMainWindow(options: { } windowStateFlushers.set(win, flushCurrentWindowState) - win.on('resize', captureNormalBounds) - win.on('move', captureNormalBounds) + let uiZoomTimer: ReturnType | null = null + const uiZoomController: WindowUiZoomController = { + zoomFactor: initialZoomFactor, + sync: (notify = true) => applyUiZoom(notify), + } + windowUiZoomControllers.set(win, uiZoomController) + + function applyUiZoom(notify = true): number { + if (win.isDestroyed() || win.webContents.isDestroyed()) { + return uiZoomController.zoomFactor + } + const mode = options.configStore.get().uiScale + const bounds = win.getBounds() + const contentBounds = win.getContentBounds() + const usePendingMaximizedBounds = pendingInitialReveal && launchMaximizedOrFull + const activeDisplay = usePendingMaximizedBounds ? targetDisplay : screen.getDisplayMatching(bounds) + const isMaxOrFull = usePendingMaximizedBounds || win.isMaximized() || win.isFullScreen() + const effectiveW = usePendingMaximizedBounds + ? launchEffectiveW + : contentBounds.width > 0 + ? contentBounds.width + : bounds.width + const effectiveH = usePendingMaximizedBounds + ? launchEffectiveH + : contentBounds.height > 0 + ? contentBounds.height + : bounds.height + const nextZoom = resolveEffectiveUiZoomFactor(mode, { + displayWidth: activeDisplay.bounds.width, + displayHeight: activeDisplay.bounds.height, + displayScaleFactor: activeDisplay.scaleFactor, + windowWidth: effectiveW, + windowHeight: effectiveH, + isPortrait: !isMaxOrFull && effectiveH > effectiveW, + }) + + if (Math.abs(win.webContents.getZoomFactor() - nextZoom) > 0.001) { + win.webContents.setZoomFactor(nextZoom) + } + const changed = Math.abs(uiZoomController.zoomFactor - nextZoom) > 0.001 + uiZoomController.zoomFactor = nextZoom + if (changed && notify) { + options.onUiZoomChanged?.(nextZoom) + } + return nextZoom + } + + const scheduleUiZoomSync = () => { + if (win.isDestroyed()) return + if (uiZoomTimer) { + clearTimeout(uiZoomTimer) + } + uiZoomTimer = setTimeout(() => { + uiZoomTimer = null + applyUiZoom(true) + }, 120) + } + + win.on('resize', () => { + captureNormalBounds() + scheduleUiZoomSync() + }) + win.on('move', () => { + captureNormalBounds() + scheduleUiZoomSync() + }) + win.on('maximize', () => { + applyUiZoom(true) + }) + screen.on('display-metrics-changed', scheduleUiZoomSync) win.on('close', flushCurrentWindowState) win.on('unmaximize', () => { + applyUiZoom(true) if (!restoreNormalBoundsOnUnmaximize) return restoreNormalBoundsOnUnmaximize = false if (win.isDestroyed() || win.isFullScreen()) return @@ -381,12 +502,14 @@ export function createMainWindow(options: { }) win.on('enter-full-screen', () => { + applyUiZoom(true) if (!win.isDestroyed()) { win.webContents.send('planet:fullscreen', { fullscreen: true }) } }) win.on('leave-full-screen', () => { + applyUiZoom(true) if (!win.isDestroyed()) { win.webContents.send('planet:fullscreen', { fullscreen: false }) } @@ -429,6 +552,12 @@ export function createMainWindow(options: { ipcMain.on('planet:splash-first-paint', onSplashFirstPaint) win.once('closed', () => { + if (uiZoomTimer) { + clearTimeout(uiZoomTimer) + uiZoomTimer = null + } + screen.removeListener('display-metrics-changed', scheduleUiZoomSync) + windowUiZoomControllers.delete(win) windowStateFlushers.delete(win) cancelInitialUnmaximizeRestore.delete(win) showGate.dispose() @@ -452,6 +581,7 @@ export function createMainWindow(options: { win.webContents.on('did-finish-load', () => { void win.webContents.setVisualZoomLevelLimits(1, 1) + applyUiZoom(true) }) win.webContents.setWindowOpenHandler(({ url }) => { @@ -487,11 +617,12 @@ export function openServerSettingsDialog( onUpdated: () => void, ): void { const current = configStore.get() + const zoomFactor = getWindowUiZoomFactor(parentWindow) const modal = new BrowserWindow({ parent: parentWindow, modal: true, - width: 520, - height: 370, + width: Math.round(520 * zoomFactor), + height: Math.round(370 * zoomFactor), resizable: false, minimizable: false, maximizable: false, @@ -502,9 +633,15 @@ export function openServerSettingsDialog( contextIsolation: true, nodeIntegration: false, sandbox: true, + zoomFactor, }, }) modal.removeMenu() + modal.webContents.once('did-finish-load', () => { + if (!modal.isDestroyed() && !modal.webContents.isDestroyed()) { + modal.webContents.setZoomFactor(zoomFactor) + } + }) const escapeAttr = (value: string) => value.replace(/&/g, '&').replace(/"/g, '"').replace(//g, '>') diff --git a/client/src/preload/index.ts b/client/src/preload/index.ts index 6ac8e951..93c976a5 100644 --- a/client/src/preload/index.ts +++ b/client/src/preload/index.ts @@ -104,6 +104,8 @@ contextBridge.exposeInMainWorld('planetDesktop', { getVersionInfo: () => ipcRenderer.invoke('planet:get-version-info'), getEarthSessionToken: (opts?: { forceRefresh?: boolean }) => ipcRenderer.invoke('planet:get-earth-session-token', opts) as Promise, + getAssetCacheStats: () => ipcRenderer.invoke('planet:get-asset-cache-stats'), + clearAssetCache: (buckets?: string[]) => ipcRenderer.invoke('planet:clear-asset-cache', buckets), }) ipcRenderer.on('planet:visibility', (_event, detail) => { diff --git a/client/tests/protocol.test.ts b/client/tests/protocol.test.ts index 9ee173e4..bc1edfa1 100644 --- a/client/tests/protocol.test.ts +++ b/client/tests/protocol.test.ts @@ -7,8 +7,10 @@ import { afterAll, beforeAll, describe, expect, test } from 'bun:test' import { DesktopConfigStore, deriveBackendWsUrl } from '../src/main/config' import { resolveExternalTargetUrl } from '../src/main/external-links' import { + clearDiskAssetCache, createEarthProtocolHandler, createStaticFileResponse, + getDiskAssetCacheStats, isProxiedBackendPath, parseByteRange, resolveEarthStaticPath, @@ -219,6 +221,62 @@ describe('protocol-core static and range handling', () => { expect(traversal.status).toBe(200) expect(upstreamCalls.length).toBe(callsBeforeHit + 1) }) + + test('caches card-images, tiles, and terrain under unified assetCacheDir with HEAD, LRU eviction, stats, and clear', async () => { + const fs = require('node:fs') + const assetCacheDir = path.join(tempRoot, 'unified-asset-cache') + const seen: string[] = [] + const handler = createEarthProtocolHandler({ + earthBundleRoot: bundleRoot, + assetCacheDir, + bucketMaxBytes: { tiles: 24 }, + getBackendUrl: () => 'http://127.0.0.1:8000', + fetchImpl: (async (input: RequestInfo | URL) => { + const url = String(input) + seen.push(url) + if (url.includes('/tiles/')) { + return new Response(new Uint8Array(15).fill(7), { + status: 200, + headers: { 'Content-Type': 'image/webp' }, + }) + } + return new Response('img-data', { + status: 200, + headers: { 'Content-Type': 'image/webp' }, + }) + }) as typeof fetch, + }) + + const cardUrl = 'planet://earth/api/v1/earth/card-images/files/sample.webp' + const c1 = await handler(new Request(cardUrl)) + expect(c1.status).toBe(200) + expect(await c1.text()).toBe('img-data') + + const c2 = await handler(new Request(cardUrl)) + expect(c2.status).toBe(200) + expect(await c2.text()).toBe('img-data') + + const cHead = await handler(new Request(cardUrl, { method: 'HEAD' })) + expect(cHead.status).toBe(200) + expect(cHead.headers.get('Cache-Control')).toContain('immutable') + expect(seen).toHaveLength(1) + + await handler(new Request('planet://earth/api/v1/visualization/terrain/terrarium/1/0/0.png')) + await handler(new Request('planet://earth/api/v1/earth/tiles/sentinel2/2/0/0.webp')) + await handler(new Request('planet://earth/api/v1/earth/tiles/sentinel2/2/0/1.webp')) + + const stats = getDiskAssetCacheStats(assetCacheDir) + expect(stats.buckets['card-images'].count).toBe(1) + expect(stats.buckets.terrain.count).toBe(1) + expect(stats.buckets.tiles.bytes).toBeLessThanOrEqual(24) + + clearDiskAssetCache(assetCacheDir, ['tiles']) + expect(fs.existsSync(path.join(assetCacheDir, 'tiles'))).toBe(false) + expect(fs.existsSync(path.join(assetCacheDir, 'card-images', 'sample.webp'))).toBe(true) + + clearDiskAssetCache(assetCacheDir) + expect(getDiskAssetCacheStats(assetCacheDir).totalCount).toBe(0) + }) }) describe('external links and runtime config', () => { diff --git a/client/tests/recording-core.test.ts b/client/tests/recording-core.test.ts index 526b7a6c..ece2d343 100644 --- a/client/tests/recording-core.test.ts +++ b/client/tests/recording-core.test.ts @@ -80,6 +80,15 @@ describe('recording-core helpers & preference persistence', () => { expect(tinyWindow.x + tinyWindow.width).toBeLessThanOrEqual(130) expect(tinyWindow.y).toBeGreaterThanOrEqual(30) expect(tinyWindow.y + tinyWindow.height).toBeLessThanOrEqual(110) + + const zoomedLandscape = computeIndicatorBounds({ + contentBounds: { x: 0, y: 0, width: 2560, height: 1440 }, + elapsedMs: 12_000, + zoomFactor: 1.5, + }) + expect(zoomedLandscape.width).toBe(180) + expect(zoomedLandscape.height).toBe(54) + expect(zoomedLandscape.y).toBe(84) }) it('renders transparent HUD pill HTML with blinking red dot, hover square stop morph, and click action', () => { diff --git a/client/tests/ui-scale.test.ts b/client/tests/ui-scale.test.ts new file mode 100644 index 00000000..d56beb6a --- /dev/null +++ b/client/tests/ui-scale.test.ts @@ -0,0 +1,154 @@ +import fs from 'node:fs' +import os from 'node:os' +import path from 'node:path' + +import { afterEach, describe, expect, it } from 'bun:test' + +import { DesktopConfigStore } from '../src/main/config' +import { + computeAutoUiZoomFactor, + computeDisplayAutoUiZoomFactor, + formatUiScalePercent, + normalizeUiScaleMode, + resolveEffectiveUiZoomFactor, +} from '../src/main/ui-scale' + +const tempDirs: string[] = [] + +afterEach(() => { + while (tempDirs.length > 0) { + const dir = tempDirs.pop()! + fs.rmSync(dir, { recursive: true, force: true }) + } +}) + +describe('ui-scale normalization, auto high-res/low-dpi calculation & config persistence', () => { + it('normalizes auto, numeric presets, percentage strings, and rejects unsupported values', () => { + expect(normalizeUiScaleMode('auto')).toBe('auto') + expect(normalizeUiScaleMode(' AUTO ')).toBe('auto') + expect(normalizeUiScaleMode(1.5)).toBe(1.5) + expect(normalizeUiScaleMode('1.25')).toBe(1.25) + expect(normalizeUiScaleMode('150%')).toBe(1.5) + expect(normalizeUiScaleMode('175 %')).toBe(1.75) + expect(normalizeUiScaleMode('200%')).toBe(2) + expect(normalizeUiScaleMode('0.5')).toBe('auto') + expect(normalizeUiScaleMode('not-a-scale', 1.25)).toBe(1.25) + }) + + it('defaults 4K@100% low-DPI displays to 1.5x and avoids double-scaling high-DPI OS setups', () => { + // 1080p @ 100% -> 1x + expect(computeDisplayAutoUiZoomFactor(1920, 1080, 1)).toBe(1) + // 2560x1440 @ 100% -> 1.25x + expect(computeDisplayAutoUiZoomFactor(2560, 1440, 1)).toBe(1.25) + // 4K 3840x2160 @ 100% -> 1.5x (requested default) + expect(computeDisplayAutoUiZoomFactor(3840, 2160, 1)).toBe(1.5) + // 4K @ 125% (3072x1728 DIP) -> 1.25x (effective 156%) + expect(computeDisplayAutoUiZoomFactor(3072, 1728, 1.25)).toBe(1.25) + // 4K @ 150% (2560x1440 DIP, osScale >= 1.25) -> 1x (no double scaling) + expect(computeDisplayAutoUiZoomFactor(2560, 1440, 1.5)).toBe(1) + // 4K @ 200% (1920x1080 DIP) -> 1x + expect(computeDisplayAutoUiZoomFactor(1920, 1080, 2)).toBe(1) + // 5K+ @ 100% (5120x2880 DIP) -> 2x + expect(computeDisplayAutoUiZoomFactor(5120, 2880, 1)).toBe(2) + }) + + it('clamps floating windows so zoomed CSS viewports never drop into cramped mobile sizes and respects portrait', () => { + // Maximized 4K@100% -> full 1.5x + expect( + computeAutoUiZoomFactor({ + displayWidth: 3840, + displayHeight: 2160, + displayScaleFactor: 1, + windowWidth: 3840, + windowHeight: 2080, + }), + ).toBe(1.5) + + // Fresh scaled initial window on 4K@100% (2160x1350 -> 1440x900 @ 1.5x) + expect( + computeAutoUiZoomFactor({ + displayWidth: 3840, + displayHeight: 2160, + displayScaleFactor: 1, + windowWidth: 2160, + windowHeight: 1350, + }), + ).toBe(1.5) + + // Small 1440x900 floating window on 4K@100% steps down to 1x so logical width stays >= 1180 + expect( + computeAutoUiZoomFactor({ + displayWidth: 3840, + displayHeight: 2160, + displayScaleFactor: 1, + windowWidth: 1440, + windowHeight: 900, + }), + ).toBe(1) + + // Portrait mobile window always stays at 1x + expect( + computeAutoUiZoomFactor({ + displayWidth: 3840, + displayHeight: 2160, + displayScaleFactor: 1, + windowWidth: 480, + windowHeight: 900, + isPortrait: true, + }), + ).toBe(1) + + // Manual preset overrides auto regardless of display + expect( + resolveEffectiveUiZoomFactor(1.75, { + displayWidth: 1920, + displayHeight: 1080, + displayScaleFactor: 1, + windowWidth: 1440, + windowHeight: 900, + }), + ).toBe(1.75) + + expect(formatUiScalePercent(1.5)).toBe('150%') + }) + + it('persists uiScale in DesktopConfigStore and honors env and CLI overrides', () => { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'planet-ui-scale-')) + tempDirs.push(tempDir) + + const store = new DesktopConfigStore({ + userDataDir: tempDir, + exeDir: tempDir, + argv: [], + env: {}, + }) + expect(store.get().uiScale).toBe('auto') + + store.updateUiScale(1.5) + expect(store.get().uiScale).toBe(1.5) + + const reloaded = new DesktopConfigStore({ + userDataDir: tempDir, + exeDir: tempDir, + argv: [], + env: {}, + }) + expect(reloaded.get().uiScale).toBe(1.5) + + const envOverride = new DesktopConfigStore({ + userDataDir: tempDir, + exeDir: tempDir, + argv: [], + env: { PLANET_UI_SCALE: '175%' }, + }) + expect(envOverride.get().uiScale).toBe(1.75) + + const cliOverride = new DesktopConfigStore({ + userDataDir: tempDir, + exeDir: tempDir, + argv: ['--ui-scale=2'], + env: { PLANET_UI_SCALE: '1.25' }, + }) + expect(cliOverride.get().uiScale).toBe(2) + }) +}) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index e8b0f468..9be57ecf 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -8,6 +8,21 @@ This project follows the repository versioning rule: - `improvement` -> `+0.0.1`(bugfix + 小功能混合) - `bugfix` -> `+0.0.1` +## [0.85.0] — 2026-12-06 + +Released: 2026-12-06 + +### Highlights + +- **地球全域态势感知二至四期融合(Phase 2–4)**: + - 航空与 GPS 干扰(Phase 2):上线 ADS-B(adsb.lol / OpenSky / 航空器注册表)与 GPS 干扰数据源(`39`–`42`,迁移 `0008`),新增列式打包采样、Worker 解包与大圆航迹外推渲染。 + - 全球自然灾害、海事与推演汇聚(Phase 3):上线 USGS/GDACS/FIRMS/EONET 灾害与 NGA 海事航行警告/战略港口与咽喉要道(数据源 `43`–`47`,迁移 `0009`)、实体本体与关系策展(迁移 `0010`)、电子围栏与 H3 多源汇聚/推演情景(迁移 `0011`)及多源新鲜度与真实性诚实标识。 + - 四维回放、案例档案与私有工作流(Phase 4):上线 4D 历史回放与 2D 本体关系图谱、调查档案案例(迁移 `0012`)、私有 CSV/JSON/REST 接入向导、动作审批矩阵与 Webhook(迁移 `0013`)及离线依赖降级矩阵。 +- **地球 UI、3D↔2D 视图与桌面端增强**: 上线详情卡图片本地 SWR 缓存与 Electron 磁盘分桶缓存、MapLibre 3D↔2D 平滑视图切换、桌面端 UI 缩放模式(Auto/1x–2x)与无边框录屏增强,并优化 BGP 启动并发请求与客户端离线冒烟校验。 +- **质量清理与文档门禁**: 修复 `datasource_connectivity.py` 未定义变量与重复分支,清理 backend/frontend 测试夹具与 `ruff` 告警,同步中英文采集器与性能基线文档并发布全平台桌面安装包与生产容器镜像。 + +--- + ## [0.84.2] — 2026-12-05 Released: 2026-12-05 diff --git a/docs/plans/phase2-4-continuous-plan.md b/docs/plans/phase2-4-continuous-plan.md new file mode 100755 index 00000000..4af4df0d --- /dev/null +++ b/docs/plans/phase2-4-continuous-plan.md @@ -0,0 +1,423 @@ +# Planet 二至四期连续执行计划 + +> **状态(2026-12-06)**:Phase 2(航空器 ADS-B + GPS 干扰 + 机型库,数据源 39–42,迁移 `0008`)、Phase 3(新鲜度盲区 + 灾害/海缆/港口/咽喉 + 本体 + 围栏 + H3 收敛与双兵棋场景,数据源 43–47,迁移 `0009`–`0011`)及 Phase 4(4D 回放 + 2D 本体图谱 + 调查卷宗 `0012` + 私有数据落图 + 审批矩阵 `0013` + 离线矩阵)已全部实施并经单元测试、规则门禁、性能基线对比与实景截图验收,随 `v0.85.0` 发布。 +> 本文件写给执行代理。一期(算力数据修订闭环)已完成并验收,本文件覆盖剩余的 **Phase 2 → Phase 3 → Phase 4**。 +> 仓库路径:`/home/ray/dev/linkong/planet`(Windows 侧 `\\wsl.localhost\Ubuntu\home\ray\dev\linkong\planet`)。 +> 遇到与代码现状不符的地方,以代码为准,在阶段报告中说明处理方式。 + +--- + +## 0. 连续执行规则(最重要,先读) + +1. **三个阶段必须连续做完。** Phase 2 门禁全部通过后,**立即**开始 Phase 3;Phase 3 门禁通过后,**立即**开始 Phase 4。阶段报告写完就继续,不等用户回复。 +2. **阶段边界不是停止点。** 只有第 0.5 节列出的情况才允许停下来问用户。其余问题(测试失败、构建报错、接口不通、截图不对)自己定位、修复、重跑,直到通过。 +3. **门禁失败不能跳过。** 某阶段门禁没过,不能进入下一阶段,修到通过为止。 +4. **不要缩减范围。** 本文件列出的每一项都要交付。某项确实无法按原方案实现时,采用文中写明的降级方案,或自行选择最保守的等价方案,并在报告中说明;不能直接删掉这一项。 +5. 最终交付前,确认所有后台任务都已结束。 + +### 0.1 先读这些文件 +1. `rules.md`(必载 `core` / `security` / `workflow`;按需加载 `backend`、`frontend`、`earth`、`uiux`、`ai`、`docs`) +2. `AGENTS.md`、`CODEMAP.md`、`docs/HARNESS.md` +3. `docs/documentation-coverage-rules.md`(含**凭据采集器规则**) +4. `docs/plans/phase1-compute-revision-plan.md`(一期的版本、血缘、演播、脱敏做法,后续阶段复用) +5. `docs/technical/zh/platform-data-flows.md`、`docs/technical/zh/earth-render-layer-order.md`、`docs/technical/zh/earth-frontend-context.md` + +开工前: +```bash +git status --short +scripts/harness/doctor.sh +``` + +### 0.2 工作区保护 +- 工作区可能有其他线程尚未提交的改动。**禁止** `git checkout` / `git stash` / `git restore` / `git reset`,禁止格式化或回滚无关文件。 +- 禁止 `git commit` / `git push`,除非用户明确要求。 +- 不修改已存在的迁移文件(迁移运行器校验 checksum)。新迁移用下一个空闲编号。 + +### 0.3 当前基线(开工时再确认一遍) +| 项目 | 当前值 | 本计划的用法 | +| --- | --- | --- | +| 最新迁移 | `0007_add_compute_configuration_revisions.py` | 新迁移从 `0008` 起,每次先 `ls backend/app/db/migration_steps/` | +| 已占用数据源 ID | `1–38`(35–38 为云图瓦片、两种底图、风场) | 新源从 `39` 起;开工时检查 `datasource_defaults.py`,若已被占用则顺延,并同步更新本计划中的编号 | +| 用户角色 | `viewer` / `admin` / `super_admin`(`backend/app/core/enums.py`) | 不新增角色 | +| Earth 图层适配器 | vessels、cables、satellites、computeCenters、bgp、media、news、interactables、situationalAwareness、clouds、windField、basemap | 新增图层在 `earth_layer_adapters.py` 注册 | +| 一期成果 | `compute_configuration_revisions`、`compute_revision_diff.py`、`compute_lineage.py`、逐国 `value_sources`、演播补播、血缘抽屉与脱敏 | 后续对象的出处、新鲜度、脱敏照此实现 | + +### 0.4 硬性规则 +- 前端只用 Bun;本地开发走 Vite(`./planet.sh start` / `./planet.sh restart -f`),不运行静态 Nginx `planet_admin` 容器。 +- 后端用结构化日志,禁止 `print()`,禁止 `except Exception: pass`。 +- 新增 Python 依赖用 `uv add`,不要手改 `uv.lock`;新增前端依赖用 `bun add`。依赖越少越好,有现成实现时不加。 +- 密钥只放环境变量或现有设置存储,不写进代码和文档示例。 +- 单个提交进仓库的数据文件不超过 5 MB;大型静态库走运行时下载缓存(见各节)。 +- 外部数据源必须遵守许可: + - `adsb.lol`:ODbL,界面与文档需署名; + - OpenSky:仅限非商业 / 研究用途,在数据源说明和管理界面中注明; + - `airplanes.live`、`adsb.fi` 点查询:非商业,**默认关闭**,只有管理员显式开启才使用; + - `gpsjam.org`:开工前核对其使用条款与署名要求,写入数据源说明; + - NASA FIRMS 需要免费 MAP_KEY,按凭据采集器规则接入。 + +### 0.5 只有这些情况可以停下来问用户 +- 外部数据源条款明确禁止本用途,且没有可替代的公开源; +- 需要新增用户角色,或需要修改已存在的迁移文件; +- 需要改动 BGP 主动研判逻辑或一期已验收的算力修订核心流程(`compute_configuration_revisions`、发布、血缘)的行为; +- 计划中的某项会破坏已有功能,且找不到保守做法。 + +其他情况一律自行处理并继续。 + +### 0.6 全局约束 + +**A. 对象出处与新鲜度(沿用一期做法)** +每个新增对象的接口响应都带:`source`、`observed_at`(数据描述的时间)、`ingested_at`(入库时间)、`is_stale`(超过该源的新鲜度阈值)。详情卡显示这些字段。 + +**B. 证据边界** +- 同一 H3 网格、同一时间窗出现多种信号,只能生成 **“待核查关联”**,界面和 AI 文案不得写成因果; +- 只有存在有出处的依赖关系(例如海缆 ↔ 登陆点 ↔ ASN 拓扑)或独立告警(例如 NGA 海缆告警)时,才能画影响链; +- 沿用 `workflow_registry.py` 中“无独立海缆告警证据时严禁把地理邻近推断为断缆”的守卫。 + +**C. 性能测量协议(替代“JS ≤ 3.5 ms”的旧口径)** +1. Phase 2 开工前,在当前演示机上记录基线:1920×1080 与 3840×2160 两种分辨率,开启现有全部业务图层,固定相机视角(默认视角与一个 50% 远景),用 `frontend/public/earth/js/frame-stats.js` 记录 30 秒的帧间隔均值、**P95**、CPU、Draw calls,写入 `docs/technical/zh/earth-performance-baseline.md`(中英双语)。 +2. 每新增一个图层:在同样条件下开启该图层再测一次。 +3. 合格标准: + - 基线 P95 ≤ 8.33 ms 时,加图层后 P95 仍 ≤ 8.33 ms; + - 基线已超过 8.33 ms 时,单个新图层使 P95 增加不超过 0.5 ms; + - 新图层常规状态 Draw calls ≤ 2; + - 图层关闭后,Draw calls 回到基线,`renderer.info.memory` 中几何与纹理数量回到开启前。 +4. 不合格时用 `frameProfile` 区分 CPU / GPU 瓶颈并优化,直到合格。 + +**D. 渲染实现规则** +- 海量点一律单批 `THREE.Points` 或实例化几何,禁止一个对象一个 Mesh / Sprite / DOM; +- 解析、三角化、空间索引放在 Web Worker,用 Transferable `Float32Array` 传回主线程(参照 `satellite-position-worker.js`); +- 动画循环中不分配新对象,复用 scratch 变量; +- 新图层默认关闭;关闭时不请求接口、不建几何,并立即 `dispose()`; +- 每新增或调整 `renderOrder`、半径偏移、深度策略,同步更新 `earth-render-layer-order.md`(中英)。下文给出的 renderOrder 是建议值,先对照当前文档确认没有冲突,有冲突就选相邻的空闲值并保持同样的层级意图。 + +**E. 凭据采集器** +`requires_credentials: true` 且 `credential_status: supported` 的采集器,必须同时具备:`credential_provider`、`credential_guides.py` 教程、`datasource_connectivity.py` 连通性测试、`PlainResourcePages.tsx` 中的凭据表单或指引、一条缺失时会失败的回归测试(见 `docs/documentation-coverage-rules.md`)。 + +**F. 文档** +每个阶段更新 `docs/technical/{zh,en}/platform-data-flows.md` 与 `earth-render-layer-order.md`;用户可见功能更新 `manual.md` / `quickstart.md`(中英);运维相关(环境变量、下载缓存、凭据)更新 `ops-runbook.md`(中英)。每阶段运行 `scripts/harness/docs-consistency-check.sh`。 + +--- + +## Phase 2:空域与电磁(飞机 ADS-B + GPS/GNSS 干扰) + +### 2.1 数据源编号 +| ID | 名称 | 凭据 | 频率 | 说明 | +| --- | --- | --- | --- | --- | +| 39 | `adsb_lol_aircraft` | 不需要 | 60 秒 | `api.adsb.lol`:`/v2/mil` 军机,`/v2/sqk/7500`、`/7600`、`/7700` 紧急应答机,可选配置的重点区域 `/v2/point/{lat}/{lon}/{radius}` | +| 40 | `opensky_aircraft` | OAuth2 Client Credentials | 120 秒 | `/api/states/all`,可配置 bbox 列表;未配凭据时安静跳过,状态显示“未配置” | +| 41 | `gpsjam_interference` | 不需要 | 6 小时 | `gpsjam.org` H3 干扰数据(数据按天发布,频率不必更高) | +| 42 | `aircraft_registry` | 不需要 | 7 天 | 开放的 icao24 机型库(OpenSky aircraft database 或同类开放库,开工前核对许可),运行时下载 | + +在 `datasource_defaults.py`、`data_sources.py`(`COLLECTOR_URL_KEYS`)、`data_sources.yaml`、`collectors/__init__.py` 注册;40 号按凭据采集器规则补齐全部配套;`storage_policy.py` 的 `HIGH_VOLUME_SOURCES` 加入 39、40;`datasource_connectivity.py` 支持 39–42 的连通性测试。 + +### 2.2 数据模型(迁移 `0008_add_aircraft_and_gps_jamming.py`) +新模型 `backend/app/models/aircraft.py`: + +| 表 | 主键 | 字段 | +| --- | --- | --- | +| `aircraft_static` | `icao24` | `registration`、`aircraft_type`(ICAO 机型代码)、`type_description`、`operator`、`owner`、`origin_country`、`category`、`is_military`、`source`、`updated_at` | +| `aircraft_current_state` | `icao24` | `callsign`、`lat`、`lon`、`baro_altitude_m`、`geo_altitude_m`、`ground_speed_ms`、`track_deg`、`vertical_rate_ms`、`squawk`、`on_ground`、`category`、`is_military`、`is_emergency`、`emergency_code`、`source`、`observed_at`、`ingested_at` | +| `aircraft_position` | `id` 自增 | `icao24`、`lat`、`lon`、`altitude_m`、`ground_speed_ms`、`track_deg`、`observed_at`;索引 `(icao24, observed_at)`、`observed_at` | +| `adsb_source_health` | `source` | `connection_state`、`active_count`、`last_success_at`、`last_error`、`cooldown_until`、`updated_at` | + +新模型 `backend/app/models/gps_jamming.py`: + +| 表 | 主键 | 字段 | +| --- | --- | --- | +| `gps_jamming_cells` | `(h3_index, observed_date)` | `lat`、`lon`、`resolution`、`level`(`low`/`medium`/`high`)、`bad_ratio`、`aircraft_count`、`boundary`(JSON 顶点数组)、`source`、`ingested_at` | + +迁移兼容 PostgreSQL 与 SQLite,在 PostgreSQL 中让 `aircraft_current_state`、`gps_jamming_cells` 参与现有 `earth_data_change_events` outbox 通知(参照已有表的触发器写法)。 + +### 2.3 分类、富化与聚合 +- `backend/app/services/aircraft_types.py`: + - 军机 ICAO 24 位地址段表(覆盖主要国家军用号段,注明出处)与军用呼号前缀规则; + - 分类枚举 `commercial` / `cargo` / `military` / `emergency` / `general` / `helicopter` / `other`;7500/7600/7700 一律 `emergency`,同时保留 `is_military`。 +- `backend/app/services/aircraft_registry.py`(42 号源):下载开放机型库到 `data/aircraft_registry/`(路径走配置,加入 `.gitignore`),解析写入 `aircraft_static`;下载失败或离线时保留旧数据,不报错。 +- `backend/app/services/aircraft_aggregation.py`: + - 多源合并写 `aircraft_current_state`:同一 `icao24` 以 `observed_at` 更新者为准,同一时刻 `adsb_lol` 优先(含军机标记); + - 批量 UPSERT,一个采集批次只触发一次图层变更通知; + - `aircraft_position` 降采样写入:距上次记录超过 30 秒,或航向变化超过 10°,或高度变化超过 300 m; + - 清理:`aircraft_current_state` 超过 15 分钟未更新的删除;`aircraft_position` 保留时长可配置,**默认 24 小时**(Phase 4 回放需要),定时清理。 +- OpenSky 采集器:Token 缓存到过期前 60 秒刷新;遇 429 写 `cooldown_until` 并跳过后续请求直到冷却结束;请求间隔可配置。 +- adsb.lol 采集器:单次请求失败最多重试 2 次,指数退避;全部失败时保留上一批数据直到过期。 + +### 2.4 接口、适配器、AI 工具 +- `backend/app/api/v1/aircraft.py`,挂到 `api/main.py`: + - `GET /api/v1/aircraft/snapshot`:参数 `bbox`、`category`(逗号分隔)、`include_ground`(默认 false)、`limit`(≤ 20000)、`since_minutes`(默认 15)。返回**列式紧凑结构**:`{"fields": [...], "rows": [[...], ...], "generated_at", "source_health"}`,避免大 JSON 对象数组。无数据返回 200 空集合。权限 `require_earth_or_api_access("aircraft:read")`。 + - `GET /api/v1/aircraft/{icao24}`:当前状态 + 静态档案 + 出处与新鲜度字段。 + - `GET /api/v1/aircraft/{icao24}/track?hours=3`:轨迹点。 +- `backend/app/api/v1/gps_jamming.py`:`GET /api/v1/gps-jamming/snapshot?date=` 返回干扰单元与分级统计,权限 `gps_jamming:read`。 +- 在 API Key 权限范围(`ApiKeySettings.tsx` 与后端 scope 列表)加入 `aircraft:read`、`gps_jamming:read`。 +- `earth_layer_adapters.py` 注册 `aircraft`(`cache_patterns=("aircraft*", "summary*")`,`refresh_strategy="reload"`)和 `gpsJamming`。 +- `visualization.py` 的 summary 加 `aircraft_count`、`military_aircraft_count`、`emergency_aircraft_count`、`gps_jamming_high_count`;`data_products.py` 加 `aircraft`、`gps_jamming` 两个数据产品。 +- `tool_registry.py` 新增只读工具 `query_aircraft_posture`(按区域统计军机 / 紧急 / 民航数量、重点空域列表)、`query_gps_jamming_posture`(高 / 中干扰区域列表与覆盖国家);在 `workflow_registry.py` 的 `TOOL_CATALOG` 注册,并加入 `default.general` 与 `wargame.infrastructure` 的可用工具;`entity_resolver.py` 的 `EntityRef.entity_type` 增加 `aircraft`、`gps_jamming_cell`,`workflow_registry.py` 的 bindings 实体类型白名单同步增加。 + +### 2.5 Earth 渲染 +建议渲染层级(先对照当前 `earth-render-layer-order.md`): + +| 图层 | 半径 | renderOrder | 深度 | 说明 | +| --- | --- | --- | --- | --- | +| `gpsJamming` | `R + 0.48`(与高清地表同壳) | 0.968 | `depthTest: true`、`depthWrite: false` | 高于影响区 0.965,低于国界线 0.97 | +| 飞机选中尾迹 | 按高度 | 4.7 | 复用 `surface-ribbon.js` | 仅选中目标 | +| `aircraft` | `R + 0.75` ~ `R + 1.85`,按高度线性映射 | 4.9 | 锚点遮挡(参照船只) | 高于算力中心 4.5,低于卫星尾迹 5.9 | + +文件: +- `frontend/public/earth/js/aircraft-worker.js`:解包列式快照;为每架飞机计算球面初始位置、切向速度向量、显示半径、图集槽位(32 档航向 × 分类颜色);构建 5°×5° 经纬网格桶索引;用 Transferable 传回。 +- `frontend/public/earth/js/aircraft.js`: + - 单批 `THREE.Points` + 自定义着色器:顶点着色器根据 `uElapsedSec` 沿大圆外推位置(航位推算),并做球体遮挡;每帧只更新这一个 uniform; + - 新快照到达时在 Worker 里生成新缓冲区,主线程替换属性,过渡 300 ms 内插值,避免跳点; + - 悬停 / 点击:拖动和惯性期间不拾取;平时先查网格桶,再在候选中做屏幕空间最近点判断; + - 点击加载 3 小时轨迹,用 `surface-ribbon.js` 绘制; + - 图例分类过滤;核显或移动端按上限降密度(优先保留军机和紧急航班)。 +- `frontend/public/earth/js/gps-jamming.js`:Worker 中把 H3 六边形三角化合并为一个 `BufferGeometry`,顶点颜色按等级;悬停显示干扰比例、受影响飞机数、日期。 +- 接线:`main.js`(图层注册、`earth_updates` 刷新、拾取)、`controls.js`、`index.html`、`layer-startup-tasks.js`、`legend.js`、`legend-filters.js`、`info-card.js`(呼号、icao24、注册号、机型、运营方、高度、地速、航向、升降率、应答机码、出处与新鲜度)、`search.js`(呼号 / icao24 / 注册号)、`i18n.js`。 +- 详情卡与图层说明中显示数据源署名(adsb.lol ODbL、OpenSky、gpsjam.org)。 + +### 2.6 Admin +- `datasourceConfigHelpers.ts`:40 号 OAuth2 `client_id` / `client_secret` 与 bbox 列表配置;39 号重点区域点位配置;`airplanes.live` / `adsb.fi` 补盲开关(默认关闭,开关旁注明“非商业用途”)。 +- `PlainResourcePages.tsx`:40 号凭据指引。 +- 数据源健康页显示 `adsb_source_health`。 + +### 2.7 Phase 2 测试 +后端(新文件 `backend/tests/test_aircraft_*.py`、`test_gps_jamming.py`): +1. adsb.lol 军机与紧急码响应解析(用录制的样例 JSON 作为 fixture,不访问外网); +2. OpenSky Token 缓存、429 冷却、未配凭据时跳过; +3. 军机号段与呼号分类; +4. 多源合并优先级、轨迹降采样、过期清理; +5. 快照接口列式结构、空数据 200、bbox 与分类过滤、权限; +6. gpsjam 解析与 H3 边界生成; +7. 机型库离线降级; +8. 40 号凭据采集器配套回归测试。 + +前端(`bun test`): +1. Worker 解包与航向槽位计算; +2. 航位推算外推函数(与 CPU 参考实现对比误差); +3. 网格桶拾取候选; +4. H3 三角化顶点数量与颜色映射。 + +### 2.8 Phase 2 门禁 +- 第 8 节检查命令全部通过; +- 第 0.6.C 性能测量:`aircraft` 与 `gpsJamming` 各自开启、两者同时开启都合格; +- 浏览器实测:飞机平滑移动无跳点,点击显示详情与尾迹,图例过滤生效,关闭图层后无残留;GPS 干扰面不闪烁、不穿模(50% 远景与近景各截图);桌面、移动端、125% / 150% 缩放截图; +- 文档更新完成。 + +通过后写 Phase 2 报告,**立即进入 Phase 3**。 + +--- + +## Phase 3:全域感知、本体扩展与跨域融合 + +Phase 3 内部按 3.1 → 3.10 顺序执行,每一节完成后跑相关测试再进入下一节。 + +### 3.1 新鲜度与情报盲区 +- `backend/app/services/source_freshness.py`:为每个业务域定义新鲜度阈值(建议:aircraft 5 分钟、vessels 30 分钟、bgp 30 分钟、disasters 60 分钟、gps_jamming 36 小时、satellites 48 小时、cables 14 天、compute 以发布版本为准、news 6 小时),状态 `fresh` / `stale` / `very_stale` / `degraded` / `offline` / `disabled` / `not_configured`,附原因。 +- `GET /api/v1/system/freshness`:返回各域状态、最后成功时间、原因。公开 Earth 可读(不含内部错误详情)。 +- AI 接入:`query_global_situational` 结果附 `blind_spots`;`default.general`、`wargame.*` 工作流的系统提示要求在回答中列出盲区。不是 `fresh` 的域不得被描述为“无事件”。 +- Earth HUD:紧凑的数据源健康胶囊,2 Hz 以下刷新,点击展开各域状态。遵守 `.hud-panel` 规范。 + +### 3.2 自然灾害 +| ID | 名称 | 凭据 | 频率 | +| --- | --- | --- | --- | +| 43 | `usgs_earthquakes` | 不需要 | 5 分钟(M4.5+ 全球 GeoJSON feed) | +| 44 | `nasa_firms_wildfires` | MAP_KEY(凭据采集器) | 30 分钟(VIIRS 近实时;未配 Key 时状态 `not_configured`) | +| 45 | `gdacs_disasters` | 不需要 | 15 分钟(过滤绿色级别) | +| 46 | `nasa_eonet_events` | 不需要 | 30 分钟(排除地震类别,避免与 USGS 重复) | + +- 模型 `disaster_events`(迁移 `0009_add_disaster_events.py`,与 3.3–3.4 的表合并到同一迁移也可以):`id`、`source`、`source_event_id`、`event_type`(earthquake / wildfire / cyclone / flood / volcano / drought / other)、`severity`、`title`、`lat`、`lon`、`magnitude`、`started_at`、`ended_at`、`url`、`observed_at`、`ingested_at`、`raw`(JSON);唯一约束 `(source, source_event_id)`;0.1° 网格 + 时间窗去重跨源同一事件(保留各源记录,标注 `duplicate_of`)。 +- 野火热点量大:按 0.25° 网格聚合为热点簇存储,保留簇内点数与最大亮温。 +- 接口 `GET /api/v1/disasters/snapshot?types=&since_hours=`,适配器 `disasters`,AI 工具 `query_disaster_posture`。 +- Earth:`frontend/public/earth/js/disasters.js`,单批 `THREE.Points`(建议 renderOrder 4.6,半径 `R + 0.52`),顶点属性区分类型与严重度,脉动在着色器中完成;默认关闭;详情卡含出处与新鲜度。 + +### 3.3 海缆告警(NGA) +| ID | 名称 | 凭据 | 频率 | +| --- | --- | --- | --- | +| 47 | `nga_navigation_warnings` | 不需要 | 6 小时 | + +- 读取 NGA MSI 公开航行警告(开工时确认接口地址与格式),用关键词规则(cable / submarine cable / cable repair / cable ship 等)筛出海缆相关警告,提取坐标(经纬度格式解析写单元测试)。 +- 模型 `cable_advisories`:`id`、`source_warning_id`、`text`、`lat`、`lon`、`polygon`(可选)、`issued_at`、`cancelled_at`、`matched_cable_ids`(按距离匹配现有海缆,阈值可配置,默认 50 km)、`match_method`、`ingested_at`。 +- 匹配结果用于海缆图层高亮(复用现有海缆样式纹理的强调通道,不新增 Draw call);海缆详情卡显示相关告警原文与出处。 +- AI 工具 `query_cable_posture` 结果附 `advisories`。 + +### 3.4 港口、咽喉要道与军舰识别 +- 静态字典 `backend/app/data/maritime_chokepoints.json`(咽喉要道多边形:马六甲、霍尔木兹、曼德、苏伊士、巴拿马、直布罗陀、博斯普鲁斯、台湾海峡、朝鲜海峡等)与 `strategic_ports.json`(战略港口:名称、坐标、类型 container / oil_lng / naval / mixed / bulk、吞吐量排名、出处)。每条记录注明来源。 +- `vessel_types.py` 扩展:军舰识别(AIS 船型 35、名称前缀 USS / HMS / HMCS / HMAS / INS / JS / ROKS / TCG 等、已知舰名白名单附出处),输出 `military_role`;海缆维修船识别(名称白名单 + AIS 船型)。 +- 船舶快照与 `query_vessel_posture` 输出各咽喉内船舶数、军舰数、与 7 天滚动基线对比。 +- Earth:咽喉要道作为低透明度区域(复用 `influence-zones.js` 的合成方式,不新增独立 Mesh),港口进入现有 `earth_interactables` 体系或算力中心同类的点批次。 + +### 3.5 新闻来源分级 +- 新闻源配置与 `earth_news_items` 增加 `credibility_tier`(1–4)、`state_affiliated`(布尔)、`theater_tags`(数组)。迁移加列,现有数据默认 `tier` 为空(界面显示“未分级”,不当作 4 级)。 +- Admin 新闻源配置页可编辑分级;Earth 新闻卡显示分级徽章;新闻面板增加战区预设筛选(全球 / 俄乌 / 中东 / 印太 / 欧洲)。 +- AI 研判引用新闻时按分级排序,国家背景媒体加标注。 + +### 3.6 通用空间对比卡片(一期遗留的通用化) +一期已经让算力卡片和参谋共用同一 `publish_id` / 口径。本节把验证过的部分抽成通用能力,供 3.10 两个场景使用: +- `workbench-blocks.js` 新增积木:`bilateral_duel`、`stacked_composition`、`corridor_with_milestones`、`entity_samples`,抽取自 `compute-topic.js` 现有实现,渲染结果保持一致; +- `scene_spec` 增加 `spatial_cards`(卡片 key、锚点、左右偏好、对比伙伴 key、积木列表)和 `overlays`(首批:`national_hubs`、`chokepoints`、`geofences`、`dependency_arcs`); +- 新增 `frontend/public/earth/js/spatial-workflow-cards.js`,使用 `regionCallouts.scope("workflow")` 渲染工作流产生的球面卡片; +- `presentation_compiler.py` 的 `StageStepSpec` 增加通用字段 `workflow_params`、`spotlight_card_keys`、`overlays`,保留现有算力字段以兼容; +- **算力卡片保持现有行为**,不在本阶段删除 `compute-topic.js`;新增一条测试:算力工作流输出的 `spatial_cards` 在新渲染器中显示的数值与原卡片一致。 + +### 3.7 本体扩展 +- 关系与实体解析继续**读取时推导**,不建镜像表:扩展 `entity_resolver.py`,支持 aircraft、vessel、cable、landing_point、asn、gps_jamming_cell、disaster_event、chokepoint、port、compute_center、country,统一 `object_id` 格式 `{type}:{id}`; +- 新增两张**只存无法推导内容**的表(迁移 `0010_add_ontology_curation.py`): + - `ontology_entity_aliases`:`alias`、`object_id`、`source`、`created_by`、`created_at`(新闻中的船名、航司名、海缆别名等人工或规则确认的别名); + - `analyst_links`:`from_object_id`、`to_object_id`、`relation_type`、`note`、`evidence_ids`、`created_by`、`created_at`、`status`(分析员人工确认的关系); +- 接口 `GET /api/v1/ontology/objects/{object_id}`(对象详情 + 出处 + 新鲜度)与 `GET /api/v1/ontology/objects/{object_id}/neighborhood?depth=1..2`(推导关系 + 人工关系,标注每条关系的来源类型:`derived_topology` / `derived_spatial` / `analyst_asserted`)。 + +### 3.8 电子围栏与确定性异常 +- 迁移 `0011_add_geofences_and_incidents.py`: + - `geofences`:`id`、`name`、`kind`(preset / custom)、`geometry`(GeoJSON Polygon)、`rules`(JSON)、`enabled`、`created_by`、`created_at`、`updated_at`; + - `situational_incidents`:`id`、`incident_type`、`severity`、`status`(open / acknowledged / dismissed / resolved)、`h3_index`、`window_start`、`window_end`、`object_ids`、`signal_summary`、`evidence`、`assessment_kind`(`rule_alert` / `candidate_correlation` / `dependency_impact`)、`created_at`、`updated_by`、`resolution_note`; +- 预置围栏:主要海缆走廊(按海缆几何生成缓冲带,宽度可配置)、3.4 的咽喉要道; +- `backend/app/services/fusion/anomaly_engine.py`(后台定时任务,按 `scheduler.py` 现有写法注册): + 1. 海缆走廊内船速 < 3 节且停留 > 30 分钟(疑似拖锚 / 徘徊); + 2. 重点围栏内船舶或飞机信号中断超过阈值(暗目标); + 3. 围栏内目标数比 14 天同时段基线增加超过 2 个标准差(激增); + 每条告警写入 `situational_incidents`(`assessment_kind="rule_alert"`),同一对象同一规则在冷却期内不重复生成; +- Earth:`frontend/public/earth/js/geofence-editor.js`,在球面点选顶点闭合多边形,保存到后端;全部围栏合批为一个轮廓 + 填充几何(建议 renderOrder 0.969);`admin` / `super_admin` 可编辑,`viewer` 只读; +- 告警列表进入现有告警 / 态势面板,可确认、驳回(必填理由)、解决。 + +### 3.9 待核查关联与依赖影响链 +- 引入 H3(`uv add h3`),分辨率 4; +- `backend/app/services/fusion/convergence.py`:按 6 小时和 24 小时窗口扫描各域异常信号(3.8 规则告警、紧急应答机、高 GPS 干扰、灾害、BGP 异常、海缆告警、新闻热点),同一网格出现 ≥ 2 类信号时生成 `assessment_kind="candidate_correlation"` 的事件,标题固定使用“待核查关联”字样; +- `backend/app/services/fusion/dependency_impact.py`:只基于有出处的拓扑(海缆 ↔ 登陆点 ↔ ASN ↔ 算力中心 ↔ 国家)计算断链影响与备用路径;只有存在 NGA 海缆告警、海缆运营方公告或 BGP 证据时才生成 `dependency_impact`; +- 扩展 `proactive_pipeline.py`:新增 `process_fusion_incident(...)`,对新的待核查关联与依赖影响事件触发对应工作流和演播;**不修改**现有 BGP 函数和算力修订函数; +- 前端:待核查关联显示为虚线网格高亮,文案“待核查”;依赖影响链显示为实线弧(复用 `surface-ribbon.js`)。两者图例分开。 + +### 3.10 两个端到端场景 +在 `workflow_registry.py` 的内置工作流中新增,使用 3.6 的空间卡片与 3.7 的本体接口: + +1. **`wargame.cable_protection`(海缆安全护卫)** + 输入:海缆走廊规则告警或 NGA 告警或 BGP 异常。流程:取海缆、附近船舶轨迹、NGA 告警、BGP 事件 → 判断证据等级(只有邻近 = 待核查;有独立告警 = 依赖影响)→ 生成影响清单、空间卡片(海缆状态 / 可疑船舶 / 受影响国家与算力)和多幕演播。 + 验收样例:用录制数据复现“某海缆走廊船舶徘徊 + 同时段 BGP 异常”,结果显示为“待核查关联”;再加入一条匹配的 NGA 告警,结果升级为“依赖影响”,并画出影响链。 + +2. **`wargame.air_sea_em`(空海电磁联合态势)** + 输入:待核查关联事件(军机 / 紧急航班 / GPS 干扰 / 咽喉军舰 / 灾害 / 新闻)。流程:汇总区域内各域对象 → 生成双边或多区域空间对比卡片、AI 简报(列出盲区)、演播。 + 验收样例:用录制数据复现“某海域高 GPS 干扰 + 军机集中 + 军舰通过咽喉”,生成待核查关联、空间卡片与简报,简报中不出现因果断言。 + +两个场景的事件都能“确认 / 驳回(必填理由)”,结果写回 `situational_incidents` 并在地球上更新状态。 + +### 3.11 Phase 3 测试 +- 每个采集器的解析测试(录制样例,不访问外网),44 号凭据配套回归测试; +- 跨源去重、野火聚合; +- NGA 坐标解析与海缆匹配; +- 军舰识别、咽喉计数与基线对比; +- 新鲜度状态计算与 `blind_spots` 注入; +- 三类异常规则(含冷却去重); +- 待核查关联只在 ≥ 2 类信号时生成,且文案不含因果词;依赖影响在无独立证据时不生成; +- 本体推导与人工关系接口、权限; +- 空间卡片新旧渲染一致性; +- 两个场景的端到端测试(后端工作流 + 前端渲染截图)。 + +### 3.12 Phase 3 门禁 +- 检查命令全部通过; +- 新增图层(disasters、咽喉区域、围栏、关联高亮)逐一与全部同时开启的性能测量合格; +- 浏览器实测:两个场景完整走通(截图),围栏绘制与保存,告警确认 / 驳回,数据源健康胶囊;桌面、移动端、125% / 150%; +- 文档更新完成。 + +通过后写 Phase 3 报告,**立即进入 Phase 4**。 + +--- + +## Phase 4:4D 研判工作台与政企底座 + +### 4.1 4D 时间回放 +- 数据保留:`aircraft_position` 默认 24 小时(Phase 2 已设)、船舶位置沿用现有保留期(核对并在界面上显示实际可回放范围)、BGP / 灾害 / 新闻 / 事件按各自表的时间字段;卫星按回放时间用 TLE 现场传播。 +- `GET /api/v1/replay/frames?start=&end=&step_sec=60&layers=&bbox=`:按时间片返回列式关键帧,单次请求最长 6 小时,前端分段请求;超出保留范围的时段返回 `unavailable` 标记。 +- Earth 底部时间轴:实时 / 回放切换、拖动定位、0.5×–60× 倍速、显示每个图层的可回放范围;回放态下图层数据来自回放接口,返回实时态时恢复。 +- 帧间插值在 Worker 中完成,主线程双缓冲切换属性;回放播放时性能测量同样要合格。 +- 回放时间与一期的“系统发布时间轴”(算力 `as_of`)联动:拖到某时刻时,算力卡片自动切到当时生效的发布版本。 + +### 4.2 关系图谱与时间线 +- Earth 侧栏按需加载(动态 import)的 Canvas 2D 关系图谱,数据来自 `/ontology/objects/{id}/neighborhood`;自实现轻量力导向布局,不引入大型依赖;关系线按来源类型区分样式(推导 / 人工)。 +- 事件时间线:所选对象及其关联对象的事件(告警、修订、新闻、轨迹段)按时间排列。 +- 三者联动:点图谱节点 → 地球飞到对象并高亮;点地球对象 → 图谱与时间线展开;点时间线条目 → 时间轴跳到该时刻。 +- 图谱与时间线在 WebGL 帧循环之外渲染,交互时不影响地球帧率(性能测量验证)。 + +### 4.3 研判卷宗 +- 迁移 `0012_add_investigation_cases.py`: + - `investigation_cases`:`id`、`title`、`status`(draft / in_review / frozen / closed)、`owner_id`、`summary`、`created_at`、`updated_at`; + - `case_items`:`case_id`、`item_type`(object / incident / evidence / camera_bookmark / note / ai_result / compute_revision)、`ref_id`、`payload`(JSON 快照)、`added_by`、`added_at`; + - `case_versions`:`case_id`、`version`、`snapshot`(JSON)、`content_sha256`、`frozen_by`、`frozen_at`; +- 从地球、参谋、事件面板都能“加入卷宗”;卷宗冻结后生成不可变版本与哈希; +- 导出 Markdown(复用 `export_revision_bound_markdown_report` 的风格),包含每条证据的出处与哈希;PDF 通过浏览器打印样式实现,不引入服务端 PDF 依赖; +- 权限:`admin` / `super_admin` 创建与编辑,`viewer` 只读已共享卷宗。 + +### 4.4 私有数据上球 +- 复用现有 `custom_datasource_runtime.py` 与 `datasource_mapping.py`(字段映射 DSL)以及 `collection.assist` 工作流; +- Admin 向导:上传 CSV / JSON 或配置 REST 接口 → 预览字段 → 映射为对象(必填:标识、名称、纬度、经度;可选:类型、分类、时间、任意属性)→ 预览地图 → 保存; +- 映射结果写入现有 `earth_interactables`(已有 delta 刷新和通用图标渲染),`kind` 使用用户定义的类型;对象自动进入本体推导(`object_id = interactable:{id}`),可参与围栏规则和 AI 研判; +- 上传文件大小上限与行数上限可配置(默认 20 MB / 10 万行),超出时提示分批; +- 测试:CSV、JSON、REST 三种来源各一条端到端测试。 + +### 4.5 处置动作与审批 +- 迁移 `0013_add_action_requests.py`: + - `action_types`(内置注册表即可,不一定建表):`add_to_watchlist`、`create_case`、`create_ticket_webhook`、`notify_webhook`,每种有风险等级; + - `action_requests`:`id`、`action_type`、`target_object_ids`、`params`、`risk_level`、`status`(pending / approved / rejected / executed / failed)、`requested_by`、`requested_at`、`approved_by`、`approved_at`、`decision_reason`、`execution_result`、`source_workflow_run_id`; +- 审批规则(基于现有三角色): + - `viewer` 不能发起; + - `admin` 可发起;低风险动作 `admin` 可直接执行; + - 高风险动作(对外 Webhook 推送)需要 `super_admin` 审批,且审批人不能是发起人; + - 审批与驳回都必须填写理由; +- Webhook 执行器:通用 JSON Webhook、企业微信 / 钉钉 / 飞书机器人消息格式;目标地址只能来自管理员预先配置的白名单;复用现有 SSRF 防护;签名密钥存设置存储;超时与重试有上限; +- AI 工作流可以“建议动作”(生成 `pending` 请求),不能直接执行; +- 所有动作写 `AuditLog`;地球对象详情显示与其相关的动作记录。 + +### 4.6 离线交付验证 +- 列出所有外部依赖(数据源、底图、模型),为每项写明离线时的行为:静态库(机型库、港口 / 咽喉字典、国界、海缆底表)随数据目录打包;外部源不可达时新鲜度显示 `offline`,界面不报错;AI 通过 `aiprovider` 指向本地模型; +- 断网测试:断开外网后启动服务与 Electron 客户端(`planet://earth/`),截图证明地球、已缓存图层、卷宗、回放(保留期内)可用; +- 结果写入 `ops-runbook.md`(中英)的离线部署章节。 + +### 4.7 Phase 4 测试 +- 回放接口分段、保留期外 `unavailable`、算力 `as_of` 联动; +- 插值函数单元测试; +- 卷宗冻结哈希稳定、导出内容含出处; +- 私有数据三种来源上球与围栏联动; +- 审批规则矩阵(角色 × 风险等级 × 发起人是否为审批人)全覆盖;Webhook 白名单与 SSRF 拦截; +- 离线模式启动测试。 + +### 4.8 Phase 4 门禁(即最终验收) +- 检查命令全部通过,并运行 `scripts/harness/validate.sh`; +- 回放播放、图谱交互时性能测量合格; +- 浏览器实测(截图):回放一段海缆场景、从图谱跳转对象、冻结并导出卷宗、上传 CSV 上球、发起并审批一条 Webhook 动作、断网启动;桌面、移动端、125% / 150%; +- 文档更新完成; +- 所有后台任务结束。 + +--- + +## 8. 检查命令 + +每节完成后跑相关测试;每个阶段门禁跑全部: +```bash +cd backend && uv run --frozen --group dev --project .. python -m pytest -q +scripts/harness/backend-rules-check.sh +cd frontend && bun install --frozen-lockfile && bun run build && bun run build:admin +cd frontend && bun test +scripts/harness/frontend-rules-check.sh +scripts/harness/docs-consistency-check.sh +scripts/harness/quick-check.sh +``` +Phase 4 结束再跑 `scripts/harness/validate.sh`。新增依赖后用 `uv sync` / `bun install` 更新锁文件,并确认 `--frozen` 命令仍通过。 + +测试失败时先判断它保护的行为:实现回归就修实现;只有断言绑定的是本计划明确改变的旧细节时才改测试,并在报告中说明。 + +--- + +## 9. 阶段报告格式 + +每个阶段结束写一次,写完立即继续下一阶段: +``` +## Phase {n} 完成报告 +- 完成内容:(按小节编号列出) +- 新增数据源与 ID: +- 新增迁移: +- 改动文件:(路径列表) +- 新增/修改测试:(测试名 + 结果) +- 检查命令结果: +- 性能测量:(分辨率 / 图层组合 / 帧间隔均值 / P95 / Draw calls,与基线对比) +- 浏览器实测截图:(文件路径) +- 与计划不一致之处及处理方式: +- 遗留风险: +``` + +最终交付时附一份总表:三个阶段的全部数据源、迁移、接口、图层、工作流、测试数量与门禁结果。 diff --git a/docs/technical/en/backend-collectors.md b/docs/technical/en/backend-collectors.md index e3b97a44..c972b085 100644 --- a/docs/technical/en/backend-collectors.md +++ b/docs/technical/en/backend-collectors.md @@ -92,6 +92,15 @@ The CelesTrak TLE collector prefers the complete `active` catalog. If CelesTrak | TeleGeography | submarine_cable | Submarine cable information | 7 days | | BarentsWatch AIS | vessel | AIS vessel positions, speed, heading, MMSI, and related fields | Collector settings | | AISStream Vessels | vessel_ais | AIS WebSocket realtime stream, written to the raw observation layer and displayed through aggregation | Collector settings | +| ADS-B.lol Aircraft | aircraft_adsb | Global military, emergency squawk, and priority-airspace ADS-B snapshots (`aircraft_current_state` + observations) | 1 minute | +| OpenSky Aircraft | aircraft_adsb | OpenSky public / OAuth2 aircraft state snapshots (optional OAuth2 credentials) | 5 minutes | +| GPSJam Interference | gps_jamming | Global H3 resolution-4 GPS/GNSS interference grid (`gps_jamming_cells`) | 6 hours | +| Aircraft Registry | aircraft_registry | Mictronics / OpenSky open aircraft type registry index for airframe/military classification | 7 days | +| USGS Earthquakes | disaster_event | USGS global earthquake GeoJSON feed (persisted to `disaster_events`) | 10 minutes | +| GDACS Alerts | disaster_event | UN/EC GDACS global disaster alert RSS feed (persisted to `disaster_events`) | 15 minutes | +| NASA EONET Events | disaster_event | NASA EONET global natural event feed (persisted to `disaster_events`) | 30 minutes | +| NASA FIRMS Wildfires | disaster_event | NASA FIRMS satellite fire hotspots CSV (requires `MAP_KEY` credential; persisted to `disaster_events`) | 30 minutes | +| NGA Maritime Advisories | maritime_advisory | US NGA broadcast maritime warnings (matched against cables/chokepoints in `cable_advisories`) | 6 hours | AIS vessel collectors use a different persistence path from regular `CollectedData` collectors. BarentsWatch, AISStream, and custom `vessel_ais` sources write into the AIS raw observation layer and also upsert `vessel_current_state`: one row per MMSI with the latest position, speed, course, navigation state, vessel type, name, and source metadata. This preserves raw observation history for tracks, audit, and situational analysis while letting the Earth vessel layer read the current-state table instead of scanning historical AIS rows. diff --git a/docs/technical/en/datasource-collector-settings-connectivity.md b/docs/technical/en/datasource-collector-settings-connectivity.md index cf115453..7c2a5196 100644 --- a/docs/technical/en/datasource-collector-settings-connectivity.md +++ b/docs/technical/en/datasource-collector-settings-connectivity.md @@ -480,5 +480,14 @@ Credential providers currently supported: - `barentswatch` - `aisstream` - `spacetrack` +- `opensky` (`opensky_aircraft`, OAuth2 `client_credentials`; **Non-Commercial / Research use only**, supports configured `bboxes`, silently reports `not_configured` when omitted, and respects `cooldown_until` on HTTP 429) +- `nasa_firms` (`nasa_firms_wildfires`, NASA FIRMS VIIRS `MAP_KEY` credential; returns explicit `not_configured` status with registration instructions and 100 req/min rate limit notes when omitted, never skipping silently) Other collectors with `requires_credentials=true` return that their credential chain has not been wired yet, and the frontend shows `Unavailable`. + +### Phase 2 Aircraft & GNSS Interference Collector Licensing + +- `adsb_lol_aircraft` (ID `39`): consumes `api.adsb.lol` under **ODbL** attribution in info cards and docs; optional `focus_points` circles supported, while opt-in non-commercial `airplanes.live` / `adsb.fi` gap-fill stays disabled by default. +- `opensky_aircraft` (ID `40`): authenticates via OpenSky OAuth2 `client_id` / `client_secret` strictly for non-commercial / research usage. +- `gpsjam_interference` (ID `41`): fetches daily H3 resolution-4 CSVs from `gpsjam.org` (underlying community telemetry via `airplanes.live` and `ADS-B Exchange`), reflecting high-altitude aircraft-reported GNSS accuracy drops. +- `aircraft_registry` (ID `42`): refreshes local `aircraft_static` metadata from open ICAO24 registries cached under `data/aircraft_registry/`, gracefully retaining prior rows offline. diff --git a/docs/technical/en/earth-frontend-context.md b/docs/technical/en/earth-frontend-context.md index 76bba467..d75cf16a 100644 --- a/docs/technical/en/earth-frontend-context.md +++ b/docs/technical/en/earth-frontend-context.md @@ -648,3 +648,12 @@ When compute image configuration has no model/group rules, resolution uses a bou - **Published-revision selector and historical banner** (`compute-topic.js` + `compute-topic.css`): adds a `Published revision` selector backed by the redacted public endpoint `/api/v1/data-products/compute/revisions/public` alongside Period and Measure, forwarding `publish_id` / `as_of` on both `/series` and `/posture/compute`. Viewing a historical revision renders a top banner (`Viewing revision published {ts} (not current)`) with a one-click `Return to current` button, while pre-baseline timestamps surface an `Incomplete historical snapshot` notice. - **Per-country provenance and Lineage Drawer** (`compute-topic.js` + `compute-topic-model.js`): adds an inline provenance button beside each hero metric using per-country `evidence_by_code` and fetches `/api/v1/data-products/compute/lineage` (attaching Bearer auth only when the stored session role is `admin` or `super_admin` so public/viewer traffic remains redacted without triggering 403), rendering current value, source title/locator/excerpt/SHA-256, object-level timestamps, and revision timeline inside `#compute-evidence`. - **Copilot same-source binding and mismatch guard** (`situational-copilot.js` + `workbench-blocks.js` + `main.js`): forwards `publishId`, `asOf`, `mode`, and `focusYear` from Compute Cards into Copilot sessions/turns and listens to `earth:compute-view-changed` to compare each turn's `view_spec` `(publish_id, mode, focus_year)` against live card state. Any divergence displays a mismatch banner with a `Re-evaluate for current view` button in **both** the narrative text area and the chart/workbench area so charts and prose never silently disagree. `stage-narrative-player.js` labels `compute-revision-notice` as `Compute Data Revision` and syncs the updated `publishId`. + +### Local Asset SWR Cache & 3D/2D Map View Switching + +- **Stale-While-Revalidate Local Asset Cache & Server Memory Reduction** (`asset-swr-cache.js` + `card-images.js` + `earth-texture-image.js` + `cloud-map.js` + `wind-layer.js` + `terrain.js` + `cables.js` + `compute-centers.js` + `brand.js` + `about.js` + `earth_layer_cache.py` + `visualization.py` + `card_images.py`): + - **0 ms stale display + background fingerprint/ETag check**: `asset-swr-cache.js` (IndexedDB LRU) renders cached imagery and big datasets first while validating `ETag`/`If-None-Match` or `/card-images/fingerprint` in the background, swapping card images in place when fingerprints diverge and retaining stale assets offline; backend `/brand`, `/about`, `/card-images/resolve`, and `/card-images/files/{filename}` serve deterministic `ETag` and `304` responses. + - **Low server RSS & trimmed desktop bundle**: `earth_layer_cache.py` keeps single-buffer gzip payloads under an `8 MiB` cap, and `visualization.py` moves Terrarium tiles to a disk LRU under `data/earth-terrain-cache/`; `client/scripts/build-earth-bundle.mjs` trims duplicate bundled imagery in favor of on-demand `userData/asset-cache/` persistence, paired with usage reporting and one-click clearing under Settings → System (`Local Asset Cache` / `Clear Cache`). +- **Crisp Admin-1 Borders, Nine-Dash China Hover & 3D/2D View Controller** (`surface-ribbon.js` + `country-boundaries.js` + `map-view-controller.js` + `map-2d.js` + `main.js`): + - **Readable un-dimmed admin-1 borders**: `createDashedRibbonMaterial()` draws screen-space dashed borders with a dark casing (`6px/4px`, `admin1MinViewZoom = 1.85`) over bright/dark imagery; `effectiveAdmin1Opacity()` never dims province/state borders on country hover, and hovering `CHN` or `TWN` highlights mainland borders, coastlines, and the South China Sea nine-dash line (`claim_line`) together. + - **MapLibre GL 2D flat view** (bundled `maplibre-gl@6.21.0` + `Protocol` reusing 3D's `IndexedDbPmtilesSource` archive): toggles seamlessly from the toolbar orb or the `500%` max-zoom pill prompt (`#map-2d-zoom-pill`), syncing basemap tiles, China-POV vector borders, 2D geo-labels, business overlays, and feature selection while pausing the 3D `requestAnimationFrame` loop and bi-directionally syncing camera coordinates/zoom back to 3D. diff --git a/docs/technical/en/earth-layer-style-reference.md b/docs/technical/en/earth-layer-style-reference.md index 4fffedbe..355a794b 100644 --- a/docs/technical/en/earth-layer-style-reference.md +++ b/docs/technical/en/earth-layer-style-reference.md @@ -79,7 +79,7 @@ The land/ocean base is an Earth base-map asset and preloads at startup; the "Bor | Boundary tile zoom thresholds | `COUNTRY_BOUNDARY_CONFIG.tileZoomThresholds` | `0 -> z2`, `1.3 -> z4`, `2.3 -> z6`, `3.8 -> z8` | 4-tier PMTiles zoom schedule (`borderMaxZoom = 6`; `z8` refines OSM coastlines only) | | Boundary tile cache limit | `COUNTRY_BOUNDARY_CONFIG.tileCacheLimit` | `640` | Frontend LRU cache entries for loaded tile geometries | | Boundary tile debounce | `COUNTRY_BOUNDARY_CONFIG.tileDebounceMs` | `180` | Trailing-edge view-change debounce before queuing visible tiles | -| Admin-1 fade & style | `admin1MinViewZoom / FullViewZoom / Color / Opacity` | `2.0 / 2.8 / 0x9fd0ff / 0.26` | `country-admin1-batch` smoothly fades in as zoom increases | +| Admin-1 fade & style | `admin1MinViewZoom / FullViewZoom / Color / Opacity / Casing` | `1.85 / 2.6 / 0xd8e8f8 / 0.46` + `0x050a14 / 0.36` | `surface-ribbon.js` screen-space `6px/4px` dash with dark casing; never dimmed on country hover; 2D mirrors via `boundary-admin1` / `boundary-admin1-casing` | | Ocean fill color | local `OCEAN_HEX` | `0x010609` | Land/ocean base canvas background | | Land fill color | `COUNTRY_BOUNDARY_CONFIG.landColor` | `0x080f1b` | Land/ocean base canvas land | | Land/ocean base opacity | `COUNTRY_BOUNDARY_CONFIG.landOpacity` | `1.0` | `MeshBasicMaterial.opacity` | diff --git a/docs/technical/en/earth-performance-baseline.md b/docs/technical/en/earth-performance-baseline.md new file mode 100644 index 00000000..86481125 --- /dev/null +++ b/docs/technical/en/earth-performance-baseline.md @@ -0,0 +1,89 @@ +# Earth Rendering Performance Baseline (Step 0) + +This document records the `/earth/` rendering baseline captured before Phase 2 implementation and defines the quantitative performance gates for newly added layers, 4D replay, and interactive overlays. + +## Test Environment and Methodology + +- Date captured: 2026-12-06 +- Instrumentation: `frontend/public/earth/js/frame-stats.js` (`?profileFrames` enabled with HUD FPS monitor, 30-second sampling windows) +- Browser runtime: Playwright Headless Chromium (Linux/WSL) with WebGL via `ANGLE (Mesa, llvmpipe (LLVM 20.1.2 256 bits), OpenGL 4.5)` software rasterizer +- Enabled layers: all existing operational and visual layers (`toggle-cables`, `toggle-satellites`, `toggle-compute-centers`, `toggle-vessels`, `toggle-bgp`, `toggle-earth-high-res-texture`, `toggle-weather`, `toggle-country-boundaries`) +- Camera views: default camera view (100%) and zoomed-out 50% view +- Notes: At 4K viewport (3840×2160), `computeEffectivePixelRatio` in `main.js` caps the drawing buffer to 2880×1620 to bound fill-rate cost. Because headless WSL uses the `llvmpipe` software renderer, absolute P95 frame intervals exceed the 8.33 ms (120 FPS) hardware target. + +## Step 0 Baseline Measurements + +| Resolution | Camera View | Render Buffer | Sample Window | Median Frame Interval (ms) | Median P95 (ms) | Median CPU (ms) | Draw Calls | Avg FPS | Top Frame Stages | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | +| 1920×1080 | Default view | 1920×1080 | 30.3 s (28 samples) | 80.22 | 88.10 | 6.11 | 87 | 12.43 | `wind-streamlines` (2.33 ms), `scene-render` (2.15 ms), `globe-motion` (0.72 ms) | +| 1920×1080 | 50% far zoom | 1920×1080 | 30.6 s (27 samples) | 88.28 | 94.50 | 6.80 | 119 | 11.71 | `scene-render` (2.22 ms), `wind-streamlines` (1.83 ms), `globe-motion` (0.58 ms) | +| 3840×2160 | Default view | 2880×1620 | 31.0 s (27 samples) | 107.96 | 116.30 | 7.49 | 86 | 9.36 | `scene-render` (2.95 ms), `wind-streamlines` (2.20 ms), `globe-motion` (0.71 ms) | +| 3840×2160 | 50% far zoom | 2880×1620 | 30.5 s (27 samples) | 107.81 | 117.40 | 7.14 | 119 | 9.40 | `wind-streamlines` (2.72 ms), `scene-render` (2.30 ms), `globe-motion` (0.70 ms) | + +## Acceptance Thresholds for New Layers + +Per the Phase 2–4 performance measurement protocol: + +1. Because the software-rasterized baseline P95 exceeds 8.33 ms, **each new layer enabled under identical settings must keep P95 delta ≤ 0.50 ms** (on hardware GPU environments where baseline P95 ≤ 8.33 ms, P95 must remain ≤ 8.33 ms); +2. **Steady-state Draw Calls increase per new layer ≤ 2**; +3. **Immediate cleanup on toggle-off (`dispose()`)**: Draw Calls return to baseline, `renderer.info.memory` (`geometries` and `textures`) returns to pre-enable counts, and background polling stops immediately; +4. Any regression exceeding the threshold must be diagnosed with `frameProfile` and renderer metrics and optimized before updating the measurement table. + +## Phase 2 Measurements (`aircraft` + `gpsJamming`) + +Measured under the same `llvmpipe` software rasterizer with fixed camera, 240 live aircraft (plus 3h selected trail ribbon), and H3 res-4 GPS jamming cells over 30-second sampling windows (`renderer.info.memory` settled baseline: `geometries=1321`, `textures=52`): + +| Resolution | Layer Combination | Camera View | Median Frame Interval (ms) | Median P95 (ms) | Median CPU (ms) | Draw Calls (settled baseline 120) | Memory (`geometries` / `textures`) | +| --- | --- | --- | --- | --- | --- | --- | --- | +| 1920×1080 | Settled baseline (all prior layers, Phase 2 off) | Default view | 115.59 | 123.30 | 6.82 | 120 | 1321 / 52 | +| 1920×1080 | `aircraft` only (single `Points` batch + DR) | Default view | 87.27 | 93.60 | 6.51 | 121 (**+1**) | 1322 / 53 (+1/+1) | +| 1920×1080 | `gpsJamming` only (single fan mesh) | Default view | 108.07 | 116.00 | 6.52 | 122 (**≤ +2**) | 1322 / 52 (+1/+0) | +| 1920×1080 | `aircraft` + `gpsJamming` together | Default view | 92.27 | 101.60 | 6.78 | 123 | 1323 / 53 (+2/+1) | +| 1920×1080 | `aircraft` + `gpsJamming` together | 50% far zoom | 97.00 | 111.70 | 6.72 | 123 (vs 120 far baseline) | 1323 / 53 | +| 3840×2160 (`2880×1620`) | Settled baseline (Phase 2 off) | Default view | 113.29 | 122.00 | 7.03 | 120 | 1321 / 52 | +| 3840×2160 (`2880×1620`) | `aircraft` only | Default view | 104.62 | 114.10 | 7.61 | 121 (**+1**) | 1322 / 53 | +| 3840×2160 (`2880×1620`) | `gpsJamming` only | Default view | 107.88 | 116.00 | 8.11 | 122 (**≤ +2**) | 1322 / 52 | +| 3840×2160 (`2880×1620`) | `aircraft` + `gpsJamming` together | Default / 50% far | 106.68 / 104.98 | 114.90 / 116.50 | 7.91 / 7.86 | 123 / 123 | 1323 / 53 | +| 1080p & 4K | After toggling `aircraft` + `gpsJamming` OFF | Default view | — | — | — | **Restored to 120** | **Exact `1321 / 52` (zero leak)** | + +Result: Both `aircraft` and `gpsJamming` stay within Draw Calls delta `≤ 2`, keep P95 within software-rendering baseline variance (CPU delta ≤ 0.5 ms), and release all allocated GPU geometries and textures on disable. + +## Phase 3 Measurements (`disasters` + `chokepoints` + `geofences` + `fusion`) + +Measured under the same `llvmpipe` software rasterizer with fixed camera across 30-second sampling windows per configuration (settled post-load baseline at 1080p: `drawCalls=122`, `geometries=1326`, `textures=54`; at 4K: `drawCalls=86`, `geometries=1292`, `textures=20`): + +| Resolution | Layer Combination | Median Frame Interval (ms) | Median P95 (ms) | Median CPU (ms) | Draw Calls (vs settled baseline) | Memory (`geometries` / `textures`) | +| --- | --- | --- | --- | --- | --- | --- | +| 1920×1080 | Initial baseline (Phase 3 layers off) | 148.81 | 160.90 | 6.94 | 87 (settled restore baseline **122**) | 1289 / 20 (settled `1326 / 54`) | +| 1920×1080 | `disasters` only | 163.26 | 184.60 | 8.06 | 123 (**+1** vs settled) | 1324 / 55 | +| 1920×1080 | `chokepoints` only | 158.70 | 182.80 | 7.45 | 121 (**≤ 0** vs settled) | 1324 / 55 | +| 1920×1080 | `geofences` only | 163.88 | 189.15 | 7.66 | 124 (**+2** vs settled) | 1326 / 55 | +| 1920×1080 | `fusion` only (convergence hexes + arcs) | 171.60 | 189.70 | 7.72 | 123 (**+1** vs settled) | 1326 / 55 | +| 1920×1080 | All 4 Phase 3 layers enabled | 172.86 | 204.75 | 7.67 | 127 (+5 combined) | 1326 / 55 | +| 1920×1080 | After toggling all 4 OFF (`dispose()`) | — | — | — | **Exact return to 122** | **`1326 / 54` (zero leak)** | +| 3840×2160 (`2880×1620`) | Baseline (Phase 3 layers off) | 231.82 | 245.70 | 5.92 | 86 | 1288 / 19 | +| 3840×2160 (`2880×1620`) | `disasters` only | 237.58 | 266.35 | 5.93 | 87 (**+1**) | 1289 / 19 | +| 3840×2160 (`2880×1620`) | `chokepoints` only | 236.97 | 249.50 | 5.51 | 88 (**+2**) | 1290 / 21 | +| 3840×2160 (`2880×1620`) | `geofences` only | 228.91 | 243.45 | 6.03 | 89 (CPU +0.11 ms) | 1292 / 20 | +| 3840×2160 (`2880×1620`) | `fusion` only | 218.81 | 233.65 | 5.59 | 86 (**+0**) | 1292 / 20 | +| 3840×2160 (`2880×1620`) | All 4 Phase 3 layers enabled | 240.82 | 266.00 | 6.06 | 91 (+5 combined) | 1292 / 21 | +| 3840×2160 (`2880×1620`) | After toggling all 4 OFF (`dispose()`) | — | — | — | **Exact return to 86** | **`1292 / 20`** | + +Result: Across both 1080p and 4K, toggling all Phase 3 layers OFF via `dispose()` restores Draw Calls cleanly (`122 -> 122` at 1080p, `86 -> 86` at 4K) with zero geometry or texture leaks. + +## Phase 4 Measurements (4D Spatiotemporal Replay + On-Demand 2D Ontology Graph) + +Measured under the same `llvmpipe` software rasterizer across 30-second sampling windows during active 4D Replay (Web Worker columnar interpolation + single-batch `Points` overlay) and dynamically imported 2D Canvas Ontology Graph inspection: + +| Resolution | Interaction Mode | Median Frame Interval (ms) | Median P95 (ms) | Median CPU (ms) | Draw Calls | Memory (`geometries` / `textures`) | +| --- | --- | --- | --- | --- | --- | --- | +| 1920×1080 | Initial baseline (Replay & Graph closed) | 146.06 | 159.85 | 6.81 | 87 (settled **122**) | 1289 / 20 | +| 1920×1080 | 4D Replay active (Worker double-buffer interpolation) | 155.97 | 170.80 | **6.79** | 121 | 1323 / 55 | +| 1920×1080 | Replay + Ontology Graph drawer open (2D Canvas outside WebGL RAF) | 177.97 | 201.30 | 7.73 | 122 | 1324 / 55 | +| 1920×1080 | After exiting Replay & closing Graph (`dispose()`) | — | — | — | **122** | **1324 / 55** | +| 3840×2160 (`2880×1620`) | Initial baseline (Replay & Graph closed) | 232.78 | 251.20 | 6.56 | 87 (settled **122**) | 1289 / 20 | +| 3840×2160 (`2880×1620`) | 4D Replay active | 230.90 | 242.50 | **6.54** | 121 | 1323 / 55 | +| 3840×2160 (`2880×1620`) | Replay + Ontology Graph drawer open | 249.46 | 260.00 | **6.98 (CPU +0.42 ms)** | 122 | 1323 / 55 | +| 3840×2160 (`2880×1620`) | After exiting Replay & closing Graph (`dispose()`) | — | — | — | **122** | **1323 / 55** | + +Result: Web Worker replay interpolation adds zero main-thread CPU regression (1080p `6.81 -> 6.79 ms`, 4K `6.56 -> 6.54 ms`), the lazily loaded 2D Canvas ontology graph isolates rendering outside the Three.js loop, and exiting replay cleanly disposes the temporary point cloud geometry and material. diff --git a/docs/technical/en/earth-render-layer-order.md b/docs/technical/en/earth-render-layer-order.md index 952a85d4..ed37985b 100644 --- a/docs/technical/en/earth-render-layer-order.md +++ b/docs/technical/en/earth-render-layer-order.md @@ -23,6 +23,10 @@ Note: the layer control panel order and the registration / startup load order ar | 0.96 | HD Earth texture | `earth.js` | `textureOverlayAltitudeOffset = EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET = 0.48` | Surface picking target when visible | HD texture always overlays the land/ocean base fill; radius must stay above the land/ocean base and far enough from the base sphere; uses Rayleigh terminator shading and subtle grazing water reflection. | | 0.962 | Cloud shadow shell | `earth.js` | Shared HD surface radius with slight angular offset | `depthTest: true`, `depthWrite: false`, raycast disabled | Follows the cloud toggle and casts soft surface cloud shadows from `earth_clouds_2048.png`, strictly above `0.96` and below `0.965`. | | 0.965 | Surface influence zones | `influence-zones.js`, `scene_directives.py` | Reuses the `128×128` spherical shell at `r = 100.48` (`EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET`); `renderOrderBase = 0.965`, stepping by `0.0003` per tier | `depthTest: true`, `depthWrite: false`, raycast disabled | Supports single-pass offscreen soft blur compositing for country presets and great-circle fragment shading for circular zones; stays above `0.96` HD imagery and strictly below `0.97` borders and all surface icons. | +| 0.968 | GPS/GNSS interference H3 grid | `gps-jamming.js`, `gps-jamming-worker.js` | `R + 0.515` (clears H3 res-4 chord sagitta above `0.48` HD surface); Worker fan-triangulates cells into one `BufferGeometry` + `ShaderMaterial` (Draw calls = 1) | `depthTest: true`, `depthWrite: false`, `polygonOffset(-2, -2)`, raycast disabled (surface hover lookup) | Defaults off; vertex RGBA encodes severity (`high`/`medium`/`low`), strictly above `0.965` and below `0.97` country borders. | +| 0.969 | Geofences batched fill & outline | `geofence-editor.js` | `R + 0.14` single `Mesh` + single `LineSegments` (Draw calls = 2) | `depthTest: true`, `depthWrite: false`, surface vertex pick only while drawing | Defaults off; preset cable/chokepoint fences in cyan, `admin`/`super_admin` custom polygons in amber; disposed cleanly on hide. | +| 0.971 | Candidate correlation dashed H3 hexes | `fusion-overlays.js`, `surface-ribbon.js` | `R + 0.19` single batched `createSurfaceRibbonGeometry` + `createDashedRibbonMaterial` (Draw call = 1) | `depthTest: true`, `depthWrite: false`, raycast disabled | Represents "Pending Verification" (`>=2` distinct domains in one H3 cell) with a separate legend entry from dependency impact chains. | +| 0.972 | Dependency impact solid arcs | `fusion-overlays.js`, `surface-ribbon.js` | `R + 0.22..1.87` single batched `createSurfaceRibbonMaterial` (Draw call = 1) | `depthTest: true`, `depthWrite: false`, raycast disabled | Emitted and drawn only when corroborated by NGA warnings, operator notices, or grounded BGP evidence. | | 1 / 1.1 | Atmosphere / clouds | `earth.js` | One atmosphere shell at R×1.025; clouds at R+3 (`FrontSide` shader + `earth_clouds_2048.png`) | Atmosphere uses BackSide, depthWrite=false, depthTest=true; cloud toggle retained | Inner scattering and Mie forward glow combine across the surface/atmosphere shells without fullscreen post-processing. | | 1 | Submarine cables / landing points | `cables.js`, `cable-batches.js` | All cable segments share one `LineSegments`; all landing points use instanced billboards; render order remains `1`; cables and landing-point anchors share the HD surface offset `0.48` and the same triangle-surface coordinates | Original `Line` / `Sprite` objects retain per-item picking and selection state but no longer draw individually; landing-point sphere occlusion remains, with `depthTest: false` on the batch | Style textures and instance attributes preserve color, pulse, size, visibility, and click behavior. | | 1.2 | Real terrain | `earth.js`, `terrain.js` | `TERRAIN_CONFIG.baseRadiusOffset` plus terrain displacement | Raycast disabled | Terrain overlays HD texture; temporarily hidden when HD texture is off, restores to prior state when re-enabled. | @@ -35,6 +39,9 @@ Note: the layer control panel order and the registration / startup load order ar | 4.3 | AIS vessel track lines | `vessels.js` | `VESSEL_RENDER_ORDER - 0.1`; `CONFIG.earthRadius + VESSEL_CONFIG.track.altitudeOffset` | Follows vessel selection, not independently picked | Recent track for the selected vessel, below vessel markers. | | 4.4 | AIS vessel markers | `vessels.js`, `interactable.js` | `VESSEL_RENDER_ORDER`; business radius `CONFIG.earthRadius + VESSEL_CONFIG.altitudeOffset`; normal markers are bucketed `THREE.Points`, hover / locked states are single-point overlays; whole-anchor occlusion matches BGP and compute markers at the globe limb | `depthTest: false`, with visibility decided by anchor occlusion; `main.js` uses screen-space picking for front-facing markers; `cluster: false` and `avoidance: false` | Moving vessels use triangular point textures, anchored / slow vessels use dots. Dense waterways may overlap and do not participate in dynamic screen clustering, avoiding Points rebuilds during rotation. | | 4.5 | Compute centers | `compute-centers.js`, `interactable.js` | `COMPUTE_CENTER_RENDER_ORDER` | Screen-space Interactable picking, with surface-icon collision handling | Surface facilities, below satellites. | +| 4.6 | Natural disasters pulsing `Points` batch | `disasters.js` | `R + 0.52` single `THREE.Points` + `ShaderMaterial` (`aType`, `aSeverity`, `aPhase`; Draw call = 1) | `depthTest: true`, `depthWrite: false` | Defaults off; aggregates USGS earthquakes, NASA FIRMS clusters, GDACS, and NASA EONET. | +| 4.7 | Selected aircraft 3h track | `aircraft.js`, `surface-ribbon.js` | Reuses `surface-ribbon.js` mapped to altitude (`R+0.72..R+1.82`) | Rendered only for selected aircraft; non-pickable | Immediately disposed on layer hide/clear. | +| 4.9 | ADS-B aircraft batch | `aircraft.js`, `aircraft-worker.js` | Single-batch `THREE.Points` + shader great-circle extrapolation + 300ms snapshot lerp, linear altitude `R+0.75..R+1.85` (Draw calls = 1) | `depthTest: true`, `depthWrite: false`, vertex horizon occlusion; 5°×5° grid bucket picking | Defaults off; 32 heading bins × 7 categories atlas; density capping preserves military and emergency aircraft first. | | 5.9 | Satellite trails | `satellites.js` | Samples ~12.6s semi-transparent tapered tails at 1.4s steps following the real-altitude toggle and compression slider; instanced screen-space ribbon | `depthTest=true`, `depthWrite=false`, `NormalBlending` | Draws above HD surface and surface icons, just below satellite dots; far-side segments occluded by the Earth occluder. | | 6 | Satellite dots | `satellites.js` | SGP4 altitude continuously adjustable from 100% (`R+4..25` log-compressed) down to 0% (1:1 true ratio, capped at `R+720`); fallback `R+8` | `depthTest=false`; vertex shader tests camera-to-satellite segment occlusion against an R×0.998 sphere; screen-space picking | Visible sprites remain complete; truly occluded points move outside clip space instead of being partially depth-clipped near the limb; idle breathing modulates both alpha and point size. | | 12+ | Satellite locked ring, halo, predicted orbit | `satellites.js` | `SATELLITE_CONFIG.overlayRenderOrder` and offsets; predicted orbit follows the same real-altitude toggle and fixes the lock-time globe pose to draw an open full-period inertial curve with forward-flow highlights; returns to same-sphere mode when real altitude is disabled | Satellite overlay path | Used for selected/locked satellite emphasis. | diff --git a/docs/technical/en/manual.md b/docs/technical/en/manual.md index b90b9fec..db747846 100644 --- a/docs/technical/en/manual.md +++ b/docs/technical/en/manual.md @@ -143,6 +143,12 @@ Steps: - `total stored`, `last 24h`, `last 1h`, and `unique MMSI` show historical collection volume - `disconnected` with a recent error means the upstream or network dropped; click `Reconnect` +### Aircraft (ADS-B) and GPS/GNSS Interference Layers + +- **Aircraft (`aircraft`)**: defaults to OFF; reads columnar aircraft states from `/api/v1/aircraft/snapshot`, extrapolates positions smoothly in WebGL, opens detail cards (`ICAO24`, registration, airframe type, operator, provenance, freshness) and 3-hour elevation tracks on click, and filters categories in the legend panel. Attribution follows `adsb.lol (ODbL)` and `OpenSky Network (Non-Commercial / Research)`. +- **GPS Interference (`gpsJamming`)**: defaults to OFF; renders daily H3 resolution-4 interference zones from `gpsjam.org`, displaying interference severity, bad ratio, aircraft count, and observed date on hover. +- **OpenSky OAuth2 Credentials**: configure `opensky_aircraft` `Client ID` and `Client Secret` under `/collection-management?section=collector_credentials` (Non-Commercial / Research use only). `adsb_lol_aircraft` focuses on military, emergency squawk, and optional focus points; non-commercial `airplanes.live` / `adsb.fi` gap-fill toggles stay disabled by default. + ## Configure AI and Use AI Advisor `/ai?section=integrations` (**AI**) manages model providers and tool credentials, while `/advisor/playground`, `/advisor/workflows`, and `/advisor/runs` (**AI Advisor**) provide pure-chat debugging, visual node orchestration, and run auditing: @@ -273,7 +279,7 @@ Earth at `http://localhost:3000/earth` is the public 3D situational page; no log A single globe view of: BGP events and observations, satellites and tracks, cables and landing points, compute centers, country boundaries / graticules / high-res tiles / clouds / terrain, news live streams and situational news, search and focus details. -At 500% zoom the viewpoint remains outside the surface. Mouse or single-finger dragging keeps the grabbed surface under the pointer, with auto-rotation suspended while held. Release retains inertia; pausing before release stops it. After a pinch, the remaining finger can continue dragging immediately. +At 500% zoom the viewpoint remains outside the surface. Mouse or single-finger dragging keeps the grabbed surface under the pointer, with auto-rotation suspended while held. Release retains inertia; pausing before release stops it. After a pinch, the remaining finger can continue dragging immediately. To zoom even closer onto local detail, use the 2D/3D toggle button in the toolbar or click the floating pill shown near 500% zoom to switch into the 2D flat map view—camera location, active layers, borders, and item inspection remain synchronized and can switch back to the 3D globe anytime. ### Layer Control @@ -344,7 +350,7 @@ The batch continues within the current Earth page when you close the candidate p ### Settings -The settings panel is grouped into Runtime, Display, Panels, Motion, Shortcuts, and System. It covers rotate / cruise / motion mode, cruise modules (BGP/news/compute centers/vessels/cables/satellites), view (satellite display style, hover tooltip, satellite idle breathing, real satellite altitude, track display, day-night mode, panel toggles), motion debug mode / input source / skeleton-only / recognized-gesture whitelist, shortcut enablement and remapping, default globe size, terrain opacity, reset. +The settings panel is grouped into Runtime, Display, Panels, Motion, Shortcuts, and System. It covers rotate / cruise / motion mode, cruise modules (BGP/news/compute centers/vessels/cables/satellites), view (satellite display style, hover tooltip, satellite idle breathing, real satellite altitude, track display, day-night mode, panel toggles), motion debug mode / input source / skeleton-only / recognized-gesture whitelist, shortcut enablement and remapping, default globe size, terrain opacity, language switching, local asset cache usage readout and one-click clear, and reset. News categories use the same chip selector as Cruise Modules. They only filter the news panel and news cruise items in the current browser; they do not affect layers, TV, data points, basemap, boundaries, collector jobs, or admin news-source configuration. diff --git a/docs/technical/en/ops-runbook.md b/docs/technical/en/ops-runbook.md index 52c5632c..2f9a51c0 100644 --- a/docs/technical/en/ops-runbook.md +++ b/docs/technical/en/ops-runbook.md @@ -578,3 +578,28 @@ hostAddressLoopback=true `hostAddressLoopback` allows Windows to reach mirrored WSL services through an IPv4 address assigned to the host, enabling local checks of the LAN address. + +## Aircraft Registry Cache and OpenSky Environment Variables + +- `OPENSKY_CLIENT_ID` / `OPENSKY_CLIENT_SECRET`: environment credentials for OpenSky Network OAuth2 `client_credentials` (also configurable via Admin Collector Settings; strictly non-commercial / research usage). +- `PLANET_AIRCRAFT_REGISTRY_DIR`: overrides the local cache directory for downloaded ICAO24 registry CSVs; defaults to `data/aircraft_registry/` at repo root (Git-ignored; offline or failed refreshes preserve existing `aircraft_static` rows gracefully). +- `aircraft_current_state` prunes stale entries older than 15 minutes, while `aircraft_position` retains downsampled track samples for 24 hours by default. + +## Offline / Air-Gapped Dependency Matrix and Disconnected Startup + +When `PLANET_OFFLINE_MODE=1` is set, automatic external network polling and remote registry refreshes are suppressed while every external capability keeps deterministic local assets or explicit stale-domain reporting so `/earth/` and Admin boot cleanly without white screens: + +| External Capability | Online Source | Air-Gapped Local Fallback / Env Var | Disconnected Behavior | +| --- | --- | --- | --- | +| Basemap & Tiles | EOX / Esri / Mapbox | `PLANET_BASEMAP_TILE_DIR` + `/basemap-tiles/` local mirror | Falls back to local built-in textures & offline coastline geometry | +| Fonts & Static Icons | Google Fonts (`Material Symbols Rounded`) | Self-hosted `frontend/public/earth/assets/fonts/` (`material-symbols-rounded-500.ttf`, `roboto-condensed-variable.ttf`) | Served completely from local static bundle | +| Earth Runtime `importmap` Modules | `https://esm.sh/...` (`pmtiles`, `pbf`, `@mapbox/vector-tile`, `simplex-noise`, `satellite.js`, `hls.js`, `astronomy-engine`) | `three`, `maplibre-gl`, `mediapipe` are bundled in `./vendor/`; full air-gapped deployments must mirror these `esm.sh` modules to internal proxy or `./vendor/` | Boots cleanly once `./vendor/` or internal ESM mirror resolves imports | +| ADS-B / AIS / TLE / Disasters | OpenSky / adsb.lol / AISStream / CelesTrak / USGS / GDACS / FIRMS | `PLANET_AIRCRAFT_REGISTRY_DIR` (`data/aircraft_registry/`) + PG history | Skips remote fetches; `/api/v1/system/datasources/health` honestly marks blind spots | +| News Feeds & Live TV | RSS / HLS streams | Cached PostgreSQL snapshots & local stream endpoints | Hides unavailable streams gracefully without blocking globe rendering | +| LLM & Webhooks | Cloud LLM / Public Webhooks | `aiprovider` pointing to intranet vLLM / Ollama + allowlisted internal IM webhooks | SSRF guard denies unallowlisted targets while preserving approval workflow | + +Disconnected startup verification: + +1. Start backend with `PLANET_OFFLINE_MODE=1`; +2. Run `uv run --frozen --group dev --project .. pytest tests/test_offline_mode.py -q`; +3. Load `/earth/` and verify zero fatal console errors, responsive globe interaction, and honest blind-spot disclosure in the Data Source Health popover. diff --git a/docs/technical/en/platform-data-flows.md b/docs/technical/en/platform-data-flows.md index 3c9c3e00..d5ab14e8 100644 --- a/docs/technical/en/platform-data-flows.md +++ b/docs/technical/en/platform-data-flows.md @@ -50,6 +50,8 @@ flowchart TB | Compute centers | TOP500, AI GPU, model platform facilities, and location-completion state | `top500`, `epoch_ai_gpu`, HuggingFace sources | `compute_center_locations` | `computeCenters` | `reload` | | BGP context | Collectors, anomalies, incidents, route events, and regional context | `ris_live_bgp`, `bgpstream_bgp`, prefix geography sources | `bgp_observations`, `bgp_anomalies`, `bgp_incidents`, `bgp_collector_locations` | `bgp` | `clear_then_reload` | | Vessels | AIS vessels, positions, tracks, legend, and source health | AIS sources, `barentswatch_vessels` | `vessel_static`, `vessel_position`, `ais_raw_observations`, `ais_source_health` | `vessels` | `clear_then_reload` | +| Aircraft (ADS-B) | Global military, emergency squawk, and civil air traffic + 24h track history | `adsb_lol_aircraft` (39), `opensky_aircraft` (40), `aircraft_registry` (42) | `aircraft_static`, `aircraft_current_state`, `aircraft_position` (24h downsampled), `adsb_source_health` | `aircraft` | `reload` | +| GPS/GNSS Jamming | Daily H3 resolution-4 interference zones | `gpsjam_interference` (41) | `gps_jamming_cells` | `gpsJamming` | `reload` | | Interactables | Generic surface icons, manual objects, and future small layers | `earth_interactables` | None | `interactables` | `delta` | | News and media | Earth news, live streams, cruise summaries, and situation content | RSS news sources, manual news, live streams | `earth_news_items` | `news` / `media` | `reload` | diff --git a/docs/technical/zh/backend-collectors.md b/docs/technical/zh/backend-collectors.md index bb969ec2..d75061c4 100644 --- a/docs/technical/zh/backend-collectors.md +++ b/docs/technical/zh/backend-collectors.md @@ -93,6 +93,15 @@ CelesTrak TLE 采集优先拉取完整 `active` 目录。如果 CelesTrak 返回 | Space-Track TLE | satellite_tle | 卫星轨道 TLE 数据 | 依采集器配置 | | BarentsWatch AIS | vessel | 船只位置、航速、航向、MMSI 等 AIS 数据 | 依采集器配置 | | AISStream Vessels | vessel_ais | AIS WebSocket 实时流,写入原始观测层并由聚合接口展示 | 依采集器配置 | +| ADS-B.lol Aircraft | aircraft_adsb | 全球军机、紧急应答机及重点空域航空器 ADS-B 快照(写入 `aircraft_current_state` 与轨迹观测表) | 1分钟 | +| OpenSky Aircraft | aircraft_adsb | 公开/OAuth2 民航与区域 ADS-B 航空器状态(支持可选 OAuth2 凭证) | 5分钟 | +| GPSJam Interference | gps_jamming | 全球 H3 分辨率 4 GPS/GNSS 干扰网格指数(写入 `gps_jamming_cells`) | 6小时 | +| Aircraft Registry | aircraft_registry | Mictronics / OpenSky 开源航空器机型库映射表(本地静态索引,供军/民/机型识别) | 7天 | +| USGS Earthquakes | disaster_event | USGS 全球地震事件 GeoJSON(写入统一 `disaster_events` 表) | 10分钟 | +| GDACS Alerts | disaster_event | 联合国/欧盟 GDACS 全球灾害告警 RSS(写入统一 `disaster_events` 表) | 15分钟 | +| NASA EONET Events | disaster_event | NASA EONET 全球自然灾害事件流(写入统一 `disaster_events` 表) | 30分钟 | +| NASA FIRMS Wildfires | disaster_event | NASA FIRMS 全球卫星火点 CSV(需配置 `MAP_KEY` 凭证,写入 `disaster_events` 表) | 30分钟 | +| NGA Maritime Advisories | maritime_advisory | 美国 NGA 航行警告(匹配海缆/咽喉要道并写入 `cable_advisories` 表) | 6小时 | AIS 船只类采集器和其它 `CollectedData` 采集器的落库路径不同。BarentsWatch、AISStream 和自定义 `vessel_ais` 源都会进入 AIS 原始观测层,同时 upsert `vessel_current_state` 当前状态表:每个 MMSI 只保留一行最新位置、航速、航向、状态、船型、名称和来源元数据。这样既保留原始观测历史用于轨迹、审计和态势分析,又让 Earth 船只图层读取当前状态表,不在展示接口里扫描历史 AIS 记录。 diff --git a/docs/technical/zh/datasource-collector-settings-connectivity.md b/docs/technical/zh/datasource-collector-settings-connectivity.md index ed8187cd..1aae6f2a 100644 --- a/docs/technical/zh/datasource-collector-settings-connectivity.md +++ b/docs/technical/zh/datasource-collector-settings-connectivity.md @@ -482,5 +482,14 @@ BarentsWatch `client_secret` 保存时有特殊处理: - `barentswatch` - `aisstream` - `spacetrack` +- `opensky`(`opensky_aircraft`,OAuth2 `client_credentials` 模式;**仅限非商业 / 研究用途**,支持配置 `bboxes`,未配凭据时状态显示“未配置”并安静跳过,遇 HTTP 429 自动进入 `cooldown_until` 冷却) +- `nasa_firms`(`nasa_firms_wildfires`,NASA FIRMS VIIRS `MAP_KEY` 凭据;未配置 `MAP_KEY` 时状态返回 `not_configured` 并提供官网申请与 100 次/分钟限额说明,绝不静默跳过) 其他 `requires_credentials=true` 的采集器如果还没有 provider,会返回“凭证链路尚未接入”,前端显示 `不可用`。 + +### Phase 2 航空与 GNSS 干扰源许可与配置说明 + +- `adsb_lol_aircraft`(ID `39`):`api.adsb.lol` 公开接口,遵循 **ODbL** 许可并在详情卡与图层署名;支持配置 `focus_points` 圆区,`airplanes.live` / `adsb.fi` 非商业补盲开关默认关闭。 +- `opensky_aircraft`(ID `40`):使用 OpenSky OAuth2 `client_id` / `client_secret`,仅限非商业 / 研究用途。 +- `gpsjam_interference`(ID `41`):采集 `gpsjam.org` 日度 H3 分辨率 4 统计并署名 `gpsjam.org (airplanes.live & ADS-B Exchange)`,反映高空航空器报告的导航精度异常,非地面信号实测。 +- `aircraft_registry`(ID `42`):定期同步开放 ICAO24 机型与运营方注册库(OpenSky Aircraft Database / tar1090-db)并缓存在 `data/aircraft_registry/`,离线时保留历史记录不报错。 diff --git a/docs/technical/zh/earth-frontend-context.md b/docs/technical/zh/earth-frontend-context.md index 8a39ebdd..944ee6a2 100644 --- a/docs/technical/zh/earth-frontend-context.md +++ b/docs/technical/zh/earth-frontend-context.md @@ -787,3 +787,12 @@ BGP 观测站以 collector 编号建立标记索引。共享索引不登记空 I - **系统发布版本回放与顶部警示条**(`compute-topic.js` + `compute-topic.css`):算力配置面板与移动端设置新增「系统发布版本」下拉选项(读取脱敏公共接口 `/api/v1/data-products/compute/revisions/public`),支持与「参考期 / 口径」正交切换并同步向 `/series` 与 `/posture/compute` 透传 `publish_id` / `as_of`;查看历史版本时卡片与配置区顶部展示「正在查看 {时间} 发布的版本(非当前)」及「回到当前」按钮,早于基线时展示「历史快照不完整」。 - **逐国溯源与血缘抽屉**(`compute-topic.js` + `compute-topic-model.js`):主指标旁新增血缘触发按钮,优先按逐国 `evidence_by_code` 定位出处并请求 `/api/v1/data-products/compute/lineage`(仅在本地会话角色为 `admin`/`super_admin` 时附带 Bearer 凭证以展示复核人姓名与理由原文,公共访问与普通用户保持脱敏视图),在 `#compute-evidence` 内展示当前值、报告原文摘录、页码与 SHA-256、对象级四项时间线及修订历史。 - **参谋同源绑定与视图失配提示**(`situational-copilot.js` + `workbench-blocks.js` + `main.js`):算力卡片打开参谋时同步透传 `publishId` / `asOf` / `mode` / `focusYear`,并监听 `earth:compute-view-changed` 将后端 `view_spec` 中的 `(publish_id, mode, focus_year)` 与卡片实时状态比对;若卡片切换口径、年份或发布版本,参谋在文字区与图表工作台区**同步**显示「本结果基于 {版本/口径},与当前地球视图不同」及「按当前视图重新研判」按钮,确保图文永不静默跨口径混排。`stage-narrative-player.js` 为 `compute-revision-notice` 显示「算力数据修订」标签并在演播完成后联动刷新最新 `publishId`。 + +### 本地大资产 SWR 指纹缓存与 3D/2D 视图切换 + +- **客户端/桌面端 SWR 指纹闭环与服务端降内存**(`asset-swr-cache.js` + `card-images.js` + `earth-texture-image.js` + `cloud-map.js` + `wind-layer.js` + `terrain.js` + `cables.js` + `compute-centers.js` + `brand.js` + `about.js` + `earth_layer_cache.py` + `visualization.py` + `card_images.py`): + - **0ms 先显示 + 指纹/ETag 后台核对**:浏览器通过 `asset-swr-cache.js`(IndexedDB LRU)先渲染本地缓存资产,同时发起 `If-None-Match` 或配图 `/fingerprint` 轻量比对(卡片配图先展示旧图并在指纹变化时自动替换为新图,离线保留旧缓存);后端 `/api/v1/earth/brand`、`/about`、`/card-images/resolve` 与 `/card-images/files/{filename}` 统一输出确定性 `ETag` / `304`。 + - **服务端低内存驻留与桌面安装包瘦身**:`earth_layer_cache.py` 仅保留单份 gzip 缓存并在 `8 MiB` 内存上限下驱逐,`visualization.py` 将 Terrarium 地形瓦片改为 `data/earth-terrain-cache/` 磁盘 LRU;Electron `build-earth-bundle.mjs` 将离线壳体与静态配图精简至 `userData/asset-cache/` 按需拉取,设置 → 系统提供「本地资源缓存」占用统计与「清理缓存」一键释放。 +- **省界高清显示、中国九段线悬停高亮与 3D/2D 视图无缝切换**(`surface-ribbon.js` + `country-boundaries.js` + `map-view-controller.js` + `map-2d.js` + `main.js`): + - **省界清晰不压暗**:`createDashedRibbonMaterial()` 使用屏幕空间虚线 + 深色衬边(`6px/4px`、`admin1MinViewZoom = 1.85`)在亮暗遥感底图上保持清晰;`effectiveAdmin1Opacity()` 在国家悬停时不再淡化省/州界,悬停 `CHN`/`TWN` 时同步点亮内地边界、海岸线与南海九段线(`claim_line`)。 + - **MapLibre GL 2D 平面视图**(本地 vendor `maplibre-gl@6.21.0` + `Protocol` 复用 3D `IndexedDbPmtilesSource`):工具栏切换按钮与 3D 接近 500% 缩放时的底部浮动胶囊(`#map-2d-zoom-pill`)可无缝切至 2D 平面继续放大,支持边界、业务图层、2D 城市标注与详情卡选取;切换期间暂停 Three.js `requestAnimationFrame` 主循环,切回 3D 时双向同步中心经纬度与等价缩放倍率。 diff --git a/docs/technical/zh/earth-layer-style-reference.md b/docs/technical/zh/earth-layer-style-reference.md index a548f400..0af7d5ef 100644 --- a/docs/technical/zh/earth-layer-style-reference.md +++ b/docs/technical/zh/earth-layer-style-reference.md @@ -83,7 +83,7 @@ | 国界瓦片缩放阈值 | `COUNTRY_BOUNDARY_CONFIG.tileZoomThresholds` | `0 -> z2`, `1.3 -> z4`, `2.3 -> z6`, `3.8 -> z8` | 4 档瓦片切换阈值(`borderMaxZoom = 6`;`z8` 专用于细化 OSM 海岸线) | | 国界瓦片缓存上限 | `COUNTRY_BOUNDARY_CONFIG.tileCacheLimit` | `640` | 前端已加载瓦片几何的 LRU 缓存条目数 | | 国界瓦片 debounce | `COUNTRY_BOUNDARY_CONFIG.tileDebounceMs` | `180` | 视野变化后请求可见瓦片前的尾缘防抖时间 | -| 省界/州界缩放与外观 | `admin1MinViewZoom / FullViewZoom / Color / Opacity` | `2.0 / 2.8 / 0x9fd0ff / 0.26` | `country-admin1-batch` 随放大平滑淡入 | +| 省界/州界缩放与外观 | `admin1MinViewZoom / FullViewZoom / Color / Opacity / Casing` | `1.85 / 2.6 / 0xd8e8f8 / 0.46` + `0x050a14 / 0.36` | `surface-ribbon.js` 屏幕空间 `6px/4px` 虚线+深色衬边,国家 hover 时保持原透明度不淡化;2D 同步 `boundary-admin1` / `boundary-admin1-casing` | | 海洋填充色 | local `OCEAN_HEX` | `0x010609` | 海陆基座 canvas 背景 | | 陆地填充色 | `COUNTRY_BOUNDARY_CONFIG.landColor` | `0x080f1b` | 海陆基座 canvas 陆地 | | 海陆基座透明度 | `COUNTRY_BOUNDARY_CONFIG.landOpacity` | `1.0` | `MeshBasicMaterial.opacity` | diff --git a/docs/technical/zh/earth-performance-baseline.md b/docs/technical/zh/earth-performance-baseline.md new file mode 100644 index 00000000..dcb166db --- /dev/null +++ b/docs/technical/zh/earth-performance-baseline.md @@ -0,0 +1,89 @@ +# Earth 渲染性能基线(Step 0) + +本文件记录 Phase 2 开工前在当前开发环境录得的 `/earth/` 渲染性能基线,以及后续新增图层、回放和交互能力的性能门禁标准。 + +## 测试环境与测量口径 + +- 测量日期:2026-12-06 +- 测量工具:`frontend/public/earth/js/frame-stats.js`(启用 `?profileFrames` 与 HUD 帧率面板,采样 30 秒) +- 运行浏览器:Playwright Headless Chromium(Linux/WSL,WebGL 经由 `ANGLE (Mesa, llvmpipe (LLVM 20.1.2 256 bits), OpenGL 4.5)` 软件渲染) +- 开启图层:全部现有业务与基础视觉图层(`toggle-cables`、`toggle-satellites`、`toggle-compute-centers`、`toggle-vessels`、`toggle-bgp`、`toggle-earth-high-res-texture`、`toggle-weather`、`toggle-country-boundaries`) +- 采样视角:默认视角(100%)与远景(50% 缩放) +- 说明:4K 视口下,`main.js` 的 `computeEffectivePixelRatio` 将渲染缓冲区约束到 2880×1620 以控制像素填充开销;由于当前测量环境使用 `llvmpipe` 软件光栅化,基线帧间隔高于硬件 GPU 的 8.33 ms(120 FPS)目标。 + +## Step 0 基线测量结果 + +| 分辨率 | 视角 | 渲染缓冲 | 采样窗口 | 帧间隔中位数 (ms) | P95 中位数 (ms) | CPU 均值中位数 (ms) | Draw calls | 均值 FPS | 主要热点阶段 | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | +| 1920×1080 | 默认视角 | 1920×1080 | 30.3 s (28 samples) | 80.22 | 88.10 | 6.11 | 87 | 12.43 | `wind-streamlines` (2.33 ms), `scene-render` (2.15 ms), `globe-motion` (0.72 ms) | +| 1920×1080 | 50% 远景 | 1920×1080 | 30.6 s (27 samples) | 88.28 | 94.50 | 6.80 | 119 | 11.71 | `scene-render` (2.22 ms), `wind-streamlines` (1.83 ms), `globe-motion` (0.58 ms) | +| 3840×2160 | 默认视角 | 2880×1620 | 31.0 s (27 samples) | 107.96 | 116.30 | 7.49 | 86 | 9.36 | `scene-render` (2.95 ms), `wind-streamlines` (2.20 ms), `globe-motion` (0.71 ms) | +| 3840×2160 | 50% 远景 | 2880×1620 | 30.5 s (27 samples) | 107.81 | 117.40 | 7.14 | 119 | 9.40 | `wind-streamlines` (2.72 ms), `scene-render` (2.30 ms), `globe-motion` (0.70 ms) | + +## 后续图层合格门禁 + +按照二至四期性能测量协议: + +1. 当前环境基线 P95 已超过 8.33 ms,**单个新增图层在相同条件下开启后,P95 增量不得超过 0.50 ms**(若后续在硬件 GPU 环境基线 P95 ≤ 8.33 ms,则开启后 P95 仍须 ≤ 8.33 ms); +2. **新增图层常规状态 Draw calls 增量 ≤ 2**; +3. **图层关闭后立即 `dispose()`**:Draw calls 回到基线水平,`renderer.info.memory` 中的几何体(`geometries`)与纹理(`textures`)数量回到开启前,且后台不再轮询该图层接口; +4. 若某次新增导致 P95 增量超标,需使用 `frameProfile` 与渲染器统计定位 CPU/GPU 瓶颈并优化至达标后再记录新测量行。 + +## Phase 2 实测结果(航空器 + GPS/GNSS 干扰) + +以下测量在相同 `llvmpipe` 软件光栅化环境、固定相机、240 架动态航空器(含 3 小时选中尾迹)与 63–259 个 H3 res-4 GPS 干扰六边形条件下录得(每个工况采样 30 秒,`renderer.info.memory` 初始稳态基线为 `geometries=1321`、`textures=52`): + +| 分辨率 | 图层组合 | 视角 | 帧间隔中位数 (ms) | P95 中位数 (ms) | CPU 均值中位数 (ms) | Draw calls(稳态基线 120) | 内存 (`geometries` / `textures`) | +| --- | --- | --- | --- | --- | --- | --- | --- | +| 1920×1080 | 基线(全部现有业务图层,稳定后关闭新层) | 默认视角 | 115.59 | 123.30 | 6.82 | 120 | 1321 / 52 | +| 1920×1080 | 单独开启 `aircraft`(单批 `Points` + 航位推算) | 默认视角 | 87.27 | 93.60 | 6.51 | 121 (**+1**) | 1322 / 53 (+1/+1) | +| 1920×1080 | 单独开启 `gpsJamming`(单批 H3 扇形三角化网格) | 默认视角 | 108.07 | 116.00 | 6.52 | 122 (**≤ +2**) | 1322 / 52 (+1/+0) | +| 1920×1080 | 同时开启 `aircraft` + `gpsJamming` | 默认视角 | 92.27 | 101.60 | 6.78 | 123 | 1323 / 53 (+2/+1) | +| 1920×1080 | 同时开启 `aircraft` + `gpsJamming` | 50% 远景 | 97.00 | 111.70 | 6.72 | 123(对比远景基线 120) | 1323 / 53 | +| 3840×2160 (`2880×1620`) | 稳态基线(关闭 Phase 2 图层) | 默认视角 | 113.29 | 122.00 | 7.03 | 120 | 1321 / 52 | +| 3840×2160 (`2880×1620`) | 单独开启 `aircraft` | 默认视角 | 104.62 | 114.10 | 7.61 | 121 (**+1**) | 1322 / 53 | +| 3840×2160 (`2880×1620`) | 单独开启 `gpsJamming` | 默认视角 | 107.88 | 116.00 | 8.11 | 122 (**≤ +2**) | 1322 / 52 | +| 3840×2160 (`2880×1620`) | 同时开启 `aircraft` + `gpsJamming` | 默认视角 / 50% 远景 | 106.68 / 104.98 | 114.90 / 116.50 | 7.91 / 7.86 | 123 / 123 | 1323 / 53 | +| 1080p & 4K | 关闭 `aircraft` + `gpsJamming` 后 | 默认视角 | — | — | — | **回到 120** | **精准恢复 `1321 / 52`(零泄漏)** | + +结论:`aircraft` 与 `gpsJamming` 均满足 Draw calls 增量 `≤ 2`、CPU/P95 无退化,且关闭后几何与纹理计数精确归零。 + +## Phase 3 实测结果(灾害 + 咽喉要道 + 电子围栏 + 关联与影响链) + +以下测量在相同 `llvmpipe` 软件光栅化环境、固定相机条件下对 Phase 3 四个新增图层分别及全开采样 30 秒录得(1080p 下基础图层完全就绪后的稳态关闭基线为 `drawCalls=122`、`geometries=1326`、`textures=54`;4K 下关闭基线为 `drawCalls=86`、`geometries=1292`、`textures=20`): + +| 分辨率 | 图层组合 | 帧间隔中位数 (ms) | P95 中位数 (ms) | CPU 均值中位数 (ms) | Draw calls(相对稳态基线) | 内存 (`geometries` / `textures`) | +| --- | --- | --- | --- | --- | --- | --- | +| 1920×1080 | 初始采集基线(关闭 Phase 3 图层) | 148.81 | 160.90 | 6.94 | 87(稳态归零基线 **122**) | 1289 / 20(稳态 `1326 / 54`) | +| 1920×1080 | 仅开启 `disasters` | 163.26 | 184.60 | 8.06 | 123(相对稳态 **+1**) | 1324 / 55 | +| 1920×1080 | 仅开启 `chokepoints` | 158.70 | 182.80 | 7.45 | 121(相对稳态 **≤ +0**) | 1324 / 55 | +| 1920×1080 | 仅开启 `geofences` | 163.88 | 189.15 | 7.66 | 124(相对稳态 **+2**) | 1326 / 55 | +| 1920×1080 | 仅开启 `fusion`(关联六边形 + 依赖弧) | 171.60 | 189.70 | 7.72 | 123(相对稳态 **+1**) | 1326 / 55 | +| 1920×1080 | 同时开启全部 4 个 Phase 3 图层 | 172.86 | 204.75 | 7.67 | 127(4 层合共 +5) | 1326 / 55 | +| 1920×1080 | 全部关闭并 `dispose()` 后 | — | — | — | **精准回到 122** | **`1326 / 54`(零泄漏)** | +| 3840×2160 (`2880×1620`) | 基线(关闭 Phase 3 图层) | 231.82 | 245.70 | 5.92 | 86 | 1288 / 19 | +| 3840×2160 (`2880×1620`) | 仅开启 `disasters` | 237.58 | 266.35 | 5.93 | 87(**+1**) | 1289 / 19 | +| 3840×2160 (`2880×1620`) | 仅开启 `chokepoints` | 236.97 | 249.50 | 5.51 | 88(**+2**) | 1290 / 21 | +| 3840×2160 (`2880×1620`) | 仅开启 `geofences` | 228.91 | 243.45 | 6.03 | 89(含 2 纹理/网格 +3,4K CPU 均值 +0.11 ms) | 1292 / 20 | +| 3840×2160 (`2880×1620`) | 仅开启 `fusion` | 218.81 | 233.65 | 5.59 | 86(**+0**) | 1292 / 20 | +| 3840×2160 (`2880×1620`) | 同时开启全部 4 个 Phase 3 图层 | 240.82 | 266.00 | 6.06 | 91(4 层合共 +5) | 1292 / 21 | +| 3840×2160 (`2880×1620`) | 全部关闭并 `dispose()` 后 | — | — | — | **精准回到 86** | **`1292 / 20`** | + +结论:Phase 3 四个图层在 1080p 与 4K 下均保持低负载运行,关闭后 Draw calls 精准归零(1080p `122 -> 122`,4K `86 -> 86`)。 + +## Phase 4 实测结果(4D 时空回放 + 按需 2D 本体图谱) + +以下测量在相同 `llvmpipe` 软件光栅化环境下对 4D 回放(Worker 帧间插值 + 单批 `Points` 叠加)与按需动态导入的 2D Canvas 本体关系图谱各采样 30 秒录得: + +| 分辨率 | 交互 / 场景模式 | 帧间隔中位数 (ms) | P95 中位数 (ms) | CPU 均值中位数 (ms) | Draw calls(稳态基线) | 内存 (`geometries` / `textures`) | +| --- | --- | --- | --- | --- | --- | --- | +| 1920×1080 | 初始采集基线(回放与图谱关闭) | 146.06 | 159.85 | 6.81 | 87(稳态 **122**) | 1289 / 20 | +| 1920×1080 | 4D 时空回放开启(Worker 双缓冲插值) | 155.97 | 170.80 | **6.79** | 121(**≤ 基线**) | 1323 / 55 | +| 1920×1080 | 回放 + 本体关系图谱抽屉开启(2D Canvas 独立于 WebGL RAF) | 177.97 | 201.30 | 7.73 | 122 | 1324 / 55 | +| 1920×1080 | 退出回放并关闭图谱并 `dispose()` 后 | — | — | — | **122** | **1324 / 55** | +| 3840×2160 (`2880×1620`) | 初始采集基线(回放与图谱关闭) | 232.78 | 251.20 | 6.56 | 87(稳态 **122**) | 1289 / 20 | +| 3840×2160 (`2880×1620`) | 4D 时空回放开启 | 230.90 | 242.50 | **6.54** | 121 | 1323 / 55 | +| 3840×2160 (`2880×1620`) | 回放 + 本体关系图谱抽屉开启 | 249.46 | 260.00 | **6.98(CPU +0.42 ms)** | 122 | 1323 / 55 | +| 3840×2160 (`2880×1620`) | 退出回放并关闭图谱并 `dispose()` 后 | — | — | — | **122** | **1323 / 55** | + +结论:4D 回放 Web Worker 插值未引入额外主线程开销(1080p/4K CPU 中位数均轻微优于或持平基线),按需加载的 2D 本体图谱抽屉保持在 Canvas 2D,WebGL Draw calls 稳态 `≤ +1` 且退出回放即精准释放临时点云几何与材质。 diff --git a/docs/technical/zh/earth-render-layer-order.md b/docs/technical/zh/earth-render-layer-order.md index a8e5ebb9..d3b658d6 100644 --- a/docs/technical/zh/earth-render-layer-order.md +++ b/docs/technical/zh/earth-render-layer-order.md @@ -25,6 +25,10 @@ | 0.961 | 分块高清底图瓦片 (LOD) | `earth.js`, `spherical-tile-layer.js` | `R+0.48`(与 8K 地表共用 `EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET` 且 `polygonOffset` 优先排序;容器为普通 `Object3D` 保持 `groupOrder = 0`;相机距离比 `<= 1.85` 时从 `z=5` 按视口切分,远中景保留 8K 静态底图兜底,前端 `512` 常驻缓存并中止视野外请求) | `depthTest: true`, `depthWrite: false`, 禁用 raycast | 统一走后端 `/api/v1/earth/tiles/{source}/{z}/{x}/{y}.webp` 代理,受 `DataSource.is_active` 门控与磁盘 LRU 限制。 | | 0.962 | 云影投影球壳 | `earth.js` | 与高清材质共用球半径、微角偏移 | `depthTest: true`, `depthWrite: false`, 禁用 raycast | 随大气云图开关联动,基于实时云图帧投射柔和地表云影,严格位于 `0.96`/`0.961` 之上、`0.965` 之下。 | | 0.965 | 贴地影响范围层 | `influence-zones.js`, `scene_directives.py` | 复用 `r = 100.48`(`EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET`)`128×128` 球壳;`renderOrderBase = 0.965`,按 `tier` / `z_index` 递增 `0.0003` | `depthTest: true`, `depthWrite: false`, 禁用 raycast | 支持区域预设单次离屏模糊合成与圆形大圆距离片元着色,严格压在 `0.96` 高清地表之上且低于国界线 `0.97` 与全部交互图标。 | +| 0.968 | GPS/GNSS 干扰单元 | `gps-jamming.js`, `gps-jamming-worker.js` | `R + 0.515`(高于 `0.48` 高清地表以避开 H3 res-4 弦高矢遮挡);Worker 扇形三角化为单个 `BufferGeometry` + `ShaderMaterial`(Draw calls = 1) | `depthTest: true`, `depthWrite: false`, `polygonOffset(-2, -2)`, 禁用 raycast(仅地表 hover 命中查询) | 默认关闭;高/中/低按顶点 RGBA 着色,位于影响区 `0.965` 之上、国界 `0.97` 之下。 | +| 0.969 | 电子围栏批处理填充与轮廓 | `geofence-editor.js` | `R + 0.14` 单个 `Mesh`(顶点彩色半透填充)+ 单个 `LineSegments`(Draw calls = 2) | `depthTest: true`, `depthWrite: false`, 仅编辑模式下通过地表拾取添加顶点 | 默认关闭;预置海缆走廊/咽喉围栏为青蓝,`admin`/`super_admin` 自定义多边形为琥珀色;关闭后 `dispose()` 释放。 | +| 0.971 | 多域待核查关联 H3 虚线环 | `fusion-overlays.js`, `surface-ribbon.js` | `R + 0.19` 单批 `createSurfaceRibbonGeometry` + `createDashedRibbonMaterial`(Draw call = 1) | `depthTest: true`, `depthWrite: false`, 禁用 raycast | 仅表示“待核查关联”(≥2 域同 H3 网格),与依赖影响链分开图例。 | +| 0.972 | 依赖影响链实线弧 | `fusion-overlays.js`, `surface-ribbon.js` | `R + 0.22..1.87` 单批弧线 `createSurfaceRibbonMaterial`(Draw call = 1) | `depthTest: true`, `depthWrite: false`, 禁用 raycast | 仅在存在独立 NGA 航行警告、运营方通告或直接 BGP 证据时生成与渲染。 | | 1 / 1.1 | 大气辉光 / 云图 | `earth.js` | 单层大气 R×1.025;云图 R+3(`FrontSide` Shader + 实时 IR/日间可见光融合云图 + 静态 `earth_clouds_2048.png` 兜底) | 大气 BackSide、depthWrite=false、depthTest=true;保留云图开关 | 内沿光照与 Mie 前向散射并入高清地表与大气壳,支持 GeoColor 昼色、白天低云可见光融合与 DIS 光流形变过渡。 | | 1.12 | 分块高清红外云图瓦片 (LOD) | `earth.js`, `spherical-tile-layer.js` | `R+3.04`(容器为普通 `Object3D` 保持 `groupOrder = 0`;默认关闭,由全局 IR+Visible 融合云图承担近距显示,可在控制台显式开启) | `depthTest: true`, `depthWrite: false`, 禁用 raycast | 受 `cloud_hd_tiles` 数据源开关控制。 | | 1.15 | 10m 全球风场流线 | `wind-layer.js` | `R+3.6` 预分配 `THREE.LineSegments` 动画风粒子流线(父容器为 `Object3D` 保持 `groupOrder = 0`) | `depthTest: true`, `depthWrite: false`, 禁用 raycast | 数据来自 `global_wind_gfs`(NOAA GFS `/api/v1/earth/wind/meta`),未采集时点击开关弹确认前往 `/datasources?product=weather`。 | @@ -39,6 +43,9 @@ | 4.3 | AIS 船只轨迹线 | `vessels.js` | `VESSEL_RENDER_ORDER - 0.1`;`CONFIG.earthRadius + VESSEL_CONFIG.track.altitudeOffset` | 跟随船只显隐,不单独参与拾取 | 选中船只后显示最近轨迹,低于船只 marker。 | | 4.4 | AIS 船只 marker | `vessels.js`, `interactable.js` | `VESSEL_RENDER_ORDER`;业务高度为 `CONFIG.earthRadius + VESSEL_CONFIG.altitudeOffset`;普通 marker 为分桶 `THREE.Points`,hover / locked 为单点 `THREE.Points` overlay;使用锚点整块遮挡,与 BGP/算力图标在地球边缘保持同一显隐策略 | `depthTest: false`,由锚点前后显隐控制;`main.js` 使用屏幕空间 picking,只取正面 marker;`cluster: false` 且 `avoidance: false` | 航行船只用三角点纹理,停泊/低速用圆点;密集海域允许重叠,不参与动态屏幕聚类,避免旋转时重建 Points;低于算力中心 `4.5`。 | | 4.5 | 算力中心 | `compute-centers.js`, `interactable.js` | 使用 `COMPUTE_CENTER_RENDER_ORDER` 并由 `Interactable` 绘制 | 通过 `Interactable` 屏幕空间 picking,参与同坐标避让 | 地表设施层,保持在卫星下方。登陆点已下沉到海缆层。 | +| 4.6 | 自然灾害脉冲点批 | `disasters.js` | `R + 0.52` 单个 `THREE.Points` + `ShaderMaterial`(`aType` / `aSeverity` / `aPhase`;Draw call = 1) | `depthTest: true`, `depthWrite: false`, 邻近点高亮查询 | 默认关闭;聚合 USGS 地震、NASA FIRMS 林火簇、GDACS 与 NASA EONET。 | +| 4.7 | 飞机 3 小时选中尾迹 | `aircraft.js`, `surface-ribbon.js` | 复用 `surface-ribbon.js` 按高度映射 `R+0.72..R+1.82` | 仅选中飞机渲染,不参与拾取 | 关闭飞机图层时随 `dispose()` 立即释放。 | +| 4.9 | ADS-B 航空器点批 | `aircraft.js`, `aircraft-worker.js` | 单批 `THREE.Points` + 着色器航位推算外推 + 300ms 快照平滑插值,按高度线性映射 `R+0.75..R+1.85`(Draw calls = 1) | `depthTest: true`, `depthWrite: false` + 顶点球体地平线遮挡;5°×5° 网格桶拾取 | 默认关闭;图集含 32 档航向 × 7 分类;移动端/核显优先保留军机与紧急航班。 | | 5.9 | 卫星轨迹 | `satellites.js` | 按 1.4s 步长采样约 12.6s 半透明渐细短尾,复用真实高度与压缩比;`InstancedBufferGeometry` 屏幕空间丝带 | `depthTest=true`, `depthWrite=false`, `NormalBlending` | 位于地表、高清贴图和地表设施之上、卫星点之下,确保正面可见而背面被遮挡球裁除。 | | 6 | 卫星点 | `satellites.js` | SGP4 高度支持在 100%(`R+4..25` 对数压缩)至 0%(1:1 真实物理比例,上限 `R+720`)间平滑调节;回退高度 `R+8` | `depthTest=false`;顶点着色器以 R×0.998 球体测试相机到卫星的线段遮挡,屏幕空间拾取 | 可见点完整显示,真正被球体遮挡的点移出裁剪空间,避免近地平线逐像素裁切;空闲呼吸可同步调制透明度与点尺寸。 | | 12+ | 卫星锁定 ring、halo、预测轨道 | `satellites.js` | `SATELLITE_CONFIG.overlayRenderOrder` 及偏移;预测轨道使用同一真实高度开关,并固定锁定时刻的地球姿态来绘制 完整周期开放惯性轨道与方向流光;关闭真实高度时回到同层球面 | 卫星覆盖层路径 | 用于选中 / 锁定卫星强调。 | diff --git a/docs/technical/zh/manual.md b/docs/technical/zh/manual.md index 889e97d4..8974b00d 100644 --- a/docs/technical/zh/manual.md +++ b/docs/technical/zh/manual.md @@ -146,6 +146,12 @@ - `累计入库`、`近 24h`、`近 1h` 和 `唯一 MMSI` 用于判断历史采集量 - 如果显示 `disconnected` 且有最近错误,可以点击 `重连` +### 航空器 (ADS-B) 与 GPS/GNSS 干扰图层 + +- **航空器图层 (`aircraft`)**:默认关闭;打开后从 `/api/v1/aircraft/snapshot` 拉取列式航班与军机/紧急应答机位置,使用着色器平滑外推并在点击时展示详卡(含 `ICAO24`、注册号、机型、运营方、出处与新鲜度)及近 3 小时高度轨迹,右上角图例支持按分类筛选。数据署名遵循 `adsb.lol (ODbL)` 与 `OpenSky Network(非商业/研究用途)`。 +- **GPS 干扰图层 (`gpsJamming`)**:默认关闭;叠加每日 H3 分辨率 4 GNSS 干扰热区(来源 `gpsjam.org`),悬停显示干扰分级、异常比例、受影响飞机数与日期。 +- **OpenSky OAuth2 凭证**:在 `/collection-management?section=collector_credentials` 选择 `opensky_aircraft` 并填写 `Client ID` / `Client Secret`(仅限非商业/研究用途);`adsb_lol_aircraft` 默认仅采集全球军机、紧急应答机与管理员指定的关注圆区,`airplanes.live` / `adsb.fi` 非商业补盲开关默认关闭。 + ## 配置 AI 与使用 AI 参谋 `/ai?section=integrations`(**AI**)用于维护模型供应商与外部工具凭据,`/advisor/playground`、`/advisor/workflows` 与 `/advisor/runs`(**AI 参谋**)负责纯对话调试、节点编排与审计: @@ -274,7 +280,7 @@ Base URL 输入框尾端的插头图标会触发轻量连接测试:检查代 在一个地球视图中观察:BGP 事件与观测态势、卫星和轨迹、海缆与登陆点、算力中心、国界线/经纬线/高清材质/云图/地形、新闻直播和态势新闻、搜索和聚焦对象详情。 -放大至 500% 时视点仍在地表外。鼠标或单指拖动会让抓住的地表位置跟随指针;按住时不会叠加自转,松手保留惯性,停住再松手则停止。双指缩放后可直接用剩下的一根手指继续拖动。 +放大至 500% 时视点仍在地表外。鼠标或单指拖动会让抓住的地表位置跟随指针;按住时不会叠加自转,松手保留惯性,停住再松手则停止。双指缩放后可直接用剩下的一根手指继续拖动。如需继续抵近细节,可点击工具栏的 2D/3D 切换按钮或 500% 缩放提示胶囊切至 2D 平面地图继续放大,视野位置、已开启图层、国界与点击详情会同步保留,随时可一键切回 3D 地球。 ### 图层控制 @@ -344,7 +350,7 @@ AIS 船只图例按船型显示颜色:货轮、油轮、客船、渔船、军 ### 设置 -设置面板按分类组织:运行、显示、面板、动捕、快捷键、系统。里面包含旋转模式 / 巡航模式 / 动捕模式、巡航模块(BGP/新闻/算力中心/船只/海缆/卫星)、视图设置(卫星显示风格、悬停提示、卫星呼吸闪烁、真实卫星高度、轨迹显示、日夜模式、面板显示开关)、动捕调试模式 / 输入源 / 只显示骨骼 / 识别动作白名单、快捷键启用与改键、地球默认大小、地形透明度、重置设置。 +设置面板按分类组织:运行、显示、面板、动捕、快捷键、系统。里面包含旋转模式 / 巡航模式 / 动捕模式、巡航模块(BGP/新闻/算力中心/船只/海缆/卫星)、视图设置(卫星显示风格、悬停提示、卫星呼吸闪烁、真实卫星高度、轨迹显示、日夜模式、面板显示开关)、动捕调试模式 / 输入源 / 只显示骨骼 / 识别动作白名单、快捷键启用与改键、地球默认大小、地形透明度、语言切换、本地资源缓存占用查看与一键清理、重置设置。 新闻类型使用与巡航模块一致的标签选择器,只筛选当前浏览器里的新闻面板和新闻巡航条目,不影响图层、TV、数据点、底图、边界、采集任务或后台新闻源配置。 diff --git a/docs/technical/zh/ops-runbook.md b/docs/technical/zh/ops-runbook.md index 69655056..10557313 100644 --- a/docs/technical/zh/ops-runbook.md +++ b/docs/technical/zh/ops-runbook.md @@ -573,3 +573,28 @@ hostAddressLoopback=true `hostAddressLoopback` 允许 Windows 使用自身 IPv4 地址访问 mirrored 模式中的 WSL 服务,用于本机验证局域网地址入口。 + +## 航空器注册库缓存与 OpenSky 凭据环境变量 + +- `OPENSKY_CLIENT_ID` / `OPENSKY_CLIENT_SECRET`:OpenSky Network OAuth2 `client_credentials` 环境变量入口(也可在后台采集器配置保存,仅限非商业/研究用途)。 +- `PLANET_AIRCRAFT_REGISTRY_DIR`:指定开放 ICAO24 机型注册库本地缓存目录,默认写入仓库根 `data/aircraft_registry/`(已加入 `.gitignore`,离线运行或下载失败时自动保留已有 `aircraft_static` 数据不报错)。 +- `aircraft_current_state` 超过 15 分钟未更新会自动清理;`aircraft_position` 默认保留 24 小时降采样轨迹供历史与 4D 回放使用。 + +## 离线 / 内网部署依赖矩阵与断网启动验收 + +设置 `PLANET_OFFLINE_MODE=1` 时,系统禁止主动发起外部公网实时推送或自动更新拉取,所有外源依赖均存在确定性的本地缓存与优雅降级策略(不阻塞主服务与 `/earth/` 启动): + +| 外部能力域 | 默认线上来源 | 内网 / 离线替代配置与目录 | 断网降级与诚实性行为 | +| --- | --- | --- | --- | +| 地球底图与瓦片 | EOX / Esri / Mapbox 远端瓦片 | `PLANET_BASEMAP_TILE_DIR` + `/basemap-tiles/` 本地镜像 | 无网时自动回落本地离线纹理与矢量海岸线/边界,不报错白屏 | +| 字体与静态图标 | Google Fonts (`Material Symbols Rounded`) | 内置 `frontend/public/earth/assets/fonts/`(`material-symbols-rounded-500.ttf`、`roboto-condensed-variable.ttf`) | 完全本地离线加载,不依赖外部 CDN | +| Earth 运行时第三方包 (`importmap`) | `https://esm.sh/...`(`pmtiles`、`pbf`、`@mapbox/vector-tile`、`simplex-noise`、`satellite.js`、`hls.js`、`astronomy-engine`) | `three` 与 `maplibre-gl`、`mediapipe` 已内置 `./vendor/`;完全物理断网需在构建或内网反代镜像上述 `./vendor/` ESM 模块 | 有内网/本地 `./vendor/` 镜像时可完全脱网启动 | +| ADS-B / AIS / TLE / 自然灾害 | OpenSky / adsb.lol / AISStream / CelesTrak / USGS / GDACS / FIRMS | `PLANET_AIRCRAFT_REGISTRY_DIR`(`data/aircraft_registry/`)与 PG 历史快照 | 采集跳过外部请求;`/api/v1/system/datasources/health` 与盲区浮层标注「未知 / 盲区」 | +| 新闻流与直播视频 | RSSHub / Live TV HLS | 后台预置静态历史新闻快照与自定义本地流 | 前端平滑隐藏失效外链播放卡片,不影响 3D 态势操作 | +| AI 推理与外发动作 | 云端 LLM / 外部 Webhook | `aiprovider` 指向内网 vLLM / Ollama;动作 Webhook 白名单指向内网 IM 网关 | SSRF 守卫默认拦截未登记域名并保留审批流完整性 | + +断网启动验证步骤: + +1. 启动参数注入 `PLANET_OFFLINE_MODE=1`; +2. 执行 `uv run --frozen --group dev --project .. pytest tests/test_offline_mode.py -q`(验证零外网启动、`earth_layer_cache` / 新鲜度端点返回 `200`); +3. 打开 `/earth/` 检查控制台零致命异常、底图可交互,且顶部「数据源健康与盲区」诚实标注过期域。 diff --git a/docs/technical/zh/platform-data-flows.md b/docs/technical/zh/platform-data-flows.md index 3ee308e6..1246485f 100644 --- a/docs/technical/zh/platform-data-flows.md +++ b/docs/technical/zh/platform-data-flows.md @@ -50,6 +50,8 @@ flowchart TB | 算力中心 | 展示 TOP500、AI GPU、HuggingFace 等算力节点 | `top500`、`epoch_ai_gpu`、HuggingFace sources | `compute_center_locations` | `computeCenters` | `reload` | | BGP 态势 | 展示观测站、异常事件、路由事件和区域态势 | `ris_live_bgp`、`bgpstream_bgp`、prefix geography sources | `bgp_observations`、`bgp_anomalies`、`bgp_incidents`、`bgp_collector_locations` | `bgp` | `clear_then_reload` | | 船舶 | 展示 AIS 船只、位置、轨迹和源健康 | AIS sources、`barentswatch_vessels` | `vessel_static`、`vessel_position`、`ais_raw_observations`、`ais_source_health` | `vessels` | `clear_then_reload` | +| 航空器 (ADS-B) | 展示全球军机、紧急应答机与民航实时航迹 | `adsb_lol_aircraft` (39)、`opensky_aircraft` (40)、`aircraft_registry` (42) | `aircraft_static`、`aircraft_current_state`、`aircraft_position` (24h 降采样)、`adsb_source_health` | `aircraft` | `reload` | +| GPS/GNSS 干扰 | 展示每日 H3 分辨率 4 卫星导航干扰热区 | `gpsjam_interference` (41) | `gps_jamming_cells` | `gpsJamming` | `reload` | | 可交互对象 | 支撑通用地表图标、人工点位和未来扩展对象 | `earth_interactables` | 无 | `interactables` | `delta` | | 新闻与媒体 | 支撑 Earth 新闻、直播和巡航摘要 | RSS news sources、手动新闻、直播源 | `earth_news_items` | `news` / `media` | `reload` | diff --git a/docs/version-history.md b/docs/version-history.md index 1bc0fffc..0780cf46 100644 --- a/docs/version-history.md +++ b/docs/version-history.md @@ -16,12 +16,13 @@ ## Current Version - `main` 当前主线历史推导到:`0.16.5` -- `dev` 当前开发分支历史推导到:`0.84.2` +- `dev` 当前开发分支历史推导到:`0.85.0` ## Timeline | Version | Type | Branch | Commit | Summary | | --- | --- | --- | --- | --- | +| `0.85.0` | feature | `dev` | `v0.85.0` | 地球全域态势感知 Phase 2–4(航空器/GPS干扰/灾害/海事/本体图谱/电子围栏/H3汇聚与推演/4D回放/调查案例/私有接入/动作审批)、3D↔2D 视图切换与本地 SWR 缓存、桌面端缩放与全平台客户端发布 | | `0.84.2` | improvement | `dev` | `v0.84.2` | 后台数据台账英文和控件改进、Earth 图标对齐与卫星刷新、云图和底图内存优化、OCI 热更新与全平台客户端发布 | | `0.84.1` | bugfix | `dev` | `v0.84.1` | 在 backend/Dockerfile 补齐 OpenCV 运行时共享库(libxcb1/libgl1/libglib2.0-0 等),修复生产容器启动导入 cv2 失败并完成 v0.84 线上发布与 L1 热更上线 | | `0.84.0` | feature | `dev` | `v0.84.0` | 算力台账不可变修订/双时间轴/只读血缘、全球实时云图与风场/高清底图瓦片、高精度中国 POV 边界 PMTiles 与 3D 城市分级标注、图层数据台账与 9 节点位置 DAG 统一、修复线上独立 Admin 默认品牌/云图预览裂图及文档清理 | diff --git a/frontend/bun.lock b/frontend/bun.lock index f1307ab1..0f88e9a3 100644 --- a/frontend/bun.lock +++ b/frontend/bun.lock @@ -24,6 +24,7 @@ "echarts": "^6.0.0", "i18next": "26.3.3", "lucide-react": "^1.16.0", + "maplibre-gl": "^6.21.0", "mermaid": "^11.15.0", "pbf": "^4.0.1", "pmtiles": "^4.4.1", @@ -170,10 +171,24 @@ "@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.31", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="], + "@mapbox/jsonlint-lines-primitives": ["@mapbox/jsonlint-lines-primitives@2.0.3", "", {}, "sha512-0SElaV0uMxEnxzBhhX9WTuPyUeMsAN/SS0i16tjuba4/mio63MG9khjC1a0JAiPGXAwvwm4UfHJURCN7nyudQg=="], + "@mapbox/point-geometry": ["@mapbox/point-geometry@1.1.0", "", {}, "sha512-YGcBz1cg4ATXDCM/71L9xveh4dynfGmcLDqufR+nQQy3fKwsAZsWd/x4621/6uJaeB9mwOHE6hPeDgXz9uViUQ=="], + "@mapbox/tiny-sdf": ["@mapbox/tiny-sdf@2.3.0", "", {}, "sha512-gBvcNDBBB66bgQYvnaJ6Jk+VCaMmVq5+IZR2kWPisT88Z8s0kBQt6hfVi8QgRW8Vpg0UWZzBA4ZSyzHHC+VeRA=="], + + "@mapbox/unitbezier": ["@mapbox/unitbezier@1.0.0", "", {}, "sha512-fqd515fjBmANKGGsQ286E2Wvj/XvDFpGzwJxq4CI6jMQue6Oy04uCKp+JWKF00xRTmk6cEu1jPJ9p3xqH8YWqQ=="], + "@mapbox/vector-tile": ["@mapbox/vector-tile@2.0.4", "", { "dependencies": { "@mapbox/point-geometry": "~1.1.0", "@types/geojson": "^7946.0.16", "pbf": "^4.0.1" } }, "sha512-AkOLcbgGTdXScosBWwmmD7cDlvOjkg/DetGva26pIRiZPdeJYjYKarIlb4uxVzi6bwHO6EWH82eZ5Nuv4T5DUg=="], + "@maplibre/geojson-vt": ["@maplibre/geojson-vt@7.0.1", "", { "dependencies": { "kdbush": "^4.1.0" } }, "sha512-xq3+TiG4hZtx9lHjq/oZginEBtJLJTJqRVmEIhPDSznlkl231z/p4foorEqASpD233EHO9+GVnnu6GNA4Pl+YQ=="], + + "@maplibre/maplibre-gl-style-spec": ["@maplibre/maplibre-gl-style-spec@27.1.0", "", { "dependencies": { "@mapbox/jsonlint-lines-primitives": "^2.0.3", "@mapbox/unitbezier": "^1.0.0", "json-stringify-pretty-compact": "^4.0.0", "minimist": "^1.2.8", "quickselect": "^3.0.0", "tinyqueue": "^3.0.0" }, "bin": { "gl-style-format": "dist/gl-style-format.mjs", "gl-style-migrate": "dist/gl-style-migrate.mjs", "gl-style-validate": "dist/gl-style-validate.mjs" } }, "sha512-8EkIhwOdhjhX6HdugboL0JEGQejqln7Xuve7X2sFFU35IUaCgucHRuuO0+0yWSzYEmEa/z4knkpwOYZdrF/wFA=="], + + "@maplibre/mlt": ["@maplibre/mlt@1.4.0", "", { "dependencies": { "@mapbox/point-geometry": "^1.1.0" } }, "sha512-kDjapA8mGAkSAAZr+ZF875w38PdJg7xS79oEADD7S/QdXELmd4hNHgZR/o5WRkWLBgWjKHJdHj/yRyYmU9Inbg=="], + + "@maplibre/vt-pbf": ["@maplibre/vt-pbf@4.3.3", "", { "dependencies": { "@mapbox/point-geometry": "^1.1.0", "@types/geojson": "^7946.0.16", "pbf": "^5.1.2" } }, "sha512-dEe5XUd64RQbxNxy2OzIkJnwNDWjVmSXjCd0A7zLirm7QJ/WWbmtDFIkfsiM4yt1cplqzG6oSivRYeWx1SM1yg=="], + "@mediapipe/tasks-vision": ["@mediapipe/tasks-vision@0.10.35", "", {}, "sha512-HOvadwVRE6JC+45nyYhmnywnr5h/J8KZvOeUNVOG9q/0875pZgItznFB9bRTvLc264YSJqiZ1NsIpCStJw/egg=="], "@mermaid-js/parser": ["@mermaid-js/parser@1.1.1", "", { "dependencies": { "@chevrotain/types": "~11.1.1" } }, "sha512-VuHdsYMK1bT6X2JbcAaWAhugTRvRBRyuZgd+c22swUeI9g/ntaxF7CY7dYarhZovofCbUNO0G7JesfmNtjYOCw=="], @@ -410,6 +425,8 @@ "baseline-browser-mapping": ["baseline-browser-mapping@2.10.30", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-xjOFN16Ha1+Rz4nFYKqHU/LSB+gx/Vi3yQLX7r7sAW+Wa+8hhF2h4pvqTrTMc8+WcDBEunnUurr46Jvv0jk3Vg=="], + "bidi-js": ["bidi-js@1.1.0", "", { "dependencies": { "require-from-string": "^2.0.2" } }, "sha512-fX1Onk0tdVPC7obPWB5EbJ1z7NVhLq4m2xZLq2YXBkxzMXIGRpNMU88n0EPgWseKl12J7zXs7qrDxPK4sRs2fg=="], + "browserslist": ["browserslist@4.28.2", "", { "dependencies": { "baseline-browser-mapping": "^2.10.12", "caniuse-lite": "^1.0.30001782", "electron-to-chromium": "^1.5.328", "node-releases": "^2.0.36", "update-browserslist-db": "^1.2.3" }, "bin": { "browserslist": "cli.js" } }, "sha512-48xSriZYYg+8qXna9kwqjIVzuQxi+KYWp2+5nCYnYKPTr0LvD89Jqk2Or5ogxz0NUMfIjhh2lIUX/LyX9B4oIg=="], "call-bind-apply-helpers": ["call-bind-apply-helpers@1.0.2", "", { "dependencies": { "es-errors": "^1.3.0", "function-bind": "^1.1.2" } }, "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ=="], @@ -518,6 +535,8 @@ "dunder-proto": ["dunder-proto@1.0.1", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="], + "earcut": ["earcut@3.2.4", "", {}, "sha512-FHc6yNpnTORB0tM5kmZ03iD2mDuNakDE2lvf4Hw1XkfxtEHIGVi01B/GqUSwx+NcC1WGjidAfpTXzeALtPtfpg=="], + "echarts": ["echarts@6.0.0", "", { "dependencies": { "tslib": "2.3.0", "zrender": "6.0.0" } }, "sha512-Tte/grDQRiETQP4xz3iZWSvoHrkCQtwqd6hs+mifXcjrCuo2iKWbajFObuLJVBlDIJlOzgQPd1hsaKt/3+OMkQ=="], "electron-to-chromium": ["electron-to-chromium@1.5.357", "", {}, "sha512-NHlTIQDK8fmVwHwuIzmXYEJ1Ewq3D9wDNc0cWXxDGysP6Pb21giwGNkxiTifyKy/4SoPuN5l6GLP1W9Sv7zB2g=="], @@ -560,6 +579,8 @@ "get-proto": ["get-proto@1.0.1", "", { "dependencies": { "dunder-proto": "^1.0.1", "es-object-atoms": "^1.0.0" } }, "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g=="], + "gl-matrix": ["gl-matrix@3.4.4", "", {}, "sha512-latSnyDNt/8zYUB6VIJ6PCh2jBjJX6gnDsoCZ7LyW7GkqrD51EWwa9qCoGixj8YqBtETQK/xY7OmpTF8xz1DdQ=="], + "gopd": ["gopd@1.2.0", "", {}, "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg=="], "hachure-fill": ["hachure-fill@0.5.2", "", {}, "sha512-3GKBOn+m2LX9iq+JC1064cSFprJY4jL1jCXTcpnfER5HYE2l/4EfWSGzkPa/ZDBmYI0ZOEj5VHV/eKnPGkHuOg=="], @@ -584,10 +605,14 @@ "jsesc": ["jsesc@3.1.0", "", { "bin": "bin/jsesc" }, "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA=="], + "json-stringify-pretty-compact": ["json-stringify-pretty-compact@4.0.0", "", {}, "sha512-3CNZ2DnrpByG9Nqj6Xo8vqbjT4F6N+tb4Gb28ESAZjYZ5yqvmc56J+/kuIwkaAMOyblTQhUW7PxMkUb8Q36N3Q=="], + "json5": ["json5@2.2.3", "", { "bin": "lib/cli.js" }, "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg=="], "katex": ["katex@0.16.47", "", { "dependencies": { "commander": "^8.3.0" }, "bin": { "katex": "cli.js" } }, "sha512-Eeo8Ys1doU1z+x8AZsPpQu+p/QcZBI5PeOo7QGQdy2x2m0MU/hYagBbGOmXwr5KVbEfVuWv9LpnQWeehogurjg=="], + "kdbush": ["kdbush@4.1.0", "", {}, "sha512-e9vurzrXJQrFX6ckpHP3bvj5l+9CnYzkxDNnNQ1h2QTqdWsUAJgXiKdGNcOa1EY85dU8KbQ+z/FdQdB7P+9yfQ=="], + "khroma": ["khroma@2.1.0", "", {}, "sha512-Ls993zuzfayK269Svk9hzpeGUKob/sIgZzyHYdjQoAdQetRKpOLj+k/QQQ/6Qi0Yz65mlROrfd+Ev+1+7dz9Kw=="], "layout-base": ["layout-base@1.0.2", "", {}, "sha512-8h2oVEZNktL4BH2JCOI90iD1yXwL6iNW7KcCKT2QZgQJR2vbqDsldCTPRU9NifTCqHZci57XvQQ15YTu+sTYPg=="], @@ -600,6 +625,8 @@ "lucide-react": ["lucide-react@1.16.0", "", { "peerDependencies": { "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-dYwyPzb4MEKpGUmNYk3WKWPnMrHs3FKM+q94kAnJrcDIqqn1hq2xY8scaS2ovsOCM5D51ey2gaRG3PBb1vgoYQ=="], + "maplibre-gl": ["maplibre-gl@6.21.0", "", { "dependencies": { "@mapbox/point-geometry": "^1.1.0", "@mapbox/tiny-sdf": "^2.3.0", "@mapbox/unitbezier": "^1.0.0", "@mapbox/vector-tile": "^3.0.0", "@maplibre/geojson-vt": "^7.0.1", "@maplibre/maplibre-gl-style-spec": "^27.0.0", "@maplibre/mlt": "^1.4.0", "@maplibre/vt-pbf": "^4.3.3", "@types/geojson": "^7946.0.16", "bidi-js": "^1.1.0", "earcut": "^3.2.4", "gl-matrix": "^3.4.4", "kdbush": "^4.1.0", "murmurhash-js": "^1.0.0", "pbf": "^5.2.1", "potpack": "^2.1.0", "quickselect": "^3.0.0", "tinyqueue": "^3.0.0", "zustand": "^5.1.0" } }, "sha512-mjMFzw99R1kvuWo3xj6XKcFFbVpwTPhO7g2TeyJyT5DdM1E6zKIC/uWG17WpXO6dnRFZ/3un9k44+KtDNjD2Hw=="], + "marked": ["marked@16.4.2", "", { "bin": { "marked": "bin/marked.js" } }, "sha512-TI3V8YYWvkVf3KJe1dRkpnjs68JUPyEa5vjKrp1XEEJUAOaQc+Qj+L1qWbPd0SJuAdQkFU0h73sXXqwDYxsiDA=="], "math-intrinsics": ["math-intrinsics@1.1.0", "", {}, "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g=="], @@ -610,8 +637,12 @@ "mime-types": ["mime-types@2.1.35", "", { "dependencies": { "mime-db": "1.52.0" } }, "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw=="], + "minimist": ["minimist@1.2.8", "", {}, "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA=="], + "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], + "murmurhash-js": ["murmurhash-js@1.0.0", "", {}, "sha512-TvmkNhkv8yct0SVBSy+o8wYzXjE4Zz3PCesbfs8HiCXXdcTuocApFv11UWlNFWKYsP2okqrhb7JNlSm9InBhIw=="], + "nanoid": ["nanoid@3.3.11", "", { "bin": "bin/nanoid.cjs" }, "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w=="], "node-releases": ["node-releases@2.0.44", "", {}, "sha512-5WUyunoPMsvvEhS8AxHtRzP+oA8UCkJ7YRxatWKjngndhDGLiqEVAQKWjFAiAiuL8zMRGzGSJxFnLetoa43qGQ=="], @@ -636,12 +667,16 @@ "postcss-value-parser": ["postcss-value-parser@4.2.0", "", {}, "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ=="], + "potpack": ["potpack@2.1.0", "", {}, "sha512-pcaShQc1Shq0y+E7GqJqvZj8DTthWV1KeHGdi0Z6IAin2Oi3JnLCOfwnCo84qc+HAp52wT9nK9H7FAJp5a44GQ=="], + "prop-types": ["prop-types@15.8.1", "", { "dependencies": { "loose-envify": "^1.4.0", "object-assign": "^4.1.1", "react-is": "^16.13.1" } }, "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg=="], "protocol-buffers-schema": ["protocol-buffers-schema@3.6.1", "", {}, "sha512-VG2K63Igkiv9p76tk1lilczEK1cT+kCjKtkdhw1dQZV3k3IXJbd3o6Ho8b9zJZaHSnT2hKe4I+ObmX9w6m5SmQ=="], "proxy-from-env": ["proxy-from-env@1.1.0", "", {}, "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg=="], + "quickselect": ["quickselect@3.0.0", "", {}, "sha512-XdjUArbK4Bm5fLLvlm5KpTFOiOThgfWWI4axAZDWg4E/0mKdZyI9tNEfds27qCi1ze/vwTR16kvmmGhRra3c2g=="], + "react": ["react@18.3.1", "", { "dependencies": { "loose-envify": "^1.1.0" } }, "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ=="], "react-compiler-runtime": ["react-compiler-runtime@1.0.0", "", { "peerDependencies": { "react": "^17.0.0 || ^18.0.0 || ^19.0.0 || ^0.0.0-experimental" } }, "sha512-rRfjYv66HlG8896yPUDONgKzG5BxZD1nV9U6rkm+7VCuvQc903C4MjcoZR4zPw53IKSOX9wMQVpA1IAbRtzQ7w=="], @@ -670,6 +705,8 @@ "react-style-singleton": ["react-style-singleton@2.2.3", "", { "dependencies": { "get-nonce": "^1.0.0", "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-b6jSvxvVnyptAiLjbkWLE/lOnR4lfTtDAl+eUC7RZy+QQWc6wRzIV2CE6xBuMmDxc2qIihtDCZD5NPOFl7fRBQ=="], + "require-from-string": ["require-from-string@2.0.2", "", {}, "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw=="], + "resolve-protobuf-schema": ["resolve-protobuf-schema@2.1.0", "", { "dependencies": { "protocol-buffers-schema": "^3.3.1" } }, "sha512-kI5ffTiZWmJaS/huM8wZfEMer1eRd7oJQhDuxeCLe3t7N7mX3z94CN0xPxBQxFYQTSNz9T0i+v6inKqSdK8xrQ=="], "robust-predicates": ["robust-predicates@3.0.3", "", {}, "sha512-NS3levdsRIUOmiJ8FZWCP7LG3QpJyrs/TE0Zpf1yvZu8cAJJ6QMW92H1c7kWpdIHo8RvmLxN/o2JXTKHp74lUA=="], @@ -704,6 +741,8 @@ "tinyexec": ["tinyexec@1.2.2", "", {}, "sha512-M/Q0B2cp4K7kynaT/vnED1j8TlLY+Pp7C6Wl2bl/7u/F0mUVwdyOpwomQb8JpYLitHUssAJRmLZdMCGsrx7i+g=="], + "tinyqueue": ["tinyqueue@3.0.0", "", {}, "sha512-gRa9gwYU3ECmQYv3lslts5hxuIa90veaEcxDYuu3QGOIAEM2mOZkVHp48ANJuu1CURtRdHKUBY5Lm1tHV+sD4g=="], + "ts-dedent": ["ts-dedent@2.2.0", "", {}, "sha512-q5W7tVM71e2xjHZTlgfTDoPF/SmqKG5hddq9SzR49CH2hayqRKJtQ4mtRlSxKaJlR/+9rEM+mnBHf7I2/BQcpQ=="], "tslib": ["tslib@2.3.0", "", {}, "sha512-N82ooyxVNm6h1riLCoyS9e3fuJ3AMG2zIZs2Gd1ATcSFjSA23Q0fzjjZeh0jbJvWVDZ0cJT8yaNNaaXHzueNjg=="], @@ -740,6 +779,8 @@ "@babel/helper-compilation-targets/browserslist": ["browserslist@4.28.1", "", { "dependencies": { "baseline-browser-mapping": "^2.9.0", "caniuse-lite": "^1.0.30001759", "electron-to-chromium": "^1.5.263", "node-releases": "^2.0.27", "update-browserslist-db": "^1.2.0" }, "bin": "cli.js" }, "sha512-ZC5Bd0LgJXgwGqUknZY/vkUQ04r8NXnJZ3yYi4vDmSiZmC/pdSN0NbNRPxZpbtO4uAfDUAFffO8IZoM3Gj8IkA=="], + "@maplibre/vt-pbf/pbf": ["pbf@5.2.1", "", { "dependencies": { "protocol-buffers-schema": "^3.6.1" }, "bin": { "pbf": "bin/pbf" } }, "sha512-5s6y6g3akGMF98eemb+3QZAWTCUHyox40TJOwcY4M1w40RvoXrfbRUVmY02RlRiEPyE6KVaM0xxfF4+4vjSJTQ=="], + "@radix-ui/react-collection/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="], "@radix-ui/react-dialog/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="], @@ -762,6 +803,12 @@ "d3-sankey/d3-shape": ["d3-shape@1.3.7", "", { "dependencies": { "d3-path": "1" } }, "sha512-EUkvKjqPFUAZyOlhY5gzCxCeI0Aep04LwIRpsZ/mLFelJiUfnK56jo5JMDSE7yyP2kLSb6LtF+S5chMk7uqPqw=="], + "maplibre-gl/@mapbox/vector-tile": ["@mapbox/vector-tile@3.0.0", "", { "dependencies": { "@mapbox/point-geometry": "~1.1.0", "@types/geojson": "^7946.0.16", "pbf": "^5.0.0" } }, "sha512-Qf10S1uIHMk20ri/IVBnpS+esUEkVaR5Hftmz88jTInrpmWgPGJfPe3LVjjlE77trLx8tH6qjTG7uWH9hIq/0Q=="], + + "maplibre-gl/pbf": ["pbf@5.2.1", "", { "dependencies": { "protocol-buffers-schema": "^3.6.1" }, "bin": { "pbf": "bin/pbf" } }, "sha512-5s6y6g3akGMF98eemb+3QZAWTCUHyox40TJOwcY4M1w40RvoXrfbRUVmY02RlRiEPyE6KVaM0xxfF4+4vjSJTQ=="], + + "maplibre-gl/zustand": ["zustand@5.1.0", "", { "peerDependencies": { "@types/react": ">=18.0.0", "immer": ">=9.0.6", "react": ">=18.0.0", "use-sync-external-store": ">=1.2.0" }, "optionalPeers": ["@types/react", "immer", "react", "use-sync-external-store"] }, "sha512-ciJZlP48M1PTQbVQq81CGVFxHTLpZNrFjKqwjtCU34AWuXTZT/jrF3p9+fI84Cf1eSCMLapxqBy/SNTfwOBuqA=="], + "vite/postcss": ["postcss@8.5.6", "", { "dependencies": { "nanoid": "^3.3.11", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg=="], "@babel/helper-compilation-targets/browserslist/baseline-browser-mapping": ["baseline-browser-mapping@2.9.19", "", { "bin": "dist/cli.js" }, "sha512-ipDqC8FrAl/76p2SSWKSI+H9tFwm7vYqXQrItCuiVPt26Km0jS+NzSsBWAaBusvSbQcfJG+JitdMm+wZAgTYqg=="], diff --git a/frontend/package.json b/frontend/package.json index 9d2658b8..4275d841 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "planet-frontend", - "version": "0.84.2", + "version": "0.85.0", "private": true, "packageManager": "bun@1", "dependencies": { @@ -23,6 +23,7 @@ "echarts": "^6.0.0", "i18next": "26.3.3", "lucide-react": "^1.16.0", + "maplibre-gl": "^6.21.0", "mermaid": "^11.15.0", "pbf": "^4.0.1", "pmtiles": "^4.4.1", diff --git a/frontend/public/earth/css/hud.css b/frontend/public/earth/css/hud.css index 28cd5de8..c7442007 100644 --- a/frontend/public/earth/css/hud.css +++ b/frontend/public/earth/css/hud.css @@ -202,13 +202,26 @@ /* Shared edge-to-edge header, used by layer controls and geographic cards. */ .hud-panel__header--inset, .layer-panel-header { - --hud-header-padding: calc(8px * var(--hud-scale)) calc(10px * var(--hud-scale)); - --hud-header-gap: calc(6px * var(--hud-scale)); + --hud-header-padding: calc(7px * var(--hud-scale)) calc(8px * var(--hud-scale)); + --hud-header-gap: calc(2px * var(--hud-scale)); padding: var(--hud-header-padding); gap: var(--hud-header-gap); margin-bottom: 0; } +.layer-panel-header .layer-panel-title { + white-space: nowrap; + flex-shrink: 0; +} + +.layer-panel-header .layer-panel-btn { + padding: calc(3px * var(--hud-scale)); +} + +.layer-panel-header .layer-panel-btn .material-symbols-rounded { + font-size: calc(14px * var(--hud-scale)); +} + .hud-panel__title, .hud-panel__header .hud-panel-title, .hud-panel-header .hud-panel-title { @@ -5522,3 +5535,625 @@ body:has(.earth-toolbar-cluster.is-expanded) .earth-bottom-dock { height: 16px; line-height: 16px; } + +/* ── Source freshness HUD capsule ─────────────────────────────────────────── */ + +.source-freshness-hud { + position: relative; + width: calc(276px * var(--hud-scale)); + margin-top: calc(6px * var(--hud-scale)); + overflow: visible; + z-index: 25; +} + +.source-freshness-pill { + width: 100%; + display: flex; + align-items: center; + gap: calc(7px * var(--hud-scale)); + padding: calc(7px * var(--hud-scale)) calc(10px * var(--hud-scale)); + border: 0; + background: transparent; + color: var(--hud-text-soft); + font-size: calc(12px * var(--hud-scale)); + line-height: 1.2; + cursor: pointer; + text-align: left; +} + +.source-freshness-pill__dot, +.source-freshness-row__dot { + width: calc(8px * var(--hud-scale)); + height: calc(8px * var(--hud-scale)); + border-radius: 999px; + flex: none; + background: rgba(148, 163, 184, 0.72); +} + +.source-freshness-pill__dot[data-tone="fresh"], +.source-freshness-row__dot[data-tone="fresh"] { + background: #34d399; +} + +.source-freshness-pill__dot[data-tone="warn"], +.source-freshness-row__dot[data-tone="warn"] { + background: #fbbf24; +} + +.source-freshness-pill__dot[data-tone="danger"], +.source-freshness-row__dot[data-tone="danger"] { + background: #f87171; +} + +.source-freshness-pill__summary { + flex: 1 1 auto; + min-width: 0; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + font-weight: 500; +} + +.source-freshness-pill__badge { + flex: none; + padding: calc(2px * var(--hud-scale)) calc(6px * var(--hud-scale)); + border-radius: calc(3px * var(--hud-scale)); + font-size: calc(10px * var(--hud-scale)); + font-weight: 600; + background: rgba(148, 163, 184, 0.16); + color: var(--hud-text-soft); +} + +.source-freshness-pill__badge[data-tone="fresh"] { + background: rgba(16, 185, 129, 0.2); + color: #6ee7b7; +} + +.source-freshness-pill__badge[data-tone="warn"] { + background: rgba(245, 158, 11, 0.22); + color: #fcd34d; +} + +.source-freshness-pill .source-freshness-pill__chevron.material-symbols-rounded { + font-size: calc(16px * var(--hud-scale)); + width: calc(16px * var(--hud-scale)); + height: calc(16px * var(--hud-scale)); + line-height: calc(16px * var(--hud-scale)); + color: var(--hud-text-muted); + transition: transform 0.18s ease; +} + +.source-freshness-hud.is-expanded .source-freshness-pill__chevron { + transform: rotate(180deg); +} + +.source-freshness-popover { + position: absolute; + top: calc(100% + 6px * var(--hud-scale)); + left: 0; + width: min(calc(340px * var(--hud-scale)), calc(100vw - 2 * var(--hud-offset))); + max-height: min(calc(420px * var(--hud-scale)), 62vh); + display: flex; + flex-direction: column; + padding: calc(10px * var(--hud-scale)); + z-index: 64; +} + +.source-freshness-popover[hidden] { + display: none; +} + +.source-freshness-popover__header { + display: flex; + align-items: center; + gap: calc(6px * var(--hud-scale)); + padding-bottom: calc(8px * var(--hud-scale)); + border-bottom: 1px solid var(--hud-line); +} + +.source-freshness-popover__heading { + flex: 1 1 auto; + min-width: 0; + display: flex; + flex-direction: column; + gap: calc(2px * var(--hud-scale)); +} + +.source-freshness-popover__title { + font-size: calc(12px * var(--hud-scale)); + font-weight: 600; + color: var(--hud-text); +} + +.source-freshness-popover__subtitle { + font-size: calc(10.5px * var(--hud-scale)); + color: var(--hud-text-muted); +} + +.source-freshness-popover__btn { + display: inline-flex; + align-items: center; + justify-content: center; + width: calc(26px * var(--hud-scale)); + height: calc(26px * var(--hud-scale)); + padding: 0; + border: 1px solid transparent; + border-radius: calc(4px * var(--hud-scale)); + background: transparent; + color: var(--hud-text-muted); + cursor: pointer; +} + +.source-freshness-popover__btn:hover { + background: rgba(255, 255, 255, 0.08); + color: var(--hud-accent-strong); +} + +.source-freshness-popover__btn .source-freshness-popover__icon.material-symbols-rounded { + font-size: calc(15px * var(--hud-scale)); + width: calc(15px * var(--hud-scale)); + height: calc(15px * var(--hud-scale)); + line-height: calc(15px * var(--hud-scale)); +} + +.source-freshness-list { + margin-top: calc(8px * var(--hud-scale)); + overflow-y: auto; + display: flex; + flex-direction: column; + gap: calc(6px * var(--hud-scale)); + padding-right: calc(2px * var(--hud-scale)); +} + +.source-freshness-row { + padding: calc(7px * var(--hud-scale)) calc(8px * var(--hud-scale)); + border: 1px solid rgba(148, 163, 184, 0.16); + background: rgba(15, 23, 42, 0.26); + display: flex; + flex-direction: column; + gap: calc(3px * var(--hud-scale)); +} + +.source-freshness-row__top { + display: flex; + align-items: center; + gap: calc(6px * var(--hud-scale)); +} + +.source-freshness-row__name { + flex: 1 1 auto; + font-size: calc(11.5px * var(--hud-scale)); + color: var(--hud-text); + font-weight: 600; +} + +.source-freshness-row__tag { + font-size: calc(10px * var(--hud-scale)); + padding: calc(1px * var(--hud-scale)) calc(6px * var(--hud-scale)); + border-radius: calc(3px * var(--hud-scale)); + background: rgba(148, 163, 184, 0.18); + color: var(--hud-text-soft); +} + +.source-freshness-row__tag[data-tone="fresh"] { + background: rgba(16, 185, 129, 0.22); + color: #6ee7b7; +} + +.source-freshness-row__tag[data-tone="warn"] { + background: rgba(245, 158, 11, 0.22); + color: #fcd34d; +} + +.source-freshness-row__tag[data-tone="danger"] { + background: rgba(239, 68, 68, 0.24); + color: #fca5a5; +} + +.source-freshness-row__meta { + display: flex; + align-items: center; + justify-content: space-between; + gap: calc(8px * var(--hud-scale)); + font-size: calc(10.5px * var(--hud-scale)); + color: var(--hud-text-muted); +} + +.source-freshness-row__reason { + flex: 1 1 auto; + min-width: 0; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.source-freshness-row__time { + flex: none; + font-variant-numeric: tabular-nums; +} + +.layout-mode-mobile .source-freshness-hud { + width: min(calc(248px * var(--hud-scale)), calc(100vw - 2 * var(--hud-offset))); +} + +/* §3.6 Universal Spatial Workflow Cards (reuses .hud-panel liquid-glass + interior translucency <= 0.35) */ +#workflow-spatial-workspace { + position: fixed; + inset: 0; + pointer-events: none; + z-index: var(--hud-z-overlay, 38); +} + +.workflow-spatial-card { + position: fixed; + width: min(calc(340px * var(--hud-scale)), calc(100vw - 2 * var(--hud-offset))); + max-height: min(62vh, 520px); + display: flex; + flex-direction: column; + pointer-events: auto; +} + +.workflow-spatial-card__anchor { + margin-left: auto; + font-size: calc(10.5px * var(--hud-scale)); + color: var(--hud-text-muted); + white-space: nowrap; +} + +.workflow-spatial-card__body { + display: flex; + flex-direction: column; + gap: calc(8px * var(--hud-scale)); + min-height: 0; + overflow-y: auto; + padding: calc(10px * var(--hud-scale)) calc(12px * var(--hud-scale)); +} + +.wb-spatial-card__summary { + margin: 0; + font-size: calc(11.5px * var(--hud-scale)); + line-height: 1.45; + color: var(--hud-text-secondary); +} + +.wb-spatial-card__blocks { + display: flex; + flex-direction: column; + gap: calc(8px * var(--hud-scale)); +} + +.wb-spatial-duel, +.wb-spatial-stacked, +.wb-spatial-corridor, +.wb-spatial-samples { + border-radius: calc(10px * var(--hud-scale)); + padding: calc(8px * var(--hud-scale)) calc(10px * var(--hud-scale)); + background: rgba(15, 23, 42, 0.28); + border: 1px solid rgba(148, 163, 184, 0.16); +} + +.wb-spatial-corridor__head, +.wb-spatial-samples__head { + display: flex; + align-items: center; + justify-content: space-between; + font-size: calc(11px * var(--hud-scale)); + font-weight: 600; + color: var(--hud-text-primary); + margin-bottom: calc(6px * var(--hud-scale)); +} + +.wb-spatial-corridor__pts, +.wb-spatial-corridor__milestones { + display: flex; + flex-wrap: wrap; + gap: calc(4px * var(--hud-scale)); +} + +.wb-spatial-corridor__milestones { + margin-top: calc(5px * var(--hud-scale)); +} + +.wb-corridor-pt, +.wb-milestone-pill { + display: inline-flex; + align-items: center; + gap: calc(4px * var(--hud-scale)); + padding: calc(2px * var(--hud-scale)) calc(6px * var(--hud-scale)); + border-radius: calc(6px * var(--hud-scale)); + background: rgba(30, 41, 59, 0.32); + font-size: calc(10.5px * var(--hud-scale)); + color: var(--hud-text-secondary); + font-variant-numeric: tabular-nums; +} + +.wb-sample-chip { + font-size: calc(10.5px * var(--hud-scale)); +} + +/* §3.8 Incidents Triage & Geofence Editor HUD (translucent interior alpha <= 0.35) */ +.incidents-hud-panel { + position: fixed; + top: calc(var(--hud-offset) + 48px * var(--hud-scale)); + right: var(--hud-offset); + width: min(calc(376px * var(--hud-scale)), calc(100vw - 2 * var(--hud-offset))); + max-height: min(74vh, 640px); + display: flex; + flex-direction: column; + z-index: var(--hud-z-panel, 42); +} + +.incidents-hud__toolbar { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: calc(6px * var(--hud-scale)); + padding: calc(8px * var(--hud-scale)) calc(12px * var(--hud-scale)); + border-bottom: 1px solid rgba(148, 163, 184, 0.16); +} + +.incidents-hud__draw-bar { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: calc(6px * var(--hud-scale)); + width: 100%; +} + +.incidents-hud__input { + flex: 1 1 130px; + min-width: 0; + height: calc(28px * var(--hud-scale)); + padding: 0 calc(8px * var(--hud-scale)); + border-radius: calc(6px * var(--hud-scale)); + border: 1px solid rgba(148, 163, 184, 0.28); + background: rgba(15, 23, 42, 0.32); + color: var(--hud-text-primary); + font-size: calc(11.5px * var(--hud-scale)); +} + +.incidents-hud__draw-note { + font-size: calc(10.5px * var(--hud-scale)); + color: var(--hud-text-muted); +} + +.incidents-hud__list { + flex: 1 1 auto; + min-height: 0; + overflow-y: auto; + display: flex; + flex-direction: column; + gap: calc(8px * var(--hud-scale)); + padding: calc(10px * var(--hud-scale)) calc(12px * var(--hud-scale)); +} + +.incidents-hud__card { + display: flex; + flex-direction: column; + gap: calc(6px * var(--hud-scale)); + padding: calc(9px * var(--hud-scale)) calc(10px * var(--hud-scale)); + border-radius: calc(10px * var(--hud-scale)); + background: rgba(15, 23, 42, 0.30); + border: 1px solid rgba(148, 163, 184, 0.16); +} + +.incidents-hud__card-top { + display: flex; + align-items: center; + justify-content: space-between; + gap: calc(6px * var(--hud-scale)); +} + +.incidents-hud__badge { + display: inline-flex; + align-items: center; + padding: calc(2px * var(--hud-scale)) calc(6px * var(--hud-scale)); + border-radius: calc(5px * var(--hud-scale)); + font-size: calc(10px * var(--hud-scale)); + font-weight: 600; +} + +.incidents-hud__badge.is-rule { + background: rgba(239, 68, 68, 0.24); + color: #fca5a5; +} + +.incidents-hud__badge.is-candidate { + background: rgba(245, 158, 11, 0.24); + color: #fcd34d; +} + +.incidents-hud__badge.is-impact { + background: rgba(56, 189, 248, 0.24); + color: #7dd3fc; +} + +.incidents-hud__status { + font-size: calc(10.5px * var(--hud-scale)); + color: var(--hud-text-muted); +} + +.incidents-hud__card-title { + margin: 0; + font-size: calc(12px * var(--hud-scale)); + line-height: 1.4; + color: var(--hud-text-primary); +} + +.incidents-hud__chips, +.incidents-hud__actions, +.incidents-hud__dismiss-box { + display: flex; + flex-wrap: wrap; + gap: calc(5px * var(--hud-scale)); +} + +.incidents-hud__note, +.incidents-hud__empty { + margin: 0; + font-size: calc(11px * var(--hud-scale)); + color: var(--hud-text-secondary); +} + +.replay-timeline-panel { + position: fixed; + left: 50%; + bottom: calc(var(--hud-offset) + 52px); + transform: translateX(-50%); + width: min(640px, calc(100vw - 2 * var(--hud-offset))); + max-height: min(260px, 38vh); + display: flex; + flex-direction: column; + z-index: 44; +} + +.replay-timeline__body { + display: flex; + flex-direction: column; + gap: calc(8px * var(--hud-scale)); + padding: calc(10px * var(--hud-scale)) calc(12px * var(--hud-scale)); +} + +.replay-timeline__controls { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: calc(6px * var(--hud-scale)); +} + +.replay-scrubber { + flex: 1 1 160px; + min-width: 120px; +} + +.replay-speed-select { + width: auto; + min-width: 64px; +} + +.replay-cursor-time { + font-size: calc(11px * var(--hud-scale)); + font-variant-numeric: tabular-nums; + color: var(--hud-text-primary); +} + +.replay-retention-badges { + display: flex; + flex-wrap: wrap; + gap: calc(5px * var(--hud-scale)); +} + +.cases-hud-panel, +.actions-hud-panel, +.ontology-hud-panel { + position: fixed; + right: var(--hud-offset); + top: calc(var(--hud-offset) + 250px); + width: min(370px, calc(100vw - 2 * var(--hud-offset))); + max-height: min(460px, 60vh); + display: flex; + flex-direction: column; + z-index: 43; +} + +.cases-hud__body, +.ontology-hud__body { + flex: 1 1 auto; + min-height: 0; + overflow-y: auto; + display: flex; + flex-direction: column; + gap: calc(8px * var(--hud-scale)); + padding: calc(10px * var(--hud-scale)) calc(12px * var(--hud-scale)); +} + +.cases-hud__detail { + padding: calc(9px * var(--hud-scale)) calc(10px * var(--hud-scale)); + border-radius: calc(10px * var(--hud-scale)); + background: rgba(15, 23, 42, 0.30); + border: 1px solid rgba(56, 189, 248, 0.28); + display: flex; + flex-direction: column; + gap: calc(6px * var(--hud-scale)); +} + +.cases-hud__items { + display: flex; + flex-direction: column; + gap: calc(6px * var(--hud-scale)); +} + +.ontology-graph-widget__legend { + display: flex; + flex-wrap: wrap; + gap: calc(10px * var(--hud-scale)); + font-size: calc(10.5px * var(--hud-scale)); + color: var(--hud-text-secondary); +} + +.ontology-graph-widget__canvas { + width: 100%; + height: auto; + border-radius: calc(8px * var(--hud-scale)); + background: rgba(15, 23, 42, 0.28); + border: 1px solid rgba(148, 163, 184, 0.16); +} + +.ontology-graph-widget__timeline { + display: flex; + flex-direction: column; + gap: calc(4px * var(--hud-scale)); + margin-top: calc(6px * var(--hud-scale)); +} + +.ontology-timeline-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: calc(8px * var(--hud-scale)); + padding: calc(5px * var(--hud-scale)) calc(8px * var(--hud-scale)); + border-radius: calc(6px * var(--hud-scale)); + border: 1px solid rgba(148, 163, 184, 0.18); + background: rgba(15, 23, 42, 0.28); + color: var(--hud-text-primary); + font-size: calc(10.5px * var(--hud-scale)); + cursor: pointer; +} + +.og-line { + display: inline-block; + width: 14px; + height: 2px; + margin-right: 4px; + vertical-align: middle; +} + +.og-line--topo { + background: #94a3b8; +} + +.og-line--spatial { + border-top: 2px dashed #38bdf8; +} + +.og-line--analyst { + background: #fbbf24; +} + +@media print { + body > :not(#cases-board-hud) { + display: none; + } + #cases-board-hud { + position: static; + width: 100%; + max-height: none; + background: #ffffff; + color: #0f172a; + border: none; + } + .hud-panel__actions, + #cases-create-bar { + display: none; + } +} diff --git a/frontend/public/earth/css/news-panel.css b/frontend/public/earth/css/news-panel.css index d9bb7d5c..9f673fc5 100644 --- a/frontend/public/earth/css/news-panel.css +++ b/frontend/public/earth/css/news-panel.css @@ -842,3 +842,42 @@ .layout-mode-mobile .earth-news-hud { display: none !important; } + +.news-credibility-badge { + display: inline-flex; + align-items: center; + margin-left: 5px; + padding: 1px 5px; + border-radius: 3px; + font-size: 10px; + font-weight: 600; + line-height: 1.25; + vertical-align: middle; + background: rgba(148, 163, 184, 0.18); + color: rgba(226, 232, 240, 0.85); +} + +.news-credibility-badge--t1 { + background: rgba(16, 185, 129, 0.24); + color: #6ee7b7; +} + +.news-credibility-badge--t2 { + background: rgba(56, 189, 248, 0.22); + color: #7dd3fc; +} + +.news-credibility-badge--t3 { + background: rgba(245, 158, 11, 0.22); + color: #fcd34d; +} + +.news-credibility-badge--t4 { + background: rgba(248, 113, 113, 0.24); + color: #fca5a5; +} + +.news-credibility-badge--state { + background: rgba(251, 146, 60, 0.24); + color: #fdba74; +} diff --git a/frontend/public/earth/css/toolbar.css b/frontend/public/earth/css/toolbar.css index 6696dd4e..b3de4d7a 100644 --- a/frontend/public/earth/css/toolbar.css +++ b/frontend/public/earth/css/toolbar.css @@ -298,12 +298,119 @@ .earth-rotate-toggle .icon-play, .earth-rotate-toggle.is-stopped .icon-pause, .earth-layout-toggle .layout-collapse, -.earth-layout-toggle.active .layout-expand { +.earth-layout-toggle.active .layout-expand, +.earth-view-mode-toggle .view-icon-3d, +.earth-view-mode-toggle.is-2d .view-icon-2d { display: none; } .earth-rotate-toggle.is-stopped .icon-play, -.earth-layout-toggle.active .layout-collapse { +.earth-layout-toggle.active .layout-collapse, +.earth-view-mode-toggle.is-2d .view-icon-3d { + display: inline-flex; +} + +.earth-map-2d { + position: absolute; + inset: 0; + width: 100%; + height: 100%; + z-index: 1; + background: #030916; +} + +.earth-map-2d[hidden] { + display: none; +} + +.earth-app.is-2d-mode > .geo-labels, +.earth-app.is-2d-mode .map-clusters, +.earth-app.is-2d-mode .satellite-labels, +.earth-app.is-2d-mode .callout-connector { + display: none; +} + +.earth-map-2d .maplibregl-canvas { + outline: none; +} + +.earth-map-2d-zoom-pill { + position: absolute; + left: 50%; + bottom: calc(100% + 12px * var(--toolbar-scale)); + transform: translateX(-50%); + display: inline-flex; + align-items: center; + gap: 8px; + padding: 6px 8px 6px 14px; + border-radius: 999px; + font-size: calc(12px * var(--hud-scale)); + line-height: 1.25; + color: #e0f2fe; + white-space: nowrap; + pointer-events: auto; + z-index: 230; +} + +.earth-map-2d-zoom-pill[hidden] { + display: none; +} + +.earth-map-2d-zoom-pill__action, +.earth-map-2d-zoom-pill__close { + border: none; + background: transparent; + color: inherit; + font: inherit; + cursor: pointer; + padding: 0; + display: inline-flex; + align-items: center; + justify-content: center; +} + +.earth-map-2d-zoom-pill__action:hover, +.earth-map-2d-zoom-pill__action:focus-visible { + color: #38bdf8; +} + +.earth-map-2d-zoom-pill__close { + width: 22px; + height: 22px; + border-radius: 50%; + color: rgba(203, 213, 225, 0.78); +} + +.earth-map-2d-zoom-pill__close .material-symbols-rounded { + font-size: 16px; +} + +.earth-map-2d-zoom-pill__close:hover, +.earth-map-2d-zoom-pill__close:focus-visible { + background: rgba(255, 255, 255, 0.12); + color: #f8fafc; +} + +.earth-mobile-view-toggle { + display: none; + position: fixed; + top: var(--hud-offset); + right: var(--hud-offset); + width: 40px; + height: 40px; + border-radius: 50%; + align-items: center; + justify-content: center; + color: var(--hud-title); + cursor: pointer; + z-index: 22; +} + +.earth-mobile-view-toggle .material-symbols-rounded { + font-size: 20px; +} + +.layout-mode-mobile .earth-mobile-view-toggle { display: inline-flex; } diff --git a/frontend/public/earth/index.html b/frontend/public/earth/index.html index 3da95224..fbba310d 100644 --- a/frontend/public/earth/index.html +++ b/frontend/public/earth/index.html @@ -16,7 +16,8 @@ "simplex-noise": "https://esm.sh/simplex-noise@4.0.1", "satellite.js": "https://esm.sh/satellite.js@5.0.0", "hls.js": "https://esm.sh/hls.js@1.6.15", - "astronomy-engine": "https://esm.sh/astronomy-engine@2.1.19" + "astronomy-engine": "https://esm.sh/astronomy-engine@2.1.19", + "maplibre-gl": "./vendor/maplibre-gl.mjs" } } @@ -126,16 +127,71 @@
+ +
+
+ + +
+
layers 图层 + + + + + @@ -210,6 +266,56 @@
+
+ flight +
+ 航空器 + 全球军机与民航 ADS-B +
+ +
+
+ radar +
+ GPS 干扰 + GNSS 信号干扰热区 +
+ +
+
+ warning +
+ 自然灾害 + 地震、林火热点与灾难预警 +
+ +
+
+ pentagon +
+ 电子围栏 + 海缆走廊与咽喉监测区 +
+ +
+
+ share +
+ 关联与影响链 + H3 待核查关联与海缆影响链 +
+ +
hub
@@ -313,6 +419,12 @@
+
+
+
+ 本地资源缓存 + 当前占用:计算中… +
+ +
打开控制台 @@ -2227,6 +2360,17 @@
+
+
+ 本地资源缓存 + 当前占用:计算中… +
+ +
{ + applyAboutConfig(normalizeAbout(fresh?.about)); + }, + }); + applyAboutConfig(normalizeAbout(data?.about)); } catch (error) { console.warn("Earth about config unavailable, using defaults.", error); } diff --git a/frontend/public/earth/js/actions-hud.js b/frontend/public/earth/js/actions-hud.js new file mode 100644 index 00000000..a37c2c5b --- /dev/null +++ b/frontend/public/earth/js/actions-hud.js @@ -0,0 +1,212 @@ +/** + * §4.5 Action Approval Matrix & Webhook Notification Drawer + * Submits governed actions, approves/rejects pending approvals with mandatory reasons, + * and exposes object-level action history lookup. + */ + +import { getEarthLocale } from "./i18n.js"; +import { createHUDPanel } from "./hud-panels.js"; +import { sharedHudFocusStack } from "./hud-focus-stack.js"; +import { fetchAdminWriteJson, readStoredAdminAuthState } from "./admin-write-auth.js"; +import { isEditableRole } from "./geofence-editor.js"; + +const t = (zh, en) => (getEarthLocale() === "en-US" ? en : zh); + +function escapeHtml(text) { + return String(text ?? "") + .replaceAll("&", "&") + .replaceAll("<", "<") + .replaceAll(">", ">") + .replaceAll('"', """); +} + +async function fetchEarthJson(url) { + const { token } = readStoredAdminAuthState(); + const headers = token ? { Authorization: `Bearer ${token}` } : {}; + const resp = await fetch(url, { credentials: "same-origin", headers }); + if (!resp.ok) throw new Error(`HTTP ${resp.status}`); + return resp.json(); +} + +export function initActionsHud({ + rootParent = typeof document !== "undefined" ? document.body : null, + onStatus = null, +} = {}) { + const panelEl = document.createElement("aside"); + panelEl.id = "actions-center-hud"; + panelEl.className = "hud-panel actions-hud-panel hud-panel-draggable"; + panelEl.hidden = true; + panelEl.setAttribute("role", "dialog"); + panelEl.setAttribute("aria-modal", "false"); + panelEl.setAttribute("aria-label", t("动作审批中心", "Action Approvals")); + + panelEl.innerHTML = ` +
+
+ +

${escapeHtml(t("动作审批中心", "Action Approvals"))}

+
+
+ + +
+
+
+ + + + +
+
+ `; + + rootParent?.append?.(panelEl); + const hudPanel = createHUDPanel({ + panel: panelEl, + header: ".hud-panel__header", + body: "#actions-hud-list", + }); + sharedHudFocusStack.register(panelEl, { focus: false }); + + const listEl = panelEl.querySelector("#actions-hud-list"); + const submitBar = panelEl.querySelector("#actions-submit-bar"); + const typeSelect = panelEl.querySelector("#action-type-select"); + const targetInput = panelEl.querySelector("#action-target-input"); + const noteInput = panelEl.querySelector("#action-reason-input"); + const submitBtn = panelEl.querySelector("#action-submit-btn"); + + let items = []; + + const render = () => { + const editable = isEditableRole(readStoredAdminAuthState()?.user?.role); + if (submitBar) submitBar.hidden = !editable; + if (!listEl) return; + if (!items.length) { + listEl.innerHTML = `

${escapeHtml(t("暂无动作审批记录", "No action requests"))}

`; + return; + } + listEl.innerHTML = items + .map( + (req) => ` +
+
+ ${escapeHtml(req.action_type)} · ${escapeHtml(req.status)} + ${escapeHtml(req.requested_by || "system")} +
+

${escapeHtml((req.target_object_ids || []).join(", ") || "—")}

+ ${req.decision_reason ? `

${escapeHtml(req.decision_reason)}

` : ""} + ${ + editable && req.status === "pending" + ? `
+ + + +
` + : "" + } +
`, + ) + .join(""); + }; + + const refresh = async (objectId = "") => { + const url = objectId ? `/api/v1/actions?object_id=${encodeURIComponent(objectId)}` : "/api/v1/actions?limit=100"; + const data = await fetchEarthJson(url); + items = Array.isArray(data?.items) ? data.items : []; + render(); + return items; + }; + + const submitAction = async ({ actionType, targetObjectIds = [], params = {}, aiSuggested = false }) => { + const resp = await fetchAdminWriteJson("/api/v1/actions", { + action_type: actionType, + target_object_ids: targetObjectIds, + params, + ai_suggested: aiSuggested, + }); + if (!resp.ok) throw new Error(await resp.text()); + const created = await resp.json(); + await refresh().catch(() => {}); + return created; + }; + + panelEl.querySelector("#actions-close-btn")?.addEventListener("click", () => { + panelEl.hidden = true; + }); + panelEl.querySelector("#actions-refresh-btn")?.addEventListener("click", () => { + void refresh().catch((e) => onStatus?.(e?.message || String(e), "error")); + }); + + submitBtn?.addEventListener("click", async () => { + const actionType = String(typeSelect?.value || "add_to_watchlist"); + const oid = String(targetInput?.value || "").trim(); + const note = String(noteInput?.value || "").trim(); + if (!oid) { + onStatus?.(t("请输入目标对象 ID", "Target object ID required"), "error"); + return; + } + try { + const created = await submitAction({ + actionType, + targetObjectIds: [oid], + params: { summary: note || oid, title: oid }, + }); + if (noteInput) noteInput.value = ""; + onStatus?.(t(`动作已提交 (${created.status})`, `Action submitted (${created.status})`), "success"); + } catch (err) { + onStatus?.(err?.message || String(err), "error"); + } + }); + + listEl?.addEventListener("click", async (event) => { + const btn = event?.target instanceof HTMLElement ? event.target.closest("[data-action-decide]") : null; + if (!(btn instanceof HTMLElement)) return; + const actionId = Number(btn.dataset.actionId); + const decide = btn.dataset.actionDecide; + const reasonEl = panelEl.querySelector(`[data-action-decision-reason="${actionId}"]`); + const reason = String(reasonEl?.value || "").trim(); + if (!reason) { + onStatus?.(t("请填写审批或驳回理由", "Decision reason is required"), "error"); + return; + } + try { + const resp = await fetchAdminWriteJson(`/api/v1/actions/${actionId}/${decide}`, { + decision_reason: reason, + }); + if (!resp.ok) throw new Error(await resp.text()); + await refresh(); + onStatus?.(t("审批处理完成", "Action decision recorded"), "success"); + } catch (err) { + onStatus?.(err?.message || String(err), "error"); + } + }); + + const open = async (objectId = "") => { + panelEl.hidden = false; + sharedHudFocusStack.focus(panelEl); + if (objectId && targetInput) targetInput.value = objectId; + await refresh(objectId).catch((e) => onStatus?.(e?.message || String(e), "error")); + }; + + return { + open, + close: () => { + panelEl.hidden = true; + }, + refresh, + submitAction, + getItems: () => items, + destroy: () => { + hudPanel?.destroy?.(); + panelEl.remove(); + }, + }; +} diff --git a/frontend/public/earth/js/aircraft-gps-jamming.test.js b/frontend/public/earth/js/aircraft-gps-jamming.test.js new file mode 100644 index 00000000..9c935626 --- /dev/null +++ b/frontend/public/earth/js/aircraft-gps-jamming.test.js @@ -0,0 +1,134 @@ +import { expect, test } from "bun:test"; +import { + AIRCRAFT_CATEGORY_ORDER, + EARTH_REAL_RADIUS_M, + computeHeadingBin, + extrapolateGreatCircleXYZ, + gridBucketKey, + latLonRadiusToXYZ, + lookupGridBucketCandidates, + unpackColumnarAircraftSnapshot, +} from "./aircraft-math.js"; +import { + GPS_JAMMING_COLORS, + buildGpsJammingGeometryBuffers, +} from "./gps-jamming-math.js"; + +test("aircraft Worker math unpacks columnar rows, computes 32 heading bins, and prioritizes military/emergency on cap", () => { + const payload = { + fields: [ + "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", + ], + rows: [ + ["a00001", "UAL101", 37.6, -122.3, 10000, 240, 90, 0, "commercial", false, false, null, false, "opensky_aircraft", "2026-12-06T10:00:00Z"], + ["ae1234", "RCH401", 35.1, 139.4, 9000, 230, 180, 0, "military", true, false, null, false, "adsb_lol_aircraft", "2026-12-06T10:00:00Z"], + ["4ca777", "RYR777", 51.4, -0.4, 4000, 180, 270, -2, "emergency", false, true, "7700", false, "adsb_lol_aircraft", "2026-12-06T10:00:00Z"], + ], + }; + + expect(computeHeadingBin(0)).toBe(0); + expect(computeHeadingBin(90)).toBe(8); + expect(computeHeadingBin(180)).toBe(16); + expect(computeHeadingBin(270)).toBe(24); + expect(computeHeadingBin(359.9)).toBe(0); + + // When capped at 2 items, military and emergency must survive while commercial is shed first + const capped = unpackColumnarAircraftSnapshot(payload, { earthRadius: 100, maxRenderCount: 2 }); + expect(capped.count).toBe(2); + expect(capped.records.map((r) => r.icao24).sort()).toEqual(["4ca777", "ae1234"]); + expect(capped.atlasSlots[0]).toBe(24); // RYR777 270 deg + expect(capped.atlasSlots[1]).toBe(AIRCRAFT_CATEGORY_ORDER.indexOf("emergency")); + expect(capped.atlasSlots[2]).toBe(16); // RCH401 180 deg + expect(capped.atlasSlots[3]).toBe(AIRCRAFT_CATEGORY_ORDER.indexOf("military")); +}); + +test("aircraft great-circle shader extrapolation matches spherical CPU reference within float precision", () => { + const lat = 0.0; + const lon = 0.0; + const radius = 101.2; + const speedMs = 250.0; + const elapsedSec = 60.0; + + const unpacked = unpackColumnarAircraftSnapshot({ + fields: ["icao24", "lat", "lon", "altitude_m", "ground_speed_ms", "track_deg", "category", "is_military", "is_emergency", "on_ground"], + rows: [["a11111", lat, lon, 7500, speedMs, 90.0, "commercial", false, false, false]], + }); + + const pos0 = [unpacked.positions[0], unpacked.positions[1], unpacked.positions[2]]; + const vel0 = [unpacked.velocities[0], unpacked.velocities[1], unpacked.velocities[2]]; + const r0 = unpacked.radii[0]; + const extrapolated = extrapolateGreatCircleXYZ(pos0, vel0, elapsedSec, r0); + + // Heading 90 deg (due East) along equator changes longitude by + (speed * dt / EARTH_REAL_RADIUS_M) rad + const deltaLonDeg = ((speedMs * elapsedSec) / EARTH_REAL_RADIUS_M) * (180 / Math.PI); + const expected = latLonRadiusToXYZ(lat, deltaLonDeg, r0); + + expect(Math.hypot(extrapolated[0] - expected[0], extrapolated[1] - expected[1], extrapolated[2] - expected[2])).toBeLessThan(1e-4); + expect(Math.hypot(extrapolated[0], extrapolated[1], extrapolated[2])).toBeCloseTo(r0, 4); + expect(radius).toBeGreaterThan(100); +}); + +test("5x5 grid bucket spatial index finds nearby candidates including across antimeridian", () => { + const unpacked = unpackColumnarAircraftSnapshot({ + fields: ["icao24", "lat", "lon", "altitude_m", "ground_speed_ms", "track_deg", "category", "is_military", "is_emergency", "on_ground"], + rows: [ + ["a00001", 10.0, 179.5, 5000, 200, 90, "commercial", false, false, false], + ["a00002", -45.0, -70.0, 5000, 200, 180, "commercial", false, false, false], + ], + }); + + expect(gridBucketKey(10.0, 179.5)).toBe("20:71"); + const candidates = lookupGridBucketCandidates(10.2, -179.8, unpacked.gridBuckets); + expect(candidates).toEqual([0]); +}); + +test("GPS jamming H3 triangulation emits expected vertices and level RGBA mapping", () => { + const hexA = { + h3_index: "841fb49ffffffff", + observed_date: "2026-12-05", + lat: 35.0, + lon: 33.0, + level: "high", + bad_ratio: 0.25, + aircraft_count: 80, + boundary: [ + [35.2, 32.8], + [35.3, 33.0], + [35.2, 33.2], + [34.8, 33.2], + [34.7, 33.0], + [34.8, 32.8], + ], + }; + const hexB = { + ...hexA, + h3_index: "841fb4bffffffff", + level: "medium", + bad_ratio: 0.05, + }; + + const result = buildGpsJammingGeometryBuffers([hexA, hexB], { earthRadius: 100 }); + // Two 6-sided hexagons -> 2 * 6 triangles = 12 triangles = 36 vertices + expect(result.vertexCount).toBe(36); + expect(result.positions.length).toBe(36 * 3); + expect(result.colors.length).toBe(36 * 4); + expect(result.colors[0]).toBeCloseTo(GPS_JAMMING_COLORS.high[0], 4); + expect(result.colors[3]).toBeCloseTo(GPS_JAMMING_COLORS.high[3], 4); + const bOffset = 18 * 4; + expect(result.colors[bOffset]).toBeCloseTo(GPS_JAMMING_COLORS.medium[0], 4); + expect(result.colors[bOffset + 3]).toBeCloseTo(GPS_JAMMING_COLORS.medium[3], 4); +}); diff --git a/frontend/public/earth/js/aircraft-math.js b/frontend/public/earth/js/aircraft-math.js new file mode 100644 index 00000000..449f70e8 --- /dev/null +++ b/frontend/public/earth/js/aircraft-math.js @@ -0,0 +1,259 @@ +// aircraft-math.js - Shared pure math, unpacking, great-circle extrapolation, and 5x5 grid index for aircraft ADS-B + +export const EARTH_REAL_RADIUS_M = 6_371_000.0; +export const AIRCRAFT_HEADING_BINS = 32; + +export const AIRCRAFT_CATEGORY_ORDER = Object.freeze([ + "commercial", + "cargo", + "military", + "emergency", + "general", + "helicopter", + "other", +]); + +export const AIRCRAFT_CATEGORY_LABELS = Object.freeze({ + commercial: "民航", + cargo: "货机", + military: "军机", + emergency: "紧急应答", + general: "通航", + helicopter: "直升机", + other: "其他", +}); + +export const AIRCRAFT_COLORS = Object.freeze({ + commercial: "#38bdf8", + cargo: "#fb923c", + military: "#f43f5e", + emergency: "#ef4444", + general: "#a3e635", + helicopter: "#2dd4bf", + other: "#94a3b8", +}); + +const CATEGORY_INDEX_MAP = new Map( + AIRCRAFT_CATEGORY_ORDER.map((cat, index) => [cat, index]), +); + +export function getAircraftCategoryIndex(category) { + return CATEGORY_INDEX_MAP.get(String(category || "other").toLowerCase()) ?? 6; +} + +export function computeHeadingBin(trackDeg) { + if (!Number.isFinite(Number(trackDeg))) return 0; + const wrapped = ((Number(trackDeg) % 360) + 360) % 360; + return Math.round((wrapped / 360) * AIRCRAFT_HEADING_BINS) % AIRCRAFT_HEADING_BINS; +} + +export function computeAircraftRadius(altitudeM, earthRadius = 100) { + const alt = Number.isFinite(Number(altitudeM)) ? Math.max(0, Math.min(Number(altitudeM), 15000)) : 3000; + const normalized = alt / 15000; + return earthRadius + 0.75 + normalized * 1.1; +} + +export function latLonRadiusToXYZ(lat, lon, radius = 100) { + const phi = (90 - lat) * (Math.PI / 180); + const theta = (lon + 180) * (Math.PI / 180); + const sinPhi = Math.sin(phi); + return [ + -(radius * sinPhi * Math.cos(theta)), + radius * Math.cos(phi), + radius * sinPhi * Math.sin(theta), + ]; +} + +export function computeTangentAngularVelocity(lat, lon, groundSpeedMs, trackDeg) { + const speed = Number(groundSpeedMs); + if (!Number.isFinite(speed) || speed <= 0.1) return [0, 0, 0]; + const phi = (90 - lat) * (Math.PI / 180); + const theta = (lon + 180) * (Math.PI / 180); + const trackRad = (Number.isFinite(Number(trackDeg)) ? Number(trackDeg) : 0) * (Math.PI / 180); + + const cosPhi = Math.cos(phi); + const cosTheta = Math.cos(theta); + const sinTheta = Math.sin(theta); + + // Unit North tangent vector (-dP/dphi) & unit East tangent vector (+(dP/dtheta)/sin(phi)) + const nx = cosPhi * cosTheta; + const ny = Math.sin(phi); + const nz = -cosPhi * sinTheta; + + const ex = sinTheta; + const ey = 0; + const ez = cosTheta; + + const cosT = Math.cos(trackRad); + const sinT = Math.sin(trackRad); + const hx = cosT * nx + sinT * ex; + const hy = cosT * ny + sinT * ey; + const hz = cosT * nz + sinT * ez; + + const omega = speed / EARTH_REAL_RADIUS_M; + return [hx * omega, hy * omega, hz * omega]; +} + +export function extrapolateGreatCircleXYZ(pos3, vel3, elapsedSec, radius) { + const x0 = pos3[0]; + const y0 = pos3[1]; + const z0 = pos3[2]; + const vx = vel3[0]; + const vy = vel3[1]; + const vz = vel3[2]; + const omega = Math.hypot(vx, vy, vz); + if (omega <= 1e-12 || elapsedSec === 0) { + return [x0, y0, z0]; + } + const angle = Math.min(0.25, Math.max(-0.25, omega * elapsedSec)); + const cosA = Math.cos(angle); + const sinA = Math.sin(angle); + const invLen = radius > 0 ? 1 / radius : 1; + const hx = vx / omega; + const hy = vy / omega; + const hz = vz / omega; + const px = x0 * invLen; + const py = y0 * invLen; + const pz = z0 * invLen; + return [ + radius * (cosA * px + sinA * hx), + radius * (cosA * py + sinA * hy), + radius * (cosA * pz + sinA * hz), + ]; +} + +export function gridBucketKey(lat, lon) { + const clampedLat = Math.max(-90, Math.min(89.999, Number(lat) || 0)); + const wrappedLon = ((((Number(lon) || 0) + 180) % 360) + 360) % 360 - 180; + const latBin = Math.floor((clampedLat + 90) / 5); + const lonBin = Math.floor((wrappedLon + 180) / 5); + return `${latBin}:${lonBin}`; +} + +export function lookupGridBucketCandidates(lat, lon, buckets) { + const clampedLat = Math.max(-90, Math.min(89.999, Number(lat) || 0)); + const wrappedLon = ((((Number(lon) || 0) + 180) % 360) + 360) % 360 - 180; + const latBin = Math.floor((clampedLat + 90) / 5); + const lonBin = Math.floor((wrappedLon + 180) / 5); + const candidates = []; + for (let dLat = -1; dLat <= 1; dLat += 1) { + const lb = latBin + dLat; + if (lb < 0 || lb > 35) continue; + for (let dLon = -1; dLon <= 1; dLon += 1) { + const nb = ((lonBin + dLon) + 72) % 72; + const list = buckets[`${lb}:${nb}`]; + if (Array.isArray(list)) { + for (let i = 0; i < list.length; i += 1) { + candidates.push(list[i]); + } + } + } + } + return candidates; +} + +export function unpackColumnarAircraftSnapshot(payload, options = {}) { + const fields = Array.isArray(payload?.fields) ? payload.fields : []; + const rawRows = Array.isArray(payload?.rows) ? payload.rows : []; + const earthRadius = Number(options.earthRadius || 100); + const maxRenderCount = Number.isFinite(Number(options.maxRenderCount)) + ? Math.max(1, Number(options.maxRenderCount)) + : rawRows.length; + + const idxOf = (name) => fields.indexOf(name); + const iIcao = idxOf("icao24"); + const iCallsign = idxOf("callsign"); + const iLat = idxOf("lat"); + const iLon = idxOf("lon"); + const iAlt = idxOf("altitude_m"); + const iSpd = idxOf("ground_speed_ms"); + const iTrk = idxOf("track_deg"); + const iVrate = idxOf("vertical_rate_ms"); + const iCat = idxOf("category"); + const iMil = idxOf("is_military"); + const iEmg = idxOf("is_emergency"); + const iEmgCode = idxOf("emergency_code"); + const iGround = idxOf("on_ground"); + const iSource = idxOf("source"); + const iObs = idxOf("observed_at"); + + const valid = []; + for (let r = 0; r < rawRows.length; r += 1) { + const row = rawRows[r]; + if (!Array.isArray(row)) continue; + const lat = Number(row[iLat]); + const lon = Number(row[iLon]); + const icao24 = String(row[iIcao] || "").trim().toLowerCase(); + if (!icao24 || !Number.isFinite(lat) || !Number.isFinite(lon)) continue; + const isEmergency = Boolean(row[iEmg]); + const isMilitary = Boolean(row[iMil]); + valid.push({ + icao24, + callsign: row[iCallsign] || null, + lat, + lon, + altitudeM: row[iAlt] != null ? Number(row[iAlt]) : null, + groundSpeedMs: row[iSpd] != null ? Number(row[iSpd]) : null, + trackDeg: row[iTrk] != null ? Number(row[iTrk]) : 0, + verticalRateMs: row[iVrate] != null ? Number(row[iVrate]) : null, + category: String(row[iCat] || "other").toLowerCase(), + isMilitary, + isEmergency, + emergencyCode: row[iEmgCode] || null, + onGround: Boolean(row[iGround]), + source: row[iSource] || "adsb_lol_aircraft", + observedAt: row[iObs] || null, + priority: isEmergency ? 2 : isMilitary ? 1 : 0, + }); + } + + let selected = valid; + if (valid.length > maxRenderCount) { + selected = [...valid].sort((a, b) => b.priority - a.priority).slice(0, maxRenderCount); + } + + const count = selected.length; + const positions = new Float32Array(count * 3); + const velocities = new Float32Array(count * 3); + const radii = new Float32Array(count); + const atlasSlots = new Float32Array(count * 2); + const gridBuckets = Object.create(null); + + for (let i = 0; i < count; i += 1) { + const item = selected[i]; + const radius = computeAircraftRadius(item.altitudeM, earthRadius); + const [x, y, z] = latLonRadiusToXYZ(item.lat, item.lon, radius); + const [vx, vy, vz] = computeTangentAngularVelocity( + item.lat, + item.lon, + item.onGround ? 0 : item.groundSpeedMs, + item.trackDeg, + ); + const base3 = i * 3; + positions[base3] = x; + positions[base3 + 1] = y; + positions[base3 + 2] = z; + velocities[base3] = vx; + velocities[base3 + 1] = vy; + velocities[base3 + 2] = vz; + radii[i] = radius; + + const base2 = i * 2; + atlasSlots[base2] = computeHeadingBin(item.trackDeg); + atlasSlots[base2 + 1] = getAircraftCategoryIndex(item.category); + + const bKey = gridBucketKey(item.lat, item.lon); + if (!gridBuckets[bKey]) gridBuckets[bKey] = []; + gridBuckets[bKey].push(i); + } + + return { + count, + positions, + velocities, + radii, + atlasSlots, + records: selected, + gridBuckets, + }; +} diff --git a/frontend/public/earth/js/aircraft-worker.js b/frontend/public/earth/js/aircraft-worker.js new file mode 100644 index 00000000..1ac6ef3e --- /dev/null +++ b/frontend/public/earth/js/aircraft-worker.js @@ -0,0 +1,35 @@ +// aircraft-worker.js - Web Worker for columnar ADS-B unpacking & spatial bucketing +import { unpackColumnarAircraftSnapshot } from "./aircraft-math.js"; + +self.addEventListener("message", (event) => { + const { id, type, payload, options } = event.data || {}; + if (type !== "build_snapshot") return; + try { + const unpacked = unpackColumnarAircraftSnapshot(payload, options || {}); + self.postMessage( + { + id, + ok: true, + count: unpacked.count, + positions: unpacked.positions, + velocities: unpacked.velocities, + radii: unpacked.radii, + atlasSlots: unpacked.atlasSlots, + records: unpacked.records, + gridBuckets: unpacked.gridBuckets, + }, + [ + unpacked.positions.buffer, + unpacked.velocities.buffer, + unpacked.radii.buffer, + unpacked.atlasSlots.buffer, + ], + ); + } catch (error) { + self.postMessage({ + id, + ok: false, + error: error?.message || String(error), + }); + } +}); diff --git a/frontend/public/earth/js/aircraft.js b/frontend/public/earth/js/aircraft.js new file mode 100644 index 00000000..c7d73097 --- /dev/null +++ b/frontend/public/earth/js/aircraft.js @@ -0,0 +1,715 @@ +// aircraft.js - Single-batch Three.js Points + Shader dead-reckoning + 3h ribbon track +import * as THREE from "three"; +import { CONFIG, PATHS } from "./constants.js"; +import { + AIRCRAFT_CATEGORY_LABELS, + AIRCRAFT_CATEGORY_ORDER, + AIRCRAFT_COLORS, + AIRCRAFT_HEADING_BINS, + extrapolateGreatCircleXYZ, + gridBucketKey, + latLonRadiusToXYZ, + lookupGridBucketCandidates, + unpackColumnarAircraftSnapshot, +} from "./aircraft-math.js"; +import { isLegendItemEnabled } from "./legend-filters.js"; +import { createSurfaceRibbonGeometry, createSurfaceRibbonMaterial } from "./surface-ribbon.js"; +import { isSurfaceAnchorVisible } from "./surface-marker-occlusion.js"; + +const AIRCRAFT_RENDER_ORDER = 4.9; +const AIRCRAFT_TRACK_RENDER_ORDER = 4.7; +const AIRCRAFT_SNAPSHOT_TRANSITION_MS = 300; +const AIRCRAFT_POLL_INTERVAL_MS = 60_000; +const AIRCRAFT_DESKTOP_MAX = 15_000; +const AIRCRAFT_CONSTRAINED_MAX = 4_000; + +let showAircraft = false; +let aircraftGroup = null; +let aircraftPoints = null; +let aircraftMaterial = null; +let aircraftAtlasTexture = null; +let activeTrackLine = null; +let trackRequestVersion = 0; + +let workerInstance = null; +let workerRequestId = 0; +let pollTimerId = null; +let loadGeneration = 0; + +let currentRecords = []; +let currentBuckets = Object.create(null); +let prevPosArray = new Float32Array(0); +let prevVelArray = new Float32Array(0); +let currPosArray = new Float32Array(0); +let currVelArray = new Float32Array(0); +let currRadiusArray = new Float32Array(0); +let currAtlasArray = new Float32Array(0); +let visibilityMaskArray = new Float32Array(0); + +let snapshotTimestampMs = performance.now(); +let prevSnapshotTimestampMs = performance.now(); +let transitionStartMs = 0; +let lockedAircraftIcao24 = null; +let lastRenderedCount = 0; +let earthRef = null; + +// Pre-allocated scratch objects (zero per-frame heap allocations) +const scratchCenterWorld = new THREE.Vector3(); +const scratchCameraLocal = new THREE.Vector3(); +const scratchPointWorld = new THREE.Vector3(); +const scratchPointLocal = new THREE.Vector3(); +const scratchScreenPos = new THREE.Vector3(); + +function isConstrainedDevice() { + if (typeof window === "undefined") return false; + const cores = Number(navigator?.hardwareConcurrency || 8); + const mobile = Boolean(window.innerWidth <= 900); + return mobile || cores <= 4; +} + +function getEffectiveRenderCap() { + return isConstrainedDevice() ? AIRCRAFT_CONSTRAINED_MAX : AIRCRAFT_DESKTOP_MAX; +} + +function buildAircraftAtlasTexture() { + if (typeof document === "undefined") return null; + const cell = 64; + const cols = AIRCRAFT_HEADING_BINS; + const rows = AIRCRAFT_CATEGORY_ORDER.length; + const canvas = document.createElement("canvas"); + canvas.width = cols * cell; + canvas.height = rows * cell; + const ctx = canvas.getContext("2d"); + if (!ctx) return null; + + ctx.clearRect(0, 0, canvas.width, canvas.height); + + for (let row = 0; row < rows; row += 1) { + const category = AIRCRAFT_CATEGORY_ORDER[row]; + const color = AIRCRAFT_COLORS[category] || AIRCRAFT_COLORS.other; + for (let col = 0; col < cols; col += 1) { + const cx = col * cell + cell * 0.5; + const cy = row * cell + cell * 0.5; + const angle = (col / cols) * Math.PI * 2; + ctx.save(); + ctx.translate(cx, cy); + ctx.rotate(angle); + ctx.fillStyle = color; + ctx.strokeStyle = "rgba(8, 13, 24, 0.85)"; + ctx.lineWidth = 2.4; + + if (category === "military") { + // Delta-wing interceptor silhouette + ctx.beginPath(); + ctx.moveTo(0, -18); + ctx.lineTo(15, 10); + ctx.lineTo(4, 8); + ctx.lineTo(4, 15); + ctx.lineTo(-4, 15); + ctx.lineTo(-4, 8); + ctx.lineTo(-15, 10); + ctx.closePath(); + } else if (category === "helicopter") { + // Compact rotorcraft silhouette + ctx.beginPath(); + ctx.arc(0, 0, 7, 0, Math.PI * 2); + ctx.moveTo(-16, -10); + ctx.lineTo(16, 10); + ctx.moveTo(16, -10); + ctx.lineTo(-16, 10); + } else { + // Jetliner / commercial silhouette pointing UP + ctx.beginPath(); + ctx.moveTo(0, -18); + ctx.lineTo(3, -5); + ctx.lineTo(17, 4); + ctx.lineTo(17, 8); + ctx.lineTo(3, 4); + ctx.lineTo(2.5, 13); + ctx.lineTo(8, 17); + ctx.lineTo(-8, 17); + ctx.lineTo(-2.5, 13); + ctx.lineTo(-3, 4); + ctx.lineTo(-17, 8); + ctx.lineTo(-17, 4); + ctx.lineTo(-3, -5); + ctx.closePath(); + } + ctx.fill(); + ctx.stroke(); + ctx.restore(); + } + } + + const texture = new THREE.CanvasTexture(canvas); + texture.minFilter = THREE.LinearFilter; + texture.magFilter = THREE.LinearFilter; + texture.generateMipmaps = false; + texture.flipY = false; + texture.needsUpdate = true; + return texture; +} + +function createAircraftShaderMaterial(atlasTexture) { + return new THREE.ShaderMaterial({ + transparent: true, + depthTest: true, + depthWrite: false, + uniforms: { + uElapsedSec: { value: 0.0 }, + uPrevElapsedSec: { value: 0.0 }, + uTransitionMix: { value: 1.0 }, + uPointSize: { value: 26.0 }, + uCols: { value: AIRCRAFT_HEADING_BINS }, + uRows: { value: AIRCRAFT_CATEGORY_ORDER.length }, + uAtlas: { value: atlasTexture }, + uEarthCenterWorld: { value: new THREE.Vector3() }, + uOccRadius: { value: CONFIG.earthRadius * 0.999 }, + }, + vertexShader: ` + attribute vec3 aPrevPos; + attribute vec3 aPrevVel; + attribute vec3 aCurrPos; + attribute vec3 aCurrVel; + attribute float aRadius; + attribute vec2 aAtlasSlot; + attribute float aVisibleMask; + + uniform float uElapsedSec; + uniform float uPrevElapsedSec; + uniform float uTransitionMix; + uniform float uPointSize; + uniform vec3 uEarthCenterWorld; + uniform float uOccRadius; + + varying vec2 vAtlasSlot; + varying float vAlpha; + + vec3 extrapolateGC(vec3 pos, vec3 vel, float elapsed, float radius) { + float omega = length(vel); + if (omega <= 1e-10 || elapsed == 0.0) { + return pos; + } + float angle = clamp(omega * elapsed, -0.25, 0.25); + vec3 pUnit = pos / max(radius, 1.0); + vec3 hUnit = vel / omega; + return radius * (cos(angle) * pUnit + sin(angle) * hUnit); + } + + void main() { + vAtlasSlot = aAtlasSlot; + if (aVisibleMask < 0.5) { + vAlpha = 0.0; + gl_Position = vec4(2.0, 2.0, 2.0, 1.0); + gl_PointSize = 0.0; + return; + } + vec3 prevP = extrapolateGC(aPrevPos, aPrevVel, uPrevElapsedSec, aRadius); + vec3 currP = extrapolateGC(aCurrPos, aCurrVel, uElapsedSec, aRadius); + float t = smoothstep(0.0, 1.0, clamp(uTransitionMix, 0.0, 1.0)); + vec3 localPos = mix(prevP, currP, t); + + vec4 worldPos = modelMatrix * vec4(localPos, 1.0); + vec3 fromCenter = worldPos.xyz - uEarthCenterWorld; + vec3 toCam = normalize(cameraPosition - worldPos.xyz); + float horizonDot = dot(normalize(fromCenter), toCam); + + vAlpha = smoothstep(-0.08, 0.08, horizonDot); + gl_Position = projectionMatrix * viewMatrix * worldPos; + gl_PointSize = uPointSize; + } + `, + fragmentShader: ` + uniform sampler2D uAtlas; + uniform float uCols; + uniform float uRows; + + varying vec2 vAtlasSlot; + varying float vAlpha; + + void main() { + if (vAlpha <= 0.01) discard; + vec2 cellUv = (vAtlasSlot + gl_PointCoord) / vec2(uCols, uRows); + vec4 texel = texture2D(uAtlas, cellUv); + float alpha = texel.a * vAlpha; + if (alpha <= 0.04) discard; + gl_FragColor = vec4(texel.rgb, alpha); + #include + } + `, + }); +} + +function getOrCreateWorker() { + if (typeof Worker === "undefined") return null; + if (!workerInstance) { + workerInstance = new Worker(new URL("./aircraft-worker.js", import.meta.url), { + type: "module", + }); + } + return workerInstance; +} + +function terminateWorker() { + if (workerInstance) { + workerInstance.terminate(); + workerInstance = null; + } +} + +async function unpackInWorkerOrMain(payload, options) { + const worker = getOrCreateWorker(); + if (!worker) { + return unpackColumnarAircraftSnapshot(payload, options); + } + const reqId = ++workerRequestId; + return new Promise((resolve, reject) => { + const onMessage = (event) => { + const msg = event.data; + if (!msg || msg.id !== reqId) return; + worker.removeEventListener("message", onMessage); + worker.removeEventListener("error", onError); + if (msg.ok) resolve(msg); + else reject(new Error(msg.error || "Aircraft worker failed")); + }; + const onError = (err) => { + worker.removeEventListener("message", onMessage); + worker.removeEventListener("error", onError); + reject(err); + }; + worker.addEventListener("message", onMessage); + worker.addEventListener("error", onError); + worker.postMessage({ id: reqId, type: "build_snapshot", payload, options }); + }); +} + +function updateLegendMaskBuffer() { + const count = currentRecords.length; + if (visibilityMaskArray.length !== count) { + visibilityMaskArray = new Float32Array(count); + } + for (let i = 0; i < count; i += 1) { + const cat = currentRecords[i].category || "other"; + visibilityMaskArray[i] = isLegendItemEnabled("aircraft", cat) ? 1.0 : 0.0; + } + if (aircraftPoints?.geometry) { + const attr = aircraftPoints.geometry.getAttribute("aVisibleMask"); + if (attr) { + attr.copyArray(visibilityMaskArray); + attr.needsUpdate = true; + } + } +} + +function applyUnpackedSnapshot(unpacked, earth) { + if (!showAircraft || !earth) return; + const now = performance.now(); + const prevMap = new Map(); + const prevElapsed = (now - snapshotTimestampMs) * 0.001; + for (let i = 0; i < currentRecords.length; i += 1) { + prevMap.set(currentRecords[i].icao24, { + pos: [currPosArray[i * 3], currPosArray[i * 3 + 1], currPosArray[i * 3 + 2]], + vel: [currVelArray[i * 3], currVelArray[i * 3 + 1], currVelArray[i * 3 + 2]], + rad: currRadiusArray[i] || CONFIG.earthRadius + 1.0, + }); + } + + const count = unpacked.count; + const nextPrevPos = new Float32Array(count * 3); + const nextPrevVel = new Float32Array(count * 3); + for (let i = 0; i < count; i += 1) { + const rec = unpacked.records[i]; + const old = prevMap.get(rec.icao24); + const b3 = i * 3; + if (old) { + const ext = extrapolateGreatCircleXYZ(old.pos, old.vel, prevElapsed, old.rad); + nextPrevPos[b3] = ext[0]; + nextPrevPos[b3 + 1] = ext[1]; + nextPrevPos[b3 + 2] = ext[2]; + nextPrevVel[b3] = old.vel[0]; + nextPrevVel[b3 + 1] = old.vel[1]; + nextPrevVel[b3 + 2] = old.vel[2]; + } else { + nextPrevPos[b3] = unpacked.positions[b3]; + nextPrevPos[b3 + 1] = unpacked.positions[b3 + 1]; + nextPrevPos[b3 + 2] = unpacked.positions[b3 + 2]; + nextPrevVel[b3] = unpacked.velocities[b3]; + nextPrevVel[b3 + 1] = unpacked.velocities[b3 + 1]; + nextPrevVel[b3 + 2] = unpacked.velocities[b3 + 2]; + } + } + + prevSnapshotTimestampMs = now; + snapshotTimestampMs = now; + transitionStartMs = prevMap.size > 0 ? now : 0; + + prevPosArray = nextPrevPos; + prevVelArray = nextPrevVel; + currPosArray = unpacked.positions; + currVelArray = unpacked.velocities; + currRadiusArray = unpacked.radii; + currAtlasArray = unpacked.atlasSlots; + currentRecords = unpacked.records; + currentBuckets = unpacked.gridBuckets; + lastRenderedCount = count; + + visibilityMaskArray = new Float32Array(count); + for (let i = 0; i < count; i += 1) { + const cat = currentRecords[i].category || "other"; + visibilityMaskArray[i] = isLegendItemEnabled("aircraft", cat) ? 1.0 : 0.0; + } + + if (!aircraftGroup) { + aircraftGroup = new THREE.Group(); + aircraftGroup.name = "aircraft-layer-group"; + earth.add(aircraftGroup); + } + if (!aircraftAtlasTexture) { + aircraftAtlasTexture = buildAircraftAtlasTexture(); + } + if (!aircraftMaterial) { + aircraftMaterial = createAircraftShaderMaterial(aircraftAtlasTexture); + } + + const nextGeom = new THREE.BufferGeometry(); + nextGeom.setAttribute("position", new THREE.BufferAttribute(currPosArray, 3)); + nextGeom.setAttribute("aPrevPos", new THREE.BufferAttribute(prevPosArray, 3)); + nextGeom.setAttribute("aPrevVel", new THREE.BufferAttribute(prevVelArray, 3)); + nextGeom.setAttribute("aCurrPos", new THREE.BufferAttribute(currPosArray, 3)); + nextGeom.setAttribute("aCurrVel", new THREE.BufferAttribute(currVelArray, 3)); + nextGeom.setAttribute("aRadius", new THREE.BufferAttribute(currRadiusArray, 1)); + nextGeom.setAttribute("aAtlasSlot", new THREE.BufferAttribute(currAtlasArray, 2)); + nextGeom.setAttribute("aVisibleMask", new THREE.BufferAttribute(visibilityMaskArray, 1)); + nextGeom.setDrawRange(0, count); + + if (!aircraftPoints) { + aircraftPoints = new THREE.Points(nextGeom, aircraftMaterial); + aircraftPoints.renderOrder = AIRCRAFT_RENDER_ORDER; + aircraftPoints.frustumCulled = false; + aircraftPoints.raycast = () => {}; + aircraftGroup.add(aircraftPoints); + } else { + const oldGeom = aircraftPoints.geometry; + aircraftPoints.geometry = nextGeom; + oldGeom?.dispose?.(); + } + aircraftGroup.visible = showAircraft && count > 0; +} + +export function getShowAircraft() { + return showAircraft; +} + +export function getAircraftCount() { + return lastRenderedCount; +} + +export function getAircraftRecords() { + return currentRecords; +} + +export function getAircraftLegendItems() { + return AIRCRAFT_CATEGORY_ORDER.map((key) => ({ + key, + label: AIRCRAFT_CATEGORY_LABELS[key] || key, + color: AIRCRAFT_COLORS[key] || AIRCRAFT_COLORS.other, + shape: "dot", + })); +} + +export function applyAircraftLegendFilter() { + updateLegendMaskBuffer(); +} + +export function clearAircraftTrack() { + trackRequestVersion += 1; + if (activeTrackLine?.parent) { + activeTrackLine.parent.remove(activeTrackLine); + } + activeTrackLine?.geometry?.dispose?.(); + activeTrackLine?.material?.dispose?.(); + activeTrackLine = null; +} + +export function clearAircraftSelection() { + lockedAircraftIcao24 = null; + clearAircraftTrack(); +} + +export function clearAircraftData(earth = earthRef) { + loadGeneration += 1; + if (pollTimerId) { + clearTimeout(pollTimerId); + pollTimerId = null; + } + clearAircraftSelection(); + terminateWorker(); + if (aircraftPoints) { + aircraftPoints.geometry?.dispose?.(); + aircraftPoints.parent?.remove(aircraftPoints); + aircraftPoints = null; + } + if (aircraftMaterial) { + aircraftMaterial.dispose?.(); + aircraftMaterial = null; + } + if (aircraftAtlasTexture) { + aircraftAtlasTexture.dispose?.(); + aircraftAtlasTexture = null; + } + if (aircraftGroup) { + aircraftGroup.parent?.remove(aircraftGroup); + aircraftGroup = null; + } + if (earth && aircraftGroup?.parent === earth) { + earth.remove(aircraftGroup); + } + currentRecords = []; + currentBuckets = Object.create(null); + prevPosArray = new Float32Array(0); + prevVelArray = new Float32Array(0); + currPosArray = new Float32Array(0); + currVelArray = new Float32Array(0); + currRadiusArray = new Float32Array(0); + currAtlasArray = new Float32Array(0); + visibilityMaskArray = new Float32Array(0); + lastRenderedCount = 0; +} + +export function toggleAircraft(show, earth = earthRef) { + showAircraft = Boolean(show); + if (earth) earthRef = earth; + if (!showAircraft) { + clearAircraftData(earthRef); + return; + } + if (aircraftGroup) aircraftGroup.visible = true; +} + +export async function loadAircraft(_scene, earth, options = {}) { + if (earth) earthRef = earth; + if (!showAircraft || !earthRef) return { totalCount: 0 }; + const gen = ++loadGeneration; + const maxRenderCount = Number(options.limit || getEffectiveRenderCap()); + + const params = new URLSearchParams({ limit: String(maxRenderCount) }); + const response = await fetch(`${PATHS.aircraftSnapshotApi}?${params.toString()}`, { + cache: "no-store", + }); + if (!response.ok) throw new Error(`Aircraft HTTP ${response.status}`); + const payload = await response.json(); + if (gen !== loadGeneration || !showAircraft) { + return { totalCount: getAircraftCount() }; + } + + const unpacked = await unpackInWorkerOrMain(payload, { + earthRadius: CONFIG.earthRadius, + maxRenderCount, + }); + if (gen !== loadGeneration || !showAircraft) { + return { totalCount: getAircraftCount() }; + } + applyUnpackedSnapshot(unpacked, earthRef); + + if (pollTimerId) clearTimeout(pollTimerId); + if (showAircraft && !options.disablePoll) { + pollTimerId = setTimeout(() => { + if (showAircraft) { + loadAircraft(_scene, earthRef).catch((err) => console.warn("飞机刷新失败:", err)); + } + }, AIRCRAFT_POLL_INTERVAL_MS); + } + return { totalCount: unpacked.count, sourceHealth: payload?.source_health || {} }; +} + +export async function showAircraftTrack(icao24, earth = earthRef) { + clearAircraftTrack(); + if (!icao24 || !earth || !showAircraft) return null; + lockedAircraftIcao24 = String(icao24).toLowerCase(); + const ver = trackRequestVersion; + const resp = await fetch(PATHS.aircraftTrackApi(icao24, 3), { cache: "no-store" }); + if (!resp.ok) throw new Error(`Aircraft track HTTP ${resp.status}`); + const data = await resp.json(); + if (ver !== trackRequestVersion || !showAircraft) return null; + + const rawPoints = Array.isArray(data?.points) ? data.points : []; + if (rawPoints.length < 2) return null; + + const vecs = []; + for (let i = 0; i < rawPoints.length; i += 1) { + const pt = rawPoints[i]; + const lat = Number(pt?.lat); + const lon = Number(pt?.lon); + if (!Number.isFinite(lat) || !Number.isFinite(lon)) continue; + const alt = Number(pt?.altitude_m); + const r = CONFIG.earthRadius + 0.72 + Math.max(0, Math.min(Number.isFinite(alt) ? alt : 3000, 15000)) / 15000 * 1.1; + const [x, y, z] = latLonRadiusToXYZ(lat, lon, r); + vecs.push(new THREE.Vector3(x, y, z)); + } + if (vecs.length < 2) return null; + + const geom = createSurfaceRibbonGeometry(vecs); + const mat = createSurfaceRibbonMaterial({ + color: 0xfef08a, + halfWidthPx: 3.4, + opacity: 0.88, + pulseSpeed: 0.6, + pulseFreq: 2.0, + pulseIntensity: 0.45, + tailFade: 1.0, + }); + activeTrackLine = new THREE.Mesh(geom, mat); + activeTrackLine.renderOrder = AIRCRAFT_TRACK_RENDER_ORDER; + activeTrackLine.raycast = () => {}; + if (!aircraftGroup) { + aircraftGroup = new THREE.Group(); + aircraftGroup.name = "aircraft-layer-group"; + earth.add(aircraftGroup); + } + aircraftGroup.add(activeTrackLine); + return activeTrackLine; +} + +export async function fetchAircraftDetail(icao24) { + const resp = await fetch(PATHS.aircraftDetailApi(icao24), { cache: "no-store" }); + if (!resp.ok) throw new Error(`Aircraft detail HTTP ${resp.status}`); + return resp.json(); +} + +export function updateAircraftVisualState(camera) { + if (!showAircraft || !aircraftMaterial || !earthRef) return; + const now = performance.now(); + aircraftMaterial.uniforms.uElapsedSec.value = (now - snapshotTimestampMs) * 0.001; + aircraftMaterial.uniforms.uPrevElapsedSec.value = (now - prevSnapshotTimestampMs) * 0.001; + aircraftMaterial.uniforms.uTransitionMix.value = + transitionStartMs > 0 + ? Math.min(1.0, Math.max(0.0, (now - transitionStartMs) / AIRCRAFT_SNAPSHOT_TRANSITION_MS)) + : 1.0; + + earthRef.getWorldPosition(scratchCenterWorld); + aircraftMaterial.uniforms.uEarthCenterWorld.value.copy(scratchCenterWorld); + + if (camera) { + const zoomScale = Math.max(0.75, Math.min(1.35, 300 / Math.max(115, camera.position.length()))); + aircraftMaterial.uniforms.uPointSize.value = 24.0 * zoomScale * Math.min(window.devicePixelRatio || 1, 2); + } + if (activeTrackLine?.material?.uniforms?.uTime) { + activeTrackLine.material.uniforms.uTime.value = now * 0.001; + } +} + +export function getAircraftPointerIntersections({ + earth, + camera, + surfaceCoords, + clientX, + clientY, + radiusPx = 22, +} = {}) { + if (!showAircraft || !earth || !camera || !surfaceCoords || currentRecords.length === 0) { + return []; + } + const candidates = lookupGridBucketCandidates(surfaceCoords.lat, surfaceCoords.lon, currentBuckets); + if (!candidates.length) return []; + + earth.updateWorldMatrix(true, false); + scratchCameraLocal.copy(camera.position); + earth.worldToLocal(scratchCameraLocal); + + const elapsed = (performance.now() - snapshotTimestampMs) * 0.001; + const maxSq = radiusPx * radiusPx; + const halfW = (typeof window !== "undefined" ? window.innerWidth : 1920) * 0.5; + const halfH = (typeof window !== "undefined" ? window.innerHeight : 1080) * 0.5; + const occRadius = CONFIG.earthRadius * 0.999; + + let bestIdx = -1; + let bestDistSq = maxSq; + + for (let i = 0; i < candidates.length; i += 1) { + const idx = candidates[i]; + if (visibilityMaskArray[idx] < 0.5) continue; + const b3 = idx * 3; + const rad = currRadiusArray[idx] || CONFIG.earthRadius + 1.0; + const ext = extrapolateGreatCircleXYZ( + [currPosArray[b3], currPosArray[b3 + 1], currPosArray[b3 + 2]], + [currVelArray[b3], currVelArray[b3 + 1], currVelArray[b3 + 2]], + elapsed, + rad, + ); + scratchPointLocal.set(ext[0], ext[1], ext[2]); + if (!isSurfaceAnchorVisible(scratchPointLocal, scratchCameraLocal, occRadius)) continue; + + scratchPointWorld.copy(scratchPointLocal).applyMatrix4(earth.matrixWorld); + scratchScreenPos.copy(scratchPointWorld).project(camera); + if (scratchScreenPos.z > 1) continue; + + const sx = (scratchScreenPos.x + 1) * halfW; + const sy = (-scratchScreenPos.y + 1) * halfH; + const dx = sx - clientX; + const dy = sy - clientY; + const dSq = dx * dx + dy * dy; + if (dSq <= bestDistSq) { + bestDistSq = dSq; + bestIdx = idx; + } + } + + if (bestIdx < 0) return []; + const rec = currentRecords[bestIdx]; + return [ + { + index: bestIdx, + distanceSq: bestDistSq, + object: { + userData: { + type: "aircraft", + id: rec.icao24, + icao24: rec.icao24, + name: rec.callsign || rec.icao24.toUpperCase(), + callsign: rec.callsign, + latitude: rec.lat, + longitude: rec.lon, + altitude_m: rec.altitudeM, + ground_speed_ms: rec.groundSpeedMs, + track_deg: rec.trackDeg, + vertical_rate_ms: rec.verticalRateMs, + category: rec.category, + is_military: rec.isMilitary, + is_emergency: rec.isEmergency, + emergency_code: rec.emergencyCode, + on_ground: rec.onGround, + source: rec.source, + observed_at: rec.observedAt, + }, + }, + }, + ]; +} + +export function buildAircraftSearchItems(normalizedQuery, computeSearchScore) { + if (!showAircraft || !currentRecords.length) return []; + const matches = []; + for (let i = 0; i < currentRecords.length; i += 1) { + const rec = currentRecords[i]; + const score = computeSearchScore( + normalizedQuery, + rec.callsign, + rec.icao24, + rec.category, + rec.emergencyCode, + "飞机 aircraft 航班 military emergency", + ); + if (score < 0) continue; + matches.push({ + id: `aircraft:${rec.icao24}`, + kind: "aircraft", + icon: "flight", + typeLabel: rec.isMilitary ? "军机" : "航空器", + title: rec.callsign || rec.icao24.toUpperCase(), + subtitle: `${rec.icao24.toUpperCase()} · ${AIRCRAFT_CATEGORY_LABELS[rec.category] || rec.category}`, + score, + entity: rec, + }); + } + return matches.slice(0, 30); +} diff --git a/frontend/public/earth/js/asset-swr-cache.js b/frontend/public/earth/js/asset-swr-cache.js new file mode 100644 index 00000000..ed8f6665 --- /dev/null +++ b/frontend/public/earth/js/asset-swr-cache.js @@ -0,0 +1,512 @@ +/** + * Unified local Stale-While-Revalidate (SWR) cache backed by Cache Storage + * (binary/JSON bodies) + IndexedDB (metadata, ETag/fingerprint, LRU eviction). + * Falls back transparently to bounded in-memory Maps when browser storage APIs + * are unavailable (e.g., private browsing or Node/Bun unit tests). + */ + +const CACHE_PREFIX = "planet-earth-assets-v1:"; +const IDB_NAME = "planet-earth-asset-meta-v1"; +const IDB_VERSION = 1; +const STORE_ENTRIES = "entries"; +const LEGACY_BOUNDARY_IDB = "planet-earth-boundary-tiles"; + +export const BUCKET_LIMITS = Object.freeze({ + "card-images": { maxBytes: 128 * 1024 * 1024, maxItems: 250 }, + tiles: { maxBytes: 384 * 1024 * 1024, maxItems: 2400 }, + terrain: { maxBytes: 128 * 1024 * 1024, maxItems: 700 }, + clouds: { maxBytes: 64 * 1024 * 1024, maxItems: 8 }, + wind: { maxBytes: 32 * 1024 * 1024, maxItems: 8 }, + geo: { maxBytes: 64 * 1024 * 1024, maxItems: 24 }, + meta: { maxBytes: 8 * 1024 * 1024, maxItems: 128 }, +}); + +const memoryMeta = new Map(); +const memoryBlobs = new Map(); +let dbPromise = null; + +function entryId(bucket, key) { + return `${bucket}::${key}`; +} + +function syntheticCacheUrl(bucket, key) { + return `https://asset.cache.local/${encodeURIComponent(bucket)}/${encodeURIComponent(key)}`; +} + +function getBucketLimit(bucket) { + return BUCKET_LIMITS[bucket] || { maxBytes: 64 * 1024 * 1024, maxItems: 200 }; +} + +function hasCacheStorage() { + return typeof caches !== "undefined" && typeof caches?.open === "function"; +} + +function openMetaDb() { + if (typeof indexedDB === "undefined") return Promise.resolve(null); + if (dbPromise) return dbPromise; + dbPromise = new Promise((resolve) => { + try { + const req = indexedDB.open(IDB_NAME, IDB_VERSION); + req.onupgradeneeded = () => { + const db = req.result; + if (!db.objectStoreNames.contains(STORE_ENTRIES)) { + const store = db.createObjectStore(STORE_ENTRIES, { keyPath: "id" }); + store.createIndex("bucket", "bucket", { unique: false }); + store.createIndex("lastAccessedAt", "lastAccessedAt", { unique: false }); + } + }; + req.onsuccess = () => resolve(req.result); + req.onerror = () => resolve(null); + } catch { + resolve(null); + } + }); + return dbPromise; +} + +async function idbGet(id) { + const db = await openMetaDb(); + if (!db) return memoryMeta.get(id) || null; + return new Promise((resolve) => { + try { + const tx = db.transaction(STORE_ENTRIES, "readonly"); + const req = tx.objectStore(STORE_ENTRIES).get(id); + req.onsuccess = () => resolve(req.result || memoryMeta.get(id) || null); + req.onerror = () => resolve(memoryMeta.get(id) || null); + } catch { + resolve(memoryMeta.get(id) || null); + } + }); +} + +async function idbPut(record) { + memoryMeta.set(record.id, record); + const db = await openMetaDb(); + if (!db) return; + await new Promise((resolve) => { + try { + const tx = db.transaction(STORE_ENTRIES, "readwrite"); + tx.objectStore(STORE_ENTRIES).put(record); + tx.oncomplete = () => resolve(); + tx.onerror = () => resolve(); + } catch { + resolve(); + } + }); +} + +async function idbDelete(id) { + memoryMeta.delete(id); + const db = await openMetaDb(); + if (!db) return; + await new Promise((resolve) => { + try { + const tx = db.transaction(STORE_ENTRIES, "readwrite"); + tx.objectStore(STORE_ENTRIES).delete(id); + tx.oncomplete = () => resolve(); + tx.onerror = () => resolve(); + } catch { + resolve(); + } + }); +} + +async function idbListAll() { + const db = await openMetaDb(); + if (!db) return Array.from(memoryMeta.values()); + return new Promise((resolve) => { + try { + const tx = db.transaction(STORE_ENTRIES, "readonly"); + const req = tx.objectStore(STORE_ENTRIES).getAll(); + req.onsuccess = () => resolve(Array.isArray(req.result) ? req.result : []); + req.onerror = () => resolve(Array.from(memoryMeta.values())); + } catch { + resolve(Array.from(memoryMeta.values())); + } + }); +} + +async function idbListByBucket(bucket) { + const db = await openMetaDb(); + if (!db) { + return Array.from(memoryMeta.values()).filter((item) => item.bucket === bucket); + } + return new Promise((resolve) => { + try { + const tx = db.transaction(STORE_ENTRIES, "readonly"); + const index = tx.objectStore(STORE_ENTRIES).index("bucket"); + const req = index.getAll(bucket); + req.onsuccess = () => resolve(Array.isArray(req.result) ? req.result : []); + req.onerror = () => resolve(Array.from(memoryMeta.values()).filter((item) => item.bucket === bucket)); + } catch { + resolve(Array.from(memoryMeta.values()).filter((item) => item.bucket === bucket)); + } + }); +} + +async function writeBody(bucket, key, blob, contentType) { + const memKey = entryId(bucket, key); + memoryBlobs.set(memKey, blob); + if (memoryBlobs.size > 48 && hasCacheStorage()) { + const oldest = memoryBlobs.keys().next().value; + if (oldest) memoryBlobs.delete(oldest); + } + if (!hasCacheStorage()) return; + try { + const cache = await caches.open(`${CACHE_PREFIX}${bucket}`); + const response = new Response(blob, { + status: 200, + headers: { + "Content-Type": contentType || blob.type || "application/octet-stream", + }, + }); + await cache.put(syntheticCacheUrl(bucket, key), response); + } catch { + // Quota errors fall back gracefully to in-memory copy. + } +} + +async function readBody(bucket, key) { + const memKey = entryId(bucket, key); + if (hasCacheStorage()) { + try { + const cache = await caches.open(`${CACHE_PREFIX}${bucket}`); + const hit = await cache.match(syntheticCacheUrl(bucket, key)); + if (hit) { + return await hit.blob(); + } + } catch { + // Fall through to memory cache. + } + } + return memoryBlobs.get(memKey) || null; +} + +async function deleteBody(bucket, key) { + const memKey = entryId(bucket, key); + memoryBlobs.delete(memKey); + if (!hasCacheStorage()) return; + try { + const cache = await caches.open(`${CACHE_PREFIX}${bucket}`); + await cache.delete(syntheticCacheUrl(bucket, key)); + } catch { + // Ignore Cache Storage cleanup errors. + } +} + +async function enforceBucketLru(bucket) { + const { maxBytes, maxItems } = getBucketLimit(bucket); + const items = await idbListByBucket(bucket); + let totalBytes = items.reduce((sum, item) => sum + (Number(item.sizeBytes) || 0), 0); + if (items.length <= maxItems && totalBytes <= maxBytes) return; + + items.sort((a, b) => (a.lastAccessedAt || 0) - (b.lastAccessedAt || 0)); + let remaining = items.length; + for (const item of items) { + if (remaining <= maxItems && totalBytes <= maxBytes) break; + await deleteBody(bucket, item.key); + await idbDelete(item.id); + remaining -= 1; + totalBytes -= Number(item.sizeBytes) || 0; + } + if (!hasCacheStorage() && memoryBlobs.size > maxItems) { + const prefix = `${bucket}::`; + for (const key of Array.from(memoryMeta.keys())) { + if (key.startsWith(prefix) && !memoryBlobs.has(key)) memoryMeta.delete(key); + } + } +} + +export function formatBytes(bytes) { + const n = Number(bytes) || 0; + if (n <= 0) return "0 B"; + if (n < 1024) return `${Math.round(n)} B`; + if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`; + if (n < 1024 * 1024 * 1024) return `${(n / (1024 * 1024)).toFixed(1)} MB`; + return `${(n / (1024 * 1024 * 1024)).toFixed(2)} GB`; +} + +export async function getCachedAssetMeta(bucket, key) { + return idbGet(entryId(bucket, key)); +} + +export async function putCachedAssetMeta(bucket, key, metaPatch = {}) { + const id = entryId(bucket, key); + const prev = await idbGet(id); + const now = Date.now(); + const next = { + ...(prev || {}), + ...metaPatch, + id, + bucket, + key, + updatedAt: metaPatch.updatedAt ?? prev?.updatedAt ?? now, + lastAccessedAt: now, + }; + await idbPut(next); + return next; +} + +export async function putCachedAssetBlob(bucket, key, blob, metaPatch = {}) { + const now = Date.now(); + const contentType = metaPatch.contentType || blob.type || "application/octet-stream"; + await writeBody(bucket, key, blob, contentType); + const record = { + ...(await idbGet(entryId(bucket, key))), + ...metaPatch, + id: entryId(bucket, key), + bucket, + key, + contentType, + sizeBytes: Number(blob.size) || Number(metaPatch.sizeBytes) || 0, + updatedAt: now, + lastAccessedAt: now, + }; + await idbPut(record); + await enforceBucketLru(bucket); + return record; +} + +export async function readCachedAssetBlob(bucket, key) { + const blob = await readBody(bucket, key); + if (!blob) return null; + const meta = await idbGet(entryId(bucket, key)); + if (meta) { + void idbPut({ ...meta, lastAccessedAt: Date.now() }); + } + return blob; +} + +export async function putCachedAssetJson(bucket, key, data, metaPatch = {}) { + const encoded = JSON.stringify(data); + const blob = new Blob([encoded], { type: "application/json" }); + return putCachedAssetBlob(bucket, key, blob, { + ...metaPatch, + contentType: "application/json", + sizeBytes: blob.size, + }); +} + +export async function readCachedAssetJson(bucket, key) { + const blob = await readCachedAssetBlob(bucket, key); + if (!blob) return null; + try { + const text = await blob.text(); + return JSON.parse(text); + } catch { + await deleteCachedAsset(bucket, key); + return null; + } +} + +export async function deleteCachedAsset(bucket, key) { + await deleteBody(bucket, key); + await idbDelete(entryId(bucket, key)); +} + +export async function fetchBinarySwr({ + bucket, + key, + url, + fingerprint = "", + fetchImpl = globalThis.fetch?.bind(globalThis), + signal, + headers, +}) { + const meta = await getCachedAssetMeta(bucket, key); + const matchesFingerprint = fingerprint + ? meta?.fingerprint === fingerprint + : meta?.url === url; + if (meta && matchesFingerprint) { + const cachedBlob = await readCachedAssetBlob(bucket, key); + if (cachedBlob) { + return { blob: cachedBlob, fromCache: true, meta }; + } + } + + const reqHeaders = new Headers(headers || {}); + if (meta?.etag && meta.url === url && !fingerprint) { + reqHeaders.set("If-None-Match", meta.etag); + } + const response = await fetchImpl(url, { headers: reqHeaders, signal }); + if (response.status === 304 && meta) { + const cachedBlob = await readCachedAssetBlob(bucket, key); + if (cachedBlob) { + const refreshed = await putCachedAssetMeta(bucket, key, { lastCheckedAt: Date.now() }); + return { blob: cachedBlob, fromCache: true, meta: refreshed }; + } + } + if (!response.ok) { + throw new Error(`Asset fetch failed (${response.status}): ${url}`); + } + const blob = await response.blob(); + const nextMeta = await putCachedAssetBlob(bucket, key, blob, { + url, + fingerprint: fingerprint || response.headers.get("etag") || "", + etag: response.headers.get("etag") || "", + lastCheckedAt: Date.now(), + }); + return { blob, fromCache: false, meta: nextMeta }; +} + +export async function fetchJsonSwr({ + bucket = "meta", + key, + url, + fetchImpl = globalThis.fetch?.bind(globalThis), + timeoutMs = 15000, + headers, + onFresh, +}) { + const existingMeta = await getCachedAssetMeta(bucket, key); + const existingData = existingMeta ? await readCachedAssetJson(bucket, key) : null; + + const runRevalidate = async () => { + const controller = typeof AbortController !== "undefined" ? new AbortController() : null; + const timer = controller && timeoutMs > 0 + ? setTimeout(() => controller.abort(), timeoutMs) + : null; + try { + const reqHeaders = new Headers(headers || {}); + if (existingMeta?.etag) { + reqHeaders.set("If-None-Match", existingMeta.etag); + } + const response = await fetchImpl(url, { + headers: reqHeaders, + signal: controller?.signal, + cache: "no-cache", + }); + if (response.status === 304 && existingData !== null) { + const touched = await putCachedAssetMeta(bucket, key, { lastCheckedAt: Date.now() }); + return { data: existingData, status: 304, fromCache: true, etag: touched.etag || "" }; + } + if (!response.ok) { + throw new Error(`JSON SWR fetch failed (${response.status}): ${url}`); + } + const nextData = await response.json(); + const nextEtag = response.headers.get("etag") || ""; + await putCachedAssetJson(bucket, key, nextData, { + url, + etag: nextEtag, + lastCheckedAt: Date.now(), + }); + if (typeof onFresh === "function") { + onFresh(nextData, { etag: nextEtag, changed: true }); + } + return { data: nextData, status: response.status, fromCache: false, etag: nextEtag }; + } finally { + if (timer) clearTimeout(timer); + } + }; + + if (existingData !== null) { + const revalidatePromise = runRevalidate().catch(() => ({ + data: existingData, + status: 0, + fromCache: true, + etag: existingMeta?.etag || "", + })); + return { + data: existingData, + fromCache: true, + meta: existingMeta, + revalidatePromise, + }; + } + + const fresh = await runRevalidate(); + return { + data: fresh.data, + fromCache: false, + meta: await getCachedAssetMeta(bucket, key), + revalidatePromise: Promise.resolve(fresh), + }; +} + +export async function getLocalCacheStats() { + const all = await idbListAll(); + const buckets = {}; + let webBytes = 0; + let webCount = 0; + for (const item of all) { + const name = item.bucket || "other"; + if (!buckets[name]) buckets[name] = { bytes: 0, count: 0 }; + const size = Number(item.sizeBytes) || 0; + buckets[name].bytes += size; + buckets[name].count += 1; + webBytes += size; + webCount += 1; + } + + let desktop = null; + if (typeof window !== "undefined" && typeof window.planetDesktop?.getAssetCacheStats === "function") { + try { + desktop = await window.planetDesktop.getAssetCacheStats(); + } catch { + desktop = null; + } + } + + const desktopBytes = Number(desktop?.totalBytes) || 0; + const desktopCount = Number(desktop?.totalCount) || 0; + return { + web: { totalBytes: webBytes, totalCount: webCount, buckets }, + desktop, + totalBytes: webBytes + desktopBytes, + totalCount: webCount + desktopCount, + }; +} + +export async function clearLocalAssetCache(buckets = null) { + const targetBuckets = Array.isArray(buckets) && buckets.length ? new Set(buckets) : null; + const all = await idbListAll(); + for (const item of all) { + if (!targetBuckets || targetBuckets.has(item.bucket)) { + await deleteBody(item.bucket, item.key); + await idbDelete(item.id); + } + } + if (hasCacheStorage()) { + try { + const names = await caches.keys(); + await Promise.all( + names + .filter((name) => { + if (!name.startsWith(CACHE_PREFIX)) return false; + if (!targetBuckets) return true; + return targetBuckets.has(name.slice(CACHE_PREFIX.length)); + }) + .map((name) => caches.delete(name)), + ); + } catch { + // Ignore cache deletion failures. + } + } + if (!targetBuckets && typeof indexedDB !== "undefined") { + for (const legacyDb of [LEGACY_BOUNDARY_IDB]) { + try { + await new Promise((resolve) => { + const req = indexedDB.deleteDatabase(legacyDb); + req.onsuccess = () => resolve(); + req.onerror = () => resolve(); + req.onblocked = () => resolve(); + }); + } catch { + // Ignore legacy IDB cleanup failure. + } + } + } + if (typeof window !== "undefined" && typeof window.planetDesktop?.clearAssetCache === "function") { + try { + await window.planetDesktop.clearAssetCache(buckets || undefined); + } catch { + // Ignore desktop IPC error. + } + } + return getLocalCacheStats(); +} + +export function _resetMemoryCacheForTests() { + memoryMeta.clear(); + memoryBlobs.clear(); +} diff --git a/frontend/public/earth/js/asset-swr-cache.test.js b/frontend/public/earth/js/asset-swr-cache.test.js new file mode 100644 index 00000000..5834e3af --- /dev/null +++ b/frontend/public/earth/js/asset-swr-cache.test.js @@ -0,0 +1,144 @@ +import { beforeEach, expect, test } from "bun:test"; +import { + _resetMemoryCacheForTests, + clearLocalAssetCache, + fetchBinarySwr, + fetchJsonSwr, + formatBytes, + getLocalCacheStats, + putCachedAssetBlob, + readCachedAssetBlob, +} from "./asset-swr-cache.js"; + +beforeEach(() => { + _resetMemoryCacheForTests(); +}); + +test("formatBytes formats human-readable sizes cleanly", () => { + expect(formatBytes(0)).toBe("0 B"); + expect(formatBytes(512)).toBe("512 B"); + expect(formatBytes(2048)).toBe("2.0 KB"); + expect(formatBytes(3 * 1024 * 1024)).toBe("3.0 MB"); +}); + +test("fetchBinarySwr returns cached blob on matching fingerprint and re-fetches only on fingerprint change", async () => { + let fetches = 0; + const fetchMock = async (url) => { + fetches += 1; + const body = fetches === 1 ? "image-v1" : "image-v2"; + return new Response(new Blob([body], { type: "image/webp" }), { + status: 200, + headers: { "Content-Type": "image/webp", ETag: `"fp-${fetches}"` }, + }); + }; + + const first = await fetchBinarySwr({ + bucket: "card-images", + key: "card:1", + url: "/api/v1/earth/card-images/files/v1.webp", + fingerprint: "fp-1", + fetchImpl: fetchMock, + }); + expect(first.fromCache).toBe(false); + expect(await first.blob.text()).toBe("image-v1"); + + const second = await fetchBinarySwr({ + bucket: "card-images", + key: "card:1", + url: "/api/v1/earth/card-images/files/v1.webp", + fingerprint: "fp-1", + fetchImpl: fetchMock, + }); + expect(second.fromCache).toBe(true); + expect(await second.blob.text()).toBe("image-v1"); + expect(fetches).toBe(1); + + const third = await fetchBinarySwr({ + bucket: "card-images", + key: "card:1", + url: "/api/v1/earth/card-images/files/v2.webp", + fingerprint: "fp-2", + fetchImpl: fetchMock, + }); + expect(third.fromCache).toBe(false); + expect(await third.blob.text()).toBe("image-v2"); + expect(fetches).toBe(2); +}); + +test("fetchJsonSwr serves cached JSON immediately and sends If-None-Match in background", async () => { + const seenIfNoneMatch = []; + let freshUpdates = 0; + let serverVersion = 1; + + const fetchMock = async (_url, init) => { + seenIfNoneMatch.push(init?.headers?.get("If-None-Match") || null); + if (serverVersion === 1 && init?.headers?.get("If-None-Match") === '"etag-1"') { + return new Response(null, { status: 304, headers: { ETag: '"etag-1"' } }); + } + return new Response(JSON.stringify({ version: serverVersion }), { + status: 200, + headers: { "Content-Type": "application/json", ETag: `"etag-${serverVersion}"` }, + }); + }; + + const cold = await fetchJsonSwr({ + bucket: "meta", + key: "brand", + url: "/api/v1/earth/brand", + fetchImpl: fetchMock, + }); + expect(cold.fromCache).toBe(false); + expect(cold.data.version).toBe(1); + + const warmNotModified = await fetchJsonSwr({ + bucket: "meta", + key: "brand", + url: "/api/v1/earth/brand", + fetchImpl: fetchMock, + onFresh: () => { + freshUpdates += 1; + }, + }); + expect(warmNotModified.fromCache).toBe(true); + expect(warmNotModified.data.version).toBe(1); + const bg1 = await warmNotModified.revalidatePromise; + expect(bg1.status).toBe(304); + expect(freshUpdates).toBe(0); + + serverVersion = 2; + const warmUpdated = await fetchJsonSwr({ + bucket: "meta", + key: "brand", + url: "/api/v1/earth/brand", + fetchImpl: fetchMock, + onFresh: () => { + freshUpdates += 1; + }, + }); + expect(warmUpdated.fromCache).toBe(true); + expect(warmUpdated.data.version).toBe(1); + const bg2 = await warmUpdated.revalidatePromise; + expect(bg2.status).toBe(200); + expect(bg2.data.version).toBe(2); + expect(freshUpdates).toBe(1); + expect(seenIfNoneMatch).toEqual([null, '"etag-1"', '"etag-1"']); +}); + +test("LRU eviction and stats/clear report accurate totals", async () => { + await putCachedAssetBlob("clouds", "c1", new Blob(["aaaa"]), { updatedAt: 1 }); + await new Promise((r) => setTimeout(r, 5)); + await putCachedAssetBlob("clouds", "c2", new Blob(["bbbbbb"]), { updatedAt: 2 }); + for (let i = 0; i < 8; i += 1) { + await putCachedAssetBlob("clouds", `extra-${i}`, new Blob(["xx"])); + } + // clouds maxItems = 8, so c1 must have been evicted + expect(await readCachedAssetBlob("clouds", "c1")).toBeNull(); + + const stats = await getLocalCacheStats(); + expect(stats.totalCount).toBe(8); + expect(stats.totalBytes).toBeGreaterThan(0); + + const afterClear = await clearLocalAssetCache(); + expect(afterClear.totalCount).toBe(0); + expect(afterClear.totalBytes).toBe(0); +}); diff --git a/frontend/public/earth/js/bgp.js b/frontend/public/earth/js/bgp.js index c4ec1d9b..b2a1ff75 100644 --- a/frontend/public/earth/js/bgp.js +++ b/frontend/public/earth/js/bgp.js @@ -1337,18 +1337,20 @@ export async function loadBGPAnomalies(scene, earth) { } const emptyPayload = { type: "FeatureCollection", features: [], count: 0 }; - const anomaliesPayload = await fetchGeoJSONWithTimeout( - `${PATHS.bgpApi}?limit=${BGP_CONFIG.defaultFetchLimit}`, - 5000, - "BGP anomalies unavailable, falling back to collectors only:", - emptyPayload, - ); - const incidentsPayload = await fetchGeoJSONWithTimeout( - `${PATHS.bgpIncidentsApi}?limit=${BGP_CONFIG.defaultFetchLimit}`, - 5000, - "BGP incidents unavailable, falling back to anomalies:", - emptyPayload, - ); + const [anomaliesPayload, incidentsPayload] = await Promise.all([ + fetchGeoJSONWithTimeout( + `${PATHS.bgpApi}?limit=${BGP_CONFIG.defaultFetchLimit}`, + 5000, + "BGP anomalies unavailable, falling back to collectors only:", + emptyPayload, + ), + fetchGeoJSONWithTimeout( + `${PATHS.bgpIncidentsApi}?limit=${BGP_CONFIG.defaultFetchLimit}`, + 5000, + "BGP incidents unavailable, falling back to anomalies:", + emptyPayload, + ), + ]); const collectorsPayload = await collectorsResponse.json(); const collectorFeatures = Array.isArray(collectorsPayload?.features) diff --git a/frontend/public/earth/js/brand.js b/frontend/public/earth/js/brand.js index a14ff505..ea67564c 100644 --- a/frontend/public/earth/js/brand.js +++ b/frontend/public/earth/js/brand.js @@ -1,3 +1,5 @@ +import { fetchJsonSwr } from "./asset-swr-cache.js"; + const DEFAULT_BRAND_LANGUAGE = "zh"; const EARTH_BRAND_API = "/api/v1/earth/brand"; @@ -253,11 +255,14 @@ export function mountBrand(target, configOrVariant = DEFAULT_BRAND_LANGUAGE) { attachBrandImageResilience(target, defaults); } -export async function fetchEarthBrandConfig() { - const response = await fetch(EARTH_BRAND_API, { cache: "no-store" }); - if (!response.ok) { - throw new Error(`Earth brand config request failed: ${response.status}`); - } - const payload = await response.json(); - return payload?.brand ?? getDefaultBrandConfig(); +export async function fetchEarthBrandConfig(onFresh) { + const { data } = await fetchJsonSwr({ + bucket: "meta", + key: "brand", + url: EARTH_BRAND_API, + onFresh: (fresh) => { + if (typeof onFresh === "function") onFresh(fresh?.brand ?? getDefaultBrandConfig()); + }, + }); + return data?.brand ?? getDefaultBrandConfig(); } diff --git a/frontend/public/earth/js/cables.js b/frontend/public/earth/js/cables.js index 6330f5d7..ddd84ba5 100644 --- a/frontend/public/earth/js/cables.js +++ b/frontend/public/earth/js/cables.js @@ -18,6 +18,7 @@ import { getSurfaceMarkerCameraScale } from "./utils.js"; import { setEarthStatValue, updateEarthStats, showStatusMessage } from "./ui.js"; import { setLegendItems, setLegendMode } from "./legend.js"; import { earthMessage } from "./i18n.js"; +import { fetchJsonSwr } from "./asset-swr-cache.js"; export let cableLines = []; export let landingPoints = []; @@ -198,6 +199,8 @@ function createCableLine(points, color, properties) { length: properties.length || "-", coords: "-", rfs: properties.rfs || "-", + advisories: Array.isArray(properties.advisories) ? properties.advisories : [], + hasAdvisory: Boolean(Array.isArray(properties.advisories) && properties.advisories.length > 0), originalColor: color, localCenter: lineGeometry.boundingSphere?.center?.clone() || new THREE.Vector3(), @@ -238,18 +241,8 @@ export function clearCableData(earthObj = null) { clearLandingPoints(earthObj); } -export async function loadGeoJSONFromPath(scene, earthObj, options = {}) { +function applyCableGeoJson(earthObj, data, options = {}) { const { silent = false } = options; - if (!silent) { - showStatusMessage(earthMessage("loading.cableData"), "warning"); - } - - const response = await fetch(PATHS.cablesApi, { cache: "no-store" }); - if (!response.ok) { - throw new Error(`电缆接口返回 HTTP ${response.status}`); - } - - const data = await response.json(); if (!data.features || !Array.isArray(data.features)) { throw new Error("无效的电缆 GeoJSON 格式"); } @@ -350,15 +343,25 @@ export async function loadGeoJSONFromPath(scene, earthObj, options = {}) { return cableLines.length; } -export async function loadLandingPoints(scene, earthObj, options = {}) { +export async function loadGeoJSONFromPath(scene, earthObj, options = {}) { const { silent = false } = options; - - const response = await fetch(PATHS.landingPointsApi, { cache: "no-store" }); - if (!response.ok) { - throw new Error(`登陆点接口返回 HTTP ${response.status}`); + if (!silent) { + showStatusMessage(earthMessage("loading.cableData"), "warning"); } - const data = await response.json(); + const { data } = await fetchJsonSwr({ + bucket: "geo", + key: "cables", + url: PATHS.cablesApi, + onFresh: (fresh) => { + try { applyCableGeoJson(earthObj, fresh, { silent: true }); } catch {} + }, + }); + return applyCableGeoJson(earthObj, data, options); +} + +async function applyLandingPointsGeoJson(earthObj, data, options = {}) { + const { silent = false } = options; if (!data.features || !Array.isArray(data.features)) { throw new Error("无效的登陆点 GeoJSON 格式"); } @@ -445,6 +448,18 @@ export async function loadLandingPoints(scene, earthObj, options = {}) { return validCount; } +export async function loadLandingPoints(scene, earthObj, options = {}) { + const { data } = await fetchJsonSwr({ + bucket: "geo", + key: "landing-points", + url: PATHS.landingPointsApi, + onFresh: (fresh) => { + void applyLandingPointsGeoJson(earthObj, fresh, { silent: true }).catch(() => {}); + }, + }); + return applyLandingPointsGeoJson(earthObj, data, options); +} + export function handleCableClick(cable) { clearLockedCableRibbon(); lockedCable = cable; diff --git a/frontend/public/earth/js/card-images.js b/frontend/public/earth/js/card-images.js index 220dd5ba..89286483 100644 --- a/frontend/public/earth/js/card-images.js +++ b/frontend/public/earth/js/card-images.js @@ -1,9 +1,27 @@ import { isComputeSiteType } from "./compute-site-types.js"; +import { + deleteCachedAsset, + getCachedAssetMeta, + putCachedAssetBlob, + putCachedAssetMeta, + readCachedAssetBlob, +} from "./asset-swr-cache.js"; + // Optional imagery belongs to card selection, never to the animation loop. -const ENDPOINT = "/api/v1/earth/card-images/resolve"; +const RESOLVE_ENDPOINT = "/api/v1/earth/card-images/resolve"; +const FINGERPRINT_ENDPOINT = "/api/v1/earth/card-images/fingerprint"; +const CARD_CACHE_BUCKET = "card-images"; +const GLOBAL_REVISION_KEY = "__global_revision__"; +const GLOBAL_REVISION_TTL_MS = 0; export const CARD_IMAGE_REVISION_KEY = "planet.earth.card-images.revision"; -const cache = new Map(); +const memoryResolveCache = new Map(); const presenters = new Set(); +let globalRevisionState = { revision: "", checkedAt: 0, inflight: null }; + +export function _resetCardImagesRuntimeForTests() { + memoryResolveCache.clear(); + globalRevisionState = { revision: "", checkedAt: 0, inflight: null }; +} export function cardImageIdentity(type, data) { if (type === "satellite" && data?.norad_id != null) return {entity_type:"satellite",entity_id:String(data.norad_id)}; @@ -22,21 +40,82 @@ export function cardImageIdentity(type, data) { return null; } +function identityCacheKey(identity, size) { + return `${identity.entity_type}:${identity.entity_id}:${size}`; +} + +async function checkGlobalRevision(fetchImpl = globalThis.fetch?.bind(globalThis), { force = false } = {}) { + const now = Date.now(); + if (!force && globalRevisionState.revision && now - globalRevisionState.checkedAt < GLOBAL_REVISION_TTL_MS) { + return globalRevisionState.revision; + } + if (globalRevisionState.inflight) return globalRevisionState.inflight; + globalRevisionState.inflight = (async () => { + const controller = typeof AbortController !== "undefined" ? new AbortController() : null; + const timer = controller ? setTimeout(() => controller.abort(), 5000) : null; + try { + const cachedGlobal = await getCachedAssetMeta(CARD_CACHE_BUCKET, GLOBAL_REVISION_KEY); + const headers = cachedGlobal?.etag ? { "If-None-Match": cachedGlobal.etag } : {}; + const resp = await fetchImpl(FINGERPRINT_ENDPOINT, { headers, signal: controller?.signal }); + if (resp.status === 304 && cachedGlobal?.revision) { + globalRevisionState = { revision: cachedGlobal.revision, checkedAt: Date.now(), inflight: null }; + return cachedGlobal.revision; + } + if (!resp.ok) throw new Error(`Fingerprint check failed: ${resp.status}`); + const data = await resp.json(); + const rev = String(data?.revision || ""); + const etag = resp.headers.get("etag") || ""; + await putCachedAssetMeta(CARD_CACHE_BUCKET, GLOBAL_REVISION_KEY, { revision: rev, etag }); + globalRevisionState = { revision: rev, checkedAt: Date.now(), inflight: null }; + return rev; + } catch { + globalRevisionState.inflight = null; + return globalRevisionState.revision || ""; + } finally { + if (timer) clearTimeout(timer); + } + })(); + return globalRevisionState.inflight; +} + +async function fetchResolveMetadata(identity, cachedFingerprint = "", fetchImpl = globalThis.fetch?.bind(globalThis)) { + const controller = typeof AbortController !== "undefined" ? new AbortController() : null; + const timer = controller ? setTimeout(() => controller.abort(), 7000) : null; + try { + const headers = cachedFingerprint ? { "If-None-Match": `"${cachedFingerprint}"` } : {}; + const response = await fetchImpl(`${RESOLVE_ENDPOINT}?${new URLSearchParams(identity)}`, { + headers, + signal: controller?.signal, + }); + if (response.status === 304) { + return { notModified: true, asset: null, fingerprint: cachedFingerprint, revision: "" }; + } + if (response.status === 404) { + return { notModified: false, asset: null, fingerprint: "", revision: "" }; + } + if (!response.ok) { + throw new Error(`Card image lookup failed: ${response.status}`); + } + const payload = await response.json(); + return { + notModified: false, + asset: payload.image || null, + fingerprint: String(payload.fingerprint || response.headers.get("etag")?.replace(/"/g, "") || ""), + revision: String(payload.revision || ""), + }; + } finally { + if (timer) clearTimeout(timer); + } +} + async function resolveCardImage(identity) { const key = `${identity.entity_type}:${identity.entity_id}`; - const existing = cache.get(key); + const existing = memoryResolveCache.get(key); if (existing && existing.expires > Date.now()) return existing.promise; - const controller = new AbortController(); - const timeout = setTimeout(() => controller.abort(), 7000); - const promise = fetch(`${ENDPOINT}?${new URLSearchParams(identity)}`, {signal:controller.signal}) - .then(async response => { - if (response.status === 404) return null; - if (!response.ok) throw new Error(`Card image lookup failed: ${response.status}`); - return (await response.json()).image; - }).finally(() => clearTimeout(timeout)); - cache.set(key,{promise,expires:Date.now()+30000}); - if (cache.size > 100) cache.delete(cache.keys().next().value); - try {return await promise;} catch(error) {cache.delete(key);throw error;} + const promise = fetchResolveMetadata(identity, "").then((res) => res.asset); + memoryResolveCache.set(key, { promise, expires: Date.now() + 30000 }); + if (memoryResolveCache.size > 100) memoryResolveCache.delete(memoryResolveCache.keys().next().value); + try { return await promise; } catch (error) { memoryResolveCache.delete(key); throw error; } } function decodeImage(url) { @@ -46,54 +125,258 @@ function decodeImage(url) { return image.decode(); } -export function createCardImagePresenter({layer,image,credit,resolve=resolveCardImage,decode=decodeImage,getWidth=()=>640,onError=error=>console.warn("Card image unavailable",error)}) { - let revision=0, identity=null; - const clear=()=>{ - layer.hidden=true;layer.classList.remove("is-loaded"); - image.removeAttribute("src");credit.hidden=true;credit.removeAttribute("href"); - }; - async function show(next) { - const token=++revision;identity=next;clear(); - if (!next) return; - try { - const asset=await resolve(next); - if (token!==revision || !asset) return; - const size=getWidth()<=640 ? "640" : "1280"; - const url=asset.variants?.[size] || asset.url; - await decode(url); - if(token!==revision) return; - image.src=url;image.style.objectPosition=`${asset.focus_x ?? 50}% ${asset.focus_y ?? 50}%`; - layer.hidden=false;layer.classList.add("is-loaded"); - const link=asset.source_url || asset.license_url; - if(link) { - credit.href=link;credit.title=[asset.title,asset.credit,asset.license].filter(Boolean).join(" · "); - credit.setAttribute("aria-label",credit.title);credit.hidden=false; - } - } catch(error) {if(token===revision) {clear();onError(error);}} +function selectVariantUrl(asset, size) { + return asset?.variants?.[size] || asset?.url || ""; +} + +function applyCredit(credit, asset) { + const link = asset?.source_url || asset?.license_url; + if (link) { + credit.href = link; + credit.title = [asset.title, asset.credit, asset.license].filter(Boolean).join(" · "); + credit.setAttribute("aria-label", credit.title); + credit.hidden = false; + } else { + credit.hidden = true; + credit.removeAttribute("href"); } - return {show,refresh:()=>show(identity),hide:()=>{revision++;identity=null;clear();}}; +} + +export function createCardImagePresenter({ + layer, + image, + credit, + resolve, + decode = decodeImage, + fetchImpl = globalThis.fetch?.bind(globalThis), + getWidth = () => 640, + onError = (error) => console.warn("Card image unavailable", error), +}) { + let revision = 0; + let identity = null; + let activeObjectUrl = ""; + + const revokeActiveBlob = () => { + if (activeObjectUrl && typeof URL !== "undefined" && typeof URL.revokeObjectURL === "function") { + try { + URL.revokeObjectURL(activeObjectUrl); + } catch { + // Ignore revoke errors. + } + } + activeObjectUrl = ""; + }; + + const clear = () => { + layer.hidden = true; + layer.classList.remove("is-loaded"); + image.removeAttribute("src"); + credit.hidden = true; + credit.removeAttribute("href"); + revokeActiveBlob(); + }; + + const renderAssetAtUrl = async (asset, displayUrl, nextObjectUrl, token) => { + await decode(displayUrl); + if (token !== revision) { + if (nextObjectUrl && typeof URL !== "undefined" && typeof URL.revokeObjectURL === "function") { + try { URL.revokeObjectURL(nextObjectUrl); } catch {} + } + return false; + } + const prevObjectUrl = activeObjectUrl; + activeObjectUrl = nextObjectUrl || ""; + image.src = displayUrl; + image.style.objectPosition = `${asset.focus_x ?? 50}% ${asset.focus_y ?? 50}%`; + layer.hidden = false; + layer.classList.add("is-loaded"); + applyCredit(credit, asset); + if (prevObjectUrl && prevObjectUrl !== activeObjectUrl && typeof URL !== "undefined" && typeof URL.revokeObjectURL === "function") { + try { URL.revokeObjectURL(prevObjectUrl); } catch {} + } + return true; + }; + + const showWithCustomResolver = async (next, token) => { + try { + const asset = await resolve(next); + if (token !== revision || !asset) return; + const size = getWidth() <= 640 ? "640" : "1280"; + const url = selectVariantUrl(asset, size); + await renderAssetAtUrl(asset, url, "", token); + } catch (error) { + if (token === revision) { + clear(); + onError(error); + } + } + }; + + const downloadAndCacheBlob = async (cacheKey, imageUrl, metaPatch) => { + const resp = await fetchImpl(imageUrl); + if (!resp.ok) throw new Error(`Card image download failed: ${resp.status}`); + const blob = await resp.blob(); + await putCachedAssetBlob(CARD_CACHE_BUCKET, cacheKey, blob, metaPatch); + return blob; + }; + + const toDisplayUrl = (blob, fallbackUrl) => { + if (blob && typeof URL !== "undefined" && typeof URL.createObjectURL === "function") { + const objUrl = URL.createObjectURL(blob); + return { displayUrl: objUrl, objectUrl: objUrl }; + } + return { displayUrl: fallbackUrl, objectUrl: "" }; + }; + + async function show(next) { + const token = ++revision; + identity = next; + clear(); + if (!next) return; + + if (typeof resolve === "function") { + await showWithCustomResolver(next, token); + return; + } + + const size = getWidth() <= 640 ? "640" : "1280"; + const key = identityCacheKey(next, size); + const cachedMeta = await getCachedAssetMeta(CARD_CACHE_BUCKET, key); + const cachedBlob = cachedMeta?.asset ? await readCachedAssetBlob(CARD_CACHE_BUCKET, key) : null; + let hasDisplayedCached = false; + + if (cachedMeta?.asset && cachedBlob) { + try { + const { displayUrl, objectUrl } = toDisplayUrl(cachedBlob, cachedMeta.imageUrl || selectVariantUrl(cachedMeta.asset, size)); + hasDisplayedCached = await renderAssetAtUrl(cachedMeta.asset, displayUrl, objectUrl, token); + } catch { + hasDisplayedCached = false; + } + } + if (token !== revision) return; + + try { + const globalRev = await checkGlobalRevision(fetchImpl); + if (token !== revision) return; + if ( + hasDisplayedCached && + globalRev && + cachedMeta?.revision === globalRev && + cachedMeta?.fingerprint + ) { + return; + } + + const cachedFp = cachedMeta?.fingerprint || ""; + const res = await fetchResolveMetadata(next, cachedFp, fetchImpl); + if (token !== revision) return; + + if (res.notModified) { + if (cachedMeta) { + await putCachedAssetMeta(CARD_CACHE_BUCKET, key, { + revision: globalRev || cachedMeta.revision, + lastCheckedAt: Date.now(), + }); + } + return; + } + + if (!res.asset) { + if (cachedMeta) await deleteCachedAsset(CARD_CACHE_BUCKET, key); + if (hasDisplayedCached) clear(); + return; + } + + const targetUrl = selectVariantUrl(res.asset, size); + const sameFingerprint = Boolean(cachedFp && res.fingerprint && cachedFp === res.fingerprint); + const sameUrl = Boolean(cachedMeta?.imageUrl && cachedMeta.imageUrl === targetUrl); + if (hasDisplayedCached && sameFingerprint && sameUrl) { + await putCachedAssetMeta(CARD_CACHE_BUCKET, key, { + asset: res.asset, + revision: res.revision || globalRev, + lastCheckedAt: Date.now(), + }); + applyCredit(credit, res.asset); + image.style.objectPosition = `${res.asset.focus_x ?? 50}% ${res.asset.focus_y ?? 50}%`; + return; + } + + const nextBlob = await downloadAndCacheBlob(key, targetUrl, { + url: targetUrl, + imageUrl: targetUrl, + fingerprint: res.fingerprint, + revision: res.revision || globalRev, + asset: res.asset, + lastCheckedAt: Date.now(), + }); + if (token !== revision) return; + const { displayUrl, objectUrl } = toDisplayUrl(nextBlob, targetUrl); + await renderAssetAtUrl(res.asset, displayUrl, objectUrl, token); + } catch (error) { + if (token !== revision) return; + if (!hasDisplayedCached) { + clear(); + onError(error); + } + } + } + + return { + show, + refresh: () => show(identity), + hide: () => { + revision++; + identity = null; + clear(); + }, + }; } export function mountCardImage(content, header) { - const body=document.createElement("div");body.className="card-image-body"; - content.before(body);body.append(content);content.classList.add("card-image-data"); - const layer=document.createElement("div");layer.className="card-image-layer";layer.hidden=true; - layer.setAttribute("aria-hidden","true"); - const image=document.createElement("img");image.alt="";image.decoding="async";layer.append(image);body.prepend(layer); - const credit=document.createElement("a");credit.className="card-image-source hud-panel__action"; - credit.hidden=true;credit.target="_blank";credit.rel="noopener noreferrer"; - const icon=document.createElement("span");icon.className="material-symbols-rounded";icon.textContent="image";icon.setAttribute("aria-hidden","true");credit.append(icon); - if(header) { - const anchor=header.querySelector("#info-card-workbench, .info-card-close"); - if(anchor?.parentNode) anchor.parentNode.insertBefore(credit,anchor); + const body = document.createElement("div"); + body.className = "card-image-body"; + content.before(body); + body.append(content); + content.classList.add("card-image-data"); + const layer = document.createElement("div"); + layer.className = "card-image-layer"; + layer.hidden = true; + layer.setAttribute("aria-hidden", "true"); + const image = document.createElement("img"); + image.alt = ""; + image.decoding = "async"; + layer.append(image); + body.prepend(layer); + const credit = document.createElement("a"); + credit.className = "card-image-source hud-panel__action"; + credit.hidden = true; + credit.target = "_blank"; + credit.rel = "noopener noreferrer"; + const icon = document.createElement("span"); + icon.className = "material-symbols-rounded"; + icon.textContent = "image"; + icon.setAttribute("aria-hidden", "true"); + credit.append(icon); + if (header) { + const anchor = header.querySelector("#info-card-workbench, .info-card-close"); + if (anchor?.parentNode) anchor.parentNode.insertBefore(credit, anchor); else header.appendChild(credit); } - const presenter=createCardImagePresenter({layer,image,credit,getWidth:()=>body.clientWidth*(window.devicePixelRatio||1)}); + const presenter = createCardImagePresenter({ + layer, + image, + credit, + getWidth: () => body.clientWidth * (window.devicePixelRatio || 1), + }); presenters.add(presenter); return presenter; } -if (typeof window !== "undefined" && typeof window.addEventListener === "function") window.addEventListener("storage",event=>{ - if(event.key!==CARD_IMAGE_REVISION_KEY) return; - cache.clear();presenters.forEach(presenter=>void presenter.refresh()); -}); +if (typeof window !== "undefined" && typeof window.addEventListener === "function") { + window.addEventListener("storage", (event) => { + if (event.key !== CARD_IMAGE_REVISION_KEY) return; + memoryResolveCache.clear(); + globalRevisionState = { revision: "", checkedAt: 0, inflight: null }; + presenters.forEach((presenter) => void presenter.refresh()); + }); +} diff --git a/frontend/public/earth/js/card-images.test.js b/frontend/public/earth/js/card-images.test.js index 5d7cbea5..5a64650a 100644 --- a/frontend/public/earth/js/card-images.test.js +++ b/frontend/public/earth/js/card-images.test.js @@ -1,10 +1,12 @@ -import {expect,test} from "bun:test"; -import {cardImageIdentity,createCardImagePresenter} from "./card-images.js"; +import {beforeEach,expect,test} from "bun:test"; +import {_resetMemoryCacheForTests} from "./asset-swr-cache.js"; +import {_resetCardImagesRuntimeForTests,cardImageIdentity,createCardImagePresenter} from "./card-images.js"; const deferred=()=>{let resolve,reject;const promise=new Promise((a,b)=>{resolve=a;reject=b;});return {promise,resolve,reject};}; -function fixture(resolve,decode=async()=>{}) { +beforeEach(()=>{_resetMemoryCacheForTests();_resetCardImagesRuntimeForTests();}); +function fixture(resolve,decode=async()=>{},extra={}) { const node=()=>({hidden:true,style:{},classList:{add(){},remove(){}},removeAttribute(key){delete this[key];},setAttribute(key,value){this[key]=value;}}); const layer=node(),image=node(),credit=node(),errors=[]; - return {layer,image,credit,errors,presenter:createCardImagePresenter({layer,image,credit,resolve,decode,onError:e=>errors.push(e)})}; + return {layer,image,credit,errors,presenter:createCardImagePresenter({layer,image,credit,resolve,decode,onError:e=>errors.push(e),...extra})}; } test("stable identities never use collected database row IDs",()=>{ expect(cardImageIdentity("satellite",{id:1,norad_id:123})).toEqual({entity_type:"satellite",entity_id:"123"}); @@ -28,3 +30,46 @@ test("closing while decoding and broken files cannot reveal a stale layer",async const broken=fixture(async()=>({url:"bad.jpg"}),async()=>{throw new Error("decode failed");}); await broken.presenter.show({id:"a"});expect(broken.layer.hidden).toBe(true);expect(broken.errors).toHaveLength(1); }); +test("SWR presenter renders cached image at 0ms, skips binary fetch on 304, swaps on fingerprint change, and preserves stale image offline",async()=>{ + let revision="rev-1",fingerprint="fp-1",imageUrl="/earth/assets/cards/previews/v1.webp",offline=false,imageFetches=0,resolveFetches=0; + const decodedUrls=[]; + const fetchMock=async(url,init)=>{ + if (offline) throw new Error("network down"); + if (url.startsWith("/api/v1/earth/card-images/fingerprint")) { + return new Response(JSON.stringify({revision}),{status:200,headers:{ETag:`"${revision}"`}}); + } + if (url.startsWith("/api/v1/earth/card-images/resolve")) { + resolveFetches+=1; + if (init?.headers?.["If-None-Match"]===`"${fingerprint}"`) return new Response(null,{status:304,headers:{ETag:`"${fingerprint}"`}}); + return new Response(JSON.stringify({revision,fingerprint,suppressed:false,image:{id:"img",title:"T",url:imageUrl,variants:{"640":imageUrl}}}),{status:200,headers:{ETag:`"${fingerprint}"`}}); + } + imageFetches+=1; + return new Response(new Blob([`bytes:${imageUrl}`],{type:"image/webp"}),{status:200}); + }; + const identity={entity_type:"satellite",entity_id:"123"}; + const f=fixture(undefined,async(u)=>{decodedUrls.push(u);},{fetchImpl:fetchMock}); + await f.presenter.show(identity); + expect(f.layer.hidden).toBe(false);expect(imageFetches).toBe(1);expect(resolveFetches).toBe(1); + + // Warm revisit within global revision TTL: zero /resolve or image binary calls + await f.presenter.show(identity); + expect(f.layer.hidden).toBe(false);expect(imageFetches).toBe(1);expect(resolveFetches).toBe(1); + + // Revision bumps with unchanged asset -> /resolve returns 304 -> zero image binary download + _resetCardImagesRuntimeForTests(); + revision="rev-2"; + await f.presenter.show(identity); + expect(resolveFetches).toBe(2);expect(imageFetches).toBe(1); + + // Fingerprint changes -> smooth swap to new image + _resetCardImagesRuntimeForTests(); + revision="rev-3";fingerprint="fp-2";imageUrl="/earth/assets/cards/previews/v2.webp"; + await f.presenter.show(identity); + expect(resolveFetches).toBe(3);expect(imageFetches).toBe(2);expect(decodedUrls.length).toBeGreaterThanOrEqual(4); + + // Offline preserves stale displayed image with zero error escalation + _resetCardImagesRuntimeForTests(); + offline=true; + await f.presenter.show(identity); + expect(f.layer.hidden).toBe(false);expect(f.errors).toHaveLength(0); +}); diff --git a/frontend/public/earth/js/cases-hud.js b/frontend/public/earth/js/cases-hud.js new file mode 100644 index 00000000..c8ec95b9 --- /dev/null +++ b/frontend/public/earth/js/cases-hud.js @@ -0,0 +1,270 @@ +/** + * §4.3 Investigation Case Board HUD + * Manage investigation cases, attach globe/incident evidence, freeze SHA-256 versions, + * export Markdown bundles, and invoke Print-CSS PDF generation. + */ + +import { getEarthLocale } from "./i18n.js"; +import { createHUDPanel } from "./hud-panels.js"; +import { sharedHudFocusStack } from "./hud-focus-stack.js"; +import { fetchAdminWriteJson, readStoredAdminAuthState } from "./admin-write-auth.js"; +import { isEditableRole } from "./geofence-editor.js"; + +const t = (zh, en) => (getEarthLocale() === "en-US" ? en : zh); + +function escapeHtml(text) { + return String(text ?? "") + .replaceAll("&", "&") + .replaceAll("<", "<") + .replaceAll(">", ">") + .replaceAll('"', """); +} + +async function fetchEarthJson(url) { + const { token } = readStoredAdminAuthState(); + const headers = token ? { Authorization: `Bearer ${token}` } : {}; + const resp = await fetch(url, { credentials: "same-origin", headers }); + if (!resp.ok) throw new Error(`HTTP ${resp.status}`); + return resp.json(); +} + +export function initCasesHud({ + rootParent = typeof document !== "undefined" ? document.body : null, + onFocusObject = null, + onStatus = null, +} = {}) { + const panelEl = document.createElement("aside"); + panelEl.id = "cases-board-hud"; + panelEl.className = "hud-panel cases-hud-panel hud-panel-draggable"; + panelEl.hidden = true; + panelEl.setAttribute("role", "dialog"); + panelEl.setAttribute("aria-modal", "false"); + panelEl.setAttribute("aria-label", t("调查卷宗工作台", "Investigation Cases")); + + panelEl.innerHTML = ` +
+
+ +

${escapeHtml(t("调查卷宗工作台", "Investigation Cases"))}

+
+
+ + +
+
+
+ + +
+
+ `; + + rootParent?.append?.(panelEl); + const hudPanel = createHUDPanel({ + panel: panelEl, + header: ".hud-panel__header", + body: "#cases-hud-body", + }); + sharedHudFocusStack.register(panelEl, { focus: false }); + + const bodyEl = panelEl.querySelector("#cases-hud-body"); + const createBar = panelEl.querySelector("#cases-create-bar"); + const titleInput = panelEl.querySelector("#case-title-input"); + const createBtn = panelEl.querySelector("#case-create-btn"); + + let casesList = []; + let activeDetail = null; + + const render = () => { + const editable = isEditableRole(readStoredAdminAuthState()?.user?.role); + if (createBar) createBar.hidden = !editable; + if (!bodyEl) return; + + const listHtml = casesList.length + ? casesList + .map( + (c) => ` +
`, + ) + .join("") + : `

${escapeHtml(t("暂无调查卷宗,请新建或从对象详情“加入卷宗”", "No cases yet"))}

`; + + let detailHtml = ""; + if (activeDetail?.case) { + const c = activeDetail.case; + const items = activeDetail.items || []; + const versions = activeDetail.versions || []; + const latestHash = versions[0]?.content_sha256 || versions[0]?.snapshot_hash || ""; + detailHtml = ` +
+
+ ${escapeHtml(c.title)} (v${c.current_version || 1}) + ${escapeHtml(c.status)} +
+ ${latestHash ? `

SHA-256: ${escapeHtml(latestHash.slice(0, 16))}…

` : ""} +
+ ${ + editable + ? `` + : "" + } + +
+
+ ${ + items.length + ? items + .map( + (it) => `
+ ${escapeHtml(it.item_type)} + +
`, + ) + .join("") + : `

${escapeHtml(t("尚无挂载证据对象", "No evidence items attached yet"))}

` + } +
+
`; + } + + bodyEl.innerHTML = detailHtml + listHtml; + }; + + const refresh = async () => { + const payload = await fetchEarthJson("/api/v1/cases?limit=50"); + casesList = Array.isArray(payload?.items) ? payload.items : []; + if (activeDetail?.case?.id) { + activeDetail = await fetchEarthJson(`/api/v1/cases/${activeDetail.case.id}`).catch(() => activeDetail); + } + render(); + return casesList; + }; + + const openCase = async (caseId) => { + activeDetail = await fetchEarthJson(`/api/v1/cases/${caseId}`); + render(); + }; + + const attachObject = async ({ objectId, label = "", summary = "" }) => { + if (!objectId) return null; + if (!casesList.length) await refresh().catch(() => {}); + let targetId = activeDetail?.case?.id || casesList[0]?.id; + if (!targetId) { + const resp = await fetchAdminWriteJson("/api/v1/cases", { + title: t("地球研判工作卷宗", "Earth Situational Case"), + summary: summary || "", + is_shared: true, + }); + if (!resp.ok) throw new Error(await resp.text()); + const created = await resp.json(); + targetId = created.id; + } + const resp = await fetchAdminWriteJson(`/api/v1/cases/${targetId}/items`, { + item_type: "object", + ref_id: objectId, + payload: { label: label || objectId, summary }, + }); + if (!resp.ok) throw new Error(await resp.text()); + await openCase(targetId); + panelEl.hidden = false; + sharedHudFocusStack.focus(panelEl); + onStatus?.(t("已加入调查卷宗", "Added to investigation case"), "success"); + return resp.json(); + }; + + panelEl.querySelector("#cases-close-btn")?.addEventListener("click", () => { + panelEl.hidden = true; + }); + panelEl.querySelector("#cases-refresh-btn")?.addEventListener("click", () => { + void refresh().catch((err) => onStatus?.(err?.message || String(err), "error")); + }); + + createBtn?.addEventListener("click", async () => { + const title = String(titleInput?.value || "").trim(); + if (!title) return; + try { + const resp = await fetchAdminWriteJson("/api/v1/cases", { + title, + summary: "", + is_shared: true, + }); + if (!resp.ok) throw new Error(await resp.text()); + const created = await resp.json(); + if (titleInput) titleInput.value = ""; + await refresh(); + await openCase(created.id); + onStatus?.(t("调查卷宗已创建", "Case created"), "success"); + } catch (err) { + onStatus?.(err?.message || String(err), "error"); + } + }); + + bodyEl?.addEventListener("click", async (event) => { + const el = event?.target instanceof HTMLElement ? event.target : null; + if (!el) return; + const openBtn = el.closest("[data-case-open]"); + if (openBtn instanceof HTMLElement) { + await openCase(Number(openBtn.dataset.caseOpen)).catch((e) => onStatus?.(e.message, "error")); + return; + } + const freezeBtn = el.closest("[data-case-freeze]"); + if (freezeBtn instanceof HTMLElement) { + try { + const cid = Number(freezeBtn.dataset.caseFreeze); + const resp = await fetchAdminWriteJson(`/api/v1/cases/${cid}/freeze`, {}); + if (!resp.ok) throw new Error(await resp.text()); + await refresh(); + onStatus?.(t("卷宗版本已不可变固化", "Case snapshot frozen"), "success"); + } catch (err) { + onStatus?.(err?.message || String(err), "error"); + } + return; + } + const printBtn = el.closest("[data-case-print]"); + if (printBtn instanceof HTMLElement) { + panelEl.classList.add("print-active"); + window.print?.(); + setTimeout(() => panelEl.classList.remove("print-active"), 500); + return; + } + const focusBtn = el.closest("[data-focus-object]"); + if (focusBtn instanceof HTMLElement) { + onFocusObject?.(focusBtn.dataset.focusObject || ""); + } + }); + + const open = async () => { + panelEl.hidden = false; + sharedHudFocusStack.focus(panelEl); + await refresh().catch((err) => onStatus?.(err?.message || String(err), "error")); + }; + + return { + open, + close: () => { + panelEl.hidden = true; + }, + refresh, + openCase, + attachObject, + getCases: () => casesList, + destroy: () => { + hudPanel?.destroy?.(); + panelEl.remove(); + }, + }; +} diff --git a/frontend/public/earth/js/cloud-map.js b/frontend/public/earth/js/cloud-map.js index 4fb22685..0cdd7aaf 100644 --- a/frontend/public/earth/js/cloud-map.js +++ b/frontend/public/earth/js/cloud-map.js @@ -4,8 +4,11 @@ import * as THREE from "three"; import { CLOUD_LAYER_CONFIG } from "./constants.js"; import { configureColorTexture } from "./texture-colors.js"; import { earthTextureImages } from "./earth-texture-image.js"; +import { getCachedAssetMeta, putCachedAssetJson, readCachedAssetJson } from "./asset-swr-cache.js"; const CLOUD_META_ENDPOINT = "/api/v1/earth/clouds/meta"; +const CLOUD_CACHE_BUCKET = "clouds"; +const CLOUD_META_CACHE_KEY = "latest-meta"; const CLOUD_BROADCAST_CHANNEL = "planet-earth-cloud-map"; const META_TIMEOUT_MS = 3500; const CROSSFADE_DURATION_MS = 1800; @@ -438,6 +441,40 @@ export async function refreshLiveCloudMap({ forceReload = false } = {}) { let nextFlowMaxUv = 0; const isFirstLoad = !(_getMaterialsCallback?.()?.[0]?.uniforms?.uCloudMap?.value); + // Boot-time SWR: if realtime first load has a cached previous cloud frame + meta, + // render the cached frame immediately (0ms) before waiting on online /clouds/meta. + if (isFirstLoad && _mode === "realtime") { + try { + const cachedMeta = await readCachedAssetJson(CLOUD_CACHE_BUCKET, CLOUD_META_CACHE_KEY); + if (cachedMeta?.enabled && cachedMeta?.mode === "realtime" && cachedMeta?.image_url) { + const [cachedTex, cachedVis] = await Promise.all([ + decodeCloudTexture(cachedMeta.image_url).catch(() => null), + cachedMeta.geocolor_enabled !== false && cachedMeta.visual_url + ? decodeAuxTexture(cachedMeta.visual_url, { srgb: false }).catch(() => null) + : Promise.resolve(null), + ]); + if (cachedTex) { + _lastMeta = cachedMeta; + _activeVersion = cachedMeta.version || cachedMeta.image_url; + _activeImageUrl = cachedMeta.image_url; + _visualUrl = cachedMeta.visual_url || null; + _flowUrl = cachedMeta.flow_url || null; + transitionCloudTexture(cachedTex, { + crossFadeMs: 0, + visualTexture: cachedVis, + flowTexture: null, + flowMaxUv: 0, + }); + emitCloudMapStatus(); + } + } + } catch { + // Ignore corrupt local cloud cache and fall through to online fetch. + } + } + + const hadRenderedFrame = Boolean(_getMaterialsCallback?.()?.[0]?.uniforms?.uCloudMap?.value); + if (_mode === "realtime") { const meta = await fetchCloudMetaSafe(); if (meta) { @@ -455,13 +492,21 @@ export async function refreshLiveCloudMap({ forceReload = false } = {}) { nextVisualUrl = meta.geocolor_enabled !== false ? meta.visual_url || null : null; nextFlowUrl = meta.optical_flow_enabled !== false ? meta.flow_url || null : null; nextFlowMaxUv = Number(meta.flow_max_uv || 0); + void putCachedAssetJson(CLOUD_CACHE_BUCKET, CLOUD_META_CACHE_KEY, meta, { + url: CLOUD_META_ENDPOINT, + fingerprint: nextVersion, + }); } + } else if (hadRenderedFrame) { + syncTimelapseLoop(); + emitCloudMapStatus(); + return _getMaterialsCallback?.()?.[0]?.uniforms?.uCloudMap?.value || null; } } if ( !forceReload - && !isFirstLoad + && hadRenderedFrame && nextVersion === _activeVersion && targetUrl === _activeImageUrl && nextVisualUrl === _visualUrl diff --git a/frontend/public/earth/js/compute-centers.js b/frontend/public/earth/js/compute-centers.js index 724ca049..67f54651 100644 --- a/frontend/public/earth/js/compute-centers.js +++ b/frontend/public/earth/js/compute-centers.js @@ -11,6 +11,7 @@ import { import { latLonToVector3 } from "./utils.js"; import { createSurfaceRibbonGeometry, createSurfaceRibbonMaterial } from "./surface-ribbon.js"; import { fetchAdminWriteJson } from "./admin-write-auth.js"; +import { fetchJsonSwr } from "./asset-swr-cache.js"; const COMPUTE_CENTER_RENDER_ORDER = 4.5; const COMPUTE_CENTER_POINT_SIZE = 36; @@ -577,30 +578,7 @@ export function getShowComputeCenters() { return showComputeCenters; } -export async function loadComputeCenters(_scene, earth) { - const generation = ++loadGeneration; - loadController?.abort(); - loadController = new AbortController(); - const query = new URLSearchParams(computeTopicQuery || {}); - if (!query.get("year")) query.delete("year"); - const url = computeTopicQuery ? `/api/v1/data-products/compute/facilities?${query}` : PATHS.computeCentersApi; - const separator = url.includes("?") ? "&" : "?"; - let response; - try { - response = await fetch( - `${url}${separator}_=${Date.now()}`, - { cache: "no-store", signal: loadController.signal }, - ); - } catch (error) { - if (error?.name === "AbortError") { - return { count: 0, stale: true, aborted: true }; - } - throw error; - } - if (!response.ok) { - throw new Error(`Compute centers HTTP ${response.status}`); - } - const payload = await response.json(); +async function applyComputeCentersPayload(earth, payload, generation, hasTopicQuery) { const features = Array.isArray(payload?.features) ? payload.features : []; const unresolved = Array.isArray(payload?.unresolved) ? payload.unresolved : []; @@ -624,9 +602,9 @@ export async function loadComputeCenters(_scene, earth) { computeCenterIconLayer.attach(earth); computeCenterIconLayer.setVisible(showComputeCenters); - if (computeTopicQuery) window.dispatchEvent(new CustomEvent("earth:compute-topic-data", { detail: payload })); + if (hasTopicQuery) window.dispatchEvent(new CustomEvent("earth:compute-topic-data", { detail: payload })); return { - topicPayload: computeTopicQuery ? payload : null, + topicPayload: hasTopicQuery ? payload : null, totalCount: getComputeCenterCount(), supercomputerCount: typeCounts.supercomputer, gpuClusterCount: typeCounts.gpu_cluster, @@ -637,6 +615,48 @@ export async function loadComputeCenters(_scene, earth) { }; } +export async function loadComputeCenters(_scene, earth) { + const generation = ++loadGeneration; + loadController?.abort(); + loadController = new AbortController(); + const hasTopicQuery = Boolean(computeTopicQuery); + if (!hasTopicQuery) { + const { data } = await fetchJsonSwr({ + bucket: "geo", + key: "compute-centers", + url: PATHS.computeCentersApi, + onFresh: (fresh) => { + if (generation === loadGeneration) { + void applyComputeCentersPayload(earth, fresh, generation, false).catch(() => {}); + } + }, + }); + return applyComputeCentersPayload(earth, data, generation, false); + } + + const query = new URLSearchParams(computeTopicQuery || {}); + if (!query.get("year")) query.delete("year"); + const url = `/api/v1/data-products/compute/facilities?${query}`; + const separator = url.includes("?") ? "&" : "?"; + let response; + try { + response = await fetch( + `${url}${separator}_=${Date.now()}`, + { cache: "no-store", signal: loadController.signal }, + ); + } catch (error) { + if (error?.name === "AbortError") { + return { count: 0, stale: true, aborted: true }; + } + throw error; + } + if (!response.ok) { + throw new Error(`Compute centers HTTP ${response.status}`); + } + const payload = await response.json(); + return applyComputeCentersPayload(earth, payload, generation, true); +} + const NATIONAL_HUB_COLORS = { eastern_demand: "#a855f7", western_green: "#14b8a6", diff --git a/frontend/public/earth/js/compute-topic.js b/frontend/public/earth/js/compute-topic.js index 58dadb6e..a6b24d2f 100644 --- a/frontend/public/earth/js/compute-topic.js +++ b/frontend/public/earth/js/compute-topic.js @@ -1890,6 +1890,16 @@ export function initComputeTopic({ load({ refreshMap: false }); } }, + setReplayAsOfRevision(asOfRev, cursorIso) { + const nextPublishId = asOfRev?.publish_id || ""; + const nextAsOf = nextPublishId ? "" : (cursorIso || ""); + if (selectedPublishId === nextPublishId && asOf === nextAsOf) return; + selectedPublishId = nextPublishId; + asOf = nextAsOf; + if (cardsEnabled || configVisible) { + load({ refreshMap: false }); + } + }, getState() { return { cardsEnabled, diff --git a/frontend/public/earth/js/constants.js b/frontend/public/earth/js/constants.js index 28a5e52b..5255f80e 100644 --- a/frontend/public/earth/js/constants.js +++ b/frontend/public/earth/js/constants.js @@ -26,6 +26,9 @@ export const CRUISE_MODULES = { NEWS: "news", COMPUTE_CENTERS: "computeCenters", VESSELS: "vessels", + AIRCRAFT: "aircraft", + GPS_JAMMING: "gpsJamming", + DISASTERS: "disasters", CABLES: "cables", SATELLITES: "satellites", }; @@ -228,11 +231,18 @@ export const COUNTRY_BOUNDARY_CONFIG = { tilePrefetchRing: 1, tileDebounceMs: 180, tileCacheLimit: 640, - // Admin-1 (province / state) lines fade in below the national borders. - admin1MinViewZoom: 2.0, - admin1FullViewZoom: 2.8, - admin1LineColor: 0x9fd0ff, - admin1LineOpacity: 0.26, + // Admin-1 (province / state) lines fade in smoothly as a subtle slate-white dashed + // ribbon with dark casing so borders remain legible on bright/dark imagery without + // overpowering national borders. + admin1MinViewZoom: 1.85, + admin1FullViewZoom: 2.6, + admin1LineColor: 0xd8e8f8, + admin1LineOpacity: 0.46, + admin1CasingColor: 0x050a14, + admin1CasingOpacity: 0.36, + admin1DashPx: 6.0, + admin1GapPx: 4.0, + admin1HalfWidthPx: 1.65, // Keep boundary/coastline strokes on the same shell as the high-res earth // texture overlay. A lower or higher radius creates visible parallax while // the globe rotates. @@ -285,6 +295,11 @@ export const PATHS = { interactablesApi: '/api/v1/interactables/geojson', vesselsApi: '/api/v1/vessels/snapshot', vesselTrackApi: (mmsi) => `/api/v1/visualization/vessels/${encodeURIComponent(mmsi)}/track`, + aircraftSnapshotApi: '/api/v1/aircraft/snapshot', + aircraftDetailApi: (icao24) => `/api/v1/aircraft/${encodeURIComponent(icao24)}`, + aircraftTrackApi: (icao24, hours = 3) => `/api/v1/aircraft/${encodeURIComponent(icao24)}/track?hours=${hours}`, + gpsJammingSnapshotApi: '/api/v1/gps-jamming/snapshot', + disastersSnapshotApi: '/api/v1/disasters/snapshot', bgpApi: '/api/v1/visualization/geo/bgp-anomalies', bgpIncidentsApi: '/api/v1/visualization/geo/bgp-incidents', bgpCollectorsApi: '/api/v1/visualization/geo/bgp-collectors', diff --git a/frontend/public/earth/js/controls.js b/frontend/public/earth/js/controls.js index 8859391d..1cd4bc89 100644 --- a/frontend/public/earth/js/controls.js +++ b/frontend/public/earth/js/controls.js @@ -8,6 +8,7 @@ import { bindToolbarHover } from "./toolbar-hover.js"; import { distanceForGlobeZoom, globeZoomForDistance, isGlobeWheelTarget } from "./globe-navigation.js"; import { EARTH_SETTINGS_STORAGE_KEY } from "./earth-settings-storage.js"; import { getCalloutLimits, setCalloutLimits } from "./callout-limits.js"; +import { clearLocalAssetCache, formatBytes, getLocalCacheStats } from "./asset-swr-cache.js"; // controls.js - Zoom, rotate and toggle controls import * as THREE from "three"; @@ -80,6 +81,16 @@ import { getSatellitesEnabled, setVesselsEnabled, getVesselsEnabled, + setAircraftEnabled, + getAircraftEnabled, + setGpsJammingEnabled, + getGpsJammingEnabled, + setDisastersEnabled, + getDisastersEnabled, + setGeofencesEnabled, + getGeofencesEnabled, + setFusionOverlaysEnabled, + getFusionOverlaysEnabled, } from "./main.js"; import { toggleTrails, @@ -113,6 +124,7 @@ import { getShowVessels, getVesselCount, } from "./vessels.js"; +import { getAircraftCount } from "./aircraft.js"; import { ensureTVPanelReady, getActiveTVTab, @@ -3881,6 +3893,123 @@ async function setVesselsLayerEnabled(button, enabled, { persist = true, silent } } +async function setAircraftLayerEnabled(button, enabled, { persist = true, silent = false } = {}) { + clearSelectionIfHiding(!enabled); + try { + if (enabled) { + setLayerButtonState(button, { active: false, loading: true, tooltip: "航空器加载中..." }); + } + await setAircraftEnabled(enabled, { suppressStatus: silent, suppressLoadingUi: silent }); + setLayerButtonState(button, { + active: enabled, + loading: false, + tooltip: enabled ? "隐藏航空器" : "显示航空器", + }); + setEarthStatValue("aircraft-count", `${getAircraftCount()} 架`); + syncMobileLayerCards(); + if (persist) persistEarthSettings(); + return enabled; + } catch (error) { + console.error("切换航空器显示失败:", error); + setLayerButtonState(button, { active: false, loading: false, tooltip: "显示航空器" }); + syncMobileLayerCards(); + if (persist) persistEarthSettings(); + return false; + } +} + +async function setGpsJammingLayerEnabled(button, enabled, { persist = true, silent = false } = {}) { + try { + if (enabled) { + setLayerButtonState(button, { active: false, loading: true, tooltip: "GPS 干扰加载中..." }); + } + await setGpsJammingEnabled(enabled, { suppressStatus: silent, suppressLoadingUi: silent }); + setLayerButtonState(button, { + active: enabled, + loading: false, + tooltip: enabled ? "隐藏 GPS 干扰" : "显示 GPS 干扰", + }); + syncMobileLayerCards(); + if (persist) persistEarthSettings(); + return enabled; + } catch (error) { + console.error("切换 GPS 干扰显示失败:", error); + setLayerButtonState(button, { active: false, loading: false, tooltip: "显示 GPS 干扰" }); + syncMobileLayerCards(); + if (persist) persistEarthSettings(); + return false; + } +} + +async function setDisastersLayerEnabled(button, enabled, { persist = true, silent = false } = {}) { + try { + if (enabled) { + setLayerButtonState(button, { active: false, loading: true, tooltip: "自然灾害加载中..." }); + } + await setDisastersEnabled(enabled, { suppressStatus: silent, suppressLoadingUi: silent }); + setLayerButtonState(button, { + active: enabled, + loading: false, + tooltip: enabled ? "隐藏自然灾害" : "显示自然灾害", + }); + syncMobileLayerCards(); + if (persist) persistEarthSettings(); + return enabled; + } catch (error) { + console.error("切换自然灾害显示失败:", error); + setLayerButtonState(button, { active: false, loading: false, tooltip: "显示自然灾害" }); + syncMobileLayerCards(); + if (persist) persistEarthSettings(); + return false; + } +} + +async function setGeofencesLayerEnabled(button, enabled, { persist = true, silent = false } = {}) { + try { + if (enabled) { + setLayerButtonState(button, { active: false, loading: true, tooltip: "电子围栏加载中..." }); + } + await setGeofencesEnabled(enabled, { suppressStatus: silent }); + setLayerButtonState(button, { + active: enabled, + loading: false, + tooltip: enabled ? "隐藏电子围栏" : "显示电子围栏", + }); + syncMobileLayerCards(); + if (persist) persistEarthSettings(); + return enabled; + } catch (error) { + console.error("切换电子围栏显示失败:", error); + setLayerButtonState(button, { active: false, loading: false, tooltip: "显示电子围栏" }); + syncMobileLayerCards(); + if (persist) persistEarthSettings(); + return false; + } +} + +async function setFusionOverlaysLayerEnabled(button, enabled, { persist = true, silent = false } = {}) { + try { + if (enabled) { + setLayerButtonState(button, { active: false, loading: true, tooltip: "关联与影响链加载中..." }); + } + await setFusionOverlaysEnabled(enabled, { suppressStatus: silent }); + setLayerButtonState(button, { + active: enabled, + loading: false, + tooltip: enabled ? "隐藏关联与影响链" : "显示关联与影响链", + }); + syncMobileLayerCards(); + if (persist) persistEarthSettings(); + return enabled; + } catch (error) { + console.error("切换关联与影响链失败:", error); + setLayerButtonState(button, { active: false, loading: false, tooltip: "显示关联与影响链" }); + syncMobileLayerCards(); + if (persist) persistEarthSettings(); + return false; + } +} + function syncTrailsDisplayControls() { const trailsEnabled = getShowTrails(); const disabledState = getLayerDisabledState("trails"); @@ -4153,6 +4282,94 @@ function getBuiltinLayerDefinitions() { setVisible: (visible, options = {}) => setVesselsLayerEnabled(getLayerButton("vessels"), visible, options), }, + { + id: "aircraft", + productId: "aircraft", + buttonId: "toggle-aircraft", + icon: "flight", + label: "航空器", + meta: "军机与民航 ADS-B", + keywords: "航空器 飞机 ads-b aircraft flights military", + defaultActive: false, + displayOrder: 46, + startupPriority: 66, + startupMode: "visible", + startupLabel: "航空器", + startupMessage: earthMessage("startup.aircraft"), + getVisible: () => getAircraftEnabled(), + setVisible: (visible, options = {}) => + setAircraftLayerEnabled(getLayerButton("aircraft"), visible, options), + }, + { + id: "gpsJamming", + productId: "gps_jamming", + buttonId: "toggle-gps-jamming", + icon: "radar", + label: "GPS 干扰", + meta: "GNSS 干扰监测热区", + keywords: "gps干扰 gnss jamming interference", + defaultActive: false, + displayOrder: 47, + startupPriority: 67, + startupMode: "visible", + startupLabel: "GPS 干扰", + startupMessage: earthMessage("startup.gpsJamming"), + getVisible: () => getGpsJammingEnabled(), + setVisible: (visible, options = {}) => + setGpsJammingLayerEnabled(getLayerButton("gps-jamming"), visible, options), + }, + { + id: "disasters", + productId: "disasters", + buttonId: "toggle-disasters", + icon: "warning", + label: "自然灾害", + meta: "地震、林火热点与灾难预警", + keywords: "自然灾害 地震 林火 气旋 disasters earthquakes wildfires", + defaultActive: false, + displayOrder: 48, + startupPriority: 68, + startupMode: "visible", + startupLabel: "自然灾害", + startupMessage: earthMessage("startup.disasters"), + getVisible: () => getDisastersEnabled(), + setVisible: (visible, options = {}) => + setDisastersLayerEnabled(getLayerButton("disasters"), visible, options), + }, + { + id: "geofences", + buttonId: "toggle-geofences", + icon: "pentagon", + label: "电子围栏", + meta: "海缆走廊与咽喉监测区", + keywords: "电子围栏 geofences corridors", + defaultActive: false, + displayOrder: 49, + startupPriority: 69, + startupMode: "visible", + startupLabel: "电子围栏", + startupMessage: earthMessage("startup.geofences"), + getVisible: () => getGeofencesEnabled(), + setVisible: (visible, options = {}) => + setGeofencesLayerEnabled(getLayerButton("geofences"), visible, options), + }, + { + id: "fusionOverlays", + buttonId: "toggle-fusion-overlays", + icon: "share", + label: "关联与影响链", + meta: "H3 待核查关联与海缆影响链", + keywords: "多域关联 影响链 fusion correlation dependency", + defaultActive: false, + displayOrder: 50, + startupPriority: 70, + startupMode: "visible", + startupLabel: "关联与影响链", + startupMessage: earthMessage("startup.fusionOverlays"), + getVisible: () => getFusionOverlaysEnabled(), + setVisible: (visible, options = {}) => + setFusionOverlaysLayerEnabled(getLayerButton("fusion-overlays"), visible, options), + }, { id: "satellites", productId: "satellites", @@ -4382,6 +4599,9 @@ export function setZoomLevel(nextZoom, camera = activeCamera) { } camera.updateMatrixWorld(); updateZoomDisplay(zoomLevel, camera.position.z.toFixed(0)); + if (typeof window !== "undefined" && typeof CustomEvent === "function") { + window.dispatchEvent(new CustomEvent("earth:zoom-level-change", { detail: { zoomLevel } })); + } } return zoomLevel; } @@ -4545,6 +4765,7 @@ function openSettingsModal() { modal.classList.add("is-opening"); modal.classList.add("is-open"); modal.setAttribute("aria-hidden", "false"); + void refreshLocalAssetCacheUi(); requestAnimationFrame(() => { if (sheet instanceof HTMLElement) { @@ -4977,6 +5198,49 @@ async function setupBoundaryPrecisionControls() { }); } +async function refreshLocalAssetCacheUi() { + const els = document.querySelectorAll("[data-asset-cache-summary]"); + if (!els.length) return; + try { + const stats = await getLocalCacheStats(); + const text = stats.totalCount > 0 + ? `当前占用:${formatBytes(stats.totalBytes)}(${stats.totalCount} 项)` + : "当前占用:0 B"; + els.forEach((el) => { + if (el instanceof HTMLElement) { + el.textContent = text; + } + }); + } catch { + els.forEach((el) => { + if (el instanceof HTMLElement) { + el.textContent = "当前占用:0 B"; + } + }); + } +} + +function setupLocalAssetCacheControls() { + const buttons = document.querySelectorAll("[data-clear-asset-cache]"); + buttons.forEach((btn) => { + if (!(btn instanceof HTMLButtonElement)) return; + bindListener(btn, "click", async () => { + const original = btn.textContent || "清理缓存"; + btn.disabled = true; + btn.textContent = "正在清理…"; + try { + await clearLocalAssetCache(); + await refreshLocalAssetCacheUi(); + showStatusMessage(earthMessage("status.cacheCleared"), "success"); + } finally { + btn.disabled = false; + btn.textContent = original; + } + }); + }); + void refreshLocalAssetCacheUi(); +} + function setSettingsTab(root, tabId) { if (!(root instanceof HTMLElement)) return; const nextTab = tabId || "runtime"; @@ -4990,6 +5254,9 @@ function setSettingsTab(root, tabId) { if (!(panel instanceof HTMLElement)) return; panel.hidden = panel.dataset.settingsTabPanel !== nextTab; }); + if (nextTab === "system") { + void refreshLocalAssetCacheUi(); + } window.requestAnimationFrame(() => { syncSegmentedControlSliders(); }); @@ -5861,6 +6128,7 @@ function setupSettingsControls() { syncMotionDebugSkeletonOnlyToggle(motionDebugSkeletonOnly); syncMotionGestureControls(); void setupBoundaryPrecisionControls(); + setupLocalAssetCacheControls(); } function syncDisplayDetailControls() { @@ -6203,6 +6471,10 @@ function setupZoomControls(camera) { const MAX_PERCENT = CONFIG.maxZoom * 100; function doZoomStep(direction) { + if (window.__planetEarth?.is2dActive?.()) { + window.__planetEarth.zoom2dBy?.(direction > 0 ? 0.65 : -0.65); + return; + } let currentPercent = Math.round(getZoomLevelFromCamera(camera) * 100); let newPercent = direction > 0 ? currentPercent + CLICK_STEP : currentPercent - CLICK_STEP; @@ -6215,6 +6487,10 @@ function setupZoomControls(camera) { } function doContinuousZoom(direction) { + if (window.__planetEarth?.is2dActive?.()) { + window.__planetEarth.zoom2dBy?.(direction > 0 ? 0.15 : -0.15); + return; + } let currentPercent = Math.round(getZoomLevelFromCamera(camera) * 100); let newPercent = direction > 0 ? currentPercent + 1 : currentPercent - 1; @@ -6284,6 +6560,10 @@ function setupZoomControls(camera) { bindListener(zoomOut, "touchend", () => handleMouseUp(-1)); bindListener(zoomValue, "click", () => { + if (window.__planetEarth?.is2dActive?.()) { + window.__planetEarth.reset2dView?.(); + return; + } const startZoomVal = getZoomLevelFromCamera(camera); const targetZoom = getDefaultEarthZoomLevel(); @@ -6545,6 +6825,10 @@ function setupRotateControls(camera) { updateRotateUI(); bindListener(resetViewBtn, "click", () => { + if (window.__planetEarth?.is2dActive?.()) { + window.__planetEarth.reset2dView?.(); + return; + } resetView(camera); }); } diff --git a/frontend/public/earth/js/country-boundaries.js b/frontend/public/earth/js/country-boundaries.js index 002ef111..ff6e57a4 100644 --- a/frontend/public/earth/js/country-boundaries.js +++ b/frontend/public/earth/js/country-boundaries.js @@ -7,7 +7,11 @@ import Pbf from "pbf"; import { CONFIG, COUNTRY_BOUNDARY_CONFIG, EARTH_MATERIAL_CONFIG } from "./constants.js"; import { screenToEarthCoords, vector3ToLatLon } from "./utils.js"; import { appendSurfaceSegments, createEarthSurfaceGeometry } from "./earth-surface.js"; -import { createSurfaceRibbonGeometry, createSurfaceRibbonMaterial } from "./surface-ribbon.js"; +import { + createDashedRibbonMaterial, + createSurfaceRibbonGeometry, + createSurfaceRibbonMaterial, +} from "./surface-ribbon.js"; import { setEarthLandMask } from "./earth.js"; import { configureColorTexture } from "./texture-colors.js"; import { @@ -552,12 +556,33 @@ function buildClaimLines() { return lines; } +function effectiveAdmin1Opacity() { + return _admin1Opacity <= 0.001 ? 0 : _admin1Opacity; +} + +function syncAdmin1RibbonState() { + const effective = effectiveAdmin1Opacity(); + if (_admin1Material) { + _admin1Material.uniforms.uOpacity.value = effective; + _admin1Material.visible = effective > 0.001; + } + if (_batchedAdmin1Lines) { + const count = _batchedAdmin1Lines.geometry?.drawRange?.count || 0; + _batchedAdmin1Lines.visible = boundaryLegendVisible() && effective > 0.001 && count > 0; + } +} + function getAdmin1Material() { if (_admin1Material) return _admin1Material; - _admin1Material = new THREE.LineBasicMaterial({ - color: COUNTRY_BOUNDARY_CONFIG.admin1LineColor, - transparent: true, - opacity: _admin1Opacity, + _admin1Material = createDashedRibbonMaterial({ + coreColor: COUNTRY_BOUNDARY_CONFIG.admin1LineColor, + casingColor: COUNTRY_BOUNDARY_CONFIG.admin1CasingColor, + opacity: effectiveAdmin1Opacity(), + maxOpacity: COUNTRY_BOUNDARY_CONFIG.admin1LineOpacity, + casingOpacity: COUNTRY_BOUNDARY_CONFIG.admin1CasingOpacity, + halfWidthPx: COUNTRY_BOUNDARY_CONFIG.admin1HalfWidthPx, + dashPx: COUNTRY_BOUNDARY_CONFIG.admin1DashPx, + gapPx: COUNTRY_BOUNDARY_CONFIG.admin1GapPx, depthTest: true, depthWrite: false, }); @@ -605,14 +630,7 @@ function updateAdmin1Opacity(viewZoom) { const next = admin1OpacityForViewZoom(viewZoom); if (Math.abs(next - _admin1Opacity) < 0.001) return; _admin1Opacity = next; - if (_admin1Material) { - _admin1Material.opacity = next; - _admin1Material.visible = next > 0.001; - } - if (_batchedAdmin1Lines) { - const count = _batchedAdmin1Lines.geometry?.drawRange?.count || 0; - _batchedAdmin1Lines.visible = boundaryLegendVisible() && next > 0.001 && count > 0; - } + syncAdmin1RibbonState(); } function createBatchedLineObject(name, material, renderOrder) { @@ -628,13 +646,26 @@ function createBatchedLineObject(name, material, renderOrder) { return lines; } +function createBatchedRibbonMesh(name, material, renderOrder) { + const geo = new THREE.BufferGeometry(); + geo.setDrawRange(0, 0); + geo.boundingSphere = new THREE.Sphere(new THREE.Vector3(0, 0, 0), CONFIG.earthRadius + 6); + const mesh = new THREE.Mesh(geo, material); + mesh.name = name; + mesh.renderOrder = renderOrder; + mesh.visible = false; + mesh.frustumCulled = false; + mesh.raycast = () => {}; + return mesh; +} + function buildBatchedLineObjects() { _batchedBoundaryLines = createBatchedLineObject( "country-boundary-batch", getBoundaryTileMaterial(), COUNTRY_BOUNDARY_CONFIG.lineRenderOrder + 0.01, ); - _batchedAdmin1Lines = createBatchedLineObject( + _batchedAdmin1Lines = createBatchedRibbonMesh( "country-admin1-batch", getAdmin1Material(), COUNTRY_BOUNDARY_CONFIG.lineRenderOrder, @@ -732,6 +763,156 @@ function uploadIndexedBatch(lineObj, buckets) { return { vertexCount: Math.floor(totalFloats / 3), indexCount: totalIndices, drawCalls: 1 }; } +function uploadAdmin1RibbonBatch(mesh, buckets) { + if (!mesh) return { vertexCount: 0, indexCount: 0, drawCalls: 0 }; + let totalSegments = 0; + for (let i = 0; i < buckets.length; i += 1) { + const bucket = buckets[i]; + if (!bucket?.positions?.length || !bucket?.indices?.length) continue; + totalSegments += bucket.indices.length >> 1; + } + const geometry = mesh.geometry; + if (totalSegments === 0) { + geometry.setDrawRange(0, 0); + mesh.visible = false; + return { vertexCount: 0, indexCount: 0, drawCalls: 0 }; + } + + const neededVerts = totalSegments * 4; + const neededFloats = neededVerts * 3; + const neededIndices = totalSegments * 6; + + let posArr = mesh.userData._batchPos; + let otherArr = mesh.userData._batchOther; + let paramArr = mesh.userData._batchParams; + let idxArr = mesh.userData._batchIdx; + let vertGrew = false; + let idxGrew = false; + + if (!posArr || !otherArr || !paramArr || posArr.length < neededFloats) { + let capVerts = Math.max(4096, neededVerts); + if (posArr) { + capVerts = Math.floor(posArr.length / 3); + while (capVerts < neededVerts) capVerts *= 2; + } + posArr = new Float32Array(capVerts * 3); + otherArr = new Float32Array(capVerts * 3); + paramArr = new Float32Array(capVerts * 3); + mesh.userData._batchPos = posArr; + mesh.userData._batchOther = otherArr; + mesh.userData._batchParams = paramArr; + vertGrew = true; + } + + if (!idxArr || idxArr.length < neededIndices) { + let capIdx = Math.max(8192, neededIndices); + if (idxArr) { + capIdx = idxArr.length; + while (capIdx < neededIndices) capIdx *= 2; + } + idxArr = new Uint32Array(capIdx); + mesh.userData._batchIdx = idxArr; + idxGrew = true; + } + + let vertCursor = 0; + let idxCursor = 0; + for (let i = 0; i < buckets.length; i += 1) { + const bucket = buckets[i]; + const srcPos = bucket?.positions; + const srcIdx = bucket?.indices; + if (!srcPos?.length || !srcIdx?.length) continue; + + let cumLen = 0; + let prevRawB = -1; + for (let k = 0; k + 1 < srcIdx.length; k += 2) { + const rawA = srcIdx[k]; + const rawB = srcIdx[k + 1]; + const pa = rawA * 3; + const pb = rawB * 3; + if (pa + 2 >= srcPos.length || pb + 2 >= srcPos.length) continue; + + if (rawA !== prevRawB) { + cumLen = 0; + } + const ax = srcPos[pa]; + const ay = srcPos[pa + 1]; + const az = srcPos[pa + 2]; + const bx = srcPos[pb]; + const by = srcPos[pb + 1]; + const bz = srcPos[pb + 2]; + const segLen = Math.hypot(bx - ax, by - ay, bz - az); + const distA = cumLen; + const distB = cumLen + segLen; + cumLen = distB; + prevRawB = rawB; + + const baseV = vertCursor; + const f0 = baseV * 3; + // v0: start, -1 + posArr[f0] = ax; posArr[f0 + 1] = ay; posArr[f0 + 2] = az; + otherArr[f0] = bx; otherArr[f0 + 1] = by; otherArr[f0 + 2] = bz; + paramArr[f0] = 0; paramArr[f0 + 1] = -1; paramArr[f0 + 2] = distA; + // v1: start, +1 + posArr[f0 + 3] = ax; posArr[f0 + 4] = ay; posArr[f0 + 5] = az; + otherArr[f0 + 3] = bx; otherArr[f0 + 4] = by; otherArr[f0 + 5] = bz; + paramArr[f0 + 3] = 0; paramArr[f0 + 4] = 1; paramArr[f0 + 5] = distA; + // v2: end, -1 + posArr[f0 + 6] = bx; posArr[f0 + 7] = by; posArr[f0 + 8] = bz; + otherArr[f0 + 6] = ax; otherArr[f0 + 7] = ay; otherArr[f0 + 8] = az; + paramArr[f0 + 6] = 1; paramArr[f0 + 7] = -1; paramArr[f0 + 8] = distB; + // v3: end, +1 + posArr[f0 + 9] = bx; posArr[f0 + 10] = by; posArr[f0 + 11] = bz; + otherArr[f0 + 9] = ax; otherArr[f0 + 10] = ay; otherArr[f0 + 11] = az; + paramArr[f0 + 9] = 1; paramArr[f0 + 10] = 1; paramArr[f0 + 11] = distB; + vertCursor += 4; + + idxArr[idxCursor++] = baseV; + idxArr[idxCursor++] = baseV + 1; + idxArr[idxCursor++] = baseV + 2; + idxArr[idxCursor++] = baseV + 1; + idxArr[idxCursor++] = baseV + 3; + idxArr[idxCursor++] = baseV + 2; + } + } + + if (idxCursor === 0) { + geometry.setDrawRange(0, 0); + mesh.visible = false; + return { vertexCount: 0, indexCount: 0, drawCalls: 0 }; + } + + for (const [attrName, arr] of [ + ["position", posArr], + ["aOther", otherArr], + ["aParams", paramArr], + ]) { + const attr = geometry.getAttribute(attrName); + if (!attr || vertGrew) { + const nextAttr = new THREE.BufferAttribute(arr, 3); + nextAttr.setUsage(THREE.DynamicDrawUsage); + geometry.setAttribute(attrName, nextAttr); + } else { + attr.needsUpdate = true; + } + } + + const idxAttr = geometry.getIndex(); + if (!idxAttr || idxGrew) { + const nextIdx = new THREE.BufferAttribute(idxArr, 1); + nextIdx.setUsage(THREE.DynamicDrawUsage); + geometry.setIndex(nextIdx); + } else { + idxAttr.needsUpdate = true; + } + + geometry.setDrawRange(0, idxCursor); + if (!geometry.boundingSphere) { + geometry.boundingSphere = new THREE.Sphere(new THREE.Vector3(0, 0, 0), CONFIG.earthRadius + 6); + } + return { vertexCount: vertCursor, indexCount: idxCursor, drawCalls: 1 }; +} + function uploadDashedBatch(lineObj, buckets) { if (!lineObj) return { vertexCount: 0, drawCalls: 0 }; let totalFloats = 0; @@ -1014,12 +1195,12 @@ function rebuildBatchedGeometry() { } const bRes = uploadIndexedBatch(_batchedBoundaryLines, boundaryBuckets); - const aRes = uploadIndexedBatch(_batchedAdmin1Lines, admin1Buckets); + const aRes = uploadAdmin1RibbonBatch(_batchedAdmin1Lines, admin1Buckets); const cRes = uploadDashedBatch(_batchedClaimLines, claimBuckets); const showLines = boundaryLegendVisible(); _batchedBoundaryLines.visible = showLines && bRes.indexCount > 0; - _batchedAdmin1Lines.visible = showLines && _admin1Opacity > 0.001 && aRes.indexCount > 0; + _batchedAdmin1Lines.visible = showLines && effectiveAdmin1Opacity() > 0.001 && aRes.indexCount > 0; _batchedClaimLines.visible = showLines && cRes.vertexCount > 0; const visibleUnionCount = new Set([...nextCoastKeys, ...nextBorderKeys]).size; @@ -1978,6 +2159,7 @@ function setBoundaryLinesDimmed(dimmed) { } function updateBoundaryLineDimState() { + const isHoveringChina = _hoveredGroupKey === "CHN" || _hoveredGroupKey === "TWN"; if (_coastlineLines?.material) { _coastlineLines.material.opacity = COUNTRY_BOUNDARY_CONFIG.lineOpacity; _coastlineLines.material.needsUpdate = true; @@ -1988,6 +2170,12 @@ function updateBoundaryLineDimState() { ? Math.max(COUNTRY_BOUNDARY_CONFIG.dimmedLineOpacity, 0.28) : COUNTRY_BOUNDARY_CONFIG.lineOpacity; } + if (_claimTileMaterial) { + _claimTileMaterial.opacity = (_hoveredFeature && !isHoveringChina) + ? COUNTRY_BOUNDARY_CONFIG.dimmedLineOpacity + : 0.85; + } + syncAdmin1RibbonState(); setBoundaryLinesDimmed(Boolean(_hoveredFeature) || _activeTileKeys.size > 0); } @@ -2056,7 +2244,21 @@ export function extractCountryHoverGeometryData( for (const entry of coastEntries || []) collectBucket(entry?.coast); for (const entry of borderEntries || []) collectBucket(entry?.border); - if (totalIndices === 0 || matchedSlices.length === 0) { + const claimEntries = []; + if (codeSet.has("CHN") || codeSet.has("TWN")) { + const seenClaims = new Set(); + for (const entry of borderEntries || []) { + const claim = entry?.claim; + if (!claim?.positions?.length || seenClaims.has(claim)) continue; + seenClaims.add(claim); + const segs = Math.floor(claim.positions.length / 6); + if (segs <= 0) continue; + claimEntries.push(claim); + totalIndices += segs * 2; + } + } + + if (totalIndices === 0 || (matchedSlices.length === 0 && claimEntries.length === 0)) { return { positions: new Float32Array(0), indices: new Uint32Array(0), polylines: [] }; } @@ -2121,6 +2323,62 @@ export function extractCountryHoverGeometryData( } } + const ENDPOINT_EPS_SQ = 1e-10; + for (const claim of claimEntries) { + const srcPos = claim.positions; + const segCount = Math.floor(srcPos.length / 6); + let currentPoly = null; + let prevMapB = -1; + let prevBx = 0; + let prevBy = 0; + let prevBz = 0; + + for (let s = 0; s < segCount; s += 1) { + const base = s * 6; + const ax = srcPos[base]; + const ay = srcPos[base + 1]; + const az = srcPos[base + 2]; + const bx = srcPos[base + 3]; + const by = srcPos[base + 4]; + const bz = srcPos[base + 5]; + + const chained = + prevMapB !== -1 && + (ax - prevBx) * (ax - prevBx) + (ay - prevBy) * (ay - prevBy) + (az - prevBz) * (az - prevBz) <= + ENDPOINT_EPS_SQ; + + let mapA; + if (chained) { + mapA = prevMapB; + } else { + mapA = outVertCount++; + posList.push(ax, ay, az); + } + const mapB = outVertCount++; + posList.push(bx, by, bz); + + outIndices[outIdxCursor++] = mapA; + outIndices[outIdxCursor++] = mapB; + + if (chained && currentPoly) { + currentPoly.push(new THREE.Vector3(bx * glowScale, by * glowScale, bz * glowScale)); + } else { + if (currentPoly && currentPoly.length >= 2) polylines.push(currentPoly); + currentPoly = [ + new THREE.Vector3(ax * glowScale, ay * glowScale, az * glowScale), + new THREE.Vector3(bx * glowScale, by * glowScale, bz * glowScale), + ]; + } + prevMapB = mapB; + prevBx = bx; + prevBy = by; + prevBz = bz; + } + if (currentPoly && currentPoly.length >= 2) { + polylines.push(currentPoly); + } + } + return { positions: new Float32Array(posList), indices: outIndices.subarray(0, outIdxCursor), @@ -2531,6 +2789,38 @@ export function getCountryBoundaryManifest() { return _tileManifest; } +export function getBoundaryPmtilesUrl() { + return manifestPmtilesUrl(_tileManifest); +} + +export function getBoundaryPmtilesArchive() { + return _tileManifest ? ensurePmtilesArchive() : null; +} + +export function lookupCountryGroupAtLatLon(lat, lon) { + if (!_loaded || !Number.isFinite(lat) || !Number.isFinite(lon)) return null; + const found = _features.find((f) => featureContains(lat, lon, f)) || null; + if (!found) return null; + const groupKey = getCountryHighlightGroupKey(found); + const members = getHighlightFeatures(found); + const codes = [...new Set( + members + .flatMap((feat) => { + const p = feat?.properties || {}; + return [p.ADM0_A3, p.ISO_A3, p.ISO_A3_EH, p.SOV_A3]; + }) + .map((code) => String(code || "").trim().toUpperCase()) + .filter((code) => code && code !== "-99"), + )]; + if (codes.includes("CHN") && !codes.includes("TWN")) codes.push("TWN"); + if (codes.includes("TWN") && !codes.includes("CHN")) codes.push("CHN"); + return { + groupKey, + codes, + info: makeCountryInfo(found), + }; +} + /** * Show or hide the country boundary lines. * The land/ocean fill is the base earth map and stays independent from this diff --git a/frontend/public/earth/js/country-boundaries.test.js b/frontend/public/earth/js/country-boundaries.test.js index 576e52f4..48e4e28b 100644 --- a/frontend/public/earth/js/country-boundaries.test.js +++ b/frontend/public/earth/js/country-boundaries.test.js @@ -357,7 +357,7 @@ test("sortKeysCenterFirst prioritizes tiles closest to screen center", () => { expect(sorted[1]).toBe("boundary/4/12/6"); }); -test("extractCountryHoverGeometryData merges land borders and OSM coastlines cleanly without fill mask", () => { +test("extractCountryHoverGeometryData merges land borders, coastlines, and China claim lines without fill mask", () => { const coastEntry = { coast: { // Two connected segments for CHN (0->1->2) plus one island coastline for JPN (3->4->5) @@ -380,12 +380,25 @@ test("extractCountryHoverGeometryData merges land borders and OSM coastlines cle CHN: new Uint32Array([0, 2]), }, }, + claim: { + positions: new Float32Array([ + 40, 0, 0, 41, 0, 0, + 41, 0, 0, 42, 0, 0, + 50, 0, 0, 51, 0, 0, + ]), + lineDistances: new Float32Array([0, 1, 1, 2, 0, 1]), + }, }; const chn = extractCountryHoverGeometryData(["CHN"], [coastEntry], [borderEntry]); - expect(chn.indices.length).toBe(6); // 4 coast indices + 2 border indices - expect(chn.polylines).toHaveLength(2); + expect(chn.indices.length).toBe(12); // 4 coast + 2 border + 6 claim indices + expect(chn.polylines).toHaveLength(4); // 1 coast + 1 border + 2 claim chains expect(chn.polylines[0]).toHaveLength(3); // continuous 3-point coastline + expect(chn.polylines[2]).toHaveLength(3); // connected 9-dash pair stitched cleanly + + const twn = extractCountryHoverGeometryData(["TWN"], [coastEntry], [borderEntry]); + expect(twn.indices.length).toBe(6); // China POV claim lines highlight for TWN too + expect(twn.polylines).toHaveLength(2); const jpn = extractCountryHoverGeometryData(["JPN"], [coastEntry], [borderEntry]); expect(jpn.indices.length).toBe(4); diff --git a/frontend/public/earth/js/disasters.js b/frontend/public/earth/js/disasters.js new file mode 100644 index 00000000..9289fad5 --- /dev/null +++ b/frontend/public/earth/js/disasters.js @@ -0,0 +1,264 @@ +// disasters.js - Single-batch THREE.Points natural disaster overlay (R+0.52, renderOrder 4.6) + +import * as THREE from "three"; +import { CONFIG, PATHS } from "./constants.js"; +import { latLonToVector3 } from "./utils.js"; + +const DISASTER_ALTITUDE_OFFSET = 0.52; +const DISASTER_RENDER_ORDER = 4.6; + +const TYPE_CODES = { + earthquake: 0.0, + wildfire: 1.0, + cyclone: 2.0, + flood: 3.0, + volcano: 4.0, + drought: 5.0, + other: 6.0, +}; + +const TYPE_LABELS = { + earthquake: "地震", + wildfire: "林火热点簇", + cyclone: "热带气旋/风暴", + flood: "洪涝灾害", + volcano: "火山活动", + drought: "干旱", + other: "其他自然异常", +}; + +const SEVERITY_CODES = { + low: 0.0, + medium: 1.0, + high: 2.0, +}; + +let disastersGroup = null; +let disastersPoints = null; +let disasterRecords = []; +let disasterPayloadMeta = null; +let disastersVisible = false; +let disastersShaderMat = null; + +function buildShaderMaterial() { + return new THREE.ShaderMaterial({ + uniforms: { + uTime: { value: 0.0 }, + uPixelRatio: { + value: typeof window !== "undefined" ? Math.min(window.devicePixelRatio || 1, 2) : 1, + }, + }, + vertexShader: ` + attribute float aType; + attribute float aSeverity; + attribute float aPhase; + uniform float uTime; + uniform float uPixelRatio; + varying float vType; + varying float vSeverity; + varying float vPulse; + + void main() { + vType = aType; + vSeverity = aSeverity; + float speed = aSeverity > 1.5 ? 2.8 : 1.6; + vPulse = 0.5 + 0.5 * sin(uTime * speed + aPhase); + vec4 mvPosition = modelViewMatrix * vec4(position, 1.0); + float baseSize = aSeverity > 1.5 ? 16.0 : (aSeverity > 0.5 ? 12.0 : 9.0); + float pulseScale = 1.0 + vPulse * (aSeverity > 1.5 ? 0.35 : 0.18); + gl_PointSize = clamp(baseSize * pulseScale * uPixelRatio * (380.0 / max(120.0, -mvPosition.z)), 6.0, 28.0); + gl_Position = projectionMatrix * mvPosition; + } + `, + fragmentShader: ` + varying float vType; + varying float vSeverity; + varying float vPulse; + + vec3 disasterColor(float typeCode, float sevCode) { + if (typeCode < 0.5) return sevCode > 1.5 ? vec3(0.98, 0.27, 0.27) : vec3(0.98, 0.48, 0.25); // earthquake + if (typeCode < 1.5) return vec3(1.00, 0.62, 0.14); // wildfire + if (typeCode < 2.5) return vec3(0.22, 0.74, 0.97); // cyclone + if (typeCode < 3.5) return vec3(0.24, 0.52, 0.98); // flood + if (typeCode < 4.5) return vec3(0.95, 0.32, 0.58); // volcano + if (typeCode < 5.5) return vec3(0.91, 0.72, 0.22); // drought + return vec3(0.75, 0.80, 0.86); + } + + void main() { + vec2 uv = gl_PointCoord - vec2(0.5); + float dist = length(uv); + if (dist > 0.5) discard; + vec3 baseColor = disasterColor(vType, vSeverity); + float core = smoothstep(0.22, 0.04, dist); + float ring = smoothstep(0.49, 0.36, dist) * (1.0 - smoothstep(0.32, 0.18, dist)); + float alpha = clamp(core * 0.95 + ring * (0.45 + 0.45 * vPulse), 0.0, 1.0); + vec3 color = mix(baseColor, vec3(1.0, 0.96, 0.92), core * 0.35); + gl_FragColor = vec4(color, alpha); + } + `, + transparent: true, + depthTest: true, + depthWrite: false, + }); +} + +export function buildDisasterPointAttributes(items = [], radius = CONFIG.earthRadius + DISASTER_ALTITUDE_OFFSET) { + const valid = Array.isArray(items) + ? items.filter( + (it) => + it?.lat != null && + it?.lon != null && + it?.lat !== "" && + it?.lon !== "" && + Number.isFinite(Number(it.lat)) && + Number.isFinite(Number(it.lon)), + ) + : []; + const count = valid.length; + const positions = new Float32Array(count * 3); + const types = new Float32Array(count); + const severities = new Float32Array(count); + const phases = new Float32Array(count); + + for (let i = 0; i < count; i += 1) { + const item = valid[i]; + const vec = latLonToVector3(Number(item.lat), Number(item.lon), radius); + positions[i * 3] = vec.x; + positions[i * 3 + 1] = vec.y; + positions[i * 3 + 2] = vec.z; + const typeKey = String(item.event_type || "other").toLowerCase(); + const sevKey = String(item.severity || "medium").toLowerCase(); + types[i] = TYPE_CODES[typeKey] ?? TYPE_CODES.other; + severities[i] = SEVERITY_CODES[sevKey] ?? SEVERITY_CODES.medium; + phases[i] = (i * 1.37) % (Math.PI * 2); + } + return { valid, count, positions, types, severities, phases }; +} + +function disposeMesh() { + if (disastersPoints) { + disastersPoints.parent?.remove(disastersPoints); + disastersPoints.geometry?.dispose?.(); + disastersPoints = null; + } + if (disastersShaderMat) { + disastersShaderMat.dispose?.(); + disastersShaderMat = null; + } +} + +export function initDisastersLayer(earth) { + if (!earth) return null; + if (!disastersGroup) { + disastersGroup = new THREE.Group(); + disastersGroup.name = "disasters-layer-group"; + disastersGroup.visible = disastersVisible; + earth.add(disastersGroup); + } else if (disastersGroup.parent !== earth) { + earth.add(disastersGroup); + } + return disastersGroup; +} + +export function renderDisasterItems(items = [], earth) { + const group = initDisastersLayer(earth); + if (!group) return 0; + disposeMesh(); + + const built = buildDisasterPointAttributes(items); + disasterRecords = built.valid; + if (built.count === 0) { + return 0; + } + + const geometry = new THREE.BufferGeometry(); + geometry.setAttribute("position", new THREE.BufferAttribute(built.positions, 3)); + geometry.setAttribute("aType", new THREE.BufferAttribute(built.types, 1)); + geometry.setAttribute("aSeverity", new THREE.BufferAttribute(built.severities, 1)); + geometry.setAttribute("aPhase", new THREE.BufferAttribute(built.phases, 1)); + + disastersShaderMat = buildShaderMaterial(); + disastersPoints = new THREE.Points(geometry, disastersShaderMat); + disastersPoints.name = "disaster-events-points"; + disastersPoints.renderOrder = DISASTER_RENDER_ORDER; + disastersPoints.frustumCulled = false; + group.add(disastersPoints); + return built.count; +} + +export async function loadDisasters(_scene, earth) { + initDisastersLayer(earth); + const resp = await fetch(PATHS.disastersSnapshotApi, { cache: "no-store", credentials: "same-origin" }); + if (!resp.ok) { + throw new Error(`HTTP ${resp.status}`); + } + const payload = await resp.json(); + disasterPayloadMeta = payload; + const totalCount = renderDisasterItems(payload?.items || [], earth); + return { totalCount, payload }; +} + +export function toggleDisasters(visible, earth) { + disastersVisible = Boolean(visible); + if (earth) initDisastersLayer(earth); + if (disastersGroup) { + disastersGroup.visible = disastersVisible; + } +} + +export function updateDisastersFrame(elapsedSec) { + if (disastersVisible && disastersShaderMat?.uniforms?.uTime) { + disastersShaderMat.uniforms.uTime.value = Number(elapsedSec || 0); + } +} + +export function clearDisastersData(earth) { + disasterRecords = []; + disasterPayloadMeta = null; + disposeMesh(); + if (disastersGroup) { + earth?.remove?.(disastersGroup); + disastersGroup = null; + } +} + +export function getDisastersCount() { + return disasterRecords.length; +} + +export function getDisasterTypeLabel(typeKey) { + return TYPE_LABELS[String(typeKey || "other").toLowerCase()] || TYPE_LABELS.other; +} + +export function findNearestDisaster(lat, lon, maxAngleDeg = 1.8) { + if (!disastersVisible || !disasterRecords.length) return null; + const targetLat = Number(lat); + const targetLon = Number(lon); + if (!Number.isFinite(targetLat) || !Number.isFinite(targetLon)) return null; + + let best = null; + let bestDist = Infinity; + for (const item of disasterRecords) { + const dLat = Math.abs(Number(item.lat) - targetLat); + let dLon = Math.abs(Number(item.lon) - targetLon); + if (dLon > 180) dLon = 360 - dLon; + const dist = Math.hypot(dLat, dLon); + if (dist <= maxAngleDeg && dist < bestDist) { + bestDist = dist; + best = item; + } + } + return best; +} + +export function getDisastersLegendItems() { + if (!disastersVisible) return []; + const counts = disasterPayloadMeta?.by_type || {}; + return [ + { label: `地震 (${Number(counts.earthquake || 0)})`, color: "#fa4545" }, + { label: `林火簇 (${Number(counts.wildfire || 0)})`, color: "#ff9e24" }, + { label: `气旋/洪水 (${Number(counts.cyclone || 0) + Number(counts.flood || 0)})`, color: "#38bdf8" }, + { label: `火山/其他 (${Number(counts.volcano || 0) + Number(counts.drought || 0) + Number(counts.other || 0)})`, color: "#f25294" }, + ]; +} diff --git a/frontend/public/earth/js/disasters.test.js b/frontend/public/earth/js/disasters.test.js new file mode 100644 index 00000000..f07b6917 --- /dev/null +++ b/frontend/public/earth/js/disasters.test.js @@ -0,0 +1,24 @@ +import { describe, expect, test } from "bun:test"; +import { buildDisasterPointAttributes, findNearestDisaster, toggleDisasters } from "./disasters.js"; + +describe("disasters layer math and picking", () => { + test("buildDisasterPointAttributes packs type and severity float channels", () => { + const built = buildDisasterPointAttributes([ + { lat: 23.85, lon: 121.55, event_type: "earthquake", severity: "high" }, + { lat: 34.12, lon: 118.14, event_type: "wildfire", severity: "medium", cluster_count: 5 }, + { lat: null, lon: 10 }, + ]); + + expect(built.count).toBe(2); + expect(built.positions.length).toBe(6); + expect(built.types[0]).toBe(0); + expect(built.severities[0]).toBe(2); + expect(built.types[1]).toBe(1); + expect(built.severities[1]).toBe(1); + }); + + test("findNearestDisaster skips when hidden", () => { + toggleDisasters(false, null); + expect(findNearestDisaster(23.85, 121.55)).toBeNull(); + }); +}); diff --git a/frontend/public/earth/js/earth-interactables.js b/frontend/public/earth/js/earth-interactables.js index 3d13682e..85effa7b 100644 --- a/frontend/public/earth/js/earth-interactables.js +++ b/frontend/public/earth/js/earth-interactables.js @@ -50,6 +50,12 @@ function drawInteractableIcon(context, { marker, color = "#7dd3fc" }) { context.moveTo(-14, -16); context.lineTo(14, -16); context.moveTo(-14, 0); context.lineTo(14, 0); context.moveTo(-14, 16); context.lineTo(6, 16); + } else if (kind === "port") { + context.arc(0, -18, 8, 0, Math.PI * 2); + context.moveTo(0, -10); context.lineTo(0, 26); + context.moveTo(-16, -2); context.lineTo(16, -2); + context.moveTo(-22, 14); + context.quadraticCurveTo(0, 32, 22, 14); } else if (kind === "alert") { context.moveTo(0, -34); context.lineTo(34, 28); context.lineTo(-34, 28); context.closePath(); context.moveTo(0, -13); context.lineTo(0, 6); @@ -75,6 +81,7 @@ const earthInteractableLayer = createInteractableLayer({ note: "#facc15", alert: "#fb7185", place: "#86efac", + port: "#38bdf8", }, opacity: { normal: 0.9, @@ -115,6 +122,29 @@ export async function loadEarthInteractables(earth, { silent = false } = {}) { const items = (payload.features || []) .map(featureToInteractableItem) .filter(Boolean); + try { + const mcResp = await fetch("/api/v1/vessels/maritime-context", { cache: "no-store" }); + if (mcResp.ok) { + const mc = await mcResp.json(); + const existingIds = new Set(items.map((it) => it.id)); + for (const port of mc.ports || []) { + if (!port?.id || existingIds.has(port.id)) continue; + items.push({ + id: String(port.id), + label: `${port.name} (${port.port_type})`, + kind: "port", + latitude: Number(port.lat), + longitude: Number(port.lon), + description: `${port.country || "-"} · ${port.port_type || "-"} · 吞吐排名 ${port.throughput_rank ?? "-"}`, + source: port.source_citation || "Lloyd's List / NGA WPI", + status: port.port_type || "port", + revision: 1, + }); + } + } + } catch { + // Strategic ports enrichment is best-effort. + } interactableRevisions.clear(); items.forEach((item) => interactableRevisions.set(item.id, Number(item.revision || 0))); earthInteractableLayer.setData(items); diff --git a/frontend/public/earth/js/earth-texture-image.js b/frontend/public/earth/js/earth-texture-image.js index a47817fc..14673294 100644 --- a/frontend/public/earth/js/earth-texture-image.js +++ b/frontend/public/earth/js/earth-texture-image.js @@ -1,11 +1,43 @@ import { EARTH_MAP_SOURCES } from "./earth-map-sources.js"; +import { putCachedAssetBlob, readCachedAssetBlob } from "./asset-swr-cache.js"; + +function inferTextureCacheTarget(url, options = {}) { + if (options?.cacheBucket && options?.cacheKey) { + return { bucket: options.cacheBucket, key: options.cacheKey }; + } + const normalized = String(url || ""); + if (normalized.startsWith("/api/v1/earth/tiles/")) { + return { bucket: "tiles", key: normalized }; + } + if (normalized.startsWith("/api/v1/earth/clouds/") && !normalized.startsWith("/api/v1/earth/clouds/meta")) { + return { bucket: "clouds", key: options?.cacheKey || normalized }; + } + return null; +} // Keep the original 8K pixels; decode off the render path and share the result. -async function decodeEarthImage(url, { signal } = {}) { +async function decodeEarthImage(url, options = {}) { + const { signal } = options; if (typeof createImageBitmap === "function") { - const response = await fetch(url, { priority: "high", signal }); - if (!response.ok) throw new Error("地表底图加载失败,请重试"); - const blob = await response.blob(); + const cacheTarget = inferTextureCacheTarget(url, options); + let blob = null; + if (cacheTarget && !options?.bypassCache) { + blob = await readCachedAssetBlob(cacheTarget.bucket, cacheTarget.key); + } + if (signal?.aborted) { + throw new DOMException("Aborted", "AbortError"); + } + if (!blob) { + const response = await fetch(url, { priority: "high", signal }); + if (!response.ok) throw new Error("地表底图加载失败,请重试"); + blob = await response.blob(); + if (cacheTarget && blob?.size > 0) { + void putCachedAssetBlob(cacheTarget.bucket, cacheTarget.key, blob, { + url, + fingerprint: options?.cacheFingerprint || url, + }); + } + } if (signal?.aborted) { throw new DOMException("Aborted", "AbortError"); } @@ -31,9 +63,9 @@ async function decodeEarthImage(url, { signal } = {}) { export function createEarthTextureImageLoader(decode = decodeEarthImage) { let preload = null; return { - preload(url) { - if (preload?.url === url) return preload.promise; - const entry = { url, promise: decode(url) }; + preload(url, options) { + if (preload?.url === url && !options?.cacheBucket) return preload.promise; + const entry = { url, promise: decode(url, options) }; const previous = preload; preload = entry; previous?.promise.then(image => image.close?.(), () => {}); @@ -43,7 +75,7 @@ export function createEarthTextureImageLoader(decode = decodeEarthImage) { load(url, options) { const entry = preload; preload = null; - if (entry?.url === url && !options?.signal) return entry.promise; + if (entry?.url === url && !options?.signal && !options?.cacheBucket) return entry.promise; entry?.promise.then(image => image.close?.(), () => {}); return decode(url, options); }, diff --git a/frontend/public/earth/js/earth.js b/frontend/public/earth/js/earth.js index e0877ab6..51409395 100644 --- a/frontend/public/earth/js/earth.js +++ b/frontend/public/earth/js/earth.js @@ -40,6 +40,8 @@ let _cloudShadow = null; let _basemapTileLayer = null; let _cloudTileLayer = null; let _basemapChannel = null; +let _basemapTileTemplate = "/api/v1/earth/tiles/earth_imagery_sentinel2/{z}/{x}/{y}.webp"; +let _basemapMaxZoom = 7; let _cloudBaseOpacity = CLOUD_LAYER_CONFIG.opacity ?? 0.38; export let terrain = null; let showGridLines = false; @@ -652,6 +654,10 @@ export async function loadBasemapMeta() { const meta = await response.json(); const maxZoom = Number(meta?.max_zoom || 7); const lodAlt = Number(meta?.lod_switch_altitude || 1.85); + if (meta?.tile_url_template) { + _basemapTileTemplate = String(meta.tile_url_template); + } + _basemapMaxZoom = maxZoom; _basemapTileLayer?.setTemplate(meta?.tile_url_template || null, { maxZoom, lodSwitchAltitude: lodAlt, @@ -691,6 +697,13 @@ export function disposeEarthTileLayers() { } } +export function getBasemapConfigSnapshot() { + return { + tileUrlTemplate: _basemapTileTemplate, + maxZoom: _basemapMaxZoom, + }; +} + export function getEarthTextureVisible() { return _textureVisible; } diff --git a/frontend/public/earth/js/fusion-overlays.js b/frontend/public/earth/js/fusion-overlays.js new file mode 100644 index 00000000..073b00c8 --- /dev/null +++ b/frontend/public/earth/js/fusion-overlays.js @@ -0,0 +1,183 @@ +import * as THREE from "three"; + +import { CONFIG } from "./constants.js"; +import { + createDashedRibbonMaterial, + createSurfaceRibbonGeometry, + createSurfaceRibbonMaterial, +} from "./surface-ribbon.js"; +import { latLonToVector3 } from "./utils.js"; + +const CORRELATION_RENDER_ORDER = 0.971; +const IMPACT_RENDER_ORDER = 0.972; +const HEX_ALTITUDE_OFFSET = 0.19; +const ARC_PEAK_OFFSET = 1.65; + +export function buildCorrelationHexPolylines(cells = [], radius = CONFIG.earthRadius + HEX_ALTITUDE_OFFSET) { + const polylines = []; + for (const cell of Array.isArray(cells) ? cells : []) { + const boundary = Array.isArray(cell?.boundary) ? cell.boundary : []; + if (boundary.length < 3) continue; + const pts = boundary + .filter((pt) => Array.isArray(pt) && pt.length >= 2) + .map((pt) => latLonToVector3(Number(pt[0]), Number(pt[1]), radius)); + if (pts.length < 3) continue; + pts.push(pts[0].clone()); + polylines.push(pts); + } + return polylines; +} + +export function buildDependencyImpactArcPolylines( + arcs = [], + baseRadius = CONFIG.earthRadius + 0.22, + segments = 24, +) { + const polylines = []; + for (const arc of Array.isArray(arcs) ? arcs : []) { + const fLat = Number(arc?.from_lat); + const fLon = Number(arc?.from_lon); + const tLat = Number(arc?.to_lat); + const tLon = Number(arc?.to_lon); + if (!Number.isFinite(fLat) || !Number.isFinite(fLon) || !Number.isFinite(tLat) || !Number.isFinite(tLon)) { + continue; + } + const start = latLonToVector3(fLat, fLon, baseRadius).normalize(); + const end = latLonToVector3(tLat, tLon, baseRadius).normalize(); + const pts = []; + for (let i = 0; i <= segments; i += 1) { + const t = i / segments; + const vec = start.clone().lerp(end, t).normalize(); + const lift = Math.sin(t * Math.PI) * ARC_PEAK_OFFSET; + pts.push(vec.multiplyScalar(baseRadius + lift)); + } + polylines.push(pts); + } + return polylines; +} + +export function createFusionOverlaysManager({ getEarth } = {}) { + let visible = false; + let candidateCells = []; + let dependencyArcs = []; + let rootGroup = null; + let correlationMesh = null; + let dependencyMesh = null; + + const ensureGroup = () => { + const earth = getEarth?.(); + if (!earth) return null; + if (!rootGroup) { + rootGroup = new THREE.Group(); + rootGroup.name = "fusion_overlays_group"; + rootGroup.visible = visible; + earth.add(rootGroup); + } else if (rootGroup.parent !== earth) { + earth.add(rootGroup); + } + return rootGroup; + }; + + const clearMeshes = () => { + if (correlationMesh) { + correlationMesh.geometry?.dispose?.(); + correlationMesh.material?.dispose?.(); + correlationMesh.removeFromParent?.(); + correlationMesh = null; + } + if (dependencyMesh) { + dependencyMesh.geometry?.dispose?.(); + dependencyMesh.material?.dispose?.(); + dependencyMesh.removeFromParent?.(); + dependencyMesh = null; + } + }; + + const rebuild = () => { + const group = ensureGroup(); + clearMeshes(); + if (!group) return; + + const hexLines = buildCorrelationHexPolylines(candidateCells); + if (hexLines.length > 0) { + const geo = createSurfaceRibbonGeometry(hexLines); + if (geo) { + const mat = createDashedRibbonMaterial({ + color: 0xf59e0b, + opacity: 0.9, + halfWidthPx: 2.0, + dashScale: 10.0, + dashRatio: 0.55, + }); + correlationMesh = new THREE.Mesh(geo, mat); + correlationMesh.renderOrder = CORRELATION_RENDER_ORDER; + correlationMesh.name = "fusion_candidate_correlation_hex_batch"; + group.add(correlationMesh); + } + } + + const impactLines = buildDependencyImpactArcPolylines(dependencyArcs); + if (impactLines.length > 0) { + const geo = createSurfaceRibbonGeometry(impactLines); + if (geo) { + const mat = createSurfaceRibbonMaterial({ + color: 0xef4444, + opacity: 0.92, + halfWidthPx: 2.5, + }); + dependencyMesh = new THREE.Mesh(geo, mat); + dependencyMesh.renderOrder = IMPACT_RENDER_ORDER; + dependencyMesh.name = "fusion_dependency_impact_arc_batch"; + group.add(dependencyMesh); + } + } + }; + + const setOverlayData = ({ candidate_cells = [], dependency_arcs = [] } = {}) => { + candidateCells = Array.isArray(candidate_cells) ? candidate_cells : []; + dependencyArcs = Array.isArray(dependency_arcs) ? dependency_arcs : []; + rebuild(); + return { + candidateCount: candidateCells.length, + dependencyArcCount: dependencyArcs.length, + }; + }; + + const loadOverlays = async (fetchImpl = globalThis.fetch) => { + const resp = await fetchImpl("/api/v1/incidents/overlay"); + if (!resp.ok) throw new Error(`HTTP ${resp.status}`); + const payload = await resp.json(); + return setOverlayData(payload || {}); + }; + + const setVisible = (next) => { + visible = Boolean(next); + if (rootGroup) rootGroup.visible = visible; + return visible; + }; + + const getStats = () => ({ + visible, + candidateCount: candidateCells.length, + dependencyArcCount: dependencyArcs.length, + hasCorrelationMesh: Boolean(correlationMesh), + hasDependencyMesh: Boolean(dependencyMesh), + }); + + const dispose = () => { + clearMeshes(); + rootGroup?.removeFromParent?.(); + rootGroup = null; + candidateCells = []; + dependencyArcs = []; + }; + + return { + setOverlayData, + loadOverlays, + setVisible, + isVisible: () => visible, + getStats, + dispose, + }; +} diff --git a/frontend/public/earth/js/fusion-overlays.test.js b/frontend/public/earth/js/fusion-overlays.test.js new file mode 100644 index 00000000..f6c52c88 --- /dev/null +++ b/frontend/public/earth/js/fusion-overlays.test.js @@ -0,0 +1,50 @@ +import { describe, expect, test } from "bun:test"; +import * as THREE from "three"; +import { + buildCorrelationHexPolylines, + buildDependencyImpactArcPolylines, + createFusionOverlaysManager, +} from "./fusion-overlays.js"; + +describe("fusion-overlays", () => { + test("batches candidate correlation hexes and dependency impact arcs separately", () => { + const cells = [ + { + incident_id: 1, + label: "待核查", + boundary: [ + [1.1, 103.5], + [1.2, 103.6], + [1.3, 103.5], + [1.3, 103.3], + [1.2, 103.2], + [1.1, 103.3], + ], + }, + ]; + const arcs = [ + { + from_lat: 1.2, + from_lon: 103.5, + to_lat: 1.35, + to_lon: 103.82, + kind: "dependency_impact", + }, + ]; + + expect(buildCorrelationHexPolylines(cells)).toHaveLength(1); + expect(buildDependencyImpactArcPolylines(arcs)).toHaveLength(1); + + const earth = new THREE.Group(); + const mgr = createFusionOverlaysManager({ getEarth: () => earth }); + mgr.setOverlayData({ candidate_cells: cells, dependency_arcs: arcs }); + const stats = mgr.getStats(); + expect(stats.hasCorrelationMesh).toBe(true); + expect(stats.hasDependencyMesh).toBe(true); + expect(stats.candidateCount).toBe(1); + expect(stats.dependencyArcCount).toBe(1); + + mgr.dispose(); + expect(earth.children).toHaveLength(0); + }); +}); diff --git a/frontend/public/earth/js/geo-labels.js b/frontend/public/earth/js/geo-labels.js index af30aeb9..7dc0be1b 100644 --- a/frontend/public/earth/js/geo-labels.js +++ b/frontend/public/earth/js/geo-labels.js @@ -301,6 +301,8 @@ export function createGeoLabels() { } return locale; }, + getPlaces: () => places, + getLocale: () => locale, getStats() { const tierCounts = { 1: 0, 2: 0, 3: 0 }; const labels = active @@ -532,3 +534,11 @@ export function clearGeoLabels() { export function getGeoLabelStats() { return _controller.getStats(); } + +export function getLoadedGeoLabelPlaces() { + return _controller.getPlaces(); +} + +export function getGeoLabelLocale() { + return _controller.getLocale(); +} diff --git a/frontend/public/earth/js/geofence-editor.js b/frontend/public/earth/js/geofence-editor.js new file mode 100644 index 00000000..1a0141a4 --- /dev/null +++ b/frontend/public/earth/js/geofence-editor.js @@ -0,0 +1,318 @@ +import * as THREE from "three"; + +import { CONFIG } from "./constants.js"; +import { fetchAdminWriteJson, readStoredAdminAuthState } from "./admin-write-auth.js"; +import { latLonToVector3 } from "./utils.js"; + +const GEOFENCE_RENDER_ORDER = 0.969; +const GEOFENCE_SURFACE_OFFSET = 0.14; + +export function isEditableRole(role) { + const normalized = String(role || "").trim().toLowerCase(); + return normalized === "admin" || normalized === "super_admin"; +} + +export function extractRingsFromGeofence(gf) { + const geom = gf?.geometry || {}; + const gtype = String(geom.type || ""); + const coords = Array.isArray(geom.coordinates) ? geom.coordinates : []; + if (gtype === "Polygon" && coords.length > 0 && Array.isArray(coords[0])) { + return [coords[0]]; + } + if (gtype === "MultiPolygon") { + return coords.filter((poly) => Array.isArray(poly) && Array.isArray(poly[0])).map((poly) => poly[0]); + } + return []; +} + +export function buildClosedPolygonGeoJson(vertices = []) { + const valid = (Array.isArray(vertices) ? vertices : []) + .filter((v) => v && Number.isFinite(Number(v.lat)) && Number.isFinite(Number(v.lon))) + .map((v) => [Number(Number(v.lon).toFixed(5)), Number(Number(v.lat).toFixed(5))]); + if (valid.length < 3) { + throw new Error("At least 3 vertices are required to close a geofence polygon"); + } + const first = valid[0]; + const last = valid[valid.length - 1]; + if (first[0] !== last[0] || first[1] !== last[1]) { + valid.push([first[0], first[1]]); + } + return { + type: "Polygon", + coordinates: [valid], + }; +} + +export function buildGeofenceBatchBuffers(geofences = [], radius = CONFIG.earthRadius + GEOFENCE_SURFACE_OFFSET) { + const fillPositions = []; + const fillColors = []; + const linePositions = []; + const lineColors = []; + + for (const gf of Array.isArray(geofences) ? geofences : []) { + if (gf?.enabled === false) continue; + const isPreset = gf?.kind === "preset"; + const fillColor = isPreset ? [0.22, 0.74, 0.97] : [0.98, 0.75, 0.14]; + const lineColor = isPreset ? [0.38, 0.85, 1.0] : [1.0, 0.84, 0.32]; + + for (const ring of extractRingsFromGeofence(gf)) { + const pts = ring + .filter((pt) => Array.isArray(pt) && pt.length >= 2 && Number.isFinite(Number(pt[0])) && Number.isFinite(Number(pt[1]))) + .map((pt) => latLonToVector3(Number(pt[1]), Number(pt[0]), radius)); + if (pts.length < 3) continue; + + const openPts = + pts[0].distanceToSquared(pts[pts.length - 1]) < 1e-6 && pts.length > 3 + ? pts.slice(0, -1) + : pts; + + for (let i = 0; i < openPts.length; i += 1) { + const a = openPts[i]; + const b = openPts[(i + 1) % openPts.length]; + linePositions.push(a.x, a.y, a.z, b.x, b.y, b.z); + lineColors.push(...lineColor, ...lineColor); + } + + if (openPts.length >= 3) { + const centroid = new THREE.Vector3(); + for (const p of openPts) centroid.add(p); + centroid.divideScalar(openPts.length).normalize().multiplyScalar(radius); + + for (let i = 0; i < openPts.length; i += 1) { + const a = openPts[i]; + const b = openPts[(i + 1) % openPts.length]; + fillPositions.push( + centroid.x, centroid.y, centroid.z, + a.x, a.y, a.z, + b.x, b.y, b.z, + ); + fillColors.push(...fillColor, ...fillColor, ...fillColor); + } + } + } + } + + return { + fillPositions: new Float32Array(fillPositions), + fillColors: new Float32Array(fillColors), + linePositions: new Float32Array(linePositions), + lineColors: new Float32Array(lineColors), + }; +} + +export function createGeofenceLayerManager({ getEarth } = {}) { + let visible = false; + let geofences = []; + let drawingActive = false; + let draftVertices = []; + let rootGroup = null; + let fillMesh = null; + let outlineSegments = null; + let draftLine = null; + + const ensureGroup = () => { + const earth = getEarth?.(); + if (!earth) return null; + if (!rootGroup) { + rootGroup = new THREE.Group(); + rootGroup.name = "geofences_batch_group"; + rootGroup.visible = visible; + earth.add(rootGroup); + } else if (rootGroup.parent !== earth) { + earth.add(rootGroup); + } + return rootGroup; + }; + + const disposeStaticMeshes = () => { + if (fillMesh) { + fillMesh.geometry?.dispose?.(); + fillMesh.material?.dispose?.(); + fillMesh.removeFromParent?.(); + fillMesh = null; + } + if (outlineSegments) { + outlineSegments.geometry?.dispose?.(); + outlineSegments.material?.dispose?.(); + outlineSegments.removeFromParent?.(); + outlineSegments = null; + } + }; + + const disposeDraftMesh = () => { + if (draftLine) { + draftLine.geometry?.dispose?.(); + draftLine.material?.dispose?.(); + draftLine.removeFromParent?.(); + draftLine = null; + } + }; + + const rebuildMeshes = () => { + const group = ensureGroup(); + disposeStaticMeshes(); + if (!group || !geofences.length) return; + + const buffers = buildGeofenceBatchBuffers(geofences); + if (buffers.fillPositions.length > 0) { + const fGeo = new THREE.BufferGeometry(); + fGeo.setAttribute("position", new THREE.BufferAttribute(buffers.fillPositions, 3)); + fGeo.setAttribute("color", new THREE.BufferAttribute(buffers.fillColors, 3)); + const fMat = new THREE.MeshBasicMaterial({ + vertexColors: true, + transparent: true, + opacity: 0.16, + side: THREE.DoubleSide, + depthWrite: false, + }); + fillMesh = new THREE.Mesh(fGeo, fMat); + fillMesh.renderOrder = GEOFENCE_RENDER_ORDER; + fillMesh.name = "geofences_fill_batch"; + group.add(fillMesh); + } + if (buffers.linePositions.length > 0) { + const lGeo = new THREE.BufferGeometry(); + lGeo.setAttribute("position", new THREE.BufferAttribute(buffers.linePositions, 3)); + lGeo.setAttribute("color", new THREE.BufferAttribute(buffers.lineColors, 3)); + const lMat = new THREE.LineBasicMaterial({ + vertexColors: true, + transparent: true, + opacity: 0.78, + depthWrite: false, + }); + outlineSegments = new THREE.LineSegments(lGeo, lMat); + outlineSegments.renderOrder = GEOFENCE_RENDER_ORDER; + outlineSegments.name = "geofences_outline_batch"; + group.add(outlineSegments); + } + }; + + const rebuildDraftMesh = () => { + const group = ensureGroup(); + disposeDraftMesh(); + if (!group || !drawingActive || draftVertices.length === 0) return; + + const r = CONFIG.earthRadius + GEOFENCE_SURFACE_OFFSET + 0.04; + const pts = draftVertices.map((v) => latLonToVector3(v.lat, v.lon, r)); + if (pts.length >= 3) pts.push(pts[0].clone()); + const pos = new Float32Array(pts.length * 3); + pts.forEach((p, idx) => { + pos[idx * 3] = p.x; + pos[idx * 3 + 1] = p.y; + pos[idx * 3 + 2] = p.z; + }); + const dGeo = new THREE.BufferGeometry(); + dGeo.setAttribute("position", new THREE.BufferAttribute(pos, 3)); + const dMat = new THREE.LineBasicMaterial({ + color: 0xfbbf24, + transparent: true, + opacity: 0.95, + depthWrite: false, + }); + draftLine = new THREE.Line(dGeo, dMat); + draftLine.renderOrder = GEOFENCE_RENDER_ORDER + 0.001; + group.add(draftLine); + }; + + const setGeofences = (items = []) => { + geofences = Array.isArray(items) ? items : []; + rebuildMeshes(); + return geofences.length; + }; + + const loadGeofences = async (fetchImpl = globalThis.fetch) => { + const resp = await fetchImpl("/api/v1/geofences?enabled_only=true&ensure_presets=true"); + if (!resp.ok) throw new Error(`HTTP ${resp.status}`); + const payload = await resp.json(); + const count = setGeofences(payload?.items || []); + return { count, items: geofences }; + }; + + const setVisible = (nextVisible) => { + visible = Boolean(nextVisible); + if (rootGroup) rootGroup.visible = visible; + return visible; + }; + + const isVisible = () => visible; + const getGeofences = () => geofences; + const getEditable = () => isEditableRole(readStoredAdminAuthState()?.user?.role); + + const startDrawing = () => { + if (!getEditable()) { + throw new Error("Only admin or super_admin can draw geofences"); + } + drawingActive = true; + draftVertices = []; + setVisible(true); + rebuildDraftMesh(); + return true; + }; + + const cancelDrawing = () => { + drawingActive = false; + draftVertices = []; + disposeDraftMesh(); + }; + + const addVertex = (lat, lon) => { + if (!drawingActive) return 0; + draftVertices.push({ lat: Number(lat), lon: Number(lon) }); + rebuildDraftMesh(); + return draftVertices.length; + }; + + const finishPolygon = async (name, rules = {}, { fetchImpl = globalThis.fetch } = {}) => { + const cleanName = String(name || "").trim(); + if (!cleanName) throw new Error("Geofence name is required"); + const geometry = buildClosedPolygonGeoJson(draftVertices); + const resp = await fetchAdminWriteJson( + "/api/v1/geofences", + { name: cleanName, kind: "custom", geometry, rules, enabled: true }, + { fetchImpl }, + ); + if (!resp.ok) { + const txt = await resp.text(); + throw new Error(txt || `HTTP ${resp.status}`); + } + const created = await resp.json(); + cancelDrawing(); + setGeofences([created, ...geofences]); + setVisible(true); + return created; + }; + + const getStats = () => ({ + visible, + count: geofences.length, + drawingActive, + draftVertexCount: draftVertices.length, + editable: getEditable(), + hasFillMesh: Boolean(fillMesh), + hasOutlineMesh: Boolean(outlineSegments), + }); + + const dispose = () => { + cancelDrawing(); + disposeStaticMeshes(); + rootGroup?.removeFromParent?.(); + rootGroup = null; + geofences = []; + }; + + return { + setGeofences, + loadGeofences, + setVisible, + isVisible, + getGeofences, + getEditable, + isDrawing: () => drawingActive, + startDrawing, + cancelDrawing, + addVertex, + finishPolygon, + getStats, + dispose, + }; +} diff --git a/frontend/public/earth/js/geofence-editor.test.js b/frontend/public/earth/js/geofence-editor.test.js new file mode 100644 index 00000000..18bc0092 --- /dev/null +++ b/frontend/public/earth/js/geofence-editor.test.js @@ -0,0 +1,52 @@ +import { describe, expect, test } from "bun:test"; +import * as THREE from "three"; +import { + buildClosedPolygonGeoJson, + buildGeofenceBatchBuffers, + createGeofenceLayerManager, + isEditableRole, +} from "./geofence-editor.js"; + +describe("geofence-editor", () => { + test("validates role gating for admin vs viewer", () => { + expect(isEditableRole("admin")).toBe(true); + expect(isEditableRole("super_admin")).toBe(true); + expect(isEditableRole("viewer")).toBe(false); + expect(isEditableRole("")).toBe(false); + }); + + test("closes drawn polygon ring and batches multiple geofences into one fill + outline", () => { + const poly = buildClosedPolygonGeoJson([ + { lat: 1.1, lon: 103.5 }, + { lat: 1.5, lon: 103.5 }, + { lat: 1.5, lon: 104.0 }, + ]); + expect(poly.type).toBe("Polygon"); + expect(poly.coordinates[0]).toHaveLength(4); + expect(poly.coordinates[0][0]).toEqual(poly.coordinates[0][3]); + + const batch = buildGeofenceBatchBuffers([ + { id: 1, kind: "preset", enabled: true, geometry: poly }, + { + id: 2, + kind: "custom", + enabled: true, + geometry: { + type: "Polygon", + coordinates: [[[2.0, 100.0], [2.4, 100.0], [2.4, 100.5], [2.0, 100.5], [2.0, 100.0]]], + }, + }, + ]); + expect(batch.fillPositions.length).toBe(3 * 9 + 4 * 9); + expect(batch.linePositions.length).toBe(3 * 6 + 4 * 6); + + const earth = new THREE.Group(); + const mgr = createGeofenceLayerManager({ getEarth: () => earth }); + mgr.setGeofences([{ id: 1, kind: "preset", enabled: true, geometry: poly }]); + expect(mgr.getStats().hasFillMesh).toBe(true); + expect(mgr.getStats().hasOutlineMesh).toBe(true); + mgr.dispose(); + expect(mgr.getStats().hasFillMesh).toBe(false); + expect(earth.children).toHaveLength(0); + }); +}); diff --git a/frontend/public/earth/js/gps-jamming-math.js b/frontend/public/earth/js/gps-jamming-math.js new file mode 100644 index 00000000..913a7992 --- /dev/null +++ b/frontend/public/earth/js/gps-jamming-math.js @@ -0,0 +1,102 @@ +// gps-jamming-math.js - Pure H3 polygon triangulation for GPS/GNSS jamming layer + +// Raise slightly above EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET (0.48) to clear H3 res-4 chord sagitta (~0.009) +export const GPS_JAMMING_RADIUS_OFFSET = 0.515; + +export const GPS_JAMMING_COLORS = Object.freeze({ + high: [0.94, 0.24, 0.24, 0.76], + medium: [0.98, 0.58, 0.05, 0.58], + low: [0.95, 0.80, 0.08, 0.40], +}); + +const GPS_JAMMING_LEVEL_OFFSET = Object.freeze({ + high: 0.525, + medium: 0.515, + low: 0.505, +}); + +function latLonToXYZ(lat, lon, radius) { + const phi = (90 - lat) * (Math.PI / 180); + const theta = (lon + 180) * (Math.PI / 180); + const sinPhi = Math.sin(phi); + return [ + -(radius * sinPhi * Math.cos(theta)), + radius * Math.cos(phi), + radius * sinPhi * Math.sin(theta), + ]; +} + +function wrapLonNear(lon, refLon) { + let wrapped = lon; + while (wrapped - refLon > 180) wrapped -= 360; + while (wrapped - refLon < -180) wrapped += 360; + return wrapped; +} + +export function buildGpsJammingGeometryBuffers(cells, { earthRadius = 100 } = {}) { + const list = Array.isArray(cells) ? cells : []; + const radius = earthRadius + GPS_JAMMING_RADIUS_OFFSET; + let totalTriangles = 0; + const normalizedCells = []; + + for (let i = 0; i < list.length; i += 1) { + const cell = list[i]; + const boundary = Array.isArray(cell?.boundary) ? cell.boundary : []; + const lat = Number(cell?.lat); + const lon = Number(cell?.lon); + if (boundary.length < 3 || !Number.isFinite(lat) || !Number.isFinite(lon)) continue; + totalTriangles += boundary.length; + normalizedCells.push({ + ...cell, + lat, + lon, + boundary: boundary.map(([bLat, bLon]) => [Number(bLat), wrapLonNear(Number(bLon), lon)]), + }); + } + + const positions = new Float32Array(totalTriangles * 9); + const colors = new Float32Array(totalTriangles * 12); + let posOffset = 0; + let colOffset = 0; + + for (let c = 0; c < normalizedCells.length; c += 1) { + const cell = normalizedCells[c]; + const levelKey = String(cell.level || "low").toLowerCase(); + const rgba = GPS_JAMMING_COLORS[levelKey] || GPS_JAMMING_COLORS.low; + const cellRadius = earthRadius + (GPS_JAMMING_LEVEL_OFFSET[levelKey] ?? GPS_JAMMING_RADIUS_OFFSET); + const center = latLonToXYZ(cell.lat, cell.lon, cellRadius); + const ring = cell.boundary; + const ringLen = ring.length; + + for (let k = 0; k < ringLen; k += 1) { + const p1 = ring[k]; + const p2 = ring[(k + 1) % ringLen]; + const v1 = latLonToXYZ(p1[0], p1[1], cellRadius); + const v2 = latLonToXYZ(p2[0], p2[1], cellRadius); + + positions[posOffset++] = center[0]; + positions[posOffset++] = center[1]; + positions[posOffset++] = center[2]; + positions[posOffset++] = v1[0]; + positions[posOffset++] = v1[1]; + positions[posOffset++] = v1[2]; + positions[posOffset++] = v2[0]; + positions[posOffset++] = v2[1]; + positions[posOffset++] = v2[2]; + + for (let v = 0; v < 3; v += 1) { + colors[colOffset++] = rgba[0]; + colors[colOffset++] = rgba[1]; + colors[colOffset++] = rgba[2]; + colors[colOffset++] = rgba[3]; + } + } + } + + return { + vertexCount: totalTriangles * 3, + positions, + colors, + cellsMeta: normalizedCells, + }; +} diff --git a/frontend/public/earth/js/gps-jamming-worker.js b/frontend/public/earth/js/gps-jamming-worker.js new file mode 100644 index 00000000..e85c83c4 --- /dev/null +++ b/frontend/public/earth/js/gps-jamming-worker.js @@ -0,0 +1,27 @@ +// gps-jamming-worker.js - Web Worker for H3 hexagon fan triangulation +import { buildGpsJammingGeometryBuffers } from "./gps-jamming-math.js"; + +self.addEventListener("message", (event) => { + const { id, type, cells, earthRadius } = event.data || {}; + if (type !== "triangulate") return; + try { + const result = buildGpsJammingGeometryBuffers(cells, { earthRadius }); + self.postMessage( + { + id, + ok: true, + vertexCount: result.vertexCount, + positions: result.positions, + colors: result.colors, + cellsMeta: result.cellsMeta, + }, + [result.positions.buffer, result.colors.buffer], + ); + } catch (error) { + self.postMessage({ + id, + ok: false, + error: error?.message || String(error), + }); + } +}); diff --git a/frontend/public/earth/js/gps-jamming.js b/frontend/public/earth/js/gps-jamming.js new file mode 100644 index 00000000..a0a65eee --- /dev/null +++ b/frontend/public/earth/js/gps-jamming.js @@ -0,0 +1,241 @@ +// gps-jamming.js - Single-mesh H3 GNSS/GPS interference overlay (R+0.515, renderOrder 0.968) +import * as THREE from "three"; +import { CONFIG, PATHS } from "./constants.js"; +import { buildGpsJammingGeometryBuffers } from "./gps-jamming-math.js"; + +const GPS_JAMMING_RENDER_ORDER = 0.968; + +const GPS_JAMMING_VERT = ` + uniform float uEarthRadius; + varying vec4 vColor; + void main() { + float offset = length(position) - uEarthRadius; + if (offset > 0.520) { + vColor = vec4(0.94, 0.24, 0.24, 0.76); + } else if (offset > 0.510) { + vColor = vec4(0.98, 0.58, 0.05, 0.58); + } else { + vColor = vec4(0.95, 0.80, 0.08, 0.40); + } + gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); + } +`; + +const GPS_JAMMING_FRAG = ` + varying vec4 vColor; + void main() { + gl_FragColor = vColor; + } +`; + +let showGpsJamming = false; +let jammingGroup = null; +let jammingMesh = null; +let jammingMaterial = null; +let workerInstance = null; +let workerRequestId = 0; +let loadGeneration = 0; +let cellsMeta = []; +let latestSnapshotMeta = { + date: null, + stats: { total: 0, high: 0, medium: 0, low: 0 }, +}; +let earthRef = null; + +function getOrCreateWorker() { + if (typeof Worker === "undefined") return null; + if (!workerInstance) { + workerInstance = new Worker(new URL("./gps-jamming-worker.js", import.meta.url), { + type: "module", + }); + } + return workerInstance; +} + +function terminateWorker() { + if (workerInstance) { + workerInstance.terminate(); + workerInstance = null; + } +} + +async function triangulateInWorkerOrMain(cells) { + const worker = getOrCreateWorker(); + if (!worker) { + return buildGpsJammingGeometryBuffers(cells, { earthRadius: CONFIG.earthRadius }); + } + const reqId = ++workerRequestId; + return new Promise((resolve, reject) => { + const onMessage = (event) => { + const msg = event.data; + if (!msg || msg.id !== reqId) return; + worker.removeEventListener("message", onMessage); + worker.removeEventListener("error", onError); + if (msg.ok) resolve(msg); + else reject(new Error(msg.error || "GPS jamming worker failed")); + }; + const onError = (err) => { + worker.removeEventListener("message", onMessage); + worker.removeEventListener("error", onError); + reject(err); + }; + worker.addEventListener("message", onMessage); + worker.addEventListener("error", onError); + worker.postMessage({ + id: reqId, + type: "triangulate", + cells, + earthRadius: CONFIG.earthRadius, + }); + }); +} + +function applyTriangulatedMesh(buffers, earth) { + if (!showGpsJamming || !earth) return; + cellsMeta = Array.isArray(buffers.cellsMeta) ? buffers.cellsMeta : []; + + if (!jammingGroup) { + jammingGroup = new THREE.Object3D(); + jammingGroup.name = "gps-jamming-layer-group"; + earth.add(jammingGroup); + } + + const geom = new THREE.BufferGeometry(); + geom.setAttribute("position", new THREE.BufferAttribute(buffers.positions, 3)); + geom.setDrawRange(0, buffers.vertexCount); + geom.computeBoundingSphere(); + + if (!jammingMaterial) { + jammingMaterial = new THREE.ShaderMaterial({ + uniforms: { + uEarthRadius: { value: Number(CONFIG.earthRadius) || 100.0 }, + }, + vertexShader: GPS_JAMMING_VERT, + fragmentShader: GPS_JAMMING_FRAG, + transparent: true, + depthTest: true, + depthWrite: false, + side: THREE.DoubleSide, + polygonOffset: true, + polygonOffsetFactor: -2, + polygonOffsetUnits: -2, + }); + } + + if (!jammingMesh) { + jammingMesh = new THREE.Mesh(geom, jammingMaterial); + jammingMesh.renderOrder = GPS_JAMMING_RENDER_ORDER; + jammingMesh.frustumCulled = false; + jammingMesh.raycast = () => {}; + jammingGroup.add(jammingMesh); + } else { + const prevGeom = jammingMesh.geometry; + jammingMesh.geometry = geom; + prevGeom?.dispose?.(); + } + jammingGroup.visible = showGpsJamming && buffers.vertexCount > 0; +} + +export function getShowGpsJamming() { + return showGpsJamming; +} + +export function getGpsJammingCount() { + return cellsMeta.length; +} + +export function getGpsJammingSnapshotMeta() { + return latestSnapshotMeta; +} + +export function clearGpsJammingData(earth = earthRef) { + loadGeneration += 1; + terminateWorker(); + if (jammingMesh) { + jammingMesh.geometry?.dispose?.(); + jammingMesh.parent?.remove(jammingMesh); + jammingMesh = null; + } + if (jammingMaterial) { + jammingMaterial.dispose?.(); + jammingMaterial = null; + } + if (jammingGroup) { + jammingGroup.parent?.remove(jammingGroup); + jammingGroup = null; + } + if (earth && jammingGroup?.parent === earth) { + earth.remove(jammingGroup); + } + cellsMeta = []; +} + +export function toggleGpsJamming(show, earth = earthRef) { + showGpsJamming = Boolean(show); + if (earth) earthRef = earth; + if (!showGpsJamming) { + clearGpsJammingData(earthRef); + return; + } + if (jammingGroup) jammingGroup.visible = true; +} + +export async function loadGpsJamming(_scene, earth) { + if (earth) earthRef = earth; + if (!showGpsJamming || !earthRef) return { totalCount: 0 }; + const gen = ++loadGeneration; + const resp = await fetch(PATHS.gpsJammingSnapshotApi, { cache: "no-store" }); + if (!resp.ok) throw new Error(`GPS jamming HTTP ${resp.status}`); + const payload = await resp.json(); + if (gen !== loadGeneration || !showGpsJamming) return { totalCount: 0 }; + + latestSnapshotMeta = { + date: payload?.date || null, + stats: payload?.stats || { total: 0, high: 0, medium: 0, low: 0 }, + }; + const cells = Array.isArray(payload?.cells) ? payload.cells : []; + const buffers = await triangulateInWorkerOrMain(cells); + if (gen !== loadGeneration || !showGpsJamming) return { totalCount: 0 }; + + applyTriangulatedMesh(buffers, earthRef); + return { + totalCount: cellsMeta.length, + date: latestSnapshotMeta.date, + stats: latestSnapshotMeta.stats, + }; +} + +function pointInRing(lat, lon, ring) { + let inside = false; + for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) { + const yi = ring[i][0]; + const xi = ring[i][1]; + const yj = ring[j][0]; + const xj = ring[j][1]; + const intersect = (yi > lat) !== (yj > lat) && lon < ((xj - xi) * (lat - yi)) / ((yj - yi) || 1e-9) + xi; + if (intersect) inside = !inside; + } + return inside; +} + +export function findGpsJammingCellAtLatLon(lat, lon) { + if (!showGpsJamming || !cellsMeta.length || !Number.isFinite(lat) || !Number.isFinite(lon)) { + return null; + } + for (let i = 0; i < cellsMeta.length; i += 1) { + const cell = cellsMeta[i]; + if (Math.abs(cell.lat - lat) > 2.2 || Math.abs(cell.lon - lon) > 3.2) continue; + if (Array.isArray(cell.boundary) && pointInRing(lat, lon, cell.boundary)) { + return cell; + } + } + return null; +} + +export function getGpsJammingLegendItems() { + return [ + { key: "high", label: "强干扰 (>10%)", color: "#ef4444", shape: "dot" }, + { key: "medium", label: "中干扰 (2%-10%)", color: "#f59e0b", shape: "dot" }, + { key: "low", label: "低干扰 (<2%)", color: "#eab308", shape: "dot" }, + ]; +} diff --git a/frontend/public/earth/js/hud-focus-stack.js b/frontend/public/earth/js/hud-focus-stack.js index b72cf5c3..bc0977ec 100644 --- a/frontend/public/earth/js/hud-focus-stack.js +++ b/frontend/public/earth/js/hud-focus-stack.js @@ -27,6 +27,7 @@ const DYNAMIC_CARD_SELECTOR = [ ".news-region-card", "#info-panel", "#news-hud-panel", + "#source-freshness-popover", "#situational-copilot", ".compute-picker", "#media-panel", diff --git a/frontend/public/earth/js/i18n.js b/frontend/public/earth/js/i18n.js index 44cfad7c..50000fb6 100644 --- a/frontend/public/earth/js/i18n.js +++ b/frontend/public/earth/js/i18n.js @@ -36,6 +36,18 @@ const EARTH_MESSAGE_TEMPLATES = { zh: "正在加载船只数据...", en: "Loading vessel data...", }, + "loading.aircraftData": { + zh: "正在加载航空器 ADS-B 数据...", + en: "Loading aircraft ADS-B data...", + }, + "loading.gpsJammingData": { + zh: "正在加载 GPS 干扰数据...", + en: "Loading GPS jamming data...", + }, + "loading.disastersData": { + zh: "正在加载自然灾害数据...", + en: "Loading natural disaster data...", + }, "loading.satelliteData": { zh: "正在加载卫星数据...", en: "Loading satellite data...", @@ -68,6 +80,26 @@ const EARTH_MESSAGE_TEMPLATES = { zh: "正在加载船只...", en: "Loading vessels...", }, + "startup.aircraft": { + zh: "正在加载航空器...", + en: "Loading aircraft...", + }, + "startup.gpsJamming": { + zh: "正在加载 GPS 干扰热区...", + en: "Loading GPS interference cells...", + }, + "startup.disasters": { + zh: "正在加载自然灾害态势...", + en: "Loading natural disaster telemetry...", + }, + "startup.geofences": { + zh: "正在加载电子围栏...", + en: "Loading geofences...", + }, + "startup.fusionOverlays": { + zh: "正在加载多域关联与影响链...", + en: "Loading fusion correlations & dependency arcs...", + }, "startup.bgp": { zh: "正在加载BGP态势...", en: "Loading BGP situation...", @@ -188,6 +220,26 @@ const EARTH_MESSAGE_TEMPLATES = { zh: ({ detail }) => `高精国界不可用:${detail}`, en: ({ detail }) => `High-precision boundaries unavailable: ${detail}`, }, + "status.viewMode2d": { + zh: "已切换至 2D 平面地图", + en: "Switched to 2D flat map view", + }, + "status.viewMode3d": { + zh: "已返回 3D 地球视图", + en: "Returned to 3D globe view", + }, + "status.replayEntered": { + zh: "4D 时空回放已启用", + en: "4D Replay active", + }, + "status.replayExited": { + zh: "已恢复实时态势", + en: "Returned to Live", + }, + "status.viewMode2dFailed": { + zh: "2D 平面地图加载失败,已保留 3D 地球视图", + en: "2D flat map failed to load; keeping 3D globe view", + }, "status.cameraModeDetected": { zh: ({ count, mode }) => `检测到 ${count} 个物理摄像头:${mode === "dual" ? "双摄 3D" : "单摄 2D"}`, en: ({ count, mode }) => `${count} physical cameras detected: ${mode === "dual" ? "Dual 3D" : "Single 2D"}`, @@ -326,6 +378,10 @@ const EARTH_MESSAGE_TEMPLATES = { zh: "动捕识别动作已更新", en: "Motion gestures updated", }, + "status.cacheCleared": { + zh: "本地资源缓存已清理", + en: "Local asset cache cleared", + }, "status.settingsReset": { zh: "设置已重置", en: "Settings reset", @@ -527,6 +583,46 @@ const EARTH_MESSAGE_TEMPLATES = { }; const EXACT_TRANSLATIONS = { + "查看各域数据源健康与情报盲区": "Inspect domain source health and intelligence blind spots", + "数据源健康 · 检测中": "Source health · Checking", + "数据源健康与盲区": "Source Health & Blind Spots", + "非最新域不可描述为无事件": "Non-fresh domains must not be reported as event-free", + "立即刷新": "Refresh now", + "自然灾害": "Natural Disasters", + "地震、林火热点与灾难预警": "Earthquakes, wildfire clusters & disaster alerts", + "切换自然灾害显示": "Toggle natural disasters layer", + "隐藏自然灾害": "Hide natural disasters", + "显示自然灾害": "Show natural disasters", + "自然灾害加载中...": "Loading natural disasters...", + "自然灾害详情": "Natural Disaster Details", + "事件标题": "Event Title", + "灾害类型": "Disaster Type", + "严重程度": "Severity", + "震级 / 强度": "Magnitude / Intensity", + "火点簇规模": "Hotspot Cluster Count", + "最高亮温": "Max Brightness Temp", + "地震": "Earthquake", + "林火热点簇": "Wildfire Cluster", + "热带气旋/风暴": "Cyclone / Storm", + "洪涝灾害": "Flood", + "火山活动": "Volcano", + "干旱": "Drought", + "其他自然异常": "Other Hazard", + "NGA 海缆告警": "NGA Cable Advisory", + "告警出处": "Advisory Source", + "无活跃 NGA 海缆通告": "No active NGA cable advisory", + "军舰/特种角色": "Naval / Special Role", + "海缆工程船": "Cable Repair Ship", + "所在咽喉要道": "Maritime Chokepoint", + "海上咽喉要道": "Maritime Chokepoints", + "战区": "Theater", + "战区预设": "Theater Presets", + "按重点战区态势筛选。": "Filter news by regional theater.", + "俄乌": "Russia-Ukraine", + "中东": "Middle East", + "印太": "Indo-Pacific", + "未分级": "Unrated", + "国家背景": "State-Affiliated", "城市地名标注": "City labels", "放大地球时逐级显示首都、主要城市与省会名称": "Reveal capitals, major cities, and regional capitals progressively on zoom", "放大地球时逐级显示首都与主要城市": "Reveal capitals and major cities on zoom", @@ -1656,6 +1752,102 @@ const EXACT_TRANSLATIONS = { "加入多物件对比分析": "Add to joint comparison", "未定位集群": "Unlocated Cluster", "跨国部署提醒:实证位置与源登记国不同,请核对后采用": "Cross-country deployment notice: verified location differs from registered country; review manually before applying", + "本地资源缓存": "Local Asset Cache", + "清理缓存": "Clear Cache", + "正在清理…": "Clearing…", + "当前占用:计算中…": "Used: Calculating…", + "当前占用:0 B": "Used: 0 B", + "2D 平面地图": "2D Flat Map", + "切换 2D 平面视图": "Switch to 2D flat view", + "返回 3D 地球视图": "Return to 3D globe view", + "已放大至极限 · 切换 2D 平面视图继续放大": "Max 3D zoom reached · Switch to 2D view to zoom further", + "关闭提示": "Dismiss prompt", + "工作流空间态势卡片": "Workflow Spatial Comparison Cards", + "关联目标样本": "Entity Samples", + "暂无关联样本": "No linked samples", + "时序走廊": "Corridor Timeline", + "双边对比比例尺": "Bilateral Duel Scale", + "结构构成": "Composition", + "电子围栏": "Geofences", + "海缆走廊与咽喉监测区": "Cable corridor & chokepoint watchzones", + "切换电子围栏显示": "Toggle geofences display", + "显示电子围栏": "Show geofences", + "隐藏电子围栏": "Hide geofences", + "电子围栏加载中...": "Loading geofences...", + "态势事件与围栏处置": "Incidents & Geofences", + "打开态势事件与围栏处置": "Open incidents & geofences drawer", + "态势事件与围栏": "Incidents & Geofences", + "绘制电子围栏": "Draw Geofence", + "输入围栏名称": "Geofence name", + "保存围栏": "Save Polygon", + "取消": "Cancel", + "规则告警": "Rule Alert", + "待核查": "Pending Verification", + "依赖影响": "Dependency Impact", + "驳回": "Dismiss", + "解决": "Resolve", + "提交驳回": "Submit Dismiss", + "必填驳回理由": "Required dismissal reason", + "当前暂无活跃态势事件": "No active situational incidents", + "请在地球表面依次点击至少 3 个顶点": "Click at least 3 vertices on the globe", + "电子围栏已保存": "Geofence saved", + "事件状态已更新": "Incident updated", + "事件已驳回": "Incident dismissed", + "驳回必须填写理由": "Dismissal requires a reason", + "预置围栏(海缆/咽喉)": "Preset (Cables / Chokepoints)", + "自定义多边形围栏": "Custom Polygon Geofence", + "关联与影响链": "Correlations & Impact Chains", + "H3 待核查关联与海缆影响链": "H3 candidate correlations & cable impact chains", + "切换关联与影响链显示": "Toggle correlations & impact chains", + "显示关联与影响链": "Show correlations & impact chains", + "隐藏关联与影响链": "Hide correlations & impact chains", + "关联与影响链加载中...": "Loading correlations & impact chains...", + "待核查关联(虚线六边形 · 待核查)": "Candidate Correlation (Dashed Hex · Pending)", + "依赖影响链(实线弧 · 有独立证据)": "Dependency Impact Chain (Solid Arc · Corroborated)", + "4D 时空回放": "4D Replay", + "四维时空回放轴": "4D Spatiotemporal Replay", + "打开四维时空回放": "Open 4D Replay Timeline", + "实时态": "LIVE", + "回放态": "REPLAY", + "进入回放": "Enter Replay", + "返回实时": "Return Live", + "播放": "Play", + "暂停": "Pause", + "倍速": "Speed", + "时间滑块": "Time Scrubber", + "全历史": "All", + "实体关系图谱": "Ontology Graph", + "打开实体关系图谱": "Open Ontology Graph", + "关系图谱": "Ontology Graph", + "调查卷宗工作台": "Investigation Cases", + "调查卷宗": "Investigation Cases", + "打开调查卷宗工作台": "Open Investigation Cases", + "加入卷宗": "Add to Case", + "动作审批中心": "Action Approvals", + "动作审批": "Actions", + "动作与审批": "Actions", + "打开动作审批中心": "Open Action Approvals", + "新建卷宗标题(如:亚太海缆异常研判)": "New case title", + "创建卷宗": "New Case", + "固化不可变版本": "Freeze Version", + "导出 Markdown": "Export MD", + "打印 / PDF 报告": "Print / PDF", + "外发告警通知 (需审批)": "Notify Webhook (Approval)", + "加入重点关注": "Add to Watchlist", + "发起动作": "Submit Action", + "批准执行": "Approve", + "4D 时空回放已启用": "4D Replay active", + "已恢复实时态势": "Returned to Live", + "航空器": "Aircraft", + "军机与民航 ADS-B": "Military & Civil ADS-B", + "全球军机与民航 ADS-B": "Global Military & Civil ADS-B", + "GPS 干扰": "GPS Jamming", + "GNSS 干扰监测热区": "GNSS interference zones", + "GNSS 信号干扰热区": "GNSS signal interference zones", + "已启用 0 个图层": "0 layers enabled", + "切换航空器显示": "Toggle aircraft display", + "切换 GPS 干扰显示": "Toggle GPS jamming display", + "切换 BGP 观测显示": "Toggle BGP observation display", }; const PATTERN_TRANSLATIONS = [ @@ -1763,6 +1955,8 @@ const PATTERN_TRANSLATIONS = [ [/^(\d+) 分钟前$/, "$1m ago"], [/^新闻源请求失败: (\d+)$/, "News request failed: $1"], [/^来源 (.+)$/, "Source $1"], + [/^当前占用:(.+)((\d+) 项)$/, "Used: $1 ($2 items)"], + [/^当前占用:(.+)$/, "Used: $1"], [/^更新 (.+)$/, "Updated $1"], [/^置信 (.+)$/, "Confidence $1"], [/^已复制(.+):(.+)$/, (match, locale) => `Copied ${translateText(match[1], locale)}: ${match[2]}`], diff --git a/frontend/public/earth/js/incidents-hud.js b/frontend/public/earth/js/incidents-hud.js new file mode 100644 index 00000000..4af03a81 --- /dev/null +++ b/frontend/public/earth/js/incidents-hud.js @@ -0,0 +1,269 @@ +import { getEarthLocale, translateText } from "./i18n.js"; +import { createHUDPanel } from "./hud-panels.js"; +import { sharedHudFocusStack } from "./hud-focus-stack.js"; +import { fetchAdminWriteJson, readStoredAdminAuthState } from "./admin-write-auth.js"; +import { isEditableRole } from "./geofence-editor.js"; + +const t = (zh, en) => (getEarthLocale() === "en-US" ? en : zh); + +function escapeHtml(text) { + return String(text ?? "") + .replaceAll("&", "&") + .replaceAll("<", "<") + .replaceAll(">", ">") + .replaceAll('"', """); +} + +function assessmentBadge(kind) { + if (kind === "dependency_impact") { + return { cls: "is-impact", label: t("依赖影响", "Dependency Impact") }; + } + if (kind === "candidate_correlation") { + return { cls: "is-candidate", label: t("待核查", "Pending Verification") }; + } + return { cls: "is-rule", label: t("规则告警", "Rule Alert") }; +} + +export function initIncidentsHud({ + rootParent = typeof document !== "undefined" ? document.body : null, + geofenceManager = null, + onSelectIncident = null, + onIncidentsChanged = null, + onStatus = null, +} = {}) { + const panelEl = document.createElement("aside"); + panelEl.id = "incidents-triage-hud"; + panelEl.className = "hud-panel incidents-hud-panel hud-panel-draggable"; + panelEl.hidden = true; + panelEl.setAttribute("role", "dialog"); + panelEl.setAttribute("aria-modal", "false"); + panelEl.setAttribute("aria-label", t("态势事件与围栏处置", "Incidents & Geofences")); + + panelEl.innerHTML = ` +
+
+ +

${escapeHtml(t("态势事件与围栏处置", "Incidents & Geofences"))}

+
+
+ + +
+
+
+ + + +
+
+ `; + + rootParent?.append?.(panelEl); + const hudPanel = createHUDPanel({ + panel: panelEl, + header: ".hud-panel__header", + body: "#incidents-hud-list", + }); + sharedHudFocusStack.register(panelEl, { focus: false }); + + const listEl = panelEl.querySelector("#incidents-hud-list"); + const drawBtn = panelEl.querySelector("#geofence-draw-toggle"); + const drawControls = panelEl.querySelector("#geofence-draw-controls"); + const drawNameInput = panelEl.querySelector("#geofence-draw-name"); + const drawSaveBtn = panelEl.querySelector("#geofence-draw-save"); + const drawCancelBtn = panelEl.querySelector("#geofence-draw-cancel"); + const drawStatus = panelEl.querySelector("#geofence-draw-status"); + + let items = []; + let dismissingId = null; + + const syncRoleUi = () => { + const editable = isEditableRole(readStoredAdminAuthState()?.user?.role); + if (drawBtn) { + drawBtn.hidden = !editable; + } + }; + + const renderList = () => { + syncRoleUi(); + const editable = isEditableRole(readStoredAdminAuthState()?.user?.role); + if (!listEl) return; + if (!items.length) { + listEl.innerHTML = `

${escapeHtml(t("当前暂无活跃态势事件", "No active situational incidents"))}

`; + return; + } + listEl.innerHTML = items + .map((item) => { + const badge = assessmentBadge(item.assessment_kind); + const objs = Array.isArray(item.object_ids) ? item.object_ids.slice(0, 4) : []; + const isDismissing = dismissingId === item.id; + return `
+
+ ${escapeHtml(badge.label)} + ${escapeHtml(translateText(item.status || "open"))} +
+

${escapeHtml(item.title || item.incident_type)}

+ ${objs.length ? `
${objs.map((o) => ``).join("")}
` : ""} + ${item.resolution_note ? `

${escapeHtml(item.resolution_note)}

` : ""} + ${ + editable + ? `
+ + + +
` + : "" + } + ${ + editable && isDismissing + ? `
+ + +
` + : "" + } +
`; + }) + .join(""); + }; + + const refresh = async (fetchImpl = globalThis.fetch) => { + const resp = await fetchImpl("/api/v1/incidents?limit=60"); + if (!resp.ok) throw new Error(`HTTP ${resp.status}`); + const data = await resp.json(); + items = Array.isArray(data?.items) ? data.items : []; + renderList(); + return items; + }; + + const transition = async (id, action, reason = "") => { + const body = reason ? { resolution_note: reason } : {}; + const resp = await fetchAdminWriteJson(`/api/v1/incidents/${id}/${action}`, body); + if (!resp.ok) { + const errTxt = await resp.text(); + throw new Error(errTxt || `HTTP ${resp.status}`); + } + const updated = await resp.json(); + dismissingId = null; + items = items.map((it) => (it.id === updated.id ? updated : it)); + renderList(); + await onIncidentsChanged?.(updated); + return updated; + }; + + panelEl.querySelector("#incidents-close-btn")?.addEventListener("click", () => { + panelEl.hidden = true; + }); + panelEl.querySelector("#incidents-refresh-btn")?.addEventListener("click", () => { + void refresh().catch((err) => onStatus?.(err?.message || String(err), "error")); + }); + + drawBtn?.addEventListener("click", () => { + try { + geofenceManager?.startDrawing?.(); + if (drawControls) drawControls.hidden = false; + if (drawStatus) drawStatus.textContent = t("请在地球表面依次点击至少 3 个顶点", "Click at least 3 vertices on the globe"); + } catch (err) { + onStatus?.(err?.message || String(err), "error"); + } + }); + + drawCancelBtn?.addEventListener("click", () => { + geofenceManager?.cancelDrawing?.(); + if (drawControls) drawControls.hidden = true; + if (drawStatus) drawStatus.textContent = ""; + }); + + drawSaveBtn?.addEventListener("click", async () => { + try { + const name = String(drawNameInput?.value || "").trim() || `Custom Fence ${new Date().toISOString().slice(11, 16)}`; + await geofenceManager?.finishPolygon?.(name); + if (drawNameInput) drawNameInput.value = ""; + if (drawControls) drawControls.hidden = true; + if (drawStatus) drawStatus.textContent = t("电子围栏已保存", "Geofence saved"); + await onIncidentsChanged?.(); + } catch (err) { + if (drawStatus) drawStatus.textContent = err?.message || String(err); + } + }); + + listEl?.addEventListener("click", async (event) => { + const target = event?.target; + if (!(target instanceof HTMLElement)) return; + + const objBtn = target.closest("[data-object-id]"); + if (objBtn instanceof HTMLElement) { + const oid = objBtn.dataset.objectId || ""; + const found = items.find((i) => Array.isArray(i.object_ids) && i.object_ids.includes(oid)); + onSelectIncident?.(found || null, oid); + return; + } + + const actBtn = target.closest("[data-incident-action]"); + if (!(actBtn instanceof HTMLElement)) return; + const action = actBtn.dataset.incidentAction; + const id = Number(actBtn.dataset.incidentId); + if (!Number.isFinite(id)) return; + + if (action === "toggle-dismiss") { + dismissingId = dismissingId === id ? null : id; + renderList(); + return; + } + if (action === "acknowledge" || action === "resolve") { + try { + await transition(id, action); + onStatus?.(t("事件状态已更新", "Incident updated"), "info"); + } catch (err) { + onStatus?.(err?.message || String(err), "error"); + } + return; + } + if (action === "confirm-dismiss") { + const reasonInput = panelEl.querySelector(`[data-dismiss-reason-for="${id}"]`); + const reason = String(reasonInput?.value || "").trim(); + if (!reason) { + onStatus?.(t("驳回必须填写理由", "Dismissal requires a reason"), "error"); + return; + } + try { + await transition(id, "dismiss", reason); + onStatus?.(t("事件已驳回", "Incident dismissed"), "info"); + } catch (err) { + onStatus?.(err?.message || String(err), "error"); + } + } + }); + + const open = async () => { + panelEl.hidden = false; + sharedHudFocusStack.focus(panelEl); + await refresh().catch((err) => onStatus?.(err?.message || String(err), "error")); + }; + + const close = () => { + panelEl.hidden = true; + }; + + return { + open, + close, + refresh, + setVertexFeedback: (count) => { + if (drawStatus) drawStatus.textContent = t(`已拾取 ${count} 个顶点`, `${count} vertices picked`); + }, + getItems: () => items, + destroy: () => { + hudPanel?.destroy?.(); + panelEl.remove(); + }, + }; +} diff --git a/frontend/public/earth/js/info-card.js b/frontend/public/earth/js/info-card.js index 4d9a62d0..3ad7d4d2 100644 --- a/frontend/public/earth/js/info-card.js +++ b/frontend/public/earth/js/info-card.js @@ -450,6 +450,26 @@ function getMobileDetailIdentity(type, config, data) { if (data?.status && data.status !== '-') { metrics.push({ label: infoText('航行状态'), value: translateInfoCardValue(String(data.status)) }); } + } else if (type === 'aircraft') { + title = data?.callsign && data.callsign !== '-' ? `${data.callsign} (${data?.icao24 || ''})` : (data?.icao24 || infoText('航空器')); + categoryLabel = translateInfoCardValue(data?.category || 'aircraft'); + subtitle = [data?.aircraft_type, data?.operator, data?.registration].filter((v) => v && v !== '-').join(' · ') || `ICAO24 ${data?.icao24 || '-'}`; + if (data?.is_emergency) { + statusBadge = `${infoText('紧急')} ${data?.emergency_code || '7700'}`; + statusBadgeType = 'critical'; + } else if (data?.is_military) { + statusBadge = infoText('军机'); + statusBadgeType = 'warning'; + } + if (data?.altitude_m != null && data.altitude_m !== '-') { + metrics.push({ label: infoText('高度'), value: `${Math.round(Number(data.altitude_m))} m` }); + } + if (data?.speed != null && data.speed !== '-') { + metrics.push({ label: infoText('地速'), value: `${Math.round(Number(data.speed))} km/h` }); + } + if (data?.track != null && data.track !== '-') { + metrics.push({ label: infoText('航向'), value: `${Math.round(Number(data.track))}°` }); + } } else if (type === 'bgp') { title = translateInfoCardValue(data?.anomaly_type) || infoText('BGP 路由事件'); categoryLabel = infoText('BGP 路由事件'); @@ -767,6 +787,16 @@ export function buildWorkbenchTarget(config, data) { ? `请结合近 60 分钟 AIS 遥测数据,分析船舶「${targetName}」的航行状态与海运态势。` : '请结合 AIS 遥测数据,分析当前活跃海运船舶构型与在航态势。'), }; + case 'aircraft': + return { + domain: 'aircraft', + entityId: data.icao24 || data.callsign || null, + label: '在工作台分析空域', + icon: 'forum', + question: isEn + ? `Analyze the flight posture, altitude/track behavior, and regional airspace / GNSS context for aircraft "${targetName}".` + : `请结合 ADS-B 遥测数据与当前 GPS 干扰态势,分析航空器「${targetName}」的飞行动态与空域态势。`, + }; case 'supercomputer': case 'gpu_cluster': case 'data_center': @@ -1767,6 +1797,7 @@ function getMobilePopupTitle(type, data) { case 'cloud_center': case 'edge_node': return data.name || infoText(COMPUTE_SITE_TYPES[type].label); case 'vessel': return data.name || infoText('船只'); + case 'aircraft': return data.callsign || data.icao24 || infoText('航空器'); case 'earth_interactable': return data.label || data.name || infoText('交互点'); default: return infoText('详情'); } @@ -1787,6 +1818,7 @@ function getMobilePopupSubtitle(type, data) { case 'cloud_center': case 'edge_node': return localizeCountryName(data.country) || infoText(COMPUTE_SITE_TYPES[type].label); case 'vessel': return data.vessel_type || infoText('AIS 船只'); + case 'aircraft': return `${data.aircraft_type || data.category || 'ADS-B'} · ${data.icao24 || ''}`; case 'earth_interactable': return infoText(data.kind || data.description || '数据点'); default: return ''; } @@ -2017,7 +2049,9 @@ const CARD_CONFIG = { { key: 'status', label: '状态' }, { key: 'length', label: '长度' }, { key: 'owner', label: '所有者' }, - { key: 'rfs', label: '投入使用' } + { key: 'rfs', label: '投入使用' }, + { key: 'advisory_summary', label: 'NGA 海缆告警' }, + { key: 'advisory_source', label: '告警出处' } ] }, landing_point: { @@ -2183,7 +2217,49 @@ const CARD_CONFIG = { { key: 'flag', label: '旗帜' }, { key: 'mmsi', label: 'MMSI' }, { key: 'imo', label: 'IMO' }, - { key: 'length', label: '船长', unit: 'm' } + { key: 'length', label: '船长', unit: 'm' }, + { key: 'military_role', label: '军舰/特种角色' }, + { key: 'is_cable_ship', label: '海缆工程船' }, + { key: 'chokepoint_name', label: '所在咽喉要道' } + ] + }, + aircraft: { + icon: '✈', + title: '航空器详情', + className: 'aircraft', + fields: [ + { key: 'callsign', label: '呼号' }, + { key: 'icao24', label: 'ICAO24' }, + { key: 'registration', label: '注册号' }, + { key: 'aircraft_type', label: '机型' }, + { key: 'operator', label: '运营方' }, + { key: 'altitude_m', label: '高度', unit: 'm' }, + { key: 'speed', label: '地速', unit: 'km/h' }, + { key: 'track', label: '航向', unit: '°' }, + { key: 'vertical_rate', label: '升降率', unit: 'm/s' }, + { key: 'squawk', label: '应答机码' }, + { key: 'source', label: '出处' }, + { key: 'observed_at', label: '观测时间' }, + { key: 'ingested_at', label: '入库时间' }, + { key: 'freshness', label: '新鲜度' }, + { key: 'attribution', label: '数据署名' } + ] + }, + disaster: { + icon: '🌋', + title: '自然灾害详情', + className: 'disaster', + fields: [ + { key: 'title', label: '事件标题' }, + { key: 'event_type', label: '灾害类型' }, + { key: 'severity', label: '严重程度' }, + { key: 'magnitude', label: '震级 / 强度' }, + { key: 'cluster_count', label: '火点簇规模' }, + { key: 'max_brightness_k', label: '最高亮温', unit: 'K' }, + { key: 'source', label: '出处' }, + { key: 'observed_at', label: '观测时间' }, + { key: 'ingested_at', label: '入库时间' }, + { key: 'freshness', label: '新鲜度' } ] }, earth_interactable: { @@ -2324,6 +2400,15 @@ function mountCard() { 🛰️

${escapeInfoCardHtml(infoText('详情'))}

+ + + @@ -2357,6 +2442,29 @@ function mountCard() { ].forEach((evt) => card.addEventListener(evt, stopEvent, { passive: false })); // Header workbench button + const bindPhase4InfoButton = (id, eventName) => { + card.querySelector(id)?.addEventListener('click', (event) => { + event.stopPropagation(); + if (!activeWorkbenchAction?.target) return; + const { type: actionType, target, data: targetData } = activeWorkbenchAction; + const effectiveType = target.entityType || actionType || 'global'; + const normalized = normalizeEarthTarget(effectiveType, targetData); + const rawId = normalized?.sourceId || normalized?.id || target.entityId || targetData?.id || ''; + const canonicalId = String(rawId).includes(':') ? String(rawId) : `${effectiveType}:${rawId}`; + window.dispatchEvent(new CustomEvent(eventName, { + detail: { + objectId: canonicalId, + label: normalized?.label || targetData?.name || canonicalId, + type: effectiveType, + data: targetData, + }, + })); + }); + }; + bindPhase4InfoButton('#info-card-ontology', 'earth:open-ontology-graph'); + bindPhase4InfoButton('#info-card-add-case', 'earth:add-to-case'); + bindPhase4InfoButton('#info-card-actions', 'earth:open-object-actions'); + const workbenchBtn = card.querySelector('#info-card-workbench'); if (workbenchBtn) { workbenchBtn.addEventListener('click', (event) => { @@ -2592,6 +2700,10 @@ export function showInfoCard(type, data, options = {}) { const workbenchTarget = buildWorkbenchTarget(config, data); activeWorkbenchAction = workbenchTarget ? { type, target: workbenchTarget, data } : null; + for (const extraId of ['info-card-ontology', 'info-card-add-case', 'info-card-actions']) { + const extraBtn = document.getElementById(extraId); + if (extraBtn) extraBtn.hidden = !workbenchTarget; + } if (workbenchBtn) { if (workbenchTarget) { const actionLabel = infoText(workbenchTarget.label); @@ -2618,6 +2730,10 @@ export function showInfoCard(type, data, options = {}) { export function hideInfoCard() { activeWorkbenchAction = null; + for (const extraId of ['info-card-ontology', 'info-card-add-case', 'info-card-actions']) { + const extraBtn = document.getElementById(extraId); + if (extraBtn) extraBtn.hidden = true; + } const workbenchBtn = document.getElementById('info-card-workbench'); if (workbenchBtn) workbenchBtn.hidden = true; desktopCardImage?.hide(); diff --git a/frontend/public/earth/js/layer-startup-tasks.js b/frontend/public/earth/js/layer-startup-tasks.js index 4be1a57c..db9423c6 100644 --- a/frontend/public/earth/js/layer-startup-tasks.js +++ b/frontend/public/earth/js/layer-startup-tasks.js @@ -22,6 +22,21 @@ import { loadVessels, toggleVessels, } from "./vessels.js"; +import { + getAircraftLegendItems, + loadAircraft, + toggleAircraft, +} from "./aircraft.js"; +import { + getGpsJammingLegendItems, + loadGpsJamming, + toggleGpsJamming, +} from "./gps-jamming.js"; +import { + getDisastersLegendItems, + loadDisasters, + toggleDisasters, +} from "./disasters.js"; import { loadCloudTexture, loadEarthTexture, @@ -99,6 +114,9 @@ function registerBuiltinLayerStartupTasks() { registerCableStartupTask(); registerComputeCenterStartupTask(); registerVesselStartupTask(); + registerAircraftStartupTask(); + registerGpsJammingStartupTask(); + registerDisastersStartupTask(); registerBGPStartupTask(); registerSatelliteStartupTask(); } @@ -322,6 +340,76 @@ function registerCountryBoundaryStartupTask() { }); } +function registerAircraftStartupTask() { + registerLayerStartupTask("aircraft", (context) => async (layer) => { + if (!context.getShowAircraft?.()) return; + + context.setLoadingMessage( + resolveStartupMessage(layer, "load", earthMessage("startup.aircraft")), + ); + await context.yieldFrame(12); + try { + const result = await loadAircraft(context.scene, context.earth); + if (!context.isCancelled()) { + toggleAircraft(context.getShowAircraft(), context.earth); + context.updateAircraftHud?.(result); + context.setLegendItems("aircraft", getAircraftLegendItems()); + context.refreshLegend(); + } + } catch (error) { + context.reportError(layer?.startupLabel || layer?.label || "航空器", error); + } + if (context.isCancelled()) return; + await context.yieldFrame(16); + }); +} + +function registerGpsJammingStartupTask() { + registerLayerStartupTask("gpsJamming", (context) => async (layer) => { + if (!context.getShowGpsJamming?.()) return; + + context.setLoadingMessage( + resolveStartupMessage(layer, "load", earthMessage("startup.gpsJamming")), + ); + await context.yieldFrame(12); + try { + await loadGpsJamming(context.scene, context.earth); + if (!context.isCancelled()) { + toggleGpsJamming(context.getShowGpsJamming(), context.earth); + context.setLegendItems("gpsJamming", getGpsJammingLegendItems()); + context.refreshLegend(); + } + } catch (error) { + context.reportError(layer?.startupLabel || layer?.label || "GPS 干扰", error); + } + if (context.isCancelled()) return; + await context.yieldFrame(16); + }); +} + +function registerDisastersStartupTask() { + registerLayerStartupTask("disasters", (context) => async (layer) => { + if (!context.getShowDisasters?.()) return; + + context.setLoadingMessage( + resolveStartupMessage(layer, "load", earthMessage("startup.disasters")), + ); + await context.yieldFrame(12); + try { + await loadDisasters(context.scene, context.earth); + if (!context.isCancelled()) { + toggleDisasters(context.getShowDisasters(), context.earth); + context.setLegendItems("disasters", getDisastersLegendItems()); + context.refreshLegend(); + } + } catch (error) { + context.reportError(layer?.startupLabel || layer?.label || "自然灾害", error); + } + if (context.isCancelled()) return; + await context.yieldFrame(16); + }); +} + function registerComputeCenterStartupTask() { registerLayerStartupTask("computeCenters", (context) => async (layer) => { context.setLoadingMessage( diff --git a/frontend/public/earth/js/legend-filters.js b/frontend/public/earth/js/legend-filters.js index 7b515b36..6ce91c72 100644 --- a/frontend/public/earth/js/legend-filters.js +++ b/frontend/public/earth/js/legend-filters.js @@ -36,6 +36,7 @@ export function revealLegendObject(type, data = {}) { if (type === "landing_point") (data.cableNames || []).forEach(name => setLegendItemEnabled("cables", name, true)); if (type === "compute_center") setLegendItemEnabled("computeCenters", normalizeComputeSiteType(data.site_type), true); if (type === "vessel") vesselLegendKeys(data).forEach(key => setLegendItemEnabled("vessels", key, true)); + if (type === "aircraft") setLegendItemEnabled("aircraft", data.category || "other", true); if (type === "bgp") setLegendItemEnabled("bgp", `event:${data.icon_kind || data.severity || "medium"}`, true); if (type === "bgp_collector") setLegendItemEnabled("bgp", collectorLegendKey(data.icon_kind || data.activity?.tier), true); } diff --git a/frontend/public/earth/js/legend.js b/frontend/public/earth/js/legend.js index aa10ada3..1b96bd70 100644 --- a/frontend/public/earth/js/legend.js +++ b/frontend/public/earth/js/legend.js @@ -8,6 +8,11 @@ const LEGEND_MODES = { countryBoundaries: { title: "国界" }, computeCenters: { title: "算力" }, vessels: { title: "船只" }, + aircraft: { title: "航空器", compactTitleEn: "Aircraft" }, + gpsJamming: { title: "GPS干扰", compactTitleEn: "GNSS Jam" }, + disasters: { title: "自然灾害", compactTitleEn: "Disasters" }, + geofences: { title: "电子围栏", compactTitleEn: "Geofences" }, + fusionOverlays: { title: "关联与影响链", compactTitleEn: "Fusion Links" }, bgp: { title: "BGP" }, }; @@ -20,6 +25,11 @@ let legendItemsByMode = { countryBoundaries: [], computeCenters: [], vessels: [], + aircraft: [], + gpsJamming: [], + disasters: [], + geofences: [], + fusionOverlays: [], bgp: [], }; diff --git a/frontend/public/earth/js/main.js b/frontend/public/earth/js/main.js index 01c54f0b..a64c02a2 100644 --- a/frontend/public/earth/js/main.js +++ b/frontend/public/earth/js/main.js @@ -5,6 +5,12 @@ import { ensureEarthBottomDock, loadWorkflowBindings } from "./workflow-bindings import { createFrameProfile } from "./frame-profile.js"; import { createFrameStageRunner } from "./frame-stages.js"; import { initNewsRegionCards } from "./news-region-cards.js"; +import { initSpatialWorkflowCards } from "./spatial-workflow-cards.js"; +import { initSourceFreshnessHud } from "./source-freshness.js"; +import { initReplayTimeline } from "./replay-timeline.js"; +import { initOntologyHud } from "./ontology-hud.js"; +import { initCasesHud } from "./cases-hud.js"; +import { initActionsHud } from "./actions-hud.js"; import { createSpatialCallouts, createCalloutGroups } from "./spatial-callouts.js"; import { updateInteractableClusters, clearInteractableClusters } from "./interactable.js"; import { LEGEND_FILTER_EVENT, revealLegendObject } from "./legend-filters.js"; @@ -36,6 +42,7 @@ import { } from "./i18n.js"; import { CONFIG, + EARTH_CONFIG, EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET, CRUISE_MODULES, CRUISE_QUEUE_MODES, @@ -58,7 +65,7 @@ import { resolveEarthRealtimeUrl, } from "./realtime.js"; import { ensureEarthSession, startEarthSessionKeepAlive } from "./earth-session.js"; -import { vector3ToLatLon, screenToEarthCoords } from "./utils.js"; +import { latLonToVector3, vector3ToLatLon, screenToEarthCoords } from "./utils.js"; import { showStatusMessage, showSelectionStatus, @@ -95,7 +102,13 @@ import { toggleTerrain, updateEarthTileLayers, disposeEarthTileLayers, + getBasemapConfigSnapshot, } from "./earth.js"; +import { createMap2dController } from "./map-2d.js"; +import { + createMapViewController, + globeZoomRatioToMap2dZoom, +} from "./map-view-controller.js"; import { refreshLiveCloudMap, sampleCloudCoverAtLatLon } from "./cloud-map.js"; import { createWindFieldLayer, @@ -283,6 +296,48 @@ import { toggleVessels, updateVesselVisualState, } from "./vessels.js"; +import { + applyAircraftLegendFilter, + buildAircraftSearchItems, + clearAircraftData, + clearAircraftSelection, + fetchAircraftDetail, + getAircraftCount, + getAircraftLegendItems, + getAircraftPointerIntersections as getAircraftBatchPointerIntersections, + getShowAircraft, + loadAircraft, + showAircraftTrack, + toggleAircraft, + updateAircraftVisualState, +} from "./aircraft.js"; +import { + clearGpsJammingData, + findGpsJammingCellAtLatLon, + getGpsJammingCount, + getGpsJammingLegendItems, + getShowGpsJamming, + loadGpsJamming, + toggleGpsJamming, +} from "./gps-jamming.js"; +import { + clearDisastersData, + findNearestDisaster, + getDisasterTypeLabel, + getDisastersCount, + getDisastersLegendItems, + loadDisasters, + toggleDisasters, + updateDisastersFrame, +} from "./disasters.js"; +import { + applyChokepointZonesOverlay, + findNearestChokepoint, + isChokepointOverlayActive, +} from "./maritime-context.js"; +import { createGeofenceLayerManager } from "./geofence-editor.js"; +import { createFusionOverlaysManager } from "./fusion-overlays.js"; +import { initIncidentsHud } from "./incidents-hud.js"; import { applyEarthInteractableEvent, clearEarthInteractableSelection, @@ -453,7 +508,13 @@ let currentLoadToken = 0; let cablesEnabled = true; let satellitesEnabled = false; let satelliteLoadAbortController = null; +let map2dController = null; +let mapViewController = null; +let view2dActive = false; let vesselsEnabled = false; +let aircraftEnabled = false; +let gpsJammingEnabled = false; +let disastersEnabled = false; let cableToggleToken = 0; let satelliteToggleToken = 0; let satelliteHydrationToken = 0; @@ -467,7 +528,63 @@ let influenceZones = null; let influenceZonesPill = null; let unsubscribeInfluencePill = null; let newsRegionCards = null; +let spatialWorkflowCards = null; +let geofenceManager = null; +let fusionOverlaysManager = null; +let incidentsHud = null; +let replayTimeline = null; +let ontologyHud = null; +let casesHud = null; +let actionsHud = null; +let replayOverlayPoints = null; let regionCallouts = null; + +function clearReplayPointsOverlay() { + if (!replayOverlayPoints) return; + replayOverlayPoints.parent?.remove(replayOverlayPoints); + replayOverlayPoints.geometry?.dispose?.(); + replayOverlayPoints.material?.dispose?.(); + replayOverlayPoints = null; +} + +function applyReplayPointsOverlay({ aircraft, vessels } = {}) { + const earth = getEarth(); + if (!earth) return; + const coords = []; + const appendFrame = (frame, altOffset) => { + const lats = frame?.lats || []; + const lons = frame?.lons || []; + const alts = frame?.alts || []; + for (let i = 0; i < lats.length; i += 1) { + const lat = Number(lats[i]); + const lon = Number(lons[i]); + if (!Number.isFinite(lat) || !Number.isFinite(lon)) continue; + const altKm = Number(alts[i] || 0) / 1000; + const r = EARTH_CONFIG.RADIUS + altOffset + Math.min(0.18, Math.max(0, altKm * 0.008)); + const v = latLonToVector3(lat, lon, r); + coords.push(v.x, v.y, v.z); + } + }; + appendFrame(vessels, 0.06); + appendFrame(aircraft, 0.11); + if (!coords.length) { + clearReplayPointsOverlay(); + return; + } + const posAttr = new THREE.Float32BufferAttribute(coords, 3); + if (!replayOverlayPoints) { + const geom = new THREE.BufferGeometry(); + geom.setAttribute("position", posAttr); + const mat = new THREE.PointsMaterial({ color: 0xfbbf24, size: 0.24, transparent: true, opacity: 0.92, depthWrite: false }); + replayOverlayPoints = new THREE.Points(geom, mat); + replayOverlayPoints.name = "replay-overlay-points"; + replayOverlayPoints.renderOrder = 4.2; + earth.add(replayOverlayPoints); + } else { + replayOverlayPoints.geometry.setAttribute("position", posAttr); + replayOverlayPoints.geometry.computeBoundingSphere(); + } +} const frameStages = createFrameStageRunner(); let geometryProfileAt = 0; const frameProfile = createFrameProfile(new URLSearchParams(window.location.search).has("profileFrames"), @@ -835,6 +952,7 @@ export function clearLockedObject() { clearBGPSelection(); clearComputeCenterSelection(); clearVesselSelection(); + clearAircraftSelection(); clearEarthInteractableSelection(); influenceZones?.clearScope("interactable"); clearRelatedSatelliteHighlights(); @@ -1753,6 +1871,8 @@ function showMotionCandidateInfo(candidate, options = {}) { showComputeCenterInfo(candidate.object, options); } else if (candidate.type === "vessel") { showVesselInfo(candidate.object, options); + } else if (candidate.type === "aircraft") { + showAircraftInfo(candidate.object, options); } else if (candidate.type === "earth_interactable") { showEarthInteractableInfo(candidate.object, options); } else if (candidate.type === "landing_point") { @@ -1771,6 +1891,12 @@ function getMotionCandidateFocusCoords(candidate) { if (candidate.type === "bgp" || candidate.type === "bgp_collector") return getBGPFocusCoords(candidate.object); if (candidate.type === "compute_center") return getComputeCenterFocusCoords(candidate.object); if (candidate.type === "vessel") return getVesselFocusCoords(candidate.object); + if (candidate.type === "aircraft") { + const ud = candidate.object?.userData; + return ud?.latitude != null && ud?.longitude != null + ? { lat: Number(ud.latitude), lon: Number(ud.longitude) } + : null; + } if (candidate.type === "earth_interactable") return getEarthInteractableFocusCoords(candidate.object); return null; } @@ -1870,6 +1996,16 @@ function confirmInteractionCandidate(candidate, { showConfirmationFeedback = tru showVesselTrack(marker, earth).catch((error) => { console.warn("船只轨迹加载失败:", error); }); + } else if (candidate.type === "aircraft") { + const marker = candidate.object; + lockedObject = marker; + lockedObjectType = "aircraft"; + const icao24 = marker?.userData?.icao24; + if (icao24) { + showAircraftTrack(icao24, earth).catch((error) => { + console.warn("航空器轨迹加载失败:", error); + }); + } } else if (candidate.type === "earth_interactable") { const marker = candidate.object; setEarthInteractableMarkerState(marker, "locked"); @@ -1884,6 +2020,10 @@ function confirmInteractionCandidate(candidate, { showConfirmationFeedback = tru } else { influenceZones?.clearScope("interactable"); } + } else if (candidate.type === "landing_point") { + const point = candidate.object; + lockedObject = point; + lockedObjectType = "landing_point"; } else if (candidate.type === "cable") { const cable = candidate.object; setCableState(cable.userData.cableId, CABLE_STATE.LOCKED); @@ -1917,6 +2057,8 @@ function confirmInteractionCandidate(candidate, { showConfirmationFeedback = tru function showCableInfo(cable, coords) { setLegendMode("cables"); + const advisories = Array.isArray(cable.userData.advisories) ? cable.userData.advisories : []; + const firstAdv = advisories[0] || null; showInfoCard("cable", { source_id: cable.userData.source_id, name: cable.userData.name, @@ -1925,6 +2067,10 @@ function showCableInfo(cable, coords) { length: cable.userData.length, coords: cable.userData.coords, rfs: cable.userData.rfs, + advisory_summary: firstAdv + ? `${firstAdv.source_warning_id || "NGA"}: ${String(firstAdv.text || "").slice(0, 220)}` + : "无活跃 NGA 海缆通告", + advisory_source: firstAdv ? (firstAdv.source || "NGA MSI (nga_navigation_warnings)") : "-", }, coords); } @@ -2041,6 +2187,9 @@ function showVesselInfo(marker, coords) { course: marker.userData?.cog ?? marker.userData?.heading ?? "-", status: formatVesselStatus(marker.userData?.nav_status), length: marker.userData?.length ?? "-", + military_role: marker.userData?.military_role || "-", + is_cable_ship: marker.userData?.is_cable_ship ? "是" : "否", + chokepoint_name: marker.userData?.chokepoint_name || "-", received_at: marker.userData?.received_at ? new Date(marker.userData.received_at).toLocaleString(getEarthLocale(), { hour12: false }) : "-", @@ -2069,6 +2218,97 @@ function getEarthInteractableBriefHtml(marker) { return `${translateText(name)}
${translateText(kind)}`; } +function getAircraftBriefHtml(marker) { + const ud = marker?.userData || {}; + const title = ud.callsign || ud.icao24?.toUpperCase?.() || "航空器"; + const alt = ud.altitude_m != null ? `${Math.round(ud.altitude_m)} m` : "-"; + const spd = ud.ground_speed_ms != null ? `${Math.round(ud.ground_speed_ms * 3.6)} km/h` : "-"; + return `${translateText(title)}
${translateText(ud.category || "other")} · ${alt} · ${spd}`; +} + +function getGpsJammingBriefHtml(cell) { + const levelLabel = cell.level === "high" ? "强干扰" : cell.level === "medium" ? "中干扰" : "低干扰"; + const ratioPct = `${(Number(cell.bad_ratio || 0) * 100).toFixed(1)}%`; + return `${translateText("GPS 干扰")} · ${translateText(levelLabel)}
${translateText("异常比例")}: ${ratioPct} · ${translateText("受影响飞机")}: ${cell.aircraft_count || 0}
${translateText("日期")}: ${cell.observed_date || "-"} · gpsjam.org`; +} + +function getDisasterBriefHtml(event) { + const typeLabel = translateText(getDisasterTypeLabel(event.event_type)); + const title = event.title || typeLabel; + return `${title}
${typeLabel} · ${event.source || "-"}`; +} + +function showDisasterInfo(event, coords) { + if (!event) return; + setLegendMode("disasters"); + const obsAt = event.observed_at ? new Date(event.observed_at).toLocaleString(getEarthLocale(), { hour12: false }) : "-"; + const ingAt = event.ingested_at ? new Date(event.ingested_at).toLocaleString(getEarthLocale(), { hour12: false }) : "-"; + const fields = { + title: event.title || "-", + event_type: translateText(getDisasterTypeLabel(event.event_type)), + severity: event.severity || "-", + magnitude: event.magnitude != null ? Number(event.magnitude).toFixed(1) : "-", + cluster_count: event.cluster_count != null ? String(event.cluster_count) : "1", + max_brightness_k: event.max_brightness_k != null ? Number(event.max_brightness_k).toFixed(1) : "-", + source: event.source || "-", + observed_at: obsAt, + ingested_at: ingAt, + freshness: event.is_stale ? translateText("已过期") : translateText("实时新鲜"), + }; + showInfoCard("disaster", fields, coords || { lat: event.lat, lon: event.lon }); +} + +function showAircraftInfo(marker, coords) { + const ud = marker?.userData || {}; + setLegendMode("aircraft"); + const buildFields = (detail = null) => { + const resolved = detail || ud._detail || null; + const stat = resolved?.static || {}; + const curr = resolved?.current || {}; + const obsAt = resolved?.observed_at || curr.observed_at || ud.observed_at; + const ingAt = resolved?.ingested_at || curr.ingested_at; + const altVal = curr.geo_altitude_m ?? curr.baro_altitude_m ?? ud.altitude_m; + const spdVal = curr.ground_speed_ms ?? ud.ground_speed_ms; + return { + callsign: curr.callsign || ud.callsign || "-", + icao24: (curr.icao24 || ud.icao24 || "-").toUpperCase(), + registration: stat.registration || "-", + aircraft_type: stat.aircraft_type || "-", + operator: stat.operator || stat.owner || "-", + category: curr.category || ud.category || "other", + is_military: curr.is_military ?? ud.is_military, + is_emergency: curr.is_emergency ?? ud.is_emergency, + emergency_code: curr.emergency_code ?? ud.emergency_code, + altitude_m: altVal != null ? Math.round(Number(altVal)) : "-", + speed: spdVal != null ? Math.round(Number(spdVal) * 3.6) : "-", + track: (curr.track_deg ?? ud.track_deg) != null ? Math.round(Number(curr.track_deg ?? ud.track_deg)) : "-", + vertical_rate: (curr.vertical_rate_ms ?? ud.vertical_rate_ms) != null ? Number(curr.vertical_rate_ms ?? ud.vertical_rate_ms).toFixed(1) : "-", + squawk: curr.squawk || "-", + source: resolved?.source || curr.source || ud.source || "-", + observed_at: obsAt ? new Date(obsAt).toLocaleString(getEarthLocale(), { hour12: false }) : "-", + ingested_at: ingAt ? new Date(ingAt).toLocaleString(getEarthLocale(), { hour12: false }) : "-", + freshness: resolved ? (resolved.is_stale ? translateText("已过期") : translateText("实时新鲜")) : "-", + attribution: resolved?.attribution || "adsb.lol (ODbL) · OpenSky (Non-Commercial)", + }; + }; + + showInfoCard("aircraft", buildFields(null), coords); + if (ud.icao24 && coords?.reveal !== false && !ud._detail && !ud._detailFetching) { + ud._detailFetching = true; + fetchAircraftDetail(ud.icao24) + .then((detail) => { + ud._detail = detail; + if (lockedObject === marker && lockedObjectType === "aircraft") { + showInfoCard("aircraft", buildFields(detail), { ...coords, reveal: true }); + } + }) + .catch(() => {}) + .finally(() => { + ud._detailFetching = false; + }); + } +} + function getVesselBriefHtml(marker) { const name = marker.userData?.name || `MMSI ${marker.userData?.mmsi}`; const speed = marker.userData?.sog ?? "-"; @@ -2299,7 +2539,16 @@ function getEarthInteractableFocusCoords(marker) { } async function focusSearchTarget(coords, zoom = Math.max(getZoomLevel(), 1.12)) { - if (!coords || !camera) return; + if (!coords) return; + if (mapViewController?.is2dActive?.()) { + mapViewController.flyTo({ + lat: coords.lat, + lon: coords.lon, + zoom: globeZoomRatioToMap2dZoom(zoom), + }); + return; + } + if (!camera) return; await focusEarthView(camera, { lat: coords.lat, lon: coords.lon, @@ -2770,6 +3019,12 @@ function resolveEarthSearchResults(query) { }); }); + if (getShowAircraft()) { + buildAircraftSearchItems(normalizedQuery, computeSearchScore).forEach((item) => { + results.push(item); + }); + } + return results .sort((left, right) => { if (right.score !== left.score) return right.score - left.score; @@ -2804,6 +3059,43 @@ async function handleSearchSelection(result) { } if (result.kind === "vessel") { await focusSearchVessel(result.entity); + return; + } + if (result.kind === "aircraft") { + await setAircraftEnabled(true, { suppressStatus: true, suppressLoadingUi: true }); + interruptCruisePresentation({ resetLoop: true }); + clearLockedObject(); + setAutoRotate(false); + const rec = result.entity; + await focusSearchTarget({ lat: Number(rec.lat), lon: Number(rec.lon) }, Math.max(getZoomLevel(), 1.25)); + const altRadius = + CONFIG.earthRadius + + 0.75 + + (Math.max(0, Math.min(Number(rec.altitudeM) || 9000, 15000)) / 15000) * 1.1; + const pseudoMarker = { + position: latLonToVector3(Number(rec.lat), Number(rec.lon), altRadius), + parent: getEarth(), + userData: { + type: "aircraft", + id: rec.icao24, + icao24: rec.icao24, + name: rec.callsign || rec.icao24?.toUpperCase?.(), + callsign: rec.callsign, + latitude: rec.lat, + longitude: rec.lon, + altitude_m: rec.altitudeM, + ground_speed_ms: rec.groundSpeedMs, + track_deg: rec.trackDeg, + vertical_rate_ms: rec.verticalRateMs, + category: rec.category, + is_military: rec.isMilitary, + is_emergency: rec.isEmergency, + emergency_code: rec.emergencyCode, + source: rec.source, + observed_at: rec.observedAt, + }, + }; + confirmInteractionCandidate({ type: "aircraft", object: pseudoMarker }, { showConfirmationFeedback: false }); } } @@ -3036,7 +3328,10 @@ function presentSelectedObject(candidate) { return [{ x: rect.x, y: rect.y, width: rect.width, height: rect.height }]; }, }); - const source = sourceProvider() || getMotionCandidateScreenCoords(candidate); + const is2d = Boolean(mapViewController?.is2dActive?.()); + const source = is2d && candidate?.screen + ? { x: candidate.screen.x, y: candidate.screen.y, front: true, globe: null } + : (sourceProvider() || getMotionCandidateScreenCoords(candidate)); const mobile = document.body.classList.contains("layout-mode-mobile"); const scale = Number.parseFloat(getComputedStyle(document.documentElement).getPropertyValue("--hud-scale")) || 1; const estInitialHeight = candidate?.type === "satellite" ? 270 : (candidate?.type === "cable" ? 220 : 300); @@ -3079,7 +3374,7 @@ function presentSelectedObject(candidate) { hide: hideInfoCard, }, connector: { - enabled: true, + enabled: !is2d, sourceProvider: () => { const point = sourceProvider(); const element = connector.ensure(); @@ -4065,6 +4360,9 @@ function applyCableVisualState() { ((origColor & 255) / 255) * brightness, ...(THREE.SRGBColorSpace ? [THREE.SRGBColorSpace] : []), ); + } else if (cable.userData.hasAdvisory) { + cable.material.opacity = 0.95; + cable.material.color.setHex(0xf59e0b); } else { cable.material.opacity = CABLE_CONFIG.visual.normalOpacity; cable.material.color.setHex(cable.userData.originalColor); @@ -4420,6 +4718,7 @@ async function ensureVesselsEnabled() { updateVesselToggleUi(true, result.totalCount); setLegendItems("vessels", getVesselLegendItems()); refreshLegend(); + void applyChokepointZonesOverlay(influenceZones, true); return result.totalCount; } @@ -4432,6 +4731,107 @@ function disableVessels() { updateVesselToggleUi(false, 0); setLegendItems("vessels", getVesselLegendItems()); refreshLegend(); + void applyChokepointZonesOverlay(influenceZones, false); +} + +function updateAircraftToggleUi(enabled, count = getAircraftCount()) { + const btn = document.getElementById("toggle-aircraft"); + if (btn) { + setLayerButtonState(btn, { + active: enabled, + loading: false, + tooltip: enabled ? "隐藏航空器" : "显示航空器", + }); + } + setEarthStatValue("aircraft-count", `${getAuthoritativeCount("aircraftCount", count)} 架`); +} + +function updateGpsJammingToggleUi(enabled) { + const btn = document.getElementById("toggle-gps-jamming"); + if (btn) { + setLayerButtonState(btn, { + active: enabled, + loading: false, + tooltip: enabled ? "隐藏 GPS 干扰" : "显示 GPS 干扰", + }); + } +} + +function updateDisastersToggleUi(enabled) { + const btn = document.getElementById("toggle-disasters"); + if (btn) { + setLayerButtonState(btn, { + active: enabled, + loading: false, + tooltip: enabled ? "隐藏自然灾害" : "显示自然灾害", + }); + } +} + +async function ensureAircraftEnabled() { + if (!scene || !camera || !renderer || destroyed) return 0; + const earth = getEarth(); + if (!earth) return 0; + + aircraftEnabled = true; + toggleAircraft(true, earth); + const result = await loadAircraft(scene, earth); + updateAircraftToggleUi(true, result.totalCount); + setLegendItems("aircraft", getAircraftLegendItems()); + refreshLegend(); + return result.totalCount; +} + +function disableAircraft() { + aircraftEnabled = false; + toggleAircraft(false, getEarth()); + updateAircraftToggleUi(false, 0); + setLegendItems("aircraft", getAircraftLegendItems()); + refreshLegend(); +} + +async function ensureGpsJammingEnabled() { + if (!scene || !camera || !renderer || destroyed) return 0; + const earth = getEarth(); + if (!earth) return 0; + + gpsJammingEnabled = true; + toggleGpsJamming(true, earth); + const result = await loadGpsJamming(scene, earth); + updateGpsJammingToggleUi(true); + setLegendItems("gpsJamming", getGpsJammingLegendItems()); + refreshLegend(); + return result.totalCount; +} + +function disableGpsJamming() { + gpsJammingEnabled = false; + toggleGpsJamming(false, getEarth()); + updateGpsJammingToggleUi(false); + setLegendItems("gpsJamming", getGpsJammingLegendItems()); + refreshLegend(); +} + +async function ensureDisastersEnabled() { + if (!scene || !camera || !renderer || destroyed) return 0; + const earth = getEarth(); + if (!earth) return 0; + + disastersEnabled = true; + toggleDisasters(true, earth); + const result = await loadDisasters(scene, earth); + updateDisastersToggleUi(true); + setLegendItems("disasters", getDisastersLegendItems()); + refreshLegend(); + return result.totalCount; +} + +function disableDisasters() { + disastersEnabled = false; + toggleDisasters(false, getEarth()); + updateDisastersToggleUi(false); + setLegendItems("disasters", getDisastersLegendItems()); + refreshLegend(); } function disableSatellites() { @@ -4508,7 +4908,10 @@ export function init() { updateHudScale(); remountEarthBrand(); earthSessionReady - .then(() => fetchEarthBrandConfig()) + .then(() => fetchEarthBrandConfig((freshBrand) => { + runtimeBrandConfig = freshBrand; + remountEarthBrand(); + })) .then((brandConfig) => { runtimeBrandConfig = brandConfig; remountEarthBrand(); @@ -4518,6 +4921,7 @@ export function init() { }); cleanupFns.push(onEarthLocaleChange((nextLocale) => { setGeoLabelsLocale(nextLocale); + map2dController?.setLocale?.(nextLocale); remountEarthBrand(); updateCableToggleUi(getShowCables()); updateSatelliteToggleUi(getShowSatellites()); @@ -4656,6 +5060,74 @@ export function init() { }), })); newsRegionCards = initNewsRegionCards({ rootParent: regionCardRoot, spatial: regionCallouts.scope("news") }); + spatialWorkflowCards = initSpatialWorkflowCards({ + rootParent: regionCardRoot, + spatial: regionCallouts.scope("workflow"), + }); + geofenceManager = createGeofenceLayerManager({ getEarth }); + fusionOverlaysManager = createFusionOverlaysManager({ getEarth }); + incidentsHud = initIncidentsHud({ + rootParent: container || document.body, + geofenceManager, + onSelectIncident: (inc, _oid) => { + const lat = Number(inc?.signal_summary?.lat); + const lon = Number(inc?.signal_summary?.lon); + if (camera && Number.isFinite(lat) && Number.isFinite(lon)) { + void focusEarthView(camera, { lat, lon, zoom: Math.max(getZoomLevel(), 1.35), duration: 750, suppressStatus: true }); + } + }, + onIncidentsChanged: async () => { + if (geofenceManager?.isVisible?.()) { + await geofenceManager.loadGeofences().catch(() => {}); + } + if (fusionOverlaysManager?.isVisible?.()) { + await fusionOverlaysManager.loadOverlays().catch(() => {}); + } + }, + onStatus: (msg, level = "info") => showStatusMessage(msg, level), + }); + replayTimeline = initReplayTimeline({ + rootParent: container || document.body, + onReplayStateChange: (active) => { + if (!active) clearReplayPointsOverlay(); + showStatusMessage(active ? earthMessage("status.replayEntered") : earthMessage("status.replayExited"), "info"); + }, + onApplyReplayFrame: (frame) => { + applyReplayPointsOverlay(frame); + }, + onApplyComputeAsOf: (asOfRev, cursorIso) => { + computeTopic?.setReplayAsOfRevision?.(asOfRev, cursorIso); + }, + onStatus: (msg, level = "info") => showStatusMessage(msg, level), + }); + ontologyHud = initOntologyHud({ + rootParent: container || document.body, + onSelectNode: (node) => { + const lat = Number(node?.lat); + const lon = Number(node?.lon); + if (camera && Number.isFinite(lat) && Number.isFinite(lon)) { + void focusEarthView(camera, { lat, lon, zoom: Math.max(getZoomLevel(), 1.35), duration: 700, suppressStatus: true }); + } + if (node?.object_id) { + void ontologyHud?.loadObject?.(node.object_id).catch(() => {}); + } + }, + onSelectTimestamp: (iso) => { + if (iso) void replayTimeline?.seekToTimestamp?.(iso); + }, + onStatus: (msg, level = "info") => showStatusMessage(msg, level), + }); + casesHud = initCasesHud({ + rootParent: container || document.body, + onFocusObject: (oid) => { + if (oid) void ontologyHud?.loadObject?.(oid).catch(() => {}); + }, + onStatus: (msg, level = "info") => showStatusMessage(msg, level), + }); + actionsHud = initActionsHud({ + rootParent: container || document.body, + onStatus: (msg, level = "info") => showStatusMessage(msg, level), + }); void loadWorkflowBindings(); situationalCopilot = initSituationalCopilot({ rootParent: container || document.body, @@ -4680,6 +5152,7 @@ export function init() { }, onClearSceneZones() { influenceZones?.clearScope("copilot"); + spatialWorkflowCards?.clear?.(); }, onPlayPresentation(key) { if (key === "compute-posture-cn-us") { @@ -4718,6 +5191,18 @@ export function init() { influenceZones?.clearScope("copilot"); } } + if (Array.isArray(sceneSpec?.spatial_cards)) { + spatialWorkflowCards?.setCards?.(sceneSpec.spatial_cards); + } + if (Array.isArray(sceneSpec?.overlays)) { + void applyChokepointZonesOverlay(influenceZones, sceneSpec.overlays.includes("chokepoints")); + if (sceneSpec.overlays.includes("geofences")) { + void setGeofencesEnabled(true, { suppressStatus: true }); + } + if (sceneSpec.overlays.includes("dependency_arcs")) { + void setFusionOverlaysEnabled(true, { suppressStatus: true }); + } + } if (sceneSpec?.domain === "compute" && sceneSpec.enable_national_hubs) { computeTopic?.applyStageStep?.({ computeMode: sceneSpec.compute_mode || "global_share", @@ -4763,6 +5248,18 @@ export function init() { }); }, onComputeStep(step) { + if (Array.isArray(step?.spatial_cards) && step.spatial_cards.length > 0) { + spatialWorkflowCards?.setCards?.(step.spatial_cards); + } + if (Array.isArray(step?.overlays) && step.overlays.length > 0) { + void applyChokepointZonesOverlay(influenceZones, step.overlays.includes("chokepoints")); + if (step.overlays.includes("geofences")) { + void setGeofencesEnabled(true, { suppressStatus: true }); + } + if (step.overlays.includes("dependency_arcs")) { + void setFusionOverlaysEnabled(true, { suppressStatus: true }); + } + } computeTopic?.applyStageStep({ ...step, suppressAutoOpenCards: Boolean(situationalCopilot?.isOpen?.()), @@ -4782,6 +5279,7 @@ export function init() { onClearOverlays() { clearStageLogicalArcsOverlay(); influenceZones?.clearScope("stage"); + spatialWorkflowCards?.clear?.(); }, onInterruptAmbientCruise() { interruptCruisePresentation({ resetLoop: true }); @@ -4822,6 +5320,38 @@ export function init() { }); }; + bindListener(document.getElementById("open-incidents-hud"), "click", (event) => { + event.stopPropagation(); + void incidentsHud?.open?.(); + }); + bindListener(document.getElementById("open-replay-timeline"), "click", (event) => { + event.stopPropagation(); + void replayTimeline?.open?.(); + }); + bindListener(document.getElementById("open-ontology-graph"), "click", (event) => { + event.stopPropagation(); + void ontologyHud?.open?.(); + }); + bindListener(document.getElementById("open-cases-hud"), "click", (event) => { + event.stopPropagation(); + void casesHud?.open?.(); + }); + bindListener(document.getElementById("open-actions-hud"), "click", (event) => { + event.stopPropagation(); + void actionsHud?.open?.(); + }); + bindListener(window, "earth:open-ontology-graph", (event) => { + const oid = event?.detail?.objectId; + if (oid) void ontologyHud?.open?.(oid); + }); + bindListener(window, "earth:add-to-case", (event) => { + const detail = event?.detail || {}; + void casesHud?.attachObject?.({ objectId: detail.objectId, label: detail.label }).catch((err) => showStatusMessage(err?.message || String(err), "error")); + }); + bindListener(window, "earth:open-object-actions", (event) => { + const oid = event?.detail?.objectId || ""; + void actionsHud?.open?.(oid); + }); bindListener(document.getElementById("open-situational-copilot"), "click", (event) => { event.stopPropagation(); openWorkbenchForDomain("global", { entityId: null, preserveActiveContext: true, autoAsk: false }); @@ -4945,6 +5475,15 @@ export function init() { stageNarrativePlayer?.destroy(); stageNarrativePlayer = null; situationalCopilot?.destroy(); situationalCopilot = null; setComputeTopicQuery(null); computeTopic?.destroy(); computeTopic = null; + spatialWorkflowCards?.destroy(); spatialWorkflowCards = null; + incidentsHud?.destroy?.(); incidentsHud = null; + clearReplayPointsOverlay(); + replayTimeline?.destroy?.(); replayTimeline = null; + ontologyHud?.destroy?.(); ontologyHud = null; + casesHud?.destroy?.(); casesHud = null; + actionsHud?.destroy?.(); actionsHud = null; + geofenceManager?.dispose?.(); geofenceManager = null; + fusionOverlaysManager?.dispose?.(); fusionOverlaysManager = null; newsRegionCards?.destroy(); newsRegionCards = null; regionCallouts?.destroy(); regionCallouts = null; regionCardRoot.remove(); }); @@ -4959,6 +5498,9 @@ export function init() { cables: [applyCableLegendFilter, getCableLegendItems], computeCenters: [applyComputeCenterLegendFilter, getComputeCenterLegendItems], vessels: [applyVesselLegendFilter, getVesselLegendItems], + aircraft: [applyAircraftLegendFilter, getAircraftLegendItems], + gpsJamming: [() => {}, getGpsJammingLegendItems], + disasters: [() => {}, getDisastersLegendItems], bgp: [applyBGPLegendFilter, getBGPLegendItems], countryBoundaries: [applyCountryBoundaryLegendFilter, getCountryBoundaryLegendItems], }; @@ -4981,6 +5523,9 @@ export function init() { setLegendItems("countryBoundaries", getCountryBoundaryLegendItems()); setLegendItems("computeCenters", getComputeCenterLegendItems()); setLegendItems("vessels", getVesselLegendItems()); + setLegendItems("aircraft", getAircraftLegendItems()); + setLegendItems("gpsJamming", getGpsJammingLegendItems()); + setLegendItems("disasters", getDisastersLegendItems()); setLegendItems("bgp", getBGPLegendItems()); const earthObj = createEarth(scene); influenceZones = createInfluenceZonesController(earthObj); @@ -5120,6 +5665,158 @@ export function init() { createCountryBoundaryLayer(earthObj); createSatellites(scene, earthObj); + const get2dSnapshots = () => ({ + cables: getCableLines(), + landingPoints: getLandingPoints(), + computeCenters: getComputeCenterMarkers(), + vessels: getVesselMarkers(), + bgpEvents: getBGPAnomalyMarkers(), + bgpCollectors: getBGPCollectorMarkers(), + satellites: getSatelliteData(), + satellitePositions: getSatellitePositions(), + visibility: { + cables: getShowCables(), + computeCenters: getShowComputeCenters(), + vessels: getShowVessels(), + bgp: getShowBGP(), + satellites: getShowSatellites(), + countryBoundaries: getShowCountryBoundaries(), + }, + }); + + const sync2dLayers = () => { + if (!mapViewController?.is2dActive?.()) return; + map2dController?.syncLayers(get2dSnapshots()); + }; + + const syncViewModeUi = (nextMode) => { + const is2d = nextMode === "2d"; + const toggleTitle = translateText( + is2d ? "返回 3D 地球视图" : "切换 2D 平面视图", + ); + ["map-view-mode-toggle", "mobile-view-mode-toggle"].forEach((id) => { + const btn = document.getElementById(id); + if (!btn) return; + btn.classList.toggle("is-2d", is2d); + btn.classList.toggle("active", is2d); + btn.setAttribute("aria-pressed", String(is2d)); + btn.title = toggleTitle; + btn.setAttribute("aria-label", toggleTitle); + }); + document.getElementById("container")?.classList.toggle("is-2d-mode", is2d); + }; + + const map2dEl = document.getElementById("earth-map-2d"); + map2dController = createMap2dController({ + container: map2dEl, + getBasemapConfig: getBasemapConfigSnapshot, + getSnapshots: get2dSnapshots, + onViewChange: (view) => { + mapViewController?.handle2dViewChange(view); + }, + onHoverCountry: () => {}, + onSelectFeature: (item) => { + if (item) { + confirmInteractionCandidate(item, { showConfirmationFeedback: true }); + } + }, + onLocaleRequest: () => getEarthLocale(), + }); + + mapViewController = createMapViewController({ + map2d: map2dController, + getGlobeView: () => { + const center = getCurrentViewCenterCoords() || { + lat: EARTH_CONFIG.chinaLat, + lon: EARTH_CONFIG.chinaLon, + }; + return { + lat: center.lat, + lon: center.lon, + zoomRatio: getZoomLevel(), + }; + }, + applyGlobeView: ({ lat, lon, zoomRatio }) => { + const activeEarth = getEarth(); + if (!activeEarth || !camera) return; + cancelEarthViewAnimation(); + const tiltDeg = Number(EARTH_CONFIG.tilt) || 0; + const latCoeff = Number(EARTH_CONFIG.latCoefficient) || 1; + applyImmediateView(activeEarth, camera, { + lat: (lat - tiltDeg) / latCoeff, + rotLon: lon - 270, + zoom: zoomRatio, + }); + targetRotation = { + x: activeEarth.rotation.x, + y: activeEarth.rotation.y, + }; + inertialVelocity = { x: 0, y: 0 }; + activeEarth.updateMatrixWorld(true); + }, + setGlobePaused: (paused) => { + const nextPaused = Boolean(paused); + if (nextPaused === view2dActive) return; + view2dActive = nextPaused; + if (nextPaused && animationFrameId) { + cancelAnimationFrame(animationFrameId); + animationFrameId = null; + } else if (!nextPaused && !destroyed && !desktopMinimized && !webglContextLost) { + clock.getDelta(); + if (!animationFrameId) animate(); + } + }, + onModeChange: (nextMode) => { + syncViewModeUi(nextMode); + hideTooltip(); + showStatusMessage( + earthMessage(nextMode === "2d" ? "status.viewMode2d" : "status.viewMode3d"), + "info", + ); + }, + onZoomDisplay: (label) => { + const zoomEl = document.getElementById("zoom-value"); + if (zoomEl) zoomEl.textContent = label; + }, + onPillVisibilityChange: (visible) => { + const pillEl = document.getElementById("map-2d-zoom-pill"); + if (pillEl) pillEl.hidden = !visible; + }, + }); + + const handleToggle2dMode = () => { + if (!mapViewController) return; + void mapViewController.toggleMode().catch((error) => { + console.warn("[智能星球] 2D 平面视图切换失败:", error); + showStatusMessage(earthMessage("status.viewMode2dFailed"), "error"); + }); + }; + bindListener(document.getElementById("map-view-mode-toggle"), "click", handleToggle2dMode); + bindListener(document.getElementById("mobile-view-mode-toggle"), "click", handleToggle2dMode); + bindListener(document.getElementById("map-2d-zoom-pill-action"), "click", () => { + void mapViewController?.setMode("2d").catch((error) => { + console.warn("[智能星球] 2D 平面视图切换失败:", error); + showStatusMessage(earthMessage("status.viewMode2dFailed"), "error"); + }); + }); + bindListener(document.getElementById("map-2d-zoom-pill-close"), "click", () => { + mapViewController?.dismissPill(); + }); + bindListener(window, "earth:zoom-level-change", (event) => { + mapViewController?.handle3dZoomChange(event?.detail?.zoomLevel); + }); + bindListener(window, "resize", () => { + map2dController?.resize(); + }); + const layerListEl = document.getElementById("layer-panel-list"); + const scheduleSync2d = () => queueMicrotask(() => sync2dLayers()); + bindListener(layerListEl, "change", scheduleSync2d); + bindListener(layerListEl, "click", scheduleSync2d); + cleanupFns.push(() => { + window.__planetSync2dLayers = null; + }); + window.__planetSync2dLayers = sync2dLayers; + setupControls(camera, renderer, scene, earthObj) .catch((error) => { console.error("初始化 Earth 控制项失败:", error); @@ -5154,6 +5851,8 @@ export function init() { }); initTVPanel(); initNewsPanel(); + const freshnessHud = initSourceFreshnessHud(); + cleanupFns.push(() => freshnessHud?.dispose?.()); connectEarthUpdatesRealtime(); startEarthDataReconciliation(); }, 0)); @@ -5275,11 +5974,27 @@ function registerGlobalApi() { getEarth: () => getEarth(), getScene: () => scene, getRendererInfo: () => (renderer?.info?.render ? { ...renderer.info.render } : null), + getRendererMemory: () => (renderer?.info?.memory ? { ...renderer.info.memory } : null), getBoundaryStats: () => getCountryBoundaryRenderStats(), getGeoLabelStats: () => getGeoLabelStats(), setGeoLabelsEnabled: (enabled) => setGeoLabelsEnabled(enabled), getSatellitePoints: () => getSatellitePoints(), setSatellitesEnabled: (enabled) => setSatellitesEnabled(enabled), + setDisastersEnabled: (enabled) => setDisastersEnabled(enabled), + setGeofencesEnabled: (enabled) => setGeofencesEnabled(enabled), + getGeofenceStats: () => geofenceManager?.getStats?.() || null, + setFusionOverlaysEnabled: (enabled) => setFusionOverlaysEnabled(enabled), + getFusionOverlayStats: () => fusionOverlaysManager?.getStats?.() || null, + setWorkflowSpatialCards: (cards) => spatialWorkflowCards?.setCards?.(cards || []), + openIncidentsPanel: () => incidentsHud?.open?.(), + openReplayTimeline: () => replayTimeline?.open?.(), + getReplayTimeline: () => replayTimeline, + getReplayState: () => replayTimeline?.getState?.() || null, + openOntologyGraph: (objectId = "") => ontologyHud?.open?.(objectId), + openCasesBoard: () => casesHud?.open?.(), + openActionsCenter: (objectId = "") => actionsHud?.open?.(objectId), + setChokepointsEnabled: (enabled) => applyChokepointZonesOverlay(influenceZones, Boolean(enabled)), + getChokepointsEnabled: () => isChokepointOverlayActive(), selectSatellite: (idx = 0) => { const sat = getSatelliteAt(idx); if (sat) return confirmInteractionCandidate({ type: "satellite", index: idx, object: sat }); @@ -5287,6 +6002,17 @@ function registerGlobalApi() { }, presentSelectedObject: (c) => presentSelectedObject(c), getPresentationController: () => ensurePresentationController(), + getViewMode: () => mapViewController?.getMode?.() || "3d", + setViewMode: (nextMode) => mapViewController?.setMode?.(nextMode), + toggleViewMode: () => mapViewController?.toggleMode?.(), + is2dActive: () => Boolean(mapViewController?.is2dActive?.()), + zoom2dBy: (delta) => Boolean(mapViewController?.zoom2dBy?.(delta)), + reset2dView: () => Boolean(mapViewController?.reset2dView?.()), + set2dView: (view) => map2dController?.setView?.(view), + getViewCenterCoords: () => getCurrentViewCenterCoords(), + get2dDiagnostics: () => map2dController?.getDiagnostics?.() || null, + hover2dAtLatLon: (lat, lon) => map2dController?.hoverAtLatLon?.(lat, lon) || null, + select2dFirstFeature: (type) => map2dController?.selectFirstFeature?.(type) || null, clearSelection: () => { presentationController?.dismiss?.("user_close"); hideInfoCard(); @@ -5525,6 +6251,27 @@ const EARTH_DATA_LAYER_HANDLERS = { clear: applyVesselEmptyState, refresh: ensureVesselsEnabled, }, + aircraft: { + summaryKeys: ["aircraftCount"], + isVisible: () => aircraftEnabled || getShowAircraft(), + localCount: () => getAircraftCount(), + clear: () => clearAircraftData(getEarth()), + refresh: ensureAircraftEnabled, + }, + gpsJamming: { + summaryKeys: ["gpsJammingHighCount"], + isVisible: () => gpsJammingEnabled || getShowGpsJamming(), + localCount: () => getGpsJammingCount(), + clear: () => clearGpsJammingData(getEarth()), + refresh: ensureGpsJammingEnabled, + }, + disasters: { + summaryKeys: ["disasterEventCount"], + isVisible: () => disastersEnabled, + localCount: () => getDisastersCount(), + clear: () => clearDisastersData(getEarth()), + refresh: ensureDisastersEnabled, + }, }; async function refreshDataBackedEarthLayer(layer, options = {}) { @@ -5937,6 +6684,10 @@ async function loadData() { updateBGPHud, getShowComputeCenters, getShowVessels, + getShowAircraft: () => aircraftEnabled || getShowAircraft(), + getShowGpsJamming: () => gpsJammingEnabled || getShowGpsJamming(), + getShowDisasters: () => disastersEnabled, + updateAircraftHud: (res) => updateAircraftToggleUi(aircraftEnabled || getShowAircraft(), res?.totalCount ?? getAircraftCount()), getShowCountryBoundaries, getShowBGP, isEarthTextureVisible: () => getEarthTextureVisible(), @@ -6025,6 +6776,9 @@ async function loadData() { setLegendItems("countryBoundaries", getCountryBoundaryLegendItems()); setLegendItems("computeCenters", getComputeCenterLegendItems()); setLegendItems("vessels", getVesselLegendItems()); + setLegendItems("aircraft", getAircraftLegendItems()); + setLegendItems("gpsJamming", getGpsJammingLegendItems()); + setLegendItems("disasters", getDisastersLegendItems()); setLegendItems("bgp", getBGPLegendItems()); refreshLegend(); setLoading(false); @@ -6100,6 +6854,7 @@ async function loadData() { } finally { if (loadToken === currentLoadToken && !destroyed) { scheduleTerrainPrefetch(); + window.__planetSync2dLayers?.(); emitEarthStartupProgress(1, earthMessage("status.dataLoaded")); markEarthStartupReady({ loadToken, errorsCount: errors.length }); } @@ -6122,6 +6877,82 @@ export function getVesselsEnabled() { return vesselsEnabled; } +export function getAircraftEnabled() { + return aircraftEnabled; +} + +export function getGpsJammingEnabled() { + return gpsJammingEnabled; +} + +export function getDisastersEnabled() { + return disastersEnabled; +} + +export function getGeofencesEnabled() { + return Boolean(geofenceManager?.isVisible?.()); +} + +export async function setGeofencesEnabled(enabled, { suppressStatus = false } = {}) { + if (!geofenceManager) return 0; + const next = Boolean(enabled); + geofenceManager.setVisible(next); + let count = geofenceManager.getGeofences().length; + if (next) { + const res = await geofenceManager.loadGeofences(); + count = res.count; + } + const btn = document.getElementById("toggle-geofences"); + if (btn) { + setLayerButtonState(btn, { + active: next, + loading: false, + tooltip: next ? "隐藏电子围栏" : "显示电子围栏", + }); + } + setLegendItems("geofences", [ + { key: "geofence-preset", label: "预置围栏(海缆/咽喉)", color: "#38bdf8", shape: "dot" }, + { key: "geofence-custom", label: "自定义多边形围栏", color: "#fbbf24", shape: "dot" }, + ]); + refreshLegend(); + if (!suppressStatus) { + showStatusMessage(earthMessage("status.layerVisibility", { layer: "电子围栏", visible: next }), "info"); + } + return count; +} + +export function getFusionOverlaysEnabled() { + return Boolean(fusionOverlaysManager?.isVisible?.()); +} + +export async function setFusionOverlaysEnabled(enabled, { suppressStatus = false } = {}) { + if (!fusionOverlaysManager) return { candidateCount: 0, dependencyArcCount: 0 }; + const next = Boolean(enabled); + fusionOverlaysManager.setVisible(next); + let stats = fusionOverlaysManager.getStats(); + if (next) { + stats = await fusionOverlaysManager.loadOverlays(); + setLegendMode("fusionOverlays"); + } + const btn = document.getElementById("toggle-fusion-overlays"); + if (btn) { + setLayerButtonState(btn, { + active: next, + loading: false, + tooltip: next ? "隐藏关联与影响链" : "显示关联与影响链", + }); + } + setLegendItems("fusionOverlays", [ + { key: "fusion-candidate", label: "待核查关联(虚线六边形 · 待核查)", color: "#f59e0b", shape: "dot" }, + { key: "fusion-impact", label: "依赖影响链(实线弧 · 有独立证据)", color: "#ef4444", shape: "dot" }, + ]); + refreshLegend(); + if (!suppressStatus) { + showStatusMessage(earthMessage("status.layerVisibility", { layer: "关联与影响链", visible: next }), "info"); + } + return stats; +} + export async function setCablesEnabled( enabled, { suppressStatus = false, suppressLoadingUi = false } = {}, @@ -6454,6 +7285,167 @@ export async function setVesselsEnabled( } } +export async function setAircraftEnabled( + enabled, + { suppressStatus = false, suppressLoadingUi = false } = {}, +) { + if (enabled === aircraftEnabled) { + updateAircraftToggleUi(enabled); + return getAircraftCount(); + } + if (!enabled) { + clearSelectionAndInfo(); + disableAircraft(); + if (!suppressStatus) { + showStatusMessage(earthMessage("status.layerVisibility", { layer: "航空器", visible: false }), "info"); + } + return 0; + } + if (!suppressLoadingUi) { + setLoadingMessage(earthMessage("loading.aircraftData")); + setLoading(true); + hideError(); + } + try { + const count = await ensureAircraftEnabled(); + if (!suppressStatus) { + showStatusMessage(earthMessage("status.layerVisibility", { layer: "航空器", visible: true }), "info"); + } + return count; + } catch (error) { + aircraftEnabled = false; + clearAircraftData(getEarth()); + updateAircraftToggleUi(false, 0); + const reason = error?.message || String(error); + const message = earthMessage("status.layerLoadFailed", { layer: "航空器", error: reason }); + if (!suppressLoadingUi) showError(message); + if (!suppressStatus) showStatusMessage(message, "error"); + throw error; + } finally { + if (!suppressLoadingUi) setLoading(false); + } +} + +export async function setDisastersEnabled( + enabled, + { suppressStatus = false, suppressLoadingUi = false } = {}, +) { + if (enabled === disastersEnabled) { + updateDisastersToggleUi(enabled); + return getDisastersCount(); + } + if (!enabled) { + disableDisasters(); + if (!suppressStatus) { + showStatusMessage(earthMessage("status.layerVisibility", { layer: "自然灾害", visible: false }), "info"); + } + return 0; + } + if (!suppressLoadingUi) { + setLoadingMessage(earthMessage("loading.disastersData")); + setLoading(true); + hideError(); + } + try { + const count = await ensureDisastersEnabled(); + if (!suppressStatus) { + showStatusMessage(earthMessage("status.layerVisibility", { layer: "自然灾害", visible: true }), "info"); + } + return count; + } catch (error) { + disastersEnabled = false; + clearDisastersData(getEarth()); + updateDisastersToggleUi(false); + const reason = error?.message || String(error); + const message = earthMessage("status.layerLoadFailed", { layer: "自然灾害", error: reason }); + if (!suppressLoadingUi) showError(message); + if (!suppressStatus) showStatusMessage(message, "error"); + throw error; + } finally { + if (!suppressLoadingUi) setLoading(false); + } +} + +export async function setGpsJammingEnabled( + enabled, + { suppressStatus = false, suppressLoadingUi = false } = {}, +) { + if (enabled === gpsJammingEnabled) { + updateGpsJammingToggleUi(enabled); + return getGpsJammingCount(); + } + if (!enabled) { + disableGpsJamming(); + if (!suppressStatus) { + showStatusMessage(earthMessage("status.layerVisibility", { layer: "GPS 干扰", visible: false }), "info"); + } + return 0; + } + if (!suppressLoadingUi) { + setLoadingMessage(earthMessage("loading.gpsJammingData")); + setLoading(true); + hideError(); + } + try { + const count = await ensureGpsJammingEnabled(); + if (!suppressStatus) { + showStatusMessage(earthMessage("status.layerVisibility", { layer: "GPS 干扰", visible: true }), "info"); + } + return count; + } catch (error) { + gpsJammingEnabled = false; + clearGpsJammingData(getEarth()); + updateGpsJammingToggleUi(false); + const reason = error?.message || String(error); + const message = earthMessage("status.layerLoadFailed", { layer: "GPS 干扰", error: reason }); + if (!suppressLoadingUi) showError(message); + if (!suppressStatus) showStatusMessage(message, "error"); + throw error; + } finally { + if (!suppressLoadingUi) setLoading(false); + } +} + +export async function setDisastersEnabled( + enabled, + { suppressStatus = false, suppressLoadingUi = false } = {}, +) { + if (enabled === disastersEnabled) { + updateDisastersToggleUi(enabled); + return getDisastersCount(); + } + if (!enabled) { + disableDisasters(); + if (!suppressStatus) { + showStatusMessage(earthMessage("status.layerVisibility", { layer: "自然灾害", visible: false }), "info"); + } + return 0; + } + if (!suppressLoadingUi) { + setLoadingMessage(earthMessage("loading.disastersData")); + setLoading(true); + hideError(); + } + try { + const count = await ensureDisastersEnabled(); + if (!suppressStatus) { + showStatusMessage(earthMessage("status.layerVisibility", { layer: "自然灾害", visible: true }), "info"); + } + return count; + } catch (error) { + disastersEnabled = false; + clearDisastersData(getEarth()); + updateDisastersToggleUi(false); + const reason = error?.message || String(error); + const message = earthMessage("status.layerLoadFailed", { layer: "自然灾害", error: reason }); + if (!suppressLoadingUi) showError(message); + if (!suppressStatus) showStatusMessage(message, "error"); + throw error; + } finally { + if (!suppressLoadingUi) setLoading(false); + } +} + function setupEventListeners() { const handleResize = () => onWindowResize(); const handleVisibilityChange = () => onVisibilityChange(); @@ -6868,6 +7860,15 @@ function onMouseMove(event) { surfaceHover.hoveredCountry = getShowCountryBoundaries() ? updateCountryBoundaryHover(surfaceHover.coords) : null; + surfaceHover.hoveredGpsJamming = getShowGpsJamming() + ? findGpsJammingCellAtLatLon(surfaceHover.coords.lat, surfaceHover.coords.lon) + : null; + surfaceHover.hoveredDisaster = disastersEnabled + ? findNearestDisaster(surfaceHover.coords.lat, surfaceHover.coords.lon) + : null; + surfaceHover.hoveredChokepoint = isChokepointOverlayActive() + ? findNearestChokepoint(surfaceHover.coords.lat, surfaceHover.coords.lon) + : null; if (!getShowCountryBoundaries()) { clearCountryBoundaryHover(); } @@ -6949,6 +7950,27 @@ function onMouseMove(event) { getVesselBriefHtml(hoveredVesselMarker), ); objectTooltipShown = true; + } else if ( + surfaceHover?.coords && + getShowAircraft() && + !shouldSkipVesselHoverPicking() + ) { + const aircraftHits = getAircraftBatchPointerIntersections({ + earth: getEarth(), + camera, + surfaceCoords: surfaceHover.coords, + clientX: event.clientX, + clientY: event.clientY, + radiusPx: VESSEL_POINTER_RADIUS_PX, + }); + if (aircraftHits.length > 0) { + showTooltip( + event.clientX + TOOLTIP_CURSOR_OFFSET, + event.clientY + TOOLTIP_CURSOR_OFFSET, + getAircraftBriefHtml(aircraftHits[0].object), + ); + objectTooltipShown = true; + } } else if ( hoveredEarthInteractableMarker && hoveredEarthInteractableMarker !== lockedObject @@ -7011,7 +8033,33 @@ function onMouseMove(event) { if (!objectTooltipShown) { if (surfaceHover) { - const { coords, hoveredCountry } = surfaceHover; + const { coords, hoveredCountry, hoveredGpsJamming, hoveredDisaster } = surfaceHover; + if (hoveredDisaster) { + showTooltip( + event.clientX + TOOLTIP_CURSOR_OFFSET, + event.clientY + TOOLTIP_CURSOR_OFFSET, + getDisasterBriefHtml(hoveredDisaster), + ); + return; + } + if (surfaceHover.hoveredChokepoint) { + const cp = surfaceHover.hoveredChokepoint; + const deltaStr = cp.delta_vs_7d != null ? ` · 7d偏差 ${cp.delta_vs_7d >= 0 ? "+" : ""}${cp.delta_vs_7d}` : ""; + showTooltip( + event.clientX + TOOLTIP_CURSOR_OFFSET, + event.clientY + TOOLTIP_CURSOR_OFFSET, + `${cp.name}
船舶 ${cp.vessel_count || 0} · 军舰 ${cp.warship_count || 0}${deltaStr}`, + ); + return; + } + if (hoveredGpsJamming) { + showTooltip( + event.clientX + TOOLTIP_CURSOR_OFFSET, + event.clientY + TOOLTIP_CURSOR_OFFSET, + getGpsJammingBriefHtml(hoveredGpsJamming), + ); + return; + } const hoverInfoMode = getSurfaceHoverInfoMode(); const shouldShowCountry = hoverInfoMode === SURFACE_HOVER_INFO_MODES.COUNTRY || @@ -7252,6 +8300,23 @@ function onClick(event) { } updatePointerFromEvent(event); + if (geofenceManager?.isDrawing?.()) { + const drawPt = screenToEarthCoords( + event.clientX, + event.clientY, + camera, + getEarthSurfacePickTarget() || earth, + document.body, + interactionRaycaster, + interactionMouse, + ); + if (drawPt) { + const coords = vector3ToLatLon(drawPt); + const count = geofenceManager.addVertex(coords.lat, coords.lon); + incidentsHud?.setVertexFeedback?.(count); + } + return; + } invalidateToolInfoCardRestore("scene_click"); if (isMotionPresentationActive()) presentationController?.dismiss?.("replace"); @@ -7263,8 +8328,42 @@ function onClick(event) { const computeCenterIntersects = getShowComputeCenters() ? getComputeCenterPointerIntersections() : []; const vesselIntersects = getShowVessels() ? getVesselPointerIntersections() : []; + let aircraftIntersects = []; + if (getShowAircraft() && !shouldSkipVesselHoverPicking()) { + const clickSurfacePt = screenToEarthCoords( + event.clientX, + event.clientY, + camera, + getEarthSurfacePickTarget() || earth, + document.body, + interactionRaycaster, + interactionMouse, + ); + if (clickSurfacePt) { + aircraftIntersects = getAircraftBatchPointerIntersections({ + earth, + camera, + surfaceCoords: vector3ToLatLon(clickSurfacePt), + clientX: event.clientX, + clientY: event.clientY, + radiusPx: VESSEL_POINTER_RADIUS_PX, + }); + } + } const earthInteractableIntersects = getEarthInteractablePointerIntersections(); const satIntersects = getSatellitePointerIntersections(event); + if (aircraftIntersects.length > 0 && (!satIntersects.length || aircraftIntersects[0].distanceSq <= satIntersects[0].distanceSq)) { + const picked = aircraftIntersects[0]; + if (confirmInteractionCandidate({ + type: "aircraft", + object: picked.object, + screen: { x: event.clientX, y: event.clientY }, + distancePxSq: picked.distanceSq, + }, { showConfirmationFeedback: false })) { + showSelectionStatus(getInteractionCandidateLabel({ type: "aircraft", object: picked.object })); + } + return; + } const interactivePick = pickInteractiveIcon({ bgpAnomalyIntersects, bgpCollectorIntersects, @@ -7322,6 +8421,24 @@ function onClick(event) { return; } + if (disastersEnabled) { + const disasterSurfacePt = screenToEarthCoords( + event.clientX, + event.clientY, + camera, + getEarthSurfacePickTarget() || earth, + document.body, + ); + const hitDisaster = disasterSurfacePt + ? findNearestDisaster(disasterSurfacePt.lat, disasterSurfacePt.lon) + : null; + if (hitDisaster) { + showDisasterInfo(hitDisaster, { lat: hitDisaster.lat, lon: hitDisaster.lon, screen: { x: event.clientX, y: event.clientY } }); + showSelectionStatus(hitDisaster.title || hitDisaster.event_type); + return; + } + } + if (isCruiseModeActive()) interruptCruisePresentation({ resetLoop: true }); clearLockedObject(); hideInfoCard(); @@ -7329,7 +8446,7 @@ function onClick(event) { } function animate() { - if (destroyed || desktopMinimized || webglContextLost) return; + if (destroyed || desktopMinimized || webglContextLost || view2dActive) return; animationFrameId = requestAnimationFrame(animate); const frameNow = performance.now(); const stage = (name, update) => { @@ -7414,6 +8531,7 @@ function animate() { stage("bgp-visuals", () => updateBGPVisualState(lockedObjectType, lockedObject, camera, activeCruiseMarker)); stage("compute-visuals", () => updateComputeCenterVisualState(lockedObjectType, lockedObject, camera)); stage("vessel-visuals", () => updateVesselVisualState(lockedObjectType, lockedObject, camera)); + stage("aircraft-visuals", () => updateAircraftVisualState(camera)); stage("custom-marker-visuals", () => updateEarthInteractableVisualState(lockedObjectType, lockedObject, camera)); stage("landing-point-selection", () => { @@ -7493,6 +8611,7 @@ function animate() { stage("motion-connector", () => repositionMotionConnector()); stage("earth-tile-lod", () => updateEarthTileLayers(camera)); stage("wind-streamlines", () => updateWindField(deltaTime)); + stage("disasters-pulse", () => updateDisastersFrame(frameNow * 0.001)); const rendered = stage("scene-render", () => renderer.render(scene, camera)); if (rendered) stage("frame-stats", () => finishFrameStats(statsStart, renderer)); frameProfile?.flush(frameNow); @@ -7523,6 +8642,7 @@ export function destroy() { canvasResizeObserver = null; frameStages.clear(); clearInteractableClusters(); + clearDisastersData(getEarth()); screenSpaceDrag.stop(); screenSpaceInertia = false; stopVesselRealtime(); @@ -7591,6 +8711,10 @@ export function destroy() { clearTerrainData(); disposeEarthTileLayers(); disposeWindField(); + map2dController?.destroy?.(); + map2dController = null; + mapViewController = null; + view2dActive = false; if (scene) { disposeSceneObject(scene); diff --git a/frontend/public/earth/js/map-2d.js b/frontend/public/earth/js/map-2d.js new file mode 100644 index 00000000..0de204f8 --- /dev/null +++ b/frontend/public/earth/js/map-2d.js @@ -0,0 +1,824 @@ +import { Protocol } from "pmtiles"; +import { CONFIG } from "./constants.js"; +import { + ensureCountryBoundariesReady, + getBoundaryPmtilesArchive, + getBoundaryPmtilesUrl, + getShowCountryBoundaries, + lookupCountryGroupAtLatLon, +} from "./country-boundaries.js"; +import { + estimateLabelDimensions, + formatPlaceLabel, + getGeoLabelLocale, + getGeoLabelsEnabled, + getLoadedGeoLabelPlaces, + selectVisibleGeoLabels, +} from "./geo-labels.js"; + +const pmtilesProtocol = new Protocol(); +let pmtilesProtocolRegistered = false; + +const COMPUTE_SITE_COLORS = { + supercomputer: "#a855f7", + gpu_cluster: "#2dd4bf", + data_center: "#38bdf8", + cloud_center: "#60a5fa", + edge_node: "#f59e0b", + national_hub: "#14b8a6", +}; + +function ensureMapLibreStylesheet() { + if (typeof document === "undefined") return; + if (document.querySelector('link[data-maplibre-css="true"]')) return; + const link = document.createElement("link"); + link.rel = "stylesheet"; + link.href = new URL("../vendor/maplibre-gl.css", import.meta.url).href; + link.dataset.maplibreCss = "true"; + document.head?.appendChild(link); +} + +function latLonFromThreeVector(vec) { + if (!vec) return null; + const r = Math.hypot(vec.x || 0, vec.y || 0, vec.z || 0) || CONFIG.earthRadius; + const lat = 90 - (Math.acos(Math.max(-1, Math.min(1, (vec.y || 0) / r))) * 180) / Math.PI; + let lon = (Math.atan2(vec.z || 0, -(vec.x || 0)) * 180) / Math.PI - 180; + while (lon <= -180) lon += 360; + while (lon > 180) lon -= 360; + return { lat, lon }; +} + +function resolveTileUrlTemplate(rawTemplate) { + const tpl = String(rawTemplate || "/api/v1/earth/tiles/earth_imagery_sentinel2/{z}/{x}/{y}.webp").trim(); + if (/^https?:\/\//i.test(tpl) || typeof window === "undefined") return tpl; + if (tpl.startsWith("./")) { + return `${window.location.origin}${tpl.slice(1)}`; + } + if (tpl.startsWith("/")) { + return `${window.location.origin}${tpl}`; + } + return `${window.location.origin}/${tpl}`; +} + +export function createMap2dController({ + container, + getBasemapConfig = () => ({}), + getSnapshots = () => ({}), + onViewChange, + onHoverCountry, + onSelectFeature, + onLocaleRequest, +} = {}) { + let map = null; + let maplibre = null; + let initPromise = null; + let styleReady = false; + let visible = false; + let locale = getGeoLabelLocale(); + let labelRoot = null; + let labelSlots = []; + let hoveredGroupKey = null; + let hoveredCodes = []; + let pendingView = { lat: 30, lon: 105, zoom: 2.5 }; + let activeSnapshots = {}; + const interactiveLookup = new Map(); + + function buildGeoJsonCollections(snapshots) { + interactiveLookup.clear(); + let seq = 1; + + const cableFeatures = []; + for (const line of snapshots.cables || []) { + const id = seq++; + const attrs = line?.geometry?.attributes?.position; + const segments = []; + let currentSeg = []; + if (attrs && attrs.count >= 2) { + const stride = attrs.count > 120 ? Math.ceil(attrs.count / 90) : 1; + let prevLon = null; + for (let i = 0; i < attrs.count; i += stride) { + const p = latLonFromThreeVector({ x: attrs.getX(i), y: attrs.getY(i), z: attrs.getZ(i) }); + if (!p) continue; + if (prevLon !== null && Math.abs(p.lon - prevLon) > 180) { + if (currentSeg.length >= 2) segments.push(currentSeg); + currentSeg = []; + } + currentSeg.push([p.lon, p.lat]); + prevLon = p.lon; + } + if (currentSeg.length >= 2) segments.push(currentSeg); + } + if (segments.length >= 1) { + interactiveLookup.set(id, { type: "cable", object: line }); + cableFeatures.push({ + type: "Feature", + geometry: segments.length === 1 + ? { type: "LineString", coordinates: segments[0] } + : { type: "MultiLineString", coordinates: segments }, + properties: { + __lookupId: id, + color: line.userData?.color || "#38bdf8", + name: line.userData?.name || "", + }, + }); + } + } + + const lpFeatures = []; + for (const point of snapshots.landingPoints || []) { + const lat = Number(point?.userData?.latitude); + const lon = Number(point?.userData?.longitude); + if (!Number.isFinite(lat) || !Number.isFinite(lon)) continue; + const id = seq++; + interactiveLookup.set(id, { type: "landing_point", object: point }); + lpFeatures.push({ + type: "Feature", + geometry: { type: "Point", coordinates: [lon, lat] }, + properties: { __lookupId: id, name: point.userData?.name || "" }, + }); + } + + const computeFeatures = []; + for (const marker of snapshots.computeCenters || []) { + const ud = marker?.userData || {}; + const lat = Number(ud.displayLatitude ?? ud.latitude); + const lon = Number(ud.displayLongitude ?? ud.longitude); + if (!Number.isFinite(lat) || !Number.isFinite(lon)) continue; + const id = seq++; + interactiveLookup.set(id, { type: "compute_center", object: marker }); + computeFeatures.push({ + type: "Feature", + geometry: { type: "Point", coordinates: [lon, lat] }, + properties: { + __lookupId: id, + color: COMPUTE_SITE_COLORS[ud.site_type] || "#a855f7", + name: ud.name || "", + }, + }); + } + + const vesselFeatures = []; + for (const marker of snapshots.vessels || []) { + const ud = marker?.userData || {}; + const lat = Number(ud.latitude ?? ud.lat); + const lon = Number(ud.longitude ?? ud.lon); + if (!Number.isFinite(lat) || !Number.isFinite(lon)) continue; + const id = seq++; + interactiveLookup.set(id, { type: "vessel", object: marker }); + vesselFeatures.push({ + type: "Feature", + geometry: { type: "Point", coordinates: [lon, lat] }, + properties: { __lookupId: id, name: ud.name || "" }, + }); + } + + const bgpFeatures = []; + for (const marker of snapshots.bgpEvents || []) { + const ud = marker?.userData || {}; + const lat = Number(ud.latitude ?? ud.lat); + const lon = Number(ud.longitude ?? ud.lon); + if (!Number.isFinite(lat) || !Number.isFinite(lon)) continue; + const id = seq++; + interactiveLookup.set(id, { type: "bgp", object: marker }); + bgpFeatures.push({ + type: "Feature", + geometry: { type: "Point", coordinates: [lon, lat] }, + properties: { __lookupId: id, kind: "event", color: "#f97316" }, + }); + } + for (const marker of snapshots.bgpCollectors || []) { + const ud = marker?.userData || {}; + const lat = Number(ud.latitude ?? ud.lat); + const lon = Number(ud.longitude ?? ud.lon); + if (!Number.isFinite(lat) || !Number.isFinite(lon)) continue; + const id = seq++; + interactiveLookup.set(id, { type: "bgp_collector", object: marker }); + bgpFeatures.push({ + type: "Feature", + geometry: { type: "Point", coordinates: [lon, lat] }, + properties: { __lookupId: id, kind: "collector", color: "#38bdf8" }, + }); + } + + const satFeatures = []; + const sats = snapshots.satellites || []; + const satPositions = snapshots.satellitePositions || []; + for (let idx = 0; idx < Math.min(sats.length, 450); idx += 1) { + const sat = sats[idx]; + let lat = Number(sat?.lat ?? sat?.latitude); + let lon = Number(sat?.lon ?? sat?.longitude); + if (!Number.isFinite(lat) || !Number.isFinite(lon)) { + const pos = satPositions[idx]?.current || satPositions[idx]; + const coords = latLonFromThreeVector(pos); + if (coords) { + lat = coords.lat; + lon = coords.lon; + } + } + if (!Number.isFinite(lat) || !Number.isFinite(lon)) continue; + const id = seq++; + interactiveLookup.set(id, { type: "satellite", object: sat, index: idx }); + satFeatures.push({ + type: "Feature", + geometry: { type: "Point", coordinates: [lon, lat] }, + properties: { __lookupId: id, name: sat?.properties?.name || sat?.name || "" }, + }); + } + + return { + cables: { type: "FeatureCollection", features: cableFeatures }, + landingPoints: { type: "FeatureCollection", features: lpFeatures }, + computeCenters: { type: "FeatureCollection", features: computeFeatures }, + vessels: { type: "FeatureCollection", features: vesselFeatures }, + bgp: { type: "FeatureCollection", features: bgpFeatures }, + satellites: { type: "FeatureCollection", features: satFeatures }, + }; + } + + function ensureLabelOverlay() { + if (!container || labelRoot) return; + labelRoot = document.createElement("div"); + labelRoot.className = "geo-labels earth-geo-labels-2d"; + labelRoot.style.position = "absolute"; + labelRoot.style.inset = "0"; + labelRoot.style.pointerEvents = "none"; + labelRoot.style.overflow = "hidden"; + labelRoot.style.zIndex = "4"; + for (let i = 0; i < 32; i += 1) { + const el = document.createElement("div"); + el.className = "geo-map-label"; + el.hidden = true; + const dot = document.createElement("span"); + dot.className = "geo-map-label__dot"; + const name = document.createElement("span"); + name.className = "geo-map-label__name"; + el.append(dot, name); + labelRoot.appendChild(el); + labelSlots.push({ el, name }); + } + container.appendChild(labelRoot); + } + + function update2dGeoLabels() { + if (!map || !styleReady || !labelRoot) return; + const enabled = getGeoLabelsEnabled(); + const places = enabled ? getLoadedGeoLabelPlaces() : []; + if (!enabled || !places.length || !visible) { + for (const s of labelSlots) s.el.hidden = true; + return; + } + const width = container.clientWidth || 1280; + const height = container.clientHeight || 800; + const halfW = width * 0.5; + const halfH = height * 0.5; + const zoom = map.getZoom(); + const activeLocale = onLocaleRequest?.() || locale; + + const candidates = []; + for (let idx = 0; idx < places.length; idx += 1) { + const place = places[idx]; + if (place.t === 2 && zoom < 3.4) continue; + if (place.t === 3 && zoom < 4.5) continue; + const pt = map.project([place.lon, place.lat]); + if (!pt || pt.x < 40 || pt.y < 40 || pt.x > width - 40 || pt.y > height - 40) continue; + const label = formatPlaceLabel(place, activeLocale); + const dims = estimateLabelDimensions(label, place.k); + candidates.push({ + id: idx, + place, + label, + x: pt.x, + y: pt.y, + opacity: 0.92, + width: dims.width, + height: dims.height, + centerDistSq: (pt.x - halfW) ** 2 + (pt.y - halfH) ** 2, + }); + } + + const chosen = selectVisibleGeoLabels(candidates, { + maxCount: width <= 820 ? 14 : 28, + obstacles: [], + previousIds: new Set(), + viewportWidth: width, + viewportHeight: height, + }); + + for (let i = 0; i < labelSlots.length; i += 1) { + const slot = labelSlots[i]; + const item = chosen[i]; + if (!item) { + slot.el.hidden = true; + continue; + } + slot.el.hidden = false; + slot.el.dataset.tier = String(item.place.t || 2); + slot.el.dataset.kind = String(item.place.k || "major"); + slot.name.textContent = item.label; + slot.el.style.transform = `translate(${Math.round(item.x)}px,${Math.round(item.y)}px) translate(-3px,-50%)`; + slot.el.style.opacity = String(item.opacity); + } + } + + function applyHoverFilter(groupResult) { + const nextKey = groupResult?.groupKey || null; + if (nextKey === hoveredGroupKey) return; + hoveredGroupKey = nextKey; + hoveredCodes = Array.isArray(groupResult?.codes) ? groupResult.codes : []; + onHoverCountry?.(groupResult?.info || null); + + if (!map || !styleReady) return; + const codes = hoveredCodes; + const showHover = codes.length > 0 && getShowCountryBoundaries(); + const showChinaClaim = showHover && (codes.includes("CHN") || codes.includes("TWN")); + + const areaFilter = showHover + ? [ + "any", + ["in", ["get", "ADM0_A3"], ["literal", codes]], + ["in", ["get", "ISO_A3"], ["literal", codes]], + ] + : ["==", ["literal", 1], 0]; + const borderFilter = showHover + ? [ + "any", + ["in", ["get", "ADM0_L"], ["literal", codes]], + ["in", ["get", "ADM0_R"], ["literal", codes]], + ["in", ["get", "ADM0_A3"], ["literal", codes]], + ["in", ["get", "ISO_A3"], ["literal", codes]], + ] + : ["==", ["literal", 1], 0]; + + if (map.getLayer("hover-coastline")) { + map.setLayoutProperty("hover-coastline", "visibility", showHover ? "visible" : "none"); + map.setFilter("hover-coastline", areaFilter); + } + if (map.getLayer("hover-admin0")) { + map.setLayoutProperty("hover-admin0", "visibility", showHover ? "visible" : "none"); + map.setFilter("hover-admin0", borderFilter); + } + if (map.getLayer("hover-disputed")) { + map.setLayoutProperty("hover-disputed", "visibility", showHover ? "visible" : "none"); + map.setFilter("hover-disputed", borderFilter); + } + if (map.getLayer("hover-claim")) { + map.setLayoutProperty("hover-claim", "visibility", showChinaClaim ? "visible" : "none"); + } + if (map.getLayer("claim-line")) { + map.setPaintProperty( + "claim-line", + "line-opacity", + showHover && !showChinaClaim ? 0.2 : 0.85, + ); + } + // Note: boundary-admin1 & boundary-admin1-casing intentionally never dim on hover! + } + + function syncLayers(nextSnapshots) { + if (nextSnapshots) activeSnapshots = nextSnapshots; + if (!map || !styleReady) return; + const s = activeSnapshots || getSnapshots() || {}; + const collections = buildGeoJsonCollections(s); + const vis = s.visibility || {}; + + const setSrc = (id, data) => map.getSource(id)?.setData(data); + setSrc("biz-cables", collections.cables); + setSrc("biz-landing-points", collections.landingPoints); + setSrc("biz-compute-centers", collections.computeCenters); + setSrc("biz-vessels", collections.vessels); + setSrc("biz-bgp", collections.bgp); + setSrc("biz-satellites", collections.satellites); + + const setVis = (layerId, isOn) => { + if (map.getLayer(layerId)) { + map.setLayoutProperty(layerId, "visibility", isOn ? "visible" : "none"); + } + }; + const showBoundaries = vis.countryBoundaries ?? getShowCountryBoundaries(); + for (const bLayer of [ + "coastline", + "boundary-admin0", + "boundary-disputed", + "boundary-admin1-casing", + "boundary-admin1", + "claim-line", + ]) { + setVis(bLayer, showBoundaries); + } + setVis("biz-cables-line", vis.cables ?? true); + setVis("biz-landing-points-circle", vis.cables ?? true); + setVis("biz-compute-centers-circle", vis.computeCenters ?? true); + setVis("biz-vessels-circle", vis.vessels ?? false); + setVis("biz-bgp-circle", vis.bgp ?? true); + setVis("biz-satellites-circle", vis.satellites ?? false); + + update2dGeoLabels(); + } + + async function ensureMapInitialized() { + if (map) return map; + if (initPromise) return initPromise; + + initPromise = (async () => { + ensureMapLibreStylesheet(); + await ensureCountryBoundariesReady().catch(() => {}); + const imported = await import("maplibre-gl"); + maplibre = imported.default || imported; + const workerUrl = new URL("../vendor/maplibre-gl-worker.mjs", import.meta.url).href; + maplibre.setWorkerUrl?.(workerUrl); + + if (!pmtilesProtocolRegistered) { + maplibre.addProtocol("pmtiles", pmtilesProtocol.tile); + pmtilesProtocolRegistered = true; + } + + const basemapCfg = getBasemapConfig() || {}; + const tileTemplate = resolveTileUrlTemplate(basemapCfg.tileUrlTemplate); + const pmtilesPath = getBoundaryPmtilesUrl(); + const archive = getBoundaryPmtilesArchive(); + let resolvedPmtilesUrl = pmtilesPath; + if (pmtilesPath) { + if (typeof window !== "undefined") { + try { + resolvedPmtilesUrl = new URL(pmtilesPath, window.location.origin).href; + } catch { + resolvedPmtilesUrl = pmtilesPath; + } + } + if (archive) { + pmtilesProtocol.add(archive); + pmtilesProtocol.tiles.set(pmtilesPath, archive); + if (resolvedPmtilesUrl) { + pmtilesProtocol.tiles.set(resolvedPmtilesUrl, archive); + } + } + } + const sources = { + basemap: { + type: "raster", + tiles: [tileTemplate], + tileSize: 256, + minzoom: 0, + maxzoom: Number(basemapCfg.maxZoom || 7), + }, + }; + const layers = [ + { id: "bg", type: "background", paint: { "background-color": "#030916" } }, + { id: "basemap-raster", type: "raster", source: "basemap", paint: { "raster-opacity": 0.96 } }, + ]; + + if (resolvedPmtilesUrl) { + sources.boundaries = { + type: "vector", + url: `pmtiles://${resolvedPmtilesUrl}`, + }; + layers.push( + { + id: "coastline", + type: "line", + source: "boundaries", + "source-layer": "coastline", + paint: { "line-color": "#8ab4d8", "line-opacity": 0.68, "line-width": 1.1 }, + }, + { + id: "boundary-admin0", + type: "line", + source: "boundaries", + "source-layer": "boundary_admin0", + paint: { "line-color": "#b8d8f8", "line-opacity": 0.78, "line-width": 1.35 }, + }, + { + id: "boundary-disputed", + type: "line", + source: "boundaries", + "source-layer": "boundary_disputed_internal", + paint: { "line-color": "#b8d8f8", "line-opacity": 0.78, "line-width": 1.35 }, + }, + { + id: "boundary-admin1-casing", + type: "line", + source: "boundaries", + "source-layer": "boundary_admin1", + minzoom: 3, + paint: { "line-color": "#050a14", "line-opacity": 0.36, "line-width": 3.2 }, + }, + { + id: "boundary-admin1", + type: "line", + source: "boundaries", + "source-layer": "boundary_admin1", + minzoom: 3, + paint: { + "line-color": "#d8e8f8", + "line-opacity": 0.48, + "line-width": 1.2, + "line-dasharray": [6, 4], + }, + }, + { + id: "claim-line", + type: "line", + source: "boundaries", + "source-layer": "claim_line", + paint: { + "line-color": "#cbd5e1", + "line-opacity": 0.85, + "line-width": 1.8, + "line-dasharray": [6, 4], + }, + }, + { + id: "hover-coastline", + type: "line", + source: "boundaries", + "source-layer": "coastline", + layout: { visibility: "none" }, + paint: { "line-color": "#ff5a36", "line-opacity": 0.96, "line-width": 2.6 }, + }, + { + id: "hover-admin0", + type: "line", + source: "boundaries", + "source-layer": "boundary_admin0", + layout: { visibility: "none" }, + paint: { "line-color": "#ff5a36", "line-opacity": 0.96, "line-width": 2.6 }, + }, + { + id: "hover-disputed", + type: "line", + source: "boundaries", + "source-layer": "boundary_disputed_internal", + layout: { visibility: "none" }, + paint: { "line-color": "#ff5a36", "line-opacity": 0.96, "line-width": 2.6 }, + }, + { + id: "hover-claim", + type: "line", + source: "boundaries", + "source-layer": "claim_line", + layout: { visibility: "none" }, + paint: { + "line-color": "#ff5a36", + "line-opacity": 0.96, + "line-width": 2.8, + "line-dasharray": [6, 4], + }, + }, + ); + } else { + sources.boundariesFallback = { + type: "geojson", + data: new URL("../data/countries-admin0.china-pov-v1.geojson", import.meta.url).href, + }; + layers.push({ + id: "boundary-admin0", + type: "line", + source: "boundariesFallback", + paint: { "line-color": "#b8d8f8", "line-opacity": 0.78, "line-width": 1.35 }, + }); + } + + const emptyFc = { type: "FeatureCollection", features: [] }; + sources["biz-cables"] = { type: "geojson", data: emptyFc }; + sources["biz-landing-points"] = { type: "geojson", data: emptyFc }; + sources["biz-compute-centers"] = { type: "geojson", data: emptyFc }; + sources["biz-vessels"] = { type: "geojson", data: emptyFc }; + sources["biz-bgp"] = { type: "geojson", data: emptyFc }; + sources["biz-satellites"] = { type: "geojson", data: emptyFc }; + + layers.push( + { + id: "biz-cables-line", + type: "line", + source: "biz-cables", + paint: { "line-color": ["coalesce", ["get", "color"], "#38bdf8"], "line-width": 1.4, "line-opacity": 0.65 }, + }, + { + id: "biz-landing-points-circle", + type: "circle", + source: "biz-landing-points", + paint: { + "circle-color": "#f59e0b", + "circle-radius": 4, + "circle-stroke-width": 1, + "circle-stroke-color": "#0f172a", + }, + }, + { + id: "biz-compute-centers-circle", + type: "circle", + source: "biz-compute-centers", + paint: { + "circle-color": ["coalesce", ["get", "color"], "#a855f7"], + "circle-radius": 6, + "circle-stroke-width": 1.5, + "circle-stroke-color": "#f8fafc", + }, + }, + { + id: "biz-vessels-circle", + type: "circle", + source: "biz-vessels", + paint: { "circle-color": "#2dd4bf", "circle-radius": 3.5 }, + }, + { + id: "biz-bgp-circle", + type: "circle", + source: "biz-bgp", + paint: { + "circle-color": ["coalesce", ["get", "color"], "#f97316"], + "circle-radius": 5.5, + "circle-stroke-width": 1.2, + "circle-stroke-color": "#0f172a", + }, + }, + { + id: "biz-satellites-circle", + type: "circle", + source: "biz-satellites", + paint: { "circle-color": "#e0f2fe", "circle-radius": 3.2 }, + }, + ); + + ensureLabelOverlay(); + map = new maplibre.Map({ + container, + style: { version: 8, sources, layers }, + center: [pendingView.lon, pendingView.lat], + zoom: pendingView.zoom, + minZoom: 1.5, + maxZoom: 12, + attributionControl: false, + preserveDrawingBuffer: true, + dragRotate: false, + pitchWithRotate: false, + }); + + await new Promise((resolve) => { + if (map.isStyleLoaded()) { + resolve(); + return; + } + map.once("load", resolve); + }); + styleReady = true; + + map.on("move", () => { + const center = map.getCenter(); + pendingView = { lat: center.lat, lon: center.lng, zoom: map.getZoom() }; + update2dGeoLabels(); + onViewChange?.(pendingView); + }); + map.on("zoom", () => { + const center = map.getCenter(); + pendingView = { lat: center.lat, lon: center.lng, zoom: map.getZoom() }; + update2dGeoLabels(); + onViewChange?.(pendingView); + }); + map.on("mousemove", (event) => { + if (!visible) return; + const lngLat = event?.lngLat; + if (!lngLat) return; + const hit = lookupCountryGroupAtLatLon(lngLat.lat, lngLat.lng); + applyHoverFilter(hit); + }); + map.on("mouseout", () => applyHoverFilter(null)); + + const clickableLayers = [ + "biz-compute-centers-circle", + "biz-landing-points-circle", + "biz-bgp-circle", + "biz-vessels-circle", + "biz-satellites-circle", + "biz-cables-line", + ]; + map.on("click", (event) => { + if (!visible) return; + const presentLayers = clickableLayers.filter((id) => Boolean(map.getLayer(id))); + const hits = map.queryRenderedFeatures(event.point, { layers: presentLayers }); + const hit = hits?.[0]; + const lookupId = hit?.properties?.__lookupId; + const target = lookupId ? interactiveLookup.get(Number(lookupId)) : null; + if (target) { + onSelectFeature?.({ + ...target, + screen: { x: event.point.x, y: event.point.y }, + }); + } + }); + + syncLayers(getSnapshots()); + return map; + })().catch((error) => { + initPromise = null; + throw error; + }); + + return initPromise; + } + + return { + async show(view) { + if (view) pendingView = { ...view }; + visible = true; + if (container) container.hidden = false; + const m = await ensureMapInitialized(); + if (!visible) return; + m.resize(); + m.jumpTo({ center: [pendingView.lon, pendingView.lat], zoom: pendingView.zoom }); + syncLayers(getSnapshots()); + update2dGeoLabels(); + }, + hide() { + visible = false; + applyHoverFilter(null); + if (container) container.hidden = true; + if (labelSlots.length) { + for (const s of labelSlots) s.el.hidden = true; + } + }, + getView() { + if (!map) return { ...pendingView }; + const c = map.getCenter(); + return { lat: Number(c.lat.toFixed(4)), lon: Number(c.lng.toFixed(4)), zoom: Number(map.getZoom().toFixed(3)) }; + }, + setView(view) { + if (!view) return; + pendingView = { ...view }; + map?.jumpTo({ center: [pendingView.lon, pendingView.lat], zoom: pendingView.zoom }); + }, + zoomBy(delta) { + if (!map) return; + const next = Math.max(1.5, Math.min(12, map.getZoom() + (Number(delta) || 0))); + map.easeTo({ zoom: next, duration: 180 }); + }, + syncLayers, + setLocale(nextLocale) { + locale = String(nextLocale || "zh"); + update2dGeoLabels(); + }, + resize() { + map?.resize(); + }, + hoverAtLatLon(lat, lon) { + const hit = lookupCountryGroupAtLatLon(lat, lon); + applyHoverFilter(hit); + return hit; + }, + selectFirstFeature(type = null) { + for (const item of interactiveLookup.values()) { + if (!type || item.type === type) { + const ud = item.object?.userData || item.object || {}; + const lat = Number(ud.displayLatitude ?? ud.latitude ?? ud.lat); + const lon = Number(ud.displayLongitude ?? ud.longitude ?? ud.lon); + const w = container?.clientWidth || 1280; + const h = container?.clientHeight || 800; + let screen = { x: w * 0.45, y: h * 0.5 }; + if (map && Number.isFinite(lat) && Number.isFinite(lon)) { + const pt = map.project([lon, lat]); + if (pt && pt.x >= 20 && pt.x <= w - 20 && pt.y >= 20 && pt.y <= h - 20) { + screen = { x: pt.x, y: pt.y }; + } + } + const payload = { ...item, screen }; + onSelectFeature?.(payload); + return payload; + } + } + return null; + }, + getDiagnostics() { + return { + initialized: Boolean(map), + styleReady, + visible, + view: this.getView(), + hoveredGroupKey, + hoveredCodes: [...hoveredCodes], + featureCounts: { + interactive: interactiveLookup.size, + }, + admin1Opacity: map?.getLayer("boundary-admin1") + ? map.getPaintProperty("boundary-admin1", "line-opacity") + : null, + claimOpacity: map?.getLayer("claim-line") + ? map.getPaintProperty("claim-line", "line-opacity") + : null, + hoverClaimVisibility: map?.getLayer("hover-claim") + ? map.getLayoutProperty("hover-claim", "visibility") + : null, + }; + }, + destroy() { + visible = false; + map?.remove?.(); + map = null; + styleReady = false; + initPromise = null; + labelRoot?.remove(); + labelRoot = null; + labelSlots = []; + interactiveLookup.clear(); + }, + }; +} diff --git a/frontend/public/earth/js/map-view-controller.js b/frontend/public/earth/js/map-view-controller.js new file mode 100644 index 00000000..c71db907 --- /dev/null +++ b/frontend/public/earth/js/map-view-controller.js @@ -0,0 +1,200 @@ +/** + * Coordinates 3D Three.js globe <-> 2D MapLibre GL flat map view switching, + * monotonic camera coordinate + zoom conversion, 500% zoom pill prompting, + * and shared toolbar / zoom control synchronization. + */ + +export const MIN_3D_ZOOM_RATIO = 1.0; +export const MAX_3D_ZOOM_RATIO = 5.0; +export const DEFAULT_2D_MIN_ZOOM = 1.8; +export const DEFAULT_2D_MAX_ZOOM = 12.0; +export const ZOOM_2D_PILL_THRESHOLD = 4.85; + +const MAP_ZOOM_BASE = 2.0; +const MAP_ZOOM_LOG_SCALE = 2.35; + +export function clampLatForMercator(lat) { + const num = Number(lat); + if (!Number.isFinite(num)) return 0; + return Math.max(-82, Math.min(82, num)); +} + +export function normalizeLongitude(lon) { + const num = Number(lon); + if (!Number.isFinite(num)) return 0; + if (num >= -180 && num <= 180) { + return Object.is(num, -0) ? 0 : num; + } + let wrapped = (((num + 180) % 360) + 360) % 360 - 180; + wrapped = Number(wrapped.toFixed(6)); + if (Object.is(wrapped, -0)) wrapped = 0; + return wrapped; +} + +export function globeZoomRatioToMap2dZoom(zoomRatio) { + const clamped = Math.max(MIN_3D_ZOOM_RATIO, Math.min(MAX_3D_ZOOM_RATIO, Number(zoomRatio) || 1)); + const raw = MAP_ZOOM_BASE + Math.log2(clamped) * MAP_ZOOM_LOG_SCALE; + return Math.max(DEFAULT_2D_MIN_ZOOM, Math.min(DEFAULT_2D_MAX_ZOOM, Number(raw.toFixed(3)))); +} + +export function map2dZoomToGlobeZoomRatio(mapZoom) { + const z = Number(mapZoom); + if (!Number.isFinite(z)) return MIN_3D_ZOOM_RATIO; + const raw = Math.pow(2, (z - MAP_ZOOM_BASE) / MAP_ZOOM_LOG_SCALE); + return Math.max(MIN_3D_ZOOM_RATIO, Math.min(MAX_3D_ZOOM_RATIO, Number(raw.toFixed(3)))); +} + +export function globeToMap2d({ lat = 0, lon = 0, zoomRatio = 1 } = {}) { + return { + lat: clampLatForMercator(lat), + lon: normalizeLongitude(lon), + zoom: globeZoomRatioToMap2dZoom(zoomRatio), + }; +} + +export function map2dToGlobe({ lat = 0, lon = 0, zoom = MAP_ZOOM_BASE } = {}) { + return { + lat: Math.max(-90, Math.min(90, Number(lat) || 0)), + lon: normalizeLongitude(lon), + zoomRatio: map2dZoomToGlobeZoomRatio(zoom), + }; +} + +export function shouldShow2dZoomPill({ mode = "3d", zoomRatio = 1, dismissed = false } = {}) { + return mode === "3d" && !dismissed && Number(zoomRatio) >= ZOOM_2D_PILL_THRESHOLD; +} + +export function formatZoomDisplayForMode({ mode = "3d", zoomRatio = 1, mapZoom = MAP_ZOOM_BASE } = {}) { + if (mode === "2d") { + return `Z${Number(mapZoom).toFixed(1)}`; + } + return `${Math.round((Number(zoomRatio) || 1) * 100)}%`; +} + +export function createMapViewController({ + map2d, + getGlobeView, + applyGlobeView, + setGlobePaused, + onModeChange, + onZoomDisplay, + onPillVisibilityChange, +} = {}) { + let mode = "3d"; + let pillDismissed = false; + let lastZoomRatio = 1; + let lastMapZoom = MAP_ZOOM_BASE; + let switchToken = 0; + + function emitPill(zoomRatio = lastZoomRatio) { + const visible = shouldShow2dZoomPill({ + mode, + zoomRatio, + dismissed: pillDismissed, + }); + onPillVisibilityChange?.(visible); + return visible; + } + + async function setMode(nextMode) { + const target = nextMode === "2d" ? "2d" : "3d"; + if (target === mode) return mode; + const token = ++switchToken; + + if (target === "2d") { + const globeView = getGlobeView?.() || { lat: 20, lon: 105, zoomRatio: 1.5 }; + const view2d = globeToMap2d(globeView); + lastMapZoom = view2d.zoom; + lastZoomRatio = Number(globeView.zoomRatio) || 1; + mode = "2d"; + setGlobePaused?.(true); + onModeChange?.("2d"); + emitPill(lastZoomRatio); + onZoomDisplay?.(formatZoomDisplayForMode({ mode: "2d", mapZoom: view2d.zoom })); + try { + await map2d?.show?.(view2d); + if (token !== switchToken || mode !== "2d") return mode; + const live = map2d?.getView?.(); + if (live) { + lastMapZoom = live.zoom; + onZoomDisplay?.(formatZoomDisplayForMode({ mode: "2d", mapZoom: live.zoom })); + } + } catch (err) { + if (token === switchToken) { + mode = "3d"; + setGlobePaused?.(false); + map2d?.hide?.(); + onModeChange?.("3d"); + onZoomDisplay?.(formatZoomDisplayForMode({ mode: "3d", zoomRatio: lastZoomRatio })); + emitPill(lastZoomRatio); + } + throw err; + } + return mode; + } + + const live2d = map2d?.getView?.() || { lat: 20, lon: 105, zoom: lastMapZoom }; + const globeTarget = map2dToGlobe(live2d); + lastZoomRatio = globeTarget.zoomRatio; + mode = "3d"; + map2d?.hide?.(); + applyGlobeView?.(globeTarget); + setGlobePaused?.(false); + onModeChange?.("3d"); + onZoomDisplay?.(formatZoomDisplayForMode({ mode: "3d", zoomRatio: globeTarget.zoomRatio })); + emitPill(globeTarget.zoomRatio); + return mode; + } + + function handle3dZoomChange(zoomRatio) { + lastZoomRatio = Number(zoomRatio) || 1; + if (lastZoomRatio < ZOOM_2D_PILL_THRESHOLD - 0.15) { + pillDismissed = false; + } + emitPill(lastZoomRatio); + } + + function handle2dViewChange(view) { + if (!view || mode !== "2d") return; + lastMapZoom = Number(view.zoom) || lastMapZoom; + onZoomDisplay?.(formatZoomDisplayForMode({ mode: "2d", mapZoom: lastMapZoom })); + } + + function dismissPill() { + pillDismissed = true; + emitPill(lastZoomRatio); + } + + return { + getMode: () => mode, + is2dActive: () => mode === "2d", + setMode, + toggleMode: () => setMode(mode === "2d" ? "3d" : "2d"), + handle3dZoomChange, + handle2dViewChange, + dismissPill, + isPillDismissed: () => pillDismissed, + zoom2dBy: (delta) => { + if (mode !== "2d") return false; + map2d?.zoomBy?.(delta); + return true; + }, + flyTo: (target) => { + if (mode !== "2d" || !target) return false; + const zoom = Number.isFinite(Number(target.zoom)) + ? Number(target.zoom) + : Math.max(4.5, lastMapZoom); + map2d?.setView?.({ + lat: clampLatForMercator(target.lat), + lon: normalizeLongitude(target.lon), + zoom, + }); + return true; + }, + reset2dView: () => { + if (mode !== "2d") return false; + map2d?.setView?.({ lat: 30, lon: 105, zoom: 2.6 }); + return true; + }, + }; +} diff --git a/frontend/public/earth/js/map-view-controller.test.js b/frontend/public/earth/js/map-view-controller.test.js new file mode 100644 index 00000000..288b8b69 --- /dev/null +++ b/frontend/public/earth/js/map-view-controller.test.js @@ -0,0 +1,107 @@ +import { expect, test } from "bun:test"; +import { + createMapViewController, + formatZoomDisplayForMode, + globeToMap2d, + map2dToGlobe, + shouldShow2dZoomPill, +} from "./map-view-controller.js"; + +test("globeToMap2d and map2dToGlobe round-trip coordinates monotonically within Mercator bounds", () => { + const z1 = globeToMap2d({ lat: 35, lon: 115, zoomRatio: 1.0 }); + const z3 = globeToMap2d({ lat: 35, lon: 115, zoomRatio: 3.0 }); + const z5 = globeToMap2d({ lat: 35, lon: 115, zoomRatio: 5.0 }); + expect(z1.zoom).toBeLessThan(z3.zoom); + expect(z3.zoom).toBeLessThan(z5.zoom); + expect(z5.lat).toBe(35); + expect(z5.lon).toBe(115); + + const clampedPole = globeToMap2d({ lat: 89.5, lon: 190, zoomRatio: 2.0 }); + expect(clampedPole.lat).toBe(82); + expect(clampedPole.lon).toBe(-170); + + const back3d = map2dToGlobe({ lat: 35, lon: 115, zoom: z3.zoom }); + expect(Math.abs(back3d.zoomRatio - 3.0)).toBeLessThan(0.05); + expect(back3d.lat).toBe(35); + expect(back3d.lon).toBe(115); + + const deepZoomClamp = map2dToGlobe({ lat: 20, lon: 100, zoom: 11.5 }); + expect(deepZoomClamp.zoomRatio).toBe(5.0); +}); + +test("shouldShow2dZoomPill only prompts in 3D at near-max zoom when not dismissed", () => { + expect(shouldShow2dZoomPill({ mode: "3d", zoomRatio: 3.0, dismissed: false })).toBe(false); + expect(shouldShow2dZoomPill({ mode: "3d", zoomRatio: 4.9, dismissed: false })).toBe(true); + expect(shouldShow2dZoomPill({ mode: "3d", zoomRatio: 5.0, dismissed: true })).toBe(false); + expect(shouldShow2dZoomPill({ mode: "2d", zoomRatio: 5.0, dismissed: false })).toBe(false); + expect(formatZoomDisplayForMode({ mode: "2d", mapZoom: 7.46 })).toBe("Z7.5"); + expect(formatZoomDisplayForMode({ mode: "3d", zoomRatio: 2.6 })).toBe("260%"); +}); + +test("createMapViewController syncs view, pauses 3D in 2D, and recovers cleanly on show failure", async () => { + let globeView = { lat: 31.2, lon: 121.5, zoomRatio: 4.95 }; + let paused = false; + let pillVisible = false; + let lastZoomText = ""; + let current2dView = null; + let shouldFail = false; + + const map2d = { + async show(v) { + if (shouldFail) throw new Error("maplibre load failed"); + current2dView = { ...v }; + }, + hide() { + current2dView = null; + }, + getView() { + return current2dView ? { ...current2dView } : { lat: 0, lon: 0, zoom: 2 }; + }, + setView(v) { + current2dView = { ...v }; + }, + zoomBy(d) { + if (current2dView) current2dView.zoom += d; + }, + }; + + const ctrl = createMapViewController({ + map2d, + getGlobeView: () => globeView, + applyGlobeView: (next) => { + globeView = { ...next }; + }, + setGlobePaused: (val) => { + paused = val; + }, + onZoomDisplay: (txt) => { + lastZoomText = txt; + }, + onPillVisibilityChange: (v) => { + pillVisible = v; + }, + }); + + ctrl.handle3dZoomChange(4.95); + expect(pillVisible).toBe(true); + + await ctrl.toggleMode(); + expect(ctrl.getMode()).toBe("2d"); + expect(paused).toBe(true); + expect(pillVisible).toBe(false); + expect(lastZoomText.startsWith("Z")).toBe(true); + + // Move 2D camera slightly and zoom deeper, then toggle back to 3D + ctrl.flyTo({ lat: 39.9, lon: 116.4, zoom: 8.5 }); + await ctrl.toggleMode(); + expect(ctrl.getMode()).toBe("3d"); + expect(paused).toBe(false); + expect(globeView.lat).toBe(39.9); + expect(globeView.lon).toBe(116.4); + expect(globeView.zoomRatio).toBe(5.0); + + shouldFail = true; + await expect(ctrl.setMode("2d")).rejects.toThrow("maplibre load failed"); + expect(ctrl.getMode()).toBe("3d"); + expect(paused).toBe(false); +}); diff --git a/frontend/public/earth/js/maritime-context.js b/frontend/public/earth/js/maritime-context.js new file mode 100644 index 00000000..b0034fbf --- /dev/null +++ b/frontend/public/earth/js/maritime-context.js @@ -0,0 +1,97 @@ +// maritime-context.js - Strategic chokepoints (composited via influenceZones) and strategic ports + +const MARITIME_CONTEXT_API = "/api/v1/vessels/maritime-context"; + +let cachedContext = null; +let chokepointsActive = false; + +export async function fetchMaritimeContext({ force = false } = {}) { + if (cachedContext && !force) return cachedContext; + try { + const resp = await fetch(MARITIME_CONTEXT_API, { + cache: "no-store", + credentials: "same-origin", + }); + if (!resp.ok) return cachedContext; + cachedContext = await resp.json(); + return cachedContext; + } catch { + return cachedContext; + } +} + +export function buildChokepointInfluenceZones(chokepoints = []) { + const rings = (Array.isArray(chokepoints) ? chokepoints : []) + .map((cp) => cp?.polygon) + .filter((ring) => Array.isArray(ring) && ring.length >= 3); + if (!rings.length) return []; + // Batch all chokepoint polygons into a single low-alpha influence-zone mesh (1 draw call total). + return [ + { + id: "maritime-chokepoints-batch", + label: "海上咽喉要道", + color: "#22d3ee", + opacity: 0.16, + zIndex: -2, + shape: { + mode: "polygon", + coordinates: rings, + }, + edge: { + style: "sharp", + borderWidth: 1.4, + }, + animation: { + style: "none", + durationMs: 0, + }, + }, + ]; +} + +export function findNearestChokepoint(lat, lon, chokepoints = cachedContext?.chokepoints || []) { + const tLat = Number(lat); + const tLon = Number(lon); + if (!Number.isFinite(tLat) || !Number.isFinite(tLon) || !Array.isArray(chokepoints)) return null; + for (const cp of chokepoints) { + const ring = cp?.polygon; + if (!Array.isArray(ring) || ring.length < 3) continue; + let inside = false; + for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) { + const xi = Number(ring[i][0]); + const yi = Number(ring[i][1]); + const xj = Number(ring[j][0]); + const yj = Number(ring[j][1]); + const intersect = ((yi > tLat) !== (yj > tLat)) && + (tLon < ((xj - xi) * (tLat - yi)) / ((yj - yi) || 1e-12) + xi); + if (intersect) inside = !inside; + } + if (inside) return cp; + } + return null; +} + +export async function applyChokepointZonesOverlay(influenceZones, enabled) { + chokepointsActive = Boolean(enabled); + if (!influenceZones) return false; + if (!chokepointsActive) { + influenceZones.clearScope?.("chokepoints"); + return false; + } + const ctx = await fetchMaritimeContext(); + const zones = buildChokepointInfluenceZones(ctx?.chokepoints || []); + if (!zones.length) { + influenceZones.clearScope?.("chokepoints"); + return false; + } + await influenceZones.setZones(zones, { scope: "chokepoints" }); + return true; +} + +export function isChokepointOverlayActive() { + return chokepointsActive; +} + +export function getCachedStrategicPorts() { + return Array.isArray(cachedContext?.ports) ? cachedContext.ports : []; +} diff --git a/frontend/public/earth/js/news.js b/frontend/public/earth/js/news.js index f006b8e0..c1bfc08b 100644 --- a/frontend/public/earth/js/news.js +++ b/frontend/public/earth/js/news.js @@ -52,6 +52,13 @@ const NEWS_REALTIME_RECONNECT_MS = 5000; const NEWS_SUMMARY_LIMIT = 12; const NEWS_FULL_LIMIT = 50; const NEWS_SOURCE_FILTER_STORAGE_KEY = "planet.earth.newsSourceFilters.v1"; +const NEWS_THEATER_PRESETS = [ + { key: "global", label: "全球" }, + { key: "russo_ukrainian", label: "俄乌" }, + { key: "middle_east", label: "中东" }, + { key: "indo_pacific", label: "印太" }, + { key: "europe", label: "欧洲" }, +]; let initialized = false; let refreshPromise = null; @@ -73,6 +80,7 @@ let deferredPanelPayload = null; let breakingExpiryTimer = null; let tickerBreakingTimer = null; let newsRealtimeSocket = null; +let activeNewsTheaterFilter = "global"; let newsRealtimeReconnectTimer = null; let activeNewsCategoryFilters = null; let lastCategorySignature = ""; @@ -637,6 +645,10 @@ function syncFilterSummaries(nextPayload = payload) { document.querySelectorAll('[data-news-filter-summary="source"]').forEach((el) => { el.textContent = summarizeSelection(enabledSources.length, sources.length); }); + document.querySelectorAll('[data-news-filter-summary="theater"]').forEach((el) => { + const found = NEWS_THEATER_PRESETS.find((t) => t.key === activeNewsTheaterFilter) || NEWS_THEATER_PRESETS[0]; + el.textContent = translateText(found.label); + }); document.querySelectorAll('[data-news-filter-summary="limit"]').forEach((el) => { const total = Array.isArray(nextPayload?.items) ? nextPayload.items.length : 0; el.textContent = newsFullListMode @@ -695,10 +707,34 @@ function renderSourceFilterChips() { .join(""); } +function renderTheaterFilterChips() { + return NEWS_THEATER_PRESETS + .map((preset) => { + const active = activeNewsTheaterFilter === preset.key; + return ` + + `; + }) + .join(""); +} + function renderFilterPopover(kind) { - const title = translateText(kind === "source" ? "新闻来源" : "新闻类型"); - const hint = translateText(kind === "source" ? "按新闻来源筛选。" : "按新闻内容分类筛选。"); - const content = kind === "source" ? renderSourceFilterChips() : renderCategoryFilterChips(); + const title = translateText( + kind === "theater" ? "战区预设" : (kind === "source" ? "新闻来源" : "新闻类型"), + ); + const hint = translateText( + kind === "theater" + ? "按重点战区态势筛选。" + : (kind === "source" ? "按新闻来源筛选。" : "按新闻内容分类筛选。"), + ); + const content = kind === "theater" + ? renderTheaterFilterChips() + : (kind === "source" ? renderSourceFilterChips() : renderCategoryFilterChips()); activeFilterPopover = kind; document.querySelectorAll("[data-news-filter-popover]").forEach((popover) => { @@ -973,6 +1009,15 @@ function renderPayload(nextPayload, { forcePanelRender = false } = {}) { const statusLabel = getNewsEnrichmentStatusLabel(item); const breakingLabel = getNewsBreakingLabel(breakingLevel, breakingScope); const sourceDescriptor = getNewsSourceDescriptor(item, sourcesByName, sourcesById); + const tierVal = item.credibility_tier != null && Number(item.credibility_tier) >= 1 && Number(item.credibility_tier) <= 4 + ? Number(item.credibility_tier) + : null; + const tierText = tierVal !== null ? `T${tierVal}` : translateText("未分级"); + const tierClass = tierVal !== null ? ` news-credibility-badge--t${tierVal}` : " news-credibility-badge--unrated"; + const stateBadge = item.state_affiliated + ? `${escapeNewsHtml(translateText("国家背景"))}` + : ""; + const credibilityBadgeHtml = `${escapeNewsHtml(tierText)}${stateBadge}`; const summary = title && title !== leadText ? `
${escapeNewsHtml(title)}
` : ""; @@ -990,7 +1035,7 @@ function renderPayload(nextPayload, { forcePanelRender = false } = {}) { return `