****** Design ****** This document describes the architecture of aas-client3.2: how the client maps the HTTP/REST API of `the Specification of the Asset Administration Shell, Part 2: API (IDTA-01002) version 3.2`_ to Python, how it stays independent of any particular HTTP library, how authentication fits in, and how we test it. .. _the Specification of the Asset Administration Shell, Part 2\: API (IDTA-01002) version 3.2: https://industrialdigitaltwin.io/aas-specifications/IDTA-01002/v3.2/index.html Goals and Non-goals =================== Goals: * One Python function per API operation of Part 2, v3.2, named after the operation ID of the specification, written in Python's snake case. The users who know the specification, the OpenAPI or Swagger UI of their server find the functions under the names they already know. * The functions accept and return only native data: instances of :py:mod:`aas_core3_2.types`, identifiers as :py:class:`str`, and enumerations such as ``Level`` and ``Extent``. The users never see JSON, base64url-encoded identifiers or HTTP status codes in the happy path. * No dependency of the client on any HTTP library. The users bring the HTTP implementation of their choice through a small protocol that we define ourselves. We ship a ready-made implementation based on `requests`_ as an optional extra. * Authentication (OIDC, basic auth, API keys, mutual TLS, ...) is entirely the business of the HTTP implementation and stays out of this library. * A separate *testing client* with contracts (pre- and postconditions) that server developers can use to check their servers against the specification. Non-goals: * No code generation, neither from OpenAPI nor from anything else. The OpenAPI specification was meant as an overview, not for generating code. We map every operation by hand, and check the mapping mechanically against the OpenAPI (see `Cross-checking against the OpenAPI`_). * No implementation of OIDC or any other login mechanism. * No ``asyncio`` interface for now. It will come later (see `Synchronous First, asyncio Later`_). .. _requests: https://pypi.org/project/requests/ Source of Truth =============== We map the operations from the OpenAPI files of the specification, pinned to the release tag ``v3.2.0`` of `admin-shell-io/aas-specs-api`_: * `Entire-API-Collection/V3.2.yaml`_ lists all the operations, and * `Part2-API-Schemas/openapi.yaml`_ defines the payload schemas. .. _admin-shell-io/aas-specs-api: https://github.com/admin-shell-io/aas-specs-api/tree/v3.2.0 .. _Entire-API-Collection/V3.2.yaml: https://github.com/admin-shell-io/aas-specs-api/blob/v3.2.0/Entire-API-Collection/V3.2.yaml .. _Part2-API-Schemas/openapi.yaml: https://github.com/admin-shell-io/aas-specs-api/blob/v3.2.0/Part2-API-Schemas/openapi.yaml The entire collection contains 235 operations, grouped into the following APIs: * Asset Administration Shell API, * Submodel API, * Asset Administration Shell Repository API, * Submodel Repository API, * Concept Description Repository API, * Asset Administration Shell Registry API (including the Async Bulk API), * Submodel Registry API (including the Async Bulk API), * Asset Administration Shell Basic Discovery API, * AASX File Server API (including the AASX Async File Server API), * Serialization API, and * Description API. A vendored copy of the pinned OpenAPI files lives in ``dev/test_data/openapi/`` so that the conformance checks run offline. Dependencies ============ The only runtime dependency is `aas-core3.2`_. All the payload types come from :py:mod:`aas_core3_2.types`, including the types of Part 2 such as ``AssetAdministrationShellDescriptor``, ``SubmodelDescriptor``, ``ServiceDescription``, ``Result``, ``Level``, ``Extent``, ``OperationHandle``, ``Query`` and the paged results such as ``GetSubmodelsResult``. We de/serialize them with :py:mod:`aas_core3_2.jsonization`. .. _aas-core3.2: https://pypi.org/project/aas-core3.2/ This means that the users can pass the very same :py:class:`aas_core3_2.types.Submodel` they loaded from a file to the client, and get back instances they can directly verify with :py:mod:`aas_core3_2.verification`. The optional extra ``aas-client3.2[requests]`` additionally installs `requests`_ for the ready-made transport (see `Transport Protocol`_). Layers ====== .. code-block:: text aas_client3_2/ http.py # Request, Response, Transport, Server, URL encoding errors.py # HTTP status code → exception hierarchy pagination.py # Iterate over paged results _json.py # JSON bodies of the requests and the responses (internal) _query.py # Query parameters shared among the operations (internal) _submodel_operations.py # Operations on a submodel, shared by the APIs (internal) _bulk.py # Bodies and acceptance of the bulk operations (internal) requests_transport.py # Transport based on requests (optional extra) aas.py # Asset Administration Shell API submodel.py # Submodel API aas_repository.py # Asset Administration Shell Repository API submodel_repository.py # Submodel Repository API concept_description_repository.py # Concept Description Repository API aas_registry.py # Asset Administration Shell Registry API submodel_registry.py # Submodel Registry API async_bulk.py # Async Bulk Status and Result APIs discovery.py # Basic Discovery API aasx_file_server.py # AASX File Server API serialization.py # Serialization API description.py # Description API profiles.py # Service specification profiles as constants The modules ``http``, ``errors`` and ``pagination`` constitute the core. None of the modules except ``requests_transport`` imports `requests`_. The API modules follow the API groups (the tags) of the OpenAPI, which are also the groups that Swagger UI shows. A couple of small groups which belong together are merged into a single module: .. list-table:: :header-rows: 1 * - API groups in the OpenAPI - Module - Operations * - Asset Administration Shell API - ``aas`` - 48 * - Submodel API - ``submodel`` - 36 * - Asset Administration Shell Repository API - ``aas_repository`` - 56 * - Submodel Repository API - ``submodel_repository`` - 47 * - Concept Description Repository API - ``concept_description_repository`` - 8 * - Asset Administration Shell Registry API, Async Bulk Asset Administration Shell Registry API - ``aas_registry`` - 14 * - Submodel Registry API, Async Bulk Submodel Registry API - ``submodel_registry`` - 9 * - Async Bulk Status API, Async Bulk Result API (shared by both registries) - ``async_bulk`` - 2 * - Asset Administration Shell Basic Discovery API - ``discovery`` - 5 * - AASX File Server API, AASX Async File Server API, AASX Async File Server Status API, AASX Async File Server Result API - ``aasx_file_server`` - 8 * - Serialization API - ``serialization`` - 1 * - Description API - ``description`` - 1 Transport Protocol ================== We define our own minimal protocol for sending HTTP requests instead of depending on `requests`_ or any other HTTP library. The library builds the complete request itself (URL including the encoded query, headers and the body), and the transport only moves bytes over the wire. File attachments, thumbnails, AASX packages and serializations can be large, so the protocol supports streaming of both the request and the response bodies from the start: .. code-block:: python @dataclasses.dataclass(frozen=True) class StreamedBody: #: 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``; always positive length: int def __iter__(self) -> Iterator[bytes]: return self.chunks() def __len__(self) -> int: return self.length @dataclasses.dataclass(frozen=True) class Request: method: str url: str headers: Mapping[str, str] body: Union[bytes, StreamedBody, None] #: Whether the transport follows the redirects follow_redirects: bool = True @dataclasses.dataclass(frozen=True) class Response: status_code: int headers: Mapping[str, str] body: bytes @dataclasses.dataclass(frozen=True) class StreamedResponse: status_code: int headers: Mapping[str, str] chunks: Iterator[bytes] class Transport(Protocol): 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. The transport must not follow the redirects if the request says so. """ The design has the following consequences: * **The client does not depend on an HTTP library.** If `requests`_ changes or falls out of fashion, we, or the users, switch to another implementation, and the client stays the same. * **Implementations are small.** A transport implements a single method, which always streams the response. The library reads the whole body itself where it needs it (``http.send``), so the transports do not implement the same request twice. ``StreamedBody`` is iterable and reports its length through ``__len__``, which is what the HTTP libraries such as `requests`_ need to send a body with ``Content-Length``, so the transports pass it on as it is. ``StreamedResponse`` is a plain data class, so the transports fill it in instead of implementing an adapter. Hence, an implementation for `requests`_, `httpx`_ or `urllib3`_ takes about 25 lines of code. * **An empty body is always** ``b""``. ``StreamedBody`` requires a positive length, since some HTTP libraries, such as `requests`_, treat an iterable of length zero as of unknown length, and send it with chunked transfer encoding. * **The library encodes everything itself**, including base64url-encoded identifiers, query parameters and multipart bodies for file uploads. Hence the encoding is identical regardless of the transport, and we can test it with golden files. * **Requests can be replayed.** A ``bytes`` body can be sent again as-is. A ``StreamedBody`` starts a new iteration over its chunks on every call, and must yield the same bytes each time. The client guarantees this for its uploads by accepting only sources which it can read again (see `Streaming`_). This makes a retry after a refreshed token possible, also for large uploads; it is also safe, since a 401 means that the server did not process the request (see `Token Revocation`_). * **Transports compose.** Authentication, retries, logging or rate limiting are wrappers around another transport. * The library looks up header names case-insensitively, so the transports can pass the headers as a plain :py:class:`dict`. * Network errors (timeouts, refused connections, TLS errors, ...) are raised by the transport and propagate unchanged. The library does not wrap them since it can not know the exceptions of an arbitrary transport. * Timeouts, connection pooling, proxies and TLS settings are configured in the transport. * **The redirects are followed by default**, as the HTTP libraries do. The client turns this off with ``follow_redirects`` only where it must see the redirect itself: the status of a bulk operation redirects to its result, which the server may delete once it has been fetched (see `Bulk Operations`_). A transport must honor the flag; if it follows the redirect anyway, the client refuses the response, since the status endpoint never gives the result's status codes. .. _httpx: https://pypi.org/project/httpx/ .. _urllib3: https://pypi.org/project/urllib3/ Streaming --------- Which operations stream is determined by their content, not chosen by the user: * The operations with binary content stream: the attachments of ``File`` elements (``GetFileByPath``, ``PutFileByPath`` and their variants in the other APIs), the thumbnails (``GetThumbnail``, ``PutThumbnail``), the AASX packages (``GetAASXByPackageId``, ``PostAASXPackage``, ``PutAASXByPackageId``, ``PostAsyncAASXPackage``), and the serialization (``GenerateSerializationByIds``, which returns an AASX package, XML or JSON; see `Serialization`_). * All the other operations exchange JSON, and do not stream. :py:mod:`aas_core3_2.jsonization` needs the complete document anyway, so streaming would bring no benefit there. Hence every operation is still implemented by exactly one function (see `Operations in the Docstrings`_). **Uploads.** The functions which upload a file accept the content either as ``bytes``, or as a binary file object which must be readable and seekable: .. code-block:: python with open("manual.pdf", "rb") as fid: submodel_repository.put_file_by_path( server, "urn:example:submodel:1", "Documentation.Manual", fid, file_name="manual.pdf", content_type="application/pdf", ) The client reads the file object from its current position to the end, in chunks, and never holds the whole content in memory. It wraps the chunks in the multipart envelope as the specification requires (the preamble, the chunks of the file, the closing boundary), and computes the length of the whole body up-front from the size of the file. Hence the body is always sent with ``Content-Length`` and never with chunked transfer encoding, which some servers and reverse proxies reject. Whether an upload can be replayed (for example, after a refreshed token, see `Token Revocation`_) is not a property of the ``StreamedBody``, but of the source of the bytes. A seekable file can be read again from the start; a pipe, a socket, the standard input, a generator or the download stream of another server can not, and their length is not known up-front either. Hence the uploads accept only the sources which the client can read again: * **Accepted sources.** The content is either ``bytes``, or a binary file object which is readable and seekable. The function checks this when it is called, and raises an error right away otherwise, instead of failing in the middle of an upload. The check relies on the behavior, not on the methods ``readable()`` and ``seekable()`` alone: the file object must have ``read``, ``tell`` and ``seek``, it must not report ``seekable()`` as false if it has that method, and the client determines the size by seeking to the end and back. This matters since, for example, :py:class:`tempfile.SpooledTemporaryFile` supports seeking, but lacks ``readable()`` and ``seekable()`` before Python 3.11. * **Checks on every iteration.** When the upload starts, the client records the start position and the size of the content. On every new iteration over the chunks, it seeks back to the start position, and checks that the size is still the same. If the size changed (for example, because another process wrote to the file in the meantime), it raises an error instead of sending a body which contradicts its ``Content-Length``. The check can not detect a file which was rewritten in place with the same size; the users must not modify the file during an upload. * **The file object is used exclusively.** The client moves the position of the file object, so the users must not read from it, nor seek in it, from another thread during the upload. To upload the content of a source which can not be read again, the users first copy it into a temporary file. :py:class:`tempfile.SpooledTemporaryFile` keeps small content in memory, moves large content to the disk, and is seekable, so the memory stays bounded and the upload can be replayed. For example, to copy a large attachment from one server to another: .. code-block:: python with tempfile.SpooledTemporaryFile(max_size=16 * 1024 * 1024) as buffer: with submodel_repository.get_file_by_path( source_server, "urn:example:submodel:1", "Documentation.Manual" ) as download: download.write_to(buffer) buffer.seek(0) submodel_repository.put_file_by_path( target_server, "urn:example:submodel:1", "Documentation.Manual", buffer, file_name="manual.pdf", content_type="application/pdf", ) We considered accepting sources which can not be read again as well, marked as not replayable, with the length given by the users. The retry after a refreshed token would then raise the 401 instead of replaying. This would spare the temporary file when copying between servers, but it would introduce a second kind of uploads with weaker guarantees. We defer it until the users actually need it. **Downloads.** The functions which download a file return a context manager which gives a ``Download``: .. code-block:: python with submodel_repository.get_file_by_path( server, "urn:example:submodel:1", "Documentation.Manual" ) as download: print(download.content_type, download.content_length, download.file_name) with open("manual.pdf", "wb") as fid: download.write_to(fid) ``Download.iter_chunks()`` gives the chunks for processing them on the fly, and ``Download.write_to(destination)`` copies them to a binary file object. The connection is released when the context is exited, also when the download has not been read to the end. If the users need the content in memory, they write ``b"".join(download.iter_chunks())``. **The envelope.** The OpenAPI of Part 2 sends the content in a single part ``file`` of ``multipart/form-data``, and conveys the file name, "if supplied", in the ``filename`` parameter of its ``Content-Disposition``. Hence ``file_name`` is optional, and sent in UTF-8 as it is (RFC 7578); the client refuses the file names and content types with double quotes, backslashes or control characters, since they would break the envelope. The content type of the part is ``application/octet-stream`` as in the OpenAPI, unless the users give ``content_type``; `Eclipse BaSyx Go components`_ take it as the new content type of the file element. The ``Download`` (:py:class:`aas_client3_2.http.Download`) gives the content type and the length as the server announces them, and the file name from ``Content-Disposition`` (both ``filename`` and ``filename*``). If a file element refers to an external resource, the servers may redirect to it; whether a redirect is followed is a matter of the transport (`requests`_ follows it, and drops the ``Authorization`` header if the host changes). **Errors.** If the server responds with an error status, the client reads the body of the error response, releases the connection and raises the error (see `Errors`_) before giving any ``Download``. The client reads at most 1 MiB of an error body, so that a misbehaving server can not exhaust the memory. **Timeouts.** The timeouts of the transport apply between the chunks, not to the whole transfer (for example, the ``timeout`` of `requests`_ limits the wait for the next bytes). Hence a large file does not time out as long as the data keeps flowing. Ready-made Transport Based on requests -------------------------------------- We ship one implementation, in the module ``aas_client3_2.requests_transport``, based on a :py:class:`requests.Session`. It is installed with the extra ``aas-client3.2[requests]``. We chose `requests`_ over :py:mod:`urllib.request` of the standard library since the latter does not re-use connections, and `requests`_ is the de-facto standard which most users already have. The session is passed in by the user, so the session also carries the authentication, proxies, certificates *etc.*: .. code-block:: python class RequestsTransport: def __init__( self, session: requests.Session, timeout: float = 30.0, chunk_size: int = 64 * 1024, ) -> None: self.session = session self.timeout = timeout self.chunk_size = chunk_size @contextlib.contextmanager def send(self, request: http.Request) -> Iterator[http.StreamedResponse]: with self.session.request( request.method, request.url, headers=request.headers, data=request.body, timeout=self.timeout, stream=True, ) as response: yield http.StreamedResponse( status_code=response.status_code, headers=response.headers, chunks=response.iter_content(chunk_size=self.chunk_size), ) `requests`_ uses chunked transfer encoding for an iterator as body, unless it can determine the length of the body. Setting the header ``Content-Length`` explicitly does not help: `requests`_ then sends both ``Content-Length`` and ``Transfer-Encoding: chunked``, which is invalid HTTP. Since ``StreamedBody`` reports its length through ``__len__``, `requests`_ sends only ``Content-Length``. We verify this in the unit tests against a local server (see `Unit Tests`_). We use the same transport in the live tests. Mapping of the Operations ========================= Server ------ A ``Server`` bundles a transport with a base URL: .. code-block:: python @dataclasses.dataclass(frozen=True) class Server: transport: Transport base_url: str Naming Conventions ------------------ Every operation is a module-level function. We name the functions and their parameters after the specification, so that the users who know the operations from the specification, the OpenAPI or Swagger UI find them right away. We only adapt the writing to Python. **Functions.** The name of a function is the operation ID, written in snake case: 1. The suffix which tells the API apart (``_AAS``, ``_AasRepository``, ``_SubmodelRepo`` or ``_SubmodelRepository``) is removed, since the module already tells the API. 2. The rest is split into words at the hyphens and at the changes of case, where a run of capitals forms a single word (for example, ``AASXPackage`` gives ``AASX`` and ``Package``). 3. The words are written in lower case, and joined by underscores. For example, ``GetSubmodelElementByPath_SubmodelRepo`` gives ``submodel_repository.get_submodel_element_by_path``, and ``GetAllAASXPackageIds`` gives ``aasx_file_server.get_all_aasx_package_ids``. We checked these rules against all the 235 operations of the pinned OpenAPI: no two operations of the same module get the same name, and all the names are valid Python identifiers. The names follow the operation IDs faithfully, including their inconsistencies and typos. For example, the Asset Administration Shell API has ``patch_submode_by_id_metadata`` (from ``PatchSubmodeByIdMetadata_AAS``), and ``patch_submodel_element_value_by_path_value_only`` where the Submodel API has ``patch_submodel_element_by_path_value_only``. We deliberately do not correct them, so that a search for the operation ID of the specification always leads to the function. **Parameters.** The parameters are named after the parameters of the specification, written in snake case as well: * the path parameters, such as ``aasIdentifier`` → ``aas_identifier``, ``submodelIdentifier`` → ``submodel_identifier``, ``cdIdentifier`` → ``cd_identifier``, ``idShortPath`` → ``id_short_path``, ``packageId`` → ``package_id`` and ``handleId`` → ``handle_id``, * the query parameters, such as ``semanticId`` → ``semantic_id``, ``idShort`` → ``id_short``, ``assetIds`` → ``asset_ids``, ``createdFrom`` → ``created_from``, ``level``, ``extent``, ``limit`` and ``cursor``, and * the fields of the multipart bodies, such as ``fileName`` → ``file_name``. A couple of examples: .. list-table:: :header-rows: 1 * - Operation (method and path) - Operation ID - Function * - ``GET /submodels`` - ``GetAllSubmodels`` - ``submodel_repository.get_all_submodels`` * - ``POST /submodels`` - ``PostSubmodel`` - ``submodel_repository.post_submodel`` * - ``GET /submodels/{submodelIdentifier}`` - ``GetSubmodelById`` - ``submodel_repository.get_submodel_by_id`` * - ``GET /submodels/{submodelIdentifier}/$value`` - ``GetSubmodelById-ValueOnly`` - ``submodel_repository.get_submodel_by_id_value_only`` * - ``GET /submodels/$reference`` - ``GetAllSubmodels-Reference`` - ``submodel_repository.get_all_submodels_reference`` * - ``GET /submodels/{submodelIdentifier}/submodel-elements/{idShortPath}`` - ``GetSubmodelElementByPath_SubmodelRepo`` - ``submodel_repository.get_submodel_element_by_path`` * - ``PUT /submodels/{submodelIdentifier}/submodel-elements/{idShortPath}/attachment`` - ``PutFileByPath_SubmodelRepo`` - ``submodel_repository.put_file_by_path`` * - ``POST /submodels/{submodelIdentifier}/submodel-elements/{idShortPath}/invoke-async`` - ``InvokeOperationAsync_SubmodelRepository`` - ``submodel_repository.invoke_operation_async`` * - ``GET /submodel`` - ``GetSubmodel`` - ``submodel.get_submodel`` * - ``GET /shells/{aasIdentifier}/submodels/{submodelIdentifier}/submodel-elements/{idShortPath}`` - ``GetSubmodelElementByPath_AasRepository`` - ``aas_repository.get_submodel_element_by_path`` * - ``GET /shells/{aasIdentifier}/submodel-refs`` - ``GetAllSubmodelReferences_AasRepository`` - ``aas_repository.get_all_submodel_references`` * - ``GET /shell-descriptors/{aasIdentifier}/submodel-descriptors`` - ``GetAllSubmodelDescriptorsThroughSuperpath`` - ``aas_registry.get_all_submodel_descriptors_through_superpath`` * - ``GET /lookup/shells`` - ``GetAllAssetAdministrationShellIdsByAssetLink`` - ``discovery.get_all_asset_administration_shell_ids_by_asset_link`` * - ``GET /packages/{packageId}`` - ``GetAASXByPackageId`` - ``aasx_file_server.get_aasx_by_package_id`` * - ``GET /description`` - ``GetSelfDescription`` - ``description.get_self_description`` **Signatures.** The first argument is always the ``Server``. The path parameters, in the order of the path, and the payload (such as the submodel to be posted, or the content of a file to be uploaded) follow as positional arguments. Everything else is keyword-only: the query parameters, and the further fields of a body, such as the file name and the content type of an upload. .. code-block:: python def get_submodel_by_id( server: http.Server, submodel_identifier: str, *, level: Optional[aas_types.Level] = None, extent: Optional[aas_types.Extent] = None, ) -> aas_types.Submodel: ... The bare ``*`` in the signature is not a parameter. It marks all the parameters after it as keyword-only (see `PEP 3102`_), so they can only be passed by name: .. code-block:: python a_submodel = submodel_repository.get_submodel_by_id( server, "urn:example:submodel:1", level=aas_types.Level.CORE ) We make these parameters keyword-only for two reasons: * **Mix-ups can not go unnoticed.** Many of these parameters share a type, so a type checker can not catch them when they are swapped. For example, ``id_short`` and ``cursor`` of ``get_all_submodels`` are both ``Optional[str]``, and the ``file_name`` and the ``content_type`` of ``put_file_by_path`` are both ``str``. If they were positional, ``get_all_submodels(server, "Nameplate")`` might silently page from the cursor ``"Nameplate"`` instead of filtering by the ID-short. With the keyword-only parameters, the call has to read ``get_all_submodels(server, id_short="Nameplate")``. * **The signatures can evolve.** The query parameters have no meaningful order in the specification, and future versions might add new ones. Adding or reordering keyword-only parameters never breaks the existing calls. This is idiomatic Python; for example, :py:func:`sorted` and :py:func:`subprocess.run` use keyword-only parameters the same way. All the examples in this documentation pass these parameters by name. .. _PEP 3102: https://peps.python.org/pep-3102/ The identifiers are passed as plain strings. The client encodes them in base64url as the specification requires. The references and the specific asset IDs in the query, such as ``semanticId`` and ``assetIds``, are passed as instances of :py:mod:`aas_core3_2.types`. The client serializes them to JSON and encodes them in base64url, as the prose of the specification requires. The operation table and the OpenAPI of the specification speak, in contrast, of "the value of the semantic ID" for ``semanticId``. We follow the prose, as `Eclipse BaSyx Go components`_ do. The serialization modifiers ``level`` and ``extent`` are passed as ``aas_types.Level`` and ``aas_types.Extent``. Part 2 defines them as enumerations (see `Operation Parameters of Part 2`_), but only says that they are "mapped to the query parameter", and spells the values of the query inconsistently, such as ``?extent=WithBLOBValue`` in the prose and ``extent="withBlobValue"`` in an example. The OpenAPI is the only exact definition (``deep`` and ``core``, and ``withBlobValue`` and ``withoutBlobValue``), and `Eclipse BaSyx Go components`_ accept only these spellings. Since 1.0.0rc3, aas-core3.2 spells the values of these enumerations as the OpenAPI does, so the client puts them into the query as they are. Query parameters which allow only a single value, such as the deprecated ``level`` of ``GetAllSubmodels-Reference`` (only ``core``), are omitted. .. _Operation Parameters of Part 2: https://industrialdigitaltwin.io/aas-specifications/IDTA-01002/v3.2/specification/interfaces-operation-parameters.html#SerializationModifier Operations in the Docstrings ---------------------------- The docstring of every function states exactly which operation it implements: the operation ID, the HTTP method and the path, exactly as they appear in the OpenAPI. This also disambiguates the operations whose names are easily confused, such as ``submodel_repository.get_all_submodels_reference`` and ``aas_repository.get_all_submodel_references``. The operations of Part 2 which differ only in a filter, such as ``GetAllConceptDescriptionsByIdShort`` and ``GetAllConceptDescriptionsByIsCaseOf``, are a single operation in the OpenAPI, which lists them among its semantic IDs (``x-semanticIds``). We follow the OpenAPI: a single function implements them, with a keyword-only parameter per filter, and the filters are combined with "and"; its docstring names the variants it covers. We state the operation with a custom field ``:implements:`` in the docstring, alongside the standard fields such as ``:param:`` and ``:returns:``. The operation ID is the argument of the field, and the method together with the path is its body: .. code-block:: python def get_all_submodels_reference( server: http.Server, *, semantic_id: Optional[aas_types.Reference] = None, id_short: Optional[str] = None, limit: Optional[int] = None, cursor: Optional[str] = None, ) -> aas_types.GetReferencesResult: """ Get a reference for each submodel in the repository. This is not to be confused with :py:func:`aas_client3_2.aas_repository.get_all_submodel_references`, which lists the submodel references of an Asset Administration Shell. :param server: where to send the request :param semantic_id: if set, only the submodels with this semantic ID :param id_short: if set, only the submodels with this ID-short :param limit: maximum number of the references in the page :param cursor: where to continue the listing from :returns: a page of the references :implements GetAllSubmodels-Reference: ``GET /submodels/$reference`` """ def get_submodel_element_by_path( server: http.Server, aas_identifier: str, submodel_identifier: str, id_short_path: str, *, level: Optional[aas_types.Level] = None, extent: Optional[aas_types.Extent] = None, ) -> aas_types.SubmodelElement: """ Get the submodel element at the given ID-short path. :param server: where to send the request :param aas_identifier: identifier of the Asset Administration Shell :param submodel_identifier: identifier of the submodel :param id_short_path: ID-short path of the element :param level: depth of the returned element :param extent: whether to include the values of blobs :returns: the submodel element :implements GetSubmodelElementByPath_AasRepository: ``GET /shells/{aasIdentifier}/submodels/{submodelIdentifier}/submodel-elements/{idShortPath}`` """ Format ^^^^^^ The field follows a strict format so that we can check it automatically: * The field matches the regular expression: .. code-block:: text ^:implements (?P[^\s:`]+): ``(?PGET|POST|PUT|PATCH|DELETE) (?P/[^`\s]*)``$ * The operation ID and the path are copied verbatim from the pinned OpenAPI, including the inconsistencies and typos of the specification, such as ``PatchSubmodeByIdMetadata_AAS``. The method is written in upper case. * The field is never wrapped, however long the path. The line length is not enforced for the code (we leave the formatting to black, which does not touch docstrings), so this does not clash with the linters. * The field comes last, after all the other fields. Since this is the standard syntax of reStructuredText field lists, the conformance check parses the docstrings with docutils, and does not need a parser of its own. Docutils splits the field into the name (``implements`` and the operation ID) and the body (the method and the path). The rules for the functions are: * Every public function of an API module implements exactly one operation, and has exactly one ``:implements:`` field. * The name of the function is derived from the operation ID by the rules in `Naming Conventions`_, and the module from the API group of the operation (see `Layers`_). * Every operation of the pinned OpenAPI is stated in exactly one ``:implements:`` field of the client. The only exception are the query operations, whose result is either the full objects or their identifiers, depending on the query (see `Query`_). Each of them is implemented by two functions, which both state the operation: one is named after the operation ID (such as ``query_submodels``), and the other after the operation ID with ``Ids`` appended to the queried objects in the singular (such as ``query_submodel_ids``), as Part 2 names the semantic IDs of this distinction, such as ``QueryConceptDescriptionIds``. The check is strict: every field whose name starts with ``implements`` must match the regular expression, so that a malformed field is reported as an error, and can never be silently skipped. Rendering in Sphinx ^^^^^^^^^^^^^^^^^^^ Sphinx would render an unknown field as a generic field. Hence the function ``setup`` in ``docs/source/conf.py`` registers ``implements`` as a grouped field of the Python domain (a ``sphinx.util.docfields.GroupedField`` appended to the ``doc_field_types`` of the Python objects). The operation is therefore rendered under the label "Implements", like the parameters under "Parameters", with the operation ID followed by its method and path. This needs no extra dependency. Purpose ^^^^^^^ The field serves four purposes at once: * the users who come from the specification find the function by searching the documentation for the operation ID or the path, * the documentation lists all the operations in a single index (see `Documentation`_), * the reviewers compare it against the OpenAPI side by side, and * the conformance check parses it as the mapping from the operation IDs to the functions (see `Cross-checking against the OpenAPI`_). Hence the mapping lives in exactly one place, next to the code which implements it. The testing client follows the same format, and the same check applies to it. One Function per Operation -------------------------- The APIs of the specification are nested. For example, the operations of the Submodel API are served at ``/submodel`` by a Submodel Service, at ``/submodels/{submodelIdentifier}`` by a Submodel Repository, at ``/aas/submodels/{submodelIdentifier}`` by an Asset Administration Shell Service, and at ``/shells/{aasIdentifier}/submodels/{submodelIdentifier}`` by an Asset Administration Shell Repository. The OpenAPI lists every such variant as an operation of its own, with an operation ID of its own. The operation IDs of the variants are not uniform: of the 39 distinct operations served under these four prefixes, 19 have variants whose operation IDs differ by more than the suffix of the API. For example, the operation ``GET`` on the submodel itself is ``GetSubmodel`` in the Submodel API, but ``GetSubmodelById`` in the repositories, and ``PATCH`` on a submodel element is ``PatchSubmodelElementByPath`` in the Submodel API, but ``PatchSubmodelElementValueByPath_AAS`` in the Asset Administration Shell API. Hence we do not compose the nested APIs out of shared functions, which would force us to pick a single name for the differently named variants. Instead, every variant is a public function of its own, in the module of its API, and takes all the identifiers of its path as arguments: .. code-block:: python # GetSubmodelElementByPath_SubmodelRepo element = submodel_repository.get_submodel_element_by_path( server, "urn:example:submodel:1", "Motor.Speed" ) # GetSubmodelElementByPath_AasRepository element = aas_repository.get_submodel_element_by_path( server, "urn:example:aas:1", "urn:example:submodel:1", "Motor.Speed" ) # GetSubmodelElementByPath, against a Submodel Service element = submodel.get_submodel_element_by_path(server, "Motor.Speed") The variants share their implementation internally: the public function builds the path, and delegates the rest to the common build and parse functions (see `Build, Send, Parse`_). Hence the duplication is limited to thin public functions, while the users get exactly the operations they see in the specification. The common functions of the operations on a submodel live in the internal module ``_submodel_operations``. They take the encoded path of the submodel, such as ``/submodels/{submodelIdentifier}`` or ``/shells/{aasIdentifier}/submodels/{submodelIdentifier}``, and are named after the operations of the Submodel Repository API. The private functions ``_build_*`` and ``_parse_*`` of each API module stay, named after its public functions, and delegate to them, so that the testing client and the reviewers still find the build and the parse of every operation in the module of its API. The variants do not always agree in their query parameters. For example, the OpenAPI gives ``extent`` to ``GetAllSubmodelElements-Path_AasRepository``, but not to ``GetAllSubmodelElements-Path_SubmodelRepo``, and the other way around for ``GetAllSubmodelElements-ValueOnly``; and ``PatchSubmodelElementValueByPath_AasRepository`` takes both values of ``level``, while ``PatchSubmodelElementByPath_SubmodelRepo`` allows only ``core``. The common functions take all the parameters of the variants, and each public function exactly those of its own operation, as the OpenAPI lists them. The unit test ``test_openapi_conformance`` checks this for every public function: the operation, its method and path, the name of the function, the path parameters and the query parameters. Part 2 defines the superpaths only as the combination of the interfaces (see `Superpaths in Part 2`_), and says nothing more about their semantics, *e.g.*, whether deleting a submodel through the shell also removes the reference of the shell. Hence the live tests check that every operation through the shell gives the same as the operation of the Submodel Repository on the same submodel, and that a submodel to which the shell does not refer is not found through it. .. _Superpaths in Part 2: https://industrialdigitaltwin.io/aas-specifications/IDTA-01002/v3.2/http-rest-api/http-rest-api.html#superpaths Navigating from a Registry -------------------------- The descriptors in a registry list the endpoints of the services, each with the interface (such as ``SUBMODEL-3.2``) and the address (``protocolInformation.href``). The users construct a ``Server`` with the address as the base URL, and call the functions of the module which corresponds to the interface (such as ``submodel`` for ``SUBMODEL-3.2``). **The address is the resource itself.** The interactions of Part 2 (see `Interactions in Part 2`_) say that "the client application just uses the endpoint as provided in the Registry", so that it can not tell a submodel server from a repository. Their sequence fetches a submodel with ``GET`` on the endpoint, which is either ``/submodel`` of a Submodel API or ``/submodels/{submodelIdentifier}`` of a Submodel Repository, and their example of an AAS endpoint is ``https://service.example.com/aas/shells/{aasIdentifier}``. Hence the paths of the Asset Administration Shell API and of the Submodel API are relative to the address, without their prefixes ``/aas`` and ``/submodel``: the operation ``GetSubmodel`` (``GET /submodel``) is ``GET {address}``, and ``GetAllSubmodelElements`` (``GET /submodel/submodel-elements``) is ``GET {address}/submodel-elements``. `Eclipse BaSyx Go components`_ (release v1.1.2) agree. They serve no paths starting with ``/aas`` or ``/submodel``, but register the shells with the interface ``AAS-3.2`` and the address ``{externalUrl}/shells/{aasIdentifier}``, and the submodels with ``SUBMODEL-3.2`` and ``{externalUrl}/submodels/{submodelIdentifier}`` (with the identifiers in base64url), and serve the operations of the shell or the submodel under this address. Hence the modules ``aas`` and ``submodel`` take a ``Server`` whose base URL is the address of the endpoint, and append the paths of the operations without the prefix. .. _Interactions in Part 2: https://industrialdigitaltwin.io/aas-specifications/IDTA-01002/v3.2/http-rest-api/interactions.html Pagination ---------- The functions over collections return the paged results of :py:mod:`aas_core3_2.types` (such as ``GetSubmodelsResult``), which contain the items of the page and the cursor. The module ``pagination`` provides a generic helper which follows the cursors: .. code-block:: python for a_submodel in pagination.iterate( lambda cursor: submodel_repository.get_all_submodels(server, cursor=cursor) ): ... Each page is a separate request through the transport. Hence, a token refreshed or revoked between two pages takes effect on the next page. The helper stops at the first page without a cursor, and also at an empty cursor, which the specification forbids (Constraint AASa-001), since passing it back would most probably restart the listing. If the server gives a cursor which it has already given before, the helper raises ``RepeatedCursor`` instead of looping forever. Errors ------ A response with an unexpected status code raises an ``HttpError`` (or one of its subclasses, such as ``BadRequest``, ``Unauthorized``, ``Forbidden``, ``NotFound``, ``MethodNotAllowed``, ``Conflict`` or ``NotImplementedByServer``). The exception carries the raw ``Response`` and, if the body could be parsed, the ``aas_core3_2.types.Result`` with the server's messages. A response which can not be de-serialized raises an ``UnexpectedResponse`` which carries the raw ``Response`` and the de-serialization error. The client is strict about the ``Content-Type`` of the responses which it parses. A JSON payload must come as ``application/json`` (the parameters, such as ``charset``, do not matter), and a JWS of ``$signed`` as ``text/plain``; otherwise, the client raises ``UnexpectedResponse``, even if the body could be parsed. The client does not guess the format from the body, nor does it work around the servers which do not set the content type as the specification requires; such deviations are reported to the servers instead (see `Live Tests`_). The body of an error response is parsed for the messages only if it is JSON, since the servers often send HTML or plain text there, for example, from a reverse proxy; the error is raised either way. The downloads of files and thumbnails accept any content type, since it is the type of the file. All the errors of the client derive from a common base ``Error``, so that the users can catch them in one place, apart from the network errors of the transport. The client de-serializes the responses, but it does not verify them with :py:mod:`aas_core3_2.verification`. Verifying every response would be too inefficient: the verification walks the whole instance and checks all the constraints of the meta-model, which costs far more than the de-serialization, for example, for a large submodel or every page of a listing. Checking the conformance of a server is what the testing client is for (see `Testing Client with Contracts`_); the users who need a verified instance in production verify it themselves. Build, Send, Parse ------------------ Internally, every operation consists of three parts: 1. a pure function which builds the ``Request`` from the arguments, 2. sending the request through the transport, and 3. a pure function which parses the ``Response`` into the result, or raises an error. The public function only chains the three. The pure functions do no I/O, so we can unit-test them without a transport. The pure functions are private functions of the API module, named after the public function with the prefixes ``_build_`` and ``_parse_`` (for example, ``_build_get_asset_information`` and ``_parse_get_asset_information``). They live in the same module so that the reviewers see the docstring with the operation, the path and the parsing of an operation side by side. Since they are private, they show up neither in the reference documentation nor in the autocompletion of the users, and the rule that every public function of an API module implements exactly one operation stays simple (see `Operations in the Docstrings`_). The shared helpers for the JSON bodies live in the internal module ``_json``. The testing client reuses them to inspect the raw responses (see `Testing Client with Contracts`_), and the ``asyncio`` interface will reuse them later (see `Synchronous First, asyncio Later`_). Metadata -------- The operations with the path suffix ``$metadata`` take and give the metadata classes of :py:mod:`aas_core3_2.types`, such as ``SubmodelMetadata`` and ``PropertyMetadata``. These classes are not part of the meta-model of Part 1, but formalize the metadata serialization which Part 1 defines by leaving out fields of the normal classes (see `Format Metadata of Part 1`_), such as ``submodelElements`` of a submodel or ``value`` and ``valueId`` of a property. We distinguish between storing the metadata in JSON and XML files, and sending it over HTTP: * In files, aas-core3.2 gives the metadata classes model types of their own (``"modelType": "PropertyMetadata"`` in JSON, ```` in XML), so that a reader can tell a metadata instance from a normal one without any context. * Over HTTP, Part 2 sends the metadata with the model types of the normal classes (``"modelType": "Property"``), as the examples in `SerializationModifier Examples of Part 2`_ show, and as `Eclipse BaSyx Go components`_ send and expect it. The context is given by the path suffix ``$metadata`` instead. Hence the client renames the model types on the way: it removes the suffix ``Metadata`` before sending a metadata instance, and adds it to the model type of every received instance before de-serializing it with aas-core3.2. The metadata leaves out the children (``submodelElements``, ``value``, ``statements`` and ``annotations``), so only the model type at the top level of each instance, or of each item of a page, needs renaming. The client renames the parsed JSON in place, since it is fresh, so that large pages are not copied. The renaming lives in the internal module ``_metadata`` on top of ``_json``, and neither the meta-model nor aas-core3.2 needed a change for it. We deliberately do not change aas-core3.2 to use the model types of the normal classes for the metadata: a metadata file would then become ambiguous, since, for example, the metadata of a property and a property without a value would look the same. Nor can we drop the model types, since aas-core3.2 dispatches on them to the concrete classes of the submodel elements. The difference is specific to the HTTP API, so the client is the place to handle it. A server which sends the model types of aas-core3.2, such as ``"modelType": "PropertyMetadata"``, is not conformant, and the client raises an ``UnexpectedResponse``. .. _Format Metadata of Part 1: https://industrialdigitaltwin.io/aas-specifications/IDTA-01001/v3.2/mappings/mappings.html#_format_metadata_metadata_serialization .. _SerializationModifier Examples of Part 2: https://industrialdigitaltwin.io/aas-specifications/IDTA-01002/v3.2/annex/serialization-modifier-examples.html Value-Only ---------- The operations with the path suffix ``$value`` exchange the ValueOnly serialization of Part 1 (see `Value-Only Serialization of Part 1`_), which keeps only the values of the submodel elements. For example, a property ``speed`` of type ``xs:int`` with the value ``"5"`` becomes ``5``, and a collection ``motor`` with that property becomes ``{"speed": 5}``. **Getting gives JSON.** The ValueOnly serialization can not be parsed without knowing the structure behind it. For example, a range ``{"min": 1, "max": 5}`` looks exactly like a collection with the properties ``min`` and ``max``, and a file looks exactly like a blob. Part 1 says so itself: the receiver needs to take the type of the target resource into account. Hence the functions which get the values return plain JSON, :py:data:`aas_core3_2.types.JsonObject` for a submodel and :py:data:`aas_core3_2.types.JsonValue` for a submodel element, just as the pages of aas-core3.2 hold them (:py:class:`aas_core3_2.types.GetSubmodelElementsValueResult`). The users who know the structure, for example from the operations ``$metadata``, can parse the parts further, such as a range with :py:func:`aas_core3_2.jsonization.range_value_from_jsonable`. The client parses the JSON with aas-core3.2 (:py:func:`aas_core3_2.jsonization.json_value_from_jsonable`). JSON knows a single numeric type, so aas-core3.2 gives every number as a :py:class:`float`, as the SDKs of aas-core in the other languages do, and accepts only the integers which a float represents exactly (the safe integers up to 2^53 - 1, which is also the limit of Part 1 for the ValueOnly serialization). Hence the values of a single element and the values in the pages come out the same, and the users decide which numbers are integers, from the value types of the elements. **Patching takes the instances.** The other direction is always determined: the ValueOnly serialization follows from a submodel or a submodel element itself. Hence the functions which patch the values take the instances of :py:mod:`aas_core3_2.types`, as all the other functions do, and the client serializes them. This spares the users writing the ValueOnly serialization by hand, which is easy to get wrong (*e.g.*, ``"5"`` instead of ``5`` for an ``xs:int``). The client raises a :py:class:`ValueError` before sending anything if an instance has no ValueOnly serialization (an operation or a capability), or if a value can not be represented in JSON (*e.g.*, an ``xs:double`` of ``INF``, or an integer out of the safe range). The serialization lives in the internal module ``_value_only``, whose docstring lists the rules. We follow the prose, the `data type to value mapping`_ and the examples of Part 1, and the OpenAPI of Part 2, and `Eclipse BaSyx Go components`_ where they are silent. In particular, the elements without a value are left out, except in a submodel element list, where they are ``null`` so that the indices are the same as in the normal serialization. The integral numbers are written without a fraction (``5``, not ``5.0``), so that also the servers which read the numbers by their lexical form accept them. The testing client uses the same serialization in the live tests: the values which a server gives must equal the serialization of the submodel which the tests stored. **The pages are arrays.** Since V3.0.4, the OpenAPI types the results of ``GetAllSubmodels-ValueOnly`` and ``GetAllSubmodelElements-ValueOnly`` as a single JSON object instead of an array. A single object can not hold a page of several submodels, since the ValueOnly serialization carries no identifier of the submodel. aas-core3.2 follows the prose of Part 2 and `Eclipse BaSyx Go components`_ instead, and so does the client: both pages are arrays, and each item of the page of the submodel elements is a JSON object with a single key, the ID-short of the element. .. _Value-Only Serialization of Part 1: https://industrialdigitaltwin.io/aas-specifications/IDTA-01001/v3.2/mappings/mappings.html#_overview_of_value_only_serialization_attributes .. _data type to value mapping: https://industrialdigitaltwin.io/aas-specifications/IDTA-01001/v3.2/mappings/mappings.html#_data_type_to_value_mapping Paths ----- The operations with the path suffix ``$path`` give the ID-short paths of the submodel elements, such as ``motor.speed`` and ``readings[0]``. The paths always start at the top-level elements, since a submodel has no path of its own, and the paths of an element include its own path (see `SerializationModifier Examples of Part 2`_). **Bare arrays are lists of strings.** The operations on a single submodel or element give a bare JSON array of paths, which aas-core3.2 does not de-serialize on its own (it only knows the pages, :py:class:`aas_core3_2.types.GetPathItemsResult`). The client parses these arrays itself into a :py:class:`list` of :py:class:`str`. As everywhere else, the client checks only the structure, and the testing client verifies the paths with :py:func:`aas_core3_2.verification.matches_path_item`. **The pages are flat.** Part 2 gives the page of ``GetAllSubmodels-Path`` as a single flat array of paths over all the matching submodels. The paths carry no identifier of their submodel, so the paths of different submodels can not be told apart; the users filter by the ID-short or the semantic ID, or get the paths of a single submodel. The limit of the pages applies to the paths, not to the submodels or the top-level elements. .. _SerializationModifier Examples of Part 2: https://industrialdigitaltwin.io/aas-specifications/IDTA-01002/v3.2/annex/serialization-modifier-examples.html Invocation of Operations ------------------------ An operation (the submodel element ``Operation``) is invoked either synchronously, with ``/invoke``, or asynchronously, with ``/invoke-async`` (see `Asynchronous Invocation of Operations in Part 2`_). Both come in the normal form, with the arguments as operation variables (:py:class:`aas_core3_2.types.OperationRequest`), and in Value-Only, with the arguments as a mapping of ID-shorts to values (:py:class:`aas_core3_2.types.OperationRequestValueOnly`). The users write the Value-Only arguments themselves, since the client does not know the variables of the operation; aas-core3.2 checks them when it serializes the request, and gives the numbers in the result as floats, as everywhere in Value-Only (see `Value-Only`_). **A failed operation is a result.** The server gives the result of an operation with 200 also when the operation failed, and sets its ``execution_state`` to ``Failed``. Hence the client does not raise in this case, and the users check ``execution_state`` and ``success`` of the result. An error status means that the invocation itself failed, for example, 405 if the element is not an operation. **The handle comes from the location.** The server accepts an asynchronous invocation with 202, and gives the status endpoint ``.../operation-status/{handleId}`` in the header ``Location``; there is no body. ``invoke_operation_async`` takes the handle from the last segment of that path, and returns it as an :py:class:`aas_core3_2.types.OperationHandle`. The OpenAPI describes ``handleId`` in the path as "UTF8-BASE64-URL-encoded", but the client never makes up a handle: it only sends back the one from the ``Location``, which is already in the form the server expects in the path. Hence the client does not encode the handle in base64url again, but only URL-encodes it as a path segment. This works both with the servers which encode their handles in base64url, and with those which use them as they are (`Eclipse BaSyx Go components`_ give handles such as ``SMREPO-ASYNC-0WWh...``, which are not base64url-encoded). **The status follows the redirect.** While the operation runs, the status endpoint gives a :py:class:`aas_core3_2.types.BaseOperationResult` with ``Running``. Once the operation is finished, the endpoint redirects with 302 to the result. Most transports follow a redirect of a GET on their own (the one based on `requests`_ does), so the client usually sees the result instead, with the arguments. If the transport does not follow it, the client does, so that ``get_operation_async_status`` behaves the same with every transport, and gives the actual state of the finished operation (``Completed``, ``Failed``, ``Canceled`` or ``Timeout``), not just the fact that it is finished. The client follows the redirect only to the origin of the server (the same scheme, host and port as the base URL), since it sends the same headers, including the credentials, as to the status; otherwise it raises ``UnexpectedResponse``. In both cases, ``get_operation_async_status`` gives only the status, without the arguments. The users fetch the arguments with ``get_operation_async_result`` or ``get_operation_async_result_value_only``, so that the status of every invocation has the same type. The client does not poll on its own, since how often and how long to poll depends on the application; the docstring of ``invoke_operation_async`` shows a loop. The handling lives in the internal module ``_invocation``, so that the AAS Repository API and the Submodel API reuse it for their variants of the operations. .. _Asynchronous Invocation of Operations in Part 2: https://industrialdigitaltwin.io/aas-specifications/IDTA-01002/v3.2/http-rest-api/http-rest-api.html#async-invocation-of-se-operation History and Signatures ---------------------- **History.** The operations ``$history`` give the version of an AAS or a submodel which was valid at a point in time, ``date``. The version is the state as stored by the server, not the attribute ``version`` of the administrative information, and which changes make a new version is up to the server (see `GetSubmodelVersionByIdAndDate in Part 2`_). The parameter ``date`` is optional: without it, the server gives the latest version. As for the other points in time, the client refuses a ``date`` without a time zone, since the server would interpret it in a time zone of its own, and sends the fractions of a second, since a version may last less than a second. **Signatures.** The operations ``$signed`` give an AAS, a submodel or a concept description as a JSON Web Signature (JWS, RFC 7515) in the compact serialization, as plain text (see `Signatures in Part 2`_). The payload is the JSON of the identifiable, and the header carries the algorithm (``alg``, currently only RS256) and the certificate chain of the signing key (``x5c``), among others. The client gives the JWS as a :py:class:`str`, and does not verify it. A verification is only worth something against the root certificates which the users trust, and Part 2 leaves their exchange to the business partners over another secure channel. Verifying against the certificate in the JWS itself would prove nothing, since anybody can sign with a certificate of their own, and verifying against a fixed set of roots would require a cryptography library as a dependency, and a policy which belongs to the application. Hence the users verify the JWS with a JWS library of their choice and their trusted certificates, and parse the verified payload with aas-core3.2, such as :py:func:`aas_core3_2.jsonization.submodel_from_jsonable`. The client deliberately offers no function to read the payload without the verification, since that would invite skipping it. The client checks only that the body is a JWS in the compact serialization. It deliberately refuses the JWS as a JSON string in double quotes, as `Eclipse BaSyx Go components`_ send it, although the two could be told apart: the users would hand the JWS to a JWS library, which follows the specification as well, so the client does not hide a deviation which breaks later. The testing client insists on ``text/plain`` in addition, checks that the header gives ``alg`` and ``x5c``, and that the payload is a valid identifiable with the requested identifier. .. _GetSubmodelVersionByIdAndDate in Part 2: https://industrialdigitaltwin.io/aas-specifications/IDTA-01002/v3.2/specification/interfaces.html#GetSubmodelVersionByIdAndDate .. _Signatures in Part 2: https://industrialdigitaltwin.io/aas-specifications/IDTA-01002/v3.2/signatures.html Recent Changes -------------- The operations ``$recent-changes`` list pages of changes instead of the identifiables themselves: a change gives the identifier, when the identifiable was created and last updated, and a few attributes to tell it apart (the semantic IDs of a submodel, the asset IDs of an AAS), so that also a large number of changes can be listed (see `Recent Changes in Part 2`_). The users get the identifiables they are interested in with the usual operations. The operations are marked as experimental in Part 2 V3.2. The filters are combined with "and", except ``createdFrom`` and ``updatedFrom``, which are combined with "or" between them; the docstrings say so, since it differs from the other listings. The prose of Part 2 lists ``semanticId`` and ``idShort`` as mandatory inputs, while the OpenAPI makes them optional query parameters; the client follows the OpenAPI, as for all the parameters. The changes carry no ID-short, so the testing client can not check that filter, but it checks the semantic IDs, the limit and the times. The recent changes of the concept descriptions have no filters except the times, neither in the prose nor in the OpenAPI. Part 1 defines ``createdAt`` and ``updatedAt`` of the administrative information as data of the model, and Part 2 does not say whether a server records them itself. According to the maintainers of `Eclipse BaSyx Go components`_, the API task force discussed this and decided that they are the data of the users: a generic server does not set them, and the users set them themselves (`basyx-go-components#821`_). Hence the times of ``$recent-changes``, and the filters ``createdFrom`` and ``updatedFrom`` of the listings, refer to ``createdAt`` and ``updatedAt`` as the users wrote them, and an identifiable without them is never selected by these filters nor listed among the recent changes. The client follows this reading, and the live tests set the times. .. _basyx-go-components#821: https://github.com/eclipse-basyx/basyx-go-components/issues/821 .. _Recent Changes in Part 2: https://industrialdigitaltwin.io/aas-specifications/IDTA-01002/v3.2/specification/interfaces-payload.html#RecentChanges Query ----- The query operations, such as ``QuerySubmodels`` (``POST /query/submodels``) and ``QueryAssetAdministrationShells`` (``POST /query/shells``), send a query in the AAS Query Language as the JSON body, and give a page of the matching objects (see `Query Language in Part 2`_). aas-core3.2 formalizes the query language, so the users pass the query as an instance of ``aas_types.Query``, and the client serializes it with aas-core3.2 like any other payload: .. code-block:: python query = aas_types.Query( condition=aas_types.EqualComparison( eq=( aas_types.FieldOperand(field="$sm#idShort"), aas_types.StringLiteral(str_val="Nameplate"), ) ) ) for a_submodel in pagination.iterate( lambda cursor: submodel_repository.query_submodels( server, query, cursor=cursor ) ): ... The result depends on the query: the full objects by default, or only their identifiers if the query states ``"$select": "id"``. The OpenAPI therefore gives the items of the result as "an object or a string" (``QueryResultSubmodel`` and ``QueryResultAssetAdministrationShell``), and aas-core3.2 does not formalize these results, since such an item can not be represented as a union of classes. Instead of a single function with a union as the result, which every caller would have to narrow, we implement each of these operations by *two* functions with typed results: * ``query_submodels`` and ``query_asset_administration_shells`` give the pages of the full objects as the pages of aas-core3.2 (``GetSubmodelsResult`` and ``GetAssetAdministrationShellsResult``), and * ``query_submodel_ids`` and ``query_asset_administration_shell_ids`` give the pages of the identifiers as ``query_results.IdsResult``. Each function raises a ``ValueError`` before sending anything if the query selects the other kind of the result. The names of the second functions follow the semantic IDs which Part 2 gives to the same distinction in the other query operations, such as ``QueryConceptDescriptionIds`` of ``QueryConceptDescriptions``. This is the only exception to the rule of one function per operation (see `Operations in the Docstrings`_). The same holds for the concept descriptions and the descriptors in the registries, such as ``query_submodel_descriptors`` and ``query_submodel_descriptor_ids``. The OpenAPI disagrees with itself for the descriptors: ``QueryResultAssetAdministrationShellDescriptor`` allows only descriptors in the result, although the operation lists the semantic ID ``QueryAssetAdministrationShellDescriptorIds``, while ``QueryResultSubmodelDescriptor`` allows the identifiers, although the operation lists no such semantic ID. The prose of Part 2 gives both results as "descriptors or identifiers", and ``$select`` is part of the query language for every kind of object, so we follow the prose and implement both functions for both. Both pages follow the protocol of ``pagination.Page``, so the cursors are followed the same way as for the other listings. The paging metadata of a query result may state the ``resultType`` (such as ``Submodel`` or ``Identifier``), which the paging metadata of aas-core3.2 does not know. The client checks that it matches the kind of the result which was asked for, and removes it before the de-serialization. The OpenAPI requires the paging metadata in all the query results except ``QueryResultAssetAdministrationShell``; the client accepts a missing paging metadata there as a page without a cursor, and refuses it elsewhere. The testing client checks the results as for the other listings: the objects or the identifiers verify, and the page does not exceed the limit. It does not check that the results match the condition of the query, nor that the filters (``$filters``) were applied, since that would take an evaluator of the query language. The filters may remove parts of the objects, so the objects in the page are not necessarily complete. aas-core3.2 formalizes the query language differently from the schema ``Query`` of the OpenAPI. For example, it gives the items of a comparison as a tuple of two operands of a single union, and checks with the invariants that they are of a comparable kind, while the schema lists an array of two items for each kind of operand (strings, numbers, hexadecimals, booleans, date-times and times). Hence the unit tests check that the client sends exactly what the specification allows: * the examples of queries in Part 2 (copied to ``dev/test_data/query_language``) validate against the schema, pass the verification of aas-core3.2, and are sent unchanged, * for every comparison and every pair of operand kinds, aas-core3.2 accepts the query if and only if the schema does, and the accepted queries are sent unchanged after a round trip through aas-core3.2, and * these queries together cover every class of the query language in aas-core3.2. A query which can not be serialized to JSON, such as one with a number literal which is not finite, is refused with a ``ValueError`` before anything is sent. `Eclipse BaSyx Go components`_ serve the query operations, including ``$select`` and ``$filters``, and the live tests check every operator against them. The row-wise filters are a known defect of Part 2 V3.2. The section "Query Filter" says that a fragment ending with ``[]`` filters the items of a list row by row, but the condition can not tell whether it should be evaluated on each item or on the enclosing object, and both readings are useful. The fix proposed for the specification (`aas-specs-api#700`_) adds the property ``$match`` to a filter to make the choice explicit, and `Eclipse BaSyx Go components`_ already implement it (`basyx-go-components#824`_): without ``$match``, the condition is evaluated on the enclosing object, so the items of the list are either all kept or all removed, and only with ``"$match": true`` are they filtered row by row. The live tests follow this behavior. The class ``QueryFilter`` of aas-core3.2 has no ``$match``, since Part 2 V3.2 does not define it, so the client can not send it until the specification is fixed. .. _aas-specs-api#700: https://github.com/admin-shell-io/aas-specs-api/issues/700 .. _basyx-go-components#824: https://github.com/eclipse-basyx/basyx-go-components/issues/824 Bulk Operations --------------- The registries create, replace and delete many descriptors at once with the bulk operations at ``/bulk/shell-descriptors`` and ``/bulk/submodel-descriptors`` (see `Bulk Operations in Part 2`_). The body is a JSON array of at least one item, as the OpenAPI requires: the descriptors to be created or replaced, or the identifiers of the descriptors to be deleted. The client refuses an empty sequence with a ``ValueError`` before sending anything. The prose of Part 2 calls the input of the bulk deletion of the shell descriptors a "list of Asset Administration Shell Descriptor objects", while the OpenAPI gives an array of strings; we follow the OpenAPI, as for all the wire formats, and the prose of the bulk deletion of the submodel descriptors agrees with it. The bulk operations follow the asynchronous invocation of operations (see `Invocation of Operations`_), with three differences, which the module ``async_bulk`` implements: * The server accepts a bulk request with 202 and the status endpoint ``/bulk/status/{handleId}`` in the header ``Location``; the client takes the handle from it as for the invocations, and returns it as an :py:class:`aas_core3_2.types.OperationHandle`. Both registries serve the status and the result at the same paths, so ``async_bulk`` takes the server of the registry which accepted the request. * **The status does not follow the redirect.** While the bulk operation runs, the status endpoint gives a :py:class:`aas_core3_2.types.BaseOperationResult` and possibly the header ``Retry-After`` in seconds. Once it is finished, the endpoint redirects with 302 to ``/bulk/result/{handleId}``. Unlike the result of an operation, the server may delete the result of a bulk operation once it has been fetched, and `Eclipse BaSyx Go components`_ do. A transport which follows the redirect of the status would fetch the result, and the users could not fetch it afterwards. Hence the client asks the transport not to follow it (see `Transport Protocol`_), and ``bulk_get_async_status`` gives an ``async_bulk.BulkStatus``, which tells whether the bulk operation is finished, and gives the status and ``Retry-After`` while it runs. * **A failed bulk operation raises.** The result has no content if all the items were processed (204), and the messages of the failed items with 400 otherwise, since a bulk operation is atomic. Hence ``bulk_get_async_result`` returns nothing on success, and raises ``errors.BadRequest`` with the messages otherwise, as for any other bad request. As for the invocations, the client does not poll on its own; the docstring of ``bulk_get_async_status`` shows a loop. The OpenAPI names the bulk creation of the submodel descriptors ``BulkPostSubmodel``, so the function is ``bulk_post_submodel`` by the naming conventions, although it creates descriptors. Discovery --------- The Basic Discovery API links the identifier of an AAS to the IDs of its asset. The global asset ID is given as a specific asset ID with the predefined name ``globalAssetId`` (Constraint AASd-116), so the links are a list of :py:class:`aas_core3_2.types.SpecificAssetID` for an AAS, and the searches match all the given links. ``GetAllAssetAdministrationShellIdsByAssetLink`` takes them in the query, serialized to JSON and encoded in base64url as for the shells, while ``SearchAllAssetAdministrationShellIdsByAssetLink`` takes them as :py:class:`aas_core3_2.types.AssetLink` in the body, so that also many links fit. Both give pages of the identifiers as ``query_results.IdsResult``, as the queries with ``"$select": "id"`` do, since aas-core3.2 does not formalize the pages of bare strings; ``GetAllAssetLinksById`` and ``PostAllAssetLinksById`` exchange bare JSON arrays of specific asset IDs. The testing client compares the links which the server stores with the sent ones regardless of their order, and without the semantic IDs, which Part 2 lets the server ignore. AASX Packages ------------- The AASX File Server API stores packages with their content and the identifiers of the shells which they contain. The uploads stream as described in `Streaming`_, with the content type of the part fixed to ``application/asset-administration-shell-package``, as the OpenAPI encodes it; the users do not give it. The identifiers of the shells are the multipart field ``aasIds``, an array of the OpenAPI, which the client sends as one part per identifier, as text in UTF-8 (RFC 7578, section 4.3), before the file. The asynchronous upload (``PostAsyncAASXPackage``) differs from the other asynchronous operations in two ways: * The server gives the handle as an :py:class:`aas_core3_2.types.OperationHandle` in the body of the 202, which the client returns. * Since the handle comes as it is, and not as a location, the client encodes it in base64url for the paths of the status and the result, as the OpenAPI requires ("UTF8-BASE64-URL-encoded"). The handles of the invocations of operations, in contrast, come from the location in the form the server expects, and are not encoded again (see `Invocation of Operations`_). The status redirects to the result once the upload is finished, and the client follows it as for the invocations, since the result stays available. .. _Bulk Operations in Part 2: https://industrialdigitaltwin.io/aas-specifications/IDTA-01002/v3.2/http-rest-api/http-rest-api.html#bulk-operations .. _Query Language in Part 2: https://industrialdigitaltwin.io/aas-specifications/IDTA-01002/v3.2/query-language.html Serialization ------------- ``GenerateSerializationByIds`` gives an environment with the requested shells and submodels, and, if asked, the concept descriptions which they refer to. The format is an input of the operation in Part 2 (``serializationFormat``), which the HTTP API maps to the header ``Accept``. Hence it is the keyword-only parameter ``serialization_format`` of the type ``serialization.SerializationFormat``, the only keyword-only parameter which is not a query parameter; the conformance check makes an exception for it (see `Cross-checking against the OpenAPI`_). The function always streams the serialization as a ``Download``, whatever the format, since an environment can be large, and an AASX package is binary; the users parse the JSON with :py:func:`aas_core3_2.jsonization.environment_from_jsonable` themselves, as the docstring shows. A single function with a single kind of result keeps the rule of one function per operation. The specification is inconsistent about the formats: * The prose lists only JSON and XML as ``SerializationFormat``, with XML as the default. * The OpenAPI gives the AASX package as a third media type, ``application/aas+zip``. * The table of the HTTP API gives ``application/aasx+xml`` for the AASX package, and the AASX File Server API ``application/asset-administration-shell-package``. We follow the OpenAPI for the wire spellings, as everywhere, so ``SerializationFormat.AASX`` is ``application/aas+zip``. `Eclipse BaSyx Go components`_ follow the table, and refuse ``application/aas+zip``; the live test pins it as an expected failure, since it is an inconsistency of the specification rather than a bug of the server. The client always sends the format, with XML as the default of the prose, so that the result does not depend on a default of the server (`Eclipse BaSyx Go components`_ give an AASX package without a header ``Accept``). Profiles -------- The specification defines service specification profiles (for example, the read-only profile of the Submodel Repository) as subsets of the operations of an API. We do not model profiles as separate classes or modules, since there are about 30 of them and a server announces its profiles only at runtime through the Description API. The module ``profiles`` lists the profile identifiers as constants, together with the set of the functions each profile covers. The users can check which operations a server supports with ``profiles.functions_of(description.get_self_description_profiles(server))``. Each profile is defined by a normative OpenAPI document of Part 2 (``/V3.2_SSP-.yaml``), which we copy to ``dev/test_data/openapi/profiles``. The unit test ``dev/tests/test_profiles.py`` matches the operations of each document with those of the entire API collection by their methods and paths, since the documents re-use some operation IDs for different paths, and checks that the profile covers exactly the functions which implement them, including the variants such as ``query_submodel_ids``. The module covers only the operations; we do not capture which serialization modifiers a profile allows. ``functions_of`` ignores the unknown identifiers, as the OpenAPI asks, including those of the earlier versions (``.../API/3/1/...``): the client implements the operations of the version 3.2, and we do not assume that an earlier profile covers them. aas-core3.2 lacks three of the 34 profiles of the version 3.2 in ``ServiceSpecificationProfileEnum``: ``AssetAdministrationShellRepositoryServiceSpecification/SSP-006`` and ``SubmodelRepositoryServiceSpecification/SSP-007`` (the history profiles), and ``ConceptDescriptionRepositoryServiceSpecification/SSP-001`` (only in the versions 3.0 and 3.1). Hence ``description.get_self_description`` drops them as unknown, while ``description.get_self_description_profiles`` keeps them. aas-core3.2 gives the profiles of a description as the enumeration ``ServiceSpecificationProfileEnum``, as the prose of Part 2 types them. The OpenAPI, in contrast, gives them as strings, lets a server list "proprietary profiles, which are not defined in the specification", and says that "clients should be designed to ignore unknown profiles"; the description may also carry "additional, proprietary attributes". `Eclipse BaSyx Go components`_ do both, for example, with ``https://basyx.org/aas/API/3/2/...`` among their profiles. Hence the client drops the profiles and the properties which aas-core3.2 does not know before it de-serializes the description, as the OpenAPI asks. This is not a workaround for a server: the specification explicitly allows the proprietary profiles, and tells the clients how to handle them. The users who need the proprietary profiles call ``description.get_self_description_profiles`` instead, which implements the same operation, but gives all the profiles as strings, in the order of the server. If the users call an operation the server does not implement, the specification gives two possible responses (see Table 4 in `Mapping of Status Codes`_). The server either responds with 501, and the client raises ``NotImplementedByServer``, or it refuses the action due to its profile with 403, and the client raises ``Forbidden``, the same as for a missing role. A 405 means that the request does not fit the requested resource (for example, ``/invoke`` on a submodel element which is not an operation), so the client raises ``MethodNotAllowed`` instead. .. _Mapping of Status Codes: https://industrialdigitaltwin.io/aas-specifications/IDTA-01002/v3.2/http-rest-api/http-rest-api.html#mapping-of-status-codes Authentication ============== The library does not implement any login mechanism. Every login mechanism lives in the transport: * OIDC and OAuth 2: for example, the ready-made transport with an ``OAuth2Session`` of `authlib`_ or `requests-oauthlib`_, which are both sub-classes of :py:class:`requests.Session`, * basic authentication and API keys: set on the session, or as headers by a wrapping transport, * mutual TLS: the client certificate configured on the session. .. _authlib: https://pypi.org/project/Authlib/ .. _requests-oauthlib: https://pypi.org/project/requests-oauthlib/ Token Revocation ---------------- A token might become invalid at any time from outside the client: it expires, the identity provider revokes it, or the application logs the user out. The client supports this through three rules: 1. **The client never caches credentials.** Every operation, and every page of a paged result, goes through ``Transport.send``. If the application swaps or invalidates the token, the next request uses the new one. 2. **The client does not retry.** A response with status 401 raises ``Unauthorized`` which carries the response, including the ``WWW-Authenticate`` header (for example, ``error="invalid_token"``). 3. **Refreshing is a transport concern.** We document a recipe of a transport which asks a token provider of the application for the token on every request, and retries once after invalidating the token on 401. Since every body can be iterated anew (see `Transport Protocol`_), the replay is always possible, also for the uploads of large files. The transport has only one method, so the recipe wraps only ``send``, and covers both the small requests and the large uploads and downloads. A 401 means that the server did not process the request, so replaying it is also safe for non-idempotent operations. .. code-block:: python class BearerTransport: def __init__(self, inner: http.Transport, provider: TokenProvider) -> None: self.inner = inner self.provider = provider @contextlib.contextmanager def send(self, request: http.Request) -> Iterator[http.StreamedResponse]: with self.inner.send( _with_token(request, self.provider.token()) ) as response: if response.status_code != 401: yield response return # NOTE: The first connection is released before the retry. self.provider.invalidate() with self.inner.send( _with_token(request, self.provider.token()) ) as response: yield response A retry only happens if the transport actually reports the 401. A server often rejects an invalid token before it reads the body of the request, and closes the connection, while the client is still sending a large upload. We checked that the ready-made transport based on `requests`_ still reports the 401 in this case, even for an upload of 64 MiB rejected before the server read any of it. This was a test against a local server, though. Over a real network, the reset of the connection might arrive before the client reads the response, and other transports might behave differently. Then the transport raises a connection error instead of returning the 401, and the wrapping transport has no chance to retry. The client can not prevent this. The token provider makes it rarer by refreshing the tokens shortly before they expire, so that the uploads seldom start with an expired token; a token revoked from outside can still hit an upload this way. Note that a server which validates JWT access tokens only locally (signature, expiry and audience) does not notice a revocation at the identity provider until the token expires. For example, `Eclipse BaSyx Go components`_ work this way: they support neither token introspection nor opaque tokens. This is a property of the server, and the client can not change it. .. _Eclipse BaSyx Go components: https://github.com/eclipse-basyx/basyx-go-components Synchronous First, asyncio Later ================================ The client is synchronous for now. We will add an ``asyncio`` interface later, as a separate module (say, ``aas_client3_2.aio``). What ``asyncio`` brings: * many concurrent requests in a single thread, for example, when crawling thousands of submodels, and * calling the client from within an ``asyncio`` application (such as a FastAPI or aiohttp server) without blocking the event loop. What ``asyncio`` costs: * **Function coloring.** An ``async def`` function can only be awaited from another ``async def`` function. Supporting both worlds means two public interfaces: 235 synchronous and 235 asynchronous functions, plus a second protocol ``AsyncTransport`` with its own implementations (`httpx`_'s ``AsyncClient``, `aiohttp`_), its own fakes and its own tests. * **Double review effort** of the manual mapping, which is where the actual risk of the first version lies. .. _aiohttp: https://pypi.org/project/aiohttp/ Why the synchronous client suffices at first: * Scripts, notebooks, data pipelines, integration tests and server conformance tests (the main use case of the testing client) are synchronous. * Concurrency is available through threads. The transport releases the GIL while waiting on the network, so a :py:class:`concurrent.futures.ThreadPoolExecutor` gives real concurrency for dozens or hundreds of requests. * ``asyncio`` applications can call the synchronous client with :py:func:`asyncio.to_thread` without blocking the event loop. How we prepare for it: the pure build and parse functions (see `Build, Send, Parse`_) contain all the logic. The ``asyncio`` interface only needs to await the transport in between, which is mechanical. The conformance check will then also verify that both interfaces have identical signatures. Note that the specification uses "async" for something different: the AASX Async File Server API, the Async Bulk APIs of the registries and the asynchronous invocation of operations are *server-side* asynchronous operations, where the client polls a handle for the result. These are ordinary operations of the synchronous client, and keep the names of the specification, such as ``submodel_repository.invoke_operation_async`` (see `Naming Conventions`_). They return a handle immediately, and are unrelated to ``asyncio``. The future ``asyncio`` interface will have the same names in its own package, so ``aas_client3_2.aio.submodel_repository.invoke_operation_async`` will be awaitable *and* asynchronous on the server. The docstrings will point this out. Cross-checking against the OpenAPI ================================== Since we map the operations manually, we need a mechanical check that the mapping coincides with the OpenAPI. There is no off-the-shelf tool which produces OpenAPI from client code; tools such as FastAPI or apispec produce OpenAPI from server code. However, our functions follow strict conventions, so we check them in two parts against the vendored OpenAPI in ``dev/test_data/openapi``. The unit test ``dev/tests/test_openapi_conformance.py`` holds the static part, and runs both; the dynamic part lives in ``dev/dev_scripts/openapi_conformance.py``, which also loads the operations of the OpenAPI for both parts. The static part inspects the public functions of the client and of the testing client without calling them. It parses the operation each function implements from its docstring (see `Operations in the Docstrings`_), and checks that: * the operation exists, with the same method and path, * the name of the function is derived from the operation ID (see `Naming Conventions`_), * the positional parameters after the server are the path parameters, in order, * the keyword-only parameters are the query parameters and the fields of a multipart body, and * the testing client mirrors the client: the same modules, with the same functions and parameters. The API modules are discovered, not listed: they are the modules whose public functions declare an operation. A few functions implement an operation in a variant, besides the function named after it, such as ``query_submodel_ids`` of ``QuerySubmodels`` (see `Query`_) and ``get_self_description_profiles`` of ``GetSelfDescription`` (see `Profiles`_). The check recognizes them by the rule of their names: a variant extends the name of the function in the singular by a suffix, and lives next to it. The dynamic part *executes* the code: 1. Enumerate the public functions of the API modules, their signatures and type annotations with :py:mod:`inspect` and :py:func:`typing.get_type_hints`, and parse the operations they implement from their docstrings. 2. Call each function with sentinel strings, example payloads of the annotated types and all optional arguments set, on a recording transport. The recording transport stops the execution right after recording the request, so that no response is needed. 3. From each recorded request, derive the path template by replacing the encoded sentinels with ``{parameterName}``, together with whether each path parameter was encoded in base64url or given as it is. 4. Check against the operation in the OpenAPI: * the method and the path template, * the encoding of the path parameters, as their descriptions require ("UTF8-BASE64-URL-encoded"), * the names of the query parameters, and their values: the encoding, the enumerations (such as ``level``), the date-times, the integers and the booleans, * whether there is a request body, and its content type, * the media types in ``Accept`` against the media types of the responses, and * the return type against the schemas of the success responses. 5. List the operations of the OpenAPI which no function implements, the operations implemented in more than one module, and the API groups (the tags of the OpenAPI) whose operations are spread over more than one module. As much as possible is derived from the OpenAPI, so that a new version of the OpenAPI is checked without changing the check: * The return types are derived from the schemas of the success responses: a schema with the name of a class of :py:mod:`aas_core3_2.types` is that class, an array a ``List``, a paged result any page class whose items fit, ``oneOf`` any of the alternatives, a binary or a non-JSON response a ``Download``, and a schema which aas-core3.2 does not model, such as the value-only serialization, the JSON (``JsonObject`` or ``JsonValue``). * The prefixes of the APIs relative to an endpoint (``/aas`` and ``/submodel``, see `Navigating from a Registry`_) are inferred as what the path of the OpenAPI has before the recorded path; a prefix must be a single literal segment, and all the functions of a module must share it, so that a wrong path can not be explained away. Only the deliberate deviations of the client from the OpenAPI are listed explicitly, since they are design decisions: * the return types of ``GetSelfDescription`` (the profiles as strings, see `Profiles`_), ``BulkGetAsyncStatus`` (the status which tells when the operation is finished, see `Bulk Operations`_) and ``QueryAssetAdministrationShellDescriptors`` (the identifiers, which the prose allows but the OpenAPI does not list), and * the handles of the asynchronous invocations and of the bulk operations, which the OpenAPI describes as base64url-encoded, but the client takes from ``Location`` as the path segment, and sends back as given (see `Invocation of Operations`_ and `Bulk Operations`_). Like the docstrings, the deviations are checks, not a source for generation. The script writes the produced OpenAPI to a file, given with ``--output``, for manual inspection. The unit test runs both parts on every commit, and also checks the dynamic check: it gives functions which break the conventions on purpose, each in one way, and expects them to be reported. Together, the two parts catch missing operations, wrong names, wrong modules, wrong paths, wrong methods, wrong encodings, wrong parameter names and values, wrong bodies and media types, and wrong return types. They do not validate the request bodies against the schemas of the OpenAPI, since aas-core3.2 generates the serialization from the same meta-model; neither can they catch semantic errors, such as passing the wrong argument to a query parameter of the right name. The unit tests, the live tests and the testing client cover these. Testing Client with Contracts ============================= The testing client is a separate distribution, ``aas-testing-client3.2``, with the module ``aas_testing_client3_2``. It mirrors the API modules of the client with the same function names and signatures, so switching between them is a matter of the import. Every function is decorated with `icontract`_ pre- and postconditions: .. _icontract: https://pypi.org/project/icontract/ * **Preconditions** check the input, such as that the payload passes :py:mod:`aas_core3_2.verification`, and that identifiers are not empty. This makes sure that a failure is due to the server, not the test. * **Postconditions** check the server's response against the specification, such as: * the exact status code (for example, 201 for a successful ``POST``), * the content type and the presence of the required headers (such as ``Location``), * the response payload passes :py:mod:`aas_core3_2.verification`, * the identity of the returned object (such as that ``get_submodel_by_id`` returns the submodel with the requested ``id``), * invariants of pagination (such as that a page does not exceed the requested ``limit``), and * the round-trip (such as that the object returned by ``post_submodel`` equals the one sent), and * the consistency of the downloads (such as that the number of the received bytes equals ``Content-Length``, if the server sent it). The testing client implements the postconditions on the raw response by reusing the pure build and parse functions of the client (see `Build, Send, Parse`_). These functions are therefore a semi-public interface between the two distributions. They are private by name, but the testing client may use them, since it depends on exactly the same version of the client, and lives in the same repository, so that a change of these functions breaks the testing client in the same pull request, never for the users. The postconditions of `icontract`_ see only the arguments and the result of a function, not the raw response in between. Hence every operation of the testing client is split into two functions. A private function sends the request and gives an ``Exchange`` with the request, the raw response and the parsed value, and carries the postconditions. The public function carries the preconditions, and gives only the value, so that its signature equals the one of the client: .. code-block:: python @icontract.ensure(lambda result: _checks.has_json_content_type(result.response)) @icontract.ensure(lambda result: _checks.verifies(result.value)) @icontract.ensure(lambda aas_identifier, result: result.value.id == aas_identifier) def _get_asset_administration_shell_by_id( server: http.Server, aas_identifier: str ) -> _checks.Exchange[aas_types.AssetAdministrationShell]: return _checks.exchange( server, aas_repository._build_get_asset_administration_shell_by_id( server.base_url, aas_identifier ), aas_repository._parse_get_asset_administration_shell_by_id, ) @icontract.require(lambda aas_identifier: len(aas_identifier) > 0) def get_asset_administration_shell_by_id( server: http.Server, aas_identifier: str ) -> aas_types.AssetAdministrationShell: return _get_asset_administration_shell_by_id(server, aas_identifier).value The exact status codes are already checked by the parse functions of the client, which accept only the status codes of the specification, and raise an ``HttpError`` otherwise. Error Responses --------------- A well-formed request answered with a server error is always a bug of the server, whatever its configuration. Hence every function of the testing client turns a server error into :py:class:`icontract.ViolationError` ("the server failed internally"), instead of the :py:class:`~aas_client3_2.errors.HttpError` which a test could expect, for example when it checks that a request is rejected. The only exception is ``501 Not Implemented``, which Part 2 intends "for cases where API Operations beyond the supported service profiles are requested". The same decorator checks the other errors against Part 2: * **Every rejection carries a Result.** Part 2 states that "in case of a failed operation execution, a result object shall be returned", and its table of the status codes gives a result object to every failure except 501. A rejection (4xx) whose body is not a valid ``Result`` in JSON is a violation; the messages of the result are optional, so we do not require any. * **A 501 only beyond the declared profiles.** When the server answers 501, the testing client reads the description of the server, and checks that no profile which it declares covers the operation (see `Profiles`_). The other direction does not hold: Part 2 also allows 403 "due to certain restrictions, e.g. profiles or roles" for an operation beyond the profiles, and it does not forbid a server to implement more than it declares. A server which does not describe itself, or declares only profiles the client does not know, can not be checked. The decorator sits directly on each function, below ``contextlib.contextmanager``, so that it also covers the downloads, which raise when they are entered; a unit test checks that no function of the testing client lacks it. Every response with ``201`` must carry a ``Location`` header, checked once for all the operations where the testing client sends the request. The OpenAPI gives the header to every ``201`` except those of ``PutAssetAdministrationShell`` and ``PostAllAssetLinksById``. A new shell at the endpoint of the AAS API is still a resource with a URL, which HTTP expects in ``Location`` for a ``201``, so we check it there as well; the asset links have no URL of their own, so we do not. The content type of a response needs no check of its own: the parse functions of the client already reject a response whose content type is not the one which the request accepts, and the downloads are checked against the media type which the request asks for. Part 2 does not map a malformed identifier to a status code explicitly, but its table maps "a malformed request" to 400. The client always encodes the identifiers correctly, so the testing client never sends a malformed one; the live tests in ``dev/live_tests/test_error_responses.py`` send such requests themselves, and check that a malformed identifier gives 400 and a missing resource 404, both with a ``Result``. Routes to a Submodel -------------------- A submodel can be read through several routes: the Submodel Repository, the superpath of a shell in the AAS Repository, the AAS API at the endpoint of the shell, and the Submodel API at the endpoints of the submodel. Each route gives five views of the submodel and of every element: the normal one, the metadata, the values, the reference and the paths. A bug which shows only in one route under some condition, such as an access rule which breaks only the superpath, passes every check of a single call. The module :py:mod:`aas_testing_client3_2.routes` reads every view of the submodel and of all its elements through every route, and reports where the routes disagree, in the status code or in the content. On top, the values and the paths, and the metadata of the submodel, must follow from the normal view. Where Part 2 is silent, the comparison is lenient: a reference read through a shell may start with the key of the shell. The live tests in ``dev/live_tests/test_routes.py`` compare the routes on a submodel with all the kinds of elements which have a value, and the sequential live tests check the views after every change. The same comparison is meant to run under the configurations of the servers which must not change any answer, such as access rules that allow everything. Arguments --------- Every function of the testing client which takes model instances also checks that the client does not change them, since the caller might use them further. The arguments are captured with the snapshots of `icontract`_ before the call, and compared exactly, including the order, after it. These checks send no request, so they hold in both of the following subpackages as well. Sequential Testing Client ------------------------- The postconditions above see only the response. A server could answer ``204`` to a deletion and keep the submodel, or replace a sibling while adding an element, and the testing client would not notice. The subpackage :py:mod:`aas_testing_client3_2.sequential` mirrors the testing client, and checks the *effect* of every operation which changes the server. It reads the affected resource before the call with an icontract snapshot, and after the call in the postconditions: * the server stores what it accepted, such as the submodel which was put, * nothing else changes, such as the siblings of an added or deleted element (the elements named by their ID-shorts compare regardless of their order, as Part 1 does not order them; a new item of a submodel element list may go to any position, as long as the other items keep their order), * a patch of the metadata leaves the values and the children as they were, as Part 2 notes that "values remain unchanged with content=metadata", and a patch in the ValueOnly format changes nothing but the values, * the values of a patch in the ValueOnly format come back in the normal view: the stored submodel, serialized in the ValueOnly format, carries the values which were sent (the elements which the patch does not name may keep their values, since Part 2 does not say whether a patch removes them), * a ``PUT`` answers ``201`` exactly when the resource did not exist before, where the OpenAPI gives both ``201`` and ``204``, * a deleted resource is gone, and a submodel deleted through the AAS Repository is no longer referred to by the shell, as the summary of the OpenAPI states, and * a request which the server rejects has no effect, since Part 2 states that "the server is always consistent after each operation". Where Part 2 is silent, the checks are lenient: we do not check how a plain ``PATCH`` merges with the stored resource, nor whether the server updates ``defaultThumbnail`` when a thumbnail is uploaded. Three details make the snapshots work: * The state after the call is read once, lazily, by an object captured in a snapshot before the call. Several postconditions of an operation share it, and icontract evaluates a failed condition a second time to explain the failure, which would otherwise read the server again. * The postconditions of icontract do not run when the function raises, so a separate decorator checks that a rejected request had no effect. * The functions give only the value, not the status code, so the operations which must tell ``201`` from ``204`` send their requests through a transport which records the status codes. The asynchronous requests (bulk operations, asynchronous invocations and asynchronous uploads of packages) are followed across the calls. The sequential testing client remembers what the server told about every handle, per transport, and checks that the progress moves only forward (initiated, running, finished), and that a finished request keeps its outcome. Part 2 lets a server remove the result of a bulk request "after a certain amount of time", and "after a client has retrieved it at least once", so a finished result may be gone (404) afterwards, but it may not change, nor come back. A 404 before the request finished tells nothing, since the result might not be there yet. The asynchronous writes, the six bulk operations of the registries and the asynchronous upload of a package, change the server only after the call which submitted them, so a snapshot after that call would see an arbitrary intermediate state. Instead, the submitting call reads the affected resources before it sends the request, and leaves the expected effect under the handle. Once the status or the result first tells the outcome, the effect is checked once: * a successful bulk operation stored every descriptor as sent, or deleted it, * a successful upload made the server list a new package with the uploaded content, which we have to look for, since the result does not tell the identifier of the new package, and * a failed request, or one rejected outright, left all the affected resources as they were, since Part 2 states for the bulk operations that "a client must not expect that any part of the request has been persisted". The descriptors which a bulk request mentions more than once are not compared after a success, since Part 2 does not say which item wins. Part 2 does not say what a canceled or a timed out request leaves behind, so these outcomes are not checked. The module :py:mod:`aas_testing_client3_2.sequential.interrupted` drops the connection in the middle of a request with a large body: an identifiable, a submodel element, an attachment, a thumbnail or a package. It builds the same request as the client, announces the whole body in ``Content-Length``, sends only a part of it over a connection of its own, and closes the connection. Afterwards, the server must keep either the old resource or, if the whole body arrived and only the response got lost, the complete new one; a mix or a truncated attachment is never conformant, since Part 2 states that the server is always consistent after each operation. The connection bypasses the transport, so the headers which the transport would add, such as ``Authorization``, are passed explicitly. The snapshots hold only if nobody else changes the resource during the call. Hence the sequential testing client is a subpackage of its own: use it against a server which only the tests use, and from a single thread. The live tests in ``dev/live_tests/test_sequential.py`` change the servers step by step through it, and check on top that ``PUT`` and ``DELETE`` are idempotent, and that all the views of a submodel (normal, ``$metadata``, ``$value``, ``$path`` and ``$reference``) agree after every step. Concurrent Testing Client ------------------------- Part 2 does not say what a read gives while a write is in progress, except that bulk operations should be atomic. A value which is read and written concurrently is a *register*, and the theory knows three guarantees: * a *safe* register gives the last written value to a read which overlaps no write, but a read during a write may give anything, even a value which nobody ever wrote, * a *regular* register gives the last write completed before the read started, or a write which overlaps the read, and * an *atomic* register is regular, and the reads never go back in time: if a read finished before another one started, the second one does not give an older value. A safe register is not enough: no user of an AAS server accepts a submodel which nobody wrote. The users assume at least a regular register, and often an atomic one, for example across the replicas of a server. The subpackage :py:mod:`aas_testing_client3_2.concurrent` mirrors the testing client with the contracts of each single call, which hold also when the calls overlap. On top of them, it records the writes and the reads in a :py:class:`~aas_testing_client3_2.concurrent.history.History`. The history is carried by the transport of the server, so the signatures stay the same as in the client. A write of a whole resource is registered before its request is sent, and finished after the response arrived; a write which the server rejects with a client error must have no effect, and one which fails otherwise stays pending, since we do not know whether it was applied. Every read of a tracked resource by its identifier is checked against the writes when it finishes: * **not invented**: the value was written by some write which started before the read finished, * **regular**: no other write started and finished between that write and the start of the read, and * **atomic**: no read which finished before this one started can only be explained by a later write. The times are taken conservatively, so a read is only blamed if no order of the requests explains its value. The history raises on the guarantee it expects (regular by default), and records the violations of the stronger ones, so that a test can tell the strongest guarantee which a server kept. The history tracks only the resources which are written as a whole: submodels, shells, concept descriptions and descriptors. A write which changes a resource in part, such as an added element, a bulk operation or an upload, stops the tracking of that resource, since its result depends on the order in which the server applied the concurrent writes. Such writes are checked on the final state once the server is idle instead. The live tests in ``dev/live_tests/test_concurrent.py`` check: * torn reads, with test data which carries its own invariant (all the properties of a version hold the same value), and the regular and atomic guarantees, with a single writer and with several, * lost updates: every element which the server acknowledged with ``201`` while several clients added elements to the same submodel is stored, and * duplicate creations: of several concurrent creations of the same submodel, exactly one succeeds, the others get ``409``, and the stored submodel is the one of the winner. The modules of the concurrent testing client are generated from the testing client by ``dev/dev_scripts/generate_concurrent_testing_client.py``, which lists the tracked operations; a unit test checks that they are up to date. Same Repository, Separate Distribution -------------------------------------- The testing client lives in the same repository, in the directory ``aas-testing-client3.2/`` with its own ``pyproject.toml``, and is released in lockstep with the client: .. code-block:: text aas-testing-client3.2/ pyproject.toml # project name: aas-testing-client3.2 aas_testing_client3_2/ __init__.py submodel_repository.py # mirrors aas_client3_2.submodel_repository ... sequential/ # the same modules, with snapshots submodel_repository.py ... concurrent/ # the same modules, with a history history.py submodel_repository.py ... It depends on ``aas-client3.2`` of exactly the same version, and on ``icontract``. * **Separate distribution**, since most users do not need it and should not install ``icontract`` nor the testing code. A separate ``pyproject.toml`` already achieves this. * **Same repository**, since the testing client mirrors all 235 operations and depends on the internals of the client. A change in the client must change the testing client in the same pull request; with two repositories, they would drift apart. Moreover, the conformance check covers both, and the live tests run the testing client against a real server (see `Live Tests`_), so every pull request of the client tests the testing client as well. Documentation ============= Besides the design and the reference of the modules, the documentation provides two entry points for the users who are new to the client, such as students: * **Getting started.** A short page walks through the most common tasks: connecting to a server, listing and getting shells and submodels, reading the value of a submodel element, uploading and downloading a file, and logging in. It also shows how to start a local server with the same Docker Compose setup as the live tests (see `Live Tests`_), so that the examples can be tried right away. * **Index of the operations.** A page lists all the operations of the specification, grouped by API, each with its operation ID, method, path and the function which implements it. The users who only have a path from Swagger UI, or an operation ID from the specification, find the function there. The page is assembled at documentation build time from the ``:implements:`` fields (see `Operations in the Docstrings`_) by a small Sphinx extension in ``docs/source/``, so it can not drift from the code. Testing ======= Unit Tests ---------- The unit tests live in ``dev/tests/`` and use a fake transport which records the requests and returns prepared responses. They do not need any HTTP library nor network. * For every operation, we check the exact request (method, URL with the encoded identifiers and query, headers and body) and the parsing of the response against golden files in ``dev/test_data/``. The golden files are re-recorded with ``dev/dev_scripts/rerecord_tests.py``. * We check the mapping of each status code to the errors, including the parsing of ``Result`` messages. * We check the pagination and the handling of invalid payloads. * We check the ready-made transport based on `requests`_ against a local server from :py:mod:`http.server`, including the streaming: the uploads are sent with ``Content-Length`` and without chunked transfer encoding, a replayed upload sends the same bytes, the downloads arrive in chunks, and the connection is released when a download is abandoned in the middle. * We check that the uploads and downloads of a file larger than the available memory budget of the test (say, 1 GiB, generated on the fly and never materialized) pass through without the memory of the process growing with the size of the file. * We run the conformance check against the OpenAPI (see `Cross-checking against the OpenAPI`_). Live Tests ---------- The live tests run the client against a real server. They live in ``dev/live_tests/``: .. code-block:: text dev/live_tests/ docker/ docker-compose.yml # PostgreSQL, configuration service, BaSyx Go components operation_delegate.py # executes the operations which the Submodel Repository delegates docker-compose.oidc.yml # adds Keycloak, OIDC trust list and ABAC policy trustlist.json policy.json test_submodel_repository.py test_concept_description_repository.py test_aas_registry.py test_submodel_registry.py test_description_and_discovery.py test_aasx_file_server.py test_serialization.py test_aas_and_submodel_api.py ... test_oidc.py dev/dev_scripts/run_live_tests.py # compose up → wait until healthy → run tests → compose down * We use `Eclipse BaSyx Go components`_ which implement the API v3.2, started with Docker Compose. The images are pinned by their digests so that the runs are reproducible. We test against the three repositories, the two registries, the discovery, the AASX file server and the AAS environment, which serves the Serialization API (``eclipsebasyx/aasrepository-go``, ``eclipsebasyx/submodelrepository-go``, ``eclipsebasyx/conceptdescriptionrepository-go``, ``eclipsebasyx/aasregistry-go``, ``eclipsebasyx/submodelregistry-go``, ``eclipsebasyx/aasdiscovery-go``, ``eclipsebasyx/aasxfileserver-go`` and ``eclipsebasyx/aasenvironment-go``, release v1.1.5). All of them share a single database, so the AAS environment serializes what the tests store in the repositories. * ``dev/dev_scripts/run_live_tests.py`` starts the servers, waits until they respond, runs the live tests and stops the servers. With ``--keep``, the servers keep running after the tests, for example, for debugging. The live tests read the base URLs from the environment variables ``AAS_CLIENT3_2_LIVE_AAS_REPOSITORY_URL``, ``AAS_CLIENT3_2_LIVE_SUBMODEL_REPOSITORY_URL``, ``AAS_CLIENT3_2_LIVE_CONCEPT_DESCRIPTION_REPOSITORY_URL``, ``AAS_CLIENT3_2_LIVE_AAS_REGISTRY_URL``, ``AAS_CLIENT3_2_LIVE_SUBMODEL_REGISTRY_URL``, ``AAS_CLIENT3_2_LIVE_DISCOVERY_URL``, ``AAS_CLIENT3_2_LIVE_AASX_FILE_SERVER_URL`` and ``AAS_CLIENT3_2_LIVE_AAS_ENVIRONMENT_URL``. * `Eclipse BaSyx Go components`_ do not execute an operation themselves, but delegate every invocation in a POST to the URL in the qualifier ``invocationDelegation`` of the operation. To test the invocations, a small service in ``operation_delegate.py``, based only on the standard library of Python, runs next to the Submodel Repository, with a few fixed behaviors (echo, slow, failed, broken) at different paths. The repository delegates only to an allowlist of hosts, and checks both the host in the URL and every IP address it resolves to, so a service name would require a fixed IP address. Instead, the service shares the network namespace of the repository, and listens only on its loopback; ``docker-compose.yml`` explains this in detail. * The repositories keep the versions for ``$history`` only with ``HISTORY_MODE=api`` (the default ``off`` keeps none), and sign for ``$signed`` only with an RSA private key and a certificate chain. We do not commit a private key to the repository, not even a throwaway one, since secret scanners rightly flag it. Instead, a one-shot service ``jws_keys`` in ``docker-compose.yml`` generates a fresh key and a self-signed certificate with ``openssl`` on every start into a Docker volume, which the repositories mount read-only; ``docker-compose.yml`` explains this in detail. * The tests of ``$history`` compare the clock of the test machine with the times which the server records, so the two clocks must agree within half a second; that holds for the servers in Docker on the same machine, but not necessarily for a remote server. * The Concept Description Repository of `Eclipse BaSyx Go components`_ implements only the profiles SSP-001 (full) and SSP-002 (query), as its description states, and not the signature profile SSP-003, so the live test of ``$signed`` is skipped rather than expected to fail: not implementing a profile is a choice of the server, not a bug. * The known problems of the servers are marked as expected failures, with a note, so that the runs stay green, and a fix of the server shows up as an unexpected success. * The servers may order the elements named by their ID-shorts as they like, since Part 1 orders neither the elements of a submodel element collection nor those of a submodel. The tests and the testing client therefore compare them regardless of their order, while the elements of a submodel element list are compared in order. * The tests use the ready-made transport based on `requests`_, and the testing client, so that the contracts are checked as well. * `Eclipse BaSyx Go components`_ serve the Asset Administration Shell API and the Submodel API through the repositories, at the endpoints which they register (``{externalUrl}/shells/{aasIdentifier}`` and ``{externalUrl}/submodels/{submodelIdentifier}``). The tests construct the endpoints in the same way, and compare the results with those of the repositories. * The tests are agnostic of the server. They read the base URLs from environment variables and are skipped if these are not set. Hence the same tests can also run against other servers, such as Eclipse BaSyx Java or FA³ST. * The default configuration runs without access control, and covers all the operations, the pagination and the content variants. It also uploads and downloads large file attachments and AASX packages (hundreds of megabytes), and checks that the content survives the round-trip. * The OIDC configuration adds Keycloak and access control, and covers: obtaining a token through the client credentials flow, 403 for missing permissions, expired tokens (with a very short token lifetime) followed by a refresh and a retry, and invalidating the token in the application while the client is in use. As explained in `Token Revocation`_, revoking a token at Keycloak can not be tested against this server. The live tests are run on a developer's machine whenever deemed necessary.