Coverage for faststream/asgi/app.py: 79%

133 statements  

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

1import inspect 

2import logging 

3import traceback 

4from abc import abstractmethod 

5from collections.abc import AsyncGenerator, Sequence 

6from contextlib import asynccontextmanager 

7from typing import TYPE_CHECKING, Any, Optional, Protocol 

8 

9import anyio 

10from fast_depends import Provider, dependency_provider 

11from typing_extensions import Self 

12 

13from faststream._internal._compat import HAS_TYPER, HAS_UVICORN, ExceptionGroup, uvicorn 

14from faststream._internal.application import Application 

15from faststream._internal.constants import EMPTY 

16from faststream._internal.context import ContextRepo 

17from faststream._internal.di import FastDependsConfig 

18from faststream._internal.logger import logger 

19from faststream.exceptions import INSTALL_UVICORN, StartupValidationError 

20 

21from .factories import AsyncAPIRoute, make_try_it_out_handler 

22from .handlers import HttpHandler, get 

23from .response import AsgiResponse, JSONResponse 

24from .websocket import WebSocketClose 

25 

26if TYPE_CHECKING: 

27 from types import FrameType 

28 

29 from anyio.abc import TaskStatus 

30 from fast_depends.library.serializer import SerializerProto 

31 

32 from faststream._internal.basic_types import ( 

33 AnyCallable, 

34 Lifespan, 

35 LoggerProto, 

36 SettingField, 

37 ) 

38 from faststream._internal.broker import BrokerUsecase 

39 from faststream.specification.base import SpecificationFactory 

40 

41 class UvicornServerProtocol(Protocol): 

42 should_exit: bool 

43 force_exit: bool 

44 

45 def handle_exit(self, sig: int, frame: FrameType | None) -> None: ... 

46 

47 from .types import ASGIApp, Receive, Scope, Send 

48 

49 

50class ServerState(Protocol): 

51 extra_options: dict[str, "SettingField"] 

52 

53 @abstractmethod 

54 def stop(self) -> None: ... 

55 

56 

57class OuterRunState(ServerState): 

58 def __init__(self) -> None: 

59 self.extra_options = {} 

60 

61 def stop(self) -> None: 

62 # TODO: resend signal to outer uvicorn 

63 pass 

64 

65 

66class CliRunState(ServerState): 

67 def __init__( 

68 self, 

69 server: "UvicornServerProtocol", 

70 extra_options: dict[str, "SettingField"], 

71 ) -> None: 

72 self.server = server 

73 self.extra_options = extra_options 

74 

75 def stop(self) -> None: 

76 self.server.should_exit = True 

77 

78 

79def cast_uvicorn_params(params: dict[str, Any]) -> dict[str, Any]: 

80 if port := params.get("port"): 

81 params["port"] = int(port) 

82 if fd := params.get("fd"): 

83 params["fd"] = int(fd) 

84 if (access_log := params.get("access_log", EMPTY)) is not EMPTY: 

85 params["access_log"] = access_log.lower() not in {"false", ""} 

86 return params 

87 

88 

89class AsgiFastStream(Application): 

90 _server: ServerState 

91 

92 def __init__( 

93 self, 

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

95 asgi_routes: Sequence[tuple[str, "ASGIApp"]] = (), 

96 logger: Optional["LoggerProto"] = logger, 

97 provider: Provider | None = None, 

98 serializer: Optional["SerializerProto"] = EMPTY, 

99 context: ContextRepo | None = None, 

100 lifespan: Optional["Lifespan"] = None, 

101 on_startup: Sequence["AnyCallable"] = (), 

102 after_startup: Sequence["AnyCallable"] = (), 

103 on_shutdown: Sequence["AnyCallable"] = (), 

104 after_shutdown: Sequence["AnyCallable"] = (), 

105 specification: Optional["SpecificationFactory"] = None, 

106 asyncapi_path: str | AsyncAPIRoute | None = None, 

107 ) -> None: 

108 self.routes = list(asgi_routes) 

109 

110 super().__init__( 

111 *brokers, 

112 logger=logger, 

113 config=FastDependsConfig( 

114 provider=provider or dependency_provider, 

115 context=context or ContextRepo(), 

116 serializer=serializer, 

117 ), 

118 lifespan=lifespan, 

119 on_startup=on_startup, 

120 after_startup=after_startup, 

121 on_shutdown=on_shutdown, 

122 after_shutdown=after_shutdown, 

123 specification=specification, 

124 ) 

125 

126 if asyncapi_path: 

127 asyncapi_route = AsyncAPIRoute.ensure_route(asyncapi_path) 

128 handler = asyncapi_route(self.schema) 

129 handler.set_logger(logger) 

130 self.routes.append((asyncapi_route.path, handler)) 

131 

132 if asyncapi_route.asyncapi_json_path: 

133 

134 @get(include_in_schema=asyncapi_route.include_in_schema) 

135 async def json_handler(scope: "Scope") -> AsgiResponse: # ruff: ignore[unused-function-argument] 

136 return JSONResponse(self.schema.to_specification().to_jsonable()) 

137 

138 self.routes.append((asyncapi_route.asyncapi_json_path, json_handler)) 

139 

140 if asyncapi_route.try_it_out_path is not None and self.brokers: 

141 try_it_out_route = make_try_it_out_handler( 

142 self.brokers, 

143 include_in_schema=asyncapi_route.include_in_schema, 

144 ) 

145 try_it_out_route.update_fd_config(self.config) 

146 try_it_out_route.set_logger(logger) 

147 

148 self.routes.append(( 

149 asyncapi_route.try_it_out_path, 

150 try_it_out_route, 

151 )) 

152 

153 self._server = OuterRunState() 

154 

155 self._log_level: int = logging.INFO 

156 self._run_extra_options: dict[str, SettingField] = {} 

157 

158 def _init_setupable_( # ruff: ignore[bad-dunder-method-name] 

159 self, 

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

161 specification: Optional["SpecificationFactory"] = None, 

162 config: Optional["FastDependsConfig"] = None, 

163 ) -> None: 

164 super()._init_setupable_(*brokers, specification=specification, config=config) 

165 for route in self.routes: 

166 self._register_route(route) 

167 

168 @classmethod 

169 def from_app( 

170 cls, 

171 app: Application, 

172 asgi_routes: Sequence[tuple[str, "ASGIApp"]], 

173 asyncapi_path: str | AsyncAPIRoute | None = None, 

174 ) -> Self: 

175 asgi_app = cls( 

176 *app.brokers, 

177 asgi_routes=asgi_routes, 

178 asyncapi_path=asyncapi_path, 

179 logger=app.logger, 

180 lifespan=None, 

181 ) 

182 asgi_app.lifespan_context = app.lifespan_context 

183 asgi_app._on_startup_calling = app._on_startup_calling 

184 asgi_app._after_startup_calling = app._after_startup_calling 

185 asgi_app._on_shutdown_calling = app._on_shutdown_calling 

186 asgi_app._after_shutdown_calling = app._after_shutdown_calling 

187 return asgi_app 

188 

189 def mount(self, path: str, route: "ASGIApp") -> None: 

190 asgi_route = (path, route) 

191 self.routes.append(asgi_route) 

192 self._register_route(asgi_route) 

193 

194 def _register_route(self, asgi_route: tuple[str, "ASGIApp"]) -> None: 

195 path, route = asgi_route 

196 if isinstance(route, HttpHandler): 

197 self.schema.add_http_route(path, route) 

198 route.update_fd_config(self.config) 

199 route.set_logger(self.logger) 

200 

201 async def __call__( 

202 self, 

203 scope: "Scope", 

204 receive: "Receive", 

205 send: "Send", 

206 ) -> None: 

207 """ASGI implementation.""" 

208 if scope["type"] == "lifespan": 

209 await self.lifespan(scope, receive, send) 

210 return 

211 

212 if scope["type"] == "http": 

213 for path, app in self.routes: 

214 if scope["path"] == path: 

215 await app(scope, receive, send) 

216 return 

217 

218 await self.not_found(scope, receive, send) 

219 return 

220 

221 async def run( 

222 self, 

223 log_level: int = logging.INFO, 

224 run_extra_options: dict[str, "SettingField"] | None = None, 

225 ) -> None: 

226 if not HAS_UVICORN: 

227 raise ImportError(INSTALL_UVICORN) 

228 

229 self._log_level = log_level 

230 self._run_extra_options = cast_uvicorn_params(run_extra_options or {}) 

231 

232 config = uvicorn.Config( 

233 app=self, 

234 log_level=self._log_level, 

235 **{ 

236 key: v 

237 for key, v in self._run_extra_options.items() 

238 if key in set(inspect.signature(uvicorn.Config).parameters.keys()) 

239 }, 

240 ) 

241 

242 server = uvicorn.Server(config) 

243 await server.serve() 

244 

245 def exit(self) -> None: 

246 """Manual stop method.""" 

247 self._server.stop() 

248 

249 @asynccontextmanager 

250 async def start_lifespan_context( 

251 self, 

252 run_extra_options: dict[str, "SettingField"] | None = None, 

253 ) -> AsyncGenerator[None, None]: 

254 run_extra_options = run_extra_options or self._run_extra_options 

255 

256 async with self.lifespan_context(**run_extra_options): 

257 try: 

258 async with anyio.create_task_group() as tg: 

259 await tg.start(self.__start, logging.INFO, run_extra_options) 

260 

261 try: 

262 yield 

263 finally: 

264 await self._shutdown() 

265 tg.cancel_scope.cancel() 

266 

267 except ExceptionGroup as e: 

268 for ex in e.exceptions: 

269 raise ex from ex.__cause__ 

270 

271 async def __start( 

272 self, 

273 log_level: int, 

274 run_extra_options: dict[str, "SettingField"], 

275 *, 

276 task_status: "TaskStatus[None]" = anyio.TASK_STATUS_IGNORED, 

277 ) -> None: 

278 """Redefenition of `_startup` method. 

279 

280 Waits for hooks run before broker start. 

281 """ 

282 async with ( 

283 self._startup_logging(log_level=log_level), 

284 self._start_hooks_context(**run_extra_options), 

285 ): 

286 task_status.started() 

287 await self._start_broker() 

288 

289 async def lifespan(self, scope: "Scope", receive: "Receive", send: "Send") -> None: 

290 """Handle ASGI lifespan messages to start and shutdown the app.""" 

291 started = False 

292 await receive() # handle `lifespan.startup` event 

293 

294 async def process_exception(ex: BaseException) -> None: 

295 exc_text = traceback.format_exc() 

296 if started: 296 ↛ 297line 296 didn't jump to line 297 because the condition on line 296 was never true

297 await send({"type": "lifespan.shutdown.failed", "message": exc_text}) 

298 else: 

299 await send({"type": "lifespan.startup.failed", "message": exc_text}) 

300 raise ex 

301 

302 try: 

303 async with self.start_lifespan_context(): 

304 await send({"type": "lifespan.startup.complete"}) 

305 started = True 

306 await receive() # handle `lifespan.shutdown` event 

307 

308 except StartupValidationError as startup_exc: 

309 # Process `on_startup` and `lifespan` missed extra options 

310 if HAS_TYPER: 

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

312 

313 draw_startup_errors(startup_exc) 

314 await send({"type": "lifespan.startup.failed", "message": ""}) 

315 

316 else: 

317 await process_exception(startup_exc) 

318 

319 except BaseException as base_exc: 

320 await process_exception(base_exc) 

321 

322 else: 

323 await send({"type": "lifespan.shutdown.complete"}) 

324 

325 async def not_found(self, scope: "Scope", receive: "Receive", send: "Send") -> None: # ruff: ignore[no-self-use] 

326 not_found_msg = "Application doesn't support regular HTTP protocol." 

327 

328 if scope["type"] == "websocket": 

329 websocket_close = WebSocketClose( 

330 code=1000, 

331 reason=not_found_msg, 

332 ) 

333 await websocket_close(scope, receive, send) 

334 return 

335 

336 response = AsgiResponse( 

337 body=not_found_msg.encode(), 

338 status_code=404, 

339 ) 

340 

341 await response(scope, receive, send)