feat: AIS stream follows the map viewport
All checks were successful
build-and-deploy / build (push) Successful in 2m32s

The Vessels layer now retunes the server-side AISStream subscription to the
client viewport instead of a static AISSTREAM_BBOX. The frontend POSTs its
quantized viewport box to /api/vessels/subscribe on moveend; the ais_stream
worker coalesces and applies it at the service's 1 subscription/s cap, then
last-known positions for the new area arrive within a couple of seconds (the
frontend does one follow-up fetch after retuning). Bounds the in-memory
vessel store across regions. Key stays server-side.
This commit is contained in:
Sirius DevOps 2026-08-27 21:46:37 -04:00
commit 32320635dc
6 changed files with 185 additions and 6 deletions

View file

@ -14,6 +14,7 @@ import json
import logging
import os
import random
import time
from config import AISSTREAM_API_KEY, AISSTREAM_BBOX
from keystore import get_api_key
@ -29,6 +30,36 @@ FILTER_TYPES = [
"ShipStaticData",
]
# ── Viewport-following ─────────────────────────────────────────────────────
# The frontend POSTs its current viewport box to /api/vessels/subscribe; the
# worker retunes the AISStream subscription to it (throttled to 1/s, the
# service's subscription-update cap). ``None`` keeps the env AISSTREAM_BBOX
# default. Last writer wins; the key never reaches the browser.
_desired_boxes: list[list[list[float]]] | None = None
_bbox_guard = asyncio.Lock()
async def request_viewport_bbox(
minlon: float, minlat: float, maxlon: float, maxlat: float
) -> None:
"""Retune the live subscription to a viewport box (lon/lat input order)."""
global _desired_boxes
box = [[minlat, minlon], [maxlat, maxlon]] # AISStream wants [lat, lon] corners
async with _bbox_guard:
_desired_boxes = [box]
async def reset_viewport_bbox() -> None:
"""Fall back to the env AISSTREAM_BBOX default."""
global _desired_boxes
async with _bbox_guard:
_desired_boxes = None
async def _take_desired_boxes() -> list[list[list[float]]] | None:
async with _bbox_guard:
return _desired_boxes
def _parse_boxes(raw: str) -> list[list[list[float]]]:
"""Env format: minlat,minlon,maxlat,maxlon[; ...]. AIS wants [[lat,lon],[lat,lon]]."""
@ -65,7 +96,7 @@ async def run_ais_worker() -> None:
)
await asyncio.sleep(60)
continue
boxes = _parse_boxes(AISSTREAM_BBOX)
boxes = await _take_desired_boxes() or _parse_boxes(AISSTREAM_BBOX)
try:
async with websockets.connect(
WS_URL,
@ -82,7 +113,28 @@ async def run_ais_worker() -> None:
await ws.send(json.dumps(sub))
logger.info("AISStream subscribed (%d bbox(es))", len(boxes))
backoff = 2.0
async for raw in ws:
last_submit = time.monotonic()
while True:
# Follow the client viewport: coalesce to the latest request
# and honor AISStream's 1 subscription-update/s cap.
desired = await _take_desired_boxes()
if (
desired is not None
and desired != boxes
and time.monotonic() - last_submit >= 1.0
):
boxes = desired
sub["BoundingBoxes"] = boxes
await ws.send(json.dumps(sub))
last_submit = time.monotonic()
logger.info(
"AISStream re-subscribed to viewport (%d bbox)",
len(boxes),
)
try:
raw = await asyncio.wait_for(ws.recv(), timeout=0.25)
except asyncio.TimeoutError:
continue
if isinstance(raw, bytes):
raw = raw.decode("utf-8", errors="replace")
try: