From f7cc9d8e327de60b8d3d42adf22dbe2a10399bd3 Mon Sep 17 00:00:00 2001 From: David Perl Date: Thu, 26 Nov 2026 15:39:59 +0100 Subject: [PATCH 01/11] feat: use smargopolo nudge directly --- mx_bec/devices/aerotech.py | 2 +- mx_bec/devices/http.py | 21 ++++-- mx_bec/devices/smargopolo_smargon.py | 97 +++++++++++++--------------- mx_bec/tasks/mx_tasks.py | 3 +- tests/unit/mock_smargopolo.py | 32 +++++++++ tests/unit/test_smargon.py | 62 ++++++++++-------- 6 files changed, 132 insertions(+), 85 deletions(-) diff --git a/mx_bec/devices/aerotech.py b/mx_bec/devices/aerotech.py index 952a98e..6dfdc3d 100644 --- a/mx_bec/devices/aerotech.py +++ b/mx_bec/devices/aerotech.py @@ -114,7 +114,7 @@ class AerotechController(HttpDeviceControllerWithConfigVelocity): self._rest_post(params={"timeout": timeout}, endpoint=self._wait_till_done_endpoint) -class Aerotech(HttpOphydDevice): +class Aerotech(HttpOphydDevice[AerotechController]): """Aerotech sample stage driven through the AareScan REST API. Triggering runs the grid scan configured in `gridscan_config`.""" diff --git a/mx_bec/devices/http.py b/mx_bec/devices/http.py index 0e69acd..7fad29c 100644 --- a/mx_bec/devices/http.py +++ b/mx_bec/devices/http.py @@ -1,7 +1,7 @@ import time from abc import ABC, abstractmethod from threading import Event, RLock, Thread -from typing import Any +from typing import Any, Generic, TypeVar from bec_lib.logger import bec_logger from ophyd import Kind, OphydObject, Signal @@ -99,8 +99,11 @@ class HttpDeviceController(OphydObject, ABC): raise HttpRestError(resp) return resp.json() - def _rest_put(self, params: dict | None = None, body: dict | None = None): - resp = self._session.put(self._prefix + self._target_endpoint, params=params, json=body) + def _rest_put( + self, params: dict | None = None, body: dict | None = None, endpoint: str | None = None + ): + endpoint = self._target_endpoint if endpoint is None else endpoint + resp = self._session.put(self._prefix + endpoint, params=params, json=body) if not resp.ok: raise HttpRestError(resp, value=params) @@ -232,8 +235,16 @@ class HttpVelocitySignal(Signal): self._controller.register_velocity(axis_id=self._axis_id, signal=self) -class HttpOphydDevice(PSIDeviceBase): - controller_class: type[HttpDeviceController] +ControllerT = TypeVar("ControllerT", bound=HttpDeviceController) + + +class HttpOphydDevice(PSIDeviceBase, Generic[ControllerT]): + """Device whose signals talk to a REST interface through a controller. Subclasses give the + controller type twice: as the type parameter, for type checkers, and as `controller_class`, + which is what gets instantiated.""" + + controller_class: type[ControllerT] + controller: ControllerT def __init__( self, *, name: str, prefix: str = "", scan_info=None, device_manager=None, **kwargs diff --git a/mx_bec/devices/smargopolo_smargon.py b/mx_bec/devices/smargopolo_smargon.py index 5772a02..64eba87 100644 --- a/mx_bec/devices/smargopolo_smargon.py +++ b/mx_bec/devices/smargopolo_smargon.py @@ -1,6 +1,6 @@ +import time from typing import ClassVar -import numpy as np from bec_lib.logger import bec_logger from ophyd import Component as Cpt @@ -10,6 +10,7 @@ logger = bec_logger.logger _TIMESTAMP_ID = "__timestamp" _POLL_INTERVAL_SLOW = 0.1 +_TARGET_CHANGE_MM = 1e-9 # targets further apart than this are different targets class SmargonController(HttpDeviceController): @@ -17,6 +18,7 @@ class SmargonController(HttpDeviceController): _readback_endpoint = "/readbackSCS" _target_endpoint = "/targetSCS" + _nudge_endpoint = "/nudgeBCS" def __init__(self, *, prefix, **kwargs): self._readbacks: dict[str, float] = {} @@ -31,6 +33,14 @@ class SmargonController(HttpDeviceController): def put(self, axis: str, val: float): self._rest_put(params={axis: val}) + def get_targets(self) -> dict[str, float]: + """The current target position of every axis.""" + return self._rest_get(self._target_endpoint) + + def nudge(self, x_mm: float, y_mm: float, z_mm: float): + """Request a move relative to the current target, given in the beamline (lab) frame.""" + self._rest_put(params={"BX": x_mm, "BY": y_mm, "BZ": z_mm}, endpoint=self._nudge_endpoint) + def stop(self): # There doesn't appear to be a stop endpoint on the server # Best effort: set the target to the current position @@ -43,7 +53,7 @@ class SmargonController(HttpDeviceController): self._rest_put(params=targets) -class Smargon(HttpOphydDevice): +class Smargon(HttpOphydDevice[SmargonController]): USER_ACCESS: ClassVar[list[str]] = ["nudge_in_lab_frame"] controller_class = SmargonController @@ -54,56 +64,39 @@ class Smargon(HttpOphydDevice): chi = Cpt(HttpDeviceSignal, axis_identifier="CHI", tolerance=0.01) def nudge_in_lab_frame( - self, - x_mm: float, - y_mm: float, - z_mm: float = 0.0, - omega_deg: float = 0.0, - timeout_s: float | None = 2.0, + self, x_mm: float, y_mm: float, z_mm: float = 0.0, timeout_s: float | None = 2.0 ): - """Apply a relative move in the lab frame (adjusted for the rotation angle, assuming that - the frames are identical when omega = phi = chi = 0). `omega_deg` is the angle of the - rotation stage the smargon sits on (the Aerotech `u` axis), which the smargon does not - know itself.""" - x_mm, y_mm, z_mm = self._lab_frame_offset_to_smargon_nudge(x_mm, y_mm, z_mm, omega_deg) - logger.info(f"Nudging smargon by {x_mm=},{y_mm=},{z_mm=}") - ( - self.x.set(self.x.get() + x_mm) - & self.y.set(self.y.get() + y_mm) - & self.z.set(self.z.get() + z_mm) - ).wait(timeout=timeout_s) + """Apply a relative move in the lab frame (the beamline coordinate system of smargopolo) + and wait for it to finish, for at most `timeout_s` (forever if None). - def _lab_frame_offset_to_smargon_nudge( - self, x_mm: float, y_mm: float, z_mm: float = 0.0, omega_deg: float = 0.0 - ): - """adjust a move for the rotation angle, assuming that the frames are identical when omega = phi = chi = 0""" - logger.info( - f"Calculating smargon motor nudge for camera offset: {x_mm=}, {y_mm=}, {z_mm=}, at {omega_deg=}" - ) - phi = np.radians(np.around(self.phi.get(), decimals=1)) - chi = np.radians(np.around(self.chi.get(), decimals=1)) - omega = np.radians(np.around(omega_deg, decimals=1)) + The smargopolo server does the conversion to a move of its own axes (`/nudgeBCS`, see + `nudge.cpp` there), for its current phi and chi targets and its own reading of the omega + rotation stage the smargon sits on.""" + if x_mm == 0 and y_mm == 0 and z_mm == 0: + return + logger.info(f"Nudging smargon in the lab frame by {x_mm=}, {y_mm=}, {z_mm=}") + targets_before = self.controller.get_targets() + self.controller.nudge(x_mm, y_mm, z_mm) + self._wait_for_nudge(targets_before, timeout_s) - co = np.cos(omega) - so = np.sin(omega) - cp = np.cos(phi) - sp = np.sin(phi) - cc = np.cos(chi) - sc = np.sin(chi) - - res_x = ( - -z_mm * co * sp - - y_mm * so * sp - + x_mm * cp * sc - - y_mm * co * cc * cp - + z_mm * so * cc * cp - ) - res_y = ( - -z_mm * co * cp - - y_mm * so * cp - - x_mm * sc * sp - + y_mm * co * cc * sp - - z_mm * so * cc * sp - ) - res_z = -x_mm * cc - y_mm * co * sc + z_mm * so * sc - return res_x, res_y, res_z + def _wait_for_nudge(self, targets_before: dict[str, float], timeout_s: float | None): + """The nudge request only places the move: wait for the server to set the new targets, + which differ from `targets_before`, and then for the axes to reach them.""" + axes: list[HttpDeviceSignal] = [self.x, self.y, self.z] + deadline = None if timeout_s is None else time.monotonic() + timeout_s + while True: + targets = self.controller.get_targets() + target_set = any( + abs(targets[axis._axis_id] - targets_before[axis._axis_id]) > _TARGET_CHANGE_MM + for axis in axes + ) + if target_set and all( + abs(axis.get() - targets[axis._axis_id]) <= axis.tolerance for axis in axes + ): + return + if deadline is not None and time.monotonic() > deadline: + raise TimeoutError( + f"Smargon nudge did not finish within {timeout_s} s " + f"({'targets ' + str(targets) if target_set else 'no new targets were set'})" + ) + time.sleep(_POLL_INTERVAL_SLOW) diff --git a/mx_bec/tasks/mx_tasks.py b/mx_bec/tasks/mx_tasks.py index 00b7834..a707a7d 100644 --- a/mx_bec/tasks/mx_tasks.py +++ b/mx_bec/tasks/mx_tasks.py @@ -274,7 +274,8 @@ class MxTasks(TaskManager[RoleT]): if abs(dx) < 1e-4 and abs(dy) < 1e-4: return self._client.devices.aerotech.u.set(omega).wait() - self._client.devices.smargon.nudge_in_lab_frame(dx, dy, omega_deg=omega) + # smargopolo applies the nudge for its own reading of omega, which is now the raster angle + self._client.devices.smargon.nudge_in_lab_frame(dx, dy) info.current_offset_mm = (offset_x_mm, offset_y_mm) @task diff --git a/tests/unit/mock_smargopolo.py b/tests/unit/mock_smargopolo.py index 41f1ca2..8473bf2 100644 --- a/tests/unit/mock_smargopolo.py +++ b/tests/unit/mock_smargopolo.py @@ -5,6 +5,7 @@ Run it standalone with `python mock_smargopolo.py` or in-process via `run_in_thr """ import asyncio +import math import random import socket import time @@ -61,6 +62,10 @@ def make_motors() -> dict[str, Motor]: motors: dict[str, Motor] = make_motors() +# What the server reads for the omega rotation stage which the smargon sits on, in degrees (the +# `omega` key of a dict so that tests can set it). +rotation_stage: dict[str, float] = {"omega": 0.0} + @asynccontextmanager async def lifespan(app: FastAPI): @@ -117,6 +122,33 @@ async def target_scs(req: Request): return {"targets": targets, "message": "Move started"} +def nudge_bcs_to_scs(nx: float, ny: float, nz: float) -> tuple[float, float, float]: + """The beamline-frame nudge as a move of SHX, SHY, SHZ: `calculateSH` of smargopolo's + nudge.cpp, with its orientation tweak parameters (offsetOMEGA, FPRX, FPRY, FPRZ) at zero.""" + omega = math.radians(rotation_stage["omega"]) + phi = math.radians(motors["PHI"].target) + chi = math.radians(motors["CHI"].target) + co, so = math.cos(omega), math.sin(omega) + cp, sp = math.cos(phi), math.sin(phi) + cc, sc = math.cos(chi), math.sin(chi) + return ( + -nz * co * sp - ny * so * sp + nx * cp * sc - ny * co * cc * cp + nz * so * cc * cp, + -nz * co * cp - ny * so * cp - nx * sc * sp + ny * co * cc * sp - nz * so * cc * sp, + -nx * cc - ny * co * sc + nz * so * sc, + ) + + +@app.put("/nudgeBCS") +async def nudge_bcs(BX: float = 0.0, BY: float = 0.0, BZ: float = 0.0): + """Move relative to the current targets (not the readbacks), as smargopolo does.""" + for axis, nudge in zip(("SHX", "SHY", "SHZ"), nudge_bcs_to_scs(BX, BY, BZ)): + motor = motors[axis] + motor.update() + motor.target += nudge + motor.moving = True + return [BX, BY, BZ] + + def free_port() -> int: with socket.socket() as sock: sock.bind(("127.0.0.1", 0)) diff --git a/tests/unit/test_smargon.py b/tests/unit/test_smargon.py index 1157d7b..554d2b7 100644 --- a/tests/unit/test_smargon.py +++ b/tests/unit/test_smargon.py @@ -1,9 +1,10 @@ """Tests of the smargopolo Smargon device against the in-process mock server.""" -import numpy as np +from unittest import mock + import pytest import requests -from mock_smargopolo import AXES, MockSmargopolo, motors +from mock_smargopolo import AXES, MockSmargopolo, motors, rotation_stage from mx_bec.devices.smargopolo_smargon import Smargon @@ -21,6 +22,7 @@ def smargon(server): for motor in motors.values(): motor.position = motor.target = 0.0 motor.moving = False + rotation_stage["omega"] = 0.0 dev = Smargon(name="smargon", prefix=server.url) dev.wait_for_connection() yield dev @@ -28,19 +30,6 @@ def smargon(server): dev.destroy() -def reference_nudge(x, y, z, phi_deg, chi_deg, omega_deg): - """aarecommon.math.sample_geometry.SampleGeometry.smargon_nudge""" - phi, chi, omega = (np.radians(np.around(a, decimals=1)) for a in (phi_deg, chi_deg, omega_deg)) - co, so = np.cos(omega), np.sin(omega) - cp, sp = np.cos(phi), np.sin(phi) - cc, sc = np.cos(chi), np.sin(chi) - return ( - -z * co * sp - y * so * sp + x * cp * sc - y * co * cc * cp + z * so * cc * cp, - -z * co * cp - y * so * cp - x * sc * sp + y * co * cc * sp - z * so * cc * sp, - -x * cc - y * co * sc + z * so * sc, - ) - - def test_read_all_axes(smargon): motors["SHX"].position = 1.5 motors["CHI"].position = 42.0 @@ -74,17 +63,38 @@ def test_nudge_in_lab_frame_at_zero_angles(smargon): assert smargon.x.get() == pytest.approx(-0.2, abs=TOL) -@pytest.mark.parametrize( - "phi_deg, chi_deg, omega_deg", [(90.0, 0.0, 0.0), (0.0, 20.0, 0.0), (30.0, 20.0, 45.0)] -) -def test_nudge_matches_reference(smargon, phi_deg, chi_deg, omega_deg): - for ax, val in (("PHI", phi_deg), ("CHI", chi_deg)): - motors[ax].position = motors[ax].target = val - smargon.controller.manual_update() - # omega is the Aerotech rotation, which the smargon does not know: it is passed in - assert smargon._lab_frame_offset_to_smargon_nudge(1.0, 0.5, 0.25, omega_deg) == pytest.approx( - reference_nudge(1.0, 0.5, 0.25, phi_deg, chi_deg, omega_deg) - ) +def test_nudge_is_converted_by_the_server_for_its_angles(smargon): + # at chi = 90 a lab-frame x offset is a smargon x move instead of a -z move; at omega = 90 a + # lab-frame y offset is a smargon -y move instead of a -x move + motors["CHI"].position = motors["CHI"].target = 90.0 + smargon.nudge_in_lab_frame(0.2, 0.0) + assert motors["SHX"].target == pytest.approx(0.2) + assert motors["SHZ"].target == pytest.approx(0.0) + assert smargon.x.get() == pytest.approx(0.2, abs=TOL) + + motors["CHI"].position = motors["CHI"].target = 0.0 + rotation_stage["omega"] = 90.0 + smargon.nudge_in_lab_frame(0.0, 0.2) + assert motors["SHY"].target == pytest.approx(-0.2) + assert motors["SHX"].target == pytest.approx(0.2) + + +def test_nudge_sends_the_lab_frame_offset_to_the_server(smargon): + with mock.patch.object(smargon.controller, "_rest_put") as rest_put: + with pytest.raises(TimeoutError, match="no new targets were set"): + smargon.nudge_in_lab_frame(0.1, 0.2, 0.3, timeout_s=0.2) + rest_put.assert_called_once_with(params={"BX": 0.1, "BY": 0.2, "BZ": 0.3}, endpoint="/nudgeBCS") + + +def test_nudge_of_nothing_sends_nothing(smargon): + with mock.patch.object(smargon.controller, "_rest_put") as rest_put: + smargon.nudge_in_lab_frame(0.0, 0.0) + rest_put.assert_not_called() + + +def test_nudge_times_out_if_the_move_takes_too_long(smargon): + with pytest.raises(TimeoutError, match="targets"): + smargon.nudge_in_lab_frame(50.0, 0.0, timeout_s=0.3) def test_stop_targets_current_position(smargon): -- 2.54.1 From 4ff87a37827846d761881f64948af33d85fa93ee Mon Sep 17 00:00:00 2001 From: David Perl Date: Thu, 26 Nov 2026 16:11:41 +0100 Subject: [PATCH 02/11] feat: add grid scan task --- .../widgets/aare_bec/task_panel.py | 10 + mx_bec/tasks/mx_tasks.py | 173 +++++++++++++++++- 2 files changed, 180 insertions(+), 3 deletions(-) diff --git a/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py b/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py index 23e5ce4..4be983e 100644 --- a/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py +++ b/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py @@ -40,6 +40,16 @@ TASK_FORMS: dict[str, list[tuple[str, int | float | str | list[float]]]] = { ("dtz", 250), ("file_prefix", "AareBecTestGridScan"), ], + # the same scan run by BEC itself (Smargon, JFJoch and Aerotech), without AareDAQ + "grid_scan": [ + ("n_x", 4), + ("n_y", 3), + ("step_x_mm", 0.05), + ("step_y_mm", 0.05), + ("exp_time_s", 0.1), + ("omega_deg", 0.0), + ("file_prefix", "AareBecTestGridScan"), + ], "multiple_rasters": [ ("omegas_deg_list", [0, 45, 60, 90, 120, 135]), ("n_x", 10), diff --git a/mx_bec/tasks/mx_tasks.py b/mx_bec/tasks/mx_tasks.py index a707a7d..a425a89 100644 --- a/mx_bec/tasks/mx_tasks.py +++ b/mx_bec/tasks/mx_tasks.py @@ -1,15 +1,23 @@ from __future__ import annotations +import json +from dataclasses import dataclass +from importlib.resources import files from secrets import token_hex from typing import TYPE_CHECKING +from aarecommon.config.beamline import mx_beamline from aarecommon.math.coordinate import Coordinate, SmargonCoordinate -from aarecommon.models.raster_grid import CompletedRasterGrid # already imported in aaredaq.py -from aarecommon.models.raster_grid import RasterGridRequest +from aarecommon.models.beam_centre import BeamCentre +from aarecommon.models.raster_grid import ( + CompletedRasterGrid, # already imported in aaredaq.py + RasterGridRequest, +) from aarecommon.models.rotation_scan import RotationScanRequest from bec_lib.logger import bec_logger from mx_bec.decisions import ( + BeamState, CollectionRecord, GridGeometry, RasterRecord, @@ -20,6 +28,7 @@ from mx_bec.decisions import ( ) from mx_bec.device_planner import BeamlineState, StateChangePlanner, init_beamline_environment from mx_bec.endpoints import StateEndpoints +from mx_bec.jfjoch import RasterScan from mx_bec.messages import MXMeasurementSequenceMessage from mx_bec.tasks.core import MxSequenceUpdate, RoleT, TaskManager, task @@ -28,6 +37,23 @@ if TYPE_CHECKING: logger = bec_logger.logger +MAX_GRID_SCAN_S = 1200.0 # refuse grid scans expected to take longer than 20 min +JFJOCH_TIMEOUT_S = 60.0 # for JFJoch to arm the detector, and to finish once the scan is done + + +@dataclass +class BeamConditions: + """The state of the beamline which JFJoch records with a data collection.""" + + energy_keV: float + full_flux_ph_s: float # at transmission 1 + transmission: float + detector_distance_mm: float + beam_center_pxl: tuple[float, float] + beam_size_mm: tuple[float, float] + ring_current_mA: float + sample_temperature_K: float + class MxTasks(TaskManager[RoleT]): """The operations on mx beamlines which can be requested as tasks. Instantiate as @@ -36,7 +62,6 @@ class MxTasks(TaskManager[RoleT]): TODO: - categorise tasks - - add doc info to decorator, including placeholder for args, to show to GUI """ if TYPE_CHECKING: @@ -235,6 +260,148 @@ class MxTasks(TaskManager[RoleT]): auto_center, ) + def _read(self, device: str) -> float: + """The current value of the device (or signal) with this name.""" + return self._client.devices[device].read()[device]["value"] + + def _energy_eV_and_full_flux_ph_s(self, transmission: float) -> tuple[float, float]: + """The photon energy, from the monochromator angle, and the flux at the sample at + transmission 1, from the beam position monitor. Both come from PXII calibrations.""" + # pylint: disable=import-outside-toplevel + from pxii_bec.macros.calculator import ( # pyright: ignore[reportMissingImports] + convert_from_bragg, + ) + from pxii_bec.macros.flux_macros import bpm2flux # pyright: ignore[reportMissingImports] + + energy_eV = convert_from_bragg(self._read("dcm_bragg"))["energy_ev"] + _, full_flux = bpm2flux( + energy=energy_eV, bpmsum=self._read("bcu_bpmsum"), transm=transmission + ) + return energy_eV, full_flux + + def _beam_center_pxl(self, det_z_mm: float, det_y_mm: float) -> tuple[float, float]: + """Where the beam hits the detector at this detector position, from the beam centres + which aarecommon has measured for the beamline.""" + beamline = mx_beamline().value.lower() + measured = json.loads( + files("aarecommon.config").joinpath("beamline_configs/beam_centres.json").read_text() + ) + if beamline not in measured: + raise ValueError(f"aarecommon has no beam centre measurements for {beamline}") + x, y = BeamCentre.model_validate(measured[beamline]).model.predict(det_z_mm, det_y_mm) + return float(x[0]), float(y[0]) + + def _beam_conditions(self) -> BeamConditions: + transmission = self._read("transm") + energy_eV, full_flux = self._energy_eV_and_full_flux_ph_s(transmission) + det_z_mm = self._read("det_z") + beam_size_um = BeamState().beam_size_um # not measured: the strategy's default + return BeamConditions( + energy_keV=energy_eV / 1000.0, + full_flux_ph_s=full_flux, + transmission=transmission, + detector_distance_mm=det_z_mm, + beam_center_pxl=self._beam_center_pxl(det_z_mm, self._read("det_y")), + beam_size_mm=(beam_size_um[0] / 1000.0, beam_size_um[1] / 1000.0), + ring_current_mA=self._read("sls_current"), + sample_temperature_K=self._read("cryo_temp"), + ) + + def _set_grid_scan_prerequisites( + self, + n_x: int, + n_y: int, + step_x_mm: float, + step_y_mm: float, + exp_time_s: float, + omega_deg: float, + dtz: float | None, + transmission: float | None, + ) -> None: + """Rotate to the scan's omega, set the detector distance and transmission if given, and + configure the Aerotech grid scan, checking that AareScan accepts it.""" + devices, scans = self._client.devices, self._client.scans + aerotech = devices.aerotech + aerotech.u.set(omega_deg).wait() + if dtz is not None: + scans.mv(devices.det_z, dtz, relative=False).wait() + if transmission is not None: + scans.mv(devices.transm, transmission, relative=False).wait() + config = aerotech.gridscan_config + for signal, value in ( + (config.grid_elem_count_x, n_x), + (config.grid_elem_count_y, n_y), + (config.grid_elem_size_x_um, step_x_mm * 1000.0), + (config.grid_elem_size_y_um, step_y_mm * 1000.0), + (config.time_per_element_sec, exp_time_s), + ): + signal.set(value).wait() + if not config.valid.get(): + raise ValueError(f"AareScan rejected the grid scan parameters: {config.message.get()}") + + @task + def grid_scan( + self, + n_x: int, + n_y: int, + step_x_mm: float, + step_y_mm: float, + exp_time_s: float, + omega_deg: float = 0.0, + file_prefix: str | None = None, + dtz: float | None = None, + transmission: float | None = None, + ) -> None: + """Collect an n_x by n_y grid scan centred on the current position, without AareDAQ: set + the prerequisites (omega, the detector distance `dtz` and the transmission if given, the + Aerotech grid scan), nudge the Smargon to the top left corner of the grid, arm JFJoch, + then trigger the Aerotech and wait for both to finish. The Smargon stays at the corner.""" + expected_s = exp_time_s * n_x * n_y + n_y * 0.3 + if expected_s > MAX_GRID_SCAN_S: + raise ValueError(f"Grid scan is too long: {expected_s:.0f} s > {MAX_GRID_SCAN_S} s") + self._set_grid_scan_prerequisites( + n_x, n_y, step_x_mm, step_y_mm, exp_time_s, omega_deg, dtz, transmission + ) + + smargon = self._client.devices.smargon + x_offset_mm, y_offset_mm = n_x * step_x_mm * 0.5, n_y * step_y_mm * 0.5 + logger.info(f"Nudging smargon to the top left of the grid: -{x_offset_mm=} -{y_offset_mm=}") + # smargopolo applies the nudge for its own reading of omega, which is now the scan's omega + smargon.nudge_in_lab_frame(-x_offset_mm, -y_offset_mm) + + beam = self._beam_conditions() + scan = RasterScan( + n_x=n_x, + n_y=n_y, + step_x_mm=step_x_mm, + step_y_mm=step_y_mm, + omega_deg=omega_deg, + exp_time_s=exp_time_s, + detector_distance_mm=beam.detector_distance_mm, + transmission=beam.transmission, + file_prefix=file_prefix or f"grid_{token_hex(3)}", + energy_keV=beam.energy_keV, + beam_center_pxl=beam.beam_center_pxl, + beam_size_mm=beam.beam_size_mm, + ring_current_mA=beam.ring_current_mA, + flux_ph_s=beam.full_flux_ph_s, + sample_temperature_K=beam.sample_temperature_K, + smargon_phi_deg=smargon.phi.get(), + smargon_chi_deg=smargon.chi.get(), + ) + jfjoch = self._client.jfjoch + jfjoch.measure_raster(scan) + try: + jfjoch.wait_till_running(timeout_s=JFJOCH_TIMEOUT_S) + logger.info(f"Starting {n_x}x{n_y} grid scan, {exp_time_s} s per element") + self._client.devices.aerotech.trigger().wait() + result = jfjoch.wait_till_done(timeout_s=JFJOCH_TIMEOUT_S) + except Exception: + # do not leave the detector armed, waiting for triggers which will not come + jfjoch.cancel() + raise + logger.info(f"Grid scan finished: {result.file_prefix} with {len(result.images)} images") + @task def xray_centering(self, dbid: int, strategy: dict) -> MxSequenceUpdate: result = self._run_raster(**strategy) -- 2.54.1 From 9e70f063d49b0a8131372671a4909c5a10a1e000 Mon Sep 17 00:00:00 2001 From: David Perl Date: Thu, 26 Nov 2026 16:30:01 +0100 Subject: [PATCH 03/11] feat: add rotation scan task --- .../widgets/aare_bec/task_panel.py | 7 + mx_bec/devices/aerotech.py | 43 +++-- mx_bec/jfjoch.py | 82 +++++++--- mx_bec/tasks/mx_tasks.py | 153 +++++++++++++----- tests/unit/test_aerotech.py | 28 ++++ tests/unit/test_jfjoch.py | 22 ++- 6 files changed, 263 insertions(+), 72 deletions(-) diff --git a/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py b/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py index 4be983e..39fe8cc 100644 --- a/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py +++ b/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py @@ -50,6 +50,13 @@ TASK_FORMS: dict[str, list[tuple[str, int | float | str | list[float]]]] = { ("omega_deg", 0.0), ("file_prefix", "AareBecTestGridScan"), ], + "rotation_scan": [ + ("exp_time_s", 0.05), + ("incr_omega_deg", 0.1), + ("steps", 100), + ("start_omega_deg", 0.0), + ("file_prefix", "AareBecTestRotationScan"), + ], "multiple_rasters": [ ("omegas_deg_list", [0, 45, 60, 90, 120, 135]), ("n_x", 10), diff --git a/mx_bec/devices/aerotech.py b/mx_bec/devices/aerotech.py index 6dfdc3d..7217917 100644 --- a/mx_bec/devices/aerotech.py +++ b/mx_bec/devices/aerotech.py @@ -87,6 +87,7 @@ class AerotechController(HttpDeviceControllerWithConfigVelocity): _readback_endpoint = "/status" _target_endpoint = "/position" _grid_scan_endpoint = "/grid_scan" + _rotation_scan_endpoint = "/rotation_scan" _wait_till_done_endpoint = "/wait_till_done" MAX_WAIT_TILL_DONE_S = 3600 # upper bound of the AareScan timeout parameter @@ -108,6 +109,10 @@ class AerotechController(HttpDeviceControllerWithConfigVelocity): """Start a grid scan with the given (validated) request body, returning immediately.""" self._rest_post(body={**body, "run_async": True}, endpoint=self._grid_scan_endpoint) + def start_rotation_scan(self, body: dict): + """Start a rotation scan with the given (validated) request body, returning immediately.""" + self._rest_post(body={**body, "run_async": True}, endpoint=self._rotation_scan_endpoint) + def wait_till_done(self, timeout_s: float): """Block until AareScan is idle again. Raises HttpRestError on timeout (504).""" timeout = min(max(int(round(timeout_s)), 0), self.MAX_WAIT_TILL_DONE_S) @@ -115,13 +120,17 @@ class AerotechController(HttpDeviceControllerWithConfigVelocity): class Aerotech(HttpOphydDevice[AerotechController]): - """Aerotech sample stage driven through the AareScan REST API. Triggering runs the grid scan - configured in `gridscan_config`.""" + """Aerotech sample stage driven through the AareScan REST API. Triggering runs the scan + selected by `scan_type`: the grid scan configured in `gridscan_config` (the default) or the + rotation scan configured in `rotation_config`.""" controller_class = AerotechController - # margin on top of the expected grid scan duration before giving up waiting for it + GRID_SCAN: ClassVar[str] = "grid_scan" + ROTATION_SCAN: ClassVar[str] = "rotation_scan" + # margin on top of the expected scan duration before giving up waiting for it GRID_SCAN_TIMEOUT_MARGIN_S = 60.0 + scan_type = Cpt(Signal, kind=Kind.config, dtype=str, value="grid_scan") gridscan_config = Cpt(GridscanParameters) screening_config = Cpt(ScreeningParameters) rotation_config = Cpt(RotationScanParameters) @@ -147,15 +156,24 @@ class Aerotech(HttpOphydDevice[AerotechController]): ######################################## def on_trigger(self) -> StatusBase: - """Start the grid scan from `gridscan_config`; the returned status finishes once AareScan - reports the scan done.""" - config = self.gridscan_config + """Start the scan selected by `scan_type` from its config; the returned status finishes + once AareScan reports the scan done.""" + scan_type = self.scan_type.get() + if scan_type == self.GRID_SCAN: + name, config, start = "Grid scan", self.gridscan_config, self.controller.start_grid_scan + timeout_s = self.grid_scan_timeout_s() + elif scan_type == self.ROTATION_SCAN: + name, config = "Rotation scan", self.rotation_config + start, timeout_s = self.controller.start_rotation_scan, self.rotation_scan_timeout_s() + else: + raise ValueError( + f"Unknown scan type {scan_type!r}: use {self.GRID_SCAN!r} or {self.ROTATION_SCAN!r}" + ) if not config.valid.get(): - raise ValueError(f"Grid scan parameters are not valid: {config.message.get()}") - body = config.request_body() - self.controller.start_grid_scan(body) + raise ValueError(f"{name} parameters are not valid: {config.message.get()}") + start(config.request_body()) status = self.task_handler.submit_task( - self.controller.wait_till_done, task_kwargs={"timeout_s": self.grid_scan_timeout_s()} + self.controller.wait_till_done, task_kwargs={"timeout_s": timeout_s} ) self.cancel_on_stop(status) return status @@ -173,6 +191,11 @@ class Aerotech(HttpOphydDevice[AerotechController]): def grid_scan_timeout_s(self) -> float: return self.expected_grid_scan_s() * 1.1 + self.GRID_SCAN_TIMEOUT_MARGIN_S + def rotation_scan_timeout_s(self) -> float: + """As for the grid scan, on top of the configured duration of the rotation.""" + expected_s = self.rotation_config.total_time_sec.get() + return expected_s * 1.1 + self.GRID_SCAN_TIMEOUT_MARGIN_S + def _test(): a = Aerotech(name="aerotech", prefix="http://mx-x10sa-queue-01:5234") diff --git a/mx_bec/jfjoch.py b/mx_bec/jfjoch.py index 4536851..7f8fe91 100644 --- a/mx_bec/jfjoch.py +++ b/mx_bec/jfjoch.py @@ -21,20 +21,15 @@ P = ParamSpec("P") R = TypeVar("R") -class RasterScan(BaseModel): - """Everything JFJoch needs to collect one raster (grid) scan.""" +class DataCollection(BaseModel): + """What JFJoch needs for any data collection: the exposure, where the files go and the state + of the beamline.""" - # grid: n_x columns by n_y rows, stepped by step_*_mm, at a fixed omega - n_x: int = Field(ge=1) - n_y: int = Field(ge=1) - step_x_mm: float = Field(gt=0) - step_y_mm: float = Field(gt=0) - omega_deg: float # exposure exp_time_s: float = Field(gt=0) detector_distance_mm: float = Field(gt=0) transmission: float = Field(ge=0, le=1) - # output: files go to /raw/raster/ + # output: files go to /raw// file_prefix: str pgroup: str = "p16371" sample_name: str = "unknown_sample" @@ -51,6 +46,26 @@ class RasterScan(BaseModel): smargon_chi_deg: float | None = None +class RasterScan(DataCollection): + """Everything JFJoch needs to collect one raster (grid) scan: n_x columns by n_y rows, + stepped by step_*_mm, at a fixed omega.""" + + n_x: int = Field(ge=1) + n_y: int = Field(ge=1) + step_x_mm: float = Field(gt=0) + step_y_mm: float = Field(gt=0) + omega_deg: float + + +class RotationScan(DataCollection): + """Everything JFJoch needs to collect one rotation scan: `steps` images of `incr_omega_deg` + each, from `start_omega_deg`.""" + + steps: int = Field(ge=1) + incr_omega_deg: float = Field(gt=0) + start_omega_deg: float + + class JFJochError(RuntimeError): """A call to the JFJoch detector broker failed.""" @@ -67,7 +82,8 @@ def needs_connection(method: Callable[P, R]) -> Callable[P, R]: class JFJoch: - """Thin wrapper around the JFJoch detector broker REST API, for raster (grid) scans. + """Thin wrapper around the JFJoch detector broker REST API, for raster (grid) and rotation + scans. Adapted from aaredaq's `JFJochWrapper`: the client is created on first use and every API call is wrapped so that failures raise `JFJochError`. @@ -115,6 +131,12 @@ class JFJoch: """Start a raster scan data collection; wait with `wait_till_running` / `wait_till_done`.""" self._call("start_post", dataset_settings=self.dataset_settings(scan, async_start)) + @needs_connection + def measure_rotation(self, scan: RotationScan, async_start: bool = True) -> None: + """Start a rotation scan data collection; wait with `wait_till_running` / + `wait_till_done`.""" + self._call("start_post", dataset_settings=self.dataset_settings(scan, async_start)) + @needs_connection def wait_till_running(self, timeout_s: float = 60) -> None: """Block until JFJoch reports the detector armed, or raise.""" @@ -140,11 +162,27 @@ class JFJoch: return self._call("result_scan_get") def dataset_settings( - self, scan: RasterScan, async_start: bool = True + self, scan: RasterScan | RotationScan, async_start: bool = True ) -> jfjoch_client.DatasetSettings: - """Build the JFJoch dataset settings for a raster scan.""" - # a single column is collected as one trigger with n_y images - ntrigger, images = (1, scan.n_y) if scan.n_x == 1 else (scan.n_y, scan.n_x) + """Build the JFJoch dataset settings for a raster or rotation scan.""" + if isinstance(scan, RasterScan): + kind = "raster" + # a single column is collected as one trigger with n_y images + ntrigger, images = (1, scan.n_y) if scan.n_x == 1 else (scan.n_y, scan.n_x) + omega_start, omega_step = scan.omega_deg, 0 + grid_scan = jfjoch_client.GridScan( + n_fast=scan.n_x, + snake=True, + step_x_um=scan.step_x_mm * 1000.0, + step_y_um=scan.step_y_mm * 1000.0, + vertical=False, + ) + else: + kind = "rotation" + # the whole rotation is one trigger + ntrigger, images = 1, scan.steps + omega_start, omega_step = scan.start_omega_deg, scan.incr_omega_deg + grid_scan = None if scan.smargon_phi_deg is not None and scan.smargon_chi_deg is not None: smargon = DatasetSettingsSmargon( phi_deg=scan.smargon_phi_deg, chi_deg=max(scan.smargon_chi_deg, 0) @@ -157,7 +195,7 @@ class JFJoch: ntrigger=ntrigger, images_per_trigger=images, detector_distance_mm=scan.detector_distance_mm, - file_prefix=f"{scan.pgroup}/raw/raster/{scan.file_prefix}", + file_prefix=f"{scan.pgroup}/raw/{kind}/{scan.file_prefix}", incident_energy_keV=scan.energy_keV, sample_name=scan.sample_name, image_time_us=round(scan.exp_time_s * 1e6), @@ -177,13 +215,11 @@ class JFJoch: polarization_factor=1.0, images_per_file=self._client.aare_config.jfjoch.n_images_per_file or None, goniometer=jfjoch_client.RotationAxis( - step=0, start=scan.omega_deg, name="omega", vector=[-1, 0, 0], screening_wedge_deg=0 - ), - grid_scan=jfjoch_client.GridScan( - n_fast=scan.n_x, - snake=True, - step_x_um=scan.step_x_mm * 1000.0, - step_y_um=scan.step_y_mm * 1000.0, - vertical=False, + step=omega_step, + start=omega_start, + name="omega", + vector=[-1, 0, 0], + screening_wedge_deg=0, ), + grid_scan=grid_scan, ) diff --git a/mx_bec/tasks/mx_tasks.py b/mx_bec/tasks/mx_tasks.py index a425a89..f25cbde 100644 --- a/mx_bec/tasks/mx_tasks.py +++ b/mx_bec/tasks/mx_tasks.py @@ -28,7 +28,7 @@ from mx_bec.decisions import ( ) from mx_bec.device_planner import BeamlineState, StateChangePlanner, init_beamline_environment from mx_bec.endpoints import StateEndpoints -from mx_bec.jfjoch import RasterScan +from mx_bec.jfjoch import DataCollection, RasterScan, RotationScan from mx_bec.messages import MXMeasurementSequenceMessage from mx_bec.tasks.core import MxSequenceUpdate, RoleT, TaskManager, task @@ -38,6 +38,7 @@ if TYPE_CHECKING: logger = bec_logger.logger MAX_GRID_SCAN_S = 1200.0 # refuse grid scans expected to take longer than 20 min +MAX_ROTATION_SCAN_S = 1200.0 # and rotation scans JFJOCH_TIMEOUT_S = 60.0 # for JFJoch to arm the detector, and to finish once the scan is done @@ -320,24 +321,81 @@ class MxTasks(TaskManager[RoleT]): ) -> None: """Rotate to the scan's omega, set the detector distance and transmission if given, and configure the Aerotech grid scan, checking that AareScan accepts it.""" - devices, scans = self._client.devices, self._client.scans - aerotech = devices.aerotech + aerotech = self._client.devices.aerotech aerotech.u.set(omega_deg).wait() + self._set_detector_distance_and_transmission(dtz, transmission) + config = aerotech.gridscan_config + self._configure_aerotech_scan( + "grid_scan", + config, + { + config.grid_elem_count_x: n_x, + config.grid_elem_count_y: n_y, + config.grid_elem_size_x_um: step_x_mm * 1000.0, + config.grid_elem_size_y_um: step_y_mm * 1000.0, + config.time_per_element_sec: exp_time_s, + }, + ) + + def _set_detector_distance_and_transmission( + self, dtz: float | None, transmission: float | None + ) -> None: + """Move the detector to `dtz` and set the transmission; what is None is left as it is.""" + devices, scans = self._client.devices, self._client.scans if dtz is not None: scans.mv(devices.det_z, dtz, relative=False).wait() if transmission is not None: scans.mv(devices.transm, transmission, relative=False).wait() - config = aerotech.gridscan_config - for signal, value in ( - (config.grid_elem_count_x, n_x), - (config.grid_elem_count_y, n_y), - (config.grid_elem_size_x_um, step_x_mm * 1000.0), - (config.grid_elem_size_y_um, step_y_mm * 1000.0), - (config.time_per_element_sec, exp_time_s), - ): + + def _configure_aerotech_scan(self, scan_type: str, config, values: dict) -> None: + """Make `scan_type` ("grid_scan" or "rotation_scan") the scan which triggering the + Aerotech runs, set the signals of its `config`, and check that AareScan accepts them.""" + self._client.devices.aerotech.scan_type.set(scan_type).wait() + for signal, value in values.items(): signal.set(value).wait() if not config.valid.get(): - raise ValueError(f"AareScan rejected the grid scan parameters: {config.message.get()}") + raise ValueError( + f"AareScan rejected the {scan_type} parameters: {config.message.get()}" + ) + + def _data_collection_settings(self, file_prefix: str) -> dict: + """The fields of a JFJoch `DataCollection` which describe the beamline as it is now.""" + beam = self._beam_conditions() + smargon = self._client.devices.smargon + return dict( + detector_distance_mm=beam.detector_distance_mm, + transmission=beam.transmission, + file_prefix=file_prefix, + energy_keV=beam.energy_keV, + beam_center_pxl=beam.beam_center_pxl, + beam_size_mm=beam.beam_size_mm, + ring_current_mA=beam.ring_current_mA, + flux_ph_s=beam.full_flux_ph_s, + sample_temperature_K=beam.sample_temperature_K, + smargon_phi_deg=smargon.phi.get(), + smargon_chi_deg=smargon.chi.get(), + ) + + def _collect(self, scan: DataCollection, description: str) -> None: + """Arm JFJoch for `scan`, trigger the Aerotech scan which was configured for it, and wait + for both to finish.""" + jfjoch = self._client.jfjoch + if isinstance(scan, RasterScan): + jfjoch.measure_raster(scan) + elif isinstance(scan, RotationScan): + jfjoch.measure_rotation(scan) + else: + raise TypeError(f"Cannot collect a {type(scan).__name__}") + try: + jfjoch.wait_till_running(timeout_s=JFJOCH_TIMEOUT_S) + logger.info(f"Starting {description}") + self._client.devices.aerotech.trigger().wait() + result = jfjoch.wait_till_done(timeout_s=JFJOCH_TIMEOUT_S) + except Exception: + # do not leave the detector armed, waiting for triggers which will not come + jfjoch.cancel() + raise + logger.info(f"Finished {description}: {result.file_prefix}, {len(result.images)} images") @task def grid_scan( @@ -363,13 +421,11 @@ class MxTasks(TaskManager[RoleT]): n_x, n_y, step_x_mm, step_y_mm, exp_time_s, omega_deg, dtz, transmission ) - smargon = self._client.devices.smargon x_offset_mm, y_offset_mm = n_x * step_x_mm * 0.5, n_y * step_y_mm * 0.5 logger.info(f"Nudging smargon to the top left of the grid: -{x_offset_mm=} -{y_offset_mm=}") # smargopolo applies the nudge for its own reading of omega, which is now the scan's omega - smargon.nudge_in_lab_frame(-x_offset_mm, -y_offset_mm) + self._client.devices.smargon.nudge_in_lab_frame(-x_offset_mm, -y_offset_mm) - beam = self._beam_conditions() scan = RasterScan( n_x=n_x, n_y=n_y, @@ -377,30 +433,51 @@ class MxTasks(TaskManager[RoleT]): step_y_mm=step_y_mm, omega_deg=omega_deg, exp_time_s=exp_time_s, - detector_distance_mm=beam.detector_distance_mm, - transmission=beam.transmission, - file_prefix=file_prefix or f"grid_{token_hex(3)}", - energy_keV=beam.energy_keV, - beam_center_pxl=beam.beam_center_pxl, - beam_size_mm=beam.beam_size_mm, - ring_current_mA=beam.ring_current_mA, - flux_ph_s=beam.full_flux_ph_s, - sample_temperature_K=beam.sample_temperature_K, - smargon_phi_deg=smargon.phi.get(), - smargon_chi_deg=smargon.chi.get(), + **self._data_collection_settings(file_prefix or f"grid_{token_hex(3)}"), + ) + self._collect(scan, f"{n_x}x{n_y} grid scan, {exp_time_s} s per element") + + @task + def rotation_scan( + self, + exp_time_s: float, + incr_omega_deg: float, + steps: int, + start_omega_deg: float = 0.0, + file_prefix: str | None = None, + dtz: float | None = None, + transmission: float | None = None, + ) -> None: + """Collect a rotation scan of `steps` images of `incr_omega_deg` each, from + `start_omega_deg`, at the current Smargon position and without AareDAQ: set the + prerequisites (the detector distance `dtz` and the transmission if given, the Aerotech + rotation scan), arm JFJoch, then trigger the Aerotech and wait for both to finish.""" + total_time_s = exp_time_s * steps + if total_time_s > MAX_ROTATION_SCAN_S: + raise ValueError( + f"Rotation scan is too long: {total_time_s:.0f} s > {MAX_ROTATION_SCAN_S} s" + ) + self._set_detector_distance_and_transmission(dtz, transmission) + config = self._client.devices.aerotech.rotation_config + self._configure_aerotech_scan( + "rotation_scan", + config, + { + config.rotation_deg: incr_omega_deg * steps, + config.total_time_sec: total_time_s, + config.start_pos_deg: start_omega_deg, + }, + ) + scan = RotationScan( + steps=steps, + incr_omega_deg=incr_omega_deg, + start_omega_deg=start_omega_deg, + exp_time_s=exp_time_s, + **self._data_collection_settings(file_prefix or f"rotation_{token_hex(3)}"), + ) + self._collect( + scan, f"rotation scan, {steps} images of {incr_omega_deg} deg, {exp_time_s} s each" ) - jfjoch = self._client.jfjoch - jfjoch.measure_raster(scan) - try: - jfjoch.wait_till_running(timeout_s=JFJOCH_TIMEOUT_S) - logger.info(f"Starting {n_x}x{n_y} grid scan, {exp_time_s} s per element") - self._client.devices.aerotech.trigger().wait() - result = jfjoch.wait_till_done(timeout_s=JFJOCH_TIMEOUT_S) - except Exception: - # do not leave the detector armed, waiting for triggers which will not come - jfjoch.cancel() - raise - logger.info(f"Grid scan finished: {result.file_prefix} with {len(result.images)} images") @task def xray_centering(self, dbid: int, strategy: dict) -> MxSequenceUpdate: diff --git a/tests/unit/test_aerotech.py b/tests/unit/test_aerotech.py index db5354f..87b5504 100644 --- a/tests/unit/test_aerotech.py +++ b/tests/unit/test_aerotech.py @@ -86,6 +86,34 @@ def test_trigger_refuses_invalid_config(aerotech): session.post.assert_not_called() +def test_trigger_starts_the_rotation_scan_if_selected(aerotech): + session = aerotech.controller._session + config = aerotech.rotation_config + config.rotation_deg.put(10.0) + config.total_time_sec.put(5.0) + config.start_pos_deg.put(30.0) + aerotech.scan_type.put(Aerotech.ROTATION_SCAN) + session.post.reset_mock() + + aerotech.trigger().wait(timeout=5) + + expected_timeout = round(5.0 * 1.1 + Aerotech.GRID_SCAN_TIMEOUT_MARGIN_S) + assert session.post.call_args_list == [ + call( + f"{PREFIX}/rotation_scan", + params=None, + json={**config.request_body(), "run_async": True}, + ), + call(f"{PREFIX}/wait_till_done", params={"timeout": expected_timeout}, json=None), + ] + + +def test_trigger_refuses_an_unknown_scan_type(aerotech): + aerotech.scan_type.put("helical") + with pytest.raises(ValueError, match="Unknown scan type 'helical'"): + aerotech.trigger() + + def test_wait_till_done_timeout_is_clamped(aerotech): session = aerotech.controller._session aerotech.controller.wait_till_done(timeout_s=1e6) diff --git a/tests/unit/test_jfjoch.py b/tests/unit/test_jfjoch.py index 4b3bd81..6ca23a4 100644 --- a/tests/unit/test_jfjoch.py +++ b/tests/unit/test_jfjoch.py @@ -3,7 +3,7 @@ from unittest.mock import MagicMock, patch import pytest from pydantic import ValidationError -from mx_bec.jfjoch import JFJoch, JFJochError, RasterScan +from mx_bec.jfjoch import JFJoch, JFJochError, RasterScan, RotationScan @pytest.fixture @@ -122,6 +122,26 @@ def test_measure_raster_builds_grid_dataset_settings(jfjoch): ) +def test_measure_rotation_builds_rotation_dataset_settings(jfjoch): + grid_fields = ("n_x", "n_y", "step_x_mm", "step_y_mm", "omega_deg") + common = {k: v for k, v in _scan().model_dump().items() if k not in grid_fields} + scan = RotationScan(steps=900, incr_omega_deg=0.2, start_omega_deg=30.0, **common) + with patch("mx_bec.jfjoch.jfjoch_client") as jfjoch_client: + jfjoch.measure_rotation(scan) + settings = jfjoch_client.DatasetSettings.call_args.kwargs + # the whole rotation is one trigger, and there is no grid + assert settings["ntrigger"] == 1 and settings["images_per_trigger"] == 900 + assert settings["file_prefix"] == "p16371/raw/rotation/test" + assert settings["grid_scan"] is None + jfjoch_client.GridScan.assert_not_called() + jfjoch_client.RotationAxis.assert_called_once_with( + step=0.2, start=30.0, name="omega", vector=[-1, 0, 0], screening_wedge_deg=0 + ) + jfjoch_client.DefaultApi.return_value.start_post.assert_called_once_with( + dataset_settings=jfjoch_client.DatasetSettings.return_value + ) + + def test_single_column_raster_is_one_trigger(jfjoch): with patch("mx_bec.jfjoch.jfjoch_client") as jfjoch_client: jfjoch.dataset_settings(_scan(n_x=1, n_y=4)) -- 2.54.1 From f82680c5699e878f0857db5bdaee2ec0f19ac399 Mon Sep 17 00:00:00 2001 From: David Perl Date: Wed, 2 Dec 2026 12:58:35 +0100 Subject: [PATCH 04/11] refactor: move external services to module --- .../systemd/mx-bec-service-restart.path | 9 + .../systemd/mx-bec-service-restart.service | 7 + deployment/systemd/mx-bec-service.service | 19 + mx_bec/external_services/__init__.py | 0 mx_bec/{ => external_services}/aaredaq.py | 0 mx_bec/{ => external_services}/jfjoch.py | 0 .../optical_centering.py | 0 mx_bec/service.py | 6 +- mx_bec/tasks/mx_tasks.py | 2 +- tests/unit/test_aaredaq.py | 24 +- tests/unit/test_grid_scan_task.py | 424 ++++++++++++++++++ tests/unit/test_jfjoch.py | 22 +- 12 files changed, 492 insertions(+), 21 deletions(-) create mode 100644 deployment/systemd/mx-bec-service-restart.path create mode 100644 deployment/systemd/mx-bec-service-restart.service create mode 100644 deployment/systemd/mx-bec-service.service create mode 100644 mx_bec/external_services/__init__.py rename mx_bec/{ => external_services}/aaredaq.py (100%) rename mx_bec/{ => external_services}/jfjoch.py (100%) rename mx_bec/{ => external_services}/optical_centering.py (100%) create mode 100644 tests/unit/test_grid_scan_task.py diff --git a/deployment/systemd/mx-bec-service-restart.path b/deployment/systemd/mx-bec-service-restart.path new file mode 100644 index 0000000..ff16773 --- /dev/null +++ b/deployment/systemd/mx-bec-service-restart.path @@ -0,0 +1,9 @@ +[Unit] +Description=Watch the deployed mx_bec pyproject.toml, to restart the MX BEC service on a new deployment + +[Path] +PathChanged=/sls/x10sa/config/bec/test/mx_bec/pyproject.toml +Unit=mx-bec-service-restart.service + +[Install] +WantedBy=multi-user.target diff --git a/deployment/systemd/mx-bec-service-restart.service b/deployment/systemd/mx-bec-service-restart.service new file mode 100644 index 0000000..dc41ac7 --- /dev/null +++ b/deployment/systemd/mx-bec-service-restart.service @@ -0,0 +1,7 @@ +[Unit] +Description=Restart the MX BEC service after a new deployment + +[Service] +Type=oneshot +# try-restart: leave the service stopped if it was stopped on purpose +ExecStart=/usr/bin/systemctl try-restart mx-bec-service.service diff --git a/deployment/systemd/mx-bec-service.service b/deployment/systemd/mx-bec-service.service new file mode 100644 index 0000000..ee7b219 --- /dev/null +++ b/deployment/systemd/mx-bec-service.service @@ -0,0 +1,19 @@ +[Unit] +Description=MX BEC service (AareBec) +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +Environment=BEAMLINE=x10sa +Environment=CONFIG_REDIS_URL=redis://mx-x10sa-queue-01:6379 +# Started through bash: SELinux does not let systemd (init_t) execute files on NFS (nfs_t) directly +ExecStart=/bin/bash -c 'exec /sls/x10sa/config/bec/test/bec_venv/bin/mx-bec-service' +# the service shuts down cleanly on a keyboard interrupt +KillSignal=SIGINT +TimeoutStopSec=30 +Restart=on-failure +RestartSec=5 + +[Install] +WantedBy=multi-user.target diff --git a/mx_bec/external_services/__init__.py b/mx_bec/external_services/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/mx_bec/aaredaq.py b/mx_bec/external_services/aaredaq.py similarity index 100% rename from mx_bec/aaredaq.py rename to mx_bec/external_services/aaredaq.py diff --git a/mx_bec/jfjoch.py b/mx_bec/external_services/jfjoch.py similarity index 100% rename from mx_bec/jfjoch.py rename to mx_bec/external_services/jfjoch.py diff --git a/mx_bec/optical_centering.py b/mx_bec/external_services/optical_centering.py similarity index 100% rename from mx_bec/optical_centering.py rename to mx_bec/external_services/optical_centering.py diff --git a/mx_bec/service.py b/mx_bec/service.py index a46485e..d4da1c5 100644 --- a/mx_bec/service.py +++ b/mx_bec/service.py @@ -9,13 +9,13 @@ from bec_lib.client import BECClient from bec_lib.logger import bec_logger from redis.client import Redis -from mx_bec.aaredaq import AareDaq from mx_bec.actor_manager import AareActorManager from mx_bec.constants import AareBecWorkflowState from mx_bec.endpoints import QueueEndpoints -from mx_bec.jfjoch import JFJoch +from mx_bec.external_services.aaredaq import AareDaq +from mx_bec.external_services.jfjoch import JFJoch +from mx_bec.external_services.optical_centering import OpticalPrediction from mx_bec.messages import MXQueueChangedMessage -from mx_bec.optical_centering import OpticalPrediction from mx_bec.sample_info import SampleInfo from mx_bec.tasks import MxTaskQueue, MxTasks, Server, UnknownTask diff --git a/mx_bec/tasks/mx_tasks.py b/mx_bec/tasks/mx_tasks.py index f25cbde..589ce3b 100644 --- a/mx_bec/tasks/mx_tasks.py +++ b/mx_bec/tasks/mx_tasks.py @@ -28,7 +28,7 @@ from mx_bec.decisions import ( ) from mx_bec.device_planner import BeamlineState, StateChangePlanner, init_beamline_environment from mx_bec.endpoints import StateEndpoints -from mx_bec.jfjoch import DataCollection, RasterScan, RotationScan +from mx_bec.external_services.jfjoch import DataCollection, RasterScan, RotationScan from mx_bec.messages import MXMeasurementSequenceMessage from mx_bec.tasks.core import MxSequenceUpdate, RoleT, TaskManager, task diff --git a/tests/unit/test_aaredaq.py b/tests/unit/test_aaredaq.py index 88ade01..df11b44 100644 --- a/tests/unit/test_aaredaq.py +++ b/tests/unit/test_aaredaq.py @@ -7,7 +7,7 @@ from aarecommon.models.auth import BatonStatus 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 +from mx_bec.external_services.aaredaq import DEFAULT_URLS, AareDaq, AareDaqError URL, CERT, TOKEN = "https://daq.test", "/certs/daq.crt", "eyJ.abc.def" @@ -24,7 +24,9 @@ def _response(status_code=200, json_data=None, text=""): @pytest.fixture def curl(): - with patch("mx_bec.aaredaq.subprocess.run", return_value=_curl_result()) as run: + with patch( + "mx_bec.external_services.aaredaq.subprocess.run", return_value=_curl_result() + ) as run: yield run @@ -77,8 +79,10 @@ def test_url_and_cert_are_resolved_from_beamline_config_on_first_use(curl, monke 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, + patch("mx_bec.external_services.aaredaq.mx_beamline", return_value="X10SA"), + patch( + "mx_bec.external_services.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" @@ -218,7 +222,7 @@ def test_take_baton_waits_for_the_holder(daq): daq._responses["GET"] = MagicMock() daq._responses["GET"].ok, daq._responses["GET"].status_code = True, 200 daq._responses["GET"].json.side_effect = lambda: next(checks) - with patch("mx_bec.aaredaq.time.sleep") as sleep: + with patch("mx_bec.external_services.aaredaq.time.sleep") as sleep: daq.take_baton(poll_interval_s=0.5) assert [url for url, _ in _calls(daq, "GET")] == [f"{URL}/baton/check_timeout"] * 2 sleep.assert_called_with(0.5) @@ -227,14 +231,20 @@ def test_take_baton_waits_for_the_holder(daq): def test_take_baton_refused_by_holder(daq): _set_posts(daq, _response(json_data={"pending": True})) daq._responses["GET"] = _response(json_data={"refused": True}) - with patch("mx_bec.aaredaq.time.sleep"), pytest.raises(AareDaqError, match="refused"): + with ( + patch("mx_bec.external_services.aaredaq.time.sleep"), + pytest.raises(AareDaqError, match="refused"), + ): daq.take_baton() def test_take_baton_gives_up_after_wait(daq): _set_posts(daq, _response(json_data={"queued": True})) daq._responses["GET"] = _response(json_data={"queued": True}) - with patch("mx_bec.aaredaq.time.sleep"), pytest.raises(AareDaqError, match="not granted"): + with ( + patch("mx_bec.external_services.aaredaq.time.sleep"), + pytest.raises(AareDaqError, match="not granted"), + ): daq.take_baton(wait_s=0) diff --git a/tests/unit/test_grid_scan_task.py b/tests/unit/test_grid_scan_task.py new file mode 100644 index 0000000..81992f0 --- /dev/null +++ b/tests/unit/test_grid_scan_task.py @@ -0,0 +1,424 @@ +from types import SimpleNamespace +from unittest.mock import MagicMock, call + +import pytest +from aarelcinfer_client.models import LatestPredictionModel + +from mx_bec.decisions import RotationPlan +from mx_bec.endpoints import StateEndpoints +from mx_bec.external_services.jfjoch import RasterScan, RotationScan +from mx_bec.sample_info import OpticalCenteringResults, SampleInfo +from mx_bec.tasks import MxTasks, Server +from mx_bec.tasks.mx_tasks import MAX_GRID_SCAN_S, MAX_ROTATION_SCAN_S, BeamConditions + +GRID = dict(n_x=4, n_y=3, step_x_mm=0.05, step_y_mm=0.04, exp_time_s=0.1) +BEAM = BeamConditions( + energy_keV=12.658, + full_flux_ph_s=1e12, + transmission=0.5, + detector_distance_mm=150.0, + beam_center_pxl=(1000.0, 1100.0), + beam_size_mm=(0.02, 0.01), + ring_current_mA=400.0, + sample_temperature_K=100.0, +) +# what the devices read, by name +READINGS = {"transm": 0.5, "det_z": 200.0, "det_y": 62.0, "sls_current": 400.0, "cryo_temp": 100.0} + + +@pytest.fixture +def client(): + client = MagicMock() + client.devices.aerotech.gridscan_config.valid.get.return_value = True + client.devices.aerotech.rotation_config.valid.get.return_value = True + client.devices.smargon.phi.get.return_value = 30.0 + client.devices.smargon.chi.get.return_value = 20.0 + client.devices.__getitem__.side_effect = lambda name: SimpleNamespace( + read=lambda: {name: {"value": READINGS[name]}} + ) + # a plain result so that logging it doesn't record extra mock calls + client.jfjoch.wait_till_done.return_value = SimpleNamespace( + file_prefix="p16371/raw/raster/grid", images=[1, 2, 3], rotation_bravais="tP" + ) + return client + + +@pytest.fixture +def tasks(client, monkeypatch): + tasks = MxTasks[Server](client) + monkeypatch.setattr(tasks, "_beam_conditions", lambda: BEAM) + return tasks + + +def test_grid_scan_is_a_task(): + assert MxTasks.is_task("grid_scan") + + +def test_grid_scan_sequence(tasks, client): + devices, jfjoch = client.devices, client.jfjoch + # one mock to record the order across the devices and jfjoch + sequence = MagicMock() + sequence.attach_mock(devices.aerotech.u.set, "rotate") + sequence.attach_mock(devices.aerotech.scan_type.set, "scan_type") + sequence.attach_mock(devices.aerotech.gridscan_config.valid.get, "validate") + sequence.attach_mock(devices.smargon.nudge_in_lab_frame, "nudge") + sequence.attach_mock(jfjoch, "jfjoch") + sequence.attach_mock(devices.aerotech.trigger, "trigger") + + tasks.grid_scan(**GRID, omega_deg=12.0, file_prefix="grid") + + scan = jfjoch.measure_raster.call_args.args[0] + assert scan == RasterScan( + n_x=4, + n_y=3, + step_x_mm=0.05, + step_y_mm=0.04, + omega_deg=12.0, + exp_time_s=0.1, + detector_distance_mm=150.0, + transmission=0.5, + file_prefix="grid", + energy_keV=12.658, + beam_center_pxl=(1000.0, 1100.0), + beam_size_mm=(0.02, 0.01), + ring_current_mA=400.0, + flux_ph_s=1e12, + sample_temperature_K=100.0, + smargon_phi_deg=30.0, + smargon_chi_deg=20.0, + ) + # prerequisites, then the smargon goes to the top left corner (half the grid away), then + # JFJoch is armed before the Aerotech moves, and the result is collected afterwards + assert sequence.mock_calls == [ + call.rotate(12.0), + call.rotate().wait(), + call.scan_type("grid_scan"), + call.scan_type().wait(), + call.validate(), + call.nudge(pytest.approx(-0.1), pytest.approx(-0.06)), + call.jfjoch.measure_raster(scan), + call.jfjoch.wait_till_running(timeout_s=60.0), + call.trigger(), + call.trigger().wait(), + call.jfjoch.wait_till_done(timeout_s=60.0), + ] + + +def test_grid_scan_configures_the_aerotech_in_microns(tasks, client): + tasks.grid_scan(**GRID) + config = client.devices.aerotech.gridscan_config + config.grid_elem_count_x.set.assert_called_once_with(4) + config.grid_elem_count_y.set.assert_called_once_with(3) + config.grid_elem_size_x_um.set.assert_called_once_with(pytest.approx(50.0)) + config.grid_elem_size_y_um.set.assert_called_once_with(pytest.approx(40.0)) + config.time_per_element_sec.set.assert_called_once_with(0.1) + assert config.time_per_element_sec.set.return_value.wait.called + + +def test_grid_scan_leaves_detector_distance_and_transmission_unless_given(tasks, client): + tasks.grid_scan(**GRID) + client.scans.mv.assert_not_called() + tasks.grid_scan(**GRID, dtz=180.0, transmission=0.2) + assert client.scans.mv.call_args_list == [ + call(client.devices.det_z, 180.0, relative=False), + call(client.devices.transm, 0.2, relative=False), + ] + + +def test_grid_scan_names_the_files_itself_if_no_prefix_is_given(tasks, client): + tasks.grid_scan(**GRID) + tasks.grid_scan(**GRID) + first, second = (c.args[0].file_prefix for c in client.jfjoch.measure_raster.call_args_list) + assert first.startswith("grid_") and second.startswith("grid_") and first != second + + +def test_grid_scan_refuses_invalid_parameters(tasks, client): + config = client.devices.aerotech.gridscan_config + config.valid.get.return_value = False + config.message.get.return_value = "too many elements" + with pytest.raises(ValueError, match="too many elements"): + tasks.grid_scan(**GRID) + client.devices.smargon.nudge_in_lab_frame.assert_not_called() + client.jfjoch.measure_raster.assert_not_called() + client.devices.aerotech.trigger.assert_not_called() + + +def test_grid_scan_refuses_too_long_scans(tasks, client): + too_long = {**GRID, "n_x": 100, "n_y": 100, "exp_time_s": MAX_GRID_SCAN_S / 100} + with pytest.raises(ValueError, match="too long"): + tasks.grid_scan(**too_long) + client.devices.aerotech.u.set.assert_not_called() + + +def test_grid_scan_cancels_jfjoch_if_the_aerotech_scan_fails(tasks, client): + client.devices.aerotech.trigger.return_value.wait.side_effect = RuntimeError("stage fault") + with pytest.raises(RuntimeError, match="stage fault"): + tasks.grid_scan(**GRID) + client.jfjoch.cancel.assert_called_once_with() + client.jfjoch.wait_till_done.assert_not_called() + + +ROTATION = dict(exp_time_s=0.05, incr_omega_deg=0.1, steps=100) + + +def test_rotation_scan_is_a_task(): + assert MxTasks.is_task("rotation_scan") + + +def test_rotation_scan_sequence(tasks, client): + devices, jfjoch = client.devices, client.jfjoch + sequence = MagicMock() + sequence.attach_mock(devices.aerotech.scan_type.set, "scan_type") + sequence.attach_mock(devices.aerotech.rotation_config.valid.get, "validate") + sequence.attach_mock(jfjoch, "jfjoch") + sequence.attach_mock(devices.aerotech.trigger, "trigger") + + tasks.rotation_scan(**ROTATION, start_omega_deg=30.0, file_prefix="rot") + + scan = jfjoch.measure_rotation.call_args.args[0] + assert scan == RotationScan( + steps=100, + incr_omega_deg=0.1, + start_omega_deg=30.0, + exp_time_s=0.05, + detector_distance_mm=150.0, + transmission=0.5, + file_prefix="rot", + energy_keV=12.658, + beam_center_pxl=(1000.0, 1100.0), + beam_size_mm=(0.02, 0.01), + ring_current_mA=400.0, + flux_ph_s=1e12, + sample_temperature_K=100.0, + smargon_phi_deg=30.0, + smargon_chi_deg=20.0, + ) + # the Aerotech is set to run its rotation scan, then JFJoch is armed before it is triggered + assert sequence.mock_calls == [ + call.scan_type("rotation_scan"), + call.scan_type().wait(), + call.validate(), + call.jfjoch.measure_rotation(scan), + call.jfjoch.wait_till_running(timeout_s=60.0), + call.trigger(), + call.trigger().wait(), + call.jfjoch.wait_till_done(timeout_s=60.0), + ] + # the sample stays where it is + devices.smargon.nudge_in_lab_frame.assert_not_called() + jfjoch.measure_raster.assert_not_called() + + +def test_rotation_scan_configures_the_aerotech_with_totals(tasks, client): + tasks.rotation_scan(**ROTATION, start_omega_deg=30.0) + config = client.devices.aerotech.rotation_config + config.rotation_deg.set.assert_called_once_with(pytest.approx(10.0)) + config.total_time_sec.set.assert_called_once_with(pytest.approx(5.0)) + config.start_pos_deg.set.assert_called_once_with(30.0) + + +def test_rotation_scan_sets_detector_distance_and_transmission_if_given(tasks, client): + tasks.rotation_scan(**ROTATION) + client.scans.mv.assert_not_called() + tasks.rotation_scan(**ROTATION, dtz=180.0, transmission=0.2) + assert client.scans.mv.call_args_list == [ + call(client.devices.det_z, 180.0, relative=False), + call(client.devices.transm, 0.2, relative=False), + ] + + +def test_rotation_scan_refuses_invalid_parameters(tasks, client): + config = client.devices.aerotech.rotation_config + config.valid.get.return_value = False + config.message.get.return_value = "too fast" + with pytest.raises(ValueError, match="too fast"): + tasks.rotation_scan(**ROTATION) + client.jfjoch.measure_rotation.assert_not_called() + client.devices.aerotech.trigger.assert_not_called() + + +def test_rotation_scan_refuses_too_long_scans(tasks, client): + with pytest.raises(ValueError, match="too long"): + tasks.rotation_scan(exp_time_s=1.0, incr_omega_deg=0.1, steps=int(MAX_ROTATION_SCAN_S) + 1) + client.devices.aerotech.scan_type.set.assert_not_called() + + +def test_rotation_scan_cancels_jfjoch_if_the_aerotech_scan_fails(tasks, client): + client.devices.aerotech.trigger.return_value.wait.side_effect = RuntimeError("stage fault") + with pytest.raises(RuntimeError, match="stage fault"): + tasks.rotation_scan(**ROTATION) + client.jfjoch.cancel.assert_called_once_with() + + +def test_beam_conditions_are_read_from_the_devices(client, monkeypatch): + monkeypatch.setenv("BEAMLINE", "X10SA") + tasks = MxTasks[Server](client) + # energy and flux come from beamline plugin calibrations + energy_and_flux = MagicMock(return_value=(12658.0, 2e12)) + monkeypatch.setattr(tasks, "_energy_eV_and_full_flux_ph_s", energy_and_flux) + + beam = tasks._beam_conditions() + + energy_and_flux.assert_called_once_with(0.5) + assert beam.energy_keV == pytest.approx(12.658) + assert (beam.full_flux_ph_s, beam.transmission) == (2e12, 0.5) + assert (beam.detector_distance_mm, beam.ring_current_mA) == (200.0, 400.0) + assert beam.sample_temperature_K == 100.0 + # from aarecommon's measurements for X10SA, which lie around (2080, 2230) at this position + assert beam.beam_center_pxl == pytest.approx((2080, 2230), abs=30) + assert beam.beam_size_mm == pytest.approx((0.025, 0.025)) + + +def test_beam_center_needs_measurements_for_the_beamline(client, monkeypatch): + monkeypatch.setenv("BEAMLINE", "SIMULATED") + with pytest.raises(ValueError, match="no beam centre measurements"): + MxTasks[Server](client)._beam_center_pxl(200.0, 62.0) + + +# ---- the tasks built on the grid and rotation scans; none of them may go through AareDAQ ---- + + +def test_multiple_rasters_scans_at_each_omega_and_returns_to_the_centre(tasks, client): + client.sample_info = SampleInfo(sample_id=5) + tasks.multiple_rasters([0.0, 90.0], **GRID, file_prefix="multi") + endpoint, msg = client.connector.set_and_publish.call_args.args + + scans = [c.args[0] for c in client.jfjoch.measure_raster.call_args_list] + assert [scan.omega_deg for scan in scans] == [0.0, 90.0] + assert scans[0].file_prefix.startswith("multi_0_0.00deg_") + assert scans[1].file_prefix.startswith("multi_1_90.00deg_") + # to the corner and back for each grid, so every grid is centred on the same point + to_corner = call(pytest.approx(-0.1), pytest.approx(-0.06)) + back = call(pytest.approx(0.1), pytest.approx(0.06)) + assert client.devices.smargon.nudge_in_lab_frame.call_args_list == [ + to_corner, + back, + to_corner, + back, + ] + assert endpoint == StateEndpoints.sample_done() + assert (msg.sample_id, msg.success) == (5, True) + assert client.aaredaq.mock_calls == [] + + +def test_multiple_rasters_returns_to_the_centre_if_a_scan_fails(tasks, client): + client.devices.aerotech.trigger.return_value.wait.side_effect = RuntimeError("stage fault") + with pytest.raises(RuntimeError, match="stage fault"): + tasks.multiple_rasters([0.0, 90.0], **GRID) + assert client.devices.smargon.nudge_in_lab_frame.call_count == 2 + + +def test_xray_centering_records_the_raster_and_stays_at_its_start(tasks, client): + client.sample_info = SampleInfo(sample_id=5) + strategy = dict(GRID, omega_deg=30.0, file_prefix="xc", dtz=200.0) + + tasks.xray_centering(5, strategy) + endpoint, msg = client.connector.set_and_publish.call_args.args + + client.jfjoch.measure_raster.assert_called_once() + client.devices.smargon.nudge_in_lab_frame.assert_called_once() + raster = client.sample_info.raster + assert raster.strategy == strategy + assert raster.images == [1, 2, 3] + assert (raster.geometry.n_x, raster.geometry.n_y) == (4, 3) + assert raster.geometry.omega_deg == 30.0 + assert endpoint == StateEndpoints.xray_centering_done() + assert (msg.sample_id, msg.success) == (5, True) + assert client.aaredaq.mock_calls == [] + + +def test_collect_dataset_runs_a_rotation_scan_per_chi(tasks, client): + client.sample_info = SampleInfo(sample_id=5) + plan = RotationPlan( + position_index=0, + offset_x_mm=0.0, + offset_y_mm=0.0, + chi_deg_list="0,20", + incr_omega_deg=0.1, + steps=100, + exp_time_s=0.05, + transmission=0.2, + dtz=180.0, + file_prefix="data", + dose_MGy=1.0, + target_res_A=2.0, + ) + + tasks.collect_dataset(5, plan.model_dump()) + endpoint, msg = client.connector.set_and_publish.call_args.args + + scans = [c.args[0] for c in client.jfjoch.measure_rotation.call_args_list] + assert [scan.file_prefix for scan in scans] == ["data_chi0", "data_chi20"] + assert [scan.steps for scan in scans] == [100, 100] + chi = client.devices.smargon.chi.set + assert chi.call_args_list == [call(0.0), call(20.0), call(0.0)] # and back to 0 at the end + [record] = client.sample_info.collections + assert [(s.chi_deg, s.images, s.bravais) for s in record.sweeps] == [ + (0.0, [1, 2, 3], "tP"), + (20.0, [1, 2, 3], "tP"), + ] + assert endpoint == StateEndpoints.rotation_done() + assert (msg.sample_id, msg.success) == (5, True) + assert client.aaredaq.mock_calls == [] + + +def _prediction(target_point, geometry=None): + return LatestPredictionModel( + frame_id=1, + time=0.0, + image_width=1000, + image_height=800, + target_point=target_point, + geometry=geometry, + conf=0.5, + infer_scale=1.0, + skip=0, + max_fps=10.0, + tracker="none", + worker_shard_index=0, + worker_shard_count=1, + pixel_format="BGR", + ) + + +def _optical_centering(tasks, client, prediction): + """Run the task with `prediction` as what the optical prediction service returns.""" + client.sample_info = SampleInfo(sample_id=5) + + def update_latest(): + client.sample_info.optical_centering_results = OpticalCenteringResults( + prediction=prediction, microns_per_pixel=2.0 + ) + + client.optical_prediction.update_latest.side_effect = update_latest + tasks.run_optical_centering(5) + return client.connector.set_and_publish.call_args.args + + +def test_optical_centering_nudges_the_target_point_to_the_beam(tasks, client): + geometry = dict(zoom=400.0, um_per_px=2.0, beam_x=600.0, beam_y=300.0, source="test") + target = dict(x=650, y=250, source="test") + endpoint, msg = _optical_centering(tasks, client, _prediction(target, geometry)) + # 50 px right of and 50 px above the beam, at 2 um per pixel + client.devices.smargon.nudge_in_lab_frame.assert_called_once_with( + pytest.approx(0.1), pytest.approx(-0.1) + ) + # the prediction is taken again once the sample has moved + assert client.optical_prediction.update_latest.call_count == 2 + assert endpoint == StateEndpoints.optical_centering_done() + assert (msg.sample_id, msg.success) == (5, True) + assert client.aaredaq.mock_calls == [] + + +def test_optical_centering_assumes_the_beam_at_the_image_centre_without_geometry(tasks, client): + _optical_centering(tasks, client, _prediction(dict(x=400, y=500, source="test"))) + client.devices.smargon.nudge_in_lab_frame.assert_called_once_with( + pytest.approx(-0.2), pytest.approx(0.2) + ) + + +def test_optical_centering_fails_without_a_target_point(tasks, client): + endpoint, msg = _optical_centering(tasks, client, _prediction(None)) + client.devices.smargon.nudge_in_lab_frame.assert_not_called() + assert endpoint == StateEndpoints.optical_centering_done() + assert (msg.sample_id, msg.success) == (5, False) diff --git a/tests/unit/test_jfjoch.py b/tests/unit/test_jfjoch.py index 6ca23a4..8c8fa72 100644 --- a/tests/unit/test_jfjoch.py +++ b/tests/unit/test_jfjoch.py @@ -3,12 +3,12 @@ from unittest.mock import MagicMock, patch import pytest from pydantic import ValidationError -from mx_bec.jfjoch import JFJoch, JFJochError, RasterScan, RotationScan +from mx_bec.external_services.jfjoch import JFJoch, JFJochError, RasterScan, RotationScan @pytest.fixture def api(): - with patch("mx_bec.jfjoch.jfjoch_client") as jfjoch_client: + with patch("mx_bec.external_services.jfjoch.jfjoch_client") as jfjoch_client: yield jfjoch_client.DefaultApi.return_value @@ -51,8 +51,10 @@ def test_url_is_resolved_from_beamline_config_on_first_use(client, monkeypatch): monkeypatch.delenv("BEAMLINE", raising=False) jfjoch = JFJoch(client) # must not need BEAMLINE yet with ( - patch("mx_bec.jfjoch.mx_beamline", return_value="X10SA") as beamline, - patch("mx_bec.jfjoch.get_jfjoch_url", return_value="http://gpu:8080") as get_url, + patch("mx_bec.external_services.jfjoch.mx_beamline", return_value="X10SA") as beamline, + patch( + "mx_bec.external_services.jfjoch.get_jfjoch_url", return_value="http://gpu:8080" + ) as get_url, ): assert jfjoch.url == "http://gpu:8080" assert jfjoch.url == "http://gpu:8080" @@ -99,7 +101,7 @@ def test_wait_till_done_returns_scan_result(jfjoch, api): def test_measure_raster_builds_grid_dataset_settings(jfjoch): # re-patch to capture the DatasetSettings constructor; connect() happens inside, so the # API mock to check is this patch's, not the `api` fixture's - with patch("mx_bec.jfjoch.jfjoch_client") as jfjoch_client: + with patch("mx_bec.external_services.jfjoch.jfjoch_client") as jfjoch_client: jfjoch.measure_raster(_scan()) settings = jfjoch_client.DatasetSettings.call_args.kwargs assert settings["ntrigger"] == 2 and settings["images_per_trigger"] == 3 @@ -126,7 +128,7 @@ def test_measure_rotation_builds_rotation_dataset_settings(jfjoch): grid_fields = ("n_x", "n_y", "step_x_mm", "step_y_mm", "omega_deg") common = {k: v for k, v in _scan().model_dump().items() if k not in grid_fields} scan = RotationScan(steps=900, incr_omega_deg=0.2, start_omega_deg=30.0, **common) - with patch("mx_bec.jfjoch.jfjoch_client") as jfjoch_client: + with patch("mx_bec.external_services.jfjoch.jfjoch_client") as jfjoch_client: jfjoch.measure_rotation(scan) settings = jfjoch_client.DatasetSettings.call_args.kwargs # the whole rotation is one trigger, and there is no grid @@ -143,22 +145,22 @@ def test_measure_rotation_builds_rotation_dataset_settings(jfjoch): def test_single_column_raster_is_one_trigger(jfjoch): - with patch("mx_bec.jfjoch.jfjoch_client") as jfjoch_client: + with patch("mx_bec.external_services.jfjoch.jfjoch_client") as jfjoch_client: jfjoch.dataset_settings(_scan(n_x=1, n_y=4)) settings = jfjoch_client.DatasetSettings.call_args.kwargs assert settings["ntrigger"] == 1 and settings["images_per_trigger"] == 4 def test_dataset_settings_clamps_negative_chi(jfjoch): - with patch("mx_bec.jfjoch.DatasetSettingsSmargon") as smargon: + with patch("mx_bec.external_services.jfjoch.DatasetSettingsSmargon") as smargon: jfjoch.dataset_settings(_scan()) smargon.assert_called_once_with(phi_deg=10.0, chi_deg=0) def test_dataset_settings_without_smargon_angles(jfjoch): with ( - patch("mx_bec.jfjoch.jfjoch_client") as jfjoch_client, - patch("mx_bec.jfjoch.DatasetSettingsSmargon") as smargon, + patch("mx_bec.external_services.jfjoch.jfjoch_client") as jfjoch_client, + patch("mx_bec.external_services.jfjoch.DatasetSettingsSmargon") as smargon, ): jfjoch.dataset_settings(_scan(smargon_phi_deg=None)) smargon.assert_not_called() -- 2.54.1 From 9a94dc715d6f4796bd87e58d3c893ac31305817d Mon Sep 17 00:00:00 2001 From: David Perl Date: Wed, 2 Dec 2026 13:07:29 +0100 Subject: [PATCH 05/11] refactor: remove now unused aaredaq stuff --- .../widgets/aare_bec/task_panel.py | 20 +- mx_bec/external_services/aaredaq.py | 63 +--- mx_bec/external_services/optical_centering.py | 17 ++ mx_bec/tasks/mx_tasks.py | 279 +++++++----------- tests/unit/test_aaredaq.py | 46 +-- tests/unit/test_aaredaq_tasks.py | 73 +---- 6 files changed, 145 insertions(+), 353 deletions(-) diff --git a/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py b/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py index 39fe8cc..cd093c1 100644 --- a/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py +++ b/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py @@ -28,19 +28,7 @@ logger = bec_logger.logger TASK_FORMS: dict[str, list[tuple[str, int | float | str | list[float]]]] = { "aaredaq_mount_sample": [("dbid", 0)], "run_optical_centering": [("sample_id", 0)], - "cleanup_beamline": [], - # the AareDAQ-driven tasks; their bool/optional arguments keep their defaults here - "aaredaq_raster_scan": [ - ("n_x", 4), - ("n_y", 3), - ("step_x_mm", 0.05), - ("step_y_mm", 0.05), - ("exp_time_s", 0.1), - ("omega_deg", 0.0), - ("dtz", 250), - ("file_prefix", "AareBecTestGridScan"), - ], - # the same scan run by BEC itself (Smargon, JFJoch and Aerotech), without AareDAQ + # run by BEC itself: Smargon, JFJoch and Aerotech "grid_scan": [ ("n_x", 4), ("n_y", 3), @@ -67,12 +55,6 @@ TASK_FORMS: dict[str, list[tuple[str, int | float | str | list[float]]]] = { ("dtz", 200), ("file_prefix", "AareBecTestGridScan"), ], - "aaredaq_rotation_scan": [ - ("exp_time_s", 0.05), - ("incr_omega_deg", 0.1), - ("steps", 100), - ("start_omega_deg", 0.0), - ], } diff --git a/mx_bec/external_services/aaredaq.py b/mx_bec/external_services/aaredaq.py index 257143d..cd0fcc3 100644 --- a/mx_bec/external_services/aaredaq.py +++ b/mx_bec/external_services/aaredaq.py @@ -9,8 +9,6 @@ import requests from aarecommon.config.beamline import cfg_get, mx_beamline from aarecommon.models.auth import BatonStatus 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: @@ -29,7 +27,7 @@ DEFAULT_CERT_PATHS = { } TOKEN_TIMEOUT_S = 120.0 REQUEST_TIMEOUT_S = 30.0 # for quick calls such as the baton endpoints -SCAN_TIMEOUT_S = 3600.0 # the scan endpoints block until the scan is done +MOUNT_TIMEOUT_S = 600.0 # the mount endpoint blocks until the sample is mounted BATON_WAIT_S = 60.0 # covers the server's 30 s for the current holder to answer a request BATON_POLL_INTERVAL_S = 1.0 @@ -39,13 +37,14 @@ class AareDaqError(RuntimeError): class AareDaq: - """Client for the AareDAQ REST API (aaredaq `server.py`). + """Client for the part of the AareDAQ REST API (aaredaq `server.py`) which AareBec still uses: + mounting a sample. 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. Hardware operations - take the beamline baton first if this session does not hold it yet. + its certificate come from the aarecommon beamline config unless given. AareDAQ only mounts + for the session holding the beamline baton, so it is taken first if not held yet. """ def __init__( @@ -111,7 +110,7 @@ class AareDaq: *, params: dict[str, Any] | None = None, body: dict[str, Any] | None = None, - timeout_s: float = SCAN_TIMEOUT_S, + timeout_s: float = REQUEST_TIMEOUT_S, ) -> Any: """Call `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.""" @@ -148,7 +147,7 @@ class AareDaq: *, params: dict[str, Any] | None = None, body: dict[str, Any] | None = None, - timeout_s: float = SCAN_TIMEOUT_S, + timeout_s: float = REQUEST_TIMEOUT_S, ) -> Any: return self._request("POST", endpoint, params=params, body=body, timeout_s=timeout_s) @@ -182,10 +181,6 @@ class AareDaq: if time.monotonic() > deadline: raise AareDaqError(f"AareDAQ baton not granted within {wait_s} s: {result}") - def release_baton(self) -> None: - """Release the baton, leaving the beamline vacant.""" - self._post("/baton/release", timeout_s=REQUEST_TIMEOUT_S) - def ensure_baton(self) -> None: """Take the baton unless this session already holds it.""" if not self.baton_status().you_are_holder: @@ -193,50 +188,12 @@ class AareDaq: # ---- hardware operations ---- - def mount_sample(self, dbid: int, reference: bool = False, timeout_s: float = 600.0) -> None: + def mount_sample( + self, dbid: int, reference: bool = False, timeout_s: float = MOUNT_TIMEOUT_S + ) -> None: """Mount the sample with database id `dbid` (from the reference tools if `reference`).""" self.ensure_baton() 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 unmount_sample_then_park(self, timeout_s: float = 600.0) -> None: - """unmount the current sample.""" - self.ensure_baton() - logger.info("AareDAQ: unmounting sample, then putting the robot to a safe place") - self._post("/sample/unmount_then_park_and_dry", timeout_s=timeout_s) - - def auto_loop_center(self): - self.ensure_baton() - self._post("/alc/center_loop") - - 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).""" - self.ensure_baton() - 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).""" - self.ensure_baton() - 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) diff --git a/mx_bec/external_services/optical_centering.py b/mx_bec/external_services/optical_centering.py index a8748c2..b44a826 100644 --- a/mx_bec/external_services/optical_centering.py +++ b/mx_bec/external_services/optical_centering.py @@ -15,6 +15,23 @@ if TYPE_CHECKING: logger = bec_logger.logger +def target_offset_mm(results: OpticalCenteringResults) -> tuple[float, float] | None: + """Where the prediction's target point is relative to the beam, as (x, y) in mm in the image + plane (x to the right, y down), or None if no target point was found. The beam is where the + prediction's geometry puts it, or else at the centre of the image.""" + prediction = results.prediction + if (target := prediction.target_point) is None: + return None + geometry = prediction.geometry + if geometry is not None and geometry.beam_x is not None and geometry.beam_y is not None: + beam_x, beam_y = geometry.beam_x, geometry.beam_y + else: + logger.warning("The prediction has no beam position, assuming the centre of the image") + beam_x, beam_y = prediction.image_width / 2, prediction.image_height / 2 + mm_per_pixel = results.microns_per_pixel / 1000.0 + return (target.x - beam_x) * mm_per_pixel, (target.y - beam_y) * mm_per_pixel + + class OpticalPrediction: def __init__(self, client: AareBec): self._client = client diff --git a/mx_bec/tasks/mx_tasks.py b/mx_bec/tasks/mx_tasks.py index 589ce3b..a1142e8 100644 --- a/mx_bec/tasks/mx_tasks.py +++ b/mx_bec/tasks/mx_tasks.py @@ -7,13 +7,7 @@ from secrets import token_hex from typing import TYPE_CHECKING from aarecommon.config.beamline import mx_beamline -from aarecommon.math.coordinate import Coordinate, SmargonCoordinate from aarecommon.models.beam_centre import BeamCentre -from aarecommon.models.raster_grid import ( - CompletedRasterGrid, # already imported in aaredaq.py - RasterGridRequest, -) -from aarecommon.models.rotation_scan import RotationScanRequest from bec_lib.logger import bec_logger from mx_bec.decisions import ( @@ -23,16 +17,17 @@ from mx_bec.decisions import ( RasterRecord, RotationPlan, SweepRecord, - scan_images, - smargon_nudge, ) from mx_bec.device_planner import BeamlineState, StateChangePlanner, init_beamline_environment from mx_bec.endpoints import StateEndpoints from mx_bec.external_services.jfjoch import DataCollection, RasterScan, RotationScan +from mx_bec.external_services.optical_centering import target_offset_mm from mx_bec.messages import MXMeasurementSequenceMessage from mx_bec.tasks.core import MxSequenceUpdate, RoleT, TaskManager, task if TYPE_CHECKING: + from jfjoch_client.models.scan_result import ScanResult + from mx_bec.service import AareBec logger = bec_logger.logger @@ -83,12 +78,24 @@ class MxTasks(TaskManager[RoleT]): @task def run_optical_centering(self, sample_id: int): - """warning: Updates the sample id to whatever you enter even if it's not the real one!""" + """Naive optical centering: take the loop prediction for the sample camera image and + nudge the Smargon so that the prediction's target point sits in the beam. One view only, + so the sample is not centred along the beam. Fails if the prediction has no target point. + warning: Updates the sample id to whatever you enter even if it's not the real one!""" if self._client.sample_info is None or self._client.sample_info.sample_id != sample_id: self._client.reset_sample_info(sample_id) - self._client.aaredaq.auto_loop_center() self._client.scans.mv(self._client.devices.scam_zoom, 400, relative=False).wait() - self._client.optical_prediction.update_latest() + prediction = self._client.optical_prediction + prediction.update_latest() + results = self._client.sample_info.optical_centering_results + offset_mm = target_offset_mm(results) if results is not None else None + if offset_mm is None: + logger.warning("Optical centering: no target point predicted, not moving the sample") + return self._optical_centering_done_update(sample_id, success=False) + logger.info(f"Optical centering: nudging the target point to the beam, {offset_mm=}") + # same convention as the grid scans: a nudge by v brings the point at v into the beam + self._client.devices.smargon.nudge_in_lab_frame(*offset_mm) + prediction.update_latest() # the results for the grid strategy describe the centred loop return self._optical_centering_done_update(sample_id, success=True) def _optical_centering_done_update(self, sample_id: int, *, success: bool): @@ -116,11 +123,6 @@ class MxTasks(TaskManager[RoleT]): MXMeasurementSequenceMessage(sample_id=dbid, success=True), ) - @task - def cleanup_beamline(self): - """Unmount the current sample and send the gripper to dry""" - self._client.aaredaq.unmount_sample_then_park() - @task def multiple_rasters( self, @@ -133,17 +135,19 @@ class MxTasks(TaskManager[RoleT]): file_prefix: str | None = None, dtz: float | None = None, ) -> MxSequenceUpdate: - """Run multiple raster scans at different omega values""" + """Run multiple raster scans at different omega values, each centred on the position + the Smargon is at now.""" for i, omega in enumerate(omegas_deg_list): - self._run_raster( + self._grid_scan( n_x, n_y, step_x_mm, step_y_mm, exp_time_s, - file_prefix=f"{file_prefix}_{i}_{omega:.2f}deg_{token_hex(3)}", - dtz=dtz, omega_deg=omega, + file_prefix=f"{file_prefix or 'grid'}_{i}_{omega:.2f}deg_{token_hex(3)}", + dtz=dtz, + return_to_centre=True, ) logger.info(f"Raster {i + 1} out of {len(omegas_deg_list)} done.") return ( @@ -153,114 +157,6 @@ class MxTasks(TaskManager[RoleT]): ), ) - @task - def aaredaq_rotation_scan( - self, - exp_time_s: float, - incr_omega_deg: float, - steps: int, - start_omega_deg: float = 0.0, - file_prefix: str | None = None, - dtz: float | None = None, - transmission: float | None = None, - screening: bool = False, - wedge_omega_deg: float | None = None, - ) -> None: - """Have AareDAQ run a rotation (or screening) scan of `steps` images of `incr_omega_deg` - each, starting at the current Smargon position (`start`/`end` are left unset).""" - request = RotationScanRequest( - exp_time_s=exp_time_s, - incr_omega_deg=incr_omega_deg, - steps=steps, - start_omega_deg=start_omega_deg, - file_prefix=file_prefix, - dtz=dtz, - transmission=transmission, - screening=screening, - wedge_omega_deg=wedge_omega_deg, - ) - result = self._client.aaredaq.rotation_scan(request) - logger.info(f"AareDAQ rotation scan done: {len(result.result.images)} images") - - def _run_raster( - self, - n_x: int, - n_y: int, - step_x_mm: float, - step_y_mm: float, - exp_time_s: float, - omega_deg: float = 0.0, - file_prefix: str | None = None, - dtz: float | None = None, - transmission: float | None = None, - smargon_top_left: SmargonCoordinate | None = None, - auto_center: bool = False, - ) -> CompletedRasterGrid: - if not smargon_top_left: - x_offset_mm = n_x * step_x_mm * 0.5 - y_offset_mm = n_y * step_y_mm * 0.5 - logger.info( - f"offsetting smargon x,y by half of grid: {x_offset_mm=} {y_offset_mm=} (grid x to smargon z)" - ) - smargon = self._client.devices.smargon - # aerotech = self._client.devices.aerotech - adjustment = smargon_nudge( - smargon.phi.get(), - smargon.chi.get(), - omega_deg, - Coordinate(x=x_offset_mm, y=y_offset_mm, z=0), - ) - smargon_top_left = SmargonCoordinate( - sh_mm=Coordinate(x=smargon.x.get(), y=smargon.y.get(), z=smargon.z.get()) - - adjustment, - chi_deg=smargon.chi.get(), - phi_deg=smargon.phi.get(), - ) - logger.info(f"Smargon top left: {smargon_top_left}") - request = RasterGridRequest( - n_x=n_x, - n_y=n_y, - grid_size_mm=Coordinate(x=step_x_mm, y=step_y_mm), - exp_time_s=exp_time_s, - omega_deg=omega_deg, - file_prefix=file_prefix, - dtz=dtz, - transmission=transmission, - smargon_top_left=smargon_top_left, - ) - result = self._client.aaredaq.raster_scan(request, auto_center=auto_center) - logger.info(f"Raster scan finished with {len(scan_images(result))} images") - return result - - @task - def aaredaq_raster_scan( - self, - n_x: int, - n_y: int, - step_x_mm: float, - step_y_mm: float, - exp_time_s: float, - omega_deg: float = 0.0, - file_prefix: str | None = None, - dtz: float | None = None, - transmission: float | None = None, - smargon_top_left: SmargonCoordinate | None = None, - auto_center: bool = False, - ) -> None: - self._run_raster( - n_x, - n_y, - step_x_mm, - step_y_mm, - exp_time_s, - omega_deg, - file_prefix, - dtz, - transmission, - smargon_top_left, - auto_center, - ) - def _read(self, device: str) -> float: """The current value of the device (or signal) with this name.""" return self._client.devices[device].read()[device]["value"] @@ -376,9 +272,9 @@ class MxTasks(TaskManager[RoleT]): smargon_chi_deg=smargon.chi.get(), ) - def _collect(self, scan: DataCollection, description: str) -> None: - """Arm JFJoch for `scan`, trigger the Aerotech scan which was configured for it, and wait - for both to finish.""" + def _collect(self, scan: DataCollection, description: str) -> ScanResult: + """Arm JFJoch for `scan`, trigger the Aerotech scan which was configured for it, wait for + both to finish, and return the JFJoch result.""" jfjoch = self._client.jfjoch if isinstance(scan, RasterScan): jfjoch.measure_raster(scan) @@ -396,6 +292,51 @@ class MxTasks(TaskManager[RoleT]): jfjoch.cancel() raise logger.info(f"Finished {description}: {result.file_prefix}, {len(result.images)} images") + return result + + def _grid_scan( + self, + n_x: int, + n_y: int, + step_x_mm: float, + step_y_mm: float, + exp_time_s: float, + omega_deg: float = 0.0, + file_prefix: str | None = None, + dtz: float | None = None, + transmission: float | None = None, + return_to_centre: bool = False, + ) -> ScanResult: + """Collect a grid scan as the `grid_scan` task describes and return the JFJoch result. + The Smargon stays at the top left corner of the grid, unless `return_to_centre` undoes + the nudge to the corner once the scan is done.""" + expected_s = exp_time_s * n_x * n_y + n_y * 0.3 + if expected_s > MAX_GRID_SCAN_S: + raise ValueError(f"Grid scan is too long: {expected_s:.0f} s > {MAX_GRID_SCAN_S} s") + self._set_grid_scan_prerequisites( + n_x, n_y, step_x_mm, step_y_mm, exp_time_s, omega_deg, dtz, transmission + ) + + x_offset_mm, y_offset_mm = n_x * step_x_mm * 0.5, n_y * step_y_mm * 0.5 + logger.info(f"Nudging smargon to the top left of the grid: -{x_offset_mm=} -{y_offset_mm=}") + # smargopolo applies the nudge for its own reading of omega, which is now the scan's omega + smargon = self._client.devices.smargon + smargon.nudge_in_lab_frame(-x_offset_mm, -y_offset_mm) + try: + scan = RasterScan( + n_x=n_x, + n_y=n_y, + step_x_mm=step_x_mm, + step_y_mm=step_y_mm, + omega_deg=omega_deg, + exp_time_s=exp_time_s, + **self._data_collection_settings(file_prefix or f"grid_{token_hex(3)}"), + ) + return self._collect(scan, f"{n_x}x{n_y} grid scan, {exp_time_s} s per element") + finally: + if return_to_centre: + self._client.devices.aerotech.u.set(omega_deg).wait() + smargon.nudge_in_lab_frame(x_offset_mm, y_offset_mm) @task def grid_scan( @@ -410,35 +351,15 @@ class MxTasks(TaskManager[RoleT]): dtz: float | None = None, transmission: float | None = None, ) -> None: - """Collect an n_x by n_y grid scan centred on the current position, without AareDAQ: set - the prerequisites (omega, the detector distance `dtz` and the transmission if given, the - Aerotech grid scan), nudge the Smargon to the top left corner of the grid, arm JFJoch, - then trigger the Aerotech and wait for both to finish. The Smargon stays at the corner.""" - expected_s = exp_time_s * n_x * n_y + n_y * 0.3 - if expected_s > MAX_GRID_SCAN_S: - raise ValueError(f"Grid scan is too long: {expected_s:.0f} s > {MAX_GRID_SCAN_S} s") - self._set_grid_scan_prerequisites( - n_x, n_y, step_x_mm, step_y_mm, exp_time_s, omega_deg, dtz, transmission + """Collect an n_x by n_y grid scan centred on the current position: set the prerequisites + (omega, the detector distance `dtz` and the transmission if given, the Aerotech grid + scan), nudge the Smargon to the top left corner of the grid, arm JFJoch, then trigger the + Aerotech and wait for both to finish. The Smargon stays at the corner.""" + self._grid_scan( + n_x, n_y, step_x_mm, step_y_mm, exp_time_s, omega_deg, file_prefix, dtz, transmission ) - x_offset_mm, y_offset_mm = n_x * step_x_mm * 0.5, n_y * step_y_mm * 0.5 - logger.info(f"Nudging smargon to the top left of the grid: -{x_offset_mm=} -{y_offset_mm=}") - # smargopolo applies the nudge for its own reading of omega, which is now the scan's omega - self._client.devices.smargon.nudge_in_lab_frame(-x_offset_mm, -y_offset_mm) - - scan = RasterScan( - n_x=n_x, - n_y=n_y, - step_x_mm=step_x_mm, - step_y_mm=step_y_mm, - omega_deg=omega_deg, - exp_time_s=exp_time_s, - **self._data_collection_settings(file_prefix or f"grid_{token_hex(3)}"), - ) - self._collect(scan, f"{n_x}x{n_y} grid scan, {exp_time_s} s per element") - - @task - def rotation_scan( + def _rotation_scan( self, exp_time_s: float, incr_omega_deg: float, @@ -447,11 +368,9 @@ class MxTasks(TaskManager[RoleT]): file_prefix: str | None = None, dtz: float | None = None, transmission: float | None = None, - ) -> None: - """Collect a rotation scan of `steps` images of `incr_omega_deg` each, from - `start_omega_deg`, at the current Smargon position and without AareDAQ: set the - prerequisites (the detector distance `dtz` and the transmission if given, the Aerotech - rotation scan), arm JFJoch, then trigger the Aerotech and wait for both to finish.""" + ) -> ScanResult: + """Collect a rotation scan as the `rotation_scan` task describes and return the JFJoch + result.""" total_time_s = exp_time_s * steps if total_time_s > MAX_ROTATION_SCAN_S: raise ValueError( @@ -475,13 +394,34 @@ class MxTasks(TaskManager[RoleT]): exp_time_s=exp_time_s, **self._data_collection_settings(file_prefix or f"rotation_{token_hex(3)}"), ) - self._collect( + return self._collect( scan, f"rotation scan, {steps} images of {incr_omega_deg} deg, {exp_time_s} s each" ) + @task + def rotation_scan( + self, + exp_time_s: float, + incr_omega_deg: float, + steps: int, + start_omega_deg: float = 0.0, + file_prefix: str | None = None, + dtz: float | None = None, + transmission: float | None = None, + ) -> None: + """Collect a rotation scan of `steps` images of `incr_omega_deg` each, from + `start_omega_deg`, at the current Smargon position: set the prerequisites (the detector + distance `dtz` and the transmission if given, the Aerotech rotation scan), arm JFJoch, + then trigger the Aerotech and wait for both to finish.""" + self._rotation_scan( + exp_time_s, incr_omega_deg, steps, start_omega_deg, file_prefix, dtz, transmission + ) + @task def xray_centering(self, dbid: int, strategy: dict) -> MxSequenceUpdate: - result = self._run_raster(**strategy) + """Collect the grid scan described by `strategy` (the arguments of `grid_scan`) and + record its per-image results for the sample. The Smargon stays at the raster start.""" + result = self._grid_scan(**strategy) info = self._client.sample_info if info is None or info.sample_id != dbid: self._client.reset_sample_info(dbid) @@ -496,7 +436,7 @@ class MxTasks(TaskManager[RoleT]): omega_deg=strategy.get("omega_deg", 0.0), snake=True, # jfjoch.dataset_settings uses GridScan(snake=True) ), - images=scan_images(result), + images=list(result.images), ) return ( StateEndpoints.xray_centering_done(), @@ -536,7 +476,7 @@ class MxTasks(TaskManager[RoleT]): try: for chi in p.chi_values(): smargon.chi.set(chi).wait() - request = RotationScanRequest( + result = self._rotation_scan( exp_time_s=p.exp_time_s, incr_omega_deg=p.incr_omega_deg, steps=p.steps, @@ -545,12 +485,9 @@ class MxTasks(TaskManager[RoleT]): dtz=p.dtz, transmission=p.transmission, ) - result = self._client.aaredaq.rotation_scan(request) record.sweeps.append( SweepRecord( - chi_deg=chi, - images=scan_images(result), - bravais=getattr(result.result, "rotation_bravais", None), + chi_deg=chi, images=list(result.images), bravais=result.rotation_bravais ) ) finally: diff --git a/tests/unit/test_aaredaq.py b/tests/unit/test_aaredaq.py index df11b44..1cd0e12 100644 --- a/tests/unit/test_aaredaq.py +++ b/tests/unit/test_aaredaq.py @@ -2,10 +2,7 @@ import subprocess from unittest.mock import MagicMock, call, patch import pytest -from aarecommon.math.coordinate import Coordinate, SmargonCoordinate from aarecommon.models.auth import BatonStatus -from aarecommon.models.raster_grid import CompletedRasterGrid, RasterGridRequest -from aarecommon.models.rotation_scan import CompletedRotationScan, RotationScanRequest from mx_bec.external_services.aaredaq import DEFAULT_URLS, AareDaq, AareDaqError @@ -61,20 +58,6 @@ def _set_posts(daq, *responses): ) -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 @@ -135,28 +118,6 @@ def test_mount_sample(daq): ] -def test_raster_scan(daq): - request = _raster_request() - completed = CompletedRasterGrid(r=[]) - _set_posts(daq, _response(json_data=completed.model_dump(mode="json"))) - assert daq.raster_scan(request, auto_center=True) == completed - [(url, kwargs)] = _calls(daq, "POST") - assert url == 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": []}) - _set_posts(daq, _response(json_data=completed.model_dump(mode="json"))) - assert daq.rotation_scan(request) == completed - [(url, kwargs)] = _calls(daq, "POST") - assert url == f"{URL}/scan/rotation" - assert 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"}')] _set_posts(daq, _response(401), _response(json_data="OK")) @@ -176,7 +137,7 @@ def test_persistent_401_is_an_error(daq): def test_http_error_reports_status_and_body(daq): _set_posts(daq, _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)) + daq.mount_sample(1) # ---- baton ---- @@ -246,8 +207,3 @@ def test_take_baton_gives_up_after_wait(daq): pytest.raises(AareDaqError, match="not granted"), ): daq.take_baton(wait_s=0) - - -def test_release_baton(daq): - daq.release_baton() - assert [url for url, _ in _calls(daq, "POST")] == [f"{URL}/baton/release"] diff --git a/tests/unit/test_aaredaq_tasks.py b/tests/unit/test_aaredaq_tasks.py index 86edf63..ad67290 100644 --- a/tests/unit/test_aaredaq_tasks.py +++ b/tests/unit/test_aaredaq_tasks.py @@ -1,23 +1,13 @@ from unittest.mock import MagicMock import pytest -from aarecommon.math.coordinate import Coordinate, SmargonCoordinate -from aarecommon.models.raster_grid import RasterGridRequest -from aarecommon.models.rotation_scan import RotationScanRequest -from mx_bec.decisions import smargon_nudge from mx_bec.tasks import MxTasks, Server -# where the mock smargon sits -SMARGON_POSITION = {"x": 1.0, "y": 2.0, "z": 3.0, "phi": 0.0, "chi": 0.0} - @pytest.fixture def client(): - client = MagicMock() - for axis, position in SMARGON_POSITION.items(): - getattr(client.devices.smargon, axis).get.return_value = position - return client + return MagicMock() @pytest.fixture @@ -25,11 +15,15 @@ def tasks(client): return MxTasks[Server](client) +def test_mount_sample_is_a_task(): + assert MxTasks.is_task("aaredaq_mount_sample") + + @pytest.mark.parametrize( - "name", ["aaredaq_mount_sample", "aaredaq_raster_scan", "aaredaq_rotation_scan"] + "name", ["aaredaq_raster_scan", "aaredaq_rotation_scan", "cleanup_beamline"] ) -def test_aaredaq_methods_are_tasks(name): - assert MxTasks.is_task(name) +def test_other_aaredaq_tasks_are_gone(name): + assert not MxTasks.is_task(name) def test_mount_sample(tasks, client): @@ -39,57 +33,6 @@ def test_mount_sample(tasks, client): client.aaredaq.mount_sample.assert_called_with(7, reference=True) -def test_raster_scan_builds_request_from_flat_arguments(tasks, client): - tasks.aaredaq_raster_scan( - n_x=4, n_y=3, step_x_mm=0.05, step_y_mm=0.04, exp_time_s=0.1, omega_deg=12.0, dtz=150.0 - ) - request, kwargs = ( - client.aaredaq.raster_scan.call_args.args[0], - client.aaredaq.raster_scan.call_args.kwargs, - ) - # without a top left corner, the grid is centred on the current smargon position: the corner - # is half the grid away, in the lab frame at the scan's omega - half_grid = Coordinate(x=4 * 0.05 / 2, y=3 * 0.04 / 2, z=0) - top_left = Coordinate(x=1.0, y=2.0, z=3.0) - smargon_nudge(0.0, 0.0, 12.0, half_grid) - assert request == RasterGridRequest( - n_x=4, - n_y=3, - grid_size_mm=Coordinate(x=0.05, y=0.04), - exp_time_s=0.1, - omega_deg=12.0, - dtz=150.0, - smargon_top_left=SmargonCoordinate(sh_mm=top_left, chi_deg=0.0, phi_deg=0.0), - ) - assert kwargs == {"auto_center": False} - - -def test_raster_scan_uses_a_given_top_left_corner(tasks, client): - top_left = SmargonCoordinate(sh_mm=Coordinate(x=0.1, y=0.2, z=0.3), chi_deg=10.0, phi_deg=20.0) - tasks.aaredaq_raster_scan(1, 1, 0.05, 0.05, 0.1, smargon_top_left=top_left) - assert client.aaredaq.raster_scan.call_args.args[0].smargon_top_left == top_left - client.devices.smargon.x.get.assert_not_called() - - -def test_raster_scan_passes_auto_center(tasks, client): - tasks.aaredaq_raster_scan(1, 1, 0.05, 0.05, 0.1, auto_center=True) - assert client.aaredaq.raster_scan.call_args.kwargs == {"auto_center": True} - - -def test_rotation_scan_builds_request_from_flat_arguments(tasks, client): - tasks.aaredaq_rotation_scan( - exp_time_s=0.05, incr_omega_deg=0.1, steps=100, start_omega_deg=90.0, file_prefix="rot" - ) - assert client.aaredaq.rotation_scan.call_args.args[0] == RotationScanRequest( - exp_time_s=0.05, incr_omega_deg=0.1, steps=100, start_omega_deg=90.0, file_prefix="rot" - ) - - -def test_screening_scan(tasks, client): - tasks.aaredaq_rotation_scan(0.05, 1.0, 4, screening=True, wedge_omega_deg=90.0) - request = client.aaredaq.rotation_scan.call_args.args[0] - assert request.screening is True and request.wedge_omega_deg == 90.0 - - def test_failed_aaredaq_call_pauses_queue_and_reraises(tasks, client): client.aaredaq.mount_sample.side_effect = RuntimeError("sample not found") with pytest.raises(RuntimeError, match="sample not found"): -- 2.54.1 From 201dd968832c26232aab6758f261c5b17d37f7b7 Mon Sep 17 00:00:00 2001 From: David Perl Date: Wed, 2 Dec 2026 13:11:21 +0100 Subject: [PATCH 06/11] tidy up --- mx_bec/tasks/mx_tasks.py | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/mx_bec/tasks/mx_tasks.py b/mx_bec/tasks/mx_tasks.py index a1142e8..4094d1f 100644 --- a/mx_bec/tasks/mx_tasks.py +++ b/mx_bec/tasks/mx_tasks.py @@ -79,11 +79,10 @@ class MxTasks(TaskManager[RoleT]): @task def run_optical_centering(self, sample_id: int): """Naive optical centering: take the loop prediction for the sample camera image and - nudge the Smargon so that the prediction's target point sits in the beam. One view only, - so the sample is not centred along the beam. Fails if the prediction has no target point. - warning: Updates the sample id to whatever you enter even if it's not the real one!""" + nudge the Smargon so that the prediction's target point sits in the beam. One view only. + Fails if the prediction has no target point.""" if self._client.sample_info is None or self._client.sample_info.sample_id != sample_id: - self._client.reset_sample_info(sample_id) + logger.error("No sample mounted, cannot run optical centring") self._client.scans.mv(self._client.devices.scam_zoom, 400, relative=False).wait() prediction = self._client.optical_prediction prediction.update_latest() @@ -91,17 +90,17 @@ class MxTasks(TaskManager[RoleT]): offset_mm = target_offset_mm(results) if results is not None else None if offset_mm is None: logger.warning("Optical centering: no target point predicted, not moving the sample") - return self._optical_centering_done_update(sample_id, success=False) + return ( + StateEndpoints.optical_centering_done(), + MXMeasurementSequenceMessage(sample_id=sample_id, success=False), + ) logger.info(f"Optical centering: nudging the target point to the beam, {offset_mm=}") # same convention as the grid scans: a nudge by v brings the point at v into the beam self._client.devices.smargon.nudge_in_lab_frame(*offset_mm) prediction.update_latest() # the results for the grid strategy describe the centred loop - return self._optical_centering_done_update(sample_id, success=True) - - def _optical_centering_done_update(self, sample_id: int, *, success: bool): return ( StateEndpoints.optical_centering_done(), - MXMeasurementSequenceMessage(sample_id=sample_id, success=success), + MXMeasurementSequenceMessage(sample_id=sample_id, success=True), ) @task -- 2.54.1 From 9d86f6449de32c2e0ff9e450f74cef376859707b Mon Sep 17 00:00:00 2001 From: David Perl Date: Wed, 2 Dec 2026 13:55:45 +0100 Subject: [PATCH 07/11] tidy up: remove pxii specific macros --- mx_bec/actors/core.py | 5 +--- mx_bec/service.py | 17 ++++++++++++ mx_bec/tasks/mx_tasks.py | 46 ++++++++++--------------------- tests/unit/test_grid_scan_task.py | 13 +++++---- tests/unit/test_service.py | 10 ++++++- 5 files changed, 50 insertions(+), 41 deletions(-) diff --git a/mx_bec/actors/core.py b/mx_bec/actors/core.py index 9f3407e..d8c0695 100644 --- a/mx_bec/actors/core.py +++ b/mx_bec/actors/core.py @@ -109,14 +109,11 @@ class MXAutomationActor(SubscriptionActor, ABC): ) -> bool: """Plan a rotation dataset at a spot of the sample's grid analysis and queue it. Finishes the sample as failed, and returns False, if no dataset can be planned there.""" - # pyright: ignore[reportMissingImports] - from pxii_bec.macros.flux_macros import bpm2flux - info = client.sample_info assert info is not None, "No sample loaded" assert info.grid_analysis is not None, "No grid analysed" prefix = f"S{info.sample_id}_{secrets.token_hex(3)}" - _, self.strategy.beam.flux_ph_s = bpm2flux() + self.strategy.beam.flux_ph_s = client.full_flux_ph_s() # dummy data, for now try: plan = plan_rotation( info.grid_analysis, diff --git a/mx_bec/service.py b/mx_bec/service.py index d4da1c5..b4cdecf 100644 --- a/mx_bec/service.py +++ b/mx_bec/service.py @@ -28,6 +28,11 @@ if TYPE_CHECKING: logger = bec_logger.logger +# placeholders for what only beamline specific calibrations can tell, see `AareBec.energy_eV` and +# `AareBec.full_flux_ph_s` +DUMMY_ENERGY_EV = 12398.42 # a wavelength of 1 A +DUMMY_FULL_FLUX_PH_S = 1e12 + class AareBec(BECClient): """Custom MX BEC client, managing automation tasks and data flow.""" @@ -95,6 +100,18 @@ class AareBec(BECClient): def _start_actor_manager(self): self.actor_manager = AareActorManager(self) + def energy_eV(self) -> float: + """The photon energy. DUMMY DATA: the real value needs a beamline specific calibration + (monochromator angle to energy), which mx_bec does not have.""" + logger.warning(f"Using a dummy photon energy: {DUMMY_ENERGY_EV} eV") + return DUMMY_ENERGY_EV + + def full_flux_ph_s(self) -> float: + """The flux at the sample at transmission 1. DUMMY DATA: the real value needs a beamline + specific calibration (beam position monitor to flux), which mx_bec does not have.""" + logger.warning(f"Using a dummy full flux: {DUMMY_FULL_FLUX_PH_S:.1e} ph/s") + return DUMMY_FULL_FLUX_PH_S + def reset_sample_info(self, sample_id: int): self.sample_info = SampleInfo(sample_id=sample_id) diff --git a/mx_bec/tasks/mx_tasks.py b/mx_bec/tasks/mx_tasks.py index 4094d1f..c647103 100644 --- a/mx_bec/tasks/mx_tasks.py +++ b/mx_bec/tasks/mx_tasks.py @@ -160,21 +160,6 @@ class MxTasks(TaskManager[RoleT]): """The current value of the device (or signal) with this name.""" return self._client.devices[device].read()[device]["value"] - def _energy_eV_and_full_flux_ph_s(self, transmission: float) -> tuple[float, float]: - """The photon energy, from the monochromator angle, and the flux at the sample at - transmission 1, from the beam position monitor. Both come from PXII calibrations.""" - # pylint: disable=import-outside-toplevel - from pxii_bec.macros.calculator import ( # pyright: ignore[reportMissingImports] - convert_from_bragg, - ) - from pxii_bec.macros.flux_macros import bpm2flux # pyright: ignore[reportMissingImports] - - energy_eV = convert_from_bragg(self._read("dcm_bragg"))["energy_ev"] - _, full_flux = bpm2flux( - energy=energy_eV, bpmsum=self._read("bcu_bpmsum"), transm=transmission - ) - return energy_eV, full_flux - def _beam_center_pxl(self, det_z_mm: float, det_y_mm: float) -> tuple[float, float]: """Where the beam hits the detector at this detector position, from the beam centres which aarecommon has measured for the beamline.""" @@ -189,12 +174,11 @@ class MxTasks(TaskManager[RoleT]): def _beam_conditions(self) -> BeamConditions: transmission = self._read("transm") - energy_eV, full_flux = self._energy_eV_and_full_flux_ph_s(transmission) det_z_mm = self._read("det_z") beam_size_um = BeamState().beam_size_um # not measured: the strategy's default return BeamConditions( - energy_keV=energy_eV / 1000.0, - full_flux_ph_s=full_flux, + energy_keV=self._client.energy_eV() / 1000.0, # dummy data, for now + full_flux_ph_s=self._client.full_flux_ph_s(), # dummy data, for now transmission=transmission, detector_distance_mm=det_z_mm, beam_center_pxl=self._beam_center_pxl(det_z_mm, self._read("det_y")), @@ -257,19 +241,19 @@ class MxTasks(TaskManager[RoleT]): """The fields of a JFJoch `DataCollection` which describe the beamline as it is now.""" beam = self._beam_conditions() smargon = self._client.devices.smargon - return dict( - detector_distance_mm=beam.detector_distance_mm, - transmission=beam.transmission, - file_prefix=file_prefix, - energy_keV=beam.energy_keV, - beam_center_pxl=beam.beam_center_pxl, - beam_size_mm=beam.beam_size_mm, - ring_current_mA=beam.ring_current_mA, - flux_ph_s=beam.full_flux_ph_s, - sample_temperature_K=beam.sample_temperature_K, - smargon_phi_deg=smargon.phi.get(), - smargon_chi_deg=smargon.chi.get(), - ) + return { + "detector_distance_mm": beam.detector_distance_mm, + "transmission": beam.transmission, + "file_prefix": file_prefix, + "energy_keV": beam.energy_keV, + "beam_center_pxl": beam.beam_center_pxl, + "beam_size_mm": beam.beam_size_mm, + "ring_current_mA": beam.ring_current_mA, + "flux_ph_s": beam.full_flux_ph_s, + "sample_temperature_K": beam.sample_temperature_K, + "smargon_phi_deg": smargon.phi.get(), + "smargon_chi_deg": smargon.chi.get(), + } def _collect(self, scan: DataCollection, description: str) -> ScanResult: """Arm JFJoch for `scan`, trigger the Aerotech scan which was configured for it, wait for diff --git a/tests/unit/test_grid_scan_task.py b/tests/unit/test_grid_scan_task.py index 81992f0..c2d8379 100644 --- a/tests/unit/test_grid_scan_task.py +++ b/tests/unit/test_grid_scan_task.py @@ -9,7 +9,11 @@ from mx_bec.endpoints import StateEndpoints from mx_bec.external_services.jfjoch import RasterScan, RotationScan from mx_bec.sample_info import OpticalCenteringResults, SampleInfo from mx_bec.tasks import MxTasks, Server -from mx_bec.tasks.mx_tasks import MAX_GRID_SCAN_S, MAX_ROTATION_SCAN_S, BeamConditions +from mx_bec.tasks.mx_tasks import ( + MAX_GRID_SCAN_S, + MAX_ROTATION_SCAN_S, + BeamConditions, +) GRID = dict(n_x=4, n_y=3, step_x_mm=0.05, step_y_mm=0.04, exp_time_s=0.1) BEAM = BeamConditions( @@ -253,13 +257,12 @@ def test_rotation_scan_cancels_jfjoch_if_the_aerotech_scan_fails(tasks, client): def test_beam_conditions_are_read_from_the_devices(client, monkeypatch): monkeypatch.setenv("BEAMLINE", "X10SA") tasks = MxTasks[Server](client) - # energy and flux come from beamline plugin calibrations - energy_and_flux = MagicMock(return_value=(12658.0, 2e12)) - monkeypatch.setattr(tasks, "_energy_eV_and_full_flux_ph_s", energy_and_flux) + + client.energy_eV.return_value, client.full_flux_ph_s.return_value = 12658.0, 2e12 beam = tasks._beam_conditions() - energy_and_flux.assert_called_once_with(0.5) + # energy and flux come from the AareBec client assert beam.energy_keV == pytest.approx(12.658) assert (beam.full_flux_ph_s, beam.transmission) == (2e12, 0.5) assert (beam.detector_distance_mm, beam.ring_current_mA) == (200.0, 400.0) diff --git a/tests/unit/test_service.py b/tests/unit/test_service.py index 864ed10..509bf7b 100644 --- a/tests/unit/test_service.py +++ b/tests/unit/test_service.py @@ -8,7 +8,7 @@ from bec_lib.tests.utils import ConnectorMock from mx_bec.constants import AareBecWorkflowState from mx_bec.endpoints import QueueEndpoints from mx_bec.messages import MXQueueChangedMessage, MXTaskExecutionMessage -from mx_bec.service import AareBec +from mx_bec.service import DUMMY_ENERGY_EV, DUMMY_FULL_FLUX_PH_S, AareBec from mx_bec.tasks import MxTasks, RoleT, Server, task @@ -177,3 +177,11 @@ def test_failed_task_reraises_even_if_pausing_fails(): client.task_queue.pause.side_effect = ConnectionError("redis gone") with pytest.raises(RuntimeError, match="boom"): _FailingTasks[Server](client).boom() + + +def test_energy_and_full_flux_are_dummy_data_with_a_warning(service): + with patch("mx_bec.service.logger") as logger: + assert service.energy_eV() == DUMMY_ENERGY_EV + assert service.full_flux_ph_s() == DUMMY_FULL_FLUX_PH_S + messages = [c.args[0] for c in logger.warning.call_args_list] + assert len(messages) == 2 and all("dummy" in message for message in messages) -- 2.54.1 From 6fcc8543531eb0c649bba2b62773062cebaed358 Mon Sep 17 00:00:00 2001 From: David Perl Date: Wed, 2 Dec 2026 14:40:32 +0100 Subject: [PATCH 08/11] add forwarded auth infra --- mx_bec/automation_permission.py | 269 +++++++++++++++++++++++ mx_bec/endpoints.py | 38 ++++ mx_bec/external_services/aaredaq.py | 146 ++++-------- mx_bec/messages.py | 45 ++++ mx_bec/service.py | 9 +- pyproject.toml | 1 + tests/unit/test_aaredaq.py | 202 +++++------------ tests/unit/test_automation_permission.py | 208 ++++++++++++++++++ tests/unit/test_service.py | 16 +- 9 files changed, 675 insertions(+), 259 deletions(-) create mode 100644 mx_bec/automation_permission.py create mode 100644 tests/unit/test_automation_permission.py diff --git a/mx_bec/automation_permission.py b/mx_bec/automation_permission.py new file mode 100644 index 0000000..41e6429 --- /dev/null +++ b/mx_bec/automation_permission.py @@ -0,0 +1,269 @@ +"""Permission for the AareBec service to act on a user's behalf. + +Secured actions (mounting a sample, ...) are carried out by a server which wants to know which +user is asking: what is kept of AareDAQ, which issues a bearer token to a user who authenticates +by Kerberos. The service has no user identity of its own, so a client forwards the user's token: + +1. the service generates an RSA key pair when it starts and publishes the public key on + `AuthEndpoints.forwarded_auth_public_key()`; +2. the client gets a token from the server, encrypts it for that public key and adds it to the + stream `AuthEndpoints.automation_permission()` (`grant_automation_permission` does both); +3. the service decrypts the token with its private key, which never leaves the process, and uses + it for the secured actions until another token arrives. + +Every client can read the stream, hence the encryption. A token is longer than what RSA can +encrypt directly, so it is encrypted with a one-off AES-256-GCM key, which in turn is encrypted +for the service with RSA-OAEP. +""" + +from __future__ import annotations + +import base64 +import hashlib +import json +import os +import time +from dataclasses import dataclass, field +from threading import Lock +from typing import TYPE_CHECKING + +from bec_lib.logger import bec_logger +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import padding, rsa +from cryptography.hazmat.primitives.ciphers.aead import AESGCM + +from mx_bec.endpoints import AuthEndpoints +from mx_bec.messages import ( + MXAutomationPermissionMessage, + MXAutomationPermissionStatusMessage, + MXForwardedAuthPublicKeyMessage, +) + +if TYPE_CHECKING: + from bec_lib.redis_connector import RedisConnector + + from mx_bec.service import AareBec + +logger = bec_logger.logger + +RSA_KEY_SIZE = 2048 +RSA_PUBLIC_EXPONENT = 65537 +AES_KEY_BYTES = 32 +GCM_NONCE_BYTES = 12 +# set to "1" (or "true"/"on"/"yes") in the environment of the service to turn the authentication on +ENABLED_ENV_VAR = "MX_BEC_AUTOMATION_PERMISSION" + + +class AutomationPermissionError(RuntimeError): + """The service has no permission to act on a user's behalf.""" + + +@dataclass(frozen=True) +class AuthInfo: + """What a user gave the service so that it can act on their behalf.""" + + username: str + token: str = field(repr=False) # keep it out of logs + received_at: float = field(default_factory=time.time) + + @property + def claims(self) -> dict: + """What the token says about the user, if it is a JWT (as the tokens of AareDAQ are: + `sub`, `pgroups`, `staff`, `exp`). NOT verified: the service does not have the key the + token was signed with, so this is for information only.""" + try: + payload = self.token.split(".")[1] + claims = json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4))) + except (IndexError, ValueError): + return {} + return claims if isinstance(claims, dict) else {} + + @property + def pgroups(self) -> list[str] | None: + """The pgroups named in the token, or None if it does not name any.""" + pgroups = self.claims.get("pgroups") + if not isinstance(pgroups, list): + return None + return [str(pgroup) for pgroup in pgroups] + + +def _oaep() -> padding.OAEP: + return padding.OAEP( + mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None + ) + + +def _b64(data: bytes) -> str: + return base64.b64encode(data).decode("ascii") + + +def key_id(public_key_pem: str) -> str: + """A short fingerprint of a public key, to tell which key a token was encrypted for.""" + return hashlib.sha256(public_key_pem.encode("ascii")).hexdigest()[:16] + + +def encrypt_token( + public_key: MXForwardedAuthPublicKeyMessage, username: str, token: str +) -> MXAutomationPermissionMessage: + """Encrypt `token` so that only the service which published `public_key` can read it.""" + rsa_key = serialization.load_pem_public_key(public_key.public_key_pem.encode("ascii")) + if not isinstance(rsa_key, rsa.RSAPublicKey): + raise AutomationPermissionError("The published forwarded auth key is not an RSA key") + aes_key, nonce = AESGCM.generate_key(bit_length=AES_KEY_BYTES * 8), os.urandom(GCM_NONCE_BYTES) + # the username and key id are authenticated with the token, so they cannot be swapped + associated = f"{public_key.key_id}:{username}".encode() + return MXAutomationPermissionMessage( + username=username, + key_id=public_key.key_id, + encrypted_key=_b64(rsa_key.encrypt(aes_key, _oaep())), + nonce=_b64(nonce), + encrypted_token=_b64(AESGCM(aes_key).encrypt(nonce, token.encode(), associated)), + ) + + +def grant_automation_permission(connector: RedisConnector, username: str, token: str) -> None: + """For clients: give the AareBec service permission to act for `username` with their + `token`, encrypted for the public key which the service published.""" + public_key = connector.get(AuthEndpoints.forwarded_auth_public_key()) + if public_key is None: + raise AutomationPermissionError( + "The AareBec service has not published a public key: is it running?" + ) + msg = encrypt_token(public_key, username, token) + connector.xadd(AuthEndpoints.automation_permission(), {"data": msg}, max_size=1) + + +class AutomationPermission: + """Holds the permission of the AareBec service to act on a user's behalf: the token which a + client forwarded, see the module documentation. + + The authentication is off by default (`enabled=False`): `token` is then None without a + forwarded token, and what uses it carries on as it would without this class. If it is on, + asking for the token without one having been forwarded is an AutomationPermissionError. A + forwarded token is taken up either way. + """ + + def __init__(self, client: AareBec, enabled: bool = False) -> None: + self._client = client + self.enabled = enabled + self._lock = Lock() + self._auth_info: AuthInfo | None = None + self._private_key = rsa.generate_private_key( + public_exponent=RSA_PUBLIC_EXPONENT, key_size=RSA_KEY_SIZE + ) + self.public_key_pem = ( + self._private_key.public_key() + .public_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PublicFormat.SubjectPublicKeyInfo, + ) + .decode("ascii") + ) + self.key_id = key_id(self.public_key_pem) + self._listening = False + + @staticmethod + def enabled_in_environment() -> bool: + return os.environ.get(ENABLED_ENV_VAR, "").strip().lower() in ("1", "true", "on", "yes") + + def start(self) -> None: + """Publish the public key and listen for forwarded tokens. Needs the client's connector, + so it is called once the client has started.""" + connector = self._client.connector + connector.set_and_publish( + AuthEndpoints.forwarded_auth_public_key(), + MXForwardedAuthPublicKeyMessage(public_key_pem=self.public_key_pem, key_id=self.key_id), + ) + connector.register(AuthEndpoints.automation_permission(), cb=self._on_permission) + self._listening = True + self._publish_status() + logger.info( + f"Automation permission: published public key {self.key_id}, authentication is " + f"{'on' if self.enabled else 'off'}" + ) + + def shutdown(self) -> None: + if self._listening: + self._client.connector.unregister( + AuthEndpoints.automation_permission(), cb=self._on_permission + ) + self.clear() + self._listening = False + + def _on_permission(self, msg_dict: dict, **_kwargs) -> None: + """Take up the token forwarded on the stream. What cannot be decrypted is ignored, and + the permission the service already has is kept.""" + msg: MXAutomationPermissionMessage = msg_dict["data"] + try: + token = self._decrypt(msg) + except Exception as e: # pylint: disable=broad-except + logger.warning(f"Ignoring the automation permission sent for {msg.username}: {e}") + return + with self._lock: + self._auth_info = AuthInfo(username=msg.username, token=token) + logger.info(f"Automation permission granted by {msg.username}") + self._publish_status() + + def _decrypt(self, msg: MXAutomationPermissionMessage) -> str: + if msg.key_id != self.key_id: + raise AutomationPermissionError( + f"it was encrypted for the key {msg.key_id}, not the current key {self.key_id}" + ) + aes_key = self._private_key.decrypt(base64.b64decode(msg.encrypted_key), _oaep()) + associated = f"{msg.key_id}:{msg.username}".encode() + token = AESGCM(aes_key).decrypt( + base64.b64decode(msg.nonce), base64.b64decode(msg.encrypted_token), associated + ) + return token.decode() + + @property + def auth_info(self) -> AuthInfo | None: + """The forwarded permission, if there is one.""" + with self._lock: + return self._auth_info + + @property + def granted(self) -> bool: + return self.auth_info is not None + + @property + def token(self) -> str | None: + """The forwarded token for secured actions. Without one: None if the authentication is + off, an AutomationPermissionError if it is on.""" + if (info := self.auth_info) is not None: + return info.token + if self.enabled: + raise AutomationPermissionError( + "No user has given the AareBec service permission to act on their behalf: " + "authenticate from a client first (grant_automation_permission)" + ) + return None + + def clear(self) -> None: + """Forget the forwarded permission, e.g. once the server has rejected its token.""" + with self._lock: + self._auth_info = None + self._publish_status() + + def status(self) -> MXAutomationPermissionStatusMessage: + """The current permission, as published on `AuthEndpoints.automation_permission_status()`.""" + info = self.auth_info + if info is None: + return MXAutomationPermissionStatusMessage(granted=False) + claims = info.claims + staff, expires_at = claims.get("staff"), claims.get("exp") + return MXAutomationPermissionStatusMessage( + granted=True, + username=info.username, + pgroups=info.pgroups, + staff=staff if isinstance(staff, bool) else None, + expires_at=float(expires_at) if isinstance(expires_at, (int, float)) else None, + received_at=info.received_at, + ) + + def _publish_status(self) -> None: + """Publish the status, once the service has started (before, there is no connector).""" + if self._listening: + self._client.connector.set_and_publish( + AuthEndpoints.automation_permission_status(), self.status() + ) diff --git a/mx_bec/endpoints.py b/mx_bec/endpoints.py index 38565e1..f452ac1 100644 --- a/mx_bec/endpoints.py +++ b/mx_bec/endpoints.py @@ -2,6 +2,9 @@ from bec_lib.endpoints import EndpointInfo, EndpointType, MessageOp from bec_lib.messages import AvailableResourceMessage, BoolConfigDefaultFalse from mx_bec.messages import ( + MXAutomationPermissionMessage, + MXAutomationPermissionStatusMessage, + MXForwardedAuthPublicKeyMessage, MXMeasurementSequenceMessage, MXQueueChangedMessage, MXSampleExecutionMessage, @@ -58,6 +61,41 @@ class StateEndpoints: ) +class AuthEndpoints: + """Endpoints through which a client gives the AareBec service permission to act on a user's + behalf, see `mx_bec.automation_permission`.""" + + @staticmethod + def forwarded_auth_public_key(): + """The public key which the AareBec service generated when it started. Clients encrypt + the token they forward with it.""" + return EndpointInfo( + endpoint=f"{EndpointType.INFO.value}/mx/auth/forwarded_auth_public_key", + message_type=MXForwardedAuthPublicKeyMessage, + message_op=MessageOp.SET_PUBLISH, + ) + + @staticmethod + def automation_permission(): + """Stream to which clients add a user's encrypted token. The AareBec service listens to + it and takes up the latest one.""" + return EndpointInfo( + endpoint=f"{EndpointType.USER.value}/mx/auth/automation_permission", + message_type=MXAutomationPermissionMessage, + message_op=MessageOp.STREAM, + ) + + @staticmethod + def automation_permission_status(): + """The current permission of the AareBec service: whether a token has been forwarded, + by whom, and for which pgroups. Updated by the service whenever it changes.""" + return EndpointInfo( + endpoint=f"{EndpointType.INFO.value}/mx/auth/automation_permission_status", + message_type=MXAutomationPermissionStatusMessage, + message_op=MessageOp.SET_PUBLISH, + ) + + class ActorEndpoints: """Per-actor configuration, keyed by the actor's `config_key`.""" diff --git a/mx_bec/external_services/aaredaq.py b/mx_bec/external_services/aaredaq.py index cd0fcc3..a403af1 100644 --- a/mx_bec/external_services/aaredaq.py +++ b/mx_bec/external_services/aaredaq.py @@ -1,13 +1,9 @@ from __future__ import annotations -import json -import subprocess -import time from typing import TYPE_CHECKING, Any import requests from aarecommon.config.beamline import cfg_get, mx_beamline -from aarecommon.models.auth import BatonStatus from aarecommon.models.beamline import MXBeamline from bec_lib.logger import bec_logger @@ -25,11 +21,8 @@ DEFAULT_CERT_PATHS = { MXBeamline.X06DA: "/sls/x06da/misc/.cert/6d.crt", MXBeamline.X10SA: "/sls/x10sa/misc/.cert/10s.crt", } -TOKEN_TIMEOUT_S = 120.0 -REQUEST_TIMEOUT_S = 30.0 # for quick calls such as the baton endpoints +REQUEST_TIMEOUT_S = 30.0 MOUNT_TIMEOUT_S = 600.0 # the mount endpoint blocks until the sample is mounted -BATON_WAIT_S = 60.0 # covers the server's 30 s for the current holder to answer a request -BATON_POLL_INTERVAL_S = 1.0 class AareDaqError(RuntimeError): @@ -40,11 +33,10 @@ class AareDaq: """Client for the part of the AareDAQ REST API (aaredaq `server.py`) which AareBec still uses: mounting a sample. - 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. AareDAQ only mounts - for the session holding the beamline baton, so it is taken first if not held yet. + The service has no identity of its own towards AareDAQ: every request is made with the + bearer token of a user who gave the service permission to act on their behalf, see + `mx_bec.automation_permission`. Without such a token no request is made. The server URL and + its certificate come from the aarecommon beamline config unless given. """ def __init__( @@ -53,7 +45,6 @@ class AareDaq: self._client = client self._url = url self._cert_path = cert_path - self._token: str | None = None self._session = requests.Session() @property @@ -74,34 +65,16 @@ class AareDaq: 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: + def _token(self) -> str: + """The token which a user forwarded to the service. Needed for every request, whether + or not the automation permission is enforced otherwise.""" + info = self._client.automation_permission.auth_info + if info is None: raise AareDaqError( - f"AareDAQ token request failed (curl exit {result.returncode}): " - f"{result.stderr[:500]}. Is the Kerberos ticket valid (kinit)?" + "No token for AareDAQ: a user must first give the AareBec service permission to " + "act on their behalf (mx_bec.automation_permission.grant_automation_permission)" ) - 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 + return info.token def _request( self, @@ -112,34 +85,33 @@ class AareDaq: body: dict[str, Any] | None = None, timeout_s: float = REQUEST_TIMEOUT_S, ) -> Any: - """Call `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.request( - method, - 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 {method} {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 {method} {endpoint} failed with {resp.status_code}: {resp.text[:500]}" - ) - return resp.json() - raise AssertionError("unreachable") # pragma: no cover - - def _get(self, endpoint: str, timeout_s: float = REQUEST_TIMEOUT_S) -> Any: - return self._request("GET", endpoint, timeout_s=timeout_s) + """Call `endpoint` with the forwarded bearer token and return the decoded JSON response. + If the server rejects the token (401), the permission is dropped, so that a user has to + grant it again. Any error becomes an AareDaqError.""" + token = self._token() + try: + resp = self._session.request( + method, + f"{self.url}{endpoint}", + params=params, + json=body, + headers={"Authorization": f"Bearer {token}"}, + verify=self.cert_path, + timeout=timeout_s, + ) + except requests.RequestException as e: + raise AareDaqError(f"AareDAQ {method} {endpoint} failed: {e}") from e + if resp.status_code == 401: + self._client.automation_permission.clear() + raise AareDaqError( + f"AareDAQ rejected the forwarded token for {method} {endpoint} (401): it may " + f"have expired. Grant the automation permission again. {resp.text[:500]}" + ) + if not resp.ok: + raise AareDaqError( + f"AareDAQ {method} {endpoint} failed with {resp.status_code}: {resp.text[:500]}" + ) + return resp.json() def _post( self, @@ -151,48 +123,10 @@ class AareDaq: ) -> Any: return self._request("POST", endpoint, params=params, body=body, timeout_s=timeout_s) - # ---- baton: AareDAQ only runs hardware operations for the session holding the baton ---- - - def baton_status(self) -> BatonStatus: - return BatonStatus.model_validate(self._get("/baton/status")) - - def take_baton( - self, wait_s: float = BATON_WAIT_S, poll_interval_s: float = BATON_POLL_INTERVAL_S - ) -> None: - """Take the baton. Granted at once if the beamline is vacant (or we are staff); otherwise - the current holder is asked, and we poll until they accept or their time to answer runs - out, for up to `wait_s`. Raises AareDaqError if refused or not granted in time.""" - result = self._post("/baton/request", timeout_s=REQUEST_TIMEOUT_S) - if result.get("granted") or result.get("already_holder"): - logger.info(f"AareDAQ baton: {result.get('message')}") - return - if not (result.get("pending") or result.get("queued")): - raise AareDaqError(f"AareDAQ refused the baton request: {result.get('message')}") - logger.info(f"AareDAQ baton: {result.get('message')}; waiting for it") - deadline = time.monotonic() + wait_s - while True: - time.sleep(poll_interval_s) - result = self._get("/baton/check_timeout") - if result.get("granted"): - logger.info("AareDAQ baton acquired") - return - if result.get("refused"): - raise AareDaqError("AareDAQ baton request was refused by the current holder") - if time.monotonic() > deadline: - raise AareDaqError(f"AareDAQ baton not granted within {wait_s} s: {result}") - - def ensure_baton(self) -> None: - """Take the baton unless this session already holds it.""" - if not self.baton_status().you_are_holder: - self.take_baton() - - # ---- hardware operations ---- - def mount_sample( self, dbid: int, reference: bool = False, timeout_s: float = MOUNT_TIMEOUT_S ) -> None: """Mount the sample with database id `dbid` (from the reference tools if `reference`).""" - self.ensure_baton() 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 diff --git a/mx_bec/messages.py b/mx_bec/messages.py index 5b7d202..4af4920 100644 --- a/mx_bec/messages.py +++ b/mx_bec/messages.py @@ -59,3 +59,48 @@ class OpticalPredictionMessage(BECMessage): timestamp: float = Field(default_factory=time.time) prediction: LatestPredictionModel + + +class MXForwardedAuthPublicKeyMessage(BECMessage): + """The public key of the AareBec service, for clients to encrypt the token with which they + give the service permission to act on their behalf.""" + + msg_type: ClassVar[str] = "mx_forwarded_auth_public_key_message" + + public_key_pem: str = Field(description="RSA public key, PEM encoded SubjectPublicKeyInfo") + key_id: str = Field(description="Fingerprint of the key, changes when the service restarts") + + +class MXAutomationPermissionMessage(BECMessage): + """A user's token for secured actions, encrypted for the AareBec service: the token is + encrypted with a one-off AES-256-GCM key, and that key with the service's RSA public key + (OAEP, SHA-256). The binary fields are base64 encoded.""" + + msg_type: ClassVar[str] = "mx_automation_permission_message" + + username: str = Field(description="Who the token belongs to") + key_id: str = Field(description="`key_id` of the public key the token was encrypted for") + encrypted_key: str = Field(description="The AES key, RSA-OAEP encrypted") + nonce: str = Field(description="The AES-GCM nonce") + encrypted_token: str = Field(description="The token, AES-GCM encrypted") + + +class MXAutomationPermissionStatusMessage(BECMessage): + """Whether the AareBec service has permission to act on a user's behalf, and whose. The + pgroups and expiry are read from the forwarded token as it is: only the server which issued + the token can verify it.""" + + msg_type: ClassVar[str] = "mx_automation_permission_status_message" + + granted: bool = Field(description="Whether a user's token has been forwarded") + username: str | None = Field(default=None, description="Who forwarded the token") + pgroups: list[str] | None = Field( + default=None, description="The pgroups named in the token, if it names any" + ) + staff: bool | None = Field(default=None, description="The staff flag of the token, if any") + expires_at: float | None = Field( + default=None, description="When the token expires (unix time), if it says" + ) + received_at: float | None = Field( + default=None, description="When the token was forwarded (unix time)" + ) diff --git a/mx_bec/service.py b/mx_bec/service.py index b4cdecf..4138dca 100644 --- a/mx_bec/service.py +++ b/mx_bec/service.py @@ -10,6 +10,7 @@ from bec_lib.logger import bec_logger from redis.client import Redis from mx_bec.actor_manager import AareActorManager +from mx_bec.automation_permission import AutomationPermission from mx_bec.constants import AareBecWorkflowState from mx_bec.endpoints import QueueEndpoints from mx_bec.external_services.aaredaq import AareDaq @@ -55,7 +56,11 @@ 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 + # permission to act on a user's behalf, forwarded by a client; off unless set in the env + self.automation_permission = AutomationPermission( + client=self, enabled=AutomationPermission.enabled_in_environment() + ) + self.aaredaq = AareDaq(client=self) # uses the token forwarded to automation_permission self.tasks = MxTasks[Server](self) self.task_queue: MxTaskQueue | None = None self.sample_info: SampleInfo | None = None @@ -69,6 +74,7 @@ class AareBec(BECClient): def start(self): super().start() + self.automation_permission.start() self._start_actor_manager() self.task_queue = MxTaskQueue(self, self.tasks) self.task_queue.start() @@ -121,6 +127,7 @@ class AareBec(BECClient): self.actor_manager.shutdown() self.actor_manager = None if self.started: # the connector only exists once the client has been started + self.automation_permission.shutdown() self.connector.unregister(QueueEndpoints.task_request(), cb=self._on_task_request) if self.task_queue is not None: self.task_queue.shutdown() diff --git a/pyproject.toml b/pyproject.toml index 305055a..8686295 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -26,6 +26,7 @@ dependencies = [ "aarelcinfer_client @ https://gitea.psi.ch/api/packages/mx/pypi/files/aarelcinfer-client/0.2.0/aarelcinfer_client-0.2.0-py3-none-any.whl", "jfjoch_client @ https://gitea.psi.ch/api/packages/mx/pypi/files/jfjoch-client/1.0.0rc188/jfjoch_client-1.0.0rc188-py3-none-any.whl", "bec_lib>=3.130.3", + "cryptography", "bec-server>=3.130.3", "bec-ipython-client>=3.130.3", "ophyd_devices>=1.46", diff --git a/tests/unit/test_aaredaq.py b/tests/unit/test_aaredaq.py index 1cd0e12..3cb596e 100644 --- a/tests/unit/test_aaredaq.py +++ b/tests/unit/test_aaredaq.py @@ -1,18 +1,14 @@ -import subprocess -from unittest.mock import MagicMock, call, patch +from unittest.mock import MagicMock, patch import pytest -from aarecommon.models.auth import BatonStatus +import requests +from mx_bec.automation_permission import AuthInfo from mx_bec.external_services.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 @@ -20,47 +16,31 @@ def _response(status_code=200, json_data=None, text=""): @pytest.fixture -def curl(): - with patch( - "mx_bec.external_services.aaredaq.subprocess.run", return_value=_curl_result() - ) as run: - yield run - - -def _status(you_are_holder: bool) -> dict: - return BatonStatus(you_are_holder=you_are_holder).model_dump(mode="json") +def client(): + """An AareBec to which a user has forwarded their token.""" + client = MagicMock() + client.automation_permission.auth_info = AuthInfo(username="e12345", token=TOKEN) + return client @pytest.fixture -def daq(curl): - """Client with a mocked HTTP session: by default this session holds the baton and every - POST answers "OK".""" - daq = AareDaq(MagicMock(), url=URL, cert_path=CERT) +def daq(client): + """Client with a mocked HTTP session, which answers "OK" unless `daq._response` is set.""" + daq = AareDaq(client, url=URL, cert_path=CERT) daq._session = MagicMock() - responses = {"GET": _response(json_data=_status(True)), "POST": _response(json_data="OK")} - daq._session.request.side_effect = lambda method, *a, **k: responses[method] - daq._responses = responses + daq._response = _response(json_data="OK") + daq._session.request.side_effect = lambda *a, **k: daq._response return daq -def _calls(daq, method): - """(url, kwargs) of the recorded requests of the given method, in order.""" - return [ - (c.args[1], c.kwargs) for c in daq._session.request.call_args_list if c.args[0] == method - ] +def _calls(daq): + """(method, url, kwargs) of the recorded requests, in order.""" + return [(c.args[0], c.args[1], c.kwargs) for c in daq._session.request.call_args_list] -def _set_posts(daq, *responses): - """Make successive POSTs answer with the given responses (GETs keep the default).""" - posts = iter(responses) - daq._session.request.side_effect = lambda method, *a, **k: ( - next(posts) if method == "POST" else daq._responses["GET"] - ) - - -def test_url_and_cert_are_resolved_from_beamline_config_on_first_use(curl, monkeypatch): +def test_url_and_cert_are_resolved_from_beamline_config_on_first_use(client, monkeypatch): monkeypatch.delenv("BEAMLINE", raising=False) - daq = AareDaq(MagicMock()) # must not need the beamline environment yet + daq = AareDaq(client) # must not need the beamline environment yet with ( patch("mx_bec.external_services.aaredaq.mx_beamline", return_value="X10SA"), patch( @@ -72,40 +52,11 @@ def test_url_and_cert_are_resolved_from_beamline_config_on_first_use(curl, monke 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=""), "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): +def test_mount_sample_uses_the_forwarded_token(daq): daq.mount_sample(42) - assert _calls(daq, "POST") == [ + assert _calls(daq) == [ ( + "POST", f"{URL}/sample/mount", { "params": {"dbid": 42, "reference": False}, @@ -118,92 +69,43 @@ def test_mount_sample(daq): ] -def test_expired_token_is_renewed_once(daq, curl): - curl.side_effect = [_curl_result(), _curl_result('{"access_token": "new"}')] - _set_posts(daq, _response(401), _response(json_data="OK")) - daq.mount_sample(1) - headers = [kwargs["headers"]["Authorization"] for _, kwargs in _calls(daq, "POST")] - assert headers == [f"Bearer {TOKEN}", "Bearer new"] - assert daq.token == "new" +def test_mount_sample_from_the_reference_tools(daq): + daq.mount_sample(7, reference=True) + [(_, _, kwargs)] = _calls(daq) + assert kwargs["params"] == {"dbid": 7, "reference": True} -def test_persistent_401_is_an_error(daq): - _set_posts(daq, _response(401, text="nope"), _response(401, text="nope")) - with pytest.raises(AareDaqError, match="401"): +def test_no_request_is_made_without_a_forwarded_token(daq, client): + client.automation_permission.auth_info = None + with pytest.raises(AareDaqError, match="No token for AareDAQ"): daq.mount_sample(1) - assert len(_calls(daq, "POST")) == 2 + daq._session.request.assert_not_called() -def test_http_error_reports_status_and_body(daq): - _set_posts(daq, _response(422, text='{"detail": "bad request"}')) +def test_the_latest_forwarded_token_is_used(daq, client): + daq.mount_sample(1) + client.automation_permission.auth_info = AuthInfo(username="e99999", token="new") + daq.mount_sample(2) + headers = [kwargs["headers"]["Authorization"] for _, _, kwargs in _calls(daq)] + assert headers == [f"Bearer {TOKEN}", "Bearer new"] + + +def test_a_rejected_token_drops_the_permission(daq, client): + daq._response = _response(401, text="nope") + with pytest.raises(AareDaqError, match="rejected the forwarded token"): + daq.mount_sample(1) + assert len(_calls(daq)) == 1 # there is no other token to try again with + client.automation_permission.clear.assert_called_once_with() + + +def test_http_error_reports_status_and_body(daq, client): + daq._response = _response(422, text='{"detail": "bad request"}') with pytest.raises(AareDaqError, match="422.*bad request"): daq.mount_sample(1) + client.automation_permission.clear.assert_not_called() -# ---- baton ---- - - -def test_baton_status(daq): - assert daq.baton_status() == BatonStatus(you_are_holder=True) - [(url, kwargs)] = _calls(daq, "GET") - assert url == f"{URL}/baton/status" and kwargs["timeout"] == 30.0 - - -def test_hardware_calls_skip_the_baton_request_when_already_holder(daq): - daq.mount_sample(1) - assert [url for url, _ in _calls(daq, "POST")] == [f"{URL}/sample/mount"] - - -def test_hardware_calls_take_the_baton_first(daq): - daq._responses["GET"] = _response(json_data=_status(False)) - _set_posts(daq, _response(json_data={"granted": True}), _response(json_data="OK")) - daq.mount_sample(1) - assert [url for url, _ in _calls(daq, "POST")] == [ - f"{URL}/baton/request", - f"{URL}/sample/mount", - ] - - -@pytest.mark.parametrize("result", [{"granted": True}, {"already_holder": True}]) -def test_take_baton_immediately(daq, result): - _set_posts(daq, _response(json_data=result)) - daq.take_baton() - assert [url for url, _ in _calls(daq, "POST")] == [f"{URL}/baton/request"] - - -def test_take_baton_refused_by_policy(daq): - _set_posts(daq, _response(json_data={"error": True, "message": "disabled by policy"})) - with pytest.raises(AareDaqError, match="disabled by policy"): - daq.take_baton() - - -def test_take_baton_waits_for_the_holder(daq): - _set_posts(daq, _response(json_data={"pending": True, "message": "asked"})) - checks = iter([{"pending": True, "remaining_seconds": 20}, {"granted": True}]) - daq._responses["GET"] = MagicMock() - daq._responses["GET"].ok, daq._responses["GET"].status_code = True, 200 - daq._responses["GET"].json.side_effect = lambda: next(checks) - with patch("mx_bec.external_services.aaredaq.time.sleep") as sleep: - daq.take_baton(poll_interval_s=0.5) - assert [url for url, _ in _calls(daq, "GET")] == [f"{URL}/baton/check_timeout"] * 2 - sleep.assert_called_with(0.5) - - -def test_take_baton_refused_by_holder(daq): - _set_posts(daq, _response(json_data={"pending": True})) - daq._responses["GET"] = _response(json_data={"refused": True}) - with ( - patch("mx_bec.external_services.aaredaq.time.sleep"), - pytest.raises(AareDaqError, match="refused"), - ): - daq.take_baton() - - -def test_take_baton_gives_up_after_wait(daq): - _set_posts(daq, _response(json_data={"queued": True})) - daq._responses["GET"] = _response(json_data={"queued": True}) - with ( - patch("mx_bec.external_services.aaredaq.time.sleep"), - pytest.raises(AareDaqError, match="not granted"), - ): - daq.take_baton(wait_s=0) +def test_connection_error_becomes_an_aaredaq_error(daq): + daq._session.request.side_effect = requests.ConnectionError("no route") + with pytest.raises(AareDaqError, match="no route"): + daq.mount_sample(1) diff --git a/tests/unit/test_automation_permission.py b/tests/unit/test_automation_permission.py new file mode 100644 index 0000000..dad6be0 --- /dev/null +++ b/tests/unit/test_automation_permission.py @@ -0,0 +1,208 @@ +import base64 +import json +import time +from unittest.mock import MagicMock + +import fakeredis +import pytest +from bec_lib.redis_connector import RedisConnector + +from mx_bec.automation_permission import ( + ENABLED_ENV_VAR, + AutomationPermission, + AutomationPermissionError, + encrypt_token, + grant_automation_permission, +) +from mx_bec.endpoints import AuthEndpoints +from mx_bec.messages import MXAutomationPermissionMessage, MXForwardedAuthPublicKeyMessage + +# as long as a real token, which is far more than RSA 2048 can encrypt directly +TOKEN = "eyJhbGciOiJIUzI1NiJ9." + "x" * 600 + ".signature" + + +@pytest.fixture(scope="module") +def keypair_permission(): + """Generating a key pair is slow, so the tests of one module share one.""" + return AutomationPermission(MagicMock()) + + +@pytest.fixture +def permission(keypair_permission): + keypair_permission._client = MagicMock() + keypair_permission.enabled = False + keypair_permission.clear() + return keypair_permission + + +def _public_key(permission) -> MXForwardedAuthPublicKeyMessage: + return MXForwardedAuthPublicKeyMessage( + public_key_pem=permission.public_key_pem, key_id=permission.key_id + ) + + +def test_generates_a_2048_bit_rsa_key_pair(permission): + assert permission._private_key.key_size == 2048 + assert permission.public_key_pem.startswith("-----BEGIN PUBLIC KEY-----") + + +def test_authentication_is_off_by_default(monkeypatch): + monkeypatch.delenv(ENABLED_ENV_VAR, raising=False) + assert not AutomationPermission.enabled_in_environment() + monkeypatch.setenv(ENABLED_ENV_VAR, "1") + assert AutomationPermission.enabled_in_environment() + + +def test_start_publishes_the_public_key_and_listens_to_the_stream(permission): + permission.start() + connector = permission._client.connector + endpoint, msg = connector.set_and_publish.call_args_list[0].args + assert endpoint == AuthEndpoints.forwarded_auth_public_key() + assert msg == _public_key(permission) + connector.register.assert_called_once_with( + AuthEndpoints.automation_permission(), cb=permission._on_permission + ) + permission.shutdown() + connector.unregister.assert_called_once_with( + AuthEndpoints.automation_permission(), cb=permission._on_permission + ) + + +def test_a_forwarded_token_populates_the_auth_info(permission): + assert permission.auth_info is None and not permission.granted + msg = encrypt_token(_public_key(permission), "e12345", TOKEN) + permission._on_permission({"data": msg}) + assert permission.granted + assert (permission.auth_info.username, permission.auth_info.token) == ("e12345", TOKEN) + assert permission.token == TOKEN + assert TOKEN not in repr(permission.auth_info) + + +def test_the_token_is_not_readable_on_the_stream(permission): + msg = encrypt_token(_public_key(permission), "e12345", TOKEN) + assert TOKEN not in msg.model_dump_json() + # a fresh key for every message + assert ( + encrypt_token(_public_key(permission), "e12345", TOKEN).encrypted_key != msg.encrypted_key + ) + + +def test_without_a_token_only_an_enabled_permission_refuses(permission): + assert permission.token is None + permission.enabled = True + with pytest.raises(AutomationPermissionError, match="No user has given"): + _ = permission.token + + +@pytest.mark.parametrize( + "tamper", + [ + lambda msg: msg.model_copy(update={"username": "someone_else"}), + lambda msg: msg.model_copy(update={"key_id": "0" * 16}), + lambda msg: msg.model_copy(update={"encrypted_token": msg.encrypted_token[4:]}), + lambda msg: msg.model_copy(update={"encrypted_key": "not base64!"}), + ], +) +def test_a_message_which_cannot_be_decrypted_keeps_the_current_permission(permission, tamper): + permission._on_permission({"data": encrypt_token(_public_key(permission), "e12345", TOKEN)}) + bad = tamper(encrypt_token(_public_key(permission), "e99999", "other token")) + permission._on_permission({"data": bad}) + assert (permission.auth_info.username, permission.token) == ("e12345", TOKEN) + + +def test_a_token_for_another_services_key_is_ignored(permission): + other = AutomationPermission(MagicMock()) + permission._on_permission({"data": encrypt_token(_public_key(other), "e12345", TOKEN)}) + assert not permission.granted + + +def test_clear_forgets_the_permission(permission): + permission._on_permission({"data": encrypt_token(_public_key(permission), "e12345", TOKEN)}) + permission.clear() + assert not permission.granted + + +@pytest.fixture +def connector(): + conn = RedisConnector("localhost:1", redis_cls=lambda *_, **__: fakeredis.FakeRedis()) + conn._managed_connection.flushall() + yield conn + conn.shutdown() + + +def test_client_grants_permission_through_redis(permission, connector): + """The whole path: the service publishes its key and listens, the client reads the key and + adds the encrypted token to the stream, the service decrypts it.""" + permission._client.connector = connector + permission.start() + try: + grant_automation_permission(connector, "e12345", TOKEN) + deadline = time.monotonic() + 5 + while not permission.granted and time.monotonic() < deadline: + time.sleep(0.01) + assert permission.granted + assert (permission.auth_info.username, permission.token) == ("e12345", TOKEN) + on_stream = connector.get_last(AuthEndpoints.automation_permission(), "data") + assert isinstance(on_stream, MXAutomationPermissionMessage) + finally: + permission.shutdown() + + +def test_client_cannot_grant_permission_without_a_published_key(): + connector = MagicMock() + connector.get.return_value = None + with pytest.raises(AutomationPermissionError, match="has not published a public key"): + grant_automation_permission(connector, "e12345", TOKEN) + connector.xadd.assert_not_called() + + +def _jwt(claims: dict) -> str: + """A token shaped like those of AareDAQ (the signature is not checked by the service).""" + + def segment(data: dict) -> str: + return base64.urlsafe_b64encode(json.dumps(data).encode()).decode().rstrip("=") + + return f"{segment({'alg': 'HS256', 'typ': 'JWT'})}.{segment(claims)}.signature" + + +def _published_status(permission): + endpoint, msg = permission._client.connector.set_and_publish.call_args.args + assert endpoint == AuthEndpoints.automation_permission_status() + return msg + + +def test_status_is_published_on_start_grant_and_clear(permission): + permission.start() + status = _published_status(permission) + assert not status.granted + assert (status.username, status.pgroups, status.staff, status.expires_at) == (None,) * 4 + + claims = {"sub": "e12345", "pgroups": ["p16371", "p20000"], "staff": False, "exp": 1.8e9} + token = _jwt(claims | {"session": 1}) + permission._on_permission({"data": encrypt_token(_public_key(permission), "e12345", token)}) + status = _published_status(permission) + assert (status.granted, status.username) == (True, "e12345") + assert status.pgroups == ["p16371", "p20000"] + assert (status.staff, status.expires_at) == (False, 1.8e9) + assert status.received_at == permission.auth_info.received_at + assert token not in status.model_dump_json() + + permission.clear() + status = _published_status(permission) + assert (status.granted, status.username, status.pgroups) == (False, None, None) + permission.shutdown() + + +def test_status_has_no_pgroups_for_a_token_which_names_none(permission): + permission.start() + for token in (TOKEN, "not a jwt", _jwt({"sub": "e12345"})): + permission._on_permission({"data": encrypt_token(_public_key(permission), "e1", token)}) + status = _published_status(permission) + assert (status.granted, status.pgroups, status.expires_at) == (True, None, None) + permission.shutdown() + + +def test_status_is_not_published_before_start(permission): + permission._on_permission({"data": encrypt_token(_public_key(permission), "e1", TOKEN)}) + permission._client.connector.set_and_publish.assert_not_called() + assert permission.status().granted diff --git a/tests/unit/test_service.py b/tests/unit/test_service.py index 509bf7b..f52c3d1 100644 --- a/tests/unit/test_service.py +++ b/tests/unit/test_service.py @@ -6,7 +6,7 @@ from bec_lib.service_config import ServiceConfig from bec_lib.tests.utils import ConnectorMock from mx_bec.constants import AareBecWorkflowState -from mx_bec.endpoints import QueueEndpoints +from mx_bec.endpoints import AuthEndpoints, QueueEndpoints from mx_bec.messages import MXQueueChangedMessage, MXTaskExecutionMessage from mx_bec.service import DUMMY_ENERGY_EV, DUMMY_FULL_FLUX_PH_S, AareBec from mx_bec.tasks import MxTasks, RoleT, Server, task @@ -74,11 +74,23 @@ def test_shutdown_stops_actor_manager_and_task_queue(service): def test_start_registers_task_request_callback(started_service): service, *_ = started_service - service.connector.register.assert_called_once_with( + service.connector.register.assert_any_call( QueueEndpoints.task_request(), cb=service._on_task_request ) +def test_start_publishes_the_forwarded_auth_public_key_and_listens(started_service): + service, *_ = started_service + permission = service.automation_permission + assert not permission.enabled # off unless turned on in the environment + endpoint, msg = service.connector.set_and_publish.call_args_list[0].args + assert endpoint == AuthEndpoints.forwarded_auth_public_key() + assert msg.public_key_pem == permission.public_key_pem + service.connector.register.assert_any_call( + AuthEndpoints.automation_permission(), cb=permission._on_permission + ) + + def test_shutdown_unregisters_task_request_callback(service): service.started = True service.connector = MagicMock() -- 2.54.1 From 56d41ce42a717e024de107877f83d82bcad0f043 Mon Sep 17 00:00:00 2001 From: David Perl Date: Wed, 2 Dec 2026 14:43:55 +0100 Subject: [PATCH 09/11] add forwarded auth widget --- .../bec_widgets/widgets/aare_bec/__init__.py | 2 + .../widgets/aare_bec/automation_permission.py | 144 ++++++++++++++++++ mx_bec/external_services/aaredaq.py | 62 +++++++- tests/unit/test_aaredaq.py | 52 ++++++- .../unit/test_automation_permission_widget.py | 83 ++++++++++ 5 files changed, 334 insertions(+), 9 deletions(-) create mode 100644 mx_bec/bec_widgets/widgets/aare_bec/automation_permission.py create mode 100644 tests/unit/test_automation_permission_widget.py diff --git a/mx_bec/bec_widgets/widgets/aare_bec/__init__.py b/mx_bec/bec_widgets/widgets/aare_bec/__init__.py index d624b39..79cf99e 100644 --- a/mx_bec/bec_widgets/widgets/aare_bec/__init__.py +++ b/mx_bec/bec_widgets/widgets/aare_bec/__init__.py @@ -1,4 +1,5 @@ from .actors_config import MxActorConfigWidget +from .automation_permission import MxAutomationPermissionWidget from .sample_queue import SampleQueueWidget from .sample_spreadsheet_display import SampleSpreadsheetDisplay from .task_panel import MxTaskPanel @@ -6,6 +7,7 @@ from .task_queue import MxTaskQueueWidget __all__ = [ "MxActorConfigWidget", + "MxAutomationPermissionWidget", "SampleQueueWidget", "SampleSpreadsheetDisplay", "MxTaskPanel", diff --git a/mx_bec/bec_widgets/widgets/aare_bec/automation_permission.py b/mx_bec/bec_widgets/widgets/aare_bec/automation_permission.py new file mode 100644 index 0000000..d200908 --- /dev/null +++ b/mx_bec/bec_widgets/widgets/aare_bec/automation_permission.py @@ -0,0 +1,144 @@ +from __future__ import annotations + +from datetime import datetime +from threading import Thread + +from bec_lib.logger import bec_logger +from bec_widgets.utils.bec_connector import ConnectionConfig +from bec_widgets.utils.bec_widget import BECWidget +from bec_widgets.utils.error_popups import SafeSlot +from qtpy.QtCore import Signal +from qtpy.QtWidgets import QFormLayout, QLabel, QPushButton, QVBoxLayout, QWidget + +from mx_bec.automation_permission import grant_automation_permission +from mx_bec.endpoints import AuthEndpoints +from mx_bec.external_services.aaredaq import request_user_token +from mx_bec.messages import MXAutomationPermissionStatusMessage + +logger = bec_logger.logger + +NOT_SET = "-" + + +def _time(timestamp: float | None) -> str: + if timestamp is None: + return NOT_SET + return datetime.fromtimestamp(timestamp).strftime("%Y-%m-%d %H:%M:%S") + + +class MxAutomationPermissionWidget(BECWidget, QWidget): + """ + Widget to give the AareBec service permission to act on the user's behalf (to mount samples, + ...), and to show the permission it currently has. + + The button gets a token for the user running the GUI from AareDAQ, which needs a valid + Kerberos ticket, and forwards it to the service, encrypted for the public key the service + published. The status is what the service publishes on `automation_permission_status`. + """ + + PLUGIN = True + ICON_NAME = "key" + USER_ACCESS = ["grant_permission", "refresh"] + + # the token request runs on a worker thread; its outcome is shown on the GUI thread + _grant_finished = Signal(str) + + def __init__( + self, + parent: QWidget | None = None, + client=None, + config: ConnectionConfig | None = None, + gui_id: str | None = None, + **kwargs, + ) -> None: + super().__init__(parent=parent, client=client, config=config, gui_id=gui_id, **kwargs) + self._worker: Thread | None = None + + self._granted = QLabel(parent=self) + self._username = QLabel(parent=self) + self._pgroups = QLabel(parent=self) + self._pgroups.setWordWrap(True) + self._staff = QLabel(parent=self) + self._received_at = QLabel(parent=self) + self._expires_at = QLabel(parent=self) + form = QFormLayout() + form.addRow("Permission", self._granted) + form.addRow("User", self._username) + form.addRow("Pgroups", self._pgroups) + form.addRow("Staff", self._staff) + form.addRow("Granted at", self._received_at) + form.addRow("Token expires", self._expires_at) + + self._button = QPushButton("Authenticate and grant permission", parent=self) + self._button.clicked.connect(self.grant_permission) + self._message = QLabel(parent=self) + self._message.setWordWrap(True) + + layout = QVBoxLayout(self) + layout.addLayout(form) + layout.addWidget(self._button) + layout.addWidget(self._message) + layout.addStretch() + + self._grant_finished.connect(self._on_grant_finished) + # released automatically by BECWidget.cleanup() (disconnect_owner) + self.bec_dispatcher.connect_slot( + self._on_status, AuthEndpoints.automation_permission_status() + ) + self.refresh() + + @SafeSlot() + def refresh(self): + """Reload the permission status from Redis.""" + self._show_status(self.client.connector.get(AuthEndpoints.automation_permission_status())) + + @SafeSlot(dict, dict) + def _on_status(self, content: dict, _metadata: dict): + self._show_status(MXAutomationPermissionStatusMessage(**content)) + + def _show_status(self, status: MXAutomationPermissionStatusMessage | None) -> None: + if status is None: + self._granted.setText("unknown: the AareBec service has not published a status") + for label in (self._username, self._pgroups, self._staff): + label.setText(NOT_SET) + self._received_at.setText(NOT_SET) + self._expires_at.setText(NOT_SET) + return + self._granted.setText("granted" if status.granted else "not granted") + self._username.setText(status.username or NOT_SET) + self._pgroups.setText(", ".join(status.pgroups) if status.pgroups else NOT_SET) + self._staff.setText(NOT_SET if status.staff is None else "yes" if status.staff else "no") + self._received_at.setText(_time(status.received_at)) + self._expires_at.setText(_time(status.expires_at)) + + @SafeSlot() + def grant_permission(self): + """Get a token for the current user from AareDAQ and forward it to the AareBec service. + Returns at once; the outcome is shown in the widget.""" + if self._worker is not None and self._worker.is_alive(): + return + self._button.setEnabled(False) + self._message.setText("Authenticating with AareDAQ...") + self._worker = Thread(target=self._grant, name="mx-grant-permission", daemon=True) + self._worker.start() + + def _grant(self) -> None: + """Runs on the worker thread: the token request can take a while.""" + try: + username, token = request_user_token() + grant_automation_permission(self.client.connector, username, token) + except Exception as e: # pylint: disable=broad-except + logger.warning(f"Could not grant the automation permission: {e}") + self._grant_finished.emit(f"Failed: {e}") + return + self._grant_finished.emit(f"Token of {username} forwarded to the AareBec service.") + + @SafeSlot(str) + def _on_grant_finished(self, message: str): + self._message.setText(message) + self._button.setEnabled(True) + + def cleanup(self): + if self._worker is not None: + self._worker.join(timeout=1) + super().cleanup() diff --git a/mx_bec/external_services/aaredaq.py b/mx_bec/external_services/aaredaq.py index a403af1..64ce499 100644 --- a/mx_bec/external_services/aaredaq.py +++ b/mx_bec/external_services/aaredaq.py @@ -1,5 +1,7 @@ from __future__ import annotations +import json +import subprocess from typing import TYPE_CHECKING, Any import requests @@ -22,6 +24,7 @@ DEFAULT_CERT_PATHS = { MXBeamline.X10SA: "/sls/x10sa/misc/.cert/10s.crt", } REQUEST_TIMEOUT_S = 30.0 +TOKEN_TIMEOUT_S = 120.0 MOUNT_TIMEOUT_S = 600.0 # the mount endpoint blocks until the sample is mounted @@ -29,6 +32,55 @@ class AareDaqError(RuntimeError): """A call to the AareDAQ server failed.""" +def configured_url() -> str: + """The URL of the AareDAQ server, from the aarecommon beamline config.""" + beamline = mx_beamline() + if (url := cfg_get("gui.daq.daq_url", DEFAULT_URLS.get(beamline))) is None: + raise AareDaqError(f"No AareDAQ URL configured for beamline {beamline}") + return url + + +def configured_cert_path() -> str: + """The certificate of the AareDAQ server, from the aarecommon beamline config.""" + beamline = mx_beamline() + if (cert_path := cfg_get("gui.daq.cert_path", DEFAULT_CERT_PATHS.get(beamline))) is None: + raise AareDaqError(f"No AareDAQ certificate configured for beamline {beamline}") + return cert_path + + +def request_user_token(url: str | None = None, cert_path: str | None = None) -> tuple[str, str]: + """For clients, not the service: get an AareDAQ token for the user running this process and + return (username, token). Authenticates by Kerberos (`curl --negotiate` against the Apache + proxy in front of the server, as the AareDAQ GUI does), so it needs a valid ticket (kinit). + The token can then be forwarded to the AareBec service, see `mx_bec.automation_permission`. + """ + url, cert_path = url or configured_url(), cert_path or configured_cert_path() + cmd = ["curl", "-s", "--cacert", cert_path, "--negotiate", "-u", ":", "-XPOST", f"{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: + response = json.loads(result.stdout) + except json.JSONDecodeError as e: + raise AareDaqError(f"AareDAQ token response is not JSON: {result.stdout[:500]}") from e + token = response.get("access_token") if isinstance(response, dict) else None + if not isinstance(token, str) or not token: + raise AareDaqError(f"AareDAQ token response has no access_token: {result.stdout[:500]}") + info = response.get("info") + username = info.get("sub") if isinstance(info, dict) else None + if not isinstance(username, str) or not username: + raise AareDaqError("AareDAQ token response does not say which user the token is for") + return username, token + + class AareDaq: """Client for the part of the AareDAQ REST API (aaredaq `server.py`) which AareBec still uses: mounting a sample. @@ -50,19 +102,13 @@ class AareDaq: @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}") + self._url = configured_url() 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}") + self._cert_path = configured_cert_path() return self._cert_path def _token(self) -> str: diff --git a/tests/unit/test_aaredaq.py b/tests/unit/test_aaredaq.py index 3cb596e..f65facb 100644 --- a/tests/unit/test_aaredaq.py +++ b/tests/unit/test_aaredaq.py @@ -1,10 +1,12 @@ +import json +import subprocess from unittest.mock import MagicMock, patch import pytest import requests from mx_bec.automation_permission import AuthInfo -from mx_bec.external_services.aaredaq import DEFAULT_URLS, AareDaq, AareDaqError +from mx_bec.external_services.aaredaq import DEFAULT_URLS, AareDaq, AareDaqError, request_user_token URL, CERT, TOKEN = "https://daq.test", "/certs/daq.crt", "eyJ.abc.def" @@ -109,3 +111,51 @@ def test_connection_error_becomes_an_aaredaq_error(daq): daq._session.request.side_effect = requests.ConnectionError("no route") with pytest.raises(AareDaqError, match="no route"): daq.mount_sample(1) + + +# ---- the token request, which clients (not the service) make for the user running them ---- + + +def _curl_result(stdout=None, returncode=0, stderr=""): + if stdout is None: + stdout = json.dumps( + {"access_token": TOKEN, "token_type": "bearer", "info": {"sub": "e12345"}} + ) + return subprocess.CompletedProcess(args=[], returncode=returncode, stdout=stdout, stderr=stderr) + + +@pytest.fixture +def curl(): + with patch( + "mx_bec.external_services.aaredaq.subprocess.run", return_value=_curl_result() + ) as run: + yield run + + +def test_user_token_is_requested_by_kerberos_curl(curl): + assert request_user_token(URL, CERT) == ("e12345", 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=""), "not JSON"), + (_curl_result(stdout="{}"), "no access_token"), + (_curl_result(stdout='{"access_token": "t"}'), "which user"), + ], +) +def test_user_token_request_failures(curl, result, match): + curl.return_value = result + with pytest.raises(AareDaqError, match=match): + request_user_token(URL, CERT) + + +def test_user_token_request_timeout(curl): + curl.side_effect = subprocess.TimeoutExpired(cmd="curl", timeout=120) + with pytest.raises(AareDaqError, match="token request failed"): + request_user_token(URL, CERT) diff --git a/tests/unit/test_automation_permission_widget.py b/tests/unit/test_automation_permission_widget.py new file mode 100644 index 0000000..58ad77a --- /dev/null +++ b/tests/unit/test_automation_permission_widget.py @@ -0,0 +1,83 @@ +from unittest.mock import MagicMock, patch + +import pytest + +from mx_bec.bec_widgets.widgets.aare_bec import MxAutomationPermissionWidget +from mx_bec.endpoints import AuthEndpoints +from mx_bec.external_services.aaredaq import AareDaqError +from mx_bec.messages import MXAutomationPermissionStatusMessage + +WIDGET = "mx_bec.bec_widgets.widgets.aare_bec.automation_permission" +GRANTED = MXAutomationPermissionStatusMessage( + granted=True, + username="e12345", + pgroups=["p16371", "p20000"], + staff=False, + expires_at=1.8e9, + received_at=1.7e9, +) + + +@pytest.fixture +def client(): + client = MagicMock() + client.connector.get.return_value = None + return client + + +@pytest.fixture +def widget(qtbot, client): + widget = MxAutomationPermissionWidget(client=client) + qtbot.addWidget(widget) + yield widget + widget.cleanup() + + +def test_shows_that_no_status_is_published(widget, client): + client.connector.get.assert_called_with(AuthEndpoints.automation_permission_status()) + assert widget._granted.text().startswith("unknown") + assert widget._username.text() == "-" + + +def test_shows_the_status_read_on_refresh(widget, client): + client.connector.get.return_value = GRANTED + widget.refresh() + assert widget._granted.text() == "granted" + assert widget._username.text() == "e12345" + assert widget._pgroups.text() == "p16371, p20000" + assert widget._staff.text() == "no" + assert widget._received_at.text() != "-" and widget._expires_at.text() != "-" + + +def test_shows_status_updates_from_the_service(widget): + widget._on_status(GRANTED.content, {}) + assert widget._granted.text() == "granted" + widget._on_status(MXAutomationPermissionStatusMessage(granted=False).content, {}) + assert widget._granted.text() == "not granted" + assert (widget._username.text(), widget._pgroups.text(), widget._staff.text()) == ("-",) * 3 + + +def test_button_gets_a_token_and_forwards_it(widget, client, qtbot): + with ( + patch(f"{WIDGET}.request_user_token", return_value=("e12345", "token")) as request, + patch(f"{WIDGET}.grant_automation_permission") as grant, + qtbot.waitSignal(widget._grant_finished, timeout=5000), + ): + widget._button.click() + request.assert_called_once_with() + grant.assert_called_once_with(client.connector, "e12345", "token") + assert "e12345" in widget._message.text() + assert "token" not in widget._message.text().replace("Token of", "") + assert widget._button.isEnabled() + + +def test_a_failed_token_request_is_shown(widget, qtbot): + with ( + patch(f"{WIDGET}.request_user_token", side_effect=AareDaqError("no ticket (kinit)")), + patch(f"{WIDGET}.grant_automation_permission") as grant, + qtbot.waitSignal(widget._grant_finished, timeout=5000), + ): + widget.grant_permission() + grant.assert_not_called() + assert widget._message.text() == "Failed: no ticket (kinit)" + assert widget._button.isEnabled() -- 2.54.1 From 403f3da8f35f700878f9783d46afc93342a25fad Mon Sep 17 00:00:00 2001 From: David Perl Date: Thu, 3 Dec 2026 11:23:28 +0100 Subject: [PATCH 10/11] make aaredaq usable from client --- mx_bec/external_services/aaredaq.py | 163 +++++++++++++++++++++------- tests/unit/test_aaredaq.py | 127 +++++++++++++++++++++- 2 files changed, 248 insertions(+), 42 deletions(-) diff --git a/mx_bec/external_services/aaredaq.py b/mx_bec/external_services/aaredaq.py index 64ce499..7598e45 100644 --- a/mx_bec/external_services/aaredaq.py +++ b/mx_bec/external_services/aaredaq.py @@ -8,6 +8,7 @@ import requests from aarecommon.config.beamline import cfg_get, mx_beamline from aarecommon.models.beamline import MXBeamline from bec_lib.logger import bec_logger +from pydantic import BaseModel, ConfigDict if TYPE_CHECKING: from mx_bec.service import AareBec @@ -32,6 +33,21 @@ class AareDaqError(RuntimeError): """A call to the AareDAQ server failed.""" +class LoadedSampleInfo(BaseModel): + """An aareDB sample together with where it sits in the beamline's TELL: what AareDAQ answers + to `GET /sample/{sample_id}` (`aare.daq.aaredb.LoadedSampleInfo`). The sample record itself + is kept as the plain dictionary of the aareDB `Sample`, as mx_bec does not depend on the + aareDB client.""" + + model_config = ConfigDict(extra="allow") + + sample: dict[str, Any] + puck_name: str + puck_pgroup: str + dewar_name: str | None = None + tell_position: str | None = None + + def configured_url() -> str: """The URL of the AareDAQ server, from the aarecommon beamline config.""" beamline = mx_beamline() @@ -81,23 +97,88 @@ def request_user_token(url: str | None = None, cert_path: str | None = None) -> return username, token -class AareDaq: - """Client for the part of the AareDAQ REST API (aaredaq `server.py`) which AareBec still uses: - mounting a sample. +class _ForwardedToken: + """For the AareBec service: the token which a user forwarded to it, see + `mx_bec.automation_permission`. The service has no identity of its own towards AareDAQ.""" - The service has no identity of its own towards AareDAQ: every request is made with the - bearer token of a user who gave the service permission to act on their behalf, see - `mx_bec.automation_permission`. Without such a token no request is made. The server URL and - its certificate come from the aarecommon beamline config unless given. + def __init__(self, client: AareBec) -> None: + self._client = client + + def get(self) -> str: + # needed for every request, whether or not the permission is enforced otherwise + info = self._client.automation_permission.auth_info + if info is None: + raise AareDaqError( + "No token for AareDAQ: a user must first give the AareBec service permission to " + "act on their behalf (mx_bec.automation_permission.grant_automation_permission)" + ) + return info.token + + def rejected(self) -> bool: + """The server did not accept the token: drop the permission, so that a user has to grant + it again. There is no other token to try again with.""" + self._client.automation_permission.clear() + return False + + rejected_hint = "it may have expired. Grant the automation permission again." + + +class _UserToken: + """For a user's own process: the token given, or else one requested from AareDAQ for the + user running the process when it is first needed (by Kerberos, see `request_user_token`).""" + + def __init__(self, daq: AareDaq, token: str | None) -> None: + self._daq = daq + self._token = token + self._given = token is not None + + def get(self) -> str: + if self._token is None: + _, self._token = request_user_token(self._daq.url, self._daq.cert_path) + return self._token + + def rejected(self) -> bool: + """The server did not accept the token. A token which was requested here is requested + again, once; one which was given cannot be renewed.""" + if self._given: + return False + logger.info("AareDAQ rejected the token, requesting a new one") + self._token = None + return True + + rejected_hint = "it may have expired." + + +class AareDaq: + """Client for the part of the AareDAQ REST API (aaredaq `server.py`) which mx_bec uses. + Every request carries the bearer token of a user, which comes from one of two places: + + - `AareDaq(client=aare_bec)`, in the AareBec service: the token which a user forwarded to + the service, see `mx_bec.automation_permission`. Without one no request is made, and if + the server rejects it the permission is dropped. + - `AareDaq()` or `AareDaq(token=...)`, in a user's own process (a BEC client, the GUI): the + user's own token. If none is given, one is requested for the user running the process + when it is first needed, which needs a valid Kerberos ticket, and requested again once if + the server rejects it. + + 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 + self, + client: AareBec | None = None, + url: str | None = None, + cert_path: str | None = None, + token: str | None = None, ) -> None: - self._client = client + if client is not None and token is not None: + raise ValueError("Give either the AareBec service (forwarded token) or a token") self._url = url self._cert_path = cert_path self._session = requests.Session() + self._token_source: _ForwardedToken | _UserToken = ( + _ForwardedToken(client) if client is not None else _UserToken(self, token) + ) @property def url(self) -> str: @@ -111,17 +192,6 @@ class AareDaq: self._cert_path = configured_cert_path() return self._cert_path - def _token(self) -> str: - """The token which a user forwarded to the service. Needed for every request, whether - or not the automation permission is enforced otherwise.""" - info = self._client.automation_permission.auth_info - if info is None: - raise AareDaqError( - "No token for AareDAQ: a user must first give the AareBec service permission to " - "act on their behalf (mx_bec.automation_permission.grant_automation_permission)" - ) - return info.token - def _request( self, method: str, @@ -131,27 +201,30 @@ class AareDaq: body: dict[str, Any] | None = None, timeout_s: float = REQUEST_TIMEOUT_S, ) -> Any: - """Call `endpoint` with the forwarded bearer token and return the decoded JSON response. - If the server rejects the token (401), the permission is dropped, so that a user has to - grant it again. Any error becomes an AareDaqError.""" - token = self._token() - try: - resp = self._session.request( - method, - f"{self.url}{endpoint}", - params=params, - json=body, - headers={"Authorization": f"Bearer {token}"}, - verify=self.cert_path, - timeout=timeout_s, - ) - except requests.RequestException as e: - raise AareDaqError(f"AareDAQ {method} {endpoint} failed: {e}") from e - if resp.status_code == 401: - self._client.automation_permission.clear() + """Call `endpoint` with the bearer token and return the decoded JSON response. If the + server rejects the token (401), the request is repeated once if there is a new token to + be had (see the class documentation). Any error becomes an AareDaqError.""" + for attempt in range(2): + token = self._token_source.get() + try: + resp = self._session.request( + method, + f"{self.url}{endpoint}", + params=params, + json=body, + headers={"Authorization": f"Bearer {token}"}, + verify=self.cert_path, + timeout=timeout_s, + ) + except requests.RequestException as e: + raise AareDaqError(f"AareDAQ {method} {endpoint} failed: {e}") from e + if resp.status_code != 401: + break + if attempt == 0 and self._token_source.rejected(): + continue raise AareDaqError( - f"AareDAQ rejected the forwarded token for {method} {endpoint} (401): it may " - f"have expired. Grant the automation permission again. {resp.text[:500]}" + f"AareDAQ rejected the token for {method} {endpoint} (401): " + f"{self._token_source.rejected_hint} {resp.text[:500]}" ) if not resp.ok: raise AareDaqError( @@ -159,6 +232,9 @@ class AareDaq: ) return resp.json() + def _get(self, endpoint: str, timeout_s: float = REQUEST_TIMEOUT_S) -> Any: + return self._request("GET", endpoint, timeout_s=timeout_s) + def _post( self, endpoint: str, @@ -177,3 +253,10 @@ class AareDaq: self._post( "/sample/mount", params={"dbid": dbid, "reference": reference}, timeout_s=timeout_s ) + + def sample_info(self, sample_id: int) -> LoadedSampleInfo: + """The aareDB record of the sample with database id `sample_id`, with its puck, dewar + and TELL position. AareDAQ refuses if the sample is not loaded at this beamline (400), + or if the user who forwarded the token is neither in the sample's pgroup nor staff + (403); both are an AareDaqError.""" + return LoadedSampleInfo.model_validate(self._get(f"/sample/{sample_id}")) diff --git a/tests/unit/test_aaredaq.py b/tests/unit/test_aaredaq.py index f65facb..3c119ac 100644 --- a/tests/unit/test_aaredaq.py +++ b/tests/unit/test_aaredaq.py @@ -6,7 +6,13 @@ import pytest import requests from mx_bec.automation_permission import AuthInfo -from mx_bec.external_services.aaredaq import DEFAULT_URLS, AareDaq, AareDaqError, request_user_token +from mx_bec.external_services.aaredaq import ( + DEFAULT_URLS, + AareDaq, + AareDaqError, + LoadedSampleInfo, + request_user_token, +) URL, CERT, TOKEN = "https://daq.test", "/certs/daq.crt", "eyJ.abc.def" @@ -94,7 +100,9 @@ def test_the_latest_forwarded_token_is_used(daq, client): def test_a_rejected_token_drops_the_permission(daq, client): daq._response = _response(401, text="nope") - with pytest.raises(AareDaqError, match="rejected the forwarded token"): + with pytest.raises( + AareDaqError, match="rejected the token.*Grant the automation permission again" + ): daq.mount_sample(1) assert len(_calls(daq)) == 1 # there is no other token to try again with client.automation_permission.clear.assert_called_once_with() @@ -113,6 +121,55 @@ def test_connection_error_becomes_an_aaredaq_error(daq): daq.mount_sample(1) +SAMPLE_INFO = { + "sample": {"id": 42, "sample_name": "lyso_1", "pgroup": "p16371", "position": 3}, + "puck_name": "PUCK7", + "puck_pgroup": "p16371", + "dewar_name": "dewar_a", + "tell_position": "B2", +} + + +def test_sample_info(daq): + daq._response = _response(json_data=SAMPLE_INFO) + info = daq.sample_info(42) + assert info == LoadedSampleInfo(**SAMPLE_INFO) + assert (info.sample["sample_name"], info.puck_name, info.tell_position) == ( + "lyso_1", + "PUCK7", + "B2", + ) + [(method, url, kwargs)] = _calls(daq) + assert (method, url) == ("GET", f"{URL}/sample/42") + assert kwargs["headers"] == {"Authorization": f"Bearer {TOKEN}"} + assert kwargs["timeout"] == 30.0 + + +def test_sample_info_without_dewar_and_tell_position(daq): + daq._response = _response( + json_data={"sample": {"id": 1}, "puck_name": "P", "puck_pgroup": "p1"} + ) + info = daq.sample_info(1) + assert (info.dewar_name, info.tell_position) == (None, None) + + +@pytest.mark.parametrize( + "status, text", [(400, "Sample 42 is not loaded at this beamline."), (403, "not in p16371")] +) +def test_sample_info_refused(daq, client, status, text): + daq._response = _response(status, text=text) + with pytest.raises(AareDaqError, match=f"{status}.*{text}"): + daq.sample_info(42) + client.automation_permission.clear.assert_not_called() + + +def test_sample_info_needs_a_forwarded_token(daq, client): + client.automation_permission.auth_info = None + with pytest.raises(AareDaqError, match="No token for AareDAQ"): + daq.sample_info(42) + daq._session.request.assert_not_called() + + # ---- the token request, which clients (not the service) make for the user running them ---- @@ -159,3 +216,69 @@ def test_user_token_request_timeout(curl): curl.side_effect = subprocess.TimeoutExpired(cmd="curl", timeout=120) with pytest.raises(AareDaqError, match="token request failed"): request_user_token(URL, CERT) + + +# ---- used directly by a user, with their own token instead of one forwarded to the service ---- + + +@pytest.fixture +def user_daq(): + """Client without the AareBec service, with a mocked HTTP session answering "OK".""" + daq = AareDaq(url=URL, cert_path=CERT) + daq._session = MagicMock() + daq._session.request.side_effect = None + daq._session.request.return_value = _response(json_data="OK") + return daq + + +def test_user_token_is_requested_lazily_and_once(user_daq, curl): + curl.assert_not_called() + user_daq.mount_sample(1) + user_daq.mount_sample(2) + curl.assert_called_once() + headers = [kwargs["headers"]["Authorization"] for _, _, kwargs in _calls(user_daq)] + assert headers == [f"Bearer {TOKEN}"] * 2 + + +def test_rejected_user_token_is_renewed_once(user_daq, curl): + new = json.dumps({"access_token": "new", "info": {"sub": "e12345"}}) + curl.side_effect = [_curl_result(), _curl_result(new)] + user_daq._session.request.side_effect = [_response(401), _response(json_data="OK")] + user_daq.mount_sample(1) + headers = [kwargs["headers"]["Authorization"] for _, _, kwargs in _calls(user_daq)] + assert headers == [f"Bearer {TOKEN}", "Bearer new"] + + +def test_persistently_rejected_user_token_is_an_error(user_daq, curl): + user_daq._session.request.return_value = _response(401, text="nope") + with pytest.raises(AareDaqError, match="rejected the token.*nope"): + user_daq.mount_sample(1) + assert len(_calls(user_daq)) == 2 + assert curl.call_count == 2 + + +def test_failed_user_token_request_is_an_error_before_any_request(user_daq, curl): + curl.return_value = _curl_result(returncode=6, stderr="could not resolve") + with pytest.raises(AareDaqError, match="curl exit 6"): + user_daq.sample_info(1) + user_daq._session.request.assert_not_called() + + +def test_a_given_token_is_used_and_not_renewed(curl): + daq = AareDaq(url=URL, cert_path=CERT, token="mine") + daq._session = MagicMock() + daq._session.request.return_value = _response(json_data="OK") + daq.mount_sample(1) + [(_, _, kwargs)] = _calls(daq) + assert kwargs["headers"] == {"Authorization": "Bearer mine"} + + daq._session.request.return_value = _response(401, text="nope") + with pytest.raises(AareDaqError, match="rejected the token"): + daq.mount_sample(1) + assert len(_calls(daq)) == 2 # the one above and one rejected: no second attempt + curl.assert_not_called() + + +def test_service_and_token_cannot_both_be_given(client): + with pytest.raises(ValueError, match="either"): + AareDaq(client, token="mine") -- 2.54.1 From 66c66bedb7115f8b54dd171749ce4256f1e90156 Mon Sep 17 00:00:00 2001 From: David Perl Date: Thu, 3 Dec 2026 11:25:40 +0100 Subject: [PATCH 11/11] add current sample widget --- .../bec_widgets/widgets/aare_bec/__init__.py | 2 + .../widgets/aare_bec/current_sample.py | 147 ++++++++++++++++++ tests/unit/test_current_sample_widget.py | 105 +++++++++++++ 3 files changed, 254 insertions(+) create mode 100644 mx_bec/bec_widgets/widgets/aare_bec/current_sample.py create mode 100644 tests/unit/test_current_sample_widget.py diff --git a/mx_bec/bec_widgets/widgets/aare_bec/__init__.py b/mx_bec/bec_widgets/widgets/aare_bec/__init__.py index 79cf99e..7e86a16 100644 --- a/mx_bec/bec_widgets/widgets/aare_bec/__init__.py +++ b/mx_bec/bec_widgets/widgets/aare_bec/__init__.py @@ -1,5 +1,6 @@ from .actors_config import MxActorConfigWidget from .automation_permission import MxAutomationPermissionWidget +from .current_sample import MxCurrentSampleWidget from .sample_queue import SampleQueueWidget from .sample_spreadsheet_display import SampleSpreadsheetDisplay from .task_panel import MxTaskPanel @@ -8,6 +9,7 @@ from .task_queue import MxTaskQueueWidget __all__ = [ "MxActorConfigWidget", "MxAutomationPermissionWidget", + "MxCurrentSampleWidget", "SampleQueueWidget", "SampleSpreadsheetDisplay", "MxTaskPanel", diff --git a/mx_bec/bec_widgets/widgets/aare_bec/current_sample.py b/mx_bec/bec_widgets/widgets/aare_bec/current_sample.py new file mode 100644 index 0000000..f927751 --- /dev/null +++ b/mx_bec/bec_widgets/widgets/aare_bec/current_sample.py @@ -0,0 +1,147 @@ +from __future__ import annotations + +from threading import Thread + +from bec_lib.logger import bec_logger +from bec_widgets.utils.bec_connector import ConnectionConfig +from bec_widgets.utils.bec_widget import BECWidget +from bec_widgets.utils.error_popups import SafeSlot +from qtpy.QtCore import Signal +from qtpy.QtWidgets import ( + QFormLayout, + QHeaderView, + QLabel, + QTableWidget, + QTableWidgetItem, + QVBoxLayout, + QWidget, +) + +from mx_bec.endpoints import StateEndpoints +from mx_bec.external_services.aaredaq import AareDaq, LoadedSampleInfo +from mx_bec.messages import MXMeasurementSequenceMessage + +logger = bec_logger.logger + +NOT_SET = "-" + + +class MxCurrentSampleWidget(BECWidget, QWidget): + """ + Widget to show the mounted sample: its aareDB record, and its puck, dewar and TELL position. + + Whenever the AareBec service announces that a sample was mounted (`sample_mounted`), the + record is fetched from AareDAQ with the token of the user running the GUI, which needs a + valid Kerberos ticket, and is only given for samples the user may work on. + """ + + PLUGIN = True + ICON_NAME = "science" + USER_ACCESS = ["refresh", "show_sample"] + + # the record is fetched on a worker thread; the outcome is shown on the GUI thread: + # (sample id, record or None, message) + _fetched = Signal(int, object, str) + + def __init__( + self, + parent: QWidget | None = None, + client=None, + config: ConnectionConfig | None = None, + gui_id: str | None = None, + **kwargs, + ) -> None: + super().__init__(parent=parent, client=client, config=config, gui_id=gui_id, **kwargs) + self._daq = AareDaq() # with the user's own token, requested on first use + self._worker: Thread | None = None + self._sample_id: int | None = None + + self._id = QLabel(NOT_SET, parent=self) + self._puck = QLabel(NOT_SET, parent=self) + self._pgroup = QLabel(NOT_SET, parent=self) + self._dewar = QLabel(NOT_SET, parent=self) + self._tell_position = QLabel(NOT_SET, parent=self) + form = QFormLayout() + form.addRow("Sample ID", self._id) + form.addRow("Puck", self._puck) + form.addRow("Puck pgroup", self._pgroup) + form.addRow("Dewar", self._dewar) + form.addRow("TELL position", self._tell_position) + + self._record = QTableWidget(0, 2, parent=self) + self._record.setHorizontalHeaderLabels(["Field", "Value"]) + self._record.verticalHeader().setVisible(False) + self._record.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers) + self._record.horizontalHeader().setSectionResizeMode( + 0, QHeaderView.ResizeMode.ResizeToContents + ) + self._record.horizontalHeader().setStretchLastSection(True) + self._message = QLabel("No sample mounted", parent=self) + self._message.setWordWrap(True) + + layout = QVBoxLayout(self) + layout.addLayout(form) + layout.addWidget(QLabel("Sample record", parent=self)) + layout.addWidget(self._record) + layout.addWidget(self._message) + + self._fetched.connect(self._on_fetched) + # released automatically by BECWidget.cleanup() (disconnect_owner) + self.bec_dispatcher.connect_slot(self._on_sample_mounted, StateEndpoints.sample_mounted()) + self.refresh() + + @SafeSlot() + def refresh(self): + """Show the sample which was mounted last, as announced by the AareBec service.""" + self._show_mounted(self.client.connector.get(StateEndpoints.sample_mounted())) + + @SafeSlot(dict, dict) + def _on_sample_mounted(self, content: dict, _metadata: dict): + self._show_mounted(MXMeasurementSequenceMessage(**content)) + + def _show_mounted(self, msg: MXMeasurementSequenceMessage | None) -> None: + if msg is None or not msg.success: + return # nothing (new) was mounted: keep what is shown + self.show_sample(msg.sample_id) + + @SafeSlot(int) + def show_sample(self, sample_id: int): + """Fetch the record of the sample with this database id from AareDAQ and show it. + Returns at once; the record, or why it could not be fetched, appears in the widget.""" + self._sample_id = sample_id + self._id.setText(str(sample_id)) + self._message.setText(f"Fetching the record of sample {sample_id}...") + self._worker = Thread( + target=self._fetch, args=(sample_id,), name="mx-sample-info", daemon=True + ) + self._worker.start() + + def _fetch(self, sample_id: int) -> None: + """Runs on a worker thread: the first request also has to get a token.""" + try: + info = self._daq.sample_info(sample_id) + except Exception as e: # pylint: disable=broad-except + logger.warning(f"Could not fetch the record of sample {sample_id}: {e}") + self._fetched.emit(sample_id, None, f"Could not fetch the sample record: {e}") + return + self._fetched.emit(sample_id, info, "") + + @SafeSlot(int, object, str) + def _on_fetched(self, sample_id: int, info: LoadedSampleInfo | None, message: str): + if sample_id != self._sample_id: + return # another sample was mounted in the meantime + self._message.setText(message) + self._puck.setText(info.puck_name if info else NOT_SET) + self._pgroup.setText(info.puck_pgroup if info else NOT_SET) + self._dewar.setText((info.dewar_name if info else None) or NOT_SET) + self._tell_position.setText((info.tell_position if info else None) or NOT_SET) + record = info.sample if info else {} + self._record.setRowCount(len(record)) + for row, (field, value) in enumerate(record.items()): + self._record.setItem(row, 0, QTableWidgetItem(str(field))) + self._record.setItem(row, 1, QTableWidgetItem("" if value is None else str(value))) + + def cleanup(self): + if self._worker is not None: + self._worker.join(timeout=1) + super().cleanup() diff --git a/tests/unit/test_current_sample_widget.py b/tests/unit/test_current_sample_widget.py new file mode 100644 index 0000000..0b4c108 --- /dev/null +++ b/tests/unit/test_current_sample_widget.py @@ -0,0 +1,105 @@ +from unittest.mock import MagicMock, patch + +import pytest + +from mx_bec.bec_widgets.widgets.aare_bec import MxCurrentSampleWidget +from mx_bec.endpoints import StateEndpoints +from mx_bec.external_services.aaredaq import AareDaqError, LoadedSampleInfo +from mx_bec.messages import MXMeasurementSequenceMessage + +WIDGET = "mx_bec.bec_widgets.widgets.aare_bec.current_sample" +INFO = LoadedSampleInfo( + sample={"id": 42, "sample_name": "lyso_1", "pgroup": "p16371", "comment": None}, + puck_name="PUCK7", + puck_pgroup="p16371", + dewar_name="dewar_a", + tell_position="B2", +) + + +@pytest.fixture +def daq(): + with patch(f"{WIDGET}.AareDaq") as daq_cls: + daq_cls.return_value.sample_info.return_value = INFO + yield daq_cls.return_value + + +@pytest.fixture +def client(): + client = MagicMock() + client.connector.get.return_value = None + return client + + +@pytest.fixture +def widget(qtbot, client, daq): + widget = MxCurrentSampleWidget(client=client) + qtbot.addWidget(widget) + yield widget + widget.cleanup() + + +def _record(widget) -> dict[str, str]: + table = widget._record + return {table.item(row, 0).text(): table.item(row, 1).text() for row in range(table.rowCount())} + + +def _mounted(sample_id: int, success: bool = True) -> dict: + return MXMeasurementSequenceMessage(sample_id=sample_id, success=success).content + + +def test_shows_nothing_before_a_sample_is_mounted(widget, client, daq): + client.connector.get.assert_called_with(StateEndpoints.sample_mounted()) + assert widget._id.text() == "-" and widget._message.text() == "No sample mounted" + daq.sample_info.assert_not_called() + + +def test_shows_the_record_when_a_sample_is_mounted(widget, daq, qtbot): + with qtbot.waitSignal(widget._fetched, timeout=5000): + widget._on_sample_mounted(_mounted(42), {}) + daq.sample_info.assert_called_once_with(42) + assert widget._id.text() == "42" + assert (widget._puck.text(), widget._pgroup.text()) == ("PUCK7", "p16371") + assert (widget._dewar.text(), widget._tell_position.text()) == ("dewar_a", "B2") + assert _record(widget) == { + "id": "42", + "sample_name": "lyso_1", + "pgroup": "p16371", + "comment": "", + } + assert widget._message.text() == "" + + +def test_shows_the_sample_mounted_before_the_widget_opened(qtbot, client, daq): + client.connector.get.return_value = MXMeasurementSequenceMessage(sample_id=7, success=True) + widget = MxCurrentSampleWidget(client=client) + qtbot.addWidget(widget) + qtbot.waitUntil(lambda: widget._puck.text() == "PUCK7", timeout=5000) + daq.sample_info.assert_called_once_with(7) + widget.cleanup() + + +def test_a_failed_mount_keeps_what_is_shown(widget, daq, qtbot): + with qtbot.waitSignal(widget._fetched, timeout=5000): + widget._on_sample_mounted(_mounted(42), {}) + widget._on_sample_mounted(_mounted(43, success=False), {}) + assert widget._id.text() == "42" + daq.sample_info.assert_called_once_with(42) + + +def test_shows_why_the_record_could_not_be_fetched(widget, daq, qtbot): + with qtbot.waitSignal(widget._fetched, timeout=5000): + widget._on_sample_mounted(_mounted(42), {}) + daq.sample_info.side_effect = AareDaqError("403: not in p20000") + with qtbot.waitSignal(widget._fetched, timeout=5000): + widget.show_sample(43) + assert widget._id.text() == "43" + assert "403: not in p20000" in widget._message.text() + # nothing of the previous sample is left + assert widget._puck.text() == "-" and _record(widget) == {} + + +def test_a_late_answer_for_a_previous_sample_is_ignored(widget): + widget._sample_id = 43 + widget._on_fetched(42, INFO, "") + assert widget._puck.text() == "-" -- 2.54.1