forked from mtusi2026/mtusi2026lab2
feat: complete lab2 with postgres, auth, migrations, and persistence
This commit is contained in:
@@ -18,3 +18,5 @@ __pycache__
|
|||||||
node_modules
|
node_modules
|
||||||
evidence
|
evidence
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
.venv
|
||||||
|
venv
|
||||||
|
|||||||
+27
@@ -0,0 +1,27 @@
|
|||||||
|
FROM python:3.12-slim
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# ДОБАВЛЯЕМ curl В СПИСОК УСТАНАВЛИВАЕМЫХ ПАКЕТОВ
|
||||||
|
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||||
|
make \
|
||||||
|
curl \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
RUN groupadd -r appgroup && useradd -r -g appgroup appuser
|
||||||
|
|
||||||
|
COPY requirements.txt requirements-dev.txt ./
|
||||||
|
RUN pip install --no-cache-dir -r requirements.txt -r requirements-dev.txt
|
||||||
|
|
||||||
|
COPY src/ ./src/
|
||||||
|
COPY tests/ ./tests/
|
||||||
|
COPY scripts/ ./scripts/
|
||||||
|
COPY contracts/ ./contracts/
|
||||||
|
COPY Makefile lab.json ./
|
||||||
|
|
||||||
|
RUN chown -R appuser:appgroup /app
|
||||||
|
|
||||||
|
USER appuser
|
||||||
|
|
||||||
|
# Exec-форма для корректного получения SIGTERM
|
||||||
|
CMD ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8080"]
|
||||||
@@ -1,37 +1,49 @@
|
|||||||
# Отчёт — лабораторная 2
|
# Отчёт по Лабораторной работе №2: PostgreSQL, сессии и аутентификация
|
||||||
|
|
||||||
- Автор, группа: TODO
|
## Целевая оценка
|
||||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
**4** (Реализованы все требования базового уровня, а также требования уровня стажёра: параметризованные запросы, connection pool, индексы, атомарные операции и надежное хранение сессий с TTL).
|
||||||
- Commit/PR: TODO после публикации
|
|
||||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
|
||||||
|
|
||||||
## Запуск из чистого clone
|
## Архитектура решения
|
||||||
|
- **Framework**: FastAPI (асинхронный)
|
||||||
|
- **ORM / Database Driver**: SQLAlchemy 2.0 + `asyncpg` (обеспечивает встроенный connection pool и высокую производительность)
|
||||||
|
- **База данных**: PostgreSQL 16 (хранение пользователей, сессий, чатов и сообщений)
|
||||||
|
- **Миграции**: Alembic (версионированное управление схемой БД)
|
||||||
|
- **Безопасность**: `bcrypt` для хеширования паролей, криптографически стойкие opaque Bearer-токены с TTL (24 часа).
|
||||||
|
|
||||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
## Реализованные требования
|
||||||
|
|
||||||
## Архитектура и решения
|
### 1. Переход на постоянное хранилище (PostgreSQL)
|
||||||
|
- Все данные (Users, Sessions, Chats, ChatMembers, Messages) перенесены из in-memory в PostgreSQL.
|
||||||
|
- Настроены **версионированные миграции** через Alembic (`alembic/versions/`). Команда `alembic upgrade head` разворачивает схему с нуля.
|
||||||
|
- Составная операция создания чата (создание Chat + запись в ChatMember) выполняется **атомарно** в рамках одной транзакции SQLAlchemy.
|
||||||
|
|
||||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
### 2. Аутентификация и сессии
|
||||||
|
- При регистрации поле `password` обязательно и хешируется с помощью `bcrypt` (KDF).
|
||||||
|
- Реализован эндпоинт `POST /api/v1/auth/sessions`, принимающий HTTP Basic Auth и выдающий opaque Bearer-токен.
|
||||||
|
- Сессии хранятся в таблице `sessions` с полем `expires_at`. При каждом запросе проверяется актуальность токена.
|
||||||
|
- Реализован отзыв сессии (logout) через `DELETE /api/v1/auth/sessions/current`.
|
||||||
|
|
||||||
## Доказательства критериев
|
### 3. Безопасность и изоляция данных
|
||||||
|
- Все защищённые эндпоинты используют зависимость `get_current_user`, которая извлекает токен из заголовка `Authorization: Bearer <token>`.
|
||||||
|
- Реализована защита от несанкционированного доступа: при попытке прочитать чужой чат или сообщения возвращается **404 Not Found** (Security by Obscurity), а не 403.
|
||||||
|
- Добавлен глобальный обработчик ошибок, приводящий все ответы к единому формату OpenAPI-контракта с заголовком `X-Request-Id`.
|
||||||
|
|
||||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
### 4. Оптимизация и надёжность (Уровень 4)
|
||||||
| --- | --- | --- | --- |
|
- Используются **параметризованные запросы** через SQLAlchemy, что полностью исключает риск SQL-инъекций.
|
||||||
| Публичный smoke | make test | TODO | TODO |
|
- Драйвер `asyncpg` автоматически управляет **connection pool**, предотвращая исчерпание соединений.
|
||||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
- Добавлены **индексы** для ускорения частых операций:
|
||||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
- `ix_users_username` (B-tree) для быстрого поиска при логине и проверке уникальности.
|
||||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
- `ix_messages_created_at` (B-tree) для эффективной курсорной пагинации без полного сканирования таблицы (Full Scan).
|
||||||
|
- Курсорная пагинация реализована корректно: запрашивается `LIMIT + 1` записей, чтобы точно определить наличие следующей страницы (`next_cursor`).
|
||||||
|
|
||||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
### 5. Инфраструктура и воспроизводимость
|
||||||
|
- Приложение и база данных запускаются единой командой `docker compose up -d --build`.
|
||||||
|
- Использованы именованные volumes (`postgres_data`) для сохранения данных.
|
||||||
|
- Настроены `healthcheck` для обоих сервисов, гарантирующие правильный порядок запуска (app ждёт готовности db).
|
||||||
|
- Скрипт `scripts/restart.sh` успешно проходит тест `make test-persistence`, доказывая, что данные и активные сессии переживают перезапуск контейнеров.
|
||||||
|
|
||||||
## Эксперименты и отказы
|
## Как запустить
|
||||||
|
1. Убедитесь, что Docker запущен.
|
||||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
2. Выполните: `docker compose up -d --build`
|
||||||
|
3. Дождитесь статуса `healthy` для обоих сервисов (`docker compose ps`).
|
||||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
4. Запустите тесты: `make test` и `make test-persistence ACTION_SCRIPT=scripts/restart.sh`
|
||||||
| --- | --- | --- | --- |
|
|
||||||
| TODO | TODO | TODO | TODO |
|
|
||||||
|
|
||||||
## Ограничения и следующие шаги
|
|
||||||
|
|
||||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
|
||||||
+149
@@ -0,0 +1,149 @@
|
|||||||
|
# A generic, single database configuration.
|
||||||
|
|
||||||
|
[alembic]
|
||||||
|
# path to migration scripts.
|
||||||
|
# this is typically a path given in POSIX (e.g. forward slashes)
|
||||||
|
# format, relative to the token %(here)s which refers to the location of this
|
||||||
|
# ini file
|
||||||
|
script_location = %(here)s/alembic
|
||||||
|
|
||||||
|
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
|
||||||
|
# Uncomment the line below if you want the files to be prepended with date and time
|
||||||
|
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
|
||||||
|
# for all available tokens
|
||||||
|
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
|
||||||
|
# Or organize into date-based subdirectories (requires recursive_version_locations = true)
|
||||||
|
# file_template = %%(year)d/%%(month).2d/%%(day).2d_%%(hour).2d%%(minute).2d_%%(second).2d_%%(rev)s_%%(slug)s
|
||||||
|
|
||||||
|
# sys.path path, will be prepended to sys.path if present.
|
||||||
|
# defaults to the current working directory. for multiple paths, the path separator
|
||||||
|
# is defined by "path_separator" below.
|
||||||
|
prepend_sys_path = .
|
||||||
|
|
||||||
|
|
||||||
|
# timezone to use when rendering the date within the migration file
|
||||||
|
# as well as the filename.
|
||||||
|
# If specified, requires the tzdata library which can be installed by adding
|
||||||
|
# `alembic[tz]` to the pip requirements.
|
||||||
|
# string value is passed to ZoneInfo()
|
||||||
|
# leave blank for localtime
|
||||||
|
# timezone =
|
||||||
|
|
||||||
|
# max length of characters to apply to the "slug" field
|
||||||
|
# truncate_slug_length = 40
|
||||||
|
|
||||||
|
# set to 'true' to run the environment during
|
||||||
|
# the 'revision' command, regardless of autogenerate
|
||||||
|
# revision_environment = false
|
||||||
|
|
||||||
|
# set to 'true' to allow .pyc and .pyo files without
|
||||||
|
# a source .py file to be detected as revisions in the
|
||||||
|
# versions/ directory
|
||||||
|
# sourceless = false
|
||||||
|
|
||||||
|
# version location specification; This defaults
|
||||||
|
# to <script_location>/versions. When using multiple version
|
||||||
|
# directories, initial revisions must be specified with --version-path.
|
||||||
|
# The path separator used here should be the separator specified by "path_separator"
|
||||||
|
# below.
|
||||||
|
# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions
|
||||||
|
|
||||||
|
# path_separator; This indicates what character is used to split lists of file
|
||||||
|
# paths, including version_locations and prepend_sys_path within configparser
|
||||||
|
# files such as alembic.ini.
|
||||||
|
# The default rendered in new alembic.ini files is "os", which uses os.pathsep
|
||||||
|
# to provide os-dependent path splitting.
|
||||||
|
#
|
||||||
|
# Note that in order to support legacy alembic.ini files, this default does NOT
|
||||||
|
# take place if path_separator is not present in alembic.ini. If this
|
||||||
|
# option is omitted entirely, fallback logic is as follows:
|
||||||
|
#
|
||||||
|
# 1. Parsing of the version_locations option falls back to using the legacy
|
||||||
|
# "version_path_separator" key, which if absent then falls back to the legacy
|
||||||
|
# behavior of splitting on spaces and/or commas.
|
||||||
|
# 2. Parsing of the prepend_sys_path option falls back to the legacy
|
||||||
|
# behavior of splitting on spaces, commas, or colons.
|
||||||
|
#
|
||||||
|
# Valid values for path_separator are:
|
||||||
|
#
|
||||||
|
# path_separator = :
|
||||||
|
# path_separator = ;
|
||||||
|
# path_separator = space
|
||||||
|
# path_separator = newline
|
||||||
|
#
|
||||||
|
# Use os.pathsep. Default configuration used for new projects.
|
||||||
|
path_separator = os
|
||||||
|
|
||||||
|
# set to 'true' to search source files recursively
|
||||||
|
# in each "version_locations" directory
|
||||||
|
# new in Alembic version 1.10
|
||||||
|
# recursive_version_locations = false
|
||||||
|
|
||||||
|
# the output encoding used when revision files
|
||||||
|
# are written from script.py.mako
|
||||||
|
# output_encoding = utf-8
|
||||||
|
|
||||||
|
# database URL. This is consumed by the user-maintained env.py script only.
|
||||||
|
# other means of configuring database URLs may be customized within the env.py
|
||||||
|
# file.
|
||||||
|
sqlalchemy.url = postgresql+asyncpg://app_user:secure_password_123@localhost:5432/messenger_db
|
||||||
|
|
||||||
|
|
||||||
|
[post_write_hooks]
|
||||||
|
# post_write_hooks defines scripts or Python functions that are run
|
||||||
|
# on newly generated revision scripts. See the documentation for further
|
||||||
|
# detail and examples
|
||||||
|
|
||||||
|
# format using "black" - use the console_scripts runner, against the "black" entrypoint
|
||||||
|
# hooks = black
|
||||||
|
# black.type = console_scripts
|
||||||
|
# black.entrypoint = black
|
||||||
|
# black.options = -l 79 REVISION_SCRIPT_FILENAME
|
||||||
|
|
||||||
|
# lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module
|
||||||
|
# hooks = ruff
|
||||||
|
# ruff.type = module
|
||||||
|
# ruff.module = ruff
|
||||||
|
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
|
||||||
|
|
||||||
|
# Alternatively, use the exec runner to execute a binary found on your PATH
|
||||||
|
# hooks = ruff
|
||||||
|
# ruff.type = exec
|
||||||
|
# ruff.executable = ruff
|
||||||
|
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
|
||||||
|
|
||||||
|
# Logging configuration. This is also consumed by the user-maintained
|
||||||
|
# env.py script only.
|
||||||
|
[loggers]
|
||||||
|
keys = root,sqlalchemy,alembic
|
||||||
|
|
||||||
|
[handlers]
|
||||||
|
keys = console
|
||||||
|
|
||||||
|
[formatters]
|
||||||
|
keys = generic
|
||||||
|
|
||||||
|
[logger_root]
|
||||||
|
level = WARNING
|
||||||
|
handlers = console
|
||||||
|
qualname =
|
||||||
|
|
||||||
|
[logger_sqlalchemy]
|
||||||
|
level = WARNING
|
||||||
|
handlers =
|
||||||
|
qualname = sqlalchemy.engine
|
||||||
|
|
||||||
|
[logger_alembic]
|
||||||
|
level = INFO
|
||||||
|
handlers =
|
||||||
|
qualname = alembic
|
||||||
|
|
||||||
|
[handler_console]
|
||||||
|
class = StreamHandler
|
||||||
|
args = (sys.stderr,)
|
||||||
|
level = NOTSET
|
||||||
|
formatter = generic
|
||||||
|
|
||||||
|
[formatter_generic]
|
||||||
|
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||||
|
datefmt = %H:%M:%S
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
Generic single-database configuration.
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
import asyncio
|
||||||
|
from logging.config import fileConfig
|
||||||
|
from sqlalchemy import pool
|
||||||
|
from sqlalchemy.engine import Connection
|
||||||
|
from sqlalchemy.ext.asyncio import async_engine_from_config
|
||||||
|
|
||||||
|
from alembic import context
|
||||||
|
|
||||||
|
# 1. Импортируем наши настройки и модели
|
||||||
|
from src.database import DATABASE_URL, Base
|
||||||
|
from src import models # Обязательно! Чтобы Alembic "увидел" наши таблицы
|
||||||
|
|
||||||
|
config = context.config
|
||||||
|
|
||||||
|
# Настройка логирования
|
||||||
|
if config.config_file_name is not None:
|
||||||
|
fileConfig(config.config_file_name)
|
||||||
|
|
||||||
|
# Метаданные для autogenerate
|
||||||
|
target_metadata = Base.metadata
|
||||||
|
|
||||||
|
# Переопределяем URL подключения из нашего .env (игнорируем alembic.ini)
|
||||||
|
config.set_main_option("sqlalchemy.url", "postgresql+asyncpg://postgres:postgres@localhost:5433/messenger_db")
|
||||||
|
|
||||||
|
def run_migrations_offline() -> None:
|
||||||
|
"""Запуск миграций в 'offline' режиме (без подключения к БД)."""
|
||||||
|
url = config.get_main_option("sqlalchemy.url")
|
||||||
|
context.configure(
|
||||||
|
url=url,
|
||||||
|
target_metadata=target_metadata,
|
||||||
|
literal_binds=True,
|
||||||
|
dialect_opts={"paramstyle": "named"},
|
||||||
|
)
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
def do_run_migrations(connection: Connection) -> None:
|
||||||
|
"""Непосредственно применение миграций к соединению."""
|
||||||
|
context.configure(connection=connection, target_metadata=target_metadata)
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
async def run_async_migrations() -> None:
|
||||||
|
"""Асинхронный запуск миграций."""
|
||||||
|
connectable = async_engine_from_config(
|
||||||
|
config.get_section(config.config_ini_section, {}),
|
||||||
|
prefix="sqlalchemy.",
|
||||||
|
poolclass=pool.NullPool,
|
||||||
|
)
|
||||||
|
|
||||||
|
async with connectable.connect() as connection:
|
||||||
|
await connection.run_sync(do_run_migrations)
|
||||||
|
|
||||||
|
await connectable.dispose()
|
||||||
|
|
||||||
|
def run_migrations_online() -> None:
|
||||||
|
"""Запуск миграций в 'online' режиме."""
|
||||||
|
asyncio.run(run_async_migrations())
|
||||||
|
|
||||||
|
# Точка входа Alembic
|
||||||
|
if context.is_offline_mode():
|
||||||
|
run_migrations_offline()
|
||||||
|
else:
|
||||||
|
run_migrations_online()
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
"""${message}
|
||||||
|
|
||||||
|
Revision ID: ${up_revision}
|
||||||
|
Revises: ${down_revision | comma,n}
|
||||||
|
Create Date: ${create_date}
|
||||||
|
|
||||||
|
"""
|
||||||
|
from typing import Sequence, Union
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
${imports if imports else ""}
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision: str = ${repr(up_revision)}
|
||||||
|
down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)}
|
||||||
|
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
|
||||||
|
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
"""Upgrade schema."""
|
||||||
|
${upgrades if upgrades else "pass"}
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
"""Downgrade schema."""
|
||||||
|
${downgrades if downgrades else "pass"}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
"""initial tables
|
||||||
|
|
||||||
|
Revision ID: d74c0ccadc85
|
||||||
|
Revises:
|
||||||
|
Create Date: 2026-11-03 11:36:06.290700
|
||||||
|
|
||||||
|
"""
|
||||||
|
from typing import Sequence, Union
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision: str = 'd74c0ccadc85'
|
||||||
|
down_revision: Union[str, Sequence[str], None] = None
|
||||||
|
branch_labels: Union[str, Sequence[str], None] = None
|
||||||
|
depends_on: Union[str, Sequence[str], None] = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
"""Upgrade schema."""
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.create_table('chats',
|
||||||
|
sa.Column('id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('title', sa.String(length=100), nullable=False),
|
||||||
|
sa.Column('created_at', sa.DateTime(timezone=True), nullable=True),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
op.create_table('users',
|
||||||
|
sa.Column('id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('username', sa.String(length=32), nullable=False),
|
||||||
|
sa.Column('display_name', sa.String(length=100), nullable=False),
|
||||||
|
sa.Column('password_hash', sa.String(length=255), nullable=False),
|
||||||
|
sa.Column('created_at', sa.DateTime(timezone=True), nullable=True),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
op.create_index(op.f('ix_users_username'), 'users', ['username'], unique=True)
|
||||||
|
op.create_table('chat_members',
|
||||||
|
sa.Column('chat_id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('user_id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('joined_at', sa.DateTime(timezone=True), nullable=True),
|
||||||
|
sa.ForeignKeyConstraint(['chat_id'], ['chats.id'], ondelete='CASCADE'),
|
||||||
|
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'),
|
||||||
|
sa.PrimaryKeyConstraint('chat_id', 'user_id')
|
||||||
|
)
|
||||||
|
op.create_table('messages',
|
||||||
|
sa.Column('id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('chat_id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('sender_id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('text', sa.Text(), nullable=False),
|
||||||
|
sa.Column('created_at', sa.DateTime(timezone=True), nullable=True),
|
||||||
|
sa.ForeignKeyConstraint(['chat_id'], ['chats.id'], ondelete='CASCADE'),
|
||||||
|
sa.ForeignKeyConstraint(['sender_id'], ['users.id'], ondelete='CASCADE'),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
op.create_index(op.f('ix_messages_chat_id'), 'messages', ['chat_id'], unique=False)
|
||||||
|
op.create_index(op.f('ix_messages_created_at'), 'messages', ['created_at'], unique=False)
|
||||||
|
op.create_table('sessions',
|
||||||
|
sa.Column('id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('user_id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('token', sa.String(length=255), nullable=False),
|
||||||
|
sa.Column('expires_at', sa.DateTime(timezone=True), nullable=False),
|
||||||
|
sa.Column('created_at', sa.DateTime(timezone=True), nullable=True),
|
||||||
|
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
op.create_index(op.f('ix_sessions_token'), 'sessions', ['token'], unique=True)
|
||||||
|
# ### end Alembic commands ###
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
"""Downgrade schema."""
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.drop_index(op.f('ix_sessions_token'), table_name='sessions')
|
||||||
|
op.drop_table('sessions')
|
||||||
|
op.drop_index(op.f('ix_messages_created_at'), table_name='messages')
|
||||||
|
op.drop_index(op.f('ix_messages_chat_id'), table_name='messages')
|
||||||
|
op.drop_table('messages')
|
||||||
|
op.drop_table('chat_members')
|
||||||
|
op.drop_index(op.f('ix_users_username'), table_name='users')
|
||||||
|
op.drop_table('users')
|
||||||
|
op.drop_table('chats')
|
||||||
|
# ### end Alembic commands ###
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
services:
|
||||||
|
db:
|
||||||
|
image: postgres:16-alpine
|
||||||
|
container_name: lab2_postgres
|
||||||
|
environment:
|
||||||
|
POSTGRES_USER: postgres
|
||||||
|
POSTGRES_PASSWORD: postgres
|
||||||
|
POSTGRES_DB: messenger_db
|
||||||
|
ports:
|
||||||
|
- "5433:5432" # Пробрасываем на 5433, чтобы не конфликтовать с локальным Mac PG
|
||||||
|
volumes:
|
||||||
|
- postgres_data:/var/lib/postgresql/data
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U postgres -d messenger_db"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 5
|
||||||
|
|
||||||
|
app:
|
||||||
|
build: .
|
||||||
|
container_name: lab2_app
|
||||||
|
environment:
|
||||||
|
# Внутри Docker сеть имя сервиса 'db' резолвится в IP контейнера базы, порт 5432
|
||||||
|
- DATABASE_URL=postgresql+asyncpg://postgres:postgres@db:5432/messenger_db
|
||||||
|
ports:
|
||||||
|
- "8080:8080"
|
||||||
|
depends_on:
|
||||||
|
db:
|
||||||
|
condition: service_healthy
|
||||||
|
restart: unless-stopped
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "curl", "-f", "http://localhost:8080/health/ready"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
postgres_data:
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
# Web framework
|
||||||
|
fastapi==0.115.0
|
||||||
|
uvicorn==0.30.6
|
||||||
|
pydantic==2.9.2
|
||||||
|
|
||||||
|
# Database & Migrations
|
||||||
|
sqlalchemy==2.0.35
|
||||||
|
asyncpg==0.30.0
|
||||||
|
alembic==1.13.3
|
||||||
|
|
||||||
|
# Security
|
||||||
|
bcrypt==4.2.0
|
||||||
Executable
+14
@@ -0,0 +1,14 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
# Скрипт для перезапуска сервисов с сохранением volumes (доказательство работы БД)
|
||||||
|
set -e
|
||||||
|
|
||||||
|
echo "🔄 Перезапускаем сервисы (сохраняя volumes)..."
|
||||||
|
docker compose restart app db
|
||||||
|
|
||||||
|
echo "⏳ Ожидаем восстановления healthcheck (10 секунд)..."
|
||||||
|
sleep 10
|
||||||
|
|
||||||
|
# Проверяем, что сервисы снова healthy
|
||||||
|
docker compose ps | grep -q "healthy" || (echo "❌ Сервисы не стали healthy!" && exit 1)
|
||||||
|
|
||||||
|
echo "✅ Сервисы успешно перезапущены и готовы к работе!"
|
||||||
+20
@@ -0,0 +1,20 @@
|
|||||||
|
import secrets
|
||||||
|
import bcrypt
|
||||||
|
from datetime import datetime, timezone, timedelta
|
||||||
|
|
||||||
|
def hash_password(plain_password: str) -> str:
|
||||||
|
"""Хеширует пароль с использованием bcrypt."""
|
||||||
|
salt = bcrypt.gensalt()
|
||||||
|
return bcrypt.hashpw(plain_password.encode('utf-8'), salt).decode('utf-8')
|
||||||
|
|
||||||
|
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
||||||
|
"""Проверяет, совпадает ли пароль с хешем."""
|
||||||
|
return bcrypt.checkpw(plain_password.encode('utf-8'), hashed_password.encode('utf-8'))
|
||||||
|
|
||||||
|
def generate_token() -> str:
|
||||||
|
"""Генерирует криптографически стойкий opaque-токен."""
|
||||||
|
return secrets.token_urlsafe(32)
|
||||||
|
|
||||||
|
def get_token_expiry(hours: int = 24) -> datetime:
|
||||||
|
"""Возвращает время истечения срока действия токена."""
|
||||||
|
return datetime.now(timezone.utc) + timedelta(hours=hours)
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import os
|
||||||
|
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
|
||||||
|
from sqlalchemy.orm import DeclarativeBase
|
||||||
|
|
||||||
|
DATABASE_URL = os.getenv(
|
||||||
|
"DATABASE_URL",
|
||||||
|
"postgresql+asyncpg://postgres:postgres@localhost:5432/messenger_db"
|
||||||
|
)
|
||||||
|
|
||||||
|
engine = create_async_engine(
|
||||||
|
DATABASE_URL,
|
||||||
|
echo=False,
|
||||||
|
pool_pre_ping=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
async_session_maker = async_sessionmaker(
|
||||||
|
engine, class_=AsyncSession, expire_on_commit=False
|
||||||
|
)
|
||||||
|
|
||||||
|
class Base(DeclarativeBase):
|
||||||
|
pass
|
||||||
|
|
||||||
|
async def get_db():
|
||||||
|
async with async_session_maker() as session:
|
||||||
|
yield session
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
from fastapi import Depends, HTTPException, status, Security
|
||||||
|
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
from sqlalchemy import select
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
from src.database import get_db
|
||||||
|
from src.models import Session, User
|
||||||
|
|
||||||
|
# auto_error=False позволяет нам самим контролировать ответ при отсутствии заголовка
|
||||||
|
security = HTTPBearer(auto_error=False)
|
||||||
|
|
||||||
|
async def get_current_user(
|
||||||
|
credentials: HTTPAuthorizationCredentials = Security(security),
|
||||||
|
db: AsyncSession = Depends(get_db)
|
||||||
|
) -> User:
|
||||||
|
# 1. Проверяем наличие заголовка Authorization
|
||||||
|
if not credentials:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="Missing authentication credentials",
|
||||||
|
headers={"WWW-Authenticate": 'Bearer realm="messenger"'}
|
||||||
|
)
|
||||||
|
|
||||||
|
token = credentials.credentials
|
||||||
|
|
||||||
|
# 2. Ищем сессию по токену
|
||||||
|
result = await db.execute(select(Session).where(Session.token == token))
|
||||||
|
session = result.scalar_one_or_none()
|
||||||
|
|
||||||
|
if not session:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="Invalid or unknown token",
|
||||||
|
headers={"WWW-Authenticate": 'Bearer realm="messenger"'}
|
||||||
|
)
|
||||||
|
|
||||||
|
# 3. Проверяем, не истёк ли токен
|
||||||
|
if session.expires_at < datetime.now(timezone.utc):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="Token expired",
|
||||||
|
headers={"WWW-Authenticate": 'Bearer realm="messenger"'}
|
||||||
|
)
|
||||||
|
|
||||||
|
# 4. Получаем пользователя, привязанного к сессии
|
||||||
|
result = await db.execute(select(User).where(User.id == session.user_id))
|
||||||
|
user = result.scalar_one_or_none()
|
||||||
|
|
||||||
|
if not user:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="User not found",
|
||||||
|
headers={"WWW-Authenticate": 'Bearer realm="messenger"'}
|
||||||
|
)
|
||||||
|
|
||||||
|
return user
|
||||||
+270
@@ -0,0 +1,270 @@
|
|||||||
|
import uuid
|
||||||
|
from fastapi import FastAPI, Depends, HTTPException, status, Query, Request, Security
|
||||||
|
from fastapi.responses import JSONResponse
|
||||||
|
from fastapi.security import HTTPBasic, HTTPBasicCredentials
|
||||||
|
from fastapi.exceptions import RequestValidationError
|
||||||
|
from starlette.middleware.base import BaseHTTPMiddleware
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
from sqlalchemy import select, func, and_, delete
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from src.database import get_db
|
||||||
|
from src.models import User, Session, Chat, ChatMember, Message
|
||||||
|
from src.schemas import UserCreate, UserResponse, SessionResponse, CreateChat, CreateMessage, format_dt
|
||||||
|
from src.auth import hash_password, verify_password, generate_token, get_token_expiry
|
||||||
|
from src.dependencies import get_current_user
|
||||||
|
|
||||||
|
app = FastAPI(title="Messenger API", version="2.0.0")
|
||||||
|
@app.exception_handler(RequestValidationError)
|
||||||
|
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
||||||
|
request_id = getattr(request.state, "request_id", str(uuid.uuid4()))
|
||||||
|
|
||||||
|
# Собираем все ошибки валидации в одну понятную строку
|
||||||
|
error_details = []
|
||||||
|
for err in exc.errors():
|
||||||
|
field = ".".join(str(x) for x in err.get("loc", []) if x != "body")
|
||||||
|
msg = err.get("msg", "Invalid value")
|
||||||
|
error_details.append(f"{field}: {msg}" if field else msg)
|
||||||
|
|
||||||
|
message = ", ".join(error_details) if error_details else "Invalid request payload"
|
||||||
|
|
||||||
|
return JSONResponse(
|
||||||
|
status_code=status.HTTP_400_BAD_REQUEST, # <-- Тест ожидает именно 400, а не 422
|
||||||
|
content={
|
||||||
|
"error": {
|
||||||
|
"code": "invalid_request",
|
||||||
|
"message": message,
|
||||||
|
"request_id": request_id
|
||||||
|
}
|
||||||
|
},
|
||||||
|
headers={"X-Request-Id": request_id}
|
||||||
|
)
|
||||||
|
# 1. Middleware для X-Request-Id
|
||||||
|
class RequestIDMiddleware(BaseHTTPMiddleware):
|
||||||
|
async def dispatch(self, request: Request, call_next):
|
||||||
|
request_id = str(uuid.uuid4())
|
||||||
|
request.state.request_id = request_id
|
||||||
|
response = await call_next(request)
|
||||||
|
response.headers["X-Request-Id"] = request_id
|
||||||
|
return response
|
||||||
|
|
||||||
|
app.add_middleware(RequestIDMiddleware)
|
||||||
|
|
||||||
|
# 2. Глобальный обработчик ошибок под формат OpenAPI
|
||||||
|
@app.exception_handler(HTTPException)
|
||||||
|
async def custom_http_exception_handler(request: Request, exc: HTTPException):
|
||||||
|
request_id = getattr(request.state, "request_id", str(uuid.uuid4()))
|
||||||
|
code_map = {
|
||||||
|
400: "invalid_request", 401: "unauthorized", 403: "unauthorized",
|
||||||
|
404: "not_found", 409: "conflict", 413: "payload_too_large",
|
||||||
|
415: "unsupported_media_type", 429: "rate_limited", 503: "unavailable", 500: "internal_error"
|
||||||
|
}
|
||||||
|
code = code_map.get(exc.status_code, "internal_error")
|
||||||
|
message = exc.detail if isinstance(exc.detail, str) else "An error occurred"
|
||||||
|
|
||||||
|
headers = dict(exc.headers) if exc.headers else {}
|
||||||
|
headers["X-Request-Id"] = request_id
|
||||||
|
|
||||||
|
return JSONResponse(status_code=exc.status_code, content={
|
||||||
|
"error": {"code": code, "message": message, "request_id": request_id}
|
||||||
|
}, headers=headers)
|
||||||
|
|
||||||
|
# --- Healthcheck ---
|
||||||
|
@app.get("/health/live")
|
||||||
|
async def health_live():
|
||||||
|
return {"status": "ok"}
|
||||||
|
|
||||||
|
@app.get("/health/ready")
|
||||||
|
async def health_ready(db: AsyncSession = Depends(get_db)):
|
||||||
|
try:
|
||||||
|
await db.execute(select(func.now()))
|
||||||
|
return {"status": "ok"}
|
||||||
|
except Exception:
|
||||||
|
raise HTTPException(status_code=503, detail="Database not ready")
|
||||||
|
|
||||||
|
# --- Регистрация ---
|
||||||
|
@app.post("/api/v1/users", status_code=status.HTTP_201_CREATED, response_model=UserResponse)
|
||||||
|
async def create_user(user_data: UserCreate, db: AsyncSession = Depends(get_db)):
|
||||||
|
result = await db.execute(select(User).where(User.username == user_data.username))
|
||||||
|
if result.scalar_one_or_none():
|
||||||
|
raise HTTPException(status_code=409, detail="Username already exists")
|
||||||
|
|
||||||
|
new_user = User(username=user_data.username, display_name=user_data.display_name, password_hash=hash_password(user_data.password))
|
||||||
|
db.add(new_user)
|
||||||
|
await db.commit()
|
||||||
|
await db.refresh(new_user)
|
||||||
|
|
||||||
|
return UserResponse(id=str(new_user.id), username=new_user.username, display_name=new_user.display_name, created_at=new_user.created_at)
|
||||||
|
|
||||||
|
# --- Аутентификация ---
|
||||||
|
security_basic = HTTPBasic()
|
||||||
|
|
||||||
|
@app.post("/api/v1/auth/sessions", status_code=status.HTTP_201_CREATED, response_model=SessionResponse)
|
||||||
|
async def create_session(credentials: HTTPBasicCredentials = Security(security_basic), db: AsyncSession = Depends(get_db)):
|
||||||
|
result = await db.execute(select(User).where(User.username == credentials.username))
|
||||||
|
user = result.scalar_one_or_none()
|
||||||
|
|
||||||
|
if not user or not verify_password(credentials.password, user.password_hash):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=401,
|
||||||
|
detail="Invalid username or password",
|
||||||
|
headers={"WWW-Authenticate": "Basic"} # <--- ВОТ ЭТА СТРОЧКА РЕШАЕТ ВСЁ
|
||||||
|
)
|
||||||
|
|
||||||
|
token = generate_token()
|
||||||
|
expires_at = get_token_expiry(hours=24)
|
||||||
|
|
||||||
|
new_session = Session(user_id=user.id, token=token, expires_at=expires_at)
|
||||||
|
db.add(new_session)
|
||||||
|
await db.commit()
|
||||||
|
|
||||||
|
return SessionResponse(
|
||||||
|
token=token, token_type="Bearer", expires_at=expires_at,
|
||||||
|
user=UserResponse(id=str(user.id), username=user.username, display_name=user.display_name, created_at=user.created_at)
|
||||||
|
)
|
||||||
|
|
||||||
|
# --- Logout ---
|
||||||
|
@app.delete("/api/v1/auth/sessions/current", status_code=status.HTTP_204_NO_CONTENT)
|
||||||
|
async def delete_session(current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)):
|
||||||
|
await db.execute(delete(Session).where(Session.user_id == current_user.id))
|
||||||
|
await db.commit()
|
||||||
|
|
||||||
|
# --- Текущий пользователь ---
|
||||||
|
@app.get("/api/v1/users/me", response_model=UserResponse)
|
||||||
|
async def get_me(current_user: User = Depends(get_current_user)):
|
||||||
|
return UserResponse(id=str(current_user.id), username=current_user.username, display_name=current_user.display_name, created_at=current_user.created_at)
|
||||||
|
|
||||||
|
# --- Создание чата ---
|
||||||
|
@app.post("/api/v1/chats", status_code=status.HTTP_201_CREATED)
|
||||||
|
async def create_chat(
|
||||||
|
chat_data: CreateChat,
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
db: AsyncSession = Depends(get_db)
|
||||||
|
):
|
||||||
|
if str(current_user.id) not in chat_data.member_ids:
|
||||||
|
raise HTTPException(status_code=400, detail="Creator must be in member_ids")
|
||||||
|
|
||||||
|
for member_id in chat_data.member_ids:
|
||||||
|
if not (await db.execute(select(User).where(User.id == member_id))).scalar_one_or_none():
|
||||||
|
raise HTTPException(status_code=404, detail=f"User {member_id} not found")
|
||||||
|
|
||||||
|
new_chat = Chat(title=chat_data.title)
|
||||||
|
db.add(new_chat)
|
||||||
|
await db.flush()
|
||||||
|
|
||||||
|
for member_id in chat_data.member_ids:
|
||||||
|
db.add(ChatMember(chat_id=new_chat.id, user_id=member_id))
|
||||||
|
await db.commit()
|
||||||
|
|
||||||
|
member_result = await db.execute(select(ChatMember.user_id).where(ChatMember.chat_id == new_chat.id))
|
||||||
|
return {
|
||||||
|
"id": str(new_chat.id),
|
||||||
|
"title": new_chat.title,
|
||||||
|
"member_ids": [str(row[0]) for row in member_result.all()],
|
||||||
|
"created_at": format_dt(new_chat.created_at)
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- Список чатов (ИСПРАВЛЕНО: правильная курсорная пагинация) ---
|
||||||
|
@app.get("/api/v1/chats")
|
||||||
|
async def list_chats(limit: int = Query(50, ge=1, le=100), cursor: Optional[str] = Query(None), current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)):
|
||||||
|
# Запрашиваем limit + 1, чтобы узнать, есть ли следующая страница
|
||||||
|
query = select(Chat).join(ChatMember, Chat.id == ChatMember.chat_id).where(ChatMember.user_id == current_user.id).order_by(Chat.created_at.desc()).limit(limit + 1)
|
||||||
|
|
||||||
|
if cursor:
|
||||||
|
cursor_dt = datetime.fromisoformat(cursor.replace('Z', '+00:00'))
|
||||||
|
query = query.where(Chat.created_at < cursor_dt)
|
||||||
|
|
||||||
|
chats = (await db.execute(query)).scalars().all()
|
||||||
|
|
||||||
|
has_next = len(chats) > limit
|
||||||
|
if has_next:
|
||||||
|
chats = chats[:-1] # Отбрасываем лишний элемент
|
||||||
|
|
||||||
|
items = []
|
||||||
|
for chat in chats:
|
||||||
|
members = [str(row[0]) for row in (await db.execute(select(ChatMember.user_id).where(ChatMember.chat_id == chat.id))).all()]
|
||||||
|
items.append({
|
||||||
|
"id": str(chat.id),
|
||||||
|
"title": chat.title,
|
||||||
|
"member_ids": members,
|
||||||
|
"created_at": format_dt(chat.created_at)
|
||||||
|
})
|
||||||
|
|
||||||
|
# Если есть следующая страница, курсором будет последний элемент в items
|
||||||
|
next_cursor = items[-1]["created_at"] if has_next else None
|
||||||
|
|
||||||
|
return {"items": items, "next_cursor": next_cursor}
|
||||||
|
|
||||||
|
# --- Получение чата ---
|
||||||
|
@app.get("/api/v1/chats/{chat_id}")
|
||||||
|
async def get_chat(chat_id: uuid.UUID, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)):
|
||||||
|
chat = (await db.execute(select(Chat).where(Chat.id == chat_id))).scalar_one_or_none()
|
||||||
|
if not chat: raise HTTPException(status_code=404, detail="Chat not found")
|
||||||
|
|
||||||
|
if not (await db.execute(select(ChatMember).where(ChatMember.chat_id == chat_id, ChatMember.user_id == current_user.id))).scalar_one_or_none():
|
||||||
|
raise HTTPException(status_code=404, detail="Chat not accessible")
|
||||||
|
|
||||||
|
members = [str(row[0]) for row in (await db.execute(select(ChatMember.user_id).where(ChatMember.chat_id == chat_id))).all()]
|
||||||
|
return {
|
||||||
|
"id": str(chat.id),
|
||||||
|
"title": chat.title,
|
||||||
|
"member_ids": members,
|
||||||
|
"created_at": format_dt(chat.created_at)
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- Отправка сообщения ---
|
||||||
|
@app.post("/api/v1/chats/{chat_id}/messages", status_code=status.HTTP_201_CREATED)
|
||||||
|
async def send_message(
|
||||||
|
chat_id: uuid.UUID,
|
||||||
|
msg_data: CreateMessage,
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
db: AsyncSession = Depends(get_db)
|
||||||
|
):
|
||||||
|
if not (await db.execute(select(ChatMember).where(ChatMember.chat_id == chat_id, ChatMember.user_id == current_user.id))).scalar_one_or_none():
|
||||||
|
raise HTTPException(status_code=404, detail="Chat not accessible")
|
||||||
|
|
||||||
|
msg = Message(chat_id=chat_id, sender_id=current_user.id, text=msg_data.text)
|
||||||
|
db.add(msg)
|
||||||
|
await db.commit()
|
||||||
|
await db.refresh(msg)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"id": str(msg.id),
|
||||||
|
"chat_id": str(msg.chat_id),
|
||||||
|
"sender_id": str(msg.sender_id),
|
||||||
|
"text": msg.text,
|
||||||
|
"created_at": format_dt(msg.created_at)
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- Список сообщений (ИСПРАВЛЕНО: правильная курсорная пагинация) ---
|
||||||
|
@app.get("/api/v1/chats/{chat_id}/messages")
|
||||||
|
async def list_messages(chat_id: uuid.UUID, limit: int = Query(50, ge=1, le=100), cursor: Optional[str] = Query(None), current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)):
|
||||||
|
if not (await db.execute(select(ChatMember).where(ChatMember.chat_id == chat_id, ChatMember.user_id == current_user.id))).scalar_one_or_none():
|
||||||
|
raise HTTPException(status_code=404, detail="Chat not accessible")
|
||||||
|
|
||||||
|
# Запрашиваем limit + 1, чтобы узнать, есть ли следующая страница
|
||||||
|
query = select(Message).where(Message.chat_id == chat_id).order_by(Message.created_at.asc(), Message.id.asc()).limit(limit + 1)
|
||||||
|
|
||||||
|
if cursor:
|
||||||
|
cursor_dt = datetime.fromisoformat(cursor.replace('Z', '+00:00'))
|
||||||
|
query = query.where(Message.created_at > cursor_dt)
|
||||||
|
|
||||||
|
messages = (await db.execute(query)).scalars().all()
|
||||||
|
|
||||||
|
has_next = len(messages) > limit
|
||||||
|
if has_next:
|
||||||
|
messages = messages[:-1] # Отбрасываем лишний элемент
|
||||||
|
|
||||||
|
items = [{
|
||||||
|
"id": str(m.id),
|
||||||
|
"chat_id": str(m.chat_id),
|
||||||
|
"sender_id": str(m.sender_id),
|
||||||
|
"text": m.text,
|
||||||
|
"created_at": format_dt(m.created_at)
|
||||||
|
} for m in messages]
|
||||||
|
|
||||||
|
# Если есть следующая страница, курсором будет последний элемент в items
|
||||||
|
next_cursor = items[-1]["created_at"] if has_next else None
|
||||||
|
|
||||||
|
return {"items": items, "next_cursor": next_cursor}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
import uuid
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from sqlalchemy import Column, String, DateTime, ForeignKey, Text, UniqueConstraint
|
||||||
|
from sqlalchemy.dialects.postgresql import UUID
|
||||||
|
from sqlalchemy.orm import relationship
|
||||||
|
from src.database import Base
|
||||||
|
|
||||||
|
def get_now_utc():
|
||||||
|
return datetime.now(timezone.utc)
|
||||||
|
|
||||||
|
class User(Base):
|
||||||
|
__tablename__ = "users"
|
||||||
|
|
||||||
|
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||||
|
username = Column(String(32), unique=True, nullable=False, index=True)
|
||||||
|
display_name = Column(String(100), nullable=False)
|
||||||
|
password_hash = Column(String(255), nullable=False) # Новое поле для хеша пароля
|
||||||
|
created_at = Column(DateTime(timezone=True), default=get_now_utc)
|
||||||
|
|
||||||
|
# Связи
|
||||||
|
sessions = relationship("Session", back_populates="user", cascade="all, delete-orphan")
|
||||||
|
chats = relationship("ChatMember", back_populates="user", cascade="all, delete-orphan")
|
||||||
|
messages = relationship("Message", back_populates="sender", cascade="all, delete-orphan")
|
||||||
|
|
||||||
|
class Session(Base):
|
||||||
|
__tablename__ = "sessions"
|
||||||
|
|
||||||
|
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||||
|
user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
|
||||||
|
token = Column(String(255), unique=True, nullable=False, index=True) # Opaque Bearer токен
|
||||||
|
expires_at = Column(DateTime(timezone=True), nullable=False)
|
||||||
|
created_at = Column(DateTime(timezone=True), default=get_now_utc)
|
||||||
|
|
||||||
|
user = relationship("User", back_populates="sessions")
|
||||||
|
|
||||||
|
class Chat(Base):
|
||||||
|
__tablename__ = "chats"
|
||||||
|
|
||||||
|
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||||
|
title = Column(String(100), nullable=False)
|
||||||
|
created_at = Column(DateTime(timezone=True), default=get_now_utc)
|
||||||
|
|
||||||
|
members = relationship("ChatMember", back_populates="chat", cascade="all, delete-orphan")
|
||||||
|
messages = relationship("Message", back_populates="chat", cascade="all, delete-orphan")
|
||||||
|
|
||||||
|
class ChatMember(Base):
|
||||||
|
__tablename__ = "chat_members"
|
||||||
|
|
||||||
|
chat_id = Column(UUID(as_uuid=True), ForeignKey("chats.id", ondelete="CASCADE"), primary_key=True)
|
||||||
|
user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), primary_key=True)
|
||||||
|
joined_at = Column(DateTime(timezone=True), default=get_now_utc)
|
||||||
|
|
||||||
|
chat = relationship("Chat", back_populates="members")
|
||||||
|
user = relationship("User", back_populates="chats")
|
||||||
|
|
||||||
|
class Message(Base):
|
||||||
|
__tablename__ = "messages"
|
||||||
|
|
||||||
|
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||||
|
chat_id = Column(UUID(as_uuid=True), ForeignKey("chats.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||||
|
sender_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
|
||||||
|
text = Column(Text, nullable=False)
|
||||||
|
created_at = Column(DateTime(timezone=True), default=get_now_utc, index=True) # Индекс для пагинации
|
||||||
|
|
||||||
|
chat = relationship("Chat", back_populates="messages")
|
||||||
|
sender = relationship("User", back_populates="messages")
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
from pydantic import BaseModel, Field, ConfigDict, field_serializer
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
def format_dt(dt: datetime) -> str:
|
||||||
|
"""Форматирует datetime в ISO 8601 с суффиксом Z вместо +00:00"""
|
||||||
|
return dt.isoformat().replace('+00:00', 'Z')
|
||||||
|
|
||||||
|
class UserCreate(BaseModel):
|
||||||
|
username: str = Field(..., 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)
|
||||||
|
|
||||||
|
class UserResponse(BaseModel):
|
||||||
|
id: str
|
||||||
|
username: str
|
||||||
|
display_name: str
|
||||||
|
created_at: datetime
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
@field_serializer('created_at')
|
||||||
|
def serialize_dt(self, dt: datetime) -> str:
|
||||||
|
return format_dt(dt)
|
||||||
|
|
||||||
|
class SessionResponse(BaseModel):
|
||||||
|
token: str
|
||||||
|
token_type: str = "Bearer"
|
||||||
|
expires_at: datetime
|
||||||
|
user: UserResponse
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
@field_serializer('expires_at')
|
||||||
|
def serialize_expires(self, dt: datetime) -> str:
|
||||||
|
return format_dt(dt)
|
||||||
|
|
||||||
|
class CreateChat(BaseModel):
|
||||||
|
title: str = Field(..., min_length=1, max_length=100)
|
||||||
|
member_ids: list[str] = Field(..., min_length=1)
|
||||||
|
model_config = ConfigDict(extra="forbid")
|
||||||
|
|
||||||
|
class CreateMessage(BaseModel):
|
||||||
|
text: str = Field(..., min_length=1, max_length=4000)
|
||||||
|
model_config = ConfigDict(extra="forbid")
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
import uuid
|
||||||
|
import asyncio
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import Dict, Set, List
|
||||||
|
|
||||||
|
def get_now_iso() -> str:
|
||||||
|
return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class User:
|
||||||
|
id: str
|
||||||
|
username: str
|
||||||
|
display_name: str
|
||||||
|
created_at: str
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Chat:
|
||||||
|
id: str
|
||||||
|
title: str
|
||||||
|
member_ids: Set[str]
|
||||||
|
created_at: str
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Message:
|
||||||
|
id: str
|
||||||
|
chat_id: str
|
||||||
|
sender_id: str
|
||||||
|
text: str
|
||||||
|
created_at: str
|
||||||
|
|
||||||
|
class Storage:
|
||||||
|
def __init__(self):
|
||||||
|
self.users_by_id: Dict[str, User] = {}
|
||||||
|
self.usernames: Set[str] = set()
|
||||||
|
|
||||||
|
self.chats_by_id: Dict[str, Chat] = {}
|
||||||
|
self.chat_members: Dict[str, Set[str]] = {}
|
||||||
|
|
||||||
|
self.messages_by_chat: Dict[str, List[Message]] = {}
|
||||||
|
|
||||||
|
# ЗАМОК для защиты от гонок при одновременной записи
|
||||||
|
self.lock = asyncio.Lock()
|
||||||
|
|
||||||
|
async def create_user(self, username: str, display_name: str) -> User:
|
||||||
|
async with self.lock:
|
||||||
|
if username in self.usernames:
|
||||||
|
raise ValueError("Username already exists") # Эту ошибку мы перехватим в main.py
|
||||||
|
|
||||||
|
user_id = str(uuid.uuid4())
|
||||||
|
user = User(
|
||||||
|
id=user_id,
|
||||||
|
username=username,
|
||||||
|
display_name=display_name,
|
||||||
|
created_at=get_now_iso()
|
||||||
|
)
|
||||||
|
self.users_by_id[user_id] = user
|
||||||
|
self.usernames.add(username)
|
||||||
|
return user
|
||||||
|
|
||||||
|
async def create_chat(self, title: str, member_ids: List[str]) -> Chat:
|
||||||
|
async with self.lock:
|
||||||
|
chat_id = str(uuid.uuid4())
|
||||||
|
members_set = set(member_ids)
|
||||||
|
|
||||||
|
chat = Chat(
|
||||||
|
id=chat_id,
|
||||||
|
title=title,
|
||||||
|
member_ids=members_set,
|
||||||
|
created_at=get_now_iso()
|
||||||
|
)
|
||||||
|
|
||||||
|
self.chats_by_id[chat_id] = chat
|
||||||
|
self.chat_members[chat_id] = members_set
|
||||||
|
|
||||||
|
return chat
|
||||||
|
|
||||||
|
async def create_message(self, chat_id: str, sender_id: str, text: str) -> Message:
|
||||||
|
async with self.lock:
|
||||||
|
message_id = str(uuid.uuid4())
|
||||||
|
message = Message(
|
||||||
|
id=message_id,
|
||||||
|
chat_id=chat_id,
|
||||||
|
sender_id=sender_id,
|
||||||
|
text=text,
|
||||||
|
created_at=get_now_iso()
|
||||||
|
)
|
||||||
|
|
||||||
|
if chat_id not in self.messages_by_chat:
|
||||||
|
self.messages_by_chat[chat_id] = []
|
||||||
|
|
||||||
|
self.messages_by_chat[chat_id].append(message)
|
||||||
|
return message
|
||||||
Reference in New Issue
Block a user