"""Strict request models for the lab 2 API.""" from __future__ import annotations import re import uuid from pydantic import BaseModel, ConfigDict, Field, field_validator USERNAME_PATTERN = re.compile(r"^[a-z0-9_]{3,32}$") PASSWORD_MIN_LENGTH = 12 PASSWORD_MAX_LENGTH = 128 class StrictModel(BaseModel): model_config = ConfigDict(extra="forbid", strict=True) def _not_blank(value: str, field: str) -> str: if not value.strip(): raise ValueError(field + " must not be blank") return value class CreateUser(StrictModel): """Registration body; the password never appears in a response.""" username: str = Field( min_length=3, max_length=32, pattern=USERNAME_PATTERN.pattern ) display_name: str = Field(min_length=1, max_length=100) password: str = Field( min_length=PASSWORD_MIN_LENGTH, max_length=PASSWORD_MAX_LENGTH ) @field_validator("display_name") @classmethod def display_name_is_not_blank(cls, value: str) -> str: return _not_blank(value, "display_name") @field_validator("password") @classmethod def password_length_in_code_points(cls, value: str) -> str: # Python len() counts Unicode code points, which is what the contract uses. if not PASSWORD_MIN_LENGTH <= len(value) <= PASSWORD_MAX_LENGTH: raise ValueError("password length is out of range") return value class CreateChat(StrictModel): 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 title_is_not_blank(cls, value: str) -> str: return _not_blank(value, "title") @field_validator("member_ids") @classmethod def members_are_valid_and_unique(cls, value: list[str]) -> list[str]: try: normalized = [str(uuid.UUID(member_id)) for member_id in value] except (ValueError, AttributeError): raise ValueError("member_ids must contain UUID strings") from None if len(normalized) != len(set(normalized)): raise ValueError("member_ids must be unique") return normalized class CreateMessage(StrictModel): text: str = Field(min_length=1, max_length=4000) @field_validator("text") @classmethod def text_is_not_blank(cls, value: str) -> str: return _not_blank(value, "text")