"""Общие шаги keyset-пагинации для сервисов списков.""" from collections.abc import Sequence from src.core import exceptions from src.schemas import dataclasses from src.utils.cursor import ( CursorError, CursorKey, decode_cursor, encode_cursor, ) type PageItem = dataclasses.ChatFullDTO | dataclasses.MessageFullDTO def decode_page_cursor(cursor: str | None, *, scope: str) -> CursorKey | None: """Ключ из курсора; нет курсора — первая страница.""" if cursor is None: return None try: return decode_cursor(cursor, scope=scope) except CursorError as e: raise exceptions.InvalidCursor from e def split_page[T: PageItem]( rows: Sequence[T], *, limit: int, scope: str, ) -> tuple[tuple[T, ...], str | None]: """Страница и next_cursor из выборки repo длиной до `limit + 1`. Лишний элемент означает, что следующая страница есть; курсор строится из последнего элемента страницы, а не из лишнего. """ items = tuple(rows[:limit]) if len(rows) <= limit: return items, None last = items[-1] next_cursor = encode_cursor( scope=scope, created_at=last.created_at, item_id=last.id, ) return items, next_cursor