129 lines
2.7 KiB
Python
129 lines
2.7 KiB
Python
from __future__ import annotations
|
|
|
|
import base64
|
|
import binascii
|
|
import json
|
|
import re
|
|
from datetime import datetime
|
|
from uuid import UUID
|
|
|
|
from fastapi import Request
|
|
from fastapi.responses import JSONResponse
|
|
|
|
from app.errors import invalid
|
|
from app.responses import json_response, utc_text
|
|
|
|
|
|
def encode_cursor(scope: str, item: dict) -> str:
|
|
raw = json.dumps(
|
|
{
|
|
"scope": scope,
|
|
"created_at": utc_text(item["created_at"]),
|
|
"id": str(item["id"]),
|
|
},
|
|
separators=(",", ":"),
|
|
).encode("utf-8")
|
|
|
|
return (
|
|
base64.urlsafe_b64encode(raw)
|
|
.decode("ascii")
|
|
.rstrip("=")
|
|
)
|
|
|
|
|
|
def decode_cursor(
|
|
cursor: str,
|
|
scope: str,
|
|
) -> tuple[datetime, UUID]:
|
|
if not cursor or len(cursor) > 2048:
|
|
raise invalid("Некорректный cursor")
|
|
|
|
try:
|
|
padded = cursor + "=" * (-len(cursor) % 4)
|
|
|
|
raw = base64.b64decode(
|
|
padded,
|
|
altchars=b"-_",
|
|
validate=True,
|
|
)
|
|
|
|
data = json.loads(raw.decode("utf-8"))
|
|
|
|
if (
|
|
not isinstance(data, dict)
|
|
or set(data) != {"scope", "created_at", "id"}
|
|
or data["scope"] != scope
|
|
):
|
|
raise ValueError
|
|
|
|
timestamp = data["created_at"]
|
|
|
|
if (
|
|
not isinstance(timestamp, str)
|
|
or not timestamp.endswith("Z")
|
|
or not isinstance(data["id"], str)
|
|
):
|
|
raise ValueError
|
|
|
|
created_at = datetime.fromisoformat(
|
|
timestamp[:-1] + "+00:00"
|
|
)
|
|
|
|
item_id = UUID(data["id"])
|
|
|
|
return created_at, item_id
|
|
|
|
except (
|
|
ValueError,
|
|
TypeError,
|
|
UnicodeError,
|
|
binascii.Error,
|
|
OverflowError,
|
|
):
|
|
raise invalid("Некорректный cursor") from None
|
|
|
|
|
|
def pagination(
|
|
request: Request,
|
|
scope: str,
|
|
) -> tuple[int, tuple[datetime, UUID] | None]:
|
|
raw_limit = request.query_params.get("limit", "50")
|
|
|
|
if (
|
|
len(raw_limit) > 10
|
|
or re.fullmatch(r"[0-9]+", raw_limit) is None
|
|
):
|
|
raise invalid("Некорректный limit")
|
|
|
|
limit = int(raw_limit)
|
|
|
|
if not 1 <= limit <= 100:
|
|
raise invalid("Некорректный limit")
|
|
|
|
raw_cursor = request.query_params.get("cursor")
|
|
after = None
|
|
|
|
if raw_cursor is not None:
|
|
after = decode_cursor(raw_cursor, scope)
|
|
|
|
return limit, after
|
|
|
|
|
|
def page_response(
|
|
rows: list[dict],
|
|
limit: int,
|
|
scope: str,
|
|
) -> JSONResponse:
|
|
items = rows[:limit]
|
|
next_cursor = None
|
|
|
|
if len(rows) > limit:
|
|
next_cursor = encode_cursor(scope, items[-1])
|
|
|
|
return json_response(
|
|
{
|
|
"items": items,
|
|
"next_cursor": next_cursor,
|
|
}
|
|
)
|