Files
mtusi2026lab4/src/main.py
T
2026-10-29 02:56:13 +03:00

725 lines
19 KiB
Python

from datetime import datetime, timedelta, timezone
from uuid import UUID, uuid4
import os
import re
import base64
import binascii
import asyncio
from fastapi import Depends, FastAPI, Request, Header, Query
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, Response
from fastapi.security import (
HTTPAuthorizationCredentials,
HTTPBearer,
)
from botocore.exceptions import BotoCoreError, ClientError
from sqlalchemy.exc import IntegrityError, SQLAlchemyError
from sqlalchemy.ext.asyncio import AsyncSession
from starlette.exceptions import HTTPException as StarletteHTTPException
from contextlib import asynccontextmanager
from src.database import engine, get_db_session, ping_database, SessionFactory
from src.errors import APIError
from src.models import CreateUser, SessionResponse, User, CreateChat, Chat, ChatPage, CreateMessage, Message, MessagePage, Attachment
from src.repositories import (
create_chat,
list_chats,
create_user as create_user_in_db,
get_user_by_id,
get_chat_by_id,
get_user_credentials_by_username,
create_message,
get_messages,
create_attachment,
get_attachment,
attachment_key_exists,
)
from src.security import verify_password
from src.sessions import (
create_session,
delete_session,
get_session_user_id,
ping_session_store,
redis_client,
)
from src.images import MAX_UPLOAD_BYTES, validate_image
from src.storage import delete_object, put_object, get_object
@asynccontextmanager
async def lifespan(app: FastAPI):
yield
await redis_client.aclose()
await engine.dispose()
app = FastAPI(lifespan=lifespan)
INSTANCE_ID = os.getenv("INSTANCE_ID") or str(uuid4())
bearer_security = HTTPBearer(auto_error=False)
async def get_current_user(
credentials: HTTPAuthorizationCredentials | None = Depends(bearer_security),
session: AsyncSession = Depends(get_db_session),
) -> User:
if credentials is None or credentials.scheme.lower() != "bearer":
raise APIError(
status_code=401,
code="unauthorized",
message="Unauthorized",
headers={
"WWW-Authenticate": "Bearer",
},
)
user_id = await get_session_user_id(credentials.credentials)
if user_id is None:
raise APIError(
status_code=401,
code="unauthorized",
message="Unauthorized",
headers={
"WWW-Authenticate": "Bearer",
},
)
user = await get_user_by_id(session, user_id)
if user is None:
raise APIError(
status_code=401,
code="unauthorized",
message="Unauthorized",
headers={
"WWW-Authenticate": "Bearer",
},
)
return user
@app.middleware("http")
async def request_middleware(request: Request, call_next):
request_id = str(uuid4())
request.state.request_id = request_id
if request.method in {"POST", "PUT", "PATCH"}:
content_type = request.headers.get("content-type")
if content_type is not None:
media_type = content_type.split(";", 1)[0].strip().lower()
is_attachment_upload = (
request.method == "POST"
and re.fullmatch(
r"/api/v1/chats/[^/]+/attachments",
request.url.path,
) is not None
)
allowed_media_types = (
{"image/png", "image/jpeg"}
if is_attachment_upload
else {"application/json"}
)
if media_type not in allowed_media_types:
return JSONResponse(
status_code=415,
content={
"error": {
"code": "unsupported_media_type",
"message": "Unsupported media type",
"request_id": request_id,
}
},
headers={
"X-Request-Id": request_id,
"X-Instance-Id": INSTANCE_ID,
},
)
response = await call_next(request)
response.headers["X-Request-Id"] = request_id
response.headers["X-Instance-Id"] = INSTANCE_ID
return response
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(
request: Request,
exc: RequestValidationError,
):
request_id = request.state.request_id
return JSONResponse(
status_code=400,
content={
"error": {
"code": "invalid_request",
"message": "Invalid request",
"request_id": request_id,
}
},
)
@app.exception_handler(APIError)
async def api_error_handler(request: Request, exc: APIError):
request_id = request.state.request_id
return JSONResponse(
status_code=exc.status_code,
content={
"error": {
"code": exc.code,
"message": exc.message,
"request_id": request_id,
}
},
headers=exc.headers,
)
@app.exception_handler(SQLAlchemyError)
async def database_exception_handler(
request: Request,
exc: SQLAlchemyError,
):
request_id = request.state.request_id
return JSONResponse(
status_code=503,
content={
"error": {
"code": "unavailable",
"message": "Database unavailable",
"request_id": request_id,
}
},
)
@app.exception_handler(OSError)
async def database_connection_exception_handler(
request: Request,
exc: OSError,
):
request_id = request.state.request_id
return JSONResponse(
status_code=503,
content={
"error": {
"code": "unavailable",
"message": "Database unavailable",
"request_id": request_id,
}
},
)
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(
request: Request,
exc: StarletteHTTPException,
):
request_id = request.state.request_id
if exc.status_code == 404:
code = "not_found"
message = "Not found"
else:
code = "invalid_request"
message = "Invalid request"
return JSONResponse(
status_code=exc.status_code,
content={
"error": {
"code": code,
"message": message,
"request_id": request_id,
}
},
headers=exc.headers,
)
@app.exception_handler(Exception)
async def unexpected_exception_handler(
request: Request,
exc: Exception,
):
request_id = request.state.request_id
return JSONResponse(
status_code=500,
content={
"error": {
"code": "internal_error",
"message": "Internal server error",
"request_id": request_id,
}
},
)
@app.get("/health/live")
async def health_live():
return {"status": "ok"}
@app.get("/health/ready")
async def health_ready():
database_ready = await ping_database()
session_store_ready = await ping_session_store()
if not database_ready or not session_store_ready:
raise APIError(
status_code=503,
code="unavailable",
message="Service dependencies unavailable",
)
return {"status": "ok"}
@app.post("/api/v1/users", response_model=User, status_code=201)
async def create_user(
data: CreateUser,
session: AsyncSession = Depends(get_db_session),
):
try:
async with session.begin():
return await create_user_in_db(session, data)
except IntegrityError as exc:
raise APIError(
status_code=409,
code="conflict",
message="Username already exists",
) from exc
@app.get("/api/v1/users/me", response_model=User)
async def get_me(
current_user: User = Depends(get_current_user),
):
return current_user
@app.post(
"/api/v1/auth/sessions",
response_model=SessionResponse,
status_code=201,
)
async def create_auth_session(
authorization: str | None = Header(default=None),
session: AsyncSession = Depends(get_db_session),
):
credentials = None
if authorization is not None:
scheme, separator, encoded = authorization.partition(" ")
if separator and scheme.lower() == "basic":
try:
decoded = base64.b64decode(encoded.strip(), validate=True).decode("utf-8")
if ":" in decoded:
credentials = decoded.split(":", 1)
except (ValueError, UnicodeError, binascii.Error):
pass
if credentials is None:
raise APIError(
status_code=401,
code="unauthorized",
message="Unauthorized",
headers={
"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"',
},
)
user_credentials = await get_user_credentials_by_username(
session,
credentials[0],
)
if user_credentials is None:
raise APIError(
status_code=401,
code="unauthorized",
message="Unauthorized",
headers={
"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"',
},
)
if not verify_password(
user_credentials.password_hash,
credentials[1],
):
raise APIError(
status_code=401,
code="unauthorized",
message="Unauthorized",
headers={
"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"',
},
)
user = User(
id=user_credentials.id,
username=user_credentials.username,
display_name=user_credentials.display_name,
created_at=user_credentials.created_at,
)
token, ttl = await create_session(user.id)
expires_at = datetime.now(timezone.utc) + timedelta(seconds=ttl)
return SessionResponse(
token=token,
token_type="Bearer",
expires_at=expires_at,
user=user,
)
@app.delete(
"/api/v1/auth/sessions/current",
status_code=204,
)
async def delete_current_session(
credentials: HTTPAuthorizationCredentials | None = Depends(bearer_security),
current_user: User = Depends(get_current_user),
):
await delete_session(credentials.credentials)
@app.post(
"/api/v1/chats",
response_model=Chat,
status_code=201,
)
async def create_chat_endpoint(
data: CreateChat,
current_user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_db_session),
) -> Chat:
try:
chat = await create_chat(
session=session,
data=data,
current_user_id=current_user.id,
)
await session.commit()
except Exception:
await session.rollback()
raise
return chat
@app.get(
"/api/v1/chats",
response_model=ChatPage,
)
async def get_chats(
limit: int = 50,
cursor: str | None = None,
current_user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_db_session),
) -> ChatPage:
if limit < 1 or limit > 100:
raise APIError(
status_code=400,
code="invalid_request",
message="Limit must be between 1 and 100",
)
return await list_chats(
session=session,
current_user_id=current_user.id,
limit=limit,
cursor=cursor,
)
@app.get(
"/api/v1/chats/{chat_id}",
response_model=Chat,
)
async def get_chat_endpoint(
chat_id: UUID,
current_user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_db_session),
) -> Chat:
chat = await get_chat_by_id(
session=session,
chat_id=chat_id,
current_user_id=current_user.id,
)
if chat is None:
raise APIError(
status_code=404,
code="not_found",
message="Chat not found",
)
return chat
@app.post(
"/api/v1/chats/{chat_id}/messages",
response_model=Message,
status_code=201,
)
async def create_message_endpoint(
chat_id: UUID,
data: CreateMessage,
idempotency_key: str | None = Header(
default=None,
alias="Idempotency-Key",
),
current_user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_db_session),
) -> Message:
if (
idempotency_key is None
or re.fullmatch(
r"[A-Za-z0-9._:-]{1,128}",
idempotency_key,
) is None
):
raise APIError(
status_code=400,
code="invalid_request",
message="Invalid or missing Idempotency-Key",
)
try:
message = await create_message(
session=session,
chat_id=chat_id,
current_user_id=current_user.id,
data=data,
idempotency_key=idempotency_key,
)
await session.commit()
except Exception:
await session.rollback()
raise
return message
@app.get(
"/api/v1/chats/{chat_id}/messages",
response_model=MessagePage,
)
async def get_messages_endpoint(
chat_id: UUID,
limit: int = 50,
cursor: str | None = None,
current_user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_db_session),
) -> MessagePage:
if limit < 1 or limit > 100:
raise APIError(
status_code=400,
code="invalid_request",
message="Limit must be between 1 and 100",
)
return await get_messages(
session=session,
chat_id=chat_id,
current_user_id=current_user.id,
limit=limit,
cursor=cursor,
)
@app.post(
"/api/v1/chats/{chat_id}/attachments",
response_model=Attachment,
status_code=201,
)
async def upload_attachment_endpoint(
chat_id: UUID,
request: Request,
filename: str = Query(min_length=1, max_length=255),
current_user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_db_session),
) -> Attachment:
chat = await get_chat_by_id(
session=session,
chat_id=chat_id,
current_user_id=current_user.id,
)
if chat is None:
raise APIError(
status_code=404,
code="not_found",
message="Chat not found",
)
content_type = request.headers.get("content-type", "").split(";", 1)[0].strip().lower()
if content_type not in {"image/png", "image/jpeg"}:
raise APIError(
status_code=415,
code="unsupported_media_type",
message="Only PNG and JPEG images are supported",
)
body = bytearray()
async for chunk in request.stream():
if len(body) + len(chunk) > MAX_UPLOAD_BYTES:
raise APIError(
status_code=413,
code="payload_too_large",
message="Image exceeds maximum upload size",
)
body.extend(chunk)
image_bytes = bytes(body)
size_bytes, sha256 = validate_image(image_bytes, content_type)
attachment_id = uuid4()
extension = "png" if content_type == "image/png" else "jpg"
s3_key = f"attachments/{chat_id}/{attachment_id}.{extension}"
try:
await put_object(
key=s3_key,
body=image_bytes,
content_type=content_type,
)
except (BotoCoreError, ClientError, OSError, TimeoutError) as exc:
raise APIError(
status_code=503,
code="unavailable",
message="Object storage unavailable",
) from exc
try:
attachment = await create_attachment(
session=session,
attachment_id=attachment_id,
chat_id=chat_id,
owner_id=current_user.id,
filename=filename,
content_type=content_type,
size_bytes=size_bytes,
sha256=sha256,
s3_key=s3_key,
)
await session.commit()
except BaseException:
try:
await session.rollback()
except Exception:
pass
try:
async with SessionFactory() as verification_session:
exists = await attachment_key_exists(
verification_session,
s3_key,
)
except Exception:
exists = True
if not exists:
try:
await asyncio.shield(delete_object(s3_key))
except Exception:
pass
raise
return attachment
@app.get(
"/api/v1/attachments/{attachment_id}",
response_model=Attachment,
)
async def get_attachment_endpoint(
attachment_id: UUID,
current_user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_db_session),
) -> Attachment:
result = await get_attachment(
session=session,
attachment_id=attachment_id,
current_user_id=current_user.id,
)
if result is None:
raise APIError(
status_code=404,
code="not_found",
message="Attachment not found",
)
attachment, s3_key = result
return attachment
@app.get("/api/v1/attachments/{attachment_id}/content")
async def get_attachment_content_endpoint(
attachment_id: UUID,
current_user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_db_session),
):
result = await get_attachment(
session=session,
attachment_id=attachment_id,
current_user_id=current_user.id,
)
if result is None:
raise APIError(
status_code=404,
code="not_found",
message="Attachment not found",
)
attachment, s3_key = result
try:
body = await get_object(s3_key)
except (BotoCoreError, ClientError, OSError, TimeoutError) as exc:
raise APIError(
status_code=503,
code="unavailable",
message="Object storage unavailable",
) from exc
return Response(
content=body,
media_type=attachment.content_type,
headers={
"Cache-Control": "private, no-store",
"X-Content-Type-Options": "nosniff",
},
)