Skip to content

The agent that grows with you

fix(webapp): save a standalone profile's port under a lock every gateway shares

unsupportedpastels1f3da07f3a93
diff --git a/hermes_cli/web_routers/webapp_access.py b/hermes_cli/web_routers/webapp_access.py
index 6fb1a18b179..9218e9fa68e 100644
--- a/hermes_cli/web_routers/webapp_access.py
+++ b/hermes_cli/web_routers/webapp_access.py
@@ -120,9 +120,11 @@ async def webapp_access_status(profile: Optional[str] = None):
async def start_webapp_access(body: StartBody, profile: Optional[str] = None):
profile = destructive_profile(profile, "POST /api/webapp-access/start")
async with _one_change_at_a_time():
+ # Writes a standalone profile's first port claim, so it takes the config lock.
gateway, (host, port, public_url, callback) = await _scoped(
- profile, lambda gateway: (gateway, webapp_access.plan(body.mode, body.public_url)))
- # The bundle before anything lasting: a failed build registers, writes and restarts nothing.
+ profile, lambda gateway: (gateway, webapp_access.plan(body.mode, body.public_url)), config_write=True)
+ # The bundle before anything else lasting: a failed build registers, restarts and writes nothing
+ # but that port claim.
await _in_gateway_home(gateway, webapp_access.build_bundle)
await _in_gateway_home(gateway, lambda: webapp_access.register(callback))
await _scoped(profile, lambda _gateway: webapp_access.serve(host, public_url, port), config_write=True)
diff --git a/hermes_cli/webapp_access.py b/hermes_cli/webapp_access.py
index 4d868f1fb23..ae1450c2a46 100644
--- a/hermes_cli/webapp_access.py
+++ b/hermes_cli/webapp_access.py
@@ -22,6 +22,7 @@ from __future__ import annotations
import json
import os
import socket
+import threading
from pathlib import Path
from typing import Optional
from urllib.parse import urlsplit
@@ -155,8 +156,9 @@ def _register_nous_sign_in(callback_url: str) -> None:
def plan(mode: str, public_url: Optional[str] = None) -> tuple[str, Optional[int], str, str]:
"""Check that *mode* can be served and signed in to; returns ``(host, port, public_url, callback)``:
the bind host, the port to write (None to keep the config's, :func:`_port_to_serve`) and the URL to
- pin for :func:`serve`, and the sign-in callback for :func:`register`. Changes nothing, so Start
- runs it before any slow or lasting step."""
+ pin for :func:`serve`, and the sign-in callback for :func:`register`. Changes nothing but the port
+ claim of a standalone profile that has none (:func:`_port_to_serve`), so Start runs it, in the
+ config write scope, before any slow or lasting step."""
if mode == "lan":
address = lan_address()
if address is None:
@@ -177,6 +179,11 @@ def plan(mode: str, public_url: Optional[str] = None) -> tuple[str, Optional[int
#: How many ports above the default Start tries for a standalone profile's Webapp.
_PORT_SEARCH = 100
+#: Under the Hermes root every profile shares: one standalone profile's gateway at a time chooses and
+#: saves its Webapp port, so a Start in another gateway's process sees that claim before it chooses.
+_PORT_CLAIM_LOCK = Path("webapp") / "port-claim.lock"
+_PORT_CLAIM_HOLDER = threading.local()
+_PORT_CLAIM_TIMEOUT_SECONDS = 10.0
def _port_to_serve(home: Path, host: str) -> tuple[int, Optional[int]]:
@@ -187,20 +194,43 @@ def _port_to_serve(home: Path, host: str) -> tuple[int, Optional[int]]:
profile's gateway with no ``webapp.port`` would find the default port taken by the default gateway's
Webapp, so it gets the first port above it that no other Hermes home on this machine claims and
nothing listens on now, and Start writes it to that profile's ``webapp.port``: the profile keeps that
- address across restarts, and the gateway, the launcher and the sign-in callback all use it."""
+ address across restarts, and the gateway, the launcher and the sign-in callback all use it.
+
+ Each standalone profile's gateway has its own change lock, so the port is chosen and saved under a
+ lock every gateway on this machine shares, before the slow steps of Start: a Start that fails after
+ this keeps the port, which is that profile's from then on, as one a finished Start writes. *home* is
+ the home in scope, whose config :func:`save_config` writes (Start runs in its gateway's scope)."""
from gateway.webapp_listener import DEFAULT_PORT, webapp_settings
+ from hermes_cli.auth import _file_lock
from hermes_constants import named_profile_home
- if _own_port(home) is not None or named_profile_home(home) is None:
+ profile = named_profile_home(home)
+ if _own_port(home) is not None or profile is None:
return webapp_settings(home).port, None
- claimed = _claimed_ports(home)
- for port in range(DEFAULT_PORT + 1, DEFAULT_PORT + 1 + _PORT_SEARCH):
- if port not in claimed and _port_free(host, port):
- return port, port
+ try:
+ with _file_lock(profile.parent.parent / _PORT_CLAIM_LOCK, _PORT_CLAIM_HOLDER, _PORT_CLAIM_TIMEOUT_SECONDS,
+ "Timed out waiting for another Hermes profile to choose its Webapp port"):
+ claimed = _claimed_ports(home)
+ for port in range(DEFAULT_PORT + 1, DEFAULT_PORT + 1 + _PORT_SEARCH):
+ if port not in claimed and _port_free(host, port):
+ _save_port(port)
+ return port, port
+ except TimeoutError as exc:
+ raise WebappAccessError(f"{exc}. Start again in a moment.") from exc
raise WebappAccessError(f"No free port for the Webapp from {DEFAULT_PORT + 1} to {DEFAULT_PORT + _PORT_SEARCH}. "
f"Set webapp.port in {home / 'config.yaml'} to a free port, then start again.")
+def _save_port(port: int) -> None:
+ """Claim *port* as the ``webapp.port`` of the home in scope, changing nothing else."""
+ from hermes_cli.config import load_config, save_config
+
+ cfg = load_config()
+ webapp = cfg.get("webapp")
+ cfg["webapp"] = {**(webapp if isinstance(webapp, dict) else {}), "port": port}
+ save_config(cfg)
+
+
def _own_port(home: Path) -> Optional[object]:
"""The ``webapp.port`` *home*'s gateway is configured with, valid or not (the gateway reports an
invalid one by name), or None when neither *home*'s ``config.yaml`` nor the managed scope sets one.
diff --git a/tests/hermes_cli/test_webapp_access_ports.py b/tests/hermes_cli/test_webapp_access_ports.py
index 118ed5f5c12..63915f53f81 100644
--- a/tests/hermes_cli/test_webapp_access_ports.py
+++ b/tests/hermes_cli/test_webapp_access_ports.py
@@ -135,6 +135,53 @@ def test_with_no_free_port_start_refuses_and_names_the_setting(machine):
assert "port" not in _webapp_block(machine["solo"])
+def test_two_profiles_starting_at_once_never_save_the_same_port(machine):
+ """Each standalone profile's gateway has its own change lock, so two first Starts can overlap. The
+ probes wait for each other: without a lock both gateways share, both would see the same free port
+ and save it. Each runs as its own profile (a context-local home, as its gateway's scope does)."""
+ import threading
+ from concurrent.futures import ThreadPoolExecutor
+
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+
+ twin = _write(machine["root"] / "profiles" / "twin", "gateway:\n standalone: true\n")
+ both_probe = threading.Barrier(2, timeout=2)
+
+ def port_free(_host, port):
+ try:
+ both_probe.wait() # until the other probes too, or (holding the lock) it never can
+ except threading.BrokenBarrierError:
+ pass
+ return port not in machine["listening"]
+
+ machine["monkeypatch"].setattr(webapp_access, "_port_free", port_free)
+
+ def start(home: Path) -> int:
+ token = set_hermes_home_override(home)
+ try:
+ host, port, public_url, _callback = webapp_access.plan("lan")
+ webapp_access.serve(host, public_url, port)
+ return _webapp_block(home)["port"]
+ finally:
+ reset_hermes_home_override(token)
+
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ starts = [pool.submit(start, home) for home in (machine["solo"], twin)]
+ chosen = sorted(started.result(timeout=30) for started in starts)
+ # 9120 is the default profile's, 9121 is in use, 9122 is the other profile's.
+ assert chosen == [9123, 9124]
+
+
+def test_a_start_that_fails_after_choosing_keeps_the_port(machine):
+ """The port is saved when it is chosen, before the bundle build and the registration, so another
+ profile never takes it; a Start that then fails leaves the profile that port and nothing else."""
+ webapp_access.plan("lan")
+ assert _webapp_block(machine["solo"]) == {"port": 9123}
+ machine["probed"].clear()
+ _host, port, _public_url, callback = webapp_access.plan("lan")
+ assert (port, callback, machine["probed"]) == (None, "http://192.168.1.50:9123/auth/callback", [])
+
+
def test_the_probe_sees_a_port_a_listener_holds():
"""On a port the OS picked, not a real service's."""
with socket.socket() as held: