"""The control-mesh communicator: the Rust ZeroMQ transport vendored in
``rust/`` (``mstar_rust.ZmqCommunicator``) behind ``BaseCommunicator``. The
codec is a :class:`Codec` (typed msgpack by default, so an edge can
terminate in a Rust process); ``register_event_for_poll`` forwards the eventfd to
the Rust poller; a readiness poll buffers any consumed message so nothing is
dropped or reordered. Build: ``maturin develop --release`` in ``rust/``
(see ``docs/installation.rst``)."""
from __future__ import annotations
import logging
import os
import time
from collections import deque
try:
from mstar_rust import ZmqCommunicator as _RustZmq
except ModuleNotFoundError:
# Only RustZMQCommunicator needs the extension; the codecs above it are
# pure Python and are imported by suites that never build rust/ (the
# CPU-only CI job). Failing here would break collection for all of them.
_RustZmq = None
from mstar.communication.codec import ( # noqa: F401 (re-exported)
Codec,
MsgpackCodec,
WireCodec,
decode_each,
default_codec,
)
from mstar.communication.communicator import BaseCommunicator, CommProtocol
from mstar.communication.event import EventWakeup
logger = logging.getLogger(__name__)
#: Slice bound for indefinite blocking waits. Events (message / wakeup) end a
#: slice immediately, so this is not a latency knob — it bounds how long one
#: FFI poll can hold the thread, keeping Python signal handling and the
#: ``timeout_s`` deadline check responsive. Matches ``wait_for_work``'s tick.
BLOCKING_POLL_SLICE_MS = 50
[docs]
class RustZMQCommunicator(BaseCommunicator):
"""``BaseCommunicator`` over the Rust transport."""
def __init__(
self,
my_id: str,
push_ids: list[str],
protocol: CommProtocol = CommProtocol.IPC,
ipc_socket_path_prefix: str = "/tmp/mstar/",
codec: type[Codec] | None = None,
):
if _RustZmq is None:
raise RuntimeError(
"RustZMQCommunicator needs the mstar_rust extension; build it "
"with `maturin develop --release` in rust/ "
"(see docs/installation.rst)"
)
transport = os.getenv("MSTAR_ZMQ_TRANSPORT", protocol.value).upper()
self.protocol = CommProtocol(transport)
self.my_id = my_id
self.ipc_socket_path_prefix = ipc_socket_path_prefix
self.codec = codec or default_codec()
self.event: EventWakeup | None = None
# Messages consumed by a readiness poll, awaiting get_all_new_messages.
self._buffered: deque = deque()
if self.protocol == CommProtocol.IPC:
os.makedirs(ipc_socket_path_prefix, exist_ok=True)
self._lock_deployment(my_id)
self._inner = _RustZmq(my_id, ipc_socket_path_prefix)
elif self.protocol == CommProtocol.TCP:
self._inner = _RustZmq.bind_endpoint(my_id, self._endpoint(my_id))
# TCP has no directory scheme: register every peer explicitly
# (lazily extended in send() for peers not known up front).
self._registered: set[str] = set()
for peer in push_ids:
if peer != my_id:
self._register(peer)
else:
raise NotImplementedError(f"Protocol {protocol} not yet supported yet")
# endpoint scheme: `_endpoint` / `_tcp_port` come from BaseCommunicator.
def _register(self, entity_id: str) -> None:
if entity_id not in self._registered:
self._inner.register_peer(entity_id, self._endpoint(entity_id))
self._registered.add(entity_id)
# -- the wrapped surface -------------------------------------------------
[docs]
def register_event_for_poll(self, event: EventWakeup) -> None:
self._inner.register_wakeup_fd(event.fd)
self.event = event
def _poll_once(self, timeout_ms: int) -> str:
"""One wake-aware poll; returns ``"msg"`` / ``"wake"`` / ``"timeout"``.
A consumed message goes to the buffer; a wakeup drains the event."""
kind, payload = self._inner.recv_or_wake(timeout_ms)
if kind == "msg":
self._buffered.append(payload)
elif kind == "wake" and self.event is not None:
self.event.drain()
return kind
[docs]
def wait_for_work(self, timeout_ms: int = 50) -> None:
if self._buffered:
return # work is already waiting
self._poll_once(timeout_ms)
[docs]
def poll_for_messages(self, timeout_ms: int = 20) -> bool:
"""Block until a message is readable, a registered wakeup event
fires, or ``timeout_ms`` elapses — whichever comes first. True when
a message is available (buffered here, delivered by
``get_all_new_messages``); a wakeup ends the poll early with False
(the event is drained, exactly as in ``wait_for_work``)."""
if self._buffered:
return True
self._poll_once(timeout_ms)
return bool(self._buffered)
[docs]
def send(self, entity_id: str, msg) -> None:
# no str(): the repr is ~10us on an InputSignals and DEBUG is off here
logger.debug("%s to send a message %s to entity %s", self.my_id, msg, entity_id)
if self.protocol == CommProtocol.TCP:
self._register(entity_id)
self._inner.send(entity_id, self.codec.encode(msg))
[docs]
def try_send_bytes(self, entity_id: str, data: bytes) -> bool:
if self.protocol == CommProtocol.TCP:
self._register(entity_id)
return self._inner.try_send(entity_id, data)
[docs]
def get_all_new_messages(
self, blocking: bool = False, timeout_s: float | None = None,
) -> list:
if blocking and not self._buffered:
# Wait until a message is readable before draining. A
# registered wakeup event also ends the wait, so a completed
# compute future can interrupt a blocking receive. `timeout_s` bounds the wait
# (None = wait indefinitely); on expiry, drain whatever is there.
deadline = None if timeout_s is None else (
time.monotonic() + timeout_s)
while self._poll_once(BLOCKING_POLL_SLICE_MS) == "timeout":
if deadline is not None and time.monotonic() >= deadline:
break
messages = decode_each(self.codec, self._buffered, self.my_id)
self._buffered.clear()
# One FFI call for the whole queued batch (vs try_recv per message).
messages.extend(decode_each(self.codec, self._inner.drain(), self.my_id))
return messages