Coverage for faststream/nats/subscriber/factory.py: 70%
114 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 warnings
2from typing import TYPE_CHECKING, Any, Optional, TypedDict
4from nats.aio.subscription import (
5 DEFAULT_SUB_PENDING_BYTES_LIMIT,
6 DEFAULT_SUB_PENDING_MSGS_LIMIT,
7)
8from nats.js.api import ConsumerConfig, DeliverPolicy
9from nats.js.client import (
10 DEFAULT_JS_SUB_PENDING_BYTES_LIMIT,
11 DEFAULT_JS_SUB_PENDING_MSGS_LIMIT,
12)
14from faststream._internal.constants import EMPTY
15from faststream._internal.endpoint.subscriber import SubscriberSpecification
16from faststream._internal.endpoint.subscriber.call_item import CallsCollection
17from faststream.exceptions import SetupError
18from faststream.middlewares import AckPolicy
20from .config import NatsSubscriberConfig, NatsSubscriberSpecificationConfig
21from .specification import NatsSubscriberSpecification, NotIncludeSpecifation
22from .usecases import (
23 BatchPullStreamSubscriber,
24 ConcurrentCoreSubscriber,
25 ConcurrentPullStreamSubscriber,
26 ConcurrentPushStreamSubscriber,
27 CoreSubscriber,
28 KeyValueWatchSubscriber,
29 LogicSubscriber,
30 ObjStoreWatchSubscriber,
31 PullStreamSubscriber,
32 PushStreamSubscriber,
33)
35if TYPE_CHECKING:
36 from nats.js import api
38 from faststream.nats.configs import NatsBrokerConfig
39 from faststream.nats.schemas import JStream, KvWatch, ObjWatch, PullSub
42class SharedOptions(TypedDict):
43 config: NatsSubscriberConfig
44 specification: SubscriberSpecification[Any, Any]
45 calls: CallsCollection[Any]
48def create_subscriber(
49 *,
50 subject: str,
51 queue: str,
52 pending_msgs_limit: int | None,
53 pending_bytes_limit: int | None,
54 # Core args
55 max_msgs: int,
56 # JS args
57 durable: str | None,
58 config: Optional["api.ConsumerConfig"],
59 ordered_consumer: bool,
60 idle_heartbeat: float | None,
61 flow_control: bool | None,
62 deliver_policy: Optional["api.DeliverPolicy"],
63 headers_only: bool | None,
64 # pull args
65 pull_sub: Optional["PullSub"],
66 kv_watch: Optional["KvWatch"],
67 obj_watch: Optional["ObjWatch"],
68 inbox_prefix: bytes,
69 # custom args
70 max_workers: int,
71 stream: Optional["JStream"],
72 # Subscriber args
73 ack_policy: "AckPolicy",
74 no_reply: bool,
75 broker_config: "NatsBrokerConfig",
76 # Specification information
77 title_: str | None,
78 description_: str | None,
79 include_in_schema: bool,
80) -> "LogicSubscriber[Any]":
81 _validate_input_for_misconfigure(
82 subject=subject,
83 queue=queue,
84 pending_msgs_limit=pending_msgs_limit,
85 pending_bytes_limit=pending_bytes_limit,
86 max_msgs=max_msgs,
87 durable=durable,
88 config=config,
89 ordered_consumer=ordered_consumer,
90 idle_heartbeat=idle_heartbeat,
91 flow_control=flow_control,
92 deliver_policy=deliver_policy,
93 headers_only=headers_only,
94 pull_sub=pull_sub,
95 ack_policy=ack_policy,
96 kv_watch=kv_watch,
97 obj_watch=obj_watch,
98 max_workers=max_workers,
99 stream=stream,
100 )
102 config = config or ConsumerConfig(filter_subjects=[])
103 if config.durable_name is None: 103 ↛ 105line 103 didn't jump to line 105 because the condition on line 103 was always true
104 config.durable_name = durable
105 if config.idle_heartbeat is None: 105 ↛ 107line 105 didn't jump to line 107 because the condition on line 105 was always true
106 config.idle_heartbeat = idle_heartbeat
107 if config.headers_only is None: 107 ↛ 109line 107 didn't jump to line 109 because the condition on line 107 was always true
108 config.headers_only = headers_only
109 if config.deliver_policy is DeliverPolicy.ALL: 109 ↛ 112line 109 didn't jump to line 112 because the condition on line 109 was always true
110 config.deliver_policy = deliver_policy or DeliverPolicy.ALL
112 if stream:
113 # Both JS Subscribers
114 extra_options: dict[str, Any] = {
115 "pending_msgs_limit": pending_msgs_limit or DEFAULT_JS_SUB_PENDING_MSGS_LIMIT,
116 "pending_bytes_limit": pending_bytes_limit
117 or DEFAULT_JS_SUB_PENDING_BYTES_LIMIT,
118 "durable": durable,
119 "stream": stream.name,
120 }
122 if pull_sub is not None:
123 # JS Pull Subscriber
124 extra_options.update({"inbox_prefix": inbox_prefix})
126 else:
127 # JS Push Subscriber
128 if ack_policy is AckPolicy.ACK_FIRST: 128 ↛ 129line 128 didn't jump to line 129 because the condition on line 128 was never true
129 manual_ack = False
130 ack_policy = AckPolicy.MANUAL
131 else:
132 manual_ack = True
134 extra_options.update(
135 {
136 "ordered_consumer": ordered_consumer,
137 "idle_heartbeat": idle_heartbeat,
138 "flow_control": flow_control,
139 "deliver_policy": deliver_policy,
140 "headers_only": headers_only,
141 "manual_ack": manual_ack,
142 },
143 )
145 else:
146 # Core Subscriber
147 extra_options = {
148 "pending_msgs_limit": pending_msgs_limit or DEFAULT_SUB_PENDING_MSGS_LIMIT,
149 "pending_bytes_limit": pending_bytes_limit or DEFAULT_SUB_PENDING_BYTES_LIMIT,
150 "max_msgs": max_msgs,
151 }
153 subscriber_config = NatsSubscriberConfig(
154 subject=subject,
155 sub_config=config,
156 extra_options=extra_options,
157 no_reply=no_reply,
158 _outer_config=broker_config,
159 _ack_policy=ack_policy,
160 )
162 calls = CallsCollection[Any]()
164 specification_config = NatsSubscriberSpecificationConfig(
165 subject=subject,
166 queue=queue or None,
167 filter_subjects=list(config.filter_subjects or ()),
168 title_=title_,
169 description_=description_,
170 include_in_schema=include_in_schema,
171 )
173 specification = NatsSubscriberSpecification(
174 _outer_config=broker_config,
175 calls=calls,
176 specification_config=specification_config,
177 )
179 not_include_spec = NotIncludeSpecifation(
180 _outer_config=broker_config,
181 calls=calls,
182 specification_config=specification_config,
183 )
185 subscriber_options: SharedOptions = {
186 "config": subscriber_config,
187 "specification": specification,
188 "calls": calls,
189 }
191 if obj_watch is not None:
192 return ObjStoreWatchSubscriber(
193 **(subscriber_options | {"specification": not_include_spec}),
194 obj_watch=obj_watch,
195 )
197 if kv_watch is not None:
198 return KeyValueWatchSubscriber(
199 **(subscriber_options | {"specification": not_include_spec}),
200 kv_watch=kv_watch,
201 )
203 if stream is None:
204 if max_workers > 1:
205 return ConcurrentCoreSubscriber(
206 **subscriber_options,
207 max_workers=max_workers,
208 queue=queue,
209 )
211 return CoreSubscriber(
212 **subscriber_options,
213 queue=queue,
214 )
216 if max_workers > 1:
217 if pull_sub is not None: 217 ↛ 226line 217 didn't jump to line 226 because the condition on line 217 was always true
218 return ConcurrentPullStreamSubscriber(
219 **subscriber_options,
220 max_workers=max_workers,
221 queue=queue,
222 stream=stream,
223 pull_sub=pull_sub,
224 )
226 return ConcurrentPushStreamSubscriber(
227 **subscriber_options,
228 max_workers=max_workers,
229 queue=queue,
230 stream=stream,
231 )
233 if pull_sub is not None:
234 if pull_sub.batch:
235 return BatchPullStreamSubscriber(
236 **subscriber_options,
237 pull_sub=pull_sub,
238 stream=stream,
239 )
241 return PullStreamSubscriber(
242 **subscriber_options,
243 queue=queue,
244 pull_sub=pull_sub,
245 stream=stream,
246 )
248 return PushStreamSubscriber(
249 **subscriber_options,
250 queue=queue,
251 stream=stream,
252 )
255def _validate_input_for_misconfigure( # ruff: ignore[too-many-statements]
256 subject: str,
257 queue: str, # default ""
258 pending_msgs_limit: int | None,
259 pending_bytes_limit: int | None,
260 max_msgs: int, # default 0
261 durable: str | None,
262 config: Optional["api.ConsumerConfig"],
263 ordered_consumer: bool, # default False
264 idle_heartbeat: float | None,
265 flow_control: bool | None,
266 deliver_policy: Optional["api.DeliverPolicy"],
267 headers_only: bool | None,
268 pull_sub: Optional["PullSub"],
269 kv_watch: Optional["KvWatch"],
270 obj_watch: Optional["ObjWatch"],
271 ack_policy: "AckPolicy", # default EMPTY
272 max_workers: int, # default 1
273 stream: Optional["JStream"],
274) -> None:
275 if ack_policy is not EMPTY:
276 if obj_watch is not None: 276 ↛ 277line 276 didn't jump to line 277 because the condition on line 276 was never true
277 warnings.warn(
278 "You can't use acknowledgement policy with ObjectStorage watch subscriber.",
279 RuntimeWarning,
280 stacklevel=4,
281 )
283 elif kv_watch is not None: 283 ↛ 284line 283 didn't jump to line 284 because the condition on line 283 was never true
284 warnings.warn(
285 "You can't use acknowledgement policy with KeyValue watch subscriber.",
286 RuntimeWarning,
287 stacklevel=4,
288 )
290 elif stream is None and ack_policy is not AckPolicy.MANUAL: 290 ↛ 291line 290 didn't jump to line 291 because the condition on line 290 was never true
291 warnings.warn(
292 (
293 "Core subscriber supports only `ack_policy=AckPolicy.MANUAL` option for very specific cases. "
294 "If you are using different option, probably, you should use JetStream Subscriber instead."
295 ),
296 RuntimeWarning,
297 stacklevel=4,
298 )
300 if max_msgs > 0 and any((stream, kv_watch, obj_watch)): 300 ↛ 301line 300 didn't jump to line 301 because the condition on line 300 was never true
301 warnings.warn(
302 "The `max_msgs` option can be used only with a NATS Core Subscriber.",
303 RuntimeWarning,
304 stacklevel=4,
305 )
307 if pull_sub is not None and pull_sub.batch and max_workers > 1:
308 warnings.warn(
309 "The `batch` option of `PullSub` is ignored with `max_workers`.",
310 RuntimeWarning,
311 stacklevel=4,
312 )
314 if ack_policy is EMPTY:
315 ack_policy = AckPolicy.REJECT_ON_ERROR
317 if stream and kv_watch: 317 ↛ 318line 317 didn't jump to line 318 because the condition on line 317 was never true
318 msg = "You can't use both the `stream` and `kv_watch` options simultaneously."
319 raise SetupError(msg)
321 if stream and obj_watch: 321 ↛ 322line 321 didn't jump to line 322 because the condition on line 321 was never true
322 msg = "You can't use both the `stream` and `obj_watch` options simultaneously."
323 raise SetupError(msg)
325 if kv_watch and obj_watch: 325 ↛ 326line 325 didn't jump to line 326 because the condition on line 325 was never true
326 msg = "You can't use both the `kv_watch` and `obj_watch` options simultaneously."
327 raise SetupError(msg)
329 if pull_sub and not stream: 329 ↛ 330line 329 didn't jump to line 330 because the condition on line 329 was never true
330 msg = "JetStream Pull Subscriber can only be used with the `stream` option."
331 raise SetupError(msg)
333 if not subject and not config:
334 msg = "You must provide either the `subject` or `config` option."
335 raise SetupError(msg)
337 if not stream:
338 if obj_watch or kv_watch:
339 # Obj/Kv Subscriber
340 if pending_msgs_limit is not None: 340 ↛ 341line 340 didn't jump to line 341 because the condition on line 340 was never true
341 warnings.warn(
342 message="The `pending_msgs_limit` option can be used only with JetStream (Pull/Push) or Core Subscription.",
343 category=RuntimeWarning,
344 stacklevel=4,
345 )
347 if pending_bytes_limit is not None: 347 ↛ 348line 347 didn't jump to line 348 because the condition on line 347 was never true
348 warnings.warn(
349 message="The `pending_bytes_limit` option can be used only with JetStream (Pull/Push) or Core Subscription.",
350 category=RuntimeWarning,
351 stacklevel=4,
352 )
354 if queue: 354 ↛ 355line 354 didn't jump to line 355 because the condition on line 354 was never true
355 warnings.warn(
356 message="The `queue` option can be used only with JetStream Push or Core Subscription.",
357 category=RuntimeWarning,
358 stacklevel=4,
359 )
361 if max_workers > 1: 361 ↛ 362line 361 didn't jump to line 362 because the condition on line 361 was never true
362 warnings.warn(
363 message="The `max_workers` option can be used only with JetStream (Pull/Push) or Core Subscription.",
364 category=RuntimeWarning,
365 stacklevel=4,
366 )
368 # Core/Obj/Kv Subscriber
369 if durable: 369 ↛ 370line 369 didn't jump to line 370 because the condition on line 369 was never true
370 warnings.warn(
371 message="The `durable` option can be used only with JetStream (Pull/Push) Subscription.",
372 category=RuntimeWarning,
373 stacklevel=4,
374 )
376 if config is not None: 376 ↛ 377line 376 didn't jump to line 377 because the condition on line 376 was never true
377 warnings.warn(
378 message="The `config` option can be used only with JetStream (Pull/Push) Subscription.",
379 category=RuntimeWarning,
380 stacklevel=4,
381 )
383 if ordered_consumer: 383 ↛ 384line 383 didn't jump to line 384 because the condition on line 383 was never true
384 warnings.warn(
385 message="The `ordered_consumer` option can be used only with JetStream (Pull/Push) Subscription.",
386 category=RuntimeWarning,
387 stacklevel=4,
388 )
390 if idle_heartbeat is not None: 390 ↛ 391line 390 didn't jump to line 391 because the condition on line 390 was never true
391 warnings.warn(
392 message="The `idle_heartbeat` option can be used only with JetStream (Pull/Push) Subscription.",
393 category=RuntimeWarning,
394 stacklevel=4,
395 )
397 if flow_control: 397 ↛ 398line 397 didn't jump to line 398 because the condition on line 397 was never true
398 warnings.warn(
399 message="The `flow_control` option can be used only with JetStream Push Subscription.",
400 category=RuntimeWarning,
401 stacklevel=4,
402 )
404 if deliver_policy: 404 ↛ 405line 404 didn't jump to line 405 because the condition on line 404 was never true
405 warnings.warn(
406 message="The `deliver_policy` option can be used only with JetStream (Pull/Push) Subscription.",
407 category=RuntimeWarning,
408 stacklevel=4,
409 )
411 if headers_only: 411 ↛ 412line 411 didn't jump to line 412 because the condition on line 411 was never true
412 warnings.warn(
413 message="The `headers_only` option can be used only with JetStream (Pull/Push) Subscription.",
414 category=RuntimeWarning,
415 stacklevel=4,
416 )
418 if ack_policy is AckPolicy.ACK_FIRST: 418 ↛ 419line 418 didn't jump to line 419 because the condition on line 418 was never true
419 warnings.warn(
420 message="The `ack_policy=AckPolicy.ACK_FIRST:` option can be used only with JetStream Push Subscription.",
421 category=RuntimeWarning,
422 stacklevel=4,
423 )
425 # JetStream Subscribers
426 elif pull_sub:
427 if queue: 427 ↛ 428line 427 didn't jump to line 428 because the condition on line 427 was never true
428 warnings.warn(
429 message="The `queue` option has no effect with JetStream Pull Subscription. You probably wanted to use the `durable` option instead.",
430 category=RuntimeWarning,
431 stacklevel=4,
432 )
434 if ordered_consumer: 434 ↛ 435line 434 didn't jump to line 435 because the condition on line 434 was never true
435 warnings.warn(
436 "The `ordered_consumer` option has no effect with JetStream Pull Subscription. It can only be used with JetStream Push Subscription.",
437 RuntimeWarning,
438 stacklevel=4,
439 )
441 if ack_policy is AckPolicy.ACK_FIRST: 441 ↛ 442line 441 didn't jump to line 442 because the condition on line 441 was never true
442 warnings.warn(
443 message="The `ack_policy=AckPolicy.ACK_FIRST` option has no effect with JetStream Pull Subscription. It can only be used with JetStream Push Subscription.",
444 category=RuntimeWarning,
445 stacklevel=4,
446 )
448 if flow_control: 448 ↛ 449line 448 didn't jump to line 449 because the condition on line 448 was never true
449 warnings.warn(
450 message="The `flow_control` option has no effect with JetStream Pull Subscription. It can only be used with JetStream Push Subscription.",
451 category=RuntimeWarning,
452 stacklevel=4,
453 )
455 # JS PushSub
456 elif durable is not None: 456 ↛ 457line 456 didn't jump to line 457 because the condition on line 456 was never true
457 warnings.warn(
458 message="The JetStream Push consumer with the `durable` option can't be scaled horizontally across multiple instances. You probably wanted to use the `queue` option instead. Also, we strongly recommend using the Jetstream PullSubscriber with the `durable` option as the default.",
459 category=RuntimeWarning,
460 stacklevel=4,
461 )