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/schemas.py ADDED
@@ -0,0 +1,152 @@
1
+ from __future__ import annotations
2
+
3
+ import inspect
4
+ import re
5
+ from collections.abc import Callable
6
+ from typing import Any, NamedTuple
7
+
8
+ from kernel.requests import Request
9
+ from kernel.responses import Response
10
+ from kernel.routing import BaseRoute, Host, Mount, Route
11
+
12
+ try:
13
+ import yaml
14
+ except ModuleNotFoundError: # pragma: no cover
15
+ yaml = None # type: ignore[assignment]
16
+
17
+
18
+ class OpenAPIResponse(Response):
19
+ media_type = "application/vnd.oai.openapi"
20
+
21
+ def render(self, content: Any) -> bytes:
22
+ assert yaml is not None, "`pyyaml` must be installed to use OpenAPIResponse."
23
+ assert isinstance(content, dict), "The schema passed to OpenAPIResponse should be a dictionary."
24
+ return yaml.dump(content, default_flow_style=False).encode("utf-8")
25
+
26
+
27
+ class EndpointInfo(NamedTuple):
28
+ path: str
29
+ http_method: str
30
+ func: Callable[..., Any]
31
+
32
+
33
+ _remove_converter_pattern = re.compile(r":\w+}")
34
+
35
+
36
+ class BaseSchemaGenerator:
37
+ def get_schema(self, routes: list[BaseRoute]) -> dict[str, Any]:
38
+ raise NotImplementedError() # pragma: no cover
39
+
40
+ def get_endpoints(self, routes: list[BaseRoute]) -> list[EndpointInfo]:
41
+ """
42
+ Given the routes, yields the following information:
43
+
44
+ - path
45
+ eg: /users/
46
+ - http_method
47
+ one of 'get', 'post', 'put', 'patch', 'delete', 'options', 'query'
48
+ - func
49
+ method ready to extract the docstring
50
+ """
51
+ endpoints_info: list[EndpointInfo] = []
52
+
53
+ for route in routes:
54
+ if isinstance(route, Mount | Host):
55
+ routes = route.routes or []
56
+ if isinstance(route, Mount):
57
+ path = self._remove_converter(route.path)
58
+ else:
59
+ path = ""
60
+ sub_endpoints = [
61
+ EndpointInfo(
62
+ path="".join((path, sub_endpoint.path)),
63
+ http_method=sub_endpoint.http_method,
64
+ func=sub_endpoint.func,
65
+ )
66
+ for sub_endpoint in self.get_endpoints(routes)
67
+ ]
68
+ endpoints_info.extend(sub_endpoints)
69
+
70
+ elif not isinstance(route, Route) or not route.include_in_schema:
71
+ continue
72
+
73
+ elif inspect.isfunction(route.endpoint) or inspect.ismethod(route.endpoint):
74
+ path = self._remove_converter(route.path)
75
+ for method in route.methods or ["GET"]:
76
+ if method == "HEAD":
77
+ continue
78
+ endpoints_info.append(EndpointInfo(path, method.lower(), route.endpoint))
79
+ else:
80
+ path = self._remove_converter(route.path)
81
+ for method in ["get", "post", "put", "patch", "delete", "options", "query"]:
82
+ if not hasattr(route.endpoint, method):
83
+ continue
84
+ func = getattr(route.endpoint, method)
85
+ endpoints_info.append(EndpointInfo(path, method.lower(), func))
86
+
87
+ return endpoints_info
88
+
89
+ def _remove_converter(self, path: str) -> str:
90
+ """
91
+ Remove the converter from the path.
92
+ For example, a route like this:
93
+ Route("/users/{id:int}", endpoint=get_user, methods=["GET"])
94
+ Should be represented as `/users/{id}` in the OpenAPI schema.
95
+ """
96
+ return _remove_converter_pattern.sub("}", path)
97
+
98
+ def parse_docstring(self, func_or_method: Callable[..., Any]) -> dict[str, Any]:
99
+ """
100
+ Given a function, parse the docstring as YAML and return a dictionary of info.
101
+ """
102
+ docstring = func_or_method.__doc__
103
+ if not docstring:
104
+ return {}
105
+
106
+ assert yaml is not None, "`pyyaml` must be installed to use parse_docstring."
107
+
108
+ # We support having regular docstrings before the schema
109
+ # definition. Here we return just the schema part from
110
+ # the docstring.
111
+ docstring = docstring.split("---")[-1]
112
+
113
+ parsed = yaml.safe_load(docstring)
114
+
115
+ if not isinstance(parsed, dict):
116
+ # A regular docstring (not yaml formatted) can return
117
+ # a simple string here, which wouldn't follow the schema.
118
+ return {}
119
+
120
+ return parsed
121
+
122
+ def OpenAPIResponse(self, request: Request) -> Response:
123
+ routes = request.app.routes
124
+ schema = self.get_schema(routes=routes)
125
+ return OpenAPIResponse(schema)
126
+
127
+
128
+ class SchemaGenerator(BaseSchemaGenerator):
129
+ def __init__(self, base_schema: dict[str, Any]) -> None:
130
+ self.base_schema = base_schema
131
+
132
+ def get_schema(self, routes: list[BaseRoute]) -> dict[str, Any]:
133
+ schema = dict(self.base_schema)
134
+ schema.setdefault("paths", {})
135
+ openapi_version_match = re.match(r"^(\d+)\.(\d+)", str(schema.get("openapi", "")))
136
+ supports_query = openapi_version_match is not None and tuple(map(int, openapi_version_match.groups())) >= (3, 2)
137
+ endpoints_info = self.get_endpoints(routes)
138
+
139
+ for endpoint in endpoints_info:
140
+ if endpoint.http_method == "query" and not supports_query:
141
+ continue
142
+ parsed = self.parse_docstring(endpoint.func)
143
+
144
+ if not parsed:
145
+ continue
146
+
147
+ if endpoint.path not in schema["paths"]:
148
+ schema["paths"][endpoint.path] = {}
149
+
150
+ schema["paths"][endpoint.path][endpoint.http_method] = parsed
151
+
152
+ return schema
kernel/staticfiles.py ADDED
@@ -0,0 +1,231 @@
1
+ from __future__ import annotations
2
+
3
+ import errno
4
+ import importlib.util
5
+ import os
6
+ import stat
7
+ from email.utils import parsedate
8
+ from typing import Union
9
+
10
+ import anyio
11
+ import anyio.to_thread
12
+
13
+ from kernel._utils import get_route_path
14
+ from kernel.datastructures import URL, Headers
15
+ from kernel.exceptions import HTTPException
16
+ from kernel.responses import FileResponse, RedirectResponse, Response
17
+ from kernel.types import Receive, Scope, Send
18
+ from kernel.websockets import WebSocketClose
19
+
20
+ PathLike = Union[str, "os.PathLike[str]"]
21
+
22
+
23
+ class NotModifiedResponse(Response):
24
+ NOT_MODIFIED_HEADERS = (
25
+ "cache-control",
26
+ "content-location",
27
+ "date",
28
+ "etag",
29
+ "expires",
30
+ "vary",
31
+ )
32
+
33
+ def __init__(self, headers: Headers):
34
+ super().__init__(
35
+ status_code=304,
36
+ headers={name: value for name, value in headers.items() if name in self.NOT_MODIFIED_HEADERS},
37
+ )
38
+
39
+
40
+ class StaticFiles:
41
+ def __init__(
42
+ self,
43
+ *,
44
+ directory: PathLike | None = None,
45
+ packages: list[str | tuple[str, str]] | None = None,
46
+ html: bool = False,
47
+ check_dir: bool = True,
48
+ follow_symlink: bool = False,
49
+ ) -> None:
50
+ self.directory = directory
51
+ self.packages = packages
52
+ self.all_directories = self.get_directories(directory, packages)
53
+ self.html = html
54
+ self.config_checked = False
55
+ self.follow_symlink = follow_symlink
56
+ if check_dir and directory is not None and not os.path.isdir(directory):
57
+ raise RuntimeError(f"Directory '{directory}' does not exist")
58
+
59
+ def get_directories(
60
+ self,
61
+ directory: PathLike | None = None,
62
+ packages: list[str | tuple[str, str]] | None = None,
63
+ ) -> list[PathLike]:
64
+ """
65
+ Given `directory` and `packages` arguments, return a list of all the
66
+ directories that should be used for serving static files from.
67
+ """
68
+ directories = []
69
+ if directory is not None:
70
+ directories.append(directory)
71
+
72
+ for package in packages or []:
73
+ if isinstance(package, tuple):
74
+ package, statics_dir = package
75
+ else:
76
+ statics_dir = "statics"
77
+ spec = importlib.util.find_spec(package)
78
+ assert spec is not None, f"Package {package!r} could not be found."
79
+ assert spec.origin is not None, f"Package {package!r} could not be found."
80
+ package_directory = os.path.normpath(os.path.join(spec.origin, "..", statics_dir))
81
+ assert os.path.isdir(package_directory), (
82
+ f"Directory '{statics_dir!r}' in package {package!r} could not be found."
83
+ )
84
+ directories.append(package_directory)
85
+
86
+ return directories
87
+
88
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
89
+ """
90
+ The ASGI entry point.
91
+ """
92
+ if scope["type"] == "websocket":
93
+ websocket_close = WebSocketClose()
94
+ await websocket_close(scope, receive, send)
95
+ return
96
+
97
+ assert scope["type"] == "http"
98
+
99
+ if not self.config_checked:
100
+ await self.check_config()
101
+ self.config_checked = True
102
+
103
+ path = self.get_path(scope)
104
+ response = await self.get_response(path, scope)
105
+ await response(scope, receive, send)
106
+
107
+ def get_path(self, scope: Scope) -> str:
108
+ """
109
+ Given the ASGI scope, return the `path` string to serve up,
110
+ with OS specific path separators, and any '..', '.' components removed.
111
+ """
112
+ route_path = get_route_path(scope)
113
+ return os.path.normpath(os.path.join(*route_path.split("/")))
114
+
115
+ async def get_response(self, path: str, scope: Scope) -> Response:
116
+ """
117
+ Returns an HTTP response, given the incoming path, method and request headers.
118
+ """
119
+ if scope["method"] not in ("GET", "HEAD"):
120
+ raise HTTPException(status_code=405, headers={"Allow": "GET, HEAD"})
121
+
122
+ try:
123
+ full_path, stat_result = await anyio.to_thread.run_sync(self.lookup_path, path)
124
+ except PermissionError:
125
+ raise HTTPException(status_code=401)
126
+ except OSError as exc:
127
+ # Filename is too long, so it can't be a valid static file.
128
+ if exc.errno == errno.ENAMETOOLONG:
129
+ raise HTTPException(status_code=404)
130
+
131
+ raise exc
132
+ except ValueError:
133
+ # Null bytes or other invalid characters in the path.
134
+ raise HTTPException(status_code=404)
135
+
136
+ if stat_result and stat.S_ISREG(stat_result.st_mode):
137
+ # We have a static file to serve.
138
+ return self.file_response(full_path, stat_result, scope)
139
+
140
+ elif stat_result and stat.S_ISDIR(stat_result.st_mode) and self.html:
141
+ # We're in HTML mode, and have got a directory URL.
142
+ # Check if we have 'index.html' file to serve.
143
+ index_path = os.path.join(path, "index.html")
144
+ full_path, stat_result = await anyio.to_thread.run_sync(self.lookup_path, index_path)
145
+ if stat_result is not None and stat.S_ISREG(stat_result.st_mode):
146
+ if not scope["path"].endswith("/"):
147
+ # Directory URLs should redirect to always end in "/".
148
+ url = URL(scope=scope)
149
+ url = url.replace(path=url.path + "/")
150
+ return RedirectResponse(url=url)
151
+ return self.file_response(full_path, stat_result, scope)
152
+
153
+ if self.html:
154
+ # Check for '404.html' if we're in HTML mode.
155
+ full_path, stat_result = await anyio.to_thread.run_sync(self.lookup_path, "404.html")
156
+ if stat_result and stat.S_ISREG(stat_result.st_mode):
157
+ return FileResponse(full_path, stat_result=stat_result, status_code=404)
158
+ raise HTTPException(status_code=404)
159
+
160
+ def lookup_path(self, path: str) -> tuple[str, os.stat_result | None]:
161
+ # Reject absolute paths so they cannot escape the served directory.
162
+ if path.startswith(("/", "\\")):
163
+ return "", None
164
+ for directory in self.all_directories:
165
+ joined_path = os.path.join(directory, path)
166
+ if self.follow_symlink:
167
+ full_path = os.path.abspath(joined_path)
168
+ directory = os.path.abspath(directory)
169
+ else:
170
+ full_path = os.path.realpath(joined_path)
171
+ directory = os.path.realpath(directory)
172
+ if os.path.commonpath([full_path, directory]) != str(directory):
173
+ # Don't allow misbehaving clients to break out of the static files directory.
174
+ continue
175
+ try:
176
+ return full_path, os.stat(full_path)
177
+ except (FileNotFoundError, NotADirectoryError):
178
+ continue
179
+ return "", None
180
+
181
+ def file_response(
182
+ self,
183
+ full_path: PathLike,
184
+ stat_result: os.stat_result,
185
+ scope: Scope,
186
+ status_code: int = 200,
187
+ ) -> Response:
188
+ request_headers = Headers(scope=scope)
189
+
190
+ response = FileResponse(full_path, status_code=status_code, stat_result=stat_result)
191
+ if self.is_not_modified(response.headers, request_headers):
192
+ return NotModifiedResponse(response.headers)
193
+ return response
194
+
195
+ async def check_config(self) -> None:
196
+ """
197
+ Perform a one-off configuration check that StaticFiles is actually
198
+ pointed at a directory, so that we can raise loud errors rather than
199
+ just returning 404 responses.
200
+ """
201
+ if self.directory is None:
202
+ return
203
+
204
+ try:
205
+ stat_result = await anyio.to_thread.run_sync(os.stat, self.directory)
206
+ except FileNotFoundError:
207
+ raise RuntimeError(f"StaticFiles directory '{self.directory}' does not exist.")
208
+ if not (stat.S_ISDIR(stat_result.st_mode) or stat.S_ISLNK(stat_result.st_mode)):
209
+ raise RuntimeError(f"StaticFiles path '{self.directory}' is not a directory.")
210
+
211
+ def is_not_modified(self, response_headers: Headers, request_headers: Headers) -> bool:
212
+ """
213
+ Given the request and response headers, return `True` if an HTTP
214
+ "Not Modified" response could be returned instead.
215
+ """
216
+ if if_none_match := request_headers.get("if-none-match"):
217
+ if if_none_match.strip() == "*":
218
+ return True
219
+ # The "etag" header is added by FileResponse, so it's always present.
220
+ etag = response_headers["etag"]
221
+ return etag in [tag.strip().removeprefix("W/") for tag in if_none_match.split(",")]
222
+
223
+ try:
224
+ if_modified_since = parsedate(request_headers["if-modified-since"])
225
+ last_modified = parsedate(response_headers["last-modified"])
226
+ if if_modified_since is not None and last_modified is not None and if_modified_since >= last_modified:
227
+ return True
228
+ except KeyError:
229
+ pass
230
+
231
+ return False
kernel/status.py ADDED
@@ -0,0 +1,211 @@
1
+ """
2
+ HTTP codes
3
+ See HTTP Status Code Registry:
4
+ https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
5
+
6
+ And RFC 9110 - https://www.rfc-editor.org/rfc/rfc9110
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import warnings
12
+
13
+ from kernel.exceptions import StarletteDeprecationWarning
14
+
15
+ __all__ = [
16
+ "HTTP_100_CONTINUE",
17
+ "HTTP_101_SWITCHING_PROTOCOLS",
18
+ "HTTP_102_PROCESSING",
19
+ "HTTP_103_EARLY_HINTS",
20
+ "HTTP_200_OK",
21
+ "HTTP_201_CREATED",
22
+ "HTTP_202_ACCEPTED",
23
+ "HTTP_203_NON_AUTHORITATIVE_INFORMATION",
24
+ "HTTP_204_NO_CONTENT",
25
+ "HTTP_205_RESET_CONTENT",
26
+ "HTTP_206_PARTIAL_CONTENT",
27
+ "HTTP_207_MULTI_STATUS",
28
+ "HTTP_208_ALREADY_REPORTED",
29
+ "HTTP_226_IM_USED",
30
+ "HTTP_300_MULTIPLE_CHOICES",
31
+ "HTTP_301_MOVED_PERMANENTLY",
32
+ "HTTP_302_FOUND",
33
+ "HTTP_303_SEE_OTHER",
34
+ "HTTP_304_NOT_MODIFIED",
35
+ "HTTP_305_USE_PROXY",
36
+ "HTTP_306_RESERVED",
37
+ "HTTP_307_TEMPORARY_REDIRECT",
38
+ "HTTP_308_PERMANENT_REDIRECT",
39
+ "HTTP_400_BAD_REQUEST",
40
+ "HTTP_401_UNAUTHORIZED",
41
+ "HTTP_402_PAYMENT_REQUIRED",
42
+ "HTTP_403_FORBIDDEN",
43
+ "HTTP_404_NOT_FOUND",
44
+ "HTTP_405_METHOD_NOT_ALLOWED",
45
+ "HTTP_406_NOT_ACCEPTABLE",
46
+ "HTTP_407_PROXY_AUTHENTICATION_REQUIRED",
47
+ "HTTP_408_REQUEST_TIMEOUT",
48
+ "HTTP_409_CONFLICT",
49
+ "HTTP_410_GONE",
50
+ "HTTP_411_LENGTH_REQUIRED",
51
+ "HTTP_412_PRECONDITION_FAILED",
52
+ "HTTP_413_CONTENT_TOO_LARGE",
53
+ "HTTP_414_URI_TOO_LONG",
54
+ "HTTP_415_UNSUPPORTED_MEDIA_TYPE",
55
+ "HTTP_416_RANGE_NOT_SATISFIABLE",
56
+ "HTTP_417_EXPECTATION_FAILED",
57
+ "HTTP_418_IM_A_TEAPOT",
58
+ "HTTP_421_MISDIRECTED_REQUEST",
59
+ "HTTP_422_UNPROCESSABLE_CONTENT",
60
+ "HTTP_423_LOCKED",
61
+ "HTTP_424_FAILED_DEPENDENCY",
62
+ "HTTP_425_TOO_EARLY",
63
+ "HTTP_426_UPGRADE_REQUIRED",
64
+ "HTTP_428_PRECONDITION_REQUIRED",
65
+ "HTTP_429_TOO_MANY_REQUESTS",
66
+ "HTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE",
67
+ "HTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS",
68
+ "HTTP_500_INTERNAL_SERVER_ERROR",
69
+ "HTTP_501_NOT_IMPLEMENTED",
70
+ "HTTP_502_BAD_GATEWAY",
71
+ "HTTP_503_SERVICE_UNAVAILABLE",
72
+ "HTTP_504_GATEWAY_TIMEOUT",
73
+ "HTTP_505_HTTP_VERSION_NOT_SUPPORTED",
74
+ "HTTP_506_VARIANT_ALSO_NEGOTIATES",
75
+ "HTTP_507_INSUFFICIENT_STORAGE",
76
+ "HTTP_508_LOOP_DETECTED",
77
+ "HTTP_510_NOT_EXTENDED",
78
+ "HTTP_511_NETWORK_AUTHENTICATION_REQUIRED",
79
+ "WS_1000_NORMAL_CLOSURE",
80
+ "WS_1001_GOING_AWAY",
81
+ "WS_1002_PROTOCOL_ERROR",
82
+ "WS_1003_UNSUPPORTED_DATA",
83
+ "WS_1005_NO_STATUS_RCVD",
84
+ "WS_1006_ABNORMAL_CLOSURE",
85
+ "WS_1007_INVALID_FRAME_PAYLOAD_DATA",
86
+ "WS_1008_POLICY_VIOLATION",
87
+ "WS_1009_MESSAGE_TOO_BIG",
88
+ "WS_1010_MANDATORY_EXT",
89
+ "WS_1011_INTERNAL_ERROR",
90
+ "WS_1012_SERVICE_RESTART",
91
+ "WS_1013_TRY_AGAIN_LATER",
92
+ "WS_1014_BAD_GATEWAY",
93
+ "WS_1015_TLS_HANDSHAKE",
94
+ ]
95
+
96
+ HTTP_100_CONTINUE = 100
97
+ HTTP_101_SWITCHING_PROTOCOLS = 101
98
+ HTTP_102_PROCESSING = 102
99
+ HTTP_103_EARLY_HINTS = 103
100
+ HTTP_200_OK = 200
101
+ HTTP_201_CREATED = 201
102
+ HTTP_202_ACCEPTED = 202
103
+ HTTP_203_NON_AUTHORITATIVE_INFORMATION = 203
104
+ HTTP_204_NO_CONTENT = 204
105
+ HTTP_205_RESET_CONTENT = 205
106
+ HTTP_206_PARTIAL_CONTENT = 206
107
+ HTTP_207_MULTI_STATUS = 207
108
+ HTTP_208_ALREADY_REPORTED = 208
109
+ HTTP_226_IM_USED = 226
110
+ HTTP_300_MULTIPLE_CHOICES = 300
111
+ HTTP_301_MOVED_PERMANENTLY = 301
112
+ HTTP_302_FOUND = 302
113
+ HTTP_303_SEE_OTHER = 303
114
+ HTTP_304_NOT_MODIFIED = 304
115
+ HTTP_305_USE_PROXY = 305
116
+ HTTP_306_RESERVED = 306
117
+ HTTP_307_TEMPORARY_REDIRECT = 307
118
+ HTTP_308_PERMANENT_REDIRECT = 308
119
+ HTTP_400_BAD_REQUEST = 400
120
+ HTTP_401_UNAUTHORIZED = 401
121
+ HTTP_402_PAYMENT_REQUIRED = 402
122
+ HTTP_403_FORBIDDEN = 403
123
+ HTTP_404_NOT_FOUND = 404
124
+ HTTP_405_METHOD_NOT_ALLOWED = 405
125
+ HTTP_406_NOT_ACCEPTABLE = 406
126
+ HTTP_407_PROXY_AUTHENTICATION_REQUIRED = 407
127
+ HTTP_408_REQUEST_TIMEOUT = 408
128
+ HTTP_409_CONFLICT = 409
129
+ HTTP_410_GONE = 410
130
+ HTTP_411_LENGTH_REQUIRED = 411
131
+ HTTP_412_PRECONDITION_FAILED = 412
132
+ HTTP_413_CONTENT_TOO_LARGE = 413
133
+ HTTP_414_URI_TOO_LONG = 414
134
+ HTTP_415_UNSUPPORTED_MEDIA_TYPE = 415
135
+ HTTP_416_RANGE_NOT_SATISFIABLE = 416
136
+ HTTP_417_EXPECTATION_FAILED = 417
137
+ HTTP_418_IM_A_TEAPOT = 418
138
+ HTTP_421_MISDIRECTED_REQUEST = 421
139
+ HTTP_422_UNPROCESSABLE_CONTENT = 422
140
+ HTTP_423_LOCKED = 423
141
+ HTTP_424_FAILED_DEPENDENCY = 424
142
+ HTTP_425_TOO_EARLY = 425
143
+ HTTP_426_UPGRADE_REQUIRED = 426
144
+ HTTP_428_PRECONDITION_REQUIRED = 428
145
+ HTTP_429_TOO_MANY_REQUESTS = 429
146
+ HTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE = 431
147
+ HTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS = 451
148
+ HTTP_500_INTERNAL_SERVER_ERROR = 500
149
+ HTTP_501_NOT_IMPLEMENTED = 501
150
+ HTTP_502_BAD_GATEWAY = 502
151
+ HTTP_503_SERVICE_UNAVAILABLE = 503
152
+ HTTP_504_GATEWAY_TIMEOUT = 504
153
+ HTTP_505_HTTP_VERSION_NOT_SUPPORTED = 505
154
+ HTTP_506_VARIANT_ALSO_NEGOTIATES = 506
155
+ HTTP_507_INSUFFICIENT_STORAGE = 507
156
+ HTTP_508_LOOP_DETECTED = 508
157
+ HTTP_510_NOT_EXTENDED = 510
158
+ HTTP_511_NETWORK_AUTHENTICATION_REQUIRED = 511
159
+
160
+
161
+ """
162
+ WebSocket codes
163
+ https://www.iana.org/assignments/websocket/websocket.xml#close-code-number
164
+ https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent
165
+ """
166
+ WS_1000_NORMAL_CLOSURE = 1000
167
+ WS_1001_GOING_AWAY = 1001
168
+ WS_1002_PROTOCOL_ERROR = 1002
169
+ WS_1003_UNSUPPORTED_DATA = 1003
170
+ WS_1005_NO_STATUS_RCVD = 1005
171
+ WS_1006_ABNORMAL_CLOSURE = 1006
172
+ WS_1007_INVALID_FRAME_PAYLOAD_DATA = 1007
173
+ WS_1008_POLICY_VIOLATION = 1008
174
+ WS_1009_MESSAGE_TOO_BIG = 1009
175
+ WS_1010_MANDATORY_EXT = 1010
176
+ WS_1011_INTERNAL_ERROR = 1011
177
+ WS_1012_SERVICE_RESTART = 1012
178
+ WS_1013_TRY_AGAIN_LATER = 1013
179
+ WS_1014_BAD_GATEWAY = 1014
180
+ WS_1015_TLS_HANDSHAKE = 1015
181
+
182
+ __deprecated__ = {
183
+ "HTTP_413_REQUEST_ENTITY_TOO_LARGE": 413,
184
+ "HTTP_414_REQUEST_URI_TOO_LONG": 414,
185
+ "HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE": 416,
186
+ "HTTP_422_UNPROCESSABLE_ENTITY": 422,
187
+ }
188
+
189
+
190
+ def __getattr__(name: str) -> int:
191
+ deprecation_changes = {
192
+ "HTTP_413_REQUEST_ENTITY_TOO_LARGE": "HTTP_413_CONTENT_TOO_LARGE",
193
+ "HTTP_414_REQUEST_URI_TOO_LONG": "HTTP_414_URI_TOO_LONG",
194
+ "HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE": "HTTP_416_RANGE_NOT_SATISFIABLE",
195
+ "HTTP_422_UNPROCESSABLE_ENTITY": "HTTP_422_UNPROCESSABLE_CONTENT",
196
+ }
197
+
198
+ deprecated = __deprecated__.get(name)
199
+ if deprecated:
200
+ warnings.warn(
201
+ f"'{name}' is deprecated. Use '{deprecation_changes[name]}' instead.",
202
+ category=StarletteDeprecationWarning,
203
+ stacklevel=3,
204
+ )
205
+ return deprecated
206
+
207
+ raise AttributeError(f"module 'kernel.status' has no attribute '{name}'")
208
+
209
+
210
+ def __dir__() -> list[str]:
211
+ return sorted(list(__all__) + list(__deprecated__.keys())) # pragma: no cover