Debian Codegraph @

debian/vendor/hypercorn/asyncio/lifespan.py

raw
1 from __future__ import annotations
2
3 import asyncio
4 from functools import partial
5 from typing import Any, Callable
6
7 from ..config import Config
8 from ..typing import AppWrapper, ASGIReceiveEvent, ASGISendEvent, LifespanScope
9 from ..utils import LifespanFailureError, LifespanTimeoutError
10
11
12 class UnexpectedMessageError(Exception):
13 pass
14
15
16 class Lifespan:
17 def __init__(self, app: AppWrapper, config: Config, loop: asyncio.AbstractEventLoop) -> None:
18 self.app = app
19 self.config = config
20 self.startup = asyncio.Event()
21 self.shutdown = asyncio.Event()
22 self.app_queue: asyncio.Queue = asyncio.Queue(config.max_app_queue_size)
23 self.supported = True
24 self.loop = loop
25
26 # This mimics the Trio nursery.start task_status and is
27 # required to ensure the support has been checked before
28 # waiting on timeouts.
29 self._started = asyncio.Event()
30
31 async def handle_lifespan(self) -> None:
32 self._started.set()
33 scope: LifespanScope = {
34 "type": "lifespan",
35 "asgi": {"spec_version": "2.0", "version": "3.0"},
36 }
37
38 def _call_soon(func: Callable, *args: Any) -> Any:
39 future = asyncio.run_coroutine_threadsafe(func(*args), self.loop)
40 return future.result()
41
42 try:
43 await self.app(
44 scope,
45 self.asgi_receive,
46 self.asgi_send,
47 partial(self.loop.run_in_executor, None),
48 _call_soon,
49 )
50 except LifespanFailureError:
51 # Lifespan failures should crash the server
52 raise
53 except Exception:
54 self.supported = False
55 if not self.startup.is_set():
56 await self.config.log.warning(
57 "ASGI Framework Lifespan error, continuing without Lifespan support"
58 )
59 elif not self.shutdown.is_set():
60 await self.config.log.exception(
61 "ASGI Framework Lifespan error, shutdown without Lifespan support"
62 )
63 else:
64 await self.config.log.exception("ASGI Framework Lifespan errored after shutdown.")
65 finally:
66 self.startup.set()
67 self.shutdown.set()
68
69 async def wait_for_startup(self) -> None:
70 await self._started.wait()
71 if not self.supported:
72 return
73
74 await self.app_queue.put({"type": "lifespan.startup"})
75 try:
76 await asyncio.wait_for(self.startup.wait(), timeout=self.config.startup_timeout)
77 except asyncio.TimeoutError as error:
78 raise LifespanTimeoutError("startup") from error
79
80 async def wait_for_shutdown(self) -> None:
81 await self._started.wait()
82 if not self.supported:
83 return
84
85 await self.app_queue.put({"type": "lifespan.shutdown"})
86 try:
87 await asyncio.wait_for(self.shutdown.wait(), timeout=self.config.shutdown_timeout)
88 except asyncio.TimeoutError as error:
89 raise LifespanTimeoutError("shutdown") from error
90
91 async def asgi_receive(self) -> ASGIReceiveEvent:
92 return await self.app_queue.get()
93
94 async def asgi_send(self, message: ASGISendEvent) -> None:
95 if message["type"] == "lifespan.startup.complete":
96 self.startup.set()
97 elif message["type"] == "lifespan.shutdown.complete":
98 self.shutdown.set()
99 elif message["type"] == "lifespan.startup.failed":
100 self.startup.set()
101 raise LifespanFailureError("startup", message.get("message", ""))
102 elif message["type"] == "lifespan.shutdown.failed":
103 self.shutdown.set()
104 raise LifespanFailureError("shutdown", message.get("message", ""))
105 else:
106 raise UnexpectedMessageError(message["type"])