Coverage for faststream/_internal/utils/path.py: 98%

99 statements  

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

1import re 

2from collections.abc import Callable 

3from dataclasses import dataclass 

4from re import Pattern 

5from typing import Any 

6 

7from faststream.exceptions import SetupError 

8 

9PARAM_REGEX = re.compile(r"(?<!\{)\{([a-zA-Z0-9_]+)\}(?!\})") 

10 

11 

12ESCAPED_LEFT_BRACE = "__faststream_escaped_left__" 

13ESCAPED_RIGHT_BRACE = "__faststream_escaped_right__" 

14 

15 

16class Address: 

17 """An Address template together with the Broker address it compiles to. 

18 

19 `logs.{level}` written at a declaration site produces two values: the template 

20 itself, which documents the contract and which a Publisher formats arguments 

21 into, and the address actually handed to the infrastructure broker (`logs.*`). 

22 Both are read from here under distinct names, so neither can overwrite the other. 

23 

24 A declaration escapes a literal brace as `{{`, which is syntax for the parameter 

25 parser and for nothing else. It is undone once, on the way in, so that nobody 

26 reading a template afterwards has to know the escape exists. 

27 

28 Compilation is lazy and cached, so a template can still be decorated with a 

29 Router prefix after this object is built and nothing is compiled until a Broker 

30 address or a capture regex is asked for. 

31 """ 

32 

33 __slots__ = ("_compiled", "_declaration", "_syntax", "template") 

34 

35 def __init__(self, declaration: str, syntax: "AddressSyntax") -> None: 

36 self._declaration = declaration 

37 """The declaration verbatim, escapes and all: what the parser reads.""" 

38 

39 self.template = _restore_literal_braces(declaration) 

40 """The address as it was declared, e.g. `logs.{level}`.""" 

41 

42 self._syntax = syntax 

43 self._compiled: tuple[Pattern[str] | None, str] | None = None 

44 

45 @classmethod 

46 def literal(cls, value: str) -> "Address": 

47 """An Address read as characters: what it says is what it names. 

48 

49 Kafka topics are the case this exists for. A topic is handed to the broker 

50 as written, so reading one as a template would report capture groups that 

51 nothing ever fills. A Router prefix added later keeps the address literal. 

52 """ 

53 return _LiteralAddress(value) 

54 

55 def __repr__(self) -> str: 

56 return f"{self.__class__.__name__}({self._declaration!r})" 

57 

58 def __bool__(self) -> bool: 

59 """Whether an address was declared at all.""" 

60 return bool(self._declaration) 

61 

62 @property 

63 def broker_address(self) -> str: 

64 """The address as it reaches the broker, e.g. `logs.*` for `logs.{level}`.""" 

65 return self._compile()[1] 

66 

67 @property 

68 def regex(self) -> Pattern[str] | None: 

69 """Captures each Path parameter out of an incoming message's address.""" 

70 return self._compile()[0] 

71 

72 def describe(self) -> str: 

73 """Name this address the way an error message should.""" 

74 return repr(self.template) 

75 

76 def add_prefix(self, prefix: str) -> "Address": 

77 """Decorate the template with a Router prefix; the Broker address follows.""" 

78 if not prefix: 

79 return self 

80 

81 return Address(f"{prefix}{self._declaration}", self._syntax) 

82 

83 def _compile(self) -> tuple[Pattern[str] | None, str]: 

84 if self._compiled is None: 

85 self._compiled = compile_path( 

86 self._declaration, 

87 replace_symbol=self._syntax.replace_symbol, 

88 patch_regex=self._syntax.patch_regex, 

89 param_regex=self._syntax.param_regex, 

90 ) 

91 

92 return self._compiled 

93 

94 

95@dataclass(frozen=True, slots=True) 

96class AddressSyntax: 

97 """How one broker spells a wildcard where an Address template has a Path parameter. 

98 

99 Attributes: 

100 replace_symbol: What each `{param}` becomes in the Broker address. 

101 patch_regex: Broker-specific fixups applied to the compiled capture regex. 

102 param_regex: What a `{param}` may capture — one whole segment, which means 

103 everything up to whatever this broker separates segments with. 

104 """ 

105 

106 replace_symbol: str 

107 patch_regex: Callable[[str], str] 

108 param_regex: str = "[^.]+" 

109 

110 

111def compile_path( 

112 path: str, 

113 replace_symbol: str, 

114 patch_regex: Callable[[str], str] = lambda x: x, 

115 *, 

116 param_regex: str = "[^.]+", 

117) -> tuple[Pattern[str] | None, str]: 

118 path = _escape_literal_braces(path) 

119 path_regex = "^.*?" 

120 original_path = "" 

121 

122 idx = 0 

123 params = set() 

124 duplicated_params = set() 

125 for match in PARAM_REGEX.finditer(path): 

126 param_name = match.groups("str")[0] 

127 

128 path_regex += _restore_braces_in_regex(re.escape(path[idx : match.start()])) 

129 path_regex += f"(?P<{param_name.replace('+', '')}>{param_regex})" 

130 

131 original_path += path[idx : match.start()] 

132 original_path += replace_symbol 

133 

134 if param_name in params: 

135 duplicated_params.add(param_name) 

136 else: 

137 params.add(param_name) 

138 

139 idx = match.end() 

140 

141 if duplicated_params: 

142 names = ", ".join(sorted(duplicated_params)) 

143 ending = "s" if len(duplicated_params) > 1 else "" 

144 msg = f"Duplicated param name{ending} {names} at path {path}" 

145 raise SetupError(msg) 

146 

147 if idx == 0: 

148 regex = None 

149 else: 

150 path_regex += _restore_braces_in_regex(re.escape(path[idx:])) + "$" 

151 regex = re.compile(patch_regex(path_regex)) 

152 

153 original_path += path[idx:] 

154 return regex, _restore_braces(original_path) 

155 

156 

157def match_path(pattern: Pattern[str] | None, subject: str) -> dict[str, Any]: 

158 """Match subject against pattern and return named groups, or {} if no match.""" 

159 if pattern is not None and (match := pattern.match(subject)): 

160 return match.groupdict() 

161 return {} 

162 

163 

164class _LiteralAddress(Address): 

165 """An Address that is not a template: its declaration is its Broker address. 

166 

167 Nothing is compiled, so a `{` in it is a character, and `{{` is two of them. 

168 """ 

169 

170 __slots__ = () 

171 

172 def __init__(self, value: str) -> None: 

173 self._declaration = value 

174 self.template = value 

175 self._compiled = (None, value) 

176 

177 def add_prefix(self, prefix: str) -> Address: 

178 if not prefix: 178 ↛ 179line 178 didn't jump to line 179 because the condition on line 178 was never true

179 return self 

180 

181 return _LiteralAddress(f"{prefix}{self._declaration}") 

182 

183 

184def _escape_literal_braces(path: str) -> str: 

185 result = "" 

186 idx = 0 

187 while idx < len(path): 

188 if path.startswith("{{", idx): 

189 result += ESCAPED_LEFT_BRACE 

190 idx += 2 

191 elif path.startswith("}}", idx): 

192 result += ESCAPED_RIGHT_BRACE 

193 idx += 2 

194 else: 

195 result += path[idx] 

196 idx += 1 

197 return result 

198 

199 

200def _restore_literal_braces(path: str) -> str: 

201 """Undo a declaration's `{{`/`}}` escaping, leaving each `{param}` alone. 

202 

203 Goes through the same scan the parameter parser uses rather than looking for 

204 the pairs a second time, so one function decides what an escape is. 

205 """ 

206 return _restore_braces(_escape_literal_braces(path)) 

207 

208 

209def _restore_braces(fragment: str) -> str: 

210 """Put a declaration's literal braces back into an address.""" 

211 return fragment.replace(ESCAPED_LEFT_BRACE, "{").replace(ESCAPED_RIGHT_BRACE, "}") 

212 

213 

214def _restore_braces_in_regex(fragment: str) -> str: 

215 """Put a declaration's literal braces back into a capture regex. 

216 

217 Escaped, unlike an address: a bare `{2}` in a pattern is a quantifier on 

218 whatever precedes it, not the two characters somebody wrote. 

219 """ 

220 return fragment.replace(ESCAPED_LEFT_BRACE, r"\{").replace( 

221 ESCAPED_RIGHT_BRACE, 

222 r"\}", 

223 )