Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring
TypeScript diagramhomelabhomelab-infrastructure-observabilitynetworkproxmox-veself-hostedzigbeezwavezwave-js
fix(status): stop an endless response body from OOM-killing the backend
Pouzorc29680a75fff
diff --git a/backend/app/services/http_probe.py b/backend/app/services/http_probe.pyindex 8ed9319..554de4d 100644--- a/backend/app/services/http_probe.py+++ b/backend/app/services/http_probe.py@@ -16,7 +16,11 @@ logger = logging.getLogger(__name__)# Headers that commonly carry the application name._SIGNAL_HEADERS = ("Server", "X-Powered-By")-# Cap how much body we read when hunting for <title> — avoids large downloads.+# Cap how much body we read when hunting for <title>. This is a cap on the+# download itself, not just on what we scan: the body is streamed and the+# connection dropped once we hold this much. Some endpoints stream without end+# and send no Content-Length (bandwidth-test endpoints, MJPEG cameras), so+# buffering a full response would OOM the backend._MAX_BODY_BYTES = 64 * 1024_TITLE_RE = re.compile(r"<title[^>]*>(.*?)</title>", re.IGNORECASE | re.DOTALL)_PROBE_TIMEOUT = 3.0@@ -24,6 +28,23 @@ _PROBE_TIMEOUT = 3.0_NON_HTTP_PORTS = frozenset({22, 21, 23, 25, 53, 110, 143, 161, 162, 179, 445, 3306, 5432, 6379})+async def _read_capped(resp: httpx.Response) -> str:+ """Read at most _MAX_BODY_BYTES of a streaming response, then stop."""+ chunks: list[bytes] = []+ size = 0+ async for chunk in resp.aiter_bytes():+ chunks.append(chunk)+ size += len(chunk)+ if size >= _MAX_BODY_BYTES:+ break+ raw = b"".join(chunks)[:_MAX_BODY_BYTES]+ encoding = resp.charset_encoding or "utf-8"+ try:+ return raw.decode(encoding, errors="replace")+ except LookupError:+ return raw.decode("utf-8", errors="replace")++def _extract_title(body: str) -> str | None:m = _TITLE_RE.search(body)if not m:@@ -34,11 +55,11 @@ def _extract_title(body: str) -> str | None:async def _probe_scheme(client: httpx.AsyncClient, url: str) -> dict[str, Any] | None:try:- resp = await client.get(url, follow_redirects=True)+ async with client.stream("GET", url, follow_redirects=True) as resp:+ headers = {h: resp.headers[h] for h in _SIGNAL_HEADERS if h in resp.headers}+ body = await _read_capped(resp)except (httpx.HTTPError, OSError):return None- headers = {h: resp.headers[h] for h in _SIGNAL_HEADERS if h in resp.headers}- body = resp.text[:_MAX_BODY_BYTES] if resp.text else ""title = _extract_title(body)if not title and not headers:return Nonediff --git a/backend/app/services/status_checker.py b/backend/app/services/status_checker.pyindex b682704..45da3fd 100644--- a/backend/app/services/status_checker.py+++ b/backend/app/services/status_checker.py@@ -103,8 +103,16 @@ async def _ping(host: str) -> bool:async def _http_get(url: str, verify: bool = False) -> bool:- async with httpx.AsyncClient(verify=verify, timeout=5) as client:- resp = await client.get(url, follow_redirects=True)+ # Only the status line matters here. A plain .get() buffers the whole body+ # first, and some endpoints stream without end (bandwidth-test endpoints,+ # MJPEG cameras, log tails) — enough to OOM the backend. timeout=5 does not+ # save us: httpx applies it per network operation, not to the total time+ # spent draining a socket that keeps delivering data. stream() closes the+ # connection on exit without draining it.+ async with (+ httpx.AsyncClient(verify=verify, timeout=5) as client,+ client.stream("GET", url, follow_redirects=True) as resp,+ ):return resp.status_code < 500diff --git a/backend/tests/test_http_probe.py b/backend/tests/test_http_probe.pyindex 4175d63..e7c171f 100644--- a/backend/tests/test_http_probe.py+++ b/backend/tests/test_http_probe.py@@ -1,10 +1,11 @@"""Tests for the HTTP probe used by deep-scan service identification."""-from unittest.mock import AsyncMock, patch+from unittest.mock import patchimport httpximport pytestfrom app.services.http_probe import (+ _MAX_BODY_BYTES,_extract_title,probe_open_ports,probe_port,@@ -15,6 +16,39 @@ def _response(text: str = "", headers: dict | None = None, status: int = 200) ->return httpx.Response(status_code=status, text=text, headers=headers or {})+class _TransportClient:+ """+ Patch target for httpx.AsyncClient that routes through a MockTransport.++ Real client, fake network: the probe exercises the genuine httpx request+ path (including .stream() and aiter_bytes()) instead of a mock that would+ happily accept any call shape. `requests` records what was actually sent.+ """++ def __init__(self, handler):+ self._handler = handler+ # Bound before patching, so building the real client here does not+ # recurse back into this stand-in.+ self._real = httpx.AsyncClient+ self.kwargs: list[dict] = []+ self.requests: list[httpx.Request] = []++ def _record(self, request: httpx.Request) -> httpx.Response:+ self.requests.append(request)+ return self._handler(request)++ def __call__(self, **kwargs):+ self.kwargs.append(dict(kwargs))+ kwargs.pop("verify", None)+ return self._real(transport=httpx.MockTransport(self._record), **kwargs)+++def _patch_client(handler) -> tuple:+ """Return (context manager, factory) patching http_probe's AsyncClient."""+ factory = _TransportClient(handler)+ return patch("app.services.http_probe.httpx.AsyncClient", factory), factory++# ── _extract_title ──────────────────────────────────────────────────────────def test_extract_title_basic():@@ -37,15 +71,18 @@ def test_extract_title_case_insensitive():@pytest.mark.asyncioasync def test_probe_port_reads_title():- with patch("httpx.AsyncClient.get", new=AsyncMock(return_value=_response("<title>Jellyfin</title>"))):+ ctx, _ = _patch_client(lambda req: _response("<title>Jellyfin</title>"))+ with ctx:result = await probe_port("10.0.0.5", 8096)assert result == {"title": "Jellyfin", "headers": {}}@pytest.mark.asyncioasync def test_probe_port_reads_headers():- resp = _response("", headers={"Server": "nginx", "X-Powered-By": "Express"})- with patch("httpx.AsyncClient.get", new=AsyncMock(return_value=resp)):+ ctx, _ = _patch_client(+ lambda req: _response("", headers={"Server": "nginx", "X-Powered-By": "Express"})+ )+ with ctx:result = await probe_port("10.0.0.5", 3000)assert result["headers"] == {"Server": "nginx", "X-Powered-By": "Express"}@@ -53,30 +90,33 @@ async def test_probe_port_reads_headers():@pytest.mark.asyncioasync def test_probe_port_falls_back_to_http():# https raises, http succeeds- calls = {"n": 0}-- async def fake_get(self, url, **kw):- calls["n"] += 1- if url.startswith("https"):+ def handler(request):+ if str(request.url).startswith("https"):raise httpx.ConnectError("tls fail")return _response("<title>HTTP App</title>")- with patch("httpx.AsyncClient.get", new=fake_get):+ ctx, factory = _patch_client(handler)+ with ctx:result = await probe_port("10.0.0.5", 8080)assert result["title"] == "HTTP App"- assert calls["n"] == 2 # tried https then http+ assert len(factory.requests) == 2 # tried https then http@pytest.mark.asyncioasync def test_probe_port_no_signal_returns_none():- with patch("httpx.AsyncClient.get", new=AsyncMock(return_value=_response(""))):+ ctx, _ = _patch_client(lambda req: _response(""))+ with ctx:result = await probe_port("10.0.0.5", 8080)assert result is None@pytest.mark.asyncioasync def test_probe_port_timeout_returns_none():- with patch("httpx.AsyncClient.get", new=AsyncMock(side_effect=httpx.TimeoutException("slow"))):+ def handler(request):+ raise httpx.TimeoutException("slow")++ ctx, _ = _patch_client(handler)+ with ctx:result = await probe_port("10.0.0.5", 8080)assert result is None@@ -84,33 +124,101 @@ async def test_probe_port_timeout_returns_none():@pytest.mark.asyncioasync def test_probe_port_skips_non_http_ports():# SSH should never trigger an HTTP request- get = AsyncMock()- with patch("httpx.AsyncClient.get", new=get):+ ctx, factory = _patch_client(lambda req: _response("<title>nope</title>"))+ with ctx:result = await probe_port("10.0.0.5", 22)assert result is None- get.assert_not_called()+ assert factory.requests == []@pytest.mark.asyncioasync def test_probe_port_verify_tls_flag_passed():- with patch("app.services.http_probe.httpx.AsyncClient") as client_cls:- instance = client_cls.return_value.__aenter__.return_value- instance.get = AsyncMock(return_value=_response("<title>X</title>"))+ ctx, factory = _patch_client(lambda req: _response("<title>X</title>"))+ with ctx:await probe_port("10.0.0.5", 8443, verify_tls=True)- assert client_cls.call_args.kwargs["verify"] is True+ assert factory.kwargs[0]["verify"] is True+++# ── endless bodies (issue #375) ─────────────────────────────────────────────++_CHUNK_SIZE = 16 * 1024+++def _endless_body(counter: dict, head: bytes = b""):+ """+ A body that never ends and declares no Content-Length. Bounded at 512+ chunks so a regression fails the test instead of hanging the suite.+ """++ async def gen():+ if head:+ counter["bytes"] += len(head)+ yield head+ for _ in range(512):+ counter["bytes"] += _CHUNK_SIZE+ yield b"\0" * _CHUNK_SIZE++ return gen()+++async def test_probe_caps_the_download_of_an_endless_body():+ # _MAX_BODY_BYTES caps the download, not just the <title> scan: the body is+ # streamed and the connection dropped once we hold enough. Allow one chunk+ # of overshoot — the read stops on a chunk boundary.+ counter = {"bytes": 0}++ def handler(request):+ # Plain HTTP only, like the reproducer, so the counter covers one probe.+ if str(request.url).startswith("https"):+ raise httpx.ConnectError("no tls")+ return httpx.Response(+ 200,+ headers={"Content-Type": "application/octet-stream"},+ content=_endless_body(counter),+ )++ ctx, _ = _patch_client(handler)+ with ctx:+ result = await probe_port("10.0.0.5", 8095)+ assert result is None # null bytes carry no title and no signal header+ assert counter["bytes"] <= _MAX_BODY_BYTES + _CHUNK_SIZE+++async def test_probe_still_reads_a_title_from_an_endless_body():+ # Stopping early must not cost us the signal: a <title> in the first chunk+ # is still found even though the rest of the stream is abandoned.+ counter = {"bytes": 0}++ def handler(request):+ if str(request.url).startswith("https"):+ raise httpx.ConnectError("no tls")+ return httpx.Response(+ 200,+ headers={"Content-Type": "text/html"},+ content=_endless_body(counter, head=b"<html><title>Jellyfin</title>"),+ )++ ctx, _ = _patch_client(handler)+ with ctx:+ result = await probe_port("10.0.0.5", 8096)+ assert result["title"] == "Jellyfin"+ assert counter["bytes"] <= _MAX_BODY_BYTES + _CHUNK_SIZE# ── probe_open_ports ─────────────────────────────────────────────────────────@pytest.mark.asyncioasync def test_probe_open_ports_enriches_each_port():- async def fake_get(self, url, **kw):- if ":8096" in url:+ def handler(request):+ if ":8096" in str(request.url):return _response("<title>Jellyfin</title>")return _response("")ports = [{"port": 8096, "protocol": "tcp"}, {"port": 9999, "protocol": "tcp"}]- with patch("httpx.AsyncClient.get", new=fake_get):+ ctx, _ = _patch_client(handler)+ with ctx:result = await probe_open_ports("10.0.0.5", ports)by_port = {p["port"]: p for p in result}diff --git a/backend/tests/test_status_checker.py b/backend/tests/test_status_checker.pyindex 11b8b5a..c26c10f 100644--- a/backend/tests/test_status_checker.py+++ b/backend/tests/test_status_checker.py@@ -1,6 +1,7 @@"""Tests for status_checker service: each check method."""from unittest.mock import AsyncMock, MagicMock, patch+import httpximport pytestfrom app.services.status_checker import (@@ -13,16 +14,31 @@ from app.services.status_checker import ()+class _TransportClient:+ """+ Patch target for httpx.AsyncClient that routes through a MockTransport.++ Real client, fake network: _http_get exercises the genuine httpx request+ path (including .stream()) instead of a mock that would happily accept any+ call shape.+ """++ def __init__(self, handler):+ self._handler = handler+ # Bound before patching, so building the real client here does not+ # recurse back into this stand-in.+ self._real = httpx.AsyncClient+ self.kwargs = []++ def __call__(self, **kwargs):+ self.kwargs.append(dict(kwargs))+ kwargs.pop("verify", None)+ return self._real(transport=httpx.MockTransport(self._handler), **kwargs)++def _mock_httpx_client(status_code):"""Build a stand-in for httpx.AsyncClient whose GET returns status_code."""- resp = MagicMock()- resp.status_code = status_code- client = MagicMock()- client.get = AsyncMock(return_value=resp)- ctx = MagicMock()- ctx.__aenter__ = AsyncMock(return_value=client)- ctx.__aexit__ = AsyncMock(return_value=False)- return MagicMock(return_value=ctx)+ return _TransportClient(lambda request: httpx.Response(status_code))# --- check_node dispatcher ---@@ -554,6 +570,43 @@ async def test_check_services_empty_list():# --- _http_get status-code interpretation (real primitive, mocked transport) ---+# --- Regression: an endless response body must not be buffered (issue #375) ---++_CHUNK = b"\0" * 65536+++def _endless_body(counter: dict):+ """+ A body that never ends and declares no Content-Length — the Freebox+ bandwidth-test endpoint from issue #375. Bounded at 512 chunks (32 MiB) so+ a regression fails the test instead of hanging the suite forever.+ """++ async def gen():+ for _ in range(512):+ counter["chunks"] += 1+ yield _CHUNK++ return gen()+++async def test_http_get_does_not_read_the_body():+ # _http_get only needs the status line. Buffering the body of an endless+ # stream is what OOM-killed the backend, so assert not one byte is pulled.+ counter = {"chunks": 0}+ factory = _TransportClient(+ lambda request: httpx.Response(+ 200,+ headers={"Content-Type": "application/octet-stream"},+ content=_endless_body(counter),+ )+ )+ with patch("app.services.status_checker.httpx.AsyncClient", factory):+ assert await _http_get("http://192.168.1.254:8095/") is True+ assert counter["chunks"] == 0++@pytest.mark.asyncioasync def test_http_get_true_on_2xx():with patch("app.services.status_checker.httpx.AsyncClient", _mock_httpx_client(200)):