Coverage for faststream/_internal/configs/broker.py: 98%

135 statements  

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

1from collections.abc import Mapping, Sequence 

2from dataclasses import dataclass, field 

3from typing import TYPE_CHECKING, Any, Generic, Optional, TypeAlias, Union 

4 

5from typing_extensions import TypeVar as TypeVar313 

6 

7from faststream._internal.constants import EMPTY 

8from faststream._internal.di import FastDependsConfig 

9from faststream._internal.logger import LoggerState 

10from faststream._internal.producer import ProducerProto, ProducerUnset 

11from faststream._internal.types import IdGenerator 

12from faststream.message import gen_cor_id 

13 

14if TYPE_CHECKING: 

15 from fast_depends.dependencies import Dependant 

16 

17 from faststream._internal.context import ContextRepo 

18 from faststream._internal.parser import CodecProto 

19 from faststream._internal.types import BrokerMiddleware, CustomCallable 

20 from faststream.middlewares import AckPolicy 

21 

22 

23@dataclass(kw_only=True, slots=True) 

24class UnderlyingDriverAnnotation: 

25 """A driver class mapped to the context annotation that injects it. 

26 

27 Attributes: 

28 type_hint: the context annotation to use instead. 

29 module: where that annotation is importable from. 

30 name: its name in that module. 

31 """ 

32 

33 type_hint: Any 

34 module: str 

35 name: str 

36 

37 

38UnderlyingDriverAnnotations: TypeAlias = Mapping[Any, UnderlyingDriverAnnotation | Any] 

39 

40 

41@dataclass(kw_only=True) 

42class BrokerConfig: 

43 prefix: str = "" 

44 include_in_schema: bool | None = True 

45 

46 broker_middlewares: Sequence["BrokerMiddleware[Any]"] = () 

47 broker_parser: Optional["CustomCallable"] = None 

48 broker_decoder: Optional["CustomCallable"] = None 

49 broker_codec: Optional["CodecProto"] = None 

50 

51 producer: "ProducerProto[Any]" = field(default_factory=ProducerUnset) 

52 logger: "LoggerState" = field(default_factory=LoggerState) 

53 fd_config: "FastDependsConfig" = field(default_factory=FastDependsConfig) 

54 id_generator: IdGenerator = gen_cor_id 

55 

56 # subscriber options 

57 underlying_driver_annotations: UnderlyingDriverAnnotations = field( 

58 default_factory=dict 

59 ) 

60 default_driver_annotations: UnderlyingDriverAnnotations = field(default_factory=dict) 

61 broker_dependencies: Sequence["Dependant"] = () 

62 graceful_timeout: float | None = 15.0 

63 ack_policy: "AckPolicy" = field(default_factory=lambda: EMPTY) 

64 extra_context: dict[str, Any] = field(default_factory=dict) 

65 

66 def __post_init__(self) -> None: 

67 # untyped callers still pass a generator: the first subscriber would spend it 

68 self.broker_dependencies = tuple(self.broker_dependencies) 

69 

70 @property 

71 def resolved_underlying_driver_annotations( 

72 self, 

73 ) -> UnderlyingDriverAnnotations: 

74 # A broker's own rows are the defaults; anything the user passed wins. 

75 return { 

76 **self.default_driver_annotations, 

77 **self.underlying_driver_annotations, 

78 } 

79 

80 def __repr__(self) -> str: 

81 return f"{self.__class__.__name__}(id: {id(self)})" 

82 

83 def __bool__(self) -> bool: 

84 return bool( 

85 self.include_in_schema is not None 

86 or self.broker_middlewares 

87 or self.broker_dependencies 

88 or self.prefix, 

89 ) 

90 

91 @property 

92 def context(self) -> "ContextRepo": 

93 return self.fd_config.context 

94 

95 def add_middleware(self, middleware: "BrokerMiddleware[Any]") -> None: 

96 self.broker_middlewares = (*self.broker_middlewares, middleware) 

97 

98 def insert_middleware(self, middleware: "BrokerMiddleware[Any]") -> None: 

99 self.broker_middlewares = (middleware, *self.broker_middlewares) 

100 

101 

102BrokerConfigType_co = TypeVar313( 

103 "BrokerConfigType_co", 

104 bound=BrokerConfig, 

105 default=BrokerConfig, 

106 covariant=True, 

107) 

108 

109ConfigType = Union["ConfigComposition[Any]", "BrokerConfigType_co", BrokerConfig] 

110 

111 

112class ConfigComposition(Generic[BrokerConfigType_co]): # ruff: ignore[too-many-public-methods] 

113 def __init__(self, config: BrokerConfigType_co) -> None: 

114 self.configs: tuple[ConfigType[BrokerConfigType_co], ...] = (config,) 

115 

116 @property 

117 def broker_config(self) -> "BrokerConfigType_co": 

118 assert self.configs 

119 return self.configs[0] # type: ignore[return-value] 

120 

121 def __repr__(self) -> str: 

122 return f"{self.__class__.__name__}({', '.join(repr(c) for c in self.configs)})" 

123 

124 def add_config(self, config: "ConfigType[BrokerConfigType_co]") -> None: 

125 self.configs = (config, *self.configs) 

126 

127 def reset(self) -> None: 

128 self.configs = (self.configs[-1],) 

129 

130 # broker priority options 

131 @property 

132 def producer(self) -> "ProducerProto[Any]": 

133 return self.broker_config.producer 

134 

135 @property 

136 def logger(self) -> "LoggerState": 

137 return self.broker_config.logger 

138 

139 @property 

140 def fd_config(self) -> "FastDependsConfig": 

141 return self.broker_config.fd_config 

142 

143 @fd_config.setter 

144 def fd_config(self, value: "FastDependsConfig") -> None: 

145 self.broker_config.fd_config = value 

146 

147 @property 

148 def context(self) -> "ContextRepo": 

149 return self.broker_config.context 

150 

151 @property 

152 def graceful_timeout(self) -> float | None: 

153 return self.broker_config.graceful_timeout 

154 

155 @property 

156 def id_generator(self) -> IdGenerator: 

157 return self.broker_config.id_generator 

158 

159 def add_middleware(self, middleware: "BrokerMiddleware[Any]") -> None: 

160 self.broker_config.add_middleware(middleware) 

161 

162 def insert_middleware(self, middleware: "BrokerMiddleware[Any]") -> None: 

163 self.broker_config.insert_middleware(middleware) 

164 

165 def __getattr__(self, name: str) -> Any: 

166 return getattr(self.broker_config, name) 

167 

168 # first valuable option 

169 @property 

170 def broker_parser(self) -> Optional["CustomCallable"]: 

171 for c in self.configs: 

172 if c.broker_parser: 

173 return c.broker_parser 

174 return None 

175 

176 @property 

177 def broker_decoder(self) -> Optional["CustomCallable"]: 

178 for c in self.configs: 

179 if c.broker_decoder: 

180 return c.broker_decoder 

181 return None 

182 

183 @property 

184 def broker_codec(self) -> Optional["CodecProto"]: 

185 for c in self.configs: 

186 if c.broker_codec: 

187 return c.broker_codec 

188 return None 

189 

190 @property 

191 def ack_policy(self) -> "AckPolicy": 

192 for c in reversed(self.configs): 

193 ack = c.ack_policy 

194 if ack is not EMPTY: 

195 return ack 

196 return EMPTY # type: ignore[no-any-return] 

197 

198 # merged options 

199 @property 

200 def extra_context(self) -> dict[str, Any]: 

201 context: dict[str, Any] = {} 

202 for c in self.configs: 

203 context |= c.extra_context 

204 return context 

205 

206 @property 

207 def underlying_driver_annotations( 

208 self, 

209 ) -> UnderlyingDriverAnnotations: 

210 annotations: dict[Any, Any] = {} 

211 for c in self.configs: 

212 annotations |= c.underlying_driver_annotations 

213 return annotations 

214 

215 @property 

216 def default_driver_annotations( 

217 self, 

218 ) -> UnderlyingDriverAnnotations: 

219 annotations: dict[Any, Any] = {} 

220 for c in self.configs: 

221 annotations |= c.default_driver_annotations 

222 return annotations 

223 

224 @property 

225 def resolved_underlying_driver_annotations( 

226 self, 

227 ) -> UnderlyingDriverAnnotations: 

228 return { 

229 **self.default_driver_annotations, 

230 **self.underlying_driver_annotations, 

231 } 

232 

233 @property 

234 def prefix(self) -> str: 

235 return "".join(c.prefix for c in self.configs) 

236 

237 @property 

238 def include_in_schema(self) -> bool: 

239 return all(c.include_in_schema is not False for c in self.configs) 

240 

241 @property 

242 def broker_middlewares(self) -> Sequence["BrokerMiddleware[Any]"]: 

243 return [m for c in self.configs for m in c.broker_middlewares] 

244 

245 @property 

246 def broker_dependencies(self) -> Sequence["Dependant"]: 

247 return [b for c in self.configs for b in c.broker_dependencies]