This commit is contained in:
k00kzaAntonovaIra
2026-11-22 19:55:50 +03:00
parent 470d9d6f1e
commit 2d10a9b788
186 changed files with 15732 additions and 425 deletions
+1
View File
@@ -0,0 +1 @@
"""Бизнес-логика: проверки доступа, транзакции и ошибки API."""
+304
View File
@@ -0,0 +1,304 @@
"""Приём, durable публикация, попытки и фиксация результата обработки."""
import asyncio
from collections.abc import Callable
from contextlib import nullcontext
from dataclasses import dataclass
from pathlib import Path
from tempfile import TemporaryDirectory
from uuid import UUID, uuid4
from minio.error import MinioException
from opentelemetry.context import Context
from opentelemetry.trace import SpanKind
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
from sqlalchemy.ext.asyncio import AsyncSession
from urllib3.exceptions import HTTPError as StorageHTTPError
from app.core.jobs import JobSettings
from app.core.telemetry import Telemetry
from app.domain.job_retry import classify_failure, retry_delay
from app.domain.job_files import fetch_original, render_variants
from app.errors.exceptions import ProcessingError
from app.schemas.attachment import VARIANT_FILENAMES
from app.schemas.job import JobMessage
from app.storage import jobs, outbox
from app.storage.broker import JobBroker
from app.storage.jobs import JobWork
from app.storage.s3 import MinioStorage
@dataclass(frozen=True)
class Claim:
work: JobWork | None = None
acknowledge: bool = False
async def enqueue_attachment_job(
session: AsyncSession, attachment_id: UUID, staging_key: str
) -> UUID:
"""Включить намерение обработки в транзакцию queued metadata; без commit."""
return await jobs.create_job(session, attachment_id, staging_key)
async def publish_next_job(
session: AsyncSession,
broker: JobBroker,
*,
attachment_id: UUID | None = None,
before_publish: Callable[[UUID], None] | None = None,
telemetry: Telemetry | None = None,
) -> bool:
"""Отметка publish следует за durable publisher confirm; crash допускает тот же job-дубль."""
job = await outbox.next_unpublished_job(session, attachment_id=attachment_id)
published = job is not None
if job is not None:
if before_publish is not None:
before_publish(job.attachment_id)
parent = TraceContextTextMapPropagator().extract(
job.trace_context or {}, context=Context()
)
with (
telemetry.span(
"rabbitmq.publish",
context=parent,
kind=SpanKind.PRODUCER,
attributes={
"messaging.system": "rabbitmq",
"job.attempt": job.attempt + 1,
},
)
if telemetry
else nullcontext()
):
await broker.publish_job(
JobMessage(
job_id=job.id,
attachment_id=job.attachment_id,
pipeline_version=job.pipeline_version,
attempt=job.attempt + 1,
created_at=job.created_at,
)
)
outbox.mark_published(job)
await session.commit()
return published
async def claim_job(
session: AsyncSession, message: JobMessage, settings: JobSettings
) -> Claim:
"""Дубликат не захватывает живую аренду и не откатывает terminal-состояние."""
row = await jobs.lock_job(session, message.job_id)
result = Claim()
if row is None:
raise ProcessingError("unknown_job")
job, attachment = row
if (
message.attachment_id != attachment.id
or message.pipeline_version != job.pipeline_version
):
raise ProcessingError("invalid_job")
now = await jobs.database_time(session)
if job.attempt_limit is None:
job.attempt_limit = settings.job_max_attempts
if attachment.status in {"ready", "failed"}:
result = Claim(acknowledge=True)
elif message.attempt <= job.attempt and attachment.status == "queued":
# Предыдущая попытка уже устойчиво заменена новой в PostgreSQL.
result = Claim(acknowledge=True)
elif message.attempt < job.attempt:
result = Claim(acknowledge=True)
elif message.attempt > job.attempt + 1:
raise ProcessingError("invalid_attempt")
elif attachment.status == "queued" and job.next_attempt_at <= now:
if (
job.attempt >= (job.attempt_limit or settings.job_max_attempts)
or job.staging_key is None
):
jobs.record_failure(
job, attachment, now, "retry_exhausted", terminal=True, retry_seconds=0
)
result = Claim(acknowledge=True)
else:
result = Claim(
work=jobs.start_job(
job, attachment, uuid4(), now, settings.job_lease_seconds
)
)
await session.commit()
return result
async def save_failure(
session: AsyncSession,
work: JobWork,
settings: JobSettings,
code: str,
*,
permanent: bool,
) -> None:
# Неоднозначный COMMIT проверяется повторным чтением: ready сохраняется.
await session.rollback()
row = await jobs.lock_job(session, work.job_id)
if row is not None:
job, attachment = row
if attachment.status == "processing" and job.lease_token == work.lease_token:
exhausted = job.attempt >= (job.attempt_limit or settings.job_max_attempts)
jobs.record_failure(
job,
attachment,
await jobs.database_time(session),
"retry_exhausted" if exhausted and not permanent else code,
terminal=permanent or exhausted,
retry_seconds=retry_delay(
settings, job.attempt - job.cycle_start_attempt
),
)
job.last_error_code = code
job.last_error_permanent = permanent
await session.commit()
async def build_result(
session: AsyncSession,
storage: MinioStorage,
work: JobWork,
after_object: Callable[[UUID, str], None] | None = None,
telemetry: Telemetry | None = None,
) -> bool:
"""Фиксированные ключи и блокировка job защищают PUT от устаревшей попытки."""
with TemporaryDirectory(prefix="messenger-job-") as directory:
source = Path(directory) / "original"
with telemetry.span("s3.read_staging") if telemetry else nullcontext():
await fetch_original(storage, work, source)
result = await render_variants(storage, work, source, Path(directory))
row = await jobs.lock_job(session, work.job_id)
if row is None:
await session.rollback()
return True
job, attachment = row
now = await jobs.database_time(session)
if attachment.status != "processing" or job.lease_token != work.lease_token:
await session.rollback()
return True
if job.lease_until is None or job.lease_until <= now:
await session.rollback()
return False
# Блокировка остаётся до завершения PUT/COMMIT; reaper использует SKIP LOCKED.
# При отмене S3 adapter дожидается SDK-потока до освобождения блокировки.
with telemetry.span("s3.write_result") if telemetry else nullcontext():
await storage.put_file(
work.original_key,
source,
size_bytes=work.size_bytes,
content_type=work.content_type,
sha256=work.sha256,
)
if after_object is not None:
after_object(work.attachment_id, "original")
for variant in result.variants:
await storage.put_file(
work.variant_key(variant.name),
Path(directory) / VARIANT_FILENAMES[variant.name],
size_bytes=variant.size_bytes,
content_type=variant.content_type,
sha256=variant.sha256,
)
if after_object is not None:
after_object(work.attachment_id, variant.name)
with telemetry.span("postgres.commit_ready") if telemetry else nullcontext():
ready_at = await jobs.database_time(session)
accepted_at = job.created_at
jobs.complete_job(
job,
attachment,
work,
[variant.model_dump() for variant in result.variants],
ready_at,
)
await session.commit()
if telemetry and telemetry.enabled:
telemetry.time_to_ready.record(
max(0, (ready_at - accepted_at).total_seconds())
)
return True
async def process_attachment_job(
session: AsyncSession,
storage: MinioStorage,
message: JobMessage,
settings: JobSettings,
*,
after_object: Callable[[UUID, str], None] | None = None,
before_processing: Callable[[UUID], None] | None = None,
telemetry: Telemetry | None = None,
) -> bool:
with telemetry.span("postgres.claim_job") if telemetry else nullcontext():
claim = await claim_job(session, message, settings)
acknowledge = claim.acknowledge
if claim.work is not None:
work = claim.work
with telemetry.job_attempt() if telemetry else nullcontext({}) as result:
try:
async with asyncio.timeout(settings.job_timeout_seconds):
if before_processing is not None:
before_processing(work.attachment_id)
acknowledge = await build_result(
session, storage, work, after_object, telemetry
)
result["outcome"] = "success" if acknowledge else "deferred"
except (
ProcessingError,
MinioException,
StorageHTTPError,
OSError,
TimeoutError,
) as error:
code, permanent = classify_failure(error)
await save_failure(session, work, settings, code, permanent=permanent)
result.update(outcome="error", error_code=code)
acknowledge = True
# Ошибка БД/неизвестная ошибка или отмена не подтверждают доставку.
return acknowledge
async def recover_expired_jobs(session: AsyncSession, settings: JobSettings) -> int:
rows = await jobs.expired_jobs(session)
now = await jobs.database_time(session)
for job, attachment in rows:
if job.attempt_limit is None:
job.attempt_limit = settings.job_max_attempts
exhausted = job.attempt >= (job.attempt_limit or settings.job_max_attempts)
jobs.record_failure(
job,
attachment,
now,
"retry_exhausted" if exhausted else "worker_timeout",
terminal=exhausted,
retry_seconds=retry_delay(settings, job.attempt - job.cycle_start_attempt),
)
job.last_error_code = "worker_timeout"
job.last_error_permanent = False
await session.commit()
return len(rows)
async def cleanup_staging(
session: AsyncSession, storage: MinioStorage, settings: JobSettings, *, apply: bool
) -> int:
rows = await jobs.terminal_staging(
session,
settings.staging_retention_seconds,
settings.failed_staging_retention_seconds,
)
if apply:
for job, attachment in rows:
if job.staging_key != attachment.object_key:
await storage.delete_object(job.staging_key)
jobs.clear_staging(job)
await session.commit()
else:
await session.rollback()
return len(rows)
+337
View File
@@ -0,0 +1,337 @@
"""Авторизация, приём оригинала и согласованность 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.attachment_jobs import enqueue_attachment_job
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, VARIANT_FILENAMES
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:
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)
with suppress(*RECOVERABLE_STORAGE_ERRORS):
await session.rollback()
async def stage_attachment(
session: AsyncSession,
storage: MinioStorage,
user: User,
chat_id: UUID,
*,
original: OriginalFile,
filename: str,
content_type: str,
) -> Attachment:
id = uuid4()
key = f"staging/{uuid4().hex}"
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=f"originals/{id.hex}/v1",
status="queued",
filename=filename,
content_type=content_type,
size_bytes=original.size_bytes,
sha256=original.sha256,
)
await enqueue_attachment_job(session, id, key)
await repository.finish_upload(session, id)
result = Attachment.model_validate(record)
await session.commit()
except BaseException:
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")
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 stage_attachment(
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)
@dataclass(frozen=True)
class DownloadInfo:
filename: str
content_type: str
size_bytes: int
async def download_attachment(
session: AsyncSession,
storage: MinioStorage | None,
user: User,
attachment_id: UUID,
*,
variant: str = "original",
) -> tuple[DownloadInfo, AsyncIterator[bytes]]:
result = await get_attachment(session, user, attachment_id)
if result.status != "ready":
raise conflict("Вложение пока недоступно для скачивания")
storage = require_storage(storage)
record = await repository.get_attachment(session, attachment_id)
if record is None:
raise not_found()
if variant == "original":
key = record.object_key
info = DownloadInfo(result.filename, result.content_type, result.size_bytes)
else:
selected = next(
(item for item in result.variants if item.name == variant), None
)
keys = {
"thumbnail": record.thumbnail_key,
"crop": record.crop_key,
"optimized": record.optimized_key,
}
key = keys.get(variant)
if selected is None or key is None:
raise not_found()
info = DownloadInfo(
VARIANT_FILENAMES[variant], selected.content_type, selected.size_bytes
)
await session.rollback()
stored = await storage.stat_object(key)
if stored.size_bytes != info.size_bytes or stored.content_type != info.content_type:
raise unavailable("Файл временно недоступен")
stream = await storage.open_object(key)
return info, 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 == "failed" 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)
+81
View File
@@ -0,0 +1,81 @@
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:
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:
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:
is_deleted = await sessions_storage.delete_session(
redis, security.hash_token(token)
)
if not is_deleted:
raise unauthorized_bearer()
+98
View File
@@ -0,0 +1,98 @@
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:
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:
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:
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:
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:
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
+36
View File
@@ -0,0 +1,36 @@
"""Условия готовности реплики и ограниченная проверка зависимостей."""
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")
+75
View File
@@ -0,0 +1,75 @@
"""Атомарная отправка сообщения с защитой от повторов."""
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:
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")
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
+101
View File
@@ -0,0 +1,101 @@
"""Thumbnail, crop и WebP; один ограниченный процесс, последовательная обработка."""
import hashlib
from pathlib import Path
from PIL import Image, ImageOps
from app.core.image_processing import ImageSettings
from app.domain.image_validation import decode_image
from app.schemas.attachment import PipelineResult, Variant
def fitted_size(size: tuple[int, int], maximum: int) -> tuple[int, int]:
longest = max(size)
result = size
if longest > maximum:
result = (
max(1, size[0] * maximum // longest),
max(1, size[1] * maximum // longest),
)
return result
def describe_variant(
name: str, content_type: str, path: Path, size: tuple[int, int]
) -> Variant:
checksum = hashlib.sha256()
with path.open("rb") as source:
for chunk in iter(lambda: source.read(65536), b""):
checksum.update(chunk)
return Variant(
name=name,
content_type=content_type,
size_bytes=path.stat().st_size,
width=size[0],
height=size[1],
sha256=checksum.hexdigest(),
)
def save_jpeg(image: Image.Image, destination: Path, quality: int) -> None:
with Image.new("RGB", image.size, "white") as clean:
with image.getchannel("A") as alpha:
clean.paste(image, mask=alpha)
clean.save(destination, format="JPEG", quality=quality, exif=b"")
def create_thumbnail(image: Image.Image, destination: Path, quality: int) -> Variant:
size = fitted_size(image.size, 256)
with image.resize(size, Image.Resampling.LANCZOS) as resized:
save_jpeg(resized, destination, quality)
return describe_variant("thumbnail", "image/jpeg", destination, size)
def create_crop(image: Image.Image, destination: Path, quality: int) -> Variant:
with ImageOps.fit(
image, (128, 128), method=Image.Resampling.LANCZOS, centering=(0.5, 0.5)
) as crop:
save_jpeg(crop, destination, quality)
return describe_variant("crop", "image/jpeg", destination, (128, 128))
def create_optimized(
image: Image.Image, destination: Path, settings: ImageSettings
) -> Variant:
size = fitted_size(image.size, 1280)
with image.resize(size, Image.Resampling.LANCZOS) as resized:
with Image.new("RGBA", size) as clean:
clean.paste(resized)
clean.save(
destination,
format="WEBP",
lossless=False,
quality=settings.webp_quality,
method=settings.webp_method,
exif=b"",
icc_profile=b"",
xmp=b"",
)
return describe_variant("optimized", "image/webp", destination, size)
def create_variants(
source: Path,
directory: Path,
content_type: str,
max_pixels: int,
settings: ImageSettings,
) -> PipelineResult:
decode_image(source, content_type, max_pixels)
with Image.open(source, formats=["PNG", "JPEG"]) as image:
ImageOps.exif_transpose(image, in_place=True)
with image.convert("RGBA") as pixels:
variants = [
create_thumbnail(
pixels, directory / "thumbnail.jpg", settings.jpeg_quality
),
create_crop(pixels, directory / "crop.jpg", settings.jpeg_quality),
create_optimized(pixels, directory / "optimized.webp", settings),
]
return PipelineResult(variants=variants)
+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()
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)
+157
View File
@@ -0,0 +1,157 @@
"""Replay только failed с проверенным исходником и ограниченным новым бюджетом."""
import asyncio
import re
from pathlib import Path
from tempfile import TemporaryDirectory
from uuid import uuid4
from minio.error import S3Error
from app.domain.job_files import fetch_original
from app.errors.exceptions import JobOperationError, ProcessingError
from app.storage import job_admin, jobs
from app.storage.jobs import JobWork
REPLAY_REASONS = ("dependency_restored", "configuration_fixed", "manual_review")
def snapshot(job, attachment):
return dict(
job_id=str(job.id),
attachment_id=str(attachment.id),
status=attachment.status,
attempt=job.attempt,
attempt_limit=job.attempt_limit,
cycle_start_attempt=job.cycle_start_attempt,
error_code=attachment.error_code,
last_error_code=job.last_error_code,
last_error_permanent=job.last_error_permanent,
staging_retained=job.staging_key is not None,
next_attempt_at=job.next_attempt_at,
lease_until=job.lease_until,
finished_at=job.finished_at,
)
async def list_failed(session, limit):
return [
snapshot(job, attachment)
for job, attachment in await job_admin.failed_jobs(session, limit)
]
async def show_job(session, job_id):
row = await jobs.lock_job(session, job_id)
if row is None:
raise JobOperationError("unknown_job")
result = snapshot(*row)
await session.rollback()
return result
async def history(session, job_id):
return [
dict(
request_id=str(row.id),
actor=row.actor,
reason=row.reason,
previous_attempt=row.previous_attempt,
attempt_limit=row.attempt_limit,
previous_error_code=row.previous_error_code,
created_at=row.created_at,
)
for row in await job_admin.replay_history(session, job_id)
]
def same_request(record, job_id, actor, reason):
if record.job_id != job_id or record.actor != actor or record.reason != reason:
raise JobOperationError("request_conflict")
return {
"request_id": str(record.id),
"job_id": str(job_id),
"already_applied": True,
}
def validate_replay_request(actor: str, reason: str) -> None:
if (
re.fullmatch(r"[A-Za-z0-9._-]{1,64}", actor) is None
or reason not in REPLAY_REASONS
):
raise JobOperationError("invalid_audit_fields")
def validate_replay_job(job, attachment) -> None:
if attachment.status != "failed":
raise JobOperationError("job_not_failed")
if job.staging_key is None:
raise JobOperationError("source_expired")
async def verify_replay_source(storage, settings, job, attachment) -> None:
work = JobWork(
job.id,
attachment.id,
uuid4(),
job.pipeline_version,
job.staging_key,
attachment.content_type,
attachment.size_bytes,
attachment.sha256,
)
try:
async with asyncio.timeout(settings.job_timeout_seconds):
with TemporaryDirectory(prefix="replay-source-") as directory:
await fetch_original(storage, work, Path(directory) / "original")
except ProcessingError as error:
raise JobOperationError(error.code) from None
except S3Error as error:
if error.code in {"NoSuchKey", "NoSuchObject"}:
raise JobOperationError("source_missing") from None
raise
async def replay_failed_job(
session, storage, settings, job_id, *, request_id, actor, reason
):
validate_replay_request(actor, reason)
row = await jobs.lock_job(session, job_id)
if row is None:
raise JobOperationError("unknown_job")
record = await job_admin.replay_record(session, request_id)
if record is not None:
result = same_request(record, job_id, actor, reason)
await session.rollback()
return result
job, attachment = row
validate_replay_job(job, attachment)
await verify_replay_source(storage, settings, job, attachment)
limit = job.attempt + settings.job_max_attempts
inserted = await job_admin.insert_replay(
session,
id=request_id,
job_id=job_id,
actor=actor,
reason=reason,
previous_attempt=job.attempt,
attempt_limit=limit,
previous_error_code=job.last_error_code,
)
if not inserted:
result = same_request(
await job_admin.replay_record(session, request_id), job_id, actor, reason
)
await session.rollback()
return result
job_admin.reset_failed(job, attachment, await jobs.database_time(session), limit)
await session.commit()
return {
"request_id": str(request_id),
"job_id": str(job_id),
"already_applied": False,
"status": "queued",
"attempt_limit": limit,
}
+72
View File
@@ -0,0 +1,72 @@
"""Получение исходника и запуск изолированного процесса обработки вариантов."""
import asyncio
import errno
import hashlib
from pathlib import Path
import sys
from anyio import CancelScope
from app.errors.exceptions import ProcessingError
from app.schemas.attachment import PipelineResult
from app.storage.jobs import JobWork
from app.storage.s3 import MinioStorage
async def fetch_original(
storage: MinioStorage, work: JobWork, destination: Path
) -> None:
if work.size_bytes > storage.settings.max_upload_bytes:
raise ProcessingError("image_limits")
checksum = hashlib.sha256()
size = 0
stream = await storage.open_object(work.staging_key)
try:
with destination.open("wb") as target:
async for chunk in stream:
size += len(chunk)
if size > work.size_bytes:
raise ProcessingError("source_mismatch")
target.write(chunk)
checksum.update(chunk)
finally:
await stream.aclose()
if size != work.size_bytes or checksum.hexdigest() != work.sha256:
raise ProcessingError("source_mismatch")
async def render_variants(
storage: MinioStorage, work: JobWork, source: Path, directory: Path
) -> PipelineResult:
metadata = directory / "variants.json"
process = await asyncio.create_subprocess_exec(
sys.executable,
"-m",
"app.core.thumbnail_worker",
str(source),
str(directory),
str(metadata),
work.content_type,
str(storage.settings.max_image_pixels),
stdout=asyncio.subprocess.DEVNULL,
stderr=asyncio.subprocess.DEVNULL,
)
try:
code = await process.wait()
finally:
if process.returncode is None:
process.kill()
with CancelScope(shield=True):
await process.wait()
if code == 2:
raise ProcessingError("invalid_image")
if code == 3 or code < 0:
raise ProcessingError("image_limits")
if code == 4:
raise OSError(errno.EIO, "Pipeline filesystem unavailable")
if code == 5:
raise ProcessingError("processing_configuration")
if code != 0:
raise RuntimeError("Image pipeline subprocess failed")
return PipelineResult.model_validate_json(metadata.read_text())
+51
View File
@@ -0,0 +1,51 @@
"""Ограниченный exponential backoff: jitter сохраняется вместе с новой попыткой."""
import errno
import random
from minio.error import S3Error
from app.core.jobs import JobSettings
from app.errors.exceptions import ProcessingError
def retry_delay(settings: JobSettings, cycle_attempt: int) -> float:
ceiling = min(
settings.job_retry_max_seconds,
settings.job_retry_seconds * 2 ** min(30, max(0, cycle_attempt - 1)),
)
return random.uniform(ceiling / 2, ceiling)
def classify_failure(error: Exception) -> tuple[str, bool]:
if isinstance(error, ProcessingError):
return error.code, True
if isinstance(error, S3Error):
if error.code in {"NoSuchKey", "NoSuchObject"}:
return "source_missing", True
if error.code in {
"AccessDenied",
"InvalidAccessKeyId",
"SignatureDoesNotMatch",
"NoSuchBucket",
}:
return "storage_configuration", True
if error.code in {
"InternalError",
"SlowDown",
"ServiceUnavailable",
"RequestTimeout",
"Throttling",
}:
return "storage_unavailable", False
return "storage_rejected", True
if isinstance(error, TimeoutError):
return "processing_timeout", False
if isinstance(error, OSError) and error.errno in {
errno.EACCES,
errno.EPERM,
errno.EROFS,
errno.ENOENT,
}:
return "processing_configuration", True
return "processing_unavailable", False
+47
View File
@@ -0,0 +1,47 @@
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:
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
+78
View File
@@ -0,0 +1,78 @@
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):
@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:
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:
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]:
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:
if not has_next:
return None
last_item = items[-1]
return encode_cursor(kind, resource_id, last_item.created_at, last_item.id)
+39
View File
@@ -0,0 +1,39 @@
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:
user_schema = User.model_validate(user)
return user_schema
async def register_user(session: AsyncSession, new_user: CreateUser) -> User:
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