feat: перенос структуры приложения из четвертой лабы

This commit is contained in:
Ильяс
2026-11-07 16:51:38 +03:00
parent 276dbdad8a
commit 7cfc6d40a6
28 changed files with 3749 additions and 1 deletions
+207
View File
@@ -0,0 +1,207 @@
from __future__ import annotations
import datetime as dt
import re
from enum import Enum
from uuid import UUID
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
def now_utc_iso() -> str:
"""Возвращает текущее время в формате RFC 3339 UTC с суффиксом Z."""
return dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
class ErrorCode(str, Enum):
INVALID_REQUEST = "invalid_request"
UNAUTHORIZED = "unauthorized"
NOT_FOUND = "not_found"
CONFLICT = "conflict"
PAYLOAD_TOO_LARGE = "payload_too_large"
UNSUPPORTED_MEDIA_TYPE = "unsupported_media_type"
RATE_LIMITED = "rate_limited"
UNAVAILABLE = "unavailable"
INTERNAL_ERROR = "internal_error"
class ErrorDetail(BaseModel):
model_config = ConfigDict(extra="forbid")
code: ErrorCode
message: str = Field(min_length=1)
request_id: str = Field(min_length=1)
class ErrorResponse(BaseModel):
model_config = ConfigDict(extra="forbid")
error: ErrorDetail
class HealthResponse(BaseModel):
model_config = ConfigDict(extra="forbid")
status: str = Field(default="ok")
class CreateUserRequest(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
username: str = Field(min_length=3, max_length=32)
display_name: str = Field(min_length=1, max_length=100)
password: str = Field(min_length=12, max_length=128)
@field_validator("username")
@classmethod
def validate_username(cls, v: str) -> str:
if not re.match(r"^[a-z0-9_]{3,32}\Z", v):
raise ValueError("Имя пользователя должно соответствовать шаблону ^[a-z0-9_]{3,32}$")
return v
@field_validator("display_name")
@classmethod
def validate_display_name(cls, v: str) -> str:
if not v.strip():
raise ValueError("Отображаемое имя не может состоять только из пробелов")
return v
@field_validator("password")
@classmethod
def validate_password(cls, v: str) -> str:
if not v.strip():
raise ValueError("Пароль не может состоять только из пробелов")
return v
class UserResponse(BaseModel):
model_config = ConfigDict(extra="forbid")
id: str
username: str
display_name: str
created_at: str
class SessionResponse(BaseModel):
model_config = ConfigDict(extra="forbid")
token: str = Field(min_length=32)
token_type: str = Field(default="Bearer")
expires_at: str
user: UserResponse
class CreateChatRequest(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
title: str = Field(min_length=1, max_length=100)
member_ids: list[str] = Field(min_length=1, max_length=100)
@field_validator("title")
@classmethod
def validate_title(cls, v: str) -> str:
if not v.strip():
raise ValueError("Название не может состоять только из пробелов")
return v
@field_validator("member_ids")
@classmethod
def validate_member_ids(cls, v: list[str]) -> list[str]:
if len(v) != len(set(v)):
raise ValueError("Идентификаторы участников должны быть уникальными")
for member_id in v:
try:
UUID(member_id)
except ValueError:
raise ValueError(f"Идентификатор участника '{member_id}' не является валидным UUID")
return v
class ChatResponse(BaseModel):
model_config = ConfigDict(extra="forbid")
id: str
title: str
member_ids: list[str]
created_at: str
class ChatPageResponse(BaseModel):
model_config = ConfigDict(extra="forbid")
items: list[ChatResponse]
next_cursor: str | None = None
class VariantResponse(BaseModel):
model_config = ConfigDict(extra="forbid")
name: str
content_type: str
size_bytes: int
width: int
height: int
sha256: str
class AttachmentResponse(BaseModel):
model_config = ConfigDict(extra="forbid")
id: str
chat_id: str
owner_id: str
filename: str
content_type: str
size_bytes: int
sha256: str
status: str = "ready"
variants: list[VariantResponse] = Field(default_factory=list)
error_code: str | None = None
created_at: str
updated_at: str
class CreateMessageRequest(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
text: str = Field(default="", max_length=4000)
attachment_ids: list[str] = Field(default_factory=list, max_length=10)
@field_validator("attachment_ids")
@classmethod
def validate_attachment_ids(cls, v: list[str]) -> list[str]:
if len(v) != len(set(v)):
raise ValueError("attachment_ids must contain unique items")
for item in v:
try:
UUID(item)
except ValueError:
raise ValueError(f"Идентификатор вложения '{item}' не является валидным UUID")
return v
@model_validator(mode="after")
def check_text_or_attachment(self) -> CreateMessageRequest:
has_text = bool(self.text and self.text.strip())
has_attachments = bool(self.attachment_ids)
if not has_text and not has_attachments:
raise ValueError("Сообщение должно содержать непустой текст или хотя бы одно вложение")
return self
class MessageResponse(BaseModel):
model_config = ConfigDict(extra="forbid")
id: str
chat_id: str
sender_id: str
text: str
created_at: str
attachment_ids: list[str] = Field(default_factory=list)
class MessagePageResponse(BaseModel):
model_config = ConfigDict(extra="forbid")
items: list[MessageResponse]
next_cursor: str | None = None