From f779a4100785395f28d4713fe2e8f27692d2b271 Mon Sep 17 00:00:00 2001 From: David Perl Date: Thu, 3 Dec 2026 11:02:51 +0100 Subject: [PATCH] get info for loaded samples --- src/aare/daq/aaredb.py | 46 +++++++++++++++++++++++---- src/aare/daq/server.py | 31 +++++++++++++++++- tests/conftest.py | 1 + tests/unit/daq/test_aaredb.py | 40 +++++++++++++++++++++++ tests/unit/daq/test_server.py | 60 +++++++++++++++++++++++++++++++++++ 5 files changed, 171 insertions(+), 7 deletions(-) diff --git a/src/aare/daq/aaredb.py b/src/aare/daq/aaredb.py index 94d85436..e9edd5a7 100644 --- a/src/aare/daq/aaredb.py +++ b/src/aare/daq/aaredb.py @@ -4,11 +4,23 @@ import aareDB from aarecommon.config.logger import setup_logger from aarecommon.config.logger_events import log_timing from aarecommon.models.beamline import MXBeamline +from aareDB.models.puck_with_tell_position import PuckWithTellPosition from aareDB.models.sample import Sample +from pydantic import BaseModel logger = setup_logger("aareDAQ") +class LoadedSampleInfo(BaseModel): + """An aareDB sample together with where it currently sits in this beamline's TELL.""" + + sample: Sample + puck_name: str + puck_pgroup: str + dewar_name: str | None = None + tell_position: str | None = None + + class AareWrapper: def __init__(self, bl: MXBeamline, host: str = "https://mx-aaredb-dmz-01.psi.ch/dispatcher"): configuration = aareDB.Configuration(host=host) @@ -36,15 +48,37 @@ class AareWrapper: self._tell_api = aareDB.TellsRunnerApi(self.client) self._bl = bl + def _find_loaded(self, sample_id: int) -> tuple[PuckWithTellPosition, Sample] | None: + pucks = self._tell_api.get_pucks_with_tell_position(tell=self._bl.value.upper()) + for puck in pucks: + for sample in puck.samples or []: + if sample.id == sample_id: + return puck, sample + return None + @log_timing(logger, "AareDB call") def find_loaded_sample(self, sample_id: int) -> Sample | None: """Look up a sample among the pucks currently loaded in this beamline's TELL. Returns None when no loaded puck holds a sample with that database id. """ - pucks = self._tell_api.get_pucks_with_tell_position(tell=self._bl.value.upper()) - for puck in pucks: - for sample in puck.samples or []: - if sample.id == sample_id: - return sample - return None + found = self._find_loaded(sample_id) + return found[1] if found else None + + @log_timing(logger, "AareDB call") + def get_sample_info(self, sample_id: int) -> LoadedSampleInfo | None: + """Full aareDB record of a loaded sample plus its puck/dewar/TELL location. + + Returns None when the sample is not loaded at this beamline. + """ + found = self._find_loaded(sample_id) + if found is None: + return None + puck, sample = found + return LoadedSampleInfo( + sample=sample, + puck_name=puck.puck_name, + puck_pgroup=puck.pgroup, + dewar_name=puck.dewar_name, + tell_position=puck.tell_position, + ) diff --git a/src/aare/daq/server.py b/src/aare/daq/server.py index 95aeecc1..ab56791a 100644 --- a/src/aare/daq/server.py +++ b/src/aare/daq/server.py @@ -14,7 +14,7 @@ from fastapi.concurrency import run_in_threadpool from fastapi.security import OAuth2PasswordBearer from aare.daq import auth -from aare.daq.aaredb import AareWrapper +from aare.daq.aaredb import AareWrapper, LoadedSampleInfo from aare.daq.auth import SampleAccess from aare.daq.samples import DummySampleStore, MountResult from aare.daq.server_exception_handler import register_exception_handlers @@ -101,6 +101,35 @@ async def sample_access(sample_id: int, token: str = Depends(oauth2_scheme)) -> return auth.check_sample_access(data, sample_id, sample.pgroup if sample else None) +@app.get("/sample/{sample_id}") +async def sample_info(sample_id: int, token: str = Depends(oauth2_scheme)) -> LoadedSampleInfo: + """ + Fetch the aareDB record of a sample loaded at this beamline. + + Same access rule as mounting: the token's user must be a member of the sample's + p-group, or staff. + + Args: + sample_id: aareDB database identifier of the sample. + token: OAuth2 access token of the user asking. + + Returns: + LoadedSampleInfo: the sample plus its puck, dewar and TELL position. + + Raises: + SampleException: the sample is not loaded at this beamline (400). + UserRightsException: the user may not work on this sample (403). + """ + data = auth.parse_token(token) + info = await run_in_threadpool(aaredb.get_sample_info, sample_id) + if info is None: + raise SampleException(f"Sample {sample_id} is not loaded at this beamline.") + access = auth.check_sample_access(data, sample_id, info.sample.pgroup) + if not access.allowed: + raise UserRightsException(message=access.reason, code=AuthErrorCode.FORBIDDEN) + return info + + @app.post("/sample/mount/{sample_id}") async def mount_sample(sample_id: int, token: str = Depends(oauth2_scheme)) -> MountResult: """ diff --git a/tests/conftest.py b/tests/conftest.py index 61543b57..de9def82 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -28,6 +28,7 @@ def server_module(): def mock_aaredb(): db = MagicMock() db.find_loaded_sample.return_value = None + db.get_sample_info.return_value = None return db diff --git a/tests/unit/daq/test_aaredb.py b/tests/unit/daq/test_aaredb.py index 369f0e6f..790aa324 100644 --- a/tests/unit/daq/test_aaredb.py +++ b/tests/unit/daq/test_aaredb.py @@ -1,6 +1,8 @@ from unittest.mock import MagicMock, patch import pytest +from aareDB.models.puck_with_tell_position import PuckWithTellPosition +from aareDB.models.sample import Sample from aare.daq.aaredb import AareWrapper @@ -26,6 +28,7 @@ def wrapper(mock_bl): def _puck(*sample_ids, pgroup="p12345"): puck = MagicMock() + puck.pgroup = pgroup puck.samples = [MagicMock(id=i, pgroup=pgroup) for i in sample_ids] return puck @@ -51,3 +54,40 @@ def test_find_loaded_sample_puck_without_samples(wrapper): puck.samples = None wrapper._tell_api.get_pucks_with_tell_position.return_value = [puck] assert wrapper.find_loaded_sample(1) is None + + +def _real_sample(sample_id, pgroup): + return Sample( + id=sample_id, + pgroup=pgroup, + sample_name=f"s{sample_id}", + position=1, + data_collection_parameters=None, + ) + + +def test_get_sample_info(wrapper): + puck = PuckWithTellPosition( + id=10, + puck_name="PUCK-A", + puck_type="unipuck", + pgroup="p67890", + dewar_name="DEWAR-1", + tell_position="B3", + samples=[_real_sample(5, "p67890"), _real_sample(6, "p67890")], + ) + wrapper._tell_api.get_pucks_with_tell_position.return_value = [puck] + + info = wrapper.get_sample_info(6) + assert info is not None + assert info.sample.id == 6 + assert info.sample.pgroup == "p67890" + assert info.puck_name == "PUCK-A" + assert info.puck_pgroup == "p67890" + assert info.dewar_name == "DEWAR-1" + assert info.tell_position == "B3" + + +def test_get_sample_info_missing(wrapper): + wrapper._tell_api.get_pucks_with_tell_position.return_value = [_puck(1, 2)] + assert wrapper.get_sample_info(99) is None diff --git a/tests/unit/daq/test_server.py b/tests/unit/daq/test_server.py index 6089eb9e..b20dc97c 100644 --- a/tests/unit/daq/test_server.py +++ b/tests/unit/daq/test_server.py @@ -1,7 +1,9 @@ from unittest.mock import MagicMock, patch import pytest +from aareDB.models.sample import Sample +from aare.daq.aaredb import LoadedSampleInfo from aare.daq.auth import TokenData from aare.daq.samples import DummySample @@ -147,3 +149,61 @@ def test_mount_against_shipped_catalogue(server_module, mock_aaredb): assert c.post("/sample/mount/1", headers=AUTH).status_code == 200 assert c.post("/sample/mount/4", headers=AUTH).status_code == 403 assert c.post("/sample/mount/999", headers=AUTH).status_code == 400 + + +# --------------------------------------------------------------------------- +# GET /sample/{sample_id} +# --------------------------------------------------------------------------- +def _loaded(sample_id, pgroup): + return LoadedSampleInfo( + sample=Sample( + id=sample_id, + pgroup=pgroup, + sample_name="lyso_01", + position=3, + data_collection_parameters=None, + ), + puck_name="PUCK-A", + puck_pgroup=pgroup, + dewar_name="DEWAR-1", + tell_position="B3", + ) + + +def test_sample_info_requires_token(client): + assert client.get("/sample/1").status_code == 401 + + +def test_sample_info_own_pgroup(client, mock_aaredb): + mock_aaredb.get_sample_info.return_value = _loaded(1, "p12345") + with _as_user(["p12345"]): + response = client.get("/sample/1", headers=AUTH) + assert response.status_code == 200 + body = response.json() + assert body["sample"]["id"] == 1 + assert body["sample"]["sample_name"] == "lyso_01" + assert body["puck_name"] == "PUCK-A" + assert body["tell_position"] == "B3" + mock_aaredb.get_sample_info.assert_called_once_with(1) + + +def test_sample_info_other_pgroup_is_403(client, mock_aaredb): + mock_aaredb.get_sample_info.return_value = _loaded(4, "p67890") + with _as_user(["p12345"]): + response = client.get("/sample/4", headers=AUTH) + assert response.status_code == 403 + assert response.json()["code"] == "FORBIDDEN" + + +def test_sample_info_staff_any_pgroup(client, mock_aaredb): + mock_aaredb.get_sample_info.return_value = _loaded(4, "p67890") + with _as_user(["p11111"], staff=True): + assert client.get("/sample/4", headers=AUTH).status_code == 200 + + +def test_sample_info_not_loaded_is_400(client, mock_aaredb): + mock_aaredb.get_sample_info.return_value = None + with _as_user(["p12345"]): + response = client.get("/sample/999", headers=AUTH) + assert response.status_code == 400 + assert response.json()["exception_class"] == "SampleException"