forked from mtusi2026/mtusi2026lab2
54 lines
1.9 KiB
Python
54 lines
1.9 KiB
Python
"""Opaque keyset cursors for ``(created_at, id)`` ascending pagination."""
|
|
from __future__ import annotations
|
|
|
|
import base64
|
|
import binascii
|
|
import datetime as dt
|
|
import json
|
|
import uuid
|
|
from typing import Optional, Tuple
|
|
|
|
from .errors import ApiError
|
|
|
|
CursorKey = Tuple[dt.datetime, str]
|
|
|
|
|
|
def encode_cursor(resource_id: str, created_at: dt.datetime, item_id: str) -> str:
|
|
payload = json.dumps(
|
|
{
|
|
"r": resource_id,
|
|
"t": created_at.astimezone(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ"),
|
|
"i": item_id,
|
|
},
|
|
separators=(",", ":"),
|
|
).encode("utf-8")
|
|
return base64.urlsafe_b64encode(payload).decode("ascii").rstrip("=")
|
|
|
|
|
|
def decode_cursor(cursor: str) -> Tuple[str, CursorKey]:
|
|
try:
|
|
padded = cursor + "=" * (-len(cursor) % 4)
|
|
data = json.loads(base64.urlsafe_b64decode(padded).decode("utf-8"))
|
|
if not isinstance(data, dict):
|
|
raise ValueError("cursor payload must be an object")
|
|
resource = data["r"]
|
|
item_id = data["i"]
|
|
if not isinstance(resource, str) or not isinstance(item_id, str):
|
|
raise ValueError("cursor fields must be strings")
|
|
created = dt.datetime.strptime(data["t"], "%Y-%m-%dT%H:%M:%S.%fZ").replace(
|
|
tzinfo=dt.timezone.utc
|
|
)
|
|
return resource, (created, str(uuid.UUID(item_id)))
|
|
except (binascii.Error, ValueError, KeyError, TypeError, AttributeError, UnicodeDecodeError):
|
|
raise ApiError(400, "invalid_request", "Некорректный cursor")
|
|
|
|
|
|
def bound_cursor(cursor: str, expected_resource: str) -> Optional[CursorKey]:
|
|
"""Validate resource binding and return the key, or None for empty cursor."""
|
|
if cursor is None:
|
|
return None
|
|
resource, key = decode_cursor(cursor)
|
|
if resource != expected_resource:
|
|
raise ApiError(400, "invalid_request", "cursor относится к другому ресурсу")
|
|
return key
|