Coverage for faststream/_internal/cli/docs.py: 57%

76 statements  

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

1import json 

2import sys 

3import warnings 

4from pathlib import Path 

5from pprint import pformat 

6from typing import TYPE_CHECKING, cast 

7 

8import typer 

9from pydantic import ValidationError 

10 

11from faststream._internal._compat import json_dumps, model_parse 

12from faststream._internal.cli.utils.imports import import_from_string 

13from faststream.exceptions import INSTALL_WATCHFILES, INSTALL_YAML, SCHEMA_NOT_SUPPORTED 

14from faststream.specification.asyncapi.site import serve_app 

15from faststream.specification.asyncapi.v2_6_0.schema import ( # ruff: ignore[banned-module-level-imports] 

16 ApplicationSchema as SchemaV2_6, 

17) 

18from faststream.specification.asyncapi.v3_0_0.schema import ( # ruff: ignore[banned-module-level-imports] 

19 ApplicationSchema as SchemaV3, 

20) 

21 

22from .dto import RunArgs 

23from .options import ( 

24 APP_ARGUMENT, 

25 APP_DIR_OPTION, 

26 FACTORY_OPTION, 

27 RELOAD_EXTENSIONS_OPTION, 

28 RELOAD_FLAG, 

29) 

30 

31if TYPE_CHECKING: 

32 from collections.abc import Sequence 

33 

34 from faststream.specification.base import SpecificationFactory 

35 

36 

37docs_app = typer.Typer(pretty_exceptions_short=True) 

38 

39 

40@docs_app.command(name="serve") 

41def serve( 

42 docs: str = typer.Argument( 

43 ..., 

44 help="[python_module:FastStream] or [asyncapi.json/.yaml] - path to your application or documentation.", 

45 show_default=False, 

46 ), 

47 host: str = typer.Option( 

48 "localhost", 

49 help="Documentation hosting address.", 

50 ), 

51 port: int = typer.Option( 

52 8000, 

53 help="Documentation hosting port.", 

54 ), 

55 app_dir: str = APP_DIR_OPTION, 

56 is_factory: bool = FACTORY_OPTION, 

57 reload: bool = RELOAD_FLAG, 

58 watch_extensions: list[str] = RELOAD_EXTENSIONS_OPTION, 

59) -> None: 

60 """Serve project AsyncAPI schema.""" 

61 if ":" in docs: 

62 if app_dir: # pragma: no branch 

63 sys.path.insert(0, app_dir) 

64 

65 module, _ = import_from_string(docs, is_factory=is_factory) 

66 

67 module_parent = module.parent 

68 extra_extensions: Sequence[str] = watch_extensions 

69 

70 else: 

71 module_parent = Path.cwd() 

72 schema_filepath = module_parent / docs 

73 extra_extensions = (schema_filepath.suffix, *watch_extensions) 

74 

75 run_args = RunArgs( 

76 app=docs, 

77 extra_options={"host": host, "port": port}, 

78 is_factory=is_factory, 

79 ) 

80 

81 if reload: 

82 try: 

83 from faststream._internal.cli.supervisors.watchfiles import WatchReloader 

84 

85 except ImportError: 

86 warnings.warn(INSTALL_WATCHFILES, category=ImportWarning, stacklevel=1) 

87 _parse_and_serve(run_args) 

88 

89 else: 

90 WatchReloader( 

91 target=_parse_and_serve, 

92 args=run_args, 

93 reload_dirs=(str(module_parent),), 

94 extra_extensions=extra_extensions, 

95 ).run() 

96 

97 else: 

98 _parse_and_serve(run_args) 

99 

100 

101@docs_app.command(name="gen") 

102def gen( 

103 app: str = APP_ARGUMENT, 

104 yaml: bool = typer.Option( 

105 False, 

106 "-y", 

107 "--yaml", 

108 help="Generate `asyncapi.yaml` schema.", 

109 ), 

110 out: str | None = typer.Option( 

111 None, 

112 "-o", 

113 "--out", 

114 help="Output filename.", 

115 show_default="asyncapi.json/.yaml", 

116 ), 

117 debug: bool = typer.Option( 

118 False, 

119 "-d", 

120 "--debug", 

121 help="Do not save generated schema to file. Print it instead.", 

122 ), 

123 app_dir: str = APP_DIR_OPTION, 

124 is_factory: bool = FACTORY_OPTION, 

125) -> None: 

126 """Generate project AsyncAPI schema.""" 

127 if app_dir: # pragma: no branch 

128 sys.path.insert(0, app_dir) 

129 

130 _, app_obj = import_from_string(app, is_factory=is_factory) 

131 schema_factory = cast( 

132 "SpecificationFactory | None", 

133 getattr(app_obj, "schema", None), 

134 ) 

135 if not schema_factory: 135 ↛ 136line 135 didn't jump to line 136 because the condition on line 135 was never true

136 msg = f"{app_obj} doesn't have `schema` attribute" 

137 raise ValueError(msg) 

138 

139 raw_schema = schema_factory.to_specification() 

140 

141 if yaml: 

142 try: 

143 schema = raw_schema.to_yaml() 

144 except ImportError as e: # pragma: no cover 

145 typer.echo(INSTALL_YAML, err=True) 

146 raise typer.Exit(1) from e 

147 

148 filename = out or "asyncapi.yaml" 

149 

150 if not debug: 150 ↛ 163line 150 didn't jump to line 163 because the condition on line 150 was always true

151 Path(filename).write_text(schema, encoding="utf-8") 

152 else: 

153 schema = raw_schema.to_jsonable() 

154 filename = out or "asyncapi.json" 

155 

156 if not debug: 156 ↛ 161line 156 didn't jump to line 161 because the condition on line 156 was always true

157 with Path(filename).open("w", encoding="utf-8") as f: 

158 json.dump(schema, f, indent=2) 

159 

160 else: 

161 schema = pformat(schema) 

162 

163 if debug: 163 ↛ 164line 163 didn't jump to line 164 because the condition on line 163 was never true

164 typer.echo("Generated schema:\n") 

165 typer.echo(schema, color=True) 

166 

167 else: 

168 typer.echo(f"Your project AsyncAPI scheme was placed to `{filename}`") 

169 

170 

171def _yaml_quoting_hint( 

172 validation_errors: "list[tuple[str, ValidationError]]", 

173) -> "str | None": 

174 """Build the quoting hint for the first bare YAML scalar read as a number.""" 

175 # PyYAML reads an unquoted `protocolVersion: 3.2` as a float, 

176 # which the string fields of the schema reject 

177 for _version_label, error in validation_errors: 

178 for sub_error in error.errors(): 

179 if sub_error.get("type") == "string_type" and isinstance( 

180 sub_error.get("input"), 

181 (int, float), 

182 ): 

183 value = sub_error["input"] 

184 loc = ".".join(str(p) for p in sub_error.get("loc", ())) 

185 return ( 

186 f"Hint: YAML parses bare `{value}` at `{loc}` as " 

187 f"{type(value).__name__}; quote it as `'{value}'` " 

188 "to keep it a string." 

189 ) 

190 return None 

191 

192 

193def _parse_and_serve(args: RunArgs) -> None: 

194 if ":" in args.app: 

195 _, app_obj = import_from_string(args.app, is_factory=args.is_factory) 

196 schema_factory = cast( 

197 "SpecificationFactory | None", 

198 getattr(app_obj, "schema", None), 

199 ) 

200 if not schema_factory: 200 ↛ 201line 200 didn't jump to line 201 because the condition on line 200 was never true

201 msg = f"{app_obj} doesn't have `schema` attribute" 

202 raise ValueError(msg) 

203 raw_schema = schema_factory.to_specification() 

204 

205 else: 

206 schema_filepath = Path.cwd() / args.app 

207 is_yaml = schema_filepath.suffix in {".yaml", ".yml"} 

208 

209 if schema_filepath.suffix == ".json": 

210 data = schema_filepath.read_bytes() 

211 

212 elif is_yaml: 212 ↛ 232line 212 didn't jump to line 232 because the condition on line 212 was always true

213 try: 

214 import yaml 

215 except ImportError as e: # pragma: no cover 

216 typer.echo(INSTALL_YAML, err=True) 

217 raise typer.Exit(1) from e 

218 

219 with schema_filepath.open("r") as f: 

220 try: 

221 schema = yaml.safe_load(f) 

222 except yaml.YAMLError as e: 

223 typer.echo( 

224 f"Failed to parse YAML file `{args.app}`: {e}", 

225 err=True, 

226 ) 

227 raise typer.Exit(1) from e 

228 

229 data = json_dumps(schema) 

230 

231 else: 

232 msg = f"Unknown extension given - {args.app}; Please provide app in format [python_module:FastStream] or [asyncapi.yaml/.json] - path to your application or documentation" 

233 raise ValueError(msg) 

234 

235 validation_errors: list[tuple[str, ValidationError]] = [] 

236 raw_schema = None 

237 for version_label, schema in (("3.0", SchemaV3), ("2.6", SchemaV2_6)): 237 ↛ 244line 237 didn't jump to line 244 because the loop on line 237 didn't complete

238 try: 

239 raw_schema = model_parse(schema, data) 

240 break 

241 except ValidationError as e: 

242 validation_errors.append((version_label, e)) 

243 

244 if raw_schema is None: 244 ↛ 245line 244 didn't jump to line 245 because the condition on line 244 was never true

245 typer.echo(SCHEMA_NOT_SUPPORTED.format(schema_filename=args.app), err=True) 

246 for version_label, error in validation_errors: 

247 typer.echo( 

248 f"\nAsyncAPI v{version_label} validation errors:\n{error}", 

249 err=True, 

250 ) 

251 # JSON keeps numbers and strings apart: a number there is a real 

252 # schema error, not a PyYAML coercion 

253 if is_yaml: 

254 hint = _yaml_quoting_hint(validation_errors) 

255 if hint is not None: 

256 typer.echo(hint, err=True) 

257 raise typer.Exit(1) 

258 

259 # Both branches above guarantee a schema here (the parse branch exits on failure). 

260 assert raw_schema is not None 

261 serve_app( 

262 raw_schema, 

263 cast("str", args.extra_options.get("host", "localhost")), 

264 cast("int", args.extra_options.get("port", 8000)), 

265 )