|
| 1 | +from contextlib import suppress |
| 2 | +from multiprocessing import Event, Process, Queue |
| 3 | +from queue import Empty |
| 4 | +from typing import Callable |
| 5 | + |
| 6 | +from google.protobuf.message import Message |
| 7 | +from informaticsmatters.protobuf.datamanager.pod_message_pb2 import PodMessage |
| 8 | +from informaticsmatters.protobuf.datamanager.workflow_message_pb2 import WorkflowMessage |
| 9 | + |
| 10 | + |
| 11 | +class UnitTestMessageQueue(Process): |
| 12 | + """A simple asynchronous message passer, used by the Validator |
| 13 | + (and UnitTestInstanceLauncher) to send ProtocolBuffer messages to the Engine.""" |
| 14 | + |
| 15 | + def __init__(self, receiver: Callable[[Message], None]): |
| 16 | + super().__init__() |
| 17 | + self._stop = Event() |
| 18 | + self._queue = Queue() |
| 19 | + self._receiver = receiver |
| 20 | + |
| 21 | + def run(self): |
| 22 | + while not self._stop.is_set(): |
| 23 | + with suppress(Empty): |
| 24 | + if item := self._queue.get(True, 0.25): |
| 25 | + msg = None |
| 26 | + # We only support Workflow and Pod messages |
| 27 | + # during testing... |
| 28 | + if item["class"] == "WorkflowMessage": |
| 29 | + msg = WorkflowMessage() |
| 30 | + msg.ParseFromString(item["bytes"]) |
| 31 | + elif item["class"] == "PodMessage": |
| 32 | + msg = PodMessage() |
| 33 | + msg.ParseFromString(item["bytes"]) |
| 34 | + assert msg |
| 35 | + self._receiver(msg) |
| 36 | + |
| 37 | + def put(self, msg: Message): |
| 38 | + """Puts a protocol buffer message onto the queue.""" |
| 39 | + self._queue.put({"class": type(msg).__name__, "bytes": msg.SerializeToString()}) |
| 40 | + |
| 41 | + def stop(self): |
| 42 | + """A request to stop the process.""" |
| 43 | + self._stop.set() |
0 commit comments