hackbot-client 0.1.0__py3-none-any.whl
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.
- hackbot_client/__init__.py +29 -0
- hackbot_client/client.py +215 -0
- hackbot_client/models.py +118 -0
- hackbot_client-0.1.0.dist-info/METADATA +11 -0
- hackbot_client-0.1.0.dist-info/RECORD +6 -0
- hackbot_client-0.1.0.dist-info/WHEEL +4 -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
|
+
]
|
hackbot_client/client.py
ADDED
|
@@ -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
|
hackbot_client/models.py
ADDED
|
@@ -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,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,6 @@
|
|
|
1
|
+
hackbot_client/__init__.py,sha256=QrzUfsr24DbEsGPP9x1Gh4qqHRo-hSKIWwI4LcV3cZs,527
|
|
2
|
+
hackbot_client/client.py,sha256=y583m_b0TKMmZ_Y9CFdHsmW4MU8f6wqG1f4UFJ4tr90,7781
|
|
3
|
+
hackbot_client/models.py,sha256=7fjXlVrnVM7c5FpXCCnMk6t8ZLBYTL9iVf0ww_vSJr4,3198
|
|
4
|
+
hackbot_client-0.1.0.dist-info/METADATA,sha256=9_RUhYsEaDfw7iajypLZI0kSnuxvwH6ljsfHea7OVto,361
|
|
5
|
+
hackbot_client-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
6
|
+
hackbot_client-0.1.0.dist-info/RECORD,,
|