| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import inspect |
| 4 |
import os |
| 5 |
import socket |
| 6 |
import sys |
| 7 |
import time |
| 8 |
from enum import Enum |
| 9 |
from importlib import import_module |
| 10 |
from multiprocessing.synchronize import Event as EventType |
| 11 |
from pathlib import Path |
| 12 |
from typing import ( |
| 13 |
Any, |
| 14 |
Awaitable, |
| 15 |
Callable, |
| 16 |
cast, |
| 17 |
Dict, |
| 18 |
Iterable, |
| 19 |
List, |
| 20 |
Literal, |
| 21 |
Optional, |
| 22 |
Tuple, |
| 23 |
TYPE_CHECKING, |
| 24 |
) |
| 25 |
|
| 26 |
from .app_wrappers import ASGIWrapper, WSGIWrapper |
| 27 |
from .config import Config |
| 28 |
from .typing import AppWrapper, ASGIFramework, Framework, WSGIFramework |
| 29 |
|
| 30 |
if TYPE_CHECKING: |
| 31 |
from .protocol.events import Request |
| 32 |
|
| 33 |
|
| 34 |
class ShutdownError(Exception): |
| 35 |
pass |
| 36 |
|
| 37 |
|
| 38 |
class NoAppError(Exception): |
| 39 |
pass |
| 40 |
|
| 41 |
|
| 42 |
class LifespanTimeoutError(Exception): |
| 43 |
def __init__(self, stage: str) -> None: |
| 44 |
super().__init__( |
| 45 |
f"Timeout whilst awaiting {stage}. Your application may not support the ASGI Lifespan " |
| 46 |
f"protocol correctly, alternatively the {stage}_timeout configuration is incorrect." |
| 47 |
) |
| 48 |
|
| 49 |
|
| 50 |
class LifespanFailureError(Exception): |
| 51 |
def __init__(self, stage: str, message: str) -> None: |
| 52 |
super().__init__(f"Lifespan failure in {stage}. '{message}'") |
| 53 |
|
| 54 |
|
| 55 |
class UnexpectedMessageError(Exception): |
| 56 |
def __init__(self, state: Enum, message_type: str) -> None: |
| 57 |
super().__init__(f"Unexpected message type, {message_type} given the state {state}") |
| 58 |
|
| 59 |
|
| 60 |
class FrameTooLargeError(Exception): |
| 61 |
pass |
| 62 |
|
| 63 |
|
| 64 |
def suppress_body(method: str, status_code: int) -> bool: |
| 65 |
return method == "HEAD" or 100 <= status_code < 200 or status_code in {204, 304} |
| 66 |
|
| 67 |
|
| 68 |
def build_and_validate_headers(headers: Iterable[Tuple[bytes, bytes]]) -> List[Tuple[bytes, bytes]]: |
| 69 |
# Validates that the header name and value are bytes |
| 70 |
validated_headers: List[Tuple[bytes, bytes]] = [] |
| 71 |
for name, value in headers: |
| 72 |
if name[0] == b":"[0]: |
| 73 |
raise ValueError("Pseudo headers are not valid") |
| 74 |
validated_headers.append((bytes(name).strip(), bytes(value).strip())) |
| 75 |
return validated_headers |
| 76 |
|
| 77 |
|
| 78 |
def filter_pseudo_headers(headers: List[Tuple[bytes, bytes]]) -> List[Tuple[bytes, bytes]]: |
| 79 |
filtered_headers: List[Tuple[bytes, bytes]] = [(b"host", b"")] # Placeholder |
| 80 |
authority = None |
| 81 |
host = b"" |
| 82 |
for name, value in headers: |
| 83 |
if name == b":authority": # h2 & h3 libraries validate this is present |
| 84 |
authority = value |
| 85 |
elif name == b"host": |
| 86 |
host = value |
| 87 |
elif name[0] != b":"[0]: |
| 88 |
filtered_headers.append((name, value)) |
| 89 |
filtered_headers[0] = (b"host", authority if authority is not None else host) |
| 90 |
return filtered_headers |
| 91 |
|
| 92 |
|
| 93 |
def load_application(path: str, wsgi_max_body_size: int) -> AppWrapper: |
| 94 |
mode: Optional[Literal["asgi", "wsgi"]] = None |
| 95 |
if ":" not in path: |
| 96 |
module_name, app_name = path, "app" |
| 97 |
elif path.count(":") == 2: |
| 98 |
mode, module_name, app_name = path.split(":", 2) # type: ignore |
| 99 |
if mode not in {"asgi", "wsgi"}: |
| 100 |
raise ValueError("Invalid mode, must be 'asgi', or 'wsgi'") |
| 101 |
else: |
| 102 |
module_name, app_name = path.split(":", 1) |
| 103 |
|
| 104 |
module_path = Path(module_name).resolve() |
| 105 |
sys.path.insert(0, str(module_path.parent)) |
| 106 |
if module_path.is_file(): |
| 107 |
import_name = module_path.with_suffix("").name |
| 108 |
else: |
| 109 |
import_name = module_path.name |
| 110 |
try: |
| 111 |
module = import_module(import_name) |
| 112 |
except ModuleNotFoundError as error: |
| 113 |
if error.name == import_name: |
| 114 |
raise NoAppError(f"Cannot load application from '{path}', module not found.") |
| 115 |
else: |
| 116 |
raise |
| 117 |
try: |
| 118 |
app = eval(app_name, vars(module)) |
| 119 |
except NameError: |
| 120 |
raise NoAppError(f"Cannot load application from '{path}', application not found.") |
| 121 |
else: |
| 122 |
return wrap_app(app, wsgi_max_body_size, mode) |
| 123 |
|
| 124 |
|
| 125 |
def wrap_app( |
| 126 |
app: Framework, wsgi_max_body_size: int, mode: Optional[Literal["asgi", "wsgi"]] |
| 127 |
) -> AppWrapper: |
| 128 |
if mode is None: |
| 129 |
mode = "asgi" if is_asgi(app) else "wsgi" |
| 130 |
if mode == "asgi": |
| 131 |
return ASGIWrapper(cast(ASGIFramework, app)) |
| 132 |
else: |
| 133 |
return WSGIWrapper(cast(WSGIFramework, app), wsgi_max_body_size) |
| 134 |
|
| 135 |
|
| 136 |
def wait_for_changes(shutdown_event: EventType) -> None: |
| 137 |
last_updates: Dict[Path, float] = {} |
| 138 |
for module in list(sys.modules.values()): |
| 139 |
filename = getattr(module, "__file__", None) |
| 140 |
if filename is None: |
| 141 |
continue |
| 142 |
path = Path(filename) |
| 143 |
try: |
| 144 |
last_updates[Path(filename)] = path.stat().st_mtime |
| 145 |
except (FileNotFoundError, NotADirectoryError): |
| 146 |
pass |
| 147 |
|
| 148 |
while not shutdown_event.is_set(): |
| 149 |
time.sleep(1) |
| 150 |
|
| 151 |
for index, (path, last_mtime) in enumerate(last_updates.items()): |
| 152 |
if index % 10 == 0: |
| 153 |
# Yield to the event loop |
| 154 |
time.sleep(0) |
| 155 |
|
| 156 |
try: |
| 157 |
mtime = path.stat().st_mtime |
| 158 |
except FileNotFoundError: |
| 159 |
return |
| 160 |
else: |
| 161 |
if mtime > last_mtime: |
| 162 |
return |
| 163 |
else: |
| 164 |
last_updates[path] = mtime |
| 165 |
|
| 166 |
|
| 167 |
async def raise_shutdown(shutdown_event: Callable[..., Awaitable]) -> None: |
| 168 |
await shutdown_event() |
| 169 |
raise ShutdownError() |
| 170 |
|
| 171 |
|
| 172 |
async def check_multiprocess_shutdown_event( |
| 173 |
shutdown_event: EventType, sleep: Callable[[float], Awaitable[Any]] |
| 174 |
) -> None: |
| 175 |
while True: |
| 176 |
if shutdown_event.is_set(): |
| 177 |
return |
| 178 |
await sleep(0.1) |
| 179 |
|
| 180 |
|
| 181 |
def write_pid_file(pid_path: str) -> None: |
| 182 |
with open(pid_path, "w") as file_: |
| 183 |
file_.write(f"{os.getpid()}") |
| 184 |
|
| 185 |
|
| 186 |
def parse_socket_addr(family: int, address: tuple) -> Optional[Tuple[str, int]]: |
| 187 |
if family == socket.AF_INET: |
| 188 |
return address # type: ignore |
| 189 |
elif family == socket.AF_INET6: |
| 190 |
return (address[0], address[1]) |
| 191 |
else: |
| 192 |
return None |
| 193 |
|
| 194 |
|
| 195 |
def repr_socket_addr(family: int, address: tuple) -> str: |
| 196 |
if family == socket.AF_INET: |
| 197 |
return f"{address[0]}:{address[1]}" |
| 198 |
elif family == socket.AF_INET6: |
| 199 |
return f"[{address[0]}]:{address[1]}" |
| 200 |
elif family == socket.AF_UNIX: |
| 201 |
return f"unix:{address}" |
| 202 |
else: |
| 203 |
return f"{address}" |
| 204 |
|
| 205 |
|
| 206 |
def valid_server_name(config: Config, request: "Request") -> bool: |
| 207 |
if len(config.server_names) == 0: |
| 208 |
return True |
| 209 |
|
| 210 |
host = "" |
| 211 |
for name, value in request.headers: |
| 212 |
if name.lower() == b"host": |
| 213 |
host = value.decode() |
| 214 |
break |
| 215 |
return host in config.server_names |
| 216 |
|
| 217 |
|
| 218 |
def is_asgi(app: Any) -> bool: |
| 219 |
if inspect.iscoroutinefunction(app): |
| 220 |
return True |
| 221 |
elif hasattr(app, "__call__"): |
| 222 |
return inspect.iscoroutinefunction(app.__call__) |
| 223 |
return False |