fix(map): geofence delete, vessel snapshots, sentinel cache, news briefs

Geofences could be drawn but not removed. VesselAPI Hormuz dots vanished
on restart and DVR skipped between the 5 daily polls. Sentinel-1 re-hit
STAC on every pan and often painted a neighbouring swath. Executive
briefs truncated; ticker stayed empty unless something was critical.

- Layer-panel list + polygon popup DELETE /api/geofences/{id}
- Persist VesselAPI polls to vessels (UTC-day purge, DVR as-of, boot hydrate)
- Cache Sentinel-1 by 2° cell; pick covering scene; clip Leaflet tiles
- Retry truncated LLM JSON; ticker falls back to medium/low; 3-min HUD poll
This commit is contained in:
Sirius DevOps 2026-08-29 20:40:27 -04:00
commit c48788d4b6
No known key found for this signature in database
20 changed files with 669 additions and 57 deletions

View file

@ -17,6 +17,7 @@ from __future__ import annotations
import asyncio
import calendar
import json
import logging
import os
from datetime import date, datetime, timezone
@ -32,7 +33,7 @@ from config import (
VESSELAPI_MAX_CALLS_PER_DAY,
)
from database import async_session, engine, metadata
from live_layers import to_marker, upsert_vessel
from live_layers import parse_bbox, to_marker, upsert_vessel, vessel_last_known, vessel_lock
logger = logging.getLogger("osint.vesselapi")
@ -176,6 +177,49 @@ def transform_vesselapi_payload(payload: dict | None) -> list[dict]:
return out
def utc_day_start(now: datetime) -> datetime:
"""Floor ``now`` to 00:00:00 UTC."""
if now.tzinfo is None:
now = now.replace(tzinfo=timezone.utc)
now = now.astimezone(timezone.utc)
return now.replace(hour=0, minute=0, second=0, microsecond=0)
def pick_poll_at(poll_times: list[datetime], as_of: datetime) -> datetime | None:
"""Latest poll timestamp at or before ``as_of`` (DVR as-of)."""
if as_of.tzinfo is None:
as_of = as_of.replace(tzinfo=timezone.utc)
else:
as_of = as_of.astimezone(timezone.utc)
eligible: list[datetime] = []
for raw in poll_times:
ts = raw if raw.tzinfo else raw.replace(tzinfo=timezone.utc)
ts = ts.astimezone(timezone.utc)
if ts <= as_of:
eligible.append(ts)
return max(eligible) if eligible else None
def snapshot_as_of(rows: list[dict], as_of: datetime) -> list[dict]:
"""Keep only rows from the latest poll_at ≤ ``as_of``."""
chosen = pick_poll_at(
[r["poll_at"] for r in rows if r.get("poll_at") is not None],
as_of,
)
if chosen is None:
return []
out = []
for row in rows:
ts = row.get("poll_at")
if ts is None:
continue
if ts.tzinfo is None:
ts = ts.replace(tzinfo=timezone.utc)
if ts.astimezone(timezone.utc) == chosen:
out.append(row)
return out
# ── Durable daily quota (Postgres, survives restarts) ─────────────────────
# Mirrors keystore.api_keys: lazy CREATE TABLE IF NOT EXISTS, no alembic fork.
@ -261,6 +305,183 @@ class PgQuotaStore:
return (int(existing) if existing else 0) + 1
# ── Daily VesselAPI snapshots (DVR as-of + survive restarts) ──────────────
# Cleared at the UTC day boundary so the table holds today's 5 polls only.
_CREATE_VESSELS_SQL = text(
"""
CREATE TABLE IF NOT EXISTS vessels (
mmsi TEXT NOT NULL,
poll_at TIMESTAMPTZ NOT NULL,
lat DOUBLE PRECISION NOT NULL,
lon DOUBLE PRECISION NOT NULL,
heading DOUBLE PRECISION,
speed DOUBLE PRECISION,
label TEXT,
extra JSONB,
PRIMARY KEY (mmsi, poll_at)
)
"""
)
_CREATE_VESSELS_POLL_IDX = text(
"CREATE INDEX IF NOT EXISTS ix_vessels_poll_at ON vessels (poll_at DESC)"
)
_CREATE_VESSELS_BBOX_IDX = text(
"CREATE INDEX IF NOT EXISTS ix_vessels_bbox ON vessels (lon, lat)"
)
_vessels_lock = asyncio.Lock()
_vessels_ensured = False
async def ensure_vessels_table() -> None:
global _vessels_ensured
if _vessels_ensured:
return
async with _vessels_lock:
if _vessels_ensured:
return
async with engine.begin() as conn:
await conn.execute(_CREATE_VESSELS_SQL)
await conn.execute(_CREATE_VESSELS_POLL_IDX)
await conn.execute(_CREATE_VESSELS_BBOX_IDX)
_vessels_ensured = True
def _marker_from_vessel_row(r) -> dict:
extra = r.get("extra") or {}
if isinstance(extra, str):
try:
extra = json.loads(extra)
except (TypeError, ValueError):
extra = {}
if not isinstance(extra, dict):
extra = {}
extra.setdefault("src", "vesselapi")
poll_at = r.get("poll_at")
if poll_at is not None and hasattr(poll_at, "isoformat"):
extra["poll_at"] = poll_at.isoformat()
marker = to_marker(
str(r["id"]), r["lat"], r["lon"],
heading=r.get("heading"), speed=r.get("speed"),
label=r.get("label") or str(r["id"]),
extra=extra,
)
marker["seen_at"] = extra.get("poll_at") or datetime.now(timezone.utc).isoformat()
return marker
async def persist_vessel_snapshot(markers: list[dict], poll_at: datetime) -> None:
"""Write one VesselAPI poll into ``vessels`` (today's snapshots)."""
await ensure_vessels_table()
if not markers:
return
async with async_session() as session:
for m in markers:
vid = str(m.get("id") or "")
lat, lon = m.get("lat"), m.get("lon")
if not vid or lat is None or lon is None:
continue
extra = dict(m.get("extra") or {})
extra.setdefault("src", "vesselapi")
await session.execute(
text(
"""
INSERT INTO vessels
(mmsi, poll_at, lat, lon, heading, speed, label, extra)
VALUES
(:mmsi, :poll_at, :lat, :lon, :heading, :speed, :label,
CAST(:extra AS jsonb))
ON CONFLICT (mmsi, poll_at) DO UPDATE SET
lat = EXCLUDED.lat,
lon = EXCLUDED.lon,
heading = EXCLUDED.heading,
speed = EXCLUDED.speed,
label = EXCLUDED.label,
extra = EXCLUDED.extra
"""
),
{
"mmsi": vid,
"poll_at": poll_at,
"lat": float(lat),
"lon": float(lon),
"heading": m.get("heading"),
"speed": m.get("speed"),
"label": m.get("label") or vid,
"extra": json.dumps(extra),
},
)
await session.commit()
async def purge_old_vessels(before: datetime | None = None) -> None:
"""Drop snapshots from before the current UTC day (or ``before``)."""
await ensure_vessels_table()
cutoff = before or utc_day_start(datetime.now(timezone.utc))
async with async_session() as session:
await session.execute(
text("DELETE FROM vessels WHERE poll_at < :cutoff"),
{"cutoff": cutoff},
)
await session.commit()
async def fetch_vessels_as_of(
ts: datetime,
bbox: str | None = None,
limit: int = 2000,
) -> list[dict]:
"""Latest VesselAPI poll at or before ``ts`` (DVR as-of, not exact minute)."""
try:
await ensure_vessels_table()
async with async_session() as session:
poll = (await session.execute(
text("SELECT max(poll_at) FROM vessels WHERE poll_at <= :ts"),
{"ts": ts},
)).scalar()
if poll is None:
return []
sql = """
SELECT mmsi AS id, lat, lon, heading, speed, label, extra, poll_at
FROM vessels
WHERE poll_at = :poll
"""
params: dict = {"poll": poll, "limit": limit}
if bbox:
minlon, minlat, maxlon, maxlat = parse_bbox(bbox)
sql += (
" AND lon BETWEEN :minlon AND :maxlon"
" AND lat BETWEEN :minlat AND :maxlat"
)
params.update(
minlon=minlon, minlat=minlat, maxlon=maxlon, maxlat=maxlat,
)
sql += " LIMIT :limit"
rows = (await session.execute(text(sql), params)).mappings().all()
return [_marker_from_vessel_row(r) for r in rows]
except Exception:
logger.exception("VesselAPI snapshot fetch failed")
return []
async def hydrate_last_known() -> int:
"""Seed in-memory last-known from today's latest poll (app boot)."""
try:
rows = await fetch_vessels_as_of(datetime.now(timezone.utc))
except Exception:
logger.exception("VesselAPI hydrate failed")
return 0
if not rows:
return 0
async with vessel_lock:
for m in rows:
vid = str(m.get("id") or "")
if vid:
vessel_last_known[vid] = m
return len(rows)
# ── Budget / scheduling (pure, unit-testable) ─────────────────────────────
def days_left_in_month(now: datetime) -> int:
@ -406,6 +627,11 @@ async def poll_once(store, boxes: list[tuple[float, float, float, float]], key:
markers = transform_vesselapi_payload(data)
for m in markers:
await upsert_vessel(m)
try:
await persist_vessel_snapshot(markers, now)
await purge_old_vessels(utc_day_start(now))
except Exception: # noqa: BLE001 — live overlay must not die on persist
logger.exception("VesselAPI snapshot persist failed")
logger.info(
"VesselAPI poll OK: %d vessels (remaining=%s, calls_today=%d)",
len(markers), remaining, calls,