Перенести реализацию лабораторной 4

This commit is contained in:
2026-11-16 13:57:52 +03:00
parent 276dbdad8a
commit 4d54ba3848
67 changed files with 3393 additions and 0 deletions
+3
View File
@@ -0,0 +1,3 @@
from . import auth, chats, health, messages, users
__all__ = ['auth', 'chats', 'health', 'messages', 'users']
+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}"',
},
)
+71
View File
@@ -0,0 +1,71 @@
from __future__ import annotations
import base64
from binascii import Error as Base64Error
from fastapi import APIRouter, Depends, Header, HTTPException, status
from ...auth.tokens import create_token
from ...db.redis import RedisSessionStore
from ...domain.models import User
from ...services.users import UserService
from ..deps import bearer_token, current_user, session_store, user_service
from ..schemas import SessionOut, UserOut
from ..timefmt import to_rfc3339
router = APIRouter(prefix='/api/v1/auth/sessions', tags=['auth'])
_BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
def _unauthorized_basic() -> HTTPException:
return HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail='неверные учётные данные',
headers={'WWW-Authenticate': _BASIC_CHALLENGE},
)
def _parse_basic(authorization: str | None) -> tuple[str, str]:
if not authorization:
raise _unauthorized_basic()
scheme, separator, encoded = authorization.partition(' ')
if scheme.lower() != 'basic' or not separator or not encoded:
raise _unauthorized_basic()
try:
decoded = base64.b64decode(encoded, validate=True).decode('utf-8')
except (Base64Error, UnicodeDecodeError):
raise _unauthorized_basic() from None
username, separator, password = decoded.partition(':')
if not separator or not username:
raise _unauthorized_basic()
return username, password
@router.post('', status_code=status.HTTP_201_CREATED, response_model=SessionOut)
async def create_session(
authorization: str | None = Header(None),
users: UserService = Depends(user_service),
sessions: RedisSessionStore = Depends(session_store),
) -> SessionOut:
username, password = _parse_basic(authorization)
user = await users.authenticate(username, password)
if user is None:
raise _unauthorized_basic()
token = create_token()
expires_at = await sessions.create(user.id, token)
return SessionOut(
token=token,
token_type='Bearer',
expires_at=to_rfc3339(expires_at),
user=UserOut.from_domain(user),
)
@router.delete('/current', status_code=status.HTTP_204_NO_CONTENT, response_model=None)
async def revoke_session(
token: str = Depends(bearer_token),
_: User = Depends(current_user),
sessions: RedisSessionStore = Depends(session_store),
) -> None:
await sessions.revoke(token)
+49
View File
@@ -0,0 +1,49 @@
from typing import Optional
from uuid import UUID
from fastapi import APIRouter, Depends, Query
from ...domain.models import User
from ...services.chats import ChatService
from .. import cursors
from ..deps import chat_service, current_user
from ..schemas import (
LIMIT_DEFAULT,
LIMIT_MAX,
LIMIT_MIN,
ChatOut,
ChatPageOut,
CreateChat,
)
router = APIRouter(prefix='/api/v1/chats', tags=['chats'])
@router.post('', status_code=201, response_model=ChatOut)
async def create(
body: CreateChat,
actor: User = Depends(current_user),
chats: ChatService = Depends(chat_service),
) -> ChatOut:
return ChatOut.from_domain(await chats.create(actor, body.title, body.member_ids))
@router.get('', response_model=ChatPageOut)
async def page(
actor: User = Depends(current_user),
chats: ChatService = Depends(chat_service),
limit: int = Query(LIMIT_DEFAULT, ge=LIMIT_MIN, le=LIMIT_MAX),
cursor: Optional[str] = Query(None, min_length=1, max_length=cursors.MAX_LENGTH),
) -> ChatPageOut:
scope = f'chats:{actor.id}'
after = cursors.decode(scope, cursor) if cursor is not None else None
return ChatPageOut.from_domain(await chats.page(actor, after, limit), scope)
@router.get('/{chat_id}', response_model=ChatOut)
async def get(
chat_id: UUID,
actor: User = Depends(current_user),
chats: ChatService = Depends(chat_service),
) -> ChatOut:
return ChatOut.from_domain(await chats.get(actor, chat_id))
+29
View File
@@ -0,0 +1,29 @@
from fastapi import APIRouter, HTTPException, Request
from redis.exceptions import RedisError
from sqlalchemy import text
from sqlalchemy.exc import SQLAlchemyError
from ...domain.errors import Unavailable
from ..schemas import HealthOut
router = APIRouter(tags=['health'])
@router.get('/health/live', response_model=HealthOut)
async def live() -> HealthOut:
return HealthOut(status='ok')
@router.get('/health/ready', response_model=HealthOut)
async def ready(request: Request) -> HealthOut:
if not request.app.state.ready:
raise HTTPException(status_code=503, detail='приложение не готово принимать трафик')
try:
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')
+53
View File
@@ -0,0 +1,53 @@
from typing import Annotated, Optional
from uuid import UUID
from fastapi import APIRouter, Depends, Header, Query
from ...domain.models import User
from ...services.messages import MessageService
from .. import cursors
from ..deps import current_user, message_service
from ..schemas import (
LIMIT_DEFAULT,
LIMIT_MAX,
LIMIT_MIN,
CreateMessage,
MessageOut,
MessagePageOut,
)
router = APIRouter(prefix='/api/v1/chats/{chat_id}/messages', tags=['messages'])
@router.post('', status_code=201, response_model=MessageOut)
async def send(
chat_id: UUID,
body: CreateMessage,
idempotency_key: Annotated[
str,
Header(
alias='Idempotency-Key',
min_length=1,
max_length=128,
pattern=r'^[A-Za-z0-9._:-]+$',
),
],
actor: User = Depends(current_user),
messages: MessageService = Depends(message_service),
) -> MessageOut:
return MessageOut.from_domain(
await messages.send(actor, chat_id, body.text, body.attachment_ids, idempotency_key)
)
@router.get('', response_model=MessagePageOut)
async def page(
chat_id: UUID,
actor: User = Depends(current_user),
messages: MessageService = Depends(message_service),
limit: int = Query(LIMIT_DEFAULT, ge=LIMIT_MIN, le=LIMIT_MAX),
cursor: Optional[str] = Query(None, min_length=1, max_length=cursors.MAX_LENGTH),
) -> MessagePageOut:
scope = f'messages:{chat_id}'
after = cursors.decode(scope, cursor) if cursor is not None else None
return MessagePageOut.from_domain(await messages.history(actor, chat_id, after, limit), scope)
+18
View File
@@ -0,0 +1,18 @@
from fastapi import APIRouter, Depends
from ...domain.models import User
from ...services.users import UserService
from ..deps import current_user, user_service
from ..schemas import CreateUser, UserOut
router = APIRouter(prefix='/api/v1', tags=['users'])
@router.post('/users', status_code=201, response_model=UserOut)
async def register(body: CreateUser, users: UserService = Depends(user_service)) -> UserOut:
return UserOut.from_domain(await users.register(body.username, body.display_name, body.password))
@router.get('/users/me', response_model=UserOut)
async def me(actor: User = Depends(current_user)) -> UserOut:
return UserOut.from_domain(actor)