feat: ЛР 4 с хранением вложений в MinIO

This commit is contained in:
2026-11-05 19:45:49 +03:00
parent 5be0a6c0b4
commit 0ed4b9cea5
40 changed files with 1763 additions and 65 deletions
+6
View File
@@ -8,6 +8,7 @@ from ..db.redis import RedisSessionStore
from ..domain.errors import Unauthorized
from ..domain.models import User
from ..services.chats import ChatService
from ..services.attachments import AttachmentService
from ..services.messages import MessageService
from ..services.users import UserService
@@ -16,6 +17,7 @@ _BEARER_CHALLENGE = 'Bearer realm="messenger"'
@dataclass(frozen=True, slots=True)
class Services:
attachments: AttachmentService
users: UserService
chats: ChatService
messages: MessageService
@@ -38,6 +40,10 @@ def message_service(container: Services = Depends(services)) -> MessageService:
return container.messages
def attachment_service(container: Services = Depends(services)) -> AttachmentService:
return container.attachments
def session_store(container: Services = Depends(services)) -> RedisSessionStore:
return container.sessions
+12 -1
View File
@@ -6,7 +6,16 @@ from fastapi.responses import JSONResponse
from sqlalchemy.exc import SQLAlchemyError
from starlette.exceptions import HTTPException as StarletteHTTPException
from ..domain.errors import Conflict, DomainError, Invalid, NotFound, Unauthorized, Unavailable
from ..domain.errors import (
Conflict,
DomainError,
Invalid,
NotFound,
PayloadTooLarge,
Unauthorized,
Unavailable,
UnsupportedMediaType,
)
logger = logging.getLogger('app.error')
@@ -27,6 +36,8 @@ STATUS_BY_DOMAIN = {
Unauthorized: 401,
NotFound: 404,
Conflict: 409,
PayloadTooLarge: 413,
UnsupportedMediaType: 415,
Unavailable: 503,
}
+66
View File
@@ -0,0 +1,66 @@
from typing import Annotated
from uuid import UUID
from fastapi import APIRouter, Depends, Header, Query, Request
from fastapi.responses import StreamingResponse
from ...domain.models import User
from ...services.attachments import AttachmentService
from ..deps import attachment_service, current_user
from ..schemas import AttachmentOut
router = APIRouter(tags=['attachments'])
@router.post(
'/api/v1/chats/{chat_id}/attachments',
status_code=201,
response_model=AttachmentOut,
)
async def upload(
chat_id: UUID,
request: Request,
filename: str = Query(..., min_length=1, max_length=255),
content_type: Annotated[str | None, Header(alias='Content-Type')] = None,
actor: User = Depends(current_user),
attachments: AttachmentService = Depends(attachment_service),
) -> AttachmentOut:
attachment = await attachments.upload(
actor,
chat_id,
filename,
content_type or '',
request.stream(),
)
return AttachmentOut.from_domain(attachment)
@router.get('/api/v1/attachments/{attachment_id}', response_model=AttachmentOut)
async def metadata(
attachment_id: UUID,
actor: User = Depends(current_user),
attachments: AttachmentService = Depends(attachment_service),
) -> AttachmentOut:
return AttachmentOut.from_domain(await attachments.get(actor, attachment_id))
@router.get('/api/v1/attachments/{attachment_id}/content')
async def content(
attachment_id: UUID,
variant: str = Query('original'),
actor: User = Depends(current_user),
attachments: AttachmentService = Depends(attachment_service),
) -> StreamingResponse:
if variant != 'original':
from ...domain.errors import NotFound
raise NotFound('вариант вложения не найден')
attachment, stream = await attachments.content(actor, attachment_id)
return StreamingResponse(
stream.chunks(),
media_type=attachment.content_type,
headers={
'Content-Length': str(attachment.size_bytes),
'Content-Disposition': f'inline; filename="attachment-{attachment.id}"',
},
)
+1
View File
@@ -23,6 +23,7 @@ async def ready(request: Request) -> HealthOut:
async with request.app.state.engine.connect() as connection:
await connection.execute(text('SELECT 1'))
await request.app.state.redis.ping()
await request.app.state.storage.ping()
except (SQLAlchemyError, RedisError, Unavailable, OSError):
raise HTTPException(status_code=503, detail='обязательное хранилище недоступно') from None
return HealthOut(status='ok')
+3 -1
View File
@@ -35,7 +35,9 @@ async def send(
actor: User = Depends(current_user),
messages: MessageService = Depends(message_service),
) -> MessageOut:
return MessageOut.from_domain(await messages.send(actor, chat_id, body.text, idempotency_key))
return MessageOut.from_domain(
await messages.send(actor, chat_id, body.text, body.attachment_ids, idempotency_key)
)
@router.get('', response_model=MessagePageOut)
+49 -6
View File
@@ -1,9 +1,9 @@
from typing import Optional
from uuid import UUID
from pydantic import BaseModel, ConfigDict, Field, field_validator
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
from ..domain.models import Chat, Message, Page, User
from ..domain.models import Attachment, Chat, Message, Page, User
from . import cursors
from .timefmt import to_rfc3339
@@ -97,12 +97,21 @@ class ChatOut(Strict):
class CreateMessage(Strict):
text: str = Field(min_length=1, max_length=TEXT_MAX)
text: str = Field(max_length=TEXT_MAX)
attachment_ids: list[UUID] = Field(default_factory=list, max_length=10)
@field_validator('text')
@field_validator('attachment_ids')
@classmethod
def _text(cls, value: str) -> str:
return not_blank(value)
def _attachments_unique(cls, value: list[UUID]) -> list[UUID]:
if len(set(value)) != len(value):
raise ValueError('attachment_ids не должен содержать дубликаты')
return value
@model_validator(mode='after')
def _content_present(self) -> 'CreateMessage':
if not self.text.strip() and not self.attachment_ids:
raise ValueError('сообщение должно содержать текст или вложение')
return self
class MessageOut(Strict):
@@ -111,6 +120,7 @@ class MessageOut(Strict):
sender_id: UUID
text: str
created_at: str
attachment_ids: list[UUID]
@classmethod
def from_domain(cls, message: Message) -> 'MessageOut':
@@ -120,6 +130,39 @@ class MessageOut(Strict):
sender_id=message.sender_id,
text=message.text,
created_at=to_rfc3339(message.created_at),
attachment_ids=list(message.attachment_ids),
)
class AttachmentOut(Strict):
id: UUID
chat_id: UUID
owner_id: UUID
filename: str
content_type: str
size_bytes: int
sha256: str
status: str
variants: list = Field(default_factory=list)
error_code: str | None
created_at: str
updated_at: str
@classmethod
def from_domain(cls, attachment: Attachment) -> 'AttachmentOut':
return cls(
id=attachment.id,
chat_id=attachment.chat_id,
owner_id=attachment.owner_id,
filename=attachment.filename,
content_type=attachment.content_type,
size_bytes=attachment.size_bytes,
sha256=attachment.sha256,
status=attachment.status,
variants=[],
error_code=attachment.error_code,
created_at=to_rfc3339(attachment.created_at),
updated_at=to_rfc3339(attachment.updated_at),
)