prepared skeleton for lab5

This commit is contained in:
2026-11-07 16:10:32 +03:00
parent 276dbdad8a
commit 0a70358829
135 changed files with 9647 additions and 34 deletions
+6
View File
@@ -0,0 +1,6 @@
from app.schemas.chat import Chat
from app.schemas.message import Message
from app.schemas.session import AuthSession
from app.schemas.user import User
__all__ = ["AuthSession", "Chat", "Message", "User"]
+23
View File
@@ -0,0 +1,23 @@
"""Публичные ready-метаданные lab4; приватный object_key не выдаётся клиенту."""
from datetime import datetime
from typing import Literal
from uuid import UUID
from pydantic import Field
from app.schemas.base import Base
class Attachment(Base):
chat_id: UUID
owner_id: UUID
filename: str = Field(min_length=1, max_length=255)
content_type: Literal["image/png", "image/jpeg"]
size_bytes: int = Field(ge=1, le=10_485_760)
sha256: str = Field(pattern=r"^[a-f0-9]{64}$")
status: Literal["ready"] = "ready"
variants: list[object] = Field(default_factory=list, max_length=0)
error_code: None = None
created_at: datetime
updated_at: datetime
+35
View File
@@ -0,0 +1,35 @@
from typing import Literal
from uuid import UUID
from pydantic import BaseModel, ConfigDict, field_validator
class Base(BaseModel):
model_config = ConfigDict(extra="forbid", from_attributes=True)
id: UUID
class Health(BaseModel):
model_config = ConfigDict(extra="forbid")
status: Literal["ok"]
class BaseCreate(BaseModel):
model_config = ConfigDict(extra="forbid")
@field_validator("*", mode="before")
@classmethod
def reject_invalid_strings(cls, value: object) -> object:
"""Отклоняет строки из одних пробелов и строки с NUL, который не хранит PostgreSQL."""
if isinstance(value, str):
if not value.strip():
raise ValueError("Строка не может состоять только из пробелов")
if "\x00" in value:
raise ValueError("Строка не может содержать символ NUL")
return value
class BasePage(BaseModel):
model_config = ConfigDict(extra="forbid")
+22
View File
@@ -0,0 +1,22 @@
from datetime import datetime
from uuid import UUID
from pydantic import Field
from app.schemas.base import Base, BaseCreate, BasePage
class Chat(Base):
title: str = Field(min_length=1, max_length=100)
member_ids: list[UUID] = Field(min_length=1, max_length=100)
created_at: datetime
class CreateChat(BaseCreate):
title: str = Field(min_length=1, max_length=100)
member_ids: list[UUID] = Field(min_length=1, max_length=100)
class ChatPage(BasePage):
items: list[Chat]
next_cursor: str | None
+10
View File
@@ -0,0 +1,10 @@
"""Место для будущей схемы сообщения contracts/jobs.schema.json.
Пока классы не реализованы и сообщения не принимаются/не публикуются.
Обязательны schema_version=1, type=attachment.process.v1, job_id, attachment_id,
pipeline_version>=1, attempt>=1, created_at (UTC/RFC3339).
Допустимы traceparent и tracestate; дополнительные поля запрещены.
job_id сохраняется при redelivery; очередная управляемая попытка отражается
в attempt. Bytes, secrets, S3 keys и пользовательские пути не передаются.
Pydantic-схема должна соответствовать публичному JSON Schema, не менять его.
"""
+41
View File
@@ -0,0 +1,41 @@
from datetime import datetime
from typing import Self
from uuid import UUID
from pydantic import Field, field_validator, model_validator
from app.schemas.base import Base, BaseCreate, BasePage
class Message(Base):
chat_id: UUID
sender_id: UUID
text: str = Field(max_length=4000)
attachment_ids: list[UUID] = Field(default_factory=list, max_length=10)
created_at: datetime
class CreateMessage(BaseCreate):
text: str = Field(max_length=4000)
attachment_ids: list[UUID] = Field(default_factory=list, max_length=10)
@field_validator("*", mode="before")
@classmethod
def reject_invalid_strings(cls, value: object) -> object:
if isinstance(value, str):
if "\x00" in value or (value != "" and not value.strip()):
raise ValueError("Некорректная строка сообщения")
return value
@model_validator(mode="after")
def require_content(self) -> Self:
if not self.text and not self.attachment_ids:
raise ValueError("Нужен текст или вложение")
if len(self.attachment_ids) != len(set(self.attachment_ids)):
raise ValueError("attachment_ids содержит дубликаты")
return self
class MessagePage(BasePage):
items: list[Message]
next_cursor: str | None
+17
View File
@@ -0,0 +1,17 @@
from datetime import datetime
from typing import Literal
from pydantic import BaseModel, ConfigDict, Field
from app.schemas.user import User
class AuthSession(BaseModel):
"""Ответ POST /auth/sessions (в OpenAPI — Session)."""
model_config = ConfigDict(extra="forbid")
token: str = Field(min_length=32)
token_type: Literal["Bearer"] = "Bearer"
expires_at: datetime
user: User
+25
View File
@@ -0,0 +1,25 @@
from datetime import datetime
from pydantic import Field
from app.schemas.base import Base, BaseCreate
USERNAME_PATTERN = r"^[a-z0-9_]{3,32}$"
PASSWORD_MIN_LENGTH = 12
PASSWORD_MAX_LENGTH = 128
class User(Base):
"""Публичное представление пользователя. Пароль/хеш сюда не попадают никогда."""
username: str = Field(pattern=USERNAME_PATTERN)
display_name: str = Field(min_length=1, max_length=100)
created_at: datetime
class CreateUser(BaseCreate):
username: str = Field(pattern=USERNAME_PATTERN)
display_name: str = Field(min_length=1, max_length=100)
password: str = Field(
min_length=PASSWORD_MIN_LENGTH, max_length=PASSWORD_MAX_LENGTH, repr=False
)