Coverage for faststream/nats/subscriber/usecases/key_value_subscriber.py: 88%

64 statements  

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

1from collections.abc import AsyncIterator, Iterable 

2from contextlib import suppress 

3from typing import TYPE_CHECKING, Any, Optional, cast 

4 

5import anyio 

6from nats.errors import ConnectionClosedError, TimeoutError 

7from typing_extensions import override 

8 

9from faststream._internal.endpoint.subscriber.mixins import TasksMixin 

10from faststream._internal.endpoint.utils import process_msg 

11from faststream.nats.parser import KvParser 

12from faststream.nats.subscriber.adapters import UnsubscribeAdapter 

13 

14from .basic import LogicSubscriber 

15 

16if TYPE_CHECKING: 

17 from nats.js.kv import KeyValue 

18 

19 from faststream._internal.endpoint.publisher import PublisherProto 

20 from faststream._internal.endpoint.subscriber import SubscriberSpecification 

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

22 from faststream.message import StreamMessage 

23 from faststream.nats.message import NatsKvMessage 

24 from faststream.nats.schemas import KvWatch 

25 from faststream.nats.subscriber.config import NatsSubscriberConfig 

26 

27 

28class KeyValueWatchSubscriber( 

29 TasksMixin, 

30 LogicSubscriber["KeyValue.Entry"], 

31): 

32 __slots__ = () 

33 

34 subscription: Optional["UnsubscribeAdapter[KeyValue.KeyWatcher]"] 

35 _fetch_sub: UnsubscribeAdapter["KeyValue.KeyWatcher"] | None 

36 

37 def __init__( 

38 self, 

39 config: "NatsSubscriberConfig", 

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

41 calls: "CallsCollection[KeyValue.Entry]", 

42 *, 

43 kv_watch: "KvWatch", 

44 ) -> None: 

45 parser = KvParser(pattern=config.subject) 

46 config.decoder = parser.decode_message 

47 config.parser = parser.parse_message 

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

49 

50 self.kv_watch = kv_watch 

51 

52 @override 

53 async def get_one( 

54 self, 

55 *, 

56 timeout: float = 5, 

57 ) -> Optional["NatsKvMessage"]: 

58 assert not self.calls, ( 

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

60 ) 

61 

62 if not self._fetch_sub: 62 ↛ 78line 62 didn't jump to line 78 because the condition on line 62 was always true

63 bucket = await self._outer_config.kv_declarer.create_key_value( 

64 bucket=self.kv_watch.name, 

65 declare=self.kv_watch.declare, 

66 ) 

67 

68 fetch_sub = self._fetch_sub = UnsubscribeAdapter["KeyValue.KeyWatcher"]( 

69 await bucket.watch( 

70 keys=self.subject.broker_address, 

71 headers_only=self.kv_watch.headers_only, 

72 include_history=self.kv_watch.include_history, 

73 ignore_deletes=self.kv_watch.ignore_deletes, 

74 meta_only=self.kv_watch.meta_only, 

75 ), 

76 ) 

77 else: 

78 fetch_sub = self._fetch_sub 

79 

80 msg = None 

81 sleep_interval = timeout / 10 

82 with anyio.move_on_after(timeout): 

83 while ( # ruff: ignore[async-busy-wait] 

84 msg := await fetch_sub.obj.updates(timeout) # type: ignore[no-untyped-call] 

85 ) is None: 

86 await anyio.sleep(sleep_interval) 

87 

88 context = self._outer_config.context 

89 async_parser, async_decoder = self._get_parser_and_decoder() 

90 

91 return cast( 

92 "NatsKvMessage", 

93 await process_msg( 

94 msg=msg, 

95 middlewares=(m(msg, context=context) for m in self._broker_middlewares), 

96 parser=async_parser, 

97 decoder=async_decoder, 

98 ), 

99 ) 

100 

101 @override 

102 async def __aiter__(self) -> AsyncIterator["NatsKvMessage"]: 

103 assert not self.calls, ( 

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

105 ) 

106 

107 if not self._fetch_sub: 107 ↛ 123line 107 didn't jump to line 123 because the condition on line 107 was always true

108 bucket = await self._outer_config.kv_declarer.create_key_value( 

109 bucket=self.kv_watch.name, 

110 declare=self.kv_watch.declare, 

111 ) 

112 

113 fetch_sub = self._fetch_sub = UnsubscribeAdapter["KeyValue.KeyWatcher"]( 

114 await bucket.watch( 

115 keys=self.subject.broker_address, 

116 headers_only=self.kv_watch.headers_only, 

117 include_history=self.kv_watch.include_history, 

118 ignore_deletes=self.kv_watch.ignore_deletes, 

119 meta_only=self.kv_watch.meta_only, 

120 ), 

121 ) 

122 else: 

123 fetch_sub = self._fetch_sub 

124 

125 timeout = 5 

126 sleep_interval = timeout / 10 

127 

128 context = self._outer_config.context 

129 async_parser, async_decoder = self._get_parser_and_decoder() 

130 

131 while True: 

132 msg = None 

133 with anyio.move_on_after(timeout): 

134 while ( # ruff: ignore[async-busy-wait] 

135 msg := await fetch_sub.obj.updates(timeout) # type: ignore[no-untyped-call] 

136 ) is None: 

137 await anyio.sleep(sleep_interval) 

138 

139 if msg is None: 139 ↛ 140line 139 didn't jump to line 140 because the condition on line 139 was never true

140 continue 

141 

142 yield cast( 

143 "NatsKvMessage", 

144 await process_msg( 

145 msg=msg, 

146 middlewares=( 

147 m(msg, context=context) for m in self._broker_middlewares 

148 ), 

149 parser=async_parser, 

150 decoder=async_decoder, 

151 ), 

152 ) 

153 

154 @override 

155 async def _create_subscription(self) -> None: 

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

157 return 

158 

159 bucket = await self._outer_config.kv_declarer.create_key_value( 

160 bucket=self.kv_watch.name, 

161 declare=self.kv_watch.declare, 

162 ) 

163 

164 self.subscription = UnsubscribeAdapter["KeyValue.KeyWatcher"]( 

165 await bucket.watch( 

166 keys=self.subject.broker_address, 

167 headers_only=self.kv_watch.headers_only, 

168 include_history=self.kv_watch.include_history, 

169 ignore_deletes=self.kv_watch.ignore_deletes, 

170 meta_only=self.kv_watch.meta_only, 

171 ), 

172 ) 

173 

174 self.add_task(self.__consume_watch) 

175 

176 async def __consume_watch(self) -> None: 

177 assert self.subscription, "You should call `create_subscription` at first." 

178 

179 key_watcher = self.subscription.obj 

180 

181 while self.running: 181 ↛ exitline 181 didn't return from function '__consume_watch' because the condition on line 181 was always true

182 with suppress(ConnectionClosedError, TimeoutError): 

183 message = cast( 

184 "KeyValue.Entry | None", 

185 await key_watcher.updates(self.kv_watch.timeout), # type: ignore[no-untyped-call] 

186 ) 

187 

188 if message: 

189 await self.consume(message) 

190 

191 @override 

192 def _make_response_publisher( 

193 self, 

194 message: "StreamMessage[KeyValue.Entry]", 

195 ) -> Iterable["PublisherProto"]: 

196 """Create Publisher objects to use it as one of `publishers` in `self.consume` scope. 

197 

198 Args: 

199 message: Message requiring reply 

200 """ 

201 return () 

202 

203 def get_log_context( 

204 self, 

205 message: Optional["StreamMessage[KeyValue.Entry]"], 

206 ) -> dict[str, str]: 

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

208 

209 Args: 

210 message: Message which we are building context for 

211 """ 

212 return self.build_log_context( 

213 message=message, 

214 subject=self.subject.template, 

215 stream=self.kv_watch.name, 

216 )