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:
2026-11-08 21:34:38 +02:00
co-authored by Claude Opus 5.5
parent 9deff308b6
commit da83f2a1cd
6 changed files with 308 additions and 80 deletions
+133 -47
View File
@@ -17,9 +17,24 @@ from datetime import date, datetime, timedelta, timezone
from sqlalchemy import text
from config import settings
from database.postgres import AsyncSessionLocal
from database import latest_cache
logger = logging.getLogger("database.pg_mqtt")
# Column lists shared by the fleet-wide "latest per device" reads and the
# RETURNING clause of the matching insert, so a freshly written row lands in
# latest_cache with exactly the shape the DISTINCT ON query would return.
_HEARTBEAT_COLS = """id, device_serial, device_id, firmware_version, ip_address,
gateway, uptime_ms, uptime_display, rssi, free_heap, state, ok,
received_at AT TIME ZONE 'UTC' AS received_at"""
_ALERT_EVENT_COLS = """id, device_serial, subsystem, state, message,
occurred_at AT TIME ZONE 'UTC' AS occurred_at"""
_PING_COLS = """id, device_serial, rtt_ms,
sampled_at AT TIME ZONE 'UTC' AS sampled_at"""
_DIAG_LATEST_COLS = """id, device_serial,
cpu_temp_avg, cpu_temp_min, cpu_temp_max, cpu_temp_samples,
received_at AT TIME ZONE 'UTC' AS received_at"""
# ---------------------------------------------------------------------------
# Insert operations
@@ -54,8 +69,7 @@ async def insert_heartbeat(device_serial: str, device_id: str,
gateway, uptime_ms, uptime_display, rssi, free_heap, state, ok, received_at)
VALUES
(:serial, :device_id, :fw, :ip, :gw, :uptime_ms, :uptime_display, :rssi, :free_heap, :state, :ok, now())
RETURNING id
"""),
RETURNING """ + _HEARTBEAT_COLS),
{
"serial": device_serial,
"device_id": device_id,
@@ -70,9 +84,10 @@ async def insert_heartbeat(device_serial: str, device_id: str,
"ok": ok,
},
)
row = result.fetchone()
row = result.mappings().fetchone()
await session.commit()
return row[0]
latest_cache.put("heartbeat", _row_to_dict(row))
return row["id"]
async def insert_command(device_serial: str, command_name: str,
@@ -259,20 +274,41 @@ async def get_commands(device_serial: str, limit: int = 100,
async def get_latest_heartbeats() -> list:
"""Newest heartbeat per device — served from latest_cache once seeded."""
cached = latest_cache.snapshot("heartbeat")
if cached is not None:
return cached
async with AsyncSessionLocal() as session:
rows_result = await session.execute(
text("""
SELECT DISTINCT ON (device_serial)
id, device_serial, device_id, firmware_version, ip_address,
gateway, uptime_ms, uptime_display, rssi, free_heap, state, ok,
received_at AT TIME ZONE 'UTC' AS received_at
text(f"""
SELECT DISTINCT ON (device_serial) {_HEARTBEAT_COLS}
FROM heartbeats
ORDER BY device_serial, received_at DESC
""")
)
rows = rows_result.mappings().all()
rows = [_row_to_dict(r) for r in rows_result.mappings().all()]
latest_cache.seed("heartbeat", rows)
return latest_cache.snapshot("heartbeat")
return [_row_to_dict(r) for r in rows]
async def get_latest_heartbeat(device_serial: str) -> dict | None:
"""Newest heartbeat for one device. Cache first; otherwise a single
indexed lookup (idx_heartbeats_serial_time), never the fleet-wide scan."""
if latest_cache.is_warm("heartbeat"):
return latest_cache.get("heartbeat", device_serial)
async with AsyncSessionLocal() as session:
result = await session.execute(
text(f"""
SELECT {_HEARTBEAT_COLS}
FROM heartbeats
WHERE device_serial = :serial
ORDER BY received_at DESC
LIMIT 1
"""),
{"serial": device_serial},
)
row = result.mappings().fetchone()
return _row_to_dict(row) if row else None
async def get_pending_command(device_serial: str) -> dict | None:
@@ -361,31 +397,35 @@ async def get_alerts(device_serial: str) -> list:
async def insert_alert_event(device_serial: str, subsystem: str, state: str,
message: str | None = None):
async with AsyncSessionLocal() as session:
await session.execute(
result = await session.execute(
text("""
INSERT INTO device_alert_events (device_serial, subsystem, state, message, occurred_at)
VALUES (:serial, :subsystem, :state, :message, now())
"""),
RETURNING """ + _ALERT_EVENT_COLS),
{"serial": device_serial, "subsystem": subsystem, "state": state, "message": message},
)
row = result.mappings().fetchone()
await session.commit()
latest_cache.put("alert_event", _row_to_dict(row))
async def get_latest_alert_events() -> list:
"""Most recent alert event per device, across all devices — one row each."""
"""Most recent alert event per device, across all devices — one row each.
Served from latest_cache once seeded."""
cached = latest_cache.snapshot("alert_event")
if cached is not None:
return cached
async with AsyncSessionLocal() as session:
result = await session.execute(
text("""
SELECT DISTINCT ON (device_serial)
id, device_serial, subsystem, state, message,
occurred_at AT TIME ZONE 'UTC' AS occurred_at
text(f"""
SELECT DISTINCT ON (device_serial) {_ALERT_EVENT_COLS}
FROM device_alert_events
ORDER BY device_serial, occurred_at DESC
""")
)
rows = result.mappings().all()
return [_row_to_dict(r) for r in rows]
rows = [_row_to_dict(r) for r in result.mappings().all()]
latest_cache.seed("alert_event", rows)
return latest_cache.snapshot("alert_event")
async def get_alert_events(device_serial: str, limit: int = 100,
@@ -415,6 +455,8 @@ async def get_alert_events(device_serial: str, limit: int = 100,
async def get_latest_alert_event(device_serial: str) -> dict | None:
if latest_cache.is_warm("alert_event"):
return latest_cache.get("alert_event", device_serial)
async with AsyncSessionLocal() as session:
result = await session.execute(
text("""
@@ -718,13 +760,13 @@ async def insert_ping_sample(device_serial: str, rtt_ms: int) -> int:
text("""
INSERT INTO device_ping_samples (device_serial, rtt_ms, sampled_at)
VALUES (:serial, :rtt_ms, now())
RETURNING id
"""),
RETURNING """ + _PING_COLS),
{"serial": device_serial, "rtt_ms": rtt_ms},
)
row = result.fetchone()
row = result.mappings().fetchone()
await session.commit()
return row[0]
latest_cache.put("ping", _row_to_dict(row))
return row["id"]
async def get_ping_samples(device_serial: str, limit: int = 200, offset: int = 0,
@@ -759,19 +801,20 @@ async def get_ping_samples(device_serial: str, limit: int = 200, offset: int = 0
async def get_latest_ping_samples() -> list:
# Fleet-wide "last known" ping RTT for DeviceList — same DISTINCT ON
# pattern as get_latest_heartbeats(); devices with no RTC never appear.
cached = latest_cache.snapshot("ping")
if cached is not None:
return cached
async with AsyncSessionLocal() as session:
rows_result = await session.execute(
text("""
SELECT DISTINCT ON (device_serial)
id, device_serial, rtt_ms,
sampled_at AT TIME ZONE 'UTC' AS sampled_at
text(f"""
SELECT DISTINCT ON (device_serial) {_PING_COLS}
FROM device_ping_samples
ORDER BY device_serial, sampled_at DESC
""")
)
rows = rows_result.mappings().all()
return [_row_to_dict(r) for r in rows]
rows = [_row_to_dict(r) for r in rows_result.mappings().all()]
latest_cache.seed("ping", rows)
return latest_cache.snapshot("ping")
# ---------------------------------------------------------------------------
@@ -817,8 +860,7 @@ async def insert_diagnostics_report(
:ota_current_version, :ota_update_available, :ota_available_version,
:ota_last_check_uptime_ms, :ota_last_error,
:stack_high_water, :bell_strikes, :bell_loads, :cooling_active, now())
RETURNING id
"""),
RETURNING """ + _DIAG_LATEST_COLS),
{
"serial": device_serial,
"cpu_temp_avg": cpu_temp_avg,
@@ -839,9 +881,10 @@ async def insert_diagnostics_report(
"cooling_active": cooling_active,
},
)
row = result.fetchone()
row = result.mappings().fetchone()
await session.commit()
return row[0]
latest_cache.put("diag", _row_to_dict(row))
return row["id"]
async def get_diagnostics_reports(device_serial: str, limit: int = 200, offset: int = 0,
@@ -904,20 +947,57 @@ async def get_latest_diagnostics_report(device_serial: str) -> dict | None:
async def get_latest_diagnostics_reports() -> list:
# Fleet-wide "last known" CPU temp for DeviceList — one DISTINCT ON query
# instead of N per-device round trips, same pattern as get_latest_heartbeats().
cached = latest_cache.snapshot("diag")
if cached is not None:
return cached
async with AsyncSessionLocal() as session:
rows_result = await session.execute(
text("""
SELECT DISTINCT ON (device_serial)
id, device_serial,
cpu_temp_avg, cpu_temp_min, cpu_temp_max, cpu_temp_samples,
received_at AT TIME ZONE 'UTC' AS received_at
text(f"""
SELECT DISTINCT ON (device_serial) {_DIAG_LATEST_COLS}
FROM device_diagnostics_reports
ORDER BY device_serial, received_at DESC
""")
)
rows = rows_result.mappings().all()
rows = [_row_to_dict(r) for r in rows_result.mappings().all()]
latest_cache.seed("diag", rows)
return latest_cache.snapshot("diag")
return [_row_to_dict(r) for r in rows]
async def warm_latest_cache() -> None:
"""Seed latest_cache at startup so the first /mqtt/status after a restart
is already instant. Each kind is independent — one failing (e.g. a table
missing on a fresh DB) doesn't stop the others; that kind just seeds
lazily on its first read instead."""
for loader in (get_latest_heartbeats, get_latest_alert_events,
get_latest_ping_samples, get_latest_diagnostics_reports):
try:
await loader()
except Exception as e:
logger.warning(f"latest_cache warm-up: {loader.__name__} failed: {e}")
async def delete_device_logs_filtered(device_serial: str,
sources: list[str] | None = None,
levels: list[str] | None = None,
until: datetime | None = None) -> int:
"""Delete one device's console-stored log rows, optionally narrowed to
some sources (log / info), some levels (INFO / WARN / ERROR) and rows at
or before `until`. No filters = every log row for the device."""
where = "device_serial = :serial"
params: dict = {"serial": device_serial}
if sources:
where += " AND source = ANY(:sources)"
params["sources"] = list(sources)
if levels:
where += " AND level = ANY(:levels)"
params["levels"] = list(levels)
if until is not None:
where += " AND received_at <= :until"
params["until"] = until
async with AsyncSessionLocal() as session:
result = await session.execute(text(f"DELETE FROM device_logs WHERE {where}"), params)
await session.commit()
return result.rowcount
# ---------------------------------------------------------------------------
@@ -947,7 +1027,8 @@ async def delete_device_heartbeats(device_serial: str) -> int:
{"serial": device_serial},
)
await session.commit()
return result.rowcount
latest_cache.drop_device("heartbeat", device_serial)
return result.rowcount
async def delete_device_commands(device_serial: str) -> int:
@@ -967,7 +1048,8 @@ async def delete_device_alert_events(device_serial: str) -> int:
{"serial": device_serial},
)
await session.commit()
return result.rowcount
latest_cache.drop_device("alert_event", device_serial)
return result.rowcount
async def delete_device_current_alerts(device_serial: str) -> int:
@@ -1000,7 +1082,8 @@ async def delete_device_ping_samples(device_serial: str) -> int:
{"serial": device_serial},
)
await session.commit()
return result.rowcount
latest_cache.drop_device("ping", device_serial)
return result.rowcount
async def delete_device_diagnostics_reports(device_serial: str) -> int:
@@ -1010,7 +1093,8 @@ async def delete_device_diagnostics_reports(device_serial: str) -> int:
{"serial": device_serial},
)
await session.commit()
return result.rowcount
latest_cache.drop_device("diag", device_serial)
return result.rowcount
# ---------------------------------------------------------------------------
@@ -1190,6 +1274,8 @@ async def purge_old_data(retention_days: int | None = None):
{"cutoff": cutoff},
)
await session.commit()
for kind in ("heartbeat", "ping", "diag"):
latest_cache.drop_older_than(kind, cutoff)
logger.info(f"Purged heartbeats, commands, ping samples, diagnostics reports, and device reports older than {days} days")