# SPDX-FileCopyrightText: 2026 aas-client3.2-python AUTHORS
#
# SPDX-License-Identifier: MIT
"""
Implement the operations of the AASX File Server API.
The module also implements the AASX Async File Server API, and its Status and
Result APIs.
Every public function implements exactly one operation of the specification. The
private functions ``_build_*`` and ``_parse_*`` build the request and parse
the response of the operation. They do no I/O, and constitute a semi-public
interface for the testing client, which is released in lockstep with this client.
"""
from typing import ContextManager, Final, IO, List, Optional, Sequence, Tuple, Union
import aas_core3_2.jsonization as aas_jsonization
import aas_core3_2.types as aas_types
from aas_client3_2 import _files
from aas_client3_2 import _invocation
from aas_client3_2 import _json
from aas_client3_2 import _query
from aas_client3_2 import errors
from aas_client3_2 import http
#: Content type of an AASX package, as the OpenAPI gives it for the uploads and
#: the downloads of the packages
CONTENT_TYPE: Final[str] = "application/asset-administration-shell-package"
def _package_path(package_id: str) -> str:
"""Build the path of the package with the given ID."""
return "/packages/" + http.encode_base64url(package_id)
def _aas_ids_fields(aas_ids: Optional[Sequence[str]]) -> List[Tuple[str, str]]:
"""Give the parts of the multipart body with the identifiers of the shells."""
return [("aasIds", aas_id) for aas_id in aas_ids] if aas_ids is not None else []
def _build_upload(
method: str,
url: str,
content: Union[bytes, IO[bytes]],
aas_ids: Optional[Sequence[str]],
file_name: Optional[str],
) -> http.Request:
"""Build the request which uploads a package, streamed in a multipart body."""
return _files.build_upload_request(
method, url, content, file_name, CONTENT_TYPE, _aas_ids_fields(aas_ids)
)
def _build_get_all_aasx_package_ids(
base_url: str,
*,
aas_id: Optional[str] = None,
limit: Optional[int] = None,
cursor: Optional[str] = None,
) -> http.Request:
"""Build the request of ``GetAllAASXPackageIds``."""
query: _query.Query = []
if aas_id is not None:
query.append(("aasId", http.encode_base64url(aas_id)))
query.extend(_query.page(limit, cursor))
return _json.build_request("GET", http.build_url(base_url, "/packages", query))
def _parse_get_all_aasx_package_ids(
response: http.Response,
) -> aas_types.GetPackageDescriptionsResult:
"""Parse the response of ``GetAllAASXPackageIds``."""
errors.raise_for_unexpected_status(response, {200})
return _json.parse(
response, aas_jsonization.get_package_descriptions_result_from_jsonable
)
[docs]
def get_all_aasx_package_ids(
server: http.Server,
*,
aas_id: Optional[str] = None,
limit: Optional[int] = None,
cursor: Optional[str] = None,
) -> aas_types.GetPackageDescriptionsResult:
"""
List a page of the descriptions of the AASX packages on the server.
A description gives the ID of a package, and the identifiers of the shells it
contains.
:param server: where to send the request
:param aas_id: if set, only the packages which contain this shell
:param limit: maximum number of the descriptions in the page
:param cursor: where to continue the listing from
:returns: a page of the descriptions of the packages
:implements GetAllAASXPackageIds: ``GET /packages``
"""
request = _build_get_all_aasx_package_ids(
server.base_url, aas_id=aas_id, limit=limit, cursor=cursor
)
response = http.send(server.transport, request)
return _parse_get_all_aasx_package_ids(response)
def _build_post_aasx_package(
base_url: str,
file: Union[bytes, IO[bytes]],
*,
aas_ids: Optional[Sequence[str]] = None,
file_name: Optional[str] = None,
) -> http.Request:
"""Build the request of ``PostAASXPackage``."""
return _build_upload(
"POST", http.build_url(base_url, "/packages"), file, aas_ids, file_name
)
def _parse_post_aasx_package(response: http.Response) -> aas_types.PackageDescription:
"""Parse the response of ``PostAASXPackage``."""
errors.raise_for_unexpected_status(response, {201})
return _json.parse(response, aas_jsonization.package_description_from_jsonable)
[docs]
def post_aasx_package(
server: http.Server,
file: Union[bytes, IO[bytes]],
*,
aas_ids: Optional[Sequence[str]] = None,
file_name: Optional[str] = None,
) -> aas_types.PackageDescription:
"""
Upload a new AASX package.
The content is either ``bytes``, or a binary file object which is readable and
seekable; it is read from its current position to its end, in chunks, so that
a large package is never held in memory. The file object must not be modified
during the upload.
The package is sent with the content type :py:data:`CONTENT_TYPE`.
:param server: where to send the request
:param file: the content of the package
:param aas_ids: if set, the identifiers of the shells which the package contains
:param file_name: if set, the name of the file of the package
:returns: the description of the package, with the ID which the server assigned
:raises: :py:class:`TypeError` or :py:class:`ValueError` before sending anything
if :paramref:`file` can not be read again, or if :paramref:`file_name`
contains characters which would break the multipart envelope
:implements PostAASXPackage: ``POST /packages``
"""
request = _build_post_aasx_package(
server.base_url, file, aas_ids=aas_ids, file_name=file_name
)
response = http.send(server.transport, request)
return _parse_post_aasx_package(response)
def _build_get_aasx_by_package_id(base_url: str, package_id: str) -> http.Request:
"""Build the request of ``GetAASXByPackageId``."""
return _files.build_download_request(
http.build_url(base_url, _package_path(package_id))
)
[docs]
def get_aasx_by_package_id(
server: http.Server, package_id: str
) -> ContextManager[http.Download]:
"""
Download the AASX package with the given ID.
The content is streamed, so use the result as a context manager:
.. code-block:: python
with aasx_file_server.get_aasx_by_package_id(server, package_id) as download:
with open("package.aasx", "wb") as fid:
download.write_to(fid)
The connection is released when the context is exited.
:param server: where to send the request
:param package_id: ID of the package
:returns: a context manager which gives the download
:raises: :py:class:`~aas_client3_2.errors.NotFound` if there is no such package
:implements GetAASXByPackageId: ``GET /packages/{packageId}``
"""
request = _build_get_aasx_by_package_id(server.base_url, package_id)
return _files.download(server, request, {200})
def _build_put_aasx_by_package_id(
base_url: str,
package_id: str,
file: Union[bytes, IO[bytes]],
*,
aas_ids: Optional[Sequence[str]] = None,
file_name: Optional[str] = None,
) -> http.Request:
"""Build the request of ``PutAASXByPackageId``."""
return _build_upload(
"PUT",
http.build_url(base_url, _package_path(package_id)),
file,
aas_ids,
file_name,
)
def _parse_put_aasx_by_package_id(response: http.Response) -> None:
"""
Parse the response of ``PutAASXByPackageId``.
The server responds with 201 and the description if it created the package,
or with 204 if it replaced an existing one. We do not parse the description,
since the users gave both the ID and the shells.
"""
errors.raise_for_unexpected_status(response, {201, 204})
[docs]
def put_aasx_by_package_id(
server: http.Server,
package_id: str,
file: Union[bytes, IO[bytes]],
*,
aas_ids: Optional[Sequence[str]] = None,
file_name: Optional[str] = None,
) -> None:
"""
Create or replace the AASX package with the given ID.
See :py:func:`post_aasx_package` for the content.
:param server: where to send the request
:param package_id: ID of the package
:param file: the content of the package
:param aas_ids: if set, the identifiers of the shells which the package contains
:param file_name: if set, the name of the file of the package
:raises: :py:class:`TypeError` or :py:class:`ValueError` before sending anything
if :paramref:`file` can not be read again, or if :paramref:`file_name`
contains characters which would break the multipart envelope
:implements PutAASXByPackageId: ``PUT /packages/{packageId}``
"""
request = _build_put_aasx_by_package_id(
server.base_url, package_id, file, aas_ids=aas_ids, file_name=file_name
)
response = http.send(server.transport, request)
_parse_put_aasx_by_package_id(response)
def _build_delete_aasx_by_package_id(base_url: str, package_id: str) -> http.Request:
"""Build the request of ``DeleteAASXByPackageId``."""
return _json.build_request(
"DELETE", http.build_url(base_url, _package_path(package_id))
)
def _parse_delete_aasx_by_package_id(response: http.Response) -> None:
"""Parse the response of ``DeleteAASXByPackageId``."""
errors.raise_for_unexpected_status(response, {204})
[docs]
def delete_aasx_by_package_id(server: http.Server, package_id: str) -> None:
"""
Delete the AASX package with the given ID.
:param server: where to send the request
:param package_id: ID of the package
:implements DeleteAASXByPackageId: ``DELETE /packages/{packageId}``
"""
request = _build_delete_aasx_by_package_id(server.base_url, package_id)
response = http.send(server.transport, request)
_parse_delete_aasx_by_package_id(response)
def _build_post_async_aasx_package(
base_url: str,
file: Union[bytes, IO[bytes]],
*,
aas_ids: Optional[Sequence[str]] = None,
file_name: Optional[str] = None,
) -> http.Request:
"""Build the request of ``PostAsyncAASXPackage``."""
return _build_upload(
"POST", http.build_url(base_url, "/packages-async"), file, aas_ids, file_name
)
def _parse_post_async_aasx_package(
response: http.Response,
) -> aas_types.OperationHandle:
"""
Parse the response of ``PostAsyncAASXPackage``.
Unlike the asynchronous invocations and the bulk operations, the OpenAPI gives
the handle in the body, so we take it from there.
"""
errors.raise_for_unexpected_status(response, {202})
return _json.parse(response, aas_jsonization.operation_handle_from_jsonable)
[docs]
def post_async_aasx_package(
server: http.Server,
file: Union[bytes, IO[bytes]],
*,
aas_ids: Optional[Sequence[str]] = None,
file_name: Optional[str] = None,
) -> aas_types.OperationHandle:
"""
Start uploading a new AASX package, and return at once.
The server processes the package asynchronously. Follow its progress with
:py:func:`get_aasx_async_status`, and fetch the result with
:py:func:`get_aasx_async_result`. See :py:func:`post_aasx_package` for
the content.
:param server: where to send the request
:param file: the content of the package
:param aas_ids: if set, the identifiers of the shells which the package contains
:param file_name: if set, the name of the file of the package
:returns: the handle of the upload
:raises: :py:class:`TypeError` or :py:class:`ValueError` before sending anything
if :paramref:`file` can not be read again, or if :paramref:`file_name`
contains characters which would break the multipart envelope
:implements PostAsyncAASXPackage: ``POST /packages-async``
"""
request = _build_post_async_aasx_package(
server.base_url, file, aas_ids=aas_ids, file_name=file_name
)
response = http.send(server.transport, request)
return _parse_post_async_aasx_package(response)
def _handle_segment(handle_id: str) -> str:
"""
Encode :paramref:`handle_id` as the path segment of the status and the result.
The OpenAPI gives the handle in the path "UTF8-BASE64-URL-encoded". Unlike
the handles of the invocations, which the client takes from the location
the server gives, this handle comes from the body as it is, so we encode it.
"""
return http.encode_base64url(handle_id)
def _build_get_aasx_async_status(base_url: str, handle_id: str) -> http.Request:
"""Build the request of ``GetAasxAsyncStatus``."""
return _json.build_request(
"GET",
http.build_url(
base_url, "/packages-async/status/" + _handle_segment(handle_id)
),
)
def _parse_get_aasx_async_status(
response: http.Response,
) -> Union[aas_types.BaseOperationResult, str]:
"""
Parse the response of ``GetAasxAsyncStatus``.
:returns: the status, or the location of the result if the transport did not
follow the redirect to it
"""
return _invocation.parse_status(response)
[docs]
def get_aasx_async_status(
server: http.Server, handle_id: str
) -> aas_types.BaseOperationResult:
"""
Get the status of the asynchronous upload with the given handle.
As for the asynchronous invocations of operations, the server redirects to
the result once the upload is finished. The transport usually follows
the redirect (the one based on `requests` does); if not, the client follows it,
but only to the origin of the server. Either way, the status is taken from
the result, so its ``execution_state`` tells whether the upload completed or
failed.
:param server: where to send the request
:param handle_id: handle as given by :py:func:`post_async_aasx_package`
:returns: the status of the upload
:raises: :py:class:`~aas_client3_2.errors.NotFound` if there is no such
upload; :py:class:`~aas_client3_2.errors.UnexpectedResponse` if
the server redirects to another origin
:implements GetAasxAsyncStatus: ``GET /packages-async/status/{handleId}``
"""
request = _build_get_aasx_async_status(server.base_url, handle_id)
response = http.send(server.transport, request)
status = _parse_get_aasx_async_status(response)
if not isinstance(status, str):
return status
try:
url = _invocation.resolve_result_url(server.base_url, request.url, status)
except ValueError as exception:
raise errors.UnexpectedResponse(response, exception) from exception
followed = http.send(server.transport, _invocation.build_follow_request(url))
return _invocation.parse_followed(followed)
def _build_get_aasx_async_result(base_url: str, handle_id: str) -> http.Request:
"""Build the request of ``GetAasxAsyncResult``."""
return _json.build_request(
"GET",
http.build_url(
base_url, "/packages-async/result/" + _handle_segment(handle_id)
),
)
def _parse_get_aasx_async_result(
response: http.Response,
) -> aas_types.BaseOperationResult:
"""Parse the response of ``GetAasxAsyncResult``."""
errors.raise_for_unexpected_status(response, {200})
return _json.parse(response, aas_jsonization.base_operation_result_from_jsonable)
[docs]
def get_aasx_async_result(
server: http.Server, handle_id: str
) -> aas_types.BaseOperationResult:
"""
Get the result of the finished asynchronous upload with the given handle.
A failed upload is a result with the ``execution_state`` ``Failed``, not
an error.
:param server: where to send the request
:param handle_id: handle as given by :py:func:`post_async_aasx_package`
:returns: the result of the upload
:raises: :py:class:`~aas_client3_2.errors.NotFound` if there is no such upload
:implements GetAasxAsyncResult: ``GET /packages-async/result/{handleId}``
"""
request = _build_get_aasx_async_result(server.base_url, handle_id)
response = http.send(server.transport, request)
return _parse_get_aasx_async_result(response)