Выполнение лабораторной работы номер 7

This commit is contained in:
2026-12-04 18:15:18 +03:00
parent 20afc2c790
commit 2fae615742
77 changed files with 5212 additions and 64 deletions
+154
View File
@@ -0,0 +1,154 @@
"""Bounded image uploads, private S3 storage and authorized streaming downloads."""
import asyncio
import hashlib
import os
import tempfile
import unicodedata
import uuid
import warnings
import boto3
from botocore.config import Config
from botocore.exceptions import BotoCoreError, ClientError
from fastapi import APIRouter, Depends, HTTPException, Query, Request
from fastapi.responses import StreamingResponse
from PIL import Image, UnidentifiedImageError
from starlette.concurrency import run_in_threadpool
import db
import telemetry as ot
from psycopg.types.json import Jsonb
MAX_BYTES = 10 * 1024 * 1024
MAX_PIXELS = 40_000_000
BUCKET = os.environ.get("S3_BUCKET", "attachments")
S3 = boto3.client("s3", endpoint_url=os.environ["S3_ENDPOINT"],
aws_access_key_id=os.environ["S3_ACCESS_KEY"],
aws_secret_access_key=os.environ["S3_SECRET_KEY"],
region_name="us-east-1", verify='/ca/ca.crt', config=Config(connect_timeout=2, read_timeout=5,
retries={"total_max_attempts": 2}, s3={"addressing_style": "path"}))
Image.MAX_IMAGE_PIXELS = MAX_PIXELS
UPLOAD_SLOTS = asyncio.Semaphore(1)
def inspect_image(file, mime):
try:
file.seek(0)
with warnings.catch_warnings():
warnings.simplefilter("error", Image.DecompressionBombWarning)
with Image.open(file) as image:
if image.width * image.height > MAX_PIXELS:
raise HTTPException(413, "too many pixels")
if {"PNG": "image/png", "JPEG": "image/jpeg"}.get(image.format) != mime:
raise HTTPException(415, "invalid image type")
image.verify()
file.seek(0)
with Image.open(file) as image:
image.load()
except (Image.DecompressionBombError, Image.DecompressionBombWarning):
raise HTTPException(413, "too many pixels") from None
except (UnidentifiedImageError, OSError, ValueError, SyntaxError):
raise HTTPException(415, "invalid image") from None
file.seek(0)
def store(file, cid, user_id, filename, mime, size, checksum, is_member):
inspect_image(file, mime)
aid = uuid.uuid4()
key = f"staging/{aid}"
# Commit intent before external write, so even a killed process leaves a tracked pending row.
with db.pool.connection() as conn:
if not is_member(conn, cid, user_id):
raise HTTPException(404, "chat not found")
conn.execute("""INSERT INTO attachments(id,chat_id,owner_id,filename,content_type,size_bytes,sha256,object_key,status)
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,'pending')""",
(aid, cid, user_id, filename, mime, size, checksum, key))
with db.pool.connection() as conn:
conn.execute("SELECT id FROM attachments WHERE id=%s FOR UPDATE", (aid,)).fetchone()
try:
S3.put_object(Bucket=BUCKET, Key=key, Body=file, ContentLength=size, ContentType=mime)
except (BotoCoreError, ClientError):
raise HTTPException(503, "storage unavailable") from None
conn.execute("INSERT INTO attachment_jobs(id,trace_context) VALUES (%s,%s)", (aid,Jsonb(ot.carrier())))
return conn.execute("UPDATE attachments SET status='queued', updated_at=now() WHERE id=%s RETURNING *", (aid,)).fetchone()
def router(current_user, is_member, parse_uuid, iso):
routes = APIRouter()
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")},
"created_at": iso(row["created_at"]), "updated_at": iso(row["updated_at"]),
"variants": row["variants"], "error_code": row["error_code"]}
def authorized(aid, me):
aid = parse_uuid(aid, "attachment id")
with db.pool.connection() as conn:
row = conn.execute("SELECT * FROM attachments WHERE id=%s AND status!='pending'", (aid,)).fetchone()
if not row or not is_member(conn, row["chat_id"], me.id):
raise HTTPException(404, "attachment not found")
return row
@routes.post("/api/v1/chats/{chat_id}/attachments", status_code=202)
async def upload(chat_id: str, request: Request, filename: str = Query(...), me=Depends(current_user)):
cid = parse_uuid(chat_id, "chat id")
def check_member():
with db.pool.connection() as conn:
if not is_member(conn, cid, me.id):
raise HTTPException(404, "chat not found")
await run_in_threadpool(check_member)
if not 1 <= len(filename) <= 255 or not filename.strip() or any(c in "/\\" or unicodedata.category(c) == "Cc" for c in filename):
raise HTTPException(400, "invalid filename")
mime = request.headers.get("content-type", "").split(";", 1)[0].lower()
if mime not in ("image/png", "image/jpeg"):
raise HTTPException(415, "unsupported media type")
size = 0
digest = hashlib.sha256()
async with UPLOAD_SLOTS:
with tempfile.TemporaryFile() as file:
try:
async with asyncio.timeout(30):
async for chunk in request.stream():
size += len(chunk)
if size > MAX_BYTES:
raise HTTPException(413, "upload too large")
file.write(chunk)
digest.update(chunk)
except TimeoutError:
raise HTTPException(400, "upload timed out") from None
if not size:
raise HTTPException(415, "empty image")
row = await run_in_threadpool(store, file, cid, me.id, filename, mime, size, digest.hexdigest(), is_member)
return metadata(row)
@routes.get("/api/v1/attachments/{attachment_id}")
def get_attachment(attachment_id: str, me=Depends(current_user)):
return metadata(authorized(attachment_id, me))
@routes.get("/api/v1/attachments/{attachment_id}/content")
def download(attachment_id: str, variant: str = "original", me=Depends(current_user)):
row = authorized(attachment_id, me)
if row["status"] != "ready":
raise HTTPException(409, "attachment not ready")
if variant == "original":
key, mime, size = row["object_key"], row["content_type"], row["size_bytes"]
else:
info = next((v for v in row["variants"] if v["name"] == variant), None)
if info is None:
raise HTTPException(404, "variant not found")
key, mime, size = f"variants/{row['id']}/{variant}", info["content_type"], info["size_bytes"]
try:
body = S3.get_object(Bucket=BUCKET, Key=key)["Body"]
except (BotoCoreError, ClientError):
raise HTTPException(503, "storage unavailable") from None
def stream():
try:
yield from body.iter_chunks(chunk_size=64 * 1024)
finally:
body.close()
return StreamingResponse(stream(), media_type=mime, headers={"Content-Length": str(size)})
return routes