84 lines
2.5 KiB
Python
84 lines
2.5 KiB
Python
import base64
|
|
import json
|
|
from collections.abc import Sequence
|
|
from datetime import datetime
|
|
from typing import Protocol, TypeVar
|
|
from uuid import UUID
|
|
|
|
from app.errors.exceptions import invalid_request
|
|
from app.storage.types import Position
|
|
|
|
KIND_CHATS = "chats"
|
|
KIND_MESSAGES = "messages"
|
|
|
|
T = TypeVar("T")
|
|
|
|
|
|
class Positioned(Protocol):
|
|
"""Объект с позицией в порядке (created_at, id)."""
|
|
|
|
@property
|
|
def id(self) -> UUID: ...
|
|
|
|
@property
|
|
def created_at(self) -> datetime: ...
|
|
|
|
|
|
def encode_cursor(
|
|
kind: str,
|
|
resource_id: UUID,
|
|
created_at: datetime,
|
|
item_id: UUID,
|
|
) -> str:
|
|
"""Кодирует позицию и ресурс, к которому она привязана, в непрозрачный cursor."""
|
|
payload = {
|
|
"kind": kind,
|
|
"resource_id": str(resource_id),
|
|
"created_at": created_at.isoformat(),
|
|
"item_id": str(item_id),
|
|
}
|
|
raw = json.dumps(payload).encode()
|
|
return base64.urlsafe_b64encode(raw).decode()
|
|
|
|
|
|
def decode_cursor(cursor: str, kind: str, resource_id: UUID) -> Position:
|
|
"""Возвращает позицию из cursor; битый или чужой cursor даёт 400."""
|
|
try:
|
|
payload = json.loads(base64.urlsafe_b64decode(cursor))
|
|
cursor_kind = payload["kind"]
|
|
cursor_resource_id = UUID(payload["resource_id"])
|
|
created_at = datetime.fromisoformat(payload["created_at"])
|
|
item_id = UUID(payload["item_id"])
|
|
except (ValueError, KeyError, TypeError, AttributeError):
|
|
raise invalid_request("Некорректный cursor") from None
|
|
|
|
if (
|
|
cursor_kind != kind
|
|
or cursor_resource_id != resource_id
|
|
or created_at.tzinfo is None
|
|
):
|
|
raise invalid_request("Некорректный cursor")
|
|
|
|
return created_at, item_id
|
|
|
|
|
|
def split_page(rows: list[T], limit: int) -> tuple[list[T], bool]:
|
|
"""Отделяет страницу от лишней строки limit + 1, по которой видно продолжение."""
|
|
has_next = len(rows) > limit
|
|
items = rows[:limit]
|
|
return items, has_next
|
|
|
|
|
|
def build_next_cursor(
|
|
kind: str,
|
|
resource_id: UUID,
|
|
items: Sequence[Positioned],
|
|
has_next: bool,
|
|
) -> str | None:
|
|
"""Возвращает cursor на последний элемент страницы или None, если она последняя."""
|
|
if not has_next:
|
|
return None
|
|
|
|
last_item = items[-1]
|
|
return encode_cursor(kind, resource_id, last_item.created_at, last_item.id)
|