hackbot-client 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,62 @@
1
+ *model
2
+ *model.zst
3
+ *model.zst.etag
4
+ *data_X
5
+ *data_y
6
+ *data_X.zst
7
+ *data_X.zst.etag
8
+ *data_y.zst
9
+ *data_y.zst.etag
10
+ feature_importance.png
11
+ importance.html
12
+ importances.json
13
+ metrics.json
14
+ probs.json
15
+ services/bugbug-api/models/*model*
16
+
17
+ data/
18
+ sheets/
19
+
20
+ .mypy_cache/
21
+ .pytest_cache/
22
+ *.pyc
23
+ .coverage
24
+
25
+ # Distribution / packaging
26
+ .Python
27
+ build/
28
+ develop-eggs/
29
+ dist/
30
+ downloads/
31
+ eggs/
32
+ .eggs/
33
+ lib/
34
+ lib64/
35
+ parts/
36
+ sdist/
37
+ var/
38
+ wheels/
39
+ pip-wheel-metadata/
40
+ share/python-wheels/
41
+ *.egg-info/
42
+ .installed.cfg
43
+ *.egg
44
+ MANIFEST
45
+ cache/
46
+ node_modules/
47
+
48
+ # Logs
49
+ *.log
50
+ # Desktop Service Store
51
+ *.DS_Store
52
+
53
+ # Local env files
54
+ .env
55
+ /services/bugbug-api/docker-compose.override.yml
56
+
57
+ # Local files
58
+ *.local.*
59
+
60
+ # Claude Code local state
61
+ .claude/worktrees/
62
+ .claude/.cc-writes/
@@ -0,0 +1,11 @@
1
+ Metadata-Version: 2.5
2
+ Name: hackbot-client
3
+ Version: 0.1.0
4
+ Summary: Small shared Hackbot API client (httpx-based)
5
+ Requires-Python: >=3.14
6
+ Requires-Dist: google-auth[requests]>=2.25.0
7
+ Requires-Dist: httpx>=0.26.0
8
+ Requires-Dist: pydantic>=2.6.0
9
+ Provides-Extra: dev
10
+ Requires-Dist: pytest-asyncio>=0.23.0; extra == 'dev'
11
+ Requires-Dist: pytest>=8.0.0; extra == 'dev'
@@ -0,0 +1,94 @@
1
+ # hackbot-client
2
+
3
+ A small async Python client for the Hackbot API. It lets you trigger
4
+ agent runs and apply the actions a run produced.
5
+
6
+ ## Installation
7
+
8
+ The package lives in this repository's uv workspace. To use it from another
9
+ workspace member, add it to that member's `pyproject.toml`:
10
+
11
+ ```toml
12
+ [project]
13
+ dependencies = [
14
+ "hackbot-client",
15
+ ]
16
+
17
+ [tool.uv.sources]
18
+ hackbot-client = { workspace = true }
19
+ ```
20
+
21
+ ## Authentication
22
+
23
+ `HackbotClient` picks the first available auth method, in this order:
24
+
25
+ 1. **API key** (deprecated): pass `api_key=...`. It is sent as the
26
+ `X-API-Key` header. API key auth will be removed soon, so do not use it in
27
+ new code.
28
+ 2. **Service account key file**: pass `key_file="/path/to/key.json"`. Useful
29
+ when running outside GCP.
30
+ 3. **GCP metadata server**: used when neither of the above is given, for
31
+ example on Cloud Run or GCE.
32
+
33
+ Service account ID tokens use `base_url` as their audience, so `base_url` must
34
+ match the URL the API server is configured with. The service account must also
35
+ be on the API's allowlist of service accounts, or requests are rejected with
36
+ HTTP 401.
37
+
38
+ ## Usage
39
+
40
+ ### Trigger a run
41
+
42
+ ```python
43
+ import asyncio
44
+
45
+ from hackbot_client import HackbotClient
46
+
47
+
48
+ async def main() -> None:
49
+ # Uses the GCP metadata server. Outside GCP, pass key_file="key.json".
50
+ async with HackbotClient() as client:
51
+ run = await client.trigger_run("my-agent", {"bug_id": 123456})
52
+ print(run.run_id, run.status, run.is_new)
53
+
54
+
55
+ asyncio.run(main())
56
+ ```
57
+
58
+ The inputs must match the agent's input schema, otherwise the API rejects the
59
+ request. `base_url` defaults to `https://hackbot-api.moz.tools`. Pass a
60
+ different value to target another deployment.
61
+
62
+ ### Avoid duplicate runs
63
+
64
+ Pass a `dedupe_key` to make triggering idempotent. The first request starts the
65
+ run and returns `is_new=True`. Later requests for the same agent with the same
66
+ key start nothing and return the same run with `is_new=False`.
67
+
68
+ ```python
69
+ run = await client.trigger_run(
70
+ "my-agent",
71
+ {"bug_id": 123456},
72
+ dedupe_key="bug-123456",
73
+ )
74
+ if not run.is_new:
75
+ print(f"Run {run.run_id} already exists")
76
+ ```
77
+
78
+ ### Apply a run's actions
79
+
80
+ `apply_actions` applies every action of a run that has not landed yet. It is
81
+ safe to call more than once. A successful call does not mean every action
82
+ landed, so check the result:
83
+
84
+ ```python
85
+ actions = await client.apply_actions(run.run_id)
86
+ if not actions.all_applied:
87
+ print(f"Some actions failed: {actions.failure_summary}")
88
+ ```
89
+
90
+ ## Errors
91
+
92
+ - `HackbotAPIError`: the request failed or the API returned a non-2xx status.
93
+ - `HackbotInvalidResponseError`: a subclass of `HackbotAPIError`, raised when
94
+ the API answered successfully but with a body that cannot be parsed.
@@ -0,0 +1 @@
1
+ 0.1.0
@@ -0,0 +1,29 @@
1
+ from hackbot_client.client import (
2
+ HackbotAPIError,
3
+ HackbotClient,
4
+ HackbotInvalidResponseError,
5
+ )
6
+ from hackbot_client.models import (
7
+ ApplyActionsResponse,
8
+ Identity,
9
+ IdentityProvider,
10
+ RunAction,
11
+ RunRef,
12
+ RunStatus,
13
+ Source,
14
+ TriggeredRun,
15
+ )
16
+
17
+ __all__ = [
18
+ "HackbotAPIError",
19
+ "HackbotClient",
20
+ "HackbotInvalidResponseError",
21
+ "Identity",
22
+ "IdentityProvider",
23
+ "Source",
24
+ "RunAction",
25
+ "ApplyActionsResponse",
26
+ "RunRef",
27
+ "RunStatus",
28
+ "TriggeredRun",
29
+ ]
@@ -0,0 +1,215 @@
1
+ """Small async client for the public Hackbot API."""
2
+
3
+ import asyncio
4
+ from collections.abc import Mapping
5
+ from types import TracebackType
6
+ from typing import Any, Self
7
+ from urllib.parse import quote
8
+ from uuid import UUID
9
+
10
+ import httpx
11
+ from google.auth import compute_engine, credentials
12
+ from google.auth.transport import requests as google_requests
13
+ from google.oauth2 import service_account
14
+ from pydantic import ValidationError
15
+
16
+ from hackbot_client.models import (
17
+ ApplyActionsResponse,
18
+ Identity,
19
+ Source,
20
+ TriggeredRun,
21
+ )
22
+
23
+
24
+ class HackbotAPIError(Exception):
25
+ """A request to the Hackbot API failed (or answered with something unusable)."""
26
+
27
+
28
+ class HackbotInvalidResponseError(HackbotAPIError):
29
+ """The Hackbot API answered successfully, but with a body that is unusable."""
30
+
31
+
32
+ class HackbotClient:
33
+ """Call the public Hackbot API with either API key or service account auth."""
34
+
35
+ def __init__(
36
+ self,
37
+ base_url: str = "https://hackbot-api.moz.tools",
38
+ api_key: str = "",
39
+ key_file: str = "",
40
+ timeout_seconds: float = 30.0,
41
+ ) -> None:
42
+ """Initialize the client.
43
+
44
+ Auth is picked in this order: API key, service account key file, then
45
+ the GCP metadata server. Service account tokens use `base_url` as
46
+ their audience.
47
+
48
+ Args:
49
+ base_url: Base URL of the Hackbot API
50
+ api_key: API key for legacy authentication (optional)
51
+ key_file: Path to a service account key file, for running outside
52
+ GCP without a metadata server (optional)
53
+ timeout_seconds: HTTP request timeout
54
+ """
55
+ self._base_url = base_url.rstrip("/")
56
+ self._api_key = api_key
57
+ self._key_file = key_file
58
+ self._http = httpx.AsyncClient(timeout=timeout_seconds)
59
+ self._credentials: credentials.Credentials | None = None
60
+
61
+ async def close(self) -> None:
62
+ await self._http.aclose()
63
+
64
+ async def __aenter__(self) -> Self:
65
+ return self
66
+
67
+ async def __aexit__(
68
+ self,
69
+ exc_type: type[BaseException] | None,
70
+ exc: BaseException | None,
71
+ tb: TracebackType | None,
72
+ ) -> None:
73
+ await self.close()
74
+
75
+ def _refresh_credentials(self) -> None:
76
+ request = google_requests.Request()
77
+ if self._credentials is None:
78
+ if self._key_file:
79
+ self._credentials = (
80
+ service_account.IDTokenCredentials.from_service_account_file(
81
+ self._key_file, target_audience=self._base_url
82
+ )
83
+ )
84
+ else:
85
+ self._credentials = compute_engine.IDTokenCredentials(
86
+ request,
87
+ target_audience=self._base_url,
88
+ use_metadata_identity_endpoint=True,
89
+ )
90
+ self._credentials.refresh(request)
91
+
92
+ async def _get_headers(self) -> dict[str, str]:
93
+ """Return auth headers: API key or service account token."""
94
+ if self._api_key:
95
+ return {"X-API-Key": self._api_key}
96
+
97
+ if (
98
+ self._credentials is None
99
+ or self._credentials.token_state == credentials.TokenState.INVALID
100
+ ):
101
+ await asyncio.to_thread(self._refresh_credentials)
102
+ return {"Authorization": f"Bearer {self._credentials.token}"}
103
+
104
+ async def trigger_run(
105
+ self,
106
+ agent_name: str,
107
+ inputs: Mapping[str, Any],
108
+ *,
109
+ on_behalf_of: str | None = None,
110
+ dedupe_key: str | None = None,
111
+ source: Source | None = None,
112
+ identity: Identity | None = None,
113
+ ) -> TriggeredRun:
114
+ """Create an agent run and return the API's typed run reference.
115
+
116
+ `source` is where the run was triggered from, and `identity` is the
117
+ person who triggered it.
118
+
119
+ `dedupe_key` keys the work the run does, and a key belongs to one run
120
+ for good: repeated triggers carrying it are no-ops, answered with the
121
+ same run reference and `is_new=False`.
122
+ """
123
+ headers = await self._get_headers()
124
+ if on_behalf_of is not None:
125
+ headers["X-On-Behalf-Of"] = on_behalf_of
126
+
127
+ if source is not None:
128
+ headers["Hackbot-Source"] = source.value
129
+ if identity is not None:
130
+ headers["Hackbot-Requester-Identity-Provider"] = (
131
+ identity.identity_provider.value
132
+ )
133
+ headers["Hackbot-Requester-Id"] = identity.user_id
134
+ if identity.username is not None:
135
+ # Headers are ASCII-only, so the name is percent-encoded.
136
+ headers["Hackbot-Requester-Username"] = quote(identity.username)
137
+
138
+ params = {} if dedupe_key is None else {"dedupe_key": dedupe_key}
139
+
140
+ try:
141
+ response = await self._http.post(
142
+ f"{self._base_url}/agents/{agent_name}/runs",
143
+ json=dict(inputs),
144
+ headers=headers,
145
+ params=params,
146
+ )
147
+ except httpx.HTTPError as exc:
148
+ raise HackbotAPIError(f"Hackbot API request failed: {exc}") from exc
149
+
150
+ if not response.is_success:
151
+ raise HackbotAPIError(
152
+ f"Hackbot API returned HTTP {response.status_code} "
153
+ f"({response.reason_phrase}) for {response.request.url}"
154
+ )
155
+
156
+ try:
157
+ body = response.json()
158
+ except ValueError as exc:
159
+ raise HackbotInvalidResponseError(
160
+ f"Hackbot API returned an invalid run (HTTP {response.status_code}): "
161
+ "the body is not JSON"
162
+ ) from exc
163
+
164
+ if not isinstance(body, dict):
165
+ raise HackbotInvalidResponseError(
166
+ f"Hackbot API returned an invalid run (HTTP {response.status_code}): "
167
+ "the body is not an object"
168
+ )
169
+
170
+ # The API distinguishes the two outcomes only by status code: `201` for the
171
+ # run this request started, `200` for one a `dedupe_key` collapsed onto.
172
+ try:
173
+ return TriggeredRun.model_validate(
174
+ {**body, "is_new": response.status_code == 201}
175
+ )
176
+ except ValidationError as exc:
177
+ raise HackbotInvalidResponseError(
178
+ f"Hackbot API returned an invalid run (HTTP {response.status_code})"
179
+ ) from exc
180
+
181
+ async def apply_actions(self, run_id: str | UUID) -> ApplyActionsResponse:
182
+ """Apply every one of a run's actions that has not landed yet.
183
+
184
+ Idempotent, because the API skips rows already marked applied: calling
185
+ this on a run whose actions all landed is a no-op.
186
+ """
187
+ try:
188
+ response = await self._http.post(
189
+ f"{self._base_url}/runs/{run_id}/actions/apply",
190
+ headers=await self._get_headers(),
191
+ )
192
+ except httpx.HTTPError as exc:
193
+ raise HackbotAPIError(f"Hackbot API request failed: {exc}") from exc
194
+
195
+ if not response.is_success:
196
+ raise HackbotAPIError(
197
+ f"Hackbot API returned HTTP {response.status_code} "
198
+ f"({response.reason_phrase}) for {response.request.url}"
199
+ )
200
+
201
+ try:
202
+ body = response.json()
203
+ except ValueError as exc:
204
+ raise HackbotInvalidResponseError(
205
+ "Hackbot API returned an invalid action list "
206
+ f"(HTTP {response.status_code}): the body is not JSON"
207
+ ) from exc
208
+
209
+ try:
210
+ return ApplyActionsResponse.model_validate(body)
211
+ except ValidationError as exc:
212
+ raise HackbotInvalidResponseError(
213
+ "Hackbot API returned an invalid action list "
214
+ f"(HTTP {response.status_code})"
215
+ ) from exc
@@ -0,0 +1,118 @@
1
+ """Typed models for the public Hackbot API contract."""
2
+
3
+ from datetime import datetime
4
+ from enum import Enum
5
+ from typing import Any
6
+ from uuid import UUID
7
+
8
+ from pydantic import BaseModel, RootModel
9
+
10
+ # Duplicated in services/hackbot-api/app/schemas.py; keep these models in sync.
11
+
12
+
13
+ class RunStatus(str, Enum):
14
+ pending = "pending"
15
+ running = "running"
16
+ succeeded = "succeeded"
17
+ failed = "failed"
18
+ timed_out = "timed_out"
19
+
20
+
21
+ class Source(str, Enum):
22
+ """Where a run was triggered from."""
23
+
24
+ ui = "ui"
25
+ bugzilla = "bugzilla"
26
+ phabricator = "phabricator"
27
+ github = "github"
28
+ slack = "slack"
29
+
30
+
31
+ class IdentityProvider(str, Enum):
32
+ """The service an account's identity belongs to."""
33
+
34
+ google = "google"
35
+ bugzilla = "bugzilla"
36
+ phabricator = "phabricator"
37
+ github = "github"
38
+ slack = "slack"
39
+
40
+
41
+ class Identity(BaseModel):
42
+ """A person on an identity provider, such as a Bugzilla or GitHub user.
43
+
44
+ `user_id` is their stable ID there. `username` is their readable name,
45
+ which they can change.
46
+ """
47
+
48
+ identity_provider: IdentityProvider
49
+ user_id: str
50
+ username: str | None = None
51
+
52
+
53
+ class RunRef(BaseModel):
54
+ run_id: UUID
55
+ agent: str
56
+ status: RunStatus
57
+
58
+
59
+ class TriggeredRun(RunRef):
60
+ """The run a trigger resolved to, and whether that request is what started it.
61
+
62
+ `is_new` is a property of the request rather than of the run, and says
63
+ nothing about the run's `status`: the same run is `is_new` to the request
64
+ that created it and not to every later request carrying its `dedupe_key`.
65
+ That is why it is not on the API's own `RunRef`. Subclasses `RunRef` so a
66
+ caller that only wants the run keeps reading `run_id` off it unchanged.
67
+ """
68
+
69
+ is_new: bool
70
+
71
+
72
+ class RunAction(BaseModel):
73
+ """One recorded action of a run, and whether it has landed.
74
+
75
+ Mirrors the API's `RunActionDoc`. `status` is `"applied"` or `"failed"`:
76
+ the apply endpoint answers `200` for a pass that ran, not for a pass whose
77
+ every action succeeded, so a caller that needs the actions to have *landed*
78
+ has to read this rather than the status code.
79
+ """
80
+
81
+ idx: int
82
+ type: str
83
+ params: dict[str, Any]
84
+ ref: str | None = None
85
+ status: str
86
+ result: dict[str, Any] | None = None
87
+ error: str | None = None
88
+ applied_at: datetime | None = None
89
+
90
+ @property
91
+ def is_applied(self) -> bool:
92
+ return self.status == "applied"
93
+
94
+ def __str__(self) -> str:
95
+ return self.type if self.is_applied else f"{self.type} ({self.error})"
96
+
97
+
98
+ class ApplyActionsResponse(RootModel[list[RunAction]]):
99
+ """A run's actions and their apply state, as the API returns them."""
100
+
101
+ def __iter__(self):
102
+ return iter(self.root)
103
+
104
+ def __len__(self) -> int:
105
+ return len(self.root)
106
+
107
+ @property
108
+ def unapplied(self) -> list[RunAction]:
109
+ return [action for action in self.root if not action.is_applied]
110
+
111
+ @property
112
+ def all_applied(self) -> bool:
113
+ return not self.unapplied
114
+
115
+ @property
116
+ def failure_summary(self) -> str:
117
+ """The actions that did not land, with the reason each gave."""
118
+ return "; ".join(str(action) for action in self.unapplied)
@@ -0,0 +1,28 @@
1
+ [project]
2
+ name = "hackbot-client"
3
+ dynamic = ["version"]
4
+ description = "Small shared Hackbot API client (httpx-based)"
5
+ requires-python = ">=3.14"
6
+ dependencies = [
7
+ "google-auth[requests]>=2.25.0",
8
+ "httpx>=0.26.0",
9
+ "pydantic>=2.6.0",
10
+ ]
11
+
12
+ [project.optional-dependencies]
13
+ dev = ["pytest>=8.0.0", "pytest-asyncio>=0.23.0"]
14
+
15
+ [build-system]
16
+ requires = ["hatchling"]
17
+ build-backend = "hatchling.build"
18
+
19
+ [tool.hatch.version]
20
+ path = "VERSION"
21
+ pattern = "(?P<version>.+)"
22
+
23
+ [tool.hatch.build.targets.wheel]
24
+ packages = ["hackbot_client"]
25
+
26
+ [tool.pytest.ini_options]
27
+ asyncio_mode = "auto"
28
+ testpaths = ["tests"]
@@ -0,0 +1,403 @@
1
+ """Tests for the shared Hackbot client."""
2
+
3
+ from uuid import UUID
4
+
5
+ import httpx
6
+ import pytest
7
+ from hackbot_client import (
8
+ HackbotAPIError,
9
+ HackbotClient,
10
+ HackbotInvalidResponseError,
11
+ Identity,
12
+ IdentityProvider,
13
+ RunStatus,
14
+ Source,
15
+ )
16
+ from hackbot_client import client as client_module
17
+
18
+ RUN_ID = "d3d5f21d-d716-4bb0-a812-8c9ef3e2f1c6"
19
+
20
+
21
+ def _client(**kwargs) -> HackbotClient:
22
+ defaults = {
23
+ "base_url": "https://hackbot.example",
24
+ "api_key": "secret",
25
+ }
26
+ defaults.update(kwargs)
27
+ return HackbotClient(**defaults)
28
+
29
+
30
+ async def test_context_manager_closes_client():
31
+ client = _client()
32
+
33
+ async with client as entered:
34
+ assert entered is client
35
+ assert not client._http.is_closed
36
+
37
+ assert client._http.is_closed
38
+
39
+
40
+ async def test_context_manager_closes_client_on_error():
41
+ client = _client()
42
+ error = ValueError("Something went wrong")
43
+
44
+ with pytest.raises(ValueError) as exc_info:
45
+ async with client:
46
+ raise error
47
+
48
+ assert exc_info.value is error
49
+ assert client._http.is_closed
50
+
51
+
52
+ def _capture_post(monkeypatch, response: httpx.Response) -> dict:
53
+ """Stub httpx.AsyncClient to answer with ``response`` and capture the call."""
54
+ captured: dict = {}
55
+
56
+ class _FakeAsyncClient:
57
+ def __init__(self, timeout=None):
58
+ captured["timeout"] = timeout
59
+ captured["instances"] = captured.get("instances", 0) + 1
60
+
61
+ async def aclose(self):
62
+ captured["closed"] = True
63
+
64
+ async def post(self, url, json=None, headers=None, params=None):
65
+ captured.update(url=url, json=json, headers=headers, params=params)
66
+ response.request = httpx.Request("POST", url)
67
+ return response
68
+
69
+ monkeypatch.setattr(client_module.httpx, "AsyncClient", _FakeAsyncClient)
70
+ return captured
71
+
72
+
73
+ def _unreachable(monkeypatch) -> None:
74
+ """Stub httpx.AsyncClient so that every request fails before any answer."""
75
+
76
+ class _UnreachableAsyncClient:
77
+ def __init__(self, timeout=None):
78
+ pass
79
+
80
+ async def __aenter__(self):
81
+ return self
82
+
83
+ async def __aexit__(self, *exc):
84
+ return False
85
+
86
+ async def post(self, url, **kwargs):
87
+ raise httpx.ConnectError("connection refused")
88
+
89
+ monkeypatch.setattr(client_module.httpx, "AsyncClient", _UnreachableAsyncClient)
90
+
91
+
92
+ async def test_trigger_run_posts_inputs_and_returns_typed_reference(monkeypatch):
93
+ captured = _capture_post(
94
+ monkeypatch,
95
+ httpx.Response(
96
+ 201,
97
+ json={"run_id": RUN_ID, "agent": "bug-fix", "status": "pending"},
98
+ ),
99
+ )
100
+
101
+ run = await _client(base_url="https://hackbot.example/").trigger_run(
102
+ "bug-fix", {"bug_id": 1234}, on_behalf_of="user@example.com"
103
+ )
104
+
105
+ assert run.run_id == UUID(RUN_ID)
106
+ assert run.agent == "bug-fix"
107
+ assert run.status is RunStatus.pending
108
+ # `201`: this request is what started it.
109
+ assert run.is_new is True
110
+ assert captured == {
111
+ "timeout": 30.0,
112
+ "instances": 1,
113
+ "url": "https://hackbot.example/agents/bug-fix/runs",
114
+ "json": {"bug_id": 1234},
115
+ "headers": {
116
+ "X-API-Key": "secret",
117
+ "X-On-Behalf-Of": "user@example.com",
118
+ },
119
+ # No key means no client-assigned id on the create call.
120
+ "params": {},
121
+ }
122
+
123
+
124
+ async def test_trigger_run_omits_attribution_when_not_provided(monkeypatch):
125
+ captured = _capture_post(
126
+ monkeypatch,
127
+ httpx.Response(
128
+ 201,
129
+ json={"run_id": RUN_ID, "agent": "bug-fix", "status": "pending"},
130
+ ),
131
+ )
132
+
133
+ await _client().trigger_run("bug-fix", {"bug_id": 1234})
134
+
135
+ assert captured["headers"] == {"X-API-Key": "secret"}
136
+
137
+
138
+ async def test_trigger_run_sends_who_triggered_the_run_and_from_where(monkeypatch):
139
+ captured = _capture_post(
140
+ monkeypatch,
141
+ httpx.Response(
142
+ 201,
143
+ json={"run_id": RUN_ID, "agent": "bug-fix", "status": "pending"},
144
+ ),
145
+ )
146
+
147
+ await _client().trigger_run(
148
+ "bug-fix",
149
+ {"bug_id": 1234},
150
+ source=Source.bugzilla,
151
+ identity=Identity(
152
+ identity_provider=IdentityProvider.bugzilla,
153
+ user_id="560562",
154
+ username="josé",
155
+ ),
156
+ )
157
+
158
+ assert captured["headers"] == {
159
+ "X-API-Key": "secret",
160
+ "Hackbot-Source": "bugzilla",
161
+ "Hackbot-Requester-Identity-Provider": "bugzilla",
162
+ "Hackbot-Requester-Id": "560562",
163
+ "Hackbot-Requester-Username": "jos%C3%A9",
164
+ }
165
+
166
+
167
+ async def test_trigger_run_raises_for_http_errors(monkeypatch):
168
+ _capture_post(monkeypatch, httpx.Response(401, json={"detail": "Invalid API key"}))
169
+
170
+ with pytest.raises(HackbotAPIError, match="HTTP 401"):
171
+ await _client().trigger_run("bug-fix", {"bug_id": 1234})
172
+
173
+
174
+ async def test_trigger_run_raises_when_the_api_is_unreachable(monkeypatch):
175
+ _unreachable(monkeypatch)
176
+
177
+ with pytest.raises(HackbotAPIError, match="Hackbot API request failed"):
178
+ await _client().trigger_run("bug-fix", {"bug_id": 1234})
179
+
180
+
181
+ async def test_trigger_run_rejects_an_invalid_success_response(monkeypatch):
182
+ _capture_post(monkeypatch, httpx.Response(201, json={"run_id": RUN_ID}))
183
+
184
+ with pytest.raises(HackbotInvalidResponseError, match=r"invalid run \(HTTP 201\)"):
185
+ await _client().trigger_run("bug-fix", {"bug_id": 1234})
186
+
187
+
188
+ async def test_trigger_run_rejects_a_success_response_that_is_not_an_object(
189
+ monkeypatch,
190
+ ):
191
+ _capture_post(monkeypatch, httpx.Response(201, json=[]))
192
+
193
+ with pytest.raises(HackbotInvalidResponseError, match="not an object"):
194
+ await _client().trigger_run("bug-fix", {"bug_id": 1234})
195
+
196
+
197
+ async def test_trigger_run_rejects_a_success_response_that_is_not_json(monkeypatch):
198
+ _capture_post(monkeypatch, httpx.Response(201, text="<html>oops</html>"))
199
+
200
+ with pytest.raises(HackbotInvalidResponseError, match="not JSON"):
201
+ await _client().trigger_run("bug-fix", {"bug_id": 1234})
202
+
203
+
204
+ async def test_trigger_run_reports_a_deduplicated_run_as_not_new(monkeypatch):
205
+ # `200` rather than `201`: the key already belonged to this run, so the
206
+ # request that got this answer started nothing.
207
+ _capture_post(
208
+ monkeypatch,
209
+ httpx.Response(
210
+ 200,
211
+ json={"run_id": RUN_ID, "agent": "bug-fix", "status": "running"},
212
+ ),
213
+ )
214
+
215
+ run = await _client().trigger_run(
216
+ "bug-fix", {"bug_id": 1234}, dedupe_key="push:autoland:abc123"
217
+ )
218
+
219
+ assert run.run_id == UUID(RUN_ID)
220
+ assert run.is_new is False
221
+
222
+
223
+ async def test_trigger_run_sends_the_dedupe_key_as_a_query_parameter(monkeypatch):
224
+ captured = _capture_post(
225
+ monkeypatch,
226
+ httpx.Response(
227
+ 201,
228
+ json={"run_id": RUN_ID, "agent": "bug-fix", "status": "pending"},
229
+ ),
230
+ )
231
+
232
+ await _client().trigger_run(
233
+ "bug-fix", {"bug_id": 1234}, dedupe_key="push:autoland:abc123"
234
+ )
235
+
236
+ assert captured["params"] == {"dedupe_key": "push:autoland:abc123"}
237
+
238
+
239
+ async def test_one_client_reuses_a_single_http_client(monkeypatch):
240
+ captured = _capture_post(monkeypatch, httpx.Response(200, json=[]))
241
+
242
+ client = _client()
243
+ await client.apply_actions(RUN_ID)
244
+ await client.apply_actions(RUN_ID)
245
+ await client.close()
246
+
247
+ assert captured["instances"] == 1
248
+ assert captured["closed"] is True
249
+
250
+
251
+ async def test_apply_actions_posts_to_the_runs_apply_endpoint(monkeypatch):
252
+ captured = _capture_post(monkeypatch, httpx.Response(200, json=[]))
253
+
254
+ await _client(base_url="https://hackbot.example/").apply_actions(RUN_ID)
255
+
256
+ assert captured["url"] == f"https://hackbot.example/runs/{RUN_ID}/actions/apply"
257
+ assert captured["headers"] == {"X-API-Key": "secret"}
258
+
259
+
260
+ async def test_apply_actions_returns_each_action_with_its_state(monkeypatch):
261
+ _capture_post(
262
+ monkeypatch,
263
+ httpx.Response(
264
+ 200,
265
+ json=[
266
+ {
267
+ "idx": 0,
268
+ "type": "bugzilla.add_comment",
269
+ "params": {},
270
+ "status": "applied",
271
+ },
272
+ {
273
+ "idx": 1,
274
+ "type": "slack.post_message",
275
+ "params": {},
276
+ "status": "failed",
277
+ "error": "channel_not_found",
278
+ },
279
+ ],
280
+ ),
281
+ )
282
+
283
+ actions = await _client().apply_actions(RUN_ID)
284
+
285
+ # The response type, not a list the caller has to interrogate: whether the
286
+ # actions landed is the one thing the `200` does not say.
287
+ assert len(actions) == 2
288
+ assert [a.type for a in actions] == ["bugzilla.add_comment", "slack.post_message"]
289
+ assert actions.all_applied is False
290
+ assert [a.type for a in actions.unapplied] == ["slack.post_message"]
291
+ assert actions.failure_summary == "slack.post_message (channel_not_found)"
292
+
293
+
294
+ async def test_apply_actions_reports_a_clean_pass_as_all_applied(monkeypatch):
295
+ _capture_post(
296
+ monkeypatch,
297
+ httpx.Response(
298
+ 200,
299
+ json=[
300
+ {
301
+ "idx": 0,
302
+ "type": "bugzilla.add_comment",
303
+ "params": {},
304
+ "status": "applied",
305
+ },
306
+ {
307
+ "idx": 1,
308
+ "type": "slack.post_message",
309
+ "params": {},
310
+ "status": "applied",
311
+ },
312
+ ],
313
+ ),
314
+ )
315
+
316
+ actions = await _client().apply_actions(RUN_ID)
317
+
318
+ assert actions.all_applied is True
319
+ assert actions.unapplied == []
320
+ assert actions.failure_summary == ""
321
+
322
+
323
+ async def test_apply_actions_on_a_run_with_no_actions_is_all_applied(monkeypatch):
324
+ # Vacuously true, and the caller should read it that way: nothing failed.
325
+ _capture_post(monkeypatch, httpx.Response(200, json=[]))
326
+
327
+ actions = await _client().apply_actions(RUN_ID)
328
+
329
+ assert len(actions) == 0
330
+ assert actions.all_applied is True
331
+
332
+
333
+ async def test_apply_actions_raises_for_http_errors(monkeypatch):
334
+ _capture_post(monkeypatch, httpx.Response(404, json={"detail": "Run not found"}))
335
+
336
+ with pytest.raises(HackbotAPIError, match="HTTP 404"):
337
+ await _client().apply_actions(RUN_ID)
338
+
339
+
340
+ async def test_apply_actions_raises_when_the_api_is_unreachable(monkeypatch):
341
+ _unreachable(monkeypatch)
342
+
343
+ with pytest.raises(HackbotAPIError, match="Hackbot API request failed"):
344
+ await _client().apply_actions(RUN_ID)
345
+
346
+
347
+ async def test_apply_actions_rejects_an_invalid_success_response(monkeypatch):
348
+ _capture_post(
349
+ monkeypatch,
350
+ httpx.Response(200, json=[{"idx": 0, "type": "bugzilla.add_comment"}]),
351
+ )
352
+
353
+ with pytest.raises(
354
+ HackbotInvalidResponseError, match=r"invalid action list \(HTTP 200\)"
355
+ ):
356
+ await _client().apply_actions(RUN_ID)
357
+
358
+
359
+ async def test_apply_actions_rejects_a_success_response_that_is_not_json(monkeypatch):
360
+ _capture_post(monkeypatch, httpx.Response(200, text="<html>oops</html>"))
361
+
362
+ with pytest.raises(HackbotInvalidResponseError, match="not JSON"):
363
+ await _client().apply_actions(RUN_ID)
364
+
365
+
366
+ async def test_trigger_run_with_service_account_auth(monkeypatch):
367
+ """Client mints a Bearer token from the key file, audience is base_url."""
368
+ captured = _capture_post(
369
+ monkeypatch,
370
+ httpx.Response(
371
+ 201,
372
+ json={"run_id": RUN_ID, "agent": "bug-fix", "status": "pending"},
373
+ ),
374
+ )
375
+
376
+ class _FakeCredentials:
377
+ token = None
378
+
379
+ @property
380
+ def token_state(self):
381
+ if self.token is None:
382
+ return client_module.credentials.TokenState.INVALID
383
+ return client_module.credentials.TokenState.FRESH
384
+
385
+ def refresh(self, request):
386
+ self.token = "fake.jwt.token"
387
+
388
+ def mock_from_service_account_file(filename, target_audience):
389
+ captured.update(filename=filename, audience=target_audience)
390
+ return _FakeCredentials()
391
+
392
+ monkeypatch.setattr(
393
+ client_module.service_account.IDTokenCredentials,
394
+ "from_service_account_file",
395
+ mock_from_service_account_file,
396
+ )
397
+
398
+ client = _client(api_key="", key_file="/path/key.json")
399
+ await client.trigger_run("bug-fix", {"bug_id": 1234})
400
+
401
+ assert captured["filename"] == "/path/key.json"
402
+ assert captured["audience"] == "https://hackbot.example"
403
+ assert captured["headers"] == {"Authorization": "Bearer fake.jwt.token"}