forked from mtusi2026/mtusi2026lab2
init commit: create skeleton from lab1
This commit is contained in:
@@ -0,0 +1,79 @@
|
||||
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): ORM-модели и схемы."""
|
||||
|
||||
@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:
|
||||
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:
|
||||
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]:
|
||||
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:
|
||||
if not has_next:
|
||||
return None
|
||||
|
||||
last_item = items[-1]
|
||||
return encode_cursor(kind, resource_id, last_item.created_at, last_item.id)
|
||||
Reference in New Issue
Block a user