Files
mtusi2026lab4-fork/src/routes/attachments.py
T

140 lines
6.7 KiB
Python

"""Bounded synchronous image uploads; one decode per process."""
import asyncio
import hashlib
import tempfile
import unicodedata
import uuid
import warnings
from PIL import Image, UnidentifiedImageError
from fastapi import APIRouter, Depends, HTTPException, Request
from starlette.concurrency import run_in_threadpool
from starlette.responses import StreamingResponse
from starlette.requests import ClientDisconnect
from src.routes.common import require_user, make_error, get_request_id
from src.storage import storage, timestamp
from src.objects import client, BUCKET, object_lock
router = APIRouter()
slots = asyncio.Semaphore(1)
MAX_BYTES=10*1024*1024
Image.MAX_IMAGE_PIXELS=40_000_000
class InvalidImage(Exception):
def __init__(self,status):
self.status=status
def error(request, status, code, message):
return HTTPException(status, detail=make_error(code,message,get_request_id(request)).model_dump())
def inspect_image(stream, declared):
try:
with warnings.catch_warnings():
warnings.simplefilter('error', Image.DecompressionBombWarning)
with Image.open(stream) as image:
if image.width*image.height>40_000_000:
raise InvalidImage(413)
actual={'PNG':'image/png','JPEG':'image/jpeg'}.get(image.format)
if not actual or actual != declared:
raise InvalidImage(415)
image.verify()
stream.seek(0)
with Image.open(stream) as image:
image.load()
except (Image.DecompressionBombError,Image.DecompressionBombWarning):
raise InvalidImage(413) from None
except (UnidentifiedImageError,OSError,SyntaxError,ValueError):
raise InvalidImage(415) from None
finally:
stream.seek(0)
def metadata(row):
return {k: str(row[k]) for k in ('id','chat_id','owner_id')} | {
k:row[k] for k in ('filename','content_type','size_bytes','sha256')} | {
'status':'ready','variants':[],'error_code':None,
'created_at':timestamp(row['created_at']),'updated_at':timestamp(row['updated_at'])}
def save(stream, chat_id, owner, filename, content_type, size, digest):
attachment_id=uuid.uuid4()
key='originals/'+str(attachment_id)
# Keep this lock through S3 PUT and DB COMMIT/ROLLBACK. Reconciler shares it.
with storage.pool.connection() as conn:
object_lock(conn,key)
client().put_object(Bucket=BUCKET,Key=key,Body=stream,ContentLength=size,
ContentType=content_type,Metadata={'sha256':digest},IfNoneMatch='*')
row=conn.execute("INSERT INTO attachments(id,chat_id,owner_id,object_key,filename,content_type,size_bytes,sha256,state) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,'ready') RETURNING *",
(attachment_id,chat_id,owner,key,filename,content_type,size,digest)).fetchone()
# Never blindly delete after ambiguous COMMIT: grace-period reconciliation handles it.
return metadata(row)
@router.post('/api/v1/chats/{chat_id}/attachments',status_code=201)
async def upload(request:Request,chat_id:uuid.UUID,filename:str='',actor:str=Depends(require_user)):
if not await run_in_threadpool(storage.is_chat_member,str(chat_id),actor):
raise error(request,404,'not_found','chat not found')
if not 1<=len(filename)<=255 or any(c in '/\\' or unicodedata.category(c)=='Cc' for c in filename):
raise error(request,400,'invalid_request','invalid filename')
mime=request.headers.get('content-type','').lower()
if mime not in ('image/png','image/jpeg'):
raise error(request,415,'unsupported_media_type','PNG/JPEG required')
length=request.headers.get('content-length')
if length is not None:
if not length.isdecimal():
raise error(request,400,'invalid_request','invalid length')
if int(length)>MAX_BYTES:
raise error(request,413,'payload_too_large','limit 10 MiB')
try:
await asyncio.wait_for(slots.acquire(),timeout=25)
except asyncio.TimeoutError:
raise error(request,503,'unavailable','upload queue busy') from None
try:
with tempfile.TemporaryFile() as stream:
size=0; digest=hashlib.sha256()
async def receive():
nonlocal size
async for chunk in request.stream():
size+=len(chunk)
if size>MAX_BYTES:
raise error(request,413,'payload_too_large','limit 10 MiB')
digest.update(chunk)
await run_in_threadpool(stream.write,chunk)
try:
await asyncio.wait_for(receive(),timeout=20)
await run_in_threadpool(stream.seek,0)
await run_in_threadpool(inspect_image,stream,mime)
except ClientDisconnect:
raise error(request,400,'invalid_request','upload disconnected') from None
except asyncio.TimeoutError:
raise error(request,400,'invalid_request','upload timed out') from None
except InvalidImage as exc:
raise error(request,exc.status,'payload_too_large' if exc.status==413 else 'unsupported_media_type','invalid image') from None
return await run_in_threadpool(save,stream,str(chat_id),actor,filename,mime,size,digest.hexdigest())
finally:
slots.release()
def accessible(request,attachment_id,actor):
with storage.pool.connection() as conn:
row=conn.execute('SELECT a.* FROM attachments a JOIN chat_members m ON a.chat_id=m.chat_id WHERE a.id=%s AND m.user_id=%s',(attachment_id,actor)).fetchone()
if not row:
raise error(request,404,'not_found','attachment not found')
if row['state']!='ready':
raise error(request,503,'unavailable','original temporarily unavailable')
return row
@router.get('/api/v1/attachments/{attachment_id}')
def get_attachment(request:Request,attachment_id:uuid.UUID,actor:str=Depends(require_user)):
return metadata(accessible(request,attachment_id,actor))
@router.get('/api/v1/attachments/{attachment_id}/content')
def content(request:Request,attachment_id:uuid.UUID,variant:str='original',actor:str=Depends(require_user)):
row=accessible(request,attachment_id,actor)
if variant not in ('original','thumbnail','crop','optimized'):
raise error(request,400,'invalid_request','invalid variant')
if variant!='original':
raise error(request,404,'not_found','variant not found')
obj=client().get_object(Bucket=BUCKET,Key=row['object_key'])
def chunks():
try:
yield from obj['Body'].iter_chunks(chunk_size=64*1024)
finally:
obj['Body'].close()
return StreamingResponse(chunks(),media_type=row['content_type'],headers={'Content-Length':str(row['size_bytes'])})