This commit is contained in:
2026-09-30 12:13:29 +03:00
parent 6bc82eaa2a
commit f4198de3c8
45 changed files with 4027 additions and 875 deletions
+100 -80
View File
@@ -1,128 +1,148 @@
"""
Pydantic-схемы запросов/ответов согласно contracts/openapi.json.
ВАЖНО: все модели запросов (Create*) используют extra="forbid" - контракт
явно требует 400 на JSON с лишними полями, а Pydantic по умолчанию такие
поля молча игнорирует. Без extra="forbid" лишнее поле вроде "password"
в CreateUser проходило бы валидацию незамеченным.
"""
from __future__ import annotations
import re
import uuid
from datetime import datetime
from typing import List, Optional
from datetime import datetime, timezone
from typing import Literal
from uuid import UUID
from pydantic import BaseModel, ConfigDict, Field, field_validator
USERNAME_PATTERN = re.compile(r"^[a-z0-9_]{3,32}$")
# Пользователи
class CreateUser(BaseModel):
class ApiModel(BaseModel):
model_config = ConfigDict(extra="forbid")
username: str = Field(..., min_length=3, max_length=32)
display_name: str = Field(..., min_length=1, max_length=100)
class CreateUser(ApiModel):
username: str = Field(
min_length=3,
max_length=32,
pattern=r"^[a-z0-9_]{3,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 check_username(cls, v: str) -> str:
if not USERNAME_PATTERN.match(v):
raise ValueError("username must match [a-z0-9_]{3,32}")
return v
def username_is_not_blank(cls, value: str) -> str:
if not value.strip():
raise ValueError("username must not contain only spaces.")
return value
@field_validator("display_name")
@classmethod
def check_display_name(cls, v: str) -> str:
if not v.strip():
raise ValueError("display_name must not be blank")
return v
def display_name_is_not_blank(cls, value: str) -> str:
if not value.strip():
raise ValueError(
"display_name must not contain only spaces."
)
return value
@field_validator("password")
@classmethod
def password_is_not_blank(cls, value: str) -> str:
if not value.strip():
raise ValueError("password must not contain only spaces.")
return value
class User(BaseModel):
id: uuid.UUID
class User(ApiModel):
id: UUID
username: str
display_name: str
created_at: datetime
@field_validator("created_at")
@classmethod
def user_time_is_utc(cls, value: datetime) -> datetime:
if value.tzinfo is None:
raise ValueError("created_at must include UTC timezone.")
return value.astimezone(timezone.utc)
# Чаты
class CreateChat(BaseModel):
model_config = ConfigDict(extra="forbid")
title: str = Field(..., min_length=1, max_length=100)
member_ids: List[uuid.UUID] = Field(..., min_length=1, max_length=100)
class CreateChat(ApiModel):
title: str = Field(min_length=1, max_length=255)
member_ids: list[UUID] = Field(min_length=1)
@field_validator("title")
@classmethod
def check_title(cls, v: str) -> str:
if not v.strip():
raise ValueError("title must not be blank")
return v
@field_validator("member_ids")
@classmethod
def check_unique(cls, v: List[uuid.UUID]) -> List[uuid.UUID]:
if len(set(v)) != len(v):
raise ValueError("member_ids must be unique")
return v
def title_is_not_blank(cls, value: str) -> str:
if not value.strip():
raise ValueError("title must not contain only spaces.")
return value
class Chat(BaseModel):
id: uuid.UUID
class Chat(ApiModel):
id: UUID
title: str
member_ids: List[uuid.UUID]
member_ids: list[UUID]
created_at: datetime
class ChatPage(BaseModel):
items: List[Chat]
next_cursor: Optional[str] = None
@field_validator("created_at")
@classmethod
def chat_time_is_utc(cls, value: datetime) -> datetime:
if value.tzinfo is None:
raise ValueError("created_at must include UTC timezone.")
return value.astimezone(timezone.utc)
# Сообщения
class ChatPage(ApiModel):
items: list[Chat]
next_cursor: str | None = None
class CreateMessage(BaseModel):
model_config = ConfigDict(extra="forbid")
text: str = Field(..., min_length=1, max_length=4000)
class CreateMessage(ApiModel):
text: str = Field(min_length=1, max_length=4000)
@field_validator("text")
@classmethod
def check_text(cls, v: str) -> str:
if not v.strip():
raise ValueError("text must not be blank/whitespace-only")
return v
def text_is_not_blank(cls, value: str) -> str:
if not value.strip():
raise ValueError("text must not contain only spaces.")
return value
class Message(BaseModel):
id: uuid.UUID
chat_id: uuid.UUID
sender_id: uuid.UUID
class Message(ApiModel):
id: UUID
chat_id: UUID
sender_id: UUID
text: str
created_at: datetime
class MessagePage(BaseModel):
items: List[Message]
next_cursor: Optional[str] = None
@field_validator("created_at")
@classmethod
def message_time_is_utc(cls, value: datetime) -> datetime:
if value.tzinfo is None:
raise ValueError("created_at must include UTC timezone.")
return value.astimezone(timezone.utc)
# Health / ошибки
class Health(BaseModel):
status: str = "ok"
class MessagePage(ApiModel):
items: list[Message]
next_cursor: str | None = None
class ErrorBody(BaseModel):
code: str
message: str
request_id: str
class Session(ApiModel):
token: str = Field(min_length=1)
token_type: Literal["Bearer"]
expires_at: datetime
user: User
@field_validator("expires_at")
@classmethod
def expiry_time_is_utc(cls, value: datetime) -> datetime:
if value.tzinfo is None:
raise ValueError("expires_at must include UTC timezone.")
return value.astimezone(timezone.utc)
class ErrorResponse(BaseModel):
error: ErrorBody
class Health(ApiModel):
status: Literal["ok"]
class ErrorInner(ApiModel):
code: str = Field(min_length=1)
message: str = Field(min_length=1)
request_id: str = Field(min_length=1)
class Error(ApiModel):
error: ErrorInner