210 lines
6.5 KiB
Python
210 lines
6.5 KiB
Python
"""Схемы запросов и ответов ровно по contracts/openapi.json."""
|
|
from __future__ import annotations
|
|
|
|
from typing import Literal
|
|
from uuid import UUID
|
|
|
|
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
|
|
|
from .domain import ChatRecord, MessageRecord, UserRecord, rfc3339_z
|
|
from .sessions import IssuedSession
|
|
|
|
USERNAME_PATTERN = r"^[a-z0-9_]{3,32}$"
|
|
MIN_PASSWORD = 12
|
|
MAX_PASSWORD = 128
|
|
MAX_DISPLAY_NAME = 100
|
|
MAX_TITLE = 100
|
|
MAX_TEXT = 4000
|
|
MAX_MEMBERS = 100
|
|
MAX_LIMIT = 100
|
|
DEFAULT_LIMIT = 50
|
|
|
|
|
|
def _require_content(value: str, *, field: str) -> str:
|
|
"""Обязательная строка не может быть пустой или состоять из пробельных символов."""
|
|
if not value.strip():
|
|
raise ValueError(f"{field} must not be empty or contain only whitespace")
|
|
return value
|
|
|
|
|
|
def _visible(value: str, *, field: str, maximum: int) -> str:
|
|
"""Проверяет строку, которую предстоит сохранить в PostgreSQL.
|
|
|
|
U+0000 отвергается на границе: тип `text` его не хранит, и без этой проверки
|
|
ошибка данных клиента дошла бы до обработчика ошибок базы, где выглядела бы
|
|
отказом зависимости.
|
|
"""
|
|
_require_content(value, field=field)
|
|
if "\u0000" in value:
|
|
raise ValueError(f"{field} must not contain U+0000")
|
|
if len(value) > maximum:
|
|
raise ValueError(f"{field} must be at most {maximum} Unicode code points")
|
|
return value
|
|
|
|
|
|
class Health(BaseModel):
|
|
"""Тело ответа /health/live и /health/ready."""
|
|
|
|
model_config = ConfigDict(extra="forbid")
|
|
|
|
status: Literal["ok"] = "ok"
|
|
|
|
|
|
class User(BaseModel):
|
|
"""Публичное представление пользователя: ни пароля, ни сессий здесь нет."""
|
|
|
|
model_config = ConfigDict(extra="forbid")
|
|
|
|
id: UUID
|
|
username: str
|
|
display_name: str
|
|
created_at: str
|
|
|
|
@classmethod
|
|
def from_record(cls, record: UserRecord) -> "User":
|
|
return cls(
|
|
id=record.id,
|
|
username=record.username,
|
|
display_name=record.display_name,
|
|
created_at=rfc3339_z(record.created_at),
|
|
)
|
|
|
|
|
|
class CreateUser(BaseModel):
|
|
"""Регистрация: пароль приходит открытым текстом и дальше живёт только как хэш."""
|
|
|
|
model_config = ConfigDict(extra="forbid")
|
|
|
|
username: str = Field(pattern=USERNAME_PATTERN)
|
|
display_name: str
|
|
password: str = Field(min_length=MIN_PASSWORD, max_length=MAX_PASSWORD)
|
|
|
|
@field_validator("display_name")
|
|
@classmethod
|
|
def _check_display_name(cls, value: str) -> str:
|
|
return _visible(value, field="display_name", maximum=MAX_DISPLAY_NAME)
|
|
|
|
@field_validator("password")
|
|
@classmethod
|
|
def _check_password(cls, value: str) -> str:
|
|
"""Пароль из одних пробелов — пустое значение, а не секрет.
|
|
|
|
Пробелы внутри и по краям допустимы и не обрезаются: при входе пароль
|
|
сверяется целиком. U+0000 здесь не проверяется: в PostgreSQL попадает
|
|
только хэш, а не сам пароль.
|
|
"""
|
|
return _require_content(value, field="password")
|
|
|
|
|
|
class Session(BaseModel):
|
|
"""Выданная сессия: токен показывается клиенту один раз и в логи не попадает."""
|
|
|
|
model_config = ConfigDict(extra="forbid")
|
|
|
|
token: str
|
|
token_type: Literal["Bearer"] = "Bearer"
|
|
expires_at: str
|
|
user: User
|
|
|
|
@classmethod
|
|
def from_issued(cls, issued: IssuedSession, user: UserRecord) -> "Session":
|
|
return cls(
|
|
token=issued.token,
|
|
expires_at=rfc3339_z(issued.state.expires_at),
|
|
user=User.from_record(user),
|
|
)
|
|
|
|
|
|
class Chat(BaseModel):
|
|
model_config = ConfigDict(extra="forbid")
|
|
|
|
id: UUID
|
|
title: str
|
|
member_ids: list[UUID]
|
|
created_at: str
|
|
|
|
@classmethod
|
|
def from_record(cls, record: ChatRecord) -> "Chat":
|
|
return cls(
|
|
id=record.id,
|
|
title=record.title,
|
|
member_ids=list(record.member_ids),
|
|
created_at=rfc3339_z(record.created_at),
|
|
)
|
|
|
|
|
|
class CreateChat(BaseModel):
|
|
model_config = ConfigDict(extra="forbid")
|
|
|
|
title: str
|
|
member_ids: list[UUID]
|
|
|
|
@field_validator("title")
|
|
@classmethod
|
|
def _check_title(cls, value: str) -> str:
|
|
return _visible(value, field="title", maximum=MAX_TITLE)
|
|
|
|
@field_validator("member_ids")
|
|
@classmethod
|
|
def _check_member_ids(cls, value: list[UUID]) -> list[UUID]:
|
|
if not 1 <= len(value) <= MAX_MEMBERS:
|
|
raise ValueError(f"member_ids must contain 1..{MAX_MEMBERS} items")
|
|
if len(set(value)) != len(value):
|
|
raise ValueError("member_ids must not contain duplicates")
|
|
return value
|
|
|
|
|
|
class Message(BaseModel):
|
|
model_config = ConfigDict(extra="forbid")
|
|
|
|
id: UUID
|
|
chat_id: UUID
|
|
sender_id: UUID
|
|
text: str
|
|
created_at: str
|
|
|
|
@classmethod
|
|
def from_record(cls, record: MessageRecord) -> "Message":
|
|
return cls(
|
|
id=record.id,
|
|
chat_id=record.chat_id,
|
|
sender_id=record.sender_id,
|
|
text=record.text,
|
|
created_at=rfc3339_z(record.created_at),
|
|
)
|
|
|
|
|
|
class CreateMessage(BaseModel):
|
|
"""Поле sender_id не принимается: отправитель выводится из идентификации."""
|
|
|
|
model_config = ConfigDict(extra="forbid")
|
|
|
|
text: str
|
|
|
|
@field_validator("text")
|
|
@classmethod
|
|
def _check_text(cls, value: str) -> str:
|
|
return _visible(value, field="text", maximum=MAX_TEXT)
|
|
|
|
|
|
class ChatPage(BaseModel):
|
|
model_config = ConfigDict(extra="forbid")
|
|
|
|
items: list[Chat]
|
|
next_cursor: str | None
|
|
|
|
@classmethod
|
|
def from_records(cls, records: list[ChatRecord], next_cursor: str | None) -> "ChatPage":
|
|
return cls(items=[Chat.from_record(record) for record in records], next_cursor=next_cursor)
|
|
|
|
|
|
class MessagePage(BaseModel):
|
|
model_config = ConfigDict(extra="forbid")
|
|
|
|
items: list[Message]
|
|
next_cursor: str | None
|
|
|
|
@classmethod
|
|
def from_records(cls, records: list[MessageRecord], next_cursor: str | None) -> "MessagePage":
|
|
return cls(items=[Message.from_record(record) for record in records], next_cursor=next_cursor)
|