feat: implement S3 attachments and presigned uploads

This commit is contained in:
sinveria
2026-11-10 12:08:50 +03:00
parent aaa834e412
commit d96d4a2836
50 changed files with 3138 additions and 72 deletions
+66
View File
@@ -0,0 +1,66 @@
"""Best-effort cleanup for abandoned presigned uploads."""
import logging
from datetime import datetime, timedelta, timezone
from sqlalchemy import select
from app.core.config import settings
from app.db.models import AttachmentUpload
from app.db.session import SessionLocal
from app.services.object_storage import client
logger = logging.getLogger(__name__)
def cleanup_expired_uploads() -> int:
"""Delete old pending objects and mark their upload records expired.
A grace period protects clients completing an upload near URL expiry.
PostgreSQL SKIP LOCKED makes this safe across multiple API replicas.
"""
cutoff = datetime.now(timezone.utc) - timedelta(
seconds=settings.attachment_cleanup_grace_seconds
)
deleted_count = 0
with SessionLocal() as db:
uploads = db.scalars(
select(AttachmentUpload)
.where(
AttachmentUpload.status == "pending",
AttachmentUpload.expires_at <= cutoff,
)
.order_by(AttachmentUpload.expires_at.asc())
.limit(settings.attachment_cleanup_batch_size)
.with_for_update(skip_locked=True)
).all()
if not uploads:
return 0
s3 = client()
try:
for upload in uploads:
# DeleteObject is idempotent: a missing object is also safe.
s3.delete_object(
Bucket=settings.s3_bucket,
Key=upload.object_key,
)
upload.status = "expired"
deleted_count += 1
db.commit()
except Exception:
db.rollback()
logger.exception(
"Attachment cleanup batch failed; pending records will be retried"
)
return 0
if deleted_count:
logger.info(
"Expired abandoned attachment uploads cleaned: count=%d",
deleted_count,
)
return deleted_count
+41
View File
@@ -0,0 +1,41 @@
from io import BytesIO
from PIL import Image, UnidentifiedImageError
from fastapi import HTTPException
MAX_BYTES = 10 * 1024 * 1024
MAX_PIXELS = 40_000_000
ALLOWED = {"PNG": "image/png", "JPEG": "image/jpeg"}
def validate_image_file(fileobj, declared_type: str):
"""Validate a seekable, size-limited file without loading its full encoded bytes."""
try:
fileobj.seek(0)
with Image.open(fileobj) as image:
fmt = image.format
width, height = image.size
if fmt not in ALLOWED:
raise HTTPException(415, "Only PNG and JPEG are supported")
if width * height > MAX_PIXELS:
raise HTTPException(413, "Image exceeds 40 million pixels")
image.verify()
fileobj.seek(0)
with Image.open(fileobj) as image:
image.load()
except HTTPException:
raise
except (UnidentifiedImageError, OSError, ValueError, SyntaxError, Image.DecompressionBombError):
raise HTTPException(415, "Invalid or corrupted image") from None
actual_type = ALLOWED[fmt]
if declared_type != actual_type:
raise HTTPException(415, "Content-Type does not match image content")
fileobj.seek(0)
return actual_type, width, height
def validate_image(data: bytes, declared_type: str):
if not data:
raise HTTPException(415, "Empty image")
if len(data) > MAX_BYTES:
raise HTTPException(413, "Image exceeds 10 MiB")
return validate_image_file(BytesIO(data), declared_type)
+22 -5
View File
@@ -15,7 +15,7 @@ from sqlalchemy.dialects.postgresql import insert as pg_insert
from sqlalchemy.orm import Session
from app.core.config import settings
from app.db.models import IdempotencyRecord, Message
from app.db.models import Attachment, IdempotencyRecord, Message
from app.repositories.chat_repository import ChatRepository
from app.repositories.message_repository import MessageRepository
@@ -137,6 +137,7 @@ class MessageService:
"chat_id": str(message.chat_id),
"sender_id": str(message.sender_id),
"text": message.text,
"attachment_ids": message.attachment_ids or [],
"created_at": message.created_at.isoformat(),
}
for message in messages
@@ -154,6 +155,7 @@ class MessageService:
chat_id=uuid.UUID(item["chat_id"]),
sender_id=uuid.UUID(item["sender_id"]),
text=item["text"],
attachment_ids=item.get("attachment_ids", []),
created_at=datetime.fromisoformat(item["created_at"]),
)
for item in data["items"]
@@ -210,19 +212,34 @@ class MessageService:
sender_id: uuid.UUID,
text: str,
idempotency_key: str,
attachment_ids: list[str] | None = None,
) -> Message:
text = text.strip()
if not text or len(text) > 4000:
attachment_ids = attachment_ids or []
if (not text and not attachment_ids) or len(text) > 4000 or len(attachment_ids) > 10:
raise InvalidMessageDataError("Invalid message text")
# Access is checked for every retry, before consulting the key.
if not self.chats.is_member(chat_id, sender_id):
raise MessageNotFoundError()
if len(attachment_ids) != len(set(attachment_ids)):
raise InvalidMessageDataError("Duplicate attachment IDs")
if attachment_ids:
try:
parsed_attachment_ids = [uuid.UUID(value) for value in attachment_ids]
except (ValueError, TypeError):
raise InvalidMessageDataError("Invalid attachment UUID") from None
attachments = list(self.db.scalars(select(Attachment).where(Attachment.id.in_(parsed_attachment_ids))).all())
if len(attachments) != len(parsed_attachment_ids) or any(a.chat_id != chat_id for a in attachments):
raise MessageNotFoundError()
if any(a.status != "ready" for a in attachments):
raise InvalidMessageDataError("Attachment is not ready")
method = "POST"
path = f"/api/v1/chats/{chat_id}/messages"
request_hash = hashlib.sha256(
json.dumps({"text": text}, sort_keys=True, separators=(",", ":")).encode("utf-8")
json.dumps({"text": text, "attachment_ids": attachment_ids}, sort_keys=True, separators=(",", ":")).encode("utf-8")
).hexdigest()
now = datetime.now(timezone.utc)
expires_at = now + timedelta(seconds=max(settings.idempotency_ttl_seconds, 86400))
@@ -258,7 +275,7 @@ class MessageService:
if existing is None:
# Rare expiration race: retry once in a fresh transaction.
self.db.rollback()
return self.create_message(chat_id, sender_id, text, idempotency_key)
return self.create_message(chat_id, sender_id, text, idempotency_key, attachment_ids)
if existing.request_hash != request_hash:
self.db.rollback()
raise IdempotencyConflictError()
@@ -271,7 +288,7 @@ class MessageService:
return message
message = self.messages.create(
chat_id=chat_id, sender_id=sender_id, text=text
chat_id=chat_id, sender_id=sender_id, text=text, attachment_ids=attachment_ids
)
self.db.execute(
update(IdempotencyRecord)
+39
View File
@@ -0,0 +1,39 @@
import boto3
from botocore.config import Config
from app.core.config import settings
def client(endpoint_url=None):
return boto3.client(
"s3", endpoint_url=endpoint_url or settings.s3_endpoint_url,
aws_access_key_id=settings.s3_access_key,
aws_secret_access_key=settings.s3_secret_key,
region_name=settings.s3_region,
config=Config(signature_version="s3v4", connect_timeout=3, read_timeout=15, retries={"max_attempts": 2}, s3={"addressing_style": "path"}),
)
def ensure_bucket() -> None:
s3 = client()
try:
s3.head_bucket(Bucket=settings.s3_bucket)
except Exception:
s3.create_bucket(Bucket=settings.s3_bucket)
def presigned_client():
return client(endpoint_url=settings.s3_public_endpoint_url)
def create_presigned_upload_url(object_key: str, content_type: str) -> str:
s3 = presigned_client()
return s3.generate_presigned_url(
ClientMethod="put_object",
Params={
"Bucket": settings.s3_bucket,
"Key": object_key,
"ContentType": content_type,
},
ExpiresIn=settings.presigned_upload_ttl_seconds,
)