forked from mtusi2026/mtusi2026lab6
feat: перенос 5 лабы логики
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
from .schemas import (
|
||||
FILENAME_MAX_LENGTH,
|
||||
ORIGINAL_OBJECT_PREFIX,
|
||||
AttachmentContentType,
|
||||
AttachmentFilename,
|
||||
AttachmentSchema,
|
||||
AttachmentStatus,
|
||||
AttachmentVariant,
|
||||
AttachmentVariantSchema,
|
||||
InspectedImageSchema,
|
||||
NewAttachmentSchema,
|
||||
ReconcileReportSchema,
|
||||
StoredAttachmentSchema,
|
||||
UnfinishedUploadSchema,
|
||||
ensure_safe_filename,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"FILENAME_MAX_LENGTH",
|
||||
"ORIGINAL_OBJECT_PREFIX",
|
||||
"AttachmentContentType",
|
||||
"AttachmentFilename",
|
||||
"AttachmentStatus",
|
||||
"AttachmentVariant",
|
||||
"AttachmentVariantSchema",
|
||||
"AttachmentSchema",
|
||||
"NewAttachmentSchema",
|
||||
"StoredAttachmentSchema",
|
||||
"UnfinishedUploadSchema",
|
||||
"InspectedImageSchema",
|
||||
"ReconcileReportSchema",
|
||||
"ensure_safe_filename",
|
||||
]
|
||||
@@ -0,0 +1,164 @@
|
||||
import unicodedata
|
||||
from enum import StrEnum
|
||||
from typing import Annotated, Literal
|
||||
from uuid import UUID
|
||||
|
||||
from pydantic import AfterValidator, BaseModel, ConfigDict, Field
|
||||
|
||||
from domain.utils import NotBlankStr, UtcDateTime
|
||||
|
||||
FILENAME_MAX_LENGTH = 255
|
||||
|
||||
# Объекты оригиналов в bucket: ключ назначает сервер, filename в него не входит
|
||||
ORIGINAL_OBJECT_PREFIX = "originals/"
|
||||
|
||||
# Невидимое управление направлением текста: «photognp.exe» отображается
|
||||
# как «photoexe.png»
|
||||
BIDI_CONTROL_CHARACTERS = frozenset("")
|
||||
|
||||
|
||||
def ensure_safe_filename(value: str) -> str:
|
||||
"""
|
||||
Отображаемое имя файла — не путь и не ключ S3. Запрещены разделители путей,
|
||||
управляющие символы (включая NUL), bidi-управление и имена из одних точек.
|
||||
"""
|
||||
if "/" in value or "\\" in value:
|
||||
raise ValueError("Имя файла не может содержать / или \\")
|
||||
if any(
|
||||
unicodedata.category(char) == "Cc" or char in BIDI_CONTROL_CHARACTERS
|
||||
for char in value
|
||||
):
|
||||
raise ValueError("Имя файла не может содержать управляющие символы")
|
||||
if not value.strip("."):
|
||||
raise ValueError("Имя файла не может состоять из точек")
|
||||
return value
|
||||
|
||||
|
||||
AttachmentFilename = Annotated[
|
||||
NotBlankStr,
|
||||
Field(min_length=1, max_length=FILENAME_MAX_LENGTH),
|
||||
AfterValidator(ensure_safe_filename),
|
||||
]
|
||||
|
||||
|
||||
class AttachmentContentType(StrEnum):
|
||||
"""Допустимые форматы оригинала; определяются по содержимому"""
|
||||
|
||||
PNG = "image/png"
|
||||
JPEG = "image/jpeg"
|
||||
|
||||
|
||||
class AttachmentStatus(StrEnum):
|
||||
"""Публичные состояния pipeline и внутренние состояния приёма/очистки"""
|
||||
|
||||
PENDING = "pending"
|
||||
QUEUED = "queued"
|
||||
PROCESSING = "processing"
|
||||
READY = "ready"
|
||||
FAILED = "failed"
|
||||
DELETING = "deleting"
|
||||
|
||||
|
||||
class AttachmentVariant(StrEnum):
|
||||
"""Имена вариантов из контракта; original и производные pipeline v1"""
|
||||
|
||||
ORIGINAL = "original"
|
||||
THUMBNAIL = "thumbnail"
|
||||
CROP = "crop"
|
||||
OPTIMIZED = "optimized"
|
||||
|
||||
|
||||
class AttachmentVariantSchema(BaseModel):
|
||||
"""Производный вариант изображения; появляется с lab5"""
|
||||
|
||||
model_config = ConfigDict(frozen=True)
|
||||
|
||||
name: AttachmentVariant
|
||||
content_type: str
|
||||
size_bytes: int
|
||||
width: int
|
||||
height: int
|
||||
sha256: str
|
||||
|
||||
|
||||
class AttachmentSchema(BaseModel):
|
||||
"""Метаданные вложения; size_bytes, sha256 и content_type описывают оригинал"""
|
||||
|
||||
model_config = ConfigDict(frozen=True)
|
||||
|
||||
id: UUID
|
||||
chat_id: UUID
|
||||
owner_id: UUID
|
||||
filename: str
|
||||
content_type: AttachmentContentType
|
||||
size_bytes: int
|
||||
sha256: str
|
||||
status: Literal["queued", "processing", "ready", "failed"] = "ready"
|
||||
variants: list[AttachmentVariantSchema] = Field(default_factory=list)
|
||||
error_code: str | None = None
|
||||
created_at: UtcDateTime
|
||||
updated_at: UtcDateTime
|
||||
|
||||
|
||||
class NewAttachmentSchema(BaseModel):
|
||||
"""Проверенная загрузка: метаданные и назначенный сервером ключ объекта S3"""
|
||||
|
||||
model_config = ConfigDict(frozen=True)
|
||||
|
||||
chat_id: UUID
|
||||
owner_id: UUID
|
||||
filename: str
|
||||
content_type: AttachmentContentType
|
||||
size_bytes: int
|
||||
sha256: bytes
|
||||
object_key: str
|
||||
|
||||
|
||||
class StoredAttachmentSchema(BaseModel):
|
||||
"""Вложение вместе с ключом объекта — только внутри приложения"""
|
||||
|
||||
model_config = ConfigDict(frozen=True)
|
||||
|
||||
attachment: AttachmentSchema
|
||||
object_key: str
|
||||
variant_keys: dict[str, str] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class UnfinishedUploadSchema(BaseModel):
|
||||
"""Строка pending/deleting, забранная на очистку, и её объект S3"""
|
||||
|
||||
model_config = ConfigDict(frozen=True)
|
||||
|
||||
id: UUID
|
||||
object_key: str
|
||||
|
||||
|
||||
class InspectedImageSchema(BaseModel):
|
||||
"""Результат проверки содержимого: истинный формат и размеры"""
|
||||
|
||||
model_config = ConfigDict(frozen=True)
|
||||
|
||||
content_type: AttachmentContentType
|
||||
width: int
|
||||
height: int
|
||||
|
||||
|
||||
class ReconcileReportSchema(BaseModel):
|
||||
"""Итог одного прохода сверки S3 и БД"""
|
||||
|
||||
dry_run: bool
|
||||
unfinished_claimed: int = 0
|
||||
unfinished_objects_deleted: int = 0
|
||||
unfinished_rows_deleted: int = 0
|
||||
objects_scanned: int = 0
|
||||
orphan_objects_found: int = 0
|
||||
orphan_objects_deleted: int = 0
|
||||
|
||||
|
||||
class AttachmentDownloadSchema(BaseModel):
|
||||
"""Метаданные HTTP-выдачи original либо производного варианта"""
|
||||
|
||||
model_config = ConfigDict(frozen=True)
|
||||
|
||||
filename: str
|
||||
content_type: str
|
||||
Reference in New Issue
Block a user