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 edf9a31..ae42bfb 100644 --- a/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py +++ b/mx_bec/bec_widgets/widgets/aare_bec/task_panel.py @@ -19,9 +19,7 @@ from qtpy.QtWidgets import ( QWidget, ) -from mx_bec.endpoints import QueueEndpoints -from mx_bec.messages import MXTaskExecutionMessage -from mx_bec.tasks import MxTasks +from mx_bec.tasks import Client, MxTasks logger = bec_logger.logger @@ -100,6 +98,7 @@ class MxTaskPanel(BECWidget, QWidget): **kwargs, ) -> None: super().__init__(parent=parent, client=client, config=config, gui_id=gui_id, **kwargs) + self._tasks = MxTasks[Client](self.client) self._inputs: dict[str, dict[str, QSpinBox | QDoubleSpinBox | QLineEdit]] = {} # all the forms live in a scrollable content widget content = QWidget() @@ -193,6 +192,4 @@ class MxTaskPanel(BECWidget, QWidget): @SafeSlot(str) def request_task(self, name: str, *args, **kwargs): """Submit a task request to the AareBec service.""" - msg = MXTaskExecutionMessage(name=name, args=args, kwargs=kwargs) - logger.info(f"Requesting task: {msg}") - self.client.connector.xadd(QueueEndpoints.task_request(), {"data": msg}) + self._tasks.request(name, *args, **kwargs) diff --git a/mx_bec/service.py b/mx_bec/service.py index 283f204..a46485e 100644 --- a/mx_bec/service.py +++ b/mx_bec/service.py @@ -17,7 +17,7 @@ from mx_bec.jfjoch import JFJoch 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 +from mx_bec.tasks import MxTaskQueue, MxTasks, Server, UnknownTask if TYPE_CHECKING: from bec_lib.redis_connector import RedisConnector @@ -51,10 +51,11 @@ class AareBec(BECClient): self.optical_prediction = OpticalPrediction(client=self) self.jfjoch = JFJoch(client=self) # connects lazily on first use self.aaredaq = AareDaq(client=self) # authenticates lazily on first use - self.tasks = MxTasks(self) + self.tasks = MxTasks[Server](self) self.task_queue: MxTaskQueue | None = None self.sample_info: SampleInfo | None = None - # HAX + # HAX: copy the sample spreadsheet from the beamline redis, to put it into the BEC redis in + # start(). To be replaced by the eventual sample database connection module. _, _host, _port = config_redis_url.split(":") _port = int(_port) _hacky_redis = Redis(_host[2:], _port) @@ -68,18 +69,17 @@ class AareBec(BECClient): self.task_queue.start() self.connector.register(QueueEndpoints.task_request(), cb=self._on_task_request) self.status = messages.BECStatus.RUNNING - # HAX + # HAX: see __init__; to be replaced by the eventual sample database connection module self.connector._managed_connection.set("x10sa:sample_spreadsheet", self._spreadsheet) 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.""" + """Append a requested task to the task execution queue, unless it does not name a task + of `MxTasks`.""" 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.add_task_to_queue(msg) + try: + self.tasks.request(msg.name, *msg.args, **msg.kwargs) + except UnknownTask as e: + logger.warning(f"Rejected task request: {e}") def add_task_to_queue(self, task: MXTaskExecutionMessage): """Add a task to the task queue. The task should be validated or guaranteed possible.""" diff --git a/mx_bec/tasks/__init__.py b/mx_bec/tasks/__init__.py new file mode 100644 index 0000000..619e363 --- /dev/null +++ b/mx_bec/tasks/__init__.py @@ -0,0 +1,29 @@ +"""Tasks which can be requested from the AareBec service: `core` has the machinery (the `task` +decorator, the Server/Client roles, the task queue), `mx_tasks` the tasks themselves.""" + +from mx_bec.tasks.core import ( + BoundTask, + Client, + MxSequenceUpdate, + MxTaskQueue, + RoleT, + Server, + TaskManager, + UnknownTask, + task, +) +from mx_bec.tasks.mx_tasks import MAX_GRID_SCAN_S, MxTasks + +__all__ = [ + "MAX_GRID_SCAN_S", + "BoundTask", + "Client", + "MxSequenceUpdate", + "MxTaskQueue", + "MxTasks", + "RoleT", + "Server", + "TaskManager", + "UnknownTask", + "task", +] diff --git a/mx_bec/tasks/core.py b/mx_bec/tasks/core.py new file mode 100644 index 0000000..ec2a0d7 --- /dev/null +++ b/mx_bec/tasks/core.py @@ -0,0 +1,378 @@ +""" +Role-generic task manager, communicating through the MX task endpoints in Redis. + + class MxTasks(TaskManager[RoleT]): + @task + def mount(self, dbid: int) -> MxSequenceUpdate: ... + + server = MxTasks[Server](aare_bec) # in the AareBec service: tasks run here + client = MxTasks[Client](bec_client) # anywhere else: tasks are requested from the service + + server.mount(3) # runs here, blocking, holding the task lock + server.mount.request(3) # appends it to the task execution queue + server.request("mount", 3) # the same, looked up by name + server.execute(msg) # runs the task named by an MXTaskExecutionMessage + + client.mount(3) # sends a request to the service's task request stream + client.mount.request(3) # the same + client.request("mount", 3) # the same, looked up by name + +Nothing travels back to the requester: a task reports its outcome by returning a state update +(endpoint, message), which the server publishes once the task is done. +""" + +from __future__ import annotations + +import functools +from collections.abc import Callable +from threading import Event, RLock, Thread +from typing import TYPE_CHECKING, Any, ClassVar, Concatenate, Generic, ParamSpec, TypeVar, overload + +from bec_lib.config_values import RedisConfigValue +from bec_lib.endpoints import EndpointInfo +from bec_lib.logger import bec_logger + +from mx_bec.endpoints import QueueEndpoints +from mx_bec.messages import ( + MXMeasurementSequenceMessage, + MXQueueChangedMessage, + MXTaskExecutionMessage, +) +from mx_bec.service import AareBec + +if TYPE_CHECKING: + from bec_lib.client import BECClient + +logger = bec_logger.logger + +# What a task returns: a state to set and publish once it is done, or nothing. +MxSequenceUpdate = tuple[EndpointInfo[Any], MXMeasurementSequenceMessage] | None + +P = ParamSpec("P") +S = TypeVar("S", bound="TaskManager[Any]") + +Args = tuple[Any, ...] +Kwargs = dict[str, Any] + + +class UnknownTask(LookupError): + """The requested name is not a task of the task manager.""" + + +# --------------------------------------------------------------------------- # +# The decorator / descriptor +# --------------------------------------------------------------------------- # + + +class task(Generic[S, P]): # pylint: disable=invalid-name + """Turns a method into a task. What calling it does depends on the instance's role.""" + + def __init__(self, func: Callable[Concatenate[S, P], MxSequenceUpdate]) -> None: + self.func = func + self.name: str = func.__name__ + functools.update_wrapper(self, func) + + def __set_name__(self, owner: type, name: str) -> None: + self.name = name + + def __call__(self, obj: S, /, *args: P.args, **kwargs: P.kwargs) -> None: + """Calling through the class, `MyTasks.some_task(instance, ...)`.""" + obj._call_task(self, args, kwargs) # pylint: disable=protected-access + + @overload + def __get__(self, obj: None, objtype: type | None = None) -> task[S, P]: ... + @overload + def __get__(self, obj: S, objtype: type | None = None) -> BoundTask[P]: ... + def __get__(self, obj: S | None, objtype: type | None = None) -> task[S, P] | BoundTask[P]: + if obj is None: + return self + return BoundTask(self, obj) + + def __repr__(self) -> str: + return f"" + + +AnyTask = task[Any, ...] + + +class BoundTask(Generic[P]): + """A task attached to an instance. Calling it delegates to the instance's role.""" + + __slots__ = ("owner", "spec") + + def __init__(self, spec: task[Any, P], owner: TaskManager[Any]) -> None: + self.spec = spec + self.owner = owner + + def __call__(self, *args: P.args, **kwargs: P.kwargs) -> None: + self.owner._call_task(self.spec, args, kwargs) # pylint: disable=protected-access + + def request(self, *args: P.args, **kwargs: P.kwargs) -> None: + self.owner._request_task(self.spec, args, kwargs) # pylint: disable=protected-access + + @property + def __name__(self) -> str: + return self.spec.name + + @property + def __doc__(self) -> str | None: # pyright: ignore[reportIncompatibleVariableOverride] + return self.spec.__doc__ + + def __repr__(self) -> str: + return f"" + + +# --------------------------------------------------------------------------- # +# Roles +# --------------------------------------------------------------------------- # + + +class Role: + """Base for the 'fundamental type' a TaskManager is parameterised over. A role is mixed in + in front of the TaskManager subclass, so `self` is the task manager instance.""" + + # set by TaskManager.__init__ + _client: BECClient # pyright: ignore[reportUninitializedInstanceVariable] + + def _init_role(self) -> None: + """Set up what the role needs; called at the end of TaskManager.__init__.""" + + def _call_task(self, spec: AnyTask, args: Args, kwargs: Kwargs) -> None: + raise NotImplementedError + + def _request_task(self, spec: AnyTask, args: Args, kwargs: Kwargs) -> None: + raise NotImplementedError + + +class Server(Role): + """Tasks execute here, one at a time. For the AareBec service: `client` is the service.""" + + _busy_lock: RLock # pyright: ignore[reportUninitializedInstanceVariable] + + def _init_role(self) -> None: + self._busy_lock = RLock() # reentrant, so that a task can call other tasks + + def _call_task(self, spec: AnyTask, args: Args, kwargs: Kwargs) -> None: + """Run the task while holding the lock. If it raises, the task queue is paused before + the exception propagates, so that queued tasks don't carry on from a failed state. + Otherwise the state update it returned, if any, is published.""" + with self._busy_lock: + try: + state_update = spec.func(self, *args, **kwargs) + except Exception as e: + self._pause_queue_after_failure(spec.name, e) + raise + logger.info(f"Task: {spec.name} completed.") + if state_update: + self._client.connector.set_and_publish(*state_update) + + def _request_task(self, spec: AnyTask, args: Args, kwargs: Kwargs) -> None: + """Append the task to the execution queue, which the service's MxTaskQueue works off.""" + msg = MXTaskExecutionMessage(name=spec.name, args=args, kwargs=kwargs) + logger.info(f"Queueing task: {msg}") + self._client.connector.rpush(QueueEndpoints.task_execution(), msg) + self._client.connector.send(QueueEndpoints.task_queue_changed(), MXQueueChangedMessage()) + + def _pause_queue_after_failure(self, task_name: str, e: Exception) -> None: + # the queue only exists once the service has started + if (queue := getattr(self._client, "task_queue", None)) is None: + return + logger.warning(f"Task {task_name} failed: {e}.\n Pausing the task queue.") + try: + queue.pause() + except Exception: # pylint: disable=broad-except + # the task's own exception is the one to surface + logger.exception("Failed to pause the task queue") + + +class Client(Role): + """Tasks are forwarded to the service through the task request stream. There is no reply, + so calling a task and requesting it are the same thing.""" + + def _call_task(self, spec: AnyTask, args: Args, kwargs: Kwargs) -> None: + self._request_task(spec, args, kwargs) + + def _request_task(self, spec: AnyTask, args: Args, kwargs: Kwargs) -> None: + msg = MXTaskExecutionMessage(name=spec.name, args=args, kwargs=kwargs) + logger.info(f"Requesting task: {msg}") + self._client.connector.xadd(QueueEndpoints.task_request(), {"data": msg}) + + +RoleT = TypeVar("RoleT", bound=Role) + + +# --------------------------------------------------------------------------- # +# The generic base +# --------------------------------------------------------------------------- # + + +class TaskManager(Generic[RoleT]): + """ + Subclass this as `class MyTasks(TaskManager[RoleT])` and decorate methods with @task. + Instantiate as MyTasks[Server](service) or MyTasks[Client](bec_client). + + MyTasks[Role] builds (and caches) a real class whose MRO is + (MyTasks[Role], Role, MyTasks, TaskManager, ...), so the role's hooks + take effect and isinstance(obj, MyTasks) still holds. + """ + + _tasks: ClassVar[dict[str, AnyTask]] = {} + _role_classes: ClassVar[dict[type, type]] + + def __init__(self, client: AareBec) -> None: + self._client = client + self._init_role() + + def __init_subclass__(cls, **kwargs: Any) -> None: + super().__init_subclass__(**kwargs) + cls._tasks = { + name: attr + for klass in reversed(cls.__mro__) + for name, attr in vars(klass).items() + if isinstance(attr, task) + } + cls._role_classes = {} + + def __class_getitem__(cls, role): + if not (isinstance(role, type) and issubclass(role, Role)): + # TypeVars etc.: normal generic behaviour + return super().__class_getitem__(role) # pyright: ignore[reportAttributeAccessIssue] + if issubclass(cls, Role): + raise TypeError(f"{cls.__name__} already has a role") + if role not in cls._role_classes: + cls._role_classes[role] = type( + f"{cls.__name__}[{role.__name__}]", + (role, cls), + { + "__module__": cls.__module__, + "__qualname__": f"{cls.__qualname__}[{role.__name__}]", + }, + ) + return cls._role_classes[role] + + def __new__(cls, *args: Any, **kwargs: Any): + if not issubclass(cls, Role): + raise TypeError( + f"Instantiate {cls.__name__}[Server](...) or {cls.__name__}[Client](...), " + f"not {cls.__name__}(...)" + ) + return super().__new__(cls) + + # Fallbacks so type checkers know every TaskManager has these hooks; the role overrides them. + def _init_role(self) -> None: + raise NotImplementedError + + def _call_task(self, spec: AnyTask, args: Args, kwargs: Kwargs) -> None: + raise NotImplementedError + + def _request_task(self, spec: AnyTask, args: Args, kwargs: Kwargs) -> None: + raise NotImplementedError + + # --- public API, the same for every role --------------------------------- + + @classmethod + def task_names(cls) -> list[str]: + return list(cls._tasks) + + @classmethod + def is_task(cls, name: str) -> bool: + """Whether `name` can be requested as a task, i.e. is a method decorated with `task`.""" + return name in cls._tasks + + @classmethod + def get_task(cls, name: str) -> AnyTask: + try: + return cls._tasks[name] + except KeyError: + raise UnknownTask(f"{name!r} is not a task of {cls.__name__}") from None + + def request(self, task_: str | BoundTask[...] | AnyTask, /, *args: Any, **kwargs: Any) -> None: + """Request a task by name or by reference: a server queues it for itself, a client asks + the server. Raises UnknownTask for a name which is not a task.""" + if isinstance(task_, BoundTask): + spec = task_.spec + elif isinstance(task_, task): + spec = task_ + else: + spec = self.get_task(task_) + self._request_task(spec, args, kwargs) + + def execute(self, msg: MXTaskExecutionMessage) -> None: + """Call the task named by `msg` with its arguments, as if it had been called directly. + Raises UnknownTask for a name which is not a task.""" + self._call_task(self.get_task(msg.name), msg.args, msg.kwargs) + + +# --------------------------------------------------------------------------- # +# The queue the server works off +# --------------------------------------------------------------------------- # + + +class MxTaskQueue: + """Executes requested tasks one at a time, in order, on a background thread. + + Tasks are popped from the left of the `QueueEndpoints.task_execution()` list and run on the + given task manager. The queue can be paused through the `QueueEndpoints.task_queue_paused()` + config value (from any client): no new task is popped while paused, but a task which is + already running is left to finish. + """ + + def __init__( + self, client: BECClient, tasks: TaskManager[Server], poll_interval_s: float = 0.5 + ) -> None: + self._client = client + self._tasks = tasks + self._poll_interval_s = poll_interval_s + self._stop_event = Event() + self._paused: RedisConfigValue[bool] = RedisConfigValue( + connector=client.connector, endpoint=QueueEndpoints.task_queue_paused() + ) + self._thread = Thread(target=self._run, name="MxTaskQueue", daemon=True) + + @property + def paused(self) -> bool: + return self._paused.value + + def pause(self) -> None: + """Stop taking new tasks from the queue; the current task finishes.""" + self._paused.value = True + + def resume(self) -> None: + """Start taking tasks from the queue again.""" + self._paused.value = False + + def start(self) -> None: + self._thread.start() + + def shutdown(self) -> None: + """Stop the queue thread, waiting for a running task to finish, and drop the Redis + subscription of the paused flag.""" + self._stop_event.set() + if self._thread.is_alive(): + self._thread.join() + self._paused.unregister_all() + + def _run(self) -> None: + while not self._stop_event.is_set(): + if self._paused.value: + self._stop_event.wait(self._poll_interval_s) + continue + msg = self._client.connector.blocking_list_pop( + QueueEndpoints.task_execution(), side="LEFT", timeout_s=self._poll_interval_s + ) + if msg is not None: + self._client.connector.send( + QueueEndpoints.task_queue_changed(), MXQueueChangedMessage() + ) + self.execute(msg) + + def execute(self, msg: MXTaskExecutionMessage) -> None: + """Run a single task. Failures are logged and do not stop the queue thread (a task + manager with the Server role pauses the queue when one of its tasks fails).""" + logger.info(f"Running task {msg.name} with args={msg.args}, kwargs={msg.kwargs}") + try: + self._tasks.execute(msg) + except UnknownTask as e: + logger.warning(f"Skipping queued task: {e}") + except Exception: # pylint: disable=broad-except + logger.exception(f"Task {msg.name} failed") diff --git a/mx_bec/tasks.py b/mx_bec/tasks/mx_tasks.py similarity index 69% rename from mx_bec/tasks.py rename to mx_bec/tasks/mx_tasks.py index 7b6c37a..0029f1b 100644 --- a/mx_bec/tasks.py +++ b/mx_bec/tasks/mx_tasks.py @@ -1,10 +1,7 @@ from __future__ import annotations -import functools -import inspect from secrets import token_hex -from threading import Event, RLock, Thread -from typing import TYPE_CHECKING, Callable, Concatenate, ParamSpec, Self, TypeVar +from typing import TYPE_CHECKING from aarecommon.math.coordinate import Coordinate, SmargonCoordinate from aarecommon.models.raster_grid import ( @@ -12,19 +9,12 @@ from aarecommon.models.raster_grid import ( RasterGridRequest, ) from aarecommon.models.rotation_scan import RotationScanRequest -from bec_lib.config_values import RedisConfigValue -from bec_lib.endpoints import EndpointInfo from bec_lib.logger import bec_logger from mx_bec.devices.smargopolo_smargon import Smargon -from mx_bec.endpoints import QueueEndpoints, StateEndpoints -from mx_bec.jfjoch import RasterScan +from mx_bec.endpoints import StateEndpoints from mx_bec.math import smargon_nudge -from mx_bec.messages import ( - MXMeasurementSequenceMessage, - MXQueueChangedMessage, - MXTaskExecutionMessage, -) +from mx_bec.messages import MXMeasurementSequenceMessage from mx_bec.self_driving import ( CollectionRecord, GridGeometry, @@ -34,6 +24,7 @@ from mx_bec.self_driving import ( SweepRecord, scan_images, ) +from mx_bec.tasks.core import MxSequenceUpdate, RoleT, TaskManager, task if TYPE_CHECKING: from pxii_bec.macros.beamline_planner import StateChangePlanner @@ -42,31 +33,24 @@ if TYPE_CHECKING: logger = bec_logger.logger -P = ParamSpec("P") -R = TypeVar("R") - MAX_GRID_SCAN_S = 1200.0 # refuse grid scans expected to take longer than 20 min -MxSequenceUpdate = tuple[EndpointInfo, MXMeasurementSequenceMessage] | None +class MxTasks(TaskManager[RoleT]): + """The operations on mx beamlines which can be requested as tasks. Instantiate as + `MxTasks[Server](aare_bec)` in the AareBec service, where the tasks run, or as + `MxTasks[Client](bec_client)` anywhere else, to request them from the service. -class MxTasks: - """Holder for operations on mx beamlines. Probably needs to be reconsidered. TODO: - - categorise tasks, allow nesting with one lock + - categorise tasks - add doc info to decorator, including placeholder for args, to show to GUI """ - def __init__(self, client: AareBec): - self._client = client - self._busy_lock = RLock() - self._planner: StateChangePlanner | None = None + if TYPE_CHECKING: + # the tasks only run in the service + _client: AareBec # pyright: ignore[reportIncompatibleVariableOverride] - def _request_task(self, name: str, *args, **kwargs): - """Submit a task request to the AareBec service.""" - msg = MXTaskExecutionMessage(name=name, args=args, kwargs=kwargs) - logger.info(f"Requesting task: {msg}") - self._client.connector.xadd(QueueEndpoints.task_request(), {"data": msg}) + _planner: StateChangePlanner | None = None @property def planner(self) -> StateChangePlanner: @@ -79,47 +63,6 @@ class MxTasks: _, _, self._planner = init_beamline_environment() return self._planner - @classmethod - def is_task(cls, name: str) -> bool: - """Whether `name` can be requested as a task, i.e. is a method decorated with `task`.""" - return getattr(inspect.getattr_static(cls, name, None), "is_mx_task", False) - - @staticmethod - def task( - method: Callable[Concatenate[MxTasks, P], MxSequenceUpdate], - ) -> Callable[Concatenate[MxTasks, P], None]: - """Mark the decorated method as a task. It runs while holding `self._busy_lock`, so that - only one task runs at a time, and if it raises, the task queue is paused before the - exception propagates, so that queued tasks don't carry on from a failed state.""" - - # TODO: task becomes a callable class with methods to request, etc - - @functools.wraps(method) - def wrapper(self: MxTasks, *args, **kwargs): - # pylint: disable=protected-access - with self._busy_lock: - try: - state_update = method(self, *args, **kwargs) - except Exception as e: - self._pause_queue_after_failure(method.__name__, e) - raise - logger.info(f"Task: {method.__name__} completed.") - if state_update: - self._client.connector.set_and_publish(*state_update) - - wrapper.is_mx_task = True - return wrapper - - def _pause_queue_after_failure(self, task_name: str, e: Exception) -> None: - if (queue := getattr(self._client, "task_queue", None)) is None: - return - logger.warning(f"Task {task_name} failed: {e}.\n Pausing the task queue.") - try: - queue.pause() - except Exception: # pylint: disable=broad-except - # the task's own exception is the one to surface - logger.exception("Failed to pause the task queue") - @task def run_optical_centering_bec(self, sample_id: int): """Rotate the Aerotech to each angle from the config, update the optical centering @@ -416,71 +359,3 @@ class MxTasks: StateEndpoints.rotation_done(), MXMeasurementSequenceMessage(sample_id=dbid, success=True), ) - - -class MxTaskQueue: - """Executes requested tasks one at a time, in order, on a background thread. - - Tasks are popped from the left of the `QueueEndpoints.task_execution()` list and run on the - given `MxTasks`. The queue can be paused through the `QueueEndpoints.task_queue_paused()` - config value (from any client): no new task is popped while paused, but a task which is - already running is left to finish. - """ - - def __init__(self, client: AareBec, tasks: MxTasks, poll_interval_s: float = 0.5) -> None: - self._client = client - self._tasks = tasks - self._poll_interval_s = poll_interval_s - self._stop_event = Event() - self._paused: RedisConfigValue[bool] = RedisConfigValue( - connector=client.connector, endpoint=QueueEndpoints.task_queue_paused() - ) - self._thread = Thread(target=self._run, name="MxTaskQueue", daemon=True) - - @property - def paused(self) -> bool: - return self._paused.value - - def pause(self) -> None: - """Stop taking new tasks from the queue; the current task finishes.""" - self._paused.value = True - - def resume(self) -> None: - """Start taking tasks from the queue again.""" - self._paused.value = False - - def start(self) -> None: - self._thread.start() - - def shutdown(self) -> None: - """Stop the queue thread, waiting for a running task to finish, and drop the Redis - subscription of the paused flag.""" - self._stop_event.set() - if self._thread.is_alive(): - self._thread.join() - self._paused.unregister_all() - - def _run(self) -> None: - while not self._stop_event.is_set(): - if self._paused.value: - self._stop_event.wait(self._poll_interval_s) - continue - msg = self._client.connector.blocking_list_pop( - QueueEndpoints.task_execution(), side="LEFT", timeout_s=self._poll_interval_s - ) - if msg is not None: - self._client.connector.send( - QueueEndpoints.task_queue_changed(), MXQueueChangedMessage() - ) - self.execute(msg) - - def execute(self, msg: MXTaskExecutionMessage) -> None: - """Run a single task on `MxTasks`. Failures are logged and do not stop the queue.""" - if not MxTasks.is_task(msg.name): - logger.warning(f"Skipping queued task: {msg.name!r} is not a public MxTasks method") - return - logger.info(f"Running task {msg.name} with args={msg.args}, kwargs={msg.kwargs}") - try: - getattr(self._tasks, msg.name)(*msg.args, **msg.kwargs) - except Exception: # pylint: disable=broad-except - logger.exception(f"Task {msg.name} failed") diff --git a/tests/unit/test_aaredaq_tasks.py b/tests/unit/test_aaredaq_tasks.py index 025cccc..74c5b38 100644 --- a/tests/unit/test_aaredaq_tasks.py +++ b/tests/unit/test_aaredaq_tasks.py @@ -5,7 +5,7 @@ from aarecommon.math.coordinate import Coordinate from aarecommon.models.raster_grid import RasterGridRequest from aarecommon.models.rotation_scan import RotationScanRequest -from mx_bec.tasks import MxTasks +from mx_bec.tasks import MxTasks, Server @pytest.fixture @@ -15,7 +15,7 @@ def client(): @pytest.fixture def tasks(client): - return MxTasks(client) + return MxTasks[Server](client) @pytest.mark.parametrize( diff --git a/tests/unit/test_actors.py b/tests/unit/test_actors.py index 70e9730..23b7333 100644 --- a/tests/unit/test_actors.py +++ b/tests/unit/test_actors.py @@ -11,7 +11,7 @@ from mx_bec.actors.mx_automation import ( ) from mx_bec.endpoints import StateEndpoints from mx_bec.messages import MXMeasurementSequenceMessage -from mx_bec.service import MxTasks +from mx_bec.tasks import MxTasks, Server @pytest.fixture @@ -66,7 +66,7 @@ def test_unexpected_message_is_ignored(client): def test_actors_chain(client): """sample mounted -> optical centering -> xray centering: each actor consumes what the previous step publishes. Uses the real MxTasks with a mocked prediction and smargon.""" - client.tasks = MxTasks(client) + client.tasks = MxTasks[Server](client) client.aare_config.optical_centering.angles = [0.0] client.optical_prediction.get_target_point_offset_mm.return_value = (0.1, 0.2) first = OnSampleMountedRunOpticalCentering(client, name="a", exec_id="a") diff --git a/tests/unit/test_change_state_task.py b/tests/unit/test_change_state_task.py index c74de02..2f3a5ea 100644 --- a/tests/unit/test_change_state_task.py +++ b/tests/unit/test_change_state_task.py @@ -3,19 +3,19 @@ from unittest.mock import MagicMock, patch import pytest from pxii_bec.macros.beamline_planner import BeamlineState -from mx_bec.tasks import MxTasks +from mx_bec.tasks import MxTasks, Server @pytest.fixture def tasks(): - tasks = MxTasks(MagicMock()) + tasks = MxTasks[Server](MagicMock()) tasks._planner = MagicMock() return tasks def test_planner_is_built_lazily_from_the_beamline_environment(monkeypatch): monkeypatch.delenv("BEAMLINE", raising=False) - tasks = MxTasks(MagicMock()) # must not need the beamline environment yet + tasks = MxTasks[Server](MagicMock()) # must not need the beamline environment yet env, devices, planner = MagicMock(), MagicMock(), MagicMock() with patch( "pxii_bec.scripts.init_beamline.init_beamline_environment", diff --git a/tests/unit/test_grid_scan_task.py b/tests/unit/test_grid_scan_task.py index dbe27de..77fe441 100644 --- a/tests/unit/test_grid_scan_task.py +++ b/tests/unit/test_grid_scan_task.py @@ -4,7 +4,7 @@ from unittest.mock import MagicMock, call import pytest from mx_bec.jfjoch import RasterScan -from mx_bec.tasks import MAX_GRID_SCAN_S, MxTasks +from mx_bec.tasks import MAX_GRID_SCAN_S, MxTasks, Server GRID = dict(n_x=4, n_y=3, step_x_um=50.0, step_y_um=40.0, exp_time_s=0.1, file_prefix="grid") BEAMLINE = dict( @@ -42,7 +42,7 @@ def test_run_grid_scan_sequence(client): sequence.attach_mock(jfjoch, "jfjoch") sequence.attach_mock(aerotech.trigger, "trigger") - MxTasks(client).run_grid_scan(**GRID, **BEAMLINE) + MxTasks[Server](client).run_grid_scan(**GRID, **BEAMLINE) config.grid_elem_count_x.set.assert_called_once_with(4) config.grid_elem_count_y.set.assert_called_once_with(3) @@ -84,7 +84,7 @@ def test_run_grid_scan_refuses_invalid_parameters(client): config.valid.get.return_value = False config.message.get.return_value = "too many elements" with pytest.raises(ValueError, match="too many elements"): - MxTasks(client).run_grid_scan(**GRID, **BEAMLINE) + MxTasks[Server](client).run_grid_scan(**GRID, **BEAMLINE) client.jfjoch.measure_raster.assert_not_called() client.devices.aerotech.trigger.assert_not_called() @@ -92,7 +92,7 @@ def test_run_grid_scan_refuses_invalid_parameters(client): def test_run_grid_scan_refuses_too_long_scans(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"): - MxTasks(client).run_grid_scan(**too_long, **BEAMLINE) + MxTasks[Server](client).run_grid_scan(**too_long, **BEAMLINE) client.devices.aerotech.gridscan_config.grid_elem_count_x.set.assert_not_called() diff --git a/tests/unit/test_service.py b/tests/unit/test_service.py index ba2c6f0..4a65043 100644 --- a/tests/unit/test_service.py +++ b/tests/unit/test_service.py @@ -12,7 +12,8 @@ from mx_bec.messages import ( MXQueueChangedMessage, MXTaskExecutionMessage, ) -from mx_bec.service import AareBec, MxTasks +from mx_bec.service import AareBec +from mx_bec.tasks import MxTasks, RoleT, Server, task @pytest.fixture @@ -20,7 +21,10 @@ def service(monkeypatch): BECClient._reset_singleton() monkeypatch.setenv("CONFIG_REDIS_URL", "redis://dummy:6379") # the config client connects to the beamline redis on construction - with patch("mx_bec.service.AareConfigClient"): + # HAX: the service reads the sample spreadsheet straight from the beamline redis on + # construction (mx_bec/service.py lines 57-63), so that connection is patched out too. Remove + # this patch together with that hack. + with patch("mx_bec.service.AareConfigClient"), patch("mx_bec.service.Redis"): svc = AareBec(ServiceConfig(redis={"host": "dummy", "port": 6379}), ConnectorMock) yield svc BECClient._reset_singleton() @@ -110,7 +114,8 @@ NOT_TASKS = [ "_publish_optical_centering_done", # private method "_client", # private attribute "_busy_lock", - "task", # public, but the decorator rather than a task + "request", # public, but not a task + "execute", "is_task", "planner", # property ] @@ -129,8 +134,8 @@ def test_task_request_for_non_task_name_is_rejected(service, name): def test_tasks_are_exactly_the_decorated_methods(): - class Tasks(MxTasks): - @MxTasks.task + class Tasks(MxTasks[RoleT]): + @task def decorated(self): ... def plain(self): ... @@ -141,26 +146,26 @@ def test_tasks_are_exactly_the_decorated_methods(): assert all(not MxTasks.is_task(name) for name in NOT_TASKS) -class _FailingTasks(MxTasks): - @MxTasks.task +class _FailingTasks(MxTasks[RoleT]): + @task def boom(self): raise RuntimeError("boom") - @MxTasks.task + @task def fine(self): - return "ok" + return None def test_failed_task_pauses_the_queue_and_reraises(): client = MagicMock() with pytest.raises(RuntimeError, match="boom"): - _FailingTasks(client).boom() + _FailingTasks[Server](client).boom() client.task_queue.pause.assert_called_once() def test_successful_task_does_not_pause_the_queue(): client = MagicMock() - assert _FailingTasks(client).fine() == "ok" + assert _FailingTasks[Server](client).fine() is None client.task_queue.pause.assert_not_called() @@ -168,14 +173,14 @@ def test_failed_task_reraises_without_a_queue(): client = MagicMock() client.task_queue = None # the queue only exists once the service has started with pytest.raises(RuntimeError, match="boom"): - _FailingTasks(client).boom() + _FailingTasks[Server](client).boom() def test_failed_task_reraises_even_if_pausing_fails(): client = MagicMock() client.task_queue.pause.side_effect = ConnectionError("redis gone") with pytest.raises(RuntimeError, match="boom"): - _FailingTasks(client).boom() + _FailingTasks[Server](client).boom() @pytest.fixture @@ -201,7 +206,7 @@ def _optical_centering_done(sample_id: int, success: bool): def test_optical_centering_without_target_publishes_failure(mock_client): mock_client.optical_prediction.get_target_point_offset_mm.return_value = None - MxTasks(mock_client).run_optical_centering(sample_id=3) + MxTasks[Server](mock_client).run_optical_centering(sample_id=3) mock_client.devices.smargon.nudge_in_lab_frame.assert_not_called() assert _published(mock_client) == [_optical_centering_done(3, success=False)] @@ -210,7 +215,7 @@ def test_optical_centering_centres_at_each_angle_then_publishes_success(mock_cli smargon, aerotech = mock_client.devices.smargon, mock_client.devices.aerotech mock_client.optical_prediction.get_target_point_offset_mm.return_value = (0.1, -0.2) - MxTasks(mock_client).run_optical_centering(sample_id=3) + MxTasks[Server](mock_client).run_optical_centering(sample_id=3) assert [call.args for call in aerotech.u.set.call_args_list] == [(0.0,), (90.0,)] assert aerotech.u.set.return_value.wait.call_count == 2 @@ -224,7 +229,7 @@ def test_optical_centering_centres_at_each_angle_then_publishes_success(mock_cli def test_optical_centering_gives_up_when_a_later_angle_has_no_target(mock_client): mock_client.optical_prediction.get_target_point_offset_mm.side_effect = [(0.1, -0.2), None] - MxTasks(mock_client).run_optical_centering(sample_id=3) + MxTasks[Server](mock_client).run_optical_centering(sample_id=3) assert mock_client.devices.smargon.nudge_in_lab_frame.call_count == 1 assert _published(mock_client) == [_optical_centering_done(3, success=False)] @@ -235,5 +240,5 @@ def test_optical_centering_publishes_failure_when_move_fails(mock_client): move.wait.side_effect = TimeoutError("smargon did not reach target") with pytest.raises(TimeoutError): - MxTasks(mock_client).run_optical_centering(sample_id=3) + MxTasks[Server](mock_client).run_optical_centering(sample_id=3) assert _published(mock_client) == [_optical_centering_done(3, success=False)] diff --git a/tests/unit/test_tasks.py b/tests/unit/test_tasks.py index 34eab6a..5021f52 100644 --- a/tests/unit/test_tasks.py +++ b/tests/unit/test_tasks.py @@ -8,7 +8,7 @@ from bec_lib.redis_connector import RedisConnector from mx_bec.endpoints import QueueEndpoints from mx_bec.messages import MXQueueChangedMessage, MXTaskExecutionMessage -from mx_bec.tasks import MxTaskQueue, MxTasks +from mx_bec.tasks import MxTaskQueue, RoleT, Server, TaskManager, task @pytest.fixture @@ -26,14 +26,30 @@ def client(connector): return client +class _Tasks(TaskManager[RoleT]): + """Records the calls of its one task on `calls`.""" + + calls: MagicMock + + @task + def run_optical_centering(self, sample_id: int) -> None: + self.calls.run_optical_centering(sample_id) + + def _publish_optical_centering_done(self, sample_id: int) -> None: + self.calls._publish_optical_centering_done(sample_id) + + @pytest.fixture def tasks(): - return MagicMock(spec=MxTasks) + """The recorder of the calls made to the tasks.""" + return MagicMock() @pytest.fixture def queue(client, tasks): - q = MxTaskQueue(client, tasks, poll_interval_s=0.05) + manager = _Tasks[Server](client) + manager.calls = tasks + q = MxTaskQueue(client, manager, poll_interval_s=0.05) yield q q.shutdown() @@ -95,7 +111,7 @@ def test_paused_flag_is_shared_through_redis(connector, queue): # another client (here: a second config value on the same endpoint) can pause the queue other = MagicMock() other.connector = connector - other_queue = MxTaskQueue(other, MagicMock(spec=MxTasks)) + other_queue = MxTaskQueue(other, _Tasks[Server](other)) try: assert not queue.paused other_queue.pause() @@ -109,7 +125,7 @@ def test_paused_flag_is_shared_through_redis(connector, queue): def test_queue_skips_non_task_names(connector, queue, tasks): connector.rpush(QueueEndpoints.task_execution(), _request("_publish_optical_centering_done", 1)) connector.rpush(QueueEndpoints.task_execution(), _request("run_optical_centering", 2)) - with patch("mx_bec.tasks.logger") as logger: + with patch("mx_bec.tasks.core.logger") as logger: queue.start() _wait_for(lambda: tasks.run_optical_centering.call_count == 1) tasks.run_optical_centering.assert_called_once_with(2) @@ -121,7 +137,7 @@ def test_failed_task_is_logged_and_queue_continues(connector, queue, tasks): tasks.run_optical_centering.side_effect = [RuntimeError("boom"), None] connector.rpush(QueueEndpoints.task_execution(), _request("run_optical_centering", 1)) connector.rpush(QueueEndpoints.task_execution(), _request("run_optical_centering", 2)) - with patch("mx_bec.tasks.logger") as logger: + with patch("mx_bec.tasks.core.logger") as logger: queue.start() _wait_for(lambda: tasks.run_optical_centering.call_count == 2) logger.exception.assert_called_once() diff --git a/tests/unit/test_tasks_core.py b/tests/unit/test_tasks_core.py new file mode 100644 index 0000000..5789da4 --- /dev/null +++ b/tests/unit/test_tasks_core.py @@ -0,0 +1,198 @@ +from unittest.mock import MagicMock + +import pytest + +from mx_bec.endpoints import QueueEndpoints, StateEndpoints +from mx_bec.messages import ( + MXMeasurementSequenceMessage, + MXQueueChangedMessage, + MXTaskExecutionMessage, +) +from mx_bec.tasks.core import ( + BoundTask, + Client, + MxSequenceUpdate, + RoleT, + Server, + TaskManager, + UnknownTask, + task, +) + + +class Tasks(TaskManager[RoleT]): + """Shaped like MxTasks: tasks use `self._client` and may return a state update.""" + + @task + def mount(self, dbid: int, reference: bool = False) -> MxSequenceUpdate: + """Mount a sample""" + self._client.aaredaq.mount_sample(dbid, reference=reference) + return ( + StateEndpoints.sample_mounted(), + MXMeasurementSequenceMessage(sample_id=dbid, success=True), + ) + + @task + def quiet(self) -> None: + self._client.aaredaq.quiet() + + @task + def nested(self, dbid: int) -> None: + self.mount(dbid) + + @task + def boom(self) -> None: + raise RuntimeError("boom") + + def plain(self): ... + + def _private(self): ... + + +@pytest.fixture +def client(): + return MagicMock() + + +@pytest.fixture +def server(client): + return Tasks[Server](client) + + +@pytest.fixture +def remote(client): + return Tasks[Client](client) + + +def test_role_classes(server, remote): + assert Tasks[Server] is Tasks[Server] + assert isinstance(server, Tasks) and isinstance(server, Server) + assert isinstance(remote, Tasks) and isinstance(remote, Client) + assert type(server).__name__ == "Tasks[Server]" + with pytest.raises(TypeError, match=r"Tasks\[Server\]"): + Tasks(MagicMock()) + with pytest.raises(TypeError, match="already has a role"): + Tasks[Server][Client] + + +def test_tasks_are_exactly_the_decorated_methods(): + assert Tasks.task_names() == ["mount", "quiet", "nested", "boom"] + assert Tasks[Server].task_names() == Tasks.task_names() + assert Tasks.is_task("mount") + assert not any(Tasks.is_task(name) for name in ("plain", "_private", "request", "nope")) + + class MoreTasks(Tasks[RoleT]): + @task + def extra(self) -> None: ... + + assert MoreTasks.is_task("extra") and MoreTasks.is_task("mount") + assert not Tasks.is_task("extra") + + +def test_task_metadata(server): + assert Tasks.mount.__doc__ == "Mount a sample" + assert isinstance(server.mount, BoundTask) + assert server.mount.__name__ == "mount" + assert server.mount.__doc__ == "Mount a sample" + + +def test_server_call_runs_the_task_and_publishes_its_state_update(server, client): + assert server.mount(3, reference=True) is None + client.aaredaq.mount_sample.assert_called_once_with(3, reference=True) + endpoint, msg = client.connector.set_and_publish.call_args.args + assert endpoint.endpoint == StateEndpoints.sample_mounted().endpoint + assert msg == MXMeasurementSequenceMessage(sample_id=3, success=True) + client.task_queue.pause.assert_not_called() + + +def test_server_call_without_state_update_publishes_nothing(server, client): + server.quiet() + client.aaredaq.quiet.assert_called_once_with() + client.connector.set_and_publish.assert_not_called() + + +def test_server_task_can_call_another_task(server, client): + server.nested(5) # must not deadlock on the task lock + client.aaredaq.mount_sample.assert_called_once_with(5, reference=False) + client.connector.set_and_publish.assert_called_once() + + +def test_server_call_through_the_class(server, client): + Tasks.mount(server, 4) + client.aaredaq.mount_sample.assert_called_once_with(4, reference=False) + + +def test_failed_task_pauses_the_queue_and_reraises(server, client): + with pytest.raises(RuntimeError, match="boom"): + server.boom() + client.task_queue.pause.assert_called_once() + client.connector.set_and_publish.assert_not_called() + + +def test_failed_task_reraises_without_a_queue(server, client): + client.task_queue = None # the queue only exists once the service has started + with pytest.raises(RuntimeError, match="boom"): + server.boom() + + +def test_failed_task_reraises_even_if_pausing_fails(server, client): + client.task_queue.pause.side_effect = ConnectionError("redis gone") + with pytest.raises(RuntimeError, match="boom"): + server.boom() + + +def test_server_execute_runs_the_task_of_a_message(server, client): + server.execute(MXTaskExecutionMessage(name="mount", args=(7,), kwargs={"reference": True})) + client.aaredaq.mount_sample.assert_called_once_with(7, reference=True) + with pytest.raises(UnknownTask, match="plain"): + server.execute(MXTaskExecutionMessage(name="plain", args=(), kwargs={})) + + +@pytest.mark.parametrize( + "request_task", + [ + lambda tasks: tasks.mount.request(3, reference=True), + lambda tasks: tasks.request("mount", 3, reference=True), + lambda tasks: tasks.request(tasks.mount, 3, reference=True), + lambda tasks: tasks.request(Tasks.mount, 3, reference=True), + ], +) +def test_server_request_queues_the_task(server, client, request_task): + request_task(server) + client.aaredaq.mount_sample.assert_not_called() + endpoint, msg = client.connector.rpush.call_args.args + assert endpoint.endpoint == QueueEndpoints.task_execution().endpoint + assert msg == MXTaskExecutionMessage(name="mount", args=(3,), kwargs={"reference": True}) + endpoint, msg = client.connector.send.call_args.args + assert endpoint.endpoint == QueueEndpoints.task_queue_changed().endpoint + assert isinstance(msg, MXQueueChangedMessage) + + +def test_request_of_unknown_task_is_rejected(server, remote, client): + for tasks in (server, remote): + with pytest.raises(UnknownTask): + tasks.request("plain") + client.connector.rpush.assert_not_called() + client.connector.xadd.assert_not_called() + + +@pytest.mark.parametrize( + "call", + [ + lambda tasks: tasks.mount(3, reference=True), + lambda tasks: tasks.mount.request(3, reference=True), + lambda tasks: tasks.request("mount", 3, reference=True), + lambda tasks: tasks.execute( + MXTaskExecutionMessage(name="mount", args=(3,), kwargs={"reference": True}) + ), + ], +) +def test_client_sends_a_task_request(remote, client, call): + call(remote) + client.aaredaq.mount_sample.assert_not_called() + client.connector.rpush.assert_not_called() + endpoint, payload = client.connector.xadd.call_args.args + assert endpoint.endpoint == QueueEndpoints.task_request().endpoint + assert payload == { + "data": MXTaskExecutionMessage(name="mount", args=(3,), kwargs={"reference": True}) + }