prepared skeleton for lab5

This commit is contained in:
2026-11-07 16:10:32 +03:00
parent 276dbdad8a
commit 0a70358829
135 changed files with 9647 additions and 34 deletions
+1
View File
@@ -0,0 +1 @@
"""Бизнес-логика: проверки доступа, транзакции и ошибки API."""
+45
View File
@@ -0,0 +1,45 @@
"""Заготовки сценариев lab5; не подключены к upload или worker.
Здесь появятся транзакционные границы и бизнес-условия; SQL и SDK остаются
в storage/. Одна AsyncSession принадлежит одной последовательной задаче.
"""
from uuid import UUID
from sqlalchemy.ext.asyncio import AsyncSession
async def enqueue_attachment_job(session: AsyncSession, attachment_id: UUID) -> UUID:
"""Создать job и outbox в транзакции queued metadata после durable staging.
Возвращать стабильный job_id. Commit принадлежит сценарию приёма upload;
202 допустим только после устойчивого оригинала и успешного commit.
"""
raise NotImplementedError("Lab5: постановка задания ещё не реализована")
async def process_attachment_job(session: AsyncSession, job_id: UUID) -> None:
"""Захватить job с lease и опубликовать original и обязательные варианты.
Ready-дубль не меняет результат. Lease и версия защищают от устаревшей
попытки. S3/metadata фиксируются до ack; отмена не подавляется.
"""
raise NotImplementedError("Lab5: обработка задания ещё не реализована")
async def recover_expired_jobs(session: AsyncSession) -> int:
"""Вернуть зависший processing в очередь после истечения lease.
Учитывать лимит попыток и защиту от конкурентного завершения старым worker.
Точное правило heartbeat/deadline определяется до реализации.
"""
raise NotImplementedError("Lab5: восстановление lease ещё не реализовано")
async def replay_failed_job(session: AsyncSession, job_id: UUID) -> None:
"""Явно повторить только failed job, сохранив аудит и ключ логического эффекта.
Не переисполнять ready. Проверка допустимости, лимиты повторов и способ
операторского вызова будут определены вместе с реестром failed/DLQ.
"""
raise NotImplementedError("Lab5: replay ещё не реализован")
+315
View File
@@ -0,0 +1,315 @@
"""Авторизация, приём оригинала и согласованность PostgreSQL/MinIO."""
from collections.abc import AsyncIterator, Iterator
from contextlib import contextmanager, suppress
from dataclasses import dataclass
import hashlib
from pathlib import Path
from tempfile import TemporaryDirectory
from uuid import UUID, uuid4
from anyio import CancelScope
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.request_capacity import RequestCapacity
from app.domain.chats import ensure_chat_member
from app.domain.images import validate_filename, validate_image
from app.errors.exceptions import (
conflict,
invalid_request,
not_found,
payload_too_large,
rate_limited,
unavailable,
unsupported_media_type,
)
from app.errors.handlers import (
RECOVERABLE_STORAGE_ERRORS,
log_recoverable_error,
operation_timeout,
)
from app.schemas.attachment import Attachment
from app.schemas.user import User
from app.storage import attachments as repository
from app.storage.s3 import MinioStorage
@dataclass(frozen=True)
class CleanupResult:
examined: int
candidates: int
deleted: int
@dataclass(frozen=True)
class OriginalFile:
path: Path
size_bytes: int
sha256: str
def require_storage(storage: MinioStorage | None) -> MinioStorage:
if storage is None:
raise unavailable("Объектное хранилище не настроено")
return storage
def validate_declared_size(value: str | None, maximum: int) -> None:
if value is not None:
if not value.isascii() or not value.isdecimal() or len(value) > 20:
raise invalid_request("Некорректный Content-Length")
if int(value) > maximum:
raise payload_too_large()
@contextmanager
def upload_slot(capacity: RequestCapacity) -> Iterator[None]:
if not capacity.try_acquire():
raise rate_limited()
try:
yield
finally:
capacity.release()
async def receive_attachment(
session: AsyncSession,
storage: MinioStorage | None,
user: User,
chat_id: UUID,
*,
capacity: RequestCapacity,
filename: str,
content_type: str,
declared_length: str | None,
chunks: AsyncIterator[bytes],
) -> Attachment:
storage = require_storage(storage)
validate_declared_size(declared_length, storage.settings.max_upload_bytes)
timeout_error = invalid_request("Истекло время загрузки")
with upload_slot(capacity):
async with operation_timeout(
storage.settings.upload_timeout_seconds, timeout_error
):
result = await upload_attachment(
session,
storage,
user,
chat_id,
filename=filename,
content_type=content_type,
chunks=chunks,
)
return result
async def read_original(
chunks: AsyncIterator[bytes],
path: Path,
maximum: int,
chunk_bytes: int,
) -> OriginalFile:
checksum = hashlib.sha256()
size = 0
with path.open("wb") as target:
async for chunk in chunks:
size += len(chunk)
if size > maximum:
raise payload_too_large()
checksum.update(chunk)
view = memoryview(chunk)
for offset in range(0, len(view), chunk_bytes):
target.write(view[offset : offset + chunk_bytes])
if size == 0:
raise unsupported_media_type("Пустой файл")
return OriginalFile(path, size, checksum.hexdigest())
async def compensate_upload(
session: AsyncSession, storage: MinioStorage, id: UUID
) -> None:
"""Неоднозначный COMMIT сначала проверяется в БД: готовый объект не удаляется."""
await session.rollback()
intent = await repository.lock_upload(session, id)
if intent is not None:
if await repository.get_by_key(session, intent.object_key) is None:
await storage.delete_object(intent.object_key)
await repository.finish_upload(session, id)
await session.commit()
async def recover_upload(
session: AsyncSession, storage: MinioStorage, id: UUID
) -> None:
"""Локальное восстановление после ошибки; журнал остаётся при отказе компенсации."""
try:
await compensate_upload(session, storage, id)
except RECOVERABLE_STORAGE_ERRORS as error:
log_recoverable_error("Upload compensation", error)
# Ошибка повторного rollback не должна скрыть исходную ошибку или отмену.
with suppress(*RECOVERABLE_STORAGE_ERRORS):
await session.rollback()
async def publish_original(
session: AsyncSession,
storage: MinioStorage,
user: User,
chat_id: UUID,
*,
original: OriginalFile,
filename: str,
content_type: str,
) -> Attachment:
id = uuid4()
key = f"originals/{uuid4().hex}"
# Журнал устойчив до PUT, включая аварию процесса и неоднозначный COMMIT.
await repository.reserve_upload(session, id, key)
await session.commit()
try:
if await repository.lock_upload(session, id) is None:
raise unavailable("Загрузка отменена до записи оригинала")
await storage.put_file(
key,
original.path,
size_bytes=original.size_bytes,
content_type=content_type,
sha256=original.sha256,
)
record = await repository.create_attachment(
session,
id=id,
chat_id=chat_id,
owner_id=user.id,
object_key=key,
filename=filename,
content_type=content_type,
size_bytes=original.size_bytes,
sha256=original.sha256,
)
await repository.finish_upload(session, id)
result = Attachment.model_validate(record)
await session.commit()
except BaseException:
# Отмена тоже требует дождаться SDK и компенсировать незавершённый PUT.
with CancelScope(shield=True):
await recover_upload(session, storage, id)
raise
return result
async def upload_attachment(
session: AsyncSession,
storage: MinioStorage,
user: User,
chat_id: UUID,
*,
filename: str,
content_type: str,
chunks: AsyncIterator[bytes],
) -> Attachment:
await ensure_chat_member(session, user, chat_id)
validate_filename(filename)
if content_type not in {"image/png", "image/jpeg"}:
raise unsupported_media_type("Принимаются только image/png и image/jpeg")
# Не держим соединение PostgreSQL во время чтения медленного клиента.
await session.rollback()
settings = storage.settings
with TemporaryDirectory(prefix="messenger-upload-") as directory:
original = await read_original(
chunks,
Path(directory) / "original",
settings.max_upload_bytes,
settings.chunk_bytes,
)
await validate_image(original.path, content_type, settings)
result = await publish_original(
session,
storage,
user,
chat_id,
original=original,
filename=filename,
content_type=content_type,
)
return result
async def get_attachment(
session: AsyncSession, user: User, attachment_id: UUID
) -> Attachment:
record = await repository.get_attachment(session, attachment_id)
if record is None:
raise not_found()
await ensure_chat_member(session, user, record.chat_id)
return Attachment.model_validate(record)
async def download_attachment(
session: AsyncSession,
storage: MinioStorage | None,
user: User,
attachment_id: UUID,
*,
variant: str = "original",
) -> tuple[Attachment, AsyncIterator[bytes]]:
result = await get_attachment(session, user, attachment_id)
if variant != "original":
raise not_found()
storage = require_storage(storage)
record = await repository.get_attachment(session, attachment_id)
if record is None:
raise not_found()
key = record.object_key
await session.rollback()
info = await storage.stat_object(key)
if (
info is None
or info.size_bytes != result.size_bytes
or info.content_type != result.content_type
):
raise unavailable("Оригинал временно недоступен")
stream = await storage.open_object(key)
return result, stream
async def validate_message_attachments(
session: AsyncSession,
user: User,
chat_id: UUID,
attachment_ids: list[UUID],
) -> None:
await ensure_chat_member(session, user, chat_id)
records = await repository.get_for_chat(session, chat_id, attachment_ids)
if len(records) != len(attachment_ids):
raise not_found()
if any(record.status != "ready" for record in records):
raise conflict("Вложение ещё не готово")
async def reconcile_attachments(
session: AsyncSession,
storage: MinioStorage,
*,
batch_size: int = 20,
dry_run: bool = True,
) -> CleanupResult:
if not 1 <= batch_size <= 100:
raise invalid_request("batch_size должен быть от 1 до 100")
intents = await repository.stale_uploads(
session, storage.settings.cleanup_grace_seconds, batch_size
)
candidates = deleted = 0
for intent in intents:
if await repository.get_by_key(session, intent.object_key) is None:
candidates += 1
if not dry_run:
await storage.delete_object(intent.object_key)
deleted += 1
if not dry_run:
await repository.finish_upload(session, intent.id)
if dry_run:
await session.rollback()
else:
await session.commit()
return CleanupResult(len(intents), candidates, deleted)
+84
View File
@@ -0,0 +1,84 @@
import re
from datetime import UTC, datetime, timedelta
from redis.asyncio import Redis
from sqlalchemy.ext.asyncio import AsyncSession
from app.core import security
from app.domain.users import to_user_schema
from app.errors.exceptions import unauthorized_basic, unauthorized_bearer
from app.schemas.session import AuthSession
from app.schemas.user import (
PASSWORD_MAX_LENGTH,
PASSWORD_MIN_LENGTH,
USERNAME_PATTERN,
User,
)
from app.storage import sessions as sessions_storage
from app.storage import users as users_storage
USERNAME_RE = re.compile(USERNAME_PATTERN)
async def create_session(
session: AsyncSession,
redis: Redis,
username: str,
password: str,
ttl_seconds: int,
) -> AuthSession:
"""Проверяет учётные данные и выдаёт новый Bearer-токен."""
if (
USERNAME_RE.fullmatch(username) is None
or not PASSWORD_MIN_LENGTH <= len(password) <= PASSWORD_MAX_LENGTH
or not password.strip()
):
raise unauthorized_basic()
user = await users_storage.get_user_by_username(session, username)
await session.commit()
if user is None:
await security.dummy_verify_password(password)
raise unauthorized_basic()
if not await security.verify_password(password, user.password_hash):
raise unauthorized_basic()
token = security.generate_token()
expires_at = datetime.now(UTC) + timedelta(seconds=ttl_seconds)
await sessions_storage.create_session(
redis,
token_hash=security.hash_token(token),
user_id=user.id,
expires_at=expires_at,
)
auth_session = AuthSession(
token=token, expires_at=expires_at, user=to_user_schema(user)
)
return auth_session
async def authenticate_token(session: AsyncSession, redis: Redis, token: str) -> User:
"""Возвращает владельца действующей сессии или бросает 401."""
user_id = await sessions_storage.get_session_user_id(
redis, security.hash_token(token)
)
if user_id is None:
raise unauthorized_bearer()
user = await users_storage.get_user_by_id(session, user_id)
if user is None:
raise unauthorized_bearer()
current_user = to_user_schema(user)
return current_user
async def revoke_session(redis: Redis, token: str) -> None:
"""Отзывает текущую сессию; повторный отзыв даёт 401."""
is_deleted = await sessions_storage.delete_session(
redis, security.hash_token(token)
)
if not is_deleted:
raise unauthorized_bearer()
+104
View File
@@ -0,0 +1,104 @@
from uuid import UUID
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
from app.domain.pagination import (
KIND_CHATS,
build_next_cursor,
decode_cursor,
split_page,
)
from app.errors.exceptions import invalid_request, not_found
from app.models.chat import Chat as ChatModel
from app.schemas.chat import Chat, ChatPage, CreateChat
from app.schemas.user import User
from app.storage import chats as chats_storage
from app.storage import users as users_storage
from app.storage.types import Position
UNKNOWN_MEMBER_MESSAGE = "member_ids содержит неизвестного пользователя"
def to_chat_schema(chat: ChatModel) -> Chat:
"""Преобразует ORM-модель чата с загруженными участниками в схему."""
chat_schema = Chat(
id=chat.id,
title=chat.title,
member_ids=[member.user_id for member in chat.members],
created_at=chat.created_at,
)
return chat_schema
def validate_new_chat(creator: User, new_chat: CreateChat) -> None:
"""Проверяет состав участников без обращения к базе."""
member_ids = new_chat.member_ids
if creator.id not in member_ids:
raise invalid_request("Создатель чата должен входить в member_ids")
if len(set(member_ids)) != len(member_ids):
raise invalid_request("member_ids содержит дубликаты")
async def create_chat(
session: AsyncSession, creator: User, new_chat: CreateChat
) -> Chat:
"""Создаёт чат с участниками атомарно; неверный состав даёт 400."""
validate_new_chat(creator, new_chat)
existing_ids = await users_storage.get_existing_user_ids(
session, new_chat.member_ids
)
if existing_ids != set(new_chat.member_ids):
raise invalid_request(UNKNOWN_MEMBER_MESSAGE)
try:
chat = await chats_storage.create_chat(
session, title=new_chat.title, member_ids=new_chat.member_ids
)
await session.commit()
except IntegrityError:
await session.rollback()
raise invalid_request(UNKNOWN_MEMBER_MESSAGE) from None
created_chat = to_chat_schema(chat)
return created_chat
async def get_chat(session: AsyncSession, user: User, chat_id: UUID) -> Chat:
"""Возвращает чат участнику; чужой и несуществующий чат дают 404."""
chat = await chats_storage.get_chat_for_member(session, chat_id, user.id)
if chat is None:
raise not_found()
found_chat = to_chat_schema(chat)
return found_chat
async def ensure_chat_member(session: AsyncSession, user: User, chat_id: UUID) -> None:
"""Бросает 404, если пользователь не состоит в чате или чата нет."""
if not await chats_storage.is_chat_member(session, chat_id, user.id):
raise not_found()
async def list_chats(
session: AsyncSession,
user: User,
cursor: str | None,
limit: int,
) -> ChatPage:
"""Возвращает страницу чатов пользователя по (created_at, id)."""
after: Position | None = None
if cursor is not None:
after = decode_cursor(cursor, KIND_CHATS, user.id)
rows = await chats_storage.list_chats_for_user(session, user.id, after, limit + 1)
page_rows, has_next = split_page(rows, limit)
items = [to_chat_schema(chat) for chat in page_rows]
page = ChatPage(
items=items,
next_cursor=build_next_cursor(KIND_CHATS, user.id, items, has_next),
)
return page
+33
View File
@@ -0,0 +1,33 @@
"""Условия готовности реплики и ограниченная проверка зависимостей."""
import asyncio
from redis.asyncio import Redis
from sqlalchemy.ext.asyncio import AsyncEngine
from app.core.lifecycle import Lifecycle
from app.errors.exceptions import unavailable
from app.errors.handlers import operation_timeout
from app.schemas.base import Health
from app.storage.health import check_database, check_redis
from app.storage.s3 import MinioStorage
def liveness() -> Health:
return Health(status='ok')
async def readiness(
engine: AsyncEngine, redis: Redis, storage: MinioStorage | None,
lifecycle: Lifecycle, timeout_seconds: float,
) -> Health:
if lifecycle.draining:
raise unavailable()
checks = [check_database(engine), check_redis(redis)]
if storage is not None:
checks.append(storage.check_available())
async with operation_timeout(timeout_seconds, unavailable()):
dependencies = await asyncio.gather(*checks, return_exceptions=True)
if not all(result is True for result in dependencies):
raise unavailable()
return Health(status='ok')
+72
View File
@@ -0,0 +1,72 @@
"""Атомарная отправка сообщения с защитой от повторов."""
import hashlib
import json
import re
from uuid import UUID
from sqlalchemy.ext.asyncio import AsyncSession
from app.domain.chats import ensure_chat_member
from app.domain.attachments import validate_message_attachments
from app.errors.exceptions import conflict, invalid_request, unavailable
from app.schemas.message import CreateMessage, Message
from app.schemas.user import User
from app.storage import idempotency as key_storage
from app.storage import messages as message_storage
from app.storage import attachments as attachment_storage
IDEMPOTENCY_KEY_PATTERN = re.compile(r"[A-Za-z0-9._:-]{1,128}")
def validate_idempotency_key(key: str | None) -> str:
"""Проверяет обязательный ASCII-ключ запроса."""
if key is None or IDEMPOTENCY_KEY_PATTERN.fullmatch(key) is None:
raise invalid_request("Требуется корректный Idempotency-Key")
return key
def request_fingerprint(new_message: CreateMessage) -> str:
"""Хеширует нормализованное содержимое запроса."""
body = new_message.model_dump(mode="json")
# Сохраняет отпечатки текстовых запросов lab3 и равенство absent / [].
if not body["attachment_ids"]:
body.pop("attachment_ids")
canonical = json.dumps(body, sort_keys=True, ensure_ascii=False)
return hashlib.sha256(canonical.encode()).hexdigest()
async def send_message_idempotent(
session: AsyncSession,
sender: User,
chat_id: UUID,
new_message: CreateMessage,
idempotency_key: str,
max_messages: int,
ttl_seconds: int,
) -> Message:
"""Создаёт сообщение или возвращает результат прежнего запроса."""
await ensure_chat_member(session, sender, chat_id)
scope = (sender.id, "POST", f"/api/v1/chats/{chat_id}/messages", idempotency_key)
fingerprint = request_fingerprint(new_message)
await key_storage.lock_key(session, scope)
previous = await key_storage.get_active_key(session, scope, ttl_seconds)
if previous is not None:
if previous.request_hash != fingerprint:
raise conflict("Idempotency-Key уже использован для другого сообщения")
message = await message_storage.get_message(session, previous.message_id)
else:
await validate_message_attachments(session, sender, chat_id, new_message.attachment_ids)
if not await message_storage.reserve_message_slot(session, max_messages):
raise unavailable("Достигнут лимит количества сообщений")
message = await message_storage.create_message(
session, chat_id=chat_id, sender_id=sender.id, text=new_message.text
)
await attachment_storage.bind_attachments(session, message.id, new_message.attachment_ids)
await key_storage.save_result(session, scope, fingerprint, message.id)
links = await attachment_storage.message_attachment_ids(session, [message.id])
result = Message.model_validate(message).model_copy(update={"attachment_ids": links[message.id]})
await session.commit()
return result
+34
View File
@@ -0,0 +1,34 @@
"""Заготовки преобразований lab5, без доступа к БД, брокеру и HTTP.
Pipeline запускается внутри ограниченного процесса worker. Исходные bytes
не перекодируются; варианты удаляют метаданные по документированной политике.
Значения качества JPEG/WebP предстоит выбрать и зафиксировать в REPORT.md.
"""
from pathlib import Path
def create_thumbnail(source: Path, destination: Path) -> None:
"""Создать JPEG, вписанный в 256×256 без увеличения.
Применить EXIF orientation, alpha положить на белый; округлять размеры
вниз, минимум 1 px. Публичный fixture 320×200 должен дать 256×160.
"""
raise NotImplementedError("Lab5: thumbnail ещё не реализован")
def create_crop(source: Path, destination: Path) -> None:
"""Создать центрированный квадрат JPEG 128×128; увеличение допустимо.
Учитывать EXIF orientation и прозрачность по той же политике, что thumbnail.
"""
raise NotImplementedError("Lab5: crop ещё не реализован")
def create_optimized(source: Path, destination: Path) -> None:
"""Создать WebP, вписанный в 1280×1280 без увеличения.
Удалить метаданные и применить описанную политику качества. Уменьшение
размера любого маленького исходника не гарантируется контрактом.
"""
raise NotImplementedError("Lab5: optimized ещё не реализован")
+23
View File
@@ -0,0 +1,23 @@
"""Синхронная проверка изображения; вызывается только из ограниченного процесса."""
from pathlib import Path
import warnings
from PIL import Image
from app.errors.exceptions import payload_too_large, unsupported_media_type
def decode_image(path: Path, content_type: str, max_pixels: int) -> None:
Image.MAX_IMAGE_PIXELS = max_pixels
warnings.simplefilter("error", Image.DecompressionBombWarning)
with Image.open(path, formats=["PNG", "JPEG"]) as image:
if image.width * image.height > max_pixels:
raise payload_too_large("Превышен лимит пикселей изображения")
image_format = image.format
if image_format is None or Image.MIME.get(image_format) != content_type:
raise unsupported_media_type("Содержимое не соответствует Content-Type")
image.verify()
# Для JPEG одной verify() недостаточно: декодировать весь оригинал.
with Image.open(path, formats=["PNG", "JPEG"]) as image:
image.load()
+48
View File
@@ -0,0 +1,48 @@
"""Проверка имени и запуск ограниченного декодера."""
import asyncio
from pathlib import Path
import sys
import unicodedata
from anyio import CancelScope
from app.core.s3 import S3Settings
from app.errors.exceptions import (
image_validation_error,
invalid_request,
payload_too_large,
)
from app.errors.handlers import operation_timeout
def validate_filename(filename: str) -> None:
if not 1 <= len(filename) <= 255 or any(
char in "/\\" or unicodedata.category(char) in {"Cc", "Cf", "Cs"}
for char in filename
):
raise invalid_request("Недопустимое имя файла")
async def validate_image(path: Path, content_type: str, settings: S3Settings) -> None:
process = await asyncio.create_subprocess_exec(
sys.executable,
"-m",
"app.core.image_worker",
str(path),
content_type,
str(settings.max_image_pixels),
stdout=asyncio.subprocess.DEVNULL,
stderr=asyncio.subprocess.DEVNULL,
)
error = payload_too_large("Превышен бюджет проверки изображения")
try:
async with operation_timeout(settings.image_timeout_seconds, error):
code = await process.wait()
finally:
if process.returncode is None:
process.kill()
with CancelScope(shield=True):
await process.wait()
if code != 0:
raise image_validation_error(code)
+43
View File
@@ -0,0 +1,43 @@
from uuid import UUID
from sqlalchemy.ext.asyncio import AsyncSession
from app.domain.chats import ensure_chat_member
from app.domain.pagination import (
KIND_MESSAGES,
build_next_cursor,
decode_cursor,
split_page,
)
from app.schemas.message import Message, MessagePage
from app.schemas.user import User
from app.storage import messages as messages_storage
from app.storage import attachments as attachments_storage
from app.storage.types import Position
async def list_messages(
session: AsyncSession,
user: User,
chat_id: UUID,
cursor: str | None,
limit: int,
) -> MessagePage:
"""Возвращает страницу истории чата по (created_at, id)."""
after: Position | None = None
if cursor is not None:
after = decode_cursor(cursor, KIND_MESSAGES, chat_id)
await ensure_chat_member(session, user, chat_id)
rows = await messages_storage.list_messages(session, chat_id, after, limit + 1)
page_rows, has_next = split_page(rows, limit)
links = await attachments_storage.message_attachment_ids(session, [message.id for message in page_rows])
items = [Message.model_validate(message).model_copy(
update={"attachment_ids": links[message.id]},
) for message in page_rows]
page = MessagePage(
items=items,
next_cursor=build_next_cursor(KIND_MESSAGES, chat_id, items, has_next),
)
return page
+83
View File
@@ -0,0 +1,83 @@
import base64
import json
from collections.abc import Sequence
from datetime import datetime
from typing import Protocol, TypeVar
from uuid import UUID
from app.errors.exceptions import invalid_request
from app.storage.types import Position
KIND_CHATS = "chats"
KIND_MESSAGES = "messages"
T = TypeVar("T")
class Positioned(Protocol):
"""Объект с позицией в порядке (created_at, id)."""
@property
def id(self) -> UUID: ...
@property
def created_at(self) -> datetime: ...
def encode_cursor(
kind: str,
resource_id: UUID,
created_at: datetime,
item_id: UUID,
) -> str:
"""Кодирует позицию и ресурс, к которому она привязана, в непрозрачный cursor."""
payload = {
"kind": kind,
"resource_id": str(resource_id),
"created_at": created_at.isoformat(),
"item_id": str(item_id),
}
raw = json.dumps(payload).encode()
return base64.urlsafe_b64encode(raw).decode()
def decode_cursor(cursor: str, kind: str, resource_id: UUID) -> Position:
"""Возвращает позицию из cursor; битый или чужой cursor даёт 400."""
try:
payload = json.loads(base64.urlsafe_b64decode(cursor))
cursor_kind = payload["kind"]
cursor_resource_id = UUID(payload["resource_id"])
created_at = datetime.fromisoformat(payload["created_at"])
item_id = UUID(payload["item_id"])
except (ValueError, KeyError, TypeError, AttributeError):
raise invalid_request("Некорректный cursor") from None
if (
cursor_kind != kind
or cursor_resource_id != resource_id
or created_at.tzinfo is None
):
raise invalid_request("Некорректный cursor")
return created_at, item_id
def split_page(rows: list[T], limit: int) -> tuple[list[T], bool]:
"""Отделяет страницу от лишней строки limit + 1, по которой видно продолжение."""
has_next = len(rows) > limit
items = rows[:limit]
return items, has_next
def build_next_cursor(
kind: str,
resource_id: UUID,
items: Sequence[Positioned],
has_next: bool,
) -> str | None:
"""Возвращает cursor на последний элемент страницы или None, если она последняя."""
if not has_next:
return None
last_item = items[-1]
return encode_cursor(kind, resource_id, last_item.created_at, last_item.id)
+41
View File
@@ -0,0 +1,41 @@
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
from app.core import security
from app.errors.exceptions import conflict
from app.models.user import User as UserModel
from app.schemas.user import CreateUser, User
from app.storage import users as users_storage
USERNAME_TAKEN_MESSAGE = "Имя пользователя уже занято"
def to_user_schema(user: UserModel) -> User:
"""Преобразует ORM-модель в публичную схему без password_hash."""
user_schema = User.model_validate(user)
return user_schema
async def register_user(session: AsyncSession, new_user: CreateUser) -> User:
"""Регистрирует пользователя; занятый username даёт 409."""
existing_user = await users_storage.get_user_by_username(session, new_user.username)
await session.commit()
if existing_user is not None:
raise conflict(USERNAME_TAKEN_MESSAGE)
password_hash = await security.hash_password(new_user.password)
try:
user = await users_storage.create_user(
session,
username=new_user.username,
display_name=new_user.display_name,
password_hash=password_hash,
)
await session.commit()
except IntegrityError:
await session.rollback()
raise conflict(USERNAME_TAKEN_MESSAGE) from None
created_user = to_user_schema(user)
return created_user