# SPDX-FileCopyrightText: 2026 aas-client3.2-python AUTHORS
#
# SPDX-License-Identifier: MIT
"""
Define the protocol between the client and the HTTP implementation.
The client builds the complete :py:class:`Request` itself, including the URL with
the encoded identifiers and query, the headers and the body. A :py:class:`Transport`
only moves the bytes over the wire, so that the client does not depend on any HTTP
library.
"""
import base64
import dataclasses
import datetime
import urllib.parse
from typing import (
IO,
Callable,
ContextManager,
Iterator,
Mapping,
Optional,
Protocol,
Sequence,
Tuple,
Union,
)
[docs]
@dataclasses.dataclass(frozen=True)
class StreamedBody:
"""
Represent a request body which is sent in chunks.
The body is iterable and reports its length through ``__len__``, so that the HTTP
libraries can send it as it is, with ``Content-Length`` and without chunked
transfer encoding. Each iteration starts from the beginning of the body.
"""
#: Start a new iteration over the chunks of the body from its beginning.
#: Every call must yield the same bytes, so that the request can be replayed.
#: This is a contract which the types can not enforce; whoever constructs
#: the body is responsible for it.
chunks: Callable[[], Iterator[bytes]]
#: Length of the body in bytes, sent as ``Content-Length``
length: int
[docs]
def __post_init__(self) -> None:
"""Check that the length is positive."""
# NOTE (mristin):
# Some HTTP libraries, such as requests, treat a body of length zero as
# a body of unknown length, and send it with chunked transfer encoding.
# Hence, an empty body is always given as ``b""``.
if self.length <= 0:
raise ValueError(
f"Expected a positive length of a streamed body, "
f"but got: {self.length}; give an empty body as b''"
)
[docs]
def __iter__(self) -> Iterator[bytes]:
"""Start a new iteration over the chunks from the beginning of the body."""
return self.chunks()
[docs]
def __len__(self) -> int:
"""Give the length of the body in bytes."""
return self.length
[docs]
@dataclasses.dataclass(frozen=True)
class Request:
"""Represent a complete HTTP request as built by the client."""
#: HTTP method in upper case, such as ``GET``
method: str
#: Complete URL including the encoded query
url: str
#: Headers of the request
headers: Mapping[str, str]
#: Body of the request, if any
body: Union[bytes, StreamedBody, None]
#: Whether the transport follows the redirects, if it can follow them at all.
#:
#: The client turns this off only for the requests where it has to see
#: the redirect itself, such as the status of a bulk operation, whose result
#: the server may delete once it has been fetched.
follow_redirects: bool = True
[docs]
@dataclasses.dataclass(frozen=True)
class Response:
"""Represent an HTTP response whose body has been read completely."""
#: HTTP status code
status_code: int
#: Headers of the response; look them up with :py:func:`find_header`
headers: Mapping[str, str]
#: Complete body of the response
body: bytes
[docs]
@dataclasses.dataclass(frozen=True)
class StreamedResponse:
"""Represent an HTTP response whose body is read in chunks."""
#: HTTP status code
status_code: int
#: Headers of the response; look them up with :py:func:`find_header`
headers: Mapping[str, str]
#: Chunks of the body, which can be iterated only once
chunks: Iterator[bytes]
[docs]
class Download:
"""
Represent the binary content of a file which the server is sending.
A download is valid only within the context in which the client gave it, since
the connection is released when the context is exited. The content can be read
only once, either with :py:meth:`iter_chunks` or with :py:meth:`write_to`.
"""
#: Content type of the file as given by the server, if any
content_type: Optional[str]
#: Size of the content in bytes as announced by the server, if any
content_length: Optional[int]
#: Name of the file from the header ``Content-Disposition``, if any
file_name: Optional[str]
[docs]
def __init__(
self,
content_type: Optional[str],
content_length: Optional[int],
file_name: Optional[str],
chunks: Iterator[bytes],
) -> None:
"""Initialize with the given values."""
self.content_type = content_type
self.content_length = content_length
self.file_name = file_name
self._chunks = chunks
self._consumed = False
[docs]
def iter_chunks(self) -> Iterator[bytes]:
"""
Iterate over the chunks of the content.
:raises: :py:class:`RuntimeError` if the content has already been read
"""
if self._consumed:
raise RuntimeError("The content of the download has already been read")
self._consumed = True
return (chunk for chunk in self._chunks if len(chunk) > 0)
[docs]
def write_to(self, destination: IO[bytes]) -> int:
"""
Copy the content to :paramref:`destination`.
:param destination: binary file object to write to
:returns: number of the written bytes
:raises: :py:class:`RuntimeError` if the content has already been read
"""
written = 0
for chunk in self.iter_chunks():
destination.write(chunk)
written += len(chunk)
return written
[docs]
class Transport(Protocol):
"""
Send the requests over the wire.
Network errors (timeouts, refused connections, TLS errors, ...) are raised by
the transport and propagate unchanged through the client.
"""
[docs]
def send(self, request: Request) -> ContextManager[StreamedResponse]:
"""
Send the request, and give the response with the body in chunks.
The connection is released when the context is exited, also when the body
has not been read to the end.
The transport must not follow the redirects if
:py:attr:`Request.follow_redirects` is off, but give the redirect itself.
"""
...
[docs]
def send(transport: Transport, request: Request) -> Response:
"""
Send :paramref:`request` through :paramref:`transport`, and read the whole body.
:param transport: transport to send the request through
:param request: request to be sent
:returns: the response with the complete body
"""
with transport.send(request) as streamed:
return Response(
status_code=streamed.status_code,
headers=streamed.headers,
body=b"".join(streamed.chunks),
)
[docs]
@dataclasses.dataclass(frozen=True)
class Server:
"""Bundle a transport with the base URL of a server."""
#: Transport to send the requests through
transport: Transport
#: Base URL of the server, such as ``https://example.com/api/v3.2``
base_url: str
[docs]
def encode_base64url(text: str) -> str:
"""
Encode :paramref:`text` as UTF-8 in base64url without padding.
The specification requires this encoding for the identifiers in the paths,
and for the JSON-serialized references and key-value pairs in the query.
:param text: text to be encoded
:returns: encoded text
>>> encode_base64url("urn:example:submodel:1")
'dXJuOmV4YW1wbGU6c3VibW9kZWw6MQ'
"""
return base64.urlsafe_b64encode(text.encode("utf-8")).decode("ascii").rstrip("=")
[docs]
def decode_base64url(text: str) -> str:
"""
Decode the UTF-8 text from :paramref:`text` in base64url, with or without padding.
:param text: encoded text
:returns: decoded text
:raises: :py:class:`ValueError` if :paramref:`text` is not valid base64url,
or if the decoded bytes are not valid UTF-8
>>> decode_base64url("dXJuOmV4YW1wbGU6c3VibW9kZWw6MQ")
'urn:example:submodel:1'
"""
padded = text + "=" * (-len(text) % 4)
try:
decoded = base64.b64decode(padded, altchars=b"-_", validate=True)
except ValueError as exception:
raise ValueError(f"Invalid base64url: {text!r}") from exception
return decoded.decode("utf-8")
[docs]
def encode_id_short_path(id_short_path: str) -> str:
"""
Percent-encode :paramref:`id_short_path` as a single segment of a path.
The specification requires the ID-short paths to be URL-encoded, since they
can contain square brackets.
:param id_short_path: ID-short path such as ``sme1.sme2[0].p1``
:returns: encoded path segment
>>> encode_id_short_path("sme1.sme2[0].p1")
'sme1.sme2%5B0%5D.p1'
"""
return urllib.parse.quote(id_short_path, safe="")
[docs]
def encode_date_time(value: datetime.datetime) -> str:
"""
Encode :paramref:`value` in ISO 8601 for a query parameter.
:param value: date and time with a time zone
:returns: encoded date and time, not yet URL-encoded
:raises: :py:class:`ValueError` if :paramref:`value` has no time zone, since
the server would interpret it in a time zone of its own
>>> encode_date_time(
... datetime.datetime(2026, 10, 29, 12, 30, tzinfo=datetime.timezone.utc)
... )
'2026-10-29T12:30:00+00:00'
"""
if value.tzinfo is None or value.utcoffset() is None:
raise ValueError(f"Expected a date and time with a time zone, but got: {value}")
return value.isoformat()
[docs]
def build_url(
base_url: str,
path: str,
query: Optional[Sequence[Tuple[str, str]]] = None,
) -> str:
"""
Join :paramref:`base_url` and :paramref:`path`, and append the :paramref:`query`.
:param base_url: base URL of the server, with or without the trailing slash
:param path:
path starting with a slash, with the segments already encoded, or empty
for the base URL itself, such as the endpoint of a submodel
:param query: pairs of names and values of the query parameters, not yet encoded
:returns: complete URL
>>> build_url("https://example.com/api/", "/submodels", [("limit", "10")])
'https://example.com/api/submodels?limit=10'
>>> build_url("https://example.com", "/description")
'https://example.com/description'
>>> build_url("https://example.com/submodels/dXJuOnNtOjE/", "", [("level", "core")])
'https://example.com/submodels/dXJuOnNtOjE?level=core'
"""
if path != "" and not path.startswith("/"):
raise ValueError(
f"Expected the path to be empty or start with a slash, but got: {path!r}"
)
url = base_url.rstrip("/") + path
if query:
url += "?" + urllib.parse.urlencode(query, quote_via=urllib.parse.quote)
return url