feat: перенос 5 лабы логики

This commit is contained in:
Enterxx2
2026-11-10 13:48:00 +03:00
parent 470d9d6f1e
commit 60a71dc839
182 changed files with 14717 additions and 8 deletions
+17
View File
@@ -0,0 +1,17 @@
from fastapi import APIRouter
from .attachments import attachments_router
from .auth import auth_router
from .chats import chats_router
from .messages import messages_router
from .users import users_router
app = APIRouter(prefix="/v1")
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,99 @@
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_202_ACCEPTED,
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. 202 queued — после staging и транзакции job/outbox; resize выполняет worker.
"""
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),
)
@@ -0,0 +1,3 @@
from .endpoints import auth_router
__all__ = ["auth_router"]
@@ -0,0 +1,35 @@
from fastapi import APIRouter, Depends, Response, status
from application.api.dependencies import basic_credentials, bearer_token
from domain import BasicCredentialsSchema, SessionSchema
from infrastructure.dependencies import ServiceCreator
from infrastructure.services import AuthService
auth_router = APIRouter(prefix="/auth/sessions", tags=["Auth"])
@auth_router.post(
"",
status_code=status.HTTP_201_CREATED,
response_model=SessionSchema,
)
async def create_session(
credentials: BasicCredentialsSchema = Depends(basic_credentials),
service: AuthService = Depends(ServiceCreator.get_auth_service),
) -> SessionSchema:
"""Вход по Basic, без JSON body; возвращает Bearer-токен"""
return await service.login(credentials)
@auth_router.delete(
"/current",
status_code=status.HTTP_204_NO_CONTENT,
response_class=Response,
)
async def revoke_session(
token: str | None = Depends(bearer_token),
service: AuthService = Depends(ServiceCreator.get_auth_service),
) -> Response:
"""Logout: текущий токен перестаёт действовать; повтор — 401"""
await service.logout(token)
return Response(status_code=status.HTTP_204_NO_CONTENT)
@@ -0,0 +1,3 @@
from .endpoints import chats_router
__all__ = ["chats_router"]
@@ -0,0 +1,58 @@
from typing import Annotated
from uuid import UUID
from fastapi import APIRouter, Body, Depends, Query, status
from application.api.dependencies import get_current_user
from domain import (
ChatPageSchema,
ChatSchema,
CreateChatSchema,
UserSchema,
)
from infrastructure.dependencies import ServiceCreator
from infrastructure.services import ChatService
chats_router = APIRouter(prefix="/chats", tags=["Chats"])
@chats_router.post(
"",
status_code=status.HTTP_201_CREATED,
response_model=ChatSchema,
)
async def create_chat(
body: Annotated[CreateChatSchema, Body(...)],
current_user: UserSchema = Depends(get_current_user),
service: ChatService = Depends(ServiceCreator.get_chat_service),
) -> ChatSchema:
"""Вызывающий должен входить в member_ids"""
return await service.create_chat(current_user, body)
@chats_router.get(
"",
status_code=status.HTTP_200_OK,
response_model=ChatPageSchema,
)
async def list_chats(
limit: Annotated[int, Query(ge=1, le=100)] = 50,
cursor: Annotated[str | None, Query(min_length=1)] = None,
current_user: UserSchema = Depends(get_current_user),
service: ChatService = Depends(ServiceCreator.get_chat_service),
) -> ChatPageSchema:
"""Чаты текущего пользователя по (created_at, id) по возрастанию"""
return await service.list_chats(current_user, limit, cursor)
@chats_router.get(
"/{chat_id}",
status_code=status.HTTP_200_OK,
response_model=ChatSchema,
)
async def get_chat(
chat_id: UUID,
current_user: UserSchema = Depends(get_current_user),
service: ChatService = Depends(ServiceCreator.get_chat_service),
) -> ChatSchema:
return await service.get_chat(current_user, chat_id)
@@ -0,0 +1,3 @@
from .endpoints import messages_router
__all__ = ["messages_router"]
@@ -0,0 +1,63 @@
from typing import Annotated
from uuid import UUID
from fastapi import APIRouter, Body, Depends, Header, Query, status
from application.api.dependencies import get_current_user
from domain import (
IDEMPOTENCY_KEY_MAX_LENGTH,
IDEMPOTENCY_KEY_PATTERN,
CreateMessageSchema,
MessagePageSchema,
MessageSchema,
UserSchema,
)
from infrastructure.dependencies import ServiceCreator
from infrastructure.services import MessageService
messages_router = APIRouter(
prefix="/chats/{chat_id}/messages", tags=["Messages"]
)
@messages_router.post(
"",
status_code=status.HTTP_201_CREATED,
response_model=MessageSchema,
)
async def send_message(
chat_id: UUID,
body: Annotated[CreateMessageSchema, Body(...)],
idempotency_key: Annotated[
str,
Header(
alias="Idempotency-Key",
min_length=1,
max_length=IDEMPOTENCY_KEY_MAX_LENGTH,
pattern=IDEMPOTENCY_KEY_PATTERN,
),
],
current_user: UserSchema = Depends(get_current_user),
service: MessageService = Depends(ServiceCreator.get_message_service),
) -> MessageSchema:
"""
Idempotency-Key обязателен: повтор того же тела возвращает тот же 201
и то же сообщение, другое тело с тем же ключом — 409. Нет/неверный ключ — 400.
"""
return await service.send_message(current_user, chat_id, body, idempotency_key)
@messages_router.get(
"",
status_code=status.HTTP_200_OK,
response_model=MessagePageSchema,
)
async def list_messages(
chat_id: UUID,
limit: Annotated[int, Query(ge=1, le=100)] = 50,
cursor: Annotated[str | None, Query(min_length=1)] = None,
current_user: UserSchema = Depends(get_current_user),
service: MessageService = Depends(ServiceCreator.get_message_service),
) -> MessagePageSchema:
"""История чата: keyset cursor по (created_at, id) по возрастанию"""
return await service.list_messages(current_user, chat_id, limit, cursor)
@@ -0,0 +1,3 @@
from .endpoints import users_router
__all__ = ["users_router"]
@@ -0,0 +1,33 @@
from typing import Annotated
from fastapi import APIRouter, Body, Depends, status
from application.api.dependencies import get_current_user
from domain import CreateUserSchema, UserSchema
from infrastructure.dependencies import ServiceCreator
from infrastructure.services import UserService
users_router = APIRouter(prefix="/users", tags=["Users"])
@users_router.post(
"",
status_code=status.HTTP_201_CREATED,
response_model=UserSchema,
openapi_extra={"security": []},
)
async def register_user(
body: Annotated[CreateUserSchema, Body(...)],
service: UserService = Depends(ServiceCreator.get_user_service),
) -> UserSchema:
"""Публичная регистрация; username уникален"""
return await service.register(body)
@users_router.get(
"/me",
status_code=status.HTTP_200_OK,
response_model=UserSchema,
)
async def get_me(current_user: UserSchema = Depends(get_current_user)) -> UserSchema:
return current_user