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/websockets.py ADDED
@@ -0,0 +1,202 @@
1
+ from __future__ import annotations
2
+
3
+ import enum
4
+ import json
5
+ from collections.abc import AsyncIterator, Iterable
6
+ from typing import Any, cast
7
+
8
+ from kernel.requests import HTTPConnection, StateT
9
+ from kernel.responses import Response
10
+ from kernel.types import Message, Receive, Scope, Send
11
+
12
+
13
+ class WebSocketState(enum.Enum):
14
+ CONNECTING = 0
15
+ CONNECTED = 1
16
+ DISCONNECTED = 2
17
+ RESPONSE = 3
18
+
19
+
20
+ class WebSocketDisconnect(Exception):
21
+ def __init__(self, code: int = 1000, reason: str | None = None) -> None:
22
+ self.code = code
23
+ self.reason = reason or ""
24
+
25
+
26
+ class WebSocketDisconnected(RuntimeError):
27
+ """
28
+ Raised when attempting to use a disconnected WebSocket.
29
+ """
30
+
31
+
32
+ class WebSocket(HTTPConnection[StateT]):
33
+ def __init__(self, scope: Scope, receive: Receive, send: Send) -> None:
34
+ super().__init__(scope)
35
+ assert scope["type"] == "websocket"
36
+ self._receive = receive
37
+ self._send = send
38
+ self.client_state = WebSocketState.CONNECTING
39
+ self.application_state = WebSocketState.CONNECTING
40
+
41
+ async def receive(self) -> Message:
42
+ """
43
+ Receive ASGI websocket messages, ensuring valid state transitions.
44
+ """
45
+ if self.client_state == WebSocketState.CONNECTING:
46
+ message = await self._receive()
47
+ message_type = message["type"]
48
+ if message_type != "websocket.connect":
49
+ raise RuntimeError(f'Expected ASGI message "websocket.connect", but got {message_type!r}')
50
+ self.client_state = WebSocketState.CONNECTED
51
+ return message
52
+ elif self.client_state == WebSocketState.CONNECTED:
53
+ message = await self._receive()
54
+ message_type = message["type"]
55
+ if message_type not in {"websocket.receive", "websocket.disconnect"}:
56
+ raise RuntimeError(
57
+ f'Expected ASGI message "websocket.receive" or "websocket.disconnect", but got {message_type!r}'
58
+ )
59
+ if message_type == "websocket.disconnect":
60
+ self.client_state = WebSocketState.DISCONNECTED
61
+ return message
62
+ else:
63
+ raise WebSocketDisconnected('Cannot call "receive" once a disconnect message has been received.')
64
+
65
+ async def send(self, message: Message) -> None:
66
+ """
67
+ Send ASGI websocket messages, ensuring valid state transitions.
68
+ """
69
+ if self.application_state == WebSocketState.CONNECTING:
70
+ message_type = message["type"]
71
+ if message_type not in {"websocket.accept", "websocket.close", "websocket.http.response.start"}:
72
+ raise RuntimeError(
73
+ 'Expected ASGI message "websocket.accept", "websocket.close" or "websocket.http.response.start", '
74
+ f"but got {message_type!r}"
75
+ )
76
+ if message_type == "websocket.close":
77
+ self.application_state = WebSocketState.DISCONNECTED
78
+ elif message_type == "websocket.http.response.start":
79
+ self.application_state = WebSocketState.RESPONSE
80
+ else:
81
+ self.application_state = WebSocketState.CONNECTED
82
+ await self._send(message)
83
+ elif self.application_state == WebSocketState.CONNECTED:
84
+ message_type = message["type"]
85
+ if message_type not in {"websocket.send", "websocket.close"}:
86
+ raise RuntimeError(
87
+ f'Expected ASGI message "websocket.send" or "websocket.close", but got {message_type!r}'
88
+ )
89
+ if message_type == "websocket.close":
90
+ self.application_state = WebSocketState.DISCONNECTED
91
+ try:
92
+ await self._send(message)
93
+ except OSError:
94
+ self.application_state = WebSocketState.DISCONNECTED
95
+ raise WebSocketDisconnect(code=1006)
96
+ elif self.application_state == WebSocketState.RESPONSE:
97
+ message_type = message["type"]
98
+ if message_type != "websocket.http.response.body":
99
+ raise RuntimeError(f'Expected ASGI message "websocket.http.response.body", but got {message_type!r}')
100
+ if not message.get("more_body", False):
101
+ self.application_state = WebSocketState.DISCONNECTED
102
+ await self._send(message)
103
+ else:
104
+ raise WebSocketDisconnected('Cannot call "send" once a close message has been sent.')
105
+
106
+ async def accept(
107
+ self,
108
+ subprotocol: str | None = None,
109
+ headers: Iterable[tuple[bytes, bytes]] | None = None,
110
+ ) -> None:
111
+ headers = headers or []
112
+
113
+ if self.client_state == WebSocketState.CONNECTING: # pragma: no branch
114
+ # If we haven't yet seen the 'connect' message, then wait for it first.
115
+ await self.receive()
116
+ await self.send({"type": "websocket.accept", "subprotocol": subprotocol, "headers": headers})
117
+
118
+ def _raise_on_disconnect(self, message: Message) -> None:
119
+ if message["type"] == "websocket.disconnect":
120
+ raise WebSocketDisconnect(message["code"], message.get("reason"))
121
+
122
+ async def receive_text(self) -> str:
123
+ if self.application_state != WebSocketState.CONNECTED:
124
+ raise WebSocketDisconnected('WebSocket is not connected. Need to call "accept" first.')
125
+ message = await self.receive()
126
+ self._raise_on_disconnect(message)
127
+ return cast(str, message["text"])
128
+
129
+ async def receive_bytes(self) -> bytes:
130
+ if self.application_state != WebSocketState.CONNECTED:
131
+ raise WebSocketDisconnected('WebSocket is not connected. Need to call "accept" first.')
132
+ message = await self.receive()
133
+ self._raise_on_disconnect(message)
134
+ return cast(bytes, message["bytes"])
135
+
136
+ async def receive_json(self, mode: str = "text") -> Any:
137
+ if mode not in {"text", "binary"}:
138
+ raise RuntimeError('The "mode" argument should be "text" or "binary".')
139
+ if self.application_state != WebSocketState.CONNECTED:
140
+ raise WebSocketDisconnected('WebSocket is not connected. Need to call "accept" first.')
141
+ message = await self.receive()
142
+ self._raise_on_disconnect(message)
143
+
144
+ if mode == "text":
145
+ text = message["text"]
146
+ else:
147
+ text = message["bytes"].decode("utf-8")
148
+ return json.loads(text)
149
+
150
+ async def iter_text(self) -> AsyncIterator[str]:
151
+ try:
152
+ while True:
153
+ yield await self.receive_text()
154
+ except WebSocketDisconnect:
155
+ pass
156
+
157
+ async def iter_bytes(self) -> AsyncIterator[bytes]:
158
+ try:
159
+ while True:
160
+ yield await self.receive_bytes()
161
+ except WebSocketDisconnect:
162
+ pass
163
+
164
+ async def iter_json(self) -> AsyncIterator[Any]:
165
+ try:
166
+ while True:
167
+ yield await self.receive_json()
168
+ except WebSocketDisconnect:
169
+ pass
170
+
171
+ async def send_text(self, data: str) -> None:
172
+ await self.send({"type": "websocket.send", "text": data})
173
+
174
+ async def send_bytes(self, data: bytes) -> None:
175
+ await self.send({"type": "websocket.send", "bytes": data})
176
+
177
+ async def send_json(self, data: Any, mode: str = "text") -> None:
178
+ if mode not in {"text", "binary"}:
179
+ raise RuntimeError('The "mode" argument should be "text" or "binary".')
180
+ text = json.dumps(data, separators=(",", ":"), ensure_ascii=False)
181
+ if mode == "text":
182
+ await self.send({"type": "websocket.send", "text": text})
183
+ else:
184
+ await self.send({"type": "websocket.send", "bytes": text.encode("utf-8")})
185
+
186
+ async def close(self, code: int = 1000, reason: str | None = None) -> None:
187
+ await self.send({"type": "websocket.close", "code": code, "reason": reason or ""})
188
+
189
+ async def send_denial_response(self, response: Response) -> None:
190
+ if "websocket.http.response" in self.scope.get("extensions", {}):
191
+ await response(self.scope, self.receive, self.send)
192
+ else:
193
+ raise RuntimeError("The server doesn't support the Websocket Denial Response extension.")
194
+
195
+
196
+ class WebSocketClose:
197
+ def __init__(self, code: int = 1000, reason: str | None = None) -> None:
198
+ self.code = code
199
+ self.reason = reason or ""
200
+
201
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
202
+ await send({"type": "websocket.close", "code": self.code, "reason": self.reason})
@@ -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,41 @@
1
+ kernel/__init__.py,sha256=IRZrpkqdnIKvUzecXYFFSnwmLLk96nOd8Dy2ndXk8Dc,25
2
+ kernel/_exception_handler.py,sha256=Ebvr5yp2w1q0mEEvHmWm47BT1QgNO-kv6HT0Xh9CZLo,2356
3
+ kernel/_utils.py,sha256=orU9bOr5H8xQG-8aKmyjW7MR96gHbJWjTNj-zduDoK4,4106
4
+ kernel/applications.py,sha256=tRpjvAdovyWzSUxUreQXEVM5aRQA4O8fFiVhHJyZAnk,5736
5
+ kernel/authentication.py,sha256=fXS3GPl07mM3NFVs4BzdCrZAgKlkB6ghFO0SABbMe0o,5326
6
+ kernel/background.py,sha256=4a7jmFjTbodpDuLNH47B_7mbuPnQ8xaiOL2c34JbG2w,1116
7
+ kernel/concurrency.py,sha256=zEl01uRCQFuzd-6qzexUaLnysev-50CxsB83ZNwLlqk,1698
8
+ kernel/config.py,sha256=QtX0MNIuE1eNJ4GurcubDEIuwMmv2PvRkVXiRPol3Lk,4545
9
+ kernel/convertors.py,sha256=eRttF_jgHH6pMCGp64RAdNWUrTmDS5TjoHqrkHwSrXM,2304
10
+ kernel/datastructures.py,sha256=H32yLO6Y7YiFJ2uVHSkdneFBal5ozSAwaanijY4RrrU,23877
11
+ kernel/endpoints.py,sha256=N7NCtfNL2GFYJX0gCLD962ET0B7mhT2ZiakxecGlJuk,5311
12
+ kernel/exceptions.py,sha256=-0sNmNNLa46g9V6xpsqOqqPwDRJMoe4vEqDAbCVQJTU,1492
13
+ kernel/formparsers.py,sha256=yUWSARbkEMJ7EqP8ZCXs6A9TTOzLIl679p-ISWP39ZY,11726
14
+ kernel/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
15
+ kernel/requests.py,sha256=GZDVurHlJQ3NcgcPOQ2ZdgNOktkSMCQ2kZwjBmR8f-s,13289
16
+ kernel/responses.py,sha256=PZYay2PLD68CzaF2ORvDhANLjc4nUQkPu5f7r-diLHU,23762
17
+ kernel/routing.py,sha256=jUEEEU7RuYgem8Y8qsmyCaSn0r9bKf0VYC8fWQkTYwo,30744
18
+ kernel/schemas.py,sha256=5MTwccNRFyuRI9ndL5z0dMvQdKS7lEgL7C16WT09_SM,5485
19
+ kernel/staticfiles.py,sha256=hz7DeGH-mgSzi28hEDOzJd6cAnwOhIQF_9xP-vCnhk8,9085
20
+ kernel/status.py,sha256=Ca486iHHdGfbRJZlF69QEbPPnDmbBL-9h6s-tk-FJz8,6424
21
+ kernel/templating.py,sha256=A8lI19p5uq2I-w0dx41CdEe4Z9jQROQDBFjSB4U2r7Q,5429
22
+ kernel/testclient.py,sha256=SGGtkblChIPOdqay55aHas_lHMoy0MqAoB3C72ldL0I,24014
23
+ kernel/types.py,sha256=2kXjSeQ50jmoL_HzBB3D7_lbENlOdXhXVTwmfwIa5gE,1032
24
+ kernel/websockets.py,sha256=JTa2xkXJklQAoRjYNmxx4PfbDb_sowv4tWMXGGDKcao,8509
25
+ kernel/middleware/__init__.py,sha256=S4mEB14Qt4zKfITe4DnDbFZl9pzfQi2G1NGSqV5ENQE,1346
26
+ kernel/middleware/authentication.py,sha256=ZW_rClpCbQPTTLC9PK3PbKgmOijiHBa1iFJIV2J-r3k,1788
27
+ kernel/middleware/base.py,sha256=GZf8pk3mURYr7UGalQR6nLi98W3XpDudUVvsLBL7TUQ,10722
28
+ kernel/middleware/body_limit.py,sha256=TzvXTB5kxJ43faXkCDva74CfQZT1H5BcwaMb7aP5Rlc,4597
29
+ kernel/middleware/cors.py,sha256=dYuxAbyPSCsrLxT9reR86XXktW1gMVpJ_SxegjZ1auY,7679
30
+ kernel/middleware/errors.py,sha256=kWBA0P_LLvpl-nbxJ7uDGyjOHWjjaJ7NySX-JklJWHw,8111
31
+ kernel/middleware/exceptions.py,sha256=oV84S2XNVb9cvSRvXfYEpdIMOY--os6OABmIU_3Vvcw,2766
32
+ kernel/middleware/gzip.py,sha256=iEl5kqIRQtf3Mn09ZLzT1I6gl7M_K0Vz8iEQqPBHvrg,9313
33
+ kernel/middleware/httpsredirect.py,sha256=AdQRIIzbbO7jHkLU66oYfbKubqFiscxQoHWeZjthEg4,1014
34
+ kernel/middleware/opentelemetry.py,sha256=qV03Cj3IdLLdoVsRJbNZH9c_dTAaaDK2_O-xKE-X06c,5704
35
+ kernel/middleware/sessions.py,sha256=967G4F4Fs59XyLf8FRxfPZq5YyH2VyuvJUpD5yx-9_4,5232
36
+ kernel/middleware/trustedhost.py,sha256=vLmhDWVWGcCGf1vN3nsS4HH565gKQuF_ug_Ei5232n4,2479
37
+ kernel/middleware/wsgi.py,sha256=NjnRQUc3trTJculeSpcsYN5FJzMgi3sfUICbYesYwH0,5570
38
+ pboot_kernel-1.10.0.1.dist-info/METADATA,sha256=pnsytRd4Iu7HsOttS7QP0h-IPuNND01BVfNM3NOBQ3Y,3715
39
+ pboot_kernel-1.10.0.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
40
+ pboot_kernel-1.10.0.1.dist-info/licenses/LICENSE.md,sha256=3LlWd6AiQCQxh-lk-UGEfRmxeCHPmeWvrmhPqzKMGb8,1518
41
+ pboot_kernel-1.10.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -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.