Skip to content
Merged
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
11 changes: 6 additions & 5 deletions libs/bugzilla-client/bugzilla_client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ def __init__(self, settings: BugzillaSettings | None = None) -> None:
if self._settings.edge_key:
headers["Mozilla-Edge-Key"] = self._settings.edge_key
self._http = httpx.AsyncClient(
base_url=f"{self.base_url}/rest/",
base_url=f"{self.api_url}/",
headers=headers,
timeout=self._settings.timeout_seconds,
)
Expand All @@ -126,11 +126,12 @@ async def __aexit__(
await self.close()

@property
def base_url(self) -> str:
return self._settings.url.rstrip("/")
def api_url(self) -> str:
return self._settings.api_url.rstrip("/")

def bug_url(self, bug_id: int) -> str:
return f"{self.base_url}/show_bug.cgi?id={bug_id}"
site = self.api_url.removesuffix("/rest")
return f"{site}/show_bug.cgi?id={bug_id}"

@retry(
retry=_should_retry,
Expand All @@ -148,7 +149,7 @@ async def request(
params: dict[str, Any] | None = None,
json: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Call a REST endpoint (relative to ``/rest/``) and return its JSON body.
"""Call a REST endpoint (relative to ``api_url``) and return its JSON body.

Rate limits and gateway errors are retried with exponential backoff.
Reads are also retried on network errors; writes only when the
Expand Down
19 changes: 14 additions & 5 deletions libs/bugzilla-client/bugzilla_client/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,22 @@
``BugzillaSettings`` is a plain, validated config model with no env I/O, so it
can be embedded in a larger settings object without triggering a second
environment parse. Use :meth:`BugzillaSettings.from_env` for standalone,
env-driven config (``BUGZILLA_URL``, ``BUGZILLA_API_KEY``, ...).
env-driven config (``BUGZILLA_API_URL``, ``BUGZILLA_API_KEY``, ...). It also
accepts the site root as ``BUGZILLA_URL`` when ``BUGZILLA_API_URL`` is unset.
"""

from importlib.metadata import version
from typing import Annotated
from typing import Annotated, Self

from pydantic import BaseModel, Field
from pydantic import BaseModel, Field, model_validator
from pydantic_settings import BaseSettings, SettingsConfigDict


class BugzillaSettings(BaseModel):
# Bugzilla generates API keys as 40 random letters and digits.
api_key: Annotated[str, Field(min_length=40, max_length=40)]
# The site root, without ``/rest``; the client adds it for API calls.
url: str = "https://bugzilla.mozilla.org"
# The REST API base, used as is for API calls.
api_url: str = "https://bugzilla.mozilla.org/rest"
Comment thread
ayoubdiourin7 marked this conversation as resolved.
Resolved
timeout_seconds: float = 30
edge_key: str | None = None
user_agent: str = f"Bugbug-BugzillaClient/{version('bugzilla-client')}"
Expand All @@ -29,3 +30,11 @@ def from_env(cls) -> BugzillaSettings:

class _BugzillaEnvSettings(BugzillaSettings, BaseSettings):
model_config = SettingsConfigDict(env_prefix="BUGZILLA_", extra="ignore")
# The site root, as older configs set it; used when BUGZILLA_API_URL is unset.
url: str | None = None

@model_validator(mode="after")
def _api_url_from_site_root(self) -> Self:
if "api_url" not in self.model_fields_set and self.url:
self.api_url = self.url.rstrip("/") + "/rest"
return self
32 changes: 31 additions & 1 deletion libs/bugzilla-client/tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,39 @@ def _attachment(id: int, bug_id: int, **extra) -> dict:
}


@pytest.mark.parametrize(
("env", "api_url"),
[
(
{
"BUGZILLA_API_URL": "https://api.example.com/rest",
"BUGZILLA_URL": "https://site.example.com",
},
"https://api.example.com/rest",
),
(
{"BUGZILLA_URL": "https://site.example.com/"},
"https://site.example.com/rest",
),
({}, "https://bugzilla.mozilla.org/rest"),
],
ids=["api-url-wins", "site-root-fallback", "default"],
)
def test_from_env_reads_api_url_or_falls_back_to_site_root(monkeypatch, env, api_url):
monkeypatch.delenv("BUGZILLA_API_URL", raising=False)
monkeypatch.delenv("BUGZILLA_URL", raising=False)
monkeypatch.setenv("BUGZILLA_API_KEY", VALID_KEY)
for name, value in env.items():
monkeypatch.setenv(name, value)

assert BugzillaSettings.from_env().api_url == api_url


async def test_sends_auth_headers_and_uses_rest_base(bugzilla):
handler, requests = _recorder(httpx.Response(200, json={"version": "20260101.1"}))
client = bugzilla(handler, url="https://bugzilla.example.com", edge_key="edge")
client = bugzilla(
handler, api_url="https://bugzilla.example.com/rest", edge_key="edge"
)

assert await client.request("GET", "version") == {"version": "20260101.1"}

Expand Down