1
from __future__ import annotations
6
from collections.abc import AsyncGenerator, Awaitable, Callable, Generator
7
from contextlib import AbstractAsyncContextManager, asynccontextmanager
8
from dataclasses import dataclass
9
from ipaddress import AddressValueError, IPv6Address
10
from typing import Any, Generic, Protocol, TypeVar, overload
14
from starlette.types import Scope
16
if sys.version_info >= (3, 13): # pragma: no cover
17
from inspect import iscoroutinefunction
18
from typing import TypeIs
19
else: # pragma: no cover
20
from asyncio import iscoroutinefunction
22
from typing_extensions import TypeIs
24
if sys.version_info < (3, 11): # pragma: no cover
25
from exceptiongroup import BaseExceptionGroup
29
AwaitableCallable = Callable[..., Awaitable[T]]
31
# Reject characters that could make a Host header change the URL path or authority.
32
_HOST_RE = re.compile(
33
r"^(?P<host>[a-z0-9._~%!$&'()*+,;=-]+|\[(?:(?P<ipv6>[a-f0-9]*:[a-f0-9.:]+)|"
34
r"(?-i:v)[a-f0-9]+\.[a-z0-9._~!$&'()*+,;=:-]+)\])(?::(?P<port>[0-9]+))?$",
39
@dataclass(frozen=True, slots=True)
45
def authority(self) -> str:
46
return self.host if self.port is None else f"{self.host}:{self.port}"
49
def is_valid_port(self) -> bool:
52
port = self.port.lstrip("0")
53
return len(port) <= 5 and int(port or "0") <= 65535
57
def is_async_callable(obj: AwaitableCallable[T]) -> TypeIs[AwaitableCallable[T]]: ...
61
def is_async_callable(obj: Any) -> TypeIs[AwaitableCallable[Any]]: ...
64
def is_async_callable(obj: Any) -> Any:
65
while isinstance(obj, functools.partial):
68
return iscoroutinefunction(obj) or (callable(obj) and iscoroutinefunction(obj.__call__))
71
T_co = TypeVar("T_co", covariant=True)
74
class AwaitableOrContextManager(
75
Awaitable[T_co], AbstractAsyncContextManager[T_co], Protocol[T_co]
76
): ... # pragma: no branch
79
class SupportsAsyncClose(Protocol):
80
async def close(self) -> None: ... # pragma: no cover
83
SupportsAsyncCloseType = TypeVar("SupportsAsyncCloseType", bound=SupportsAsyncClose, covariant=False)
86
class AwaitableOrContextManagerWrapper(Generic[SupportsAsyncCloseType]):
87
__slots__ = ("aw", "entered")
89
def __init__(self, aw: Awaitable[SupportsAsyncCloseType]) -> None:
92
def __await__(self) -> Generator[Any, None, SupportsAsyncCloseType]:
93
return self.aw.__await__()
95
async def __aenter__(self) -> SupportsAsyncCloseType:
96
8
self.entered = await self.aw
99
async def __aexit__(self, *args: Any) -> None | bool:
100
await self.entered.close()
105
async def create_collapsing_task_group() -> AsyncGenerator[anyio.abc.TaskGroup, None]:
107
async with anyio.create_task_group() as tg:
109
except BaseExceptionGroup as excs:
110
if len(excs.exceptions) != 1:
113
exc = excs.exceptions[0]
114
context = None if exc.__suppress_context__ else exc.__context__
115
raise exc from exc.__cause__ or context
118
def parse_host_header(host_header: str | None) -> ParsedHost | None:
119
"""Parse `host_header` into its host and port components.
121
The host preserves brackets around IP literals. Invalid headers produce `None`.
123
if host_header is None:
126
match = _HOST_RE.fullmatch(host_header)
134
except AddressValueError:
137
return ParsedHost(match["host"], match["port"])
140
def get_route_path(scope: Scope) -> str:
141
path: str = scope["path"]
142
root_path = scope.get("root_path", "")
146
if not path.startswith(root_path):
149
if path == root_path:
152
if path[len(root_path)] == "/":
153
return path[len(root_path) :]