Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring
TypeScript diagramhomelabhomelab-infrastructure-observabilitynetworkproxmox-veself-hostedzigbeezwavezwave-js
fix(inventory): stop a renamed service being hidden on every canvas
Pouzor37dc13807c02
diff --git a/backend/app/services/device_merge.py b/backend/app/services/device_merge.pyindex a86953b..9674822 100644--- a/backend/app/services/device_merge.py+++ b/backend/app/services/device_merge.py@@ -37,6 +37,7 @@ from app.services.inventory_sync import (ip_tokens,merge_properties,merge_services,+ normalize_view_key,view_of_device,)from app.services.node_dedupe import dedupe_nodes_by_device@@ -189,7 +190,14 @@ async def _show_merged_facts(db: AsyncSession, winner: InventoryDevice) -> int:# No view at all for this list — `apply_view` already shows# everything the row holds, merged facts included.continue- listed = {str(e.get("key")) for e in entries if isinstance(e, dict)}+ # Normalized: a view written before #469 addresses a service by a+ # key that carries its name, and comparing it raw against a freshly+ # seeded key would call an already-listed service missing.+ listed = {+ normalize_view_key(str(e.get("key")), kind)+ for e in entries+ if isinstance(e, dict)+ }missing = [entry for entry in seeds[kind] if entry["key"] not in listed]if missing:view[kind] = [*entries, *missing]diff --git a/backend/app/services/inventory_sync.py b/backend/app/services/inventory_sync.pyindex 5e84b6b..ef93433 100644--- a/backend/app/services/inventory_sync.py+++ b/backend/app/services/inventory_sync.py@@ -237,8 +237,44 @@ VIEW_LISTS = ("services", "properties")def _service_view_key(svc: Any) -> str:- port, protocol, name = _service_key(svc) if isinstance(svc, dict) else (None, None, repr(svc))- return f"{port}|{protocol}|{name}"+ """This service's address in a node's view.++ Same identity as the merge uses, so a rename does not move a service out+ from under the view that addresses it: before #469 the key carried the name,+ and renaming a service in the inventory modal made every canvas already+ drawing it lose track and redraw it hidden.++ A port-less service keeps the three-part form it always had, name included —+ it is the only thing that identifies one, and rendering ``None`` for the+ absent port is what the stored keys look like.+ """+ if not isinstance(svc, dict):+ return f"None|None|{repr(svc)}"+ key = _service_identity_key(svc)+ if len(key) == 2:+ return f"{key[0]}|{key[1]}"+ return f"{key[0]}|{key[1]}|{key[2]}"+++def normalize_view_key(key: str, kind: str) -> str:+ """A stored view key in today's form.++ Views written before #469 address a service by ``port|protocol|name``. The+ name in one is a snapshot of what the service was called when the view was+ written, so a renamed service cannot be found by re-deriving it — the key+ has to be narrowed instead. A key that names a port drops everything after+ it; one that does not is port-less and is already in its final form, as is+ every property key.++ Applied on read, so a view migrates the next time its node is saved rather+ than needing a migration of its own.+ """+ if kind != "services":+ return key+ parts = key.split("|", 2)+ if len(parts) != 3 or parts[0] in ("", "None"):+ return key+ return f"{parts[0]}|{parts[1]}"def _property_view_key(prop: Any) -> str:@@ -354,7 +390,7 @@ def apply_view(items: list[Any] | None, entries: Any, kind: str) -> list[Any]:for entry in entries:if not isinstance(entry, dict):continue- key = str(entry.get("key"))+ key = normalize_view_key(str(entry.get("key")), kind)item = by_key.get(key)if item is None or key in taken:continue # Deleted from the row since — the view catches up on write.diff --git a/backend/tests/test_device_merge.py b/backend/tests/test_device_merge.pyindex 85eb321..e6ddd9d 100644--- a/backend/tests/test_device_merge.py+++ b/backend/tests/test_device_merge.py@@ -163,7 +163,10 @@ async def test_merge_shows_the_new_facts_on_a_canvas_that_never_saw_them(db_sessservices = poor.display_view["services"]assert [e["visible"] for e in services] == [True, True]- assert {e["key"] for e in services} == {"5678|tcp|http", "22|tcp|ssh"}+ # The pre-existing entry is kept exactly as it was stored — a view is+ # rewritten by a save, not by a merge — so the key seeded alongside it is+ # in today's port-keyed form while that one stays in the older one.+ assert {e["key"] for e in services} == {"5678|tcp|http", "22|tcp"}# A property list this canvas had never seen picks up the survivor's.assert [e["key"] for e in poor.display_view["properties"]] == ["vmid"]diff --git a/backend/tests/test_inventory_sync.py b/backend/tests/test_inventory_sync.pyindex 19cceab..cec31dc 100644--- a/backend/tests/test_inventory_sync.py+++ b/backend/tests/test_inventory_sync.py@@ -1409,7 +1409,7 @@ class TestPerNodeView:assert await seed_node_views(db_session) == 1await db_session.commit()assert node.display_view == {- "services": [{"key": "22|tcp|ssh", "visible": True}],+ "services": [{"key": "22|tcp", "visible": True}],"properties": [],}# Idempotent: a second boot finds nothing without a view.@@ -1542,7 +1542,7 @@ class TestPerNodeView:assert await seed_node_views(db_session, drawn=lambda: drawn) == 1await db_session.commit()- assert node.display_view["services"] == [{"key": "22|tcp|ssh", "visible": True}]+ assert node.display_view["services"] == [{"key": "22|tcp", "visible": True}]@pytest.mark.asyncioasync def test_a_node_without_a_view_still_shows_everything(self, db_session):@@ -1554,3 +1554,92 @@ class TestPerNodeView:assert hydrated_node(node, device)["services"] == [{"port": 22, "protocol": "tcp", "service_name": "ssh"}]++ @pytest.mark.asyncio+ async def test_renaming_a_service_does_not_hide_it_on_canvases(+ self, client: AsyncClient, headers, db_session+ ):+ """Issue #469, the view half.++ The view addressed a service by a key carrying its name, so renaming one+ from the inventory modal left every canvas already drawing it addressing+ a key the row no longer held — and `apply_view` appends an unlisted fact+ hidden, so the service vanished from the canvas.+ """+ db_session.add(+ InventoryDevice(+ id="d-1",+ ip="10.0.0.5",+ services=[+ {"port": 22, "protocol": "tcp", "service_name": "ssh"},+ {"port": 3001, "protocol": "tcp", "service_name": "Uptime Kuma"},+ ],+ )+ )+ await db_session.commit()+ node = await self._node_on(client, headers, await _design(db_session))++ res = await client.patch(+ "/api/v1/scan/pending/d-1",+ json={"services": [+ {"port": 22, "protocol": "tcp", "service_name": "ssh"},+ {"port": 3001, "protocol": "tcp", "service_name": "Homepage"},+ ]},+ headers=headers,+ )+ assert res.status_code == 200++ drawn = (await client.get(f"/api/v1/nodes/{node['id']}", headers=headers)).json()+ assert [(s["service_name"], s.get("visible", True)) for s in drawn["services"]] == [+ ("ssh", True), ("Homepage", True),+ ]++ @pytest.mark.asyncio+ async def test_a_view_written_before_the_fix_still_addresses_its_service(+ self, client: AsyncClient, headers, db_session+ ):+ """Old keys are narrowed on read, so nothing needs migrating.++ The hidden one stays hidden even though the row has since renamed it —+ the point of the key being the port.+ """+ db_session.add(+ InventoryDevice(+ id="d-1",+ ip="10.0.0.5",+ services=[+ {"port": 22, "protocol": "tcp", "service_name": "ssh"},+ {"port": 3001, "protocol": "tcp", "service_name": "Homepage"},+ ],+ )+ )+ node = _node(await _design(db_session), device_id="d-1")+ node.display_view = {+ "services": [+ {"key": "22|tcp|ssh", "visible": True},+ {"key": "3001|tcp|uptime kuma", "visible": False},+ ],+ "properties": [],+ }+ db_session.add(node)+ await db_session.commit()++ drawn = (await client.get(f"/api/v1/nodes/{node.id}", headers=headers)).json()+ assert [(s["service_name"], s.get("visible", True)) for s in drawn["services"]] == [+ ("ssh", True), ("Homepage", False),+ ]++ @pytest.mark.asyncio+ async def test_a_port_less_service_keeps_its_name_in_the_view_key(self, db_session):+ """Its name is its identity, so the key keeps the form it always had."""+ device = InventoryDevice(+ id="d-1", services=[{"protocol": "tcp", "service_name": "Vaultwarden"}]+ )+ node = _node(await _design(db_session), device_id="d-1")+ node.display_view = {+ "services": [{"key": "None|tcp|vaultwarden", "visible": False}],+ "properties": [],+ }+ assert hydrated_node(node, device)["services"] == [+ {"protocol": "tcp", "service_name": "Vaultwarden", "visible": False}+ ]