diff --git a/mx_bec/endpoints.py b/mx_bec/endpoints.py index 518413b..e4c28a7 100644 --- a/mx_bec/endpoints.py +++ b/mx_bec/endpoints.py @@ -1,7 +1,11 @@ from bec_lib.endpoints import EndpointInfo, EndpointType, MessageOp from bec_lib.messages import AvailableResourceMessage, BoolConfigDefaultFalse -from mx_bec.messages import MXMeasurementSequenceMessage, OpticalPredictionMessage +from mx_bec.messages import ( + MXMeasurementSequenceMessage, + MXTaskExecutionMessage, + OpticalPredictionMessage, +) class StateEndpoints: @@ -64,6 +68,30 @@ class ActorEndpoints: ) +class TaskEndpoints: + """Requests for the AareBec service to run one of its `MxTasks`.""" + + @staticmethod + def task_request(): + """Stream of task requests from clients. The AareBec service validates them and queues + the accepted ones on `task_execution`.""" + return EndpointInfo( + endpoint=f"{EndpointType.USER.value}/mx/tasks/request", + message_type=MXTaskExecutionMessage, + message_op=MessageOp.STREAM, + ) + + @staticmethod + def task_execution(): + """FIFO queue of validated tasks waiting to be executed by the AareBec service: new tasks + are appended on the right.""" + return EndpointInfo( + endpoint=f"{EndpointType.USER.value}/mx/tasks/execution", + message_type=MXTaskExecutionMessage, + message_op=MessageOp.LIST, + ) + + class DataAnalysisEndpoints: @staticmethod def optical_prediction(): diff --git a/mx_bec/messages.py b/mx_bec/messages.py index c22d43b..38f1e9c 100644 --- a/mx_bec/messages.py +++ b/mx_bec/messages.py @@ -21,7 +21,7 @@ class MXTaskExecutionMessage(BECMessage): msg_type: ClassVar[str] = "mx_task_execution_message" name: str - args: tuple[int | bool | str | float | None] + args: tuple[int | bool | str | float | None, ...] kwargs: dict[str, int | bool | str | float | None] diff --git a/mx_bec/service.py b/mx_bec/service.py index ef91af0..89e63bb 100644 --- a/mx_bec/service.py +++ b/mx_bec/service.py @@ -10,6 +10,7 @@ from bec_lib.logger import bec_logger from mx_bec.actor_manager import AareActorManager from mx_bec.constants import AareBecWorkflowState +from mx_bec.endpoints import TaskEndpoints from mx_bec.optical_centering import OpticalPrediction from mx_bec.tasks import MxTasks @@ -17,6 +18,8 @@ if TYPE_CHECKING: from bec_lib.redis_connector import RedisConnector from bec_lib.service_config import ServiceConfig + from mx_bec.messages import MXTaskExecutionMessage + logger = bec_logger.logger @@ -46,8 +49,19 @@ class AareBec(BECClient): def start(self): super().start() self._start_actor_manager() + self.connector.register(TaskEndpoints.task_request(), cb=self._on_task_request) self.status = messages.BECStatus.RUNNING + def _on_task_request(self, msg_dict: dict) -> None: + """Validate a task request and, if it names a public `MxTasks` method, append it to the + task execution queue.""" + msg: MXTaskExecutionMessage = msg_dict["data"] + if not MxTasks.is_task(msg.name): + logger.warning(f"Rejected task request: {msg.name!r} is not a public MxTasks method") + return + logger.info(f"Queueing task request: {msg}") + self.connector.rpush(TaskEndpoints.task_execution(), msg) + @property def devices(self): if self.device_manager is None: @@ -62,4 +76,6 @@ class AareBec(BECClient): if self.actor_manager is not None: self.actor_manager.shutdown() self.actor_manager = None + if self.started: # the connector only exists once the client has been started + self.connector.unregister(TaskEndpoints.task_request(), cb=self._on_task_request) super().shutdown(per_thread_timeout_s) diff --git a/mx_bec/tasks.py b/mx_bec/tasks.py index 0605e5a..a8e3811 100644 --- a/mx_bec/tasks.py +++ b/mx_bec/tasks.py @@ -1,6 +1,7 @@ from __future__ import annotations import functools +import inspect from threading import RLock from typing import TYPE_CHECKING, Callable, ParamSpec, TypeVar @@ -27,16 +28,23 @@ class MxTasks: self._client = client self._busy_lock = RLock() + @classmethod + def is_task(cls, name: str) -> bool: + """Whether `name` can be requested as a task, i.e. is a method decorated with + `with_lock`.""" + return getattr(inspect.getattr_static(cls, name, None), "is_mx_task", False) + @staticmethod def with_lock(method: Callable[P, R]) -> Callable[P, R]: - """Run the decorated method while holding `self._busy_lock`, so that only one task - runs at a time.""" + """Mark the decorated method as a task and run it while holding `self._busy_lock`, so + that only one task runs at a time.""" @functools.wraps(method) def wrapper(self: MxTasks, *args, **kwargs): - with self._busy_lock: + with self._busy_lock: # pylint: disable=protected-access return method(self, *args, **kwargs) + wrapper.is_mx_task = True return wrapper # type: ignore # self is part of P @with_lock diff --git a/tests/unit/test_service.py b/tests/unit/test_service.py index 2119a0d..702126d 100644 --- a/tests/unit/test_service.py +++ b/tests/unit/test_service.py @@ -6,8 +6,8 @@ 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 StateEndpoints -from mx_bec.messages import MXMeasurementSequenceMessage +from mx_bec.endpoints import StateEndpoints, TaskEndpoints +from mx_bec.messages import MXMeasurementSequenceMessage, MXTaskExecutionMessage from mx_bec.service import AareBec, MxTasks @@ -28,6 +28,7 @@ def test_service_is_idle_before_start(service): def test_start_creates_actor_manager(service): + service.connector = MagicMock() # normally created by the patched-out BECClient.start with ( patch.object(BECClient, "start") as base_start, patch("mx_bec.service.AareActorManager") as manager_cls, @@ -49,6 +50,77 @@ def test_shutdown_stops_actor_manager(service): assert service.actor_manager is None +def test_start_registers_task_execution_callback(service): + # BECClient.start (patched out) is what normally creates the connector + service.connector = MagicMock() + with ( + patch.object(BECClient, "start"), + patch("mx_bec.service.AareActorManager"), + patch.object(AareBec, "status", create=True), + ): + service.start() + service.connector.register.assert_called_once_with( + TaskEndpoints.task_request(), cb=service._on_task_request + ) + + +def test_shutdown_unregisters_task_request_callback(service): + service.started = True + service.connector = MagicMock() + with patch.object(BECClient, "shutdown"): + service.shutdown() + service.connector.unregister.assert_called_once_with( + TaskEndpoints.task_request(), cb=service._on_task_request + ) + + +def test_shutdown_before_start_does_not_touch_connector(service): + with patch.object(BECClient, "shutdown") as base_shutdown: + service.shutdown() + base_shutdown.assert_called_once() + + +def test_task_request_for_known_method_is_queued(service): + service.connector = MagicMock() + msg = MXTaskExecutionMessage(name="run_optical_centering", args=(3,), kwargs={}) + service._on_task_request({"data": msg}) + service.connector.rpush.assert_called_once_with(TaskEndpoints.task_execution(), msg) + + +NOT_TASKS = [ + "no_such_task", + "_publish_optical_centering_done", # private method + "_client", # private attribute + "_busy_lock", + "with_lock", # public, but a helper rather than a task + "is_task", +] + + +@pytest.mark.parametrize("name", NOT_TASKS) +def test_task_request_for_non_task_name_is_rejected(service, name): + service.connector = MagicMock() + msg = MXTaskExecutionMessage(name=name, args=(), kwargs={}) + with patch("mx_bec.service.logger") as logger: + service._on_task_request({"data": msg}) + service.connector.rpush.assert_not_called() + logger.warning.assert_called_once() + assert name in logger.warning.call_args.args[0] + + +def test_tasks_are_exactly_the_methods_decorated_with_with_lock(): + class Tasks(MxTasks): + @MxTasks.with_lock + def decorated(self): ... + + def plain(self): ... + + assert Tasks.is_task("decorated") + assert not Tasks.is_task("plain") + assert MxTasks.is_task("run_optical_centering") + assert all(not MxTasks.is_task(name) for name in NOT_TASKS) + + @pytest.fixture def mock_client(): client = MagicMock()