Done Track 4
This commit is contained in:
+103
-5
@@ -1,17 +1,26 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from collections.abc import AsyncIterator
|
||||
from contextlib import asynccontextmanager
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import Depends, FastAPI, Header, Request, Response, Security
|
||||
from typing import Literal
|
||||
|
||||
from fastapi import Depends, FastAPI, Header, Query, Request, Response, Security
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from fastapi.responses import JSONResponse, StreamingResponse
|
||||
from sqlalchemy import exc as sa_exc
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.attachments import (
|
||||
get_attachment,
|
||||
janitor_loop,
|
||||
open_attachment_content,
|
||||
upload_attachment,
|
||||
)
|
||||
from app.cache import session_cache
|
||||
from app.db import check_database_ready, engine, get_db
|
||||
from app.deps import basic_scheme, pagination_params, require_user
|
||||
@@ -25,6 +34,7 @@ from app.errors import (
|
||||
)
|
||||
from app.lifecycle import draining
|
||||
from app.models import (
|
||||
Attachment,
|
||||
Chat,
|
||||
ChatPage,
|
||||
CreateChat,
|
||||
@@ -36,6 +46,7 @@ from app.models import (
|
||||
Session,
|
||||
User,
|
||||
)
|
||||
from app.storage import storage
|
||||
from app.services import (
|
||||
create_chat,
|
||||
create_message,
|
||||
@@ -50,14 +61,19 @@ from app.services import (
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
|
||||
await storage.start()
|
||||
janitor = asyncio.create_task(janitor_loop())
|
||||
yield
|
||||
janitor.cancel()
|
||||
await asyncio.gather(janitor, return_exceptions=True)
|
||||
await storage.close()
|
||||
await session_cache.close()
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="MTUSI Messenger — лабораторная 3",
|
||||
version="1.3.0",
|
||||
title="MTUSI Messenger — лабораторная 4",
|
||||
version="1.4.0",
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
@@ -185,6 +201,9 @@ async def liveness() -> dict[str, str]:
|
||||
async def readiness() -> dict[str, str]:
|
||||
# A draining replica reports "not ready" so HAProxy stops sending new
|
||||
# requests to it before the listener is closed.
|
||||
# S3 is deliberately NOT checked: without it only attachments degrade
|
||||
# (503), users/chats/messages keep working. If readiness depended on S3,
|
||||
# an S3 outage would take every replica out of the LB.
|
||||
if draining.is_set() or not await check_database_ready():
|
||||
raise Unavailable()
|
||||
|
||||
@@ -331,6 +350,7 @@ async def create_message_route(
|
||||
db,
|
||||
chat_id=chat_id,
|
||||
text_value=payload.text,
|
||||
attachment_ids=payload.attachment_ids,
|
||||
idempotency_key=idempotency_key,
|
||||
current_user=current_user,
|
||||
)
|
||||
@@ -359,4 +379,82 @@ async def list_messages_route(
|
||||
limit=limit,
|
||||
cursor=cursor,
|
||||
current_user=current_user,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
UPLOAD_BODY = {
|
||||
"requestBody": {
|
||||
"required": True,
|
||||
"description": "Raw image bytes, not multipart and not JSON/base64.",
|
||||
"content": {
|
||||
"image/png": {"schema": {"type": "string", "format": "binary"}},
|
||||
"image/jpeg": {"schema": {"type": "string", "format": "binary"}},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@app.post(
|
||||
"/api/v1/chats/{chat_id}/attachments",
|
||||
status_code=201,
|
||||
response_model=Attachment,
|
||||
openapi_extra=UPLOAD_BODY,
|
||||
)
|
||||
async def upload_attachment_route(
|
||||
chat_id: UUID,
|
||||
request: Request,
|
||||
filename: str = Query(min_length=1, max_length=255),
|
||||
current_user: dict = Depends(require_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
return await upload_attachment(
|
||||
request,
|
||||
db,
|
||||
chat_id=chat_id,
|
||||
filename=filename,
|
||||
current_user=current_user,
|
||||
)
|
||||
|
||||
|
||||
@app.get(
|
||||
"/api/v1/attachments/{attachment_id}",
|
||||
response_model=Attachment,
|
||||
)
|
||||
async def get_attachment_route(
|
||||
attachment_id: UUID,
|
||||
current_user: dict = Depends(require_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
return await get_attachment(
|
||||
db,
|
||||
attachment_id=attachment_id,
|
||||
current_user=current_user,
|
||||
)
|
||||
|
||||
|
||||
@app.get(
|
||||
"/api/v1/attachments/{attachment_id}/content",
|
||||
response_class=StreamingResponse,
|
||||
responses={200: {"content": {"image/png": {}, "image/jpeg": {}}}},
|
||||
)
|
||||
async def download_attachment_route(
|
||||
attachment_id: UUID,
|
||||
# Known variant names are accepted so that a ready attachment without
|
||||
# that variant answers 404 (contract); any other value is 400.
|
||||
variant: Literal["original", "thumbnail", "crop", "optimized"] = Query(
|
||||
default="original"
|
||||
),
|
||||
current_user: dict = Depends(require_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
chunks, headers = await open_attachment_content(
|
||||
db,
|
||||
attachment_id=attachment_id,
|
||||
variant=variant,
|
||||
current_user=current_user,
|
||||
)
|
||||
return StreamingResponse(
|
||||
chunks,
|
||||
media_type=headers.pop("Content-Type"),
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user