Source code for aas_client3_2.pagination

# SPDX-FileCopyrightText: 2026 aas-client3.2-python AUTHORS
#
# SPDX-License-Identifier: MIT

"""
Iterate over the paged results by following the cursors.

For example:

.. 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.
"""

from typing import Any, Callable, Iterator, Optional, Protocol, Set, TypeVar

import aas_core3_2.types as aas_types

from aas_client3_2 import errors

T_co = TypeVar("T_co", covariant=True)


[docs] class Page(Protocol[T_co]): """ Represent a page of a paged result, such as ``GetSubmodelsResult``. All the paged results of :py:mod:`aas_core3_2.types` follow this protocol. """ @property def paging_metadata(self) -> aas_types.PagingMetadata: """Give the cursor to the next page.""" ...
[docs] def over_result_or_empty(self) -> Iterator[T_co]: """Iterate over the items of the page.""" ...
T = TypeVar("T") PageT = TypeVar("PageT", bound=Page[Any])
[docs] class RepeatedCursor(errors.Error): """Signal that the server gave a cursor which it has already given before.""" #: The repeated cursor cursor: str
[docs] def __init__(self, cursor: str) -> None: """Initialize with the given values.""" self.cursor = cursor super().__init__( f"The server gave the cursor {cursor!r} for the second time, " f"so following it would never end" )
[docs] def iterate_pages(fetch: Callable[[Optional[str]], PageT]) -> Iterator[PageT]: """ Iterate over the pages by following the cursors. :param fetch: fetch the page at the given cursor, or the first page if None :yields: the pages, in the order given by the server :raises: :py:class:`RepeatedCursor` if the server repeats a cursor """ seen: Set[str] = set() cursor: Optional[str] = None while True: page = fetch(cursor) yield page cursor = page.paging_metadata.cursor # NOTE (mristin): # The specification forbids empty cursors (Constraint AASa-001). We # interpret one as the end of the result set, since passing it back would # most probably restart the listing. if cursor is None or len(cursor) == 0: return if cursor in seen: raise RepeatedCursor(cursor) seen.add(cursor)
[docs] def iterate(fetch: Callable[[Optional[str]], Page[T]]) -> Iterator[T]: """ Iterate over the items of all the pages by following the cursors. :param fetch: fetch the page at the given cursor, or the first page if None :yields: the items of all the pages, in the order given by the server :raises: :py:class:`RepeatedCursor` if the server repeats a cursor """ for page in iterate_pages(fetch): yield from page.over_result_or_empty()