"""Opaque, resource-bound keyset cursors, timestamp formatting and page shaping.""" from __future__ import annotations import base64 import binascii import json import uuid from datetime import datetime, timezone from typing import Any from .errors import ApiProblem def format_timestamp(value: datetime) -> str: """RFC 3339 UTC with microseconds and a trailing Z, as the contract requires.""" return ( value.astimezone(timezone.utc) .isoformat(timespec="microseconds") .replace("+00:00", "Z") ) def parse_timestamp(value: str) -> datetime: """Parse an RFC 3339 timestamp from a cursor; reject anything else.""" candidate = value[:-1] + "+00:00" if value.endswith("Z") else value parsed = datetime.fromisoformat(candidate) if parsed.tzinfo is None: parsed = parsed.replace(tzinfo=timezone.utc) return parsed.astimezone(timezone.utc) def encode_cursor(resource: str, created_at: datetime, record_id: str) -> str: payload = json.dumps( { "resource": resource, "created_at": format_timestamp(created_at), "id": record_id, }, separators=(",", ":"), sort_keys=True, ).encode("utf-8") return base64.urlsafe_b64encode(payload).decode("ascii").rstrip("=") def decode_cursor(value: str, resource: str) -> tuple[datetime, uuid.UUID]: """Decode a cursor and bind it to the resource it was issued for.""" try: padding = "=" * (-len(value) % 4) raw = base64.b64decode(value + padding, altchars=b"-_", validate=True) payload: Any = json.loads(raw.decode("utf-8")) if not isinstance(payload, dict) or set(payload) != { "resource", "created_at", "id", }: raise ValueError("unexpected cursor payload") if payload["resource"] != resource: raise ValueError("cursor belongs to another resource") created_at = payload["created_at"] record_id = payload["id"] if not isinstance(created_at, str) or not isinstance(record_id, str): raise ValueError("cursor fields have wrong types") return parse_timestamp(created_at), uuid.UUID(record_id) except ( ValueError, TypeError, UnicodeError, binascii.Error, json.JSONDecodeError, ): raise ApiProblem(400, "invalid_request", "Cursor is invalid") from None def build_page(items: list[dict[str, Any]], resource: str, limit: int) -> dict[str, Any]: """Shape a limit+1 storage slice into the public page and its next cursor.""" page = items[:limit] next_cursor = None if len(items) > limit and page: last = page[-1] next_cursor = encode_cursor( resource, parse_timestamp(last["created_at"]), last["id"] ) return {"items": page, "next_cursor": next_cursor}