"""Resource-scoped signed cursors; SQL fetches only limit+1 rows.""" import base64 import hashlib import hmac import json import re from datetime import datetime from .domain import invalid, uuid_value class Pagination: def __init__(self, key): self._key = key def decode(self, scope, limit, cursor): if not re.fullmatch(r'[0-9]{1,3}', limit) or not 1 <= int(limit) <= 100: invalid('Limit must be between 1 and 100') after = None if cursor is not None: try: if len(cursor) > 2048: raise ValueError() raw = base64.b64decode(cursor, altchars=b'-_', validate=True) payload, signature = raw[:-32], raw[-32:] if not hmac.compare_digest(signature, hmac.digest(self._key, payload, hashlib.sha256)): raise ValueError() saved_scope, timestamp, identifier = json.loads(payload) if saved_scope != scope or not isinstance(timestamp, str): raise ValueError() datetime.fromisoformat(timestamp.replace('Z', '+00:00')) after = (timestamp, uuid_value(identifier)) except (ValueError, TypeError, UnicodeError): invalid('Invalid cursor for this resource') return int(limit), after def page(self, rows, scope, limit): items = rows[:limit] next_cursor = None if len(rows) > limit: last = items[-1] payload = json.dumps([scope, last['created_at'], last['id']], separators=(',', ':')).encode() next_cursor = base64.urlsafe_b64encode(payload + hmac.digest(self._key, payload, hashlib.sha256)).decode() return {'items': items, 'next_cursor': next_cursor}