Coverage for faststream/_internal/cli/main.py: 65%

85 statements  

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

1import logging 

2import os 

3import platform 

4import sys 

5import warnings 

6from contextlib import suppress 

7from pathlib import Path 

8from typing import TYPE_CHECKING, Any, Literal, cast 

9 

10import anyio 

11import typer 

12 

13from faststream import FastStream 

14from faststream.__about__ import __version__ 

15from faststream._internal._compat import IS_WINDOWS, json_loads 

16from faststream._internal.application import Application 

17from faststream.asgi import AsgiFastStream 

18from faststream.exceptions import INSTALL_WATCHFILES, SetupError, StartupValidationError 

19 

20from .docs import docs_app 

21from .dto import RunArgs 

22from .options import ( 

23 APP_ARGUMENT, 

24 APP_DIR_OPTION, 

25 FACTORY_OPTION, 

26 RELOAD_EXTENSIONS_OPTION, 

27 RELOAD_FLAG, 

28) 

29from .supervisors.asgi_multiprocess import ASGIMultiprocess 

30from .supervisors.multiprocess import Multiprocess 

31from .utils.imports import import_from_string 

32from .utils.logs import ( 

33 LogFiles, 

34 LogLevels, 

35 get_log_level, 

36 set_log_config, 

37 set_log_level, 

38) 

39from .utils.parser import parse_cli_args 

40 

41if TYPE_CHECKING: 

42 from faststream._internal.broker import BrokerUsecase 

43 

44rich_mode = os.getenv("FASTSTREAM_CLI_RICH_MODE", "rich") 

45if rich_mode == "none": 45 ↛ 46line 45 didn't jump to line 46 because the condition on line 45 was never true

46 rich_markup_mode: Literal["markdown", "rich"] | None = None 

47elif rich_mode in {"md", "markdown"}: 47 ↛ 48line 47 didn't jump to line 48 because the condition on line 47 was never true

48 rich_markup_mode = "markdown" 

49elif rich_mode == "rich": 49 ↛ 52line 49 didn't jump to line 52 because the condition on line 49 was always true

50 rich_markup_mode = "rich" 

51else: 

52 msg = f"Invalid rich mode: {rich_mode}" 

53 raise ValueError(msg) 

54 

55cli = typer.Typer(pretty_exceptions_short=True, rich_markup_mode=rich_markup_mode) 

56cli.add_typer(docs_app, name="docs", help="Documentations commands") 

57 

58 

59def version_callback(version: bool) -> None: 

60 """Callback function for displaying version information.""" 

61 if version: 

62 typer.echo( 

63 f"Running FastStream {__version__} with {platform.python_implementation()} " 

64 f"{platform.python_version()} on {platform.system()}", 

65 ) 

66 

67 raise typer.Exit 

68 

69 

70def loop_callback(value: str) -> str: 

71 # validate loop string in callback for more informative error 

72 if value != "auto": 72 ↛ 73line 72 didn't jump to line 73 because the condition on line 72 was never true

73 import_from_string(value) 

74 return value 

75 

76 

77@cli.callback() 

78def main( 

79 version: bool | None = typer.Option( 

80 False, 

81 "-v", 

82 "--version", 

83 callback=version_callback, 

84 is_eager=True, 

85 help="Show current platform, python and FastStream version.", 

86 ), 

87) -> None: 

88 """Generate, run and manage FastStream apps to greater development experience.""" 

89 

90 

91@cli.command( 

92 context_settings={"allow_extra_args": True, "ignore_unknown_options": True}, 

93) 

94def run( 

95 ctx: typer.Context, 

96 app: str = APP_ARGUMENT, 

97 workers: int = typer.Option( 

98 1, 

99 "-w", 

100 "--workers", 

101 show_default=False, 

102 help="Run [workers] applications with process spawning.", 

103 envvar="FASTSTREAM_WORKERS", 

104 ), 

105 app_dir: str = APP_DIR_OPTION, 

106 is_factory: bool = FACTORY_OPTION, 

107 reload: bool = RELOAD_FLAG, 

108 watch_extensions: list[str] = RELOAD_EXTENSIONS_OPTION, 

109 loop: str = typer.Option( 

110 "auto", 

111 "--loop", 

112 callback=loop_callback, 

113 help=("Event loop factory implementation."), 

114 envvar="FASTSTREAM_LOOP", 

115 ), 

116 log_level: LogLevels = typer.Option( 

117 LogLevels.notset, 

118 "-l", 

119 "--log-level", 

120 case_sensitive=False, 

121 help="Set selected level for FastStream and brokers logger objects.", 

122 envvar="FASTSTREAM_LOG_LEVEL", 

123 show_default=False, 

124 ), 

125 log_config: Path | None = typer.Option( 

126 None, 

127 "--log-config", 

128 help=( 

129 "Set file to configure logging. Support " 

130 f"{', '.join(f'`{x.value}`' for x in LogFiles)} extensions." # ruff: ignore[function-call-in-default-argument] 

131 ), 

132 show_default=False, 

133 ), 

134) -> None: 

135 """Run [MODULE:APP] FastStream application.""" 

136 if watch_extensions and not reload: 136 ↛ 137line 136 didn't jump to line 137 because the condition on line 136 was never true

137 typer.echo( 

138 "Extra reload extensions has no effect without `--reload` flag." 

139 "\nProbably, you forgot it?", 

140 ) 

141 

142 app, extra = parse_cli_args(app, *ctx.args) 

143 casted_log_level = get_log_level(log_level) 

144 

145 if app_dir: # pragma: no branch 

146 sys.path.insert(0, app_dir) 

147 

148 # Should be imported after sys.path changes 

149 module_path, app_obj = import_from_string(app, is_factory=is_factory) 

150 app_obj = cast("Application", app_obj) 

151 

152 if reload and workers > 1: 152 ↛ 153line 152 didn't jump to line 153 because the condition on line 152 was never true

153 msg = "You can't use reload option with multiprocessing" 

154 raise SetupError(msg) 

155 

156 run_args = RunArgs( 

157 app, 

158 extra_options={"worker_id": None, **extra}, 

159 is_factory=is_factory, 

160 log_config=log_config, 

161 log_level=casted_log_level, 

162 loop=loop, 

163 ) 

164 

165 if reload: 165 ↛ 166line 165 didn't jump to line 166 because the condition on line 165 was never true

166 try: 

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

168 except ImportError: 

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

170 _run(run_args) 

171 

172 else: 

173 reload_dirs = [str(module_path)] 

174 if app_dir != ".": 

175 reload_dirs.append(app_dir) 

176 

177 WatchReloader( 

178 target=_run, 

179 args=run_args, 

180 reload_dirs=reload_dirs, 

181 extra_extensions=watch_extensions, 

182 ).run() 

183 

184 elif workers > 1: 

185 if isinstance(app_obj, FastStream): 185 ↛ 194line 185 didn't jump to line 194 because the condition on line 185 was always true

186 run_args.app_level = logging.DEBUG 

187 

188 Multiprocess( 

189 target=_run, 

190 args=run_args, 

191 workers=workers, 

192 ).run() 

193 

194 elif isinstance(app_obj, AsgiFastStream): 

195 ASGIMultiprocess( 

196 target=app, 

197 args=run_args, 

198 workers=workers, 

199 ).run() 

200 

201 else: 

202 msg = f"Unexpected app type, expected FastStream or AsgiFastStream, got: {type(app_obj)}." 

203 raise typer.BadParameter(msg) 

204 

205 else: 

206 _run_imported_app(app_obj, args=run_args) 

207 

208 

209def _run(args: RunArgs) -> None: 

210 """Runs the specified application.""" 

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

212 app_obj = cast("Application", app_obj) 

213 _run_imported_app(app_obj, args=args) 

214 

215 

216def _run_imported_app(app_obj: "Application", args: RunArgs) -> None: 

217 if not isinstance(app_obj, Application): 217 ↛ 218line 217 didn't jump to line 218 because the condition on line 217 was never true

218 msg = f'Imported object "{app_obj}" must be "Application" type.' 

219 raise typer.BadParameter( 

220 msg, 

221 ) 

222 

223 if args.log_level > 0: 

224 set_log_level(args.log_level, app_obj) 

225 

226 if args.log_config is not None: 226 ↛ 227line 226 didn't jump to line 227 because the condition on line 226 was never true

227 set_log_config(args.log_config) 

228 

229 backend_options = {} 

230 if args.loop != "auto": 

231 _, loop_factory = import_from_string(args.loop) 

232 backend_options["loop_factory"] = loop_factory 

233 

234 elif not IS_WINDOWS: # pragma: no cover 

235 with suppress(ImportError): 

236 import uvloop 

237 

238 backend_options["loop_factory"] = uvloop.new_event_loop 

239 

240 try: 

241 anyio.run( 

242 app_obj.run, 

243 args.app_level, 

244 args.extra_options, 

245 backend_options=backend_options, 

246 ) 

247 

248 except StartupValidationError as startup_exc: 

249 from faststream._internal.cli.utils.errors import draw_startup_errors 

250 

251 draw_startup_errors(startup_exc) 

252 sys.exit(1) 

253 

254 

255@cli.command( 

256 context_settings={"allow_extra_args": True, "ignore_unknown_options": True}, 

257) 

258def publish( 

259 ctx: typer.Context, 

260 app: str = APP_ARGUMENT, 

261 app_dir: str = APP_DIR_OPTION, 

262 message: str = typer.Argument( 

263 ..., 

264 help="JSON Message string to publish.", 

265 show_default=False, 

266 ), 

267 rpc: bool = typer.Option( 

268 False, 

269 help="Enable RPC mode and system output.", 

270 ), 

271 is_factory: bool = FACTORY_OPTION, 

272) -> None: 

273 """Publish a message using the specified broker in a FastStream application. 

274 

275 This command publishes a message to a broker configured in a FastStream app instance. 

276 It supports various brokers and can handle extra arguments specific to each broker type. 

277 These are parsed and passed to the broker's publish method. 

278 """ 

279 app, extra = parse_cli_args(app, *ctx.args) 

280 

281 if app_dir: # pragma: no branch 

282 sys.path.insert(0, app_dir) 

283 

284 publish_extra: dict[str, Any] = extra.copy() 

285 if "timeout" in publish_extra: 

286 publish_extra["timeout"] = float(publish_extra["timeout"]) 

287 

288 try: 

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

290 

291 assert isinstance(app_obj, Application), app_obj 

292 

293 if not app_obj.broker: 

294 msg = "Broker instance not found in the app." 

295 raise ValueError(msg) 

296 

297 result = anyio.run(publish_message, app_obj.broker, rpc, message, publish_extra) 

298 

299 if rpc: 

300 typer.echo(result) 

301 

302 except Exception as e: 

303 typer.echo(f"Publish error: {e}") 

304 sys.exit(1) 

305 

306 

307async def publish_message( 

308 broker: "BrokerUsecase[Any, Any, Any]", 

309 rpc: bool, 

310 message: str, 

311 extra: dict[str, Any], 

312) -> Any: 

313 with suppress(Exception): 

314 message = json_loads(message) 

315 

316 try: 

317 async with broker: 

318 if rpc: 

319 return await broker.request(message, **extra) # type: ignore[call-arg] 

320 return await broker.publish(message, **extra) # type: ignore[call-arg] 

321 

322 except Exception as e: 

323 typer.echo(f"Error when broker was publishing: {e!r}") 

324 sys.exit(1)