remotivelabs.topology.namespaces.monitor

  1import asyncio
  2import logging
  3import uuid
  4from types import MappingProxyType
  5from typing import AsyncIterator, Awaitable, Callable
  6
  7from remotivelabs.broker import BrokerClient, Frame, FrameSubscription, NamespaceName, OnChangeMode
  8
  9from remotivelabs.topology.metrics import Metric, Metrics, Tags, get_metrics
 10
 11_logger = logging.getLogger(__name__)
 12
 13
 14class SubscriptionMonitor:
 15    """
 16    Manages active callback subscriptions for a namespace.
 17
 18    Each subscription runs in its own task, subscribing to filtered frames
 19    and invoking the registered callback. Subscriptions are identified by
 20    unique IDs and can be cancelled individually.
 21    """
 22
 23    def __init__(self, broker_client: BrokerClient, namespace: NamespaceName, metrics: Metrics | None = None):
 24        self._broker_client = broker_client
 25        self._namespace = namespace
 26        self._subscriptions: dict[str, asyncio.Task] = {}
 27        # Initialized lazily when a running event loop is available.
 28        self._subscriptions_changed: asyncio.Future | None = None
 29        self._metrics: Metrics = metrics if metrics is not None else get_metrics()
 30        self._ns_tag: Tags = MappingProxyType({"namespace": namespace})
 31
 32    @property
 33    def tasks(self) -> list[asyncio.Task]:
 34        """
 35        Return all active subscription tasks.
 36
 37        Note: the returned list is a snapshot and may not reflect future changes.
 38        """
 39        return list(self._subscriptions.values())
 40
 41    async def subscribe(  # noqa: PLR0913
 42        self,
 43        subscriptions: list[FrameSubscription],
 44        callback: Callable[[Frame], Awaitable[None]],
 45        block: bool = True,
 46        on_change: OnChangeMode = OnChangeMode.OFF,
 47        decode_named_values: bool = True,
 48        callback_label: str | None = None,
 49    ) -> str:
 50        """
 51        Create a new subscription with the given frame subscriptions and callback.
 52
 53        Args:
 54            subscriptions: Frame subscriptions to subscribe to
 55            callback: Async function to invoke for each matching frame
 56            block: If True, block until subscription is established with broker before receiving messages
 57            on_change: Controls whether every frame is delivered or only frames with changed signals
 58            decode_named_values: If True, named signal values are decoded to strings by the broker
 59            callback_label: Label used in the `callback` tag of `handler.duration` metrics. Defaults
 60                to the callback's `__name__` (or its class name).
 61
 62        Returns:
 63            Subscription ID that can be used to unsubscribe
 64        """
 65        sub_id = str(uuid.uuid4())
 66        ready: asyncio.Future[None] = asyncio.get_running_loop().create_future()
 67
 68        label = callback_label or getattr(callback, "__name__", None) or type(callback).__name__
 69        cb_tag: Tags = MappingProxyType({"namespace": self._namespace, "callback": label})
 70
 71        task = asyncio.create_task(
 72            self._subscription_task(
 73                subscriptions,
 74                callback,
 75                ready,
 76                cb_tag,
 77                block=block,
 78                on_change=on_change,
 79                decode_named_values=decode_named_values,
 80            ),
 81            name=f"subscription-{self._namespace}-{sub_id}",
 82        )
 83        self._subscriptions[sub_id] = task
 84
 85        if self._subscriptions_changed is not None and not self._subscriptions_changed.done():
 86            self._subscriptions_changed.set_result(None)
 87
 88        if block:
 89            await ready  # propagates any exception raised during broker-side setup
 90
 91        _logger.debug(f"Created subscription {sub_id} on namespace '{self._namespace}'")
 92        return sub_id
 93
 94    async def unsubscribe(self, subscription_id: str) -> None:
 95        """
 96        Cancel and remove a subscription by ID.
 97
 98        Exceptions from the subscription task are swallowed here so teardown stays reliable;
 99        they are already logged by `_subscription_task` and surfaced through `run_forever`.
100
101        Args:
102            subscription_id: The ID returned from subscribe()
103        """
104        task = self._subscriptions.pop(subscription_id, None)
105        if task is None:
106            return
107
108        if not task.done():
109            task.cancel()
110        try:
111            await task
112        except asyncio.CancelledError:
113            pass  # expected if we cancelled
114        except Exception:
115            pass  # already logged by the subscription task
116
117        if self._subscriptions_changed is not None and not self._subscriptions_changed.done():
118            self._subscriptions_changed.set_result(None)
119
120        _logger.debug(f"Unsubscribed {subscription_id} from namespace '{self._namespace}'")
121
122    async def close(self) -> None:
123        """Cancel all active subscriptions."""
124        for sub_id in list(self._subscriptions.keys()):
125            await self.unsubscribe(sub_id)
126
127    async def run_forever(self, interval: float = 1.0) -> None:
128        """
129        Monitor all subscription tasks indefinitely.
130
131        Continuously monitors the dynamic set of subscription tasks. When any task
132        completes, checks for exceptions (non-cancellation) and propagates them.
133
134        Raises:
135            Exception: Any exception from a completed subscription task
136            CancelledError: During shutdown
137        """
138        try:
139            while True:
140                # Prune completed tasks; surface any exception they ended with.
141                for sub_id, task in list(self._subscriptions.items()):
142                    if task.done():
143                        del self._subscriptions[sub_id]
144                        task.result()  # raises if the task ended with an exception
145
146                tasks = self.tasks
147
148                # Lazily create (or refresh) the change-signal future.
149                if self._subscriptions_changed is None or self._subscriptions_changed.done():
150                    self._subscriptions_changed = asyncio.get_running_loop().create_future()
151                changed = self._subscriptions_changed
152
153                await asyncio.wait(
154                    tasks + [changed],
155                    return_when=asyncio.FIRST_COMPLETED,
156                    timeout=interval,
157                )
158
159        except asyncio.CancelledError:
160            _logger.debug(f"Subscription monitor for namespace '{self._namespace}' stopped")
161            raise
162
163    async def _subscription_task(  # noqa: PLR0913
164        self,
165        subscriptions: list[FrameSubscription],
166        callback: Callable[[Frame], Awaitable[None]],
167        ready: asyncio.Future[None],
168        cb_tag: Tags,
169        block: bool = True,
170        on_change: OnChangeMode = OnChangeMode.OFF,
171        decode_named_values: bool = True,
172    ) -> None:
173        try:
174            stream: AsyncIterator[Frame] = await self._broker_client.subscribe_frames(
175                (self._namespace, subscriptions),
176                on_change=on_change,
177                initial_empty=block,
178                decode_named_values=decode_named_values,
179            )
180            ready.set_result(None)
181
182            async for frame in stream:
183                self._metrics.increment(Metric.FRAMES_RECEIVED, self._ns_tag)
184                with self._metrics.timed(Metric.HANDLER_DURATION, cb_tag):
185                    await callback(frame)
186
187        except asyncio.CancelledError:
188            if not ready.done():
189                ready.cancel()
190            _logger.debug(f"Subscription loop cancelled on namespace '{self._namespace}'")
191            raise
192        except Exception as e:
193            if not ready.done():
194                ready.set_exception(e)
195            _logger.exception(f"Subscription loop failed on namespace '{self._namespace}'")
196            raise
class SubscriptionMonitor:
 15class SubscriptionMonitor:
 16    """
 17    Manages active callback subscriptions for a namespace.
 18
 19    Each subscription runs in its own task, subscribing to filtered frames
 20    and invoking the registered callback. Subscriptions are identified by
 21    unique IDs and can be cancelled individually.
 22    """
 23
 24    def __init__(self, broker_client: BrokerClient, namespace: NamespaceName, metrics: Metrics | None = None):
 25        self._broker_client = broker_client
 26        self._namespace = namespace
 27        self._subscriptions: dict[str, asyncio.Task] = {}
 28        # Initialized lazily when a running event loop is available.
 29        self._subscriptions_changed: asyncio.Future | None = None
 30        self._metrics: Metrics = metrics if metrics is not None else get_metrics()
 31        self._ns_tag: Tags = MappingProxyType({"namespace": namespace})
 32
 33    @property
 34    def tasks(self) -> list[asyncio.Task]:
 35        """
 36        Return all active subscription tasks.
 37
 38        Note: the returned list is a snapshot and may not reflect future changes.
 39        """
 40        return list(self._subscriptions.values())
 41
 42    async def subscribe(  # noqa: PLR0913
 43        self,
 44        subscriptions: list[FrameSubscription],
 45        callback: Callable[[Frame], Awaitable[None]],
 46        block: bool = True,
 47        on_change: OnChangeMode = OnChangeMode.OFF,
 48        decode_named_values: bool = True,
 49        callback_label: str | None = None,
 50    ) -> str:
 51        """
 52        Create a new subscription with the given frame subscriptions and callback.
 53
 54        Args:
 55            subscriptions: Frame subscriptions to subscribe to
 56            callback: Async function to invoke for each matching frame
 57            block: If True, block until subscription is established with broker before receiving messages
 58            on_change: Controls whether every frame is delivered or only frames with changed signals
 59            decode_named_values: If True, named signal values are decoded to strings by the broker
 60            callback_label: Label used in the `callback` tag of `handler.duration` metrics. Defaults
 61                to the callback's `__name__` (or its class name).
 62
 63        Returns:
 64            Subscription ID that can be used to unsubscribe
 65        """
 66        sub_id = str(uuid.uuid4())
 67        ready: asyncio.Future[None] = asyncio.get_running_loop().create_future()
 68
 69        label = callback_label or getattr(callback, "__name__", None) or type(callback).__name__
 70        cb_tag: Tags = MappingProxyType({"namespace": self._namespace, "callback": label})
 71
 72        task = asyncio.create_task(
 73            self._subscription_task(
 74                subscriptions,
 75                callback,
 76                ready,
 77                cb_tag,
 78                block=block,
 79                on_change=on_change,
 80                decode_named_values=decode_named_values,
 81            ),
 82            name=f"subscription-{self._namespace}-{sub_id}",
 83        )
 84        self._subscriptions[sub_id] = task
 85
 86        if self._subscriptions_changed is not None and not self._subscriptions_changed.done():
 87            self._subscriptions_changed.set_result(None)
 88
 89        if block:
 90            await ready  # propagates any exception raised during broker-side setup
 91
 92        _logger.debug(f"Created subscription {sub_id} on namespace '{self._namespace}'")
 93        return sub_id
 94
 95    async def unsubscribe(self, subscription_id: str) -> None:
 96        """
 97        Cancel and remove a subscription by ID.
 98
 99        Exceptions from the subscription task are swallowed here so teardown stays reliable;
100        they are already logged by `_subscription_task` and surfaced through `run_forever`.
101
102        Args:
103            subscription_id: The ID returned from subscribe()
104        """
105        task = self._subscriptions.pop(subscription_id, None)
106        if task is None:
107            return
108
109        if not task.done():
110            task.cancel()
111        try:
112            await task
113        except asyncio.CancelledError:
114            pass  # expected if we cancelled
115        except Exception:
116            pass  # already logged by the subscription task
117
118        if self._subscriptions_changed is not None and not self._subscriptions_changed.done():
119            self._subscriptions_changed.set_result(None)
120
121        _logger.debug(f"Unsubscribed {subscription_id} from namespace '{self._namespace}'")
122
123    async def close(self) -> None:
124        """Cancel all active subscriptions."""
125        for sub_id in list(self._subscriptions.keys()):
126            await self.unsubscribe(sub_id)
127
128    async def run_forever(self, interval: float = 1.0) -> None:
129        """
130        Monitor all subscription tasks indefinitely.
131
132        Continuously monitors the dynamic set of subscription tasks. When any task
133        completes, checks for exceptions (non-cancellation) and propagates them.
134
135        Raises:
136            Exception: Any exception from a completed subscription task
137            CancelledError: During shutdown
138        """
139        try:
140            while True:
141                # Prune completed tasks; surface any exception they ended with.
142                for sub_id, task in list(self._subscriptions.items()):
143                    if task.done():
144                        del self._subscriptions[sub_id]
145                        task.result()  # raises if the task ended with an exception
146
147                tasks = self.tasks
148
149                # Lazily create (or refresh) the change-signal future.
150                if self._subscriptions_changed is None or self._subscriptions_changed.done():
151                    self._subscriptions_changed = asyncio.get_running_loop().create_future()
152                changed = self._subscriptions_changed
153
154                await asyncio.wait(
155                    tasks + [changed],
156                    return_when=asyncio.FIRST_COMPLETED,
157                    timeout=interval,
158                )
159
160        except asyncio.CancelledError:
161            _logger.debug(f"Subscription monitor for namespace '{self._namespace}' stopped")
162            raise
163
164    async def _subscription_task(  # noqa: PLR0913
165        self,
166        subscriptions: list[FrameSubscription],
167        callback: Callable[[Frame], Awaitable[None]],
168        ready: asyncio.Future[None],
169        cb_tag: Tags,
170        block: bool = True,
171        on_change: OnChangeMode = OnChangeMode.OFF,
172        decode_named_values: bool = True,
173    ) -> None:
174        try:
175            stream: AsyncIterator[Frame] = await self._broker_client.subscribe_frames(
176                (self._namespace, subscriptions),
177                on_change=on_change,
178                initial_empty=block,
179                decode_named_values=decode_named_values,
180            )
181            ready.set_result(None)
182
183            async for frame in stream:
184                self._metrics.increment(Metric.FRAMES_RECEIVED, self._ns_tag)
185                with self._metrics.timed(Metric.HANDLER_DURATION, cb_tag):
186                    await callback(frame)
187
188        except asyncio.CancelledError:
189            if not ready.done():
190                ready.cancel()
191            _logger.debug(f"Subscription loop cancelled on namespace '{self._namespace}'")
192            raise
193        except Exception as e:
194            if not ready.done():
195                ready.set_exception(e)
196            _logger.exception(f"Subscription loop failed on namespace '{self._namespace}'")
197            raise

Manages active callback subscriptions for a namespace.

Each subscription runs in its own task, subscribing to filtered frames and invoking the registered callback. Subscriptions are identified by unique IDs and can be cancelled individually.

SubscriptionMonitor( broker_client: remotivelabs.broker.client.BrokerClient, namespace: str, metrics: remotivelabs.topology.metrics.Metrics | None = None)
24    def __init__(self, broker_client: BrokerClient, namespace: NamespaceName, metrics: Metrics | None = None):
25        self._broker_client = broker_client
26        self._namespace = namespace
27        self._subscriptions: dict[str, asyncio.Task] = {}
28        # Initialized lazily when a running event loop is available.
29        self._subscriptions_changed: asyncio.Future | None = None
30        self._metrics: Metrics = metrics if metrics is not None else get_metrics()
31        self._ns_tag: Tags = MappingProxyType({"namespace": namespace})
tasks: list[_asyncio.Task]
33    @property
34    def tasks(self) -> list[asyncio.Task]:
35        """
36        Return all active subscription tasks.
37
38        Note: the returned list is a snapshot and may not reflect future changes.
39        """
40        return list(self._subscriptions.values())

Return all active subscription tasks.

Note: the returned list is a snapshot and may not reflect future changes.

async def subscribe( self, subscriptions: list[remotivelabs.broker.frame.FrameSubscription], callback: Callable[[remotivelabs.broker.frame.Frame], Awaitable[NoneType]], block: bool = True, on_change: remotivelabs.broker.client.OnChangeMode = <OnChangeMode.OFF: 'off'>, decode_named_values: bool = True, callback_label: str | None = None) -> str:
42    async def subscribe(  # noqa: PLR0913
43        self,
44        subscriptions: list[FrameSubscription],
45        callback: Callable[[Frame], Awaitable[None]],
46        block: bool = True,
47        on_change: OnChangeMode = OnChangeMode.OFF,
48        decode_named_values: bool = True,
49        callback_label: str | None = None,
50    ) -> str:
51        """
52        Create a new subscription with the given frame subscriptions and callback.
53
54        Args:
55            subscriptions: Frame subscriptions to subscribe to
56            callback: Async function to invoke for each matching frame
57            block: If True, block until subscription is established with broker before receiving messages
58            on_change: Controls whether every frame is delivered or only frames with changed signals
59            decode_named_values: If True, named signal values are decoded to strings by the broker
60            callback_label: Label used in the `callback` tag of `handler.duration` metrics. Defaults
61                to the callback's `__name__` (or its class name).
62
63        Returns:
64            Subscription ID that can be used to unsubscribe
65        """
66        sub_id = str(uuid.uuid4())
67        ready: asyncio.Future[None] = asyncio.get_running_loop().create_future()
68
69        label = callback_label or getattr(callback, "__name__", None) or type(callback).__name__
70        cb_tag: Tags = MappingProxyType({"namespace": self._namespace, "callback": label})
71
72        task = asyncio.create_task(
73            self._subscription_task(
74                subscriptions,
75                callback,
76                ready,
77                cb_tag,
78                block=block,
79                on_change=on_change,
80                decode_named_values=decode_named_values,
81            ),
82            name=f"subscription-{self._namespace}-{sub_id}",
83        )
84        self._subscriptions[sub_id] = task
85
86        if self._subscriptions_changed is not None and not self._subscriptions_changed.done():
87            self._subscriptions_changed.set_result(None)
88
89        if block:
90            await ready  # propagates any exception raised during broker-side setup
91
92        _logger.debug(f"Created subscription {sub_id} on namespace '{self._namespace}'")
93        return sub_id

Create a new subscription with the given frame subscriptions and callback.

Arguments:
  • subscriptions: Frame subscriptions to subscribe to
  • callback: Async function to invoke for each matching frame
  • block: If True, block until subscription is established with broker before receiving messages
  • on_change: Controls whether every frame is delivered or only frames with changed signals
  • decode_named_values: If True, named signal values are decoded to strings by the broker
  • callback_label: Label used in the callback tag of handler.duration metrics. Defaults to the callback's __name__ (or its class name).
Returns:

Subscription ID that can be used to unsubscribe

async def unsubscribe(self, subscription_id: str) -> None:
 95    async def unsubscribe(self, subscription_id: str) -> None:
 96        """
 97        Cancel and remove a subscription by ID.
 98
 99        Exceptions from the subscription task are swallowed here so teardown stays reliable;
100        they are already logged by `_subscription_task` and surfaced through `run_forever`.
101
102        Args:
103            subscription_id: The ID returned from subscribe()
104        """
105        task = self._subscriptions.pop(subscription_id, None)
106        if task is None:
107            return
108
109        if not task.done():
110            task.cancel()
111        try:
112            await task
113        except asyncio.CancelledError:
114            pass  # expected if we cancelled
115        except Exception:
116            pass  # already logged by the subscription task
117
118        if self._subscriptions_changed is not None and not self._subscriptions_changed.done():
119            self._subscriptions_changed.set_result(None)
120
121        _logger.debug(f"Unsubscribed {subscription_id} from namespace '{self._namespace}'")

Cancel and remove a subscription by ID.

Exceptions from the subscription task are swallowed here so teardown stays reliable; they are already logged by _subscription_task and surfaced through run_forever.

Arguments:
  • subscription_id: The ID returned from subscribe()
async def close(self) -> None:
123    async def close(self) -> None:
124        """Cancel all active subscriptions."""
125        for sub_id in list(self._subscriptions.keys()):
126            await self.unsubscribe(sub_id)

Cancel all active subscriptions.

async def run_forever(self, interval: float = 1.0) -> None:
128    async def run_forever(self, interval: float = 1.0) -> None:
129        """
130        Monitor all subscription tasks indefinitely.
131
132        Continuously monitors the dynamic set of subscription tasks. When any task
133        completes, checks for exceptions (non-cancellation) and propagates them.
134
135        Raises:
136            Exception: Any exception from a completed subscription task
137            CancelledError: During shutdown
138        """
139        try:
140            while True:
141                # Prune completed tasks; surface any exception they ended with.
142                for sub_id, task in list(self._subscriptions.items()):
143                    if task.done():
144                        del self._subscriptions[sub_id]
145                        task.result()  # raises if the task ended with an exception
146
147                tasks = self.tasks
148
149                # Lazily create (or refresh) the change-signal future.
150                if self._subscriptions_changed is None or self._subscriptions_changed.done():
151                    self._subscriptions_changed = asyncio.get_running_loop().create_future()
152                changed = self._subscriptions_changed
153
154                await asyncio.wait(
155                    tasks + [changed],
156                    return_when=asyncio.FIRST_COMPLETED,
157                    timeout=interval,
158                )
159
160        except asyncio.CancelledError:
161            _logger.debug(f"Subscription monitor for namespace '{self._namespace}' stopped")
162            raise

Monitor all subscription tasks indefinitely.

Continuously monitors the dynamic set of subscription tasks. When any task completes, checks for exceptions (non-cancellation) and propagates them.

Raises:
  • Exception: Any exception from a completed subscription task
  • CancelledError: During shutdown