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/endpoints.py ADDED
@@ -0,0 +1,128 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from collections.abc import Callable, Generator
5
+ from typing import Any, Literal
6
+
7
+ from kernel import status
8
+ from kernel._utils import is_async_callable
9
+ from kernel.concurrency import run_in_threadpool
10
+ from kernel.exceptions import HTTPException
11
+ from kernel.requests import Request
12
+ from kernel.responses import PlainTextResponse, Response
13
+ from kernel.types import Message, Receive, Scope, Send
14
+ from kernel.websockets import WebSocket
15
+
16
+
17
+ class HTTPEndpoint:
18
+ def __init__(self, scope: Scope, receive: Receive, send: Send) -> None:
19
+ assert scope["type"] == "http"
20
+ self.scope = scope
21
+ self.receive = receive
22
+ self.send = send
23
+ self._allowed_methods = [
24
+ method
25
+ for method in ("GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "QUERY")
26
+ if getattr(self, method.lower(), None) is not None
27
+ or (method == "HEAD" and getattr(self, "get", None) is not None)
28
+ ]
29
+
30
+ def __await__(self) -> Generator[Any, None, None]:
31
+ return self.dispatch().__await__()
32
+
33
+ async def dispatch(self) -> None:
34
+ request = Request(self.scope, receive=self.receive, send=self.send)
35
+ handler_name = "get" if request.method == "HEAD" and not hasattr(self, "head") else request.method.lower()
36
+
37
+ handler: Callable[[Request], Any]
38
+ if request.method in self._allowed_methods:
39
+ handler = getattr(self, handler_name)
40
+ else:
41
+ handler = self.method_not_allowed
42
+ is_async = is_async_callable(handler)
43
+ if is_async:
44
+ response = await handler(request)
45
+ else:
46
+ response = await run_in_threadpool(handler, request)
47
+ await response(self.scope, self.receive, self.send)
48
+
49
+ async def method_not_allowed(self, request: Request) -> Response:
50
+ # If we're running inside a pboot-kernel application then raise an
51
+ # exception, so that the configurable exception handler can deal with
52
+ # returning the response. For plain ASGI apps, just return the response.
53
+ headers = {"Allow": ", ".join(self._allowed_methods)}
54
+ if "app" in self.scope:
55
+ raise HTTPException(status_code=405, headers=headers)
56
+ return PlainTextResponse("Method Not Allowed", status_code=405, headers=headers)
57
+
58
+
59
+ class WebSocketEndpoint:
60
+ encoding: Literal["text", "bytes", "json"] | None = None
61
+
62
+ def __init__(self, scope: Scope, receive: Receive, send: Send) -> None:
63
+ assert scope["type"] == "websocket"
64
+ self.scope = scope
65
+ self.receive = receive
66
+ self.send = send
67
+
68
+ def __await__(self) -> Generator[Any, None, None]:
69
+ return self.dispatch().__await__()
70
+
71
+ async def dispatch(self) -> None:
72
+ websocket = WebSocket(self.scope, receive=self.receive, send=self.send)
73
+ await self.on_connect(websocket)
74
+
75
+ close_code = status.WS_1000_NORMAL_CLOSURE
76
+
77
+ try:
78
+ while True:
79
+ message = await websocket.receive()
80
+ if message["type"] == "websocket.receive":
81
+ data = await self.decode(websocket, message)
82
+ await self.on_receive(websocket, data)
83
+ elif message["type"] == "websocket.disconnect": # pragma: no branch
84
+ close_code = int(message.get("code") or status.WS_1000_NORMAL_CLOSURE)
85
+ break
86
+ except Exception as exc:
87
+ close_code = status.WS_1011_INTERNAL_ERROR
88
+ raise exc
89
+ finally:
90
+ await self.on_disconnect(websocket, close_code)
91
+
92
+ async def decode(self, websocket: WebSocket, message: Message) -> Any:
93
+ if self.encoding == "text":
94
+ if message.get("text") is None:
95
+ await websocket.close(code=status.WS_1003_UNSUPPORTED_DATA)
96
+ raise RuntimeError("Expected text websocket messages, but got bytes")
97
+ return message["text"]
98
+
99
+ elif self.encoding == "bytes":
100
+ if message.get("bytes") is None:
101
+ await websocket.close(code=status.WS_1003_UNSUPPORTED_DATA)
102
+ raise RuntimeError("Expected bytes websocket messages, but got text")
103
+ return message["bytes"]
104
+
105
+ elif self.encoding == "json":
106
+ if message.get("text") is not None:
107
+ text = message["text"]
108
+ else:
109
+ text = message["bytes"].decode("utf-8")
110
+
111
+ try:
112
+ return json.loads(text)
113
+ except json.decoder.JSONDecodeError:
114
+ await websocket.close(code=status.WS_1003_UNSUPPORTED_DATA)
115
+ raise RuntimeError("Malformed JSON data received.")
116
+
117
+ assert self.encoding is None, f"Unsupported 'encoding' attribute {self.encoding}"
118
+ return message["text"] if message.get("text") is not None else message["bytes"]
119
+
120
+ async def on_connect(self, websocket: WebSocket) -> None:
121
+ """Override to handle an incoming websocket connection"""
122
+ await websocket.accept()
123
+
124
+ async def on_receive(self, websocket: WebSocket, data: Any) -> None:
125
+ """Override to handle an incoming websocket message"""
126
+
127
+ async def on_disconnect(self, websocket: WebSocket, close_code: int) -> None:
128
+ """Override to handle a disconnecting websocket"""
kernel/exceptions.py ADDED
@@ -0,0 +1,43 @@
1
+ from __future__ import annotations
2
+
3
+ import http.client
4
+ from collections.abc import Mapping
5
+
6
+
7
+ class HTTPException(Exception):
8
+ def __init__(self, status_code: int, detail: str | None = None, headers: Mapping[str, str] | None = None) -> None:
9
+ if detail is None:
10
+ detail = http.client.responses.get(status_code, "")
11
+ self.status_code = status_code
12
+ self.detail = detail
13
+ self.headers = headers
14
+
15
+ def __str__(self) -> str:
16
+ return f"{self.status_code}: {self.detail}"
17
+
18
+ def __repr__(self) -> str:
19
+ class_name = self.__class__.__name__
20
+ return f"{class_name}(status_code={self.status_code!r}, detail={self.detail!r})"
21
+
22
+
23
+ class WebSocketException(Exception):
24
+ def __init__(self, code: int, reason: str | None = None) -> None:
25
+ self.code = code
26
+ self.reason = reason or ""
27
+
28
+ def __str__(self) -> str:
29
+ return f"{self.code}: {self.reason}"
30
+
31
+ def __repr__(self) -> str:
32
+ class_name = self.__class__.__name__
33
+ return f"{class_name}(code={self.code!r}, reason={self.reason!r})"
34
+
35
+
36
+ class StarletteDeprecationWarning(UserWarning):
37
+ """A custom deprecation warning for Starlette.
38
+
39
+ Unlike the built-in DeprecationWarning, this inherits from UserWarning to ensure it is visible by default, helping
40
+ users discover deprecated features without needing to enable warnings explicitly.
41
+
42
+ Reference: https://sethmlarson.dev/deprecations-via-warnings-dont-work-for-python-libraries
43
+ """
kernel/formparsers.py ADDED
@@ -0,0 +1,289 @@
1
+ from __future__ import annotations
2
+
3
+ import codecs
4
+ import sys
5
+ from collections.abc import AsyncGenerator
6
+ from dataclasses import dataclass, field
7
+ from enum import Enum
8
+ from tempfile import SpooledTemporaryFile
9
+ from typing import TYPE_CHECKING
10
+ from urllib.parse import unquote_plus
11
+
12
+ from kernel.datastructures import FormData, Headers, UploadFile
13
+ from kernel.exceptions import StarletteDeprecationWarning
14
+
15
+ if sys.version_info >= (3, 13): # pragma: no cover
16
+ from warnings import deprecated
17
+ else: # pragma: no cover
18
+ from typing_extensions import deprecated
19
+
20
+ if TYPE_CHECKING:
21
+ import python_multipart as multipart
22
+ from python_multipart.exceptions import FormParserError
23
+ from python_multipart.multipart import MultipartCallbacks, QuerystringCallbacks, parse_options_header
24
+ else:
25
+ try:
26
+ try:
27
+ import python_multipart as multipart
28
+ from python_multipart.exceptions import FormParserError
29
+ from python_multipart.multipart import parse_options_header
30
+ except ModuleNotFoundError: # pragma: no cover
31
+ import multipart
32
+ from multipart.exceptions import FormParserError
33
+ from multipart.multipart import parse_options_header
34
+ except ModuleNotFoundError: # pragma: no cover
35
+ multipart = None
36
+ parse_options_header = None
37
+
38
+
39
+ @deprecated(
40
+ "`FormMessage` is deprecated and will be removed in a future version.",
41
+ category=StarletteDeprecationWarning,
42
+ stacklevel=2,
43
+ )
44
+ class FormMessage(Enum):
45
+ FIELD_START = 1
46
+ FIELD_NAME = 2
47
+ FIELD_DATA = 3
48
+ FIELD_END = 4
49
+ END = 5
50
+
51
+
52
+ @dataclass
53
+ class MultipartPart:
54
+ content_disposition: bytes | None = None
55
+ field_name: str = ""
56
+ data: bytearray = field(default_factory=bytearray)
57
+ file: UploadFile | None = None
58
+ item_headers: list[tuple[bytes, bytes]] = field(default_factory=list)
59
+
60
+
61
+ def _user_safe_decode(src: bytes | bytearray, codec: str) -> str:
62
+ try:
63
+ return src.decode(codec)
64
+ except (UnicodeDecodeError, LookupError):
65
+ return src.decode("latin-1")
66
+
67
+
68
+ class MultiPartException(Exception):
69
+ def __init__(self, message: str) -> None:
70
+ self.message = message
71
+
72
+
73
+ class FormParser:
74
+ def __init__(
75
+ self,
76
+ headers: Headers,
77
+ stream: AsyncGenerator[bytes, None],
78
+ *,
79
+ max_fields: int | float = 1000,
80
+ max_part_size: int = 1024 * 1024, # 1MB
81
+ ) -> None:
82
+ assert multipart is not None, "The `python-multipart` library must be installed to use form parsing."
83
+ self.headers = headers
84
+ self.stream = stream
85
+ self.max_fields = max_fields
86
+ self.max_part_size = max_part_size
87
+ self._current_field_size = 0
88
+ self._current_fields = 0
89
+ self._field_name = bytearray()
90
+ self._field_value = bytearray()
91
+ self._items: list[tuple[str, str | UploadFile]] = []
92
+
93
+ def on_field_start(self) -> None:
94
+ self._current_field_size = 0
95
+ self._field_name = bytearray()
96
+ self._field_value = bytearray()
97
+
98
+ def on_field_name(self, data: bytes, start: int, end: int) -> None:
99
+ self._current_field_size += end - start
100
+ if self._current_field_size > self.max_part_size:
101
+ raise MultiPartException(f"Field exceeded maximum size of {int(self.max_part_size / 1024)}KB.")
102
+ self._field_name += data[start:end]
103
+
104
+ def on_field_data(self, data: bytes, start: int, end: int) -> None:
105
+ self._current_field_size += end - start
106
+ if self._current_field_size > self.max_part_size:
107
+ raise MultiPartException(f"Field exceeded maximum size of {int(self.max_part_size / 1024)}KB.")
108
+ self._field_value += data[start:end]
109
+
110
+ def on_field_end(self) -> None:
111
+ self._current_fields += 1
112
+ if self._current_fields > self.max_fields:
113
+ raise MultiPartException(f"Too many fields. Maximum number of fields is {self.max_fields}.")
114
+ name = unquote_plus(self._field_name.decode("latin-1"))
115
+ value = unquote_plus(self._field_value.decode("latin-1"))
116
+ self._items.append((name, value))
117
+
118
+ async def parse(self) -> FormData:
119
+ callbacks: QuerystringCallbacks = {
120
+ "on_field_start": self.on_field_start,
121
+ "on_field_name": self.on_field_name,
122
+ "on_field_data": self.on_field_data,
123
+ "on_field_end": self.on_field_end,
124
+ }
125
+ parser = multipart.QuerystringParser(callbacks)
126
+
127
+ async for chunk in self.stream:
128
+ parser.write(chunk)
129
+ parser.finalize()
130
+
131
+ return FormData(self._items)
132
+
133
+
134
+ class MultiPartParser:
135
+ spool_max_size = 1024 * 1024 # 1MB
136
+ """The maximum size of the spooled temporary file used to store file data."""
137
+ max_part_size = 1024 * 1024 # 1MB
138
+ """The maximum size of a part in the multipart request."""
139
+
140
+ def __init__(
141
+ self,
142
+ headers: Headers,
143
+ stream: AsyncGenerator[bytes, None],
144
+ *,
145
+ max_files: int | float = 1000,
146
+ max_fields: int | float = 1000,
147
+ max_part_size: int = 1024 * 1024, # 1MB
148
+ ) -> None:
149
+ assert multipart is not None, "The `python-multipart` library must be installed to use form parsing."
150
+ self.headers = headers
151
+ self.stream = stream
152
+ self.max_files = max_files
153
+ self.max_fields = max_fields
154
+ self.items: list[tuple[str, str | UploadFile]] = []
155
+ self._current_files = 0
156
+ self._current_fields = 0
157
+ self._current_partial_header_name: bytes = b""
158
+ self._current_partial_header_value: bytes = b""
159
+ self._current_part = MultipartPart()
160
+ self._charset = ""
161
+ self._file_parts_to_write: list[tuple[MultipartPart, bytes]] = []
162
+ self._file_parts_to_finish: list[MultipartPart] = []
163
+ self._files_to_close_on_error: list[SpooledTemporaryFile[bytes]] = []
164
+ self.max_part_size = max_part_size
165
+
166
+ def on_part_begin(self) -> None:
167
+ self._current_part = MultipartPart()
168
+
169
+ def on_part_data(self, data: bytes, start: int, end: int) -> None:
170
+ message_bytes = data[start:end]
171
+ if self._current_part.file is None:
172
+ if len(self._current_part.data) + len(message_bytes) > self.max_part_size:
173
+ raise MultiPartException(f"Part exceeded maximum size of {int(self.max_part_size / 1024)}KB.")
174
+ self._current_part.data.extend(message_bytes)
175
+ else:
176
+ self._file_parts_to_write.append((self._current_part, message_bytes))
177
+
178
+ def on_part_end(self) -> None:
179
+ if self._current_part.file is None:
180
+ self.items.append(
181
+ (
182
+ self._current_part.field_name,
183
+ _user_safe_decode(self._current_part.data, self._charset),
184
+ )
185
+ )
186
+ else:
187
+ self._file_parts_to_finish.append(self._current_part)
188
+ # The file can be added to the items right now even though it's not
189
+ # finished yet, because it will be finished in the `parse()` method, before
190
+ # self.items is used in the return value.
191
+ self.items.append((self._current_part.field_name, self._current_part.file))
192
+
193
+ def on_header_field(self, data: bytes, start: int, end: int) -> None:
194
+ self._current_partial_header_name += data[start:end]
195
+
196
+ def on_header_value(self, data: bytes, start: int, end: int) -> None:
197
+ self._current_partial_header_value += data[start:end]
198
+
199
+ def on_header_end(self) -> None:
200
+ field = self._current_partial_header_name.lower()
201
+ if field == b"content-disposition":
202
+ self._current_part.content_disposition = self._current_partial_header_value
203
+ self._current_part.item_headers.append((field, self._current_partial_header_value))
204
+ self._current_partial_header_name = b""
205
+ self._current_partial_header_value = b""
206
+
207
+ def on_headers_finished(self) -> None:
208
+ disposition, options = parse_options_header(self._current_part.content_disposition)
209
+ try:
210
+ self._current_part.field_name = _user_safe_decode(options[b"name"], self._charset)
211
+ except KeyError:
212
+ raise MultiPartException('The Content-Disposition header field "name" must be provided.')
213
+ if b"filename" in options:
214
+ self._current_files += 1
215
+ if self._current_files > self.max_files:
216
+ raise MultiPartException(f"Too many files. Maximum number of files is {self.max_files}.")
217
+ filename = _user_safe_decode(options[b"filename"], self._charset)
218
+ tempfile = SpooledTemporaryFile(max_size=self.spool_max_size)
219
+ self._files_to_close_on_error.append(tempfile)
220
+ self._current_part.file = UploadFile(
221
+ file=tempfile, # type: ignore[arg-type]
222
+ size=0,
223
+ filename=filename,
224
+ headers=Headers(raw=self._current_part.item_headers),
225
+ )
226
+ else:
227
+ self._current_fields += 1
228
+ if self._current_fields > self.max_fields:
229
+ raise MultiPartException(f"Too many fields. Maximum number of fields is {self.max_fields}.")
230
+ self._current_part.file = None
231
+
232
+ def on_end(self) -> None:
233
+ pass
234
+
235
+ async def parse(self) -> FormData:
236
+ # Parse the Content-Type header to get the multipart boundary.
237
+ _, params = parse_options_header(self.headers["Content-Type"])
238
+ charset = params.get(b"charset", "utf-8")
239
+ if isinstance(charset, bytes):
240
+ charset = charset.decode("latin-1")
241
+ try:
242
+ self._charset = codecs.lookup(charset).name
243
+ except LookupError:
244
+ self._charset = "latin-1"
245
+ try:
246
+ boundary = params[b"boundary"]
247
+ except KeyError:
248
+ raise MultiPartException("Missing boundary in multipart.")
249
+
250
+ # Callbacks dictionary.
251
+ callbacks: MultipartCallbacks = {
252
+ "on_part_begin": self.on_part_begin,
253
+ "on_part_data": self.on_part_data,
254
+ "on_part_end": self.on_part_end,
255
+ "on_header_field": self.on_header_field,
256
+ "on_header_value": self.on_header_value,
257
+ "on_header_end": self.on_header_end,
258
+ "on_headers_finished": self.on_headers_finished,
259
+ "on_end": self.on_end,
260
+ }
261
+
262
+ try:
263
+ parser = multipart.MultipartParser(boundary, callbacks)
264
+ # Feed the parser with data from the request.
265
+ async for chunk in self.stream:
266
+ parser.write(chunk)
267
+ # Write file data, it needs to use await with the UploadFile methods
268
+ # that call the corresponding file methods *in a threadpool*,
269
+ # otherwise, if they were called directly in the callback methods above
270
+ # (regular, non-async functions), that would block the event loop in
271
+ # the main thread.
272
+ for part, data in self._file_parts_to_write:
273
+ assert part.file # for type checkers
274
+ await part.file.write(data)
275
+ for part in self._file_parts_to_finish:
276
+ assert part.file # for type checkers
277
+ await part.file.seek(0)
278
+ self._file_parts_to_write.clear()
279
+ self._file_parts_to_finish.clear()
280
+ parser.finalize()
281
+ except BaseException as exc:
282
+ # Close all the files if parsing or reading the request stream fails.
283
+ for file in self._files_to_close_on_error:
284
+ file.close()
285
+ if isinstance(exc, FormParserError):
286
+ raise MultiPartException("Invalid multipart data.") from exc
287
+ raise
288
+
289
+ return FormData(self.items)
@@ -0,0 +1,37 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Awaitable, Callable, Iterator
4
+ from typing import Any, ParamSpec, Protocol
5
+
6
+ P = ParamSpec("P")
7
+
8
+
9
+ _Scope = Any
10
+ _Receive = Callable[[], Awaitable[Any]]
11
+ _Send = Callable[[Any], Awaitable[None]]
12
+ # Since `kernel.types.ASGIApp` type differs from `ASGIApplication` from `asgiref`
13
+ # we need to define a more permissive version of ASGIApp that doesn't cause type errors.
14
+ _ASGIApp = Callable[[_Scope, _Receive, _Send], Awaitable[None]]
15
+
16
+
17
+ class _MiddlewareFactory(Protocol[P]):
18
+ def __call__(self, app: _ASGIApp, /, *args: P.args, **kwargs: P.kwargs) -> _ASGIApp: ... # pragma: no cover
19
+
20
+
21
+ class Middleware:
22
+ def __init__(self, cls: _MiddlewareFactory[P], *args: P.args, **kwargs: P.kwargs) -> None:
23
+ self.cls = cls
24
+ self.args = args
25
+ self.kwargs = kwargs
26
+
27
+ def __iter__(self) -> Iterator[Any]:
28
+ as_tuple = (self.cls, self.args, self.kwargs)
29
+ return iter(as_tuple)
30
+
31
+ def __repr__(self) -> str:
32
+ class_name = self.__class__.__name__
33
+ args_strings = [f"{value!r}" for value in self.args]
34
+ option_strings = [f"{key}={value!r}" for key, value in self.kwargs.items()]
35
+ name = getattr(self.cls, "__name__", "")
36
+ args_repr = ", ".join([name] + args_strings + option_strings)
37
+ return f"{class_name}({args_repr})"
@@ -0,0 +1,52 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Callable
4
+
5
+ from kernel.authentication import (
6
+ AuthCredentials,
7
+ AuthenticationBackend,
8
+ AuthenticationError,
9
+ UnauthenticatedUser,
10
+ )
11
+ from kernel.requests import HTTPConnection
12
+ from kernel.responses import PlainTextResponse, Response
13
+ from kernel.types import ASGIApp, Receive, Scope, Send
14
+
15
+
16
+ class AuthenticationMiddleware:
17
+ def __init__(
18
+ self,
19
+ app: ASGIApp,
20
+ backend: AuthenticationBackend,
21
+ on_error: Callable[[HTTPConnection, AuthenticationError], Response] | None = None,
22
+ ) -> None:
23
+ self.app = app
24
+ self.backend = backend
25
+ self.on_error: Callable[[HTTPConnection, AuthenticationError], Response] = (
26
+ on_error if on_error is not None else self.default_on_error
27
+ )
28
+
29
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
30
+ if scope["type"] not in ["http", "websocket"]:
31
+ await self.app(scope, receive, send)
32
+ return
33
+
34
+ conn = HTTPConnection(scope)
35
+ try:
36
+ auth_result = await self.backend.authenticate(conn)
37
+ except AuthenticationError as exc:
38
+ response = self.on_error(conn, exc)
39
+ if scope["type"] == "websocket":
40
+ await send({"type": "websocket.close", "code": 1000})
41
+ else:
42
+ await response(scope, receive, send)
43
+ return
44
+
45
+ if auth_result is None:
46
+ auth_result = AuthCredentials(), UnauthenticatedUser()
47
+ scope["auth"], scope["user"] = auth_result
48
+ await self.app(scope, receive, send)
49
+
50
+ @staticmethod
51
+ def default_on_error(conn: HTTPConnection, exc: Exception) -> Response:
52
+ return PlainTextResponse(str(exc), status_code=400)