Coverage for faststream/nats/publisher/usecase.py: 86%
41 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, cast
4from typing_extensions import overload, override
6from faststream._internal.endpoint.publisher import PublisherUsecase
7from faststream._internal.utils.path import Address
8from faststream.nats.response import NatsPublishCommand
9from faststream.nats.schemas.js_stream import NATS_ADDRESS_SYNTAX
10from faststream.response.publish_type import PublishType
12if TYPE_CHECKING:
13 from faststream._internal.basic_types import SendableMessage
14 from faststream._internal.endpoint.publisher import PublisherSpecification
15 from faststream._internal.producer import ProducerProto
16 from faststream._internal.types import PublisherMiddleware
17 from faststream.nats.configs import NatsBrokerConfig
18 from faststream.nats.message import NatsMessage
19 from faststream.nats.schemas import PubAck
20 from faststream.response.response import PublishCommand
22 from .config import NatsPublisherConfig
25class LogicPublisher(PublisherUsecase):
26 """A class to represent a NATS publisher."""
28 __slots__ = (
29 "_subject",
30 "headers",
31 "reply_to",
32 "stream",
33 "timeout",
34 )
36 _outer_config: "NatsBrokerConfig"
38 def __init__(
39 self,
40 config: "NatsPublisherConfig",
41 specification: "PublisherSpecification[Any, Any]",
42 ) -> None:
43 """Initialize NATS publisher object."""
44 super().__init__(config, specification)
46 self._subject = config.subject
47 self.stream = config.stream
48 self.timeout = config.timeout or 0.5
49 self.headers = config.headers or {}
50 self.reply_to = config.reply_to
52 @property
53 def subject(self) -> "Address":
54 """The subject this Publisher was declared with, and its Broker address."""
55 return Address(self._subject, NATS_ADDRESS_SYNTAX).add_prefix(
56 self._outer_config.prefix,
57 )
59 @overload
60 async def publish(
61 self,
62 message: "SendableMessage",
63 subject: str = "",
64 headers: dict[str, str] | None = None,
65 reply_to: str = "",
66 correlation_id: str | None = None,
67 stream: None = None,
68 timeout: float | None = None,
69 ) -> None: ...
71 @overload
72 async def publish(
73 self,
74 message: "SendableMessage",
75 subject: str = "",
76 headers: dict[str, str] | None = None,
77 reply_to: str = "",
78 correlation_id: str | None = None,
79 stream: str | None = None,
80 timeout: float | None = None,
81 ) -> "PubAck": ...
83 @override
84 async def publish(
85 self,
86 message: "SendableMessage",
87 subject: str = "",
88 headers: dict[str, str] | None = None,
89 reply_to: str = "",
90 correlation_id: str | None = None,
91 stream: str | None = None,
92 timeout: float | None = None,
93 ) -> Optional["PubAck"]:
94 """Publish message directly.
96 Args:
97 message:
98 Message body to send.
99 Can be any encodable object (native python types or `pydantic.BaseModel`).
100 subject:
101 NATS subject to send message.
102 headers:
103 Message headers to store metainformation.
104 **content-type** and **correlation_id** will be set automatically by framework anyway.
105 reply_to:
106 NATS subject name to send response.
107 correlation_id:
108 Manual message **correlation_id** setter.
109 **correlation_id** is a useful option to trace messages.
110 stream:
111 This option validates that the target subject is in presented stream.
112 Can be omitted without any effect if you doesn't want PubAck frame.
113 timeout:
114 Timeout to send message to NATS.
116 Returns:
117 `None` if you publishes a regular message.
118 `faststream.nats.PubAck` if you publishes a message to stream.
119 """
120 cmd = NatsPublishCommand(
121 message,
122 subject=subject or self.subject.template,
123 headers=self.headers | (headers or {}),
124 reply_to=reply_to or self.reply_to,
125 correlation_id=correlation_id or self._outer_config.id_generator(),
126 stream=stream or getattr(self.stream, "name", None),
127 timeout=timeout or self.timeout,
128 _publish_type=PublishType.PUBLISH,
129 )
131 response: PubAck | None
132 if cmd.stream: 132 ↛ 133line 132 didn't jump to line 133 because the condition on line 132 was never true
133 response = cast(
134 "PubAck",
135 await self._basic_publish(
136 cmd,
137 producer=self._outer_config.js_producer,
138 _extra_middlewares=(),
139 ),
140 )
141 else:
142 response = await self._basic_publish(
143 cmd,
144 producer=self._outer_config.producer,
145 _extra_middlewares=(),
146 )
148 return response
150 @override
151 async def _publish(
152 self,
153 cmd: Union["PublishCommand", "NatsPublishCommand"],
154 *,
155 _extra_middlewares: Iterable["PublisherMiddleware"],
156 ) -> None:
157 """This method should be called in subscriber flow only."""
158 cmd = NatsPublishCommand.from_cmd(cmd)
160 cmd.destination = self.subject.template
161 cmd.add_headers(self.headers, override=False)
162 cmd.reply_to = cmd.reply_to or self.reply_to
164 if self.stream: 164 ↛ 165line 164 didn't jump to line 165 because the condition on line 164 was never true
165 cmd.stream = self.stream.name
166 cmd.timeout = self.timeout
168 if cmd.stream: 168 ↛ 169line 168 didn't jump to line 169 because the condition on line 168 was never true
169 producer: ProducerProto[Any] = self._outer_config.js_producer
170 else:
171 producer = self._outer_config.producer
173 await self._basic_publish(
174 cmd,
175 producer=producer,
176 _extra_middlewares=_extra_middlewares,
177 )
179 @override
180 async def request(
181 self,
182 message: "SendableMessage",
183 subject: str = "",
184 headers: dict[str, str] | None = None,
185 correlation_id: str | None = None,
186 stream: str | None = None,
187 timeout: float = 0.5,
188 ) -> "NatsMessage":
189 """Make a synchronous request to outer subscriber.
191 If out subscriber listens subject by stream, you should setup the same **stream** explicitly.
192 Another way you will reseave confirmation frame as a response.
194 Args:
195 message:
196 Message body to send.
197 Can be any encodable object (native python types or `pydantic.BaseModel`).
198 subject:
199 NATS subject to send message.
200 headers:
201 Message headers to store metainformation.
202 **content-type** and **correlation_id** will be set automatically by framework anyway.
203 correlation_id:
204 Manual message **correlation_id** setter.
205 **correlation_id** is a useful option to trace messages.
206 stream:
207 This allows to make RPC calls over JetStream subjects.
208 timeout:
209 Timeout to send message to NATS.
211 Returns:
212 `faststream.nats.message.NatsMessage` object as an outer subscriber response.
213 """
214 cmd = NatsPublishCommand(
215 message=message,
216 subject=subject or self.subject.template,
217 headers=self.headers | (headers or {}),
218 timeout=timeout or self.timeout,
219 correlation_id=correlation_id or self._outer_config.id_generator(),
220 stream=stream or getattr(self.stream, "name", None),
221 _publish_type=PublishType.REQUEST,
222 )
224 if cmd.stream:
225 producer: ProducerProto[Any] = self._outer_config.js_producer
226 else:
227 producer = self._outer_config.producer
229 msg: NatsMessage = await self._basic_request(cmd, producer=producer)
230 return msg