Skip to content
Open
Show file tree
Hide file tree
Changes from 2 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
4 changes: 4 additions & 0 deletions libs/lando-client/lando_client/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,18 @@
PATCH_FORMAT_HG,
LandoAPIError,
LandoClient,
LandoRequestError,
LandoUnavailableError,
encode_patch,
)
from lando_client.config import LandoSettings

__all__ = [
"LandoAPIError",
"LandoClient",
"LandoRequestError",
"LandoSettings",
"LandoUnavailableError",
"PATCH_FORMAT_GIT",
"PATCH_FORMAT_HG",
"encode_patch",
Expand Down
191 changes: 134 additions & 57 deletions libs/lando-client/lando_client/client.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,30 @@
"""Small shared Lando API client."""
"""Small shared Lando API client.

Config is injected: pass a :class:`LandoSettings`, or let the client load one
from the environment when none is provided. The API is asynchronous.

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

import base64
import logging
from types import TracebackType
from typing import Any, Self

import httpx
from tenacity import (
RetryCallState,
before_sleep_log,
retry,
stop_after_attempt,
wait_exponential_jitter,
)

from lando_client.config import LandoSettings

log = logging.getLogger(__name__)

TREEHERDER_URL = "https://treeherder.mozilla.org"

# The patch formats Lando accepts (`PatchFormat` in lando.main.scm.helpers).
Expand All @@ -16,6 +35,34 @@
class LandoAPIError(Exception):
"""Lando rejected a request (or answered with something unusable)."""

def __init__(self, message: str, *, status: int | None = None) -> None:
super().__init__(message)
self.status = status


class LandoRequestError(LandoAPIError):
"""A 4xx: the request is wrong (bad input, token, permission); resending fails too."""


class LandoUnavailableError(LandoAPIError):
"""A 5xx or a rate limit: Lando could not handle the request now, e.g. while deploying."""


def _should_retry(state: RetryCallState) -> bool:
exc = state.outcome.exception() if state.outcome else None
return exc is not None and _never_reached_lando(exc)


def _never_reached_lando(exc: BaseException) -> bool:
"""Whether resending is safe: Lando surely did not act on the request.

Lando answers 503 while it deploys. After a 500, 502 or 504 the job may have
been created, and resending could queue a second backout.
"""
if isinstance(exc, (httpx.ConnectError, httpx.ConnectTimeout)):
return True
return isinstance(exc, LandoUnavailableError) and exc.status in {429, 503}


def encode_patch(patch: bytes) -> str:
"""Base64-encode one patch for the ``patches`` array."""
Expand All @@ -25,19 +72,33 @@ def encode_patch(patch: bytes) -> str:
class LandoClient:
def __init__(self, settings: LandoSettings | None = None) -> None:
self.settings = settings or LandoSettings.from_env()
self._http = httpx.AsyncClient(
base_url=f"{self.base_url}/api/",
headers={
"Authorization": f"Bearer {self.settings.access_token}",
"User-Agent": self.settings.user_agent,
},
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:
return self.settings.url.rstrip("/")

@property
def try_patches_url(self) -> str:
return f"{self.base_url}/api/try/patches"

def repo_url(self, repo_name: str) -> str:
"""The headless API endpoint that queues actions on a landing repo."""
return f"{self.base_url}/api/repo/{repo_name}"

def job_url(self, job_id: int) -> str:
"""Lando's own page for a landing job (its live status)."""
return f"{self.base_url}/landings/{job_id}"
Expand All @@ -59,6 +120,27 @@ def treeherder_url(self, job_id: int, repo_name: str = "try") -> str:
f"&landoCommitID={job_id}"
)

@retry(
retry=_should_retry,
stop=stop_after_attempt(4),
wait=wait_exponential_jitter(max=15),
before_sleep=before_sleep_log(log, logging.WARNING),
reraise=True,
)
Comment thread
evgenyrp marked this conversation as resolved.
Resolved
async def request(
self, method: str, path: str, /, *, json: dict[str, Any]
) -> dict[str, Any]:
"""Call an API endpoint (relative to ``/api/``) and return its JSON body.

A request Lando never received (a refused connection, a 503 or a rate
limit) is resent with exponential backoff.

Raises :class:`LandoRequestError` for a 4xx, :class:`LandoUnavailableError`
for a 5xx or a 429, and :class:`LandoAPIError` for an unusable answer.
"""
response = await self._http.request(method, path, json=json)
return _parse(response)

async def submit_try_patches(
self,
patches: list[str],
Expand All @@ -75,60 +157,55 @@ async def submit_try_patches(
try repo's own SCM when ``base_commit_vcs`` differs, so a firefox git
sha is fine for the Mercurial ``try``).
"""
payload = {
"repo_name": repo_name,
"base_commit": base_commit,
"base_commit_vcs": base_commit_vcs,
"patch_format": patch_format,
"patches": patches,
}
async with httpx.AsyncClient(timeout=self.settings.timeout_seconds) as client:
response = await client.post(
self.try_patches_url,
json=payload,
headers={
"Authorization": f"Bearer {self.settings.access_token}",
"User-Agent": self.settings.user_agent,
},
)

if response.status_code >= 400:
raise LandoAPIError(_error_detail(response))

try:
return int(response.json()["id"])
except (ValueError, KeyError, TypeError) as exc:
raise LandoAPIError(
f"Lando accepted the push ({response.status_code}) but returned no "
"job id"
) from exc
body = await self.request(
"POST",
"try/patches",
json={
"repo_name": repo_name,
"base_commit": base_commit,
"base_commit_vcs": base_commit_vcs,
"patch_format": patch_format,
"patches": patches,
},
)
return _job_id(body, "id")

async def revert_commit(self, repo_name: str, commit: str) -> int:
"""Back out a recently landed ``commit`` from a repo; return the job id.

Lando runs ``git revert`` on the repo's head.
"""
payload = {"actions": [{"action": "revert", "commit": commit}]}
async with httpx.AsyncClient(timeout=self.settings.timeout_seconds) as client:
response = await client.post(
self.repo_url(repo_name),
json=payload,
headers={
"Authorization": f"Bearer {self.settings.access_token}",
"User-Agent": self.settings.user_agent,
},
)

if response.status_code >= 400:
raise LandoAPIError(_error_detail(response))

try:
return int(response.json()["job_id"])
except (ValueError, KeyError, TypeError) as exc:
raise LandoAPIError(
f"Lando accepted the push ({response.status_code}) but returned no "
"job id"
) from exc
body = await self.request(
"POST",
f"repo/{repo_name}",
json={"actions": [{"action": "revert", "commit": commit}]},
)
return _job_id(body, "job_id")


def _job_id(body: dict[str, Any], key: str) -> int:
try:
return int(body[key])
except (ValueError, KeyError, TypeError) as exc:
raise LandoAPIError(
"Lando accepted the request but returned no job id"
) from exc


def _parse(response: httpx.Response) -> dict[str, Any]:
"""Return the JSON body, raising the :class:`LandoAPIError` that fits the status."""
status = response.status_code
if status == 429 or response.is_server_error:
raise LandoUnavailableError(_error_detail(response), status=status)
if response.is_client_error:
raise LandoRequestError(_error_detail(response), status=status)
try:
body = response.json()
except ValueError:
body = None
if not isinstance(body, dict):
raise LandoAPIError(_error_detail(response), status=status)
return body


def _error_detail(response: httpx.Response) -> str:
Expand Down
1 change: 1 addition & 0 deletions libs/lando-client/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ requires-python = ">=3.14"
dependencies = [
"httpx>=0.26.0",
"pydantic-settings>=2.1.0",
"tenacity>=9.1.0",
]

[project.optional-dependencies]
Expand Down
Loading