forked from mtusi2026/mtusi2026lab5
244 lines
9.6 KiB
Python
244 lines
9.6 KiB
Python
import asyncio
|
|
import hashlib
|
|
import logging
|
|
from datetime import timedelta
|
|
from uuid import UUID, uuid4
|
|
|
|
from sqlalchemy import and_, or_, select
|
|
from sqlalchemy.exc import IntegrityError
|
|
|
|
from app.db import map_integrity, session_scope
|
|
from app.errors import AppError
|
|
from app.images import declared_content_type, inspect_image
|
|
from app.jobs import job_document
|
|
from app.models import Attachment, AttachmentJob, AttachmentVariant, ChatMember, JobOutbox
|
|
from app.pipeline import variant_names
|
|
from app.present import PublicAttachment
|
|
from app.runtime import require_settings, require_store
|
|
from app.timeutil import utcnow
|
|
|
|
logger = logging.getLogger("app.attachments")
|
|
|
|
_VARIANT_ORDER = {name: index for index, name in enumerate(variant_names())}
|
|
|
|
|
|
def validate_filename(filename: str | None) -> str:
|
|
if filename is None or filename.strip() == "":
|
|
raise AppError(400, "invalid_request", "Некорректное имя файла")
|
|
if len(filename) > 255:
|
|
raise AppError(400, "invalid_request", "Некорректное имя файла")
|
|
for char in filename:
|
|
code = ord(char)
|
|
if char in {"/", "\\", "\x00"} or code < 32 or code == 127:
|
|
raise AppError(400, "invalid_request", "Некорректное имя файла")
|
|
return filename
|
|
|
|
|
|
def _variant_dict(row: AttachmentVariant) -> dict:
|
|
return {
|
|
"name": row.name,
|
|
"content_type": row.content_type,
|
|
"size_bytes": row.size_bytes,
|
|
"width": row.width,
|
|
"height": row.height,
|
|
"sha256": row.sha256,
|
|
}
|
|
|
|
|
|
def _public(row: Attachment, variants: list[dict] | None = None) -> PublicAttachment:
|
|
visible = tuple(variants or ()) if row.status == "ready" else ()
|
|
return PublicAttachment(
|
|
id=row.id,
|
|
chat_id=row.chat_id,
|
|
owner_id=row.owner_id,
|
|
filename=row.filename,
|
|
content_type=row.content_type,
|
|
size_bytes=row.size_bytes,
|
|
sha256=row.sha256,
|
|
status=row.status,
|
|
variants=visible,
|
|
error_code=row.error_code,
|
|
created_at=row.created_at,
|
|
updated_at=row.updated_at,
|
|
)
|
|
|
|
|
|
async def _require_member(session, chat_id: UUID, user_id: UUID) -> None:
|
|
member = await session.scalar(
|
|
select(ChatMember.user_id).where(ChatMember.chat_id == chat_id, ChatMember.user_id == user_id)
|
|
)
|
|
if member is None:
|
|
raise AppError(404, "not_found", "Объект не найден")
|
|
|
|
|
|
async def _variants_for(session, attachment_id: UUID) -> list[dict]:
|
|
rows = (
|
|
await session.scalars(select(AttachmentVariant).where(AttachmentVariant.attachment_id == attachment_id))
|
|
).all()
|
|
payload = [_variant_dict(row) for row in rows]
|
|
payload.sort(key=lambda item: _VARIANT_ORDER.get(item["name"], 9))
|
|
return payload
|
|
|
|
|
|
async def create_attachment(
|
|
chat_id: UUID,
|
|
owner_id: UUID,
|
|
filename: str,
|
|
content_type_header: str | None,
|
|
payload: bytes,
|
|
) -> PublicAttachment:
|
|
settings = require_settings()
|
|
store = require_store()
|
|
filename = validate_filename(filename)
|
|
declared = declared_content_type(content_type_header)
|
|
if not payload:
|
|
raise AppError(415, "unsupported_media_type", "Неподдерживаемый тип изображения")
|
|
if len(payload) > settings.max_upload_bytes:
|
|
raise AppError(413, "payload_too_large", "Файл слишком большой")
|
|
async with session_scope() as session:
|
|
async with session.begin():
|
|
await _require_member(session, chat_id, owner_id)
|
|
await asyncio.to_thread(inspect_image, payload, declared, settings.max_image_pixels)
|
|
digest = hashlib.sha256(payload).hexdigest()
|
|
attachment_id = uuid4()
|
|
job_id = uuid4()
|
|
staging_key = "staging/%s" % attachment_id
|
|
object_key = "att/%s/original" % attachment_id
|
|
created_at = utcnow()
|
|
await store.put(staging_key, payload, declared)
|
|
try:
|
|
async with session_scope() as session:
|
|
try:
|
|
async with session.begin():
|
|
await _require_member(session, chat_id, owner_id)
|
|
session.add(
|
|
Attachment(
|
|
id=attachment_id,
|
|
chat_id=chat_id,
|
|
owner_id=owner_id,
|
|
filename=filename,
|
|
content_type=declared,
|
|
size_bytes=len(payload),
|
|
sha256=digest,
|
|
object_key=object_key,
|
|
staging_key=staging_key,
|
|
status="queued",
|
|
error_code=None,
|
|
created_at=created_at,
|
|
updated_at=created_at,
|
|
)
|
|
)
|
|
await session.flush()
|
|
session.add(
|
|
AttachmentJob(
|
|
job_id=job_id,
|
|
attachment_id=attachment_id,
|
|
pipeline_version=settings.pipeline_version,
|
|
status="queued",
|
|
attempt=0,
|
|
max_attempts=settings.job_max_attempts,
|
|
staging_key=staging_key,
|
|
objects_written_at=None,
|
|
created_at=created_at,
|
|
updated_at=created_at,
|
|
)
|
|
)
|
|
await session.flush()
|
|
session.add(
|
|
JobOutbox(
|
|
id=uuid4(),
|
|
job_id=job_id,
|
|
payload=job_document(job_id, attachment_id, settings.pipeline_version, 1, created_at),
|
|
available_at=created_at,
|
|
created_at=created_at,
|
|
published_at=None,
|
|
publish_attempts=0,
|
|
gap_injected=False,
|
|
)
|
|
)
|
|
await session.flush()
|
|
except IntegrityError as exc:
|
|
raise map_integrity(exc, "Конфликт записи") from None
|
|
except Exception:
|
|
await store.delete(staging_key)
|
|
raise
|
|
return PublicAttachment(
|
|
id=attachment_id,
|
|
chat_id=chat_id,
|
|
owner_id=owner_id,
|
|
filename=filename,
|
|
content_type=declared,
|
|
size_bytes=len(payload),
|
|
sha256=digest,
|
|
status="queued",
|
|
variants=(),
|
|
error_code=None,
|
|
created_at=created_at,
|
|
updated_at=created_at,
|
|
)
|
|
|
|
|
|
async def metadata_for_member(attachment_id: UUID, user_id: UUID) -> PublicAttachment:
|
|
async with session_scope() as session:
|
|
async with session.begin():
|
|
row = await session.get(Attachment, attachment_id)
|
|
if row is None:
|
|
raise AppError(404, "not_found", "Объект не найден")
|
|
await _require_member(session, row.chat_id, user_id)
|
|
variants = await _variants_for(session, row.id) if row.status == "ready" else []
|
|
return _public(row, variants)
|
|
|
|
|
|
async def open_content(attachment_id: UUID, user_id: UUID, variant: str) -> tuple[str, str]:
|
|
if variant not in {"original", "thumbnail", "crop", "optimized"}:
|
|
raise AppError(400, "invalid_request", "Некорректный запрос")
|
|
async with session_scope() as session:
|
|
async with session.begin():
|
|
row = await session.get(Attachment, attachment_id)
|
|
if row is None:
|
|
raise AppError(404, "not_found", "Объект не найден")
|
|
await _require_member(session, row.chat_id, user_id)
|
|
if row.status != "ready":
|
|
raise AppError(409, "conflict", "Вложение ещё не готово")
|
|
if variant == "original":
|
|
return row.object_key, row.content_type
|
|
found = await session.scalar(
|
|
select(AttachmentVariant).where(
|
|
AttachmentVariant.attachment_id == row.id,
|
|
AttachmentVariant.name == variant,
|
|
)
|
|
)
|
|
if found is None:
|
|
raise AppError(404, "not_found", "Объект не найден")
|
|
return found.object_key, found.content_type
|
|
|
|
|
|
async def known_object_keys() -> set[str]:
|
|
settings = require_settings()
|
|
retain_after = utcnow() - timedelta(seconds=settings.staging_retention_seconds)
|
|
async with session_scope() as session:
|
|
async with session.begin():
|
|
keys = set((await session.scalars(select(Attachment.object_key))).all())
|
|
keys.update((await session.scalars(select(AttachmentVariant.object_key))).all())
|
|
staging_jobs = (
|
|
await session.scalars(
|
|
select(AttachmentJob.staging_key).where(
|
|
or_(
|
|
AttachmentJob.status.in_(("queued", "processing")),
|
|
and_(AttachmentJob.status == "failed", AttachmentJob.updated_at > retain_after),
|
|
)
|
|
)
|
|
)
|
|
).all()
|
|
keys.update(staging_jobs)
|
|
staging_rows = (
|
|
await session.scalars(
|
|
select(Attachment.staging_key).where(
|
|
Attachment.staging_key.is_not(None),
|
|
Attachment.status.in_(("queued", "processing")),
|
|
)
|
|
)
|
|
).all()
|
|
keys.update(key for key in staging_rows if key)
|
|
return keys
|