|
| 1 | +# Copyright 2025-2026 Dimensional Inc. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +from __future__ import annotations |
| 16 | + |
| 17 | +from collections.abc import Callable |
| 18 | +from dataclasses import dataclass |
| 19 | +import threading |
| 20 | +from typing import TYPE_CHECKING, Any, TypeAlias |
| 21 | + |
| 22 | +from dimos.protocol.pubsub.spec import PubSub |
| 23 | +from dimos.protocol.service.zenohservice import ZenohService |
| 24 | +from dimos.utils.logging_config import setup_logger |
| 25 | + |
| 26 | +if TYPE_CHECKING: |
| 27 | + import zenoh |
| 28 | + |
| 29 | +logger = setup_logger() |
| 30 | + |
| 31 | + |
| 32 | +@dataclass(frozen=True) |
| 33 | +class Topic: |
| 34 | + """Represents a Zenoh topic (key expression).""" |
| 35 | + |
| 36 | + name: str |
| 37 | + |
| 38 | + def __str__(self) -> str: |
| 39 | + return self.name |
| 40 | + |
| 41 | + |
| 42 | +MessageCallback: TypeAlias = Callable[[Any, Topic], None] |
| 43 | + |
| 44 | + |
| 45 | +class ZenohPubSub(ZenohService, PubSub[Topic, Any]): |
| 46 | + def __init__(self, **kwargs: Any) -> None: |
| 47 | + super().__init__(**kwargs) |
| 48 | + self._publishers: dict[Topic, zenoh.Publisher] = {} |
| 49 | + self._publisher_lock = threading.Lock() |
| 50 | + self._subscribers: list[zenoh.Subscriber] = [] |
| 51 | + self._subscriber_lock = threading.Lock() |
| 52 | + |
| 53 | + def _get_publisher(self, topic: Topic) -> zenoh.Publisher: |
| 54 | + """Get or create a Publisher for the given topic.""" |
| 55 | + with self._publisher_lock: |
| 56 | + if topic not in self._publishers: |
| 57 | + self._publishers[topic] = self.session.declare_publisher(topic.name) |
| 58 | + return self._publishers[topic] |
| 59 | + |
| 60 | + def publish(self, topic: Topic, message: bytes | str) -> None: |
| 61 | + """Publish a message to a Zenoh topic.""" |
| 62 | + publisher = self._get_publisher(topic) |
| 63 | + try: |
| 64 | + publisher.put(message) |
| 65 | + except Exception as e: |
| 66 | + logger.error(f"Error publishing to topic {topic}: {e}", exc_info=True) |
| 67 | + |
| 68 | + def subscribe(self, topic: Topic, callback: MessageCallback) -> Callable[[], None]: |
| 69 | + """Subscribe to a Zenoh topic with a callback. |
| 70 | +
|
| 71 | + Each call declares its own Zenoh subscriber (Zenoh spawns a |
| 72 | + background thread per callback handler). Unsubscribe undeclares it. |
| 73 | + """ |
| 74 | + |
| 75 | + def on_sample(sample: zenoh.Sample) -> None: |
| 76 | + callback(sample.payload.to_bytes(), topic) |
| 77 | + |
| 78 | + sub = self.session.declare_subscriber(topic.name, on_sample) |
| 79 | + with self._subscriber_lock: |
| 80 | + self._subscribers.append(sub) |
| 81 | + |
| 82 | + def unsubscribe() -> None: |
| 83 | + sub.undeclare() |
| 84 | + with self._subscriber_lock: |
| 85 | + try: |
| 86 | + self._subscribers.remove(sub) |
| 87 | + except ValueError: |
| 88 | + pass |
| 89 | + |
| 90 | + return unsubscribe |
| 91 | + |
| 92 | + def stop(self) -> None: |
| 93 | + """Stop the Zenoh pub/sub and clean up resources.""" |
| 94 | + with self._subscriber_lock: |
| 95 | + for subscriber in self._subscribers: |
| 96 | + subscriber.undeclare() |
| 97 | + self._subscribers.clear() |
| 98 | + with self._publisher_lock: |
| 99 | + for publisher in self._publishers.values(): |
| 100 | + publisher.undeclare() |
| 101 | + self._publishers.clear() |
| 102 | + super().stop() |
| 103 | + |
| 104 | + |
| 105 | +__all__ = [ |
| 106 | + "MessageCallback", |
| 107 | + "Topic", |
| 108 | + "ZenohPubSub", |
| 109 | +] |
0 commit comments