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
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import html
|
|
4
|
+
import inspect
|
|
5
|
+
import sys
|
|
6
|
+
import traceback
|
|
7
|
+
|
|
8
|
+
from kernel._utils import is_async_callable
|
|
9
|
+
from kernel.concurrency import run_in_threadpool
|
|
10
|
+
from kernel.requests import Request
|
|
11
|
+
from kernel.responses import HTMLResponse, PlainTextResponse, Response
|
|
12
|
+
from kernel.types import ASGIApp, ExceptionHandler, Message, Receive, Scope, Send
|
|
13
|
+
|
|
14
|
+
STYLES = """
|
|
15
|
+
p {
|
|
16
|
+
color: #211c1c;
|
|
17
|
+
}
|
|
18
|
+
.traceback-container {
|
|
19
|
+
border: 1px solid #038BB8;
|
|
20
|
+
}
|
|
21
|
+
.traceback-title {
|
|
22
|
+
background-color: #038BB8;
|
|
23
|
+
color: lemonchiffon;
|
|
24
|
+
padding: 12px;
|
|
25
|
+
font-size: 20px;
|
|
26
|
+
margin-top: 0px;
|
|
27
|
+
}
|
|
28
|
+
.frame-line {
|
|
29
|
+
padding-left: 10px;
|
|
30
|
+
font-family: monospace;
|
|
31
|
+
}
|
|
32
|
+
.frame-filename {
|
|
33
|
+
font-family: monospace;
|
|
34
|
+
}
|
|
35
|
+
.center-line {
|
|
36
|
+
background-color: #038BB8;
|
|
37
|
+
color: #f9f6e1;
|
|
38
|
+
padding: 5px 0px 5px 5px;
|
|
39
|
+
}
|
|
40
|
+
.lineno {
|
|
41
|
+
margin-right: 5px;
|
|
42
|
+
}
|
|
43
|
+
.frame-title {
|
|
44
|
+
font-weight: unset;
|
|
45
|
+
padding: 10px 10px 10px 10px;
|
|
46
|
+
background-color: #E4F4FD;
|
|
47
|
+
margin-right: 10px;
|
|
48
|
+
color: #191f21;
|
|
49
|
+
font-size: 17px;
|
|
50
|
+
border: 1px solid #c7dce8;
|
|
51
|
+
}
|
|
52
|
+
.collapse-btn {
|
|
53
|
+
float: right;
|
|
54
|
+
padding: 0px 5px 1px 5px;
|
|
55
|
+
border: solid 1px #96aebb;
|
|
56
|
+
cursor: pointer;
|
|
57
|
+
}
|
|
58
|
+
.collapsed {
|
|
59
|
+
display: none;
|
|
60
|
+
}
|
|
61
|
+
.source-code {
|
|
62
|
+
font-family: courier;
|
|
63
|
+
font-size: small;
|
|
64
|
+
padding-bottom: 10px;
|
|
65
|
+
}
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
JS = """
|
|
69
|
+
<script type="text/javascript">
|
|
70
|
+
function collapse(element){
|
|
71
|
+
const frameId = element.getAttribute("data-frame-id");
|
|
72
|
+
const frame = document.getElementById(frameId);
|
|
73
|
+
|
|
74
|
+
if (frame.classList.contains("collapsed")){
|
|
75
|
+
element.innerHTML = "‒";
|
|
76
|
+
frame.classList.remove("collapsed");
|
|
77
|
+
} else {
|
|
78
|
+
element.innerHTML = "+";
|
|
79
|
+
frame.classList.add("collapsed");
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
</script>
|
|
83
|
+
"""
|
|
84
|
+
|
|
85
|
+
TEMPLATE = """
|
|
86
|
+
<html>
|
|
87
|
+
<head>
|
|
88
|
+
<style type='text/css'>
|
|
89
|
+
{styles}
|
|
90
|
+
</style>
|
|
91
|
+
<title>Starlette Debugger</title>
|
|
92
|
+
</head>
|
|
93
|
+
<body>
|
|
94
|
+
<h1>500 Server Error</h1>
|
|
95
|
+
<h2>{error}</h2>
|
|
96
|
+
<div class="traceback-container">
|
|
97
|
+
<p class="traceback-title">Traceback</p>
|
|
98
|
+
<div>{exc_html}</div>
|
|
99
|
+
</div>
|
|
100
|
+
{js}
|
|
101
|
+
</body>
|
|
102
|
+
</html>
|
|
103
|
+
"""
|
|
104
|
+
|
|
105
|
+
FRAME_TEMPLATE = """
|
|
106
|
+
<div>
|
|
107
|
+
<p class="frame-title">File <span class="frame-filename">{frame_filename}</span>,
|
|
108
|
+
line <i>{frame_lineno}</i>,
|
|
109
|
+
in <b>{frame_name}</b>
|
|
110
|
+
<span class="collapse-btn" data-frame-id="{frame_filename}-{frame_lineno}" onclick="collapse(this)">{collapse_button}</span>
|
|
111
|
+
</p>
|
|
112
|
+
<div id="{frame_filename}-{frame_lineno}" class="source-code {collapsed}">{code_context}</div>
|
|
113
|
+
</div>
|
|
114
|
+
""" # noqa: E501
|
|
115
|
+
|
|
116
|
+
LINE = """
|
|
117
|
+
<p><span class="frame-line">
|
|
118
|
+
<span class="lineno">{lineno}.</span> {line}</span></p>
|
|
119
|
+
"""
|
|
120
|
+
|
|
121
|
+
CENTER_LINE = """
|
|
122
|
+
<p class="center-line"><span class="frame-line center-line">
|
|
123
|
+
<span class="lineno">{lineno}.</span> {line}</span></p>
|
|
124
|
+
"""
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class ServerErrorMiddleware:
|
|
128
|
+
"""
|
|
129
|
+
Handles returning 500 responses when a server error occurs.
|
|
130
|
+
|
|
131
|
+
If 'debug' is set, then traceback responses will be returned,
|
|
132
|
+
otherwise the designated 'handler' will be called.
|
|
133
|
+
|
|
134
|
+
This middleware class should generally be used to wrap *everything*
|
|
135
|
+
else up, so that unhandled exceptions anywhere in the stack
|
|
136
|
+
always result in an appropriate 500 response.
|
|
137
|
+
"""
|
|
138
|
+
|
|
139
|
+
def __init__(
|
|
140
|
+
self,
|
|
141
|
+
app: ASGIApp,
|
|
142
|
+
handler: ExceptionHandler | None = None,
|
|
143
|
+
debug: bool = False,
|
|
144
|
+
) -> None:
|
|
145
|
+
self.app = app
|
|
146
|
+
self.handler = handler
|
|
147
|
+
self.debug = debug
|
|
148
|
+
|
|
149
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
150
|
+
if scope["type"] != "http":
|
|
151
|
+
await self.app(scope, receive, send)
|
|
152
|
+
return
|
|
153
|
+
|
|
154
|
+
response_started = False
|
|
155
|
+
|
|
156
|
+
async def _send(message: Message) -> None:
|
|
157
|
+
nonlocal response_started, send
|
|
158
|
+
|
|
159
|
+
if message["type"] == "http.response.start":
|
|
160
|
+
response_started = True
|
|
161
|
+
await send(message)
|
|
162
|
+
|
|
163
|
+
try:
|
|
164
|
+
await self.app(scope, receive, _send)
|
|
165
|
+
except Exception as exc:
|
|
166
|
+
request = Request(scope)
|
|
167
|
+
if self.debug:
|
|
168
|
+
# In debug mode, return traceback responses.
|
|
169
|
+
response = await run_in_threadpool(self.debug_response, request, exc)
|
|
170
|
+
elif self.handler is None:
|
|
171
|
+
# Use our default 500 error handler.
|
|
172
|
+
response = self.error_response(request, exc)
|
|
173
|
+
else:
|
|
174
|
+
# Use an installed 500 error handler.
|
|
175
|
+
if is_async_callable(self.handler):
|
|
176
|
+
response = await self.handler(request, exc) # type: ignore[assignment, arg-type]
|
|
177
|
+
else:
|
|
178
|
+
response = await run_in_threadpool(self.handler, request, exc) # type: ignore[arg-type]
|
|
179
|
+
|
|
180
|
+
if not response_started:
|
|
181
|
+
await response(scope, receive, send)
|
|
182
|
+
|
|
183
|
+
# We always continue to raise the exception.
|
|
184
|
+
# This allows servers to log the error, or allows test clients
|
|
185
|
+
# to optionally raise the error within the test case.
|
|
186
|
+
raise exc
|
|
187
|
+
|
|
188
|
+
def format_line(self, index: int, line: str, frame_lineno: int, frame_index: int) -> str:
|
|
189
|
+
values = {
|
|
190
|
+
# HTML escape - line could contain < or >
|
|
191
|
+
"line": html.escape(line).replace(" ", " "),
|
|
192
|
+
"lineno": (frame_lineno - frame_index) + index,
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
if index != frame_index:
|
|
196
|
+
return LINE.format(**values)
|
|
197
|
+
return CENTER_LINE.format(**values)
|
|
198
|
+
|
|
199
|
+
def generate_frame_html(self, frame: inspect.FrameInfo, is_collapsed: bool) -> str:
|
|
200
|
+
code_context = "".join(
|
|
201
|
+
self.format_line(
|
|
202
|
+
index,
|
|
203
|
+
line,
|
|
204
|
+
frame.lineno,
|
|
205
|
+
frame.index, # type: ignore[arg-type]
|
|
206
|
+
)
|
|
207
|
+
for index, line in enumerate(frame.code_context or [])
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
values = {
|
|
211
|
+
# HTML escape - filename could contain < or >, especially if it's a virtual
|
|
212
|
+
# file e.g. <stdin> in the REPL
|
|
213
|
+
"frame_filename": html.escape(frame.filename),
|
|
214
|
+
"frame_lineno": frame.lineno,
|
|
215
|
+
# HTML escape - if you try very hard it's possible to name a function with <
|
|
216
|
+
# or >
|
|
217
|
+
"frame_name": html.escape(frame.function),
|
|
218
|
+
"code_context": code_context,
|
|
219
|
+
"collapsed": "collapsed" if is_collapsed else "",
|
|
220
|
+
"collapse_button": "+" if is_collapsed else "‒",
|
|
221
|
+
}
|
|
222
|
+
return FRAME_TEMPLATE.format(**values)
|
|
223
|
+
|
|
224
|
+
def generate_html(self, exc: Exception, limit: int = 7) -> str:
|
|
225
|
+
traceback_obj = traceback.TracebackException.from_exception(exc, capture_locals=True)
|
|
226
|
+
|
|
227
|
+
exc_html = ""
|
|
228
|
+
is_collapsed = False
|
|
229
|
+
exc_traceback = exc.__traceback__
|
|
230
|
+
if exc_traceback is not None:
|
|
231
|
+
frames = inspect.getinnerframes(exc_traceback, limit)
|
|
232
|
+
for frame in reversed(frames):
|
|
233
|
+
exc_html += self.generate_frame_html(frame, is_collapsed)
|
|
234
|
+
is_collapsed = True
|
|
235
|
+
|
|
236
|
+
if sys.version_info >= (3, 13): # pragma: no cover
|
|
237
|
+
exc_type_str = traceback_obj.exc_type_str
|
|
238
|
+
else: # pragma: no cover
|
|
239
|
+
exc_type_str = traceback_obj.exc_type.__name__
|
|
240
|
+
|
|
241
|
+
# escape error class and text
|
|
242
|
+
error = f"{html.escape(exc_type_str)}: {html.escape(str(traceback_obj))}"
|
|
243
|
+
|
|
244
|
+
return TEMPLATE.format(styles=STYLES, js=JS, error=error, exc_html=exc_html)
|
|
245
|
+
|
|
246
|
+
def generate_plain_text(self, exc: Exception) -> str:
|
|
247
|
+
return "".join(traceback.format_exception(type(exc), exc, exc.__traceback__))
|
|
248
|
+
|
|
249
|
+
def debug_response(self, request: Request, exc: Exception) -> Response:
|
|
250
|
+
accept = request.headers.get("accept", "")
|
|
251
|
+
|
|
252
|
+
if "text/html" in accept:
|
|
253
|
+
content = self.generate_html(exc)
|
|
254
|
+
return HTMLResponse(content, status_code=500)
|
|
255
|
+
content = self.generate_plain_text(exc)
|
|
256
|
+
return PlainTextResponse(content, status_code=500)
|
|
257
|
+
|
|
258
|
+
def error_response(self, request: Request, exc: Exception) -> Response:
|
|
259
|
+
return PlainTextResponse("Internal Server Error", status_code=500)
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from kernel._exception_handler import (
|
|
7
|
+
ExceptionHandlers,
|
|
8
|
+
StatusHandlers,
|
|
9
|
+
wrap_app_handling_exceptions,
|
|
10
|
+
)
|
|
11
|
+
from kernel.exceptions import HTTPException, WebSocketException
|
|
12
|
+
from kernel.requests import Request
|
|
13
|
+
from kernel.responses import PlainTextResponse, Response
|
|
14
|
+
from kernel.types import ASGIApp, ExceptionHandler, Receive, Scope, Send
|
|
15
|
+
from kernel.websockets import WebSocket
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class ExceptionMiddleware:
|
|
19
|
+
def __init__(
|
|
20
|
+
self,
|
|
21
|
+
app: ASGIApp,
|
|
22
|
+
handlers: Mapping[Any, ExceptionHandler] | None = None,
|
|
23
|
+
debug: bool = False,
|
|
24
|
+
) -> None:
|
|
25
|
+
self.app = app
|
|
26
|
+
self.debug = debug # TODO: We ought to handle 404 cases if debug is set.
|
|
27
|
+
self._status_handlers: StatusHandlers = {}
|
|
28
|
+
self._exception_handlers: ExceptionHandlers = {
|
|
29
|
+
HTTPException: self.http_exception,
|
|
30
|
+
WebSocketException: self.websocket_exception,
|
|
31
|
+
}
|
|
32
|
+
if handlers is not None: # pragma: no branch
|
|
33
|
+
for key, value in handlers.items():
|
|
34
|
+
self.add_exception_handler(key, value)
|
|
35
|
+
|
|
36
|
+
def add_exception_handler(
|
|
37
|
+
self,
|
|
38
|
+
exc_class_or_status_code: int | type[Exception],
|
|
39
|
+
handler: ExceptionHandler,
|
|
40
|
+
) -> None:
|
|
41
|
+
if isinstance(exc_class_or_status_code, int):
|
|
42
|
+
self._status_handlers[exc_class_or_status_code] = handler
|
|
43
|
+
else:
|
|
44
|
+
assert issubclass(exc_class_or_status_code, Exception)
|
|
45
|
+
self._exception_handlers[exc_class_or_status_code] = handler
|
|
46
|
+
|
|
47
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
48
|
+
if scope["type"] not in ("http", "websocket"):
|
|
49
|
+
await self.app(scope, receive, send)
|
|
50
|
+
return
|
|
51
|
+
|
|
52
|
+
scope["starlette.exception_handlers"] = (
|
|
53
|
+
self._exception_handlers,
|
|
54
|
+
self._status_handlers,
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
conn: Request | WebSocket
|
|
58
|
+
if scope["type"] == "http":
|
|
59
|
+
conn = Request(scope, receive, send)
|
|
60
|
+
else:
|
|
61
|
+
conn = WebSocket(scope, receive, send)
|
|
62
|
+
|
|
63
|
+
await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send)
|
|
64
|
+
|
|
65
|
+
async def http_exception(self, request: Request, exc: Exception) -> Response:
|
|
66
|
+
assert isinstance(exc, HTTPException)
|
|
67
|
+
if exc.status_code in {204, 304}:
|
|
68
|
+
return Response(status_code=exc.status_code, headers=exc.headers)
|
|
69
|
+
return PlainTextResponse(exc.detail, status_code=exc.status_code, headers=exc.headers)
|
|
70
|
+
|
|
71
|
+
async def websocket_exception(self, websocket: WebSocket, exc: Exception) -> None:
|
|
72
|
+
assert isinstance(exc, WebSocketException)
|
|
73
|
+
await websocket.close(code=exc.code, reason=exc.reason) # pragma: no cover
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import zlib
|
|
4
|
+
from typing import NoReturn
|
|
5
|
+
|
|
6
|
+
import anyio.lowlevel
|
|
7
|
+
import anyio.to_thread
|
|
8
|
+
|
|
9
|
+
from kernel.datastructures import Headers, MutableHeaders
|
|
10
|
+
from kernel.types import ASGIApp, Message, Receive, Scope, Send
|
|
11
|
+
|
|
12
|
+
# TODO(v2): We should rename `DEFAULT_EXCLUDED_CONTENT_TYPES` to `DEFAULT_EXCLUDE_CONTENT_TYPES`.
|
|
13
|
+
DEFAULT_EXCLUDED_CONTENT_TYPES = (
|
|
14
|
+
"application/grpc",
|
|
15
|
+
"application/gzip",
|
|
16
|
+
"application/x-gzip",
|
|
17
|
+
"application/zip",
|
|
18
|
+
"audio/*",
|
|
19
|
+
"font/woff",
|
|
20
|
+
"font/woff2",
|
|
21
|
+
"image/avif",
|
|
22
|
+
"image/gif",
|
|
23
|
+
"image/jpeg",
|
|
24
|
+
"image/png",
|
|
25
|
+
"image/webp",
|
|
26
|
+
"text/event-stream",
|
|
27
|
+
"video/*",
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
_gzip_capacity_limiter: anyio.lowlevel.RunVar[anyio.CapacityLimiter] = anyio.lowlevel.RunVar("_gzip_capacity_limiter")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _get_gzip_capacity_limiter() -> anyio.CapacityLimiter:
|
|
34
|
+
"""Return the capacity limiter used for worker-thread GZip compression."""
|
|
35
|
+
try:
|
|
36
|
+
return _gzip_capacity_limiter.get()
|
|
37
|
+
except LookupError:
|
|
38
|
+
# Keep gzip compression isolated from AnyIO's default worker-thread
|
|
39
|
+
# capacity limiter while matching its default concurrency.
|
|
40
|
+
limiter = anyio.CapacityLimiter(40)
|
|
41
|
+
_gzip_capacity_limiter.set(limiter)
|
|
42
|
+
return limiter
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class GZipMiddleware:
|
|
46
|
+
def __init__(
|
|
47
|
+
self,
|
|
48
|
+
app: ASGIApp,
|
|
49
|
+
minimum_size: int = 500,
|
|
50
|
+
compresslevel: int = 9,
|
|
51
|
+
thread_minimum_size: int = 128 * 1024, # 128 KiB
|
|
52
|
+
*,
|
|
53
|
+
exclude_content_types: tuple[str, ...] = DEFAULT_EXCLUDED_CONTENT_TYPES,
|
|
54
|
+
) -> None:
|
|
55
|
+
self.app = app
|
|
56
|
+
self.minimum_size = minimum_size
|
|
57
|
+
self.compresslevel = compresslevel
|
|
58
|
+
self.thread_minimum_size = thread_minimum_size
|
|
59
|
+
self.exclude_content_types = _normalize_content_types(exclude_content_types)
|
|
60
|
+
|
|
61
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
62
|
+
if scope["type"] != "http": # pragma: no cover
|
|
63
|
+
await self.app(scope, receive, send)
|
|
64
|
+
return
|
|
65
|
+
|
|
66
|
+
headers = Headers(scope=scope)
|
|
67
|
+
responder: ASGIApp
|
|
68
|
+
if "gzip" in headers.get("Accept-Encoding", ""):
|
|
69
|
+
responder = GZipResponder(
|
|
70
|
+
self.app,
|
|
71
|
+
self.minimum_size,
|
|
72
|
+
compresslevel=self.compresslevel,
|
|
73
|
+
thread_minimum_size=self.thread_minimum_size,
|
|
74
|
+
exclude_content_types=self.exclude_content_types,
|
|
75
|
+
)
|
|
76
|
+
else:
|
|
77
|
+
responder = IdentityResponder(self.app, self.minimum_size, exclude_content_types=self.exclude_content_types)
|
|
78
|
+
|
|
79
|
+
await responder(scope, receive, send)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class IdentityResponder:
|
|
83
|
+
content_encoding: str
|
|
84
|
+
|
|
85
|
+
def __init__(
|
|
86
|
+
self,
|
|
87
|
+
app: ASGIApp,
|
|
88
|
+
minimum_size: int,
|
|
89
|
+
*,
|
|
90
|
+
exclude_content_types: tuple[str, ...] = DEFAULT_EXCLUDED_CONTENT_TYPES,
|
|
91
|
+
) -> None:
|
|
92
|
+
self.app = app
|
|
93
|
+
self.minimum_size = minimum_size
|
|
94
|
+
self.exclude_content_types = _normalize_content_types(exclude_content_types)
|
|
95
|
+
self.send: Send = unattached_send
|
|
96
|
+
self.initial_message: Message = {}
|
|
97
|
+
self.started = False
|
|
98
|
+
self.content_encoding_set = False
|
|
99
|
+
self.content_type_is_excluded = False
|
|
100
|
+
self.partial_response = False
|
|
101
|
+
|
|
102
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
103
|
+
self.send = send
|
|
104
|
+
await self.app(scope, receive, self.send_with_compression)
|
|
105
|
+
|
|
106
|
+
async def send_with_compression(self, message: Message) -> None:
|
|
107
|
+
message_type = message["type"]
|
|
108
|
+
if message_type == "http.response.start":
|
|
109
|
+
# Don't send the initial message until we've determined how to
|
|
110
|
+
# modify the outgoing headers correctly.
|
|
111
|
+
self.initial_message = message
|
|
112
|
+
message.setdefault("headers", [])
|
|
113
|
+
headers = Headers(raw=self.initial_message["headers"])
|
|
114
|
+
self.content_encoding_set = "content-encoding" in headers
|
|
115
|
+
self.partial_response = message["status"] == 206
|
|
116
|
+
media_type = headers.get("content-type", "").partition(";")[0].strip().lower()
|
|
117
|
+
media_types = {media_type, media_type.partition("/")[0] + "/*"}
|
|
118
|
+
if media_type.startswith("application/grpc+"):
|
|
119
|
+
media_types.add("application/grpc")
|
|
120
|
+
self.content_type_is_excluded = not media_types.isdisjoint(self.exclude_content_types)
|
|
121
|
+
if self.content_encoding_set or self.partial_response or self.content_type_is_excluded:
|
|
122
|
+
await self.send(self.initial_message)
|
|
123
|
+
elif message_type in ("http.response.body", "http.response.pathsend") and (
|
|
124
|
+
self.content_encoding_set or self.partial_response or self.content_type_is_excluded
|
|
125
|
+
):
|
|
126
|
+
await self.send(message)
|
|
127
|
+
elif message_type == "http.response.body" and not self.started:
|
|
128
|
+
self.started = True
|
|
129
|
+
body = message.get("body", b"")
|
|
130
|
+
more_body = message.get("more_body", False)
|
|
131
|
+
if len(body) < self.minimum_size and not more_body:
|
|
132
|
+
# Don't apply compression to small outgoing responses.
|
|
133
|
+
await self.send(self.initial_message)
|
|
134
|
+
await self.send(message)
|
|
135
|
+
elif not more_body:
|
|
136
|
+
# Standard response.
|
|
137
|
+
body = await self.apply_compression(body, more_body=False)
|
|
138
|
+
|
|
139
|
+
headers = MutableHeaders(raw=self.initial_message["headers"])
|
|
140
|
+
headers.add_vary_header("Accept-Encoding")
|
|
141
|
+
if body != message["body"]:
|
|
142
|
+
headers["Content-Encoding"] = self.content_encoding
|
|
143
|
+
if self.initial_message.get("trailers", False):
|
|
144
|
+
del headers["Content-Length"]
|
|
145
|
+
else:
|
|
146
|
+
headers["Content-Length"] = str(len(body))
|
|
147
|
+
message["body"] = body
|
|
148
|
+
|
|
149
|
+
await self.send(self.initial_message)
|
|
150
|
+
await self.send(message)
|
|
151
|
+
else:
|
|
152
|
+
# Initial body in streaming response.
|
|
153
|
+
body = await self.apply_compression(body, more_body=True)
|
|
154
|
+
|
|
155
|
+
headers = MutableHeaders(raw=self.initial_message["headers"])
|
|
156
|
+
headers.add_vary_header("Accept-Encoding")
|
|
157
|
+
if body != message["body"]:
|
|
158
|
+
headers["Content-Encoding"] = self.content_encoding
|
|
159
|
+
del headers["Content-Length"]
|
|
160
|
+
message["body"] = body
|
|
161
|
+
|
|
162
|
+
await self.send(self.initial_message)
|
|
163
|
+
await self.send(message)
|
|
164
|
+
elif message_type == "http.response.body":
|
|
165
|
+
# Remaining body in streaming response.
|
|
166
|
+
body = message.get("body", b"")
|
|
167
|
+
more_body = message.get("more_body", False)
|
|
168
|
+
|
|
169
|
+
message["body"] = await self.apply_compression(body, more_body=more_body)
|
|
170
|
+
|
|
171
|
+
await self.send(message)
|
|
172
|
+
elif message_type in ("http.response.early_hint", "http.response.trailers"):
|
|
173
|
+
await self.send(message)
|
|
174
|
+
elif message_type == "http.response.pathsend": # pragma: no branch
|
|
175
|
+
# Don't apply GZip to pathsend responses
|
|
176
|
+
await self.send(self.initial_message)
|
|
177
|
+
await self.send(message)
|
|
178
|
+
|
|
179
|
+
async def apply_compression(self, body: bytes, *, more_body: bool) -> bytes:
|
|
180
|
+
"""Apply compression on the response body.
|
|
181
|
+
|
|
182
|
+
If more_body is False, the compression stream is finalized. Compression
|
|
183
|
+
resources are only allocated once a body is actually compressed.
|
|
184
|
+
"""
|
|
185
|
+
return body
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
class GZipResponder(IdentityResponder):
|
|
189
|
+
content_encoding = "gzip"
|
|
190
|
+
|
|
191
|
+
def __init__(
|
|
192
|
+
self,
|
|
193
|
+
app: ASGIApp,
|
|
194
|
+
minimum_size: int,
|
|
195
|
+
compresslevel: int = 9,
|
|
196
|
+
*,
|
|
197
|
+
thread_minimum_size: int = 128 * 1024, # 128 KiB
|
|
198
|
+
exclude_content_types: tuple[str, ...] = DEFAULT_EXCLUDED_CONTENT_TYPES,
|
|
199
|
+
) -> None:
|
|
200
|
+
super().__init__(app, minimum_size, exclude_content_types=exclude_content_types)
|
|
201
|
+
|
|
202
|
+
self.compresslevel = compresslevel
|
|
203
|
+
self.thread_minimum_size = thread_minimum_size
|
|
204
|
+
self._compressor: zlib._Compress | None = None
|
|
205
|
+
|
|
206
|
+
@property
|
|
207
|
+
def compressor(self) -> zlib._Compress:
|
|
208
|
+
if self._compressor is None:
|
|
209
|
+
self._compressor = zlib.compressobj(self.compresslevel, zlib.DEFLATED, 16 + zlib.MAX_WBITS)
|
|
210
|
+
return self._compressor
|
|
211
|
+
|
|
212
|
+
async def apply_compression(self, body: bytes, *, more_body: bool) -> bytes:
|
|
213
|
+
if len(body) >= self.thread_minimum_size:
|
|
214
|
+
# Compressing large chunks inline would block the event loop.
|
|
215
|
+
limiter = _get_gzip_capacity_limiter()
|
|
216
|
+
return await anyio.to_thread.run_sync(self._compress_body, body, more_body, limiter=limiter)
|
|
217
|
+
return self._compress_body(body, more_body)
|
|
218
|
+
|
|
219
|
+
def _compress_body(self, body: bytes, more_body: bool) -> bytes:
|
|
220
|
+
if more_body:
|
|
221
|
+
return self.compressor.compress(body) + self.compressor.flush(zlib.Z_SYNC_FLUSH)
|
|
222
|
+
return self.compressor.compress(body) + self.compressor.flush()
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
async def unattached_send(message: Message) -> NoReturn:
|
|
226
|
+
raise RuntimeError("send awaitable not set") # pragma: no cover
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _normalize_content_types(content_types: tuple[str, ...]) -> tuple[str, ...]:
|
|
230
|
+
return tuple(content_type.partition(";")[0].strip().lower() for content_type in content_types)
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
from kernel.datastructures import URL
|
|
2
|
+
from kernel.responses import PlainTextResponse, RedirectResponse
|
|
3
|
+
from kernel.types import ASGIApp, Receive, Scope, Send
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class HTTPSRedirectMiddleware:
|
|
7
|
+
def __init__(self, app: ASGIApp) -> None:
|
|
8
|
+
self.app = app
|
|
9
|
+
|
|
10
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
11
|
+
if scope["type"] in ("http", "websocket") and scope["scheme"] in ("http", "ws"):
|
|
12
|
+
url = URL(scope=scope)
|
|
13
|
+
if not url.netloc:
|
|
14
|
+
await PlainTextResponse("Invalid host header", status_code=400)(scope, receive, send)
|
|
15
|
+
return
|
|
16
|
+
redirect_scheme = {"http": "https", "ws": "wss"}[url.scheme]
|
|
17
|
+
netloc = url.hostname if url.port in (80, 443) else url.netloc
|
|
18
|
+
url = url.replace(scheme=redirect_scheme, netloc=netloc)
|
|
19
|
+
response = RedirectResponse(url, status_code=307)
|
|
20
|
+
await response(scope, receive, send)
|
|
21
|
+
else:
|
|
22
|
+
await self.app(scope, receive, send)
|