feat: add replicated messenger and reproducible lab3 stand
This commit is contained in:
@@ -0,0 +1,88 @@
|
||||
"""Keyset-пагинация по `(created_at, id)` и непрозрачный курсор.
|
||||
|
||||
Курсор — base64url без `=` от строки `<scope>|<микросекунды>|<id hex>`:
|
||||
ключ последнего элемента страницы плюс область списка. Область —
|
||||
`chat:<id>` для истории чата и `chats-of:<id>` для списка чатов
|
||||
пользователя, поэтому курсор другого чата или пользователя не
|
||||
принимается (400). Клиент курсор не разбирает, формат можно менять.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
from collections.abc import Sequence
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import Protocol
|
||||
from uuid import UUID
|
||||
|
||||
from src.domain import Page
|
||||
from src.errors import InvalidCursor
|
||||
|
||||
type SortKey = tuple[datetime, UUID]
|
||||
|
||||
_EPOCH = datetime(1970, 1, 1, tzinfo=UTC)
|
||||
_MICROSECOND = timedelta(microseconds=1)
|
||||
_SEPARATOR = "|"
|
||||
|
||||
|
||||
class Keyed(Protocol):
|
||||
@property
|
||||
def id(self) -> UUID: ...
|
||||
|
||||
@property
|
||||
def created_at(self) -> datetime: ...
|
||||
|
||||
|
||||
def sort_key(item: Keyed) -> SortKey:
|
||||
"""Порядок контракта: `created_at`, при равенстве — `id` как UUID."""
|
||||
return item.created_at, item.id
|
||||
|
||||
|
||||
def history_scope(chat_id: UUID) -> str:
|
||||
return f"chat:{chat_id}"
|
||||
|
||||
|
||||
def chat_list_scope(user_id: UUID) -> str:
|
||||
return f"chats-of:{user_id}"
|
||||
|
||||
|
||||
def encode_cursor(scope: str, key: SortKey) -> str:
|
||||
created_at, item_id = key
|
||||
micros = (created_at - _EPOCH) // _MICROSECOND
|
||||
raw = _SEPARATOR.join((scope, str(micros), item_id.hex))
|
||||
return base64.urlsafe_b64encode(raw.encode()).rstrip(b"=").decode("ascii")
|
||||
|
||||
|
||||
def decode_cursor(cursor: str | None, scope: str) -> SortKey | None:
|
||||
"""Ключ, после которого начинается страница; нет курсора — `None`.
|
||||
|
||||
Битый курсор или курсор другой области — `InvalidCursor`.
|
||||
"""
|
||||
if cursor is None:
|
||||
return None
|
||||
try:
|
||||
padded = cursor + "=" * (-len(cursor) % 4)
|
||||
# Нестрогий декодер молча игнорировал посторонние символы курсора.
|
||||
raw = base64.b64decode(
|
||||
padded.encode("ascii"), altchars=b"-_", validate=True
|
||||
).decode()
|
||||
cursor_scope, micros, item_hex = raw.split(_SEPARATOR)
|
||||
created_at = _EPOCH + int(micros) * _MICROSECOND
|
||||
item_id = UUID(hex=item_hex)
|
||||
except (ValueError, UnicodeError, binascii.Error, OverflowError):
|
||||
raise InvalidCursor from None
|
||||
if cursor_scope != scope:
|
||||
raise InvalidCursor
|
||||
return created_at, item_id
|
||||
|
||||
|
||||
def make_page[T: Keyed](rows: Sequence[T], *, limit: int, scope: str) -> Page[T]:
|
||||
"""Страница из выборки длиной до `limit + 1`.
|
||||
|
||||
Лишний элемент значит, что дальше есть ещё записи. Курсор строится по
|
||||
последнему элементу страницы, а не по лишнему: тот придёт первым на
|
||||
следующей странице.
|
||||
"""
|
||||
items = tuple(rows[:limit])
|
||||
if len(rows) <= limit:
|
||||
return Page(items=items, next_cursor=None)
|
||||
return Page(items=items, next_cursor=encode_cursor(scope, sort_key(items[-1])))
|
||||
Reference in New Issue
Block a user