pboot-kernel 1.10.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- kernel/__init__.py +1 -0
- kernel/_exception_handler.py +67 -0
- kernel/_utils.py +152 -0
- kernel/applications.py +124 -0
- kernel/authentication.py +157 -0
- kernel/background.py +36 -0
- kernel/concurrency.py +59 -0
- kernel/config.py +142 -0
- kernel/convertors.py +89 -0
- kernel/datastructures.py +717 -0
- kernel/endpoints.py +128 -0
- kernel/exceptions.py +43 -0
- kernel/formparsers.py +289 -0
- kernel/middleware/__init__.py +37 -0
- kernel/middleware/authentication.py +52 -0
- kernel/middleware/base.py +254 -0
- kernel/middleware/body_limit.py +132 -0
- kernel/middleware/cors.py +177 -0
- kernel/middleware/errors.py +259 -0
- kernel/middleware/exceptions.py +73 -0
- kernel/middleware/gzip.py +230 -0
- kernel/middleware/httpsredirect.py +22 -0
- kernel/middleware/opentelemetry.py +126 -0
- kernel/middleware/sessions.py +139 -0
- kernel/middleware/trustedhost.py +66 -0
- kernel/middleware/wsgi.py +157 -0
- kernel/py.typed +0 -0
- kernel/requests.py +357 -0
- kernel/responses.py +616 -0
- kernel/routing.py +772 -0
- kernel/schemas.py +152 -0
- kernel/staticfiles.py +231 -0
- kernel/status.py +211 -0
- kernel/templating.py +156 -0
- kernel/testclient.py +624 -0
- kernel/types.py +26 -0
- kernel/websockets.py +202 -0
- pboot_kernel-1.10.0.1.dist-info/METADATA +95 -0
- pboot_kernel-1.10.0.1.dist-info/RECORD +41 -0
- pboot_kernel-1.10.0.1.dist-info/WHEEL +4 -0
- pboot_kernel-1.10.0.1.dist-info/licenses/LICENSE.md +27 -0
kernel/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "1.10.0.1"
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from kernel._utils import is_async_callable
|
|
6
|
+
from kernel.concurrency import run_in_threadpool
|
|
7
|
+
from kernel.exceptions import HTTPException
|
|
8
|
+
from kernel.requests import Request
|
|
9
|
+
from kernel.types import ASGIApp, ExceptionHandler, Message, Receive, Scope, Send
|
|
10
|
+
from kernel.websockets import WebSocket
|
|
11
|
+
|
|
12
|
+
ExceptionHandlers = dict[Any, ExceptionHandler]
|
|
13
|
+
StatusHandlers = dict[int, ExceptionHandler]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _lookup_exception_handler(exc_handlers: ExceptionHandlers, exc: Exception) -> ExceptionHandler | None:
|
|
17
|
+
for cls in type(exc).__mro__:
|
|
18
|
+
if cls in exc_handlers:
|
|
19
|
+
return exc_handlers[cls]
|
|
20
|
+
return None
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def wrap_app_handling_exceptions(app: ASGIApp, conn: Request | WebSocket) -> ASGIApp:
|
|
24
|
+
exception_handlers: ExceptionHandlers
|
|
25
|
+
status_handlers: StatusHandlers
|
|
26
|
+
try:
|
|
27
|
+
exception_handlers, status_handlers = conn.scope["starlette.exception_handlers"]
|
|
28
|
+
except KeyError:
|
|
29
|
+
exception_handlers, status_handlers = {}, {}
|
|
30
|
+
|
|
31
|
+
async def wrapped_app(scope: Scope, receive: Receive, send: Send) -> None:
|
|
32
|
+
response_started = False
|
|
33
|
+
|
|
34
|
+
async def sender(message: Message) -> None:
|
|
35
|
+
nonlocal response_started
|
|
36
|
+
|
|
37
|
+
if message["type"] == "http.response.start":
|
|
38
|
+
response_started = True
|
|
39
|
+
await send(message)
|
|
40
|
+
|
|
41
|
+
try:
|
|
42
|
+
await app(scope, receive, sender)
|
|
43
|
+
except Exception as exc:
|
|
44
|
+
handler = None
|
|
45
|
+
|
|
46
|
+
if isinstance(exc, HTTPException):
|
|
47
|
+
handler = status_handlers.get(exc.status_code)
|
|
48
|
+
|
|
49
|
+
if handler is None:
|
|
50
|
+
handler = _lookup_exception_handler(exception_handlers, exc)
|
|
51
|
+
|
|
52
|
+
if handler is None:
|
|
53
|
+
raise exc
|
|
54
|
+
|
|
55
|
+
if response_started:
|
|
56
|
+
raise RuntimeError("Caught handled exception, but response already started.") from exc
|
|
57
|
+
|
|
58
|
+
if is_async_callable(handler):
|
|
59
|
+
response = await handler(conn, exc) # type: ignore[arg-type]
|
|
60
|
+
else:
|
|
61
|
+
response = await run_in_threadpool(handler, conn, exc) # type: ignore[arg-type]
|
|
62
|
+
if response is not None:
|
|
63
|
+
await response(scope, receive, sender)
|
|
64
|
+
# Reused exception instances accumulate tracebacks across requests.
|
|
65
|
+
exc.__traceback__ = None
|
|
66
|
+
|
|
67
|
+
return wrapped_app
|
kernel/_utils.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import functools
|
|
4
|
+
import re
|
|
5
|
+
import sys
|
|
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
|
|
11
|
+
|
|
12
|
+
import anyio.abc
|
|
13
|
+
|
|
14
|
+
from kernel.types import Scope
|
|
15
|
+
|
|
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
|
|
21
|
+
|
|
22
|
+
from typing_extensions import TypeIs
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
T = TypeVar("T")
|
|
26
|
+
AwaitableCallable = Callable[..., Awaitable[T]]
|
|
27
|
+
|
|
28
|
+
# Reject characters that could make a Host header change the URL path or authority.
|
|
29
|
+
_HOST_RE = re.compile(
|
|
30
|
+
r"^(?P<host>[a-z0-9._~%!$&'()*+,;=-]+|\[(?:(?P<ipv6>[a-f0-9]*:[a-f0-9.:]+)|"
|
|
31
|
+
r"(?-i:v)[a-f0-9]+\.[a-z0-9._~!$&'()*+,;=:-]+)\])(?::(?P<port>[0-9]+))?$",
|
|
32
|
+
re.IGNORECASE,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True, slots=True)
|
|
37
|
+
class ParsedHost:
|
|
38
|
+
host: str
|
|
39
|
+
port: str | None
|
|
40
|
+
|
|
41
|
+
@property
|
|
42
|
+
def authority(self) -> str:
|
|
43
|
+
return self.host if self.port is None else f"{self.host}:{self.port}"
|
|
44
|
+
|
|
45
|
+
@property
|
|
46
|
+
def is_valid_port(self) -> bool:
|
|
47
|
+
if self.port is None:
|
|
48
|
+
return True
|
|
49
|
+
port = self.port.lstrip("0")
|
|
50
|
+
return len(port) <= 5 and int(port or "0") <= 65535
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@overload
|
|
54
|
+
def is_async_callable(obj: AwaitableCallable[T]) -> TypeIs[AwaitableCallable[T]]: ...
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@overload
|
|
58
|
+
def is_async_callable(obj: Any) -> TypeIs[AwaitableCallable[Any]]: ...
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def is_async_callable(obj: Any) -> Any:
|
|
62
|
+
while isinstance(obj, functools.partial):
|
|
63
|
+
obj = obj.func
|
|
64
|
+
|
|
65
|
+
return iscoroutinefunction(obj) or (callable(obj) and iscoroutinefunction(obj.__call__))
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
T_co = TypeVar("T_co", covariant=True)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class AwaitableOrContextManager(
|
|
72
|
+
Awaitable[T_co], AbstractAsyncContextManager[T_co], Protocol[T_co]
|
|
73
|
+
): ... # pragma: no branch
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class SupportsAsyncClose(Protocol):
|
|
77
|
+
async def close(self) -> None: ... # pragma: no cover
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
SupportsAsyncCloseType = TypeVar("SupportsAsyncCloseType", bound=SupportsAsyncClose, covariant=False)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class AwaitableOrContextManagerWrapper(Generic[SupportsAsyncCloseType]):
|
|
84
|
+
__slots__ = ("aw", "entered")
|
|
85
|
+
|
|
86
|
+
def __init__(self, aw: Awaitable[SupportsAsyncCloseType]) -> None:
|
|
87
|
+
self.aw = aw
|
|
88
|
+
|
|
89
|
+
def __await__(self) -> Generator[Any, None, SupportsAsyncCloseType]:
|
|
90
|
+
return self.aw.__await__()
|
|
91
|
+
|
|
92
|
+
async def __aenter__(self) -> SupportsAsyncCloseType:
|
|
93
|
+
self.entered = await self.aw
|
|
94
|
+
return self.entered
|
|
95
|
+
|
|
96
|
+
async def __aexit__(self, *args: Any) -> None | bool:
|
|
97
|
+
await self.entered.close()
|
|
98
|
+
return None
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@asynccontextmanager
|
|
102
|
+
async def create_collapsing_task_group() -> AsyncGenerator[anyio.abc.TaskGroup, None]:
|
|
103
|
+
try:
|
|
104
|
+
async with anyio.create_task_group() as tg:
|
|
105
|
+
yield tg
|
|
106
|
+
except BaseExceptionGroup as excs:
|
|
107
|
+
if len(excs.exceptions) != 1:
|
|
108
|
+
raise
|
|
109
|
+
|
|
110
|
+
exc = excs.exceptions[0]
|
|
111
|
+
context = None if exc.__suppress_context__ else exc.__context__
|
|
112
|
+
raise exc from exc.__cause__ or context
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def parse_host_header(host_header: str | None) -> ParsedHost | None:
|
|
116
|
+
"""Parse `host_header` into its host and port components.
|
|
117
|
+
|
|
118
|
+
The host preserves brackets around IP literals. Invalid headers produce `None`.
|
|
119
|
+
"""
|
|
120
|
+
if host_header is None:
|
|
121
|
+
return None
|
|
122
|
+
|
|
123
|
+
match = _HOST_RE.fullmatch(host_header)
|
|
124
|
+
if match is None:
|
|
125
|
+
return None
|
|
126
|
+
|
|
127
|
+
ipv6 = match["ipv6"]
|
|
128
|
+
if ipv6 is not None:
|
|
129
|
+
try:
|
|
130
|
+
IPv6Address(ipv6)
|
|
131
|
+
except AddressValueError:
|
|
132
|
+
return None
|
|
133
|
+
|
|
134
|
+
return ParsedHost(match["host"], match["port"])
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def get_route_path(scope: Scope) -> str:
|
|
138
|
+
path: str = scope["path"]
|
|
139
|
+
root_path = scope.get("root_path", "")
|
|
140
|
+
if not root_path:
|
|
141
|
+
return path
|
|
142
|
+
|
|
143
|
+
if not path.startswith(root_path):
|
|
144
|
+
return path
|
|
145
|
+
|
|
146
|
+
if path == root_path:
|
|
147
|
+
return ""
|
|
148
|
+
|
|
149
|
+
if path[len(root_path)] == "/":
|
|
150
|
+
return path[len(root_path) :]
|
|
151
|
+
|
|
152
|
+
return path
|
kernel/applications.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Awaitable, Callable, Mapping, Sequence
|
|
4
|
+
from typing import Any, ParamSpec, TypeVar
|
|
5
|
+
|
|
6
|
+
from kernel.datastructures import State, URLPath
|
|
7
|
+
from kernel.middleware import Middleware, _MiddlewareFactory
|
|
8
|
+
from kernel.middleware.body_limit import RequestBodyLimitMiddleware
|
|
9
|
+
from kernel.middleware.errors import ServerErrorMiddleware
|
|
10
|
+
from kernel.middleware.exceptions import ExceptionMiddleware
|
|
11
|
+
from kernel.requests import Request
|
|
12
|
+
from kernel.responses import Response
|
|
13
|
+
from kernel.routing import BaseRoute, Router
|
|
14
|
+
from kernel.types import ASGIApp, ExceptionHandler, Lifespan, Receive, Scope, Send
|
|
15
|
+
|
|
16
|
+
AppType = TypeVar("AppType", bound="Starlette")
|
|
17
|
+
P = ParamSpec("P")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Starlette:
|
|
21
|
+
"""Creates a Starlette application."""
|
|
22
|
+
|
|
23
|
+
def __init__(
|
|
24
|
+
self: AppType,
|
|
25
|
+
debug: bool = False,
|
|
26
|
+
routes: Sequence[BaseRoute] | None = None,
|
|
27
|
+
middleware: Sequence[Middleware] | None = None,
|
|
28
|
+
exception_handlers: Mapping[Any, ExceptionHandler] | None = None,
|
|
29
|
+
lifespan: Lifespan[AppType] | None = None,
|
|
30
|
+
*,
|
|
31
|
+
max_body_size: int | None = None,
|
|
32
|
+
) -> None:
|
|
33
|
+
"""Initializes the application.
|
|
34
|
+
|
|
35
|
+
Parameters:
|
|
36
|
+
debug: Boolean indicating if debug tracebacks should be returned on errors.
|
|
37
|
+
routes: A list of routes to serve incoming HTTP and WebSocket requests.
|
|
38
|
+
middleware: A list of middleware to run for every request. A starlette
|
|
39
|
+
application will always automatically include two middleware classes.
|
|
40
|
+
`ServerErrorMiddleware` is added as the very outermost middleware, to handle
|
|
41
|
+
any uncaught errors occurring anywhere in the entire stack.
|
|
42
|
+
`ExceptionMiddleware` is added as the very innermost middleware, to deal
|
|
43
|
+
with handled exception cases occurring in the routing or endpoints.
|
|
44
|
+
exception_handlers: A mapping of either integer status codes,
|
|
45
|
+
or exception class types onto callables which handle the exceptions.
|
|
46
|
+
Exception handler callables should be of the form
|
|
47
|
+
`handler(request, exc) -> response` and may be either standard functions, or
|
|
48
|
+
async functions.
|
|
49
|
+
lifespan: A lifespan context function, which can be used to perform
|
|
50
|
+
startup and shutdown tasks. This is a newer style that replaces the
|
|
51
|
+
`on_startup` and `on_shutdown` handlers. Use one or the other, not both.
|
|
52
|
+
max_body_size: Non-negative maximum total size in bytes of an HTTP request
|
|
53
|
+
body. The default, `None`, does not limit request body size.
|
|
54
|
+
"""
|
|
55
|
+
self.debug = debug
|
|
56
|
+
self.state = State()
|
|
57
|
+
self.router = Router(routes, lifespan=lifespan)
|
|
58
|
+
self.max_body_size = max_body_size
|
|
59
|
+
self.exception_handlers = {} if exception_handlers is None else dict(exception_handlers)
|
|
60
|
+
self.user_middleware = [] if middleware is None else list(middleware)
|
|
61
|
+
self.middleware_stack: ASGIApp | None = None
|
|
62
|
+
|
|
63
|
+
def build_middleware_stack(self) -> ASGIApp:
|
|
64
|
+
debug = self.debug
|
|
65
|
+
error_handler = None
|
|
66
|
+
exception_handlers: dict[Any, ExceptionHandler] = {}
|
|
67
|
+
|
|
68
|
+
for key, value in self.exception_handlers.items():
|
|
69
|
+
if key in (500, Exception):
|
|
70
|
+
error_handler = value
|
|
71
|
+
else:
|
|
72
|
+
exception_handlers[key] = value
|
|
73
|
+
|
|
74
|
+
middleware = [Middleware(ServerErrorMiddleware, handler=error_handler, debug=debug)]
|
|
75
|
+
if self.max_body_size is not None:
|
|
76
|
+
middleware.append(Middleware(RequestBodyLimitMiddleware, max_body_size=self.max_body_size))
|
|
77
|
+
middleware += self.user_middleware
|
|
78
|
+
middleware.append(Middleware(ExceptionMiddleware, handlers=exception_handlers, debug=debug))
|
|
79
|
+
|
|
80
|
+
app = self.router
|
|
81
|
+
for cls, args, kwargs in reversed(middleware):
|
|
82
|
+
app = cls(app, *args, **kwargs)
|
|
83
|
+
return app
|
|
84
|
+
|
|
85
|
+
@property
|
|
86
|
+
def routes(self) -> list[BaseRoute]:
|
|
87
|
+
return self.router.routes
|
|
88
|
+
|
|
89
|
+
def url_path_for(self, name: str, /, **path_params: Any) -> URLPath:
|
|
90
|
+
return self.router.url_path_for(name, **path_params)
|
|
91
|
+
|
|
92
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
93
|
+
scope["app"] = self
|
|
94
|
+
if self.middleware_stack is None:
|
|
95
|
+
self.middleware_stack = self.build_middleware_stack()
|
|
96
|
+
await self.middleware_stack(scope, receive, send)
|
|
97
|
+
|
|
98
|
+
def mount(self, path: str, app: ASGIApp, name: str | None = None) -> None:
|
|
99
|
+
self.router.mount(path, app=app, name=name) # pragma: no cover
|
|
100
|
+
|
|
101
|
+
def host(self, host: str, app: ASGIApp, name: str | None = None) -> None:
|
|
102
|
+
self.router.host(host, app=app, name=name) # pragma: no cover
|
|
103
|
+
|
|
104
|
+
def add_middleware(self, middleware_class: _MiddlewareFactory[P], *args: P.args, **kwargs: P.kwargs) -> None:
|
|
105
|
+
if self.middleware_stack is not None: # pragma: no cover
|
|
106
|
+
raise RuntimeError("Cannot add middleware after an application has started")
|
|
107
|
+
self.user_middleware.insert(0, Middleware(middleware_class, *args, **kwargs))
|
|
108
|
+
|
|
109
|
+
def add_exception_handler(
|
|
110
|
+
self,
|
|
111
|
+
exc_class_or_status_code: int | type[Exception],
|
|
112
|
+
handler: ExceptionHandler,
|
|
113
|
+
) -> None: # pragma: no cover
|
|
114
|
+
self.exception_handlers[exc_class_or_status_code] = handler
|
|
115
|
+
|
|
116
|
+
def add_route(
|
|
117
|
+
self,
|
|
118
|
+
path: str,
|
|
119
|
+
route: Callable[[Request], Awaitable[Response] | Response],
|
|
120
|
+
methods: list[str] | None = None,
|
|
121
|
+
name: str | None = None,
|
|
122
|
+
include_in_schema: bool = True,
|
|
123
|
+
) -> None: # pragma: no cover
|
|
124
|
+
self.router.add_route(path, route, methods=methods, name=name, include_in_schema=include_in_schema)
|
kernel/authentication.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import functools
|
|
4
|
+
import inspect
|
|
5
|
+
from collections.abc import Callable, Sequence
|
|
6
|
+
from typing import Any, ParamSpec
|
|
7
|
+
from urllib.parse import urlencode
|
|
8
|
+
|
|
9
|
+
from kernel._utils import is_async_callable
|
|
10
|
+
from kernel.exceptions import HTTPException
|
|
11
|
+
from kernel.requests import HTTPConnection, Request
|
|
12
|
+
from kernel.responses import RedirectResponse
|
|
13
|
+
from kernel.websockets import WebSocket
|
|
14
|
+
|
|
15
|
+
_P = ParamSpec("_P")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def has_required_scope(conn: HTTPConnection, scopes: Sequence[str]) -> bool:
|
|
19
|
+
for scope in scopes:
|
|
20
|
+
if scope not in conn.auth.scopes:
|
|
21
|
+
return False
|
|
22
|
+
return True
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def requires(
|
|
26
|
+
scopes: str | Sequence[str],
|
|
27
|
+
status_code: int = 403,
|
|
28
|
+
redirect: str | None = None,
|
|
29
|
+
) -> Callable[[Callable[_P, Any]], Callable[_P, Any]]:
|
|
30
|
+
scopes_list = [scopes] if isinstance(scopes, str) else list(scopes)
|
|
31
|
+
|
|
32
|
+
def decorator(
|
|
33
|
+
func: Callable[_P, Any],
|
|
34
|
+
) -> Callable[_P, Any]:
|
|
35
|
+
sig = inspect.signature(func)
|
|
36
|
+
for idx, parameter in enumerate(sig.parameters.values()):
|
|
37
|
+
if parameter.name == "request" or parameter.name == "websocket":
|
|
38
|
+
type_ = parameter.name
|
|
39
|
+
break
|
|
40
|
+
else:
|
|
41
|
+
raise Exception(f'No "request" or "websocket" argument on function "{func}"')
|
|
42
|
+
|
|
43
|
+
if type_ == "websocket":
|
|
44
|
+
# Handle websocket functions. (Always async)
|
|
45
|
+
@functools.wraps(func)
|
|
46
|
+
async def websocket_wrapper(*args: _P.args, **kwargs: _P.kwargs) -> None:
|
|
47
|
+
websocket = kwargs.get("websocket", args[idx] if idx < len(args) else None)
|
|
48
|
+
assert isinstance(websocket, WebSocket), (
|
|
49
|
+
"Parameter with name 'websocket' is required to be of type 'WebSocket'"
|
|
50
|
+
f" not '{type(websocket).__name__}'"
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
if not has_required_scope(websocket, scopes_list):
|
|
54
|
+
await websocket.close()
|
|
55
|
+
else:
|
|
56
|
+
await func(*args, **kwargs)
|
|
57
|
+
|
|
58
|
+
return websocket_wrapper
|
|
59
|
+
|
|
60
|
+
elif is_async_callable(func):
|
|
61
|
+
# Handle async request/response functions.
|
|
62
|
+
@functools.wraps(func)
|
|
63
|
+
async def async_wrapper(*args: _P.args, **kwargs: _P.kwargs) -> Any:
|
|
64
|
+
request = kwargs.get("request", args[idx] if idx < len(args) else None)
|
|
65
|
+
assert isinstance(request, Request), (
|
|
66
|
+
f"Parameter with name 'request' is required to be of type 'Request' not '{type(request).__name__}'"
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
if not has_required_scope(request, scopes_list):
|
|
70
|
+
if redirect is not None:
|
|
71
|
+
orig_request_qparam = urlencode({"next": str(request.url)})
|
|
72
|
+
next_url = f"{request.url_for(redirect)}?{orig_request_qparam}"
|
|
73
|
+
return RedirectResponse(url=next_url, status_code=303)
|
|
74
|
+
raise HTTPException(status_code=status_code)
|
|
75
|
+
return await func(*args, **kwargs)
|
|
76
|
+
|
|
77
|
+
return async_wrapper
|
|
78
|
+
|
|
79
|
+
else:
|
|
80
|
+
# Handle sync request/response functions.
|
|
81
|
+
@functools.wraps(func)
|
|
82
|
+
def sync_wrapper(*args: _P.args, **kwargs: _P.kwargs) -> Any:
|
|
83
|
+
request = kwargs.get("request", args[idx] if idx < len(args) else None)
|
|
84
|
+
assert isinstance(request, Request), (
|
|
85
|
+
f"Parameter with name 'request' is required to be of type 'Request' not '{type(request).__name__}'"
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
if not has_required_scope(request, scopes_list):
|
|
89
|
+
if redirect is not None:
|
|
90
|
+
orig_request_qparam = urlencode({"next": str(request.url)})
|
|
91
|
+
next_url = f"{request.url_for(redirect)}?{orig_request_qparam}"
|
|
92
|
+
return RedirectResponse(url=next_url, status_code=303)
|
|
93
|
+
raise HTTPException(status_code=status_code)
|
|
94
|
+
return func(*args, **kwargs)
|
|
95
|
+
|
|
96
|
+
return sync_wrapper
|
|
97
|
+
|
|
98
|
+
return decorator
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class AuthenticationError(Exception):
|
|
102
|
+
pass
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class AuthenticationBackend:
|
|
106
|
+
async def authenticate(self, conn: HTTPConnection) -> tuple[AuthCredentials, BaseUser] | None:
|
|
107
|
+
raise NotImplementedError() # pragma: no cover
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class AuthCredentials:
|
|
111
|
+
def __init__(self, scopes: Sequence[str] | None = None):
|
|
112
|
+
self.scopes = [] if scopes is None else list(scopes)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
class BaseUser:
|
|
116
|
+
@property
|
|
117
|
+
def is_authenticated(self) -> bool:
|
|
118
|
+
raise NotImplementedError() # pragma: no cover
|
|
119
|
+
|
|
120
|
+
@property
|
|
121
|
+
def display_name(self) -> str:
|
|
122
|
+
raise NotImplementedError() # pragma: no cover
|
|
123
|
+
|
|
124
|
+
@property
|
|
125
|
+
def identity(self) -> str:
|
|
126
|
+
raise NotImplementedError() # pragma: no cover
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
class SimpleUser(BaseUser):
|
|
130
|
+
def __init__(self, username: str) -> None:
|
|
131
|
+
self.username = username
|
|
132
|
+
|
|
133
|
+
@property
|
|
134
|
+
def is_authenticated(self) -> bool:
|
|
135
|
+
return True
|
|
136
|
+
|
|
137
|
+
@property
|
|
138
|
+
def display_name(self) -> str:
|
|
139
|
+
return self.username
|
|
140
|
+
|
|
141
|
+
@property
|
|
142
|
+
def identity(self) -> str:
|
|
143
|
+
return self.username
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
class UnauthenticatedUser(BaseUser):
|
|
147
|
+
@property
|
|
148
|
+
def is_authenticated(self) -> bool:
|
|
149
|
+
return False
|
|
150
|
+
|
|
151
|
+
@property
|
|
152
|
+
def display_name(self) -> str:
|
|
153
|
+
return ""
|
|
154
|
+
|
|
155
|
+
@property
|
|
156
|
+
def identity(self) -> str:
|
|
157
|
+
return ""
|
kernel/background.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable, Sequence
|
|
4
|
+
from typing import Any, ParamSpec
|
|
5
|
+
|
|
6
|
+
from kernel._utils import is_async_callable
|
|
7
|
+
from kernel.concurrency import run_in_threadpool
|
|
8
|
+
|
|
9
|
+
P = ParamSpec("P")
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class BackgroundTask:
|
|
13
|
+
def __init__(self, func: Callable[P, Any], *args: P.args, **kwargs: P.kwargs) -> None:
|
|
14
|
+
self.func = func
|
|
15
|
+
self.args = args
|
|
16
|
+
self.kwargs = kwargs
|
|
17
|
+
self.is_async = is_async_callable(func)
|
|
18
|
+
|
|
19
|
+
async def __call__(self) -> None:
|
|
20
|
+
if self.is_async:
|
|
21
|
+
await self.func(*self.args, **self.kwargs)
|
|
22
|
+
else:
|
|
23
|
+
await run_in_threadpool(self.func, *self.args, **self.kwargs)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class BackgroundTasks(BackgroundTask):
|
|
27
|
+
def __init__(self, tasks: Sequence[BackgroundTask] | None = None):
|
|
28
|
+
self.tasks = list(tasks) if tasks else []
|
|
29
|
+
|
|
30
|
+
def add_task(self, func: Callable[P, Any], *args: P.args, **kwargs: P.kwargs) -> None:
|
|
31
|
+
task = BackgroundTask(func, *args, **kwargs)
|
|
32
|
+
self.tasks.append(task)
|
|
33
|
+
|
|
34
|
+
async def __call__(self) -> None:
|
|
35
|
+
for task in self.tasks:
|
|
36
|
+
await task()
|
kernel/concurrency.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import functools
|
|
4
|
+
import warnings
|
|
5
|
+
from collections.abc import AsyncIterator, Callable, Coroutine, Iterable, Iterator
|
|
6
|
+
from typing import ParamSpec, TypeVar
|
|
7
|
+
|
|
8
|
+
import anyio.to_thread
|
|
9
|
+
|
|
10
|
+
from kernel.exceptions import StarletteDeprecationWarning
|
|
11
|
+
|
|
12
|
+
P = ParamSpec("P")
|
|
13
|
+
T = TypeVar("T")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
async def run_until_first_complete(*args: tuple[Callable, dict]) -> None: # type: ignore[type-arg]
|
|
17
|
+
warnings.warn(
|
|
18
|
+
"run_until_first_complete is deprecated and will be removed in a future version.",
|
|
19
|
+
StarletteDeprecationWarning,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
async with anyio.create_task_group() as task_group:
|
|
23
|
+
|
|
24
|
+
async def run(func: Callable[[], Coroutine]) -> None: # type: ignore[type-arg]
|
|
25
|
+
await func()
|
|
26
|
+
task_group.cancel_scope.cancel()
|
|
27
|
+
|
|
28
|
+
for func, kwargs in args:
|
|
29
|
+
task_group.start_soon(run, functools.partial(func, **kwargs))
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
async def run_in_threadpool(func: Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> T:
|
|
33
|
+
func = functools.partial(func, *args, **kwargs)
|
|
34
|
+
return await anyio.to_thread.run_sync(func)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class _StopIteration(Exception):
|
|
38
|
+
pass
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _next(iterator: Iterator[T]) -> T:
|
|
42
|
+
# We can't raise `StopIteration` from within the threadpool iterator
|
|
43
|
+
# and catch it outside that context, so we coerce them into a different
|
|
44
|
+
# exception type.
|
|
45
|
+
try:
|
|
46
|
+
return next(iterator)
|
|
47
|
+
except StopIteration:
|
|
48
|
+
raise _StopIteration
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
async def iterate_in_threadpool(
|
|
52
|
+
iterator: Iterable[T],
|
|
53
|
+
) -> AsyncIterator[T]:
|
|
54
|
+
as_iterator = iter(iterator)
|
|
55
|
+
while True:
|
|
56
|
+
try:
|
|
57
|
+
yield await anyio.to_thread.run_sync(_next, as_iterator)
|
|
58
|
+
except _StopIteration:
|
|
59
|
+
break
|