import base64 import json import re from datetime import UTC, datetime from uuid import UUID class Failure(Exception): def __init__(self, status: int, message: str, headers: dict | None = None): self.status = status self.message = message self.headers = headers or {} def timestamp() -> str: return datetime.now(UTC).isoformat(timespec="microseconds").replace("+00:00", "Z") def identifier(value: str) -> str: try: return str(UUID(value)) except (ValueError, TypeError, AttributeError): raise Failure(400, "Некорректный UUID") from None def boundary(scope: str, cursor: str | None) -> tuple[str, str] | None: if cursor is None: return None try: if not cursor or len(cursor) > 1024 or not re.fullmatch(r"[A-Za-z0-9_-]+", cursor): raise ValueError data = json.loads(base64.urlsafe_b64decode(cursor + "=" * (-len(cursor) % 4))) if ( not isinstance(data, list) or len(data) != 4 or type(data[0]) is not int or data[0] != 1 or data[1] != scope ): raise ValueError date, uid = data[2:] if not isinstance(date, str) or not re.fullmatch( r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]{1,6})?Z", date, ): raise ValueError datetime.fromisoformat(date.replace("Z", "+00:00")) if not isinstance(uid, str) or str(UUID(uid)) != uid: raise ValueError return date, uid except (ValueError, TypeError, KeyError, UnicodeError): raise Failure(400, "Некорректный cursor или область запроса") from None def page(items: list[dict], limit: int, scope: str) -> dict: more = len(items) > limit selected = items[:limit] cursor = None if more: last = selected[-1] payload = json.dumps([1, scope, last["created_at"], last["id"]], separators=(",", ":")) cursor = base64.urlsafe_b64encode(payload.encode()).decode().rstrip("=") return {"items": selected, "next_cursor": cursor}