Coverage for faststream/rabbit/publisher/usecase.py: 93%
62 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 collections.abc import Iterable
2from typing import TYPE_CHECKING, Any, Optional, Union
4from typing_extensions import Unpack, override
6from faststream._internal.endpoint.publisher import PublisherUsecase
7from faststream._internal.utils.data import filter_by_dict
8from faststream.rabbit.response import RabbitPublishCommand
9from faststream.rabbit.schemas import RabbitExchange, RabbitQueue
10from faststream.response.publish_type import PublishType
12from .options import BasicMessageOptions, PublishKwargs, PublishOptions
14if TYPE_CHECKING:
15 import aiormq
17 from faststream._internal.endpoint.publisher import PublisherSpecification
18 from faststream._internal.types import PublisherMiddleware
19 from faststream.rabbit.configs import RabbitBrokerConfig
20 from faststream.rabbit.message import RabbitMessage
21 from faststream.rabbit.types import AioPikaSendableMessage
22 from faststream.response.response import PublishCommand
24 from .config import RabbitPublisherConfig
27class RabbitPublisher(PublisherUsecase):
28 """A class to represent a RabbitMQ publisher."""
30 __slots__ = (
31 "_message_options",
32 "exchange",
33 "headers",
34 "publish_options",
35 "queue",
36 "reply_to",
37 "routing_key",
38 "timeout",
39 )
41 _outer_config: "RabbitBrokerConfig"
43 def __init__(
44 self,
45 config: "RabbitPublisherConfig",
46 specification: "PublisherSpecification[Any, Any]",
47 ) -> None:
48 super().__init__(config, specification)
50 self.queue = config.queue
51 self.routing_key = config.routing_address.template
53 self.exchange = config.exchange
55 self.headers = config.message_kwargs.pop("headers") or {}
56 self.reply_to = config.message_kwargs.pop("reply_to", None) or ""
57 self.timeout = config.message_kwargs.pop("timeout", None)
59 message_options, _ = filter_by_dict(
60 BasicMessageOptions,
61 dict(config.message_kwargs),
62 )
63 self._message_options = message_options
65 publish_options, _ = filter_by_dict(PublishOptions, dict(config.message_kwargs))
66 self.publish_options = publish_options
68 @property
69 def message_options(self) -> "BasicMessageOptions":
70 if self._outer_config.app_id and "app_id" not in self._message_options: 70 ↛ 75line 70 didn't jump to line 75 because the condition on line 70 was always true
71 message_options = self._message_options.copy()
72 message_options["app_id"] = self._outer_config.app_id
73 return message_options
75 return self._message_options
77 def routing(
78 self,
79 *,
80 queue: Union["RabbitQueue", str, None] = None,
81 routing_key: str = "",
82 ) -> str:
83 if not routing_key:
84 if q := RabbitQueue.validate(queue):
85 routing_key = q.routing()
86 else:
87 r = self.routing_key or self.queue.routing()
88 routing_key = f"{self._outer_config.prefix}{r}"
90 return routing_key
92 async def start(self) -> None:
93 if self.exchange is not None: 93 ↛ 95line 93 didn't jump to line 95 because the condition on line 93 was always true
94 await self._outer_config.declarer.declare_exchange(self.exchange)
95 return await super().start()
97 @override
98 async def publish(
99 self,
100 message: "AioPikaSendableMessage",
101 queue: Union["RabbitQueue", str, None] = None,
102 exchange: Union["RabbitExchange", str, None] = None,
103 *,
104 routing_key: str = "",
105 **publish_kwargs: "Unpack[PublishKwargs]",
106 ) -> Optional["aiormq.abc.ConfirmationFrameType"]:
107 if "headers" in publish_kwargs:
108 headers = self.headers | (publish_kwargs.pop("headers") or {})
109 else:
110 headers = self.headers
112 correlation_id = (
113 publish_kwargs.pop("correlation_id", None)
114 or self._outer_config.id_generator()
115 )
117 cmd = RabbitPublishCommand(
118 message,
119 routing_key=self.routing(queue=queue, routing_key=routing_key),
120 exchange=RabbitExchange.validate(exchange or self.exchange),
121 headers=headers,
122 correlation_id=correlation_id,
123 _publish_type=PublishType.PUBLISH,
124 **(self.publish_options | self.message_options | publish_kwargs), # type: ignore[operator]
125 )
127 frame: aiormq.abc.ConfirmationFrameType | None = await self._basic_publish(
128 cmd,
129 producer=self._outer_config.producer,
130 _extra_middlewares=(),
131 )
132 return frame
134 @override
135 async def _publish(
136 self,
137 cmd: Union["RabbitPublishCommand", "PublishCommand"],
138 *,
139 _extra_middlewares: Iterable["PublisherMiddleware"],
140 ) -> None:
141 """This method should be called in subscriber flow only."""
142 cmd = RabbitPublishCommand.from_cmd(cmd)
144 cmd.exchange = RabbitExchange.validate(cmd._exchange or self.exchange)
146 cmd.destination = self.routing()
147 cmd.reply_to = cmd.reply_to or self.reply_to
148 cmd.add_headers(self.headers, override=False)
150 cmd.timeout = cmd.timeout or self.timeout
152 cmd.message_options = {**self.message_options, **cmd.message_options}
153 cmd.publish_options = {**self.publish_options, **cmd.publish_options}
155 await self._basic_publish(
156 cmd,
157 producer=self._outer_config.producer,
158 _extra_middlewares=_extra_middlewares,
159 )
161 @override
162 async def request(
163 self,
164 message: "AioPikaSendableMessage",
165 queue: Union["RabbitQueue", str, None] = None,
166 exchange: Union["RabbitExchange", str, None] = None,
167 *,
168 routing_key: str = "",
169 **publish_kwargs: "Unpack[PublishKwargs]",
170 ) -> "RabbitMessage":
171 if "headers" in publish_kwargs: 171 ↛ 172line 171 didn't jump to line 172 because the condition on line 171 was never true
172 headers = self.headers | (publish_kwargs.pop("headers") or {})
173 else:
174 headers = self.headers
176 correlation_id = (
177 publish_kwargs.pop("correlation_id", None)
178 or self._outer_config.id_generator()
179 )
181 cmd = RabbitPublishCommand(
182 message,
183 routing_key=self.routing(queue=queue, routing_key=routing_key),
184 exchange=RabbitExchange.validate(exchange or self.exchange),
185 correlation_id=correlation_id,
186 headers=headers,
187 _publish_type=PublishType.PUBLISH,
188 **(self.publish_options | self.message_options | publish_kwargs), # type: ignore[operator]
189 )
191 msg: RabbitMessage = await self._basic_request(
192 cmd,
193 producer=self._outer_config.producer,
194 )
195 return msg