Files
mtusi2026lab3-fork/app/cursor.py
T
2026-11-02 20:05:33 +03:00

52 lines
1.9 KiB
Python

"""Непрозрачный keyset-курсор пагинации.
Хранит позицию (микросекунды, id) и область действия, поэтому курсор
другого ресурса отвергается.
"""
import base64
import binascii
import json
import re
from typing import Tuple
from .timeutil import MAX_TIMESTAMP_MICROS
Key = Tuple[int, str]
UUID_RE = re.compile(
r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}"
)
MAX_CURSOR_LENGTH = 512
def encode_cursor(scope: str, key: Key) -> str:
"""Закодировать позицию и область в URL-безопасную строку."""
payload = json.dumps({"s": scope, "t": key[0], "i": key[1]}, separators=(",", ":"))
return base64.urlsafe_b64encode(payload.encode("ascii")).decode("ascii").rstrip("=")
def decode_cursor(text: str, scope: str) -> Key:
"""Раскодировать курсор; ValueError, если он испорчен или чужой."""
if len(text) > MAX_CURSOR_LENGTH or not re.fullmatch(r"[A-Za-z0-9_-]+", text):
raise ValueError("bad cursor")
try:
padded = text + "=" * (-len(text) % 4)
data = json.loads(base64.urlsafe_b64decode(padded.encode("ascii")))
except (binascii.Error, ValueError, UnicodeError):
raise ValueError("bad cursor")
if not isinstance(data, dict) or set(data) != {"s", "t", "i"}:
raise ValueError("bad cursor")
stamp, ident = data["t"], data["i"]
if data["s"] != scope:
raise ValueError("cursor belongs to another resource")
if (
not isinstance(stamp, int)
or isinstance(stamp, bool)
or not 0 <= stamp <= MAX_TIMESTAMP_MICROS
):
raise ValueError("bad cursor")
if not isinstance(ident, str) or not UUID_RE.fullmatch(ident):
raise ValueError("bad cursor")
return stamp, ident