Files
mtusi2026lab3/src/messenger/domain.py
T
2026-11-06 18:09:01 +03:00

84 lines
2.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Сущности предметной области, порядок сортировки и формат метки времени."""
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime, timezone
from typing import Protocol, Sequence
from uuid import UUID
def utc_now() -> datetime:
return datetime.now(timezone.utc)
def rfc3339_z(moment: datetime) -> str:
"""RFC 3339 в UTC с суффиксом Z и микросекундной точностью."""
return moment.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")
def parse_rfc3339_z(value: str) -> datetime:
"""Разбирает метку в формате `rfc3339_z`; иначе ValueError."""
if not value.endswith("Z"):
raise ValueError("timestamp is not UTC with Z suffix")
return datetime.fromisoformat(value[:-1] + "+00:00")
class Sortable(Protocol):
"""Общая часть записей: пара, по которой строится порядок и keyset-курсор.
Порядок выборок — (created_at, id) по возрастанию. UUID упорядочивается
своим целым значением (так же, как `uuid.UUID(x).int` в публичном smoke),
поэтому порядок PostgreSQL и порядок клиента совпадают.
"""
created_at: datetime
id: UUID
# Место в этом порядке, откуда продолжается выборка: пара (created_at, id).
Position = tuple[datetime, UUID]
class UsernameTaken(Exception):
"""username уже занят другим пользователем."""
class UnknownMembers(Exception):
"""В member_ids есть идентификаторы несуществующих пользователей."""
def __init__(self, member_ids: Sequence[UUID]) -> None:
super().__init__("unknown members")
self.member_ids = tuple(member_ids)
class IdempotencyConflict(Exception):
"""Тот же ключ идемпотентности использован с другим телом запроса."""
@dataclass(frozen=True)
class UserRecord:
id: UUID
username: str
display_name: str
created_at: datetime
@dataclass(frozen=True)
class ChatRecord:
id: UUID
title: str
member_ids: tuple[UUID, ...]
created_at: datetime
def has_member(self, user_id: UUID) -> bool:
"""Состав участников задаётся при создании и не меняется."""
return user_id in self.member_ids
@dataclass(frozen=True)
class MessageRecord:
id: UUID
chat_id: UUID
sender_id: UUID
text: str
created_at: datetime