diff --git a/.dockerignore b/.dockerignore index bc16e556..fd625c8c 100644 --- a/.dockerignore +++ b/.dockerignore @@ -18,3 +18,7 @@ __pycache__ node_modules evidence .DS_Store +**/bin +**/obj +**/*.csproj.user +scr/Messenger.Api/Test diff --git a/.env.example b/.env.example index 119384b5..a7b71ae0 100644 --- a/.env.example +++ b/.env.example @@ -3,6 +3,9 @@ APP_HOST=0.0.0.0 APP_PORT=8080 APP_ENV=lab +# Public API port on the host. Override locally when older labs use 8080. +LB_PUBLISHED_PORT=8080 +LB_STATS_PORT=8404 SESSION_TTL_SECONDS=3600 # Choose credentials locally. File paths contain no secret values. DATABASE_URL_FILE=/run/secrets/database_url diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..dfdb8b77 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +*.sh text eol=lf diff --git a/.github/workflows/contracts.yml b/.github/workflows/contracts.yml index 11cf289f..2ce5557f 100644 --- a/.github/workflows/contracts.yml +++ b/.github/workflows/contracts.yml @@ -12,5 +12,20 @@ jobs: python-version: '3.12' - run: python -m pip install -r requirements-dev.txt - run: make check validate PYTHON=python -# This job validates the skeleton, not a student solution. -# Add build, readiness and make test in a separate application job. + application: + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - run: cp .env.example .env + - run: sh scripts/init-secrets.sh + - run: docker compose config --quiet + - run: docker compose up -d --build --wait --wait-timeout 180 + - run: curl --fail --silent --retry 15 --retry-all-errors --retry-delay 1 http://localhost:8080/health/ready + - run: make test PYTHON=python + - run: python student-tests/pipeline.py + - if: always() + run: docker compose down diff --git a/.gitignore b/.gitignore index b5a71896..7de3ee87 100644 --- a/.gitignore +++ b/.gitignore @@ -30,3 +30,10 @@ coverage/ .vscode/ # Keep small, sanitized evidence summaries in evidence/ under version control. # Inspect git diff --cached: ignore rules are not a secret scanner. +# Local IDE/user files +*.csproj.user +.vs/ +scr/Messenger.Api/Test/ +secrets/ + +!scr/Messenger.Api/Data/ \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..6588e81c --- /dev/null +++ b/Dockerfile @@ -0,0 +1,36 @@ +# Версии закреплены тегом и digest (SDK 10.0.401, runtime 10.0.12), сборка воспроизводима. +FROM mcr.microsoft.com/dotnet/sdk:10.0.401@sha256:e70cdb7f80b0348f5cb85f19a8f670fca061f033d57eed12fa003d58b0e06317 AS build +WORKDIR /src +ARG TARGETARCH + +COPY scr/Messenger.Api/Messenger.Api.csproj scr/Messenger.Api/ +RUN dotnet restore scr/Messenger.Api/Messenger.Api.csproj -a "$TARGETARCH" + +COPY scr/Messenger.Api/ scr/Messenger.Api/ +RUN dotnet publish scr/Messenger.Api/Messenger.Api.csproj \ + -a "$TARGETARCH" --self-contained false \ + --configuration Release \ + --output /app/publish \ + --no-restore + +FROM mcr.microsoft.com/dotnet/aspnet:10.0.12@sha256:222759b391a1aaf241166672c8f99b2d4ada452e7b5319f3c6e8f265a37b5ad4 AS runtime +WORKDIR /app + +COPY --from=build /app/publish . + +# Версия сборки (видна в логе старта; отличает старую реплику от новой при rolling update). +# ARG стоит после COPY: смена версии пересобирает только этот слой, а не всю сборку. +ARG APP_VERSION=dev +ENV APP_VERSION=${APP_VERSION} +LABEL org.opencontainers.image.version=${APP_VERSION} + +ENV ASPNETCORE_URLS=http://0.0.0.0:8080 +EXPOSE 8080 + +# Непривилегированный пользователь (APP_UID задан в базовом образе aspnet). +USER $APP_UID + +# curl в образе нет, поэтому проверку выполняет само приложение (/health/live). +HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 CMD ["dotnet", "Messenger.Api.dll", "--healthcheck"] + +ENTRYPOINT ["dotnet", "Messenger.Api.dll"] diff --git a/REPORT.md b/REPORT.md index e98f75e9..abb06720 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,101 @@ -# Отчёт — лабораторная 5 +# Отчёт о лабораторной работе 5 -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO +- Автор, группа: Полуднев Юлиан, БВТ2303 +- Целевая оценка; выбранный трек 5, если нужен: 5, трек 2 - Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- Использованные источники, библиотеки и помощь ИИ: AWSSDK.S3 4.1.0, StbImageSharp 2.30.16 (декодирование PNG/JPEG), EF Core/Npgsql, Argon2 и Valkey-клиент. Claude Code помог с реализацией. -## Запуск из чистого clone +## Запуск из чистого клона -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +Нужны Docker Engine с Linux-контейнерами, Docker Compose v2, POSIX shell и Python 3.9+. В Windows подготовку файлов можно выполнить в Git Bash, Python-проверки запускаются из PowerShell или Git Bash. -## Архитектура и решения +```sh +cp .env.example .env +sh scripts/init-secrets.sh +docker compose config --quiet +docker compose up -d --build --wait --wait-timeout 180 +curl --fail --retry 15 --retry-all-errors --retry-delay 1 http://localhost:8080/health/ready +python scripts/check_contract.py +python tests/smoke.py +python student-tests/pipeline.py +``` -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab4, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +Если порт занят, измените `LB_PUBLISHED_PORT` и `LB_STATS_PORT` в локальном `.env` и передайте `--base-url` с фактическим портом в HTTP-тесты. Публичные проверки сохранности и отказа запускаются в POSIX-среде с исполняемыми скриптами. -## Доказательства критериев +В Compose API слушает `0.0.0.0:8080` через `ASPNETCORE_URLS`. Сессии хранятся в PostgreSQL. `APP_HOST`, `APP_ENV` и `SESSION_STORE` в примере обозначают параметры контракта стенда. Число реплик, лимиты и настройки очереди передаются из `.env` через Compose. -| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | -| --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | +```sh +chmod +x scripts/restart.sh scripts/stop-one.sh +make test-persistence PYTHON=python ACTION_SCRIPT=scripts/restart.sh +make test-failover PYTHON=python ACTION_SCRIPT=scripts/stop-one.sh +docker compose start api +``` -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +Для остановки с сохранением томов служит `docker compose down`. Команда намеренного сброса всех учебных данных проекта — `docker compose down -v`. -## Эксперименты и отказы +| Сервис | Образ и назначение | Готовность, данные и доступ | +| --- | --- | --- | +| `api`, `migrate` | .NET SDK 10.0.401 и ASP.NET Runtime 10.0.12. Две реплики API, одноразовые миграции EF Core | HAProxy проверяет `/health/ready`. API требует PostgreSQL и MinIO. Строка базы и ключи S3 передаются файлами | +| `lb` | HAProxy 3.0 | Публичный порт 8080, статистика по умолчанию только на 127.0.0.1:8404 | +| `db` | PostgreSQL 17 | `pg_isready`, том `pgdata`, пароль через файл | +| `s3`, `s3-init` | MinIO, закреплённый digest, и одноразовый bootstrap | `/minio/health/ready`, том `s3data`, приватный bucket и отдельные политики API и worker | +| `cache` | Valkey 8.1, кэш истории | `ping`, данные восстанавливаются из PostgreSQL | +| `broker` | RabbitMQ 4.2.4 | Проверка доступности listener, том `brokerdata`, AMQP и management в сети Compose. Пароль из Docker secret | +| `dispatcher`, `worker` | Тот же образ приложения, отдельные процессы | Проверка жизни PID 1, соединения восстанавливаются в цикле. URL брокера через файл. Процессы объявляют устойчивую очередь при подключении | -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +## Границы сохранности -| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | -| --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +API проверяет MIME, структуру и размеры PNG/JPEG, принимает максимум 10 MiB и 40 млн пикселей. Сохраняет оригинал в S3 `staging/`, затем одной транзакцией создаёт вложение и запись `attachment_jobs`, удаляет журнал незавершённого приёма и отвечает `202 queued`. Существующая логика сообщений и сессий остаётся в PostgreSQL. Миграция создаёт задания для старых вложений из уже опубликованных оригиналов с сохранением их ID. -## Ограничения и следующие шаги +Dispatcher читает неотправленные записи с `FOR UPDATE SKIP LOCKED`. После publisher confirm он сохраняет `published_at`. Сбой между отправкой и фиксацией отметки допускает повторную публикацию с тем же `job_id`. Worker получает из RabbitMQ только идентификаторы, версию, номер попытки и время из схемы jobs. Перед записью в S3 он проверяет текущую версию, состояние и попытку под блокировками PostgreSQL. -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +В S3 оригинал записывается в `originals/`, варианты в `variants//v/`. Условный PUT создаёт объект один раз. Если объект уже появился до аварии, worker сверяет его размер и SHA-256. Ключ варианта в PostgreSQL состоит из ID вложения, версии pipeline и имени. Метаданные вариантов и `ready` коммитятся вместе, затем worker посылает consumer ack. Ack может подтверждать также устойчиво записанную повторную попытку или конечную ошибку. Повторная доставка после COMMIT проверяет версию, попытку и состояние, затем завершается без записи результата. Это at-least-once доставка с идемпотентными эффектами. + +## Обработка и повтор + +- Magick.NET Q8 15.1.1 декодирует изображение в отдельном дочернем процессе. Worker завершает этот процесс по дедлайну `JOB_TIMEOUT_SECONDS` (60 с). Docker ограничивает worker 2 CPU и 1 GiB памяти. ImageMagick ограничивает пиксельный кэш и использует один поток на обработку. `WORKER_CONCURRENCY` задаёт число каналов, по умолчанию 2. Каждый канал держит не более одной неподтверждённой доставки. +- EXIF orientation применяется перед геометрией. Форматы вариантов — JPEG thumbnail до 256×256, JPEG центральный crop 128×128, WebP до 1280×1280. Thumbnail и WebP сохраняют пропорции и размер небольших файлов. JPEG компонуется на белый фон, WebP сохраняет прозрачность. Метаданные удаляются. В v1 качество thumbnail, crop и WebP равно 85, 85 и 78. В v2 качество thumbnail и WebP равно 92 и 86, crop остаётся 85. +- Повреждённое изображение получает `invalid_image`. Для временных сбоев интервал растёт как 1, 2, 4, 8 секунд при пяти попытках и получает случайную добавку до 25%. По истечении аренды задание снова доступно для обработки. По умолчанию `JOB_MAX_ATTEMPTS=5`, затем устанавливается `retry_exhausted`. +- Staging для готового вложения удаляется после COMMIT результата. Staging для failed хранится `STAGING_RETENTION_SECONDS`, по умолчанию сутки. Replay доступен до истечения retention. Хранятся время replay и первый номер попытки новой серии. Повтор доставки старого номера не может запустить обработку. + +```sh +docker compose exec -T api dotnet Messenger.Api.dll --failed-jobs +docker compose exec -T api dotnet Messenger.Api.dll --replay-job JOB_UUID +docker compose exec -T api dotnet Messenger.Api.dll --upgrade-attachment ATTACHMENT_UUID +``` + +Upgrade ставит v2 в очередь для готовой v1 и берёт исходник из постоянного ключа оригинала. API публикует метаданные только текущей версии. Доступ к вложению проверяется у участников чата. До `ready` скачивание возвращает 409. Повтор отправки с тем же `Idempotency-Key` возвращает ранее принятое сообщение, даже если связанное вложение позднее стало `failed`. + +## Исследование и доказательства + +Гипотеза трека 2. После принудительной остановки или доставки в изменённом порядке каждый подтверждённый upload достигает наблюдаемого результата. Для каждой пары «вложение и версия» существует только один опубликованный набор вариантов. Доставка v1 после публикации v2 сохраняет метаданные и SHA-256 всех публичных объектов v2. + +Проверяемые инварианты: + +1. При `202` сохранены исходник и строка задания. Переход в `ready` сохраняет один и тот же ID вложения и побайтовый оригинал. +2. `ready` означает, что все три объекта вариантов уже существуют, а их метаданные зафиксированы вместе. Для каждой пары «версия и имя варианта» сохраняется ровно одна строка. +3. Выполнять работу может только текущая попытка текущей версии. Дубли, будущая попытка, доставленная первой, и устаревшая версия проходят через ту же проверку. +4. Повтор доставки от RabbitMQ и повторная попытка приложения различимы. Новый номер попытки выделяет PostgreSQL. Флаг redelivery может измениться при неизменном номере. + +Методика. `student-tests/pipeline.py` использует синтетический PNG 320×200, отдельные команды Compose, SQL для снимков состояния и API для сравнения байтов. Целевая инъекция адресуется по UUID вложения. Тестовый процесс выходит с кодом 71 перед publish, перед записью в S3, после записи в S3 или перед ack. Для проверки аренды в аварийном worker используется дедлайн 10 с. В обычных сервисах инъекция отсутствует. Нагрузочные показатели не являются частью этой методики. + +Локальная среда прогона 27 ноября 2026 года — Docker Desktop 29.4.1, Linux x86-64, 16 логических CPU и около 7,48 GiB памяти VM. Рабочий стенд использовал порт 18085, проверка со свежими томами — 18086. + +| Критерий | Проверка | Наблюдаемый результат | +| --- | --- | --- | +| Контракт и сквозной smoke | `python scripts/check_contract.py`, `python scripts/validate_openapi.py`, `python tests/smoke.py` | Структура и схемы прошли валидацию. Smoke прошёл на рабочем стенде и с новыми томами | +| Сохранность и отказ реплики | `test-persistence` и `test-failover` из публичного набора | При рестарте зависимостей сохранились данные, оригинал и действующая сессия. При остановке одной из двух реплик принято 105 записей, ошибок и дублей не было, первая запись после остановки прошла через 4,799 с от начала операции | +| Устойчивый приём и at-least-once | `pipeline.py --scenario minimum` | При остановленном worker после 202 созданы обычное сообщение и сообщение с вложением. До и после рестарта двух реплик API и RabbitMQ в очереди было одно задание. Worker получил его с флагом redelivery. Оригинал совпал побайтно, JPEG был 256×160 | +| Crop, optimized и исходные байты | `pipeline.py --scenario failures`, `dotnet test` | Проверены размеры и форматы всех файлов, центральная обрезка, WebP 1280×640 для исходника 1600×800, EXIF orientation и удаление EXIF, округление размеров и белый фон. Прошёл 91 .NET-тест | +| Лимиты и постоянная ошибка | `pipeline.py --scenario limits`, `docker inspect` | 10 MiB + 1 байт и PNG с 48 млн пикселей дали 413. Неверная сигнатура дала 415. PNG с корректной внешней структурой и неверным фильтром строки стал `failed/invalid_image` на первой попытке. Docker применил worker 1 GiB памяти и 2 CPU | +| Outbox и аварийные остановки | `pipeline.py --scenario failures` | Задание осталось в БД после сбоя до publish. API показал `processing` и вернул 409 на скачивание. После записи в S3 метаданные были скрыты до COMMIT. После остановки перед ack результат остался доступным. Три варианта опубликованы на третьей попытке для того же ID, повторная доставка сохранила их | +| Ограничение попыток, реестр, replay и cleanup | `pipeline.py --scenario retry` | После двух временных сбоев API показал `failed` и `retry_exhausted`. Replay довёл тот же ID до `ready` на попытке 3. Staging очищен, replay готовой задачи отклонён | +| Дубли, reorder и устаревшая версия | `pipeline.py --scenario versions` | Будущая попытка v2 пришла до первой. Worker подтвердил дубли и позднюю v1. В БД три варианта v1 и три v2, SHA-256 двух миниатюр различаются. Поздняя v1 сохранила публичный результат v2 | + +Результаты сценариев — [первый прогон](evidence/pipeline-verified.jsonl) и [повторная проверка по README](evidence/readme-audit.jsonl). Вывод публичных проверок отказов — [evidence/resilience.txt](evidence/resilience.txt). На Windows тесты вызывали те же POSIX-скрипты через временные `.cmd`-обёртки. + +## Ограничения + +Стенд использует один Docker-host и по одному экземпляру RabbitMQ, PostgreSQL и MinIO. Тесты исследуют рестарты с сохранёнными томами и аварии процессов. Потерю диска и одновременный отказ хоста они не моделируют. Файлы версий сохраняются для проверки истории эксперимента. Задания отсутствуют в публичном API, операторские команды требуют доступа к Compose. + +Источники — [RabbitMQ .NET Client](https://www.rabbitmq.com/client-libraries/dotnet-api-guide), [подтверждения RabbitMQ](https://www.rabbitmq.com/docs/confirms), [лимиты ImageMagick](https://imagemagick.org/resources/). diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 00000000..499f4801 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,362 @@ +# ЛР5: API за HAProxy, PostgreSQL, приватный MinIO и асинхронная обработка через RabbitMQ. +# Запуск (одна последовательность): +# sh scripts/init-secrets.sh && docker compose --env-file .env up -d --build --wait +name: messenger-lab5 + +# Один образ и для API, и для миграций: схема всегда соответствует коду. build продублирован намеренно, +# чтобы `up --build` собрал образ раньше, чем стартует migrate (второй build берётся из кэша). +x-api-image: &api-image + image: messenger-api:lab5 + build: + context: . + dockerfile: Dockerfile + args: + APP_VERSION: ${APP_VERSION:-1} + +# MinIO RELEASE.2025-09-07T16-13-09Z; включает mc RELEASE.2025-08-13T08-35-41Z. +x-s3-image: &s3-image + image: quay.io/minio/minio@sha256:14cea493d9a34af32f524e538b8346cf79f3321eff8e708c1e2960462bd8936e + +services: + broker: + image: public.ecr.aws/docker/library/rabbitmq:4.2.4-management@sha256:aeee1db0ff9fdb1347f3585242c14ed10877b56c22eeaa113b21208ef3dd3edf + hostname: broker + restart: unless-stopped + entrypoint: ["/bin/sh", "-ec", 'export RABBITMQ_DEFAULT_PASS="$$(cat /run/secrets/broker_password)"; exec docker-entrypoint.sh rabbitmq-server'] + environment: + RABBITMQ_DEFAULT_USER: messenger + RABBITMQ_SERVER_ADDITIONAL_ERL_ARGS: "+S 2:2" + secrets: [broker_password] + volumes: [brokerdata:/var/lib/rabbitmq] + healthcheck: + test: ["CMD", "rabbitmq-diagnostics", "-q", "check_port_connectivity"] + interval: 5s + timeout: 5s + retries: 20 + networks: [backend] + + dispatcher: + <<: *api-image + command: ["--dispatch"] + restart: unless-stopped + depends_on: + migrate: { condition: service_completed_successfully } + broker: { condition: service_healthy } + environment: &job-settings + DATABASE_URL_FILE: /run/secrets/database_url + BROKER_URL_FILE: /run/secrets/broker_url + JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60} + JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5} + STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-86400} + secrets: [database_url, broker_url] + healthcheck: &job-health + test: ["CMD-SHELL", "kill -0 1"] + interval: 10s + start_period: 3s + start_interval: 1s + networks: [backend] + + worker: + <<: *api-image + command: ["--worker"] + restart: unless-stopped + depends_on: + migrate: { condition: service_completed_successfully } + broker: { condition: service_healthy } + s3-init: { condition: service_completed_successfully } + environment: + <<: *job-settings + WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-2} + S3_ENDPOINT: http://s3:9000 + S3_REGION: ${S3_REGION:-us-east-1} + S3_BUCKET: ${S3_BUCKET:-messenger-attachments} + S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_worker_access_key + S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_worker_secret_key + MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760} + MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000} + MAGICK_THREAD_LIMIT: "1" + MAGICK_MEMORY_LIMIT: 256MiB + MAGICK_MAP_LIMIT: 256MiB + MAGICK_DISK_LIMIT: 512MiB + secrets: [database_url, broker_url, s3_worker_access_key, s3_worker_secret_key] + healthcheck: *job-health + deploy: + resources: + limits: { cpus: "2", memory: 1g } + networks: [backend] + + s3: + <<: *s3-image + restart: unless-stopped + entrypoint: ["/bin/sh", "/infra/start.sh"] + environment: + MINIO_SITE_REGION: ${S3_REGION:-us-east-1} + MINIO_BROWSER: "off" + secrets: + - s3_root_user + - s3_root_password + volumes: + - s3data:/data + - ./infra/s3:/infra:ro + # S3 и административная консоль не публикуются на хост. + healthcheck: + test: ["CMD", "curl", "--fail", "--silent", "http://127.0.0.1:9000/minio/health/ready"] + interval: 5s + timeout: 3s + retries: 20 + start_period: 10s + deploy: + resources: + limits: + cpus: "1" + memory: 512m + networks: [backend] + + s3-init: + <<: *s3-image + restart: "no" + entrypoint: ["/bin/sh", "/infra/bootstrap.sh"] + depends_on: + s3: + condition: service_healthy + environment: + S3_BUCKET: ${S3_BUCKET:-messenger-attachments} + MC_CONFIG_DIR: /tmp/mc + secrets: + - s3_root_user + - s3_root_password + - s3_access_key_id + - s3_secret_access_key + - s3_worker_access_key + - s3_worker_secret_key + volumes: + - ./infra/s3:/infra:ro + networks: [backend] + + s3-check: + <<: *s3-image + profiles: [tools] + restart: "no" + entrypoint: ["/bin/sh", "/infra/check.sh"] + depends_on: + s3-init: + condition: service_completed_successfully + environment: + S3_BUCKET: ${S3_BUCKET:-messenger-attachments} + MC_CONFIG_DIR: /tmp/mc + secrets: + - s3_access_key_id + - s3_secret_access_key + volumes: + - ./infra/s3:/infra:ro + - ./tests/fixtures:/fixtures:ro + networks: [backend] + + s3-client-check: + image: mcr.microsoft.com/dotnet/aspnet:10.0.12@sha256:222759b391a1aaf241166672c8f99b2d4ada452e7b5319f3c6e8f265a37b5ad4 + profiles: [tools] + restart: "no" + entrypoint: ["dotnet", "/check/StorageCheck.dll", "/fixtures/sample.png"] + depends_on: + s3-init: + condition: service_completed_successfully + environment: + S3_ENDPOINT: http://s3:9000 + S3_REGION: ${S3_REGION:-us-east-1} + S3_BUCKET: ${S3_BUCKET:-messenger-attachments} + S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_access_key_id + S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key + secrets: + - s3_access_key_id + - s3_secret_access_key + volumes: + - ./tools/StorageCheck/bin/Release/net10.0:/check:ro + - ./tests/fixtures:/fixtures:ro + networks: [backend] + + db: + # PostgreSQL 17.11; тег закреплён digest'ом, сборка воспроизводима. + image: postgres:17@sha256:b8faeff7712663c2773a190181e1246e37e364b887611c04658c28b44e2408fe + restart: unless-stopped + # max_connections с запасом: до 8 реплик x пул DB_MAX_POOL_SIZE (по умолчанию 20) + миграции + служебные. + command: ["postgres", "-c", "max_connections=300"] + environment: + POSTGRES_DB: messenger + POSTGRES_USER: messenger + POSTGRES_PASSWORD_FILE: /run/secrets/db_password + secrets: + - db_password + volumes: + # Именованный volume: переживает restart/down; удаляется только явным `docker compose down -v`. + - pgdata:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"] + interval: 5s + timeout: 3s + retries: 20 + start_period: 10s + deploy: + resources: + limits: + cpus: "${DB_CPUS:-2}" + memory: ${DB_MEMORY:-1g} + networks: [backend] + + cache: + # Valkey 8.1: кэш страниц истории сообщений. Источник истины — PostgreSQL, потеря содержимого кэша ничего не ломает, + # поэтому persistence выключена (--save "" --appendonly no). Память ограничена, вытеснение LRU. + # Кэш общий для всех реплик: ключ содержит версию истории чата, поэтому реплики не отдают друг другу устаревшие страницы. + image: valkey/valkey:8.1@sha256:640c5e62cea04b6d6f2084232651d0cc70362d31f4f805e7be94dbed6855e8f2 + restart: unless-stopped + command: + - sh + - -c + - exec valkey-server --requirepass "$$(cat /run/secrets/cache_password)" --save "" --appendonly no --maxmemory 64mb --maxmemory-policy allkeys-lru + secrets: + - cache_password + healthcheck: + test: ["CMD-SHELL", "REDISCLI_AUTH=\"$$(cat /run/secrets/cache_password)\" valkey-cli ping | grep -q PONG"] + interval: 5s + timeout: 3s + retries: 10 + deploy: + resources: + limits: + cpus: "0.5" + memory: 128m + networks: [backend] + + # One-shot: применяет миграции и завершается. API-реплики схему не меняют (MIGRATE_ON_START выключен), + # поэтому одновременный старт N реплик не создаёт гонку. Миграции только добавляют объекты (expand), что + # совместимо с ещё работающей предыдущей версией API при rolling update. + migrate: + <<: *api-image + command: ["--migrate"] + restart: "no" + depends_on: + db: + condition: service_healthy + environment: + DATABASE_URL_FILE: /run/secrets/database_url + secrets: + - database_url + networks: [backend] + + api: + <<: *api-image + restart: unless-stopped + # Без container_name и без published ports: сервис масштабируется (--scale api=N / API_REPLICAS), а снаружи + # реплики доступны только через lb. Кэш не входит в depends_on: API обязан работать без него. + depends_on: + migrate: + condition: service_completed_successfully + db: + condition: service_healthy + s3-init: + condition: service_completed_successfully + environment: + ASPNETCORE_URLS: http://0.0.0.0:8080 + APP_PORT: "8080" + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + DATABASE_URL_FILE: /run/secrets/database_url + CACHE_URL_FILE: /run/secrets/cache_url + CACHE_TTL_SECONDS: ${CACHE_TTL_SECONDS:-300} + DIAGNOSTIC_HEADERS: ${DIAGNOSTIC_HEADERS:-false} + DB_MAX_POOL_SIZE: ${DB_MAX_POOL_SIZE:-20} + IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400} + SHUTDOWN_DRAIN_SECONDS: ${SHUTDOWN_DRAIN_SECONDS:-3} + MIGRATE_ON_START: "false" + S3_ENDPOINT: http://s3:9000 + S3_REGION: ${S3_REGION:-us-east-1} + S3_BUCKET: ${S3_BUCKET:-messenger-attachments} + S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_access_key_id + S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key + MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760} + MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000} + UPLOAD_CLEANUP_GRACE_SECONDS: ${UPLOAD_CLEANUP_GRACE_SECONDS:-300} + UPLOAD_CLEANUP_INTERVAL_SECONDS: ${UPLOAD_CLEANUP_INTERVAL_SECONDS:-30} + secrets: + - database_url + - cache_url + - s3_access_key_id + - s3_secret_access_key + expose: + - "8080" + healthcheck: + # Живость процесса (готовность проверяет LB). start_interval ускоряет первый успех для `up --wait`. + test: ["CMD", "dotnet", "Messenger.Api.dll", "--healthcheck"] + interval: 10s + timeout: 3s + retries: 3 + start_period: 20s + start_interval: 2s + # SIGTERM -> drain 3 с + до 5 с на активные запросы = < 10 с; 15 с — запас до SIGKILL. + stop_grace_period: 15s + deploy: + replicas: ${API_REPLICAS:-2} + resources: + limits: + cpus: "${API_CPUS:-1}" + memory: ${API_MEMORY:-512m} + networks: [backend] + + lb: + # HAProxy 3.0 LTS; digest закреплён. Образ получен через mirror.gcr.io (зеркало официального образа Docker Hub, + # тот же digest), потому что Docker Hub был недоступен при разработке. + image: mirror.gcr.io/library/haproxy:3.0-alpine@sha256:1c15903c50d5510dcc01de755049e7015a6dd3f35bb2dc4582e888116cb71d8f + restart: unless-stopped + depends_on: + api: + condition: service_healthy + volumes: + - ./infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + ports: + # Единственная публичная точка входа. + - "${LB_PUBLISHED_PORT:-8080}:8080" + # Статистика LB (состояние backend'ов): только с этого компьютера. + - "127.0.0.1:${LB_STATS_PORT:-8404}:8404" + healthcheck: + test: ["CMD-SHELL", "wget -q --spider http://127.0.0.1:8404/healthz"] + interval: 5s + timeout: 3s + retries: 5 + deploy: + resources: + limits: + cpus: "${LB_CPUS:-1}" + memory: 128m + networks: [backend] + +volumes: + pgdata: + s3data: + brokerdata: + +networks: + backend: + +secrets: + broker_password: + file: ./secrets/broker_password + broker_url: + file: ./secrets/broker_url + s3_worker_access_key: + file: ./secrets/s3_worker_access_key + s3_worker_secret_key: + file: ./secrets/s3_worker_secret_key + db_password: + file: ./secrets/db_password + database_url: + file: ./secrets/database_url.compose + cache_password: + file: ./secrets/cache_password + cache_url: + file: ./secrets/cache_url + s3_root_user: + file: ./secrets/s3_root_user + s3_root_password: + file: ./secrets/s3_root_password + s3_access_key_id: + file: ./secrets/s3_access_key_id + s3_secret_access_key: + file: ./secrets/s3_secret_access_key diff --git a/evidence/pipeline-verified.jsonl b/evidence/pipeline-verified.jsonl new file mode 100644 index 00000000..c3a287c3 --- /dev/null +++ b/evidence/pipeline-verified.jsonl @@ -0,0 +1,4 @@ +{"scenario": "restart_and_redelivery", "attachment": "01a21ddd-9deb-7a08-b045-1c52d74f7668", "job": "01a21ddd-9e6c-7c40-90f7-87412125a2c9", "api_replicas": 2, "queue_before": 1, "queue_after": 1, "thumbnail": [256, 160], "original_sha256": "99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75", "seconds": 38.34, "redelivered": true, "result": "PASS"} +{"scenario": "crash_windows", "attachment": "01a21de1-3cf9-78f3-98ab-9a72efa218e9", "job": "01a21de1-3d6e-7b21-9009-98824b707fc2", "attempt": 3, "committed_variants": "1|3", "seconds": 69.12, "result": "PASS"} +{"scenario": "duplicate_reorder_old_version", "attachment": "01a21de2-4230-7a49-b7be-50ec6344f4ab", "v1": "01a21de2-4341-7c74-a171-799d3ce19106", "v2": "01a21de2-5d0a-7c8c-aa1d-91b770d44d31", "committed_variants": "1|3\n2|3", "v1_sha256": "13c5e74bd325a76ccda822802d605d0f436006b9ea97916a80224427f1c2f190", "v2_sha256": "d2c07c08f5edb27d53a4d7b7ed26186811cc93e69348fb15cbd6dc91de4e5e56", "seconds": 30.24, "result": "PASS"} +{"scenario": "bounded_retry_replay", "attachment": "01a21de3-922c-7828-bf66-745ea9e9d524", "job": "01a21de3-9245-7d1d-b5cb-6c21ff562a81", "failed_attempt": 2, "recovery_attempt": 3, "seconds": 45.35, "result": "PASS"} diff --git a/evidence/readme-audit.jsonl b/evidence/readme-audit.jsonl new file mode 100644 index 00000000..e721d471 --- /dev/null +++ b/evidence/readme-audit.jsonl @@ -0,0 +1,5 @@ +{"scenario": "restart_and_redelivery", "attachment": "01a21dee-0985-7abe-b8ad-f9339f4922c6", "job": "01a21dee-099b-791a-80eb-9392fe193a40", "api_replicas": 2, "queue_before": 1, "queue_after": 1, "thumbnail": [256, 160], "original_sha256": "99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75", "seconds": 25.64, "redelivered": true, "result": "PASS"} +{"scenario": "crash_windows", "attachment": "01a21dee-77ad-7cb7-8a1e-b3a5101d8386", "job": "01a21dee-7879-7512-b4e2-523d75480a9d", "attempt": 3, "committed_variants": "1|3", "seconds": 63.29, "result": "PASS"} +{"scenario": "duplicate_reorder_old_version", "attachment": "01a21def-6539-7adb-bc89-35e2d2308085", "v1": "01a21def-658f-7db3-97e4-d3570b1194e6", "v2": "01a21def-7b4c-7404-b362-ecf83b2f496b", "committed_variants": "1|3\n2|3", "v1_sha256": "13c5e74bd325a76ccda822802d605d0f436006b9ea97916a80224427f1c2f190", "v2_sha256": "d2c07c08f5edb27d53a4d7b7ed26186811cc93e69348fb15cbd6dc91de4e5e56", "seconds": 32.8, "result": "PASS"} +{"scenario": "bounded_retry_replay", "attachment": "01a21def-dc5d-794a-b7aa-7cb901ad4463", "job": "01a21def-dc75-70a7-9179-978a5762c700", "failed_attempt": 2, "recovery_attempt": 3, "seconds": 42.16, "result": "PASS"} +{"scenario": "image_limits_and_permanent_failure", "attachment": "01a21df0-7f02-7c1e-a964-551566b41fdf", "bytes": 413, "pixels": 413, "wrong_signature": 415, "error_code": "invalid_image", "attempt": 1, "result": "PASS"} diff --git a/evidence/resilience.txt b/evidence/resilience.txt new file mode 100644 index 00000000..33019396 --- /dev/null +++ b/evidence/resilience.txt @@ -0,0 +1,5 @@ +Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. +Executing explicit failover hook; hook output suppressed to avoid leaking secrets. +{"observed_instances_before": 2, "successful_writes": 105, "failed_attempts": 0, "first_recovery_seconds": 4.799} +PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence. diff --git a/infra/haproxy/haproxy.cfg b/infra/haproxy/haproxy.cfg new file mode 100644 index 00000000..28a163b8 --- /dev/null +++ b/infra/haproxy/haproxy.cfg @@ -0,0 +1,62 @@ +# Единая публичная точка входа лабораторной 3: HAProxy распределяет запросы между API-репликами. +# +# Как LB узнаёт адреса реплик: `server-template` создаёт до 8 «слотов», а встроенный DNS-резолвер раз в секунду +# спрашивает у Docker (127.0.0.11) все A-записи имени `api`. Реплика добавилась/исчезла — слот получил/потерял адрес +# без перезапуска LB. Именно поэтому масштабирование (`--scale api=N`) и замена контейнеров не требуют правки конфига. +# +# Как LB исключает неработающий backend: активная проверка GET /health/ready каждую секунду; +# 2 неудачи подряд (fall 2) → слот DOWN, 2 успеха (rise 2) → снова UP. Расчёт времени обнаружения — в REPORT.md. +# Sticky-сессий нет: любой запрос может попасть на любую реплику, состояние (сессии, ключи идемпотентности) в PostgreSQL. + +global + log stdout format raw local0 info + maxconn 4096 + +resolvers docker + nameserver dns1 127.0.0.11:53 + accepted_payload_size 8192 + resolve_retries 3 + timeout resolve 1s + timeout retry 1s + hold valid 2s + hold other 1s + hold refused 1s + hold nx 1s + hold timeout 1s + hold obsolete 1s + +defaults + mode http + log global + option httplog + option dontlognull + timeout connect 2s + timeout client 20s + timeout server 20s + timeout http-request 10s + timeout http-keep-alive 5s + timeout check 2s + # Повторяем только ошибку соединения до отправки запроса. Upload не имеет ключа идемпотентности. + retries 3 + option redispatch 1 + retry-on conn-failure + +frontend public + bind :8080 + default_backend api + +backend api + balance roundrobin + option httpchk + http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host api + http-check expect status 200 + default-server check inter 1s fall 2 rise 2 resolvers docker resolve-prefer ipv4 init-addr none + server-template api 1-8 api:8080 + +# Служебный порт внутри сети Compose (наружу публикуется только на 127.0.0.1): состояние backend'ов и healthcheck самого LB. +frontend ops + bind :8404 + monitor-uri /healthz + stats enable + stats uri /stats + stats refresh 2s diff --git a/infra/s3/README.md b/infra/s3/README.md new file mode 100644 index 00000000..28dbe24c --- /dev/null +++ b/infra/s3/README.md @@ -0,0 +1,20 @@ +# Приватное хранилище MinIO + +`s3` запускает MinIO с постоянным томом `s3data`. `s3-init` идемпотентно создаёт bucket, отключает анонимный доступ и устанавливает политики. Образ закреплён по digest в [compose.yaml](../../compose.yaml). Порты MinIO доступны только в сети Compose. + +На первом запуске `scripts/init-secrets.sh` создаёт локальные ключи. Для повторного применения политик после изменения bootstrap используется команда `docker compose run --rm --no-deps s3-init`. Доступ администратора нужен серверу и bootstrap. + +| Роль | Полномочия | +| --- | --- | +| API | Запись, чтение и уборка в `staging/`, чтение в `originals/` и `variants/`, удаление осиротевших ключей от старой схемы приёма | +| Worker | Чтение в `staging/`, условная запись и чтение в `originals/` и `variants/` | + +S3-ключи формируются из серверного UUID и версии обработки. Оригинал скачивается через API с проверкой членства в чате и контрольной суммы. + +```sh +docker compose run --rm --no-deps s3-check +dotnet build tools/StorageCheck/StorageCheck.csproj -c Release +docker compose run --rm --no-deps s3-client-check +``` + +Эти команды проверяют временный объект в `staging/` через mc и через S3-клиент приложения. Подробности приёма и очистки описаны в [cleanup.md](cleanup.md). diff --git a/infra/s3/bootstrap.sh b/infra/s3/bootstrap.sh new file mode 100644 index 00000000..ae55d64e --- /dev/null +++ b/infra/s3/bootstrap.sh @@ -0,0 +1,62 @@ +#!/bin/sh +# Повторный запуск сохраняет bucket и объекты; обновляет только нашу политику/пользователя. +set -eu +umask 077 +bucket=${S3_BUCKET:?S3_BUCKET is required} +case "$bucket" in + ''|*[!a-z0-9.-]*) echo 'Invalid bucket name' >&2; exit 1 ;; +esac + +mc alias set storage http://s3:9000 \ + "$(cat /run/secrets/s3_root_user)" \ + "$(cat /run/secrets/s3_root_password)" >/dev/null +mc mb --ignore-existing "storage/$bucket" >/dev/null +mc anonymous set none "storage/$bucket" >/dev/null + +cat > /tmp/attachments-policy.json </dev/null +access_key=$(cat /run/secrets/s3_access_key_id) +mc admin user add storage "$access_key" "$(cat /run/secrets/s3_secret_access_key)" >/dev/null +mc admin policy attach storage attachments-api --user "$access_key" >/dev/null +cat > /tmp/worker-policy.json </dev/null +worker_key=$(cat /run/secrets/s3_worker_access_key) +mc admin user add storage "$worker_key" "$(cat /run/secrets/s3_worker_secret_key)" >/dev/null +mc admin policy attach storage attachments-worker --user "$worker_key" >/dev/null +echo 'S3 bootstrap complete: private bucket, API and worker policies.' diff --git a/infra/s3/check.sh b/infra/s3/check.sh new file mode 100644 index 00000000..2137f997 --- /dev/null +++ b/infra/s3/check.sh @@ -0,0 +1,37 @@ +#!/bin/sh +# Проверка непосредственно S3. Endpoint приложения будет добавлен на следующем этапе. +set -eu +umask 077 +bucket=${S3_BUCKET:?S3_BUCKET is required} +mc alias set app http://s3:9000 \ + "$(cat /run/secrets/s3_access_key_id)" \ + "$(cat /run/secrets/s3_secret_access_key)" >/dev/null +key="staging/infra-check-$(cat /proc/sys/kernel/random/uuid).png" +cleanup() { mc rm "app/$bucket/$key" >/dev/null 2>&1 || true; } +trap cleanup EXIT + +mc cp /fixtures/sample.png "app/$bucket/$key" >/dev/null +mc cp "app/$bucket/$key" /tmp/download.png >/dev/null +original_hash=$(sha256sum /fixtures/sample.png | cut -d ' ' -f 1) +download_hash=$(sha256sum /tmp/download.png | cut -d ' ' -f 1) +[ "$original_hash" = "$download_hash" ] +[ "$(wc -c < /fixtures/sample.png)" = "$(wc -c < /tmp/download.png)" ] +echo 'PASS: API credentials upload/download match SHA-256 and size.' + +code=$(curl --silent --show-error --max-time 10 --output /dev/null --write-out '%{http_code}' "http://s3:9000/$bucket/$key") +[ "$code" = 403 ] || { echo "FAIL: anonymous GET returned $code" >&2; exit 1; } +echo 'PASS: anonymous GET of an existing object returns 403.' + +if mc admin info app >/dev/null 2>&1; then + echo 'FAIL: API credentials have admin access' >&2; exit 1 +fi +if mc cp /fixtures/sample.png "app/$bucket/forbidden-check.png" >/dev/null 2>&1; then + mc rm "app/$bucket/forbidden-check.png" >/dev/null + echo 'FAIL: API credentials can write outside staging/' >&2; exit 1 +fi +echo 'PASS: API credentials cannot administer S3 or write to the bucket root.' +mc rm "app/$bucket/$key" >/dev/null +if mc stat "app/$bucket/$key" >/dev/null 2>&1; then + echo 'FAIL: object was not deleted' >&2; exit 1 +fi +echo 'PASS: API credentials delete the temporary object.' diff --git a/infra/s3/cleanup.md b/infra/s3/cleanup.md new file mode 100644 index 00000000..5406ad38 --- /dev/null +++ b/infra/s3/cleanup.md @@ -0,0 +1,14 @@ +# Очистка объектов staging + +API создаёт устойчивую запись `upload_intents` до PUT. После записи оригинала API блокирует запись приёма, проверяет срок действия и одной транзакцией создаёт вложение и задание, а затем удаляет запись приёма. При неопределённом исходе COMMIT наличие записи определяет, требуется ли уборка. Активное задание хранит ключ исходника. + +Worker добавляет запись очистки в ту же транзакцию, которая фиксирует `ready` или `failed`. Для `ready` объект доступен для уборки сразу. Для `failed` отсчёт retention начинается с фиксации ошибки. Replay блокирует запись очистки и снимает её до возврата задания в очередь. + +На каждой реплике API очистка выбирает просроченные записи пакетами через `FOR UPDATE SKIP LOCKED`. Запись с ключом действующего задания защищена от удаления. У непринятой загрузки после DELETE остаётся запись для повторной уборки, если её PUT завершится с опозданием. Для терминальных задач запись снимается после успешного DELETE. + +```sh +docker compose run --rm --no-deps api --cleanup-uploads +dotnet test --filter FullyQualifiedName~UploadCleanupTests +``` + +Ручной проход использует те же ограничения, что фоновый. Настройки `UPLOAD_CLEANUP_GRACE_SECONDS` и `UPLOAD_CLEANUP_INTERVAL_SECONDS` по умолчанию равны 300 и 30 секундам. Срок хранения исходников failed задаёт `STAGING_RETENTION_SECONDS`. diff --git a/infra/s3/start.sh b/infra/s3/start.sh new file mode 100644 index 00000000..147fedc6 --- /dev/null +++ b/infra/s3/start.sh @@ -0,0 +1,5 @@ +#!/bin/sh +set -eu +export MINIO_ROOT_USER="$(cat /run/secrets/s3_root_user)" +export MINIO_ROOT_PASSWORD="$(cat /run/secrets/s3_root_password)" +exec minio server /data --address :9000 diff --git a/mtusi2026lab3-fork.sln b/mtusi2026lab3-fork.sln new file mode 100644 index 00000000..1ef9e1c6 --- /dev/null +++ b/mtusi2026lab3-fork.sln @@ -0,0 +1,36 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.5.2.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "scr", "scr", "{027FA04E-56EC-7B26-372C-A48CC532505F}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Messenger.Api", "scr\Messenger.Api\Messenger.Api.csproj", "{630C0B6F-93DF-AAC7-9A7B-184D4E60B431}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Messenger.Api.Tests", "scr\Messenger.Api.Tests\Messenger.Api.Tests.csproj", "{4F2D7000-2CE0-BBF9-8937-6B7E8F80C7D2}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {630C0B6F-93DF-AAC7-9A7B-184D4E60B431}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {630C0B6F-93DF-AAC7-9A7B-184D4E60B431}.Debug|Any CPU.Build.0 = Debug|Any CPU + {630C0B6F-93DF-AAC7-9A7B-184D4E60B431}.Release|Any CPU.ActiveCfg = Release|Any CPU + {630C0B6F-93DF-AAC7-9A7B-184D4E60B431}.Release|Any CPU.Build.0 = Release|Any CPU + {4F2D7000-2CE0-BBF9-8937-6B7E8F80C7D2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4F2D7000-2CE0-BBF9-8937-6B7E8F80C7D2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4F2D7000-2CE0-BBF9-8937-6B7E8F80C7D2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4F2D7000-2CE0-BBF9-8937-6B7E8F80C7D2}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {630C0B6F-93DF-AAC7-9A7B-184D4E60B431} = {027FA04E-56EC-7B26-372C-A48CC532505F} + {4F2D7000-2CE0-BBF9-8937-6B7E8F80C7D2} = {027FA04E-56EC-7B26-372C-A48CC532505F} + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {41A93240-9911-4469-8EAB-F192C6DC6640} + EndGlobalSection +EndGlobal diff --git a/scr/Messenger.Api.Tests/ApiFixture.cs b/scr/Messenger.Api.Tests/ApiFixture.cs new file mode 100644 index 00000000..6b1b3aab --- /dev/null +++ b/scr/Messenger.Api.Tests/ApiFixture.cs @@ -0,0 +1,135 @@ +using DotNet.Testcontainers.Builders; +using DotNet.Testcontainers.Containers; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Npgsql; +using StackExchange.Redis; +using Testcontainers.PostgreSql; +using Amazon.S3; +using Amazon.S3.Model; +using Messenger.Api.Jobs; +using Microsoft.Extensions.DependencyInjection; + +namespace Messenger.Api.Tests; + +// Один одноразовый контейнер PostgreSQL и один Valkey на весь тестовый прогон. Приложение поднимается в процессе теста +// и применяет миграции к пустой БД, как при настоящем старте. Нужен только запущенный Docker. +// Настройки передаются через UseSetting (а не переменные окружения), поэтому тест может поднять второй экземпляр +// приложения с другими настройками: fixture.WithWebHostBuilder(b => b.UseSetting("SESSION_TTL_SECONDS", "2")). +public sealed class ApiFixture : WebApplicationFactory, IAsyncLifetime +{ + public const string PostgresImage = "postgres:17@sha256:b8faeff7712663c2773a190181e1246e37e364b887611c04658c28b44e2408fe"; + private const string ValkeyImage = "valkey/valkey:8.1@sha256:640c5e62cea04b6d6f2084232651d0cc70362d31f4f805e7be94dbed6855e8f2"; + + private readonly PostgreSqlContainer _db = new PostgreSqlBuilder().WithImage(PostgresImage).Build(); + + private readonly IContainer _cache = new ContainerBuilder() + .WithImage(ValkeyImage) + .WithPortBinding(6379, true) + .WithWaitStrategy(Wait.ForUnixContainer().UntilMessageIsLogged("Ready to accept connections")) + .Build(); + + private string _connectionFile = string.Empty; + private string _s3AccessFile = string.Empty; + private string _s3SecretFile = string.Empty; + private const string S3Access = "integration-test-user"; + private const string S3Secret = "integration-only-not-a-real-secret"; + private readonly IContainer _s3 = new ContainerBuilder() + .WithImage("quay.io/minio/minio@sha256:14cea493d9a34af32f524e538b8346cf79f3321eff8e708c1e2960462bd8936e") + .WithEnvironment("MINIO_ROOT_USER", S3Access) + .WithEnvironment("MINIO_ROOT_PASSWORD", S3Secret) + .WithEnvironment("MINIO_BROWSER", "off") + .WithCommand("server", "/data") + .WithPortBinding(9000, true) + .WithWaitStrategy(Wait.ForUnixContainer().UntilHttpRequestIsSucceeded(r => r.ForPort(9000).ForPath("/minio/health/ready"))) + .Build(); + + public string ConnectionString => _db.GetConnectionString(); + public string CacheConnection => $"{_cache.Hostname}:{_cache.GetMappedPublicPort(6379)}"; + + public async Task InitializeAsync() + { + await Task.WhenAll(_db.StartAsync(), _cache.StartAsync(), _s3.StartAsync()); + _connectionFile = WriteConnectionFile(_db.GetConnectionString()); + _s3AccessFile = WriteConnectionFile(S3Access); + _s3SecretFile = WriteConnectionFile(S3Secret); + using var client = new AmazonS3Client(S3Access, S3Secret, new AmazonS3Config + { ServiceURL = $"http://{_s3.Hostname}:{_s3.GetMappedPublicPort(9000)}", ForcePathStyle = true, AuthenticationRegion = "us-east-1" }); + await client.PutBucketAsync(new PutBucketRequest { BucketName = "integration-attachments" }); + } + + async Task IAsyncLifetime.DisposeAsync() + { + await _db.DisposeAsync(); + await _cache.DisposeAsync(); + await _s3.DisposeAsync(); + File.Delete(_connectionFile); + File.Delete(_s3AccessFile); + File.Delete(_s3SecretFile); + } + + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + builder.UseSetting("DATABASE_URL_FILE", _connectionFile); + builder.UseSetting("CACHE_CONNECTION", CacheConnection); + builder.UseSetting("DIAGNOSTIC_HEADERS", "true"); + builder.UseSetting("S3_ENDPOINT", $"http://{_s3.Hostname}:{_s3.GetMappedPublicPort(9000)}"); + builder.UseSetting("S3_BUCKET", "integration-attachments"); + builder.UseSetting("S3_ACCESS_KEY_ID_FILE", _s3AccessFile); + builder.UseSetting("S3_SECRET_ACCESS_KEY_FILE", _s3SecretFile); + // В Compose схему применяет отдельный контейнер (--migrate); тестовый процесс мигрирует пустую БД сам. + builder.UseSetting("MIGRATE_ON_START", "true"); + builder.UseSetting("SHUTDOWN_DRAIN_SECONDS", "0"); + builder.ConfigureServices(services => + { + services.AddSingleton(new JobSettings(2, TimeSpan.FromSeconds(30), 1, TimeSpan.FromHours(1))); + services.AddScoped(); + }); + } + + public static string WriteConnectionFile(string connectionString) + { + var path = Path.Combine(Path.GetTempPath(), $"messenger-test-{Guid.NewGuid():N}.conn"); + File.WriteAllText(path, connectionString); + return path; + } + + // Прямой доступ к БД для проверок, которые нельзя выразить через API (например, состояние таблицы sessions). + public async Task OpenConnectionAsync() + { + var connection = new NpgsqlConnection(ConnectionString); + await connection.OpenAsync(); + return connection; + } + + public async Task ScalarAsync(string sql, params (string Name, object Value)[] parameters) + { + await using var db = await OpenConnectionAsync(); + await using var command = new NpgsqlCommand(sql, db); + foreach (var (name, value) in parameters) + { + command.Parameters.AddWithValue(name, value); + } + + var result = await command.ExecuteScalarAsync(); + return result is null or DBNull ? default : (T)result; + } + + public async Task ExecuteAsync(string sql) + { + await using var db = await OpenConnectionAsync(); + await using var command = new NpgsqlCommand(sql, db); + await command.ExecuteNonQueryAsync(); + } + + // Полная очистка содержимого кэша (эквивалент FLUSHALL / перезапуска Valkey без persistence). + public async Task FlushCacheAsync() + { + using var connection = await ConnectionMultiplexer.ConnectAsync( + new ConfigurationOptions { EndPoints = { CacheConnection }, AllowAdmin = true }); + await connection.GetServer(connection.GetEndPoints()[0]).FlushAllDatabasesAsync(); + } +} + +[CollectionDefinition("api")] +public sealed class ApiCollection : ICollectionFixture; diff --git a/scr/Messenger.Api.Tests/ApiHelpers.cs b/scr/Messenger.Api.Tests/ApiHelpers.cs new file mode 100644 index 00000000..2b73a4e7 --- /dev/null +++ b/scr/Messenger.Api.Tests/ApiHelpers.cs @@ -0,0 +1,104 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text; +using System.Text.Json; + +namespace Messenger.Api.Tests; + +internal sealed record TestUser(Guid Id, string Username, string Password, string Token); + +internal static class ApiHelpers +{ + public const string DefaultPassword = "correct horse battery staple"; + + public static StringContent Json(string raw) => + new(raw, Encoding.UTF8, "application/json"); + + // user != null — запрос с Bearer-токеном этого пользователя. + public static HttpRequestMessage Request(HttpMethod method, string url, TestUser? user = null, HttpContent? content = null) + { + var request = new HttpRequestMessage(method, url) { Content = content }; + if (user is not null) + { + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", user.Token); + } + + return request; + } + + public static async Task ReadJsonAsync(HttpResponseMessage response) + { + var body = await response.Content.ReadAsStringAsync(); + return JsonDocument.Parse(body).RootElement.Clone(); + } + + public static async Task ErrorCodeAsync(HttpResponseMessage response) + { + var json = await ReadJsonAsync(response); + return json.GetProperty("error").GetProperty("code").GetString()!; + } + + public static string BasicHeader(string username, string password) => + "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes($"{username}:{password}")); + + public static async Task LoginAsync(HttpClient client, string username, string password) + { + using var request = new HttpRequestMessage(HttpMethod.Post, "/api/v1/auth/sessions"); + request.Headers.TryAddWithoutValidation("Authorization", BasicHeader(username, password)); + return await client.SendAsync(request); + } + + // Регистрирует пользователя и входит: возвращает его с рабочим Bearer-токеном. + public static async Task CreateUserAsync(HttpClient client, string? username = null) + { + username ??= "u" + Guid.NewGuid().ToString("N")[..12]; + var response = await client.PostAsJsonAsync("/api/v1/users", + new { username, display_name = "Тест", password = DefaultPassword }); + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + var id = (await ReadJsonAsync(response)).GetProperty("id").GetGuid(); + + var login = await LoginAsync(client, username, DefaultPassword); + Assert.Equal(HttpStatusCode.Created, login.StatusCode); + var token = (await ReadJsonAsync(login)).GetProperty("token").GetString()!; + return new TestUser(id, username, DefaultPassword, token); + } + + public static async Task CreateChatAsync(HttpClient client, TestUser owner, params TestUser[] others) + { + var members = others.Append(owner).Select(u => u.Id).ToArray(); + using var request = Request(HttpMethod.Post, "/api/v1/chats", owner, + JsonContent.Create(new { title = "Чат", member_ids = members })); + var response = await client.SendAsync(request); + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + return (await ReadJsonAsync(response)).GetProperty("id").GetGuid(); + } + + // key == null — новый уникальный Idempotency-Key (каждое сообщение независимо); иначе повтор с заданным ключом. + public static async Task SendMessageAsync( + HttpClient client, TestUser sender, Guid chatId, string text, string? key = null) + { + using var request = Request(HttpMethod.Post, $"/api/v1/chats/{chatId}/messages", sender, + JsonContent.Create(new { text })); + request.Headers.Add("Idempotency-Key", key ?? Guid.NewGuid().ToString("N")); + return await client.SendAsync(request); + } + + public static async Task> ReadAllMessagesAsync(HttpClient client, Guid chatId, TestUser user, int limit) + { + string? cursor = null; + var received = new List(); + do + { + var url = $"/api/v1/chats/{chatId}/messages?limit={limit}" + + (cursor is null ? "" : "&cursor=" + Uri.EscapeDataString(cursor)); + using var request = Request(HttpMethod.Get, url, user); + var page = await ReadJsonAsync(await client.SendAsync(request)); + received.AddRange(page.GetProperty("items").EnumerateArray().Select(m => m.GetProperty("id").GetGuid())); + var next = page.GetProperty("next_cursor"); + cursor = next.ValueKind == JsonValueKind.Null ? null : next.GetString(); + } + while (cursor is not null); + return received; + } +} diff --git a/scr/Messenger.Api.Tests/ApiTests.cs b/scr/Messenger.Api.Tests/ApiTests.cs new file mode 100644 index 00000000..77c45a16 --- /dev/null +++ b/scr/Messenger.Api.Tests/ApiTests.cs @@ -0,0 +1,303 @@ +using System.Net; +using System.Text.Json; +using static Messenger.Api.Tests.ApiHelpers; + +namespace Messenger.Api.Tests; + +[Collection("api")] +public class ApiTests(ApiFixture fixture) +{ + private HttpClient NewClient() => fixture.CreateClient(); + + [Fact] + public async Task CreateUser_WithMalformedJson_ReturnsBadRequest() + { + using var client = NewClient(); + + var response = await client.PostAsync("/api/v1/users", Json("{bad")); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Equal("invalid_request", await ErrorCodeAsync(response)); + Assert.True(response.Headers.Contains("X-Request-Id")); + } + + [Fact] + public async Task CreateUser_WithoutBody_ReturnsBadRequest() + { + using var client = NewClient(); + + var response = await client.PostAsync("/api/v1/users", null); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Equal("invalid_request", await ErrorCodeAsync(response)); + } + + [Fact] + public async Task CreateUser_WithDuplicateUsername_ReturnsConflict() + { + using var client = NewClient(); + var user = await CreateUserAsync(client); + + var response = await client.PostAsync("/api/v1/users", + Json($$"""{"username":"{{user.Username}}","display_name":"Другой","password":"{{DefaultPassword}}"}""")); + + Assert.Equal(HttpStatusCode.Conflict, response.StatusCode); + Assert.Equal("conflict", await ErrorCodeAsync(response)); + } + + [Theory] + [InlineData("short")] + [InlineData("12345678901")] // 11 символов + public async Task CreateUser_WithShortPassword_ReturnsBadRequest(string password) + { + using var client = NewClient(); + + var response = await client.PostAsync("/api/v1/users", + Json($$"""{"username":"short_pw_probe","display_name":"A","password":"{{password}}"}""")); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + [Fact] + public async Task CreateUser_Response_DoesNotExposePasswordOrHash() + { + using var client = NewClient(); + + var response = await client.PostAsync("/api/v1/users", + Json($$"""{"username":"no_leak_probe","display_name":"A","password":"{{DefaultPassword}}"}""")); + + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + var body = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("password", body, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("argon2", body, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task GetChat_ByNonMember_ReturnsNotFound() + { + using var client = NewClient(); + var alice = await CreateUserAsync(client); + var bob = await CreateUserAsync(client); + var eve = await CreateUserAsync(client); + var chatId = await CreateChatAsync(client, alice, bob); + + using var request = Request(HttpMethod.Get, $"/api/v1/chats/{chatId}", eve); + var response = await client.SendAsync(request); + + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + Assert.Equal("not_found", await ErrorCodeAsync(response)); + } + + [Fact] + public async Task ListChats_ShowsOnlyChatsOfCurrentUser() + { + using var client = NewClient(); + var alice = await CreateUserAsync(client); + var bob = await CreateUserAsync(client); + var eve = await CreateUserAsync(client); + var shared = await CreateChatAsync(client, alice, bob); + var other = await CreateChatAsync(client, eve); + + using var request = Request(HttpMethod.Get, "/api/v1/chats", bob); + var page = await ReadJsonAsync(await client.SendAsync(request)); + var ids = page.GetProperty("items").EnumerateArray().Select(c => c.GetProperty("id").GetGuid()).ToList(); + + Assert.Contains(shared, ids); + Assert.DoesNotContain(other, ids); + } + + [Fact] + public async Task CreateChat_WithUnknownMember_ReturnsBadRequestAndCreatesNothing() + { + using var client = NewClient(); + var alice = await CreateUserAsync(client); + + using var request = Request(HttpMethod.Post, "/api/v1/chats", alice, + Json($$"""{"title":"X","member_ids":["{{alice.Id}}","{{Guid.NewGuid()}}"]}""")); + var response = await client.SendAsync(request); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + using var list = Request(HttpMethod.Get, "/api/v1/chats", alice); + var page = await ReadJsonAsync(await client.SendAsync(list)); + Assert.Empty(page.GetProperty("items").EnumerateArray()); + } + + [Fact] + public async Task SendMessage_ToForeignChat_ReturnsNotFound() + { + using var client = NewClient(); + var alice = await CreateUserAsync(client); + var bob = await CreateUserAsync(client); + var eve = await CreateUserAsync(client); + var chatId = await CreateChatAsync(client, alice, bob); + + var response = await SendMessageAsync(client, eve, chatId, "чужое"); + + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + public async Task SendMessage_WithEmptyText_ReturnsBadRequest(string text) + { + using var client = NewClient(); + var alice = await CreateUserAsync(client); + var chatId = await CreateChatAsync(client, alice); + + var response = await SendMessageAsync(client, alice, chatId, text); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Equal("invalid_request", await ErrorCodeAsync(response)); + } + + [Fact] + public async Task SendMessage_SenderIsTakenFromSession_NotFromRequest() + { + using var client = NewClient(); + var alice = await CreateUserAsync(client); + var bob = await CreateUserAsync(client); + var chatId = await CreateChatAsync(client, alice, bob); + + using var request = Request(HttpMethod.Post, $"/api/v1/chats/{chatId}/messages", alice, + Json($$"""{"text":"привет","sender_id":"{{bob.Id}}"}""")); + request.Headers.Add("Idempotency-Key", Guid.NewGuid().ToString("N")); + var withSender = await client.SendAsync(request); + var ok = await SendMessageAsync(client, alice, chatId, "привет"); + + Assert.Equal(HttpStatusCode.BadRequest, withSender.StatusCode); // sender_id в запросе не принимается + Assert.Equal(alice.Id, (await ReadJsonAsync(ok)).GetProperty("sender_id").GetGuid()); + } + + [Fact] + public async Task ListMessages_WalksAllPagesWithoutGapsOrDuplicates() + { + using var client = NewClient(); + var alice = await CreateUserAsync(client); + var bob = await CreateUserAsync(client); + var chatId = await CreateChatAsync(client, alice, bob); + const int total = 7; + var sent = new List(); + for (var i = 0; i < total; i++) + { + var response = await SendMessageAsync(client, i % 2 == 0 ? alice : bob, chatId, $"сообщение {i}"); + sent.Add((await ReadJsonAsync(response)).GetProperty("id").GetGuid()); + } + + var received = new List(); + string? cursor = null; + var pages = 0; + do + { + var url = $"/api/v1/chats/{chatId}/messages?limit=3" + + (cursor is null ? "" : "&cursor=" + Uri.EscapeDataString(cursor)); + using var request = Request(HttpMethod.Get, url, alice); + var page = await ReadJsonAsync(await client.SendAsync(request)); + received.AddRange(page.GetProperty("items").EnumerateArray().Select(m => m.GetProperty("id").GetGuid())); + var next = page.GetProperty("next_cursor"); + cursor = next.ValueKind == JsonValueKind.Null ? null : next.GetString(); + pages++; + } + while (cursor is not null && pages < 10); + + Assert.Equal(3, pages); + Assert.Equal(total, received.Count); + // Один автор в одном чате: порядок истории совпадает с порядком отправки. + Assert.Equal(sent, received); + } + + [Fact] + public async Task ListMessages_WithCursorFromAnotherChat_ReturnsBadRequest() + { + using var client = NewClient(); + var alice = await CreateUserAsync(client); + var chat1 = await CreateChatAsync(client, alice); + var chat2 = await CreateChatAsync(client, alice); + await SendMessageAsync(client, alice, chat1, "a"); + await SendMessageAsync(client, alice, chat1, "b"); + using var first = Request(HttpMethod.Get, $"/api/v1/chats/{chat1}/messages?limit=1", alice); + var cursor = (await ReadJsonAsync(await client.SendAsync(first))).GetProperty("next_cursor").GetString()!; + + using var request = Request(HttpMethod.Get, + $"/api/v1/chats/{chat2}/messages?cursor={Uri.EscapeDataString(cursor)}", alice); + var response = await client.SendAsync(request); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + [Fact] + public async Task ListMessages_ReturnsSameOrderForAnyPageSize() + { + using var client = NewClient(); + var alice = await CreateUserAsync(client); + var chatId = await CreateChatAsync(client, alice); + var sent = new List(); + for (var i = 0; i < 120; i++) + { + var response = await SendMessageAsync(client, alice, chatId, $"m{i}"); + sent.Add((await ReadJsonAsync(response)).GetProperty("id").GetGuid()); + } + + var baseline = await ReadAllMessagesAsync(client, chatId, alice, 100); + Assert.Equal(sent, baseline); + foreach (var limit in new[] { 1, 7, 50 }) + { + var received = await ReadAllMessagesAsync(client, chatId, alice, limit); + Assert.Equal(baseline, received); + } + } + + [Fact] + public async Task ListMessages_AfterConcurrentSends_IsOrderedByTimeThenId() + { + using var client = NewClient(); + var users = new List(); + for (var i = 0; i < 10; i++) + { + users.Add(await CreateUserAsync(client)); + } + + var chatId = await CreateChatAsync(client, users[0], users.Skip(1).ToArray()); + + var sends = Enumerable.Range(0, 300).Select(i => SendMessageAsync(client, users[i % 10], chatId, $"m{i}")); + foreach (var response in await Task.WhenAll(sends)) + { + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + } + + var items = new List<(string CreatedAt, Guid Id)>(); + string? cursor = null; + do + { + var url = $"/api/v1/chats/{chatId}/messages?limit=100" + + (cursor is null ? "" : "&cursor=" + Uri.EscapeDataString(cursor)); + using var request = Request(HttpMethod.Get, url, users[0]); + var page = await ReadJsonAsync(await client.SendAsync(request)); + items.AddRange(page.GetProperty("items").EnumerateArray() + .Select(m => (m.GetProperty("created_at").GetString()!, m.GetProperty("id").GetGuid()))); + var next = page.GetProperty("next_cursor"); + cursor = next.ValueKind == JsonValueKind.Null ? null : next.GetString(); + } + while (cursor is not null); + + Assert.Equal(300, items.Count); + Assert.Equal(300, items.Select(x => x.Id).Distinct().Count()); + // Серверное время строго возрастает внутри чата (см. last_message_at), поэтому порядок истории — порядок записи. + Assert.Equal(300, items.Select(x => x.CreatedAt).Distinct().Count()); + Assert.Equal(items.OrderBy(x => x.CreatedAt, StringComparer.Ordinal).ToList(), items); + } + + [Theory] + [InlineData("""{"USERNAME":"probe_case_a","display_name":"A","password":"correct horse battery staple"}""")] + [InlineData("""{"username":"probe_case_b","Display_Name":"A","password":"correct horse battery staple"}""")] + [InlineData("""{"Username":"probe_case_c","display_name":"A","password":"correct horse battery staple"}""")] + public async Task CreateUser_WithDifferentlyCasedFieldNames_ReturnsBadRequest(string body) + { + using var client = NewClient(); + + var response = await client.PostAsync("/api/v1/users", Json(body)); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Equal("invalid_request", await ErrorCodeAsync(response)); + } +} diff --git a/scr/Messenger.Api.Tests/AuthTests.cs b/scr/Messenger.Api.Tests/AuthTests.cs new file mode 100644 index 00000000..e2cd91ef --- /dev/null +++ b/scr/Messenger.Api.Tests/AuthTests.cs @@ -0,0 +1,252 @@ +using System.Net; +using System.Net.Http.Headers; +using static Messenger.Api.Tests.ApiHelpers; + +namespace Messenger.Api.Tests; + +[Collection("api")] +public class AuthTests(ApiFixture fixture) +{ + private static readonly string[] ProtectedGets = + [ + "/api/v1/users/me", + "/api/v1/chats", + "/api/v1/chats/00000000-0000-0000-0000-000000000001", + "/api/v1/chats/00000000-0000-0000-0000-000000000001/messages" + ]; + + [Fact] + public async Task Login_WithValidCredentials_ReturnsOpaqueBearerSession() + { + using var client = fixture.CreateClient(); + var user = await CreateUserAsync(client); + + var response = await LoginAsync(client, user.Username, user.Password); + + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + var json = await ReadJsonAsync(response); + Assert.Equal("Bearer", json.GetProperty("token_type").GetString()); + Assert.True(json.GetProperty("token").GetString()!.Length >= 43); // 256 бит в base64url + Assert.Equal(user.Id, json.GetProperty("user").GetProperty("id").GetGuid()); + Assert.DoesNotContain("password", await response.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task Login_AcceptsColonInPassword() + { + using var client = fixture.CreateClient(); + var username = "colon" + Guid.NewGuid().ToString("N")[..8]; + await client.PostAsync("/api/v1/users", + Json($$"""{"username":"{{username}}","display_name":"A","password":"pass:with:colons-123"}""")); + + var response = await LoginAsync(client, username, "pass:with:colons-123"); + + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + } + + [Fact] + public async Task Login_WrongPasswordAndUnknownUser_GiveIdenticalUnauthorized() + { + using var client = fixture.CreateClient(); + var user = await CreateUserAsync(client); + + var wrongPassword = await LoginAsync(client, user.Username, "totally-wrong-password"); + var unknownUser = await LoginAsync(client, "nobody_" + Guid.NewGuid().ToString("N")[..8], DefaultPassword); + + foreach (var response in new[] { wrongPassword, unknownUser }) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("Basic realm=\"messenger\", charset=\"UTF-8\"", response.Headers.WwwAuthenticate.ToString()); + Assert.Equal("unauthorized", await ErrorCodeAsync(response)); + } + + var a = (await ReadJsonAsync(wrongPassword)).GetProperty("error").GetProperty("message").GetString(); + var b = (await ReadJsonAsync(unknownUser)).GetProperty("error").GetProperty("message").GetString(); + Assert.Equal(a, b); + } + + [Theory] + [InlineData("Basic !!!not-base64")] + [InlineData("Basic bm9jb2xvbg==")] // "nocolon" + [InlineData("Bearer sometoken")] + [InlineData("")] + public async Task Login_WithMalformedAuthorization_ReturnsUnauthorized(string header) + { + using var client = fixture.CreateClient(); + using var request = new HttpRequestMessage(HttpMethod.Post, "/api/v1/auth/sessions"); + if (header.Length > 0) + { + request.Headers.TryAddWithoutValidation("Authorization", header); + } + + var response = await client.SendAsync(request); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.StartsWith("Basic", response.Headers.WwwAuthenticate.ToString()); + } + + [Theory] + [MemberData(nameof(ProtectedUrls))] + public async Task ProtectedEndpoints_WithoutToken_ReturnUnauthorizedWithBearerChallenge(string url) + { + using var client = fixture.CreateClient(); + + var response = await client.GetAsync(url); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("Bearer realm=\"messenger\"", response.Headers.WwwAuthenticate.ToString()); + Assert.True(response.Headers.Contains("X-Request-Id")); + } + + public static IEnumerable ProtectedUrls() => ProtectedGets.Select(u => new object[] { u }); + + [Fact] + public async Task ProtectedEndpoint_WithBasicAuth_ReturnsUnauthorized() + { + using var client = fixture.CreateClient(); + var user = await CreateUserAsync(client); + using var request = new HttpRequestMessage(HttpMethod.Get, "/api/v1/users/me"); + request.Headers.TryAddWithoutValidation("Authorization", BasicHeader(user.Username, user.Password)); + + var response = await client.SendAsync(request); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + [Fact] + public async Task XUserIdHeader_IsIgnored() + { + using var client = fixture.CreateClient(); + var alice = await CreateUserAsync(client); + var eve = await CreateUserAsync(client); + + // Без токена X-User-Id не даёт доступа. + using var anonymous = new HttpRequestMessage(HttpMethod.Get, "/api/v1/users/me"); + anonymous.Headers.Add("X-User-Id", alice.Id.ToString()); + Assert.Equal(HttpStatusCode.Unauthorized, (await client.SendAsync(anonymous)).StatusCode); + + // С токеном — владелец сессии не подменяется. + using var spoofed = Request(HttpMethod.Get, "/api/v1/users/me", alice); + spoofed.Headers.Add("X-User-Id", eve.Id.ToString()); + var me = await ReadJsonAsync(await client.SendAsync(spoofed)); + Assert.Equal(alice.Id, me.GetProperty("id").GetGuid()); + } + + [Fact] + public async Task UnauthenticatedPostWithMalformedBody_ReturnsUnauthorizedNotBadRequest() + { + using var client = fixture.CreateClient(); + + var response = await client.PostAsync("/api/v1/chats", Json("{bad")); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); // сначала аутентификация + } + + [Fact] + public async Task Logout_RevokesTokenAndSecondLogoutIsUnauthorized() + { + using var client = fixture.CreateClient(); + var user = await CreateUserAsync(client); + + using var first = Request(HttpMethod.Delete, "/api/v1/auth/sessions/current", user); + var firstResponse = await client.SendAsync(first); + Assert.Equal(HttpStatusCode.NoContent, firstResponse.StatusCode); + Assert.Equal(0, firstResponse.Content.Headers.ContentLength ?? 0); + + using var again = Request(HttpMethod.Delete, "/api/v1/auth/sessions/current", user); + Assert.Equal(HttpStatusCode.Unauthorized, (await client.SendAsync(again)).StatusCode); + using var me = Request(HttpMethod.Get, "/api/v1/users/me", user); + Assert.Equal(HttpStatusCode.Unauthorized, (await client.SendAsync(me)).StatusCode); + } + + [Fact] + public async Task LogoutOfOneSession_DoesNotAffectAnotherSessionOfSameUser() + { + using var client = fixture.CreateClient(); + var user = await CreateUserAsync(client); + var secondLogin = await ReadJsonAsync(await LoginAsync(client, user.Username, user.Password)); + var second = user with { Token = secondLogin.GetProperty("token").GetString()! }; + + using var logout = Request(HttpMethod.Delete, "/api/v1/auth/sessions/current", user); + await client.SendAsync(logout); + + using var me = Request(HttpMethod.Get, "/api/v1/users/me", second); + Assert.Equal(HttpStatusCode.OK, (await client.SendAsync(me)).StatusCode); + } + + [Fact] + public async Task ExpiredSession_IsRejected() + { + using var client = fixture.CreateClient(); + var user = await CreateUserAsync(client); + using var before = Request(HttpMethod.Get, "/api/v1/users/me", user); + Assert.Equal(HttpStatusCode.OK, (await client.SendAsync(before)).StatusCode); + + // Состарим сессию в БД: created_at < expires_at < now (ограничение таблицы требует expires_at > created_at). + await using (var db = await fixture.OpenConnectionAsync()) + await using (var age = new Npgsql.NpgsqlCommand( + "update sessions set created_at = now() - interval '10 seconds', expires_at = now() - interval '5 seconds' where user_id = @u", db)) + { + age.Parameters.AddWithValue("u", user.Id); + Assert.Equal(1, await age.ExecuteNonQueryAsync()); + } + + using var after = Request(HttpMethod.Get, "/api/v1/users/me", user); + Assert.Equal(HttpStatusCode.Unauthorized, (await client.SendAsync(after)).StatusCode); + } + + [Fact] + public async Task ShortSessionTtl_ExpiresSessionByItself() + { + // Отдельный экземпляр приложения с SESSION_TTL_SECONDS=2 поверх той же БД: никаких подмен данных в таблице. + await using var app = fixture.WithWebHostBuilder(b => b.UseSetting("SESSION_TTL_SECONDS", "2")); + using var client = app.CreateClient(); + var user = await CreateUserAsync(client); + + using (var alive = Request(HttpMethod.Get, "/api/v1/users/me", user)) + { + Assert.Equal(HttpStatusCode.OK, (await client.SendAsync(alive)).StatusCode); + } + + await Task.Delay(TimeSpan.FromSeconds(3)); + + using var expired = Request(HttpMethod.Get, "/api/v1/users/me", user); + var response = await client.SendAsync(expired); + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("Bearer realm=\"messenger\"", response.Headers.WwwAuthenticate.ToString()); + // Истёкшая сессия не продлевается: повторный вход выдаёт новую. + Assert.Equal(HttpStatusCode.Created, (await LoginAsync(client, user.Username, user.Password)).StatusCode); + } + + [Fact] + public async Task SessionsTable_StoresTokenHashNotToken() + { + using var client = fixture.CreateClient(); + var user = await CreateUserAsync(client); + + await using var db = await fixture.OpenConnectionAsync(); + await using var query = new Npgsql.NpgsqlCommand( + "select token_hash from sessions where user_id = @u", db); + query.Parameters.AddWithValue("u", user.Id); + var stored = (byte[])(await query.ExecuteScalarAsync())!; + + Assert.Equal(32, stored.Length); + Assert.NotEqual(System.Text.Encoding.UTF8.GetBytes(user.Token), stored); + Assert.Equal(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(user.Token)), stored); + } + + [Fact] + public async Task PasswordsAreStoredAsArgon2id() + { + using var client = fixture.CreateClient(); + var user = await CreateUserAsync(client); + + await using var db = await fixture.OpenConnectionAsync(); + await using var query = new Npgsql.NpgsqlCommand("select password_hash from users where id = @u", db); + query.Parameters.AddWithValue("u", user.Id); + var hash = (string)(await query.ExecuteScalarAsync())!; + + Assert.StartsWith("$argon2id$", hash); + Assert.DoesNotContain(user.Password, hash); + } +} diff --git a/scr/Messenger.Api.Tests/CacheTests.cs b/scr/Messenger.Api.Tests/CacheTests.cs new file mode 100644 index 00000000..70b0e24b --- /dev/null +++ b/scr/Messenger.Api.Tests/CacheTests.cs @@ -0,0 +1,150 @@ +using System.Net; +using Microsoft.AspNetCore.Mvc.Testing; +using static Messenger.Api.Tests.ApiHelpers; + +namespace Messenger.Api.Tests; + +[Collection("api")] +public class CacheTests(ApiFixture fixture) +{ + private static string Header(HttpResponseMessage response, string name) => + response.Headers.TryGetValues(name, out var values) ? values.First() : ""; + + private static async Task GetPageAsync( + HttpClient client, TestUser user, Guid chatId, int limit = 50, string? cursor = null) + { + var url = $"/api/v1/chats/{chatId}/messages?limit={limit}" + + (cursor is null ? "" : "&cursor=" + Uri.EscapeDataString(cursor)); + using var request = Request(HttpMethod.Get, url, user); + return await client.SendAsync(request); + } + + private static async Task<(TestUser Alice, TestUser Bob, Guid Chat)> ChatWithMessagesAsync(HttpClient client, int messages) + { + var alice = await CreateUserAsync(client); + var bob = await CreateUserAsync(client); + var chat = await CreateChatAsync(client, alice, bob); + for (var i = 0; i < messages; i++) + { + Assert.Equal(HttpStatusCode.Created, (await SendMessageAsync(client, alice, chat, $"m{i}")).StatusCode); + } + + return (alice, bob, chat); + } + + [Fact] + public async Task SecondRead_IsServedFromCache_WithFewerSqlQueries_AndIdenticalBody() + { + using var client = fixture.CreateClient(); + var (_, bob, chat) = await ChatWithMessagesAsync(client, 3); + + var first = await GetPageAsync(client, bob, chat); + var second = await GetPageAsync(client, bob, chat); + + Assert.Equal("miss", Header(first, "X-Cache")); + Assert.Equal("hit", Header(second, "X-Cache")); + // miss: сессия + версия/доступ + страница; hit: сессия + версия/доступ. + Assert.Equal("3", Header(first, "X-Db-Queries")); + Assert.Equal("2", Header(second, "X-Db-Queries")); + Assert.Equal(await first.Content.ReadAsStringAsync(), await second.Content.ReadAsStringAsync()); + } + + [Fact] + public async Task ReadAfterWrite_NeverReturnsStaleCachedPage() + { + using var client = fixture.CreateClient(); + var (alice, bob, chat) = await ChatWithMessagesAsync(client, 2); + await GetPageAsync(client, bob, chat); // прогрели кэш + Assert.Equal("hit", Header(await GetPageAsync(client, bob, chat), "X-Cache")); + + for (var i = 0; i < 20; i++) + { + var sent = await SendMessageAsync(client, alice, chat, $"new {i}"); + var id = (await ReadJsonAsync(sent)).GetProperty("id").GetGuid(); + + // Сразу после подтверждённой записи (201) следующее чтение обязано содержать новое сообщение. + var ids = await ReadAllMessagesAsync(client, chat, bob, 100); + Assert.Contains(id, ids); + Assert.Equal(3 + i, ids.Count); + } + } + + [Fact] + public async Task FlushedCache_DoesNotChangeResults() + { + using var client = fixture.CreateClient(); + var (_, bob, chat) = await ChatWithMessagesAsync(client, 5); + var before = await ReadAllMessagesAsync(client, chat, bob, 2); + Assert.Equal("hit", Header(await GetPageAsync(client, bob, chat, 2), "X-Cache")); + + await fixture.FlushCacheAsync(); + + var response = await GetPageAsync(client, bob, chat, 2); + Assert.Equal("miss", Header(response, "X-Cache")); + Assert.Equal(before, await ReadAllMessagesAsync(client, chat, bob, 2)); + } + + [Fact] + public async Task CachedPage_IsNotVisibleToNonMember() + { + using var client = fixture.CreateClient(); + var (_, bob, chat) = await ChatWithMessagesAsync(client, 2); + var eve = await CreateUserAsync(client); + await GetPageAsync(client, bob, chat); + Assert.Equal("hit", Header(await GetPageAsync(client, bob, chat), "X-Cache")); + + var response = await GetPageAsync(client, eve, chat); + + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); // доступ проверяется до обращения к кэшу + Assert.DoesNotContain("m0", await response.Content.ReadAsStringAsync()); + } + + [Fact] + public async Task PagesWithDifferentLimitsAndCursors_AreCachedSeparately() + { + using var client = fixture.CreateClient(); + var (_, bob, chat) = await ChatWithMessagesAsync(client, 9); + + var firstPass = await ReadAllMessagesAsync(client, chat, bob, 4); + var secondPass = await ReadAllMessagesAsync(client, chat, bob, 4); // все страницы уже в кэше + var otherLimit = await ReadAllMessagesAsync(client, chat, bob, 3); + + Assert.Equal(9, firstPass.Count); + Assert.Equal(firstPass, secondPass); + Assert.Equal(firstPass, otherLimit); + } + + [Fact] + public async Task UnavailableCache_IsBypassed_AndRequestsStillSucceed() + { + using var client = fixture.CreateClient(); + var (_, bob, chat) = await ChatWithMessagesAsync(client, 3); + var expected = await ReadAllMessagesAsync(client, chat, bob, 100); + + // Второй экземпляр приложения, у которого кэш указывает на закрытый порт. + await using var broken = fixture.WithWebHostBuilder(b => b.UseSetting("CACHE_CONNECTION", "127.0.0.1:1")); + using var brokenClient = broken.CreateClient(); + + for (var i = 0; i < 3; i++) + { + var response = await GetPageAsync(brokenClient, bob, chat); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("bypass", Header(response, "X-Cache")); + } + + Assert.Equal(expected, await ReadAllMessagesAsync(brokenClient, chat, bob, 100)); + // Запись тоже не зависит от кэша. + Assert.Equal(HttpStatusCode.Created, (await SendMessageAsync(brokenClient, bob, chat, "при отказе кэша")).StatusCode); + } + + [Fact] + public async Task UnavailableCache_DoesNotTrustAnonymousRequests() + { + await using var broken = fixture.WithWebHostBuilder(b => b.UseSetting("CACHE_CONNECTION", "127.0.0.1:1")); + using var client = broken.CreateClient(); + + var response = await client.GetAsync($"/api/v1/chats/{Guid.NewGuid()}/messages"); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } +} diff --git a/scr/Messenger.Api.Tests/ConcurencyTests.cs b/scr/Messenger.Api.Tests/ConcurencyTests.cs new file mode 100644 index 00000000..772273e2 --- /dev/null +++ b/scr/Messenger.Api.Tests/ConcurencyTests.cs @@ -0,0 +1,79 @@ +using System.Net; +using static Messenger.Api.Tests.ApiHelpers; + +namespace Messenger.Api.Tests; + +[Collection("api")] +public class ConcurencyTests(ApiFixture fixture) +{ + [Fact] + public async Task Create100MessagesBy10DifferentUsers_Concurrent() + { + using var client = fixture.CreateClient(); + var users = new List(); + for (var i = 0; i < 10; i++) + { + users.Add(await CreateUserAsync(client)); + } + + var chat = await CreateChatAsync(client, users[0], users.Skip(1).ToArray()); + + var messageTasks = Enumerable.Range(0, 100) + .Select(i => SendMessageAsync(client, users[i % 10], chat, $"Message {i + 1} from {users[i % 10].Username}")) + .ToList(); + + foreach (var response in await Task.WhenAll(messageTasks)) + { + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + } + + var messages = await ReadAllMessagesAsync(client, chat, users[0], 7); + + Assert.Equal(100, messages.Count); + Assert.Equal(100, messages.Distinct().Count()); + } + + [Fact] + public async Task RegisterSameUsernameConcurrently_ExactlyOneSucceeds_NoServerErrors() + { + // Проверяется гарантия уникального индекса, а не скорость железа: очередь хеширования делаем практически + // неограниченной по времени (по умолчанию лишние запросы получают 503, см. следующий тест). + await using var app = fixture.WithWebHostBuilder(b => b.UseSetting("PASSWORD_HASH_QUEUE_TIMEOUT_SECONDS", "120")); + using var client = app.CreateClient(); + var username = "race" + Guid.NewGuid().ToString("N")[..10]; + + var attempts = Enumerable.Range(0, 20).Select(_ => client.PostAsync("/api/v1/users", + Json($$"""{"username":"{{username}}","display_name":"Гонка","password":"{{DefaultPassword}}"}"""))); + var statuses = (await Task.WhenAll(attempts)).Select(r => r.StatusCode).ToList(); + + Assert.Single(statuses, HttpStatusCode.Created); + Assert.Equal(19, statuses.Count(s => s == HttpStatusCode.Conflict)); + + await using var db = await fixture.OpenConnectionAsync(); + await using var count = new Npgsql.NpgsqlCommand("select count(*) from users where username = @u", db); + count.Parameters.AddWithValue("u", username); + Assert.Equal(1L, await count.ExecuteScalarAsync()); + } + + [Fact] + public async Task RegistrationBurstBeyondHashingCapacity_GetsBoundedUnavailable_NotServerError() + { + // Один слот Argon2 и ожидание 50 мс: пачка регистраций разных пользователей упирается в лимит. + // Лишние запросы получают 503 unavailable (а не 500 и не зависание), принятые — 201. + await using var app = fixture.WithWebHostBuilder(b => b + .UseSetting("PASSWORD_HASH_CONCURRENCY", "1") + .UseSetting("PASSWORD_HASH_QUEUE_TIMEOUT_SECONDS", "0.05")); + using var client = app.CreateClient(); + var prefix = "burst" + Guid.NewGuid().ToString("N")[..6]; + + var responses = await Task.WhenAll(Enumerable.Range(0, 12).Select(i => client.PostAsync("/api/v1/users", + Json($$"""{"username":"{{prefix}}_{{i}}","display_name":"Пачка","password":"{{DefaultPassword}}"}""")))); + var statuses = responses.Select(r => r.StatusCode).ToList(); + + Assert.All(statuses, s => Assert.True(s is HttpStatusCode.Created or HttpStatusCode.ServiceUnavailable, $"неожиданный статус {s}")); + Assert.Contains(HttpStatusCode.Created, statuses); + Assert.Contains(HttpStatusCode.ServiceUnavailable, statuses); + var rejected = responses.First(r => r.StatusCode == HttpStatusCode.ServiceUnavailable); + Assert.Equal("unavailable", await ErrorCodeAsync(rejected)); + } +} diff --git a/scr/Messenger.Api.Tests/DependencyFailureTests.cs b/scr/Messenger.Api.Tests/DependencyFailureTests.cs new file mode 100644 index 00000000..b1338c25 --- /dev/null +++ b/scr/Messenger.Api.Tests/DependencyFailureTests.cs @@ -0,0 +1,192 @@ +using System.Diagnostics; +using System.Net; +using System.Net.Sockets; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Testcontainers.PostgreSql; +using static Messenger.Api.Tests.ApiHelpers; + +namespace Messenger.Api.Tests; + +[Collection("api")] +public class DependencyFailureTests(ApiFixture fixture) +{ + private static int FreePort() + { + using var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + return ((IPEndPoint)listener.LocalEndpoint).Port; + } + + [Fact] + public async Task DatabaseDown_Returns503_NeverTrustsAnonymous_AndRecovers() + { + // Отдельный контейнер БД, который тест останавливает и запускает снова на том же порту. + var port = FreePort(); + await using var pg = new PostgreSqlBuilder().WithImage(ApiFixture.PostgresImage).WithPortBinding(port, 5432).Build(); + await pg.StartAsync(); + var file = ApiFixture.WriteConnectionFile(pg.GetConnectionString()); + try + { + await using var app = fixture.WithWebHostBuilder(b => b + .UseSetting("DATABASE_URL_FILE", file) + .UseSetting("DB_CONNECT_TIMEOUT_SECONDS", "2")); + using var client = app.CreateClient(); + var user = await CreateUserAsync(client); + using (var ok = Request(HttpMethod.Get, "/api/v1/users/me", user)) + { + Assert.Equal(HttpStatusCode.OK, (await client.SendAsync(ok)).StatusCode); + } + + await pg.StopAsync(); + + // Аутентифицированный запрос: ограниченная ошибка 503 без внутренних деталей. + using var down = Request(HttpMethod.Get, "/api/v1/users/me", user); + var downResponse = await client.SendAsync(down); + Assert.Equal(HttpStatusCode.ServiceUnavailable, downResponse.StatusCode); + Assert.Equal("unavailable", await ErrorCodeAsync(downResponse)); + var body = await downResponse.Content.ReadAsStringAsync(); + Assert.DoesNotContain("Npgsql", body); + Assert.DoesNotContain("Host=", body); + Assert.True(downResponse.Headers.Contains("X-Request-Id")); + + // Анонимный запрос не становится доверенным: без токена по-прежнему 401, а не 200/503 «как гость». + Assert.Equal(HttpStatusCode.Unauthorized, (await client.GetAsync("/api/v1/chats")).StatusCode); + // Токен, который нельзя проверить, не принимается. + Assert.Equal(HttpStatusCode.ServiceUnavailable, + (await LoginAsync(client, user.Username, user.Password)).StatusCode); + // Готовность отражает отказ, живость — нет. + Assert.Equal(HttpStatusCode.ServiceUnavailable, (await client.GetAsync("/health/ready")).StatusCode); + Assert.Equal(HttpStatusCode.OK, (await client.GetAsync("/health/live")).StatusCode); + + // Восстановление: после запуска БД тот же токен снова работает (данные не потеряны), без перезапуска API. + await pg.StartAsync(); + var recovered = false; + var started = Stopwatch.StartNew(); + while (started.Elapsed < TimeSpan.FromSeconds(30) && !recovered) + { + using var retry = Request(HttpMethod.Get, "/api/v1/users/me", user); + recovered = (await client.SendAsync(retry)).StatusCode == HttpStatusCode.OK; + if (!recovered) + { + await Task.Delay(500); + } + } + + Assert.True(recovered, "API не восстановился после возврата PostgreSQL"); + } + finally + { + File.Delete(file); + } + } + + [Fact] + public async Task ExhaustedConnectionPool_ReturnsBoundedError() + { + using var setup = fixture.CreateClient(); + var user = await CreateUserAsync(setup); + + // Пул из одного соединения и короткое ожидание: пока тест держит единственное соединение, запросы не зависают. + await using var app = fixture.WithWebHostBuilder(b => b + .UseSetting("DB_MAX_POOL_SIZE", "1") + .UseSetting("DB_CONNECT_TIMEOUT_SECONDS", "1")); + using var client = app.CreateClient(); + + using var scope = app.Services.CreateScope(); + var held = scope.ServiceProvider.GetRequiredService(); + await held.Database.OpenConnectionAsync(); + try + { + var started = Stopwatch.StartNew(); + using var request = Request(HttpMethod.Get, "/api/v1/users/me", user); + var response = await client.SendAsync(request); + started.Stop(); + + Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode); + Assert.True(started.Elapsed < TimeSpan.FromSeconds(6), $"ответ занял {started.Elapsed}"); + } + finally + { + await held.Database.CloseConnectionAsync(); + } + + // После освобождения соединения сервис работает. + using var after = Request(HttpMethod.Get, "/api/v1/users/me", user); + Assert.Equal(HttpStatusCode.OK, (await client.SendAsync(after)).StatusCode); + } + + [Fact] + public async Task FailedMessageInsert_RollsBackVersionAndTimestamp() + { + using var client = fixture.CreateClient(); + var alice = await CreateUserAsync(client); + var chat = await CreateChatAsync(client, alice); + Assert.Equal(HttpStatusCode.Created, (await SendMessageAsync(client, alice, chat, "до сбоя")).StatusCode); + + var marker = "boom-" + Guid.NewGuid().ToString("N"); + var suffix = Guid.NewGuid().ToString("N")[..8]; + // Сбой «после UPDATE чата, во время INSERT сообщения»: триггер БД отклоняет сообщение с маркером. + await fixture.ExecuteAsync($$""" + CREATE FUNCTION fail_{{suffix}}() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN IF NEW.text = '{{marker}}' THEN RAISE EXCEPTION 'injected failure'; END IF; RETURN NEW; END $$; + CREATE TRIGGER tr_{{suffix}} BEFORE INSERT ON messages FOR EACH ROW EXECUTE FUNCTION fail_{{suffix}}(); + """); + try + { + var versionBefore = await fixture.ScalarAsync("select history_version from chats where id = @c", ("c", chat)); + var lastBefore = await fixture.ScalarAsync("select last_message_at from chats where id = @c", ("c", chat)); + + var failed = await SendMessageAsync(client, alice, chat, marker); + + Assert.Equal(HttpStatusCode.InternalServerError, failed.StatusCode); + var body = await failed.Content.ReadAsStringAsync(); + Assert.Contains("internal_error", body); + Assert.DoesNotContain("injected", body); // внутренние детали не раскрываются + Assert.Equal(versionBefore, await fixture.ScalarAsync("select history_version from chats where id = @c", ("c", chat))); + Assert.Equal(lastBefore, await fixture.ScalarAsync("select last_message_at from chats where id = @c", ("c", chat))); + Assert.Equal(1L, await fixture.ScalarAsync("select count(*) from messages where chat_id = @c", ("c", chat))); + + // Блокировка строки чата снята, следующая запись проходит и версия растёт ровно на 1. + Assert.Equal(HttpStatusCode.Created, (await SendMessageAsync(client, alice, chat, "после сбоя")).StatusCode); + Assert.Equal(versionBefore + 1, await fixture.ScalarAsync("select history_version from chats where id = @c", ("c", chat))); + } + finally + { + await fixture.ExecuteAsync($"DROP TRIGGER tr_{suffix} ON messages; DROP FUNCTION fail_{suffix}();"); + } + } + + [Fact] + public async Task FailedChatMemberInsert_RollsBackWholeChat() + { + using var client = fixture.CreateClient(); + var alice = await CreateUserAsync(client); + var bob = await CreateUserAsync(client); + var suffix = Guid.NewGuid().ToString("N")[..8]; + var title = "rollback-" + suffix; + + // Сбой при добавлении второго участника, уже после вставки строки чата и первого участника. + await fixture.ExecuteAsync($$""" + CREATE FUNCTION fail_{{suffix}}() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN IF NEW.user_id = '{{bob.Id}}' THEN RAISE EXCEPTION 'injected failure'; END IF; RETURN NEW; END $$; + CREATE TRIGGER tr_{{suffix}} BEFORE INSERT ON chat_members FOR EACH ROW EXECUTE FUNCTION fail_{{suffix}}(); + """); + try + { + using var request = Request(HttpMethod.Post, "/api/v1/chats", alice, + Json($$"""{"title":"{{title}}","member_ids":["{{alice.Id}}","{{bob.Id}}"]}""")); + var response = await client.SendAsync(request); + + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + Assert.Equal(0L, await fixture.ScalarAsync("select count(*) from chats where title = @t", ("t", title))); + Assert.Equal(0L, await fixture.ScalarAsync( + "select count(*) from chat_members where user_id in (@a, @b) ", ("a", alice.Id), ("b", bob.Id))); + } + finally + { + await fixture.ExecuteAsync($"DROP TRIGGER tr_{suffix} ON chat_members; DROP FUNCTION fail_{suffix}();"); + } + } +} diff --git a/scr/Messenger.Api.Tests/HealthTests.cs b/scr/Messenger.Api.Tests/HealthTests.cs new file mode 100644 index 00000000..dc46951e --- /dev/null +++ b/scr/Messenger.Api.Tests/HealthTests.cs @@ -0,0 +1,28 @@ +using System.Net; + +namespace Messenger.Api.Tests; + +[Collection("api")] +public class HealthTests(ApiFixture fixture) +{ + [Fact] + public async Task Live_ReturnsOk() + { + using var client = fixture.CreateClient(); + + var response = await client.GetAsync("/health/live"); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact] + public async Task Ready_ReturnsOkWhenDatabaseIsAvailable() + { + using var client = fixture.CreateClient(); + + var response = await client.GetAsync("/health/ready"); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.True(response.Headers.Contains("X-Request-Id")); + } +} diff --git a/scr/Messenger.Api.Tests/IdempotencyTests.cs b/scr/Messenger.Api.Tests/IdempotencyTests.cs new file mode 100644 index 00000000..1e28cc84 --- /dev/null +++ b/scr/Messenger.Api.Tests/IdempotencyTests.cs @@ -0,0 +1,261 @@ +using System.Net; +using static Messenger.Api.Tests.ApiHelpers; + +namespace Messenger.Api.Tests; + +// lab3: общая идемпотентность отправки сообщения. «Разные реплики» в тесте моделируются разными экземплярами приложения +// (fixture.WithWebHostBuilder) с общей PostgreSQL — ровно так же, как в Compose работают реплики за балансировщиком. +[Collection("api")] +public class IdempotencyTests(ApiFixture fixture) +{ + private static string NewKey() => Guid.NewGuid().ToString("N"); + + private static async Task CountMessagesAsync(HttpClient client, Guid chat, TestUser user) => + (await ReadAllMessagesAsync(client, chat, user, 100)).Count; + + [Fact] + public async Task Replay_ReturnsSameCodeAndSameMessage_WithoutDuplicate() + { + using var client = fixture.CreateClient(); + var alice = await CreateUserAsync(client); + var chat = await CreateChatAsync(client, alice); + var key = NewKey(); + + var first = await SendMessageAsync(client, alice, chat, "привет", key); + var second = await SendMessageAsync(client, alice, chat, "привет", key); + + Assert.Equal(HttpStatusCode.Created, first.StatusCode); + Assert.Equal(HttpStatusCode.Created, second.StatusCode); + Assert.Equal((await ReadJsonAsync(first)).ToString(), (await ReadJsonAsync(second)).ToString()); + Assert.Equal(1, await CountMessagesAsync(client, chat, alice)); + } + + [Fact] + public async Task SameKeyDifferentBody_Conflict_AndOriginalIsKept() + { + using var client = fixture.CreateClient(); + var alice = await CreateUserAsync(client); + var chat = await CreateChatAsync(client, alice); + var key = NewKey(); + + await SendMessageAsync(client, alice, chat, "первое", key); + var other = await SendMessageAsync(client, alice, chat, "второе", key); + + Assert.Equal(HttpStatusCode.Conflict, other.StatusCode); + Assert.Equal("conflict", await ErrorCodeAsync(other)); + Assert.Equal(1, await CountMessagesAsync(client, chat, alice)); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("has space")] + [InlineData("кириллица")] + public async Task MissingOrInvalidKey_BadRequest(string? key) + { + using var client = fixture.CreateClient(); + var alice = await CreateUserAsync(client); + var chat = await CreateChatAsync(client, alice); + + using var request = Request(HttpMethod.Post, $"/api/v1/chats/{chat}/messages", alice, + Json("""{"text":"x"}""")); + if (key is not null) + { + request.Headers.TryAddWithoutValidation("Idempotency-Key", key); + } + + var response = await client.SendAsync(request); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Equal(0, await CountMessagesAsync(client, chat, alice)); + } + + [Fact] + public async Task KeyTooLong_BadRequest_ButMaxLengthAccepted() + { + using var client = fixture.CreateClient(); + var alice = await CreateUserAsync(client); + var chat = await CreateChatAsync(client, alice); + + var tooLong = await SendMessageAsync(client, alice, chat, "x", new string('a', 129)); + var maxLength = await SendMessageAsync(client, alice, chat, "x", new string('a', 128)); + + Assert.Equal(HttpStatusCode.BadRequest, tooLong.StatusCode); + Assert.Equal(HttpStatusCode.Created, maxLength.StatusCode); + } + + [Fact] + public async Task SameKeyIsIndependent_ForDifferentUsersAndDifferentChats() + { + using var client = fixture.CreateClient(); + var alice = await CreateUserAsync(client); + var bob = await CreateUserAsync(client); + var chat1 = await CreateChatAsync(client, alice, bob); + var chat2 = await CreateChatAsync(client, alice, bob); + var key = NewKey(); + + var statuses = new[] + { + (await SendMessageAsync(client, alice, chat1, "a1", key)).StatusCode, + (await SendMessageAsync(client, bob, chat1, "b1", key)).StatusCode, + (await SendMessageAsync(client, alice, chat2, "a2", key)).StatusCode, + }; + + Assert.All(statuses, s => Assert.Equal(HttpStatusCode.Created, s)); + Assert.Equal(2, await CountMessagesAsync(client, chat1, alice)); + Assert.Equal(1, await CountMessagesAsync(client, chat2, alice)); + } + + [Fact] + public async Task Replay_StillRequiresValidSessionAndAccess() + { + using var client = fixture.CreateClient(); + var alice = await CreateUserAsync(client); + var eve = await CreateUserAsync(client); + var chat = await CreateChatAsync(client, alice); + var key = NewKey(); + await SendMessageAsync(client, alice, chat, "секрет", key); + + // Посторонний не может «прочитать» чужой результат по ключу; без токена — 401. + var asEve = await SendMessageAsync(client, eve, chat, "секрет", key); + using var anonymous = Request(HttpMethod.Post, $"/api/v1/chats/{chat}/messages", null, Json("""{"text":"секрет"}""")); + anonymous.Headers.Add("Idempotency-Key", key); + var noToken = await client.SendAsync(anonymous); + + Assert.Equal(HttpStatusCode.NotFound, asEve.StatusCode); + Assert.Equal(HttpStatusCode.Unauthorized, noToken.StatusCode); + } + + [Fact] + public async Task ConcurrentReplays_OnOneInstance_CreateExactlyOneMessage() + { + using var client = fixture.CreateClient(); + var alice = await CreateUserAsync(client); + var chat = await CreateChatAsync(client, alice); + var key = NewKey(); + + var responses = await Task.WhenAll(Enumerable.Range(0, 30) + .Select(_ => Task.Run(() => SendMessageAsync(client, alice, chat, "гонка", key)))); + + Assert.All(responses, r => Assert.Equal(HttpStatusCode.Created, r.StatusCode)); + var ids = await Task.WhenAll(responses.Select(async r => (await ReadJsonAsync(r)).GetProperty("id").GetGuid())); + Assert.Single(ids.Distinct()); + Assert.Equal(1, await CountMessagesAsync(client, chat, alice)); + } + + [Fact] + public async Task ConcurrentReplays_ThroughDifferentInstances_CreateExactlyOneMessage() + { + // Три независимых экземпляра приложения (как три реплики) с общей PostgreSQL. + await using var replicaB = fixture.WithWebHostBuilder(b => b.UseSetting("INSTANCE_ID", "replica-b")); + await using var replicaC = fixture.WithWebHostBuilder(b => b.UseSetting("INSTANCE_ID", "replica-c")); + using var a = fixture.CreateClient(); + using var b = replicaB.CreateClient(); + using var c = replicaC.CreateClient(); + + var alice = await CreateUserAsync(a); // сессия создана на A и действует на B и C: сессии общие + var chat = await CreateChatAsync(a, alice); + var clients = new[] { a, b, c }; + + for (var round = 0; round < 5; round++) + { + var key = NewKey(); + var responses = await Task.WhenAll(Enumerable.Range(0, 30) + .Select(i => Task.Run(() => SendMessageAsync(clients[i % 3], alice, chat, $"гонка {round}", key)))); + + Assert.All(responses, r => Assert.Equal(HttpStatusCode.Created, r.StatusCode)); + var ids = await Task.WhenAll(responses.Select(async r => (await ReadJsonAsync(r)).GetProperty("id").GetGuid())); + Assert.Single(ids.Distinct()); + } + + Assert.Equal(5, await CountMessagesAsync(b, chat, alice)); + } + + [Fact] + public async Task ConcurrentSameKeyWithDifferentBodies_ExactlyOneWins_OthersConflict() + { + using var client = fixture.CreateClient(); + var alice = await CreateUserAsync(client); + var chat = await CreateChatAsync(client, alice); + var key = NewKey(); + + var responses = await Task.WhenAll(Enumerable.Range(0, 10) + .Select(i => Task.Run(() => SendMessageAsync(client, alice, chat, $"вариант {i}", key)))); + + var created = responses.Count(r => r.StatusCode == HttpStatusCode.Created); + var conflicts = responses.Count(r => r.StatusCode == HttpStatusCode.Conflict); + Assert.True(created >= 1 && created + conflicts == 10, $"created={created}, conflicts={conflicts}"); + Assert.Equal(1, await CountMessagesAsync(client, chat, alice)); + } + + [Fact] + public async Task FailedWrite_IsNotRemembered_AndCanBeRetriedWithSameKey() + { + using var client = fixture.CreateClient(); + var alice = await CreateUserAsync(client); + var chat = await CreateChatAsync(client, alice); + var key = NewKey(); + + // Принудительная ошибка БД при вставке сообщения: транзакция (вместе с ключом) откатывается. + var suffix = Guid.NewGuid().ToString("N")[..8]; + await fixture.ExecuteAsync($$""" + CREATE FUNCTION fail_idem_{{suffix}}() RETURNS trigger AS $$ BEGIN RAISE EXCEPTION 'forced failure' USING ERRCODE = '53000'; END $$ LANGUAGE plpgsql; + CREATE TRIGGER tr_idem_{{suffix}} BEFORE INSERT ON messages FOR EACH ROW WHEN (NEW.chat_id = '{{chat}}') EXECUTE FUNCTION fail_idem_{{suffix}}(); + """); + try + { + var failed = await SendMessageAsync(client, alice, chat, "повторимо", key); + Assert.True((int)failed.StatusCode >= 500, $"expected 5xx, got {(int)failed.StatusCode}"); + Assert.Equal(0L, await fixture.ScalarAsync("select count(*) from idempotency_keys where chat_id = @c", ("c", chat))); + } + finally + { + await fixture.ExecuteAsync($"DROP TRIGGER tr_idem_{suffix} ON messages; DROP FUNCTION fail_idem_{suffix}();"); + } + + var retried = await SendMessageAsync(client, alice, chat, "повторимо", key); + var again = await SendMessageAsync(client, alice, chat, "повторимо", key); + + Assert.Equal(HttpStatusCode.Created, retried.StatusCode); + Assert.Equal(HttpStatusCode.Created, again.StatusCode); + Assert.Equal(1, await CountMessagesAsync(client, chat, alice)); + } + + [Fact] + public async Task ExpiredKey_CanBeReused_AsNewMessage() + { + await using var shortTtl = fixture.WithWebHostBuilder(b => b.UseSetting("IDEMPOTENCY_TTL_SECONDS", "1")); + using var client = shortTtl.CreateClient(); + var alice = await CreateUserAsync(client); + var chat = await CreateChatAsync(client, alice); + var key = NewKey(); + + var first = await SendMessageAsync(client, alice, chat, "срок", key); + await Task.Delay(TimeSpan.FromMilliseconds(1500)); + var second = await SendMessageAsync(client, alice, chat, "срок", key); + + Assert.Equal(HttpStatusCode.Created, first.StatusCode); + Assert.Equal(HttpStatusCode.Created, second.StatusCode); + Assert.NotEqual( + (await ReadJsonAsync(first)).GetProperty("id").GetGuid(), + (await ReadJsonAsync(second)).GetProperty("id").GetGuid()); + } + + [Fact] + public async Task EveryResponse_HasInstanceId_IncludingErrorsAndHealth() + { + await using var replica = fixture.WithWebHostBuilder(b => b.UseSetting("INSTANCE_ID", "replica-x")); + using var client = replica.CreateClient(); + + var health = await client.GetAsync("/health/live"); + var ready = await client.GetAsync("/health/ready"); + var unauthorized = await client.GetAsync("/api/v1/users/me"); + var notFound = await client.GetAsync("/no/such/route"); + var badJson = await client.PostAsync("/api/v1/users", Json("{broken")); + + foreach (var response in new[] { health, ready, unauthorized, notFound, badJson }) + { + Assert.Equal("replica-x", Assert.Single(response.Headers.GetValues("X-Instance-Id"))); + } + } +} diff --git a/scr/Messenger.Api.Tests/Messenger.Api.Tests.csproj b/scr/Messenger.Api.Tests/Messenger.Api.Tests.csproj new file mode 100644 index 00000000..62302f8b --- /dev/null +++ b/scr/Messenger.Api.Tests/Messenger.Api.Tests.csproj @@ -0,0 +1,27 @@ + + + + net10.0 + enable + enable + false + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/scr/Messenger.Api.Tests/PasswordHasherTests.cs b/scr/Messenger.Api.Tests/PasswordHasherTests.cs new file mode 100644 index 00000000..a9ea0333 --- /dev/null +++ b/scr/Messenger.Api.Tests/PasswordHasherTests.cs @@ -0,0 +1,69 @@ +using Messenger.Api.Services; + +namespace Messenger.Api.Tests; + +public class PasswordHasherTests +{ + private readonly Argon2PasswordHasher _hasher = new(new PasswordHashingSettings(4, TimeSpan.FromSeconds(30))); + + [Fact] + public async Task Hash_IsArgon2idPhcString_WithoutPlaintext() + { + var hash = await _hasher.HashAsync("correct horse battery staple", CancellationToken.None); + + Assert.StartsWith("$argon2id$", hash); + Assert.DoesNotContain("correct horse", hash); + } + + [Fact] + public async Task Hash_UsesRandomSalt() + { + var a = await _hasher.HashAsync("same-password-123", CancellationToken.None); + var b = await _hasher.HashAsync("same-password-123", CancellationToken.None); + + Assert.NotEqual(a, b); + } + + [Theory] + [InlineData("correct horse battery staple")] + [InlineData("пароль-с-юникодом-и:двоеточием-12")] + public async Task Verify_AcceptsCorrect_RejectsWrong(string password) + { + var hash = await _hasher.HashAsync(password, CancellationToken.None); + + Assert.True(await _hasher.VerifyAsync(hash, password, CancellationToken.None)); + Assert.False(await _hasher.VerifyAsync(hash, password + "x", CancellationToken.None)); + } + + [Fact] + public async Task Verify_DoesNotTruncateLongPasswords() + { + // Это ограничение bcrypt (72 байта); Argon2id его не имеет. Пароли отличаются только хвостом. + var prefix = new string('я', 60); // 120 байт в UTF-8 + var hash = await _hasher.HashAsync(prefix + "A", CancellationToken.None); + + Assert.False(await _hasher.VerifyAsync(hash, prefix + "B", CancellationToken.None)); + } + + [Fact] + public async Task Hash_WhenAllSlotsAreBusy_FailsWithBusyException() + { + // Один слот и почти нулевое ожидание: параллельные вызовы не копят память, лишние получают исключение (→ 503). + var hasher = new Argon2PasswordHasher(new PasswordHashingSettings(1, TimeSpan.FromMilliseconds(20))); + + var attempts = await Task.WhenAll(Enumerable.Range(0, 6).Select(async _ => + { + try { await hasher.HashAsync("some-long-enough-password", CancellationToken.None); return true; } + catch (PasswordHasherBusyException) { return false; } + })); + + Assert.Contains(true, attempts); // кто-то получил слот + Assert.Contains(false, attempts); // остальные получили контролируемый отказ + } + + [Fact] + public async Task Verify_UnknownUser_ReturnsFalse() + { + Assert.False(await _hasher.VerifyAsync(null, "any-password-123", CancellationToken.None)); + } +} diff --git a/scr/Messenger.Api.Tests/ThumbnailTests.cs b/scr/Messenger.Api.Tests/ThumbnailTests.cs new file mode 100644 index 00000000..8b63df19 --- /dev/null +++ b/scr/Messenger.Api.Tests/ThumbnailTests.cs @@ -0,0 +1,74 @@ +using ImageMagick; +using Messenger.Api.Jobs; + +namespace Messenger.Api.Tests; + +public class ThumbnailTests +{ + [Theory] + [InlineData(321, 200, 256, 159)] + [InlineData(1, 800, 1, 256)] + [InlineData(7, 9, 7, 9)] + public void FitsWithoutUpscalingAndCompositesAlphaOntoWhite(int w, int h, int expectedW, int expectedH) + { + using var source = new MagickImage(MagickColors.Transparent, (uint)w, (uint)h); + using var input = new MemoryStream(source.ToByteArray(MagickFormat.Png)); + var thumbnail = ImageVariant.CreateAll(input, "image/png", 40000000, 1)[0]; + using var jpeg = new MagickImage(thumbnail.Bytes); + Assert.Equal(MagickFormat.Jpeg, jpeg.Format); + Assert.Equal((expectedW, expectedH), ((int)jpeg.Width, (int)jpeg.Height)); + using var pixels = jpeg.GetPixels(); + var color = pixels.GetPixel(0, 0).ToColor()!; + Assert.True(color.R >= 250 && color.G >= 250 && color.B >= 250); + } + + [Fact] + public void AppliesExifOrientationBeforeSizing() + { + using var source = new MagickImage(MagickColors.Red, 320, 200); + var profile = new ExifProfile(); + profile.SetValue(ExifTag.Orientation, (ushort)6); + source.SetProfile(profile); + source.Orientation = Orientation.RightTop; + using var input = new MemoryStream(source.ToByteArray(MagickFormat.Jpeg)); + var variants = ImageVariant.CreateAll(input, "image/jpeg", 40000000, 1); + var thumb = Assert.Single(variants, v => v.Name == "thumbnail"); + Assert.Equal((160, 256), (thumb.Width, thumb.Height)); + foreach (var variant in variants) + { + using var decoded = new MagickImage(variant.Bytes); + Assert.Null(decoded.GetExifProfile()); + } + } + + [Fact] + public void UsesCentralCropAndFitsLargeWebPWithin1280Pixels() + { + using var source = new MagickImage(MagickColors.Red, 1600, 800); + using var center = new MagickImage(MagickColors.Lime, 1000, 800); + source.Composite(center, Gravity.Center, CompositeOperator.Over); + using var input = new MemoryStream(source.ToByteArray(MagickFormat.Png)); + var variants = ImageVariant.CreateAll(input, "image/png", 40000000, 1); + + using var crop = new MagickImage(Assert.Single(variants, v => v.Name == "crop").Bytes); + Assert.Equal((128u, 128u), (crop.Width, crop.Height)); + using var pixels = crop.GetPixels(); + foreach (var x in new[] { 0, 127 }) + { + var color = pixels.GetPixel(x, 64).ToColor()!; + Assert.True(color.G >= 240 && color.R <= 15); + } + + using var optimized = new MagickImage(Assert.Single(variants, v => v.Name == "optimized").Bytes); + Assert.Equal(MagickFormat.WebP, optimized.Format); + Assert.Equal((1280u, 640u), (optimized.Width, optimized.Height)); + } + + [Fact] + public void RefusesAnImageOverThePixelLimit() + { + using var source = new MagickImage(MagickColors.Red, 11, 10); + using var input = new MemoryStream(source.ToByteArray(MagickFormat.Png)); + Assert.Throws(() => ImageVariant.CreateAll(input, "image/png", 100, 1)); + } +} diff --git a/scr/Messenger.Api.Tests/UploadCleanupTests.cs b/scr/Messenger.Api.Tests/UploadCleanupTests.cs new file mode 100644 index 00000000..25c7b07a --- /dev/null +++ b/scr/Messenger.Api.Tests/UploadCleanupTests.cs @@ -0,0 +1,220 @@ +using System.Net; +using Amazon.S3; +using Messenger.Api.Data; +using Messenger.Api.Jobs; +using Messenger.Api.Services; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Diagnostics; +using Microsoft.Extensions.DependencyInjection; +using static Messenger.Api.Tests.ApiHelpers; + +namespace Messenger.Api.Tests; + +[Collection("api")] +public class UploadCleanupTests(ApiFixture fixture) +{ + private static byte[] Png => File.ReadAllBytes(Path.Combine(FindRoot(), "tests/fixtures/sample.png")); + private static string FindRoot() + { + var dir = new DirectoryInfo(AppContext.BaseDirectory); + while (dir is not null && !File.Exists(Path.Combine(dir.FullName, "lab.json"))) dir = dir.Parent; + return dir?.FullName ?? throw new InvalidOperationException("Repository root missing"); + } + + private static async Task Upload(HttpClient client, TestUser user, Guid chat, string filename) + { + using var content = new ByteArrayContent(Png); + content.Headers.ContentType = new("image/png"); + using var request = Request(HttpMethod.Post, $"/api/v1/chats/{chat}/attachments?filename={filename}", user, content); + return await client.SendAsync(request); + } + + private sealed class MetadataFailure : SaveChangesInterceptor + { + public override ValueTask> SavingChangesAsync(DbContextEventData data, + InterceptionResult result, CancellationToken ct = default) + { + if (data.Context!.ChangeTracker.Entries().Any(e => e.State == EntityState.Added)) + throw new InvalidOperationException("injected metadata commit failure"); + return ValueTask.FromResult(result); + } + } + + private sealed class StorageDecorator(IAttachmentStorage inner) : IAttachmentStorage, IDisposable + { + public bool FailDelete { get; set; } + public Func? AfterPut { get; set; } + public Task CheckAsync(CancellationToken ct) => inner.CheckAsync(ct); + public async Task PutAsync(string key, Stream content, string mime, CancellationToken ct, bool createOnly = false) + { await inner.PutAsync(key, content, mime, ct, createOnly); if (AfterPut is not null) await AfterPut(key); } + public Task CopyToAsync(string key, Stream output, CancellationToken ct) => inner.CopyToAsync(key, output, ct); + public Task DeleteAsync(string key, CancellationToken ct) => FailDelete + ? throw new HttpRequestException("injected S3 outage") : inner.DeleteAsync(key, ct); + public void Dispose() => (inner as IDisposable)?.Dispose(); + } + + private async Task Seed(IServiceProvider services, bool expired = true) + { + using var scope = services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var id = Guid.NewGuid(); + var now = Timestamps.UtcNowMilliseconds(); + var intent = new UploadIntentEntity { Id = id, ObjectKey = $"staging/{id:N}", CreatedAt = now, + ExpiresAt = expired ? now.AddMinutes(-1) : now.AddMinutes(5), NextAttemptAt = expired ? now.AddMinutes(-1) : now.AddMinutes(5) }; + db.UploadIntents.Add(intent); + await db.SaveChangesAsync(); + await scope.ServiceProvider.GetRequiredService().PutAsync(intent.ObjectKey, + new MemoryStream(Png), "image/png", CancellationToken.None); + return intent; + } + + private static async Task AssertMissing(IServiceProvider services, string key) + { + var storage = services.GetRequiredService(); + var error = await Assert.ThrowsAnyAsync(() => storage.CopyToAsync(key, Stream.Null, CancellationToken.None)); + Assert.Equal(HttpStatusCode.NotFound, error.StatusCode); + } + + [Fact] + public async Task MetadataFailureAfterS3Put_SurvivesApiRecreation_AndIsCleaned() + { + Guid pendingId; + string key; + var filename = $"fault-{Guid.NewGuid():N}.png"; + await using (var broken = fixture.WithWebHostBuilder(b => b.ConfigureServices(services => + services.AddDbContext(options => options.AddInterceptors(new MetadataFailure()))))) + { + using var client = broken.CreateClient(); + var user = await CreateUserAsync(client); + var chat = await CreateChatAsync(client, user); + var response = await Upload(client, user, chat, filename); + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + using var scope = broken.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + Assert.False(await db.Attachments.AnyAsync(a => a.Filename == filename)); + var intent = await db.UploadIntents.OrderByDescending(i => i.CreatedAt).FirstAsync(); + pendingId = intent.Id; key = intent.ObjectKey; + using var output = new MemoryStream(); + await broken.Services.GetRequiredService().CopyToAsync(key, output, CancellationToken.None); + Assert.Equal(Png, output.ToArray()); + } + // Новый экземпляр приложения читает тот же устойчивый журнал. + await fixture.ExecuteAsync($"UPDATE upload_intents SET expires_at=now()-interval '1 minute', next_attempt_at=now()-interval '1 minute' WHERE id='{pendingId}'"); + await using var recovered = fixture.WithWebHostBuilder(_ => { }); + using var recoveredClient = recovered.CreateClient(); + var deadline = DateTime.UtcNow.AddSeconds(10); + while (await fixture.ScalarAsync("SELECT delete_count FROM upload_intents WHERE id=@id",("id",pendingId)) == 0 && DateTime.UtcNow < deadline) + await Task.Delay(50); + await AssertMissing(recovered.Services, key); + Assert.Equal(1L, await fixture.ScalarAsync("SELECT count(*) FROM upload_intents WHERE id=@id AND delete_count>0", ("id",pendingId))); + } + + [Fact] + public async Task FreshIntent_IsProtectedByGracePeriod() + { + using var client = fixture.CreateClient(); + var intent = await Seed(fixture.Services, expired: false); + await fixture.Services.GetRequiredService().RunOnceAsync(CancellationToken.None); + using var result = new MemoryStream(); + await fixture.Services.GetRequiredService().CopyToAsync(intent.ObjectKey, result, CancellationToken.None); + Assert.Equal(Png, result.ToArray()); + Assert.Equal(0, await fixture.ScalarAsync("SELECT delete_count FROM upload_intents WHERE id=@id",("id",intent.Id))); + } + + [Fact] + public async Task PublishedAttachment_IsNeverDeleted_EvenWithAnExpiredIntent() + { + using var client = fixture.CreateClient(); + var user = await CreateUserAsync(client); + var chat = await CreateChatAsync(client, user); + var response = await Upload(client, user, chat, "protected.png"); + Assert.Equal(HttpStatusCode.Accepted, response.StatusCode); + var id = (await ReadJsonAsync(response)).GetProperty("id").GetGuid(); + using (var worker = fixture.Services.CreateScope()) + { + var job = await worker.ServiceProvider.GetRequiredService().AttachmentJobs.SingleAsync(j => j.AttachmentId == id); + await worker.ServiceProvider.GetRequiredService().ProcessAsync(JobMessage.From(job), CancellationToken.None); + } + using var scope = fixture.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var attachment = await db.Attachments.SingleAsync(a => a.Id == id); + Assert.Equal("ready", attachment.Status); + var old = DateTimeOffset.UtcNow.AddMinutes(-1); + // У оригинала отдельная проверочная запись. После ready worker планирует уборку staging с ID вложения. + var staleIntentId = Guid.NewGuid(); + db.UploadIntents.Add(new() { Id = staleIntentId, ObjectKey = attachment.ObjectKey, CreatedAt = old, + ExpiresAt = old, NextAttemptAt = old }); + await db.SaveChangesAsync(); + await fixture.Services.GetRequiredService().RunOnceAsync(CancellationToken.None); + using var request = Request(HttpMethod.Get,$"/api/v1/attachments/{id}/content",user); + Assert.Equal(Png, await (await client.SendAsync(request)).Content.ReadAsByteArrayAsync()); + Assert.False(await db.UploadIntents.AsNoTracking().AnyAsync(i => i.Id == staleIntentId)); + } + + [Fact] + public async Task CleanupRetriesAfterS3Failure_AndDeletesALatePutAgain() + { + StorageDecorator? decorator = null; + await using var app = fixture.WithWebHostBuilder(b => b.ConfigureServices(services => + services.AddSingleton(sp => decorator = new(new S3AttachmentStorage(sp.GetRequiredService()))))); + using var client = app.CreateClient(); + var intent = await Seed(app.Services); + decorator!.FailDelete = true; + var failed = await app.Services.GetRequiredService().RunOnceAsync(CancellationToken.None); + Assert.True(failed.Failed >= 1); + Assert.Equal(0, await fixture.ScalarAsync("SELECT delete_count FROM upload_intents WHERE id=@id",("id",intent.Id))); + decorator.FailDelete = false; + await fixture.ExecuteAsync($"UPDATE upload_intents SET next_attempt_at=now()-interval '1 minute' WHERE id='{intent.Id}'"); + await app.Services.GetRequiredService().RunOnceAsync(CancellationToken.None); + await AssertMissing(app.Services,intent.ObjectKey); + // Имитация PUT, завершившегося с задержкой после первого DELETE. + await decorator.PutAsync(intent.ObjectKey,new MemoryStream(Png),"image/png",CancellationToken.None); + await fixture.ExecuteAsync($"UPDATE upload_intents SET next_attempt_at=now()-interval '1 minute' WHERE id='{intent.Id}'"); + await app.Services.GetRequiredService().RunOnceAsync(CancellationToken.None); + await AssertMissing(app.Services,intent.ObjectKey); + Assert.Equal(2, await fixture.ScalarAsync("SELECT delete_count FROM upload_intents WHERE id=@id",("id",intent.Id))); + } + + [Fact] + public async Task ExpiredUploadCannotPublish_AfterItsLeaseWasRevoked() + { + await using var app = fixture.WithWebHostBuilder(b => b.ConfigureServices(services => + services.AddSingleton(sp => new StorageDecorator(new S3AttachmentStorage(sp.GetRequiredService())) + { AfterPut = async key => + { + var id = Guid.ParseExact(key["staging/".Length..],"N"); + await fixture.ExecuteAsync($"UPDATE upload_intents SET expires_at=now()-interval '1 minute', next_attempt_at=now()-interval '1 minute' WHERE id='{id}'"); + } + }))); + using var client = app.CreateClient(); + var user = await CreateUserAsync(client); + var chat = await CreateChatAsync(client,user); + var name = $"expired-{Guid.NewGuid():N}.png"; + Assert.Equal(HttpStatusCode.ServiceUnavailable,(await Upload(client,user,chat,name)).StatusCode); + using var scope = app.Services.CreateScope(); + Assert.False(await scope.ServiceProvider.GetRequiredService().Attachments.AnyAsync(a=>a.Filename==name)); + await app.Services.GetRequiredService().RunOnceAsync(CancellationToken.None); + } + + [Fact] + public async Task ConcurrentCleaners_ClaimAnIntentOnce() + { + using var client = fixture.CreateClient(); + var intent = await Seed(fixture.Services); + var cleaner = fixture.Services.GetRequiredService(); + await Task.WhenAll(cleaner.RunOnceAsync(CancellationToken.None),cleaner.RunOnceAsync(CancellationToken.None)); + await AssertMissing(fixture.Services,intent.ObjectKey); + Assert.Equal(1,await fixture.ScalarAsync("SELECT delete_count FROM upload_intents WHERE id=@id",("id",intent.Id))); + } + + [Fact] + public async Task OldTombstone_RemainsSoALatePutCannotBeForgotten() + { + using var client = fixture.CreateClient(); + var intent = await Seed(fixture.Services); + await fixture.ExecuteAsync($"UPDATE upload_intents SET expires_at=now()-interval '2 days' WHERE id='{intent.Id}'"); + await fixture.Services.GetRequiredService().RunOnceAsync(CancellationToken.None); + await AssertMissing(fixture.Services,intent.ObjectKey); + Assert.Equal(1L,await fixture.ScalarAsync("SELECT count(*) FROM upload_intents WHERE id=@id AND delete_count>0",("id",intent.Id))); + } +} diff --git a/scr/Messenger.Api/Data/DesignTimeDbContextFactory.cs b/scr/Messenger.Api/Data/DesignTimeDbContextFactory.cs new file mode 100644 index 00000000..20cedd06 --- /dev/null +++ b/scr/Messenger.Api/Data/DesignTimeDbContextFactory.cs @@ -0,0 +1,20 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Design; + +namespace Messenger.Api.Data; + +// Используется только командами `dotnet ef`. Для генерации миграций подключение к БД не открывается; +// для `dotnet ef database update` строка берётся из MESSENGER_DESIGN_CONNECTION. +public sealed class DesignTimeDbContextFactory : IDesignTimeDbContextFactory +{ + public MessengerDbContext CreateDbContext(string[] args) + { + var connection = Environment.GetEnvironmentVariable("MESSENGER_DESIGN_CONNECTION") + ?? "Host=localhost;Database=messenger;Username=design;Password=design"; + var options = new DbContextOptionsBuilder() + .UseNpgsql(connection) + .UseSnakeCaseNamingConvention() + .Options; + return new MessengerDbContext(options); + } +} diff --git a/scr/Messenger.Api/Data/Entities.cs b/scr/Messenger.Api/Data/Entities.cs new file mode 100644 index 00000000..a81d4a4f --- /dev/null +++ b/scr/Messenger.Api/Data/Entities.cs @@ -0,0 +1,130 @@ +namespace Messenger.Api.Data; + +// Долговечное намерение записать S3 object. Создаётся ДО PUT, удаляется атомарно +// с публикацией Attachment. После аварии остаётся для фоновой очистки. +public sealed class UploadIntentEntity +{ + public Guid Id { get; set; } + public string ObjectKey { get; set; } = string.Empty; + public DateTimeOffset CreatedAt { get; set; } + public DateTimeOffset ExpiresAt { get; set; } + public DateTimeOffset NextAttemptAt { get; set; } + public int DeleteCount { get; set; } +} + +// Строки таблиц. API-модели (Messenger.Api.Models) остаются отдельными: в них нет password_hash и служебных полей. + +public sealed class UserEntity +{ + public Guid Id { get; set; } + public string Username { get; set; } = string.Empty; + public string DisplayName { get; set; } = string.Empty; + // Результат Argon2id (PHC-строка с солью и параметрами). Наружу не отдаётся никогда. + public string PasswordHash { get; set; } = string.Empty; + public DateTimeOffset CreatedAt { get; set; } +} + +public sealed class ChatEntity +{ + public Guid Id { get; set; } + public string Title { get; set; } = string.Empty; + public DateTimeOffset CreatedAt { get; set; } + + // Версия истории: растёт на 1 в той же транзакции, что и вставка сообщения (UPDATE ... RETURNING). + // Источник версии для ключей кэша; одновременно сериализует записи в один чат (см. DESIGN). + public long HistoryVersion { get; set; } + + // Время последнего сообщения. Обновляется тем же UPDATE, что и версия: следующее сообщение получает + // created_at строго больше этого значения, поэтому порядок (created_at, id) совпадает с порядком коммитов. + public DateTimeOffset? LastMessageAt { get; set; } +} + +public sealed class ChatMemberEntity +{ + public Guid ChatId { get; set; } + public Guid UserId { get; set; } +} + +public sealed class MessageEntity +{ + public Guid Id { get; set; } + public Guid ChatId { get; set; } + public Guid SenderId { get; set; } + public string Text { get; set; } = string.Empty; + public DateTimeOffset CreatedAt { get; set; } + public Guid[] AttachmentIds { get; set; } = []; +} + +public sealed class SessionEntity +{ + public Guid Id { get; set; } + // SHA-256 от токена. Сам токен в БД не хранится: утечка БД не даёт действующих Bearer-токенов. + public byte[] TokenHash { get; set; } = Array.Empty(); + public Guid UserId { get; set; } + public DateTimeOffset CreatedAt { get; set; } + public DateTimeOffset ExpiresAt { get; set; } + public DateTimeOffset? RevokedAt { get; set; } +} + +// Результат идемпотентной отправки сообщения. Область уникальности: пользователь + чат (метод и путь у эндпоинта один: +// POST /api/v1/chats/{chat_id}/messages) + ключ. Строка создаётся в той же транзакции, что и сообщение. +public sealed class IdempotencyKeyEntity +{ + public Guid UserId { get; set; } + public Guid ChatId { get; set; } + public string Key { get; set; } = string.Empty; + // SHA-256 от смысла запроса (см. IdempotencyKeys.RequestHash): другой хеш при том же ключе → 409. + public byte[] RequestHash { get; set; } = Array.Empty(); + public Guid MessageId { get; set; } + public DateTimeOffset CreatedAt { get; set; } + public DateTimeOffset ExpiresAt { get; set; } +} + +public sealed class AttachmentEntity +{ + public Guid Id { get; set; } + public Guid ChatId { get; set; } + public Guid OwnerId { get; set; } + public string Filename { get; set; } = string.Empty; + public string ObjectKey { get; set; } = string.Empty; + public string ContentType { get; set; } = string.Empty; + public long SizeBytes { get; set; } + public string ChecksumSha256 { get; set; } = string.Empty; + + public string Status { get; set; } = "queued"; + public string? ErrorCode { get; set; } + public int PipelineVersion { get; set; } = 1; + public DateTimeOffset CreatedAt { get; set; } + public DateTimeOffset? UpdatedAt { get; set; } + public List Variants { get; set; } = []; +} + +// The same row is the processing record and the transactional outbox until publication is confirmed. +public sealed class AttachmentJobEntity +{ + public Guid Id { get; set; } + public Guid AttachmentId { get; set; } + public AttachmentEntity Attachment { get; set; } = null!; + public string SourceKey { get; set; } = string.Empty; + public int PipelineVersion { get; set; } = 1; + public int Attempt { get; set; } = 1; + public int FirstAttempt { get; set; } = 1; + public DateTimeOffset? ReplayedAt { get; set; } + public DateTimeOffset CreatedAt { get; set; } + public DateTimeOffset NextAttemptAt { get; set; } + public DateTimeOffset? PublishedAt { get; set; } + public DateTimeOffset? LeaseUntil { get; set; } +} + +public sealed class AttachmentVariantEntity +{ + public Guid AttachmentId { get; set; } + public int PipelineVersion { get; set; } + public string Name { get; set; } = string.Empty; + public string ObjectKey { get; set; } = string.Empty; + public string ContentType { get; set; } = string.Empty; + public int Width { get; set; } + public int Height { get; set; } + public long SizeBytes { get; set; } + public string Sha256 { get; set; } = string.Empty; +} diff --git a/scr/Messenger.Api/Data/MessengerDbContext.cs b/scr/Messenger.Api/Data/MessengerDbContext.cs new file mode 100644 index 00000000..84ea27af --- /dev/null +++ b/scr/Messenger.Api/Data/MessengerDbContext.cs @@ -0,0 +1,181 @@ +using Microsoft.EntityFrameworkCore; + +namespace Messenger.Api.Data; + +public sealed class MessengerDbContext(DbContextOptions options) : DbContext(options) +{ + public DbSet Users => Set(); + public DbSet Chats => Set(); + public DbSet ChatMembers => Set(); + public DbSet Messages => Set(); + public DbSet Sessions => Set(); + public DbSet IdempotencyKeys => Set(); + public DbSet Attachments => Set(); + public DbSet UploadIntents => Set(); + public DbSet AttachmentJobs => Set(); + public DbSet AttachmentVariants => Set(); + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder.Entity(e => + { + e.ToTable("upload_intents"); + e.HasKey(x => x.Id); + e.Property(x => x.Id).ValueGeneratedNever(); + e.Property(x => x.ObjectKey).IsRequired(); + e.HasIndex(x => x.ObjectKey).IsUnique(); + e.HasIndex(x => new { x.NextAttemptAt, x.ExpiresAt }); + }); + // Идентификаторы создаёт приложение (Guid.CreateVersion7: монотонные, индексы вставляются «справа»). + // Время created_at тоже назначает приложение, а не DEFAULT now(): см. порядок операций отправки сообщения. + + modelBuilder.Entity(e => + { + e.ToTable("users", t => + { + t.HasCheckConstraint("ck_users_username_format", @"username ~ '^[a-z0-9_]{3,32}$'"); + t.HasCheckConstraint("ck_users_display_name_not_blank", @"display_name ~ '\S'"); + }); + e.HasKey(x => x.Id); + e.Property(x => x.Id).ValueGeneratedNever(); + e.Property(x => x.Username).HasMaxLength(32).IsRequired(); + e.Property(x => x.DisplayName).HasMaxLength(100).IsRequired(); // varchar(n) считает символы, не байты + e.Property(x => x.PasswordHash).IsRequired(); + e.Property(x => x.CreatedAt).IsRequired(); + e.HasIndex(x => x.Username).IsUnique().HasDatabaseName("ux_users_username"); + }); + + modelBuilder.Entity(e => + { + e.ToTable("chats", t => + { + t.HasCheckConstraint("ck_chats_title_not_blank", @"title ~ '\S'"); + t.HasCheckConstraint("ck_chats_history_version_nonneg", "history_version >= 0"); + }); + e.HasKey(x => x.Id); + e.Property(x => x.Id).ValueGeneratedNever(); + e.Property(x => x.Title).HasMaxLength(100).IsRequired(); + e.Property(x => x.CreatedAt).IsRequired(); + e.Property(x => x.HistoryVersion).HasDefaultValue(0L).IsRequired(); + // Список чатов: сортировка по (created_at, id) с keyset-курсором. + e.HasIndex(x => new { x.CreatedAt, x.Id }).HasDatabaseName("ix_chats_created_at_id"); + }); + + modelBuilder.Entity(e => + { + e.ToTable("chat_members"); + e.HasKey(x => new { x.ChatId, x.UserId }); // один пользователь не может быть в чате дважды + e.HasOne().WithMany().HasForeignKey(x => x.ChatId).OnDelete(DeleteBehavior.Cascade); + e.HasOne().WithMany().HasForeignKey(x => x.UserId).OnDelete(DeleteBehavior.Restrict); + // PK обслуживает «участники чата»; этот индекс — «чаты пользователя» и проверку доступа. + e.HasIndex(x => x.UserId).HasDatabaseName("ix_chat_members_user_id"); + }); + + modelBuilder.Entity(e => + { + e.ToTable("messages", t => + { + t.HasCheckConstraint("ck_messages_text_or_attachments", @"text ~ '\S' OR cardinality(attachment_ids) > 0"); + t.HasCheckConstraint("ck_messages_attachment_limit", "cardinality(attachment_ids) <= 10"); + }); + // До 10 ссылок: храним порядок без дополнительных запросов для каждой строки истории. + e.Property(x => x.AttachmentIds).HasColumnType("uuid[]").HasDefaultValueSql("'{}'::uuid[]").IsRequired(); + e.HasKey(x => x.Id); + e.Property(x => x.Id).ValueGeneratedNever(); + e.Property(x => x.Text).HasMaxLength(4000).IsRequired(); + e.Property(x => x.CreatedAt).IsRequired(); + // Составной FK: отправитель обязан быть участником именно этого чата. Он же гарантирует существование + // чата и пользователя, поэтому отдельные FK на chats/users не нужны. + e.HasOne().WithMany() + .HasForeignKey(x => new { x.ChatId, x.SenderId }) + .HasPrincipalKey(x => new { x.ChatId, x.UserId }) + .OnDelete(DeleteBehavior.Cascade); + // Страница истории: WHERE chat_id = @c AND (created_at, id) > (@t, @i) ORDER BY created_at, id LIMIT n. + e.HasIndex(x => new { x.ChatId, x.CreatedAt, x.Id }).HasDatabaseName("ix_messages_chat_history"); + }); + + modelBuilder.Entity(e => + { + e.ToTable("sessions", t => + { + t.HasCheckConstraint("ck_sessions_token_hash_len", "octet_length(token_hash) = 32"); + t.HasCheckConstraint("ck_sessions_expiry_after_creation", "expires_at > created_at"); + }); + e.HasKey(x => x.Id); + e.Property(x => x.Id).ValueGeneratedNever(); + e.Property(x => x.TokenHash).IsRequired(); + e.Property(x => x.CreatedAt).IsRequired(); + e.Property(x => x.ExpiresAt).IsRequired(); + e.HasOne().WithMany().HasForeignKey(x => x.UserId).OnDelete(DeleteBehavior.Cascade); + // Аутентификация каждого запроса: поиск по хешу токена. + e.HasIndex(x => x.TokenHash).IsUnique().HasDatabaseName("ux_sessions_token_hash"); + // Фоновая очистка истёкших сессий. + e.HasIndex(x => x.ExpiresAt).HasDatabaseName("ix_sessions_expires_at"); + }); + + modelBuilder.Entity(e => + { + e.ToTable("idempotency_keys", t => + { + t.HasCheckConstraint("ck_idempotency_keys_hash_len", "octet_length(request_hash) = 32"); + t.HasCheckConstraint("ck_idempotency_keys_expiry", "expires_at > created_at"); + }); + // PK = область уникальности. Именно его уникальный индекс заставляет конкурентные запросы с одним ключом + // ждать друг друга. FK на messages(id) (DEFERRABLE INITIALLY DEFERRED) добавлен в миграции вручную. + e.HasKey(x => new { x.UserId, x.ChatId, x.Key }); + e.Property(x => x.Key).HasMaxLength(128).IsRequired(); + e.Property(x => x.RequestHash).IsRequired(); + e.Property(x => x.CreatedAt).IsRequired(); + e.Property(x => x.ExpiresAt).IsRequired(); + // Очистка истёкших ключей. + e.HasIndex(x => x.ExpiresAt).HasDatabaseName("ix_idempotency_keys_expires_at"); + }); + + modelBuilder.Entity(e => + { + e.ToTable("attachment_jobs"); + e.HasKey(j => j.Id); + e.Property(j => j.Id).ValueGeneratedNever(); + e.Property(j => j.FirstAttempt).HasDefaultValue(1); + e.HasOne(j => j.Attachment).WithMany().HasForeignKey(j => j.AttachmentId); + e.HasIndex(j => new { j.AttachmentId, j.PipelineVersion }).IsUnique(); + e.HasIndex(j => j.NextAttemptAt).HasFilter("published_at IS NULL"); + e.HasIndex(j => j.LeaseUntil).HasFilter("lease_until IS NOT NULL"); + }); + + modelBuilder.Entity(e => + { + e.ToTable("attachment_variants"); + e.HasKey(v => new { v.AttachmentId, v.PipelineVersion, v.Name }); + e.HasOne().WithMany(a => a.Variants).HasForeignKey(v => v.AttachmentId); + e.HasIndex(v => v.ObjectKey).IsUnique(); + }); + + modelBuilder.Entity(e => + { + e.ToTable("attachments"); + e.HasKey(x => x.Id); + e.Property(x => x.Id).ValueGeneratedNever(); + + e.Property(x => x.Filename).HasMaxLength(255).IsRequired(); + e.Property(x => x.ObjectKey).IsRequired(); + e.Property(x => x.ContentType).HasMaxLength(100).IsRequired(); + e.Property(x => x.ChecksumSha256).HasMaxLength(64).IsRequired(); + e.Property(x => x.Status).HasMaxLength(20).IsRequired(); + e.Property(x => x.PipelineVersion).HasDefaultValue(1); + + e.HasIndex(x => x.ObjectKey).IsUnique(); + e.HasIndex(x => x.ChatId); + + e.HasOne() + .WithMany() + .HasForeignKey(x => x.ChatId) + .OnDelete(DeleteBehavior.Restrict); + + e.HasOne() + .WithMany() + .HasForeignKey(x => x.OwnerId) + .OnDelete(DeleteBehavior.Restrict); + }); + } +} diff --git a/scr/Messenger.Api/Data/Migrations/20261023140810_InitialSchema.Designer.cs b/scr/Messenger.Api/Data/Migrations/20261023140810_InitialSchema.Designer.cs new file mode 100644 index 00000000..cc15e205 --- /dev/null +++ b/scr/Messenger.Api/Data/Migrations/20261023140810_InitialSchema.Designer.cs @@ -0,0 +1,251 @@ +// +using System; +using Messenger.Api.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Messenger.Api.Data.Migrations +{ + [DbContext(typeof(MessengerDbContext))] + [Migration("20261023140810_InitialSchema")] + partial class InitialSchema + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.13") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Messenger.Api.Data.ChatEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("HistoryVersion") + .ValueGeneratedOnAdd() + .HasColumnType("bigint") + .HasDefaultValue(0L) + .HasColumnName("history_version"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("title"); + + b.HasKey("Id") + .HasName("pk_chats"); + + b.HasIndex("CreatedAt", "Id") + .HasDatabaseName("ix_chats_created_at_id"); + + b.ToTable("chats", null, t => + { + t.HasCheckConstraint("ck_chats_history_version_nonneg", "history_version >= 0"); + + t.HasCheckConstraint("ck_chats_title_not_blank", "title ~ '\\S'"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.ChatMemberEntity", b => + { + b.Property("ChatId") + .HasColumnType("uuid") + .HasColumnName("chat_id"); + + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.HasKey("ChatId", "UserId") + .HasName("pk_chat_members"); + + b.HasIndex("UserId") + .HasDatabaseName("ix_chat_members_user_id"); + + b.ToTable("chat_members", (string)null); + }); + + modelBuilder.Entity("Messenger.Api.Data.MessageEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("ChatId") + .HasColumnType("uuid") + .HasColumnName("chat_id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("SenderId") + .HasColumnType("uuid") + .HasColumnName("sender_id"); + + b.Property("Text") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("character varying(4000)") + .HasColumnName("text"); + + b.HasKey("Id") + .HasName("pk_messages"); + + b.HasIndex("ChatId", "SenderId") + .HasDatabaseName("ix_messages_chat_id_sender_id"); + + b.HasIndex("ChatId", "CreatedAt", "Id") + .HasDatabaseName("ix_messages_chat_history"); + + b.ToTable("messages", null, t => + { + t.HasCheckConstraint("ck_messages_text_not_blank", "text ~ '\\S'"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.SessionEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("expires_at"); + + b.Property("RevokedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("revoked_at"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("bytea") + .HasColumnName("token_hash"); + + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.HasKey("Id") + .HasName("pk_sessions"); + + b.HasIndex("ExpiresAt") + .HasDatabaseName("ix_sessions_expires_at"); + + b.HasIndex("TokenHash") + .IsUnique() + .HasDatabaseName("ux_sessions_token_hash"); + + b.HasIndex("UserId") + .HasDatabaseName("ix_sessions_user_id"); + + b.ToTable("sessions", null, t => + { + t.HasCheckConstraint("ck_sessions_expiry_after_creation", "expires_at > created_at"); + + t.HasCheckConstraint("ck_sessions_token_hash_len", "octet_length(token_hash) = 32"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.UserEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("display_name"); + + b.Property("PasswordHash") + .IsRequired() + .HasColumnType("text") + .HasColumnName("password_hash"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)") + .HasColumnName("username"); + + b.HasKey("Id") + .HasName("pk_users"); + + b.HasIndex("Username") + .IsUnique() + .HasDatabaseName("ux_users_username"); + + b.ToTable("users", null, t => + { + t.HasCheckConstraint("ck_users_display_name_not_blank", "display_name ~ '\\S'"); + + t.HasCheckConstraint("ck_users_username_format", "username ~ '^[a-z0-9_]{3,32}$'"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.ChatMemberEntity", b => + { + b.HasOne("Messenger.Api.Data.ChatEntity", null) + .WithMany() + .HasForeignKey("ChatId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_chat_members_chats_chat_id"); + + b.HasOne("Messenger.Api.Data.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_chat_members_users_user_id"); + }); + + modelBuilder.Entity("Messenger.Api.Data.MessageEntity", b => + { + b.HasOne("Messenger.Api.Data.ChatMemberEntity", null) + .WithMany() + .HasForeignKey("ChatId", "SenderId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_messages_chat_members_chat_id_sender_id"); + }); + + modelBuilder.Entity("Messenger.Api.Data.SessionEntity", b => + { + b.HasOne("Messenger.Api.Data.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_sessions_users_user_id"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/scr/Messenger.Api/Data/Migrations/20261023140810_InitialSchema.cs b/scr/Messenger.Api/Data/Migrations/20261023140810_InitialSchema.cs new file mode 100644 index 00000000..686e73e3 --- /dev/null +++ b/scr/Messenger.Api/Data/Migrations/20261023140810_InitialSchema.cs @@ -0,0 +1,179 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Messenger.Api.Data.Migrations +{ + /// + public partial class InitialSchema : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "chats", + columns: table => new + { + id = table.Column(type: "uuid", nullable: false), + title = table.Column(type: "character varying(100)", maxLength: 100, nullable: false), + created_at = table.Column(type: "timestamp with time zone", nullable: false), + history_version = table.Column(type: "bigint", nullable: false, defaultValue: 0L) + }, + constraints: table => + { + table.PrimaryKey("pk_chats", x => x.id); + table.CheckConstraint("ck_chats_history_version_nonneg", "history_version >= 0"); + table.CheckConstraint("ck_chats_title_not_blank", "title ~ '\\S'"); + }); + + migrationBuilder.CreateTable( + name: "users", + columns: table => new + { + id = table.Column(type: "uuid", nullable: false), + username = table.Column(type: "character varying(32)", maxLength: 32, nullable: false), + display_name = table.Column(type: "character varying(100)", maxLength: 100, nullable: false), + password_hash = table.Column(type: "text", nullable: false), + created_at = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("pk_users", x => x.id); + table.CheckConstraint("ck_users_display_name_not_blank", "display_name ~ '\\S'"); + table.CheckConstraint("ck_users_username_format", "username ~ '^[a-z0-9_]{3,32}$'"); + }); + + migrationBuilder.CreateTable( + name: "chat_members", + columns: table => new + { + chat_id = table.Column(type: "uuid", nullable: false), + user_id = table.Column(type: "uuid", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("pk_chat_members", x => new { x.chat_id, x.user_id }); + table.ForeignKey( + name: "fk_chat_members_chats_chat_id", + column: x => x.chat_id, + principalTable: "chats", + principalColumn: "id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "fk_chat_members_users_user_id", + column: x => x.user_id, + principalTable: "users", + principalColumn: "id", + onDelete: ReferentialAction.Restrict); + }); + + migrationBuilder.CreateTable( + name: "sessions", + columns: table => new + { + id = table.Column(type: "uuid", nullable: false), + token_hash = table.Column(type: "bytea", nullable: false), + user_id = table.Column(type: "uuid", nullable: false), + created_at = table.Column(type: "timestamp with time zone", nullable: false), + expires_at = table.Column(type: "timestamp with time zone", nullable: false), + revoked_at = table.Column(type: "timestamp with time zone", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("pk_sessions", x => x.id); + table.CheckConstraint("ck_sessions_expiry_after_creation", "expires_at > created_at"); + table.CheckConstraint("ck_sessions_token_hash_len", "octet_length(token_hash) = 32"); + table.ForeignKey( + name: "fk_sessions_users_user_id", + column: x => x.user_id, + principalTable: "users", + principalColumn: "id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "messages", + columns: table => new + { + id = table.Column(type: "uuid", nullable: false), + chat_id = table.Column(type: "uuid", nullable: false), + sender_id = table.Column(type: "uuid", nullable: false), + text = table.Column(type: "character varying(4000)", maxLength: 4000, nullable: false), + created_at = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("pk_messages", x => x.id); + table.CheckConstraint("ck_messages_text_not_blank", "text ~ '\\S'"); + table.ForeignKey( + name: "fk_messages_chat_members_chat_id_sender_id", + columns: x => new { x.chat_id, x.sender_id }, + principalTable: "chat_members", + principalColumns: new[] { "chat_id", "user_id" }, + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "ix_chat_members_user_id", + table: "chat_members", + column: "user_id"); + + migrationBuilder.CreateIndex( + name: "ix_chats_created_at_id", + table: "chats", + columns: new[] { "created_at", "id" }); + + migrationBuilder.CreateIndex( + name: "ix_messages_chat_history", + table: "messages", + columns: new[] { "chat_id", "created_at", "id" }); + + migrationBuilder.CreateIndex( + name: "ix_messages_chat_id_sender_id", + table: "messages", + columns: new[] { "chat_id", "sender_id" }); + + migrationBuilder.CreateIndex( + name: "ix_sessions_expires_at", + table: "sessions", + column: "expires_at"); + + migrationBuilder.CreateIndex( + name: "ix_sessions_user_id", + table: "sessions", + column: "user_id"); + + migrationBuilder.CreateIndex( + name: "ux_sessions_token_hash", + table: "sessions", + column: "token_hash", + unique: true); + + migrationBuilder.CreateIndex( + name: "ux_users_username", + table: "users", + column: "username", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "messages"); + + migrationBuilder.DropTable( + name: "sessions"); + + migrationBuilder.DropTable( + name: "chat_members"); + + migrationBuilder.DropTable( + name: "chats"); + + migrationBuilder.DropTable( + name: "users"); + } + } +} diff --git a/scr/Messenger.Api/Data/Migrations/20261023170730_AddChatLastMessageAt.Designer.cs b/scr/Messenger.Api/Data/Migrations/20261023170730_AddChatLastMessageAt.Designer.cs new file mode 100644 index 00000000..f96f9c43 --- /dev/null +++ b/scr/Messenger.Api/Data/Migrations/20261023170730_AddChatLastMessageAt.Designer.cs @@ -0,0 +1,255 @@ +// +using System; +using Messenger.Api.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Messenger.Api.Data.Migrations +{ + [DbContext(typeof(MessengerDbContext))] + [Migration("20261023170730_AddChatLastMessageAt")] + partial class AddChatLastMessageAt + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.13") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Messenger.Api.Data.ChatEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("HistoryVersion") + .ValueGeneratedOnAdd() + .HasColumnType("bigint") + .HasDefaultValue(0L) + .HasColumnName("history_version"); + + b.Property("LastMessageAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("last_message_at"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("title"); + + b.HasKey("Id") + .HasName("pk_chats"); + + b.HasIndex("CreatedAt", "Id") + .HasDatabaseName("ix_chats_created_at_id"); + + b.ToTable("chats", null, t => + { + t.HasCheckConstraint("ck_chats_history_version_nonneg", "history_version >= 0"); + + t.HasCheckConstraint("ck_chats_title_not_blank", "title ~ '\\S'"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.ChatMemberEntity", b => + { + b.Property("ChatId") + .HasColumnType("uuid") + .HasColumnName("chat_id"); + + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.HasKey("ChatId", "UserId") + .HasName("pk_chat_members"); + + b.HasIndex("UserId") + .HasDatabaseName("ix_chat_members_user_id"); + + b.ToTable("chat_members", (string)null); + }); + + modelBuilder.Entity("Messenger.Api.Data.MessageEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("ChatId") + .HasColumnType("uuid") + .HasColumnName("chat_id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("SenderId") + .HasColumnType("uuid") + .HasColumnName("sender_id"); + + b.Property("Text") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("character varying(4000)") + .HasColumnName("text"); + + b.HasKey("Id") + .HasName("pk_messages"); + + b.HasIndex("ChatId", "SenderId") + .HasDatabaseName("ix_messages_chat_id_sender_id"); + + b.HasIndex("ChatId", "CreatedAt", "Id") + .HasDatabaseName("ix_messages_chat_history"); + + b.ToTable("messages", null, t => + { + t.HasCheckConstraint("ck_messages_text_not_blank", "text ~ '\\S'"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.SessionEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("expires_at"); + + b.Property("RevokedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("revoked_at"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("bytea") + .HasColumnName("token_hash"); + + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.HasKey("Id") + .HasName("pk_sessions"); + + b.HasIndex("ExpiresAt") + .HasDatabaseName("ix_sessions_expires_at"); + + b.HasIndex("TokenHash") + .IsUnique() + .HasDatabaseName("ux_sessions_token_hash"); + + b.HasIndex("UserId") + .HasDatabaseName("ix_sessions_user_id"); + + b.ToTable("sessions", null, t => + { + t.HasCheckConstraint("ck_sessions_expiry_after_creation", "expires_at > created_at"); + + t.HasCheckConstraint("ck_sessions_token_hash_len", "octet_length(token_hash) = 32"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.UserEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("display_name"); + + b.Property("PasswordHash") + .IsRequired() + .HasColumnType("text") + .HasColumnName("password_hash"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)") + .HasColumnName("username"); + + b.HasKey("Id") + .HasName("pk_users"); + + b.HasIndex("Username") + .IsUnique() + .HasDatabaseName("ux_users_username"); + + b.ToTable("users", null, t => + { + t.HasCheckConstraint("ck_users_display_name_not_blank", "display_name ~ '\\S'"); + + t.HasCheckConstraint("ck_users_username_format", "username ~ '^[a-z0-9_]{3,32}$'"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.ChatMemberEntity", b => + { + b.HasOne("Messenger.Api.Data.ChatEntity", null) + .WithMany() + .HasForeignKey("ChatId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_chat_members_chats_chat_id"); + + b.HasOne("Messenger.Api.Data.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_chat_members_users_user_id"); + }); + + modelBuilder.Entity("Messenger.Api.Data.MessageEntity", b => + { + b.HasOne("Messenger.Api.Data.ChatMemberEntity", null) + .WithMany() + .HasForeignKey("ChatId", "SenderId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_messages_chat_members_chat_id_sender_id"); + }); + + modelBuilder.Entity("Messenger.Api.Data.SessionEntity", b => + { + b.HasOne("Messenger.Api.Data.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_sessions_users_user_id"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/scr/Messenger.Api/Data/Migrations/20261023170730_AddChatLastMessageAt.cs b/scr/Messenger.Api/Data/Migrations/20261023170730_AddChatLastMessageAt.cs new file mode 100644 index 00000000..82002c62 --- /dev/null +++ b/scr/Messenger.Api/Data/Migrations/20261023170730_AddChatLastMessageAt.cs @@ -0,0 +1,29 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Messenger.Api.Data.Migrations +{ + /// + public partial class AddChatLastMessageAt : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "last_message_at", + table: "chats", + type: "timestamp with time zone", + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "last_message_at", + table: "chats"); + } + } +} diff --git a/scr/Messenger.Api/Data/Migrations/20261106145724_AddIdempotencyKeys.Designer.cs b/scr/Messenger.Api/Data/Migrations/20261106145724_AddIdempotencyKeys.Designer.cs new file mode 100644 index 00000000..d0ee58b6 --- /dev/null +++ b/scr/Messenger.Api/Data/Migrations/20261106145724_AddIdempotencyKeys.Designer.cs @@ -0,0 +1,301 @@ +// +using System; +using Messenger.Api.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Messenger.Api.Data.Migrations +{ + [DbContext(typeof(MessengerDbContext))] + [Migration("20261106145724_AddIdempotencyKeys")] + partial class AddIdempotencyKeys + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.13") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Messenger.Api.Data.ChatEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("HistoryVersion") + .ValueGeneratedOnAdd() + .HasColumnType("bigint") + .HasDefaultValue(0L) + .HasColumnName("history_version"); + + b.Property("LastMessageAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("last_message_at"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("title"); + + b.HasKey("Id") + .HasName("pk_chats"); + + b.HasIndex("CreatedAt", "Id") + .HasDatabaseName("ix_chats_created_at_id"); + + b.ToTable("chats", null, t => + { + t.HasCheckConstraint("ck_chats_history_version_nonneg", "history_version >= 0"); + + t.HasCheckConstraint("ck_chats_title_not_blank", "title ~ '\\S'"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.ChatMemberEntity", b => + { + b.Property("ChatId") + .HasColumnType("uuid") + .HasColumnName("chat_id"); + + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.HasKey("ChatId", "UserId") + .HasName("pk_chat_members"); + + b.HasIndex("UserId") + .HasDatabaseName("ix_chat_members_user_id"); + + b.ToTable("chat_members", (string)null); + }); + + modelBuilder.Entity("Messenger.Api.Data.IdempotencyKeyEntity", b => + { + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.Property("ChatId") + .HasColumnType("uuid") + .HasColumnName("chat_id"); + + b.Property("Key") + .HasMaxLength(128) + .HasColumnType("character varying(128)") + .HasColumnName("key"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("expires_at"); + + b.Property("MessageId") + .HasColumnType("uuid") + .HasColumnName("message_id"); + + b.Property("RequestHash") + .IsRequired() + .HasColumnType("bytea") + .HasColumnName("request_hash"); + + b.HasKey("UserId", "ChatId", "Key") + .HasName("pk_idempotency_keys"); + + b.HasIndex("ExpiresAt") + .HasDatabaseName("ix_idempotency_keys_expires_at"); + + b.ToTable("idempotency_keys", null, t => + { + t.HasCheckConstraint("ck_idempotency_keys_expiry", "expires_at > created_at"); + + t.HasCheckConstraint("ck_idempotency_keys_hash_len", "octet_length(request_hash) = 32"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.MessageEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("ChatId") + .HasColumnType("uuid") + .HasColumnName("chat_id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("SenderId") + .HasColumnType("uuid") + .HasColumnName("sender_id"); + + b.Property("Text") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("character varying(4000)") + .HasColumnName("text"); + + b.HasKey("Id") + .HasName("pk_messages"); + + b.HasIndex("ChatId", "SenderId") + .HasDatabaseName("ix_messages_chat_id_sender_id"); + + b.HasIndex("ChatId", "CreatedAt", "Id") + .HasDatabaseName("ix_messages_chat_history"); + + b.ToTable("messages", null, t => + { + t.HasCheckConstraint("ck_messages_text_not_blank", "text ~ '\\S'"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.SessionEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("expires_at"); + + b.Property("RevokedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("revoked_at"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("bytea") + .HasColumnName("token_hash"); + + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.HasKey("Id") + .HasName("pk_sessions"); + + b.HasIndex("ExpiresAt") + .HasDatabaseName("ix_sessions_expires_at"); + + b.HasIndex("TokenHash") + .IsUnique() + .HasDatabaseName("ux_sessions_token_hash"); + + b.HasIndex("UserId") + .HasDatabaseName("ix_sessions_user_id"); + + b.ToTable("sessions", null, t => + { + t.HasCheckConstraint("ck_sessions_expiry_after_creation", "expires_at > created_at"); + + t.HasCheckConstraint("ck_sessions_token_hash_len", "octet_length(token_hash) = 32"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.UserEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("display_name"); + + b.Property("PasswordHash") + .IsRequired() + .HasColumnType("text") + .HasColumnName("password_hash"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)") + .HasColumnName("username"); + + b.HasKey("Id") + .HasName("pk_users"); + + b.HasIndex("Username") + .IsUnique() + .HasDatabaseName("ux_users_username"); + + b.ToTable("users", null, t => + { + t.HasCheckConstraint("ck_users_display_name_not_blank", "display_name ~ '\\S'"); + + t.HasCheckConstraint("ck_users_username_format", "username ~ '^[a-z0-9_]{3,32}$'"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.ChatMemberEntity", b => + { + b.HasOne("Messenger.Api.Data.ChatEntity", null) + .WithMany() + .HasForeignKey("ChatId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_chat_members_chats_chat_id"); + + b.HasOne("Messenger.Api.Data.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_chat_members_users_user_id"); + }); + + modelBuilder.Entity("Messenger.Api.Data.MessageEntity", b => + { + b.HasOne("Messenger.Api.Data.ChatMemberEntity", null) + .WithMany() + .HasForeignKey("ChatId", "SenderId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_messages_chat_members_chat_id_sender_id"); + }); + + modelBuilder.Entity("Messenger.Api.Data.SessionEntity", b => + { + b.HasOne("Messenger.Api.Data.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_sessions_users_user_id"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/scr/Messenger.Api/Data/Migrations/20261106145724_AddIdempotencyKeys.cs b/scr/Messenger.Api/Data/Migrations/20261106145724_AddIdempotencyKeys.cs new file mode 100644 index 00000000..e9883548 --- /dev/null +++ b/scr/Messenger.Api/Data/Migrations/20261106145724_AddIdempotencyKeys.cs @@ -0,0 +1,57 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Messenger.Api.Data.Migrations +{ + /// + public partial class AddIdempotencyKeys : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "idempotency_keys", + columns: table => new + { + user_id = table.Column(type: "uuid", nullable: false), + chat_id = table.Column(type: "uuid", nullable: false), + key = table.Column(type: "character varying(128)", maxLength: 128, nullable: false), + request_hash = table.Column(type: "bytea", nullable: false), + message_id = table.Column(type: "uuid", nullable: false), + created_at = table.Column(type: "timestamp with time zone", nullable: false), + expires_at = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("pk_idempotency_keys", x => new { x.user_id, x.chat_id, x.key }); + table.CheckConstraint("ck_idempotency_keys_expiry", "expires_at > created_at"); + table.CheckConstraint("ck_idempotency_keys_hash_len", "octet_length(request_hash) = 32"); + }); + + migrationBuilder.CreateIndex( + name: "ix_idempotency_keys_expires_at", + table: "idempotency_keys", + column: "expires_at"); + + // Ключ идемпотентности вставляется РАНЬШЕ сообщения (claim → резервирование слота → вставка), поэтому FK + // проверяется при COMMIT (DEFERRABLE INITIALLY DEFERRED): запись «ключ → сообщение» без сообщения не переживёт транзакцию. + // Миграция только добавляет таблицу: запущенная предыдущая версия API её не использует и продолжает работать + // (совместимость для rolling update). + migrationBuilder.Sql(""" + ALTER TABLE idempotency_keys + ADD CONSTRAINT fk_idempotency_keys_messages_message_id + FOREIGN KEY (message_id) REFERENCES messages (id) ON DELETE CASCADE + DEFERRABLE INITIALLY DEFERRED; + """); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "idempotency_keys"); + } + } +} diff --git a/scr/Messenger.Api/Data/Migrations/20261113163634_AddAttachments.Designer.cs b/scr/Messenger.Api/Data/Migrations/20261113163634_AddAttachments.Designer.cs new file mode 100644 index 00000000..67f763ff --- /dev/null +++ b/scr/Messenger.Api/Data/Migrations/20261113163634_AddAttachments.Designer.cs @@ -0,0 +1,389 @@ +// +using System; +using Messenger.Api.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Messenger.Api.Data.Migrations +{ + [DbContext(typeof(MessengerDbContext))] + [Migration("20261113163634_AddAttachments")] + partial class AddAttachments + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.13") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Messenger.Api.Data.AttachmentEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("ChatId") + .HasColumnType("uuid") + .HasColumnName("chat_id"); + + b.Property("ChecksumSha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("checksum_sha256"); + + b.Property("ContentType") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("content_type"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("Filename") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("filename"); + + b.Property("ObjectKey") + .IsRequired() + .HasColumnType("text") + .HasColumnName("object_key"); + + b.Property("OwnerId") + .HasColumnType("uuid") + .HasColumnName("owner_id"); + + b.Property("SizeBytes") + .HasColumnType("bigint") + .HasColumnName("size_bytes"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasColumnName("status"); + + b.Property("UploadedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("uploaded_at"); + + b.HasKey("Id") + .HasName("pk_attachments"); + + b.HasIndex("ChatId") + .HasDatabaseName("ix_attachments_chat_id"); + + b.HasIndex("ObjectKey") + .IsUnique() + .HasDatabaseName("ix_attachments_object_key"); + + b.HasIndex("OwnerId") + .HasDatabaseName("ix_attachments_owner_id"); + + b.ToTable("attachments", (string)null); + }); + + modelBuilder.Entity("Messenger.Api.Data.ChatEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("HistoryVersion") + .ValueGeneratedOnAdd() + .HasColumnType("bigint") + .HasDefaultValue(0L) + .HasColumnName("history_version"); + + b.Property("LastMessageAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("last_message_at"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("title"); + + b.HasKey("Id") + .HasName("pk_chats"); + + b.HasIndex("CreatedAt", "Id") + .HasDatabaseName("ix_chats_created_at_id"); + + b.ToTable("chats", null, t => + { + t.HasCheckConstraint("ck_chats_history_version_nonneg", "history_version >= 0"); + + t.HasCheckConstraint("ck_chats_title_not_blank", "title ~ '\\S'"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.ChatMemberEntity", b => + { + b.Property("ChatId") + .HasColumnType("uuid") + .HasColumnName("chat_id"); + + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.HasKey("ChatId", "UserId") + .HasName("pk_chat_members"); + + b.HasIndex("UserId") + .HasDatabaseName("ix_chat_members_user_id"); + + b.ToTable("chat_members", (string)null); + }); + + modelBuilder.Entity("Messenger.Api.Data.IdempotencyKeyEntity", b => + { + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.Property("ChatId") + .HasColumnType("uuid") + .HasColumnName("chat_id"); + + b.Property("Key") + .HasMaxLength(128) + .HasColumnType("character varying(128)") + .HasColumnName("key"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("expires_at"); + + b.Property("MessageId") + .HasColumnType("uuid") + .HasColumnName("message_id"); + + b.Property("RequestHash") + .IsRequired() + .HasColumnType("bytea") + .HasColumnName("request_hash"); + + b.HasKey("UserId", "ChatId", "Key") + .HasName("pk_idempotency_keys"); + + b.HasIndex("ExpiresAt") + .HasDatabaseName("ix_idempotency_keys_expires_at"); + + b.ToTable("idempotency_keys", null, t => + { + t.HasCheckConstraint("ck_idempotency_keys_expiry", "expires_at > created_at"); + + t.HasCheckConstraint("ck_idempotency_keys_hash_len", "octet_length(request_hash) = 32"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.MessageEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("ChatId") + .HasColumnType("uuid") + .HasColumnName("chat_id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("SenderId") + .HasColumnType("uuid") + .HasColumnName("sender_id"); + + b.Property("Text") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("character varying(4000)") + .HasColumnName("text"); + + b.HasKey("Id") + .HasName("pk_messages"); + + b.HasIndex("ChatId", "SenderId") + .HasDatabaseName("ix_messages_chat_id_sender_id"); + + b.HasIndex("ChatId", "CreatedAt", "Id") + .HasDatabaseName("ix_messages_chat_history"); + + b.ToTable("messages", null, t => + { + t.HasCheckConstraint("ck_messages_text_not_blank", "text ~ '\\S'"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.SessionEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("expires_at"); + + b.Property("RevokedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("revoked_at"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("bytea") + .HasColumnName("token_hash"); + + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.HasKey("Id") + .HasName("pk_sessions"); + + b.HasIndex("ExpiresAt") + .HasDatabaseName("ix_sessions_expires_at"); + + b.HasIndex("TokenHash") + .IsUnique() + .HasDatabaseName("ux_sessions_token_hash"); + + b.HasIndex("UserId") + .HasDatabaseName("ix_sessions_user_id"); + + b.ToTable("sessions", null, t => + { + t.HasCheckConstraint("ck_sessions_expiry_after_creation", "expires_at > created_at"); + + t.HasCheckConstraint("ck_sessions_token_hash_len", "octet_length(token_hash) = 32"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.UserEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("display_name"); + + b.Property("PasswordHash") + .IsRequired() + .HasColumnType("text") + .HasColumnName("password_hash"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)") + .HasColumnName("username"); + + b.HasKey("Id") + .HasName("pk_users"); + + b.HasIndex("Username") + .IsUnique() + .HasDatabaseName("ux_users_username"); + + b.ToTable("users", null, t => + { + t.HasCheckConstraint("ck_users_display_name_not_blank", "display_name ~ '\\S'"); + + t.HasCheckConstraint("ck_users_username_format", "username ~ '^[a-z0-9_]{3,32}$'"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.AttachmentEntity", b => + { + b.HasOne("Messenger.Api.Data.ChatEntity", null) + .WithMany() + .HasForeignKey("ChatId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_attachments_chats_chat_id"); + + b.HasOne("Messenger.Api.Data.UserEntity", null) + .WithMany() + .HasForeignKey("OwnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_attachments_users_owner_id"); + }); + + modelBuilder.Entity("Messenger.Api.Data.ChatMemberEntity", b => + { + b.HasOne("Messenger.Api.Data.ChatEntity", null) + .WithMany() + .HasForeignKey("ChatId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_chat_members_chats_chat_id"); + + b.HasOne("Messenger.Api.Data.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_chat_members_users_user_id"); + }); + + modelBuilder.Entity("Messenger.Api.Data.MessageEntity", b => + { + b.HasOne("Messenger.Api.Data.ChatMemberEntity", null) + .WithMany() + .HasForeignKey("ChatId", "SenderId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_messages_chat_members_chat_id_sender_id"); + }); + + modelBuilder.Entity("Messenger.Api.Data.SessionEntity", b => + { + b.HasOne("Messenger.Api.Data.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_sessions_users_user_id"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/scr/Messenger.Api/Data/Migrations/20261113163634_AddAttachments.cs b/scr/Messenger.Api/Data/Migrations/20261113163634_AddAttachments.cs new file mode 100644 index 00000000..437d3624 --- /dev/null +++ b/scr/Messenger.Api/Data/Migrations/20261113163634_AddAttachments.cs @@ -0,0 +1,71 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Messenger.Api.Data.Migrations +{ + /// + public partial class AddAttachments : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "attachments", + columns: table => new + { + id = table.Column(type: "uuid", nullable: false), + chat_id = table.Column(type: "uuid", nullable: false), + owner_id = table.Column(type: "uuid", nullable: false), + filename = table.Column(type: "character varying(255)", maxLength: 255, nullable: false), + object_key = table.Column(type: "text", nullable: false), + content_type = table.Column(type: "character varying(100)", maxLength: 100, nullable: false), + size_bytes = table.Column(type: "bigint", nullable: false), + checksum_sha256 = table.Column(type: "character varying(64)", maxLength: 64, nullable: false), + status = table.Column(type: "character varying(20)", maxLength: 20, nullable: false), + created_at = table.Column(type: "timestamp with time zone", nullable: false), + uploaded_at = table.Column(type: "timestamp with time zone", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("pk_attachments", x => x.id); + table.ForeignKey( + name: "fk_attachments_chats_chat_id", + column: x => x.chat_id, + principalTable: "chats", + principalColumn: "id", + onDelete: ReferentialAction.Restrict); + table.ForeignKey( + name: "fk_attachments_users_owner_id", + column: x => x.owner_id, + principalTable: "users", + principalColumn: "id", + onDelete: ReferentialAction.Restrict); + }); + + migrationBuilder.CreateIndex( + name: "ix_attachments_chat_id", + table: "attachments", + column: "chat_id"); + + migrationBuilder.CreateIndex( + name: "ix_attachments_object_key", + table: "attachments", + column: "object_key", + unique: true); + + migrationBuilder.CreateIndex( + name: "ix_attachments_owner_id", + table: "attachments", + column: "owner_id"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "attachments"); + } + } +} diff --git a/scr/Messenger.Api/Data/Migrations/20261113171218_AddMessageAttachments.Designer.cs b/scr/Messenger.Api/Data/Migrations/20261113171218_AddMessageAttachments.Designer.cs new file mode 100644 index 00000000..408d0969 --- /dev/null +++ b/scr/Messenger.Api/Data/Migrations/20261113171218_AddMessageAttachments.Designer.cs @@ -0,0 +1,398 @@ +// +using System; +using Messenger.Api.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Messenger.Api.Data.Migrations +{ + [DbContext(typeof(MessengerDbContext))] + [Migration("20261113171218_AddMessageAttachments")] + partial class AddMessageAttachments + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.13") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Messenger.Api.Data.AttachmentEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("ChatId") + .HasColumnType("uuid") + .HasColumnName("chat_id"); + + b.Property("ChecksumSha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("checksum_sha256"); + + b.Property("ContentType") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("content_type"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("Filename") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("filename"); + + b.Property("ObjectKey") + .IsRequired() + .HasColumnType("text") + .HasColumnName("object_key"); + + b.Property("OwnerId") + .HasColumnType("uuid") + .HasColumnName("owner_id"); + + b.Property("SizeBytes") + .HasColumnType("bigint") + .HasColumnName("size_bytes"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasColumnName("status"); + + b.Property("UploadedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("uploaded_at"); + + b.HasKey("Id") + .HasName("pk_attachments"); + + b.HasIndex("ChatId") + .HasDatabaseName("ix_attachments_chat_id"); + + b.HasIndex("ObjectKey") + .IsUnique() + .HasDatabaseName("ix_attachments_object_key"); + + b.HasIndex("OwnerId") + .HasDatabaseName("ix_attachments_owner_id"); + + b.ToTable("attachments", (string)null); + }); + + modelBuilder.Entity("Messenger.Api.Data.ChatEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("HistoryVersion") + .ValueGeneratedOnAdd() + .HasColumnType("bigint") + .HasDefaultValue(0L) + .HasColumnName("history_version"); + + b.Property("LastMessageAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("last_message_at"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("title"); + + b.HasKey("Id") + .HasName("pk_chats"); + + b.HasIndex("CreatedAt", "Id") + .HasDatabaseName("ix_chats_created_at_id"); + + b.ToTable("chats", null, t => + { + t.HasCheckConstraint("ck_chats_history_version_nonneg", "history_version >= 0"); + + t.HasCheckConstraint("ck_chats_title_not_blank", "title ~ '\\S'"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.ChatMemberEntity", b => + { + b.Property("ChatId") + .HasColumnType("uuid") + .HasColumnName("chat_id"); + + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.HasKey("ChatId", "UserId") + .HasName("pk_chat_members"); + + b.HasIndex("UserId") + .HasDatabaseName("ix_chat_members_user_id"); + + b.ToTable("chat_members", (string)null); + }); + + modelBuilder.Entity("Messenger.Api.Data.IdempotencyKeyEntity", b => + { + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.Property("ChatId") + .HasColumnType("uuid") + .HasColumnName("chat_id"); + + b.Property("Key") + .HasMaxLength(128) + .HasColumnType("character varying(128)") + .HasColumnName("key"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("expires_at"); + + b.Property("MessageId") + .HasColumnType("uuid") + .HasColumnName("message_id"); + + b.Property("RequestHash") + .IsRequired() + .HasColumnType("bytea") + .HasColumnName("request_hash"); + + b.HasKey("UserId", "ChatId", "Key") + .HasName("pk_idempotency_keys"); + + b.HasIndex("ExpiresAt") + .HasDatabaseName("ix_idempotency_keys_expires_at"); + + b.ToTable("idempotency_keys", null, t => + { + t.HasCheckConstraint("ck_idempotency_keys_expiry", "expires_at > created_at"); + + t.HasCheckConstraint("ck_idempotency_keys_hash_len", "octet_length(request_hash) = 32"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.MessageEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.PrimitiveCollection("AttachmentIds") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("uuid[]") + .HasColumnName("attachment_ids") + .HasDefaultValueSql("'{}'::uuid[]"); + + b.Property("ChatId") + .HasColumnType("uuid") + .HasColumnName("chat_id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("SenderId") + .HasColumnType("uuid") + .HasColumnName("sender_id"); + + b.Property("Text") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("character varying(4000)") + .HasColumnName("text"); + + b.HasKey("Id") + .HasName("pk_messages"); + + b.HasIndex("ChatId", "SenderId") + .HasDatabaseName("ix_messages_chat_id_sender_id"); + + b.HasIndex("ChatId", "CreatedAt", "Id") + .HasDatabaseName("ix_messages_chat_history"); + + b.ToTable("messages", null, t => + { + t.HasCheckConstraint("ck_messages_attachment_limit", "cardinality(attachment_ids) <= 10"); + + t.HasCheckConstraint("ck_messages_text_or_attachments", "text ~ '\\S' OR cardinality(attachment_ids) > 0"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.SessionEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("expires_at"); + + b.Property("RevokedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("revoked_at"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("bytea") + .HasColumnName("token_hash"); + + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.HasKey("Id") + .HasName("pk_sessions"); + + b.HasIndex("ExpiresAt") + .HasDatabaseName("ix_sessions_expires_at"); + + b.HasIndex("TokenHash") + .IsUnique() + .HasDatabaseName("ux_sessions_token_hash"); + + b.HasIndex("UserId") + .HasDatabaseName("ix_sessions_user_id"); + + b.ToTable("sessions", null, t => + { + t.HasCheckConstraint("ck_sessions_expiry_after_creation", "expires_at > created_at"); + + t.HasCheckConstraint("ck_sessions_token_hash_len", "octet_length(token_hash) = 32"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.UserEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("display_name"); + + b.Property("PasswordHash") + .IsRequired() + .HasColumnType("text") + .HasColumnName("password_hash"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)") + .HasColumnName("username"); + + b.HasKey("Id") + .HasName("pk_users"); + + b.HasIndex("Username") + .IsUnique() + .HasDatabaseName("ux_users_username"); + + b.ToTable("users", null, t => + { + t.HasCheckConstraint("ck_users_display_name_not_blank", "display_name ~ '\\S'"); + + t.HasCheckConstraint("ck_users_username_format", "username ~ '^[a-z0-9_]{3,32}$'"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.AttachmentEntity", b => + { + b.HasOne("Messenger.Api.Data.ChatEntity", null) + .WithMany() + .HasForeignKey("ChatId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_attachments_chats_chat_id"); + + b.HasOne("Messenger.Api.Data.UserEntity", null) + .WithMany() + .HasForeignKey("OwnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_attachments_users_owner_id"); + }); + + modelBuilder.Entity("Messenger.Api.Data.ChatMemberEntity", b => + { + b.HasOne("Messenger.Api.Data.ChatEntity", null) + .WithMany() + .HasForeignKey("ChatId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_chat_members_chats_chat_id"); + + b.HasOne("Messenger.Api.Data.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_chat_members_users_user_id"); + }); + + modelBuilder.Entity("Messenger.Api.Data.MessageEntity", b => + { + b.HasOne("Messenger.Api.Data.ChatMemberEntity", null) + .WithMany() + .HasForeignKey("ChatId", "SenderId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_messages_chat_members_chat_id_sender_id"); + }); + + modelBuilder.Entity("Messenger.Api.Data.SessionEntity", b => + { + b.HasOne("Messenger.Api.Data.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_sessions_users_user_id"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/scr/Messenger.Api/Data/Migrations/20261113171218_AddMessageAttachments.cs b/scr/Messenger.Api/Data/Migrations/20261113171218_AddMessageAttachments.cs new file mode 100644 index 00000000..3b025aed --- /dev/null +++ b/scr/Messenger.Api/Data/Migrations/20261113171218_AddMessageAttachments.cs @@ -0,0 +1,57 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Messenger.Api.Data.Migrations +{ + /// + public partial class AddMessageAttachments : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropCheckConstraint( + name: "ck_messages_text_not_blank", + table: "messages"); + + migrationBuilder.AddColumn( + name: "attachment_ids", + table: "messages", + type: "uuid[]", + nullable: false, + defaultValueSql: "'{}'::uuid[]"); + + migrationBuilder.AddCheckConstraint( + name: "ck_messages_attachment_limit", + table: "messages", + sql: "cardinality(attachment_ids) <= 10"); + + migrationBuilder.AddCheckConstraint( + name: "ck_messages_text_or_attachments", + table: "messages", + sql: "text ~ '\\S' OR cardinality(attachment_ids) > 0"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropCheckConstraint( + name: "ck_messages_attachment_limit", + table: "messages"); + + migrationBuilder.DropCheckConstraint( + name: "ck_messages_text_or_attachments", + table: "messages"); + + migrationBuilder.DropColumn( + name: "attachment_ids", + table: "messages"); + + migrationBuilder.AddCheckConstraint( + name: "ck_messages_text_not_blank", + table: "messages", + sql: "text ~ '\\S'"); + } + } +} diff --git a/scr/Messenger.Api/Data/Migrations/20261113175727_AddUploadIntents.Designer.cs b/scr/Messenger.Api/Data/Migrations/20261113175727_AddUploadIntents.Designer.cs new file mode 100644 index 00000000..e4734a9d --- /dev/null +++ b/scr/Messenger.Api/Data/Migrations/20261113175727_AddUploadIntents.Designer.cs @@ -0,0 +1,438 @@ +// +using System; +using Messenger.Api.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Messenger.Api.Data.Migrations +{ + [DbContext(typeof(MessengerDbContext))] + [Migration("20261113175727_AddUploadIntents")] + partial class AddUploadIntents + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.13") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Messenger.Api.Data.AttachmentEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("ChatId") + .HasColumnType("uuid") + .HasColumnName("chat_id"); + + b.Property("ChecksumSha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("checksum_sha256"); + + b.Property("ContentType") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("content_type"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("Filename") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("filename"); + + b.Property("ObjectKey") + .IsRequired() + .HasColumnType("text") + .HasColumnName("object_key"); + + b.Property("OwnerId") + .HasColumnType("uuid") + .HasColumnName("owner_id"); + + b.Property("SizeBytes") + .HasColumnType("bigint") + .HasColumnName("size_bytes"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasColumnName("status"); + + b.Property("UploadedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("uploaded_at"); + + b.HasKey("Id") + .HasName("pk_attachments"); + + b.HasIndex("ChatId") + .HasDatabaseName("ix_attachments_chat_id"); + + b.HasIndex("ObjectKey") + .IsUnique() + .HasDatabaseName("ix_attachments_object_key"); + + b.HasIndex("OwnerId") + .HasDatabaseName("ix_attachments_owner_id"); + + b.ToTable("attachments", (string)null); + }); + + modelBuilder.Entity("Messenger.Api.Data.ChatEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("HistoryVersion") + .ValueGeneratedOnAdd() + .HasColumnType("bigint") + .HasDefaultValue(0L) + .HasColumnName("history_version"); + + b.Property("LastMessageAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("last_message_at"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("title"); + + b.HasKey("Id") + .HasName("pk_chats"); + + b.HasIndex("CreatedAt", "Id") + .HasDatabaseName("ix_chats_created_at_id"); + + b.ToTable("chats", null, t => + { + t.HasCheckConstraint("ck_chats_history_version_nonneg", "history_version >= 0"); + + t.HasCheckConstraint("ck_chats_title_not_blank", "title ~ '\\S'"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.ChatMemberEntity", b => + { + b.Property("ChatId") + .HasColumnType("uuid") + .HasColumnName("chat_id"); + + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.HasKey("ChatId", "UserId") + .HasName("pk_chat_members"); + + b.HasIndex("UserId") + .HasDatabaseName("ix_chat_members_user_id"); + + b.ToTable("chat_members", (string)null); + }); + + modelBuilder.Entity("Messenger.Api.Data.IdempotencyKeyEntity", b => + { + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.Property("ChatId") + .HasColumnType("uuid") + .HasColumnName("chat_id"); + + b.Property("Key") + .HasMaxLength(128) + .HasColumnType("character varying(128)") + .HasColumnName("key"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("expires_at"); + + b.Property("MessageId") + .HasColumnType("uuid") + .HasColumnName("message_id"); + + b.Property("RequestHash") + .IsRequired() + .HasColumnType("bytea") + .HasColumnName("request_hash"); + + b.HasKey("UserId", "ChatId", "Key") + .HasName("pk_idempotency_keys"); + + b.HasIndex("ExpiresAt") + .HasDatabaseName("ix_idempotency_keys_expires_at"); + + b.ToTable("idempotency_keys", null, t => + { + t.HasCheckConstraint("ck_idempotency_keys_expiry", "expires_at > created_at"); + + t.HasCheckConstraint("ck_idempotency_keys_hash_len", "octet_length(request_hash) = 32"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.MessageEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.PrimitiveCollection("AttachmentIds") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("uuid[]") + .HasColumnName("attachment_ids") + .HasDefaultValueSql("'{}'::uuid[]"); + + b.Property("ChatId") + .HasColumnType("uuid") + .HasColumnName("chat_id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("SenderId") + .HasColumnType("uuid") + .HasColumnName("sender_id"); + + b.Property("Text") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("character varying(4000)") + .HasColumnName("text"); + + b.HasKey("Id") + .HasName("pk_messages"); + + b.HasIndex("ChatId", "SenderId") + .HasDatabaseName("ix_messages_chat_id_sender_id"); + + b.HasIndex("ChatId", "CreatedAt", "Id") + .HasDatabaseName("ix_messages_chat_history"); + + b.ToTable("messages", null, t => + { + t.HasCheckConstraint("ck_messages_attachment_limit", "cardinality(attachment_ids) <= 10"); + + t.HasCheckConstraint("ck_messages_text_or_attachments", "text ~ '\\S' OR cardinality(attachment_ids) > 0"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.SessionEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("expires_at"); + + b.Property("RevokedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("revoked_at"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("bytea") + .HasColumnName("token_hash"); + + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.HasKey("Id") + .HasName("pk_sessions"); + + b.HasIndex("ExpiresAt") + .HasDatabaseName("ix_sessions_expires_at"); + + b.HasIndex("TokenHash") + .IsUnique() + .HasDatabaseName("ux_sessions_token_hash"); + + b.HasIndex("UserId") + .HasDatabaseName("ix_sessions_user_id"); + + b.ToTable("sessions", null, t => + { + t.HasCheckConstraint("ck_sessions_expiry_after_creation", "expires_at > created_at"); + + t.HasCheckConstraint("ck_sessions_token_hash_len", "octet_length(token_hash) = 32"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.UploadIntentEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("DeleteCount") + .HasColumnType("integer") + .HasColumnName("delete_count"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("expires_at"); + + b.Property("NextAttemptAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("next_attempt_at"); + + b.Property("ObjectKey") + .IsRequired() + .HasColumnType("text") + .HasColumnName("object_key"); + + b.HasKey("Id") + .HasName("pk_upload_intents"); + + b.HasIndex("ObjectKey") + .IsUnique() + .HasDatabaseName("ix_upload_intents_object_key"); + + b.HasIndex("NextAttemptAt", "ExpiresAt") + .HasDatabaseName("ix_upload_intents_next_attempt_at_expires_at"); + + b.ToTable("upload_intents", (string)null); + }); + + modelBuilder.Entity("Messenger.Api.Data.UserEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("display_name"); + + b.Property("PasswordHash") + .IsRequired() + .HasColumnType("text") + .HasColumnName("password_hash"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)") + .HasColumnName("username"); + + b.HasKey("Id") + .HasName("pk_users"); + + b.HasIndex("Username") + .IsUnique() + .HasDatabaseName("ux_users_username"); + + b.ToTable("users", null, t => + { + t.HasCheckConstraint("ck_users_display_name_not_blank", "display_name ~ '\\S'"); + + t.HasCheckConstraint("ck_users_username_format", "username ~ '^[a-z0-9_]{3,32}$'"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.AttachmentEntity", b => + { + b.HasOne("Messenger.Api.Data.ChatEntity", null) + .WithMany() + .HasForeignKey("ChatId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_attachments_chats_chat_id"); + + b.HasOne("Messenger.Api.Data.UserEntity", null) + .WithMany() + .HasForeignKey("OwnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_attachments_users_owner_id"); + }); + + modelBuilder.Entity("Messenger.Api.Data.ChatMemberEntity", b => + { + b.HasOne("Messenger.Api.Data.ChatEntity", null) + .WithMany() + .HasForeignKey("ChatId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_chat_members_chats_chat_id"); + + b.HasOne("Messenger.Api.Data.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_chat_members_users_user_id"); + }); + + modelBuilder.Entity("Messenger.Api.Data.MessageEntity", b => + { + b.HasOne("Messenger.Api.Data.ChatMemberEntity", null) + .WithMany() + .HasForeignKey("ChatId", "SenderId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_messages_chat_members_chat_id_sender_id"); + }); + + modelBuilder.Entity("Messenger.Api.Data.SessionEntity", b => + { + b.HasOne("Messenger.Api.Data.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_sessions_users_user_id"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/scr/Messenger.Api/Data/Migrations/20261113175727_AddUploadIntents.cs b/scr/Messenger.Api/Data/Migrations/20261113175727_AddUploadIntents.cs new file mode 100644 index 00000000..545d228c --- /dev/null +++ b/scr/Messenger.Api/Data/Migrations/20261113175727_AddUploadIntents.cs @@ -0,0 +1,49 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Messenger.Api.Data.Migrations +{ + /// + public partial class AddUploadIntents : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "upload_intents", + columns: table => new + { + id = table.Column(type: "uuid", nullable: false), + object_key = table.Column(type: "text", nullable: false), + created_at = table.Column(type: "timestamp with time zone", nullable: false), + expires_at = table.Column(type: "timestamp with time zone", nullable: false), + next_attempt_at = table.Column(type: "timestamp with time zone", nullable: false), + delete_count = table.Column(type: "integer", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("pk_upload_intents", x => x.id); + }); + + migrationBuilder.CreateIndex( + name: "ix_upload_intents_next_attempt_at_expires_at", + table: "upload_intents", + columns: new[] { "next_attempt_at", "expires_at" }); + + migrationBuilder.CreateIndex( + name: "ix_upload_intents_object_key", + table: "upload_intents", + column: "object_key", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "upload_intents"); + } + } +} diff --git a/scr/Messenger.Api/Data/Migrations/20261127162010_AsyncAttachments.Designer.cs b/scr/Messenger.Api/Data/Migrations/20261127162010_AsyncAttachments.Designer.cs new file mode 100644 index 00000000..c3ffc4c6 --- /dev/null +++ b/scr/Messenger.Api/Data/Migrations/20261127162010_AsyncAttachments.Designer.cs @@ -0,0 +1,577 @@ +// +using System; +using Messenger.Api.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Messenger.Api.Data.Migrations +{ + [DbContext(typeof(MessengerDbContext))] + [Migration("20261127162010_AsyncAttachments")] + partial class AsyncAttachments + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.13") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Messenger.Api.Data.AttachmentEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("ChatId") + .HasColumnType("uuid") + .HasColumnName("chat_id"); + + b.Property("ChecksumSha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("checksum_sha256"); + + b.Property("ContentType") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("content_type"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("ErrorCode") + .HasColumnType("text") + .HasColumnName("error_code"); + + b.Property("Filename") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("filename"); + + b.Property("ObjectKey") + .IsRequired() + .HasColumnType("text") + .HasColumnName("object_key"); + + b.Property("OwnerId") + .HasColumnType("uuid") + .HasColumnName("owner_id"); + + b.Property("SizeBytes") + .HasColumnType("bigint") + .HasColumnName("size_bytes"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasColumnName("status"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("updated_at"); + + b.HasKey("Id") + .HasName("pk_attachments"); + + b.HasIndex("ChatId") + .HasDatabaseName("ix_attachments_chat_id"); + + b.HasIndex("ObjectKey") + .IsUnique() + .HasDatabaseName("ix_attachments_object_key"); + + b.HasIndex("OwnerId") + .HasDatabaseName("ix_attachments_owner_id"); + + b.ToTable("attachments", (string)null); + }); + + modelBuilder.Entity("Messenger.Api.Data.AttachmentJobEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("AttachmentId") + .HasColumnType("uuid") + .HasColumnName("attachment_id"); + + b.Property("Attempt") + .HasColumnType("integer") + .HasColumnName("attempt"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("LeaseUntil") + .HasColumnType("timestamp with time zone") + .HasColumnName("lease_until"); + + b.Property("NextAttemptAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("next_attempt_at"); + + b.Property("PipelineVersion") + .HasColumnType("integer") + .HasColumnName("pipeline_version"); + + b.Property("PublishedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("published_at"); + + b.Property("SourceKey") + .IsRequired() + .HasColumnType("text") + .HasColumnName("source_key"); + + b.HasKey("Id") + .HasName("pk_attachment_jobs"); + + b.HasIndex("AttachmentId") + .IsUnique() + .HasDatabaseName("ix_attachment_jobs_attachment_id"); + + b.HasIndex("LeaseUntil") + .HasDatabaseName("ix_attachment_jobs_lease_until") + .HasFilter("lease_until IS NOT NULL"); + + b.HasIndex("NextAttemptAt") + .HasDatabaseName("ix_attachment_jobs_next_attempt_at") + .HasFilter("published_at IS NULL"); + + b.ToTable("attachment_jobs", (string)null); + }); + + modelBuilder.Entity("Messenger.Api.Data.AttachmentVariantEntity", b => + { + b.Property("AttachmentId") + .HasColumnType("uuid") + .HasColumnName("attachment_id"); + + b.Property("PipelineVersion") + .HasColumnType("integer") + .HasColumnName("pipeline_version"); + + b.Property("Name") + .HasColumnType("text") + .HasColumnName("name"); + + b.Property("ContentType") + .IsRequired() + .HasColumnType("text") + .HasColumnName("content_type"); + + b.Property("Height") + .HasColumnType("integer") + .HasColumnName("height"); + + b.Property("ObjectKey") + .IsRequired() + .HasColumnType("text") + .HasColumnName("object_key"); + + b.Property("Sha256") + .IsRequired() + .HasColumnType("text") + .HasColumnName("sha256"); + + b.Property("SizeBytes") + .HasColumnType("bigint") + .HasColumnName("size_bytes"); + + b.Property("Width") + .HasColumnType("integer") + .HasColumnName("width"); + + b.HasKey("AttachmentId", "PipelineVersion", "Name") + .HasName("pk_attachment_variants"); + + b.HasIndex("ObjectKey") + .IsUnique() + .HasDatabaseName("ix_attachment_variants_object_key"); + + b.ToTable("attachment_variants", (string)null); + }); + + modelBuilder.Entity("Messenger.Api.Data.ChatEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("HistoryVersion") + .ValueGeneratedOnAdd() + .HasColumnType("bigint") + .HasDefaultValue(0L) + .HasColumnName("history_version"); + + b.Property("LastMessageAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("last_message_at"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("title"); + + b.HasKey("Id") + .HasName("pk_chats"); + + b.HasIndex("CreatedAt", "Id") + .HasDatabaseName("ix_chats_created_at_id"); + + b.ToTable("chats", null, t => + { + t.HasCheckConstraint("ck_chats_history_version_nonneg", "history_version >= 0"); + + t.HasCheckConstraint("ck_chats_title_not_blank", "title ~ '\\S'"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.ChatMemberEntity", b => + { + b.Property("ChatId") + .HasColumnType("uuid") + .HasColumnName("chat_id"); + + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.HasKey("ChatId", "UserId") + .HasName("pk_chat_members"); + + b.HasIndex("UserId") + .HasDatabaseName("ix_chat_members_user_id"); + + b.ToTable("chat_members", (string)null); + }); + + modelBuilder.Entity("Messenger.Api.Data.IdempotencyKeyEntity", b => + { + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.Property("ChatId") + .HasColumnType("uuid") + .HasColumnName("chat_id"); + + b.Property("Key") + .HasMaxLength(128) + .HasColumnType("character varying(128)") + .HasColumnName("key"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("expires_at"); + + b.Property("MessageId") + .HasColumnType("uuid") + .HasColumnName("message_id"); + + b.Property("RequestHash") + .IsRequired() + .HasColumnType("bytea") + .HasColumnName("request_hash"); + + b.HasKey("UserId", "ChatId", "Key") + .HasName("pk_idempotency_keys"); + + b.HasIndex("ExpiresAt") + .HasDatabaseName("ix_idempotency_keys_expires_at"); + + b.ToTable("idempotency_keys", null, t => + { + t.HasCheckConstraint("ck_idempotency_keys_expiry", "expires_at > created_at"); + + t.HasCheckConstraint("ck_idempotency_keys_hash_len", "octet_length(request_hash) = 32"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.MessageEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.PrimitiveCollection("AttachmentIds") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("uuid[]") + .HasColumnName("attachment_ids") + .HasDefaultValueSql("'{}'::uuid[]"); + + b.Property("ChatId") + .HasColumnType("uuid") + .HasColumnName("chat_id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("SenderId") + .HasColumnType("uuid") + .HasColumnName("sender_id"); + + b.Property("Text") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("character varying(4000)") + .HasColumnName("text"); + + b.HasKey("Id") + .HasName("pk_messages"); + + b.HasIndex("ChatId", "SenderId") + .HasDatabaseName("ix_messages_chat_id_sender_id"); + + b.HasIndex("ChatId", "CreatedAt", "Id") + .HasDatabaseName("ix_messages_chat_history"); + + b.ToTable("messages", null, t => + { + t.HasCheckConstraint("ck_messages_attachment_limit", "cardinality(attachment_ids) <= 10"); + + t.HasCheckConstraint("ck_messages_text_or_attachments", "text ~ '\\S' OR cardinality(attachment_ids) > 0"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.SessionEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("expires_at"); + + b.Property("RevokedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("revoked_at"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("bytea") + .HasColumnName("token_hash"); + + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.HasKey("Id") + .HasName("pk_sessions"); + + b.HasIndex("ExpiresAt") + .HasDatabaseName("ix_sessions_expires_at"); + + b.HasIndex("TokenHash") + .IsUnique() + .HasDatabaseName("ux_sessions_token_hash"); + + b.HasIndex("UserId") + .HasDatabaseName("ix_sessions_user_id"); + + b.ToTable("sessions", null, t => + { + t.HasCheckConstraint("ck_sessions_expiry_after_creation", "expires_at > created_at"); + + t.HasCheckConstraint("ck_sessions_token_hash_len", "octet_length(token_hash) = 32"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.UploadIntentEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("DeleteCount") + .HasColumnType("integer") + .HasColumnName("delete_count"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("expires_at"); + + b.Property("NextAttemptAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("next_attempt_at"); + + b.Property("ObjectKey") + .IsRequired() + .HasColumnType("text") + .HasColumnName("object_key"); + + b.HasKey("Id") + .HasName("pk_upload_intents"); + + b.HasIndex("ObjectKey") + .IsUnique() + .HasDatabaseName("ix_upload_intents_object_key"); + + b.HasIndex("NextAttemptAt", "ExpiresAt") + .HasDatabaseName("ix_upload_intents_next_attempt_at_expires_at"); + + b.ToTable("upload_intents", (string)null); + }); + + modelBuilder.Entity("Messenger.Api.Data.UserEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("display_name"); + + b.Property("PasswordHash") + .IsRequired() + .HasColumnType("text") + .HasColumnName("password_hash"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)") + .HasColumnName("username"); + + b.HasKey("Id") + .HasName("pk_users"); + + b.HasIndex("Username") + .IsUnique() + .HasDatabaseName("ux_users_username"); + + b.ToTable("users", null, t => + { + t.HasCheckConstraint("ck_users_display_name_not_blank", "display_name ~ '\\S'"); + + t.HasCheckConstraint("ck_users_username_format", "username ~ '^[a-z0-9_]{3,32}$'"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.AttachmentEntity", b => + { + b.HasOne("Messenger.Api.Data.ChatEntity", null) + .WithMany() + .HasForeignKey("ChatId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_attachments_chats_chat_id"); + + b.HasOne("Messenger.Api.Data.UserEntity", null) + .WithMany() + .HasForeignKey("OwnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_attachments_users_owner_id"); + }); + + modelBuilder.Entity("Messenger.Api.Data.AttachmentJobEntity", b => + { + b.HasOne("Messenger.Api.Data.AttachmentEntity", "Attachment") + .WithOne() + .HasForeignKey("Messenger.Api.Data.AttachmentJobEntity", "AttachmentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_attachment_jobs_attachments_attachment_id"); + + b.Navigation("Attachment"); + }); + + modelBuilder.Entity("Messenger.Api.Data.AttachmentVariantEntity", b => + { + b.HasOne("Messenger.Api.Data.AttachmentEntity", null) + .WithMany("Variants") + .HasForeignKey("AttachmentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_attachment_variants_attachments_attachment_id"); + }); + + modelBuilder.Entity("Messenger.Api.Data.ChatMemberEntity", b => + { + b.HasOne("Messenger.Api.Data.ChatEntity", null) + .WithMany() + .HasForeignKey("ChatId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_chat_members_chats_chat_id"); + + b.HasOne("Messenger.Api.Data.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_chat_members_users_user_id"); + }); + + modelBuilder.Entity("Messenger.Api.Data.MessageEntity", b => + { + b.HasOne("Messenger.Api.Data.ChatMemberEntity", null) + .WithMany() + .HasForeignKey("ChatId", "SenderId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_messages_chat_members_chat_id_sender_id"); + }); + + modelBuilder.Entity("Messenger.Api.Data.SessionEntity", b => + { + b.HasOne("Messenger.Api.Data.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_sessions_users_user_id"); + }); + + modelBuilder.Entity("Messenger.Api.Data.AttachmentEntity", b => + { + b.Navigation("Variants"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/scr/Messenger.Api/Data/Migrations/20261127162010_AsyncAttachments.cs b/scr/Messenger.Api/Data/Migrations/20261127162010_AsyncAttachments.cs new file mode 100644 index 00000000..4e6784af --- /dev/null +++ b/scr/Messenger.Api/Data/Migrations/20261127162010_AsyncAttachments.cs @@ -0,0 +1,133 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Messenger.Api.Data.Migrations +{ + /// + public partial class AsyncAttachments : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.RenameColumn( + name: "uploaded_at", + table: "attachments", + newName: "updated_at"); + + migrationBuilder.AddColumn( + name: "error_code", + table: "attachments", + type: "text", + nullable: true); + + migrationBuilder.CreateTable( + name: "attachment_jobs", + columns: table => new + { + id = table.Column(type: "uuid", nullable: false), + attachment_id = table.Column(type: "uuid", nullable: false), + source_key = table.Column(type: "text", nullable: false), + pipeline_version = table.Column(type: "integer", nullable: false), + attempt = table.Column(type: "integer", nullable: false), + created_at = table.Column(type: "timestamp with time zone", nullable: false), + next_attempt_at = table.Column(type: "timestamp with time zone", nullable: false), + published_at = table.Column(type: "timestamp with time zone", nullable: true), + lease_until = table.Column(type: "timestamp with time zone", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("pk_attachment_jobs", x => x.id); + table.ForeignKey( + name: "fk_attachment_jobs_attachments_attachment_id", + column: x => x.attachment_id, + principalTable: "attachments", + principalColumn: "id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "attachment_variants", + columns: table => new + { + attachment_id = table.Column(type: "uuid", nullable: false), + pipeline_version = table.Column(type: "integer", nullable: false), + name = table.Column(type: "text", nullable: false), + object_key = table.Column(type: "text", nullable: false), + content_type = table.Column(type: "text", nullable: false), + width = table.Column(type: "integer", nullable: false), + height = table.Column(type: "integer", nullable: false), + size_bytes = table.Column(type: "bigint", nullable: false), + sha256 = table.Column(type: "text", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("pk_attachment_variants", x => new { x.attachment_id, x.pipeline_version, x.name }); + table.ForeignKey( + name: "fk_attachment_variants_attachments_attachment_id", + column: x => x.attachment_id, + principalTable: "attachments", + principalColumn: "id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "ix_attachment_jobs_attachment_id", + table: "attachment_jobs", + column: "attachment_id", + unique: true); + + migrationBuilder.CreateIndex( + name: "ix_attachment_jobs_lease_until", + table: "attachment_jobs", + column: "lease_until", + filter: "lease_until IS NOT NULL"); + + migrationBuilder.CreateIndex( + name: "ix_attachment_jobs_next_attempt_at", + table: "attachment_jobs", + column: "next_attempt_at", + filter: "published_at IS NULL"); + + migrationBuilder.CreateIndex( + name: "ix_attachment_variants_object_key", + table: "attachment_variants", + column: "object_key", + unique: true); + + // Старые originals уже устойчивы. Обрабатываем их на месте, сохраняя ID и ссылки сообщений. + migrationBuilder.Sql(""" + INSERT INTO attachment_jobs (id, attachment_id, source_key, pipeline_version, attempt, created_at, next_attempt_at) + SELECT gen_random_uuid(), id, object_key, 1, 1, now(), now() FROM attachments WHERE status = 'ready'; + UPDATE attachments SET status = 'queued', updated_at = now() WHERE status = 'ready'; + """); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.Sql(""" + DO $$ BEGIN + IF EXISTS (SELECT 1 FROM attachments WHERE status <> 'ready') THEN + RAISE EXCEPTION 'Lab4 requires a published original for every attachment'; + END IF; + END $$; + """); + migrationBuilder.DropTable( + name: "attachment_jobs"); + + migrationBuilder.DropTable( + name: "attachment_variants"); + + migrationBuilder.DropColumn( + name: "error_code", + table: "attachments"); + + migrationBuilder.RenameColumn( + name: "updated_at", + table: "attachments", + newName: "uploaded_at"); + } + } +} diff --git a/scr/Messenger.Api/Data/Migrations/20261127163030_VersionedAttachmentJobs.Designer.cs b/scr/Messenger.Api/Data/Migrations/20261127163030_VersionedAttachmentJobs.Designer.cs new file mode 100644 index 00000000..192c31fd --- /dev/null +++ b/scr/Messenger.Api/Data/Migrations/20261127163030_VersionedAttachmentJobs.Designer.cs @@ -0,0 +1,593 @@ +// +using System; +using Messenger.Api.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Messenger.Api.Data.Migrations +{ + [DbContext(typeof(MessengerDbContext))] + [Migration("20261127163030_VersionedAttachmentJobs")] + partial class VersionedAttachmentJobs + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.13") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Messenger.Api.Data.AttachmentEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("ChatId") + .HasColumnType("uuid") + .HasColumnName("chat_id"); + + b.Property("ChecksumSha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("checksum_sha256"); + + b.Property("ContentType") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("content_type"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("ErrorCode") + .HasColumnType("text") + .HasColumnName("error_code"); + + b.Property("Filename") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("filename"); + + b.Property("ObjectKey") + .IsRequired() + .HasColumnType("text") + .HasColumnName("object_key"); + + b.Property("OwnerId") + .HasColumnType("uuid") + .HasColumnName("owner_id"); + + b.Property("PipelineVersion") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1) + .HasColumnName("pipeline_version"); + + b.Property("SizeBytes") + .HasColumnType("bigint") + .HasColumnName("size_bytes"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasColumnName("status"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("updated_at"); + + b.HasKey("Id") + .HasName("pk_attachments"); + + b.HasIndex("ChatId") + .HasDatabaseName("ix_attachments_chat_id"); + + b.HasIndex("ObjectKey") + .IsUnique() + .HasDatabaseName("ix_attachments_object_key"); + + b.HasIndex("OwnerId") + .HasDatabaseName("ix_attachments_owner_id"); + + b.ToTable("attachments", (string)null); + }); + + modelBuilder.Entity("Messenger.Api.Data.AttachmentJobEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("AttachmentId") + .HasColumnType("uuid") + .HasColumnName("attachment_id"); + + b.Property("Attempt") + .HasColumnType("integer") + .HasColumnName("attempt"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("FirstAttempt") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1) + .HasColumnName("first_attempt"); + + b.Property("LeaseUntil") + .HasColumnType("timestamp with time zone") + .HasColumnName("lease_until"); + + b.Property("NextAttemptAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("next_attempt_at"); + + b.Property("PipelineVersion") + .HasColumnType("integer") + .HasColumnName("pipeline_version"); + + b.Property("PublishedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("published_at"); + + b.Property("ReplayedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("replayed_at"); + + b.Property("SourceKey") + .IsRequired() + .HasColumnType("text") + .HasColumnName("source_key"); + + b.HasKey("Id") + .HasName("pk_attachment_jobs"); + + b.HasIndex("LeaseUntil") + .HasDatabaseName("ix_attachment_jobs_lease_until") + .HasFilter("lease_until IS NOT NULL"); + + b.HasIndex("NextAttemptAt") + .HasDatabaseName("ix_attachment_jobs_next_attempt_at") + .HasFilter("published_at IS NULL"); + + b.HasIndex("AttachmentId", "PipelineVersion") + .IsUnique() + .HasDatabaseName("ix_attachment_jobs_attachment_id_pipeline_version"); + + b.ToTable("attachment_jobs", (string)null); + }); + + modelBuilder.Entity("Messenger.Api.Data.AttachmentVariantEntity", b => + { + b.Property("AttachmentId") + .HasColumnType("uuid") + .HasColumnName("attachment_id"); + + b.Property("PipelineVersion") + .HasColumnType("integer") + .HasColumnName("pipeline_version"); + + b.Property("Name") + .HasColumnType("text") + .HasColumnName("name"); + + b.Property("ContentType") + .IsRequired() + .HasColumnType("text") + .HasColumnName("content_type"); + + b.Property("Height") + .HasColumnType("integer") + .HasColumnName("height"); + + b.Property("ObjectKey") + .IsRequired() + .HasColumnType("text") + .HasColumnName("object_key"); + + b.Property("Sha256") + .IsRequired() + .HasColumnType("text") + .HasColumnName("sha256"); + + b.Property("SizeBytes") + .HasColumnType("bigint") + .HasColumnName("size_bytes"); + + b.Property("Width") + .HasColumnType("integer") + .HasColumnName("width"); + + b.HasKey("AttachmentId", "PipelineVersion", "Name") + .HasName("pk_attachment_variants"); + + b.HasIndex("ObjectKey") + .IsUnique() + .HasDatabaseName("ix_attachment_variants_object_key"); + + b.ToTable("attachment_variants", (string)null); + }); + + modelBuilder.Entity("Messenger.Api.Data.ChatEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("HistoryVersion") + .ValueGeneratedOnAdd() + .HasColumnType("bigint") + .HasDefaultValue(0L) + .HasColumnName("history_version"); + + b.Property("LastMessageAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("last_message_at"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("title"); + + b.HasKey("Id") + .HasName("pk_chats"); + + b.HasIndex("CreatedAt", "Id") + .HasDatabaseName("ix_chats_created_at_id"); + + b.ToTable("chats", null, t => + { + t.HasCheckConstraint("ck_chats_history_version_nonneg", "history_version >= 0"); + + t.HasCheckConstraint("ck_chats_title_not_blank", "title ~ '\\S'"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.ChatMemberEntity", b => + { + b.Property("ChatId") + .HasColumnType("uuid") + .HasColumnName("chat_id"); + + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.HasKey("ChatId", "UserId") + .HasName("pk_chat_members"); + + b.HasIndex("UserId") + .HasDatabaseName("ix_chat_members_user_id"); + + b.ToTable("chat_members", (string)null); + }); + + modelBuilder.Entity("Messenger.Api.Data.IdempotencyKeyEntity", b => + { + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.Property("ChatId") + .HasColumnType("uuid") + .HasColumnName("chat_id"); + + b.Property("Key") + .HasMaxLength(128) + .HasColumnType("character varying(128)") + .HasColumnName("key"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("expires_at"); + + b.Property("MessageId") + .HasColumnType("uuid") + .HasColumnName("message_id"); + + b.Property("RequestHash") + .IsRequired() + .HasColumnType("bytea") + .HasColumnName("request_hash"); + + b.HasKey("UserId", "ChatId", "Key") + .HasName("pk_idempotency_keys"); + + b.HasIndex("ExpiresAt") + .HasDatabaseName("ix_idempotency_keys_expires_at"); + + b.ToTable("idempotency_keys", null, t => + { + t.HasCheckConstraint("ck_idempotency_keys_expiry", "expires_at > created_at"); + + t.HasCheckConstraint("ck_idempotency_keys_hash_len", "octet_length(request_hash) = 32"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.MessageEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.PrimitiveCollection("AttachmentIds") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("uuid[]") + .HasColumnName("attachment_ids") + .HasDefaultValueSql("'{}'::uuid[]"); + + b.Property("ChatId") + .HasColumnType("uuid") + .HasColumnName("chat_id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("SenderId") + .HasColumnType("uuid") + .HasColumnName("sender_id"); + + b.Property("Text") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("character varying(4000)") + .HasColumnName("text"); + + b.HasKey("Id") + .HasName("pk_messages"); + + b.HasIndex("ChatId", "SenderId") + .HasDatabaseName("ix_messages_chat_id_sender_id"); + + b.HasIndex("ChatId", "CreatedAt", "Id") + .HasDatabaseName("ix_messages_chat_history"); + + b.ToTable("messages", null, t => + { + t.HasCheckConstraint("ck_messages_attachment_limit", "cardinality(attachment_ids) <= 10"); + + t.HasCheckConstraint("ck_messages_text_or_attachments", "text ~ '\\S' OR cardinality(attachment_ids) > 0"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.SessionEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("expires_at"); + + b.Property("RevokedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("revoked_at"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("bytea") + .HasColumnName("token_hash"); + + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.HasKey("Id") + .HasName("pk_sessions"); + + b.HasIndex("ExpiresAt") + .HasDatabaseName("ix_sessions_expires_at"); + + b.HasIndex("TokenHash") + .IsUnique() + .HasDatabaseName("ux_sessions_token_hash"); + + b.HasIndex("UserId") + .HasDatabaseName("ix_sessions_user_id"); + + b.ToTable("sessions", null, t => + { + t.HasCheckConstraint("ck_sessions_expiry_after_creation", "expires_at > created_at"); + + t.HasCheckConstraint("ck_sessions_token_hash_len", "octet_length(token_hash) = 32"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.UploadIntentEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("DeleteCount") + .HasColumnType("integer") + .HasColumnName("delete_count"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("expires_at"); + + b.Property("NextAttemptAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("next_attempt_at"); + + b.Property("ObjectKey") + .IsRequired() + .HasColumnType("text") + .HasColumnName("object_key"); + + b.HasKey("Id") + .HasName("pk_upload_intents"); + + b.HasIndex("ObjectKey") + .IsUnique() + .HasDatabaseName("ix_upload_intents_object_key"); + + b.HasIndex("NextAttemptAt", "ExpiresAt") + .HasDatabaseName("ix_upload_intents_next_attempt_at_expires_at"); + + b.ToTable("upload_intents", (string)null); + }); + + modelBuilder.Entity("Messenger.Api.Data.UserEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("display_name"); + + b.Property("PasswordHash") + .IsRequired() + .HasColumnType("text") + .HasColumnName("password_hash"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)") + .HasColumnName("username"); + + b.HasKey("Id") + .HasName("pk_users"); + + b.HasIndex("Username") + .IsUnique() + .HasDatabaseName("ux_users_username"); + + b.ToTable("users", null, t => + { + t.HasCheckConstraint("ck_users_display_name_not_blank", "display_name ~ '\\S'"); + + t.HasCheckConstraint("ck_users_username_format", "username ~ '^[a-z0-9_]{3,32}$'"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.AttachmentEntity", b => + { + b.HasOne("Messenger.Api.Data.ChatEntity", null) + .WithMany() + .HasForeignKey("ChatId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_attachments_chats_chat_id"); + + b.HasOne("Messenger.Api.Data.UserEntity", null) + .WithMany() + .HasForeignKey("OwnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_attachments_users_owner_id"); + }); + + modelBuilder.Entity("Messenger.Api.Data.AttachmentJobEntity", b => + { + b.HasOne("Messenger.Api.Data.AttachmentEntity", "Attachment") + .WithMany() + .HasForeignKey("AttachmentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_attachment_jobs_attachments_attachment_id"); + + b.Navigation("Attachment"); + }); + + modelBuilder.Entity("Messenger.Api.Data.AttachmentVariantEntity", b => + { + b.HasOne("Messenger.Api.Data.AttachmentEntity", null) + .WithMany("Variants") + .HasForeignKey("AttachmentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_attachment_variants_attachments_attachment_id"); + }); + + modelBuilder.Entity("Messenger.Api.Data.ChatMemberEntity", b => + { + b.HasOne("Messenger.Api.Data.ChatEntity", null) + .WithMany() + .HasForeignKey("ChatId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_chat_members_chats_chat_id"); + + b.HasOne("Messenger.Api.Data.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_chat_members_users_user_id"); + }); + + modelBuilder.Entity("Messenger.Api.Data.MessageEntity", b => + { + b.HasOne("Messenger.Api.Data.ChatMemberEntity", null) + .WithMany() + .HasForeignKey("ChatId", "SenderId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_messages_chat_members_chat_id_sender_id"); + }); + + modelBuilder.Entity("Messenger.Api.Data.SessionEntity", b => + { + b.HasOne("Messenger.Api.Data.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_sessions_users_user_id"); + }); + + modelBuilder.Entity("Messenger.Api.Data.AttachmentEntity", b => + { + b.Navigation("Variants"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/scr/Messenger.Api/Data/Migrations/20261127163030_VersionedAttachmentJobs.cs b/scr/Messenger.Api/Data/Migrations/20261127163030_VersionedAttachmentJobs.cs new file mode 100644 index 00000000..dba52042 --- /dev/null +++ b/scr/Messenger.Api/Data/Migrations/20261127163030_VersionedAttachmentJobs.cs @@ -0,0 +1,85 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Messenger.Api.Data.Migrations +{ + /// + public partial class VersionedAttachmentJobs : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "ix_attachment_jobs_attachment_id", + table: "attachment_jobs"); + + migrationBuilder.AddColumn( + name: "pipeline_version", + table: "attachments", + type: "integer", + nullable: false, + defaultValue: 1); + + migrationBuilder.AddColumn( + name: "first_attempt", + table: "attachment_jobs", + type: "integer", + nullable: false, + defaultValue: 1); + + migrationBuilder.AddColumn( + name: "replayed_at", + table: "attachment_jobs", + type: "timestamp with time zone", + nullable: true); + + migrationBuilder.CreateIndex( + name: "ix_attachment_jobs_attachment_id_pipeline_version", + table: "attachment_jobs", + columns: new[] { "attachment_id", "pipeline_version" }, + unique: true); + + // Установки с ранним worker могут хранить только thumbnail. Оригинал уже в S3. + migrationBuilder.Sql(""" + WITH partial AS ( + UPDATE attachments a SET pipeline_version = 2, status = 'queued', updated_at = now() + WHERE status = 'ready' AND NOT EXISTS ( + SELECT 1 FROM attachment_variants v WHERE v.attachment_id = a.id + AND v.pipeline_version = 1 AND v.name = 'optimized' + ) + RETURNING id, object_key + ) + INSERT INTO attachment_jobs (id, attachment_id, source_key, pipeline_version, attempt, created_at, next_attempt_at) + SELECT gen_random_uuid(), id, object_key, 2, 1, now(), now() FROM partial; + """); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "ix_attachment_jobs_attachment_id_pipeline_version", + table: "attachment_jobs"); + + migrationBuilder.DropColumn( + name: "pipeline_version", + table: "attachments"); + + migrationBuilder.DropColumn( + name: "first_attempt", + table: "attachment_jobs"); + + migrationBuilder.DropColumn( + name: "replayed_at", + table: "attachment_jobs"); + + migrationBuilder.CreateIndex( + name: "ix_attachment_jobs_attachment_id", + table: "attachment_jobs", + column: "attachment_id", + unique: true); + } + } +} diff --git a/scr/Messenger.Api/Data/Migrations/MessengerDbContextModelSnapshot.cs b/scr/Messenger.Api/Data/Migrations/MessengerDbContextModelSnapshot.cs new file mode 100644 index 00000000..8f235eba --- /dev/null +++ b/scr/Messenger.Api/Data/Migrations/MessengerDbContextModelSnapshot.cs @@ -0,0 +1,590 @@ +// +using System; +using Messenger.Api.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Messenger.Api.Data.Migrations +{ + [DbContext(typeof(MessengerDbContext))] + partial class MessengerDbContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.13") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Messenger.Api.Data.AttachmentEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("ChatId") + .HasColumnType("uuid") + .HasColumnName("chat_id"); + + b.Property("ChecksumSha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("checksum_sha256"); + + b.Property("ContentType") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("content_type"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("ErrorCode") + .HasColumnType("text") + .HasColumnName("error_code"); + + b.Property("Filename") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("filename"); + + b.Property("ObjectKey") + .IsRequired() + .HasColumnType("text") + .HasColumnName("object_key"); + + b.Property("OwnerId") + .HasColumnType("uuid") + .HasColumnName("owner_id"); + + b.Property("PipelineVersion") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1) + .HasColumnName("pipeline_version"); + + b.Property("SizeBytes") + .HasColumnType("bigint") + .HasColumnName("size_bytes"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasColumnName("status"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("updated_at"); + + b.HasKey("Id") + .HasName("pk_attachments"); + + b.HasIndex("ChatId") + .HasDatabaseName("ix_attachments_chat_id"); + + b.HasIndex("ObjectKey") + .IsUnique() + .HasDatabaseName("ix_attachments_object_key"); + + b.HasIndex("OwnerId") + .HasDatabaseName("ix_attachments_owner_id"); + + b.ToTable("attachments", (string)null); + }); + + modelBuilder.Entity("Messenger.Api.Data.AttachmentJobEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("AttachmentId") + .HasColumnType("uuid") + .HasColumnName("attachment_id"); + + b.Property("Attempt") + .HasColumnType("integer") + .HasColumnName("attempt"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("FirstAttempt") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1) + .HasColumnName("first_attempt"); + + b.Property("LeaseUntil") + .HasColumnType("timestamp with time zone") + .HasColumnName("lease_until"); + + b.Property("NextAttemptAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("next_attempt_at"); + + b.Property("PipelineVersion") + .HasColumnType("integer") + .HasColumnName("pipeline_version"); + + b.Property("PublishedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("published_at"); + + b.Property("ReplayedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("replayed_at"); + + b.Property("SourceKey") + .IsRequired() + .HasColumnType("text") + .HasColumnName("source_key"); + + b.HasKey("Id") + .HasName("pk_attachment_jobs"); + + b.HasIndex("LeaseUntil") + .HasDatabaseName("ix_attachment_jobs_lease_until") + .HasFilter("lease_until IS NOT NULL"); + + b.HasIndex("NextAttemptAt") + .HasDatabaseName("ix_attachment_jobs_next_attempt_at") + .HasFilter("published_at IS NULL"); + + b.HasIndex("AttachmentId", "PipelineVersion") + .IsUnique() + .HasDatabaseName("ix_attachment_jobs_attachment_id_pipeline_version"); + + b.ToTable("attachment_jobs", (string)null); + }); + + modelBuilder.Entity("Messenger.Api.Data.AttachmentVariantEntity", b => + { + b.Property("AttachmentId") + .HasColumnType("uuid") + .HasColumnName("attachment_id"); + + b.Property("PipelineVersion") + .HasColumnType("integer") + .HasColumnName("pipeline_version"); + + b.Property("Name") + .HasColumnType("text") + .HasColumnName("name"); + + b.Property("ContentType") + .IsRequired() + .HasColumnType("text") + .HasColumnName("content_type"); + + b.Property("Height") + .HasColumnType("integer") + .HasColumnName("height"); + + b.Property("ObjectKey") + .IsRequired() + .HasColumnType("text") + .HasColumnName("object_key"); + + b.Property("Sha256") + .IsRequired() + .HasColumnType("text") + .HasColumnName("sha256"); + + b.Property("SizeBytes") + .HasColumnType("bigint") + .HasColumnName("size_bytes"); + + b.Property("Width") + .HasColumnType("integer") + .HasColumnName("width"); + + b.HasKey("AttachmentId", "PipelineVersion", "Name") + .HasName("pk_attachment_variants"); + + b.HasIndex("ObjectKey") + .IsUnique() + .HasDatabaseName("ix_attachment_variants_object_key"); + + b.ToTable("attachment_variants", (string)null); + }); + + modelBuilder.Entity("Messenger.Api.Data.ChatEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("HistoryVersion") + .ValueGeneratedOnAdd() + .HasColumnType("bigint") + .HasDefaultValue(0L) + .HasColumnName("history_version"); + + b.Property("LastMessageAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("last_message_at"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("title"); + + b.HasKey("Id") + .HasName("pk_chats"); + + b.HasIndex("CreatedAt", "Id") + .HasDatabaseName("ix_chats_created_at_id"); + + b.ToTable("chats", null, t => + { + t.HasCheckConstraint("ck_chats_history_version_nonneg", "history_version >= 0"); + + t.HasCheckConstraint("ck_chats_title_not_blank", "title ~ '\\S'"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.ChatMemberEntity", b => + { + b.Property("ChatId") + .HasColumnType("uuid") + .HasColumnName("chat_id"); + + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.HasKey("ChatId", "UserId") + .HasName("pk_chat_members"); + + b.HasIndex("UserId") + .HasDatabaseName("ix_chat_members_user_id"); + + b.ToTable("chat_members", (string)null); + }); + + modelBuilder.Entity("Messenger.Api.Data.IdempotencyKeyEntity", b => + { + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.Property("ChatId") + .HasColumnType("uuid") + .HasColumnName("chat_id"); + + b.Property("Key") + .HasMaxLength(128) + .HasColumnType("character varying(128)") + .HasColumnName("key"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("expires_at"); + + b.Property("MessageId") + .HasColumnType("uuid") + .HasColumnName("message_id"); + + b.Property("RequestHash") + .IsRequired() + .HasColumnType("bytea") + .HasColumnName("request_hash"); + + b.HasKey("UserId", "ChatId", "Key") + .HasName("pk_idempotency_keys"); + + b.HasIndex("ExpiresAt") + .HasDatabaseName("ix_idempotency_keys_expires_at"); + + b.ToTable("idempotency_keys", null, t => + { + t.HasCheckConstraint("ck_idempotency_keys_expiry", "expires_at > created_at"); + + t.HasCheckConstraint("ck_idempotency_keys_hash_len", "octet_length(request_hash) = 32"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.MessageEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.PrimitiveCollection("AttachmentIds") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("uuid[]") + .HasColumnName("attachment_ids") + .HasDefaultValueSql("'{}'::uuid[]"); + + b.Property("ChatId") + .HasColumnType("uuid") + .HasColumnName("chat_id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("SenderId") + .HasColumnType("uuid") + .HasColumnName("sender_id"); + + b.Property("Text") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("character varying(4000)") + .HasColumnName("text"); + + b.HasKey("Id") + .HasName("pk_messages"); + + b.HasIndex("ChatId", "SenderId") + .HasDatabaseName("ix_messages_chat_id_sender_id"); + + b.HasIndex("ChatId", "CreatedAt", "Id") + .HasDatabaseName("ix_messages_chat_history"); + + b.ToTable("messages", null, t => + { + t.HasCheckConstraint("ck_messages_attachment_limit", "cardinality(attachment_ids) <= 10"); + + t.HasCheckConstraint("ck_messages_text_or_attachments", "text ~ '\\S' OR cardinality(attachment_ids) > 0"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.SessionEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("expires_at"); + + b.Property("RevokedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("revoked_at"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("bytea") + .HasColumnName("token_hash"); + + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.HasKey("Id") + .HasName("pk_sessions"); + + b.HasIndex("ExpiresAt") + .HasDatabaseName("ix_sessions_expires_at"); + + b.HasIndex("TokenHash") + .IsUnique() + .HasDatabaseName("ux_sessions_token_hash"); + + b.HasIndex("UserId") + .HasDatabaseName("ix_sessions_user_id"); + + b.ToTable("sessions", null, t => + { + t.HasCheckConstraint("ck_sessions_expiry_after_creation", "expires_at > created_at"); + + t.HasCheckConstraint("ck_sessions_token_hash_len", "octet_length(token_hash) = 32"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.UploadIntentEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("DeleteCount") + .HasColumnType("integer") + .HasColumnName("delete_count"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("expires_at"); + + b.Property("NextAttemptAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("next_attempt_at"); + + b.Property("ObjectKey") + .IsRequired() + .HasColumnType("text") + .HasColumnName("object_key"); + + b.HasKey("Id") + .HasName("pk_upload_intents"); + + b.HasIndex("ObjectKey") + .IsUnique() + .HasDatabaseName("ix_upload_intents_object_key"); + + b.HasIndex("NextAttemptAt", "ExpiresAt") + .HasDatabaseName("ix_upload_intents_next_attempt_at_expires_at"); + + b.ToTable("upload_intents", (string)null); + }); + + modelBuilder.Entity("Messenger.Api.Data.UserEntity", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("display_name"); + + b.Property("PasswordHash") + .IsRequired() + .HasColumnType("text") + .HasColumnName("password_hash"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)") + .HasColumnName("username"); + + b.HasKey("Id") + .HasName("pk_users"); + + b.HasIndex("Username") + .IsUnique() + .HasDatabaseName("ux_users_username"); + + b.ToTable("users", null, t => + { + t.HasCheckConstraint("ck_users_display_name_not_blank", "display_name ~ '\\S'"); + + t.HasCheckConstraint("ck_users_username_format", "username ~ '^[a-z0-9_]{3,32}$'"); + }); + }); + + modelBuilder.Entity("Messenger.Api.Data.AttachmentEntity", b => + { + b.HasOne("Messenger.Api.Data.ChatEntity", null) + .WithMany() + .HasForeignKey("ChatId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_attachments_chats_chat_id"); + + b.HasOne("Messenger.Api.Data.UserEntity", null) + .WithMany() + .HasForeignKey("OwnerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_attachments_users_owner_id"); + }); + + modelBuilder.Entity("Messenger.Api.Data.AttachmentJobEntity", b => + { + b.HasOne("Messenger.Api.Data.AttachmentEntity", "Attachment") + .WithMany() + .HasForeignKey("AttachmentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_attachment_jobs_attachments_attachment_id"); + + b.Navigation("Attachment"); + }); + + modelBuilder.Entity("Messenger.Api.Data.AttachmentVariantEntity", b => + { + b.HasOne("Messenger.Api.Data.AttachmentEntity", null) + .WithMany("Variants") + .HasForeignKey("AttachmentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_attachment_variants_attachments_attachment_id"); + }); + + modelBuilder.Entity("Messenger.Api.Data.ChatMemberEntity", b => + { + b.HasOne("Messenger.Api.Data.ChatEntity", null) + .WithMany() + .HasForeignKey("ChatId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_chat_members_chats_chat_id"); + + b.HasOne("Messenger.Api.Data.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_chat_members_users_user_id"); + }); + + modelBuilder.Entity("Messenger.Api.Data.MessageEntity", b => + { + b.HasOne("Messenger.Api.Data.ChatMemberEntity", null) + .WithMany() + .HasForeignKey("ChatId", "SenderId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_messages_chat_members_chat_id_sender_id"); + }); + + modelBuilder.Entity("Messenger.Api.Data.SessionEntity", b => + { + b.HasOne("Messenger.Api.Data.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_sessions_users_user_id"); + }); + + modelBuilder.Entity("Messenger.Api.Data.AttachmentEntity", b => + { + b.Navigation("Variants"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/scr/Messenger.Api/Endpoints/AttachmentEndpoints.cs b/scr/Messenger.Api/Endpoints/AttachmentEndpoints.cs new file mode 100644 index 00000000..1bff6b52 --- /dev/null +++ b/scr/Messenger.Api/Endpoints/AttachmentEndpoints.cs @@ -0,0 +1,176 @@ +using System.Security.Cryptography; +using Messenger.Api.Data; +using Messenger.Api.Models; +using Messenger.Api.Services; +using Microsoft.EntityFrameworkCore; +using StbImageSharp; + +namespace Messenger.Api.Endpoints; + +public static class AttachmentEndpoints +{ + public static IEndpointRouteBuilder MapAttachmentEndpoints(this IEndpointRouteBuilder endpoints) + { + endpoints.MapPost("/api/v1/chats/{chatId}/attachments", Upload).RequireAuthorization(); + endpoints.MapGet("/api/v1/attachments/{attachmentId}", Metadata).RequireAuthorization(); + endpoints.MapGet("/api/v1/attachments/{attachmentId}/content", Content).RequireAuthorization(); + return endpoints; + } + + private static async Task Upload(Guid chatId, HttpContext http, MessengerDbContext db, + IAttachmentStorage storage, UploadSettings limits, UploadGate gate, UploadCleanupSettings cleanup) + { + var user = http.GetUserId(); + if (!await db.ChatMembers.AnyAsync(m => m.ChatId == chatId && m.UserId == user, http.RequestAborted)) + return ApiErrors.Error(http, 404, "not_found", "Объект не найден"); + var names = http.Request.Query["filename"]; + var name = names.Count == 1 ? names[0] : null; + if (string.IsNullOrWhiteSpace(name) || ApiErrors.CodePoints(name) > 255 || + name.Any(c => c is '/' or '\\' || char.IsControl(c))) + return ApiErrors.Error(http, 400, "invalid_request", "Некорректное имя файла"); + var mime = http.Request.ContentType?.Split(';', 2)[0].Trim().ToLowerInvariant(); + if (mime is not ("image/png" or "image/jpeg")) + return ApiErrors.Error(http, 415, "unsupported_media_type", "Требуется PNG или JPEG"); + if (http.Request.ContentLength > limits.MaxBytes) + return ApiErrors.Error(http, 413, "payload_too_large", "Файл превышает лимит размера"); + + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(http.RequestAborted); + timeout.CancelAfter(TimeSpan.FromSeconds(30)); + var ct = timeout.Token; + if (!await gate.Slots.WaitAsync(TimeSpan.FromSeconds(2), ct)) + return ApiErrors.Error(http, 503, "unavailable", "Загрузка временно перегружена"); + try + { + // Временный файл ограничивает память API при приёме HTTP-тела. + var path = Path.Combine(Path.GetTempPath(), $"attachment-{Guid.NewGuid():N}"); + await using var file = new FileStream(path, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, + 65536, FileOptions.Asynchronous | FileOptions.DeleteOnClose); + var buffer = new byte[65536]; + long size = 0; + while (true) + { + var count = await http.Request.Body.ReadAsync(buffer, ct); + if (count == 0) break; + size += count; + if (size > limits.MaxBytes) + return ApiErrors.Error(http, 413, "payload_too_large", "Файл превышает лимит размера"); + await file.WriteAsync(buffer.AsMemory(0, count), ct); + } + file.Position = 0; + try + { + var signature = new byte[8]; + if (size < 12) throw new InvalidDataException("Truncated image"); + await file.ReadExactlyAsync(signature, ct); + var actual = signature.AsSpan().SequenceEqual(new byte[] {137,80,78,71,13,10,26,10}) ? "image/png" : + signature[0] == 255 && signature[1] == 216 ? "image/jpeg" : "unknown"; + if (actual != mime) + return ApiErrors.Error(http, 415, "unsupported_media_type", "Содержимое не соответствует MIME"); + file.Position = 0; + var info = ImageInfo.FromStream(file) ?? throw new InvalidDataException("Invalid image header"); + if (info.Width <= 0 || info.Height <= 0) throw new InvalidDataException("Invalid dimensions"); + if ((long)info.Width * info.Height > limits.MaxPixels) + return ApiErrors.Error(http, 413, "payload_too_large", "Слишком много пикселей"); + if (mime == "image/png") await PngIntegrity.ValidateAsync(file, + (long)info.Width * info.Height * 8 + info.Height * 8L + 1024, ct); + // Декодеры могут принимать обрезанные JPEG: обязательно проверяем окончание файла. + var tail = new byte[12]; + if (size < tail.Length) throw new InvalidDataException("Truncated image"); + file.Position = size - tail.Length; + await file.ReadExactlyAsync(tail, ct); + if (mime == "image/png" && !tail.AsSpan().SequenceEqual(new byte[] { 0,0,0,0,73,69,78,68,174,66,96,130 }) || + mime == "image/jpeg" && (tail[^2] != 255 || tail[^1] != 217)) + throw new InvalidDataException("Truncated image"); + } + catch (Exception ex) when (ex is InvalidDataException or EndOfStreamException or InvalidOperationException or ArgumentException or IndexOutOfRangeException) + { + return ApiErrors.Error(http, 415, "unsupported_media_type", "Повреждённое изображение"); + } + file.Position = 0; + var hash = Convert.ToHexStringLower(await SHA256.HashDataAsync(file, ct)); + var id = Guid.CreateVersion7(); + var now = Timestamps.UtcNowMilliseconds(); + var entity = new AttachmentEntity + { + Id = id, ChatId = chatId, OwnerId = user, Filename = name!, ContentType = mime!, + ObjectKey = $"originals/{id:N}", SizeBytes = size, ChecksumSha256 = hash, + Status = "queued", CreatedAt = now, UpdatedAt = now + }; + var intent = new UploadIntentEntity + { + Id = id, ObjectKey = $"staging/{id:N}", CreatedAt = now, + ExpiresAt = now + cleanup.Grace, NextAttemptAt = now + cleanup.Grace + }; + db.UploadIntents.Add(intent); + await db.SaveChangesAsync(ct); // S3 PUT не начинается без устойчивого журнала. + file.Position = 0; + await storage.PutAsync(intent.ObjectKey, file, entity.ContentType, ct); + await using var tx = await db.Database.BeginTransactionAsync(ct); + var activeIntent = await db.UploadIntents.FromSqlInterpolated($""" + SELECT * FROM upload_intents WHERE id = {id} AND expires_at > clock_timestamp() FOR UPDATE + """).SingleOrDefaultAsync(ct); + if (activeIntent is null) + return ApiErrors.Error(http, 503, "unavailable", "Время публикации вложения истекло"); + db.Attachments.Add(entity); + db.AttachmentJobs.Add(new AttachmentJobEntity + { + Id = Guid.CreateVersion7(), AttachmentId = id, SourceKey = intent.ObjectKey, + CreatedAt = now, NextAttemptAt = now + }); + db.UploadIntents.Remove(activeIntent); + await db.SaveChangesAsync(ct); + await tx.CommitAsync(ct); + // Возвращаем снимок приёма даже если worker уже успел закончить. + return Results.Accepted($"/api/v1/attachments/{id}", ToDto(entity)); + } + catch (OperationCanceledException) when (!http.RequestAborted.IsCancellationRequested) + { + return ApiErrors.Error(http, 503, "unavailable", "Истекло время загрузки"); + } + finally { gate.Slots.Release(); } + } + + private static Task Find(Guid id, HttpContext http, MessengerDbContext db) => + db.Attachments.AsNoTracking().Include(a => a.Variants).FirstOrDefaultAsync(a => a.Id == id && + db.ChatMembers.Any(m => m.ChatId == a.ChatId && m.UserId == http.GetUserId()), http.RequestAborted); + + private static async Task Metadata(Guid attachmentId, HttpContext http, MessengerDbContext db) + { + var entity = await Find(attachmentId, http, db); + return entity is null ? ApiErrors.Error(http, 404, "not_found", "Объект не найден") : Results.Ok(ToDto(entity)); + } + + private static async Task Content(Guid attachmentId, HttpContext http, MessengerDbContext db, + IAttachmentStorage storage, string? variant) + { + var entity = await Find(attachmentId, http, db); + if (entity is null) return ApiErrors.Error(http, 404, "not_found", "Объект не найден"); + if (entity.Status != "ready") return ApiErrors.Error(http, 409, "conflict", "Вложение не готово"); + var (key, mime, size, hash) = (entity.ObjectKey, entity.ContentType, entity.SizeBytes, entity.ChecksumSha256); + if (variant is not (null or "original")) + { + var selected = entity.Variants.SingleOrDefault(v => v.PipelineVersion == entity.PipelineVersion && v.Name == variant); + if (selected is null) return ApiErrors.Error(http, 404, "not_found", "Вариант не найден"); + (key, mime, size, hash) = (selected.ObjectKey, selected.ContentType, selected.SizeBytes, selected.Sha256); + } + // Ограниченный 10 MiB буфер до начала ответа позволяет честно вернуть 503 при отказе S3. + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(http.RequestAborted); + timeout.CancelAfter(TimeSpan.FromSeconds(30)); + using var output = new LimitedDownloadStream(Math.Min(size, 10485760)); + try { await storage.CopyToAsync(key, output, timeout.Token); } + catch (OperationCanceledException) when (!http.RequestAborted.IsCancellationRequested) + { return ApiErrors.Error(http, 503, "unavailable", "Истекло время скачивания"); } + catch (IOException) { return ApiErrors.Error(http, 503, "unavailable", "Ошибка чтения объекта"); } + if (output.Length != size || + Convert.ToHexStringLower(SHA256.HashData(output.GetBuffer().AsSpan(0, (int)output.Length))) != hash) + return ApiErrors.Error(http, 503, "unavailable", "Объект не соответствует метаданным"); + http.Response.Headers["X-Content-Type-Options"] = "nosniff"; + return Results.File(output.ToArray(), mime); + } + + private static Attachment ToDto(AttachmentEntity a) => new(a.Id, a.ChatId, a.OwnerId, a.Filename, + a.ContentType, a.SizeBytes, a.ChecksumSha256, a.Status, + a.Variants.Where(v => a.Status == "ready" && v.PipelineVersion == a.PipelineVersion) + .OrderBy(v => v.Name).Select(v => new AttachmentVariant(v.Name, v.ContentType, v.SizeBytes, v.Width, v.Height, v.Sha256)).ToArray(), + a.ErrorCode, a.CreatedAt, a.UpdatedAt ?? a.CreatedAt); +} diff --git a/scr/Messenger.Api/Endpoints/AuthEndpoints.cs b/scr/Messenger.Api/Endpoints/AuthEndpoints.cs new file mode 100644 index 00000000..d3bfff22 --- /dev/null +++ b/scr/Messenger.Api/Endpoints/AuthEndpoints.cs @@ -0,0 +1,146 @@ +using System.Text; +using Messenger.Api.Data; +using Messenger.Api.Models; +using Messenger.Api.Services; +using Microsoft.EntityFrameworkCore; + +namespace Messenger.Api.Endpoints; + +public static class AuthEndpoints +{ + private const string BasicChallenge = "Basic realm=\"messenger\", charset=\"UTF-8\""; + + public static IEndpointRouteBuilder MapAuthEndpoints(this IEndpointRouteBuilder endpoints) + { + endpoints.MapPost("/api/v1/auth/sessions", CreateSession); + endpoints.MapDelete("/api/v1/auth/sessions/current", RevokeCurrentSession).RequireAuthorization(); + return endpoints; + } + + private static async Task CreateSession( + HttpContext httpContext, + MessengerDbContext db, + IPasswordHasher hasher, + AuthSessionOptions options, + CancellationToken ct) + { + // Любая проблема с заголовком или credentials даёт один и тот же ответ. + var unauthorized = () => ApiErrors.Unauthorized(httpContext, BasicChallenge, "Неверное имя пользователя или пароль"); + + if (!TryParseBasic(httpContext.Request, out var username, out var password)) + { + return unauthorized(); + } + + var user = await db.Users.AsNoTracking().FirstOrDefaultAsync(u => u.Username == username, ct); + + // Проверка выполняется и для несуществующего пользователя (null → заглушка), чтобы время ответа + // не выдавало, существует ли username. + bool passwordOk; + try + { + passwordOk = await hasher.VerifyAsync(user?.PasswordHash, password, ct); + } + catch (PasswordHasherBusyException) + { + return ApiErrors.Error(httpContext, 503, "unavailable", "Сервис временно перегружен, повторите запрос позже"); + } + + if (user is null || !passwordOk) + { + return unauthorized(); + } + + var token = SessionTokens.Generate(); + var now = Timestamps.UtcNowMilliseconds(); + var session = new SessionEntity + { + Id = Guid.CreateVersion7(), + TokenHash = SessionTokens.Hash(token), + UserId = user.Id, + CreatedAt = now, + ExpiresAt = now + options.Ttl + }; + + db.Sessions.Add(session); + await db.SaveChangesAsync(ct); + + // Ответ с токеном нельзя кэшировать промежуточными узлами. + httpContext.Response.Headers.CacheControl = "no-store"; + + return Results.Json( + new SessionResponse( + token, + "Bearer", + session.ExpiresAt, + new User + { + Id = user.Id, + Username = user.Username, + DisplayName = user.DisplayName, + CreatedAt = user.CreatedAt + }), + statusCode: StatusCodes.Status201Created); + } + + private static async Task RevokeCurrentSession( + HttpContext httpContext, + MessengerDbContext db, + CancellationToken ct) + { + var sessionId = httpContext.GetSessionId(); + var now = Timestamps.UtcNowMilliseconds(); + + // Один UPDATE с условием: отзыв атомарен даже при двух параллельных DELETE с одним токеном. + var revoked = await db.Sessions + .Where(s => s.Id == sessionId && s.RevokedAt == null) + .ExecuteUpdateAsync(s => s.SetProperty(x => x.RevokedAt, now), ct); + + return revoked == 0 + ? ApiErrors.Unauthorized(httpContext, BearerAuth.Challenge, "Требуется действительный Bearer-токен") + : Results.NoContent(); + } + + // Basic: base64("username:password"), разделитель — ПЕРВОЕ двоеточие (в пароле двоеточие допустимо). + // Всё, что не разбирается строго (схема, base64, UTF-8, формат), считается неверными credentials. + private static bool TryParseBasic(HttpRequest request, out string username, out string password) + { + username = password = string.Empty; + + if (request.Headers.Authorization.Count != 1) + { + return false; + } + + var header = request.Headers.Authorization[0]; + const string prefix = "Basic "; + if (header is null || !header.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) + { + return false; + } + + string decoded; + try + { + var bytes = Convert.FromBase64String(header[prefix.Length..].Trim()); + decoded = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true).GetString(bytes); + } + catch (Exception ex) when (ex is FormatException or DecoderFallbackException) + { + return false; + } + + var separator = decoded.IndexOf(':'); + if (separator <= 0) + { + return false; + } + + username = decoded[..separator]; + password = decoded[(separator + 1)..]; + + // Username по контракту — ASCII [a-z0-9_]{3,32}; пароль — 12..128 code points. Отсекаем до дорогого Argon2. + var length = ApiErrors.CodePoints(password); + return username.Length is >= 3 and <= 32 && length is >= 12 and <= 128; + } +} diff --git a/scr/Messenger.Api/Endpoints/ChatEndpoints.cs b/scr/Messenger.Api/Endpoints/ChatEndpoints.cs new file mode 100644 index 00000000..087feebc --- /dev/null +++ b/scr/Messenger.Api/Endpoints/ChatEndpoints.cs @@ -0,0 +1,158 @@ +using Messenger.Api.Data; +using Messenger.Api.Models; +using Messenger.Api.Services; +using Microsoft.EntityFrameworkCore; +using Npgsql; + +namespace Messenger.Api.Endpoints; + +public static class ChatEndpoints +{ + public static IEndpointRouteBuilder MapChatEndpoints( + this IEndpointRouteBuilder endpoints) + { + endpoints.MapPost("/api/v1/chats", CreateChat).RequireAuthorization(); + endpoints.MapGet("/api/v1/chats", ListChats).RequireAuthorization(); + endpoints.MapGet("/api/v1/chats/{chatId}", GetChat).RequireAuthorization(); + return endpoints; + } + + private static async Task CreateChat( + CreateChatRequest request, + HttpContext httpContext, + MessengerDbContext db, + CancellationToken ct) + { + var userId = httpContext.GetUserId(); + + if (string.IsNullOrWhiteSpace(request.Title) || + ApiErrors.CodePoints(request.Title) > 100 || + request.MemberIds.Count is < 1 or > 100 || + request.MemberIds.Distinct().Count() != request.MemberIds.Count) + { + return ApiErrors.Error(httpContext, 400, "invalid_request", "Некорректные данные чата"); + } + + if (!request.MemberIds.Contains(userId)) + { + return ApiErrors.Error(httpContext, 400, "invalid_request", "Создатель должен быть участником чата"); + } + + var knownMembers = await db.Users.CountAsync(u => request.MemberIds.Contains(u.Id), ct); + if (knownMembers != request.MemberIds.Count) + { + return ApiErrors.Error(httpContext, 400, "invalid_request", "Неизвестный участник чата"); + } + + var chat = new ChatEntity + { + Id = Guid.CreateVersion7(), + Title = request.Title, + CreatedAt = Timestamps.UtcNowMilliseconds() + }; + + // Чат и все его участники сохраняются одним SaveChanges, то есть одной транзакцией: + // либо создано всё, либо ничего (нет чата без участников). + db.Chats.Add(chat); + db.ChatMembers.AddRange(request.MemberIds.Select(id => new ChatMemberEntity { ChatId = chat.Id, UserId = id })); + + try + { + await db.SaveChangesAsync(ct); + } + catch (DbUpdateException ex) when (ex.InnerException is PostgresException { SqlState: PostgresErrorCodes.ForeignKeyViolation }) + { + return ApiErrors.Error(httpContext, 400, "invalid_request", "Неизвестный участник чата"); + } + + return Results.Created($"/api/v1/chats/{chat.Id}", ToDto(chat, request.MemberIds.Order().ToList())); + } + + private static async Task ListChats( + int? limit, + string? cursor, + HttpContext httpContext, + MessengerDbContext db, + CancellationToken ct) + { + var userId = httpContext.GetUserId(); + var pageSize = limit ?? 50; + + if (pageSize is < 1 or > 100 || !Cursors.TryDecode(cursor, Cursors.Chats, out var after)) + { + return ApiErrors.Error(httpContext, 400, "invalid_request", "Некорректные параметры пагинации"); + } + + // Keyset: строковое сравнение (created_at, id) > (курсор), без OFFSET и без просмотра всей выдачи. + IQueryable source = after is null + ? db.Chats.FromSql($""" + SELECT c.* FROM chats c + WHERE EXISTS (SELECT 1 FROM chat_members m WHERE m.chat_id = c.id AND m.user_id = {userId}) + """) + : db.Chats.FromSql($""" + SELECT c.* FROM chats c + WHERE EXISTS (SELECT 1 FROM chat_members m WHERE m.chat_id = c.id AND m.user_id = {userId}) + AND (c.created_at, c.id) > ({after.Value.CreatedAt}, {after.Value.Id}) + """); + + var chats = await source + .AsNoTracking() + .OrderBy(c => c.CreatedAt).ThenBy(c => c.Id) + .Take(pageSize + 1) + .ToListAsync(ct); + + var hasNext = chats.Count > pageSize; + if (hasNext) + { + chats.RemoveAt(chats.Count - 1); + } + + var ids = chats.Select(c => c.Id).ToList(); + var members = (await db.ChatMembers + .AsNoTracking() + .Where(m => ids.Contains(m.ChatId)) + .Select(m => new { m.ChatId, m.UserId }) + .ToListAsync(ct)) + .ToLookup(m => m.ChatId, m => m.UserId); + + var items = chats.Select(c => ToDto(c, members[c.Id].Order().ToList())).ToList(); + var nextCursor = hasNext ? Cursors.Encode(Cursors.Chats, chats[^1].CreatedAt, chats[^1].Id) : null; + + return Results.Ok(new { items, next_cursor = nextCursor }); + } + + private static async Task GetChat( + Guid chatId, + HttpContext httpContext, + MessengerDbContext db, + CancellationToken ct) + { + var userId = httpContext.GetUserId(); + + // Отсутствующий и чужой чат неразличимы: оба дают 404. + var chat = await db.Chats + .AsNoTracking() + .FirstOrDefaultAsync(c => c.Id == chatId && db.ChatMembers.Any(m => m.ChatId == c.Id && m.UserId == userId), ct); + + if (chat is null) + { + return ApiErrors.Error(httpContext, 404, "not_found", "Объект не найден"); + } + + var memberIds = await db.ChatMembers + .AsNoTracking() + .Where(m => m.ChatId == chatId) + .Select(m => m.UserId) + .ToListAsync(ct); + + return Results.Ok(ToDto(chat, memberIds.Order().ToList())); + } + + private static Chat ToDto(ChatEntity chat, List memberIds) => new() + { + Id = chat.Id, + Title = chat.Title, + MemberIds = memberIds, + CreatedAt = chat.CreatedAt + }; +} diff --git a/scr/Messenger.Api/Endpoints/MessageEndpoints.cs b/scr/Messenger.Api/Endpoints/MessageEndpoints.cs new file mode 100644 index 00000000..d87033ef --- /dev/null +++ b/scr/Messenger.Api/Endpoints/MessageEndpoints.cs @@ -0,0 +1,244 @@ +using Messenger.Api.Data; +using Messenger.Api.Models; +using Messenger.Api.Services; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Storage; +using Microsoft.Extensions.Options; +using Npgsql; + +namespace Messenger.Api.Endpoints; + +public static class MessageEndpoints +{ + public static IEndpointRouteBuilder MapMessageEndpoints( + this IEndpointRouteBuilder endpoints) + { + endpoints.MapPost("/api/v1/chats/{chatId}/messages", CreateMessage).RequireAuthorization(); + endpoints.MapGet("/api/v1/chats/{chatId}/messages", ListMessages).RequireAuthorization(); + return endpoints; + } + + private static async Task CreateMessage( + Guid chatId, + CreateMessageRequest request, + HttpContext httpContext, + MessengerDbContext db, + IdempotencySettings idempotency, + CancellationToken ct) + { + var userId = httpContext.GetUserId(); + + // Сначала доступ к ресурсу (404 для постороннего), затем валидация ключа и тела. Доступ проверяется при каждом + // запросе, в том числе при повторе с тем же Idempotency-Key. + if (!await IsMemberAsync(db, chatId, userId, ct)) + { + return ApiErrors.Error(httpContext, 404, "not_found", "Объект не найден"); + } + + var key = IdempotencyKeys.ReadKey(httpContext.Request); + if (key is null) + { + return ApiErrors.Error(httpContext, 400, "invalid_request", "Требуется заголовок Idempotency-Key ([A-Za-z0-9._:-], 1-128 символов)"); + } + + if (request.AttachmentIds is null || request.AttachmentIds.Length > 10 || + request.AttachmentIds.Distinct().Count() != request.AttachmentIds.Length || + (string.IsNullOrWhiteSpace(request.Text) && request.AttachmentIds.Length == 0) || + ApiErrors.CodePoints(request.Text) > 4000) + { + return ApiErrors.Error(httpContext, 400, "invalid_request", "Некорректный текст сообщения"); + } + + // Транзакция: (0) claim ключа идемпотентности, (1) UPDATE чата берёт блокировку его строки и выдаёт created_at, + // (2) INSERT сообщения, (3) COMMIT. Записи в один чат идут строго по очереди, поэтому порядок коммитов совпадает + // с порядком (created_at, id) и курсор не может «проскочить» сообщение, закоммиченное позже. Версия истории + // растёт в той же транзакции. Ключ и сообщение коммитятся вместе: при любой ошибке откатывается и то и другое, + // поэтому 5xx не «запоминается» как результат, а клиент может безопасно повторить запрос с тем же ключом. + await using var tx = await db.Database.BeginTransactionAsync(ct); + + var messageId = Guid.CreateVersion7(); + var (claim, storedMessageId) = await IdempotencyKeys.ClaimAsync( + db, tx, userId, chatId, key, IdempotencyKeys.RequestHash(request.Text, request.AttachmentIds), messageId, idempotency.Ttl, ct); + + if (claim == ClaimResult.Conflict) + { + return ApiErrors.Error(httpContext, 409, "conflict", "Idempotency-Key уже использован с другим сообщением"); + } + + if (claim == ClaimResult.Replay) + { + // Повтор: ничего не пишем, возвращаем то же сообщение и тот же код 201. + var original = await db.Messages.AsNoTracking().FirstAsync(m => m.Id == storedMessageId, ct); + return Results.Created($"/api/v1/chats/{chatId}/messages", ToDto(original)); + } + + if (request.AttachmentIds.Length > 0) + { + // Блокировка до COMMIT упорядочивает отправку сообщения и переход вложения в failed. + var attachments = await db.Attachments.FromSql($""" + SELECT * FROM attachments WHERE chat_id = {chatId} AND id = ANY({request.AttachmentIds}) + ORDER BY id FOR SHARE + """).AsNoTracking().ToListAsync(ct); + if (attachments.Count != request.AttachmentIds.Length) + return ApiErrors.Error(httpContext, 404, "not_found", "Объект не найден"); + if (attachments.Any(a => a.Status == "failed")) + return ApiErrors.Error(httpContext, 409, "conflict", "Обработка вложения завершилась ошибкой"); + } + + var createdAt = await ReserveMessageSlotAsync(db, tx, chatId, userId, ct); + if (createdAt is null) + { + return ApiErrors.Error(httpContext, 404, "not_found", "Объект не найден"); + } + + var message = new MessageEntity + { + Id = messageId, + ChatId = chatId, + SenderId = userId, + Text = request.Text, + AttachmentIds = request.AttachmentIds, + CreatedAt = createdAt.Value + }; + + db.Messages.Add(message); + try + { + await db.SaveChangesAsync(ct); + } + catch (DbUpdateException ex) when (ex.InnerException is PostgresException { SqlState: PostgresErrorCodes.CheckViolation }) + { + return ApiErrors.Error(httpContext, 400, "invalid_request", "Некорректный текст сообщения"); + } + + await tx.CommitAsync(ct); + + return Results.Created($"/api/v1/chats/{chatId}/messages", ToDto(message)); + } + + private static async Task ListMessages( + Guid chatId, + int? limit, + string? cursor, + HttpContext httpContext, + MessengerDbContext db, + IMessageHistoryCache cache, + DiagnosticsSettings diagnostics, + IOptions jsonOptions, + CancellationToken ct) + { + var userId = httpContext.GetUserId(); + var pageSize = limit ?? 50; + + // Один запрос проверяет доступ (null → 404) и читает актуальную версию истории из PostgreSQL. + // Версия берётся из БД при каждом чтении, а не из кэша: после подтверждённой записи ключ гарантированно новый. + var version = await db.Chats + .AsNoTracking() + .Where(c => c.Id == chatId && db.ChatMembers.Any(m => m.ChatId == c.Id && m.UserId == userId)) + .Select(c => (long?)c.HistoryVersion) + .FirstOrDefaultAsync(ct); + + if (version is null) + { + return ApiErrors.Error(httpContext, 404, "not_found", "Объект не найден"); + } + + if (pageSize is < 1 or > 100 || !Cursors.TryDecode(cursor, Cursors.Messages(chatId), out var after)) + { + return ApiErrors.Error(httpContext, 400, "invalid_request", "Некорректные параметры пагинации"); + } + + // Ключ = чат + версия истории + размер страницы + курсор. Страница под этим ключом никогда не устаревает: + // любая запись увеличивает версию, и читатели переходят на другой ключ. + var key = $"hist4:{chatId:N}:v{version}:l{pageSize}:{cursor ?? "-"}"; + + var (cached, status) = await cache.GetAsync(key, ct); + if (cached is not null) + { + return CachedJson(httpContext, diagnostics, cached, status); + } + + // Keyset по индексу (chat_id, created_at, id): читается только страница, а не вся история. + IQueryable source = after is null + ? db.Messages.FromSql($"SELECT * FROM messages WHERE chat_id = {chatId}") + : db.Messages.FromSql($""" + SELECT * FROM messages + WHERE chat_id = {chatId} AND (created_at, id) > ({after.Value.CreatedAt}, {after.Value.Id}) + """); + + var messages = await source + .AsNoTracking() + .OrderBy(m => m.CreatedAt).ThenBy(m => m.Id) + .Take(pageSize + 1) + .ToListAsync(ct); + + var hasNext = messages.Count > pageSize; + if (hasNext) + { + messages.RemoveAt(messages.Count - 1); + } + + var nextCursor = hasNext + ? Cursors.Encode(Cursors.Messages(chatId), messages[^1].CreatedAt, messages[^1].Id) + : null; + + var json = System.Text.Json.JsonSerializer.Serialize( + new { items = messages.Select(ToDto).ToList(), next_cursor = nextCursor }, + jsonOptions.Value.SerializerOptions); + + await cache.SetAsync(key, json, ct); + return CachedJson(httpContext, diagnostics, json, status); + } + + // Ответ из кэша и ответ из БД байт-в-байт одинаковы: сериализуется одна и та же структура теми же настройками. + private static IResult CachedJson(HttpContext context, DiagnosticsSettings diagnostics, string json, CacheStatus status) + { + if (diagnostics.Headers) + { + context.Response.Headers["X-Cache"] = status.ToString().ToLowerInvariant(); + } + + return Results.Content(json, "application/json; charset=utf-8"); + } + + private static Task IsMemberAsync(MessengerDbContext db, Guid chatId, Guid userId, CancellationToken ct) => + db.ChatMembers.AnyAsync(m => m.ChatId == chatId && m.UserId == userId, ct); + + // Атомарно: проверяет членство, увеличивает версию истории и возвращает created_at нового сообщения — + // строго больше времени предыдущего (даже при откате системных часов или двух сообщениях в одну миллисекунду). + // null — чата нет или пользователь не участник. + private static async Task ReserveMessageSlotAsync( + MessengerDbContext db, + IDbContextTransaction tx, + Guid chatId, + Guid userId, + CancellationToken ct) + { + var connection = (NpgsqlConnection)db.Database.GetDbConnection(); + await using var command = new NpgsqlCommand(""" + UPDATE chats c + SET history_version = c.history_version + 1, + last_message_at = GREATEST(@now, COALESCE(c.last_message_at + interval '1 millisecond', @now)) + WHERE c.id = @chat + AND EXISTS (SELECT 1 FROM chat_members m WHERE m.chat_id = c.id AND m.user_id = @user) + RETURNING c.last_message_at + """, connection, (NpgsqlTransaction)tx.GetDbTransaction()); + + command.Parameters.AddWithValue("now", Timestamps.UtcNowMilliseconds()); + command.Parameters.AddWithValue("chat", chatId); + command.Parameters.AddWithValue("user", userId); + + await using var reader = await command.ExecuteReaderAsync(ct); + return await reader.ReadAsync(ct) ? reader.GetFieldValue(0) : null; + } + + private static Message ToDto(MessageEntity m) => new() + { + Id = m.Id, + ChatId = m.ChatId, + SenderId = m.SenderId, + Text = m.Text, + CreatedAt = m.CreatedAt, + AttachmentIds = m.AttachmentIds + }; +} diff --git a/scr/Messenger.Api/Endpoints/UserEndpoints.cs b/scr/Messenger.Api/Endpoints/UserEndpoints.cs new file mode 100644 index 00000000..db68d5c2 --- /dev/null +++ b/scr/Messenger.Api/Endpoints/UserEndpoints.cs @@ -0,0 +1,125 @@ +using System.Text.RegularExpressions; +using Messenger.Api.Models; +using Messenger.Api.Services; +using Microsoft.EntityFrameworkCore; +using Messenger.Api.Data; +using Npgsql; + +namespace Messenger.Api.Endpoints; + +public static class UserEndpoints +{ + public static IEndpointRouteBuilder MapUserEndpoints( + this IEndpointRouteBuilder endpoints) + { + endpoints.MapPost( + "/api/v1/users", + CreateUser); + + endpoints.MapGet( + "/api/v1/users/me", + GetCurrentUser).RequireAuthorization(); + + return endpoints; + } + + private static async Task CreateUser( + CreateUserRequest request, + HttpContext httpContext, + MessengerDbContext db, + IPasswordHasher hasher, + CancellationToken ct) + { + if (!Regex.IsMatch(request.Username, @"\A[a-z0-9_]{3,32}\z")) + { + return ApiErrors.Error(httpContext, 400, "invalid_request", "Некорректный username"); + } + + if (string.IsNullOrWhiteSpace(request.DisplayName) || + ApiErrors.CodePoints(request.DisplayName) > 100) + { + return ApiErrors.Error(httpContext, 400, "invalid_request", "display_name должен содержать от 1 до 100 символов"); + } + + var passwordLength = ApiErrors.CodePoints(request.Password); + if (passwordLength < 12 || passwordLength > 128) + { + return ApiErrors.Error(httpContext, 400, "invalid_request", "Пароль должен содержать от 12 до 128 символов"); + } + + // Быстрый отказ, чтобы не тратить дорогой Argon2 на заведомо занятый username. + // Это только оптимизация: от гонки защищает уникальный индекс (см. catch ниже). + if (await db.Users.AnyAsync(u => u.Username == request.Username, ct)) + { + return ApiErrors.Error(httpContext, 409, "conflict", "Username уже занят"); + } + + // Хеш считается до SaveChanges: соединение с БД не простаивает на CPU-работе. + string passwordHash; + try + { + passwordHash = await hasher.HashAsync(request.Password, ct); + } + catch (PasswordHasherBusyException) + { + return ApiErrors.Error(httpContext, 503, "unavailable", "Сервис временно перегружен, повторите запрос позже"); + } + + var entity = new UserEntity + { + Id = Guid.CreateVersion7(), + Username = request.Username, + DisplayName = request.DisplayName, + PasswordHash = passwordHash, + CreatedAt = Timestamps.UtcNowMilliseconds() + }; + + db.Users.Add(entity); + try + { + await db.SaveChangesAsync(ct); + } + catch (DbUpdateException ex) when ( + ex.InnerException is PostgresException { SqlState: PostgresErrorCodes.UniqueViolation, ConstraintName: "ux_users_username" }) + { + // Параллельный запрос с тем же username успел раньше проверки AnyAsync. + return ApiErrors.Error(httpContext, 409, "conflict", "Username уже занят"); + } + + // В ответ уходит API-модель без password_hash, а не сущность таблицы. + var user = new User + { + Id = entity.Id, + Username = entity.Username, + DisplayName = entity.DisplayName, + CreatedAt = entity.CreatedAt + }; + + return Results.Created($"/api/v1/users/{user.Id}", user); + } + + private static async Task GetCurrentUser( + HttpContext httpContext, + MessengerDbContext db, + CancellationToken ct) + { + var userId = httpContext.GetUserId(); + + var user = await db.Users + .AsNoTracking() + .Where(u => u.Id == userId) + .Select(u => new User + { + Id = u.Id, + Username = u.Username, + DisplayName = u.DisplayName, + CreatedAt = u.CreatedAt + }) + .FirstOrDefaultAsync(ct); + + // Сессия ссылается на пользователя внешним ключом, поэтому null здесь невозможен; ответ всё равно безопасный. + return user is null + ? ApiErrors.Unauthorized(httpContext, BearerAuth.Challenge, "Требуется действительный Bearer-токен") + : Results.Ok(user); + } +} diff --git a/scr/Messenger.Api/Jobs/AttachmentJobs.cs b/scr/Messenger.Api/Jobs/AttachmentJobs.cs new file mode 100644 index 00000000..4941108a --- /dev/null +++ b/scr/Messenger.Api/Jobs/AttachmentJobs.cs @@ -0,0 +1,75 @@ +using Messenger.Api.Data; +using Messenger.Api.Services; +using Microsoft.EntityFrameworkCore; + +namespace Messenger.Api.Jobs; + +public sealed record JobSettings(int MaxAttempts, TimeSpan Timeout, int Concurrency, TimeSpan FailedRetention) +{ + public static JobSettings From(IConfiguration config) + { + var attempts = config.GetValue("JOB_MAX_ATTEMPTS", 5); + var timeout = config.GetValue("JOB_TIMEOUT_SECONDS", 60); + var concurrency = config.GetValue("WORKER_CONCURRENCY", 2); + var retention = config.GetValue("STAGING_RETENTION_SECONDS", 86400); + if (attempts < 1 || timeout < 1 || concurrency < 1 || retention < 0) + throw new InvalidOperationException("Некорректные настройки обработки вложений"); + return new(attempts, TimeSpan.FromSeconds(timeout), concurrency, TimeSpan.FromSeconds(retention)); + } +} + +public sealed record JobMessage(int SchemaVersion, Guid JobId, string Type, Guid AttachmentId, + int PipelineVersion, int Attempt, DateTimeOffset CreatedAt) +{ + public const string ProcessType = "attachment.process.v1"; + public static JobMessage From(AttachmentJobEntity job) => + new(1, job.Id, ProcessType, job.AttachmentId, job.PipelineVersion, job.Attempt, job.CreatedAt); +} + +internal static class AttachmentJobs +{ + // Все изменения состояния используют один порядок блокировок: сначала job, затем attachment. + public static async Task LockAsync(MessengerDbContext db, Guid id, CancellationToken ct) + { + var job = await db.AttachmentJobs.FromSql($"SELECT * FROM attachment_jobs WHERE id = {id} FOR UPDATE") + .SingleOrDefaultAsync(ct); + if (job is not null) + job.Attachment = await LockAttachmentAsync(db, job.AttachmentId, ct); + return job; + } + + public static Task LockAttachmentAsync(MessengerDbContext db, Guid id, CancellationToken ct) => + db.Attachments.FromSql($"SELECT * FROM attachments WHERE id = {id} FOR NO KEY UPDATE").SingleAsync(ct); + + public static void FailAttempt(MessengerDbContext db, AttachmentJobEntity job, JobSettings settings, + string code, bool permanent) + { + var now = Timestamps.UtcNowMilliseconds(); + job.LeaseUntil = null; + job.Attachment.UpdatedAt = now; + var used = job.Attempt - job.FirstAttempt + 1; + if (permanent || used >= settings.MaxAttempts) + { + job.Attachment.Status = "failed"; + job.Attachment.ErrorCode = permanent ? code : "retry_exhausted"; + ScheduleCleanup(db, job, now + settings.FailedRetention); + return; + } + job.Attempt++; + job.Attachment.Status = "queued"; + var delay = Math.Min(30, Math.Pow(2, used - 1)); + job.NextAttemptAt = now.AddSeconds(delay + Random.Shared.NextDouble() * delay * 0.25); + job.PublishedAt = null; + } + + public static void ScheduleCleanup(MessengerDbContext db, AttachmentJobEntity job, DateTimeOffset after) + { + // При переносе из ЛР4 источником служит сам постоянный оригинал. + if (job.SourceKey != $"staging/{job.AttachmentId:N}") return; + db.UploadIntents.Add(new UploadIntentEntity + { + Id = job.AttachmentId, ObjectKey = job.SourceKey, CreatedAt = Timestamps.UtcNowMilliseconds(), + ExpiresAt = after, NextAttemptAt = after + }); + } +} diff --git a/scr/Messenger.Api/Jobs/AttachmentProcessor.cs b/scr/Messenger.Api/Jobs/AttachmentProcessor.cs new file mode 100644 index 00000000..6853c61d --- /dev/null +++ b/scr/Messenger.Api/Jobs/AttachmentProcessor.cs @@ -0,0 +1,108 @@ +using System.Security.Cryptography; +using Messenger.Api.Data; +using Messenger.Api.Services; +using Microsoft.EntityFrameworkCore; + +namespace Messenger.Api.Jobs; + +public sealed class AttachmentProcessor(MessengerDbContext db, IAttachmentStorage storage, + JobSettings settings, UploadSettings limits, ILogger logger) +{ + public async Task ProcessAsync(JobMessage message, CancellationToken stopping) + { + var job = await ClaimAsync(message, stopping); + if (job is null) return; + + using var deadline = CancellationTokenSource.CreateLinkedTokenSource(stopping); + deadline.CancelAfter(settings.Timeout); + var ct = deadline.Token; + try + { + var attachment = job.Attachment; + JobFaultInjection.At("transient", attachment.Id); + using var original = new LimitedDownloadStream(Math.Min(attachment.SizeBytes, limits.MaxBytes)); + await storage.CopyToAsync(job.SourceKey, original, ct); + original.Position = 0; + if (original.Length != attachment.SizeBytes || + Convert.ToHexStringLower(await SHA256.HashDataAsync(original, ct)) != attachment.ChecksumSha256) + throw new InvalidDataException("Source checksum mismatch"); + var variants = await ImageRenderer.RenderAsync(original, attachment.ContentType, limits.MaxPixels, message.PipelineVersion, ct); + ct.ThrowIfCancellationRequested(); + await PublishResultAsync(message, original, variants, ct); + } + catch (Exception ex) when (!stopping.IsCancellationRequested) + { + logger.LogWarning("Job {JobId} attempt {Attempt} failed ({Kind})", + message.JobId, message.Attempt, ex.GetType().Name); + db.ChangeTracker.Clear(); + await using var tx = await db.Database.BeginTransactionAsync(stopping); + var current = await AttachmentJobs.LockAsync(db, message.JobId, stopping); + if (OwnsAttempt(current, message)) + { + var permanent = ex is InvalidDataException; + AttachmentJobs.FailAttempt(db, current!, settings, "invalid_image", permanent); + await db.SaveChangesAsync(stopping); + } + await tx.CommitAsync(stopping); + } + } + + private async Task ClaimAsync(JobMessage message, CancellationToken ct) + { + await using var tx = await db.Database.BeginTransactionAsync(ct); + var job = await AttachmentJobs.LockAsync(db, message.JobId, ct); + if (job is null || job.AttachmentId != message.AttachmentId || job.PipelineVersion != message.PipelineVersion || + job.Attempt != message.Attempt || job.Attachment.PipelineVersion != message.PipelineVersion || + job.Attachment.Status != "queued") + return null; + var now = Timestamps.UtcNowMilliseconds(); + job.Attachment.Status = "processing"; + job.Attachment.UpdatedAt = now; + job.PublishedAt ??= now; + job.LeaseUntil = now + settings.Timeout; + await db.SaveChangesAsync(ct); + await tx.CommitAsync(ct); + return job; + } + + private static bool OwnsAttempt(AttachmentJobEntity? job, JobMessage message) => + job is not null && job.Attempt == message.Attempt && job.Attachment.PipelineVersion == message.PipelineVersion && + job.Attachment.Status == "processing"; + + private async Task PublishResultAsync(JobMessage message, Stream original, ImageVariant[] variants, CancellationToken ct) + { + db.ChangeTracker.Clear(); + await using var tx = await db.Database.BeginTransactionAsync(ct); + var job = await AttachmentJobs.LockAsync(db, message.JobId, ct); + if (!OwnsAttempt(job, message)) return; + var attachment = job!.Attachment; + JobFaultInjection.At("before-write", attachment.Id); + // Устаревшая попытка не может писать в S3 после захвата работы другой попыткой. + if (job.SourceKey != attachment.ObjectKey) + { + original.Position = 0; + await storage.PutAsync(attachment.ObjectKey, original, attachment.ContentType, ct, createOnly: true); + } + foreach (var variant in variants) + { + var extension = variant.ContentType == "image/webp" ? "webp" : "jpg"; + var key = $"variants/{attachment.Id:N}/v{job.PipelineVersion}/{variant.Name}.{extension}"; + using var file = new MemoryStream(variant.Bytes, writable: false); + await storage.PutAsync(key, file, variant.ContentType, ct, createOnly: true); + db.AttachmentVariants.Add(new AttachmentVariantEntity + { + AttachmentId = attachment.Id, PipelineVersion = job.PipelineVersion, Name = variant.Name, + ObjectKey = key, ContentType = variant.ContentType, Width = variant.Width, Height = variant.Height, + SizeBytes = file.Length, Sha256 = Convert.ToHexStringLower(SHA256.HashData(variant.Bytes)) + }); + } + JobFaultInjection.At("after-write", attachment.Id); + var now = Timestamps.UtcNowMilliseconds(); + attachment.Status = "ready"; + attachment.UpdatedAt = now; + job.LeaseUntil = null; + AttachmentJobs.ScheduleCleanup(db, job, now); + await db.SaveChangesAsync(ct); + await tx.CommitAsync(ct); + } +} diff --git a/scr/Messenger.Api/Jobs/AttachmentQueue.cs b/scr/Messenger.Api/Jobs/AttachmentQueue.cs new file mode 100644 index 00000000..9746f934 --- /dev/null +++ b/scr/Messenger.Api/Jobs/AttachmentQueue.cs @@ -0,0 +1,99 @@ +using System.Text.Json; +using Messenger.Api.Data; +using Microsoft.EntityFrameworkCore; +using RabbitMQ.Client; + +namespace Messenger.Api.Jobs; + +internal sealed class AttachmentQueue(ConnectionFactory connections, IServiceScopeFactory scopes, + JobSettings settings, bool publisher, ILogger logger) : BackgroundService +{ + internal const string QueueName = "attachments.v1"; + private static readonly JsonSerializerOptions WireFormat = new() { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower }; + + protected override Task ExecuteAsync(CancellationToken stoppingToken) => + Task.WhenAll(Enumerable.Range(0, publisher ? 1 : settings.Concurrency).Select(_ => RunChannelAsync(stoppingToken))); + + private async Task RunChannelAsync(CancellationToken ct) + { + while (!ct.IsCancellationRequested) + { + try + { + await using var connection = await connections.CreateConnectionAsync(ct); + var options = new CreateChannelOptions(publisherConfirmationsEnabled: publisher, + publisherConfirmationTrackingEnabled: publisher); + await using var channel = await connection.CreateChannelAsync(options, ct); + await channel.QueueDeclareAsync(QueueName, durable: true, exclusive: false, autoDelete: false, + arguments: new Dictionary { ["x-queue-type"] = "classic" }, cancellationToken: ct); + while (channel.IsOpen && !ct.IsCancellationRequested) + { + var didWork = publisher ? await PublishNextAsync(channel, ct) : await ConsumeNextAsync(channel, ct); + if (!didWork) await Task.Delay(400, ct); + } + } + catch (Exception ex) when (!ct.IsCancellationRequested) + { + // Закрытие канала возвращает брокеру все доставки, которым worker ещё не послал ack. + logger.LogWarning("Attachment queue reconnecting after {Kind}", ex.GetType().Name); + await Task.Delay(TimeSpan.FromSeconds(2), ct); + } + } + } + + private async Task PublishNextAsync(IChannel channel, CancellationToken ct) + { + using var scope = scopes.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await using var tx = await db.Database.BeginTransactionAsync(ct); + var job = await db.AttachmentJobs.FromSqlRaw(""" + SELECT * FROM attachment_jobs + WHERE (published_at IS NULL AND next_attempt_at <= clock_timestamp()) + OR lease_until <= clock_timestamp() + ORDER BY next_attempt_at, id LIMIT 1 FOR UPDATE SKIP LOCKED + """).SingleOrDefaultAsync(ct); + if (job is null) return false; + if (job.LeaseUntil.HasValue) + { + job.Attachment = await AttachmentJobs.LockAttachmentAsync(db, job.AttachmentId, ct); + AttachmentJobs.FailAttempt(db, job, settings, "processing_timeout", permanent: false); + } + else + { + JobFaultInjection.At("before-publish", job.AttachmentId); + var payload = JsonSerializer.SerializeToUtf8Bytes(JobMessage.From(job), WireFormat); + var properties = new BasicProperties { Persistent = true, ContentType = "application/json", MessageId = job.Id.ToString() }; + using var confirm = CancellationTokenSource.CreateLinkedTokenSource(ct); + confirm.CancelAfter(TimeSpan.FromSeconds(5)); + await channel.BasicPublishAsync("", QueueName, mandatory: true, properties, payload, confirm.Token); + job.PublishedAt = DateTimeOffset.UtcNow; + } + await db.SaveChangesAsync(ct); + await tx.CommitAsync(ct); + return true; + } + + private async Task ConsumeNextAsync(IChannel channel, CancellationToken ct) + { + // Один неподтверждённый файл на канал. Каждый параллельный обработчик имеет собственный канал. + var delivery = await channel.BasicGetAsync(QueueName, autoAck: false, ct); + if (delivery is null) return false; + JobMessage? message; + try { message = JsonSerializer.Deserialize(delivery.Body.Span, WireFormat); } + catch (JsonException) { message = null; } + if (message is not { SchemaVersion: 1, Type: JobMessage.ProcessType, PipelineVersion: 1 or 2, Attempt: >= 1 } || + message.JobId == Guid.Empty || message.AttachmentId == Guid.Empty || message.CreatedAt == default) + { + logger.LogWarning("Discarded malformed attachment job"); + await channel.BasicRejectAsync(delivery.DeliveryTag, requeue: false, ct); + return true; + } + using var scope = scopes.CreateScope(); + await scope.ServiceProvider.GetRequiredService().ProcessAsync(message, ct); + JobFaultInjection.At("before-ack", message.AttachmentId, message.Attempt); + await channel.BasicAckAsync(delivery.DeliveryTag, multiple: false, ct); + logger.LogInformation("Ack job {JobId} attempt {Attempt} redelivered {Redelivered}", + message.JobId, message.Attempt, delivery.Redelivered); + return true; + } +} diff --git a/scr/Messenger.Api/Jobs/ImageRenderer.cs b/scr/Messenger.Api/Jobs/ImageRenderer.cs new file mode 100644 index 00000000..ea4c70fe --- /dev/null +++ b/scr/Messenger.Api/Jobs/ImageRenderer.cs @@ -0,0 +1,79 @@ +using System.Diagnostics; +using System.Globalization; +using System.Text.Json; +using ImageMagick; +using Messenger.Api.Services; + +namespace Messenger.Api.Jobs; + +internal static class ImageRenderer +{ + public static async Task RenderAsync(Stream input, string mime, long maxPixels, int version, + CancellationToken ct) + { + // Нативное декодирование выполняется в дочернем процессе, который можно завершить по дедлайну. + var start = new ProcessStartInfo(Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? "dotnet") + { + RedirectStandardInput = true, RedirectStandardOutput = true, UseShellExecute = false + }; + start.ArgumentList.Add(typeof(ImageRenderer).Assembly.Location); + start.ArgumentList.Add("--render-attachment"); + start.ArgumentList.Add(mime); + start.ArgumentList.Add(maxPixels.ToString(CultureInfo.InvariantCulture)); + start.ArgumentList.Add(version.ToString(CultureInfo.InvariantCulture)); + using var process = Process.Start(start) ?? throw new IOException("Cannot start image renderer"); + try + { + var response = process.StandardOutput.ReadToEndAsync(ct); + input.Position = 0; + try + { + await input.CopyToAsync(process.StandardInput.BaseStream, ct); + process.StandardInput.Close(); + } + catch (IOException) + { + // Дочерний процесс может завершиться до окончания передачи. + process.StandardInput.Close(); + } + await process.WaitForExitAsync(ct); + var json = await response; + return process.ExitCode switch + { + 0 => JsonSerializer.Deserialize(json) ?? throw new IOException("Empty renderer result"), + 2 => throw new InvalidDataException("Invalid image"), + _ => throw new IOException($"Image renderer exit code {process.ExitCode}") + }; + } + finally + { + if (!process.HasExited) + { + try { process.Kill(entireProcessTree: true); } + catch (InvalidOperationException) { } + await process.WaitForExitAsync(); + } + } + } + + public static async Task RunAsync(string mime, long maxPixels, int version) + { + try + { + using var original = new LimitedDownloadStream(10485760); + await Console.OpenStandardInput().CopyToAsync(original); + var result = ImageVariant.CreateAll(original, mime, maxPixels, version); + await JsonSerializer.SerializeAsync(Console.OpenStandardOutput(), result); + return 0; + } + catch (Exception ex) when (ex is InvalidDataException or MagickCorruptImageErrorException or MagickCoderErrorException) + { + return 2; + } + catch (Exception ex) + { + Console.Error.WriteLine($"Image renderer: {ex.GetType().Name}"); + return 3; + } + } +} diff --git a/scr/Messenger.Api/Jobs/ImageVariant.cs b/scr/Messenger.Api/Jobs/ImageVariant.cs new file mode 100644 index 00000000..b2aceefe --- /dev/null +++ b/scr/Messenger.Api/Jobs/ImageVariant.cs @@ -0,0 +1,59 @@ +using ImageMagick; +using StbImageSharp; + +namespace Messenger.Api.Jobs; + +public sealed record ImageVariant(string Name, string ContentType, byte[] Bytes, int Width, int Height) +{ + public static ImageVariant[] CreateAll(Stream original, string mime, long maxPixels, int version) + { + if (version is not (1 or 2) || mime is not ("image/png" or "image/jpeg")) + throw new InvalidDataException("Unsupported image or pipeline version"); + original.Position = 0; + var header = ImageInfo.FromStream(original); + if (header is null || header.Value.Width <= 0 || header.Value.Height <= 0 || + (long)header.Value.Width * header.Value.Height > maxPixels) + throw new InvalidDataException("Invalid image dimensions"); + original.Position = 0; + var read = new MagickReadSettings + { + Format = mime == "image/png" ? MagickFormat.Png : MagickFormat.Jpeg, FrameCount = 1 + }; + using var image = new MagickImage(original, read); + if (image.Width != header.Value.Width || image.Height != header.Value.Height) + throw new InvalidDataException("Image dimensions changed during decode"); + image.AutoOrient(); + image.Strip(); + + using var thumbnail = image.Clone(); + Fit(thumbnail, 256); + using var crop = image.Clone(); + var side = Math.Min(crop.Width, crop.Height); + crop.Crop(side, side, Gravity.Center); + crop.ResetPage(); + crop.Resize(128, 128); + + Fit(image, 1280); + image.Quality = version == 1 ? 78u : 86u; + return [EncodeJpeg(thumbnail, "thumbnail", version == 1 ? 85u : 92u), + EncodeJpeg(crop, "crop", 85), + new ImageVariant("optimized", "image/webp", image.ToByteArray(MagickFormat.WebP), (int)image.Width, (int)image.Height)]; + } + + private static void Fit(IMagickImage image, uint limit) + { + var longest = Math.Max(image.Width, image.Height); + if (longest <= limit) return; + var width = (uint)Math.Max(1L, image.Width * (long)limit / longest); + var height = (uint)Math.Max(1L, image.Height * (long)limit / longest); + image.Resize(new MagickGeometry(width, height) { IgnoreAspectRatio = true }); + } + + private static ImageVariant EncodeJpeg(IMagickImage image, string name, uint quality) + { + image.BackgroundColor = MagickColors.White; + image.Alpha(AlphaAction.Remove); + image.Quality = quality; + return new(name, "image/jpeg", image.ToByteArray(MagickFormat.Jpeg), (int)image.Width, (int)image.Height); + } +} diff --git a/scr/Messenger.Api/Jobs/JobFaultInjection.cs b/scr/Messenger.Api/Jobs/JobFaultInjection.cs new file mode 100644 index 00000000..5e54f674 --- /dev/null +++ b/scr/Messenger.Api/Jobs/JobFaultInjection.cs @@ -0,0 +1,13 @@ +namespace Messenger.Api.Jobs; + +internal static class JobFaultInjection +{ + public static void At(string stage, Guid attachmentId, int? attempt = null) + { + var target = attempt is null ? $"{stage}:{attachmentId:D}" : $"{stage}:{attachmentId:D}:{attempt}"; + if (Environment.GetEnvironmentVariable("LAB5_TEST_FAULT") != target) return; + Console.Error.WriteLine($"Injected fault {stage} for {attachmentId:D}"); + if (stage == "transient") throw new IOException("Injected storage error"); + Environment.Exit(71); + } +} diff --git a/scr/Messenger.Api/Jobs/JobOperations.cs b/scr/Messenger.Api/Jobs/JobOperations.cs new file mode 100644 index 00000000..bc4bfe13 --- /dev/null +++ b/scr/Messenger.Api/Jobs/JobOperations.cs @@ -0,0 +1,85 @@ +using Messenger.Api.Data; +using Messenger.Api.Services; +using Microsoft.EntityFrameworkCore; + +namespace Messenger.Api.Jobs; + +internal static class JobOperations +{ + public static async Task RunAsync(string action, Guid id = default) + { + var config = Host.CreateApplicationBuilder().Configuration; + var options = new DbContextOptionsBuilder() + .UseNpgsql(DatabaseSettings.From(config).ConnectionString).UseSnakeCaseNamingConvention().Options; + await using var db = new MessengerDbContext(options); + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(15)); + var ct = timeout.Token; + + if (action == "--failed-jobs") + { + var failed = await db.AttachmentJobs.Where(j => j.Attachment.Status == "failed" && + j.Attachment.PipelineVersion == j.PipelineVersion).OrderByDescending(j => j.Attachment.UpdatedAt) + .Take(100).Select(j => new { j.Id, j.AttachmentId, j.PipelineVersion, j.Attempt, j.Attachment.ErrorCode }).ToListAsync(ct); + foreach (var job in failed) + Console.WriteLine($"{job.Id} attachment={job.AttachmentId} version={job.PipelineVersion} attempt={job.Attempt} code={job.ErrorCode}"); + return 0; + } + + await using var tx = await db.Database.BeginTransactionAsync(ct); + var now = Timestamps.UtcNowMilliseconds(); + if (action == "--replay-job") + { + var job = await AttachmentJobs.LockAsync(db, id, ct); + if (job is null || job.Attachment.Status != "failed" || job.Attachment.PipelineVersion != job.PipelineVersion) + return Reject("Job must be the failed current version"); + if (job.SourceKey != job.Attachment.ObjectKey) + { + var intent = await db.UploadIntents.FromSql($""" + SELECT * FROM upload_intents WHERE id = {job.AttachmentId} + AND expires_at > clock_timestamp() FOR UPDATE + """).SingleOrDefaultAsync(ct); + if (intent is null) return Reject("The staged original is outside its retention window"); + db.UploadIntents.Remove(intent); + } + job.Attempt = checked(job.Attempt + 1); + job.FirstAttempt = job.Attempt; + job.ReplayedAt = now; + job.NextAttemptAt = now; + job.PublishedAt = null; + SetQueued(job.Attachment, now); + } + else + { + var attachment = await db.Attachments.FromSql($"SELECT * FROM attachments WHERE id = {id} FOR NO KEY UPDATE") + .SingleOrDefaultAsync(ct); + if (attachment is not { Status: "ready", PipelineVersion: 1 }) + return Reject("Version 2 requires a ready version 1"); + attachment.PipelineVersion = 2; + SetQueued(attachment, now); + var job = new AttachmentJobEntity + { + Id = Guid.CreateVersion7(), AttachmentId = id, PipelineVersion = 2, SourceKey = attachment.ObjectKey, + CreatedAt = now, NextAttemptAt = now + }; + db.AttachmentJobs.Add(job); + id = job.Id; + } + await db.SaveChangesAsync(ct); + await tx.CommitAsync(ct); + Console.WriteLine($"Queued job {id}"); + return 0; + } + + private static void SetQueued(AttachmentEntity attachment, DateTimeOffset now) + { + attachment.Status = "queued"; + attachment.ErrorCode = null; + attachment.UpdatedAt = now; + } + + private static int Reject(string message) + { + Console.Error.WriteLine(message); + return 2; + } +} diff --git a/scr/Messenger.Api/Jobs/QueueHost.cs b/scr/Messenger.Api/Jobs/QueueHost.cs new file mode 100644 index 00000000..6a9e4cb2 --- /dev/null +++ b/scr/Messenger.Api/Jobs/QueueHost.cs @@ -0,0 +1,37 @@ +using Messenger.Api.Data; +using Messenger.Api.Services; +using Microsoft.EntityFrameworkCore; +using RabbitMQ.Client; + +namespace Messenger.Api.Jobs; + +internal static class QueueHost +{ + public static async Task RunAsync(bool publisher) + { + var builder = Host.CreateApplicationBuilder(); + var config = builder.Configuration; + var urlFile = config["BROKER_URL_FILE"] ?? throw new InvalidOperationException("BROKER_URL_FILE не задан"); + var connections = new ConnectionFactory + { + Uri = new Uri(File.ReadAllText(urlFile).Trim()), AutomaticRecoveryEnabled = false, + RequestedConnectionTimeout = TimeSpan.FromSeconds(5) + }; + var settings = JobSettings.From(config); + var database = DatabaseSettings.From(config); + builder.Logging.AddFilter("Microsoft.EntityFrameworkCore.Database.Command", LogLevel.Warning); + builder.Services.AddSingleton(settings); + builder.Services.AddDbContext(options => + options.UseNpgsql(database.ConnectionString).UseSnakeCaseNamingConvention()); + if (!publisher) + { + builder.Services.AddSingleton(UploadSettings.From(config)); + builder.Services.AddSingleton(_ => new S3AttachmentStorage(S3Settings.From(config))); + builder.Services.AddScoped(); + } + builder.Services.AddHostedService(sp => new AttachmentQueue(connections, + sp.GetRequiredService(), settings, publisher, sp.GetRequiredService>())); + using var host = builder.Build(); + await host.RunAsync(); + } +} diff --git a/scr/Messenger.Api/Messenger.Api.csproj b/scr/Messenger.Api/Messenger.Api.csproj new file mode 100644 index 00000000..b8006759 --- /dev/null +++ b/scr/Messenger.Api/Messenger.Api.csproj @@ -0,0 +1,29 @@ + + + + net10.0 + enable + enable + + + + + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + + + diff --git a/scr/Messenger.Api/Models/Attachment.cs b/scr/Messenger.Api/Models/Attachment.cs new file mode 100644 index 00000000..5b1eea67 --- /dev/null +++ b/scr/Messenger.Api/Models/Attachment.cs @@ -0,0 +1,9 @@ +namespace Messenger.Api.Models; + +public sealed record Attachment( + Guid Id, Guid ChatId, Guid OwnerId, string Filename, string ContentType, + long SizeBytes, string Sha256, string Status, AttachmentVariant[] Variants, + string? ErrorCode, DateTimeOffset CreatedAt, DateTimeOffset UpdatedAt); + +public sealed record AttachmentVariant(string Name, string ContentType, long SizeBytes, + int Width, int Height, string Sha256); diff --git a/scr/Messenger.Api/Models/Chat.cs b/scr/Messenger.Api/Models/Chat.cs new file mode 100644 index 00000000..71777680 --- /dev/null +++ b/scr/Messenger.Api/Models/Chat.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Messenger.Api.Models +{ + public sealed class Chat + { + public Guid Id { get; init; } + public string Title { get; init; } = String.Empty; + public List MemberIds { get; init; } = new List(); + public DateTimeOffset CreatedAt { get; init; } + } +} diff --git a/scr/Messenger.Api/Models/CreateChatRequest.cs b/scr/Messenger.Api/Models/CreateChatRequest.cs new file mode 100644 index 00000000..8b2e4611 --- /dev/null +++ b/scr/Messenger.Api/Models/CreateChatRequest.cs @@ -0,0 +1,6 @@ +namespace Messenger.Api.Models +{ + public sealed record CreateChatRequest( + [property: System.Text.Json.Serialization.JsonRequired] string Title, + [property: System.Text.Json.Serialization.JsonRequired] List MemberIds); +} diff --git a/scr/Messenger.Api/Models/CreateMessageRequest.cs b/scr/Messenger.Api/Models/CreateMessageRequest.cs new file mode 100644 index 00000000..1c56d91e --- /dev/null +++ b/scr/Messenger.Api/Models/CreateMessageRequest.cs @@ -0,0 +1,6 @@ +namespace Messenger.Api.Models; + +public sealed record CreateMessageRequest([property: System.Text.Json.Serialization.JsonRequired] string Text) +{ + public Guid[] AttachmentIds { get; init; } = []; +} diff --git a/scr/Messenger.Api/Models/CreateUserRequest.cs b/scr/Messenger.Api/Models/CreateUserRequest.cs new file mode 100644 index 00000000..49415b63 --- /dev/null +++ b/scr/Messenger.Api/Models/CreateUserRequest.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Messenger.Api.Models +{ + public sealed record CreateUserRequest( + [property: System.Text.Json.Serialization.JsonRequired] string Username, + [property: System.Text.Json.Serialization.JsonRequired] string DisplayName, + [property: System.Text.Json.Serialization.JsonRequired] string Password); + +} diff --git a/scr/Messenger.Api/Models/Message.cs b/scr/Messenger.Api/Models/Message.cs new file mode 100644 index 00000000..6216ea7c --- /dev/null +++ b/scr/Messenger.Api/Models/Message.cs @@ -0,0 +1,17 @@ +using Microsoft.AspNetCore.Http.HttpResults; +using System; +using System.Collections.Generic; +using System.Text; + +namespace Messenger.Api.Models +{ + public sealed class Message + { + public Guid Id { get; init; } + public Guid ChatId { get; init; } + public Guid SenderId { get; init; } + public string Text { get; init; } = String.Empty; + public DateTimeOffset CreatedAt { get; init; } + public Guid[] AttachmentIds { get; init; } = []; + } +} diff --git a/scr/Messenger.Api/Models/SessionResponse.cs b/scr/Messenger.Api/Models/SessionResponse.cs new file mode 100644 index 00000000..7c3b7bf1 --- /dev/null +++ b/scr/Messenger.Api/Models/SessionResponse.cs @@ -0,0 +1,7 @@ +namespace Messenger.Api.Models; + +public sealed record SessionResponse( + string Token, + string TokenType, + DateTimeOffset ExpiresAt, + User User); diff --git a/scr/Messenger.Api/Models/User.cs b/scr/Messenger.Api/Models/User.cs new file mode 100644 index 00000000..bb088c33 --- /dev/null +++ b/scr/Messenger.Api/Models/User.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Messenger.Api.Models +{ + public sealed class User + { + public Guid Id { get; init; } + public string Username { get; init; } = string.Empty; + public string DisplayName { get; init; } = string.Empty; + public DateTimeOffset CreatedAt { get; init; } + } +} diff --git a/scr/Messenger.Api/Program.cs b/scr/Messenger.Api/Program.cs new file mode 100644 index 00000000..d0ca7dd2 --- /dev/null +++ b/scr/Messenger.Api/Program.cs @@ -0,0 +1,295 @@ +using Microsoft.AspNetCore.Diagnostics; +using Messenger.Api.Endpoints; +using Messenger.Api.Services; +using Messenger.Api.Data; +using Messenger.Api.Jobs; +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using Microsoft.AspNetCore.Authentication; + +if (args is ["--render-attachment", var mime, var pixels, var pipeline]) + return await ImageRenderer.RunAsync(mime, long.Parse(pixels), int.Parse(pipeline)); + +if (args is ["--failed-jobs"]) + return await JobOperations.RunAsync(args[0]); + +if (args is ["--replay-job" or "--upgrade-attachment", var identifier]) + return Guid.TryParse(identifier, out var id) ? await JobOperations.RunAsync(args[0], id) : 2; + +if (args is ["--worker"] or ["--dispatch"]) +{ + await QueueHost.RunAsync(publisher: args[0] == "--dispatch"); + return 0; +} + +// Режим для Docker HEALTHCHECK: в образе aspnet нет curl, поэтому проверку выполняет само приложение. +if (args.Contains("--healthcheck")) +{ + var port = Environment.GetEnvironmentVariable("APP_PORT") ?? "8080"; + try + { + using var probe = new HttpClient { Timeout = TimeSpan.FromSeconds(2) }; + var probeResponse = await probe.GetAsync($"http://127.0.0.1:{port}/health/live"); + return probeResponse.IsSuccessStatusCode ? 0 : 1; + } + catch (Exception) + { + return 1; + } +} + +var builder = WebApplication.CreateBuilder(args); + +// SIGTERM: сначала drain (SHUTDOWN_DRAIN_SECONDS, /health/ready → 503, запросы ещё принимаются), затем слушатель +// закрывается и активные запросы получают не более 5 секунд. Итого < 10 секунд (лимит задания) и < stop_grace_period. +builder.Services.Configure(options => options.ShutdownTimeout = TimeSpan.FromSeconds(5)); + +// Настройки читаются лениво из IConfiguration (после Build), поэтому тесты могут задавать их через UseSetting. +builder.Services.AddSingleton(sp => DatabaseSettings.From(sp.GetRequiredService())); +builder.Services.AddSingleton(sp => AuthSessionOptions.From(sp.GetRequiredService())); +builder.Services.AddSingleton(sp => CacheSettings.From(sp.GetRequiredService())); +builder.Services.AddSingleton(sp => DiagnosticsSettings.From(sp.GetRequiredService())); +builder.Services.AddSingleton(sp => InstanceSettings.From(sp.GetRequiredService())); +builder.Services.AddSingleton(sp => IdempotencySettings.From(sp.GetRequiredService())); +builder.Services.AddSingleton(sp => S3Settings.From(sp.GetRequiredService())); +builder.Services.AddSingleton(sp => UploadSettings.From(sp.GetRequiredService())); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(sp => UploadCleanupSettings.From(sp.GetRequiredService())); +builder.Services.AddSingleton(); +builder.Services.AddHostedService(); +builder.Services.AddSingleton(sp => +{ + var s3Settings = sp.GetRequiredService(); + return new S3AttachmentStorage(s3Settings); +}); +builder.Services.AddSingleton(); +builder.Services.AddHostedService(); +builder.Services.AddHttpContextAccessor(); +builder.Services.AddSingleton(); +builder.Services.AddDbContext((sp, options) => +{ + options.UseNpgsql(sp.GetRequiredService().ConnectionString) + .UseSnakeCaseNamingConvention(); + if (sp.GetRequiredService().Headers) + { + options.AddInterceptors(sp.GetRequiredService()); + } +}); +builder.Services.AddSingleton(sp => PasswordHashingSettings.From(sp.GetRequiredService())); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(sp => +{ + var settings = sp.GetRequiredService(); + return settings.Enabled + ? new ValkeyMessageHistoryCache(settings, sp.GetRequiredService>()) + : new NullMessageHistoryCache(); +}); +builder.Services.AddAuthentication(BearerAuth.Scheme) + .AddScheme(BearerAuth.Scheme, null); +builder.Services.AddAuthorization(); +builder.Services.ConfigureHttpJsonOptions(options => +{ + options.SerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower; + options.SerializerOptions.Converters.Add(new UtcDateTimeOffsetJsonConverter()); + options.SerializerOptions.UnmappedMemberHandling = System.Text.Json.Serialization.JsonUnmappedMemberHandling.Disallow; + options.SerializerOptions.RespectNullableAnnotations = true; + // Web-настройки по умолчанию включают регистронезависимое сопоставление имён: контракт его не допускает. + options.SerializerOptions.PropertyNameCaseInsensitive = false; +}); + +var app = builder.Build(); + +// Режим one-shot миграции (`dotnet Messenger.Api.dll --migrate`): отдельный контейнер применяет схему и завершается. +// API-реплики схему не меняют, поэтому одновременный старт N реплик не создаёт гонку миграций. +if (args.Contains("--migrate")) +{ + using var migrationScope = app.Services.CreateScope(); + migrationScope.ServiceProvider.GetRequiredService().Database.Migrate(); + app.Logger.LogInformation("Migrations applied"); + return 0; +} + +if (args.Contains("--cleanup-uploads")) +{ + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(25)); + var result = await app.Services.GetRequiredService().RunOnceAsync(timeout.Token); + Console.WriteLine(JsonSerializer.Serialize(result)); + return 0; +} + +// Только для локального запуска и тестов (MIGRATE_ON_START=true); в Compose выключено. +if (app.Services.GetRequiredService().MigrateOnStart) +{ + using var scope = app.Services.CreateScope(); + scope.ServiceProvider.GetRequiredService().Database.Migrate(); +} + +// Диагностика (только при DIAGNOSTIC_HEADERS=true): число SQL-команд EF Core за запрос — в заголовке X-Db-Queries. +if (app.Services.GetRequiredService().Headers) +{ + app.Use(async (context, next) => + { + var counter = new QueryCounter(); + context.Items[QueryCountingInterceptor.ItemKey] = counter; + context.Response.OnStarting(() => + { + context.Response.Headers["X-Db-Queries"] = Volatile.Read(ref counter.Count).ToString(); + return Task.CompletedTask; + }); + await next(); + }); +} + +// X-Instance-Id в каждом ответе API (включая ошибки и health). Заголовок ставится в OnStarting: UseExceptionHandler +// очищает заголовки, а этот обратный вызов срабатывает уже после очистки, перед отправкой ответа. +var instanceId = app.Services.GetRequiredService().InstanceId; +app.Use(async (context, next) => +{ + context.Response.OnStarting(() => + { + context.Response.Headers["X-Instance-Id"] = instanceId; + return Task.CompletedTask; + }); + await next(); +}); + +app.Use(async (context, next) => +{ + var requestId = Guid.NewGuid().ToString(); + context.Items["request_id"] = requestId; + context.Response.Headers["X-Request-Id"] = requestId; + await next(); +}); + +// Лог запроса: метод, путь, статус, время, request_id. Тело и query не логируются. +app.Use(async (context, next) => +{ + var logger = context.RequestServices.GetRequiredService().CreateLogger("Messenger.Requests"); + var started = System.Diagnostics.Stopwatch.GetTimestamp(); + try + { + await next(); + } + finally + { + logger.LogInformation( + "{Method} {Path} -> {Status} in {ElapsedMs:0.0} ms (request_id={RequestId})", + context.Request.Method, + context.Request.Path.Value, + context.Response.StatusCode, + System.Diagnostics.Stopwatch.GetElapsedTime(started).TotalMilliseconds, + context.Items["request_id"]); + } +}); + +app.UseExceptionHandler(errorApp => errorApp.Run(context => +{ + // В Development ошибки чтения запроса приходят исключением: сохраняем их 400/415 вместо 500. + var error = context.Features.Get()?.Error; + if (error is BadHttpRequestException { StatusCode: 413 } tooLarge) + return ApiErrors.Error(context, 413, "payload_too_large", "Файл превышает лимит размера").ExecuteAsync(context); + if (error is BadHttpRequestException { StatusCode: 400 or 415 } badRequest) + { + var (code, message) = badRequest.StatusCode == 415 + ? ("unsupported_media_type", "Требуется Content-Type: application/json") + : ("invalid_request", "Некорректный запрос"); + return ApiErrors.Error(context, badRequest.StatusCode, code, message).ExecuteAsync(context); + } + + // PostgreSQL недоступен или перегружен: ограниченный ответ 503 без внутренних деталей (стек и SQL только в логе). + if (DependencyFailures.IsDatabaseUnavailable(error) || error is Amazon.S3.AmazonS3Exception or HttpRequestException) + { + return ApiErrors.Error(context, 503, "unavailable", "Сервис временно недоступен").ExecuteAsync(context); + } + + return ApiErrors.Error(context, 500, "internal_error", "Внутренняя ошибка сервера").ExecuteAsync(context); +})); + +// Пустые ответы 400/404/415 (ошибки привязки, неизвестный маршрут) получают стандартное тело ошибки. +app.UseStatusCodePages(context => +{ + var http = context.HttpContext; + var (code, message) = http.Response.StatusCode switch + { + 400 => ("invalid_request", "Некорректный запрос"), + 404 => ("not_found", "Объект не найден"), + 415 => ("unsupported_media_type", "Требуется Content-Type: application/json"), + 413 => ("payload_too_large", "Файл превышает лимит размера"), + 503 => ("unavailable", "Сервис временно недоступен"), + _ => ("internal_error", "Ошибка запроса") + }; + return ApiErrors.Error(http, http.Response.StatusCode, code, message).ExecuteAsync(http); +}); + +// Аутентификация (Bearer) выполняется до выбора обработчика и разбора тела: 401 приоритетнее 400/404. +app.UseAuthentication(); +app.UseAuthorization(); + +app.MapGet("/health/live", () => +{ + return Results.Ok(new + { + status = "ok" + }); +}); + +// Готовность = API может обслуживать обязательный синхронный путь, а он требует PostgreSQL (сессии, данные, ключи +// идемпотентности), а загрузки требуют S3. Valkey не критичен: без него чтение идёт напрямую из PostgreSQL. После SIGTERM — всегда 503: +// балансировщик выводит экземпляр из ротации ещё до закрытия слушателя. Таймаут проверки (1 с) меньше таймаута +// проверки в HAProxy (2 с), чтобы зависшая БД давала явный 503, а не обрыв проверки. +app.MapGet("/health/ready", async (HttpContext context, MessengerDbContext db, ShutdownState shutdown, IAttachmentStorage storage) => +{ + if (shutdown.Draining) + { + return ApiErrors.Error(context, 503, "unavailable", "Экземпляр останавливается"); + } + + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(context.RequestAborted); + timeout.CancelAfter(TimeSpan.FromSeconds(1)); + try + { + await storage.CheckAsync(timeout.Token); + return await db.Database.CanConnectAsync(timeout.Token) + ? Results.Ok(new { status = "ok" }) + : ApiErrors.Error(context, 503, "unavailable", "База данных недоступна"); + } + catch (OperationCanceledException) when (!context.RequestAborted.IsCancellationRequested) + { + return ApiErrors.Error(context, 503, "unavailable", "Зависимость недоступна"); + } + catch (Exception ex) when (ex is Amazon.S3.AmazonS3Exception or HttpRequestException) + { + return ApiErrors.Error(context, 503, "unavailable", "Хранилище недоступно"); + } +}); + +app.MapUserEndpoints(); +app.MapAuthEndpoints(); +app.MapChatEndpoints(); +app.MapMessageEndpoints(); +app.MapAttachmentEndpoints(); + + +app.Lifetime.ApplicationStarted.Register(() => + app.Logger.LogInformation("Messenger API started (instance {InstanceId}, version {Version})", + instanceId, Environment.GetEnvironmentVariable("APP_VERSION") ?? "dev")); +// ApplicationStopping выполняется синхронно ДО остановки Kestrel: пока этот обработчик спит, слушатель ещё открыт, +// а /health/ready уже отвечает 503. Так балансировщик (inter 1s, fall 2) успевает убрать экземпляр до обрыва соединений. +app.Lifetime.ApplicationStopping.Register(() => +{ + var shutdown = app.Services.GetRequiredService(); + var drain = app.Services.GetRequiredService().DrainDelay; + shutdown.StartDraining(); + app.Logger.LogInformation("SIGTERM received: readiness=503, draining {Seconds} s, then the listener closes", drain.TotalSeconds); + if (drain > TimeSpan.Zero) + { + Thread.Sleep(drain); + } +}); +app.Lifetime.ApplicationStopped.Register(() => app.Logger.LogInformation("Messenger API stopped")); + +app.Run(); +return 0; + +// Делает Program доступным для WebApplicationFactory в тестах. +public partial class Program { } diff --git a/scr/Messenger.Api/Properties/launchSettings.json b/scr/Messenger.Api/Properties/launchSettings.json new file mode 100644 index 00000000..1e19d965 --- /dev/null +++ b/scr/Messenger.Api/Properties/launchSettings.json @@ -0,0 +1,23 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5015", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7165;http://localhost:5015", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/scr/Messenger.Api/Services/ApiErrors.cs b/scr/Messenger.Api/Services/ApiErrors.cs new file mode 100644 index 00000000..7348ac68 --- /dev/null +++ b/scr/Messenger.Api/Services/ApiErrors.cs @@ -0,0 +1,37 @@ +namespace Messenger.Api.Services; + +public static class ApiErrors +{ + public static int CodePoints(string value) => value.EnumerateRunes().Count(); + + // 401 с обязательным заголовком WWW-Authenticate (контракт: Basic для входа, Bearer для остального API). + public static IResult Unauthorized(HttpContext context, string challenge, string message) + { + context.Response.Headers.WWWAuthenticate = challenge; + return Error(context, 401, "unauthorized", message); + } + + public static IResult Error( + HttpContext context, + int statusCode, + string code, + string message) + { + var requestId = context.Items["request_id"]?.ToString() ?? context.TraceIdentifier; + + // UseExceptionHandler очищает заголовки ответа, поэтому выставляем X-Request-Id заново. + context.Response.Headers["X-Request-Id"] = requestId; + + return Results.Json( + new + { + error = new + { + code, + message, + request_id = requestId + } + }, + statusCode: statusCode); + } +} \ No newline at end of file diff --git a/scr/Messenger.Api/Services/Argon2PasswordHasher.cs b/scr/Messenger.Api/Services/Argon2PasswordHasher.cs new file mode 100644 index 00000000..6b677d08 --- /dev/null +++ b/scr/Messenger.Api/Services/Argon2PasswordHasher.cs @@ -0,0 +1,68 @@ +using Isopoh.Cryptography.Argon2; + +namespace Messenger.Api.Services; + +public sealed class Argon2PasswordHasher : IPasswordHasher +{ + // Минимум по рекомендации OWASP для Argon2id: m=19 MiB, t=2, p=1. Обоснование и выбор — в REPORT.md. + private const int TimeCost = 2; + private const int MemoryCostKiB = 19 * 1024; + private const int Parallelism = 1; + + // Каждое вычисление занимает ~19 MiB и ядро CPU: без лимита 100 параллельных входов = ~2 GiB памяти. + // Размер и время ожидания слотов задаются PASSWORD_HASH_CONCURRENCY / PASSWORD_HASH_QUEUE_TIMEOUT_SECONDS. + private readonly SemaphoreSlim _slots; + private readonly TimeSpan _slotWaitTimeout; + + // Хеш от случайного пароля, который никто не знает. Нужен только для выравнивания времени при неизвестном username. + private readonly string _dummyHash; + + public Argon2PasswordHasher(PasswordHashingSettings settings) + { + _slots = new SemaphoreSlim(settings.MaxConcurrency, settings.MaxConcurrency); + _slotWaitTimeout = settings.QueueTimeout; + _dummyHash = HashCore(Convert.ToBase64String(System.Security.Cryptography.RandomNumberGenerator.GetBytes(32))); + } + + public async Task HashAsync(string password, CancellationToken ct) + { + await AcquireSlotAsync(ct); + try + { + return await Task.Run(() => HashCore(password), ct); + } + finally + { + _slots.Release(); + } + } + + public async Task VerifyAsync(string? hash, string password, CancellationToken ct) + { + await AcquireSlotAsync(ct); + try + { + return await Task.Run(() => + { + var ok = Argon2.Verify(hash ?? _dummyHash, password, secret: null, secureArrayCall: null); + return hash is not null && ok; + }, ct); + } + finally + { + _slots.Release(); + } + } + + private async Task AcquireSlotAsync(CancellationToken ct) + { + if (!await _slots.WaitAsync(_slotWaitTimeout, ct)) + { + throw new PasswordHasherBusyException(); + } + } + + // HybridAddressing — это Argon2id. Соль генерируется библиотекой и входит в возвращаемую строку. + private static string HashCore(string password) => + Argon2.Hash(password, TimeCost, MemoryCostKiB, Parallelism, Argon2Type.HybridAddressing); +} diff --git a/scr/Messenger.Api/Services/BearerAuth.cs b/scr/Messenger.Api/Services/BearerAuth.cs new file mode 100644 index 00000000..132d9bd8 --- /dev/null +++ b/scr/Messenger.Api/Services/BearerAuth.cs @@ -0,0 +1,91 @@ +using System.Security.Claims; +using System.Text.Encodings.Web; +using Messenger.Api.Data; +using Microsoft.AspNetCore.Authentication; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Options; + +namespace Messenger.Api.Services; + +public static class BearerAuth +{ + public const string Scheme = "Bearer"; + public const string Challenge = "Bearer realm=\"messenger\""; + public const string SessionIdClaim = "session_id"; + + // Ровно один заголовок Authorization вида "Bearer "; иначе null (Basic и прочее здесь не принимаются). + public static string? ExtractToken(HttpRequest request) + { + if (request.Headers.Authorization.Count != 1) + { + return null; + } + + var value = request.Headers.Authorization[0]; + const string prefix = "Bearer "; + if (value is null || !value.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) + { + return null; + } + + var token = value[prefix.Length..].Trim(); + return token.Length == 0 ? null : token; + } + + public static Guid GetUserId(this HttpContext context) => + Guid.Parse(context.User.FindFirstValue(ClaimTypes.NameIdentifier)!); + + public static Guid GetSessionId(this HttpContext context) => + Guid.Parse(context.User.FindFirstValue(SessionIdClaim)!); +} + +// Стандартный обработчик аутентификации ASP.NET: превращает Bearer-токен в ClaimsPrincipal. +// Срабатывает до выбора и выполнения эндпоинта (в том числе до разбора тела), поэтому 401 всегда раньше 400/404. +public sealed class SessionAuthenticationHandler( + IOptionsMonitor options, + ILoggerFactory logger, + UrlEncoder encoder, + MessengerDbContext db) + : AuthenticationHandler(options, logger, encoder) +{ + protected override async Task HandleAuthenticateAsync() + { + var token = BearerAuth.ExtractToken(Request); + if (token is null) + { + return AuthenticateResult.NoResult(); + } + + var hash = SessionTokens.Hash(token); + var now = Timestamps.UtcNowMilliseconds(); + + // Неизвестный, истёкший и отозванный токен неразличимы для клиента: во всех случаях это один 401. + var session = await db.Sessions + .AsNoTracking() + .Where(s => s.TokenHash == hash && s.RevokedAt == null && s.ExpiresAt > now) + .Select(s => new { s.Id, s.UserId }) + .FirstOrDefaultAsync(Context.RequestAborted); + + if (session is null) + { + return AuthenticateResult.Fail("Недействительная сессия"); + } + + var identity = new ClaimsIdentity( + [ + new Claim(ClaimTypes.NameIdentifier, session.UserId.ToString()), + new Claim(BearerAuth.SessionIdClaim, session.Id.ToString()) + ], + BearerAuth.Scheme); + + return AuthenticateResult.Success( + new AuthenticationTicket(new ClaimsPrincipal(identity), BearerAuth.Scheme)); + } + + protected override async Task HandleChallengeAsync(AuthenticationProperties properties) + { + await ApiErrors + .Unauthorized(Context, BearerAuth.Challenge, "Требуется действительный Bearer-токен") + .ExecuteAsync(Context); + } +} diff --git a/scr/Messenger.Api/Services/Cursors.cs b/scr/Messenger.Api/Services/Cursors.cs new file mode 100644 index 00000000..166d9e7f --- /dev/null +++ b/scr/Messenger.Api/Services/Cursors.cs @@ -0,0 +1,56 @@ +using System.Text; + +namespace Messenger.Api.Services; + +// Непрозрачный для клиента cursor keyset-пагинации: (created_at, id) последнего элемента страницы. +// Привязан к ресурсу (scope): cursor от другого списка или чата отклоняется как 400. +public static class Cursors +{ + public const string Chats = "chats"; + + public static string Messages(Guid chatId) => $"messages/{chatId:D}"; + + public static string Encode(string scope, DateTimeOffset createdAt, Guid id) => + Convert.ToBase64String(Encoding.UTF8.GetBytes($"{scope}|{createdAt.UtcTicks}:{id:D}")); + + // cursor == null — первая страница (успех, value == null). Любая ошибка формата или чужой scope — false. + public static bool TryDecode(string? cursor, string scope, out (DateTimeOffset CreatedAt, Guid Id)? value) + { + value = null; + if (cursor is null) + { + return true; + } + + if (cursor.Length == 0) + { + return false; + } + + try + { + var decoded = new UTF8Encoding(false, throwOnInvalidBytes: true).GetString(Convert.FromBase64String(cursor)); + var scoped = decoded.Split('|', 2); + if (scoped.Length != 2 || scoped[0] != scope) + { + return false; + } + + var parts = scoped[1].Split(':', 2); + if (parts.Length != 2 || + !long.TryParse(parts[0], out var ticks) || + ticks < DateTimeOffset.MinValue.UtcTicks || ticks > DateTimeOffset.MaxValue.UtcTicks || + !Guid.TryParse(parts[1], out var id)) + { + return false; + } + + value = (new DateTimeOffset(ticks, TimeSpan.Zero), id); + return true; + } + catch (Exception ex) when (ex is FormatException or ArgumentException or DecoderFallbackException) + { + return false; + } + } +} diff --git a/scr/Messenger.Api/Services/Diagnostics.cs b/scr/Messenger.Api/Services/Diagnostics.cs new file mode 100644 index 00000000..130b0343 --- /dev/null +++ b/scr/Messenger.Api/Services/Diagnostics.cs @@ -0,0 +1,90 @@ +using System.Data.Common; +using Microsoft.EntityFrameworkCore.Diagnostics; +using Npgsql; + +namespace Messenger.Api.Services; + +public sealed class QueryCounter +{ + public int Count; +} + +// Считает SQL-команды, выполненные EF Core в рамках текущего HTTP-запроса (для измерения «запросов к БД на запрос API»). +// Включается только при DIAGNOSTIC_HEADERS=true. Команда ReserveMessageSlot (сырой NpgsqlCommand) не учитывается. +public sealed class QueryCountingInterceptor(IHttpContextAccessor accessor) : DbCommandInterceptor +{ + public const string ItemKey = "diagnostics.query_counter"; + + private void Count() + { + if (accessor.HttpContext?.Items[ItemKey] is QueryCounter counter) + { + Interlocked.Increment(ref counter.Count); + } + } + + public override InterceptionResult ReaderExecuting(DbCommand command, CommandEventData eventData, InterceptionResult result) + { + Count(); + return result; + } + + public override ValueTask> ReaderExecutingAsync(DbCommand command, CommandEventData eventData, InterceptionResult result, CancellationToken cancellationToken = default) + { + Count(); + return ValueTask.FromResult(result); + } + + public override InterceptionResult NonQueryExecuting(DbCommand command, CommandEventData eventData, InterceptionResult result) + { + Count(); + return result; + } + + public override ValueTask> NonQueryExecutingAsync(DbCommand command, CommandEventData eventData, InterceptionResult result, CancellationToken cancellationToken = default) + { + Count(); + return ValueTask.FromResult(result); + } + + public override InterceptionResult ScalarExecuting(DbCommand command, CommandEventData eventData, InterceptionResult result) + { + Count(); + return result; + } + + public override ValueTask> ScalarExecutingAsync(DbCommand command, CommandEventData eventData, InterceptionResult result, CancellationToken cancellationToken = default) + { + Count(); + return ValueTask.FromResult(result); + } +} + +public static class DependencyFailures +{ + // Недоступность или перегрузка PostgreSQL (нет соединения, таймаут, исчерпан пул, остановка сервера) — это 503, + // а не 500: ошибка ограничена, внутренние детали не раскрываются, запрос не принимается как доверенный. + public static bool IsDatabaseUnavailable(Exception? error) + { + for (var e = error; e is not null; e = e.InnerException) + { + switch (e) + { + case PostgresException pg: + // 08 — соединение, 53 — нехватка ресурсов, 57 — вмешательство оператора (shutdown и т.п.) + if (pg.SqlState.StartsWith("08") || pg.SqlState.StartsWith("53") || pg.SqlState.StartsWith("57")) + { + return true; + } + + break; + case NpgsqlException: + case TimeoutException: + case System.Net.Sockets.SocketException: + return true; + } + } + + return false; + } +} diff --git a/scr/Messenger.Api/Services/IAttachmentStorage.cs b/scr/Messenger.Api/Services/IAttachmentStorage.cs new file mode 100644 index 00000000..9d8d87f8 --- /dev/null +++ b/scr/Messenger.Api/Services/IAttachmentStorage.cs @@ -0,0 +1,21 @@ +namespace Messenger.Api.Services; + +public interface IAttachmentStorage +{ + Task CheckAsync(CancellationToken ct); + Task PutAsync( + string objectKey, + Stream content, + string contentType, + CancellationToken ct, + bool createOnly = false); + + Task CopyToAsync( + string objectKey, + Stream destination, + CancellationToken ct); + + Task DeleteAsync( + string objectKey, + CancellationToken ct); +} diff --git a/scr/Messenger.Api/Services/IPasswordHasher.cs b/scr/Messenger.Api/Services/IPasswordHasher.cs new file mode 100644 index 00000000..fb2a91d3 --- /dev/null +++ b/scr/Messenger.Api/Services/IPasswordHasher.cs @@ -0,0 +1,18 @@ +namespace Messenger.Api.Services; + +public interface IPasswordHasher +{ + /// PHC-строка Argon2id (соль и параметры внутри). Бросает , если слот не освободился вовремя. + Task HashAsync(string password, CancellationToken ct); + + /// + /// == null означает «пользователя нет»: проверка всё равно выполняется (против заглушки), + /// чтобы время ответа не раскрывало существование username. + /// + Task VerifyAsync(string? hash, string password, CancellationToken ct); +} + +public sealed class PasswordHasherBusyException : Exception +{ + public PasswordHasherBusyException() : base("Слишком много одновременных вычислений хеша пароля") { } +} diff --git a/scr/Messenger.Api/Services/IdempotencyKeys.cs b/scr/Messenger.Api/Services/IdempotencyKeys.cs new file mode 100644 index 00000000..8696b12e --- /dev/null +++ b/scr/Messenger.Api/Services/IdempotencyKeys.cs @@ -0,0 +1,147 @@ +using System.Security.Cryptography; +using System.Text; +using System.Text.RegularExpressions; +using Messenger.Api.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Storage; +using Npgsql; + +namespace Messenger.Api.Services; + +public enum ClaimResult +{ + Claimed, // ключ наш: можно выполнять побочный эффект (вставку сообщения) в этой же транзакции + Replay, // такой ключ с тем же телом уже выполнен: вернуть сохранённое сообщение + Conflict // такой ключ уже использован с другим телом +} + +public static partial class IdempotencyKeys +{ + public const string HeaderName = "Idempotency-Key"; + + [GeneratedRegex("^[A-Za-z0-9._:-]{1,128}$")] + private static partial Regex KeyFormat(); + + // Ровно один заголовок допустимого формата; иначе null (→ 400). + public static string? ReadKey(HttpRequest request) + { + var values = request.Headers[HeaderName]; + return values.Count == 1 && values[0] is { } key && KeyFormat().IsMatch(key) ? key : null; + } + + // Отпечаток смысла запроса, а не его байтов: порядок ключей JSON и пробелы не влияют, потому что хешируются + // уже разобранные поля. Для текстового сообщения это сам text (длина кодируется, чтобы поля не склеивались). + public static byte[] RequestHash(string text, Guid[]? attachmentIds = null) => + // Пустой список сохраняет отпечаток старых текстовых запросов lab3. + SHA256.HashData(Encoding.UTF8.GetBytes($"message\n{text.Length}\n{text}" + + (attachmentIds is { Length: > 0 } ? "\nattachments\n" + string.Join(",", attachmentIds.Select(x => x.ToString("N"))) : ""))); + + // Атомарно «занимает» ключ в транзакции вызывающего. Ключевое свойство — INSERT ... ON CONFLICT: + // * ключа нет → строка вставляется, мы владеем ключом (Claimed); + // * ключ вставила другая, ещё не завершённая транзакция (в том числе на другой реплике) → INSERT ЖДЁТ её + // COMMIT/ROLLBACK на уникальном индексе. После COMMIT вставки не происходит, и мы читаем её результат (Replay); + // после ROLLBACK (например, 5xx у конкурента) вставка проходит, и ключ достаётся нам; + // * ключ есть, но истёк → перезахватывается (DO UPDATE ... WHERE expires_at <= now). + // Поэтому claim и сообщение коммитятся вместе: запись «ключ → сообщение» не может появиться без сообщения и наоборот. + public static async Task<(ClaimResult Result, Guid MessageId)> ClaimAsync( + MessengerDbContext db, + IDbContextTransaction tx, + Guid userId, + Guid chatId, + string key, + byte[] requestHash, + Guid newMessageId, + TimeSpan ttl, + CancellationToken ct) + { + var connection = (NpgsqlConnection)db.Database.GetDbConnection(); + var transaction = (NpgsqlTransaction)tx.GetDbTransaction(); + var now = Timestamps.UtcNowMilliseconds(); + + await using (var insert = new NpgsqlCommand(""" + INSERT INTO idempotency_keys (user_id, chat_id, key, request_hash, message_id, created_at, expires_at) + VALUES (@user, @chat, @key, @hash, @message, @now, @expires) + ON CONFLICT (user_id, chat_id, key) DO UPDATE + SET request_hash = EXCLUDED.request_hash, + message_id = EXCLUDED.message_id, + created_at = EXCLUDED.created_at, + expires_at = EXCLUDED.expires_at + WHERE idempotency_keys.expires_at <= EXCLUDED.created_at + RETURNING 1 + """, connection, transaction)) + { + insert.Parameters.AddWithValue("user", userId); + insert.Parameters.AddWithValue("chat", chatId); + insert.Parameters.AddWithValue("key", key); + insert.Parameters.AddWithValue("hash", requestHash); + insert.Parameters.AddWithValue("message", newMessageId); + insert.Parameters.AddWithValue("now", now); + insert.Parameters.AddWithValue("expires", now + ttl); + + if (await insert.ExecuteScalarAsync(ct) is not null) + { + return (ClaimResult.Claimed, newMessageId); + } + } + + await using var select = new NpgsqlCommand(""" + SELECT request_hash, message_id FROM idempotency_keys + WHERE user_id = @user AND chat_id = @chat AND key = @key + """, connection, transaction); + select.Parameters.AddWithValue("user", userId); + select.Parameters.AddWithValue("chat", chatId); + select.Parameters.AddWithValue("key", key); + + await using var reader = await select.ExecuteReaderAsync(ct); + if (!await reader.ReadAsync(ct)) + { + // Строку успел удалить очиститель между INSERT и SELECT: крайне редко; клиент безопасно повторит запрос. + throw new TimeoutException("idempotency key disappeared during claim"); + } + + var storedHash = reader.GetFieldValue(0); + var storedMessage = reader.GetGuid(1); + return CryptographicOperations.FixedTimeEquals(storedHash, requestHash) + ? (ClaimResult.Replay, storedMessage) + : (ClaimResult.Conflict, storedMessage); + } +} + +// Периодически удаляет истёкшие ключи. Запускается на каждой реплике; параллельные DELETE безопасны +// (физически строку удалит одна из них, остальные удалят 0). +public sealed class IdempotencyCleaner( + IServiceScopeFactory scopes, + IdempotencySettings settings, + ILogger logger) : BackgroundService +{ + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + using var timer = new PeriodicTimer(settings.CleanupInterval); + try + { + while (await timer.WaitForNextTickAsync(stoppingToken)) + { + try + { + using var scope = scopes.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var now = Timestamps.UtcNowMilliseconds(); + var removed = await db.IdempotencyKeys.Where(k => k.ExpiresAt <= now).ExecuteDeleteAsync(stoppingToken); + if (removed > 0) + { + logger.LogInformation("Удалено истёкших ключей идемпотентности: {Count}", removed); + } + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + logger.LogWarning("Очистка ключей идемпотентности не удалась ({Error}); повтор через {Seconds} с", + ex.GetType().Name, settings.CleanupInterval.TotalSeconds); + } + } + } + catch (OperationCanceledException) + { + // остановка приложения + } + } +} diff --git a/scr/Messenger.Api/Services/LimitedDownloadStream.cs b/scr/Messenger.Api/Services/LimitedDownloadStream.cs new file mode 100644 index 00000000..ed0d5ad7 --- /dev/null +++ b/scr/Messenger.Api/Services/LimitedDownloadStream.cs @@ -0,0 +1,16 @@ +namespace Messenger.Api.Services; + +// Ограничивает память даже при неожиданном размере объекта в S3. +public sealed class LimitedDownloadStream(long maximum) : MemoryStream +{ + private void Check(int count) + { + if (Position + count > maximum) throw new IOException("Object exceeds its metadata size"); + } + public override void Write(byte[] buffer, int offset, int count) { Check(count); base.Write(buffer, offset, count); } + public override void Write(ReadOnlySpan buffer) { Check(buffer.Length); base.Write(buffer); } + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken ct) + { Check(count); return base.WriteAsync(buffer, offset, count, ct); } + public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken ct = default) + { Check(buffer.Length); return base.WriteAsync(buffer, ct); } +} diff --git a/scr/Messenger.Api/Services/MessageHistoryCache.cs b/scr/Messenger.Api/Services/MessageHistoryCache.cs new file mode 100644 index 00000000..efd5525a --- /dev/null +++ b/scr/Messenger.Api/Services/MessageHistoryCache.cs @@ -0,0 +1,102 @@ +using StackExchange.Redis; + +namespace Messenger.Api.Services; + +public enum CacheStatus +{ + Disabled, // кэш не настроен + Hit, + Miss, + Bypass // кэш настроен, но недоступен: запрос обслужен напрямую из PostgreSQL +} + +// Кэш страниц истории. Источник истины — PostgreSQL; кэш лишь ускоряет чтение и никогда не обязателен. +// Согласованность: версия истории чата (chats.history_version) входит в ключ, а версия читается из PostgreSQL +// при каждом запросе (см. MessageEndpoints). Запись увеличивает версию в своей транзакции, поэтому +// после подтверждённой записи ключ меняется, и устаревшая страница недостижима — явная инвалидация не нужна. +// Старые ключи удаляются по TTL (CACHE_TTL_SECONDS) и вытесняются политикой maxmemory. +public interface IMessageHistoryCache +{ + Task<(string? Json, CacheStatus Status)> GetAsync(string key, CancellationToken ct); + Task SetAsync(string key, string json, CancellationToken ct); +} + +public sealed class NullMessageHistoryCache : IMessageHistoryCache +{ + public Task<(string? Json, CacheStatus Status)> GetAsync(string key, CancellationToken ct) => + Task.FromResult<(string?, CacheStatus)>((null, CacheStatus.Disabled)); + + public Task SetAsync(string key, string json, CancellationToken ct) => Task.CompletedTask; +} + +public sealed class ValkeyMessageHistoryCache : IMessageHistoryCache, IDisposable +{ + // После ошибки кэш пропускается на это время, чтобы каждый запрос не ждал таймаут недоступного сервера. + private static readonly TimeSpan BypassWindow = TimeSpan.FromSeconds(5); + + private readonly ConnectionMultiplexer _connection; + private readonly TimeSpan _ttl; + private readonly ILogger _logger; + private long _bypassUntilTicks; + + public ValkeyMessageHistoryCache(CacheSettings settings, ILogger logger) + { + var options = ConfigurationOptions.Parse(settings.Connection!); + // Недоступный кэш не должен ронять ни старт, ни запросы: короткие таймауты, подключение в фоне. + options.AbortOnConnectFail = false; + options.ConnectTimeout = 500; + options.SyncTimeout = 200; + options.AsyncTimeout = 200; + options.ConnectRetry = 1; + _connection = ConnectionMultiplexer.Connect(options); + _ttl = settings.Ttl; + _logger = logger; + } + + public async Task<(string? Json, CacheStatus Status)> GetAsync(string key, CancellationToken ct) + { + if (IsBypassed()) + { + return (null, CacheStatus.Bypass); + } + + try + { + var value = await _connection.GetDatabase().StringGetAsync(key); + return value.IsNull ? (null, CacheStatus.Miss) : ((string?)value, CacheStatus.Hit); + } + catch (Exception ex) when (ex is RedisException or TimeoutException) + { + StartBypass(ex); + return (null, CacheStatus.Bypass); + } + } + + public async Task SetAsync(string key, string json, CancellationToken ct) + { + if (IsBypassed()) + { + return; + } + + try + { + await _connection.GetDatabase().StringSetAsync(key, json, _ttl); + } + catch (Exception ex) when (ex is RedisException or TimeoutException) + { + StartBypass(ex); + } + } + + private bool IsBypassed() => Environment.TickCount64 < Interlocked.Read(ref _bypassUntilTicks); + + private void StartBypass(Exception ex) + { + Interlocked.Exchange(ref _bypassUntilTicks, Environment.TickCount64 + (long)BypassWindow.TotalMilliseconds); + _logger.LogWarning("Кэш недоступен ({Error}); чтение идёт напрямую из PostgreSQL ближайшие {Seconds} с", + ex.GetType().Name, BypassWindow.TotalSeconds); + } + + public void Dispose() => _connection.Dispose(); +} diff --git a/scr/Messenger.Api/Services/PngIntegrity.cs b/scr/Messenger.Api/Services/PngIntegrity.cs new file mode 100644 index 00000000..4011b614 --- /dev/null +++ b/scr/Messenger.Api/Services/PngIntegrity.cs @@ -0,0 +1,56 @@ +using System.Buffers.Binary; +using System.IO.Compression; + +namespace Messenger.Api.Services; + +// Дополняет декодер: проверяет границы и CRC всех PNG chunks, включая IDAT. +public static class PngIntegrity +{ + private static readonly uint[] Table = Enumerable.Range(0, 256).Select(i => + { + uint c = (uint)i; + for (var bit = 0; bit < 8; bit++) c = (c & 1) != 0 ? 0xedb88320U ^ (c >> 1) : c >> 1; + return c; + }).ToArray(); + + public static async Task ValidateAsync(Stream stream, long maxDecodedBytes, CancellationToken ct) + { + stream.Position = 8; + var header = new byte[8]; + var buffer = new byte[65536]; + var checksum = new byte[4]; + using var compressed = new MemoryStream(); // IDAT не больше уже ограниченного файла (10 MiB). + while (stream.Position < stream.Length) + { + await stream.ReadExactlyAsync(header, ct); + var length = BinaryPrimitives.ReadUInt32BigEndian(header); + if (length > stream.Length - stream.Position - 4) throw new InvalidDataException("Invalid PNG chunk"); + uint crc = uint.MaxValue; + for (var i = 4; i < 8; i++) crc = Table[(crc ^ header[i]) & 255] ^ (crc >> 8); + long remaining = length; + while (remaining > 0) + { + var count = (int)Math.Min(buffer.Length, remaining); + await stream.ReadExactlyAsync(buffer.AsMemory(0, count), ct); + if (header.AsSpan(4, 4).SequenceEqual("IDAT"u8)) + await compressed.WriteAsync(buffer.AsMemory(0, count), ct); + for (var i = 0; i < count; i++) crc = Table[(crc ^ buffer[i]) & 255] ^ (crc >> 8); + remaining -= count; + } + await stream.ReadExactlyAsync(checksum, ct); + if ((crc ^ uint.MaxValue) != BinaryPrimitives.ReadUInt32BigEndian(checksum)) + throw new InvalidDataException("Invalid PNG checksum"); + } + // stbi распаковывает PNG до проверки длины пикселей: сначала проверяем + // размер zlib-потока самостоятельно, не выделяя память под распаковку. + compressed.Position = 0; + using var zlib = new ZLibStream(compressed, CompressionMode.Decompress); + long decoded = 0; + int read; + while ((read = await zlib.ReadAsync(buffer, ct)) != 0) + { + decoded += read; + if (decoded > maxDecodedBytes) throw new InvalidDataException("PNG decompression exceeds dimensions"); + } + } +} diff --git a/scr/Messenger.Api/Services/S3AttachmentStorage.cs b/scr/Messenger.Api/Services/S3AttachmentStorage.cs new file mode 100644 index 00000000..ee9a9a88 --- /dev/null +++ b/scr/Messenger.Api/Services/S3AttachmentStorage.cs @@ -0,0 +1,88 @@ +using Amazon.Runtime; +using Amazon.S3; +using Amazon.S3.Model; +using System.Net; +using System.Security.Cryptography; + +namespace Messenger.Api.Services; + +public sealed class S3AttachmentStorage : IAttachmentStorage, IDisposable +{ + private readonly AmazonS3Client _client; + private readonly string _bucket; + + public S3AttachmentStorage(S3Settings settings) + { + var config = new AmazonS3Config + { + ServiceURL = settings.Endpoint, + ForcePathStyle = true, + AuthenticationRegion = settings.Region, + Timeout = TimeSpan.FromSeconds(15), + MaxErrorRetry = 1 + }; + + var credentials = new BasicAWSCredentials(settings.AccessKey, settings.SecretKey); + _client = new AmazonS3Client(credentials, config); + + _bucket = settings.Bucket; + } + + public async Task PutAsync(string objectKey, Stream content, string contentType, CancellationToken ct, bool createOnly = false) + { + var request = new PutObjectRequest + { + BucketName = _bucket, + Key = objectKey, + InputStream = content, + ContentType = contentType, + IfNoneMatch = createOnly ? "*" : null, + // Поток принадлежит вызывающему коду, а не SDK. + AutoCloseStream = false + }; + + try + { + await _client.PutObjectAsync(request, ct); + } + catch (AmazonS3Exception ex) when (createOnly && ex.StatusCode == HttpStatusCode.PreconditionFailed) + { + // Повтор после аварии использует уже записанные байты. Несовпадение закрывает публикацию. + using var existing = new LimitedDownloadStream(content.Length); + await CopyToAsync(objectKey, existing, ct); + content.Position = 0; + var expected = await SHA256.HashDataAsync(content, ct); + var actual = SHA256.HashData(existing.GetBuffer().AsSpan(0, (int)existing.Length)); + if (existing.Length != content.Length || !expected.AsSpan().SequenceEqual(actual)) + throw new IOException("Existing object differs from the pipeline result"); + } + } + + public async Task CopyToAsync(string objectKey, Stream destination, CancellationToken ct) + { + var request = new GetObjectRequest + { + BucketName = _bucket, + Key = objectKey + }; + + using var response = await _client.GetObjectAsync(request, ct); + await response.ResponseStream.CopyToAsync(destination, ct); + } + + public async Task DeleteAsync(string objectKey, CancellationToken ct) + { + var request = new DeleteObjectRequest + { + BucketName = _bucket, + Key = objectKey + }; + + await _client.DeleteObjectAsync(request, ct); + } + + public void Dispose() => _client.Dispose(); + + public async Task CheckAsync(CancellationToken ct) => + await _client.GetBucketLocationAsync(new GetBucketLocationRequest { BucketName = _bucket }, ct); +} diff --git a/scr/Messenger.Api/Services/SessionTokens.cs b/scr/Messenger.Api/Services/SessionTokens.cs new file mode 100644 index 00000000..f8a0669e --- /dev/null +++ b/scr/Messenger.Api/Services/SessionTokens.cs @@ -0,0 +1,16 @@ +using System.Security.Cryptography; +using System.Text; + +namespace Messenger.Api.Services; + +public static class SessionTokens +{ + // 32 случайных байта = 256 бит энтропии (контракт: не менее 256). В base64url это 43 символа. + public static string Generate() => + Convert.ToBase64String(RandomNumberGenerator.GetBytes(32)) + .TrimEnd('=').Replace('+', '-').Replace('/', '_'); + + // В БД хранится только SHA-256 токена. Быстрый хеш здесь уместен: токен случайный и длинный, подбирать нечего + // (в отличие от пароля, который выбирает человек и который поэтому хешируется медленным Argon2id). + public static byte[] Hash(string token) => SHA256.HashData(Encoding.UTF8.GetBytes(token)); +} diff --git a/scr/Messenger.Api/Services/Settings.cs b/scr/Messenger.Api/Services/Settings.cs new file mode 100644 index 00000000..2928ab9f --- /dev/null +++ b/scr/Messenger.Api/Services/Settings.cs @@ -0,0 +1,166 @@ +namespace Messenger.Api.Services; + +// Все настройки читаются из IConfiguration (переменные окружения и, в тестах, UseSetting), а не напрямую из окружения: +// так одно приложение можно поднять с разными настройками в одном процессе. Секреты передаются файлами (*_FILE). + +public sealed record DatabaseSettings(string ConnectionString) +{ + public static DatabaseSettings From(IConfiguration configuration) + { + var file = configuration["DATABASE_URL_FILE"] + ?? throw new InvalidOperationException("DATABASE_URL_FILE не задан"); + + var builder = new Npgsql.NpgsqlConnectionStringBuilder(File.ReadAllText(file).Trim()) + { + Pooling = true, + MinPoolSize = 1, + // Ограниченный пул: больше MaxPoolSize соединений от одного экземпляра не открывается, + // ожидающие запросы ждут не дольше Timeout и затем получают 503. + MaxPoolSize = configuration.GetValue("DB_MAX_POOL_SIZE", 20), + Timeout = configuration.GetValue("DB_CONNECT_TIMEOUT_SECONDS", 5), + CommandTimeout = configuration.GetValue("DB_COMMAND_TIMEOUT_SECONDS", 5) + }; + return new DatabaseSettings(builder.ConnectionString); + } +} + +public sealed record S3Settings(string Bucket, string Endpoint, string Region, string AccessKey, string SecretKey) +{ + public static S3Settings From(IConfiguration configuration) + { + string Required(string name) => !string.IsNullOrWhiteSpace(configuration[name]) + ? configuration[name]!.Trim() + : throw new InvalidOperationException($"{name} не задан"); + + string ReadSecret(string name) + { + var value = File.ReadAllText(Required(name)).Trim(); + return value.Length > 0 ? value + : throw new InvalidOperationException($"Файл {name} пуст"); + } + + var endpoint = Required("S3_ENDPOINT"); + if (!Uri.TryCreate(endpoint, UriKind.Absolute, out var uri) || + uri.Scheme is not ("http" or "https")) + { + throw new InvalidOperationException("S3_ENDPOINT должен быть HTTP/HTTPS URL"); + } + + return new S3Settings(Required("S3_BUCKET"), endpoint, + configuration["S3_REGION"]?.Trim() is { Length: > 0 } region ? region : "us-east-1", + ReadSecret("S3_ACCESS_KEY_ID_FILE"), ReadSecret("S3_SECRET_ACCESS_KEY_FILE")); + } + + public override string ToString() => $"S3Settings {{ Bucket = {Bucket}, Endpoint = {Endpoint}, Region = {Region} }}"; +} + +public sealed record AuthSessionOptions(TimeSpan Ttl) +{ + // SESSION_TTL_SECONDS: по умолчанию 3600; в тесте истечения допустимо 2. Неверное значение — ошибка старта, а не молчаливый дефолт. + public static AuthSessionOptions From(IConfiguration configuration) + { + var raw = configuration["SESSION_TTL_SECONDS"]; + if (string.IsNullOrWhiteSpace(raw)) + { + return new AuthSessionOptions(TimeSpan.FromSeconds(3600)); + } + + if (!int.TryParse(raw, out var seconds) || seconds < 1) + { + throw new InvalidOperationException("SESSION_TTL_SECONDS должен быть положительным целым числом"); + } + + return new AuthSessionOptions(TimeSpan.FromSeconds(seconds)); + } +} + +// Ограничитель Argon2: сколько хешей считается одновременно и сколько запрос ждёт свободный слот, прежде чем получить 503. +// Один хеш занимает ~19 MiB и ядро CPU, поэтому без лимита пачка регистраций исчерпала бы память. +public sealed record PasswordHashingSettings(int MaxConcurrency, TimeSpan QueueTimeout) +{ + public static PasswordHashingSettings From(IConfiguration configuration) + { + var concurrency = configuration.GetValue("PASSWORD_HASH_CONCURRENCY", 4); + var timeoutSeconds = configuration.GetValue("PASSWORD_HASH_QUEUE_TIMEOUT_SECONDS", 2.0); + if (concurrency < 1 || timeoutSeconds < 0) + { + throw new InvalidOperationException("PASSWORD_HASH_CONCURRENCY >= 1 и PASSWORD_HASH_QUEUE_TIMEOUT_SECONDS >= 0"); + } + + return new PasswordHashingSettings(concurrency, TimeSpan.FromSeconds(timeoutSeconds)); + } +} + +// Кэш необязателен: без CACHE_URL_FILE / CACHE_CONNECTION приложение работает только на PostgreSQL. +public sealed record CacheSettings(string? Connection, TimeSpan Ttl) +{ + public bool Enabled => !string.IsNullOrWhiteSpace(Connection); + + public static CacheSettings From(IConfiguration configuration) + { + var connection = configuration["CACHE_CONNECTION"]; + var file = configuration["CACHE_URL_FILE"]; + if (!string.IsNullOrWhiteSpace(file) && File.Exists(file)) + { + connection = File.ReadAllText(file).Trim(); + } + + return new CacheSettings(connection, TimeSpan.FromSeconds(configuration.GetValue("CACHE_TTL_SECONDS", 300))); + } +} + +// Диагностические заголовки X-Cache и X-Db-Queries для экспериментов; в обычной работе выключены. +public sealed record DiagnosticsSettings(bool Headers) +{ + public static DiagnosticsSettings From(IConfiguration configuration) => + new(configuration.GetValue("DIAGNOSTIC_HEADERS", false)); +} + +// Идентичность и жизненный цикл экземпляра (lab3). +// InstanceId — значение X-Instance-Id. В Docker hostname контейнера = первые 12 символов его ID, поэтому +// stop-one.sh по заголовку находит нужный контейнер. DrainDelay — пауза между SIGTERM и закрытием слушателя: +// за это время /health/ready уже отвечает 503, и балансировщик успевает вывести экземпляр из ротации. +// MigrateOnStart по умолчанию выключен: миграции выполняет отдельный one-shot контейнер (--migrate), а не гонка реплик. +public sealed record InstanceSettings(string InstanceId, TimeSpan DrainDelay, bool MigrateOnStart) +{ + public static InstanceSettings From(IConfiguration configuration) + { + var id = configuration["INSTANCE_ID"]; + if (string.IsNullOrWhiteSpace(id)) + { + id = Environment.MachineName; + } + + var drainSeconds = configuration.GetValue("SHUTDOWN_DRAIN_SECONDS", 3.0); + if (drainSeconds < 0) + { + throw new InvalidOperationException("SHUTDOWN_DRAIN_SECONDS должен быть >= 0"); + } + + return new InstanceSettings(id, TimeSpan.FromSeconds(drainSeconds), configuration.GetValue("MIGRATE_ON_START", false)); + } +} + +// Время хранения результата идемпотентной отправки сообщения (контракт: не менее 24 часов). +public sealed record IdempotencySettings(TimeSpan Ttl, TimeSpan CleanupInterval) +{ + public static IdempotencySettings From(IConfiguration configuration) + { + var ttl = configuration.GetValue("IDEMPOTENCY_TTL_SECONDS", 86400); + var cleanup = configuration.GetValue("IDEMPOTENCY_CLEANUP_INTERVAL_SECONDS", 300); + if (ttl < 1 || cleanup < 1) + { + throw new InvalidOperationException("IDEMPOTENCY_TTL_SECONDS и IDEMPOTENCY_CLEANUP_INTERVAL_SECONDS должны быть положительными"); + } + + return new IdempotencySettings(TimeSpan.FromSeconds(ttl), TimeSpan.FromSeconds(cleanup)); + } +} + +// Признак «экземпляр останавливается»: после SIGTERM /health/ready отвечает 503, а уже принятые запросы дорабатывают. +public sealed class ShutdownState +{ + private volatile bool _draining; + public bool Draining => _draining; + public void StartDraining() => _draining = true; +} diff --git a/scr/Messenger.Api/Services/Timestamps.cs b/scr/Messenger.Api/Services/Timestamps.cs new file mode 100644 index 00000000..d9601015 --- /dev/null +++ b/scr/Messenger.Api/Services/Timestamps.cs @@ -0,0 +1,13 @@ +namespace Messenger.Api.Services; + +public static class Timestamps +{ + // Единая точность времени для хранения, сортировки, cursor и JSON-ответа: миллисекунды. + // Клиент видит время с точностью до миллисекунды, поэтому порядок (created_at, id) должен + // определяться теми же значениями, которые он видит. + public static DateTimeOffset UtcNowMilliseconds() + { + var ticks = DateTimeOffset.UtcNow.UtcTicks; + return new DateTimeOffset(ticks - ticks % TimeSpan.TicksPerMillisecond, TimeSpan.Zero); + } +} diff --git a/scr/Messenger.Api/Services/UploadCleanup.cs b/scr/Messenger.Api/Services/UploadCleanup.cs new file mode 100644 index 00000000..14a158c7 --- /dev/null +++ b/scr/Messenger.Api/Services/UploadCleanup.cs @@ -0,0 +1,107 @@ +using Messenger.Api.Data; +using Microsoft.EntityFrameworkCore; + +namespace Messenger.Api.Services; + +public sealed record UploadCleanupSettings(TimeSpan Grace, TimeSpan Interval) +{ + public static UploadCleanupSettings From(IConfiguration configuration) + { + var grace = configuration.GetValue("UPLOAD_CLEANUP_GRACE_SECONDS", 300); + var interval = configuration.GetValue("UPLOAD_CLEANUP_INTERVAL_SECONDS", 30); + // Grace > HTTP timeout 30 с + SDK retry/таймауты + запас на отмену. + if (grace < 120 || interval < 1) + throw new InvalidOperationException("Cleanup: grace >= 120, interval >= 1"); + return new(TimeSpan.FromSeconds(grace), TimeSpan.FromSeconds(interval)); + } +} + +public sealed record UploadCleanupResult(int Scanned, int Deleted, int Protected, int Failed); + +public sealed class UploadCleanup(IServiceScopeFactory scopes, UploadCleanupSettings settings, ILogger logger) +{ + public async Task RunOnceAsync(CancellationToken ct) + { + using var scope = scopes.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var storage = scope.ServiceProvider.GetRequiredService(); + using var deadline = CancellationTokenSource.CreateLinkedTokenSource(ct); + deadline.CancelAfter(TimeSpan.FromSeconds(20)); + ct = deadline.Token; + await using var tx = await db.Database.BeginTransactionAsync(ct); + // Несколько реплик не очищают одну запись одновременно. Финализация upload + // блокирует ту же строку и запрещена после истечения lease. + var intents = await db.UploadIntents.FromSqlRaw(""" + SELECT * FROM upload_intents + WHERE expires_at <= clock_timestamp() AND next_attempt_at <= clock_timestamp() + ORDER BY next_attempt_at, id LIMIT 16 FOR UPDATE SKIP LOCKED + """).ToListAsync(ct); + int deleted = 0, protectedCount = 0, failed = 0; + foreach (var intent in intents) + { + if (await db.Attachments.AsNoTracking().AnyAsync(a => a.ObjectKey == intent.ObjectKey, ct)) + { + db.UploadIntents.Remove(intent); // Опубликованный объект никогда не удаляем. + protectedCount++; + continue; + } + var staging = intent.ObjectKey == $"staging/{intent.Id:N}"; + if (!staging && intent.ObjectKey != $"originals/{intent.Id:N}") + throw new InvalidOperationException("Invalid cleanup object key"); + string? stageOwner = null; + if (staging) + { + stageOwner = await db.Attachments.Where(a => a.Id == intent.Id) + .Select(a => a.Status).SingleOrDefaultAsync(ct); + if (stageOwner is "queued" or "processing" && + await db.AttachmentJobs.AnyAsync(j => j.AttachmentId == intent.Id && j.SourceKey == intent.ObjectKey && + j.PipelineVersion == j.Attachment.PipelineVersion, ct)) + { + db.UploadIntents.Remove(intent); // Активная job владеет staging до терминального перехода. + protectedCount++; + continue; + } + } + intent.NextAttemptAt = DateTimeOffset.UtcNow + settings.Interval; + try + { + await storage.DeleteAsync(intent.ObjectKey, ct); // DELETE отсутствующего объекта идемпотентен. + intent.DeleteCount++; + deleted++; + if (stageOwner is not null) + db.UploadIntents.Remove(intent); + // Tombstone сохраняется: даже запоздавший PUT после crash не + // превратится в забытый объект. Цена — запись в БД на неудачную загрузку. + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + failed++; + logger.LogWarning("S3 cleanup retry for {UploadId}: {Error}", intent.Id, ex.GetType().Name); + } + } + await db.SaveChangesAsync(ct); + await tx.CommitAsync(ct); + return new(intents.Count, deleted, protectedCount, failed); + } +} + +public sealed class UploadCleanupWorker(UploadCleanup cleanup, UploadCleanupSettings settings, + ILogger logger) : BackgroundService +{ + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + using var timer = new PeriodicTimer(settings.Interval); + while (!stoppingToken.IsCancellationRequested) + { + try + { + var result = await cleanup.RunOnceAsync(stoppingToken); + if (result.Scanned > 0) logger.LogInformation("Upload cleanup: {Result}", result); + } + catch (Exception ex) when (!stoppingToken.IsCancellationRequested) + { logger.LogWarning("Upload cleanup will retry: {Error}", ex.GetType().Name); } + try { if (!await timer.WaitForNextTickAsync(stoppingToken)) break; } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; } + } + } +} diff --git a/scr/Messenger.Api/Services/UploadSettings.cs b/scr/Messenger.Api/Services/UploadSettings.cs new file mode 100644 index 00000000..62195c2f --- /dev/null +++ b/scr/Messenger.Api/Services/UploadSettings.cs @@ -0,0 +1,20 @@ +namespace Messenger.Api.Services; + +public sealed record UploadSettings(long MaxBytes, long MaxPixels) +{ + public static UploadSettings From(IConfiguration configuration) + { + var bytes = configuration.GetValue("MAX_UPLOAD_BYTES", 10485760L); + var pixels = configuration.GetValue("MAX_IMAGE_PIXELS", 40000000L); + if (bytes is < 1 or > 10485760 || pixels is < 1 or > 40000000) + throw new InvalidOperationException("Лимиты upload должны быть положительными и не превышать 10 MiB / 40 млн пикселей"); + return new(bytes, pixels); + } +} + +// Ограничиваем число одновременных декодирований на реплике (до 160 MB пикселей). +public sealed class UploadGate : IDisposable +{ + public SemaphoreSlim Slots { get; } = new(1); + public void Dispose() => Slots.Dispose(); +} diff --git a/scr/Messenger.Api/Services/UtcDateTimeOffsetJsonConverter.cs b/scr/Messenger.Api/Services/UtcDateTimeOffsetJsonConverter.cs new file mode 100644 index 00000000..bf12e0cd --- /dev/null +++ b/scr/Messenger.Api/Services/UtcDateTimeOffsetJsonConverter.cs @@ -0,0 +1,28 @@ +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Messenger.Api.Services; + +public sealed class UtcDateTimeOffsetJsonConverter : JsonConverter +{ + public override DateTimeOffset Read( + ref Utf8JsonReader reader, + Type typeToConvert, + JsonSerializerOptions options) + { + return DateTimeOffset.Parse( + reader.GetString()!, + CultureInfo.InvariantCulture, + DateTimeStyles.RoundtripKind); + } + + public override void Write( + Utf8JsonWriter writer, + DateTimeOffset value, + JsonSerializerOptions options) + { + writer.WriteStringValue( + value.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss.fff'Z'", CultureInfo.InvariantCulture)); + } +} \ No newline at end of file diff --git a/scr/Messenger.Api/appsettings.Development.json b/scr/Messenger.Api/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/scr/Messenger.Api/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/scr/Messenger.Api/appsettings.json b/scr/Messenger.Api/appsettings.json new file mode 100644 index 00000000..10f68b8c --- /dev/null +++ b/scr/Messenger.Api/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/scripts/init-secrets.sh b/scripts/init-secrets.sh new file mode 100644 index 00000000..5be39b6d --- /dev/null +++ b/scripts/init-secrets.sh @@ -0,0 +1,47 @@ +#!/bin/sh +# Создаёт локальные секреты для compose.yaml, если их ещё нет. Существующие файлы не перезаписываются. +# Пароль случайный (24 символа [A-Za-z0-9]); значения не печатаются. Каталог secrets/ исключён из Git. +set -eu +cd "$(dirname "$0")/.." + +mkdir -p secrets +umask 077 +# Каталог закрыт для других пользователей хоста. Отдельные файлы для API ниже +# доступны непривилегированному пользователю контейнера через read-only bind mount. +chmod 700 secrets + +if [ ! -f secrets/db_password ]; then + # tr читает конечный поток /dev/urandom до нужной длины; head закрывает канал. + LC_ALL=C tr -dc 'A-Za-z0-9' < /dev/urandom | head -c 24 > secrets/db_password + echo "created secrets/db_password" +fi + +if [ ! -f secrets/database_url.compose ]; then + printf 'Host=db;Port=5432;Database=messenger;Username=messenger;Password=%s' "$(cat secrets/db_password)" \ + > secrets/database_url.compose + echo "created secrets/database_url.compose" +fi + +if [ ! -f secrets/cache_password ]; then + LC_ALL=C tr -dc 'A-Za-z0-9' < /dev/urandom | head -c 24 > secrets/cache_password + echo "created secrets/cache_password" +fi + +if [ ! -f secrets/cache_url ]; then + printf 'cache:6379,password=%s' "$(cat secrets/cache_password)" > secrets/cache_url + echo "created secrets/cache_url" +fi + +# Независимые учётные данные сервисов. +for secret_name in s3_root_user s3_root_password s3_access_key_id s3_secret_access_key s3_worker_access_key s3_worker_secret_key broker_password; do + if [ ! -f "secrets/$secret_name" ]; then + LC_ALL=C tr -dc 'A-Za-z0-9' < /dev/urandom | head -c 32 > "secrets/$secret_name" + echo "created secrets/$secret_name" + fi +done + +if [ ! -f secrets/broker_url ]; then + printf 'amqp://messenger:%s@broker:5672/%%2f' "$(cat secrets/broker_password)" > secrets/broker_url +fi +chmod 644 secrets/database_url.compose secrets/cache_url secrets/s3_access_key_id secrets/s3_secret_access_key \ + secrets/s3_worker_access_key secrets/s3_worker_secret_key secrets/broker_url diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100644 index 00000000..a5a8112b --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +docker compose restart db cache s3 broker api dispatcher worker diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh new file mode 100644 index 00000000..b857584d --- /dev/null +++ b/scripts/stop-one.sh @@ -0,0 +1,12 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +: "${TARGET_INSTANCE_ID:?Missing target API instance}" +for id in $(docker compose ps -q api); do + if [ "$(docker inspect --format '{{.Config.Hostname}}' "$id")" = "$TARGET_INSTANCE_ID" ]; then + docker stop --time 8 "$id" >/dev/null + exit 0 + fi +done +echo 'The target is not a running API replica of this Compose project' >&2 +exit 1 diff --git a/student-tests/pipeline.py b/student-tests/pipeline.py new file mode 100644 index 00000000..9fafd5dc --- /dev/null +++ b/student-tests/pipeline.py @@ -0,0 +1,343 @@ +"""Pipeline checks against an isolated Compose project with synthetic data.""" +import argparse +import hashlib +import json +from pathlib import Path +import struct +import subprocess +import sys +import time +import zlib + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tests")) +from client import Client, Failure, check +from image_probe import jpeg_size + + +def run_compose(*args): + return subprocess.run(["docker", "compose", *args], cwd=ROOT, capture_output=True, + text=True, encoding="utf-8", timeout=110) + + +def compose(*args): + result = run_compose(*args) + if result.returncode: + raise RuntimeError(result.stderr) + return result.stdout.strip() + + +def sql(statement): + return compose("exec", "-T", "db", "psql", "-XAt", "-v", "ON_ERROR_STOP=1", + "-U", "messenger", "-d", "messenger", "-c", statement) + + +def admin(*args): + return compose("exec", "-T", "broker", "sh", "-ec", + 'export RABBITMQADMIN_PASSWORD="$(cat /run/secrets/broker_password)" ' + 'RABBITMQADMIN_USERNAME=messenger; exec rabbitmqadmin --timeout 5 "$@"', "admin", *args) + + +def wait_for(read, expected, timeout=60): + deadline = time.monotonic() + timeout + value = None + while time.monotonic() < deadline: + try: + value = read() + except (Failure, RuntimeError) as exc: + value = str(exc) + if value == expected: + return value + time.sleep(0.5) + raise AssertionError(f"expected {expected!r}, last observed {value!r}") + + +def queue_size(): + out = compose("exec", "-T", "broker", "rabbitmqctl", "-q", "list_queues", "name", "messages_ready") + for line in out.splitlines(): + fields = line.split() + if len(fields) == 2 and fields[0] == "attachments.v1": + return int(fields[1]) + return 0 + + +def started_at(service): + ids = compose("ps", "-q", service).splitlines() + result = subprocess.run(["docker", "inspect", "--format", "{{.State.StartedAt}}", *ids], + cwd=ROOT, capture_output=True, text=True, check=True, timeout=15) + return result.stdout.splitlines() + + +def minimum(client): + started = time.monotonic() + alice, bob, _, chat = client.bootstrap() + wait_for(queue_size, 0) + compose("stop", "worker") + try: + attachment, content = client.attachment(alice, chat) + aid = attachment["id"] + route = "/api/v1/attachments/" + aid + client.call("GET", route + "/content", 409, actor=alice) + sent = client.message(alice, chat, "", attachments=[aid])["json"] + check(sent["attachment_ids"] == [aid], "queued attachment missing from message") + text = "Сообщение во время остановки worker" + check(client.message(bob, chat, text)["json"]["text"] == text, "ordinary message was blocked") + wait_for(lambda: sql(f"SELECT published_at IS NOT NULL FROM attachment_jobs WHERE attachment_id='{aid}'"), "t") + before_restart = queue_size() + check(before_restart == 1, "expected one published delivery in the isolated queue") + api_before = started_at("api") + broker_before = started_at("broker") + compose("restart", "api", "broker") + after_restart = wait_for(queue_size, before_restart) + api_after = started_at("api") + check(len(api_before) >= 2 and len(api_after) == len(api_before) and all(t not in api_before for t in api_after), + "expected both API replicas to restart") + check(started_at("broker") != broker_before, "broker was not restarted") + admin("get", "messages", "--queue", "attachments.v1", "--ack-mode", "reject_requeue_true") + job_id = sql(f"SELECT id FROM attachment_jobs WHERE attachment_id='{aid}'") + finally: + compose("start", "worker") + ready = client.wait_ready(bob, attachment) + thumb = client.call("GET", route + "/content?variant=thumbnail", actor=bob)["bytes"] + check(jpeg_size(thumb) == (256, 160), "invalid JPEG size") + check(client.call("GET", route + "/content", actor=bob)["bytes"] == content, "original changed") + wait_for(lambda: f"Ack job {job_id} attempt 1 redelivered True" in compose("logs", "worker"), True) + check(len(ready["variants"]) >= 1, "thumbnail missing from metadata") + check(sql(f"SELECT count(*) FROM attachment_variants WHERE attachment_id='{aid}' AND name='thumbnail'") == "1", + "duplicate thumbnails") + print(json.dumps({"scenario": "restart_and_redelivery", "attachment": aid, "job": job_id, + "api_replicas": len(api_before), "queue_before": before_restart, + "queue_after": after_restart, "thumbnail": list(jpeg_size(thumb)), + "original_sha256": hashlib.sha256(content).hexdigest(), "seconds": round(time.monotonic() - started, 2), + "redelivered": True, "result": "PASS"})) + + +def job(aid, version=1): + return json.loads(sql(f""" + SELECT json_build_object('id', id, 'attempt', attempt, 'published', published_at IS NOT NULL, + 'lease', lease_until IS NOT NULL, 'created_at', created_at) + FROM attachment_jobs WHERE attachment_id='{aid}' AND pipeline_version={version} + """)) + + +def state(aid): + return sql(f"SELECT status FROM attachments WHERE id='{aid}'") + + +def variant_counts(aid): + return sql(f""" + SELECT pipeline_version, count(*) FROM attachment_variants + WHERE attachment_id='{aid}' GROUP BY pipeline_version ORDER BY pipeline_version + """) + + +def inject(service, fault, aid, attempt=None): + target = f"{fault}:{aid}" if attempt is None else f"{fault}:{aid}:{attempt}" + result = run_compose("run", "--rm", "--no-deps", "-e", f"LAB5_TEST_FAULT={target}", + "-e", "JOB_TIMEOUT_SECONDS=10", service) + check(result.returncode == 71 and f"Injected fault {fault}" in result.stderr, + f"{fault} did not terminate at the expected point (exit {result.returncode})") + + +def verify_outputs(client, actor, attachment, original): + ready = client.wait_ready(actor, attachment) + expected = {"thumbnail": ("image/jpeg", (256, 160)), "crop": ("image/jpeg", (128, 128)), + "optimized": ("image/webp", (320, 200))} + route = "/api/v1/attachments/" + ready["id"] + check(client.call("GET", route + "/content", actor=actor)["bytes"] == original, "original changed") + check({v["name"] for v in ready["variants"]} == expected.keys(), "variant set differs") + for variant in ready["variants"]: + name = variant["name"] + mime, dimensions = expected[name] + response = client.call("GET", route + "/content?variant=" + name, actor=actor) + data = response["bytes"] + check(variant["content_type"] == response["headers"].get_content_type() == mime, "incorrect MIME") + check((variant["width"], variant["height"]) == dimensions, "incorrect variant dimensions") + if mime == "image/jpeg": + check(jpeg_size(data) == dimensions, "incorrect JPEG dimensions") + else: + check(webp_size(data) == dimensions, "incorrect WebP dimensions") + check(hashlib.sha256(data).hexdigest() == variant["sha256"], "checksum mismatch") + return ready + + +def webp_size(data): + check(data[:4] == b"RIFF" and data[8:12] == b"WEBP", "invalid WebP") + kind = data[12:16] + if kind == b"VP8X": + return tuple(1 + int.from_bytes(data[i:i + 3], "little") for i in (24, 27)) + if kind == b"VP8L": + packed = int.from_bytes(data[21:25], "little") + return (1 + (packed & 0x3fff), 1 + (packed >> 14 & 0x3fff)) + check(kind == b"VP8 " and data[23:26] == b"\x9d\x01\x2a", "invalid VP8 frame") + return tuple(int.from_bytes(data[i:i + 2], "little") & 0x3fff for i in (26, 28)) + + +def failures(client): + started = time.monotonic() + alice, _, _, chat = client.bootstrap() + compose("stop", "dispatcher", "worker") + try: + attachment, original = client.attachment(alice, chat) + aid = attachment["id"] + accepted = job(aid) + check(not accepted["published"] and state(aid) == "queued", "outbox did not persist first") + inject("dispatcher", "before-publish", aid) + check(job(aid) == accepted, "crash changed unpublished job") + compose("start", "dispatcher") + wait_for(lambda: job(aid)["published"], True) + inject("worker", "before-write", aid) + check(state(aid) == "processing" and job(aid)["lease"] and variant_counts(aid) == "", "invalid pre-write state") + route = "/api/v1/attachments/" + aid + processing = client.call("GET", route, actor=alice, schema="Attachment")["json"] + check(processing["status"] == "processing", "API did not expose processing") + client.call("GET", route + "/content", 409, actor=alice) + wait_for(lambda: job(aid)["attempt"], 2, 85) + wait_for(lambda: job(aid)["published"], True) + inject("worker", "after-write", aid) + check(state(aid) == "processing" and variant_counts(aid) == "", "uncommitted results became visible") + wait_for(lambda: job(aid)["attempt"], 3, 85) + wait_for(lambda: job(aid)["published"], True) + inject("worker", "before-ack", aid, attempt=3) + check(state(aid) == "ready" and variant_counts(aid) == "1|3", "result not committed before ack") + saved = verify_outputs(client, alice, attachment, original) + finally: + compose("start", "dispatcher", "worker") + wait_for(lambda: f'Ack job {accepted["id"]} attempt 3 redelivered True' in compose("logs", "worker"), True) + check(verify_outputs(client, alice, attachment, original) == saved, "redelivery changed ready result") + check(variant_counts(aid) == "1|3", "redelivery duplicated variants") + print(json.dumps({"scenario": "crash_windows", "attachment": aid, "job": accepted["id"], + "attempt": job(aid)["attempt"], "committed_variants": variant_counts(aid), + "seconds": round(time.monotonic() - started, 2), "result": "PASS"})) + + +def publish(aid, version, entry, attempt=None): + body = json.dumps({"schema_version": 1, "type": "attachment.process.v1", "job_id": entry["id"], + "attachment_id": aid, "pipeline_version": version, + "attempt": entry["attempt"] if attempt is None else attempt, "created_at": entry["created_at"]}, + separators=(",", ":")) + admin("publish", "message", "--routing-key", "attachments.v1", "--payload", body) + + +def versions(client): + started = time.monotonic() + alice, _, _, chat = client.bootstrap() + attachment, original = client.attachment(alice, chat) + aid = attachment["id"] + version_one = verify_outputs(client, alice, attachment, original) + first = job(aid) + compose("stop", "dispatcher", "worker") + try: + compose("exec", "-T", "api", "dotnet", "Messenger.Api.dll", "--upgrade-attachment", aid) + second = job(aid, 2) + # Сначала фиктивная будущая попытка v2 и устаревшая v1, затем действительная v2. + publish(aid, 2, second, attempt=2) + publish(aid, 1, first) + compose("start", "dispatcher") + wait_for(lambda: job(aid, 2)["published"], True) + publish(aid, 2, second) + compose("start", "worker") + version_two = verify_outputs(client, alice, attachment, original) + wait_for(lambda: compose("logs", "worker").count(f'Ack job {second["id"]}'), 3) + check(version_one["variants"] != version_two["variants"], "v2 did not produce a distinguishable result") + previous_acks = compose("logs", "worker").count(f'Ack job {first["id"]}') + publish(aid, 1, first) + wait_for(lambda: compose("logs", "worker").count(f'Ack job {first["id"]}'), previous_acks + 1) + check(verify_outputs(client, alice, attachment, original) == version_two, "v1 overwrote v2") + check(variant_counts(aid).splitlines() == ["1|3", "2|3"], "versioned effect keys are not unique") + finally: + compose("start", "dispatcher", "worker") + print(json.dumps({"scenario": "duplicate_reorder_old_version", "attachment": aid, + "v1": first["id"], "v2": second["id"], "committed_variants": variant_counts(aid), + "v1_sha256": next(v["sha256"] for v in version_one["variants"] if v["name"] == "thumbnail"), + "v2_sha256": next(v["sha256"] for v in version_two["variants"] if v["name"] == "thumbnail"), + "seconds": round(time.monotonic() - started, 2), "result": "PASS"})) + + +def retry_and_replay(client): + started = time.monotonic() + alice, _, _, chat = client.bootstrap() + compose("stop", "worker") + name = "lab5-test-retry" + try: + attachment, original = client.attachment(alice, chat) + aid = attachment["id"] + queued_message = client.message(alice, chat, "", key="retry-demo", attachments=[aid])["json"] + compose("run", "-d", "--rm", "--no-deps", "--name", name, "-e", f"LAB5_TEST_FAULT=transient:{aid}", + "-e", "JOB_MAX_ATTEMPTS=2", "worker") + wait_for(lambda: state(aid), "failed") + route = "/api/v1/attachments/" + aid + failed = client.call("GET", route, actor=alice, schema="Attachment")["json"] + check(failed["error_code"] == "retry_exhausted" and job(aid)["attempt"] == 2, "retry limit not enforced") + client.call("GET", route + "/content", 409, actor=alice) + client.call("POST", "/api/v1/chats/" + chat["id"] + "/messages", 409, actor=alice, + body={"text": "", "attachment_ids": [aid]}, headers={"Idempotency-Key": "failed-new"}) + jid = job(aid)["id"] + check(jid in compose("exec", "-T", "api", "dotnet", "Messenger.Api.dll", "--failed-jobs"), "job missing from registry") + check(client.message(alice, chat, "", key="retry-demo", attachments=[aid])["json"] == queued_message, + "existing message replay lost its result") + finally: + subprocess.run(["docker", "stop", name], cwd=ROOT, capture_output=True, timeout=20) + compose("start", "worker") + compose("exec", "-T", "api", "dotnet", "Messenger.Api.dll", "--replay-job", jid) + verify_outputs(client, alice, attachment, original) + wait_for(lambda: sql(f"SELECT count(*) FROM upload_intents WHERE id='{aid}'"), "0") + rejected = run_compose("exec", "-T", "api", "dotnet", "Messenger.Api.dll", "--replay-job", jid) + check(rejected.returncode == 2, "ready job can be replayed") + print(json.dumps({"scenario": "bounded_retry_replay", "attachment": aid, "job": jid, + "failed_attempt": 2, "recovery_attempt": job(aid)["attempt"], + "seconds": round(time.monotonic() - started, 2), "result": "PASS"})) + + +def synthetic_png(width, height, scanline): + def chunk(kind, data): + return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data)) + + header = struct.pack(">2I5B", width, height, 8, 2, 0, 0, 0) + return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", header) + + chunk(b"IDAT", zlib.compress(scanline)) + chunk(b"IEND", b"")) + + +def image_limits(client): + alice, _, _, chat = client.bootstrap() + upload = f'/api/v1/chats/{chat["id"]}/attachments?filename=boundary.png' + headers = {"Content-Type": "image/png"} + results = {} + for name, body, expected in ( + ("bytes", b"0" * 10485761, 413), + ("pixels", synthetic_png(8000, 6000, b"\0"), 413), + ("wrong_signature", b"not a PNG file", 415)): + results[name] = client.call("POST", upload, expected, actor=alice, headers=headers, raw=body)["status"] + + # У файла корректны структура, CRC и zlib, но фильтр строки вне диапазона PNG. + upload_response = client.call("POST", upload, 202, actor=alice, headers=headers, schema="Attachment", + raw=synthetic_png(1, 1, b"\x05\x00\x00\x00")) + aid = upload_response["json"]["id"] + route = "/api/v1/attachments/" + aid + wait_for(lambda: client.call("GET", route, actor=alice, schema="Attachment")["json"]["status"], "failed") + failed = client.call("GET", route, actor=alice, schema="Attachment")["json"] + entry = job(aid) + check(failed["error_code"] == "invalid_image" and entry["attempt"] == 1 and not entry["lease"], + "permanent decoder failure should terminate on the first attempt") + check(not failed["variants"] and variant_counts(aid) == "", "invalid image produced variants") + client.call("GET", route + "/content", 409, actor=alice) + print(json.dumps({"scenario": "image_limits_and_permanent_failure", "attachment": aid, **results, + "error_code": failed["error_code"], "attempt": entry["attempt"], "result": "PASS"})) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--base-url", default=None) + scenarios = {"minimum": minimum, "failures": failures, "versions": versions, + "retry": retry_and_replay, "limits": image_limits} + parser.add_argument("--scenario", choices=[*scenarios, "all"], default="all") + args = parser.parse_args() + client = Client(args.base_url) + for name, test in scenarios.items(): + if args.scenario in (name, "all"): + wait_for(lambda: client.call("GET", "/health/ready", schema="Health")["json"]["status"], "ok") + test(client) + + +if __name__ == "__main__": + main() diff --git a/tools/LoadTest/Helpers.cs b/tools/LoadTest/Helpers.cs new file mode 100644 index 00000000..c4c5fc6a --- /dev/null +++ b/tools/LoadTest/Helpers.cs @@ -0,0 +1,62 @@ +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Http.Json; +using System.Text; +using System.Text.Json; + +namespace LoadTest +{ + internal sealed record TestUser(Guid Id, string Username); + internal class Helpers + { + public static StringContent Json(string raw) => + new(raw, Encoding.UTF8, "application/json"); + + public static HttpRequestMessage Request(HttpMethod method, string url, Guid? userId = null, HttpContent? content = null) + { + var request = new HttpRequestMessage(method, url) { Content = content }; + if (userId is not null) + { + request.Headers.Add("X-User-Id", userId.Value.ToString()); + } + + return request; + } + + public static async Task ReadJsonAsync(HttpResponseMessage response) + { + var body = await response.Content.ReadAsStringAsync(); + return JsonDocument.Parse(body).RootElement.Clone(); + } + + public static async Task CreateUserAsync(HttpClient client, string? username = null) + { + username ??= "u" + Guid.NewGuid().ToString("N")[..12]; + var response = await client.PostAsJsonAsync("/api/v1/users", + new { username, display_name = "Тест" }); + var json = await ReadJsonAsync(response); + response.EnsureSuccessStatusCode(); + return new TestUser(json.GetProperty("id").GetGuid(), username); + } + + public static async Task CreateChatAsync(HttpClient client, TestUser owner, params TestUser[] others) + { + var members = others.Append(owner).Select(u => u.Id).ToArray(); + using var request = Request(HttpMethod.Post, "/api/v1/chats", owner.Id, + JsonContent.Create(new { title = "Чат", member_ids = members })); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + return (await ReadJsonAsync(response)).GetProperty("id").GetGuid(); + } + + public static async Task SendMessageAsync(HttpClient client, TestUser sender, Guid chatId, string text) + { + using var request = Request(HttpMethod.Post, $"/api/v1/chats/{chatId}/messages", sender.Id, + JsonContent.Create(new { text })); + var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + return response; + } + } +} diff --git a/tools/LoadTest/LoadTest.csproj b/tools/LoadTest/LoadTest.csproj new file mode 100644 index 00000000..ed9781c2 --- /dev/null +++ b/tools/LoadTest/LoadTest.csproj @@ -0,0 +1,10 @@ + + + + Exe + net10.0 + enable + enable + + + diff --git a/tools/LoadTest/Phases.cs b/tools/LoadTest/Phases.cs new file mode 100644 index 00000000..46a4f82d --- /dev/null +++ b/tools/LoadTest/Phases.cs @@ -0,0 +1,143 @@ +using System.Diagnostics; + +namespace LoadTest +{ + /// Пользователь и чат с заранее залитой историей; Cursor — позиция нужной страницы (null = первая). + internal sealed record Scenario(Guid UserId, Guid ChatId, string? Cursor); + + /// Сырые данные измерения: задержки успешных запросов, число ошибок и фактическая длительность. + internal sealed record MeasureResult(List LatenciesMs, int Errors, double ElapsedSeconds); + + internal sealed record Summary( + int Successful, + int Errors, + double ElapsedSeconds, + double Rps, + double P50Ms, + double P95Ms, + double P99Ms, + double MaxMs); + + internal static class Phases + { + /// Создаёт пользователя и чат и заливает historySize сообщений не более чем в fillConcurrency потоков. + public static async Task PrepareAsync( + HttpClient client, int historySize, int fillConcurrency, int limit, bool lastPage) + { + var user = await Helpers.CreateUserAsync(client); + var chatId = await Helpers.CreateChatAsync(client, user); + + var options = new ParallelOptions { MaxDegreeOfParallelism = fillConcurrency }; + await Parallel.ForEachAsync(Enumerable.Range(0, historySize), options, async (i, _) => + { + using var response = await Helpers.SendMessageAsync(client, user, chatId, $"history message {i}"); + response.EnsureSuccessStatusCode(); + }); + + string? cursor = null; + if (lastPage) + { + cursor = await FindLastPageCursorAsync(client, user, chatId, limit); + } + + return new Scenario(user.Id, chatId, cursor); + } + + public static async Task WarmUpAsync( + HttpClient client, Scenario scenario, int clients, TimeSpan duration, int limit) + { + // Результат прогрева отбрасывается: он нужен только для JIT, пулов потоков и соединений. + await MeasureAsync(client, scenario, clients, duration, limit); + } + + /// Замкнутый цикл: каждый из clients клиентов шлёт GET страницы истории до истечения duration. + public static async Task MeasureAsync( + HttpClient client, Scenario scenario, int clients, TimeSpan duration, int limit) + { + var url = PageUrl(scenario.ChatId, limit, scenario.Cursor); + var started = Stopwatch.GetTimestamp(); + var deadline = started + (long)(duration.TotalSeconds * Stopwatch.Frequency); + + // У каждого клиента свой список задержек: общей изменяемой структуры нет, блокировки не нужны. + var workers = Enumerable.Range(0, clients).Select(_ => Task.Run(async () => + { + var latencies = new List(); + var errors = 0; + while (Stopwatch.GetTimestamp() < deadline) + { + var requestStarted = Stopwatch.GetTimestamp(); + try + { + using var request = Helpers.Request(HttpMethod.Get, url, scenario.UserId); + // Тело читается целиком (буферизация по умолчанию), но не разбирается как JSON. + using var response = await client.SendAsync(request); + if (response.IsSuccessStatusCode) + { + latencies.Add(Stopwatch.GetElapsedTime(requestStarted).TotalMilliseconds); + } + else + { + errors++; + } + } + catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException) + { + errors++; + } + } + + return (latencies, errors); + })).ToArray(); + + var results = await Task.WhenAll(workers); + var elapsed = Stopwatch.GetElapsedTime(started).TotalSeconds; + + return new MeasureResult( + results.SelectMany(r => r.latencies).ToList(), + results.Sum(r => r.errors), + elapsed); + } + + public static Summary GetResults(MeasureResult result) + { + var sorted = result.LatenciesMs.OrderBy(x => x).ToList(); + double Percentile(double p) => + sorted.Count == 0 ? double.NaN : sorted[Math.Max(0, (int)Math.Ceiling(p * sorted.Count) - 1)]; + + return new Summary( + sorted.Count, + result.Errors, + Math.Round(result.ElapsedSeconds, 3), + Math.Round(sorted.Count / result.ElapsedSeconds, 2), + Math.Round(Percentile(0.50), 3), + Math.Round(Percentile(0.95), 3), + Math.Round(Percentile(0.99), 3), + sorted.Count == 0 ? double.NaN : Math.Round(sorted[^1], 3)); + } + + private static string PageUrl(Guid chatId, int limit, string? cursor) => + $"/api/v1/chats/{chatId}/messages?limit={limit}" + + (cursor is null ? "" : "&cursor=" + Uri.EscapeDataString(cursor)); + + /// Идёт по страницам до конца и возвращает cursor, с которым была запрошена последняя страница. + private static async Task FindLastPageCursorAsync( + HttpClient client, TestUser user, Guid chatId, int limit) + { + string? cursor = null; + while (true) + { + using var request = Helpers.Request(HttpMethod.Get, PageUrl(chatId, limit, cursor), user.Id); + using var response = await client.SendAsync(request); + response.EnsureSuccessStatusCode(); + var page = await Helpers.ReadJsonAsync(response); + var next = page.GetProperty("next_cursor"); + if (next.ValueKind == System.Text.Json.JsonValueKind.Null) + { + return cursor; + } + + cursor = next.GetString(); + } + } + } +} diff --git a/tools/LoadTest/Program.cs b/tools/LoadTest/Program.cs new file mode 100644 index 00000000..2025f313 --- /dev/null +++ b/tools/LoadTest/Program.cs @@ -0,0 +1,91 @@ +using System.Text.Json; +using LoadTest; + +// Использование (запускать в Release, сервер должен быть уже запущен): +// dotnet run -c Release --project tools/LoadTest -- --history 10000 --clients 8 --duration 15 \ +// --container mtusi-messenger-lab1 --label before --output evidence/track1/results.jsonl +var options = ParseArguments(args); +string Get(string key, string fallback) => options.TryGetValue(key, out var value) ? value : fallback; + +var url = Get("url", "http://127.0.0.1:8080"); +var history = int.Parse(Get("history", "1000")); +var clients = int.Parse(Get("clients", "1")); +var duration = TimeSpan.FromSeconds(double.Parse(Get("duration", "15"))); +var warmup = TimeSpan.FromSeconds(double.Parse(Get("warmup", "3"))); +var limit = int.Parse(Get("limit", "50")); +var fillConcurrency = int.Parse(Get("fill-concurrency", "16")); +var lastPage = Get("page", "first") == "last"; +var container = options.GetValueOrDefault("container"); +var label = Get("label", "run"); +var output = options.GetValueOrDefault("output"); + +using var client = new HttpClient { BaseAddress = new Uri(url), Timeout = TimeSpan.FromSeconds(30) }; + +var rssIdle = Rss.ReadMegabytes(container); +Console.Error.WriteLine($"[1/4] prepare: filling {history} messages ({fillConcurrency} parallel)..."); +var scenario = await Phases.PrepareAsync(client, history, fillConcurrency, limit, lastPage); +var rssAfterPrepare = Rss.ReadMegabytes(container); + +Console.Error.WriteLine($"[2/4] warm-up: {warmup.TotalSeconds} s, {clients} clients"); +await Phases.WarmUpAsync(client, scenario, clients, warmup, limit); + +Console.Error.WriteLine($"[3/4] measure: {duration.TotalSeconds} s, {clients} clients, page={(lastPage ? "last" : "first")}"); +var measured = await Phases.MeasureAsync(client, scenario, clients, duration, limit); +var rssAfterMeasure = Rss.ReadMegabytes(container); + +Console.Error.WriteLine("[4/4] results"); +var summary = Phases.GetResults(measured); + +var report = new +{ + label, + timestamp = DateTimeOffset.UtcNow.ToString("O"), + history, + clients, + page = lastPage ? "last" : "first", + limit, + duration_seconds = duration.TotalSeconds, + successful_requests = summary.Successful, + errors = summary.Errors, + elapsed_seconds = summary.ElapsedSeconds, + rps = summary.Rps, + p50_ms = summary.P50Ms, + p95_ms = summary.P95Ms, + p99_ms = summary.P99Ms, + max_ms = summary.MaxMs, + rss_mb_idle = rssIdle, + rss_mb_after_prepare = rssAfterPrepare, + rss_mb_after_measure = rssAfterMeasure, +}; + +var json = JsonSerializer.Serialize(report, new JsonSerializerOptions { WriteIndented = false }); +Console.WriteLine(JsonSerializer.Serialize(report, new JsonSerializerOptions { WriteIndented = true })); + +if (output is not null) +{ + Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(output))!); + File.AppendAllText(output, json + Environment.NewLine); +} + +return summary.Errors == 0 && summary.Successful > 0 ? 0 : 1; + +static Dictionary ParseArguments(string[] args) +{ + var result = new Dictionary(); + for (var i = 0; i < args.Length; i++) + { + if (!args[i].StartsWith("--")) + { + throw new ArgumentException($"Unexpected argument: {args[i]}"); + } + + if (i + 1 >= args.Length) + { + throw new ArgumentException($"Missing value for {args[i]}"); + } + + result[args[i][2..]] = args[++i]; + } + + return result; +} diff --git a/tools/LoadTest/Rss.cs b/tools/LoadTest/Rss.cs new file mode 100644 index 00000000..6b2fdeb0 --- /dev/null +++ b/tools/LoadTest/Rss.cs @@ -0,0 +1,45 @@ +using System.Diagnostics; + +namespace LoadTest +{ + internal static class Rss + { + /// + /// RSS процесса приложения в МБ: читает VmRSS из /proc/1/status внутри контейнера + /// (PID 1 — dotnet, ENTRYPOINT в exec-форме). Возвращает null, если контейнер не задан или недоступен. + /// + public static double? ReadMegabytes(string? container) + { + if (string.IsNullOrEmpty(container)) + { + return null; + } + + try + { + var info = new ProcessStartInfo("docker", ["exec", container, "cat", "/proc/1/status"]) + { + RedirectStandardOutput = true, + RedirectStandardError = true, + }; + using var process = Process.Start(info)!; + var output = process.StandardOutput.ReadToEnd(); + process.WaitForExit(); + + var line = output.Split('\n').FirstOrDefault(l => l.StartsWith("VmRSS:")); + if (line is null) + { + return null; + } + + var kb = double.Parse(line.Split(' ', StringSplitOptions.RemoveEmptyEntries)[1], + System.Globalization.CultureInfo.InvariantCulture); + return Math.Round(kb / 1024, 1); + } + catch (Exception) + { + return null; + } + } + } +} diff --git a/tools/LoadTest/run-matrix.ps1 b/tools/LoadTest/run-matrix.ps1 new file mode 100644 index 00000000..f71090a9 --- /dev/null +++ b/tools/LoadTest/run-matrix.ps1 @@ -0,0 +1,88 @@ +<# +.SYNOPSIS + Track 1: матрица размер истории x число клиентов с перезапуском контейнера на каждую точку. + +.EXAMPLE + # замеры "до" (образ уже собран) + .\tools\LoadTest\run-matrix.ps1 -Label before + # замеры "после": пересобрать образ и повторить те же точки + .\tools\LoadTest\run-matrix.ps1 -Label after -Rebuild + # быстрая проверка скрипта + .\tools\LoadTest\run-matrix.ps1 -Label smoke -Sizes 1000 -Clients 1 -Repeats 1 -Duration 3 -Warmup 2 -Output $env:TEMP\smoke.jsonl +#> +[CmdletBinding()] +param( + [string]$Label = 'before', + [int[]]$Sizes = @(1000, 10000, 50000), + [int[]]$Clients = @(1, 8, 32), + [int]$Repeats = 2, + [int]$Duration = 8, + [int]$Warmup = 5, + [string]$Cpus = '2', + [string]$Memory = '512m', + [string]$Output = 'evidence/track1/results.jsonl', + [string]$Image = 'mtusi-messenger:lab1', + [ValidateSet('first', 'last')][string]$Page = 'first', + [switch]$Rebuild +) + +$ErrorActionPreference = 'Stop' +Set-Location (Resolve-Path (Join-Path $PSScriptRoot '..\..')) + +$name = 'mtusi-messenger-lab1' +$url = 'http://127.0.0.1:8080' + +function Remove-Api { + if (docker ps -aq --filter "name=^/$name$") { + docker rm -f $name | Out-Null + } +} + +function Start-Api { + Remove-Api + docker run -d --rm --name $name --cpus $Cpus --memory $Memory ` + -p 127.0.0.1:8080:8080 --env-file .env $Image | Out-Null + for ($i = 0; $i -lt 60; $i++) { + try { + if ((Invoke-WebRequest "$url/health/ready" -UseBasicParsing -TimeoutSec 2).StatusCode -eq 200) { return } + } catch { } + Start-Sleep -Milliseconds 500 + } + throw 'API did not become ready within 30 s' +} + +if ($Rebuild) { + Write-Host 'Rebuilding image...' + docker build -t $Image . | Out-Null + if ($LASTEXITCODE -ne 0) { throw 'docker build failed' } +} + +dotnet build tools/LoadTest -c Release -v q | Out-Null +if ($LASTEXITCODE -ne 0) { throw 'LoadTest build failed' } + +$points = @(foreach ($n in $Sizes) { foreach ($c in $Clients) { [pscustomobject]@{ History = $n; Clients = $c } } }) +$total = $points.Count * $Repeats +$done = 0 +$started = Get-Date +Write-Host "Label=$Label page=$Page points=$($points.Count) repeats=$Repeats runs=$total cpus=$Cpus memory=$Memory output=$Output" + +try { + for ($rep = 1; $rep -le $Repeats; $rep++) { + # Случайный порядок точек в каждом повторе: эффект прогрева не должен совпасть с одним размером. + foreach ($p in ($points | Sort-Object { Get-Random })) { + $done++ + Write-Host ("[{0}/{1}] rep={2} history={3} clients={4} (elapsed {5:mm\:ss})" -f $done, $total, $rep, $p.History, $p.Clients, ((Get-Date) - $started)) + Start-Api + dotnet run -c Release --project tools/LoadTest --no-build -- ` + --url $url --history $p.History --clients $p.Clients ` + --duration $Duration --warmup $Warmup ` + --page $Page --container $name --label "$Label-r$rep" --output $Output | Out-Null + if ($LASTEXITCODE -ne 0) { Write-Warning "run failed (exit $LASTEXITCODE), continuing" } + } + } +} +finally { + Remove-Api +} + +Write-Host ("Done in {0:mm\:ss}. Results appended to {1}" -f ((Get-Date) - $started), $Output) diff --git a/tools/LoadTest/summarize.py b/tools/LoadTest/summarize.py new file mode 100644 index 00000000..b307fdcf --- /dev/null +++ b/tools/LoadTest/summarize.py @@ -0,0 +1,76 @@ +import json, statistics as st, collections, sys + +path = sys.argv[1] +rows = [json.loads(l) for l in open(path, encoding='utf-8') if l.strip()] + +def group(prefix, page='first'): + g = collections.defaultdict(list) + for r in rows: + if r['label'].startswith(prefix) and r['page'] == page: + g[(r['history'], r['clients'])].append(r) + return g + +def mean(rs, k): + v = [r[k] for r in rs if r.get(k) is not None] + return st.mean(v) + +def rng(rs, k): + v = [r[k] for r in rs if r.get(k) is not None] + return min(v), max(v) + +before = group('before-r') +after = group('after-r') + +out = [] +out.append('Track 1: before/after summary (mean of repeats; page=first, limit=50; container --cpus=2 --memory=512m)') +out.append('') +hdr = f"{'N':>6} {'C':>3} {'runs':>4} | {'RPS before':>10} {'RPS after':>10} {'x':>6} | {'p50 b':>7} {'p50 a':>7} | {'p95 b':>7} {'p95 a':>7} | {'p99 b':>7} {'p99 a':>7} | {'RSS prep b/a':>12} {'RSS end b/a':>12} | err b/a" +out.append(hdr) +for key in sorted(set(before) | set(after)): + b, a = before.get(key, []), after.get(key, []) + if not b or not a: + continue + rb, ra = mean(b, 'rps'), mean(a, 'rps') + out.append( + f"{key[0]:>6} {key[1]:>3} {len(b):>1}/{len(a):<2} | {rb:>10.0f} {ra:>10.0f} {ra/rb:>6.1f} | " + f"{mean(b,'p50_ms'):>7.1f} {mean(a,'p50_ms'):>7.1f} | {mean(b,'p95_ms'):>7.1f} {mean(a,'p95_ms'):>7.1f} | " + f"{mean(b,'p99_ms'):>7.1f} {mean(a,'p99_ms'):>7.1f} | " + f"{mean(b,'rss_mb_after_prepare'):>5.0f}/{mean(a,'rss_mb_after_prepare'):<5.0f} {mean(b,'rss_mb_after_measure'):>5.0f}/{mean(a,'rss_mb_after_measure'):<5.0f} | " + f"{sum(r['errors'] for r in b)}/{sum(r['errors'] for r in a)}") + +out.append('') +out.append('RPS spread (min-max across repeats):') +for key in sorted(set(before) | set(after)): + b, a = before.get(key, []), after.get(key, []) + if b and a: + out.append(f" N={key[0]:>6} C={key[1]:>2} before {rng(b,'rps')[0]:.0f}-{rng(b,'rps')[1]:.0f} after {rng(a,'rps')[0]:.0f}-{rng(a,'rps')[1]:.0f}") + +out.append('') +out.append('Idle RSS (empty process, MB): before %.0f, after %.0f' % ( + st.mean([r['rss_mb_idle'] for rs in before.values() for r in rs]), + st.mean([r['rss_mb_idle'] for rs in after.values() for r in rs]))) + +# last page vs first page at N=50000, C=8 +bl, al = group('before-last', 'last'), group('after-last', 'last') +out.append('') +out.append('First vs last page, N=50000, C=8 (mean RPS / p95 ms):') +key = (50000, 8) +for name, g_first, g_last in (('before', before, bl), ('after', after, al)): + f, l = g_first.get(key, []), g_last.get(key, []) + if f and l: + out.append(f" {name}: first {mean(f,'rps'):.0f} rps / {mean(f,'p95_ms'):.1f} ms ({len(f)} runs); last {mean(l,'rps'):.0f} rps / {mean(l,'p95_ms'):.1f} ms ({len(l)} runs)") + +# saturation: RPS growth with clients per N +out.append('') +out.append('Throughput vs clients (mean RPS):') +for name, g in (('before', before), ('after', after)): + for n in sorted({k[0] for k in g}): + out.append(f" {name} N={n:>6}: " + ' '.join(f"C={c}: {mean(g[(n,c)],'rps'):.0f}" for c in sorted({k[1] for k in g if k[0]==n}))) + +# per-message cost under saturation (before): 1000/rps at C=32 -> ms per request +out.append('') +out.append('Service time at saturation, C=32 (ms per request = 1000/RPS):') +for name, g in (('before', before), ('after', after)): + out.append(f" {name}: " + ' '.join(f"N={n}: {1000/mean(g[(n,32)],'rps'):.3f}" for n in sorted({k[0] for k in g}) if (n, 32) in g)) + +print('\n'.join(out)) diff --git a/tools/ScaleLoad/Program.cs b/tools/ScaleLoad/Program.cs new file mode 100644 index 00000000..435c11da --- /dev/null +++ b/tools/ScaleLoad/Program.cs @@ -0,0 +1,209 @@ +using System.Diagnostics; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text; +using System.Text.Json; + +// Генератор нагрузки для трека 1 (цена масштабирования). Замкнутый цикл: каждый из --clients потоков шлёт запрос, +// ждёт ответ и сразу шлёт следующий. Профиль: --write-ratio доля POST сообщения (уникальный Idempotency-Key), +// остальное — GET страницы истории (limit=50). У каждого пользователя свой чат с --history сообщений, +// поэтому записи разных клиентов не сериализуются на одной строке чата. +// +// Запуск (стенд поднят): +// dotnet run -c Release --project tools/ScaleLoad -- --url http://localhost:8081 --clients 64 --duration 20 \ +// --label A-2x1.0 --output evidence/track1/results.jsonl +// Загрузка CPU контейнеров снимается `docker stats` во время измерения (если доступен docker CLI). +var o = ParseArguments(args); +string Get(string k, string d) => o.TryGetValue(k, out var v) ? v : d; +var url = Get("url", "http://localhost:8080"); +var clients = int.Parse(Get("clients", "32")); +var users = int.Parse(Get("users", "32")); +var history = int.Parse(Get("history", "200")); +var duration = TimeSpan.FromSeconds(double.Parse(Get("duration", "20"))); +var warmup = TimeSpan.FromSeconds(double.Parse(Get("warmup", "5"))); +var writeRatio = double.Parse(Get("write-ratio", "0.2"), System.Globalization.CultureInfo.InvariantCulture); +var label = Get("label", "run"); +var output = o.GetValueOrDefault("output"); +var project = Get("compose-project", "messenger-lab3"); + +var handler = new SocketsHttpHandler { MaxConnectionsPerServer = clients * 2, PooledConnectionLifetime = TimeSpan.FromMinutes(5) }; +using var http = new HttpClient(handler) { BaseAddress = new Uri(url), Timeout = TimeSpan.FromSeconds(30) }; + +Console.Error.WriteLine($"[1/4] prepare: {users} users, {history} messages per chat"); +var actors = await Prepare(http, users, history); + +Console.Error.WriteLine($"[2/4] warm-up {warmup.TotalSeconds}s, {clients} clients"); +await Measure(http, actors, clients, warmup, writeRatio); + +Console.Error.WriteLine($"[3/4] measure {duration.TotalSeconds}s"); +using var statsCts = new CancellationTokenSource(); +var statsTask = Task.Run(() => SampleDockerStats(project, statsCts.Token)); +var r = await Measure(http, actors, clients, duration, writeRatio); +statsCts.Cancel(); +var stats = await statsTask; + +Console.Error.WriteLine("[4/4] results"); +var lat = r.Latencies.OrderBy(x => x).ToArray(); +double P(double p) => lat.Length == 0 ? double.NaN : Math.Round(lat[Math.Max(0, (int)Math.Ceiling(p * lat.Length) - 1)], 2); +var report = new Dictionary +{ + ["label"] = label, + ["timestamp"] = DateTimeOffset.UtcNow.ToString("O"), + ["clients"] = clients, ["users"] = users, ["history"] = history, ["write_ratio"] = writeRatio, + ["duration_s"] = Math.Round(r.Elapsed, 2), + ["ok"] = lat.Length, ["errors"] = r.Errors, ["ok_get"] = r.OkGet, ["ok_post"] = r.OkPost, + ["rps"] = Math.Round(lat.Length / r.Elapsed, 1), + ["p50_ms"] = P(0.50), ["p95_ms"] = P(0.95), ["p99_ms"] = P(0.99), + ["cpu_pct"] = stats, +}; +var line = JsonSerializer.Serialize(report); +Console.WriteLine(line); +if (output is not null) +{ + Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(output))!); + File.AppendAllText(output, line + Environment.NewLine); +} +return r.Errors == 0 ? 0 : 1; + +static async Task Prepare(HttpClient http, int users, int history) +{ + var result = new Actor[users]; + await Parallel.ForEachAsync(Enumerable.Range(0, users), new ParallelOptions { MaxDegreeOfParallelism = 4 }, async (i, ct) => + { + var username = "sl" + Guid.NewGuid().ToString("N")[..14]; + var password = "Load-" + Guid.NewGuid().ToString("N"); + using var reg = await http.PostAsJsonAsync("/api/v1/users", new { username, display_name = "Load", password }, ct); + reg.EnsureSuccessStatusCode(); + var me = (await reg.Content.ReadFromJsonAsync(ct)).GetProperty("id").GetGuid(); + using var login = new HttpRequestMessage(HttpMethod.Post, "/api/v1/auth/sessions"); + login.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{username}:{password}"))); + using var loginResponse = await http.SendAsync(login, ct); + loginResponse.EnsureSuccessStatusCode(); + var token = (await loginResponse.Content.ReadFromJsonAsync(ct)).GetProperty("token").GetString()!; + using var chatRequest = Authorized(HttpMethod.Post, "/api/v1/chats", token); + chatRequest.Content = JsonContent.Create(new { title = "Load", member_ids = new[] { me } }); + using var chatResponse = await http.SendAsync(chatRequest, ct); + chatResponse.EnsureSuccessStatusCode(); + var chatId = (await chatResponse.Content.ReadFromJsonAsync(ct)).GetProperty("id").GetGuid(); + for (var m = 0; m < history; m++) + { + using var post = PostMessage(chatId, token, $"history {m}"); + using var response = await http.SendAsync(post, ct); + response.EnsureSuccessStatusCode(); + } + result[i] = new Actor(token, chatId); + }); + return result; +} + +static HttpRequestMessage Authorized(HttpMethod method, string path, string token) +{ + var request = new HttpRequestMessage(method, path); + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); + return request; +} + +static HttpRequestMessage PostMessage(Guid chatId, string token, string text) +{ + var request = Authorized(HttpMethod.Post, $"/api/v1/chats/{chatId}/messages", token); + request.Headers.Add("Idempotency-Key", Guid.NewGuid().ToString("N")); + request.Content = JsonContent.Create(new { text }); + return request; +} + +static async Task Measure(HttpClient http, Actor[] actors, int clients, TimeSpan duration, double writeRatio) +{ + var started = Stopwatch.GetTimestamp(); + var deadline = started + (long)(duration.TotalSeconds * Stopwatch.Frequency); + var workers = Enumerable.Range(0, clients).Select(i => Task.Run(async () => + { + var actor = actors[i % actors.Length]; + var rnd = new Random(i * 7919 + Environment.TickCount); + var latencies = new List(); + int errors = 0, okGet = 0, okPost = 0; + while (Stopwatch.GetTimestamp() < deadline) + { + var write = rnd.NextDouble() < writeRatio; + var t = Stopwatch.GetTimestamp(); + try + { + using var request = write + ? PostMessage(actor.ChatId, actor.Token, "load " + Guid.NewGuid().ToString("N")) + : Authorized(HttpMethod.Get, $"/api/v1/chats/{actor.ChatId}/messages?limit=50", actor.Token); + using var response = await http.SendAsync(request); + await response.Content.ReadAsByteArrayAsync(); + if (response.IsSuccessStatusCode) + { + latencies.Add(Stopwatch.GetElapsedTime(t).TotalMilliseconds); + if (write) okPost++; else okGet++; + } + else + { + errors++; + } + } + catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException) + { + errors++; + } + } + + return (latencies, errors, okGet, okPost); + })).ToArray(); + + var results = await Task.WhenAll(workers); + return new Result( + results.SelectMany(x => x.latencies).ToList(), results.Sum(x => x.errors), + results.Sum(x => x.okGet), results.Sum(x => x.okPost), Stopwatch.GetElapsedTime(started).TotalSeconds); +} + +// Средняя загрузка CPU (в % одного ядра, как в docker stats) по роли контейнера за время измерения. +static async Task> SampleDockerStats(string project, CancellationToken ct) +{ + var sums = new Dictionary(); + try + { + while (!ct.IsCancellationRequested) + { + var info = new ProcessStartInfo("docker", ["stats", "--no-stream", "--format", "{{.Name}} {{.CPUPerc}}"]) + { RedirectStandardOutput = true, RedirectStandardError = true }; + using var p = Process.Start(info)!; + var text = await p.StandardOutput.ReadToEndAsync(ct); + await p.WaitForExitAsync(ct); + // Внутри одного снимка суммируем реплики одной роли, затем усредняем снимки. + var snapshot = new Dictionary(); + foreach (var line in text.Split('\n', StringSplitOptions.RemoveEmptyEntries)) + { + var parts = line.Trim().Split(' '); + if (parts.Length < 2 || !parts[0].StartsWith(project + "-")) continue; + var role = parts[0][(project.Length + 1)..]; + role = role[..role.LastIndexOf('-')]; + if (!double.TryParse(parts[1].TrimEnd('%'), System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var cpu)) continue; + snapshot[role] = snapshot.GetValueOrDefault(role) + cpu; + } + + foreach (var (role, cpu) in snapshot) + { + var (sum, n) = sums.GetValueOrDefault(role); + sums[role] = (sum + cpu, n + 1); + } + } + } + catch (OperationCanceledException) { } + catch (Exception) { } + return sums.ToDictionary(kv => kv.Key, kv => Math.Round(kv.Value.Sum / Math.Max(1, kv.Value.N), 1)); +} + +static Dictionary ParseArguments(string[] args) +{ + var result = new Dictionary(); + for (var i = 0; i < args.Length; i++) + { + if (!args[i].StartsWith("--") || i + 1 >= args.Length) throw new ArgumentException($"Bad argument: {args[i]}"); + result[args[i][2..]] = args[++i]; + } + return result; +} + +internal sealed record Actor(string Token, Guid ChatId); +internal sealed record Result(List Latencies, int Errors, int OkGet, int OkPost, double Elapsed); diff --git a/tools/ScaleLoad/ScaleLoad.csproj b/tools/ScaleLoad/ScaleLoad.csproj new file mode 100644 index 00000000..dfb40caa --- /dev/null +++ b/tools/ScaleLoad/ScaleLoad.csproj @@ -0,0 +1,10 @@ + + + + Exe + net10.0 + enable + enable + + + diff --git a/tools/ScaleLoad/compose.cpuset.yaml b/tools/ScaleLoad/compose.cpuset.yaml new file mode 100644 index 00000000..83c4136d --- /dev/null +++ b/tools/ScaleLoad/compose.cpuset.yaml @@ -0,0 +1,6 @@ +# Override для эксперимента трека 1: API закрепляется за ядрами (cpuset) вместо квоты CFS. +# Использование: COMPOSE_FILE=compose.yaml:tools/ScaleLoad/compose.cpuset.yaml API_CPUSET=0-1 API_CPUS=16 docker compose up -d ... +# API_CPUS=16 делает квоту CFS практически неограниченной: бюджет задаёт только cpuset. +services: + api: + cpuset: ${API_CPUSET:?задайте API_CPUSET, например 0-1} diff --git a/tools/ScaleLoad/run-config.sh b/tools/ScaleLoad/run-config.sh new file mode 100644 index 00000000..75442802 --- /dev/null +++ b/tools/ScaleLoad/run-config.sh @@ -0,0 +1,30 @@ +#!/bin/bash +# Один замер трека 1: применяет конфигурацию стенда (реплики/ресурсы), ждёт готовности LB и запускает ScaleLoad. +# Использование: +# tools/ScaleLoad/run-config.sh