The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(browser): use lru_cache for the lightpanda flag probe
kshitijk4poor3bf4fa45b8f0
diff --git a/tests/tools/test_browser_lightpanda_serve.py b/tests/tools/test_browser_lightpanda_serve.pyindex 89a5ce99658..db607ec77bf 100644--- a/tests/tools/test_browser_lightpanda_serve.py+++ b/tests/tools/test_browser_lightpanda_serve.py@@ -12,6 +12,10 @@ import pytestimport tools.browser_lightpanda as lp+# The autouse _isolate fixture swaps _binary_supports_http_cache for a lambda;+# the probe test needs the real (lru_cache-wrapped) function back.+_real_probe = lp._binary_supports_http_cache+class FakeProc:def __init__(self, pid=4242, exit_code=None):@@ -43,7 +47,8 @@ def _isolate(tmp_path, monkeypatch):# Never touch the developer's real ~/.local/bin/lightpanda.monkeypatch.setattr(lp, "_home_candidates", lambda: [])monkeypatch.setattr(lp, "_safe_start_time", lambda pid: 111)- monkeypatch.setattr(lp, "_supports_http_cache", True)+ lp._binary_supports_http_cache.cache_clear()+ monkeypatch.setattr(lp, "_binary_supports_http_cache", lambda binary: True)with lp._servers_lock:lp._servers.clear()yield state@@ -144,38 +149,45 @@ class TestLaunch:assert not list(Path(cache).glob("*.json")) # never confused with a session recorddef test_no_http_cache_flag_on_old_binary(self, monkeypatch, _isolate):- monkeypatch.setattr(lp, "_supports_http_cache", False)+ monkeypatch.setattr(lp, "_binary_supports_http_cache", lambda binary: False)_, err, calls = self._launch(monkeypatch)assert err is Noneassert "--http-cache-dir" not in calls["argv"]assert calls["argv"][-1] == "43111"def test_http_cache_probe_caches_and_detects_flag(self, monkeypatch, tmp_path):+ monkeypatch.setattr(lp, "_binary_supports_http_cache", _real_probe)+ _real_probe.cache_clear()exe = _exe(tmp_path / "lightpanda")runs = []- class FakeRun:- def __init__(self, stdout):- self.stdout = stdout-def fake_run(argv, **kwargs):runs.append(argv)- return FakeRun("--http-cache-dir <PATH>" if len(runs) == 1 else "")+ return subprocess.CompletedProcess(+ argv, returncode=0,+ stdout="--http-cache-dir <PATH>" if len(runs) == 1 else "",+ )- monkeypatch.setattr(lp, "_supports_http_cache", None)monkeypatch.setattr(lp.subprocess, "run", fake_run)assert lp._binary_supports_http_cache(str(exe)) is Trueassert lp._binary_supports_http_cache(str(exe)) is True # cached, single probeassert len(runs) == 1- monkeypatch.setattr(lp, "_supports_http_cache", None)+ lp._binary_supports_http_cache.cache_clear()def fake_run_old(argv, **kwargs):- return FakeRun("no such flag here")+ return subprocess.CompletedProcess(argv, returncode=0, stdout="no such flag")monkeypatch.setattr(lp.subprocess, "run", fake_run_old)assert lp._binary_supports_http_cache(str(exe)) is False+ def fake_run_hangs(argv, **kwargs):+ raise subprocess.TimeoutExpired(cmd=argv, timeout=3.0)++ lp._binary_supports_http_cache.cache_clear()+ monkeypatch.setattr(lp.subprocess, "run", fake_run_hangs)+ assert lp._binary_supports_http_cache(str(exe)) is False+def test_block_private_networks_flag(self, monkeypatch):_, err, calls = self._launch(monkeypatch, block_private_networks=True)assert err is Nonediff --git a/tools/browser_lightpanda.py b/tools/browser_lightpanda.pyindex 3c1bdf8d368..800c05aa054 100644--- a/tools/browser_lightpanda.py+++ b/tools/browser_lightpanda.py@@ -12,6 +12,7 @@ reaper and the atexit sweep; it calls :func:`launch_lightpanda` /left behind by a crashed Hermes."""+import functoolsimport jsonimport loggingimport os@@ -128,32 +129,28 @@ def _http_cache_dir() -> Path:return path-_supports_http_cache: Optional[bool] = None+_HTTP_CACHE_FLAG = "--http-cache-dir"[email protected]_cache(maxsize=1)def _binary_supports_http_cache(binary: str) -> bool:"""True if ``lightpanda serve`` accepts ``--http-cache-dir``.The flag landed upstream in 0.3.x; older binaries fatally reject it("unknown argument"), which would break every launch. Probing ``help``output keeps working across future flag additions without parsing- versions, and is cached for the process lifetime.+ versions, and the lru_cache keeps it once per binary per process."""- global _supports_http_cache- if _supports_http_cache is None:- try:- out = subprocess.run(- [binary, "help"], capture_output=True, text=True, timeout=10- )- _supports_http_cache = "--http-cache-dir" in out.stdout- except Exception as e:- logger.debug("lightpanda http-cache probe failed (%s); assuming no", e)- _supports_http_cache = False- if not _supports_http_cache:- logger.debug(- "lightpanda %s predates --http-cache-dir; serving without a cache", binary+ try:+ proc = subprocess.run(+ [binary, "help"],+ capture_output=True, text=True, timeout=3.0,+ stdin=subprocess.DEVNULL,)- return _supports_http_cache+ return _HTTP_CACHE_FLAG in ((proc.stdout or "") + (proc.stderr or ""))+ except Exception as e:+ logger.debug("lightpanda http-cache probe failed (%s); assuming no", e)+ return Falsedef _record_path(session_name: str) -> Path:@@ -259,7 +256,7 @@ def launch_lightpanda(port = _pick_free_loopback_port()argv = [binary, "serve", "--host", "127.0.0.1", "--port", str(port)]if _binary_supports_http_cache(binary):- argv += ["--http-cache-dir", str(_http_cache_dir())]+ argv += [_HTTP_CACHE_FLAG, str(_http_cache_dir())]if block_private_networks:argv.append("--block-private-networks")log_path = str(_state_dir() / f"{session_name}.log")