Skip to content
Open
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
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
157 changes: 100 additions & 57 deletions libs/lando-client/lando_client/client.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
"""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
from types import TracebackType
from typing import Any, Self

import httpx

Expand All @@ -16,6 +25,18 @@
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 encode_patch(patch: bytes) -> str:
"""Base64-encode one patch for the ``patches`` array."""
Expand All @@ -25,19 +46,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 +94,19 @@ def treeherder_url(self, job_id: int, repo_name: str = "try") -> str:
f"&landoCommitID={job_id}"
)

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.

Nothing is resent: Lando's write endpoints are not idempotent.

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 +123,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
69 changes: 49 additions & 20 deletions libs/lando-client/tests/test_client.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Tests for the shared Lando client."""

import json
import re
from base64 import b64decode

Expand All @@ -8,7 +9,9 @@
from lando_client import (
LandoAPIError,
LandoClient,
LandoRequestError,
LandoSettings,
LandoUnavailableError,
encode_patch,
)
from lando_client import client as client_module
Expand All @@ -19,28 +22,25 @@ def _client(**kwargs) -> LandoClient:
return LandoClient(LandoSettings(access_token="token", **kwargs))


def _capture_post(monkeypatch, response: httpx.Response) -> dict:
"""Stub httpx.AsyncClient to answer with `response`; capture the call."""
captured: dict = {}
def _capture_post(monkeypatch, *answers: httpx.Response | Exception) -> dict:
"""Answer requests with `answers` in turn (the last one repeats); capture them."""
captured: dict = {"calls": 0}
real_async_client = httpx.AsyncClient

class _FakeAsyncClient:
def __init__(self, timeout=None):
captured["timeout"] = timeout
def handler(request: httpx.Request) -> httpx.Response:
captured["url"] = str(request.url)
captured["json"] = json.loads(request.content)
captured["headers"] = request.headers
answer = answers[min(captured["calls"], len(answers) - 1)]
captured["calls"] += 1
if isinstance(answer, Exception):
raise answer
return answer

async def __aenter__(self):
return self
def fake_async_client(**kwargs):
return real_async_client(transport=httpx.MockTransport(handler), **kwargs)

async def __aexit__(self, *exc):
return False

async def post(self, url, json=None, headers=None):
captured["url"] = url
captured["json"] = json
captured["headers"] = headers
response.request = httpx.Request("POST", url)
return response

monkeypatch.setattr(client_module.httpx, "AsyncClient", _FakeAsyncClient)
monkeypatch.setattr(client_module.httpx, "AsyncClient", fake_async_client)
return captured


Expand All @@ -53,7 +53,6 @@ def test_urls_are_built_from_the_configured_host():
client = _client(url="https://lando-dev.allizom.org/")

# A trailing slash in config must not double up in the URLs.
assert client.try_patches_url == "https://lando-dev.allizom.org/api/try/patches"
assert client.job_url(7) == "https://lando-dev.allizom.org/landings/7"
assert client.automation_job_url(7) == "https://lando-dev.allizom.org/api/jobs/7/"
# Pointing at another deployment moves the Treeherder link with it, with no
Expand Down Expand Up @@ -117,6 +116,7 @@ async def test_submit_try_patches_posts_the_series_and_returns_the_job_id(monkey
assert job_id == 4321
assert captured["url"] == "https://lando.moz.tools/api/try/patches"
assert captured["headers"]["Authorization"] == "Bearer token"
assert captured["headers"]["User-Agent"] == "Lando-User/Hackbot"
assert captured["json"] == {
"repo_name": "try",
"base_commit": "a" * 40,
Expand Down Expand Up @@ -189,3 +189,32 @@ async def test_revert_commit_raises_with_the_headless_error_details(monkeypatch)

with pytest.raises(LandoAPIError, match="not allowed to revert commits"):
await _client().revert_commit("firefox-autoland", "c" * 40)


async def _revert(monkeypatch, *answers) -> tuple[dict, int | Exception]:
captured = _capture_post(monkeypatch, *answers)
try:
result = await _client().revert_commit("firefox-autoland", "c" * 40)
except LandoAPIError as exc:
result = exc
return captured, result


@pytest.mark.parametrize("status", [400, 403, 404])
async def test_a_rejected_request_raises_a_request_error(monkeypatch, status):
captured, result = await _revert(
monkeypatch, httpx.Response(status, json={"details": "no"})
)

assert isinstance(result, LandoRequestError)
assert result.status == status
assert captured["calls"] == 1


@pytest.mark.parametrize("status", [429, 500, 502, 503, 504])
async def test_a_server_error_raises_unavailable_and_is_not_resent(monkeypatch, status):
captured, result = await _revert(monkeypatch, httpx.Response(status))

assert isinstance(result, LandoUnavailableError)
assert result.status == status
assert captured["calls"] == 1
5 changes: 4 additions & 1 deletion services/hackbot-api/app/action_handlers/lando_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from functools import lru_cache
from typing import Any

from lando_client import LandoClient
from lando_client import LandoClient, LandoUnavailableError

from app.action_handlers.base import ActionResult, ApplyContext

Expand All @@ -27,6 +27,9 @@ async def apply(self, params: dict[str, Any], ctx: ApplyContext) -> ActionResult
try:
client = _client()
job_id = await client.revert_commit(lando_repo, commit)
except LandoUnavailableError as exc:
log.warning("Lando unavailable backing out %s: %s", commit, exc)
return ActionResult.failed(f"Lando is unavailable, retry later: {exc}")
except Exception as exc:
log.exception("Failed to back out %s from %s", commit, lando_repo)
return ActionResult.failed(str(exc))
Expand Down
14 changes: 13 additions & 1 deletion services/hackbot-api/tests/test_lando_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import pytest
from app.action_handlers import ApplyContext, lando_handler
from app.action_handlers.registry import get_handler
from lando_client import LandoClient
from lando_client import LandoClient, LandoUnavailableError

_PARAMS = {"lando_repo": "firefox-autoland", "commit": "c" * 40}

Expand Down Expand Up @@ -61,3 +61,15 @@ async def fake_revert(self, *args):

assert result.status == "failed"
assert "not allowed to revert commits" in result.error


async def test_apply_says_when_lando_is_only_temporarily_unavailable(monkeypatch):
async def fake_revert(self, *args):
raise LandoUnavailableError("Lando returned HTTP 503", status=503)

monkeypatch.setattr(LandoClient, "revert_commit", fake_revert)

result = await lando_handler.BackoutHandler().apply(_PARAMS, _ctx())

assert result.status == "failed"
assert result.error.startswith("Lando is unavailable, retry later")