Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring
TypeScript diagramhomelabhomelab-infrastructure-observabilitynetworkproxmox-veself-hostedzigbeezwavezwave-js
fix(inventory): keep two services that share a port
Pouzora3e8108b9385
diff --git a/backend/app/services/device_merge.py b/backend/app/services/device_merge.pyindex da1ce9c..2b02906 100644--- a/backend/app/services/device_merge.py+++ b/backend/app/services/device_merge.py@@ -38,6 +38,7 @@ from app.services.inventory_sync import (merge_properties,merge_services,normalize_view_key,+ view_key_port,view_of_device,)from app.services.node_dedupe import dedupe_nodes_by_device@@ -198,7 +199,19 @@ async def _show_merged_facts(db: AsyncSession, winner: InventoryDevice) -> int:for e in entriesif isinstance(e, dict)}- missing = [entry for entry in seeds[kind] if entry["key"] not in listed]+ if kind == "services":+ # A view written before #503 names a port and no site, so a+ # freshly seeded key never matches it as written. Both reduce to+ # the same port, and that is what says this canvas has already+ # spoken about the service — including to hide it.+ listed |= {view_key_port(key) for key in listed}+ missing = [+ entry+ for entry in seeds[kind]+ if view_key_port(entry["key"]) not in listed+ ]+ else:+ missing = [entry for entry in seeds[kind] if entry["key"] not in listed]if missing:view[kind] = [*entries, *missing]changed = Truediff --git a/backend/app/services/inventory_sync.py b/backend/app/services/inventory_sync.pyindex 9a2c14a..3f9dcc1 100644--- a/backend/app/services/inventory_sync.py+++ b/backend/app/services/inventory_sync.py@@ -199,27 +199,55 @@ def merge_properties(base: list[Any] | None, incoming: list[Any] | None) -> listreturn out+def _service_slot(svc: Any) -> tuple[str, str]:+ """What tells two services on the same port apart: the host and the path.++ Both are the user's own writing — the scanner emits neither, it only ever+ reports a port, a protocol and a guess at the name — so widening identity+ with them cannot resurrect issue #469: a rename still touches nothing the+ key reads. A node fronted by a reverse proxy serves several sites on 443,+ and each is its own service (issue #503).++ Normalized the way :func:`getServiceUrl` renders them, so two entries the+ UI would send to the same URL are one service: the host is a hostname and+ case-insensitive, and a path is anchored at ``/`` whether or not it was+ typed that way.+ """+ if not isinstance(svc, dict):+ return ("", "")+ host = str(svc.get("host") or "").strip().lower()+ path = str(svc.get("path") or "").strip()+ if path and path != "/" and not path.startswith("/"):+ path = f"/{path}"+ return (host, path)++def _service_identity_key(svc: Any) -> Any:"""What makes two service entries *the same service*, for merging.- A port is the identity: one port on one protocol is one service, whatever it- is called. The name is a label on it — the scanner guesses it from a banner- and the user corrects it — so keying identity on the name made a rename look- like a second service, and the next scan re-added the original under its own- guess (issue #469). :func:`_service_view_key` renders the same identity, so- the two never disagree about what one service is; keys already persisted in- node views are narrowed to it on read by :func:`normalize_view_key`.+ A port is the identity, qualified by the host and the path it is served on:+ one port on one protocol is one service *per site*, whatever it is called.+ The name is a label on it — the scanner guesses it from a banner and the+ user corrects it — so keying identity on the name made a rename look like a+ second service, and the next scan re-added the original under its own guess+ (issue #469). Keying on the port alone made the opposite mistake: two sites+ behind one reverse proxy collapsed into one entry and the second was lost on+ the next save (issue #503). :func:`_service_view_key` renders the same+ identity, so the two never disagree about what one service is; keys already+ persisted in node views are narrowed to it on read by+ :func:`normalize_view_key`.Only a service with no port falls back to the name, because nothing elsetells two of them apart — a hand-added entry that names a host rather than a- port, say. Those still key exactly as they did.+ port, say. Those keep the name and are qualified the same way."""if not isinstance(svc, dict):return repr(svc)+ host, path = _service_slot(svc)port = svc.get("port")if port in (None, ""):- return (None, svc.get("protocol"), (svc.get("service_name") or "").lower())- return (port, svc.get("protocol"))+ return (None, svc.get("protocol"), (svc.get("service_name") or "").lower(), host, path)+ return (port, svc.get("protocol"), host, path)# --- Per-node view of the device's list facts -----------------------------@@ -231,24 +259,73 @@ def _service_identity_key(svc: Any) -> Any:VIEW_LISTS = ("services", "properties")+def _esc(part: str) -> str:+ """``|`` separates a view key's parts, so a value carrying one is spelled out."""+ return part.replace("|", "%7C")++def _service_view_key(svc: Any) -> str:"""This service's address in a node's view.Same identity as the merge uses, so a rename does not move a service outfrom 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.+ drawing it lose track and redraw it hidden. It carries the host and the path+ for the opposite reason — without them two sites on one port share one+ address, and a view can only speak about one of them (issue #503).++ A port-less service keeps the name it always had, it being the only thing+ that tells two of them apart, and renders its absent port as ``None`` —+ which is what the stored keys look like.+ """+ if not isinstance(svc, dict):+ return f"None|None|{repr(svc)}"+ return "|".join(+ "None" if part is None else _esc(str(part)) for part in _service_identity_key(svc)+ )- 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.++def _legacy_service_key(svc: Any) -> str:+ """How a view written before #503 addressed this service: without the site.++ Such a key names a port and nothing else, so on a row that now holds two+ services on that port it cannot say which — :func:`apply_view` hands it the+ first one not already claimed, and the other is appended hidden as any+ service the row gained since would be."""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]}"+ port = svc.get("port")+ if port in (None, ""):+ return f"None|{svc.get('protocol')}|{(svc.get('service_name') or '').lower()}"+ return f"{port}|{svc.get('protocol')}"+++def view_key_port(key: str) -> str:+ """``key`` reduced to the port it names, the form a pre-#503 view stored.++ What a view addresses can move: editing a service's host or path in the+ Device Inventory rewrites its key, and the canvases drawing it still hold+ the old one. Both spell the same port, so that is what they are matched on+ once the exact key misses. A port-less service has no such form — its name+ is all it has — and keeps its key.+ """+ parts = key.split("|")+ if len(parts) < 2 or parts[0] in ("", "None"):+ return key+ return f"{parts[0]}|{parts[1]}"+++def _is_current_service_key(key: str) -> bool:+ """Whether ``key`` is already written the way :func:`_service_view_key` writes one.++ A current key ends with the path, which is rendered anchored at ``/`` or+ empty; a legacy key ends with a service name. That is what keeps a+ pre-#469 ``port|protocol|name`` whose name happens to carry a ``|`` from+ reading as a current key — today's are escaped, so they never carry one.+ """+ parts = key.split("|")+ return len(parts) in (4, 5) and (parts[-1] == "" or parts[-1].startswith("/"))def normalize_view_key(key: str, kind: str) -> str:@@ -266,10 +343,15 @@ def normalize_view_key(key: str, kind: str) -> str:the same absent port, so the empty one is spelled the new way rather thanleft to miss.+ What comes back is the narrowest form the key itself can justify: a view+ written before #503 names no host and no path, and nothing here can invent+ the one it meant. :func:`apply_view` finishes the job against the row, which+ is the only place that knows what services there are to choose between.+Applied on read, so a view migrates the next time its node is saved ratherthan needing a migration of its own."""- if kind != "services":+ if kind != "services" or _is_current_service_key(key):return keyparts = key.split("|", 2)if len(parts) != 3:@@ -373,6 +455,13 @@ def apply_view(items: list[Any] | None, entries: Any, kind: str) -> list[Any]:view does not list is appended hidden rather than dropped, so a service ascan added is one toggle away instead of invisible.+ Entries are claimed one item at a time rather than looked up by key, because+ a key no longer has to name exactly one item: a view written before #503+ addresses a service by its port alone, and the row may now hold two on that+ port. The first unclaimed match wins and the rest are appended hidden, which+ is what an upgrade looks like — the second site shows again with one toggle,+ and the view is rewritten in today's form on the next save.+A *non-empty* view that matches nothing the row still holds is treated ashaving no view at all. It means the row was replaced wholesale under thenode — every key gone, every key new — and hiding the lot would leave a node@@ -385,25 +474,38 @@ def apply_view(items: list[Any] | None, entries: Any, kind: str) -> list[Any]:if not isinstance(entries, list):return facts- by_key: dict[str, Any] = {}- for item in facts:- by_key.setdefault(key_of(item), item)+ # Every address an item answers to: its own key, and — for a service — the+ # port alone, which is both what a view written before #503 stored and what+ # is left to match on once the host or the path has been edited. Each pool+ # holds its items in the row's own order.+ pools: dict[str, list[int]] = {}+ for at, item in enumerate(facts):+ key = key_of(item)+ pools.setdefault(key, []).append(at)+ if kind == "services":+ legacy = _legacy_service_key(item)+ if legacy != key:+ pools.setdefault(legacy, []).append(at)out: list[Any] = []- taken: set[str] = set()+ claimed: set[int] = set()for entry in entries:if not isinstance(entry, dict):continuekey = normalize_view_key(str(entry.get("key")), kind)- item = by_key.get(key)- if item is None or key in taken:+ pos: int | None = next((p for p in pools.get(key, ()) if p not in claimed), None)+ if pos is None and kind == "services":+ pos = next(+ (p for p in pools.get(view_key_port(key), ()) if p not in claimed), None+ )+ if pos is None:continue # Deleted from the row since — the view catches up on write.- taken.add(key)- out.append(_stamped(item, bool(entry.get("visible", True))))- if entries and not taken:+ claimed.add(pos)+ out.append(_stamped(facts[pos], bool(entry.get("visible", True))))+ if entries and not claimed:return facts- for item in facts:- if key_of(item) not in taken:+ for at, item in enumerate(facts):+ if at not in claimed:out.append(_stamped(item, False))return out@@ -431,19 +533,47 @@ def _stamped(item: Any, visible: bool) -> Any:_CURATED_SERVICE_FIELDS = ("icon", "category", "service_name")+def _port_key(svc: Any) -> Any:+ """The port alone — all a scan knows about where a service is served.++ Identity carries the host and the path, which a fingerprint never reports,+ so this is what matches its finding against a service the user has already+ documented on that port. A row holding several of them hands over the first+ one not already spoken for, in its own order.+ """+ if not isinstance(svc, dict):+ return None+ port = svc.get("port")+ return None if port in (None, "") else (port, svc.get("protocol"))++def merge_services(base: list[Any] | None,incoming: list[Any] | None,*,discovered: bool = False,) -> list[Any]:- """Union two service lists on (port, protocol); incoming wins.+ """Union two service lists on (port, protocol, host, path); incoming wins.``discovered`` marks ``incoming`` as scanner output rather than a user edit:it still adds services and refreshes facts, but leaves an established iconand category alone. Either way a blank incoming value never clears one thatis already set — an absent field is silence, not a reset.+ A discovered entry whose key matches nothing falls back to the port: a scan+ reports a port and never the site served on it, so without that every+ "Scan network" would append a bare second entry under any service carrying a+ host override — issue #469 wearing a different hat. It takes the sites on+ that port in order and adds nothing once they are all spoken for.++ An *edit* gets no such fallback, because at this level it cannot be told+ from an addition: one entry on 443 arriving over one entry on 443 is either+ a host being corrected or a second site being added, and guessing "edit"+ would swallow the second site this issue is about (#503). Nothing is lost by+ choosing the addition — every path where the user edits a service replaces+ the list wholesale rather than merging into it, and the node-level matching+ in :func:`apply_view` is where an edit has to be recognized as one.+``base`` is collapsed on the same key as it is copied, so a row that alreadyholds the pre-#469 duplicates heals on the next merge instead of needing amigration. First entry wins: the user's renamed service was there before the@@ -451,19 +581,35 @@ def merge_services("""out: list[Any] = []index: dict[Any, int] = {}+ by_port: dict[Any, list[int]] = {}+ used: set[int] = set()++ def _record(pos: int, svc: Any, key: Any) -> None:+ index[key] = pos+ port_key = _port_key(svc)+ if port_key is not None:+ by_port.setdefault(port_key, []).append(pos)+for svc in base or []:key = _service_identity_key(svc)if key in index:continueout.append(dict(svc) if isinstance(svc, dict) else svc)- index[key] = len(out) - 1+ _record(len(out) - 1, svc, key)+for svc in incoming or []:key = _service_identity_key(svc)pos = index.get(key)+ if pos is None and discovered:+ pos = next((p for p in by_port.get(_port_key(svc), ()) if p not in used), None)if pos is None:out.append(dict(svc) if isinstance(svc, dict) else svc)- index[key] = len(out) - 1- elif isinstance(svc, dict) and isinstance(out[pos], dict):+ pos = len(out) - 1+ _record(pos, svc, key)+ used.add(pos)+ continue+ used.add(pos)+ if isinstance(svc, dict) and isinstance(out[pos], dict):merged = {**out[pos], **svc}for field_name in _CURATED_SERVICE_FIELDS:established = out[pos].get(field_name)@@ -472,6 +618,8 @@ def merge_services(out[pos] = mergedelse:out[pos] = svc+ # The entry may have moved to a new site, so it answers to a new key.+ index[_service_identity_key(out[pos])] = posreturn outdiff --git a/backend/tests/test_device_merge.py b/backend/tests/test_device_merge.pyindex dd6b986..02de54e 100644--- a/backend/tests/test_device_merge.py+++ b/backend/tests/test_device_merge.py@@ -164,9 +164,9 @@ 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]# 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"}+ # rewritten by a save, not by a merge — so the key seeded alongside it+ # names the site it is served on while that one stays in the older form.+ 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"]@@ -190,6 +190,32 @@ async def test_merge_keeps_a_deliberately_hidden_fact_hidden(db_session):assert node.display_view["services"] == [{"key": "22|tcp|ssh", "visible": False}]+async def test_merge_keeps_a_hidden_service_hidden_on_a_view_that_names_no_site(db_session):+ """A view written before #503 speaks of a port, the seed of a port and a site.++ Comparing the two as written would call the hidden service missing and+ append it again as shown, quietly undoing the canvas' choice on upgrade.+ """+ design = await _design(db_session)+ winner = await _device(+ db_session, id="w", ip="192.168.1.62",+ services=[+ {"service_name": "Pi-hole", "port": 443, "protocol": "tcp", "host": "pihole.lan"},+ ],+ )+ loser = await _device(db_session, id="l", ip="192.168.1.62", services=[])+ node = await _node(db_session, design, loser)+ node.display_view = {"services": [{"key": "443|tcp", "visible": False}], "properties": []}+ await db_session.flush()++ await merge_devices(db_session, winner, [loser])+ await db_session.flush()+ await db_session.refresh(node)++ assert node.display_view["services"] == [{"key": "443|tcp", "visible": False}]++@pytest.mark.asyncioasync def test_merge_collapses_two_nodes_that_now_draw_one_device(db_session):"""Both rows drawn on the *same* canvas: one node survives, the oldest."""diff --git a/backend/tests/test_inventory_sync.py b/backend/tests/test_inventory_sync.pyindex d7fc82d..28ce740 100644--- a/backend/tests/test_inventory_sync.py+++ b/backend/tests/test_inventory_sync.py@@ -157,6 +157,85 @@ class TestMergeRules:assert len(out) == 2+ def test_two_sites_on_one_port_are_two_services(self):+ """A reverse proxy serves several hosts on 443, and each is its own.++ The port was the whole of a service's identity, so the second collapsed+ into the first and was gone from the row on the next save (issue #503).+ """+ out = merge_services(+ [{"port": 443, "protocol": "tcp", "service_name": "Pi-hole",+ "host": "192.168.1.3", "path": "/admin"}],+ [{"port": 443, "protocol": "tcp", "service_name": "Pi-hole",+ "host": "pihole.domain.ch", "path": "/admin"}],+ )+ assert len(out) == 2+ assert [s["host"] for s in out] == ["192.168.1.3", "pihole.domain.ch"]++ def test_two_paths_on_one_host_are_two_services(self):+ """A path-routed proxy is told apart by the path alone."""+ out = merge_services(+ [{"port": 443, "protocol": "tcp", "service_name": "Photos",+ "host": "nas.lan", "path": "/photos"}],+ [{"port": 443, "protocol": "tcp", "service_name": "Files",+ "host": "nas.lan", "path": "/files"}],+ )+ assert len(out) == 2+ assert [s["service_name"] for s in out] == ["Photos", "Files"]++ def test_a_path_is_anchored_before_it_is_compared(self):+ """`admin` and `/admin` reach the same URL, so they are one service."""+ out = merge_services(+ [{"port": 443, "protocol": "tcp", "service_name": "Pi-hole", "path": "admin"}],+ [{"port": 443, "protocol": "tcp", "service_name": "Pi-hole", "path": "/admin"}],+ )+ assert len(out) == 1++ def test_a_host_is_compared_case_insensitively(self):+ """A hostname is a hostname however it was typed."""+ out = merge_services(+ [{"port": 443, "protocol": "tcp", "service_name": "Pi-hole", "host": "PiHole.LAN"}],+ [{"port": 443, "protocol": "tcp", "service_name": "Pi-hole", "host": "pihole.lan"}],+ )+ assert len(out) == 1++ def test_a_scan_never_duplicates_a_service_carrying_a_host_override(self):+ """fingerprint_ports knows a port; it never knows the site served on it."""+ out = merge_services(+ [{"port": 443, "protocol": "tcp", "service_name": "Pi-hole", "host": "pihole.lan"}],+ [{"port": 443, "protocol": "tcp", "service_name": "https", "icon": "Globe"}],+ discovered=True,+ )+ assert len(out) == 1+ assert out[0]["host"] == "pihole.lan"+ assert out[0]["service_name"] == "Pi-hole"+ assert out[0]["icon"] == "Globe"++ def test_a_scan_lands_on_one_site_and_never_adds_a_third(self):+ """Two sites on one port, one scan hit: it refreshes one of them."""+ out = merge_services(+ [+ {"port": 443, "protocol": "tcp", "service_name": "Pi-hole", "host": "a.lan"},+ {"port": 443, "protocol": "tcp", "service_name": "Gitea", "host": "b.lan"},+ ],+ [{"port": 443, "protocol": "tcp", "service_name": "https"}],+ discovered=True,+ )+ assert len(out) == 2+ assert [s["host"] for s in out] == ["a.lan", "b.lan"]++ def test_a_new_site_is_added_once_the_ones_on_the_port_are_taken(self):+ """The fallback hands over each entry once; what is left is a new service."""+ out = merge_services(+ [{"port": 443, "protocol": "tcp", "service_name": "Pi-hole", "host": "a.lan"}],+ [+ {"port": 443, "protocol": "tcp", "service_name": "Pi-hole", "host": "a.lan"},+ {"port": 443, "protocol": "tcp", "service_name": "Gitea", "host": "b.lan"},+ ],+ )+ assert len(out) == 2+ assert [s["host"] for s in out] == ["a.lan", "b.lan"]+def test_a_scan_never_repaints_an_icon_the_user_picked(self):"""Every "Scan network" used to overwrite a hand-picked brand icon."""base = [@@ -1410,7 +1489,7 @@ class TestPerNodeView:assert await seed_node_views(db_session) == 1await db_session.commit()assert node.display_view == {- "services": [{"key": "22|tcp", "visible": True}],+ "services": [{"key": "22|tcp||", "visible": True}],"properties": [],}# Idempotent: a second boot finds nothing without a view.@@ -1543,7 +1622,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", "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):@@ -1665,6 +1744,134 @@ class TestPerNodeView:]+class TestSeveralSitesOnOnePort:+ """Two services on one port are two services (issue #503).++ A node behind a reverse proxy serves several sites on 443. The port was the+ whole of a service's identity, so the second collapsed into the first on+ read, and the canvas then saved back the shortened list the node drew —+ deleting it from the inventory row for good.+ """++ _SITES = [+ {"port": 443, "protocol": "tcp", "service_name": "Pi-hole",+ "host": "192.168.1.3", "path": "/admin"},+ {"port": 443, "protocol": "tcp", "service_name": "Pi-hole",+ "host": "pihole.domain.ch", "path": "/admin"},+ ]++ async def _device_and_design(self, db_session) -> str:+ db_session.add(+ InventoryDevice(id="d-1", ip="192.168.1.3", services=[dict(s) for s in self._SITES])+ )+ await db_session.commit()+ return await _design(db_session)++ async def _node_on(self, client, headers, design_id: str) -> dict:+ res = await client.post(+ "/api/v1/nodes",+ json={"type": "nas", "label": "Pi-hole", "ip": "192.168.1.3",+ "design_id": design_id, "force": True},+ headers=headers,+ )+ assert res.status_code == 201+ return res.json()++ @pytest.mark.asyncio+ async def test_both_survive_the_canvas_save_that_used_to_delete_one(+ self, client: AsyncClient, headers, db_session+ ):+ """The reported scenario end to end: draw the device, save, look again."""+ design = await self._device_and_design(db_session)+ node = await self._node_on(client, headers, design)+ assert [s["host"] for s in node["services"]] == ["192.168.1.3", "pihole.domain.ch"]++ # A canvas save sends what the node draws, and the write-through takes+ # the list wholesale — a service missing from it is a service deleted.+ res = await client.patch(+ f"/api/v1/nodes/{node['id']}", json={"services": node["services"]}, headers=headers+ )+ assert res.status_code == 200+ assert [s["host"] for s in res.json()["services"]] == [+ "192.168.1.3", "pihole.domain.ch",+ ]++ device = await db_session.get(InventoryDevice, "d-1")+ await db_session.refresh(device)+ assert [s["host"] for s in device.services] == ["192.168.1.3", "pihole.domain.ch"]++ @pytest.mark.asyncio+ async def test_one_site_can_be_hidden_without_taking_the_other_with_it(+ self, client: AsyncClient, headers, db_session+ ):+ """The view addresses each site in its own right, not the port they share."""+ design = await self._device_and_design(db_session)+ node = await self._node_on(client, headers, design)++ hidden = [dict(self._SITES[0]), {**self._SITES[1], "visible": False}]+ res = await client.patch(+ f"/api/v1/nodes/{node['id']}", json={"services": hidden}, headers=headers+ )+ assert res.status_code == 200+ assert [(s["host"], s.get("visible", True)) for s in res.json()["services"]] == [+ ("192.168.1.3", True), ("pihole.domain.ch", False),+ ]++ again = (await client.get(f"/api/v1/nodes/{node['id']}", headers=headers)).json()+ assert [(s["host"], s.get("visible", True)) for s in again["services"]] == [+ ("192.168.1.3", True), ("pihole.domain.ch", False),+ ]++ @pytest.mark.asyncio+ async def test_a_view_written_before_the_fix_draws_one_and_brings_the_other_in_hidden(+ self, client: AsyncClient, headers, db_session+ ):+ """Upgrading must not hide a canvas' services, nor unhide what it hid.++ A stored view addresses both sites as ``443|tcp`` — it predates the+ site being part of a service's address, so it can only speak for one.+ The first is drawn as it was, and the second arrives the way any service+ the row gained since does: hidden, one toggle away.+ """+ design = await self._device_and_design(db_session)+ node = await self._node_on(client, headers, design)+ stored = await db_session.get(Node, node["id"])+ stored.display_view = {+ "services": [{"key": "443|tcp", "visible": True}],+ "properties": [],+ }+ await db_session.commit()++ drawn = (await client.get(f"/api/v1/nodes/{node['id']}", headers=headers)).json()+ assert [(s["host"], s.get("visible", True)) for s in drawn["services"]] == [+ ("192.168.1.3", True), ("pihole.domain.ch", False),+ ]++ @pytest.mark.asyncio+ async def test_editing_a_site_does_not_drop_it_from_the_canvas(+ self, client: AsyncClient, headers, db_session+ ):+ """The site is identity, so an edit rewrites the key a view holds.++ Without the fallback to the port the node would lose track of the entry+ and redraw it hidden — which is what #468 was, in a new field.+ """+ design = await self._device_and_design(db_session)+ node = await self._node_on(client, headers, design)++ device = await db_session.get(InventoryDevice, "d-1")+ device.services = [+ {**self._SITES[0], "host": "pihole.lan"},+ dict(self._SITES[1]),+ ]+ await db_session.commit()++ drawn = (await client.get(f"/api/v1/nodes/{node['id']}", headers=headers)).json()+ assert [(s["host"], s.get("visible", True)) for s in drawn["services"]] == [+ ("pihole.lan", True), ("pihole.domain.ch", True),+ ]++class TestNormalizeViewKey:"""Stored view keys, narrowed to the identity the row is addressed by."""@@ -1683,5 +1890,20 @@ class TestNormalizeViewKey:def test_a_name_carrying_a_pipe_survives_the_split(self):assert normalize_view_key("None|tcp|a|b", "services") == "None|tcp|a|b"+ def test_a_key_naming_a_site_is_left_alone(self):+ """Today's form: the port, the protocol, then the host and the path."""+ assert normalize_view_key("443|tcp|pihole.lan|/admin", "services") == (+ "443|tcp|pihole.lan|/admin"+ )++ def test_a_key_naming_no_site_is_left_alone(self):+ """The site is empty rather than absent — both segments are still there."""+ assert normalize_view_key("3001|tcp||", "services") == "3001|tcp||"++ def test_a_port_less_key_in_todays_form_keeps_its_name_and_its_site(self):+ assert normalize_view_key("None|tcp|vaultwarden|vault.lan|", "services") == (+ "None|tcp|vaultwarden|vault.lan|"+ )+def test_a_property_key_is_never_touched(self):assert normalize_view_key("rack", "properties") == "rack"diff --git a/frontend/src/utils/__tests__/deviceFacts.test.ts b/frontend/src/utils/__tests__/deviceFacts.test.tsindex 030cd6a..c178d4a 100644--- a/frontend/src/utils/__tests__/deviceFacts.test.ts+++ b/frontend/src/utils/__tests__/deviceFacts.test.ts@@ -101,6 +101,52 @@ describe('listArrangedForNode', () => {const guessed = { port: 8096, protocol: 'tcp' as const, service_name: 'TCP/8096' }const renamed = { ...guessed, service_name: 'Jellyfin' }+ const adminIp = {+ port: 443,+ protocol: 'tcp' as const,+ service_name: 'Pi-hole',+ host: '192.168.1.3',+ path: '/admin',+ }+ const adminDomain = { ...adminIp, host: 'pihole.domain.ch' }++ it('keeps two sites served on one port apart (#503)', () => {+ // A reverse proxy serves both on 443. Keying on the port alone collapsed+ // them, so the node drew one and the canvas saved that shortened list back+ // over the row — deleting the other for good.+ expect(listArrangedForNode([adminIp, adminDomain], [adminIp, adminDomain])).toEqual([+ adminIp,+ adminDomain,+ ])+ })++ it('hides one site without touching the other', () => {+ const arranged = listArrangedForNode(+ [{ ...adminIp, visible: false }, adminDomain],+ [adminIp, adminDomain],+ )+ expect(arranged).toEqual([{ ...adminIp, visible: false }, adminDomain])+ })++ it('follows an edited host rather than hiding the service', () => {+ // The site is part of a service's identity, so editing it in the Device+ // Inventory rewrites the key the node holds — #468 in a new field unless+ // the match falls back to the port.+ const moved = { ...adminIp, host: 'pihole.lan' }+ expect(listArrangedForNode([adminIp], [moved])).toEqual([moved])+ })++ it('brings a second site in hidden rather than mistaking it for an edit', () => {+ const arranged = listArrangedForNode([adminIp], [adminIp, adminDomain])+ expect(arranged).toEqual([adminIp, { ...adminDomain, visible: false }])+ })++ it('reads a path the same way the service URL does', () => {+ // `admin` and `/admin` reach the same URL, so they are one service.+ const typed = { ...adminIp, path: 'admin' }+ expect(listArrangedForNode([typed], [adminIp])).toEqual([adminIp])+ })+it('follows a rename rather than hiding the service (#468)', () => {// A service is its port, not its name. Keying on the name dropped the entry// the node drew and appended the renamed one hidden, so correcting adiff --git a/frontend/src/utils/deviceFacts.ts b/frontend/src/utils/deviceFacts.tsindex f7cd174..a63f247 100644--- a/frontend/src/utils/deviceFacts.ts+++ b/frontend/src/utils/deviceFacts.ts@@ -48,23 +48,33 @@ const encode = (value: unknown): string => JSON.stringify(value ?? null)* must not be reported as one — otherwise a rearranged canvas would push its* arrangement onto every other canvas showing the same device.*- * A service is identified by its port and protocol, never by its name — the- * same identity the backend's `_service_identity_key` uses. The name is a- * label: the scanner guesses it, the user corrects it, and keying on it made a- * rename look like a different service. `listArrangedForNode` would then drop- * the entry the node drew and append the renamed one hidden, so correcting a- * service in the Device Inventory made it vanish from every canvas (issue #468).+ * A service is identified by its port, protocol, host and path, never by its+ * name — the same identity the backend's `_service_identity_key` uses. The name+ * is a label: the scanner guesses it, the user corrects it, and keying on it+ * made a rename look like a different service. `listArrangedForNode` would then+ * drop the entry the node drew and append the renamed one hidden, so correcting+ * a service in the Device Inventory made it vanish from every canvas (issue+ * #468). The host and the path are in for the opposite reason: one node behind+ * a reverse proxy serves several sites on 443, and keying on the port alone+ * collapsed them into one entry that then overwrote the row (issue #503). The+ * scanner writes neither, so neither can resurrect #468.*- * A service with no port keeps the three-part form, name included: nothing else+ * A service with no port keeps the name, qualified the same way: nothing else* tells two of those apart.*/const keyOf = (item: Record<string, unknown>): string => {if ('key' in item) return String(item.key ?? '').toLowerCase()const { port, protocol } = item+ const host = String(item.host ?? '').trim().toLowerCase()+ // Anchored the way `getServiceUrl` renders it, so two entries the UI would+ // send to the same URL are one service.+ const raw = String(item.path ?? '').trim()+ const path = raw && raw !== '/' && !raw.startsWith('/') ? `/${raw}` : raw+ const site = `${host}|${path}`if (port === undefined || port === null || port === '') {- return `None|${protocol ?? ''}|${String(item.service_name ?? '').toLowerCase()}`+ return `None|${protocol ?? ''}|${String(item.service_name ?? '').toLowerCase()}|${site}`}- return `${port}|${protocol ?? ''}`+ return `${port}|${protocol ?? ''}|${site}`}const encodeFacts = (field: DeviceFactField, value: unknown): string => {@@ -107,6 +117,25 @@ export function changedFactFields(return DEVICE_FACT_FIELDS.filter((field) => encodeFacts(field, data[field]) !== baseline[field])}+/**+ * The port a service key names, the form the match falls back to.+ *+ * Identity carries the host and the path, so editing either in the Device+ * Inventory rewrites the key while the canvases drawing it still hold the old+ * one. Both spell the same port, so that is what they are matched on once the+ * exact key misses — otherwise the entry the node draws is dropped and the+ * edited one appended hidden, which is issue #468 in a new field. A port-less+ * service has no such form and keeps its key, as does a property — its key is+ * a name the user wrote, with no shape to read.+ */+const portKeyOf = (item: Record<string, unknown>): string => {+ const key = keyOf(item)+ if ('key' in item) return key+ const parts = key.split('|')+ if (parts.length < 2 || parts[0] === '' || parts[0] === 'None') return key+ return `${parts[0]}|${parts[1]}`+}+/*** The row's list, arranged the way this node already draws it.*@@ -115,25 +144,41 @@ export function changedFactFields(* it hid. Same rule the backend applies on read: what the node already lists* keeps its place and its flag, what the row gained since is appended hidden,* and what the row lost disappears.+ *+ * Matched one item at a time rather than by key alone: a row can hold two+ * services on one port, each its own site behind a reverse proxy (issue #503),+ * and each entry the node draws claims its own.*/export function listArrangedForNode<T extends Record<string, unknown>>(current: T[] | undefined,incoming: T[],): T[] {if (!current?.length) return incoming- const seen = new Set<string>()- const by = new Map(incoming.map((item) => [keyOf(item), item]))+ const pools = new Map<string, number[]>()+ const add = (key: string, pos: number) => {+ const pool = pools.get(key)+ if (pool) pool.push(pos)+ else pools.set(key, [pos])+ }+ incoming.forEach((item, pos) => {+ const key = keyOf(item)+ add(key, pos)+ const port = portKeyOf(item)+ if (port !== key) add(port, pos)+ })+ const claimed = new Set<number>()+ const free = (key: string) => pools.get(key)?.find((p) => !claimed.has(p))const out: T[] = []for (const item of current) {- const key = keyOf(item)- const fresh = by.get(key)- if (!fresh || seen.has(key)) continue- seen.add(key)- out.push('visible' in item ? { ...fresh, visible: item.visible } : (fresh as T))- }- for (const item of incoming) {- if (!seen.has(keyOf(item))) out.push({ ...item, visible: false })+ const pos = free(keyOf(item)) ?? free(portKeyOf(item))+ if (pos === undefined) continue+ claimed.add(pos)+ const fresh = incoming[pos]+ out.push('visible' in item ? { ...fresh, visible: item.visible } : fresh)}+ incoming.forEach((item, pos) => {+ if (!claimed.has(pos)) out.push({ ...item, visible: false })+ })return out}