feat: Саватеев А трек 4

This commit is contained in:
Enterxx2
2026-11-02 23:13:38 +03:00
parent 445cfe4789
commit 081d0fd2c8
76 changed files with 6387 additions and 77 deletions
+17 -4
View File
@@ -2,7 +2,12 @@ from fastapi import APIRouter, Depends, Request, status
from domain import HealthSchema
from domain.errors import UnavailableError
from infrastructure.dependencies import DatabasePoolManager, get_database
from infrastructure.dependencies import (
DatabasePoolManager,
ObjectStorageManager,
get_database,
get_storage,
)
health_router = APIRouter(prefix="/health", tags=["Health"])
@@ -23,14 +28,22 @@ async def liveness() -> HealthSchema:
response_model=HealthSchema,
)
async def readiness(
request: Request, database: DatabasePoolManager = Depends(get_database)
request: Request,
database: DatabasePoolManager = Depends(get_database),
storage: ObjectStorageManager = Depends(get_storage),
) -> HealthSchema:
"""
Приложение не завершается и PostgreSQL отвечает. Valkey не критичен:
без него сессии читаются из PostgreSQL, поэтому он не влияет на готовность.
Приложение не завершается, PostgreSQL и S3 отвечают: с lab4 загрузка
и скачивание вложений входят в обязательный синхронный путь.
Valkey не критичен: без него сессии читаются из PostgreSQL. Без S3
недоступны только вложения — nginx не исключает реплику по readiness,
поэтому сообщения продолжают работать, а реплика честно сообщает 503.
"""
if not getattr(request.app.state, "is_ready", False):
raise UnavailableError()
if not await database.check():
raise UnavailableError("бд недоступна")
if not await storage.check():
raise UnavailableError("хранилище файлов недоступно")
return HealthSchema()
+2
View File
@@ -1,5 +1,6 @@
from fastapi import APIRouter
from .attachments import attachments_router
from .auth import auth_router
from .chats import chats_router
from .messages import messages_router
@@ -11,5 +12,6 @@ app.include_router(users_router)
app.include_router(auth_router)
app.include_router(chats_router)
app.include_router(messages_router)
app.include_router(attachments_router)
__all__ = ["app"]
@@ -0,0 +1,3 @@
from .endpoints import attachments_router
__all__ = ["attachments_router"]
@@ -0,0 +1,100 @@
from typing import Annotated
from uuid import UUID
from fastapi import APIRouter, Depends, Header, Query, Request, status
from fastapi.responses import StreamingResponse
from starlette.background import BackgroundTask
from application.api.dependencies import get_current_user
from application.api.utils import content_disposition, request_chunks
from domain import (
AttachmentContentType,
AttachmentFilename,
AttachmentSchema,
AttachmentVariant,
UserSchema,
)
from infrastructure.dependencies import ServiceCreator
from infrastructure.services import AttachmentService
attachments_router = APIRouter(tags=["Attachments"])
IMAGE_BODY = {
content_type: {"schema": {"type": "string", "format": "binary"}}
for content_type in AttachmentContentType
}
@attachments_router.post(
"/chats/{chat_id}/attachments",
status_code=status.HTTP_201_CREATED,
response_model=AttachmentSchema,
openapi_extra={"requestBody": {"required": True, "content": IMAGE_BODY}},
)
async def upload_attachment(
chat_id: UUID,
filename: Annotated[AttachmentFilename, Query()],
request: Request,
content_type: Annotated[str | None, Header()] = None,
content_length: Annotated[int | None, Header(ge=0)] = None,
current_user: UserSchema = Depends(get_current_user),
service: AttachmentService = Depends(ServiceCreator.get_attachment_service),
) -> AttachmentSchema:
"""
Сырые байты одного PNG/JPEG, не multipart. 201 ready — только после
сохранения оригинала в S3 и метаданных в PostgreSQL.
"""
return await service.upload(
current_user,
chat_id,
filename,
content_type,
content_length,
request_chunks(request),
)
@attachments_router.get(
"/attachments/{attachment_id}",
status_code=status.HTTP_200_OK,
response_model=AttachmentSchema,
)
async def get_attachment(
attachment_id: UUID,
current_user: UserSchema = Depends(get_current_user),
service: AttachmentService = Depends(ServiceCreator.get_attachment_service),
) -> AttachmentSchema:
"""Метаданные доступны только участникам чата вложения; остальным — 404"""
return await service.get_attachment(current_user, attachment_id)
@attachments_router.get(
"/attachments/{attachment_id}/content",
status_code=status.HTTP_200_OK,
response_class=StreamingResponse,
responses={200: {"content": IMAGE_BODY}},
)
async def download_attachment(
attachment_id: UUID,
variant: Annotated[AttachmentVariant, Query()] = AttachmentVariant.ORIGINAL,
current_user: UserSchema = Depends(get_current_user),
service: AttachmentService = Depends(ServiceCreator.get_attachment_service),
) -> StreamingResponse:
"""
Байты через API, без redirect на S3: доступ проверяет приложение.
Ответ идёт потоком из S3, файл целиком в памяти реплики не собирается.
"""
attachment, content = await service.open_content(
current_user, attachment_id, variant
)
return StreamingResponse(
content.iter_chunks(),
media_type=attachment.content_type,
headers={
"Content-Length": str(content.content_length),
"Content-Disposition": content_disposition(attachment.filename),
"X-Content-Type-Options": "nosniff",
"Cache-Control": "private, no-store",
},
background=BackgroundTask(content.close),
)
+3
View File
@@ -4,10 +4,13 @@ from .errors import (
error_response,
get_request_id,
)
from .streams import content_disposition, request_chunks
__all__ = [
"REQUEST_ID_HEADER",
"INSTANCE_ID_HEADER",
"error_response",
"get_request_id",
"request_chunks",
"content_disposition",
]
+28
View File
@@ -0,0 +1,28 @@
from collections.abc import AsyncIterator
from urllib.parse import quote
from fastapi import Request
from starlette.requests import ClientDisconnect
from domain.errors import InvalidRequestError
async def request_chunks(request: Request) -> AsyncIterator[bytes]:
"""
Тело запроса потоком, без буферизации целиком. Обрыв соединения клиентом
— доменная ошибка, а не необработанное исключение (500 в журнале).
"""
try:
async for chunk in request.stream():
if chunk:
yield chunk
except ClientDisconnect:
raise InvalidRequestError("Загрузка прервана клиентом") from None
def content_disposition(filename: str) -> str:
"""
inline с именем по RFC 6266/5987: имя целиком percent-encoded, поэтому
кавычки, ; и переводы строк не могут разорвать заголовок.
"""
return f"inline; filename*=UTF-8''{quote(filename, safe='')}"