forked from mtusi2026/mtusi2026lab5
207 lines
11 KiB
Python
207 lines
11 KiB
Python
"""Вложения (lab4): потоковая загрузка PNG/JPEG в приватный S3, метаданные в PostgreSQL, авторизованное скачивание."""
|
||
import asyncio
|
||
import hashlib
|
||
import tempfile
|
||
import unicodedata
|
||
import uuid
|
||
|
||
from . import config, images
|
||
from .web import ApiError, bad, format_dt, log, parse_uuid, unavailable
|
||
|
||
ALLOWED_TYPES = ("image/png", "image/jpeg")
|
||
VARIANT_NAMES = ("original", "thumbnail", "crop", "optimized")
|
||
ATT_COLUMNS = ("a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, a.sha256, a.status, a.error_code, "
|
||
"a.s3_key, a.created_at, a.updated_at, a.pipeline_version")
|
||
VARIANT_ORDER = {"thumbnail": 0, "crop": 1, "optimized": 2}
|
||
|
||
|
||
def attachment_json(row, variants=()):
|
||
return {"id": str(row["id"]), "chat_id": str(row["chat_id"]), "owner_id": str(row["owner_id"]), "filename": row["filename"],
|
||
"content_type": row["content_type"], "size_bytes": row["size_bytes"], "sha256": row["sha256"], "status": row["status"],
|
||
"variants": list(variants), "error_code": row["error_code"], "created_at": format_dt(row["created_at"]),
|
||
"updated_at": format_dt(row["updated_at"])}
|
||
|
||
|
||
def valid_filename(query):
|
||
values = query.get("filename")
|
||
if not values or len(values) != 1:
|
||
raise bad("Требуется параметр filename")
|
||
name = values[0]
|
||
if not 1 <= len(name) <= 255 or not name.strip():
|
||
raise bad("filename: длина 1–255 символов")
|
||
try:
|
||
name.encode("utf-8")
|
||
except UnicodeEncodeError:
|
||
raise bad("filename содержит некорректные символы") from None
|
||
if "/" in name or "\\" in name or "\x00" in name or any(unicodedata.category(ch) == "Cc" for ch in name):
|
||
raise bad("filename не должен содержать / \\ NUL и управляющие символы")
|
||
return name
|
||
|
||
|
||
class StreamResponse:
|
||
"""Потоковый ответ: тело читается из S3 порциями и сразу отдаётся клиенту (без загрузки файла в память)."""
|
||
|
||
def __init__(self, content_type, length, stream):
|
||
self.content_type, self.length, self.stream = content_type, length, stream
|
||
|
||
async def send(self, send, request_id, instance_id):
|
||
headers = [(b"content-type", self.content_type.encode()), (b"content-length", str(self.length).encode()),
|
||
(b"x-request-id", request_id.encode()), (b"x-content-type-options", b"nosniff"),
|
||
(b"cache-control", b"private, no-store")]
|
||
if instance_id:
|
||
headers.append((b"x-instance-id", instance_id.encode()))
|
||
await send({"type": "http.response.start", "status": 200, "headers": headers})
|
||
try:
|
||
while True:
|
||
chunk = await self.stream.read(config.DOWNLOAD_CHUNK_BYTES)
|
||
if not chunk:
|
||
break
|
||
await send({"type": "http.response.body", "body": chunk, "more_body": True})
|
||
finally:
|
||
self.stream.close()
|
||
await send({"type": "http.response.body", "body": b""})
|
||
|
||
|
||
class AttachmentMixin:
|
||
"""Подмешивается в Messenger: требует self.db, self.s3, self.authenticate()."""
|
||
|
||
def _init_attachments(self):
|
||
self._upload_slots = asyncio.Semaphore(config.UPLOAD_CONCURRENCY)
|
||
self._upload_waiting = 0
|
||
|
||
async def _receive_upload(self, req):
|
||
"""Принимает тело в SpooledTemporaryFile (до 1 MiB в памяти, далее диск), считает SHA-256, ограничивает размер."""
|
||
declared = req.headers.get("content-length")
|
||
too_large = ApiError(413, "payload_too_large", "Файл больше 10 MiB", {"connection": "close"})
|
||
if declared is not None:
|
||
if not declared.isdigit():
|
||
raise bad("Некорректный Content-Length")
|
||
if int(declared) > config.MAX_UPLOAD_BYTES:
|
||
raise too_large
|
||
spool = tempfile.SpooledTemporaryFile(max_size=1024 * 1024)
|
||
digest, size = hashlib.sha256(), 0
|
||
try:
|
||
while True:
|
||
event = await req.receive()
|
||
if event["type"] == "http.disconnect":
|
||
raise bad("Соединение закрыто клиентом")
|
||
chunk = event.get("body", b"")
|
||
size += len(chunk)
|
||
if size > config.MAX_UPLOAD_BYTES:
|
||
raise too_large
|
||
digest.update(chunk)
|
||
spool.write(chunk)
|
||
if not event.get("more_body"):
|
||
break
|
||
except BaseException:
|
||
spool.close()
|
||
raise
|
||
if size == 0:
|
||
spool.close()
|
||
raise bad("Пустой файл")
|
||
return spool, digest.hexdigest(), size
|
||
|
||
async def upload_attachment(self, req, params):
|
||
user_id = await self.authenticate(req)
|
||
chat_id = await self._require_member(user_id, params)
|
||
filename = valid_filename(req.query)
|
||
media = req.headers.get("content-type", "").split(";")[0].strip().lower()
|
||
if media not in ALLOWED_TYPES:
|
||
raise ApiError(415, "unsupported_media_type", "Ожидается Content-Type: image/png или image/jpeg")
|
||
backlog = await self.db.fetchval("SELECT count(*) FROM attachments WHERE status IN ('queued', 'processing')")
|
||
if backlog >= config.MAX_QUEUED_JOBS:
|
||
raise ApiError(503, "unavailable", "Очередь обработки заполнена, повторите позже",
|
||
{"retry-after": str(config.BACKLOG_RETRY_AFTER_SECONDS)})
|
||
if self._upload_waiting >= config.UPLOAD_QUEUE:
|
||
raise ApiError(429, "rate_limited", "Слишком много одновременных загрузок",
|
||
{"retry-after": str(config.RETRY_AFTER_SECONDS)})
|
||
self._upload_waiting += 1
|
||
try:
|
||
await self._upload_slots.acquire() # ограничение одновременных загрузок на реплику (RAM/диск/CPU)
|
||
finally:
|
||
self._upload_waiting -= 1
|
||
try:
|
||
spool, sha256, size = await self._receive_upload(req)
|
||
try:
|
||
try:
|
||
loop = asyncio.get_running_loop()
|
||
content_type, width, height = await loop.run_in_executor(self.image_pool, images.validate, spool, media)
|
||
except images.ImageRejected as exc:
|
||
raise ApiError(exc.status, exc.code, exc.message) from None
|
||
att_id = uuid.uuid4()
|
||
staging_key = "staging/%s" % att_id
|
||
final_key = "att/%s/original" % att_id
|
||
spool.seek(0)
|
||
await self.s3.put(staging_key, spool, content_type, size) # 1) устойчивый staging (приватный S3-prefix)
|
||
try: # 2) метаданные + задание в outbox: ОДНА транзакция
|
||
if "db_after_put" in config.FAULT_INJECTION:
|
||
raise RuntimeError("injected: сбой БД после записи в staging")
|
||
async with self.db.conn() as c:
|
||
async with c.transaction():
|
||
row = await c.fetchrow(
|
||
"INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, width, "
|
||
"height, status, s3_key, staging_key) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, 'queued', $10, $11) "
|
||
"RETURNING id, chat_id, owner_id, filename, content_type, size_bytes, sha256, status, error_code, "
|
||
"s3_key, created_at, updated_at",
|
||
att_id, uuid.UUID(chat_id), uuid.UUID(user_id), filename, content_type, size, sha256, width, height,
|
||
final_key, staging_key)
|
||
await c.execute(
|
||
"INSERT INTO outbox (job_id, attachment_id, pipeline_version, attempt) VALUES ($1, $2, 1, 1)",
|
||
uuid.uuid4(), att_id)
|
||
except BaseException:
|
||
try:
|
||
if "s3_delete_fails" in config.FAULT_INJECTION:
|
||
raise OSError("injected: компенсирующее удаление не удалось")
|
||
await self.s3.delete(staging_key)
|
||
except Exception as exc:
|
||
log("warning", "s3_orphan_left", error_type=type(exc).__name__)
|
||
raise
|
||
finally:
|
||
spool.close()
|
||
finally:
|
||
self._upload_slots.release()
|
||
self.relay.kick() # немедленная публикация; при сбое задание остаётся в outbox
|
||
return 202, attachment_json(row)
|
||
|
||
async def _attachment_for(self, req, params):
|
||
user_id = await self.authenticate(req)
|
||
att_id = parse_uuid(params["attachment_id"], "attachment_id")
|
||
row = await self.db.fetchrow(
|
||
"SELECT " + ATT_COLUMNS + " FROM attachments a JOIN chat_members m ON m.chat_id = a.chat_id AND m.user_id = $2 "
|
||
"WHERE a.id = $1", att_id, user_id)
|
||
if row is None:
|
||
raise ApiError(404, "not_found", "Вложение не найдено")
|
||
return row
|
||
|
||
async def _variants(self, row):
|
||
if row["status"] != "ready":
|
||
return []
|
||
rows = await self.db.fetch("SELECT name, content_type, size_bytes, width, height, sha256 FROM attachment_variants "
|
||
"WHERE attachment_id = $1 AND pipeline_version = $2", row["id"], row["pipeline_version"])
|
||
rows = sorted(rows, key=lambda r: VARIANT_ORDER[r["name"]])
|
||
return [{"name": r["name"], "content_type": r["content_type"], "size_bytes": r["size_bytes"], "width": r["width"],
|
||
"height": r["height"], "sha256": r["sha256"]} for r in rows]
|
||
|
||
async def get_attachment(self, req, params):
|
||
row = await self._attachment_for(req, params)
|
||
return 200, attachment_json(row, await self._variants(row))
|
||
|
||
async def download_attachment(self, req, params):
|
||
row = await self._attachment_for(req, params)
|
||
variant = "original"
|
||
if "variant" in req.query:
|
||
if len(req.query["variant"]) != 1 or req.query["variant"][0] not in VARIANT_NAMES:
|
||
raise bad("variant: original | thumbnail | crop | optimized")
|
||
variant = req.query["variant"][0]
|
||
if row["status"] != "ready":
|
||
raise ApiError(409, "conflict", "Вложение ещё обрабатывается или обработка не удалась")
|
||
key, content_type = row["s3_key"], row["content_type"]
|
||
if variant != "original":
|
||
v = await self.db.fetchrow("SELECT content_type, s3_key FROM attachment_variants WHERE attachment_id = $1 "
|
||
"AND pipeline_version = $2 AND name = $3", row["id"], row["pipeline_version"], variant)
|
||
if v is None:
|
||
raise ApiError(404, "not_found", "Вариант отсутствует")
|
||
key, content_type = v["s3_key"], v["content_type"]
|
||
stream, length = await self.s3.open_stream(key)
|
||
return 200, StreamResponse(content_type, length, stream)
|