1 parent
fdd96c545f
commit
bd445867ac
7 files changed
+151
-4
No files matched your search
@@ -0,0 +1,100 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from bec_lib.config_values import RedisConfigValue
|
||||
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 bec_widgets.widgets.utility.toggle.toggle import ToggleSwitch
|
||||
from qtpy.QtCore import Signal
|
||||
from qtpy.QtWidgets import QHBoxLayout, QLabel, QListWidget, QVBoxLayout, QWidget
|
||||
|
||||
from mx_bec.endpoints import TaskEndpoints
|
||||
|
||||
logger = bec_logger.logger
|
||||
|
||||
|
||||
class MxTaskQueueWidget(BECWidget, QWidget):
|
||||
"""
|
||||
Widget to pause/resume the MX task queue and show the tasks waiting in it.
|
||||
|
||||
The toggle is bound to the `task_queue_paused` flag in Redis (checked = running), the list
|
||||
is re-read from the task execution queue whenever the service announces a change on
|
||||
`task_queue_changed`.
|
||||
"""
|
||||
|
||||
PLUGIN = True
|
||||
ICON_NAME = "pending_actions"
|
||||
USER_ACCESS = ["refresh"]
|
||||
|
||||
# Redis callbacks arrive on the connector thread; re-emit so the toggle is updated on the GUI
|
||||
# thread.
|
||||
_paused_changed = Signal(bool)
|
||||
|
||||
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._paused: RedisConfigValue[bool] = RedisConfigValue(
|
||||
connector=self.client.connector,
|
||||
endpoint=TaskEndpoints.task_queue_paused(),
|
||||
wait_for_writes=False,
|
||||
)
|
||||
# RedisConfigValue keeps a weak ref to the subscriber, which must be a bound method
|
||||
self._paused.subscribe(self._emit_paused_changed)
|
||||
self._paused_changed.connect(self._on_paused_changed)
|
||||
|
||||
self._toggle = ToggleSwitch(parent=self, checked=not self._paused.value)
|
||||
self._toggle.stateChanged.connect(self._set_running)
|
||||
self._list = QListWidget(parent=self)
|
||||
|
||||
layout = QVBoxLayout(self)
|
||||
header = QHBoxLayout()
|
||||
header.addWidget(QLabel("Task queue running", parent=self))
|
||||
header.addWidget(self._toggle)
|
||||
header.addStretch()
|
||||
layout.addLayout(header)
|
||||
layout.addWidget(QLabel("Queued tasks", parent=self))
|
||||
layout.addWidget(self._list)
|
||||
|
||||
# released automatically by BECWidget.cleanup() (disconnect_owner)
|
||||
self.bec_dispatcher.connect_slot(self._on_queue_changed, TaskEndpoints.task_queue_changed())
|
||||
self.refresh()
|
||||
|
||||
@SafeSlot()
|
||||
def refresh(self):
|
||||
"""Reload the queued tasks from Redis."""
|
||||
tasks = self.client.connector.lrange(TaskEndpoints.task_execution(), 0, -1)
|
||||
self._list.clear()
|
||||
for msg in tasks:
|
||||
args = ", ".join(
|
||||
[repr(a) for a in msg.args] + [f"{k}={v!r}" for k, v in msg.kwargs.items()]
|
||||
)
|
||||
self._list.addItem(f"{msg.name}({args})")
|
||||
|
||||
@SafeSlot(dict, dict)
|
||||
def _on_queue_changed(self, _content: dict, _metadata: dict):
|
||||
self.refresh()
|
||||
|
||||
def _emit_paused_changed(self, paused: bool):
|
||||
self._paused_changed.emit(paused)
|
||||
|
||||
@SafeSlot(bool)
|
||||
def _set_running(self, running: bool):
|
||||
self._paused.value = not running
|
||||
|
||||
@SafeSlot(bool)
|
||||
def _on_paused_changed(self, paused: bool):
|
||||
# Don't write the value we just received straight back to Redis.
|
||||
self._toggle.blockSignals(True)
|
||||
self._toggle.setChecked(not paused)
|
||||
self._toggle.blockSignals(False)
|
||||
|
||||
def cleanup(self):
|
||||
self._paused.unregister_all()
|
||||
super().cleanup()
|
||||
@@ -4,6 +4,7 @@ from bec_lib.messages import AvailableResourceMessage, BoolConfigDefaultFalse
|
||||
from mx_bec.messages import (
|
||||
MXMeasurementSequenceMessage,
|
||||
MXTaskExecutionMessage,
|
||||
MXTaskQueueChangedMessage,
|
||||
OpticalPredictionMessage,
|
||||
)
|
||||
|
||||
@@ -91,6 +92,16 @@ class TaskEndpoints:
|
||||
message_op=MessageOp.LIST,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def task_queue_changed():
|
||||
"""Pub/sub channel on which the AareBec service announces changes to the execution
|
||||
queue, so that clients know to re-read it."""
|
||||
return EndpointInfo(
|
||||
endpoint=f"{EndpointType.USER.value}/mx/tasks/queue_changed",
|
||||
message_type=MXTaskQueueChangedMessage,
|
||||
message_op=MessageOp.SEND,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def task_queue_paused():
|
||||
"""Managed bool: whether the AareBec service should stop taking tasks from the execution
|
||||
|
||||
@@ -25,6 +25,13 @@ class MXTaskExecutionMessage(BECMessage):
|
||||
kwargs: dict[str, int | bool | str | float | None]
|
||||
|
||||
|
||||
class MXTaskQueueChangedMessage(BECMessage):
|
||||
"""Notification that the task execution queue changed; carries no data, subscribers
|
||||
re-read the queue."""
|
||||
|
||||
msg_type: ClassVar[str] = "mx_task_queue_changed_message"
|
||||
|
||||
|
||||
class OpticalPredictionMessage(BECMessage):
|
||||
"""The latest optical image analysis prediction"""
|
||||
|
||||
|
||||
@@ -11,6 +11,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.messages import MXTaskQueueChangedMessage
|
||||
from mx_bec.optical_centering import OpticalPrediction
|
||||
from mx_bec.tasks import MxTaskQueue, MxTasks
|
||||
|
||||
@@ -64,6 +65,7 @@ class AareBec(BECClient):
|
||||
return
|
||||
logger.info(f"Queueing task request: {msg}")
|
||||
self.connector.rpush(TaskEndpoints.task_execution(), msg)
|
||||
self.connector.send(TaskEndpoints.task_queue_changed(), MXTaskQueueChangedMessage())
|
||||
|
||||
@property
|
||||
def devices(self):
|
||||
|
||||
+4
-1
@@ -10,7 +10,7 @@ from bec_lib.logger import bec_logger
|
||||
|
||||
from mx_bec.devices.smargopolo_smargon import Smargon
|
||||
from mx_bec.endpoints import StateEndpoints, TaskEndpoints
|
||||
from mx_bec.messages import MXMeasurementSequenceMessage
|
||||
from mx_bec.messages import MXMeasurementSequenceMessage, MXTaskQueueChangedMessage
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from mx_bec.messages import MXTaskExecutionMessage
|
||||
@@ -128,6 +128,9 @@ class MxTaskQueue:
|
||||
TaskEndpoints.task_execution(), side="LEFT", timeout_s=self._poll_interval_s
|
||||
)
|
||||
if msg is not None:
|
||||
self._client.connector.send(
|
||||
TaskEndpoints.task_queue_changed(), MXTaskQueueChangedMessage()
|
||||
)
|
||||
self.execute(msg)
|
||||
|
||||
def execute(self, msg: MXTaskExecutionMessage) -> None:
|
||||
|
||||
@@ -7,7 +7,11 @@ from bec_lib.tests.utils import ConnectorMock
|
||||
|
||||
from mx_bec.constants import AareBecWorkflowState
|
||||
from mx_bec.endpoints import StateEndpoints, TaskEndpoints
|
||||
from mx_bec.messages import MXMeasurementSequenceMessage, MXTaskExecutionMessage
|
||||
from mx_bec.messages import (
|
||||
MXMeasurementSequenceMessage,
|
||||
MXTaskExecutionMessage,
|
||||
MXTaskQueueChangedMessage,
|
||||
)
|
||||
from mx_bec.service import AareBec, MxTasks
|
||||
|
||||
|
||||
@@ -91,11 +95,14 @@ def test_shutdown_before_start_does_not_touch_connector(service):
|
||||
base_shutdown.assert_called_once()
|
||||
|
||||
|
||||
def test_task_request_for_known_method_is_queued(service):
|
||||
def test_task_request_for_known_method_is_queued_and_announced(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)
|
||||
service.connector.send.assert_called_once_with(
|
||||
TaskEndpoints.task_queue_changed(), MXTaskQueueChangedMessage()
|
||||
)
|
||||
|
||||
|
||||
NOT_TASKS = [
|
||||
@@ -115,6 +122,7 @@ def test_task_request_for_non_task_name_is_rejected(service, name):
|
||||
with patch("mx_bec.service.logger") as logger:
|
||||
service._on_task_request({"data": msg})
|
||||
service.connector.rpush.assert_not_called()
|
||||
service.connector.send.assert_not_called()
|
||||
logger.warning.assert_called_once()
|
||||
assert name in logger.warning.call_args.args[0]
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ import pytest
|
||||
from bec_lib.redis_connector import RedisConnector
|
||||
|
||||
from mx_bec.endpoints import TaskEndpoints
|
||||
from mx_bec.messages import MXTaskExecutionMessage
|
||||
from mx_bec.messages import MXTaskExecutionMessage, MXTaskQueueChangedMessage
|
||||
from mx_bec.tasks import MxTaskQueue, MxTasks
|
||||
|
||||
|
||||
@@ -62,6 +62,22 @@ def test_queue_runs_tasks_in_order(connector, queue, tasks):
|
||||
assert connector.llen(TaskEndpoints.task_execution()) == 0
|
||||
|
||||
|
||||
def test_queue_announces_each_pop(connector, queue):
|
||||
notifications = []
|
||||
|
||||
def on_changed(msg): # the connector keeps a weak ref: must be a function, not list.append
|
||||
notifications.append(msg)
|
||||
|
||||
connector.register(TaskEndpoints.task_queue_changed(), cb=on_changed)
|
||||
for sample_id in (1, 2):
|
||||
connector.rpush(
|
||||
TaskEndpoints.task_execution(), _request("run_optical_centering", sample_id)
|
||||
)
|
||||
queue.start()
|
||||
_wait_for(lambda: len(notifications) == 2)
|
||||
assert all(n.value == MXTaskQueueChangedMessage() for n in notifications)
|
||||
|
||||
|
||||
def test_queue_does_not_pop_while_paused(connector, queue, tasks):
|
||||
queue.pause()
|
||||
connector.rpush(TaskEndpoints.task_execution(), _request("run_optical_centering", 1))
|
||||
|
||||
Reference in new issue
Block a user