Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,12 @@ def build_app(inputs: BrokerInputs) -> Starlette:

@asynccontextmanager
async def lifespan(app):
async with client, bugzilla_manager.run(), phabricator_manager.run():
async with (
client,
phabricator_client,
bugzilla_manager.run(),
phabricator_manager.run(),
):
log.info(
"broker ready on %s:%d (bugzilla + phabricator read-only, "
"phabricator conduit proxy)",
Expand Down
7 changes: 6 additions & 1 deletion agents/bug-fix/hackbot_agents/bug_fix/broker.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,12 @@ def build_app(inputs: BrokerInputs) -> Starlette:

@asynccontextmanager
async def lifespan(app):
async with client, bugzilla_manager.run(), phabricator_manager.run():
async with (
client,
phabricator_client,
bugzilla_manager.run(),
phabricator_manager.run(),
):
log.info(
"broker ready on %s:%d (bugzilla + phabricator read-only, "
"phabricator conduit proxy)",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -158,9 +158,8 @@ async def run_uplift(
scratch_out.mkdir(parents=True, exist_ok=True)

# Materialize the diffs first, so the prompt names the paths they landed at.
fetched = await fetch_source_diffs(
build_phabricator_client(broker_url), sources, scratch_out
)
async with build_phabricator_client(broker_url) as phabricator_client:
fetched = await fetch_source_diffs(phabricator_client, sources, scratch_out)
await fetch_source_commits(source_repo, sources, fetched)
user_prompt = build_user_prompt(
target_branch=target_branch,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ def build_app(inputs: BrokerInputs) -> Starlette:
async def lifespan(app):
async with (
bugzilla_client,
phabricator_client,
bugzilla_manager.run(),
phabricator_manager.run(),
):
Expand Down
6 changes: 3 additions & 3 deletions libs/hackbot-runtime/hackbot_runtime/revision.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,13 +81,13 @@ async def checkout_revision(
Raises :class:`RuntimeError` if the stack cannot be resolved or a diff does
not apply, so the run fails visibly rather than editing the wrong tree.
"""
client = PhabricatorClient(
async with PhabricatorClient(
PhabricatorSettings(
url=f"{broker_url.rstrip('/')}{_PROXY_MOUNT}",
api_key=_PROXY_API_TOKEN,
)
)
stack = await _resolve_stack(client, revision_id)
) as client:
stack = await _resolve_stack(client, revision_id)

# Prepare the checkout explicitly at the stack's base commit. Must run
# before anything else touches the source (prepare_repo raises otherwise).
Expand Down
9 changes: 3 additions & 6 deletions libs/hackbot-runtime/tests/test_revision.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,14 +129,11 @@ def json(self):
return self._payload

class _FakeAsyncClient:
def __init__(self, timeout=None):
def __init__(self, **kwargs):
pass

async def __aenter__(self):
return self

async def __aexit__(self, *exc):
return False
async def aclose(self):
pass

async def post(self, url, data=None):
method = url.rsplit("/", 1)[-1]
Expand Down
37 changes: 29 additions & 8 deletions libs/phabricator-client/phabricator_client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,14 @@
one from the environment (via ``PhabricatorSettings.from_env``) when none is
provided. The API is asynchronous — both consumers run in an event loop, so the
client is async-native rather than sync-with-threadpool.

The client reuses one connection pool across requests. Close it when done,
either with ``async with`` or by calling :meth:`PhabricatorClient.close`.
"""

import json
from typing import Any
from types import TracebackType
from typing import Any, Self

import httpx

Expand Down Expand Up @@ -77,6 +81,26 @@ def _select_full_commit(ref: str, result: dict) -> str:
class PhabricatorClient:
def __init__(self, settings: PhabricatorSettings | None = None) -> None:
self.settings = settings or PhabricatorSettings.from_env()
headers = {}
if self.settings.edge_key:
headers["Mozilla-Edge-Key"] = self.settings.edge_key
self._http = httpx.AsyncClient(
headers=headers, timeout=self.settings.timeout_seconds
)

async def close(self) -> None:
await self._http.aclose()

async def __aenter__(self) -> Self:
return self

async def __aexit__(
self,
exc_type: type[BaseException] | None,
exc: BaseException | None,
tb: TracebackType | None,
) -> None:
await self.close()

@property
def base_url(self) -> str:
Expand All @@ -98,13 +122,10 @@ async def conduit_call(self, method: str, params: dict) -> dict:
credentials the request is made with.
"""
payload = {**params, "__conduit__": {"token": self.settings.api_key}}
async with httpx.AsyncClient(timeout=self.settings.timeout_seconds) as client:
if self.settings.edge_key:
client.headers["Mozilla-Edge-Key"] = self.settings.edge_key
response = await client.post(
f"{self.base_url}/api/{method}",
data={"params": json.dumps(payload), "output": "json"},
)
response = await self._http.post(
f"{self.base_url}/api/{method}",
data={"params": json.dumps(payload), "output": "json"},
)
response.raise_for_status()
return response.json()

Expand Down
63 changes: 52 additions & 11 deletions libs/phabricator-client/tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,17 +33,16 @@ def _client(api_key: str = VALID_TOKEN, **kwargs) -> PhabricatorClient:

def _capture_post(monkeypatch, payload: dict) -> dict:
"""Stub httpx.AsyncClient to return `payload`; return a dict capturing the call."""
captured: dict = {}
captured: dict = {"clients": []}

class _FakeAsyncClient:
def __init__(self, timeout=None):
captured["timeout"] = timeout
def __init__(self, **kwargs):
captured.update(kwargs)
captured["clients"].append(self)
self.closed = False

async def __aenter__(self):
return self

async def __aexit__(self, *exc):
return False
async def aclose(self):
self.closed = True

async def post(self, url, data=None):
captured["url"] = url
Expand Down Expand Up @@ -189,7 +188,7 @@ async def test_search_revisions_skips_the_call_when_nothing_to_look_up(monkeypat
captured = _capture_post(monkeypatch, {"result": {"data": []}})

assert await _client().search_revisions([]) == []
assert captured == {}
assert "url" not in captured


async def test_search_users_maps_phids_to_names(monkeypatch):
Expand Down Expand Up @@ -222,7 +221,7 @@ async def test_search_users_drops_non_user_phids(monkeypatch):
async def test_search_users_skips_call_when_nothing_to_resolve(monkeypatch):
captured = _capture_post(monkeypatch, {"result": {"data": []}})
assert await _client().search_users(["PHID-PROJ-1", None, ""]) == {}
assert captured == {} # no request was made
assert "url" not in captured # no request was made


async def test_get_project_members(monkeypatch):
Expand Down Expand Up @@ -343,7 +342,7 @@ async def test_resolve_commit_returns_full_hash_without_call(monkeypatch):
full = "9f2e8c25f0b40fdce8d2f2ca40281e8711815a6d"
captured = _capture_post(monkeypatch, {"result": {}})
assert await _client().resolve_commit(full) == full
assert captured == {} # no request was made
assert "url" not in captured # no request was made


async def test_resolve_commit_expands_abbreviated_hash(monkeypatch):
Expand Down Expand Up @@ -505,6 +504,48 @@ async def test_custom_timeout_is_passed(monkeypatch):
assert captured["timeout"] == 5


async def test_edge_key_is_sent_when_configured(monkeypatch):
captured = _capture_post(monkeypatch, {"result": {}})
await _client(edge_key="edge-secret").conduit_request("some.method")
assert captured["headers"] == {"Mozilla-Edge-Key": "edge-secret"}


async def test_no_edge_key_header_by_default(monkeypatch):
captured = _capture_post(monkeypatch, {"result": {}})
await _client().conduit_request("some.method")
assert captured["headers"] == {}


async def test_requests_share_one_http_client(monkeypatch):
captured = _capture_post(monkeypatch, {"result": {}})
client = _client()

await client.conduit_request("some.method")
await client.conduit_request("other.method")

assert len(captured["clients"]) == 1


async def test_context_manager_closes_http_client(monkeypatch):
captured = _capture_post(monkeypatch, {"result": {}})

async with _client() as client:
assert isinstance(client, PhabricatorClient)
await client.conduit_request("some.method")
assert not captured["clients"][0].closed

assert captured["clients"][0].closed


async def test_close_closes_http_client(monkeypatch):
captured = _capture_post(monkeypatch, {"result": {}})
client = _client()

await client.close()

assert captured["clients"][0].closed


def test_defaults_from_env_when_no_settings(monkeypatch):
# No settings passed -> PhabricatorSettings reads the PHABRICATOR_* env vars.
monkeypatch.setenv("PHABRICATOR_API_KEY", VALID_TOKEN)
Expand Down
9 changes: 3 additions & 6 deletions libs/phabricator-proxy/tests/test_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,14 +88,11 @@ def test_substitutes_the_proxys_own_conduit_token(monkeypatch):
captured: dict = {}

class _FakeAsyncClient:
def __init__(self, timeout=None):
def __init__(self, **kwargs):
pass

async def __aenter__(self):
return self

async def __aexit__(self, *exc):
return False
async def aclose(self):
pass

async def post(self, url, data=None):
captured["url"] = url
Expand Down
Loading