лаба 4

This commit is contained in:
2026-10-29 02:56:13 +03:00
parent f3bcdad9e8
commit 0ef8d739d7
19 changed files with 1900 additions and 58 deletions
+71
View File
@@ -0,0 +1,71 @@
import hashlib
import io
import os
from PIL import Image, UnidentifiedImageError
from src.errors import APIError
MAX_UPLOAD_BYTES = int(os.getenv("MAX_UPLOAD_BYTES", "10485760"))
MAX_IMAGE_PIXELS = int(os.getenv("MAX_IMAGE_PIXELS", "40000000"))
ALLOWED_FORMATS = {
"PNG": "image/png",
"JPEG": "image/jpeg",
}
def validate_image(body: bytes, content_type: str) -> tuple[int, str]:
if content_type not in ALLOWED_FORMATS.values():
raise APIError(
status_code=415,
code="unsupported_media_type",
message="Only PNG and JPEG images are supported",
)
size_bytes = len(body)
if size_bytes > MAX_UPLOAD_BYTES:
raise APIError(
status_code=413,
code="payload_too_large",
message="Image exceeds maximum upload size",
)
if size_bytes == 0:
raise APIError(
status_code=400,
code="invalid_request",
message="Image must not be empty",
)
try:
with Image.open(io.BytesIO(body)) as image:
if image.format not in ALLOWED_FORMATS:
raise ValueError("Unsupported image format")
if ALLOWED_FORMATS[image.format] != content_type:
raise ValueError("Content-Type does not match image format")
width, height = image.size
if width * height > MAX_IMAGE_PIXELS:
raise APIError(
status_code=413,
code="payload_too_large",
message="Image exceeds maximum pixel count",
)
image.load()
except APIError:
raise
except (UnidentifiedImageError, OSError, ValueError, Image.DecompressionBombError) as exc:
raise APIError(
status_code=400,
code="invalid_request",
message="Invalid image data",
) from exc
return size_bytes, hashlib.sha256(body).hexdigest()
+201 -5
View File
@@ -4,22 +4,24 @@ import os
import re
import base64
import binascii
import asyncio
from fastapi import Depends, FastAPI, Request, Header
from fastapi import Depends, FastAPI, Request, Header, Query
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
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
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
from src.models import CreateUser, SessionResponse, User, CreateChat, Chat, ChatPage, CreateMessage, Message, MessagePage, Attachment
from src.repositories import (
create_chat,
list_chats,
@@ -29,6 +31,9 @@ from src.repositories import (
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 (
@@ -38,6 +43,8 @@ from src.sessions import (
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
@@ -105,7 +112,21 @@ async def request_middleware(request: Request, call_next):
if content_type is not None:
media_type = content_type.split(";", 1)[0].strip().lower()
if media_type != "application/json":
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={
@@ -526,3 +547,178 @@ async def get_messages_endpoint(
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",
},
)
+44 -10
View File
@@ -1,7 +1,7 @@
from datetime import datetime
from uuid import UUID
from pydantic import BaseModel, ConfigDict, Field, field_validator
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
class CreateUser(BaseModel):
@@ -91,19 +91,24 @@ class ChatPage(BaseModel):
class CreateMessage(BaseModel):
model_config = ConfigDict(extra="forbid")
text: str = Field(
min_length=1,
max_length=4000,
)
text: str = Field(max_length=4000)
attachment_ids: list[UUID] = Field(default_factory=list, max_length=10)
@field_validator("text")
@field_validator("attachment_ids")
@classmethod
def validate_text(cls, value: str) -> str:
if not value.strip():
raise ValueError("Message text must not be blank")
def validate_attachment_ids(cls, value: list[UUID]) -> list[UUID]:
if len(value) != len(set(value)):
raise ValueError("Attachment IDs must be unique")
return value
@model_validator(mode="after")
def validate_content(self):
if not self.text.strip() and not self.attachment_ids:
raise ValueError("Message must contain text or attachments")
return self
class Message(BaseModel):
id: UUID
@@ -111,8 +116,37 @@ class Message(BaseModel):
sender_id: UUID
text: str
created_at: datetime
attachment_ids: list[UUID] = Field(default_factory=list)
class MessagePage(BaseModel):
items: list[Message]
next_cursor: str | None
next_cursor: str | None
class Variant(BaseModel):
model_config = ConfigDict(extra="forbid")
name: str = Field(pattern=r"^(thumbnail|crop|optimized)$")
content_type: str = Field(pattern=r"^image/(jpeg|png|webp)$")
size_bytes: int = Field(ge=1)
width: int = Field(ge=1)
height: int = Field(ge=1)
sha256: str = Field(pattern=r"^[a-f0-9]{64}$")
class Attachment(BaseModel):
model_config = ConfigDict(extra="forbid")
id: UUID
chat_id: UUID
owner_id: UUID
filename: str = Field(min_length=1, max_length=255)
content_type: str = Field(pattern=r"^image/(png|jpeg)$")
size_bytes: int = Field(ge=1, le=10485760)
sha256: str = Field(pattern=r"^[a-f0-9]{64}$")
status: str = Field(pattern=r"^ready$")
variants: list[Variant]
error_code: str | None
created_at: datetime
updated_at: datetime
+223 -2
View File
@@ -5,7 +5,7 @@ import json
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession
from src.models import Chat, ChatPage, CreateChat, CreateUser, User, CreateMessage, Message, MessagePage
from src.models import Attachment, Chat, ChatPage, CreateChat, CreateUser, User, CreateMessage, Message, MessagePage
from src.security import hash_password
from src.errors import APIError
from src.cursor import decode_cursor, encode_cursor, decode_chat_cursor, encode_chat_cursor
@@ -367,7 +367,10 @@ async def create_message(
)
canonical_body = json.dumps(
{"text": data.text},
{
"text": data.text,
"attachment_ids": [str(attachment_id) for attachment_id in data.attachment_ids],
},
sort_keys=True,
ensure_ascii=False,
separators=(",", ":"),
@@ -444,14 +447,57 @@ async def create_message(
),
)
attachment_result = await session.execute(
text("""
SELECT attachment_id
FROM message_attachments
WHERE message_id = :message_id
ORDER BY attachment_id
"""),
{"message_id": existing.id},
)
attachment_ids = [
UUID(str(row.attachment_id))
for row in attachment_result.all()
]
return Message(
id=UUID(str(existing.id)),
chat_id=UUID(str(existing.chat_id)),
sender_id=UUID(str(existing.sender_id)),
text=existing.text,
created_at=existing.created_at,
attachment_ids=attachment_ids,
)
if data.attachment_ids:
attachments_result = await session.execute(
text("""
SELECT id
FROM attachments
WHERE id = ANY (:attachment_ids)
AND chat_id = :chat_id
AND status = 'ready'
"""),
{
"attachment_ids": data.attachment_ids,
"chat_id": chat_id,
},
)
valid_attachment_ids = {
UUID(str(row.id))
for row in attachments_result.all()
}
if valid_attachment_ids != set(data.attachment_ids):
raise APIError(
status_code=400,
code="invalid_request",
message="Invalid attachments for this chat",
)
message_id = uuid4()
message_result = await session.execute(
@@ -485,6 +531,20 @@ async def create_message(
row = message_result.one()
for attachment_id in data.attachment_ids:
await session.execute(
text("""
INSERT INTO message_attachments (message_id,
attachment_id)
VALUES (:message_id,
:attachment_id)
"""),
{
"message_id": message_id,
"attachment_id": attachment_id,
},
)
await session.execute(
text("""
INSERT INTO message_idempotency (
@@ -517,6 +577,7 @@ async def create_message(
sender_id=UUID(str(row.sender_id)),
text=row.text,
created_at=row.created_at,
attachment_ids=data.attachment_ids,
)
@@ -627,6 +688,29 @@ async def get_messages(
has_more = len(rows) > limit
rows = rows[:limit]
attachments_by_message = {}
if rows:
attachment_result = await session.execute(
text("""
SELECT message_id, attachment_id
FROM message_attachments
WHERE message_id = ANY(:message_ids)
ORDER BY message_id, attachment_id
"""),
{
"message_ids": [row.id for row in rows],
},
)
for attachment_row in attachment_result.all():
message_id = UUID(str(attachment_row.message_id))
attachment_id = UUID(str(attachment_row.attachment_id))
attachments_by_message.setdefault(
message_id, []
).append(attachment_id)
items = [
Message(
id=UUID(str(row.id)),
@@ -634,6 +718,9 @@ async def get_messages(
sender_id=UUID(str(row.sender_id)),
text=row.text,
created_at=row.created_at,
attachment_ids=attachments_by_message.get(
UUID(str(row.id)), []
),
)
for row in rows
]
@@ -653,3 +740,137 @@ async def get_messages(
items=items,
next_cursor=next_cursor,
)
def attachment_from_row(row) -> Attachment:
return Attachment(
id=UUID(str(row.id)),
chat_id=UUID(str(row.chat_id)),
owner_id=UUID(str(row.owner_id)),
filename=row.filename,
content_type=row.content_type,
size_bytes=row.size_bytes,
sha256=row.sha256,
status=row.status,
variants=row.variants,
error_code=row.error_code,
created_at=row.created_at,
updated_at=row.updated_at,
)
async def create_attachment(
session: AsyncSession,
attachment_id: UUID,
chat_id: UUID,
owner_id: UUID,
filename: str,
content_type: str,
size_bytes: int,
sha256: str,
s3_key: str,
) -> Attachment:
result = await session.execute(
text(
"""
INSERT INTO attachments (
id,
chat_id,
owner_id,
filename,
content_type,
size_bytes,
sha256,
s3_key,
status
)
VALUES (
:id,
:chat_id,
:owner_id,
:filename,
:content_type,
:size_bytes,
:sha256,
:s3_key,
'ready'
)
RETURNING
id,
chat_id,
owner_id,
filename,
content_type,
size_bytes,
sha256,
status,
variants,
error_code,
created_at,
updated_at
"""
),
{
"id": attachment_id,
"chat_id": chat_id,
"owner_id": owner_id,
"filename": filename,
"content_type": content_type,
"size_bytes": size_bytes,
"sha256": sha256,
"s3_key": s3_key,
},
)
return attachment_from_row(result.one())
async def get_attachment(
session: AsyncSession,
attachment_id: UUID,
current_user_id: UUID,
):
result = await session.execute(
text(
"""
SELECT
a.id,
a.chat_id,
a.owner_id,
a.filename,
a.content_type,
a.size_bytes,
a.sha256,
a.s3_key,
a.status,
a.variants,
a.error_code,
a.created_at,
a.updated_at
FROM attachments AS a
JOIN chat_members AS cm
ON cm.chat_id = a.chat_id
WHERE a.id = :attachment_id
AND cm.user_id = :current_user_id
AND a.status = 'ready'
"""
),
{
"attachment_id": attachment_id,
"current_user_id": current_user_id,
},
)
row = result.one_or_none()
if row is None:
return None
return attachment_from_row(row), row.s3_key
async def attachment_key_exists(session: AsyncSession, s3_key: str) -> bool:
result = await session.execute(
text("SELECT 1 FROM attachments WHERE s3_key = :s3_key"),
{"s3_key": s3_key},
)
return result.first() is not None
+71
View File
@@ -0,0 +1,71 @@
import asyncio
import os
from pathlib import Path
import boto3
from botocore.config import Config
def read_secret(env_name: str) -> str:
path = os.environ[env_name]
return Path(path).read_text(encoding="utf-8").strip()
s3_client = boto3.client(
"s3",
endpoint_url=os.environ["S3_ENDPOINT"],
region_name=os.getenv("S3_REGION", "us-east-1"),
aws_access_key_id=read_secret("S3_ACCESS_KEY_ID_FILE"),
aws_secret_access_key=read_secret("S3_SECRET_ACCESS_KEY_FILE"),
config=Config(
signature_version="s3v4",
connect_timeout=2,
read_timeout=3,
retries={"total_max_attempts": 1, "mode": "standard"},
s3={"addressing_style": "path"},
),
)
S3_BUCKET = os.environ["S3_BUCKET"]
async def put_object(key: str, body: bytes, content_type: str) -> None:
await asyncio.to_thread(
s3_client.put_object,
Bucket=S3_BUCKET,
Key=key,
Body=body,
ContentType=content_type,
)
async def get_object(key: str) -> bytes:
def download() -> bytes:
response = s3_client.get_object(Bucket=S3_BUCKET, Key=key)
stream = response["Body"]
try:
return stream.read()
finally:
stream.close()
return await asyncio.to_thread(download)
async def delete_object(key: str) -> None:
await asyncio.to_thread(
s3_client.delete_object,
Bucket=S3_BUCKET,
Key=key,
)
async def ping_storage() -> bool:
try:
await asyncio.to_thread(
s3_client.head_bucket,
Bucket=S3_BUCKET,
)
return True
except Exception:
return False