Coverage for faststream/mqtt/broker/broker.py: 92%
43 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 21:20 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 21:20 +0000
1import logging
2from collections.abc import Awaitable, Callable, Iterable, Sequence
3from typing import (
4 TYPE_CHECKING,
5 Any,
6 Optional,
7)
8from urllib.parse import urlsplit
10import zmqtt
11from fast_depends import Provider, dependency_provider
12from typing_extensions import assert_never, override
14from faststream._internal.broker import BrokerUsecase
15from faststream._internal.constants import EMPTY
16from faststream._internal.context.repository import ContextRepo
17from faststream._internal.di import FastDependsConfig
18from faststream._internal.types import IdGenerator
19from faststream.message import gen_cor_id
20from faststream.middlewares import AckPolicy
21from faststream.mqtt.broker.config import MQTTBrokerConfig
22from faststream.mqtt.parser import MQTTVersion
23from faststream.mqtt.publisher.producer import (
24 ZmqttBaseProducer,
25 ZmqttProducerV5,
26 ZmqttProducerV311,
27)
28from faststream.mqtt.response import MQTTPublishCommand
29from faststream.mqtt.security import parse_security
30from faststream.mqtt.subscriber.usecase import MQTTBaseSubscriber
31from faststream.mqtt.utils import build_mqtt_url, parse_mqtt_url
32from faststream.response.publish_type import PublishType
33from faststream.specification.schema import BrokerSpec
35from .logging import make_mqtt_logger_state
36from .registrator import MQTTRegistrator
38if TYPE_CHECKING:
39 from types import TracebackType
41 from fast_depends.dependencies import Dependant
42 from fast_depends.library.serializer import SerializerProto
44 from faststream._internal.basic_types import LoggerProto, SendableMessage
45 from faststream._internal.configs import UnderlyingDriverAnnotations
46 from faststream._internal.parser import CodecProto
47 from faststream._internal.types import BrokerMiddleware, CustomCallable
48 from faststream.mqtt.message import MQTTMessage
49 from faststream.security import BaseSecurity
50 from faststream.specification.schema.extra import Tag, TagDict
53class MQTTBroker(
54 MQTTRegistrator,
55 BrokerUsecase[zmqtt.Message, zmqtt.MQTTClient, MQTTBrokerConfig],
56):
57 """MQTT broker for FastStream using the zmqtt client library."""
59 def __init__(
60 self,
61 url: str = "mqtt://localhost:1883",
62 port: int = EMPTY,
63 *,
64 host: str = EMPTY,
65 client_id: str = "",
66 keepalive: int = 60,
67 clean_session: bool = True,
68 will: zmqtt.Will | None = None,
69 version: MQTTVersion = "5.0",
70 reconnect: zmqtt.ReconnectConfig | None = None,
71 on_connection_recovery_failed: Callable[[], Awaitable[None]] | None = None,
72 mqtt_connect_timeout: float = 30.0,
73 session_expiry_interval: int = 0,
74 receive_maximum: int | None = None,
75 maximum_packet_size: int | None = None,
76 user_properties: Sequence[tuple[str, str]] = (),
77 request_response_information: bool | None = None,
78 request_problem_information: bool | None = None,
79 session_replay_buffer_size: int = 1000,
80 session_replay_timeout: float = 30.0,
81 stripped_prefixes: tuple[str, ...] | None = None,
82 graceful_timeout: float | None = 15.0,
83 decoder: Optional["CustomCallable"] = None,
84 parser: Optional["CustomCallable"] = None,
85 codec: Optional["CodecProto"] = None,
86 dependencies: Sequence["Dependant"] = (),
87 middlewares: Sequence["BrokerMiddleware[Any, Any]"] = (),
88 routers: Iterable[MQTTRegistrator] = (),
89 ack_policy: AckPolicy = EMPTY,
90 id_generator: IdGenerator = gen_cor_id,
91 # AsyncAPI args
92 specification_url: str | None = None,
93 protocol: str | None = None,
94 protocol_version: str | None = None,
95 description: str | None = None,
96 tags: Iterable["Tag | TagDict"] = (),
97 security: Optional["BaseSecurity"] = None,
98 # logging args
99 logger: Optional["LoggerProto"] = EMPTY,
100 log_level: int = logging.INFO,
101 # FastDepends args
102 apply_types: bool = True,
103 serializer: Optional["SerializerProto"] = EMPTY,
104 provider: Optional["Provider"] = None,
105 context: Optional["ContextRepo"] = None,
106 underlying_driver_annotations: "UnderlyingDriverAnnotations | None" = None,
107 ) -> None:
108 url_options = parse_mqtt_url(url)
109 secure_kwargs = parse_security(security)
111 connection_host = url_options.host
112 connection_port = url_options.port
114 if host is not EMPTY:
115 host_options = parse_mqtt_url(host)
116 connection_host = host_options.host
117 if port is EMPTY and host_options.port_provided:
118 connection_port = host_options.port
120 if port is not EMPTY:
121 connection_port = port
123 security_tls = secure_kwargs.pop("tls", None)
124 connection_tls = security_tls or url_options.tls
125 username = secure_kwargs.pop("username", url_options.username)
126 password = secure_kwargs.pop("password", url_options.password)
128 connection_kwargs = {
129 "host": connection_host,
130 "port": connection_port,
131 "username": username,
132 "password": password,
133 "tls": connection_tls,
134 "will": will,
135 "receive_maximum": receive_maximum,
136 "maximum_packet_size": maximum_packet_size,
137 "user_properties": user_properties,
138 "request_response_information": request_response_information,
139 "request_problem_information": request_problem_information,
140 }
141 if stripped_prefixes is not None:
142 connection_kwargs["stripped_prefixes"] = stripped_prefixes
144 producer: ZmqttBaseProducer
145 if version == "3.1.1":
146 producer = ZmqttProducerV311(
147 parser=parser, decoder=decoder, id_generator=id_generator
148 )
149 elif version == "5.0":
150 producer = ZmqttProducerV5(
151 parser=parser, decoder=decoder, id_generator=id_generator
152 )
153 else:
154 assert_never(version)
156 connection_url = build_mqtt_url(
157 host=connection_host,
158 port=connection_port,
159 tls=bool(connection_tls),
160 )
162 if specification_url is None:
163 specification_url = connection_url
165 specification_protocol = (
166 urlsplit(specification_url).scheme
167 if "://" in specification_url
168 else connection_url.split(":", 1)[0]
169 )
171 super().__init__(
172 client_id=client_id,
173 keepalive=keepalive,
174 clean_session=clean_session,
175 version=version,
176 reconnect=reconnect,
177 on_connection_recovery_failed=on_connection_recovery_failed,
178 mqtt_connect_timeout=mqtt_connect_timeout,
179 session_expiry_interval=session_expiry_interval,
180 session_replay_buffer_size=session_replay_buffer_size,
181 session_replay_timeout=session_replay_timeout,
182 **connection_kwargs,
183 **secure_kwargs,
184 # broker config
185 routers=routers,
186 config=MQTTBrokerConfig(
187 version=version,
188 producer=producer,
189 broker_middlewares=middlewares,
190 broker_parser=parser,
191 broker_decoder=decoder,
192 broker_codec=codec,
193 logger=make_mqtt_logger_state(
194 logger=logger,
195 log_level=log_level,
196 ),
197 fd_config=FastDependsConfig(
198 use_fastdepends=apply_types,
199 serializer=serializer,
200 provider=provider or dependency_provider,
201 context=context or ContextRepo(),
202 ),
203 broker_dependencies=dependencies,
204 graceful_timeout=graceful_timeout,
205 ack_policy=ack_policy,
206 id_generator=id_generator,
207 extra_context={
208 "broker": self,
209 },
210 underlying_driver_annotations=underlying_driver_annotations or {},
211 ),
212 specification=BrokerSpec(
213 description=description,
214 url=[specification_url],
215 protocol=protocol or specification_protocol,
216 protocol_version=protocol_version or version,
217 tags=tags,
218 security=security,
219 ),
220 )
222 @property
223 def connection_info(self) -> zmqtt.ConnectionInfo:
224 """Current handshake snapshot; raises MQTTDisconnectedError when disconnected."""
225 if self._connection is None:
226 msg = "No active connection information"
227 raise zmqtt.MQTTDisconnectedError(msg)
228 return self._connection.connection_info
230 @override
231 async def _connect(self) -> zmqtt.MQTTClient:
232 client = zmqtt.MQTTClient(**self._connection_kwargs)
233 await client.connect()
234 self.config.connect(client)
235 return client
237 @override
238 async def start(self) -> None:
239 await self.connect()
240 c = MQTTBaseSubscriber.build_log_context(None, "")
241 self.config.logger.log("Connection established", logging.INFO, c)
242 await super().start()
244 @override
245 async def stop(
246 self,
247 exc_type: type[BaseException] | None = None,
248 exc_val: BaseException | None = None,
249 exc_tb: Optional["TracebackType"] = None,
250 ) -> None:
251 await super().stop(exc_type, exc_val, exc_tb)
253 if self._connection is not None:
254 await self._connection.disconnect()
255 self._connection = None
257 self.config.disconnect()
259 @override
260 async def ping(self, timeout: float | None = None) -> bool:
261 if self._connection is None: 261 ↛ 262line 261 didn't jump to line 262 because the condition on line 261 was never true
262 return False
263 try:
264 await self._connection.ping(timeout=timeout or 5.0)
265 except Exception:
266 return False
267 else:
268 return True
270 @override
271 async def publish(
272 self,
273 message: "SendableMessage" = None,
274 topic: str = "",
275 *,
276 qos: zmqtt.QoS = zmqtt.QoS.AT_MOST_ONCE,
277 retain: bool = False,
278 headers: dict[str, str] | None = None,
279 correlation_id: str | None = None,
280 reply_to: str = "",
281 ) -> None:
282 """Publish a message to an MQTT topic.
284 Args:
285 message: Message body to send.
286 topic: MQTT topic to publish to.
287 qos: QoS level (0, 1, or 2).
288 retain: Whether the broker should retain the message.
289 headers: Message headers (MQTT 5.0 user properties).
290 correlation_id: Correlation ID for message tracing.
291 reply_to: Response topic (MQTT 5.0 response_topic property).
292 """
293 cmd = MQTTPublishCommand(
294 message,
295 topic=topic,
296 qos=qos,
297 retain=retain,
298 headers=headers,
299 correlation_id=correlation_id or self.config.id_generator(),
300 reply_to=reply_to,
301 _publish_type=PublishType.PUBLISH,
302 )
304 await self._basic_publish(cmd, producer=self.config.producer)
306 @override
307 async def request(
308 self,
309 message: "SendableMessage" = None,
310 topic: str = "",
311 /,
312 timeout: float = 0.5,
313 correlation_id: str | None = None,
314 headers: dict[str, str] | None = None,
315 qos: zmqtt.QoS = zmqtt.QoS.AT_MOST_ONCE,
316 reply_to: str = "",
317 ) -> "MQTTMessage":
318 cmd = MQTTPublishCommand(
319 message,
320 topic=topic,
321 correlation_id=correlation_id or self.config.id_generator(),
322 headers=headers,
323 qos=qos,
324 reply_to=reply_to,
325 timeout=timeout,
326 _publish_type=PublishType.REQUEST,
327 )
328 msg: MQTTMessage = await self._basic_request(cmd, producer=self.config.producer)
329 return msg