Skip to content

Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring

fix(unifi): record the manual import as a run in Scan History

Pouzor242a173ec526
diff --git a/backend/app/api/routes/unifi.py b/backend/app/api/routes/unifi.py
index 778a188..617bf80 100644
--- a/backend/app/api/routes/unifi.py
+++ b/backend/app/api/routes/unifi.py
@@ -75,6 +75,37 @@ async def test_connection_endpoint(
return UnifiTestConnectionResponse(connected=connected, message=message, counts=counts)
+async def _record_run(
+ db: AsyncSession,
+ target: str,
+ started_at: datetime,
+ *,
+ status: str,
+ devices_found: int = 0,
+ error: str | None = None,
+) -> str:
+ """Log a manual UniFi import in Scan History.
+
+ The manual import runs inline rather than as a background job, so unlike
+ every other importer there is no ``running`` row waiting to be finished —
+ the run is written once, already terminal. Without it the import left no
+ trace in the history at all.
+ """
+ run = ScanRun(
+ status=status,
+ kind="unifi",
+ ranges=[target],
+ devices_found=devices_found,
+ started_at=started_at,
+ finished_at=datetime.now(timezone.utc),
+ error=error,
+ )
+ db.add(run)
+ await db.commit()
+ await db.refresh(run)
+ return run.id
+
+
@router.post("/import-pending", response_model=UnifiImportResponse)
async def import_unifi_pending(
payload: UnifiConnectionRequest,
@@ -83,6 +114,8 @@ async def import_unifi_pending(
) -> UnifiImportResponse:
"""Fetch UniFi inventory and upsert into pending device inventory."""
username, password = _resolve_credentials(payload)
+ started_at = datetime.now(timezone.utc)
+ target = f"{payload.host}:{payload.port}"
try:
devices = await fetch_unifi_inventory(
host=payload.host,
@@ -96,12 +129,17 @@ async def import_unifi_pending(
active_clients=payload.modes.active_clients,
)
except ConnectionError as exc:
+ await _record_run(db, target, started_at, status="error", error=str(exc))
raise HTTPException(status_code=502, detail=str(exc)) from exc
except Exception as exc:
logger.exception("Unexpected error during UniFi import")
+ await _record_run(
+ db, target, started_at, status="error", error="Unexpected error during UniFi import"
+ )
raise HTTPException(status_code=500, detail="Unexpected error during UniFi import") from exc
result = await _persist_devices(db, devices)
+ await _record_run(db, target, started_at, status="done", devices_found=result.device_count)
return result
@@ -115,6 +153,8 @@ async def sync_unifi_now(
status_code=400,
detail="Cannot sync: no UniFi host/credentials configured on the server.",
)
+ started_at = datetime.now(timezone.utc)
+ target = f"{settings.unifi_effective_host}:{settings.unifi_effective_port}"
try:
devices = await fetch_unifi_inventory(
host=settings.unifi_effective_host,
@@ -128,9 +168,12 @@ async def sync_unifi_now(
active_clients=settings.unifi_import_active_clients,
)
except Exception as exc:
+ await _record_run(db, target, started_at, status="error", error=str(exc))
raise HTTPException(status_code=502, detail=str(exc)) from exc
- return await _persist_devices(db, devices)
+ result = await _persist_devices(db, devices)
+ await _record_run(db, target, started_at, status="done", devices_found=result.device_count)
+ return result
@router.get("/config", response_model=UnifiConfig)
diff --git a/backend/tests/test_unifi_router.py b/backend/tests/test_unifi_router.py
index 253106b..289b8ce 100644
--- a/backend/tests/test_unifi_router.py
+++ b/backend/tests/test_unifi_router.py
@@ -9,7 +9,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.api.routes.unifi import _find_existing, _persist_devices
from app.core.config import settings
-from app.db.models import InventoryDevice
+from app.db.models import InventoryDevice, ScanRun
@pytest.fixture(autouse=True)
@@ -485,3 +485,96 @@ async def test_a_merged_row_gains_the_controller_properties(
assert by_key == {
"VMID": "129", "Kind": "LXC", "Connection": "wired", "Switch port": "7",
}
+
+
+# --- scan history -----------------------------------------------------------
+# The manual import runs inline, so nothing else writes its run row. Without one
+# a finished import left no trace in Scan History at all.
+
+_IMPORT_BODY = {
+ "host": "unifi.local",
+ "port": 8443,
+ "username": "admin",
+ "password": "pw",
+ "modes": {"infrastructure": True, "known_clients": False, "active_clients": False},
+}
+
+_ONE_DEVICE = [
+ {
+ "ieee_address": "unifi-00:27:22:e0:00:09",
+ "mac": "00:27:22:e0:00:09",
+ "ip": "192.168.1.109",
+ "hostname": "USW Lite",
+ "label": "USW Lite",
+ "type": "switch",
+ "vendor": "Ubiquiti",
+ "properties": [],
+ "source": "unifi",
+ }
+]
+
+
+async def test_import_pending_records_a_scan_run(
+ client: AsyncClient, headers: dict, db_session: AsyncSession, monkeypatch
+) -> None:
+ async def _fake_fetch(**_kwargs):
+ return _ONE_DEVICE
+
+ monkeypatch.setattr("app.api.routes.unifi.fetch_unifi_inventory", _fake_fetch)
+
+ res = await client.post("/api/v1/unifi/import-pending", headers=headers, json=_IMPORT_BODY)
+ assert res.status_code == 200
+
+ runs = (await db_session.execute(select(ScanRun))).scalars().all()
+ assert len(runs) == 1
+ run = runs[0]
+ assert run.kind == "unifi"
+ assert run.status == "done"
+ assert run.devices_found == 1
+ assert run.ranges == ["unifi.local:8443"]
+ # Written already terminal — there is no background job to finish it later.
+ assert run.finished_at is not None
+ assert run.error is None
+
+
+async def test_a_failed_import_is_recorded_as_an_error_run(
+ client: AsyncClient, headers: dict, db_session: AsyncSession, monkeypatch
+) -> None:
+ async def _fake_fetch(**_kwargs):
+ raise ConnectionError("controller unreachable")
+
+ monkeypatch.setattr("app.api.routes.unifi.fetch_unifi_inventory", _fake_fetch)
+
+ res = await client.post("/api/v1/unifi/import-pending", headers=headers, json=_IMPORT_BODY)
+ assert res.status_code == 502
+
+ runs = (await db_session.execute(select(ScanRun))).scalars().all()
+ assert len(runs) == 1
+ assert runs[0].status == "error"
+ assert runs[0].error == "controller unreachable"
+ assert runs[0].devices_found == 0
+
+
+async def test_sync_now_records_a_scan_run(
+ client: AsyncClient, headers: dict, db_session: AsyncSession, monkeypatch
+) -> None:
+ monkeypatch.setattr(settings, "unifi_host", "10.0.0.5")
+ monkeypatch.setattr(settings, "unifi_username", "admin")
+ monkeypatch.setattr(settings, "unifi_password", "pw")
+
+ async def _fake_fetch(**_kwargs):
+ return _ONE_DEVICE
+
+ monkeypatch.setattr("app.api.routes.unifi.fetch_unifi_inventory", _fake_fetch)
+
+ res = await client.post("/api/v1/unifi/sync-now", headers=headers)
+ assert res.status_code == 200
+
+ runs = (await db_session.execute(select(ScanRun))).scalars().all()
+ assert len(runs) == 1
+ assert runs[0].kind == "unifi"
+ assert runs[0].status == "done"
+ assert runs[0].devices_found == 1