Coverage for faststream/specification/asyncapi/v2_6_0/generate.py: 96%

108 statements  

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

1import warnings 

2from collections.abc import Iterable, Sequence 

3from typing import TYPE_CHECKING, Any, Optional, Union 

4 

5from faststream._internal._compat import DEF_KEY 

6from faststream._internal.constants import ContentTypes 

7from faststream.specification.asyncapi.utils import clear_key, move_pydantic_refs, ref 

8from faststream.specification.asyncapi.v2_6_0.schema import ( 

9 ApplicationInfo, 

10 ApplicationSchema, 

11 Channel, 

12 Components, 

13 Contact, 

14 ExternalDocs, 

15 License, 

16 Message, 

17 Operation, 

18 Reference, 

19 Server, 

20 Tag, 

21) 

22from faststream.specification.asyncapi.v2_6_0.schema.bindings import ( 

23 OperationBinding, 

24 http as http_bindings, 

25) 

26 

27if TYPE_CHECKING: 

28 from faststream._internal.basic_types import AnyHttpUrl 

29 from faststream._internal.broker import BrokerUsecase 

30 from faststream._internal.types import ConnectionType, MsgType 

31 from faststream.asgi.handlers import HttpHandler 

32 from faststream.specification.schema.extra import ( 

33 Contact as SpecContact, 

34 ContactDict, 

35 ExternalDocs as SpecDocs, 

36 ExternalDocsDict, 

37 License as SpecLicense, 

38 LicenseDict, 

39 Tag as SpecTag, 

40 TagDict, 

41 ) 

42 

43 

44def convert_list_of_dict_to_dict( 

45 list_of: Iterable[dict[str, Any]], 

46 warn: str, 

47) -> dict[str, Any]: 

48 items: dict[str, Any] = {} 

49 for it in list_of: 

50 for key, value in it.items(): 

51 if (exist := items.get(key)) and value != exist: 

52 warnings.warn( 

53 f"Overwrite broker {warn} for an application, {warn} have the same names: `{key}`", 

54 RuntimeWarning, 

55 stacklevel=1, 

56 ) 

57 items[key] = value 

58 

59 return items 

60 

61 

62def get_app_schema( 

63 *brokers: "BrokerUsecase[Any, Any, Any]", 

64 title: str, 

65 app_version: str, 

66 schema_version: str, 

67 description: str | None, 

68 terms_of_service: Optional["AnyHttpUrl"], 

69 contact: Union["SpecContact", "ContactDict", dict[str, Any]] | None, 

70 license: Union["SpecLicense", "LicenseDict", dict[str, Any]] | None, 

71 identifier: str | None, 

72 tags: Sequence[Union["SpecTag", "TagDict", dict[str, Any]]], 

73 external_docs: Union["SpecDocs", "ExternalDocsDict", dict[str, Any]] | None, 

74 http_handlers: list[tuple[str, "HttpHandler"]], 

75) -> ApplicationSchema: 

76 """Get the application schema.""" 

77 if any(br.specification.security for br in brokers): 

78 list_of_specification_security = ( 

79 br.specification.security.get_schema() 

80 for br in brokers 

81 if br.specification.security 

82 ) 

83 security_schemes = convert_list_of_dict_to_dict( 

84 list_of_specification_security, 

85 "specification security", 

86 ) 

87 else: 

88 security_schemes = None 

89 

90 servers, broker_servers = get_broker_server(*brokers) 

91 

92 channels = convert_list_of_dict_to_dict( 

93 (get_broker_channels(br, servers=srv) for br, srv in broker_servers.items()), 

94 "channel", 

95 ) 

96 channels.update(get_asgi_routes(http_handlers)) 

97 

98 messages: dict[str, Message] = {} 

99 payloads: dict[str, dict[str, Any]] = {} 

100 

101 for channel_name, ch in channels.items(): 

102 resolve_channel_messages(ch, channel_name, payloads, messages) 

103 

104 return ApplicationSchema( 

105 info=ApplicationInfo( 

106 title=title, 

107 version=app_version, 

108 description=description, 

109 termsOfService=terms_of_service, 

110 contact=Contact.from_spec(contact), 

111 license=License.from_spec(license), 

112 ), 

113 tags=[Tag.from_spec(tag) for tag in tags] or None, 

114 externalDocs=ExternalDocs.from_spec(external_docs), 

115 asyncapi=schema_version, 

116 defaultContentType=ContentTypes.JSON.value, 

117 id=identifier, 

118 servers=servers, 

119 channels=channels, 

120 components=Components( 

121 messages=messages, 

122 schemas=payloads, 

123 securitySchemes=security_schemes, 

124 ), 

125 ) 

126 

127 

128def resolve_channel_messages( 

129 channel: Channel, 

130 channel_name: str, 

131 payloads: dict[str, dict[str, Any]], 

132 messages: dict[str, Message], 

133) -> None: 

134 if channel.subscribe is not None and channel.subscribe.message: 

135 assert isinstance(channel.subscribe.message, Message) 

136 

137 channel.subscribe.message = _resolve_msg_payloads( 

138 channel.subscribe.message, 

139 channel_name, 

140 payloads, 

141 messages, 

142 ) 

143 

144 if channel.publish is not None: 

145 assert isinstance(channel.publish.message, Message) 

146 

147 channel.publish.message = _resolve_msg_payloads( 

148 channel.publish.message, 

149 channel_name, 

150 payloads, 

151 messages, 

152 ) 

153 

154 

155def get_broker_server( 

156 *brokers: "BrokerUsecase[Any, Any, Any]", 

157) -> tuple[ 

158 dict[str, Server], 

159 dict["BrokerUsecase[Any, Any, Any]", list[str]], 

160]: 

161 """Get the broker server for an application.""" 

162 servers: list[Server] = [] 

163 broker_servers: list[tuple[BrokerUsecase[Any, Any, Any], Server]] = [] 

164 

165 for broker in brokers: 

166 specification = broker.specification 

167 

168 broker_meta: dict[str, Any] = { 

169 "protocol": specification.protocol, 

170 "protocolVersion": specification.protocol_version, 

171 "description": specification.description, 

172 "tags": [Tag.from_spec(tag) for tag in specification.tags] or None, 

173 "security": specification.security.get_requirement() 

174 if specification.security 

175 else None, 

176 # TODO 

177 # "variables": "", 

178 # "bindings": "", 

179 } 

180 

181 for url in specification.url: 

182 server = Server(url=url, **broker_meta) 

183 # deduplicate servers 

184 broker_servers.append((broker, server)) 

185 if server not in servers: 

186 servers.append(server) 

187 

188 servers_by_names: dict[str, Server] = {} 

189 single_server = len(servers) == 1 

190 for i, server in enumerate(servers, 1): 

191 server_name = "development" if single_server else f"Server{i}" 

192 servers_by_names[server_name] = server 

193 

194 broker_server_names: dict[BrokerUsecase[Any, Any, Any], list[str]] = {} 

195 for name, server in servers_by_names.items(): 

196 for broker, br_server in broker_servers: 

197 if server == br_server: 

198 broker_server_names.setdefault(broker, []).append(name) 

199 

200 return servers_by_names, broker_server_names 

201 

202 

203def get_broker_channels( 

204 broker: "BrokerUsecase[MsgType, ConnectionType, Any]", 

205 servers: list[str] | None = None, 

206) -> dict[str, Channel]: 

207 """Get the broker channels for an application.""" 

208 channels = {} 

209 

210 for s in filter(lambda s: s.specification.include_in_schema, broker.subscribers): 

211 for key, sub in s.schema().items(): 

212 if key in channels: 212 ↛ 213line 212 didn't jump to line 213 because the condition on line 212 was never true

213 warnings.warn( 

214 f"Overwrite channel handler, channels have the same names: `{key}`", 

215 RuntimeWarning, 

216 stacklevel=1, 

217 ) 

218 

219 channels[key] = Channel.from_sub(sub, servers=servers) 

220 

221 for p in filter(lambda p: p.specification.include_in_schema, broker.publishers): 

222 for key, pub in p.schema().items(): 

223 if key in channels: 223 ↛ 224line 223 didn't jump to line 224 because the condition on line 223 was never true

224 warnings.warn( 

225 f"Overwrite channel handler, channels have the same names: `{key}`", 

226 RuntimeWarning, 

227 stacklevel=1, 

228 ) 

229 

230 channels[key] = Channel.from_pub(pub, servers=servers) 

231 

232 return channels 

233 

234 

235def get_asgi_routes( 

236 http_handlers: list[tuple[str, "HttpHandler"]], 

237) -> dict[str, Channel]: 

238 """Get the ASGI routes for an application.""" 

239 channels: dict[str, Channel] = {} 

240 for path, asgi_app in http_handlers: 

241 if asgi_app.include_in_schema: 

242 channel = Channel( 

243 description=asgi_app.description, 

244 subscribe=Operation( 

245 tags=[Tag.from_spec(tag) for tag in asgi_app.tags or ()] or None, 

246 operationId=asgi_app.unique_id, 

247 bindings=OperationBinding( 

248 http=http_bindings.OperationBinding( 

249 method=", ".join(asgi_app.methods), 

250 ), 

251 ), 

252 message=None, 

253 ), 

254 ) 

255 

256 channels[path] = channel 

257 

258 return channels 

259 

260 

261def _resolve_msg_payloads( 

262 m: Message, 

263 channel_name: str, 

264 payloads: dict[str, Any], 

265 messages: dict[str, Any], 

266) -> Reference: 

267 """Replace message payload by reference and normalize payloads. 

268 

269 Payloads and messages are editable dicts to store schemas for reference in AsyncAPI. 

270 """ 

271 one_of_list: list[Reference] = [] 

272 m.payload = move_pydantic_refs(m.payload, DEF_KEY) 

273 

274 if DEF_KEY in m.payload: 

275 payloads.update(m.payload.pop(DEF_KEY)) 

276 

277 one_of = m.payload.get("oneOf") 

278 if isinstance(one_of, dict): 

279 for p_title, p in one_of.items(): 

280 formatted_payload_title = clear_key(p_title) 

281 # Promote nested Pydantic $defs from each payload into components/schemas 

282 # so that referenced nested models are available globally. 

283 if isinstance(p, dict) and DEF_KEY in p: 

284 defs = p.pop(DEF_KEY) or {} 

285 for def_name, def_schema in defs.items(): 

286 payloads[clear_key(def_name)] = def_schema 

287 payloads.update(p.pop(DEF_KEY, {})) 

288 if formatted_payload_title not in payloads: 288 ↛ 290line 288 didn't jump to line 290 because the condition on line 288 was always true

289 payloads[formatted_payload_title] = p 

290 one_of_list.append( 

291 Reference(**ref("components", "schemas", formatted_payload_title)), 

292 ) 

293 

294 elif one_of is not None: 

295 # Discriminator case 

296 for p in one_of: 

297 p_value = next(iter(p.values())) 

298 p_title = p_value.split("/")[-1] 

299 p_title = clear_key(p_title) 

300 if p_title not in payloads: 300 ↛ 301line 300 didn't jump to line 301 because the condition on line 300 was never true

301 payloads[p_title] = p 

302 one_of_list.append(Reference(**ref("components", "schemas", p_title))) 

303 

304 if not one_of_list: 

305 payloads.update(m.payload.pop(DEF_KEY, {})) 

306 p_title = m.payload.get("title", f"{channel_name}Payload") 

307 p_title = clear_key(p_title) 

308 if p_title in payloads and payloads[p_title] != m.payload: 

309 warnings.warn( 

310 f"Overwriting the message schema, data types have the same name: `{p_title}`", 

311 RuntimeWarning, 

312 stacklevel=1, 

313 ) 

314 

315 payloads[p_title] = m.payload 

316 m.payload = ref("components", "schemas", p_title) 

317 

318 else: 

319 m.payload["oneOf"] = one_of_list 

320 

321 assert m.title 

322 message_title = clear_key(m.title) 

323 messages[message_title] = m 

324 return Reference(**ref("components", "messages", message_title))