forked from mtusi2026/mtusi2026lab4
29 lines
1.1 KiB
Python
29 lines
1.1 KiB
Python
import base64
|
|
import json
|
|
from uuid import UUID
|
|
|
|
from ..domain.errors import Invalid
|
|
from ..domain.models import Keyset
|
|
from .timefmt import from_rfc3339, to_rfc3339
|
|
|
|
MAX_LENGTH = 512
|
|
|
|
|
|
def encode(scope: str, position: Keyset) -> str:
|
|
payload = {'s': scope, 't': to_rfc3339(position.created_at), 'i': str(position.id)}
|
|
raw = json.dumps(payload, separators=(',', ':'), sort_keys=True).encode('utf-8')
|
|
return base64.urlsafe_b64encode(raw).decode('ascii').rstrip('=')
|
|
|
|
|
|
def decode(scope: str, value: str) -> Keyset:
|
|
if not value or len(value) > MAX_LENGTH:
|
|
raise Invalid('cursor недействителен для этого запроса')
|
|
try:
|
|
raw = base64.urlsafe_b64decode(value + '=' * (-len(value) % 4))
|
|
payload = json.loads(raw)
|
|
if not isinstance(payload, dict) or payload.get('s') != scope:
|
|
raise ValueError('scope mismatch')
|
|
return Keyset(created_at=from_rfc3339(payload['t']), id=UUID(payload['i']))
|
|
except Exception:
|
|
raise Invalid('cursor недействителен для этого запроса') from None
|