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_heartbeats,
|
||||||
get_commands,
|
get_commands,
|
||||||
get_latest_heartbeats,
|
get_latest_heartbeats,
|
||||||
|
get_latest_heartbeat,
|
||||||
|
warm_latest_cache,
|
||||||
get_pending_command,
|
get_pending_command,
|
||||||
upsert_alert,
|
upsert_alert,
|
||||||
delete_alert,
|
delete_alert,
|
||||||
@@ -35,6 +37,7 @@ from database.pg_mqtt import (
|
|||||||
insert_report,
|
insert_report,
|
||||||
get_reports,
|
get_reports,
|
||||||
delete_device_logs,
|
delete_device_logs,
|
||||||
|
delete_device_logs_filtered,
|
||||||
delete_device_heartbeats,
|
delete_device_heartbeats,
|
||||||
delete_device_commands,
|
delete_device_commands,
|
||||||
delete_device_alert_events,
|
delete_device_alert_events,
|
||||||
@@ -65,6 +68,8 @@ __all__ = [
|
|||||||
"get_heartbeats",
|
"get_heartbeats",
|
||||||
"get_commands",
|
"get_commands",
|
||||||
"get_latest_heartbeats",
|
"get_latest_heartbeats",
|
||||||
|
"get_latest_heartbeat",
|
||||||
|
"warm_latest_cache",
|
||||||
"get_pending_command",
|
"get_pending_command",
|
||||||
"upsert_alert",
|
"upsert_alert",
|
||||||
"delete_alert",
|
"delete_alert",
|
||||||
@@ -88,6 +93,7 @@ __all__ = [
|
|||||||
"insert_report",
|
"insert_report",
|
||||||
"get_reports",
|
"get_reports",
|
||||||
"delete_device_logs",
|
"delete_device_logs",
|
||||||
|
"delete_device_logs_filtered",
|
||||||
"delete_device_heartbeats",
|
"delete_device_heartbeats",
|
||||||
"delete_device_commands",
|
"delete_device_commands",
|
||||||
"delete_device_alert_events",
|
"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 sqlalchemy import text
|
||||||
from config import settings
|
from config import settings
|
||||||
from database.postgres import AsyncSessionLocal
|
from database.postgres import AsyncSessionLocal
|
||||||
|
from database import latest_cache
|
||||||
|
|
||||||
logger = logging.getLogger("database.pg_mqtt")
|
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
|
# 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)
|
gateway, uptime_ms, uptime_display, rssi, free_heap, state, ok, received_at)
|
||||||
VALUES
|
VALUES
|
||||||
(:serial, :device_id, :fw, :ip, :gw, :uptime_ms, :uptime_display, :rssi, :free_heap, :state, :ok, now())
|
(:serial, :device_id, :fw, :ip, :gw, :uptime_ms, :uptime_display, :rssi, :free_heap, :state, :ok, now())
|
||||||
RETURNING id
|
RETURNING """ + _HEARTBEAT_COLS),
|
||||||
"""),
|
|
||||||
{
|
{
|
||||||
"serial": device_serial,
|
"serial": device_serial,
|
||||||
"device_id": device_id,
|
"device_id": device_id,
|
||||||
@@ -70,9 +84,10 @@ async def insert_heartbeat(device_serial: str, device_id: str,
|
|||||||
"ok": ok,
|
"ok": ok,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
row = result.fetchone()
|
row = result.mappings().fetchone()
|
||||||
await session.commit()
|
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,
|
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:
|
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:
|
async with AsyncSessionLocal() as session:
|
||||||
rows_result = await session.execute(
|
rows_result = await session.execute(
|
||||||
text("""
|
text(f"""
|
||||||
SELECT DISTINCT ON (device_serial)
|
SELECT DISTINCT ON (device_serial) {_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
|
|
||||||
FROM heartbeats
|
FROM heartbeats
|
||||||
ORDER BY device_serial, received_at DESC
|
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:
|
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,
|
async def insert_alert_event(device_serial: str, subsystem: str, state: str,
|
||||||
message: str | None = None):
|
message: str | None = None):
|
||||||
async with AsyncSessionLocal() as session:
|
async with AsyncSessionLocal() as session:
|
||||||
await session.execute(
|
result = await session.execute(
|
||||||
text("""
|
text("""
|
||||||
INSERT INTO device_alert_events (device_serial, subsystem, state, message, occurred_at)
|
INSERT INTO device_alert_events (device_serial, subsystem, state, message, occurred_at)
|
||||||
VALUES (:serial, :subsystem, :state, :message, now())
|
VALUES (:serial, :subsystem, :state, :message, now())
|
||||||
"""),
|
RETURNING """ + _ALERT_EVENT_COLS),
|
||||||
{"serial": device_serial, "subsystem": subsystem, "state": state, "message": message},
|
{"serial": device_serial, "subsystem": subsystem, "state": state, "message": message},
|
||||||
)
|
)
|
||||||
|
row = result.mappings().fetchone()
|
||||||
await session.commit()
|
await session.commit()
|
||||||
|
latest_cache.put("alert_event", _row_to_dict(row))
|
||||||
|
|
||||||
|
|
||||||
async def get_latest_alert_events() -> list:
|
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:
|
async with AsyncSessionLocal() as session:
|
||||||
result = await session.execute(
|
result = await session.execute(
|
||||||
text("""
|
text(f"""
|
||||||
SELECT DISTINCT ON (device_serial)
|
SELECT DISTINCT ON (device_serial) {_ALERT_EVENT_COLS}
|
||||||
id, device_serial, subsystem, state, message,
|
|
||||||
occurred_at AT TIME ZONE 'UTC' AS occurred_at
|
|
||||||
FROM device_alert_events
|
FROM device_alert_events
|
||||||
ORDER BY device_serial, occurred_at DESC
|
ORDER BY device_serial, occurred_at DESC
|
||||||
""")
|
""")
|
||||||
)
|
)
|
||||||
rows = result.mappings().all()
|
rows = [_row_to_dict(r) for r in result.mappings().all()]
|
||||||
|
latest_cache.seed("alert_event", rows)
|
||||||
return [_row_to_dict(r) for r in rows]
|
return latest_cache.snapshot("alert_event")
|
||||||
|
|
||||||
|
|
||||||
async def get_alert_events(device_serial: str, limit: int = 100,
|
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:
|
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:
|
async with AsyncSessionLocal() as session:
|
||||||
result = await session.execute(
|
result = await session.execute(
|
||||||
text("""
|
text("""
|
||||||
@@ -718,13 +760,13 @@ async def insert_ping_sample(device_serial: str, rtt_ms: int) -> int:
|
|||||||
text("""
|
text("""
|
||||||
INSERT INTO device_ping_samples (device_serial, rtt_ms, sampled_at)
|
INSERT INTO device_ping_samples (device_serial, rtt_ms, sampled_at)
|
||||||
VALUES (:serial, :rtt_ms, now())
|
VALUES (:serial, :rtt_ms, now())
|
||||||
RETURNING id
|
RETURNING """ + _PING_COLS),
|
||||||
"""),
|
|
||||||
{"serial": device_serial, "rtt_ms": rtt_ms},
|
{"serial": device_serial, "rtt_ms": rtt_ms},
|
||||||
)
|
)
|
||||||
row = result.fetchone()
|
row = result.mappings().fetchone()
|
||||||
await session.commit()
|
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,
|
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:
|
async def get_latest_ping_samples() -> list:
|
||||||
# Fleet-wide "last known" ping RTT for DeviceList — same DISTINCT ON
|
# Fleet-wide "last known" ping RTT for DeviceList — same DISTINCT ON
|
||||||
# pattern as get_latest_heartbeats(); devices with no RTC never appear.
|
# 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:
|
async with AsyncSessionLocal() as session:
|
||||||
rows_result = await session.execute(
|
rows_result = await session.execute(
|
||||||
text("""
|
text(f"""
|
||||||
SELECT DISTINCT ON (device_serial)
|
SELECT DISTINCT ON (device_serial) {_PING_COLS}
|
||||||
id, device_serial, rtt_ms,
|
|
||||||
sampled_at AT TIME ZONE 'UTC' AS sampled_at
|
|
||||||
FROM device_ping_samples
|
FROM device_ping_samples
|
||||||
ORDER BY device_serial, sampled_at DESC
|
ORDER BY device_serial, sampled_at DESC
|
||||||
""")
|
""")
|
||||||
)
|
)
|
||||||
rows = rows_result.mappings().all()
|
rows = [_row_to_dict(r) for r in rows_result.mappings().all()]
|
||||||
|
latest_cache.seed("ping", rows)
|
||||||
return [_row_to_dict(r) for r in 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_current_version, :ota_update_available, :ota_available_version,
|
||||||
:ota_last_check_uptime_ms, :ota_last_error,
|
:ota_last_check_uptime_ms, :ota_last_error,
|
||||||
:stack_high_water, :bell_strikes, :bell_loads, :cooling_active, now())
|
:stack_high_water, :bell_strikes, :bell_loads, :cooling_active, now())
|
||||||
RETURNING id
|
RETURNING """ + _DIAG_LATEST_COLS),
|
||||||
"""),
|
|
||||||
{
|
{
|
||||||
"serial": device_serial,
|
"serial": device_serial,
|
||||||
"cpu_temp_avg": cpu_temp_avg,
|
"cpu_temp_avg": cpu_temp_avg,
|
||||||
@@ -839,9 +881,10 @@ async def insert_diagnostics_report(
|
|||||||
"cooling_active": cooling_active,
|
"cooling_active": cooling_active,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
row = result.fetchone()
|
row = result.mappings().fetchone()
|
||||||
await session.commit()
|
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,
|
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:
|
async def get_latest_diagnostics_reports() -> list:
|
||||||
# Fleet-wide "last known" CPU temp for DeviceList — one DISTINCT ON query
|
# 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().
|
# 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:
|
async with AsyncSessionLocal() as session:
|
||||||
rows_result = await session.execute(
|
rows_result = await session.execute(
|
||||||
text("""
|
text(f"""
|
||||||
SELECT DISTINCT ON (device_serial)
|
SELECT DISTINCT ON (device_serial) {_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
|
|
||||||
FROM device_diagnostics_reports
|
FROM device_diagnostics_reports
|
||||||
ORDER BY device_serial, received_at DESC
|
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},
|
{"serial": device_serial},
|
||||||
)
|
)
|
||||||
await session.commit()
|
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:
|
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},
|
{"serial": device_serial},
|
||||||
)
|
)
|
||||||
await session.commit()
|
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:
|
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},
|
{"serial": device_serial},
|
||||||
)
|
)
|
||||||
await session.commit()
|
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:
|
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},
|
{"serial": device_serial},
|
||||||
)
|
)
|
||||||
await session.commit()
|
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},
|
{"cutoff": cutoff},
|
||||||
)
|
)
|
||||||
await session.commit()
|
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")
|
logger.info(f"Purged heartbeats, commands, ping samples, diagnostics reports, and device reports older than {days} days")
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+11
-11
@@ -27,7 +27,7 @@ CRM_COLLECTION = "crm_customers"
|
|||||||
|
|
||||||
|
|
||||||
@router.get("", response_model=DeviceListResponse)
|
@router.get("", response_model=DeviceListResponse)
|
||||||
async def list_devices(
|
def list_devices(
|
||||||
search: Optional[str] = Query(None),
|
search: Optional[str] = Query(None),
|
||||||
online: Optional[bool] = Query(None),
|
online: Optional[bool] = Query(None),
|
||||||
tier: Optional[str] = Query(None),
|
tier: Optional[str] = Query(None),
|
||||||
@@ -42,7 +42,7 @@ async def list_devices(
|
|||||||
|
|
||||||
|
|
||||||
@router.get("/{device_id}", response_model=DeviceInDB)
|
@router.get("/{device_id}", response_model=DeviceInDB)
|
||||||
async def get_device(
|
def get_device(
|
||||||
device_id: str,
|
device_id: str,
|
||||||
_user: TokenPayload = Depends(require_permission("devices", "view")),
|
_user: TokenPayload = Depends(require_permission("devices", "view")),
|
||||||
):
|
):
|
||||||
@@ -50,7 +50,7 @@ async def get_device(
|
|||||||
|
|
||||||
|
|
||||||
@router.get("/{device_id}/users", response_model=DeviceUsersResponse)
|
@router.get("/{device_id}/users", response_model=DeviceUsersResponse)
|
||||||
async def get_device_users(
|
def get_device_users(
|
||||||
device_id: str,
|
device_id: str,
|
||||||
_user: TokenPayload = Depends(require_permission("devices", "view")),
|
_user: TokenPayload = Depends(require_permission("devices", "view")),
|
||||||
):
|
):
|
||||||
@@ -119,7 +119,7 @@ async def get_device_alerts(
|
|||||||
# ─────────────────────────────────────────────────────────────────────────────
|
# ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@router.get("/{device_id}/notes")
|
@router.get("/{device_id}/notes")
|
||||||
async def list_device_notes(
|
def list_device_notes(
|
||||||
device_id: str,
|
device_id: str,
|
||||||
_user: TokenPayload = Depends(require_permission("devices", "view")),
|
_user: TokenPayload = Depends(require_permission("devices", "view")),
|
||||||
):
|
):
|
||||||
@@ -139,7 +139,7 @@ async def list_device_notes(
|
|||||||
|
|
||||||
|
|
||||||
@router.post("/{device_id}/notes", status_code=201)
|
@router.post("/{device_id}/notes", status_code=201)
|
||||||
async def create_device_note(
|
def create_device_note(
|
||||||
device_id: str,
|
device_id: str,
|
||||||
body: DeviceNoteCreate,
|
body: DeviceNoteCreate,
|
||||||
_user: TokenPayload = Depends(require_permission("devices", "edit")),
|
_user: TokenPayload = Depends(require_permission("devices", "edit")),
|
||||||
@@ -163,7 +163,7 @@ async def create_device_note(
|
|||||||
|
|
||||||
|
|
||||||
@router.put("/{device_id}/notes/{note_id}")
|
@router.put("/{device_id}/notes/{note_id}")
|
||||||
async def update_device_note(
|
def update_device_note(
|
||||||
device_id: str,
|
device_id: str,
|
||||||
note_id: str,
|
note_id: str,
|
||||||
body: DeviceNoteUpdate,
|
body: DeviceNoteUpdate,
|
||||||
@@ -187,7 +187,7 @@ async def update_device_note(
|
|||||||
|
|
||||||
|
|
||||||
@router.delete("/{device_id}/notes/{note_id}", status_code=204)
|
@router.delete("/{device_id}/notes/{note_id}", status_code=204)
|
||||||
async def delete_device_note(
|
def delete_device_note(
|
||||||
device_id: str,
|
device_id: str,
|
||||||
note_id: str,
|
note_id: str,
|
||||||
_user: TokenPayload = Depends(require_permission("devices", "edit")),
|
_user: TokenPayload = Depends(require_permission("devices", "edit")),
|
||||||
@@ -210,7 +210,7 @@ class TagsUpdate(BaseModel):
|
|||||||
|
|
||||||
|
|
||||||
@router.put("/{device_id}/tags", response_model=DeviceInDB)
|
@router.put("/{device_id}/tags", response_model=DeviceInDB)
|
||||||
async def update_device_tags(
|
def update_device_tags(
|
||||||
device_id: str,
|
device_id: str,
|
||||||
body: TagsUpdate,
|
body: TagsUpdate,
|
||||||
_user: TokenPayload = Depends(require_permission("devices", "edit")),
|
_user: TokenPayload = Depends(require_permission("devices", "edit")),
|
||||||
@@ -236,7 +236,7 @@ class AssignCustomerBody(BaseModel):
|
|||||||
|
|
||||||
|
|
||||||
@router.get("/{device_id}/customer-search")
|
@router.get("/{device_id}/customer-search")
|
||||||
async def search_customers_for_device(
|
def search_customers_for_device(
|
||||||
device_id: str,
|
device_id: str,
|
||||||
q: str = Query(""),
|
q: str = Query(""),
|
||||||
_user: TokenPayload = Depends(require_permission("devices", "view")),
|
_user: TokenPayload = Depends(require_permission("devices", "view")),
|
||||||
@@ -357,7 +357,7 @@ async def unassign_device_from_customer(
|
|||||||
# ─────────────────────────────────────────────────────────────────────────────
|
# ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@router.get("/{device_id}/customer")
|
@router.get("/{device_id}/customer")
|
||||||
async def get_device_customer(
|
def get_device_customer(
|
||||||
device_id: str,
|
device_id: str,
|
||||||
_user: TokenPayload = Depends(require_permission("devices", "view")),
|
_user: TokenPayload = Depends(require_permission("devices", "view")),
|
||||||
):
|
):
|
||||||
@@ -399,7 +399,7 @@ class UserSearchResult(BaseModel):
|
|||||||
|
|
||||||
|
|
||||||
@router.get("/{device_id}/user-search")
|
@router.get("/{device_id}/user-search")
|
||||||
async def search_users_for_device(
|
def search_users_for_device(
|
||||||
device_id: str,
|
device_id: str,
|
||||||
q: str = Query(""),
|
q: str = Query(""),
|
||||||
_user: TokenPayload = Depends(require_permission("devices", "view")),
|
_user: TokenPayload = Depends(require_permission("devices", "view")),
|
||||||
|
|||||||
@@ -116,6 +116,10 @@ async def startup():
|
|||||||
await sqlite_init_db()
|
await sqlite_init_db()
|
||||||
await melody_service.migrate_from_firestore()
|
await melody_service.migrate_from_firestore()
|
||||||
mqtt_manager.start(asyncio.get_event_loop())
|
mqtt_manager.start(asyncio.get_event_loop())
|
||||||
|
# Seed the in-memory latest-status cache in the background so the first
|
||||||
|
# device list / detail load after a restart doesn't pay for the slow
|
||||||
|
# fleet-wide DISTINCT ON scans (see database/latest_cache.py).
|
||||||
|
asyncio.create_task(db.warm_latest_cache())
|
||||||
asyncio.create_task(db.partition_manager_loop())
|
asyncio.create_task(db.partition_manager_loop())
|
||||||
asyncio.create_task(db.purge_loop())
|
asyncio.create_task(db.purge_loop())
|
||||||
asyncio.create_task(mqtt_manager.ping_loop())
|
asyncio.create_task(mqtt_manager.ping_loop())
|
||||||
|
|||||||
+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 typing import Optional, List
|
||||||
from auth.models import TokenPayload
|
from auth.models import TokenPayload
|
||||||
from auth.dependencies import require_permission
|
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.client import mqtt_manager
|
||||||
from mqtt import presence
|
from mqtt import presence
|
||||||
import database as db
|
import database as db
|
||||||
|
from database.postgres import get_pg_session
|
||||||
|
from shared.audit import log_action
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
router = APIRouter(prefix="/api/mqtt", tags=["mqtt"])
|
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)
|
@router.get("/status", response_model=MqttStatusResponse)
|
||||||
async def get_all_device_status(
|
async def get_all_device_status(
|
||||||
_user: TokenPayload = Depends(require_permission("mqtt", "view")),
|
_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()
|
heartbeats = await db.get_latest_heartbeats()
|
||||||
alert_events = await db.get_latest_alert_events()
|
alert_events = await db.get_latest_alert_events()
|
||||||
alert_by_serial = {a["device_serial"]: a for a in alert_events}
|
alert_by_serial = {a["device_serial"]: a for a in alert_events}
|
||||||
now = datetime.now(timezone.utc)
|
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(
|
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,
|
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)
|
@router.get("/latest-metrics", response_model=LatestMetricsResponse)
|
||||||
async def get_latest_metrics(
|
async def get_latest_metrics(
|
||||||
_user: TokenPayload = Depends(require_permission("mqtt", "view")),
|
_user: TokenPayload = Depends(require_permission("mqtt", "view")),
|
||||||
@@ -123,6 +139,31 @@ async def get_device_logs(
|
|||||||
return LogListResponse(logs=logs, total=total)
|
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)
|
@router.get("/heartbeats/{device_serial}", response_model=HeartbeatListResponse)
|
||||||
async def get_device_heartbeats(
|
async def get_device_heartbeats(
|
||||||
device_serial: str,
|
device_serial: str,
|
||||||
|
|||||||
Reference in New Issue
Block a user