"""Opaque keyset cursors. A cursor encodes the sort key `(created_at, id)` of the last item on the page plus the resource it belongs to, e.g. `v1|m|||`, packed in URL-safe base64. The client treats it as an opaque string; the server rejects cursors of another chat/user (400) and any non-canonical encoding. """ from __future__ import annotations import base64 import re from .errors import InvalidRequest from .validation import UUID_RE B64_RE = re.compile(r"[A-Za-z0-9_-]{1,512}") TS_RE = re.compile(r"[0-9]{1,19}") MESSAGES = "m" CHATS = "c" SortKey = tuple[int, str] def encode(scope: str, owner_id: str, key: SortKey) -> str: ts, item_id = key raw = f"v1|{scope}|{owner_id}|{ts}|{item_id}".encode("ascii") return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii") def decode(cursor: str, scope: str, owner_id: str) -> SortKey: """Return the sort key stored in the cursor or raise InvalidRequest.""" bad = InvalidRequest("Неверный cursor") if B64_RE.fullmatch(cursor) is None: raise bad try: raw = base64.urlsafe_b64decode(cursor + "=" * (-len(cursor) % 4)).decode("ascii") except (ValueError, UnicodeDecodeError): raise bad from None parts = raw.split("|") if len(parts) != 5 or parts[0] != "v1": raise bad _, got_scope, got_owner, ts, item_id = parts if TS_RE.fullmatch(ts) is None or UUID_RE.fullmatch(item_id) is None or item_id != item_id.lower(): raise bad key = (int(ts), item_id) if encode(got_scope, got_owner, key) != cursor: raise bad # only the canonical form produced by the server is accepted if got_scope != scope or got_owner != owner_id: raise InvalidRequest("cursor относится к другому ресурсу") return key