Coverage for faststream/redis/subscriber/usecases/channel_subscriber.py: 96%

77 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, TypeAlias 

3 

4import anyio 

5from redis.asyncio.client import ( 

6 PubSub as RPubSub, 

7) 

8from typing_extensions import override 

9 

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

11from faststream._internal.endpoint.utils import process_msg 

12from faststream.redis.message import ( 

13 PubSubMessage, 

14 RedisChannelMessage, 

15) 

16from faststream.redis.parser import ( 

17 RedisPubSubParser, 

18) 

19 

20from .basic import LogicSubscriber 

21 

22if TYPE_CHECKING: 

23 from faststream._internal.endpoint.subscriber import SubscriberSpecification 

24 from faststream._internal.endpoint.subscriber.call_item import ( 

25 CallsCollection, 

26 ) 

27 from faststream.message import StreamMessage as BrokerStreamMessage 

28 from faststream.redis.schemas import PubSub 

29 from faststream.redis.subscriber.config import RedisSubscriberConfig 

30 

31 

32TopicName: TypeAlias = bytes 

33Offset: TypeAlias = bytes 

34 

35 

36class ChannelSubscriber(LogicSubscriber): 

37 __slots__ = () 

38 

39 def __init__( 

40 self, 

41 config: "RedisSubscriberConfig", 

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

43 calls: "CallsCollection[Any]", 

44 ) -> None: 

45 assert config.channel_sub 

46 parser = RedisPubSubParser(config, pattern=config.channel_sub.path_regex) 

47 config.decoder = parser.decode_message 

48 config.parser = parser.parse_message 

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

50 

51 self._channel = config.channel_sub 

52 self.subscription: RPubSub | None = None 

53 

54 @property 

55 def channel(self) -> "PubSub": 

56 return self._channel.add_prefix(self._outer_config.prefix) 

57 

58 def get_log_context( 

59 self, 

60 message: Optional["BrokerStreamMessage[Any]"], 

61 ) -> dict[str, str]: 

62 return self.build_log_context( 

63 message=message, 

64 channel=self.channel.name, 

65 ) 

66 

67 @override 

68 async def start(self) -> None: 

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

70 return 

71 

72 self.subscription = psub = self._client.pubsub() 

73 

74 if self.channel.pattern: 

75 await psub.psubscribe(self.channel.name) 

76 else: 

77 await psub.subscribe(self.channel.name) 

78 

79 await super().start(psub) 

80 

81 async def stop(self) -> None: 

82 await super().stop() 

83 

84 if self.subscription is not None: 

85 await self.subscription.unsubscribe() 

86 await self.subscription.aclose() # type: ignore[attr-defined] 

87 self.subscription = None 

88 

89 @override 

90 async def get_one( 

91 self, 

92 *, 

93 timeout: float = 5.0, 

94 ) -> "RedisChannelMessage | None": 

95 assert self.subscription, "You should start subscriber at first." 

96 assert not self.calls, ( 

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

98 ) 

99 

100 sleep_interval = timeout / 10 

101 

102 raw_message: PubSubMessage | None = None 

103 

104 with anyio.move_on_after(timeout): 

105 while (raw_message := await self._get_message(self.subscription)) is None: # ruff: ignore[async-busy-wait] 

106 await anyio.sleep(sleep_interval) 

107 

108 context = self._outer_config.context 

109 async_parser, async_decoder = self._get_parser_and_decoder() 

110 

111 msg: RedisChannelMessage | None = await process_msg( # type: ignore[assignment] 

112 msg=raw_message, 

113 middlewares=( 

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

115 ), 

116 parser=async_parser, 

117 decoder=async_decoder, 

118 ) 

119 return msg 

120 

121 @override 

122 async def __aiter__(self) -> AsyncIterator["RedisChannelMessage"]: 

123 assert self.subscription, "You should start subscriber at first." 

124 assert not self.calls, ( 

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

126 ) 

127 

128 timeout = 5 

129 sleep_interval = timeout / 10 

130 

131 raw_message: PubSubMessage | None = None 

132 

133 context = self._outer_config.context 

134 async_parser, async_decoder = self._get_parser_and_decoder() 

135 

136 while True: 

137 with anyio.move_on_after(timeout): 

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

139 raw_message := await self._get_message(self.subscription) 

140 ) is None: 

141 await anyio.sleep(sleep_interval) 

142 

143 if raw_message is None: 143 ↛ 144line 143 didn't jump to line 144 because the condition on line 143 was never true

144 continue 

145 

146 msg: RedisChannelMessage = await process_msg( # type: ignore[assignment] 

147 msg=raw_message, 

148 middlewares=( 

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

150 ), 

151 parser=async_parser, 

152 decoder=async_decoder, 

153 ) 

154 yield msg 

155 

156 async def _get_message(self, psub: RPubSub) -> PubSubMessage | None: 

157 raw_msg = await psub.get_message( 

158 ignore_subscribe_messages=True, 

159 timeout=self.channel.polling_interval, 

160 ) 

161 

162 if raw_msg: 

163 return PubSubMessage( 

164 type=raw_msg["type"], 

165 data=raw_msg["data"], 

166 channel=raw_msg["channel"].decode(), 

167 pattern=raw_msg["pattern"], 

168 ) 

169 

170 return None 

171 

172 async def _get_msgs(self, psub: RPubSub) -> None: 

173 if msg := await self._get_message(psub): 

174 await self.consume_one(msg) 

175 

176 

177class ChannelConcurrentSubscriber( 

178 ConcurrentMixin["BrokerStreamMessage[Any]"], 

179 ChannelSubscriber, 

180): 

181 __slots__ = () 

182 

183 async def start(self) -> None: 

184 await super().start() 

185 self.start_consume_task() 

186 

187 async def consume_one(self, msg: "BrokerStreamMessage[Any]") -> None: 

188 await self._put_msg(msg)