Coverage for faststream/nats/subscriber/usecases/core_subscriber.py: 86%

49 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-17 21:20 +0000

1from collections.abc import AsyncIterator 

2from typing import TYPE_CHECKING, Any, Optional 

3 

4from nats.errors import TimeoutError 

5from typing_extensions import override 

6 

7from faststream._internal.endpoint.subscriber.mixins import ConcurrentMixin 

8from faststream._internal.endpoint.utils import process_msg 

9from faststream.nats.parser import NatsParser 

10 

11from .basic import DefaultSubscriber 

12 

13if TYPE_CHECKING: 

14 from nats.aio.msg import Msg 

15 from nats.aio.subscription import Subscription 

16 

17 from faststream._internal.endpoint.subscriber import SubscriberSpecification 

18 from faststream._internal.endpoint.subscriber.call_item import CallsCollection 

19 from faststream.message import StreamMessage 

20 from faststream.nats.message import NatsMessage 

21 from faststream.nats.subscriber.config import NatsSubscriberConfig 

22 

23 

24class CoreSubscriber(DefaultSubscriber["Msg"]): 

25 __slots__ = () 

26 

27 subscription: Optional["Subscription"] 

28 _fetch_sub: Optional["Subscription"] 

29 

30 def __init__( 

31 self, 

32 config: "NatsSubscriberConfig", 

33 specification: "SubscriberSpecification[Any, Any]", 

34 calls: "CallsCollection[Msg]", 

35 *, 

36 queue: str, 

37 ) -> None: 

38 parser = NatsParser( 

39 pattern=config.subject, 

40 is_ack_disabled=True, # core subscriber has no ack policy 

41 ) 

42 config.parser = parser.parse_message 

43 config.decoder = parser.decode_message 

44 super().__init__(config, specification, calls) 

45 

46 self.queue = queue 

47 

48 @override 

49 async def get_one( 

50 self, 

51 *, 

52 timeout: float = 5.0, 

53 ) -> "NatsMessage | None": 

54 assert not self.calls, ( 

55 "You can't use `get_one` method if subscriber has registered handlers." 

56 ) 

57 

58 if self._fetch_sub is None: 58 ↛ 65line 58 didn't jump to line 65 because the condition on line 58 was always true

59 fetch_sub = self._fetch_sub = await self.connection.subscribe( 

60 subject=self.subject.broker_address, 

61 queue=self.queue, 

62 **self.extra_options, 

63 ) 

64 else: 

65 fetch_sub = self._fetch_sub 

66 

67 try: 

68 raw_message = await fetch_sub.next_msg(timeout=timeout) 

69 except TimeoutError: 

70 return None 

71 

72 context = self._outer_config.context 

73 

74 async_parser, async_decoder = self._get_parser_and_decoder() 

75 

76 msg: NatsMessage = await process_msg( # type: ignore[assignment] 

77 msg=raw_message, 

78 middlewares=( 

79 m(raw_message, context=context) for m in self._broker_middlewares 

80 ), 

81 parser=async_parser, 

82 decoder=async_decoder, 

83 ) 

84 return msg 

85 

86 @override 

87 async def __aiter__(self) -> AsyncIterator["NatsMessage"]: 

88 assert not self.calls, ( 

89 "You can't use iterator if subscriber has registered handlers." 

90 ) 

91 

92 if self._fetch_sub is None: 92 ↛ 99line 92 didn't jump to line 99 because the condition on line 92 was always true

93 fetch_sub = self._fetch_sub = await self.connection.subscribe( 

94 subject=self.subject.broker_address, 

95 queue=self.queue, 

96 **self.extra_options, 

97 ) 

98 else: 

99 fetch_sub = self._fetch_sub 

100 

101 context = self._outer_config.context 

102 async_parser, async_decoder = self._get_parser_and_decoder() 

103 

104 async for raw_message in fetch_sub.messages: 

105 msg: NatsMessage = await process_msg( # type: ignore[assignment] 

106 msg=raw_message, 

107 middlewares=( 

108 m(raw_message, context=context) for m in self._broker_middlewares 

109 ), 

110 parser=async_parser, 

111 decoder=async_decoder, 

112 ) 

113 yield msg 

114 

115 async def _create_subscription(self) -> None: 

116 """Create NATS subscription and start consume task.""" 

117 if self.subscription: 117 ↛ 118line 117 didn't jump to line 118 because the condition on line 117 was never true

118 return 

119 

120 self.subscription = await self.connection.subscribe( 

121 subject=self.subject.broker_address, 

122 queue=self.queue, 

123 cb=self.consume, 

124 **self.extra_options, 

125 ) 

126 

127 def get_log_context( 

128 self, 

129 message: Optional["StreamMessage[Msg]"], 

130 ) -> dict[str, str]: 

131 """Log context factory using in `self.consume` scope. 

132 

133 Args: 

134 message: Message which we are building context for 

135 """ 

136 return self.build_log_context( 

137 message=message, 

138 subject=self.subject.template, 

139 queue=self.queue, 

140 ) 

141 

142 

143class ConcurrentCoreSubscriber(ConcurrentMixin["Msg"], CoreSubscriber): 

144 __slots__ = () 

145 

146 @override 

147 async def _create_subscription(self) -> None: 

148 """Create NATS subscription and start consume task.""" 

149 if self.subscription: 149 ↛ 150line 149 didn't jump to line 150 because the condition on line 149 was never true

150 return 

151 

152 self.start_consume_task() 

153 

154 self.subscription = await self.connection.subscribe( 

155 subject=self.subject.broker_address, 

156 queue=self.queue, 

157 cb=self._put_msg, 

158 **self.extra_options, 

159 )