Coverage for faststream/mqtt/parser.py: 92%
49 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
1from contextlib import suppress
2from re import Pattern
3from typing import TYPE_CHECKING, Any, Literal
5import zmqtt
6from typing_extensions import assert_never, override
8from faststream._internal._compat import json_loads
9from faststream.message import StreamMessage, decode_message
11from .message import MQTTMessage
13if TYPE_CHECKING:
14 from faststream._internal.basic_types import DecodedMessage
17MQTTVersion = Literal["3.1.1", "5.0"]
18"""The protocol versions FastStream speaks."""
21class MQTTBaseParser:
22 """Base parser for MQTT messages — shared parse + decode logic."""
24 __slots__ = ("_path_regex",)
26 def __init__(
27 self,
28 path_regex: Pattern[str] | None = None,
29 ) -> None:
30 self._path_regex = path_regex
32 def _extract_path(self, topic: str) -> dict[str, Any]:
33 if self._path_regex is None:
34 return {}
35 match = self._path_regex.match(topic)
36 if match is None: 36 ↛ 37line 36 didn't jump to line 37 because the condition on line 36 was never true
37 return {}
38 return match.groupdict()
40 async def parse_message(self, msg: zmqtt.Message) -> MQTTMessage:
41 raise NotImplementedError
43 async def decode_message(self, msg: "StreamMessage[Any]") -> "DecodedMessage": # ruff: ignore[no-self-use]
44 return decode_message(msg)
47class MQTTParserV311(MQTTBaseParser):
48 """Parser for MQTT 3.1.1 messages — raw payload, no metadata."""
50 __slots__ = ()
52 async def parse_message(self, msg: zmqtt.Message) -> MQTTMessage:
53 return MQTTMessage(
54 raw_message=msg,
55 body=msg.payload,
56 headers={},
57 path=self._extract_path(msg.topic),
58 content_type=None,
59 reply_to="",
60 correlation_id=None,
61 )
63 @override
64 async def decode_message(self, msg: "StreamMessage[Any]") -> "DecodedMessage":
65 body: bytes = msg.body
66 with suppress(Exception):
67 m: DecodedMessage = json_loads(body)
68 return m
69 with suppress(UnicodeDecodeError):
70 return body.decode()
71 return body
74class MQTTParserV5(MQTTBaseParser):
75 """Parser for MQTT 5.0 messages.
77 Extracts content_type, response_topic, correlation_data, and
78 user_properties from PUBLISH properties when available.
79 """
81 __slots__ = ()
83 async def parse_message(self, msg: zmqtt.Message) -> MQTTMessage:
84 props = msg.properties
85 content_type: str | None = None
86 reply_to: str = ""
87 correlation_id: str | None = None
88 headers: dict[str, Any] = {}
90 if props is not None: 90 ↛ 97line 90 didn't jump to line 97 because the condition on line 90 was always true
91 content_type = props.content_type
92 reply_to = props.response_topic or ""
93 if props.correlation_data is not None: 93 ↛ 95line 93 didn't jump to line 95 because the condition on line 93 was always true
94 correlation_id = props.correlation_data.decode(errors="replace")
95 headers.update(props.user_properties)
97 return MQTTMessage(
98 raw_message=msg,
99 body=msg.payload,
100 headers=headers,
101 path=self._extract_path(msg.topic),
102 content_type=content_type,
103 reply_to=reply_to,
104 correlation_id=correlation_id,
105 )
108def parser_for(version: MQTTVersion) -> type[MQTTBaseParser]:
109 """The parser class a Broker version speaks.
111 One place says it, because the Subscriber that consumes through a parser and
112 the in-memory test broker that encodes for one have to agree on the version.
113 """
114 if version == "3.1.1":
115 return MQTTParserV311
116 if version == "5.0":
117 return MQTTParserV5
118 assert_never(version)