perf(mqtt): serve device status from an in-memory latest-row cache
Device list and device detail took several seconds to show online status
because every /mqtt/status call ran SELECT DISTINCT ON (device_serial) over
the whole heartbeats + alert-event history (one heartbeat row per device
every 30s, kept for the full retention window). /mqtt/latest-metrics and
the 60s ping loop paid the same fleet-wide scans for ping samples and
diagnostics.
- database/latest_cache.py: newest heartbeat / alert event / ping sample /
diagnostics row per device, held in memory. Seeded once at startup
(warm_latest_cache) or lazily on first read; every insert writes through
via RETURNING, keeping whichever row is newer so writes that land while
the seed query runs are never lost. Per-device deletes and the retention
purge drop the matching entries so the cache never outlives the DB.
Single uvicorn process owns the MQTT client, so no cross-worker drift.
- GET /api/mqtt/status/{serial}: one device's status (cache, or a single
indexed lookup) so DeviceDetail no longer downloads the whole fleet.
- devices router: 11 GET/notes/tags handlers were `async def` but call the
synchronous Firestore client, blocking the event loop (MQTT ingest,
WebSocket, every other request) for each Firestore round trip. They are
plain `def` now so FastAPI runs them in its threadpool.
- DELETE /api/mqtt/logs/{serial}?source=&level=&until=: filtered delete of
console-stored device logs, for the Health tab's new "Delete logs".
Requires devices:edit and is audit-logged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+63
-22
@@ -1,4 +1,5 @@
|
||||
from fastapi import APIRouter, Depends, Query, WebSocket, WebSocketDisconnect
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, WebSocket, WebSocketDisconnect
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from typing import Optional, List
|
||||
from auth.models import TokenPayload
|
||||
from auth.dependencies import require_permission
|
||||
@@ -15,45 +16,60 @@ from mqtt.crash_groups import group_crashes
|
||||
from mqtt.client import mqtt_manager
|
||||
from mqtt import presence
|
||||
import database as db
|
||||
from database.postgres import get_pg_session
|
||||
from shared.audit import log_action
|
||||
from datetime import datetime, timezone
|
||||
|
||||
router = APIRouter(prefix="/api/mqtt", tags=["mqtt"])
|
||||
|
||||
|
||||
def _device_status(hb: dict, alert_event: dict | None, now: datetime) -> DeviceMqttStatus:
|
||||
try:
|
||||
received = datetime.fromisoformat(hb["received_at"])
|
||||
if received.tzinfo is None:
|
||||
received = received.replace(tzinfo=timezone.utc)
|
||||
seconds_ago = int((now - received).total_seconds())
|
||||
except (ValueError, TypeError):
|
||||
seconds_ago = 9999
|
||||
return DeviceMqttStatus(
|
||||
device_serial=hb["device_serial"],
|
||||
online=seconds_ago < 90 and not presence.is_marked_offline(hb["device_serial"]),
|
||||
last_heartbeat=HeartbeatEntry(**hb),
|
||||
seconds_since_heartbeat=seconds_ago,
|
||||
last_alert_event=AlertEventEntry(**alert_event) if alert_event else None,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/status", response_model=MqttStatusResponse)
|
||||
async def get_all_device_status(
|
||||
_user: TokenPayload = Depends(require_permission("mqtt", "view")),
|
||||
):
|
||||
# Both reads come from database/latest_cache.py (kept current by the MQTT
|
||||
# ingest), so this answers instantly instead of scanning history tables.
|
||||
heartbeats = await db.get_latest_heartbeats()
|
||||
alert_events = await db.get_latest_alert_events()
|
||||
alert_by_serial = {a["device_serial"]: a for a in alert_events}
|
||||
now = datetime.now(timezone.utc)
|
||||
devices = []
|
||||
for hb in heartbeats:
|
||||
received_str = hb["received_at"]
|
||||
try:
|
||||
received = datetime.fromisoformat(received_str)
|
||||
if received.tzinfo is None:
|
||||
received = received.replace(tzinfo=timezone.utc)
|
||||
seconds_ago = int((now - received).total_seconds())
|
||||
except (ValueError, TypeError):
|
||||
seconds_ago = 9999
|
||||
|
||||
alert_event = alert_by_serial.get(hb["device_serial"])
|
||||
|
||||
devices.append(DeviceMqttStatus(
|
||||
device_serial=hb["device_serial"],
|
||||
online=seconds_ago < 90 and not presence.is_marked_offline(hb["device_serial"]),
|
||||
last_heartbeat=HeartbeatEntry(**hb),
|
||||
seconds_since_heartbeat=seconds_ago,
|
||||
last_alert_event=AlertEventEntry(**alert_event) if alert_event else None,
|
||||
))
|
||||
return MqttStatusResponse(
|
||||
devices=devices,
|
||||
devices=[_device_status(hb, alert_by_serial.get(hb["device_serial"]), now) for hb in heartbeats],
|
||||
broker_connected=mqtt_manager.connected,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/status/{device_serial}", response_model=Optional[DeviceMqttStatus])
|
||||
async def get_device_status(
|
||||
device_serial: str,
|
||||
_user: TokenPayload = Depends(require_permission("mqtt", "view")),
|
||||
):
|
||||
"""One device's live status — what DeviceDetail needs, without shipping
|
||||
the whole fleet. null when the device has never sent a heartbeat."""
|
||||
hb = await db.get_latest_heartbeat(device_serial)
|
||||
if not hb:
|
||||
return None
|
||||
alert_event = await db.get_latest_alert_event(device_serial)
|
||||
return _device_status(hb, alert_event, datetime.now(timezone.utc))
|
||||
|
||||
|
||||
@router.get("/latest-metrics", response_model=LatestMetricsResponse)
|
||||
async def get_latest_metrics(
|
||||
_user: TokenPayload = Depends(require_permission("mqtt", "view")),
|
||||
@@ -123,6 +139,31 @@ async def get_device_logs(
|
||||
return LogListResponse(logs=logs, total=total)
|
||||
|
||||
|
||||
@router.delete("/logs/{device_serial}")
|
||||
async def delete_device_logs(
|
||||
device_serial: str,
|
||||
source: Optional[List[str]] = Query(None, description="Only these sources: log, info. Repeat param for several. Omit for all."),
|
||||
level: Optional[List[str]] = Query(None, description="Only these levels: INFO, WARN, ERROR. Repeat param for several. Omit for all."),
|
||||
until: Optional[datetime] = Query(None, description="Only rows at/before this ISO timestamp"),
|
||||
_user: TokenPayload = Depends(require_permission("devices", "edit")),
|
||||
pg: AsyncSession = Depends(get_pg_session),
|
||||
):
|
||||
"""Delete console-stored log rows for one device (Health tab → Logs →
|
||||
Delete Logs). Narrowed by source/level/time when given. Heartbeats,
|
||||
alert history and commands are cleared through the existing
|
||||
POST /api/devices/{id}/reset-stats instead."""
|
||||
bad_sources = [s for s in (source or []) if s not in ("log", "info")]
|
||||
bad_levels = [l for l in (level or []) if l not in ("INFO", "WARN", "ERROR")]
|
||||
if bad_sources or bad_levels:
|
||||
raise HTTPException(status_code=400, detail=f"Invalid filter: {bad_sources + bad_levels}")
|
||||
deleted = await db.delete_device_logs_filtered(device_serial, sources=source, levels=level, until=until)
|
||||
await log_action(pg, _user.sub, _user.name or _user.email, "DELETE", "device_logs",
|
||||
device_serial, device_serial,
|
||||
meta={"sources": source, "levels": level,
|
||||
"until": until.isoformat() if until else None, "deleted": deleted})
|
||||
return {"deleted": deleted}
|
||||
|
||||
|
||||
@router.get("/heartbeats/{device_serial}", response_model=HeartbeatListResponse)
|
||||
async def get_device_heartbeats(
|
||||
device_serial: str,
|
||||
|
||||
Reference in New Issue
Block a user