From d93eda7de36d1afebf665ea3416db4f700e34422 Mon Sep 17 00:00:00 2001 From: ZdenekSrotyr Date: Wed, 6 May 2026 15:37:20 +0200 Subject: [PATCH] perf+test(cli): cache User-Agent at module scope; pin local==min boundary --- cli/client.py | 11 ++++++++++- tests/test_client_version_check.py | 11 +++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/cli/client.py b/cli/client.py index 2e4c7ff..54efb2d 100644 --- a/cli/client.py +++ b/cli/client.py @@ -19,6 +19,15 @@ import httpx from cli.config import _config_dir, get_server_url, get_token from cli.update_check import _installed_version, _version_lt +# User-Agent is invariant for the life of the process — installed +# version doesn't change, OS doesn't change. Cache it at import time so +# every `get_client()` call doesn't re-do the importlib.metadata lookup +# + `platform.system()` call. (Reviewer note: do NOT cache the +# `_installed_version` lookup inside `_check_version_headers` — tests +# patch `cli.client._installed_version` and a cached value would defeat +# the patch. The hook keeps calling it; network cost dwarfs the lookup.) +_USER_AGENT = f"agnes/{_installed_version()} ({platform.system().lower()})" + # PID-suffixed tmp / part files — see `_download_chunked` and # `_download_single_stream`. We extract the embedded PID and reap any @@ -266,7 +275,7 @@ def get_client(timeout: float = 30.0) -> httpx.Client: headers["Authorization"] = f"Bearer {token}" return httpx.Client( base_url=get_server_url(), - headers={**headers, "User-Agent": f"agnes/{_installed_version()} ({platform.system().lower()})"}, + headers={**headers, "User-Agent": _USER_AGENT}, timeout=timeout, event_hooks={"response": [_check_version_headers]}, ) diff --git a/tests/test_client_version_check.py b/tests/test_client_version_check.py index 1cae9a2..c0ceccb 100644 --- a/tests/test_client_version_check.py +++ b/tests/test_client_version_check.py @@ -32,6 +32,17 @@ def test_local_at_or_above_min_does_not_exit(): _check_version_headers(resp) # must not raise +def test_local_equal_to_min_does_not_exit(): + """`Version("X.Y.Z") < Version("X.Y.Z")` is False — equality must pass.""" + from cli.client import _check_version_headers + with patch("cli.client._installed_version", return_value="0.35.0"): + resp = _fake_response({ + "X-Agnes-Latest-Version": "0.40.0", + "X-Agnes-Min-Version": "0.35.0", + }) + _check_version_headers(resp) # must not raise + + def test_missing_headers_no_enforcement(): """Older server without middleware → no headers → no-op.""" from cli.client import _check_version_headers