pboot-kernel 1.10.0.1__tar.gz
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.
- pboot_kernel-1.10.0.1/.gitignore +9 -0
- pboot_kernel-1.10.0.1/CHANGES.md +45 -0
- pboot_kernel-1.10.0.1/LICENSE.md +27 -0
- pboot_kernel-1.10.0.1/PKG-INFO +95 -0
- pboot_kernel-1.10.0.1/README.md +65 -0
- pboot_kernel-1.10.0.1/pyproject.toml +81 -0
- pboot_kernel-1.10.0.1/src/kernel/__init__.py +1 -0
- pboot_kernel-1.10.0.1/src/kernel/_exception_handler.py +67 -0
- pboot_kernel-1.10.0.1/src/kernel/_utils.py +152 -0
- pboot_kernel-1.10.0.1/src/kernel/applications.py +124 -0
- pboot_kernel-1.10.0.1/src/kernel/authentication.py +157 -0
- pboot_kernel-1.10.0.1/src/kernel/background.py +36 -0
- pboot_kernel-1.10.0.1/src/kernel/concurrency.py +59 -0
- pboot_kernel-1.10.0.1/src/kernel/config.py +142 -0
- pboot_kernel-1.10.0.1/src/kernel/convertors.py +89 -0
- pboot_kernel-1.10.0.1/src/kernel/datastructures.py +717 -0
- pboot_kernel-1.10.0.1/src/kernel/endpoints.py +128 -0
- pboot_kernel-1.10.0.1/src/kernel/exceptions.py +43 -0
- pboot_kernel-1.10.0.1/src/kernel/formparsers.py +289 -0
- pboot_kernel-1.10.0.1/src/kernel/middleware/__init__.py +37 -0
- pboot_kernel-1.10.0.1/src/kernel/middleware/authentication.py +52 -0
- pboot_kernel-1.10.0.1/src/kernel/middleware/base.py +254 -0
- pboot_kernel-1.10.0.1/src/kernel/middleware/body_limit.py +132 -0
- pboot_kernel-1.10.0.1/src/kernel/middleware/cors.py +177 -0
- pboot_kernel-1.10.0.1/src/kernel/middleware/errors.py +259 -0
- pboot_kernel-1.10.0.1/src/kernel/middleware/exceptions.py +73 -0
- pboot_kernel-1.10.0.1/src/kernel/middleware/gzip.py +230 -0
- pboot_kernel-1.10.0.1/src/kernel/middleware/httpsredirect.py +22 -0
- pboot_kernel-1.10.0.1/src/kernel/middleware/opentelemetry.py +126 -0
- pboot_kernel-1.10.0.1/src/kernel/middleware/sessions.py +139 -0
- pboot_kernel-1.10.0.1/src/kernel/middleware/trustedhost.py +66 -0
- pboot_kernel-1.10.0.1/src/kernel/middleware/wsgi.py +157 -0
- pboot_kernel-1.10.0.1/src/kernel/py.typed +0 -0
- pboot_kernel-1.10.0.1/src/kernel/requests.py +357 -0
- pboot_kernel-1.10.0.1/src/kernel/responses.py +616 -0
- pboot_kernel-1.10.0.1/src/kernel/routing.py +772 -0
- pboot_kernel-1.10.0.1/src/kernel/schemas.py +152 -0
- pboot_kernel-1.10.0.1/src/kernel/staticfiles.py +231 -0
- pboot_kernel-1.10.0.1/src/kernel/status.py +211 -0
- pboot_kernel-1.10.0.1/src/kernel/templating.py +156 -0
- pboot_kernel-1.10.0.1/src/kernel/testclient.py +624 -0
- pboot_kernel-1.10.0.1/src/kernel/types.py +26 -0
- pboot_kernel-1.10.0.1/src/kernel/websockets.py +202 -0
- pboot_kernel-1.10.0.1/tests/__init__.py +0 -0
- pboot_kernel-1.10.0.1/tests/conftest.py +48 -0
- pboot_kernel-1.10.0.1/tests/middleware/__init__.py +0 -0
- pboot_kernel-1.10.0.1/tests/middleware/test_base.py +1408 -0
- pboot_kernel-1.10.0.1/tests/middleware/test_body_limit.py +368 -0
- pboot_kernel-1.10.0.1/tests/middleware/test_cors.py +627 -0
- pboot_kernel-1.10.0.1/tests/middleware/test_errors.py +105 -0
- pboot_kernel-1.10.0.1/tests/middleware/test_gzip.py +546 -0
- pboot_kernel-1.10.0.1/tests/middleware/test_https_redirect.py +78 -0
- pboot_kernel-1.10.0.1/tests/middleware/test_middleware.py +57 -0
- pboot_kernel-1.10.0.1/tests/middleware/test_opentelemetry.py +548 -0
- pboot_kernel-1.10.0.1/tests/middleware/test_session.py +375 -0
- pboot_kernel-1.10.0.1/tests/middleware/test_trusted_host.py +105 -0
- pboot_kernel-1.10.0.1/tests/middleware/test_wsgi.py +186 -0
- pboot_kernel-1.10.0.1/tests/statics/example.txt +1 -0
- pboot_kernel-1.10.0.1/tests/test__utils.py +132 -0
- pboot_kernel-1.10.0.1/tests/test_applications.py +563 -0
- pboot_kernel-1.10.0.1/tests/test_authentication.py +356 -0
- pboot_kernel-1.10.0.1/tests/test_background.py +89 -0
- pboot_kernel-1.10.0.1/tests/test_concurrency.py +55 -0
- pboot_kernel-1.10.0.1/tests/test_config.py +159 -0
- pboot_kernel-1.10.0.1/tests/test_convertors.py +96 -0
- pboot_kernel-1.10.0.1/tests/test_datastructures.py +635 -0
- pboot_kernel-1.10.0.1/tests/test_endpoints.py +295 -0
- pboot_kernel-1.10.0.1/tests/test_exceptions.py +248 -0
- pboot_kernel-1.10.0.1/tests/test_formparsers.py +1122 -0
- pboot_kernel-1.10.0.1/tests/test_requests.py +713 -0
- pboot_kernel-1.10.0.1/tests/test_responses.py +1268 -0
- pboot_kernel-1.10.0.1/tests/test_routing.py +1266 -0
- pboot_kernel-1.10.0.1/tests/test_schemas.py +312 -0
- pboot_kernel-1.10.0.1/tests/test_staticfiles.py +684 -0
- pboot_kernel-1.10.0.1/tests/test_status.py +33 -0
- pboot_kernel-1.10.0.1/tests/test_templates.py +176 -0
- pboot_kernel-1.10.0.1/tests/test_testclient.py +778 -0
- pboot_kernel-1.10.0.1/tests/test_websockets.py +653 -0
- pboot_kernel-1.10.0.1/tests/types.py +27 -0
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
pboot-kernel
|
|
2
|
+
============
|
|
3
|
+
|
|
4
|
+
Version 1.10.0.1
|
|
5
|
+
---------------
|
|
6
|
+
|
|
7
|
+
Forked from Starlette 1.10.0 (BSD-3-Clause, Encode/Kludex) so pboot owns the
|
|
8
|
+
ASGI layer it spends all its time in.
|
|
9
|
+
|
|
10
|
+
- Package renamed to ``kernel``: internal imports, the ``TYPE_CHECKING``
|
|
11
|
+
hints in ``types.py``, the deprecation-warning module paths, the
|
|
12
|
+
OpenTelemetry tracer name, and the module the test suite's ``blockbuster``
|
|
13
|
+
fixture watches.
|
|
14
|
+
|
|
15
|
+
- The ``scope`` keys stay as they were: ``starlette.exception_handlers``,
|
|
16
|
+
``starlette.max_body_size``, ``starlette._body_limit_responder``,
|
|
17
|
+
``starlette.opentelemetry``. They are contract keys rather than import
|
|
18
|
+
paths — third-party ASGI middleware reads them, and pboot's own exception
|
|
19
|
+
middleware is layered on the first — so renaming them would break code we
|
|
20
|
+
do not control and save nothing at runtime. The prefix is vestigial.
|
|
21
|
+
|
|
22
|
+
- Class and function names are untouched. ``Starlette``, ``Route``,
|
|
23
|
+
``Request``, ``Response``, ``WebSocket``, the middleware, the test client:
|
|
24
|
+
all identical, so a migration is a search-and-replace of the import path.
|
|
25
|
+
|
|
26
|
+
- ``__version__`` is ``1.10.0.1`` — ``1.10.0`` plus the fork's patch level.
|
|
27
|
+
|
|
28
|
+
- Upstream's test suite came along, renamed, and passes. It is the correctness
|
|
29
|
+
contract for every later optimisation: change the router, and these tests
|
|
30
|
+
say whether the ASGI surface still behaves.
|
|
31
|
+
|
|
32
|
+
Planned, in the order that pays:
|
|
33
|
+
|
|
34
|
+
- Router matching without the per-request regex scan and without building a
|
|
35
|
+
``Request`` for paths that only need a route lookup.
|
|
36
|
+
|
|
37
|
+
- Static route lookup that does not re-derive ``get_route_path`` on every
|
|
38
|
+
call, and a 404/405 path that stops raising a Python exception to report a
|
|
39
|
+
miss.
|
|
40
|
+
|
|
41
|
+
- ``Response`` headers built once for the fixed JSON/HTML cases instead of
|
|
42
|
+
``init_headers`` on every response.
|
|
43
|
+
|
|
44
|
+
- Drop ``anyio`` from the default path for the plain-asyncio case, if the
|
|
45
|
+
measurements say the abstraction costs anything after the above.
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
Copyright © 2018, [Encode OSS Ltd](https://www.encode.io/).
|
|
2
|
+
All rights reserved.
|
|
3
|
+
|
|
4
|
+
Redistribution and use in source and binary forms, with or without
|
|
5
|
+
modification, are permitted provided that the following conditions are met:
|
|
6
|
+
|
|
7
|
+
* Redistributions of source code must retain the above copyright notice, this
|
|
8
|
+
list of conditions and the following disclaimer.
|
|
9
|
+
|
|
10
|
+
* Redistributions in binary form must reproduce the above copyright notice,
|
|
11
|
+
this list of conditions and the following disclaimer in the documentation
|
|
12
|
+
and/or other materials provided with the distribution.
|
|
13
|
+
|
|
14
|
+
* Neither the name of the copyright holder nor the names of its
|
|
15
|
+
contributors may be used to endorse or promote products derived from
|
|
16
|
+
this software without specific prior written permission.
|
|
17
|
+
|
|
18
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
19
|
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
20
|
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
21
|
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
22
|
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
23
|
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
24
|
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
25
|
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
26
|
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
27
|
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: pboot-kernel
|
|
3
|
+
Version: 1.10.0.1
|
|
4
|
+
Summary: The ASGI kernel that ships with pboot — a Starlette 1.10.0 fork.
|
|
5
|
+
Project-URL: Source, https://gitee.com/pboot-org/pboot-kernel
|
|
6
|
+
Project-URL: Homepage, https://gitee.com/pboot-org/pboot
|
|
7
|
+
Maintainer: pboot-org
|
|
8
|
+
License-Expression: BSD-3-Clause
|
|
9
|
+
License-File: LICENSE.md
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Environment :: Web Environment
|
|
12
|
+
Classifier: Framework :: AnyIO
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
18
|
+
Classifier: Typing :: Typed
|
|
19
|
+
Requires-Python: >=3.11
|
|
20
|
+
Requires-Dist: anyio<5,>=4.0.0
|
|
21
|
+
Requires-Dist: typing-extensions>=4.10.0; python_version < '3.13'
|
|
22
|
+
Provides-Extra: full
|
|
23
|
+
Requires-Dist: httpx2>=2.0.0; extra == 'full'
|
|
24
|
+
Requires-Dist: httpx<0.29.0,>=0.27.0; extra == 'full'
|
|
25
|
+
Requires-Dist: itsdangerous; extra == 'full'
|
|
26
|
+
Requires-Dist: opentelemetry-api; extra == 'full'
|
|
27
|
+
Requires-Dist: python-multipart>=0.0.18; extra == 'full'
|
|
28
|
+
Requires-Dist: pyyaml; extra == 'full'
|
|
29
|
+
Description-Content-Type: text/markdown
|
|
30
|
+
|
|
31
|
+
# pboot-kernel
|
|
32
|
+
|
|
33
|
+
The ASGI kernel that ships with [pboot](https://gitee.com/pboot-org/pboot).
|
|
34
|
+
|
|
35
|
+
It is a fork of **Starlette 1.10.0** (BSD-3-Clause, Encode/Kludex) with the
|
|
36
|
+
import package renamed to `kernel`. Same routing, same middleware, same
|
|
37
|
+
request/response objects, same test client — pboot calls it exactly the way it
|
|
38
|
+
called starlette, so the rename is the only thing that changed.
|
|
39
|
+
|
|
40
|
+
```python
|
|
41
|
+
from kernel.applications import Starlette
|
|
42
|
+
from kernel.responses import JSONResponse
|
|
43
|
+
from kernel.routing import Route
|
|
44
|
+
|
|
45
|
+
async def homepage(request):
|
|
46
|
+
return JSONResponse({"hello": "world"})
|
|
47
|
+
|
|
48
|
+
app = Starlette(routes=[Route("/", homepage)])
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Why a fork
|
|
52
|
+
|
|
53
|
+
pboot's hot path *is* this code. Starlette's router is entered on every request,
|
|
54
|
+
and the twenty performance passes on pboot were spent working around decisions
|
|
55
|
+
it makes for everyone: a linear regex scan per request, `Request` objects built
|
|
56
|
+
on paths that never look at them, headers recomputed for static responses. Those
|
|
57
|
+
were fixable from the outside, but only by duplicating logic, and every
|
|
58
|
+
duplication is a place where pboot and starlette can drift apart.
|
|
59
|
+
|
|
60
|
+
Owning the fork means the next round of optimisation edits the router itself
|
|
61
|
+
instead of shadowing it, and it means the ASGI layer ships on pboot's release
|
|
62
|
+
cadence rather than someone else's.
|
|
63
|
+
|
|
64
|
+
## What changed relative to Starlette 1.10.0
|
|
65
|
+
|
|
66
|
+
- The import package is `kernel`, everywhere: internal imports, the type
|
|
67
|
+
hints in `types.py`, the deprecation warning module paths, the OpenTelemetry
|
|
68
|
+
tracer name.
|
|
69
|
+
- `__version__` is `1.10.0.1`.
|
|
70
|
+
- Upstream's own test suite is included and renamed; it is the correctness
|
|
71
|
+
contract for the fork.
|
|
72
|
+
|
|
73
|
+
Deliberately **not** renamed: the `scope` keys `starlette.exception_handlers`,
|
|
74
|
+
`starlette.max_body_size`, `starlette._body_limit_responder` and
|
|
75
|
+
`starlette.opentelemetry`. Those are cross-package contract keys — third-party
|
|
76
|
+
ASGI middleware reads them, and pboot's own middleware layer sits on the first
|
|
77
|
+
one. Renaming them would break other people's code for zero runtime gain; the
|
|
78
|
+
prefix is now a historical string, not an import path.
|
|
79
|
+
|
|
80
|
+
Class and function names are unchanged (`Starlette`, `Route`, `Request`,
|
|
81
|
+
`Response`, `WebSocket`, …). The fork is meant to be a drop-in at the import
|
|
82
|
+
level first, and to diverge only where there is a measured reason.
|
|
83
|
+
|
|
84
|
+
## Tests
|
|
85
|
+
|
|
86
|
+
```bash
|
|
87
|
+
pytest tests -q
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
`trio` is needed for the async backends; `blockbuster` enables the "no blocking
|
|
91
|
+
calls in the event loop" fixture.
|
|
92
|
+
|
|
93
|
+
## Licence
|
|
94
|
+
|
|
95
|
+
BSD-3-Clause, same as upstream. See [LICENSE.md](LICENSE.md).
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
# pboot-kernel
|
|
2
|
+
|
|
3
|
+
The ASGI kernel that ships with [pboot](https://gitee.com/pboot-org/pboot).
|
|
4
|
+
|
|
5
|
+
It is a fork of **Starlette 1.10.0** (BSD-3-Clause, Encode/Kludex) with the
|
|
6
|
+
import package renamed to `kernel`. Same routing, same middleware, same
|
|
7
|
+
request/response objects, same test client — pboot calls it exactly the way it
|
|
8
|
+
called starlette, so the rename is the only thing that changed.
|
|
9
|
+
|
|
10
|
+
```python
|
|
11
|
+
from kernel.applications import Starlette
|
|
12
|
+
from kernel.responses import JSONResponse
|
|
13
|
+
from kernel.routing import Route
|
|
14
|
+
|
|
15
|
+
async def homepage(request):
|
|
16
|
+
return JSONResponse({"hello": "world"})
|
|
17
|
+
|
|
18
|
+
app = Starlette(routes=[Route("/", homepage)])
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Why a fork
|
|
22
|
+
|
|
23
|
+
pboot's hot path *is* this code. Starlette's router is entered on every request,
|
|
24
|
+
and the twenty performance passes on pboot were spent working around decisions
|
|
25
|
+
it makes for everyone: a linear regex scan per request, `Request` objects built
|
|
26
|
+
on paths that never look at them, headers recomputed for static responses. Those
|
|
27
|
+
were fixable from the outside, but only by duplicating logic, and every
|
|
28
|
+
duplication is a place where pboot and starlette can drift apart.
|
|
29
|
+
|
|
30
|
+
Owning the fork means the next round of optimisation edits the router itself
|
|
31
|
+
instead of shadowing it, and it means the ASGI layer ships on pboot's release
|
|
32
|
+
cadence rather than someone else's.
|
|
33
|
+
|
|
34
|
+
## What changed relative to Starlette 1.10.0
|
|
35
|
+
|
|
36
|
+
- The import package is `kernel`, everywhere: internal imports, the type
|
|
37
|
+
hints in `types.py`, the deprecation warning module paths, the OpenTelemetry
|
|
38
|
+
tracer name.
|
|
39
|
+
- `__version__` is `1.10.0.1`.
|
|
40
|
+
- Upstream's own test suite is included and renamed; it is the correctness
|
|
41
|
+
contract for the fork.
|
|
42
|
+
|
|
43
|
+
Deliberately **not** renamed: the `scope` keys `starlette.exception_handlers`,
|
|
44
|
+
`starlette.max_body_size`, `starlette._body_limit_responder` and
|
|
45
|
+
`starlette.opentelemetry`. Those are cross-package contract keys — third-party
|
|
46
|
+
ASGI middleware reads them, and pboot's own middleware layer sits on the first
|
|
47
|
+
one. Renaming them would break other people's code for zero runtime gain; the
|
|
48
|
+
prefix is now a historical string, not an import path.
|
|
49
|
+
|
|
50
|
+
Class and function names are unchanged (`Starlette`, `Route`, `Request`,
|
|
51
|
+
`Response`, `WebSocket`, …). The fork is meant to be a drop-in at the import
|
|
52
|
+
level first, and to diverge only where there is a measured reason.
|
|
53
|
+
|
|
54
|
+
## Tests
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
pytest tests -q
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
`trio` is needed for the async backends; `blockbuster` enables the "no blocking
|
|
61
|
+
calls in the event loop" fixture.
|
|
62
|
+
|
|
63
|
+
## Licence
|
|
64
|
+
|
|
65
|
+
BSD-3-Clause, same as upstream. See [LICENSE.md](LICENSE.md).
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "pboot-kernel"
|
|
3
|
+
version = "1.10.0.1"
|
|
4
|
+
description = "The ASGI kernel that ships with pboot — a Starlette 1.10.0 fork."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "BSD-3-Clause"
|
|
7
|
+
license-files = ["LICENSE.md"]
|
|
8
|
+
maintainers = [{name = "pboot-org"}]
|
|
9
|
+
classifiers = [
|
|
10
|
+
"Development Status :: 4 - Beta",
|
|
11
|
+
"Environment :: Web Environment",
|
|
12
|
+
"Framework :: AnyIO",
|
|
13
|
+
"Intended Audience :: Developers",
|
|
14
|
+
"Operating System :: OS Independent",
|
|
15
|
+
"Programming Language :: Python",
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Topic :: Internet :: WWW/HTTP",
|
|
18
|
+
"Typing :: Typed",
|
|
19
|
+
]
|
|
20
|
+
requires-python = ">=3.11"
|
|
21
|
+
dependencies = [
|
|
22
|
+
"anyio>=4.0.0,<5",
|
|
23
|
+
"typing_extensions>=4.10.0; python_version < '3.13'",
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
[project.optional-dependencies]
|
|
27
|
+
full = [
|
|
28
|
+
"itsdangerous",
|
|
29
|
+
"opentelemetry-api",
|
|
30
|
+
"python-multipart>=0.0.18",
|
|
31
|
+
"pyyaml",
|
|
32
|
+
"httpx>=0.27.0,<0.29.0",
|
|
33
|
+
"httpx2>=2.0.0",
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
[dependency-groups]
|
|
37
|
+
dev = [
|
|
38
|
+
"pboot-kernel[full]",
|
|
39
|
+
"blockbuster>=1.5.23",
|
|
40
|
+
"pytest>=9.1.1",
|
|
41
|
+
"trio>=0.34.0",
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
[project.urls]
|
|
45
|
+
Source = "https://gitee.com/pboot-org/pboot-kernel"
|
|
46
|
+
Homepage = "https://gitee.com/pboot-org/pboot"
|
|
47
|
+
|
|
48
|
+
[build-system]
|
|
49
|
+
requires = ["hatchling"]
|
|
50
|
+
build-backend = "hatchling.build"
|
|
51
|
+
|
|
52
|
+
[tool.hatch.version]
|
|
53
|
+
path = "src/kernel/__init__.py"
|
|
54
|
+
|
|
55
|
+
[tool.hatch.build.targets.wheel]
|
|
56
|
+
packages = ["src/kernel"]
|
|
57
|
+
|
|
58
|
+
[tool.ruff]
|
|
59
|
+
line-length = 120
|
|
60
|
+
|
|
61
|
+
[tool.ruff.lint]
|
|
62
|
+
select = ["E", "F", "I", "FA", "UP", "RUF100"]
|
|
63
|
+
ignore = ["UP031"]
|
|
64
|
+
|
|
65
|
+
[tool.ruff.lint.isort]
|
|
66
|
+
combine-as-imports = true
|
|
67
|
+
|
|
68
|
+
[tool.pytest.ini_options]
|
|
69
|
+
testpaths = ["tests"]
|
|
70
|
+
# 开发机 venv 里装了 pytest-asyncio,它在 configure 阶段发 DeprecationWarning;
|
|
71
|
+
# 上面的 filterwarnings=error 会把它升级成 INTERNALERROR。这个包不用它,给个默认值即可。
|
|
72
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
73
|
+
addopts = "-rXs --strict-config --strict-markers"
|
|
74
|
+
xfail_strict = true
|
|
75
|
+
filterwarnings = [
|
|
76
|
+
"error",
|
|
77
|
+
"ignore: run_until_first_complete is deprecated and will be removed in a future version.:kernel.exceptions.StarletteDeprecationWarning",
|
|
78
|
+
"ignore: kernel.middleware.wsgi is deprecated and will be removed in a future release.*:kernel.exceptions.StarletteDeprecationWarning",
|
|
79
|
+
"ignore: Use 'content=<...>' to upload raw bytes/text content.:DeprecationWarning",
|
|
80
|
+
"ignore: Using `httpx` with `kernel.testclient` is deprecated.*:kernel.exceptions.StarletteDeprecationWarning",
|
|
81
|
+
]
|
|
@@ -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
|
|
@@ -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
|
|
@@ -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)
|