Debian Codegraph @

debian/vendor/hypercorn/trio/lifespan.py

raw
1 from __future__ import annotations
2
3 import trio
4
5 from ..config import Config
6 from ..typing import AppWrapper, ASGIReceiveEvent, ASGISendEvent, LifespanScope
7 from ..utils import LifespanFailureError, LifespanTimeoutError
8
9
10 class UnexpectedMessageError(Exception):
11 pass
12
13
14 class Lifespan:
15 def __init__(self, app: AppWrapper, config: Config) -> None:
16 self.app = app
17 self.config = config
18 self.startup = trio.Event()
19 self.shutdown = trio.Event()
20 self.app_send_channel, self.app_receive_channel = trio.open_memory_channel(
21 config.max_app_queue_size
22 )
23 self.supported = True
24
25 async def handle_lifespan(
26 self, *, task_status: trio._core._run._TaskStatus = trio.TASK_STATUS_IGNORED
27 ) -> None:
28 task_status.started()
29 scope: LifespanScope = {
30 "type": "lifespan",
31 "asgi": {"spec_version": "2.0", "version": "3.0"},
32 }
33 try:
34 await self.app(
35 scope,
36 self.asgi_receive,
37 self.asgi_send,
38 trio.to_thread.run_sync,
39 trio.from_thread.run,
40 )
41 except LifespanFailureError:
42 # Lifespan failures should crash the server
43 raise
44 except Exception:
45 self.supported = False
46 if not self.startup.is_set():
47 await self.config.log.warning(
48 "ASGI Framework Lifespan error, continuing without Lifespan support"
49 )
50 elif not self.shutdown.is_set():
51 await self.config.log.exception(
52 "ASGI Framework Lifespan error, shutdown without Lifespan support"
53 )
54 else:
55 await self.config.log.exception("ASGI Framework Lifespan errored after shutdown.")
56 finally:
57 self.startup.set()
58 self.shutdown.set()
59 await self.app_send_channel.aclose()
60 await self.app_receive_channel.aclose()
61
62 async def wait_for_startup(self) -> None:
63 if not self.supported:
64 return
65
66 await self.app_send_channel.send({"type": "lifespan.startup"})
67 try:
68 with trio.fail_after(self.config.startup_timeout):
69 await self.startup.wait()
70 except trio.TooSlowError as error:
71 raise LifespanTimeoutError("startup") from error
72
73 async def wait_for_shutdown(self) -> None:
74 if not self.supported:
75 return
76
77 await self.app_send_channel.send({"type": "lifespan.shutdown"})
78 try:
79 with trio.fail_after(self.config.shutdown_timeout):
80 await self.shutdown.wait()
81 except trio.TooSlowError as error:
82 raise LifespanTimeoutError("startup") from error
83
84 async def asgi_receive(self) -> ASGIReceiveEvent:
85 return await self.app_receive_channel.receive()
86
87 async def asgi_send(self, message: ASGISendEvent) -> None:
88 if message["type"] == "lifespan.startup.complete":
89 self.startup.set()
90 elif message["type"] == "lifespan.shutdown.complete":
91 self.shutdown.set()
92 elif message["type"] == "lifespan.startup.failed":
93 raise LifespanFailureError("startup", message.get("message", ""))
94 elif message["type"] == "lifespan.shutdown.failed":
95 raise LifespanFailureError("shutdown", message.get("message", ""))
96 else:
97 raise UnexpectedMessageError(message["type"])