Coverage for faststream/specification/asyncapi/v3_0_0/generate.py: 97%

129 statements  

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

1import string 

2import warnings 

3from collections.abc import Iterable, Sequence 

4from typing import TYPE_CHECKING, Any, Optional, Union 

5from urllib.parse import urlparse 

6 

7from faststream._internal._compat import DEF_KEY 

8from faststream._internal.constants import ContentTypes 

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

10from faststream.specification.asyncapi.v3_0_0.schema import ( 

11 ApplicationInfo, 

12 ApplicationSchema, 

13 Channel, 

14 Components, 

15 Contact, 

16 ExternalDocs, 

17 License, 

18 Message, 

19 Operation, 

20 Reference, 

21 Server, 

22 Tag, 

23) 

24from faststream.specification.asyncapi.v3_0_0.schema.bindings import ( 

25 OperationBinding, 

26 http as http_bindings, 

27) 

28from faststream.specification.asyncapi.v3_0_0.schema.operations import Action 

29 

30if TYPE_CHECKING: 

31 from faststream._internal.basic_types import AnyHttpUrl 

32 from faststream._internal.broker import BrokerUsecase 

33 from faststream._internal.types import ConnectionType, MsgType 

34 from faststream.asgi.handlers import HttpHandler 

35 from faststream.specification.schema.extra import ( 

36 Contact as SpecContact, 

37 ContactDict, 

38 ExternalDocs as SpecDocs, 

39 ExternalDocsDict, 

40 License as SpecLicense, 

41 LicenseDict, 

42 Tag as SpecTag, 

43 TagDict, 

44 ) 

45 

46 

47def convert_list_of_dict_to_dict( 

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

49 warn: str, 

50) -> dict[str, Any]: 

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

52 for it in list_of: 

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

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

55 warnings.warn( 

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

57 RuntimeWarning, 

58 stacklevel=1, 

59 ) 

60 items[key] = value 

61 

62 return items 

63 

64 

65def get_app_schema( 

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

67 title: str, 

68 app_version: str, 

69 schema_version: str, 

70 description: str | None, 

71 terms_of_service: Optional["AnyHttpUrl"], 

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

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

74 identifier: str | None, 

75 tags: Sequence[Union["SpecTag", "TagDict", dict[str, Any]]] | None, 

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

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

78) -> ApplicationSchema: 

79 """Get the application schema.""" 

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

81 list_of_specification_security = ( 

82 br.specification.security.get_schema() 

83 for br in brokers 

84 if br.specification.security 

85 ) 

86 security_schemes: dict[str, dict[str, Any]] | None = convert_list_of_dict_to_dict( 

87 list_of_specification_security, 

88 "specification security", 

89 ) 

90 else: 

91 security_schemes = None 

92 

93 servers, broker_servers = get_broker_server(*brokers) 

94 

95 list_of_channels_operations = [ 

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

97 ] 

98 list_of_channels = (itchannel for itchannel, _ in list_of_channels_operations) 

99 list_of_operations = (itoperation for _, itoperation in list_of_channels_operations) 

100 

101 channels = convert_list_of_dict_to_dict(list_of_channels, "channel") 

102 operations = convert_list_of_dict_to_dict(list_of_operations, "operation") 

103 

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

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

106 

107 added_channels, added_operations = get_asgi_routes(http_handlers) 

108 channels.update(added_channels) 

109 operations.update(added_operations) 

110 

111 for channel_name, channel in channels.items(): 

112 msgs: dict[str, Message | Reference] = {} 

113 for message_name, message in channel.messages.items(): 

114 assert isinstance(message, Message) 

115 

116 msgs[message_name] = _resolve_msg_payloads( 

117 message_name, 

118 message, 

119 channel_name, 

120 payloads, 

121 messages, 

122 ) 

123 

124 channel.messages = msgs 

125 

126 return ApplicationSchema( 

127 info=ApplicationInfo( 

128 title=title, 

129 version=app_version, 

130 description=description, 

131 termsOfService=terms_of_service, 

132 contact=Contact.from_spec(contact), 

133 license=License.from_spec(license), 

134 tags=[Tag.from_spec(tag) for tag in tags] or None if tags else None, 

135 externalDocs=ExternalDocs.from_spec(external_docs), 

136 ), 

137 asyncapi=schema_version, 

138 defaultContentType=ContentTypes.JSON.value, 

139 id=identifier, 

140 servers=servers, 

141 channels=channels, 

142 operations=operations, 

143 components=Components( 

144 messages=messages, 

145 schemas=payloads, 

146 securitySchemes=security_schemes, 

147 ), 

148 ) 

149 

150 

151def get_broker_server( 

152 *brokers: "BrokerUsecase[MsgType, ConnectionType, Any]", 

153) -> tuple[ 

154 dict[str, Server], 

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

156]: 

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

158 servers: list[Server] = [] 

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

160 

161 for broker in brokers: 

162 specification = broker.specification 

163 

164 broker_meta: dict[str, Any] = { 

165 "protocol": specification.protocol, 

166 "protocolVersion": specification.protocol_version, 

167 "description": specification.description, 

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

169 # TODO 

170 # "variables": "", 

171 # "bindings": "", 

172 } 

173 

174 if specification.security is not None: 

175 broker_meta["security"] = [ 

176 Reference(**ref("components", "securitySchemes", sec)) 

177 for security_item in specification.security.get_requirement() 

178 for sec in security_item 

179 ] 

180 

181 for url in specification.url: 

182 parsed_url = urlparse(url if "://" in url else f"//{url}") 

183 server = Server( 

184 host=parsed_url.netloc, 

185 pathname=parsed_url.path, 

186 **broker_meta, 

187 ) 

188 

189 # deduplicate servers 

190 broker_servers.append((broker, server)) 

191 if server not in servers: 

192 servers.append(server) 

193 

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

195 single_server = len(servers) == 1 

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

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

198 servers_by_names[server_name] = server 

199 

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

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

202 for broker, br_server in broker_servers: 

203 if server == br_server: 

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

205 

206 return servers_by_names, broker_server_names 

207 

208 

209def get_broker_channels( 

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

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

212) -> tuple[dict[str, Channel], dict[str, Operation]]: 

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

214 channels = {} 

215 operations = {} 

216 

217 channel_servers = [ 

218 ref("servers", server_name) for server_name in (servers or ()) 

219 ] or None 

220 

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

222 sub_schema = sub.schema() 

223 

224 # A title cannot name the operations of several channels: written once 

225 # per channel it leaves one operation and the rest unreferenced. 

226 sub_title = sub.specification.config.title_ if len(sub_schema) == 1 else None 

227 

228 for sub_key, sub_channel in sub_schema.items(): 

229 channel_obj = Channel.from_sub(sub_channel, servers=channel_servers) 

230 

231 channel_key = clear_key(sub_key) 

232 if channel_key in channels: 232 ↛ 233line 232 didn't jump to line 233 because the condition on line 232 was never true

233 warnings.warn( 

234 f"Overwrite channel handler, channels have the same names: `{channel_key}`", 

235 RuntimeWarning, 

236 stacklevel=1, 

237 ) 

238 

239 channels[channel_key] = channel_obj 

240 

241 operation_key = ( 

242 f"{channel_key}Subscribe" 

243 if sub_title is None or sub_title == "/" 

244 else sub_title 

245 ) 

246 if operation_key in operations: 246 ↛ 247line 246 didn't jump to line 247 because the condition on line 246 was never true

247 warnings.warn( 

248 f"Overwrite channel handler, operations have the same names: `{operation_key}`", 

249 RuntimeWarning, 

250 stacklevel=1, 

251 ) 

252 

253 operations[operation_key] = Operation.from_sub( 

254 messages=[ 

255 Reference(**ref("channels", channel_key, "messages", msg_name)) 

256 for msg_name in channel_obj.messages 

257 ], 

258 channel=Reference(**ref("channels", channel_key)), 

259 operation=sub_channel.operation, 

260 ) 

261 

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

263 for pub_key, pub_channel in pub.schema().items(): 

264 channel_obj = Channel.from_pub(pub_channel, servers=channel_servers) 

265 

266 channel_key = clear_key(pub_key) 

267 if channel_key in channels: 267 ↛ 268line 267 didn't jump to line 268 because the condition on line 267 was never true

268 warnings.warn( 

269 f"Overwrite channel handler, channels have the same names: `{channel_key}`", 

270 RuntimeWarning, 

271 stacklevel=1, 

272 ) 

273 channels[channel_key] = channel_obj 

274 

275 operations[channel_key] = Operation.from_pub( 

276 messages=[ 

277 Reference(**ref("channels", channel_key, "messages", msg_name)) 

278 for msg_name in channel_obj.messages 

279 ], 

280 channel=Reference(**ref("channels", channel_key)), 

281 operation=pub_channel.operation, 

282 ) 

283 

284 return channels, operations 

285 

286 

287def get_asgi_routes( 

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

289) -> tuple[dict[str, Channel], dict[str, Operation]]: 

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

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

292 operations: dict[str, Operation] = {} 

293 for path, asgi_app in http_handlers: 

294 if asgi_app.include_in_schema: 

295 channel = Channel( 

296 description=asgi_app.description, 

297 address=path, 

298 messages={}, 

299 ) 

300 channel_name = "".join( 

301 char 

302 for char in path.strip("/").replace("/", "_") 

303 if char in string.ascii_letters + string.digits + "_" 

304 ) 

305 channel_name = f"{channel_name}:HttpChannel" 

306 channels[channel_name] = channel 

307 operation = Operation( 

308 action=Action.RECEIVE, 

309 channel=Reference(**ref("channels", channel_name)), 

310 bindings=OperationBinding( 

311 http=http_bindings.OperationBinding( 

312 method=_get_http_binding_method(asgi_app.methods), 

313 bindingVersion="0.3.0", 

314 ), 

315 ), 

316 ) 

317 operations[channel_name] = operation 

318 return channels, operations 

319 

320 

321def _get_http_binding_method(methods: Sequence[str]) -> str: 

322 return next((method for method in methods if method != "HEAD"), "HEAD") 

323 

324 

325def _resolve_msg_payloads( 

326 message_name: str, 

327 m: Message, 

328 channel_name: str, 

329 payloads: dict[str, Any], 

330 messages: dict[str, Any], 

331) -> Reference: 

332 assert isinstance(m.payload, dict) 

333 

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

335 

336 message_name = clear_key(message_name) 

337 channel_name = clear_key(channel_name) 

338 

339 if DEF_KEY in m.payload: 

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

341 

342 one_of = m.payload.get("oneOf", None) 

343 if isinstance(one_of, dict): 

344 one_of_list = [] 

345 processed_payloads: dict[str, dict[str, Any]] = {} 

346 for name, payload in one_of.items(): 

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

348 # so that referenced nested models are available globally. 

349 if isinstance(payload, dict) and DEF_KEY in payload: 

350 defs = payload.pop(DEF_KEY) or {} 

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

352 payloads[clear_key(def_name)] = def_schema 

353 processed_payloads[clear_key(name)] = payload 

354 one_of_list.append(Reference(**ref("components", "schemas", name))) 

355 

356 payloads.update(processed_payloads) 

357 m.payload["oneOf"] = one_of_list 

358 assert m.title 

359 messages[clear_key(m.title)] = m 

360 return Reference( 

361 **ref("components", "messages", f"{channel_name}:{message_name}"), 

362 ) 

363 

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

365 payload_name = m.payload.get("title", f"{channel_name}:{message_name}:Payload") 

366 payload_name = clear_key(payload_name) 

367 

368 if payload_name in payloads and payloads[payload_name] != m.payload: 

369 warnings.warn( 

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

371 RuntimeWarning, 

372 stacklevel=1, 

373 ) 

374 

375 payloads[payload_name] = m.payload 

376 m.payload = ref("components", "schemas", payload_name) 

377 assert m.title 

378 messages[clear_key(m.title)] = m 

379 return Reference( 

380 **ref("components", "messages", f"{channel_name}:{message_name}"), 

381 )