Complete lab 5 asynchronous image processing

This commit is contained in:
sinveria
2026-11-10 18:51:02 +03:00
parent 276dbdad8a
commit 115223f920
69 changed files with 7706 additions and 31 deletions
View File
+634
View File
@@ -0,0 +1,634 @@
import hashlib
import tempfile
import uuid
from datetime import datetime, timezone, timedelta
from urllib.parse import quote
from fastapi import APIRouter, Depends, Header, HTTPException, Query, Request, Response
from fastapi.responses import StreamingResponse
from sqlalchemy import select, func, text
from sqlalchemy.orm import Session
from botocore.exceptions import BotoCoreError, ClientError
from app.api.deps import get_db, get_current_user
from app.core.config import settings
from app.models import CreateAttachmentUpload
from app.db.models import (
Attachment,
AttachmentUpload,
AttachmentVariant,
ProcessingJob,
OutboxEvent,
User,
)
from app.services.object_storage import client, create_presigned_upload_url
from app.services.image_validation import MAX_BYTES, validate_image_file
from app.repositories.chat_repository import ChatRepository
router = APIRouter(prefix="/api/v1", tags=["Attachments"])
def iso_utc(value):
return value.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")
def attachment_json(item, db):
variants = db.scalars(
select(AttachmentVariant)
.where(AttachmentVariant.attachment_id == item.id)
.order_by(AttachmentVariant.variant)
).all()
return {
"id": str(item.id),
"chat_id": str(item.chat_id),
"owner_id": str(item.owner_id),
"filename": item.filename,
"content_type": item.content_type,
"size_bytes": item.size_bytes,
"sha256": item.sha256,
"status": item.status,
"variants": [
{
"name": variant.variant,
"content_type": variant.content_type,
"size_bytes": variant.size_bytes,
"width": variant.width,
"height": variant.height,
"sha256": variant.sha256,
}
for variant in variants
],
"error_code": item.error_code,
"created_at": iso_utc(item.created_at),
"updated_at": iso_utc(item.updated_at),
}
def member_attachment(db, attachment_id, user_id):
item = db.get(Attachment, attachment_id)
if item is None or not ChatRepository(db).is_member(item.chat_id, user_id):
raise HTTPException(404, "Attachment not found")
return item
async def read_limited(request: Request):
declared = request.headers.get("content-length")
if declared and declared.isdigit() and int(declared) > MAX_BYTES:
raise HTTPException(413, "Image exceeds 10 MiB")
size = 0
# Keep at most 1 MiB in RAM; larger bodies spill to a temporary file.
spool = tempfile.SpooledTemporaryFile(max_size=1024 * 1024, mode="w+b")
try:
async for chunk in request.stream():
size += len(chunk)
if size > MAX_BYTES:
raise HTTPException(413, "Image exceeds 10 MiB")
spool.write(chunk)
spool.seek(0)
return spool, size
except Exception:
spool.close()
raise
def sha256_file(fileobj):
digest = hashlib.sha256()
fileobj.seek(0)
while True:
chunk = fileobj.read(1024 * 1024)
if not chunk: break
digest.update(chunk)
fileobj.seek(0)
return digest.hexdigest()
@router.post("/chats/{chat_id}/attachments/presigned", status_code=201)
def create_attachment_upload(
chat_id: str,
payload: CreateAttachmentUpload,
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
):
try:
chat_uuid = uuid.UUID(chat_id)
except ValueError:
raise HTTPException(400, "Invalid chat UUID") from None
if not ChatRepository(db).is_member(chat_uuid, user.id):
raise HTTPException(404, "Chat not found")
if payload.size_bytes > settings.max_upload_bytes:
raise HTTPException(413, "Image exceeds configured upload limit")
upload_id = uuid.uuid4()
object_key = f"uploads/{chat_uuid}/{upload_id}"
expires_at = datetime.now(timezone.utc) + timedelta(
seconds=settings.presigned_upload_ttl_seconds
)
try:
upload_url = create_presigned_upload_url(
object_key=object_key,
content_type=payload.content_type,
)
except (BotoCoreError, ClientError):
raise HTTPException(503, "Object storage unavailable") from None
upload = AttachmentUpload(
id=upload_id,
chat_id=chat_uuid,
owner_id=user.id,
filename=payload.filename,
content_type=payload.content_type,
expected_size_bytes=payload.size_bytes,
expected_sha256=payload.sha256.lower(),
object_key=object_key,
status="pending",
expires_at=expires_at,
)
try:
db.add(upload)
db.commit()
except Exception:
db.rollback()
raise HTTPException(503, "Could not save upload metadata") from None
return {
"upload_id": str(upload_id),
"upload_url": upload_url,
"method": "PUT",
"headers": {
"Content-Type": payload.content_type,
},
"expires_in": settings.presigned_upload_ttl_seconds,
"expires_at": iso_utc(expires_at),
}
@router.post("/attachments/uploads/{upload_id}/complete", status_code=200)
def complete_attachment_upload(
upload_id: str,
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
):
try:
parsed_id = uuid.UUID(upload_id)
except ValueError:
raise HTTPException(400, "Invalid upload UUID") from None
# Lock the upload row to prevent concurrent completion.
upload = db.scalar(
select(AttachmentUpload)
.where(AttachmentUpload.id == parsed_id)
.with_for_update()
)
if upload is None:
raise HTTPException(404, "Upload not found")
if (
upload.owner_id != user.id
or not ChatRepository(db).is_member(upload.chat_id, user.id)
):
raise HTTPException(404, "Upload not found")
# Idempotent completion: return the existing attachment.
if upload.status == "completed":
item = db.scalar(
select(Attachment).where(
Attachment.object_key == upload.object_key
)
)
if item is None:
raise HTTPException(409, "Completed attachment not found")
return attachment_json(item, db)
if upload.status != "pending":
raise HTTPException(409, "Upload is not pending")
now = datetime.now(timezone.utc)
if upload.expires_at <= now:
upload.status = "expired"
db.commit()
try:
client().delete_object(
Bucket=settings.s3_bucket,
Key=upload.object_key,
)
except Exception:
pass
raise HTTPException(409, "Upload has expired")
s3 = client()
# Read the object from S3.
try:
result = s3.get_object(
Bucket=settings.s3_bucket,
Key=upload.object_key,
)
except ClientError as exc:
code = exc.response.get("Error", {}).get("Code", "")
if code in {"NoSuchKey", "404", "NotFound"}:
raise HTTPException(409, "Uploaded object not found") from None
raise HTTPException(503, "Object storage unavailable") from None
except BotoCoreError:
raise HTTPException(503, "Object storage unavailable") from None
body = result["Body"]
spool = tempfile.SpooledTemporaryFile(
max_size=1024 * 1024,
mode="w+b",
)
def reject_upload(status_code: int, detail: str):
upload.status = "failed"
db.commit()
try:
s3.delete_object(
Bucket=settings.s3_bucket,
Key=upload.object_key,
)
except Exception:
pass
raise HTTPException(status_code=status_code, detail=detail)
try:
actual_size = result.get("ContentLength")
if actual_size != upload.expected_size_bytes:
reject_upload(409, "Uploaded file size mismatch")
if actual_size > settings.max_upload_bytes:
reject_upload(413, "Image exceeds configured upload limit")
total = 0
digest = hashlib.sha256()
try:
while True:
chunk = body.read(64 * 1024)
if not chunk:
break
total += len(chunk)
if total > settings.max_upload_bytes:
reject_upload(413, "Image exceeds configured upload limit")
if total > upload.expected_size_bytes:
reject_upload(409, "Uploaded file size mismatch")
digest.update(chunk)
spool.write(chunk)
finally:
body.close()
if total != upload.expected_size_bytes:
reject_upload(409, "Uploaded file size mismatch")
if digest.hexdigest() != upload.expected_sha256:
reject_upload(409, "Uploaded file checksum mismatch")
# Validate the actual image content, not only S3 metadata.
try:
actual_type, _, _ = validate_image_file(
spool,
upload.content_type,
)
except HTTPException as exc:
reject_upload(exc.status_code, str(exc.detail))
attachment = Attachment(
id=uuid.uuid4(),
chat_id=upload.chat_id,
owner_id=upload.owner_id,
filename=upload.filename,
content_type=actual_type,
size_bytes=total,
sha256=digest.hexdigest(),
object_key=upload.object_key,
status="ready",
error_code=None,
)
upload.status = "completed"
upload.completed_at = now
db.add(attachment)
db.commit()
db.refresh(attachment)
return attachment_json(attachment, db)
except HTTPException:
raise
except (BotoCoreError, ClientError):
db.rollback()
raise HTTPException(503, "Object storage unavailable") from None
except Exception:
db.rollback()
raise
finally:
spool.close()
@router.post("/chats/{chat_id}/attachments", status_code=202)
async def upload_attachment(
chat_id: str,
request: Request,
filename: str = Query(..., min_length=1, max_length=255),
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
):
try:
chat_uuid = uuid.UUID(chat_id)
except ValueError:
raise HTTPException(400, "Invalid chat UUID") from None
if not ChatRepository(db).is_member(chat_uuid, user.id):
raise HTTPException(404, "Chat not found")
if (
not filename.strip()
or any(c in filename for c in ("/", "\\", "\x00"))
or any(ord(c) < 32 or ord(c) == 127 for c in filename)
):
raise HTTPException(400, "Unsafe filename")
content_type = (
request.headers.get("content-type", "")
.split(";", 1)[0]
.strip()
.lower()
)
if content_type not in {"image/png", "image/jpeg"}:
raise HTTPException(415, "Only PNG and JPEG are supported")
spool, size = await read_limited(request)
attachment_id = uuid.uuid4()
job_id = uuid.uuid4()
staging_key = f"staging/{chat_uuid}/{attachment_id}"
object_key = f"original/{chat_uuid}/{attachment_id}"
staged = False
try:
actual_type, _, _ = validate_image_file(spool, content_type)
digest = sha256_file(spool)
# Serialize admission checks across all API instances.
db.execute(
text("SELECT pg_advisory_xact_lock(:lock_id)"),
{"lock_id": 72420261110},
)
active_jobs = db.scalar(
select(func.count())
.select_from(ProcessingJob)
.where(ProcessingJob.status.in_(("queued", "processing")))
) or 0
if active_jobs >= settings.max_active_processing_jobs:
raise HTTPException(
status_code=429,
detail="Processing queue is full; retry later",
headers={"Retry-After": "5"},
)
s3 = client()
try:
spool.seek(0)
s3.put_object(
Bucket=settings.s3_bucket,
Key=staging_key,
Body=spool,
ContentType=actual_type,
)
staged = True
except (BotoCoreError, ClientError):
raise HTTPException(
503, "Object storage unavailable"
) from None
now = datetime.now(timezone.utc)
attachment = Attachment(
id=attachment_id,
chat_id=chat_uuid,
owner_id=user.id,
filename=filename,
content_type=actual_type,
size_bytes=size,
sha256=digest,
object_key=object_key,
staging_key=staging_key,
status="queued",
error_code=None,
pipeline_version=1,
)
job = ProcessingJob(
id=job_id,
attachment_id=attachment_id,
pipeline_version=1,
attempt=0,
status="queued",
available_at=now,
)
event = OutboxEvent(
event_type="attachment.process.v1",
aggregate_id=attachment_id,
payload={
"schema_version": 1,
"job_id": str(job_id),
"type": "attachment.process.v1",
"attachment_id": str(attachment_id),
"pipeline_version": 1,
"attempt": 1,
"created_at": now.isoformat(),
},
status="pending",
)
db.add_all([attachment, job, event])
db.commit()
db.refresh(attachment)
return attachment_json(attachment, db)
except HTTPException:
db.rollback()
if staged:
try:
client().delete_object(
Bucket=settings.s3_bucket,
Key=staging_key,
)
except Exception:
pass
raise
except Exception:
db.rollback()
if staged:
try:
client().delete_object(
Bucket=settings.s3_bucket,
Key=staging_key,
)
except Exception:
pass
raise HTTPException(
503, "Could not save attachment processing job"
) from None
finally:
spool.close()
@router.get("/attachments/{attachment_id}")
def get_attachment(attachment_id: str, db: Session = Depends(get_db), user: User = Depends(get_current_user)):
try: parsed = uuid.UUID(attachment_id)
except ValueError: raise HTTPException(400, "Invalid attachment UUID") from None
item = member_attachment(db, parsed, user.id)
return attachment_json(item, db)
@router.get("/attachments/{attachment_id}/content")
def download_attachment(
attachment_id: str,
variant: str = "original",
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
):
try:
parsed = uuid.UUID(attachment_id)
except ValueError:
raise HTTPException(400, "Invalid attachment UUID") from None
item = member_attachment(db, parsed, user.id)
if item.status != "ready":
raise HTTPException(409, "Attachment is not ready")
# Select the original file or a generated variant.
if variant == "original":
object_key = item.object_key
expected_size = item.size_bytes
expected_sha256 = item.sha256
content_type = item.content_type
else:
variant_item = db.scalar(
select(AttachmentVariant).where(
AttachmentVariant.attachment_id == item.id,
AttachmentVariant.variant == variant,
)
)
if variant_item is None:
raise HTTPException(404, "Variant not found")
object_key = variant_item.object_key
expected_size = variant_item.size_bytes
expected_sha256 = variant_item.sha256
content_type = variant_item.content_type
spool = tempfile.SpooledTemporaryFile(
max_size=1024 * 1024,
mode="w+b",
)
try:
result = client().get_object(
Bucket=settings.s3_bucket,
Key=object_key,
)
body = result["Body"]
total = 0
digest = hashlib.sha256()
try:
while True:
chunk = body.read(64 * 1024)
if not chunk:
break
total += len(chunk)
if total > MAX_BYTES:
raise HTTPException(
503,
"Stored object exceeds configured limit",
)
digest.update(chunk)
spool.write(chunk)
finally:
body.close()
# Verify stored object integrity.
if (
total != expected_size
or digest.hexdigest() != expected_sha256
):
raise HTTPException(
503,
"Stored object checksum mismatch",
)
spool.seek(0)
except (BotoCoreError, ClientError):
spool.close()
raise HTTPException(
503,
"Object storage unavailable",
) from None
except Exception:
spool.close()
raise
def stream_verified_file():
try:
while True:
chunk = spool.read(64 * 1024)
if not chunk:
break
yield chunk
finally:
spool.close()
return StreamingResponse(
stream_verified_file(),
media_type=content_type,
headers={
"Content-Disposition": (
f"inline; filename*=UTF-8''{quote(item.filename)}"
)
},
)
+96
View File
@@ -0,0 +1,96 @@
from datetime import timezone
from fastapi import APIRouter, Depends, Header, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from sqlalchemy.orm import Session
from app.api.deps import get_db
from app.api.users import user_to_response
from app.services.auth_service import (
AuthService,
InvalidCredentialsError,
InvalidSessionError,
)
router = APIRouter(prefix="/api/v1/auth", tags=["Authentication"])
basic_security = HTTPBasic(auto_error=False)
@router.post("/sessions", status_code=status.HTTP_201_CREATED)
def create_session(
credentials: HTTPBasicCredentials = Depends(basic_security),
db: Session = Depends(get_db),
):
if credentials is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Basic authentication required",
headers={
"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'
},
)
try:
result = AuthService(db).create_session(
username=credentials.username,
password=credentials.password,
)
expires_at = result["expires_at"]
if expires_at.tzinfo is None:
expires_at = expires_at.replace(tzinfo=timezone.utc)
else:
expires_at = expires_at.astimezone(timezone.utc)
return {
"token": result["token"],
"token_type": result["token_type"],
"expires_at": expires_at.isoformat(
timespec="microseconds"
).replace("+00:00", "Z"),
"user": user_to_response(result["user"]),
}
except InvalidCredentialsError:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid username or password",
headers={
"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'
},
) from None
@router.delete("/sessions/current", status_code=status.HTTP_204_NO_CONTENT)
def delete_current_session(
authorization: str | None = Header(default=None),
db: Session = Depends(get_db),
):
if not authorization or not authorization.startswith("Bearer "):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Bearer token required",
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
)
token = authorization[7:].strip()
if not token:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Bearer token required",
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
)
try:
AuthService(db).delete_session(token)
except InvalidSessionError:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid or expired session",
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
) from None
+90
View File
@@ -0,0 +1,90 @@
import uuid
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.orm import Session
from app.api.deps import get_db, get_current_user
from app.db.models import User as UserModel
from app.models import Chat as ChatResponse, CreateChat
from app.services.chat_service import (
ChatService,
ChatNotFoundError,
InvalidChatDataError,
)
router = APIRouter(prefix="/api/v1/chats", tags=["Chats"])
def chat_to_response(chat) -> ChatResponse:
return ChatResponse(
id=str(chat.id),
title=chat.title,
member_ids=[str(member.user_id) for member in chat.members],
created_at=chat.created_at,
)
@router.post("", response_model=ChatResponse, status_code=status.HTTP_201_CREATED)
def create_chat(
body: CreateChat,
db: Session = Depends(get_db),
user: UserModel = Depends(get_current_user),
):
try:
chat = ChatService(db).create_chat(
title=body.title,
member_ids=body.member_ids,
creator_id=user.id,
)
return chat_to_response(chat)
except InvalidChatDataError as exc:
raise HTTPException(
status_code=400,
detail=str(exc),
) from None
@router.get("")
def list_chats(
limit: int = Query(default=50, ge=1, le=100),
cursor: str | None = None,
db: Session = Depends(get_db),
user: UserModel = Depends(get_current_user),
):
if cursor is not None:
raise HTTPException(
status_code=400,
detail="Chat cursor pagination is not implemented yet",
)
chats = ChatService(db).list_chats(user.id)
chats = chats[:limit]
return {
"items": [chat_to_response(chat) for chat in chats],
"next_cursor": None,
}
@router.get("/{chat_id}", response_model=ChatResponse)
def get_chat(
chat_id: str,
db: Session = Depends(get_db),
user: UserModel = Depends(get_current_user),
):
try:
parsed_id = uuid.UUID(chat_id)
except ValueError:
raise HTTPException(status_code=400, detail="Invalid chat UUID") from None
try:
chat = ChatService(db).get_chat(parsed_id, user.id)
return chat_to_response(chat)
except ChatNotFoundError:
raise HTTPException(
status_code=404,
detail="Chat not found",
) from None
+40
View File
@@ -0,0 +1,40 @@
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from sqlalchemy.orm import Session
from app.db.session import SessionLocal
from app.services.auth_service import AuthService, InvalidSessionError
bearer_scheme = HTTPBearer(auto_error=False)
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
def get_current_user(
credentials: HTTPAuthorizationCredentials | None = Depends(bearer_scheme),
db: Session = Depends(get_db),
):
if credentials is None or credentials.scheme.lower() != "bearer":
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Bearer token required",
headers={"WWW-Authenticate": "Bearer"},
)
try:
user = AuthService(db).authenticate(credentials.credentials)
return user
except InvalidSessionError:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid or expired token",
headers={"WWW-Authenticate": "Bearer"},
) from None
+73
View File
@@ -0,0 +1,73 @@
import re
import uuid
from fastapi import APIRouter, Depends, Header, HTTPException, Query, status
from sqlalchemy.orm import Session
from app.api.deps import get_db, get_current_user
from app.db.models import User as UserModel
from app.models import CreateMessage, Message as MessageResponse
from app.services.message_service import (
MessageService, MessageNotFoundError, InvalidMessageDataError,
IdempotencyConflictError,
)
router = APIRouter(prefix="/api/v1/chats/{chat_id}/messages", tags=["Messages"])
IDEMPOTENCY_KEY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
def message_to_response(message) -> MessageResponse:
return MessageResponse(
id=str(message.id), chat_id=str(message.chat_id),
sender_id=str(message.sender_id), text=message.text,
created_at=message.created_at, attachment_ids=message.attachment_ids or [],
)
def parse_chat_id(chat_id: str) -> uuid.UUID:
try:
return uuid.UUID(chat_id)
except ValueError:
raise HTTPException(status_code=400, detail="Invalid chat UUID") from None
@router.post("", response_model=MessageResponse, status_code=status.HTTP_201_CREATED)
def create_message(
chat_id: str, body: CreateMessage,
idempotency_key: str = Header(..., alias="Idempotency-Key", min_length=1, max_length=128),
db: Session = Depends(get_db),
user: UserModel = Depends(get_current_user),
):
if not IDEMPOTENCY_KEY_RE.fullmatch(idempotency_key):
raise HTTPException(status_code=400, detail="Invalid Idempotency-Key")
parsed_id = parse_chat_id(chat_id)
try:
message = MessageService(db).create_message(
chat_id=parsed_id, sender_id=user.id, text=body.text,
idempotency_key=idempotency_key, attachment_ids=body.attachment_ids,
)
return message_to_response(message)
except MessageNotFoundError:
raise HTTPException(status_code=404, detail="Chat not found") from None
except InvalidMessageDataError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from None
except IdempotencyConflictError:
raise HTTPException(status_code=409, detail="Idempotency-Key was already used with a different request") from None
@router.get("")
def list_messages(
chat_id: str, limit: int = Query(default=50, ge=1, le=100),
cursor: str | None = None, db: Session = Depends(get_db),
user: UserModel = Depends(get_current_user),
):
parsed_id = parse_chat_id(chat_id)
try:
messages, next_cursor = MessageService(db).get_history(
chat_id=parsed_id, user_id=user.id, limit=limit, cursor=cursor
)
return {"items": [message_to_response(item) for item in messages], "next_cursor": next_cursor}
except MessageNotFoundError:
raise HTTPException(status_code=404, detail="Chat not found") from None
except InvalidMessageDataError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from None
+55
View File
@@ -0,0 +1,55 @@
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app.api.deps import get_db, get_current_user
from app.db.models import User as UserModel
from app.models import CreateUser, User
from app.services.user_service import (
UserService,
UsernameAlreadyExistsError,
)
router = APIRouter(prefix="/api/v1/users", tags=["Users"])
def user_to_response(user: UserModel) -> User:
return User(
id=str(user.id),
username=user.username,
display_name=user.display_name,
created_at=user.created_at,
)
@router.post("", response_model=User, status_code=status.HTTP_201_CREATED)
def register_user(
body: CreateUser,
db: Session = Depends(get_db),
):
try:
user = UserService(db).register(
username=body.username,
display_name=body.display_name,
password=body.password,
)
return user_to_response(user)
except UsernameAlreadyExistsError:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="Username already exists",
) from None
except ValueError as exc:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=str(exc),
) from None
@router.get("/me", response_model=User)
def get_me(
current_user: UserModel = Depends(get_current_user),
):
return user_to_response(current_user)