Coverage for faststream/rabbit/schemas/queue.py: 92%

61 statements  

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

1from copy import deepcopy 

2from enum import Enum 

3from typing import TYPE_CHECKING, Any, Literal, Optional, TypedDict, Union, overload 

4 

5from faststream._internal.constants import EMPTY 

6from faststream._internal.proto import NameRequired 

7from faststream._internal.utils.path import Address, AddressSyntax 

8from faststream.exceptions import SetupError 

9 

10if TYPE_CHECKING: 

11 from re import Pattern 

12 

13 from aio_pika.abc import TimeoutType 

14 

15 

16RABBIT_ADDRESS_SYNTAX = AddressSyntax( 

17 replace_symbol="*", 

18 patch_regex=lambda x: x.replace(r"\#", ".+"), 

19) 

20 

21 

22class QueueType(str, Enum): 

23 """Queue types for RabbitMQ. 

24 

25 Enum should be lowercase to match RabbitMQ API. 

26 """ 

27 

28 CLASSIC = "classic" 

29 QUORUM = "quorum" 

30 STREAM = "stream" 

31 

32 

33class RabbitQueue(NameRequired): 

34 """A class to represent a RabbitMQ queue. 

35 

36 You can find information about all options in the official RabbitMQ documentation: 

37 

38 https://www.rabbitmq.com/docs/queues 

39 """ 

40 

41 __slots__ = ( 

42 "arguments", 

43 "auto_delete", 

44 "bind_arguments", 

45 "declare", 

46 "durable", 

47 "exclusive", 

48 "robust", 

49 "routing_address", 

50 "timeout", 

51 ) 

52 

53 def __repr__(self) -> str: 

54 if self.declare: 

55 body = f", robust={self.robust}, durable={self.durable}, exclusive={self.exclusive}, auto_delete={self.auto_delete})" 

56 else: 

57 body = "" 

58 

59 if (r := self.routing()) != self.name: 

60 body = f", routing_key='{r}'{body}" 

61 

62 return f"{self.__class__.__name__}({self.name}{body})" 

63 

64 def __eq__(self, value: object, /) -> bool: 

65 if not isinstance(value, RabbitQueue): 

66 return NotImplemented 

67 

68 return ( 

69 self.name == value.name 

70 and self.durable == value.durable 

71 and self.exclusive == value.exclusive 

72 and self.auto_delete == value.auto_delete 

73 and (self.arguments or {}) == (value.arguments or {}) 

74 ) 

75 

76 def __hash__(self) -> int: 

77 """Supports hash to store real objects in declarer.""" 

78 

79 def _hash_dict(d: Any) -> Any: 

80 if isinstance(d, dict): 

81 return frozenset((k, _hash_dict(v)) for k, v in d.items()) 

82 return d 

83 

84 return hash( 

85 ( 

86 self.name, 

87 self.durable, 

88 self.exclusive, 

89 self.auto_delete, 

90 _hash_dict(self.arguments or {}), 

91 ), 

92 ) 

93 

94 @property 

95 def routing_key(self) -> str: 

96 """The routing key as it reaches RabbitMQ.""" 

97 return self.routing_address.broker_address 

98 

99 @property 

100 def path_regex(self) -> Optional["Pattern[str]"]: 

101 return self.routing_address.regex 

102 

103 def routing(self) -> str: 

104 """Return the Broker address of object.""" 

105 return self.routing_address.broker_address or self.name 

106 

107 def routing_template(self) -> str: 

108 """Return the Address template of object.""" 

109 if self.routing_address: 

110 return self.routing_address.template 

111 return self.name 

112 

113 def add_prefix(self, prefix: str) -> "RabbitQueue": 

114 new_q: RabbitQueue = deepcopy(self) 

115 

116 new_q.name = f"{prefix}{new_q.name}" 

117 

118 if new_q.routing_address: 

119 new_q.routing_address = new_q.routing_address.add_prefix(prefix) 

120 

121 return new_q 

122 

123 @overload 

124 def __init__( 

125 self, 

126 name: str, 

127 queue_type: Literal[QueueType.CLASSIC] = QueueType.CLASSIC, 

128 durable: bool = EMPTY, 

129 exclusive: bool = False, 

130 declare: bool = True, 

131 auto_delete: bool = False, 

132 arguments: Optional["ClassicQueueArgs"] = None, 

133 timeout: "TimeoutType" = None, 

134 robust: bool = True, 

135 bind_arguments: dict[str, Any] | None = None, 

136 routing_key: str = "", 

137 ) -> None: ... 

138 

139 @overload 

140 def __init__( 

141 self, 

142 name: str, 

143 queue_type: Literal[QueueType.QUORUM], 

144 durable: Literal[True] = EMPTY, 

145 exclusive: bool = False, 

146 declare: bool = True, 

147 auto_delete: bool = False, 

148 arguments: Optional["QuorumQueueArgs"] = None, 

149 timeout: "TimeoutType" = None, 

150 robust: bool = True, 

151 bind_arguments: dict[str, Any] | None = None, 

152 routing_key: str = "", 

153 ) -> None: ... 

154 

155 @overload 

156 def __init__( 

157 self, 

158 name: str, 

159 queue_type: Literal[QueueType.STREAM], 

160 durable: Literal[True] = EMPTY, 

161 exclusive: bool = False, 

162 declare: bool = True, 

163 auto_delete: bool = False, 

164 arguments: Optional["StreamQueueArgs"] = None, 

165 timeout: "TimeoutType" = None, 

166 robust: bool = True, 

167 bind_arguments: dict[str, Any] | None = None, 

168 routing_key: str = "", 

169 ) -> None: ... 

170 

171 def __init__( 

172 self, 

173 name: str, 

174 queue_type: QueueType = QueueType.CLASSIC, 

175 durable: bool = EMPTY, 

176 exclusive: bool = False, 

177 declare: bool = True, 

178 auto_delete: bool = False, 

179 arguments: Union[ 

180 "QuorumQueueArgs", 

181 "ClassicQueueArgs", 

182 "StreamQueueArgs", 

183 dict[str, Any], 

184 None, 

185 ] = None, 

186 timeout: "TimeoutType" = None, 

187 robust: bool = True, 

188 bind_arguments: dict[str, Any] | None = None, 

189 routing_key: str = "", 

190 ) -> None: 

191 """Initialize the RabbitMQ queue. 

192 

193 :param name: RabbitMQ queue name. 

194 :param durable: Whether the object is durable. 

195 :param exclusive: The queue can be used only in the current connection and will be deleted after connection closed. 

196 :param declare: Whether to queue automatically or just connect to it. 

197 If you want to connect to an existing queue, set this to `False`. 

198 Copy of `passive` aio-pike option. 

199 :param auto_delete: The queue will be deleted after connection closed. 

200 :param arguments: Queue declaration arguments. 

201 You can find information about them in the official RabbitMQ documentation: 

202 https://www.rabbitmq.com/docs/queues#optional-arguments 

203 :param timeout: Send confirmation time from RabbitMQ. 

204 :param robust: Whether to declare queue object as restorable. 

205 :param bind_arguments: Queue-exchange binding options. 

206 :param routing_key: Explicit binding routing key. Uses name if not present. 

207 """ 

208 if queue_type is QueueType.QUORUM or queue_type is QueueType.STREAM: 

209 if durable is EMPTY: 209 ↛ 210line 209 didn't jump to line 210 because the condition on line 209 was never true

210 durable = True 

211 elif not durable: 211 ↛ 212line 211 didn't jump to line 212 because the condition on line 211 was never true

212 error_msg = "Quorum and Stream queues must be durable" 

213 raise SetupError(error_msg) 

214 elif durable is EMPTY: 

215 durable = True 

216 

217 super().__init__(name) 

218 

219 self.durable = durable 

220 self.exclusive = exclusive 

221 self.bind_arguments = bind_arguments 

222 self.routing_address = Address(routing_key, RABBIT_ADDRESS_SYNTAX) 

223 self.robust = robust 

224 self.auto_delete = auto_delete 

225 self.arguments = {"x-queue-type": queue_type.value, **(arguments or {})} 

226 self.timeout = timeout 

227 self.declare = declare 

228 

229 

230CommonQueueArgs = TypedDict( 

231 "CommonQueueArgs", 

232 { 

233 "x-queue-leader-locator": Literal["client-local", "balanced"], 

234 "x-max-length-bytes": int, 

235 }, 

236 total=False, 

237) 

238 

239 

240SharedClassicAndQuorumQueueArgs = TypedDict( 

241 "SharedClassicAndQuorumQueueArgs", 

242 { 

243 "x-expires": int, 

244 "x-message-ttl": int, 

245 "x-single-active-consumer": bool, 

246 "x-dead-letter-exchange": str, 

247 "x-dead-letter-routing-key": str, 

248 "x-max-length": int, 

249 }, 

250 total=False, 

251) 

252 

253 

254ClassicQueueSpecificArgs = TypedDict( 

255 "ClassicQueueSpecificArgs", 

256 { 

257 "x-overflow": Literal["drop-head", "reject-publish", "reject-publish-dlx"], 

258 "x-queue-master-locator": Literal["client-local", "balanced"], 

259 "x-max-priority": int, 

260 "x-queue-mode": Literal["default", "lazy"], 

261 "x-queue-version": int, 

262 }, 

263 total=False, 

264) 

265 

266 

267QuorumQueueSpecificArgs = TypedDict( 

268 "QuorumQueueSpecificArgs", 

269 { 

270 "x-overflow": Literal["drop-head", "reject-publish"], 

271 "x-delivery-limit": int, 

272 "x-quorum-initial-group-size": int, 

273 "x-quorum-target-group-size": int, 

274 "x-dead-letter-strategy": Literal["at-most-once", "at-least-once"], 

275 "x-max-in-memory-length": int, 

276 "x-max-in-memory-bytes": int, 

277 }, 

278 total=False, 

279) 

280 

281 

282StreamQueueSpecificArgs = TypedDict( 

283 "StreamQueueSpecificArgs", 

284 { 

285 "x-max-age": str, 

286 "x-stream-max-segment-size-bytes": int, 

287 "x-stream-filter-size-bytes": int, 

288 "x-initial-cluster-size": int, 

289 }, 

290 total=False, 

291) 

292 

293 

294class ClassicQueueArgs( 

295 CommonQueueArgs, 

296 SharedClassicAndQuorumQueueArgs, 

297 ClassicQueueSpecificArgs, 

298): 

299 """rabbitmq-server/deps/rabbit/src/rabbit_classic_queue.erl.""" 

300 

301 

302class QuorumQueueArgs( 

303 CommonQueueArgs, 

304 SharedClassicAndQuorumQueueArgs, 

305 QuorumQueueSpecificArgs, 

306): 

307 """rabbitmq-server/deps/rabbit/src/rabbit_quorum_queue.erl.""" 

308 

309 

310class StreamQueueArgs(CommonQueueArgs, StreamQueueSpecificArgs): 

311 """rabbitmq-server/deps/rabbit/src/rabbit_stream_queue.erl."""