|
| 1 | +from collections.abc import Iterable |
| 2 | +from typing import TYPE_CHECKING, Any, Optional |
| 3 | + |
| 4 | +import aiomqtt |
| 5 | +import anyio |
| 6 | +from fast_depends import dependency_provider |
| 7 | +from typing_extensions import override |
| 8 | + |
| 9 | +from faststream._internal.basic_types import SendableMessage |
| 10 | +from faststream._internal.broker import BrokerUsecase |
| 11 | +from faststream._internal.constants import EMPTY |
| 12 | +from faststream._internal.context.repository import ContextRepo |
| 13 | +from faststream._internal.di import FastDependsConfig |
| 14 | +from faststream.mqtt.broker.registrator import MQTTRegistrator |
| 15 | +from faststream.mqtt.configs.broker import MQTTBrokerConfig |
| 16 | +from faststream.mqtt.response import MQTTPublishCommand |
| 17 | +from faststream.response import PublishType |
| 18 | +from faststream.security import BaseSecurity |
| 19 | +from faststream.specification.schema import BrokerSpec, Tag, TagDict |
| 20 | + |
| 21 | +if TYPE_CHECKING: |
| 22 | + from types import TracebackType |
| 23 | + |
| 24 | + from fast_depends import Provider |
| 25 | + from fast_depends.library.serializer import SerializerProto |
| 26 | + |
| 27 | + |
| 28 | +class MQTTBroker( |
| 29 | + MQTTRegistrator, |
| 30 | + BrokerUsecase[aiomqtt.Message, aiomqtt.Client], |
| 31 | +): |
| 32 | + def __init__( |
| 33 | + self, |
| 34 | + *, |
| 35 | + # mqtt broker params |
| 36 | + hostname: str = "localhost", |
| 37 | + port: int = 1883, |
| 38 | + username: str | None = None, |
| 39 | + password: str | None = None, |
| 40 | + keepalive: int = 60, |
| 41 | + bind_address: str = "", |
| 42 | + bind_port: int = 0, |
| 43 | + routers: Iterable[MQTTRegistrator] = (), |
| 44 | + # FastDepends args |
| 45 | + apply_types: bool = True, |
| 46 | + serializer: Optional["SerializerProto"] = EMPTY, |
| 47 | + provider: Optional["Provider"] = None, |
| 48 | + context: Optional["ContextRepo"] = None, |
| 49 | + # AsyncAPI args |
| 50 | + security: Optional["BaseSecurity"] = None, |
| 51 | + specification_url: str | None = None, |
| 52 | + protocol: str | None = None, |
| 53 | + protocol_version: str | None = "auto", |
| 54 | + description: str | None = None, |
| 55 | + tags: Iterable["Tag | TagDict"] = (), |
| 56 | + ) -> None: |
| 57 | + if specification_url is None: |
| 58 | + specification_url = hostname |
| 59 | + super().__init__( |
| 60 | + config=MQTTBrokerConfig( |
| 61 | + hostname="localhost", |
| 62 | + port=port, |
| 63 | + username=username, |
| 64 | + password=password, |
| 65 | + keepalive=keepalive, |
| 66 | + bind_address=bind_address, |
| 67 | + bind_port=bind_port, |
| 68 | + extra_context={ |
| 69 | + "broker": self, |
| 70 | + }, |
| 71 | + fd_config=FastDependsConfig( |
| 72 | + use_fastdepends=apply_types, |
| 73 | + serializer=serializer, |
| 74 | + provider=provider or dependency_provider, |
| 75 | + context=context or ContextRepo(), |
| 76 | + ), |
| 77 | + ), |
| 78 | + specification=BrokerSpec( |
| 79 | + url=[specification_url], |
| 80 | + protocol=None, |
| 81 | + protocol_version=None, |
| 82 | + description="MQTT Broker", |
| 83 | + tags=[], |
| 84 | + security=None, |
| 85 | + ), |
| 86 | + routers=routers, |
| 87 | + ) |
| 88 | + |
| 89 | + @override |
| 90 | + async def _connect(self) -> aiomqtt.Client: |
| 91 | + return await self.config.broker_config.connect() |
| 92 | + |
| 93 | + async def start(self) -> None: |
| 94 | + await self.connect() |
| 95 | + await super().start() |
| 96 | + |
| 97 | + async def stop( |
| 98 | + self, |
| 99 | + exc_type: type[BaseException] | None = None, |
| 100 | + exc_val: BaseException | None = None, |
| 101 | + exc_tb: Optional["TracebackType"] = None, |
| 102 | + ) -> None: |
| 103 | + await super().stop(exc_type, exc_val, exc_tb) |
| 104 | + await self.config.broker_config.disconnect(exc_type, exc_val, exc_tb) |
| 105 | + self._connection = None |
| 106 | + |
| 107 | + async def publish(self, message: "SendableMessage", topic: str) -> Any: |
| 108 | + cmd = MQTTPublishCommand( |
| 109 | + body=message, |
| 110 | + destination=topic, |
| 111 | + _publish_type=PublishType.PUBLISH, |
| 112 | + ) |
| 113 | + return await super()._basic_publish( |
| 114 | + cmd, producer=self.config.broker_config.producer |
| 115 | + ) |
| 116 | + |
| 117 | + async def ping(self, timeout: float | None) -> bool: |
| 118 | + sleep_time = (timeout or 10) / 10 |
| 119 | + ping_client = self.config.broker_config.create_client() |
| 120 | + |
| 121 | + with anyio.move_on_after(timeout) as cancel_scope: |
| 122 | + while True: |
| 123 | + if cancel_scope.cancel_called: |
| 124 | + return False |
| 125 | + try: |
| 126 | + async with ping_client: |
| 127 | + pass |
| 128 | + except aiomqtt.MqttError: |
| 129 | + await anyio.sleep(sleep_time) |
| 130 | + else: |
| 131 | + return True |
| 132 | + return False |
0 commit comments