bugzilla-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.
@@ -0,0 +1,4 @@
1
+ from bugzilla_client.client import BugzillaClient, BugzillaError, BugzillaResponse
2
+ from bugzilla_client.config import BugzillaSettings
3
+
4
+ __all__ = ["BugzillaClient", "BugzillaError", "BugzillaResponse", "BugzillaSettings"]
@@ -0,0 +1,391 @@
1
+ """Small shared Bugzilla REST client.
2
+
3
+ A minimal ``httpx``-based client for the handful of calls hackbot makes, in
4
+ place of the mix of ``requests`` and raw ``httpx`` used today. It
5
+ deliberately avoids ``libmozdata``'s bulk, futures-oriented client, which suits
6
+ the bugbug data pipelines but not single-bug reads and writes from an event
7
+ loop.
8
+
9
+ Config is injected: pass a :class:`BugzillaSettings`, or let the client load
10
+ one from the environment (via ``BugzillaSettings.from_env``) when none is
11
+ provided. The API is asynchronous.
12
+
13
+ The client reuses one connection pool across requests. Close it when done,
14
+ either with ``async with`` or by calling :meth:`BugzillaClient.close`.
15
+ """
16
+
17
+ import base64
18
+ import logging
19
+ from collections.abc import Collection
20
+ from dataclasses import dataclass
21
+ from datetime import datetime
22
+ from types import TracebackType
23
+ from typing import Any, Self
24
+
25
+ import httpx
26
+ from tenacity import (
27
+ RetryCallState,
28
+ before_sleep_log,
29
+ retry,
30
+ stop_after_attempt,
31
+ wait_exponential_jitter,
32
+ )
33
+
34
+ from bugzilla_client.config import BugzillaSettings
35
+
36
+ log = logging.getLogger(__name__)
37
+
38
+
39
+ class BugzillaError(Exception):
40
+ """Bugzilla rejected a request, or answered with something that is not JSON.
41
+
42
+ ``code`` is Bugzilla's own error code (e.g. 101 "bug does not exist", 102
43
+ "access denied") when the response carried one.
44
+ """
45
+
46
+ def __init__(
47
+ self, message: str, *, code: int | None = None, status: int | None = None
48
+ ) -> None:
49
+ super().__init__(message)
50
+ self.message = message
51
+ self.code = code
52
+ self.status = status
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class BugzillaResponse:
57
+ """What a resource method returns; ``data`` is Bugzilla's JSON body.
58
+
59
+ A wrapper rather than the bare body, so typed results can be added later
60
+ without breaking callers.
61
+ """
62
+
63
+ data: dict[str, Any]
64
+
65
+
66
+ def _should_retry(state: RetryCallState) -> bool:
67
+ """Tenacity's retry check for ``request``: is the failed call worth resending?"""
68
+ exc = state.outcome.exception() if state.outcome else None
69
+ if exc is None:
70
+ return False
71
+ # ``request(self, method, path, /, ...)``: ``method`` is always positional.
72
+ is_read = state.args[1].upper() == "GET"
73
+ return _is_transient(exc, is_read=is_read)
74
+
75
+
76
+ def _is_transient(exc: BaseException, *, is_read: bool) -> bool:
77
+ """Whether a failed request is worth sending again.
78
+
79
+ A write is only resent when Bugzilla surely did not apply it: a rate limit,
80
+ or a connection that was never made. After a gateway error or a dropped
81
+ response the write may have landed, and resending could post a comment
82
+ twice.
83
+ """
84
+ if isinstance(exc, (httpx.ConnectError, httpx.ConnectTimeout)):
85
+ return True
86
+ if isinstance(exc, httpx.TransportError):
87
+ return is_read
88
+ # Rate limiting and gateway failures: the request was not processed.
89
+ if isinstance(exc, BugzillaError) and exc.status in {429, 502, 503, 504}:
90
+ return is_read or exc.status == 429
91
+ return False
92
+
93
+
94
+ class BugzillaClient:
95
+ def __init__(self, settings: BugzillaSettings | None = None) -> None:
96
+ self._settings = settings or BugzillaSettings.from_env()
97
+ headers = {
98
+ "X-Bugzilla-API-Key": self._settings.api_key,
99
+ "User-Agent": self._settings.user_agent,
100
+ }
101
+ if self._settings.edge_key:
102
+ headers["Mozilla-Edge-Key"] = self._settings.edge_key
103
+ self._http = httpx.AsyncClient(
104
+ base_url=f"{self.api_url}/",
105
+ headers=headers,
106
+ timeout=self._settings.timeout_seconds,
107
+ )
108
+ # One resource per section from the REST API docs.
109
+ self.bugs = _Bugs(self)
110
+ self.comments = _Comments(self)
111
+ self.attachments = _Attachments(self)
112
+ self.users = _Users(self)
113
+
114
+ async def close(self) -> None:
115
+ await self._http.aclose()
116
+
117
+ async def __aenter__(self) -> Self:
118
+ return self
119
+
120
+ async def __aexit__(
121
+ self,
122
+ exc_type: type[BaseException] | None,
123
+ exc: BaseException | None,
124
+ tb: TracebackType | None,
125
+ ) -> None:
126
+ await self.close()
127
+
128
+ @property
129
+ def api_url(self) -> str:
130
+ return self._settings.api_url.rstrip("/")
131
+
132
+ def bug_url(self, bug_id: int) -> str:
133
+ site = self.api_url.removesuffix("/rest")
134
+ return f"{site}/show_bug.cgi?id={bug_id}"
135
+
136
+ @retry(
137
+ retry=_should_retry,
138
+ stop=stop_after_attempt(4),
139
+ wait=wait_exponential_jitter(max=15),
140
+ before_sleep=before_sleep_log(log, logging.WARNING),
141
+ reraise=True,
142
+ )
143
+ async def request(
144
+ self,
145
+ method: str,
146
+ path: str,
147
+ /,
148
+ *,
149
+ params: dict[str, Any] | None = None,
150
+ json: dict[str, Any] | None = None,
151
+ ) -> dict[str, Any]:
152
+ """Call a REST endpoint (relative to ``api_url``) and return its JSON body.
153
+
154
+ Rate limits and gateway errors are retried with exponential backoff.
155
+ Reads are also retried on network errors; writes only when the
156
+ connection was never made, so a comment is never posted twice.
157
+
158
+ Raises :class:`BugzillaError` for a Bugzilla-level error or a non-JSON
159
+ answer (e.g. a misconfigured URL serving HTML).
160
+ """
161
+ response = await self._http.request(method, path, params=params, json=json)
162
+ return _parse(response)
163
+
164
+
165
+ class _Resource:
166
+ def __init__(self, client: BugzillaClient) -> None:
167
+ self._client = client
168
+
169
+
170
+ class _Bugs(_Resource):
171
+ """Bugzilla REST API: https://bmo.readthedocs.io/en/latest/api/core/v1/bug.html."""
172
+
173
+ async def get(
174
+ self, ids: Collection[int], *, include_fields: Collection[str] | None = None
175
+ ) -> BugzillaResponse:
176
+ """Fetch bugs by id in one request.
177
+
178
+ Bugs the API key cannot see are left out of the result rather than
179
+ failing the request, so callers must not assume one bug per id.
180
+ """
181
+ if not ids:
182
+ raise ValueError("ids must not be empty")
183
+ params: dict[str, Any] = {"id": ",".join(str(i) for i in ids)}
184
+ if include_fields:
185
+ params["include_fields"] = ",".join(include_fields)
186
+ result = await self._client.request("GET", "bug", params=params)
187
+ return BugzillaResponse(result)
188
+
189
+ async def search(
190
+ self,
191
+ params: dict[str, Any],
192
+ *,
193
+ include_fields: Collection[str] | None = None,
194
+ ) -> BugzillaResponse:
195
+ """Find bugs matching search criteria (``GET /bug``).
196
+
197
+ ``params`` are Bugzilla search fields, e.g.
198
+ ``{"product": "Core", "status": "NEW", "keywords": "regression"}``.
199
+ Results are capped by the server (10,000 by default); page with
200
+ ``limit`` and ``offset``. Use :meth:`get` when the ids are known.
201
+ ``include_fields`` overrides the same key in ``params``.
202
+ """
203
+ if include_fields:
204
+ params = {**params, "include_fields": ",".join(include_fields)}
205
+ result = await self._client.request("GET", "bug", params=params)
206
+ return BugzillaResponse(result)
207
+
208
+ async def create(self, fields: dict[str, Any]) -> BugzillaResponse:
209
+ """File a bug; Bugzilla answers ``{"id": ...}``."""
210
+ result = await self._client.request("POST", "bug", json=fields)
211
+ return BugzillaResponse(result)
212
+
213
+ async def update(self, bug_id: int, changes: dict[str, Any]) -> BugzillaResponse:
214
+ """Apply field changes and/or a comment in one ``PUT /bug/{id}``.
215
+
216
+ Bugzilla applies the whole body as a single transaction (one bugmail,
217
+ one history entry). Each entry in the answer's ``bugs`` lists what
218
+ actually changed in ``changes``; empty when every field already had
219
+ its value (a comment is not a change).
220
+
221
+ Updates one bug only: do not pass ``ids`` in ``changes``.
222
+ """
223
+ result = await self._client.request("PUT", f"bug/{bug_id}", json=changes)
224
+ return BugzillaResponse(result)
225
+
226
+
227
+ class _Comments(_Resource):
228
+ """Bugzilla REST API: https://bmo.readthedocs.io/en/latest/api/core/v1/comment.html."""
229
+
230
+ async def get(
231
+ self,
232
+ *,
233
+ bug_ids: Collection[int] = (),
234
+ comment_ids: Collection[int] = (),
235
+ new_since: datetime | None = None,
236
+ include_fields: Collection[str] | None = None,
237
+ skip_private: bool = False,
238
+ ) -> BugzillaResponse:
239
+ """Comments by bug and/or by comment id, fetched in one request.
240
+
241
+ Bugzilla answers ``{"bugs": {bug_id: {"comments": [...]}}, "comments":
242
+ {comment_id: comment}}``, keyed by id strings. ``new_since`` only filters the
243
+ comments of ``bug_ids``; ``skip_private`` skips bugs the API key cannot
244
+ see instead of failing.
245
+ """
246
+ if not bug_ids and not comment_ids:
247
+ raise ValueError("bug_ids or comment_ids must not be empty")
248
+ # The path takes one id, the rest go in the query. Ids are repeated
249
+ # (``ids=2&ids=3``): Bugzilla rejects comma-joined ids here.
250
+ params: dict[str, Any]
251
+ if bug_ids:
252
+ first, *rest = bug_ids
253
+ path = f"bug/{first}/comment"
254
+ params = {"ids": rest, "comment_ids": list(comment_ids)}
255
+ else:
256
+ first, *rest = comment_ids
257
+ path = f"bug/comment/{first}"
258
+ params = {"comment_ids": rest}
259
+ if new_since:
260
+ params["new_since"] = new_since.isoformat()
261
+ if include_fields:
262
+ params["include_fields"] = ",".join(include_fields)
263
+ if skip_private:
264
+ params["skip_private"] = 1
265
+ result = await self._client.request("GET", path, params=params)
266
+ return BugzillaResponse(result)
267
+
268
+
269
+ class _Attachments(_Resource):
270
+ """Bugzilla REST API: https://bmo.readthedocs.io/en/latest/api/core/v1/attachment.html."""
271
+
272
+ async def get(
273
+ self,
274
+ *,
275
+ bug_ids: Collection[int] = (),
276
+ attachment_ids: Collection[int] = (),
277
+ include_data: bool = False,
278
+ ) -> BugzillaResponse:
279
+ """Attachments by bug and/or by attachment id, fetched in one request.
280
+
281
+ Bugzilla answers ``{"bugs": {bug_id: [attachment, ...]}, "attachments":
282
+ {attachment_id: attachment}}``, keyed by id strings, without the
283
+ file content unless ``include_data``. BMO leaves unknown attachment
284
+ ids out of the result rather than failing.
285
+ """
286
+ if not bug_ids and not attachment_ids:
287
+ raise ValueError("bug_ids or attachment_ids must not be empty")
288
+ # The path takes one id, the rest go in the query. Ids are repeated
289
+ # (``ids=2&ids=3``): Bugzilla rejects comma-joined ids here.
290
+ if bug_ids:
291
+ first, *rest = bug_ids
292
+ path = f"bug/{first}/attachment"
293
+ params: dict[str, Any] = {
294
+ "ids": rest,
295
+ "attachment_ids": list(attachment_ids),
296
+ }
297
+ else:
298
+ first, *rest = attachment_ids
299
+ path = f"bug/attachment/{first}"
300
+ params = {"attachment_ids": rest}
301
+ if not include_data:
302
+ params["exclude_fields"] = "data"
303
+ result = await self._client.request("GET", path, params=params)
304
+ return BugzillaResponse(result)
305
+
306
+ async def create(
307
+ self, bug_id: int, data: bytes, fields: dict[str, Any]
308
+ ) -> BugzillaResponse:
309
+ """Attach a file to a bug.
310
+
311
+ Bugzilla answers ``{"attachments": {attachment_id: attachment}}``.
312
+
313
+ ``fields`` are the other Create Attachment fields, e.g. ``file_name``,
314
+ ``summary``, ``content_type``, ``is_patch`` or ``comment``. ``data`` is
315
+ the raw file content; it is base64-encoded here.
316
+ """
317
+ body = {
318
+ **fields,
319
+ "ids": [bug_id],
320
+ "data": base64.b64encode(data).decode("ascii"),
321
+ }
322
+ result = await self._client.request(
323
+ "POST", f"bug/{bug_id}/attachment", json=body
324
+ )
325
+ return BugzillaResponse(result)
326
+
327
+
328
+ class _Users(_Resource):
329
+ """Bugzilla REST API: https://bmo.readthedocs.io/en/latest/api/core/v1/user.html."""
330
+
331
+ async def get(
332
+ self,
333
+ *,
334
+ ids: Collection[int] = (),
335
+ names: Collection[str] = (),
336
+ match: Collection[str] = (),
337
+ limit: int | None = None,
338
+ group_ids: Collection[int] = (),
339
+ groups: Collection[str] = (),
340
+ include_disabled: bool = False,
341
+ permissive: bool = False,
342
+ ) -> BugzillaResponse:
343
+ """Users by id, login name, or a ``match`` search.
344
+
345
+ ``limit`` and ``include_disabled`` only apply to ``match``;
346
+ ``permissive`` reports unknown ``names`` in ``faults`` instead of
347
+ failing. ``group_ids`` and ``groups`` keep only members of any of them.
348
+ """
349
+ if not ids and not names and not match:
350
+ raise ValueError("ids, names or match must not be empty")
351
+ # Lists are repeated (``names=a&names=b``): Bugzilla rejects commas here.
352
+ params: dict[str, Any] = {
353
+ "ids": list(ids),
354
+ "names": list(names),
355
+ "match": list(match),
356
+ "group_ids": list(group_ids),
357
+ "groups": list(groups),
358
+ }
359
+ if limit is not None:
360
+ params["limit"] = limit
361
+ if include_disabled:
362
+ params["include_disabled"] = 1
363
+ if permissive:
364
+ params["permissive"] = 1
365
+ result = await self._client.request("GET", "user", params=params)
366
+ return BugzillaResponse(result)
367
+
368
+
369
+ def _parse(response: httpx.Response) -> dict[str, Any]:
370
+ """Return the JSON body, raising :class:`BugzillaError` for any error.
371
+
372
+ Bugzilla reports errors as ``{"error": true, "code": ..., "message": ...}``;
373
+ anything else that is not a JSON success (e.g. a proxy's HTML error page)
374
+ is reported by its HTTP status.
375
+ """
376
+ unexpected = (
377
+ f"Unexpected Bugzilla response: HTTP {response.status_code} "
378
+ f"for {response.request.url}"
379
+ )
380
+ try:
381
+ data = response.json()
382
+ except ValueError as exc:
383
+ raise BugzillaError(unexpected, status=response.status_code) from exc
384
+
385
+ if isinstance(data, dict) and data.get("error"):
386
+ raise BugzillaError(
387
+ data["message"], code=data["code"], status=response.status_code
388
+ )
389
+ if response.is_error or not isinstance(data, dict):
390
+ raise BugzillaError(unexpected, status=response.status_code)
391
+ return data
@@ -0,0 +1,40 @@
1
+ """Configuration for :class:`BugzillaClient`.
2
+
3
+ ``BugzillaSettings`` is a plain, validated config model with no env I/O, so it
4
+ can be embedded in a larger settings object without triggering a second
5
+ environment parse. Use :meth:`BugzillaSettings.from_env` for standalone,
6
+ env-driven config (``BUGZILLA_API_URL``, ``BUGZILLA_API_KEY``, ...). It also
7
+ accepts the site root as ``BUGZILLA_URL`` when ``BUGZILLA_API_URL`` is unset.
8
+ """
9
+
10
+ from importlib.metadata import version
11
+ from typing import Annotated, Self
12
+
13
+ from pydantic import BaseModel, Field, model_validator
14
+ from pydantic_settings import BaseSettings, SettingsConfigDict
15
+
16
+
17
+ class BugzillaSettings(BaseModel):
18
+ # Bugzilla generates API keys as 40 random letters and digits.
19
+ api_key: Annotated[str, Field(min_length=40, max_length=40)]
20
+ # The REST API base, used as is for API calls.
21
+ api_url: str = "https://bugzilla.mozilla.org/rest"
22
+ timeout_seconds: float = 30
23
+ edge_key: str | None = None
24
+ user_agent: str = f"Bugbug-BugzillaClient/{version('bugzilla-client')}"
25
+
26
+ @classmethod
27
+ def from_env(cls) -> BugzillaSettings:
28
+ return _BugzillaEnvSettings()
29
+
30
+
31
+ class _BugzillaEnvSettings(BugzillaSettings, BaseSettings):
32
+ model_config = SettingsConfigDict(env_prefix="BUGZILLA_", extra="ignore")
33
+ # The site root, as older configs set it; used when BUGZILLA_API_URL is unset.
34
+ url: str | None = None
35
+
36
+ @model_validator(mode="after")
37
+ def _api_url_from_site_root(self) -> Self:
38
+ if "api_url" not in self.model_fields_set and self.url:
39
+ self.api_url = self.url.rstrip("/") + "/rest"
40
+ return self
@@ -0,0 +1,8 @@
1
+ Metadata-Version: 2.5
2
+ Name: bugzilla-client
3
+ Version: 0.1.0
4
+ Summary: Small shared Bugzilla REST client (httpx-based)
5
+ Requires-Python: >=3.14
6
+ Requires-Dist: httpx>=0.26.0
7
+ Requires-Dist: pydantic-settings>=2.1.0
8
+ Requires-Dist: tenacity>=9.1.0
@@ -0,0 +1,6 @@
1
+ bugzilla_client/__init__.py,sha256=RDx99n99tzzfZoOmVl471JGbpwenZ8WAEF_KgnTO4hM,222
2
+ bugzilla_client/client.py,sha256=LbLGNUP97WSRDSX2yIoKmmOohQIpq8KVnMIQfbUYVQk,14381
3
+ bugzilla_client/config.py,sha256=5dsEau1t_bJmvd68_P0piLEZeepJbF-wAVeLxn4-sHI,1613
4
+ bugzilla_client-0.1.0.dist-info/METADATA,sha256=TyP_855VnJ0xFvFiIuIeU7epGIRZ4850xJ2jlC4NCHI,240
5
+ bugzilla_client-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
6
+ bugzilla_client-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any