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.
@@ -0,0 +1,126 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from collections.abc import Sequence
5
+
6
+ try:
7
+ from opentelemetry import metrics, propagate, trace
8
+ from opentelemetry.trace import SpanKind, Status, StatusCode
9
+ except ImportError: # pragma: no cover
10
+ raise ImportError("The `opentelemetry-api` package is required to use `OpenTelemetryMiddleware`.") from None
11
+
12
+ from kernel import __version__
13
+ from kernel.datastructures import URL
14
+ from kernel.routing import Mount
15
+ from kernel.types import ASGIApp, Message, Receive, Scope, Send
16
+
17
+
18
+ class OpenTelemetryMiddleware:
19
+ """Create OpenTelemetry server spans for incoming HTTP requests.
20
+
21
+ This middleware is experimental. Its API and emitted telemetry may change in minor
22
+ releases without a deprecation period.
23
+
24
+ Args:
25
+ app: The ASGI application to wrap.
26
+ excluded_urls: Regular expressions matched against the full request URL.
27
+ Pass a comma-separated string or a sequence. By default, exclude no URLs.
28
+ tracer_provider: Optional tracer provider. If omitted, use the global tracer provider.
29
+ meter_provider: Optional meter provider. If omitted, use the global meter provider.
30
+ """
31
+
32
+ def __init__(
33
+ self,
34
+ app: ASGIApp,
35
+ *,
36
+ excluded_urls: str | Sequence[str] = (),
37
+ tracer_provider: trace.TracerProvider | None = None,
38
+ meter_provider: metrics.MeterProvider | None = None,
39
+ ) -> None:
40
+ self.app = app
41
+ self._meter_provider = meter_provider
42
+ if isinstance(excluded_urls, str):
43
+ excluded_urls = [pattern.strip() for pattern in excluded_urls.split(",")] if excluded_urls else ()
44
+ self._excluded_urls = tuple(re.compile(pattern) for pattern in excluded_urls)
45
+ self._tracer_provider = tracer_provider or trace.get_tracer_provider()
46
+
47
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
48
+ if scope["type"] != "http" or scope.get("starlette.opentelemetry"):
49
+ return await self.app(scope, receive, send)
50
+
51
+ scope["starlette.opentelemetry"] = True
52
+ try:
53
+ tracer_provider = self._tracer_provider
54
+ if isinstance(tracer_provider, trace.NoOpTracerProvider):
55
+ return await self.app(scope, receive, send)
56
+
57
+ url = URL(scope=scope)
58
+ if any(pattern.search(str(url)) for pattern in self._excluded_urls):
59
+ return await self.app(scope, receive, send)
60
+
61
+ original_method = scope.get("method", "")
62
+ method = original_method.upper()
63
+
64
+ headers: dict[str, list[str]] = {}
65
+ for name, value in scope.get("headers", []):
66
+ headers.setdefault(name.decode("latin-1").lower(), []).append(value.decode("latin-1"))
67
+
68
+ attributes: dict[str, str | int] = {
69
+ "http.request.method": method,
70
+ "url.path": scope.get("path", ""),
71
+ "url.scheme": scope.get("scheme", "http"),
72
+ }
73
+ if original_method != method:
74
+ attributes["http.request.method_original"] = original_method
75
+ if url.query:
76
+ attributes["url.query"] = url.query
77
+ if url.hostname is not None:
78
+ attributes["server.address"] = url.hostname
79
+ server = scope.get("server")
80
+ server_port = url.port if url.port is not None else server[1] if server is not None else None
81
+ if server_port is not None:
82
+ attributes["server.port"] = server_port
83
+ if scope.get("http_version"):
84
+ attributes["network.protocol.version"] = scope["http_version"]
85
+ if scope.get("client") is not None:
86
+ attributes["client.address"] = scope["client"][0]
87
+ if headers.get("user-agent"):
88
+ attributes["user_agent.original"] = headers["user-agent"][0]
89
+
90
+ with tracer_provider.get_tracer("kernel", __version__).start_as_current_span(
91
+ method,
92
+ context=propagate.extract(headers),
93
+ kind=SpanKind.SERVER,
94
+ attributes=attributes,
95
+ ) as span:
96
+
97
+ async def send_with_telemetry(message: Message) -> None:
98
+ if message["type"] == "http.response.start":
99
+ status_code = message["status"]
100
+ span.set_attribute("http.response.status_code", status_code)
101
+ if status_code >= 500:
102
+ span.set_attribute("error.type", str(status_code))
103
+ span.set_status(Status(StatusCode.ERROR))
104
+ await send(message)
105
+
106
+ try:
107
+ await self.app(scope, receive, send_with_telemetry)
108
+ except Exception as exc:
109
+ span.set_attribute("error.type", type(exc).__qualname__)
110
+ raise
111
+ finally:
112
+ route = scope.get("route")
113
+ if isinstance(route, Mount):
114
+ route_path = scope.get("root_path") or "/"
115
+ else:
116
+ path_format = getattr(route, "path_format", None)
117
+ route_path = (
118
+ scope.get("root_path", "").rstrip("/") + path_format or "/"
119
+ if isinstance(path_format, str)
120
+ else None
121
+ )
122
+ if route_path is not None:
123
+ span.update_name(f"{method} {route_path}")
124
+ span.set_attribute("http.route", route_path)
125
+ finally:
126
+ del scope["starlette.opentelemetry"]
@@ -0,0 +1,139 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import typing
5
+ from base64 import b64decode, b64encode
6
+ from typing import Literal
7
+
8
+ import itsdangerous
9
+ from itsdangerous.exc import BadSignature
10
+
11
+ from kernel.datastructures import MutableHeaders, Secret
12
+ from kernel.requests import HTTPConnection
13
+ from kernel.types import ASGIApp, Message, Receive, Scope, Send
14
+
15
+
16
+ class SessionMiddleware:
17
+ def __init__(
18
+ self,
19
+ app: ASGIApp,
20
+ secret_key: str | Secret,
21
+ session_cookie: str = "session",
22
+ max_age: int | None = 14 * 24 * 60 * 60, # 14 days, in seconds
23
+ path: str = "/",
24
+ same_site: Literal["lax", "strict", "none"] = "lax",
25
+ https_only: bool = False,
26
+ domain: str | None = None,
27
+ partitioned: bool = False,
28
+ ) -> None:
29
+ self.app = app
30
+ self.signer = itsdangerous.TimestampSigner(str(secret_key))
31
+ self.session_cookie = session_cookie
32
+ self.max_age = max_age
33
+ self.path = path
34
+ self.security_flags = "httponly; samesite=" + same_site
35
+ if https_only: # Secure flag can be used with HTTPS only
36
+ self.security_flags += "; secure"
37
+ if domain is not None:
38
+ self.security_flags += f"; domain={domain}"
39
+ if partitioned:
40
+ self.security_flags += "; partitioned"
41
+
42
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
43
+ if scope["type"] not in ("http", "websocket"): # pragma: no cover
44
+ await self.app(scope, receive, send)
45
+ return
46
+
47
+ connection = HTTPConnection(scope)
48
+ initial_session_was_empty = True
49
+
50
+ if self.session_cookie in connection.cookies:
51
+ data = connection.cookies[self.session_cookie].encode("utf-8")
52
+ try:
53
+ data = self.signer.unsign(data, max_age=self.max_age)
54
+ scope["session"] = Session(json.loads(b64decode(data)))
55
+ initial_session_was_empty = False
56
+ except BadSignature:
57
+ scope["session"] = Session()
58
+ else:
59
+ scope["session"] = Session()
60
+
61
+ async def send_wrapper(message: Message) -> None:
62
+ if message["type"] == "http.response.start":
63
+ session: Session = scope["session"]
64
+ message.setdefault("headers", [])
65
+ headers = MutableHeaders(scope=message)
66
+ if session.accessed:
67
+ headers.add_vary_header("Cookie")
68
+ if session.modified and session:
69
+ # We have session data to persist.
70
+ data = b64encode(json.dumps(session).encode("utf-8"))
71
+ data = self.signer.sign(data)
72
+ header_value = "{session_cookie}={data}; path={path}; {max_age}{security_flags}".format(
73
+ session_cookie=self.session_cookie,
74
+ data=data.decode("utf-8"),
75
+ path=self.path,
76
+ max_age=f"Max-Age={self.max_age}; " if self.max_age is not None else "",
77
+ security_flags=self.security_flags,
78
+ )
79
+ headers.append("Set-Cookie", header_value)
80
+ elif session.modified and not initial_session_was_empty:
81
+ # The session has been cleared.
82
+ header_value = "{session_cookie}={data}; path={path}; {expires}{security_flags}".format(
83
+ session_cookie=self.session_cookie,
84
+ data="null",
85
+ path=self.path,
86
+ expires="expires=Thu, 01 Jan 1970 00:00:00 GMT; ",
87
+ security_flags=self.security_flags,
88
+ )
89
+ headers.append("Set-Cookie", header_value)
90
+ await send(message)
91
+
92
+ await self.app(scope, receive, send_wrapper)
93
+
94
+
95
+ class Session(dict[str, typing.Any]):
96
+ accessed: bool = False
97
+ modified: bool = False
98
+
99
+ def mark_accessed(self) -> None:
100
+ self.accessed = True
101
+
102
+ def mark_modified(self) -> None:
103
+ self.accessed = True
104
+ self.modified = True
105
+
106
+ def __setitem__(self, key: str, value: typing.Any) -> None:
107
+ self.mark_modified()
108
+ super().__setitem__(key, value)
109
+
110
+ def __delitem__(self, key: str) -> None:
111
+ self.mark_modified()
112
+ super().__delitem__(key)
113
+
114
+ def clear(self) -> None:
115
+ self.mark_modified()
116
+ super().clear()
117
+
118
+ def pop(self, key: str, *args: typing.Any) -> typing.Any:
119
+ if key in self:
120
+ self.mark_modified()
121
+ return super().pop(key, *args)
122
+
123
+ def popitem(self) -> tuple[str, typing.Any]:
124
+ item = super().popitem()
125
+ self.mark_modified()
126
+ return item
127
+
128
+ def setdefault(self, key: str, default: typing.Any = None) -> typing.Any:
129
+ if key not in self:
130
+ self.mark_modified()
131
+ return super().setdefault(key, default)
132
+
133
+ def update(self, *args: typing.Any, **kwargs: typing.Any) -> None:
134
+ self.mark_modified()
135
+ super().update(*args, **kwargs)
136
+
137
+ def __ior__(self, other: typing.Any, /) -> Session: # type: ignore[override,misc]
138
+ self.mark_modified()
139
+ return super().__ior__(other)
@@ -0,0 +1,66 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Sequence
4
+
5
+ from kernel._utils import parse_host_header
6
+ from kernel.datastructures import URL, Headers
7
+ from kernel.responses import PlainTextResponse, RedirectResponse, Response
8
+ from kernel.types import ASGIApp, Receive, Scope, Send
9
+
10
+ ENFORCE_DOMAIN_WILDCARD = "Domain wildcard patterns must be like '*.example.com'."
11
+
12
+
13
+ class TrustedHostMiddleware:
14
+ def __init__(
15
+ self,
16
+ app: ASGIApp,
17
+ allowed_hosts: Sequence[str] | None = None,
18
+ www_redirect: bool = True,
19
+ ) -> None:
20
+ if allowed_hosts is None:
21
+ allowed_hosts = ["*"]
22
+
23
+ for pattern in allowed_hosts:
24
+ assert "*" not in pattern[1:], ENFORCE_DOMAIN_WILDCARD
25
+ if pattern.startswith("*") and pattern != "*":
26
+ assert pattern.startswith("*."), ENFORCE_DOMAIN_WILDCARD
27
+ self.app = app
28
+ self.allowed_hosts = [pattern.lower() for pattern in allowed_hosts]
29
+ self.allow_any = "*" in allowed_hosts
30
+ self.www_redirect = www_redirect
31
+
32
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
33
+ if self.allow_any or scope["type"] not in (
34
+ "http",
35
+ "websocket",
36
+ ): # pragma: no cover
37
+ await self.app(scope, receive, send)
38
+ return
39
+
40
+ headers = Headers(scope=scope)
41
+ parsed_host = parse_host_header(headers.get("host"))
42
+ if parsed_host is None:
43
+ await PlainTextResponse("Invalid host header", status_code=400)(scope, receive, send)
44
+ return
45
+ host = parsed_host.host.lower()
46
+
47
+ is_valid_host = False
48
+ found_www_redirect = False
49
+ for pattern in self.allowed_hosts:
50
+ if host == pattern or (pattern.startswith("*") and host.endswith(pattern[1:])):
51
+ is_valid_host = True
52
+ break
53
+ elif "www." + host == pattern:
54
+ found_www_redirect = True
55
+
56
+ if is_valid_host:
57
+ await self.app(scope, receive, send)
58
+ else:
59
+ response: Response
60
+ if found_www_redirect and self.www_redirect:
61
+ url = URL(scope=scope)
62
+ redirect_url = url.replace(netloc="www." + url.netloc)
63
+ response = RedirectResponse(url=str(redirect_url))
64
+ else:
65
+ response = PlainTextResponse("Invalid host header", status_code=400)
66
+ await response(scope, receive, send)
@@ -0,0 +1,157 @@
1
+ from __future__ import annotations
2
+
3
+ import io
4
+ import math
5
+ import sys
6
+ import warnings
7
+ from collections.abc import Callable, MutableMapping
8
+ from typing import Any
9
+
10
+ import anyio.from_thread
11
+ import anyio.to_thread
12
+ from anyio.abc import ObjectReceiveStream, ObjectSendStream
13
+
14
+ from kernel._utils import create_collapsing_task_group
15
+ from kernel.exceptions import StarletteDeprecationWarning
16
+ from kernel.types import Receive, Scope, Send
17
+
18
+ warnings.warn(
19
+ "kernel.middleware.wsgi is deprecated and will be removed in a future release. "
20
+ "Please refer to https://github.com/abersheeran/a2wsgi as a replacement.",
21
+ StarletteDeprecationWarning,
22
+ stacklevel=2,
23
+ )
24
+
25
+
26
+ def build_environ(scope: Scope, body: bytes) -> dict[str, Any]:
27
+ """
28
+ Builds a scope and request body into a WSGI environ object.
29
+ """
30
+
31
+ script_name = scope.get("root_path", "").encode("utf8").decode("latin1")
32
+ path_info = scope["path"].encode("utf8").decode("latin1")
33
+ if path_info == script_name or path_info.startswith(script_name.rstrip("/") + "/"):
34
+ path_info = path_info[len(script_name) :]
35
+
36
+ environ = {
37
+ "REQUEST_METHOD": scope["method"],
38
+ "SCRIPT_NAME": script_name,
39
+ "PATH_INFO": path_info,
40
+ "QUERY_STRING": scope["query_string"].decode("ascii"),
41
+ "SERVER_PROTOCOL": f"HTTP/{scope['http_version']}",
42
+ "wsgi.version": (1, 0),
43
+ "wsgi.url_scheme": scope.get("scheme", "http"),
44
+ "wsgi.input": io.BytesIO(body),
45
+ "wsgi.errors": sys.stdout,
46
+ "wsgi.multithread": True,
47
+ "wsgi.multiprocess": True,
48
+ "wsgi.run_once": False,
49
+ }
50
+
51
+ # Get server name and port - required in WSGI, not in ASGI
52
+ server = scope.get("server") or ("localhost", 80)
53
+ environ["SERVER_NAME"] = server[0]
54
+ environ["SERVER_PORT"] = server[1]
55
+
56
+ # Get client IP address
57
+ if scope.get("client"):
58
+ environ["REMOTE_ADDR"] = scope["client"][0]
59
+
60
+ # Go through headers and make them into environ entries
61
+ for name, value in scope.get("headers", []):
62
+ name = name.decode("latin1")
63
+ if name == "content-length":
64
+ corrected_name = "CONTENT_LENGTH"
65
+ elif name == "content-type":
66
+ corrected_name = "CONTENT_TYPE"
67
+ else:
68
+ corrected_name = f"HTTP_{name}".upper().replace("-", "_")
69
+ # HTTPbis say only ASCII chars are allowed in headers, but we latin1 just in
70
+ # case
71
+ value = value.decode("latin1")
72
+ if corrected_name in environ:
73
+ value = environ[corrected_name] + "," + value
74
+ environ[corrected_name] = value
75
+ return environ
76
+
77
+
78
+ class WSGIMiddleware:
79
+ def __init__(self, app: Callable[..., Any]) -> None:
80
+ self.app = app
81
+
82
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
83
+ assert scope["type"] == "http"
84
+ responder = WSGIResponder(self.app, scope)
85
+ await responder(receive, send)
86
+
87
+
88
+ class WSGIResponder:
89
+ stream_send: ObjectSendStream[MutableMapping[str, Any]]
90
+ stream_receive: ObjectReceiveStream[MutableMapping[str, Any]]
91
+
92
+ def __init__(self, app: Callable[..., Any], scope: Scope) -> None:
93
+ self.app = app
94
+ self.scope = scope
95
+ self.status = None
96
+ self.response_headers = None
97
+ self.stream_send, self.stream_receive = anyio.create_memory_object_stream(math.inf)
98
+ self.response_started = False
99
+ self.exc_info: Any = None
100
+
101
+ async def __call__(self, receive: Receive, send: Send) -> None:
102
+ body = b""
103
+ more_body = True
104
+ while more_body:
105
+ message = await receive()
106
+ body += message.get("body", b"")
107
+ more_body = message.get("more_body", False)
108
+ environ = build_environ(self.scope, body)
109
+
110
+ async with create_collapsing_task_group() as task_group:
111
+ task_group.start_soon(self.sender, send)
112
+ async with self.stream_send:
113
+ await anyio.to_thread.run_sync(self.wsgi, environ, self.start_response)
114
+ if self.exc_info is not None:
115
+ raise self.exc_info[0].with_traceback(self.exc_info[1], self.exc_info[2])
116
+
117
+ async def sender(self, send: Send) -> None:
118
+ async with self.stream_receive:
119
+ async for message in self.stream_receive:
120
+ await send(message)
121
+
122
+ def start_response(
123
+ self,
124
+ status: str,
125
+ response_headers: list[tuple[str, str]],
126
+ exc_info: Any = None,
127
+ ) -> None:
128
+ self.exc_info = exc_info
129
+ if not self.response_started: # pragma: no branch
130
+ self.response_started = True
131
+ status_code_string, _ = status.split(" ", 1)
132
+ status_code = int(status_code_string)
133
+ headers = [
134
+ (name.strip().encode("ascii").lower(), value.strip().encode("ascii"))
135
+ for name, value in response_headers
136
+ ]
137
+ anyio.from_thread.run(
138
+ self.stream_send.send,
139
+ {
140
+ "type": "http.response.start",
141
+ "status": status_code,
142
+ "headers": headers,
143
+ },
144
+ )
145
+
146
+ def wsgi(
147
+ self,
148
+ environ: dict[str, Any],
149
+ start_response: Callable[..., Any],
150
+ ) -> None:
151
+ for chunk in self.app(environ, start_response):
152
+ anyio.from_thread.run(
153
+ self.stream_send.send,
154
+ {"type": "http.response.body", "body": chunk, "more_body": True},
155
+ )
156
+
157
+ anyio.from_thread.run(self.stream_send.send, {"type": "http.response.body", "body": b""})
kernel/py.typed ADDED
File without changes