feat: add aaredaq api client
CI for mx_bec / test (push) Failing after 47s

This commit is contained in:
perl_d committed 2026-11-03 15:48:51 +01:00
1 parent 71cd3ac6b4
commit 75b51fc314
4 files changed
+316 -1

No files matched your search

+167
View File
@@ -0,0 +1,167 @@
from __future__ import annotations
import json
import subprocess
from typing import TYPE_CHECKING, Any
import requests
from aarecommon.config.beamline import cfg_get, mx_beamline
from aarecommon.models.beamline import MXBeamline
from aarecommon.models.raster_grid import CompletedRasterGrid, RasterGridRequest
from aarecommon.models.rotation_scan import CompletedRotationScan, RotationScanRequest
from bec_lib.logger import bec_logger
if TYPE_CHECKING:
from mx_bec.service import AareBec
logger = bec_logger.logger
# same defaults as the AareDAQ GUI (aare/gui/gui.py)
DEFAULT_URLS = {
MXBeamline.X06DA: "https://mx-x06da-queue-01.psi.ch",
MXBeamline.X10SA: "https://mx-x10sa-queue-01.psi.ch",
}
DEFAULT_CERT_PATHS = {
MXBeamline.X06DA: "/sls/x06da/misc/.cert/6d.crt",
MXBeamline.X10SA: "/sls/x10sa/misc/.cert/10s.crt",
}
TOKEN_TIMEOUT_S = 120.0
SCAN_TIMEOUT_S = 3600.0 # the scan endpoints block until the scan is done
class AareDaqError(RuntimeError):
"""A call to the AareDAQ server failed."""
class AareDaq:
"""Client for the AareDAQ REST API (aaredaq `server.py`).
Mirrors how the AareDAQ GUI talks to the server: a bearer token is obtained once, lazily, by
Kerberos (`curl --negotiate` against the Apache proxy in front of the server, exactly as
`aare.gui.auth.auth` does), and is renewed once if the server answers 401. The server URL and
its certificate come from the aarecommon beamline config unless given.
"""
def __init__(
self, client: AareBec, url: str | None = None, cert_path: str | None = None
) -> None:
self._client = client
self._url = url
self._cert_path = cert_path
self._token: str | None = None
self._session = requests.Session()
@property
def url(self) -> str:
if self._url is None:
beamline = mx_beamline()
self._url = cfg_get("gui.daq.daq_url", DEFAULT_URLS.get(beamline))
if self._url is None:
raise AareDaqError(f"No AareDAQ URL configured for beamline {beamline}")
return self._url
@property
def cert_path(self) -> str:
if self._cert_path is None:
beamline = mx_beamline()
self._cert_path = cfg_get("gui.daq.cert_path", DEFAULT_CERT_PATHS.get(beamline))
if self._cert_path is None:
raise AareDaqError(f"No AareDAQ certificate configured for beamline {beamline}")
return self._cert_path
@property
def token(self) -> str:
if self._token is None:
self._token = self._request_token()
return self._token
def _request_token(self) -> str:
"""POST /token through the Kerberos (SPNEGO) proxy; needs a valid ticket (kinit)."""
cmd = ["curl", "-s", "--cacert", self.cert_path, "--negotiate", "-u", ":", "-XPOST"]
cmd.append(f"{self.url}/token")
try:
result = subprocess.run(
cmd, capture_output=True, text=True, timeout=TOKEN_TIMEOUT_S, check=False
)
except (OSError, subprocess.TimeoutExpired) as e:
raise AareDaqError(f"AareDAQ token request failed: {e}") from e
if result.returncode != 0:
raise AareDaqError(
f"AareDAQ token request failed (curl exit {result.returncode}): "
f"{result.stderr[:500]}. Is the Kerberos ticket valid (kinit)?"
)
try:
token = json.loads(result.stdout).get("access_token")
except json.JSONDecodeError as e:
raise AareDaqError(f"AareDAQ token response is not JSON: {result.stdout[:500]}") from e
if not isinstance(token, str) or not token:
raise AareDaqError(f"AareDAQ token response has no access_token: {result.stdout[:500]}")
return token
def _post(
self,
endpoint: str,
*,
params: dict[str, Any] | None = None,
body: dict[str, Any] | None = None,
timeout_s: float = SCAN_TIMEOUT_S,
) -> Any:
"""POST to `endpoint` with the bearer token and return the decoded JSON response. A 401 is
retried once with a fresh token; any other error becomes an AareDaqError."""
for attempt in range(2):
try:
resp = self._session.post(
f"{self.url}{endpoint}",
params=params,
json=body,
headers={"Authorization": f"Bearer {self.token}"},
verify=self.cert_path,
timeout=timeout_s,
)
except requests.RequestException as e:
raise AareDaqError(f"AareDAQ POST {endpoint} failed: {e}") from e
if resp.status_code == 401 and attempt == 0:
logger.info("AareDAQ rejected the token, requesting a new one")
self._token = None
continue
if not resp.ok:
raise AareDaqError(
f"AareDAQ POST {endpoint} failed with {resp.status_code}: {resp.text[:500]}"
)
return resp.json()
raise AssertionError("unreachable") # pragma: no cover
def mount_sample(self, dbid: int, reference: bool = False, timeout_s: float = 600.0) -> None:
"""Mount the sample with database id `dbid` (from the reference tools if `reference`)."""
logger.info(f"AareDAQ: mounting sample {dbid}{' (reference tool)' if reference else ''}")
self._post(
"/sample/mount", params={"dbid": dbid, "reference": reference}, timeout_s=timeout_s
)
def raster_scan(
self,
request: RasterGridRequest,
auto_center: bool = False,
timeout_s: float = SCAN_TIMEOUT_S,
) -> CompletedRasterGrid:
"""Run a raster scan and return its result (blocks until the scan is done)."""
logger.info(f"AareDAQ: raster scan {request.n_x}x{request.n_y}, auto_center={auto_center}")
result = self._post(
"/scan/raster",
params={"auto_center": auto_center},
body=request.model_dump(mode="json"),
timeout_s=timeout_s,
)
return CompletedRasterGrid.model_validate(result)
def rotation_scan(
self, request: RotationScanRequest, timeout_s: float = SCAN_TIMEOUT_S
) -> CompletedRotationScan:
"""Run a rotation (or screening) scan and return its result (blocks until done)."""
logger.info(
f"AareDAQ: rotation scan, {request.steps} steps of {request.incr_omega_deg} deg"
)
result = self._post(
"/scan/rotation", body=request.model_dump(mode="json"), timeout_s=timeout_s
)
return CompletedRotationScan.model_validate(result)
+1 -1
View File
@@ -3,7 +3,7 @@ from __future__ import annotations
from pydantic import BaseModel, Field
class OpticalCenteringResults:
class OpticalCenteringResults(BaseModel):
"""Outputs from the optical centering stage"""
found: bool
+2
View File
@@ -8,6 +8,7 @@ from bec_lib import messages
from bec_lib.client import BECClient
from bec_lib.logger import bec_logger
from mx_bec.aaredaq import AareDaq
from mx_bec.actor_manager import AareActorManager
from mx_bec.constants import AareBecWorkflowState
from mx_bec.endpoints import TaskEndpoints
@@ -48,6 +49,7 @@ class AareBec(BECClient):
self.actor_manager: AareActorManager | None = None
self.optical_prediction = OpticalPrediction(client=self)
self.jfjoch = JFJoch(client=self) # connects lazily on first use
self.aaredaq = AareDaq(client=self) # authenticates lazily on first use
self.tasks = MxTasks(self)
self.task_queue: MxTaskQueue | None = None
self.sample_info: SampleInfo | None = None
+146
View File
@@ -0,0 +1,146 @@
import subprocess
from unittest.mock import MagicMock, call, patch
import pytest
from aarecommon.math.coordinate import Coordinate, SmargonCoordinate
from aarecommon.models.raster_grid import CompletedRasterGrid, RasterGridRequest
from aarecommon.models.rotation_scan import CompletedRotationScan, RotationScanRequest
from mx_bec.aaredaq import DEFAULT_URLS, AareDaq, AareDaqError
URL, CERT, TOKEN = "https://daq.test", "/certs/daq.crt", "eyJ.abc.def"
def _curl_result(stdout='{"access_token": "' + TOKEN + '"}', returncode=0, stderr=""):
return subprocess.CompletedProcess(args=[], returncode=returncode, stdout=stdout, stderr=stderr)
def _response(status_code=200, json_data=None, text=""):
resp = MagicMock(status_code=status_code, ok=200 <= status_code < 300, text=text)
resp.json.return_value = json_data
return resp
@pytest.fixture
def curl():
with patch("mx_bec.aaredaq.subprocess.run", return_value=_curl_result()) as run:
yield run
@pytest.fixture
def daq(curl):
daq = AareDaq(MagicMock(), url=URL, cert_path=CERT)
daq._session = MagicMock()
daq._session.post.return_value = _response(json_data="OK")
return daq
def _raster_request():
return RasterGridRequest(
n_x=2,
n_y=1,
grid_size_mm=Coordinate(x=0.05, y=0.05),
file_prefix="t",
exp_time_s=0.1,
dtz=150,
transmission=1,
smargon_top_left=SmargonCoordinate(),
omega_deg=0.0,
)
def test_url_and_cert_are_resolved_from_beamline_config_on_first_use(curl, monkeypatch):
monkeypatch.delenv("BEAMLINE", raising=False)
daq = AareDaq(MagicMock()) # must not need the beamline environment yet
with (
patch("mx_bec.aaredaq.mx_beamline", return_value="X10SA"),
patch("mx_bec.aaredaq.cfg_get", side_effect=lambda key, default: default) as cfg_get,
):
assert daq.url == DEFAULT_URLS["X10SA"]
assert daq.cert_path == "/sls/x10sa/misc/.cert/10s.crt"
assert cfg_get.call_args_list[0].args[0] == "gui.daq.daq_url"
def test_token_is_requested_lazily_by_kerberos_curl(daq, curl):
curl.assert_not_called()
assert daq.token == TOKEN
assert daq.token == TOKEN
curl.assert_called_once()
cmd = curl.call_args.args[0]
assert cmd[0] == "curl" and "--negotiate" in cmd and cmd[-1] == f"{URL}/token"
assert cmd[cmd.index("--cacert") + 1] == CERT
@pytest.mark.parametrize(
"result, match",
[
(_curl_result(returncode=6, stderr="could not resolve"), "curl exit 6"),
(_curl_result(stdout="<html>"), "not JSON"),
(_curl_result(stdout="{}"), "no access_token"),
],
)
def test_token_request_failures(daq, curl, result, match):
curl.return_value = result
with pytest.raises(AareDaqError, match=match):
_ = daq.token
def test_token_request_timeout(daq, curl):
curl.side_effect = subprocess.TimeoutExpired(cmd="curl", timeout=120)
with pytest.raises(AareDaqError, match="token request failed"):
_ = daq.token
def test_mount_sample(daq):
daq.mount_sample(42)
daq._session.post.assert_called_once_with(
f"{URL}/sample/mount",
params={"dbid": 42, "reference": False},
json=None,
headers={"Authorization": f"Bearer {TOKEN}"},
verify=CERT,
timeout=600.0,
)
def test_raster_scan(daq):
request = _raster_request()
completed = CompletedRasterGrid(r=[])
daq._session.post.return_value = _response(json_data=completed.model_dump(mode="json"))
assert daq.raster_scan(request, auto_center=True) == completed
kwargs = daq._session.post.call_args.kwargs
assert daq._session.post.call_args.args == (f"{URL}/scan/raster",)
assert kwargs["params"] == {"auto_center": True}
assert kwargs["json"] == request.model_dump(mode="json")
assert kwargs["timeout"] == 3600.0
def test_rotation_scan(daq):
request = RotationScanRequest(exp_time_s=0.05, incr_omega_deg=0.1, steps=100)
completed = CompletedRotationScan(request=request, result={"images": []})
daq._session.post.return_value = _response(json_data=completed.model_dump(mode="json"))
assert daq.rotation_scan(request) == completed
assert daq._session.post.call_args.args == (f"{URL}/scan/rotation",)
assert daq._session.post.call_args.kwargs["json"] == request.model_dump(mode="json")
def test_expired_token_is_renewed_once(daq, curl):
curl.side_effect = [_curl_result(), _curl_result('{"access_token": "new"}')]
daq._session.post.side_effect = [_response(401), _response(json_data="OK")]
daq.mount_sample(1)
headers = [c.kwargs["headers"]["Authorization"] for c in daq._session.post.call_args_list]
assert headers == [f"Bearer {TOKEN}", "Bearer new"]
assert daq.token == "new"
def test_persistent_401_is_an_error(daq):
daq._session.post.return_value = _response(401, text="nope")
with pytest.raises(AareDaqError, match="401"):
daq.mount_sample(1)
assert daq._session.post.call_count == 2
def test_http_error_reports_status_and_body(daq):
daq._session.post.return_value = _response(422, text='{"detail": "bad request"}')
with pytest.raises(AareDaqError, match="422.*bad request"):
daq.rotation_scan(RotationScanRequest(exp_time_s=0.05, incr_omega_deg=0.1, steps=1))