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:
@@ -12,6 +12,8 @@ from database.pg_mqtt import (
|
||||
get_heartbeats,
|
||||
get_commands,
|
||||
get_latest_heartbeats,
|
||||
get_latest_heartbeat,
|
||||
warm_latest_cache,
|
||||
get_pending_command,
|
||||
upsert_alert,
|
||||
delete_alert,
|
||||
@@ -35,6 +37,7 @@ from database.pg_mqtt import (
|
||||
insert_report,
|
||||
get_reports,
|
||||
delete_device_logs,
|
||||
delete_device_logs_filtered,
|
||||
delete_device_heartbeats,
|
||||
delete_device_commands,
|
||||
delete_device_alert_events,
|
||||
@@ -65,6 +68,8 @@ __all__ = [
|
||||
"get_heartbeats",
|
||||
"get_commands",
|
||||
"get_latest_heartbeats",
|
||||
"get_latest_heartbeat",
|
||||
"warm_latest_cache",
|
||||
"get_pending_command",
|
||||
"upsert_alert",
|
||||
"delete_alert",
|
||||
@@ -88,6 +93,7 @@ __all__ = [
|
||||
"insert_report",
|
||||
"get_reports",
|
||||
"delete_device_logs",
|
||||
"delete_device_logs_filtered",
|
||||
"delete_device_heartbeats",
|
||||
"delete_device_commands",
|
||||
"delete_device_alert_events",
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
"""In-memory "latest row per device" cache for the fleet-wide status reads.
|
||||
|
||||
Why this exists
|
||||
---------------
|
||||
/mqtt/status (device list + device detail), /mqtt/latest-metrics and the
|
||||
backend ping loop all need "the newest heartbeat / alert event / ping sample /
|
||||
diagnostics report for every device". In Postgres that is a
|
||||
`SELECT DISTINCT ON (device_serial) ... ORDER BY device_serial, ts DESC`,
|
||||
which has to walk the entire history index — heartbeats alone grow by one row
|
||||
per device every 30s and are kept for the full retention window, so each call
|
||||
took seconds and the console showed empty status columns until it finished.
|
||||
|
||||
The MQTT ingest path already sees every new row as it is written, so instead
|
||||
we keep the newest row per device in memory:
|
||||
|
||||
* seed() — one DISTINCT ON query per kind, run once at startup (and lazily
|
||||
on first read if startup warming hasn't finished yet).
|
||||
* put() — called by every insert, keeps whichever row is newer, so rows
|
||||
written while the seed query is still running are never lost.
|
||||
* drop_device() / drop_older_than() — mirror per-device deletes (Reset
|
||||
Stats, Delete Logs) and the retention purge so the cache never
|
||||
shows a row the database no longer has.
|
||||
|
||||
Single process only: the backend runs one uvicorn worker that also owns the
|
||||
MQTT client (see main.py startup), so there is no cross-process staleness.
|
||||
"""
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
# kind -> timestamp column used to decide which row is newest
|
||||
TS_FIELD = {
|
||||
"heartbeat": "received_at",
|
||||
"alert_event": "occurred_at",
|
||||
"ping": "sampled_at",
|
||||
"diag": "received_at",
|
||||
}
|
||||
|
||||
_rows: dict[str, dict[str, dict]] = {kind: {} for kind in TS_FIELD}
|
||||
_warm: dict[str, bool] = {kind: False for kind in TS_FIELD}
|
||||
|
||||
|
||||
def _ts(kind: str, row: dict) -> datetime:
|
||||
raw = row.get(TS_FIELD[kind])
|
||||
if isinstance(raw, datetime):
|
||||
return raw if raw.tzinfo else raw.replace(tzinfo=timezone.utc)
|
||||
try:
|
||||
parsed = datetime.fromisoformat(raw)
|
||||
return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)
|
||||
except (TypeError, ValueError):
|
||||
return datetime.min.replace(tzinfo=timezone.utc)
|
||||
|
||||
|
||||
def put(kind: str, row: dict) -> None:
|
||||
"""Record a row if it is the newest one seen for its device."""
|
||||
serial = row.get("device_serial")
|
||||
if not serial:
|
||||
return
|
||||
current = _rows[kind].get(serial)
|
||||
if current is None or _ts(kind, row) >= _ts(kind, current):
|
||||
_rows[kind][serial] = row
|
||||
|
||||
|
||||
def seed(kind: str, rows: list[dict]) -> None:
|
||||
for row in rows:
|
||||
put(kind, row)
|
||||
_warm[kind] = True
|
||||
|
||||
|
||||
def is_warm(kind: str) -> bool:
|
||||
return _warm[kind]
|
||||
|
||||
|
||||
def snapshot(kind: str) -> list[dict] | None:
|
||||
"""All cached rows for a kind, or None if the cache isn't seeded yet."""
|
||||
if not _warm[kind]:
|
||||
return None
|
||||
return list(_rows[kind].values())
|
||||
|
||||
|
||||
def get(kind: str, serial: str) -> dict | None:
|
||||
return _rows[kind].get(serial)
|
||||
|
||||
|
||||
def drop_device(kind: str, serial: str) -> None:
|
||||
_rows[kind].pop(serial, None)
|
||||
|
||||
|
||||
def drop_older_than(kind: str, cutoff: datetime) -> None:
|
||||
stale = [s for s, row in _rows[kind].items() if _ts(kind, row) < cutoff]
|
||||
for serial in stale:
|
||||
del _rows[kind][serial]
|
||||
+133
-47
@@ -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")
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user