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

@ -51,7 +51,9 @@ PC_SAS_TOKEN = "https://planetarycomputer.microsoft.com/api/sas/v1/token/sentine
# nginx vhost. Relative template — Leaflet resolves it against the page origin,
# so the browser never touches a raw loopback port or titiler.xyz.
TITILER_COG_TILES = f"{TITILER_PUBLIC_BASE}/cog/tiles/WebMercatorQuad/{{z}}/{{x}}/{{y}}"
SENTINEL1_TTL = 20 * 60 # 15–30 min quota-friendly window
SENTINEL1_TTL = 6 * 3600 # S-1 revisit is 6–12 days; cache the COG all afternoon
SENTINEL1_CELL = 2.0 # degrees — pan/zoom inside a cell reuses the same scene
SENTINEL1_STAC_LIMIT = 8
SENTINEL1_ATTRIBUTION = "Copernicus Sentinel-1 / Microsoft Planetary Computer"
# GPSJAM (John Wiseman / ADS-B Exchange): daily H3 hexes of aircraft nav
@ -1244,25 +1246,71 @@ def sentinel1_tile_url(signed_cog: str) -> str:
return f"{TITILER_COG_TILES}?{params}"
def feature_bbox(feat: dict) -> list[float] | None:
"""STAC Feature bbox as [minlon, minlat, maxlon, maxlat], or None."""
raw = feat.get("bbox") if isinstance(feat, dict) else None
if isinstance(raw, (list, tuple)) and len(raw) >= 4:
try:
return [float(raw[0]), float(raw[1]), float(raw[2]), float(raw[3])]
except (TypeError, ValueError):
pass
geom = (feat or {}).get("geometry") or {}
coords = geom.get("coordinates") if isinstance(geom, dict) else None
if not coords:
return None
lons: list[float] = []
lats: list[float] = []
def _walk(node: Any) -> None:
if isinstance(node, (list, tuple)) and node and isinstance(node[0], (int, float)):
lons.append(float(node[0]))
lats.append(float(node[1]))
elif isinstance(node, (list, tuple)):
for child in node:
_walk(child)
_walk(coords)
if not lons:
return None
return [min(lons), min(lats), max(lons), max(lats)]
def pick_sentinel_feature(features: list, lon: float, lat: float) -> dict | None:
"""Prefer the scene whose bbox covers the viewport center; else first."""
if not features:
return None
for feat in features:
bb = feature_bbox(feat)
if bb and bb[0] <= lon <= bb[2] and bb[1] <= lat <= bb[3]:
return feat
return features[0]
async def fetch_sentinel1(bbox: str) -> dict | None:
"""Most recent Sentinel-1 GRD COG for a viewport, signed and TiTiler-ready.
Returns the overlay tile-template dict, or ``None`` when no GRD imagery
covers the bbox in the last 7 days (caller maps to 404). Queries Planetary
Computer only when called; cached per quantized bbox + UTC day.
Computer only when called; cached per 2° cell + UTC day so pan/zoom inside
the same region reuses the COG instead of picking a neighbouring swath.
"""
minlon, minlat, maxlon, maxlat = parse_bbox(bbox)
qminlon, qminlat, qmaxlon, qmaxlat = quantize_bbox(
minlon, minlat, maxlon, maxlat, step=SENTINEL1_CELL,
)
day = datetime.now(timezone.utc).date().isoformat()
key = f"sentinel1:{day}:{bbox_cell_key(bbox)}"
key = f"sentinel1:{day}:{qminlon:.4f},{qminlat:.4f},{qmaxlon:.4f},{qmaxlat:.4f}"
clon = (qminlon + qmaxlon) / 2.0
clat = (qminlat + qmaxlat) / 2.0
async def _load() -> dict | None:
now = datetime.now(timezone.utc)
week_ago = now - timedelta(days=7)
payload = {
"collections": ["sentinel-1-grd"],
"bbox": [minlon, minlat, maxlon, maxlat],
"bbox": [qminlon, qminlat, qmaxlon, qmaxlat],
"datetime": f"{week_ago.isoformat()}/{now.isoformat()}",
"limit": 1,
"limit": SENTINEL1_STAC_LIMIT,
"sortby": [{"field": "datetime", "direction": "desc"}],
}
data = await _pc_call(_post_json(PC_STAC_SEARCH, json=payload))
@ -1270,7 +1318,9 @@ async def fetch_sentinel1(bbox: str) -> dict | None:
if not features:
return None
feat = features[0]
feat = pick_sentinel_feature(features, clon, clat)
if not feat:
return None
assets = feat.get("assets") or {}
chosen_href: str | None = None
polarization: str | None = None
@ -1299,6 +1349,7 @@ async def fetch_sentinel1(bbox: str) -> dict | None:
"datetime": props.get("datetime") or feat.get("datetime"),
"polarization": polarization,
"attribution": SENTINEL1_ATTRIBUTION,
"bbox": feature_bbox(feat),
}
return await _ttl_get(key, float(SENTINEL1_TTL), _load)

View file

@ -74,6 +74,11 @@ async def _lifespan(app: FastAPI):
await refresh_cache()
except Exception:
pass
try:
from vesselapi import hydrate_last_known
await hydrate_last_known()
except Exception:
pass
from config import AISSTREAM_IN_APP, VESSELAPI_IN_APP
ais_task = None
vesselapi_task = None
@ -1263,6 +1268,7 @@ async def list_news_summaries(
_FLAGGED = ("critical", "high")
_LESSER = ("medium", "low")
@app.get("/api/news/ticker", response_model=list[NewsTickerItemOut])
@ -1273,7 +1279,7 @@ async def list_news_ticker(
),
limit: int = Query(20, ge=1, le=50),
):
"""Flagged ticker rows (critical/high), newest first. No LLM required."""
"""Ticker rows: critical/high first; medium/low if nothing is flagged."""
async with async_session() as session:
stmt = (
select(news_items)
@ -1287,6 +1293,19 @@ async def list_news_ticker(
stmt = stmt.where(news_items.c.created_at >= since)
stmt = stmt.limit(limit)
rows = (await session.execute(stmt)).mappings().all()
if not rows:
stmt = (
select(news_items)
.where(
news_items.c.kind == "ticker",
news_items.c.importance.in_(_LESSER),
)
.order_by(news_items.c.created_at.desc())
)
if since:
stmt = stmt.where(news_items.c.created_at >= since)
stmt = stmt.limit(limit)
rows = (await session.execute(stmt)).mappings().all()
return [
NewsTickerItemOut(
id=r["id"], headline=r["headline"], importance=r["importance"],
@ -1530,7 +1549,17 @@ async def list_vessels(
from tracks import fetch_positions_at, parse_timestamp
ts = parse_timestamp(timestamp)
if ts is not None:
return overlay_json(await fetch_positions_at("vessel", ts, bbox, limit), 5)
from vesselapi import fetch_vessels_as_of
if src == "vesselapi":
return overlay_json(await fetch_vessels_as_of(ts, bbox, limit), 5)
ais = await fetch_positions_at("vessel", ts, bbox, limit)
if src == "aisstream":
return overlay_json(ais, 5)
va = await fetch_vessels_as_of(ts, bbox, limit)
by_id = {m["id"]: m for m in ais}
for m in va:
by_id[m["id"]] = m
return overlay_json(list(by_id.values())[:limit], 5)
return overlay_json(await fetch_vessels(bbox, limit, src=src), 5)
except ValueError as exc:
raise HTTPException(422, str(exc)) from exc

View file

@ -358,6 +358,11 @@
.lp-future .lp-name { cursor: not-allowed; }
.lp-error { color: var(--red); font-size: 0.66rem; }
.lp-note { font-size: 0.6rem; color: var(--muted); opacity: 0.85; line-height: 1.35; }
.gf-list { display: flex; flex-direction: column; gap: 0.22rem; max-height: 8rem; overflow-y: auto; }
.gf-item { display: flex; justify-content: space-between; align-items: center; gap: 0.4rem; font-size: 0.64rem; }
.gf-item span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--text); }
.gf-del { background: transparent; border: 1px solid var(--magenta); color: var(--magenta); font-family: 'Share Tech Mono', monospace; font-size: 0.58rem; letter-spacing: 0.08em; text-transform: uppercase; padding: 0.12rem 0.35rem; border-radius: 3px; cursor: pointer; }
.gf-del:hover { background: rgba(255,46,151,0.16); }
/* ── Camera / blip popup thumbnails ── */
.cam-pop { min-width: 210px; max-width: 260px; }
@ -583,6 +588,8 @@
.tick-item .b-tag { font-family: 'Share Tech Mono', monospace; font-size: 0.6rem; color: #1c0311; background: var(--magenta); border-radius: 2px; padding: 0.08rem 0.4rem; letter-spacing: 0.1em; }
.tick-item .b-tag.critical { background: var(--red); }
.tick-item .b-tag.high { background: var(--amber); }
.tick-item .b-tag.medium { background: var(--cyan); color: #041018; }
.tick-item .b-tag.low { background: var(--muted); color: #041018; }
.tick-item.brief:hover { color: var(--magenta); }
.tick-item.standby { color: var(--muted); opacity: 0.75; }
.tick-item.standby .price { color: var(--muted); }
@ -906,7 +913,8 @@
<div class="lp-row">
<button class="btn" id="gf-draw" type="button" onclick="toggleGeofenceDraw()">Draw geofence</button>
</div>
<div class="lp-note">No Leaflet.Draw — click vertices, double-click to close. Saved to POST /api/geofences.</div>
<div id="gf-list" class="gf-list"></div>
<div class="lp-note">Click vertices, double-click to close. Delete a saved fence from the list or its popup.</div>
</div>
<div class="lp-layer">
<div class="lp-row">
@ -1420,7 +1428,7 @@ function initMarketTicker() {
/* ═══════════════ NEWS FEED + TICKER ═══════════════ */
let newsInterval = null;
const NEWS_REFRESH_MS = 900000; // 15-min cycle
const NEWS_REFRESH_MS = 180000; // 3-min ticker/brief poll
let newsTickerBuilt = false;
function newsEsc(s) {
@ -1527,10 +1535,11 @@ function renderNewsTicker(articles, summaries, tickerItems) {
if (ticks.length) {
ticks.forEach(t => {
const imp = String(t.importance || '').toLowerCase();
const tag = imp === 'critical' ? 'CRITICAL' : 'HIGH';
const tag = imp === 'critical' ? 'CRITICAL' : imp === 'high' ? 'HIGH' : imp === 'medium' ? 'MED' : 'LOW';
const tagClass = (imp === 'critical' || imp === 'high' || imp === 'medium' || imp === 'low') ? imp : 'high';
const loc = (t.location_name || '').trim();
const inner =
`<span class="b-tag ${imp === 'critical' ? 'critical' : 'high'}">${tag}</span>` +
`<span class="b-tag ${tagClass}">${tag}</span>` +
`<span>${newsEsc((t.headline || '').trim())}</span>` +
(loc ? `<span class="dom">${newsEsc(loc)}</span>` : '') +
`<span class="tt">${newsTimeAgo(t.created_at)}</span><span class="sep">▸</span>`;
@ -1906,6 +1915,7 @@ let extraAttribs = new Set();
let radarLayer = null, radarOn = true, radarOpacity = 0.7, radarMeta = null, radarTimer = null;
let thermalLayer = null, thermalOn = false;
let sentinelLayer = null, sentinelOn = false, sentinelOpacity = 0.8;
let sentinelItemId = null, sentinelBounds = null;
let wxAlertsGroup = null, wxAlertsOn = true;
let perimGroup = null, perimOn = true;
let incidentsGroup = null, incidentsOn = false;
@ -3071,6 +3081,8 @@ async function toggleSentinel1() {
if (sentinelOn) await loadSentinel1();
else {
sentinelLayer = dropLayer(sentinelLayer);
sentinelItemId = null;
sentinelBounds = null;
const n = document.getElementById('lp-sentinel-count');
if (n) n.textContent = '7d';
}
@ -3080,8 +3092,15 @@ function setSentinelOpacity(v) {
document.getElementById('lp-sentinel-val').textContent = `${Math.round(v)}%`;
if (sentinelLayer) sentinelLayer.setOpacity(sentinelOpacity);
}
function sentinelStillCovers() {
if (!map || !sentinelBounds || sentinelBounds.length < 4) return false;
const c = map.getCenter();
return c.lng >= sentinelBounds[0] && c.lng <= sentinelBounds[2]
&& c.lat >= sentinelBounds[1] && c.lat <= sentinelBounds[3];
}
async function loadSentinel1() {
if (!map || !sentinelOn) return;
if (sentinelLayer && sentinelStillCovers()) return;
const req = ++overlayReq.sar;
const countEl = document.getElementById('lp-sentinel-count');
const hint = document.getElementById('map-hint');
@ -3093,6 +3112,8 @@ async function loadSentinel1() {
if (req !== overlayReq.sar) return;
if (r.status === 404 && body && body.error === 'no_imagery') {
sentinelLayer = dropLayer(sentinelLayer);
sentinelItemId = null;
sentinelBounds = null;
if (hint) hint.textContent = 'No Sentinel-1 imagery for this view in the last 7 days.';
if (countEl) countEl.textContent = 'none';
return;
@ -3109,13 +3130,31 @@ async function loadSentinel1() {
if (countEl) countEl.textContent = 'err';
return;
}
if (body.itemId && body.itemId === sentinelItemId && sentinelLayer) {
if (Array.isArray(body.bbox) && body.bbox.length >= 4) sentinelBounds = body.bbox;
sentinelLayer.setOpacity(sentinelOpacity);
if (countEl) countEl.textContent = String(body.polarization || 'SAR').toUpperCase();
return;
}
const attrib = body.attribution || '';
sentinelLayer = dropLayer(sentinelLayer);
sentinelLayer = L.tileLayer(body.tileUrl, {
const layerOpts = {
opacity: sentinelOpacity,
maxZoom: 18,
attribution: attrib,
}).addTo(map);
noWrap: true,
};
if (Array.isArray(body.bbox) && body.bbox.length >= 4) {
sentinelBounds = body.bbox;
layerOpts.bounds = L.latLngBounds(
[body.bbox[1], body.bbox[0]],
[body.bbox[3], body.bbox[2]],
);
} else {
sentinelBounds = null;
}
sentinelLayer = dropLayer(sentinelLayer);
sentinelLayer = L.tileLayer(body.tileUrl, layerOpts).addTo(map);
sentinelItemId = body.itemId || null;
if (countEl) countEl.textContent = String(body.polarization || 'SAR').toUpperCase();
if (hint) {
const when = body.datetime ? ` · ${body.datetime}` : '';
@ -3477,17 +3516,44 @@ async function onGfClose(e) {
toggleGeofenceDraw();
loadGeofences();
}
async function deleteGeofence(id) {
if (!id) return;
try {
const r = await fetch(`${API}/api/geofences/${encodeURIComponent(id)}`, { method: 'DELETE' });
if (!r.ok && r.status !== 204) throw new Error('delete failed');
} catch (err) { console.error('geofence delete failed', err); }
loadGeofences();
}
async function loadGeofences() {
if (!map) return;
try {
const r = await overlayFetch(`${API}/api/geofences`);
const rows = await r.json();
const list = Array.isArray(rows) ? rows : [];
const box = document.getElementById('gf-list');
if (box) {
box.innerHTML = list.map(f => {
const id = newsEsc(f.id || '');
const name = newsEsc(f.name || 'Fence');
return `<div class="gf-item"><span title="${name}">${name}</span>` +
`<button class="gf-del" type="button" onclick="deleteGeofence('${id}')">Delete</button></div>`;
}).join('');
}
if (gfSaved && map.hasLayer(gfSaved)) map.removeLayer(gfSaved);
const feats = (Array.isArray(rows) ? rows : []).map(f => ({
const feats = list.map(f => ({
type: 'Feature', properties: { name: f.name, id: f.id }, geometry: f.geojson,
}));
gfSaved = L.geoJSON({ type: 'FeatureCollection', features: feats }, {
style: { color: '#ff2e97', weight: 2, fillOpacity: 0.08 },
onEachFeature: (feat, layer) => {
const id = feat.properties && feat.properties.id;
const name = newsEsc((feat.properties && feat.properties.name) || 'Fence');
if (!id) return;
layer.bindPopup(
`<div class="gf-pop"><b>${name}</b><br>` +
`<button class="gf-del" type="button" onclick="deleteGeofence('${newsEsc(id)}')">Delete</button></div>`
);
},
}).addTo(map);
} catch (e) { if (!isAbort(e)) console.error('geofences load failed', e); }
}

View file

@ -186,15 +186,14 @@ async def track_range() -> dict:
async with async_session() as session:
row = (await session.execute(text(
"""
SELECT
LEAST(
(SELECT min(bucket) FROM vessel_tracks_1min),
(SELECT min(bucket) FROM aircraft_tracks_1min)
) AS tmin,
GREATEST(
(SELECT max(bucket) FROM vessel_tracks_1min),
(SELECT max(bucket) FROM aircraft_tracks_1min)
) AS tmax
SELECT min(t) AS tmin, max(t) AS tmax FROM (
SELECT min(bucket) AS t FROM vessel_tracks_1min
UNION ALL SELECT max(bucket) FROM vessel_tracks_1min
UNION ALL SELECT min(bucket) FROM aircraft_tracks_1min
UNION ALL SELECT max(bucket) FROM aircraft_tracks_1min
UNION ALL SELECT min(poll_at) FROM vessels
UNION ALL SELECT max(poll_at) FROM vessels
) s
"""
))).mappings().first()
if not row or row["tmin"] is None:

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,