diff --git a/.dockerignore b/.dockerignore index bc16e556..781f0450 100644 --- a/.dockerignore +++ b/.dockerignore @@ -16,5 +16,7 @@ backups .venv __pycache__ node_modules +**/bin +**/obj evidence .DS_Store diff --git a/.gitignore b/.gitignore index b5a71896..60be5d67 100644 --- a/.gitignore +++ b/.gitignore @@ -11,7 +11,7 @@ certs/private/ *.pem *.tfstate* volumes/ -data/ +/data/ backups/ # Runtime/build artifacts .venv/ @@ -30,3 +30,5 @@ coverage/ .vscode/ # Keep small, sanitized evidence summaries in evidence/ under version control. # Inspect git diff --cached: ignore rules are not a secret scanner. + +/.local/ diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..162159c5 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,39 @@ +FROM mcr.microsoft.com/dotnet/sdk:9.0.306 AS build + +WORKDIR /src + +COPY src/Messenger.Api/Messenger.Api.csproj src/Messenger.Api/ +RUN dotnet restore src/Messenger.Api/Messenger.Api.csproj + +COPY src/Messenger.Api/ src/Messenger.Api/ + +RUN dotnet publish src/Messenger.Api/Messenger.Api.csproj \ + -c Release \ + --no-restore \ + -o /app/publish + + +FROM mcr.microsoft.com/dotnet/aspnet:9.0.10 AS runtime + +RUN apt-get update \ + && apt-get install -y --no-install-recommends curl \ + && rm -rf /var/lib/apt/lists/* + +WORKDIR /app +ARG BUILD_REVISION=local +LABEL org.opencontainers.image.revision=$BUILD_REVISION + +COPY --from=build /app/publish . + +ENV APP_HOST=0.0.0.0 +ENV APP_PORT=8080 +ENV APP_ENV=lab + +EXPOSE 8080 + +USER app + +HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \ + CMD curl --fail --silent http://127.0.0.1:8080/health/ready > /dev/null || exit 1 + +ENTRYPOINT ["dotnet", "Messenger.Api.dll"] diff --git a/Makefile b/Makefile index 5d86d171..0d5c3b2b 100644 --- a/Makefile +++ b/Makefile @@ -1,5 +1,5 @@ -PYTHON ?= python3 -BASE_URL ?= http://localhost:8080 +PYTHON ?= .venv/bin/python +BASE_URL ?= http://localhost:18084 CA_FILE ?= ACTION_SCRIPT ?= TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) @@ -28,3 +28,32 @@ test-persistence: test-failover: @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2) $(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) + +.PHONY: setup up down build restore-api reconcile reconcile-apply +setup: + python3 -m venv .venv + .venv/bin/python -m pip install -r requirements-dev.txt + ./scripts/init-secrets.sh +up: + ./scripts/init-secrets.sh + ./scripts/compose.sh build api + ./scripts/compose.sh up -d --wait --wait-timeout 120 +build: + dotnet build src/Messenger.Api +restore-api: + ./scripts/compose.sh up -d --wait api lb +reconcile: + ./scripts/compose.sh exec -T api dotnet Messenger.Api.dll --reconcile +reconcile-apply: + ./scripts/compose.sh exec -T api dotnet Messenger.Api.dll --reconcile --apply +down: + ./scripts/compose.sh down + +.PHONY: student-test +student-test: + $(PYTHON) student-tests/attachments.py --base-url "$(BASE_URL)" + +.PHONY: research-grade5 +research-grade5: + $(PYTHON) student-tests/consistency.py --base-url "$(BASE_URL)" + diff --git a/REPORT.md b/REPORT.md index 9ad2b84f..6c9c9f92 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,188 @@ -# Отчёт — лабораторная 4 +# Лабораторная 4 -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +Автор: Каменский Никита, БВТ-2302. +Цель: 5, трек 2 «Согласованность двух хранилищ». +PR: [ЛР 4 - БВТ-2302 - Каменский - на 5](https://gitea.privcloud.tech/mtusi2026/mtusi2026lab4/pulls/97). -## Запуск из чистого clone +## Запуск -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +Нужны Docker Desktop, Python 3.9+, доступ в интернет для сборки. +Локальная сборка без Docker дополнительно требует .NET SDK 9. -## Архитектура и решения +```sh +make setup +make up +make check +make test +make student-test +make test-persistence ACTION_SCRIPT=scripts/restart.sh +make test-failover ACTION_SCRIPT=scripts/stop-one.sh +make restore-api +make research-grade5 +``` -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab3, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +Интерфейс: http://localhost:18084/. Регистрация требует пароль 12–128 символов. +Кнопка со скрепкой загружает PNG/JPEG; до отправки видна миниатюра, которую +можно убрать. В сообщении превью появляется автоматически. Нажатие открывает +просмотр на весь экран с увеличением, скачиванием и переходом между изображениями. +Стрелки клавиатуры перелистывают, Esc закрывает просмотр; на телефоне есть свайп. +Скачивание сохраняет исходное имя и байты файла. +Автоматический повтор загрузки не используется: повтор POST может создать новый файл. -## Доказательства критериев +Остановить с сохранением данных: `make down`. Намеренно удалить учебные данные: +`./scripts/compose.sh down -v`. Последняя команда удаляет PostgreSQL и S3 volumes. -| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | -| --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | +Секреты создаёт scripts/init-secrets.py в исключённой из Git папке secrets/. +Повторный запуск сохраняет существующие ключи. Миграции выполняет отдельный +сервис migrate с транзакционной блокировкой. s3-bootstrap создаёт bucket +только при его отсутствии и использует отдельную административную пару ключей. +API получает другую пару: Read/Write/List только bucket messenger. +Bootstrap не использует пользовательские credentials и не выводит их. -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +Версии: .NET SDK 9.0.306/runtime 9.0.10, PostgreSQL 17.6, Redis 7.4.2, +HAProxy 3.2.7-alpine, SeaweedFS 3.97, AWSSDK.S3 4.0.0, SkiaSharp 3.119.1. +Контейнер API работает под непривилегированным пользователем app. -## Эксперименты и отказы +## Архитектура -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +Клиент обращается к HAProxy, который распределяет запросы между двумя API. +PostgreSQL хранит пользователей, чаты, сообщения, сессии, ключи идемпотентности +и метаданные вложений. Redis хранит кэш сессий и heartbeat. SeaweedFS хранит +оригиналы в приватном S3 bucket. Наружу опубликован только HAProxy на localhost. -| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | -| --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +Из Lab3 перенесены собственные исходники, интерфейс, Dockerfile, HAProxy и +операционные скрипты. Skeleton, публичные tests и contracts взяты из Lab4. +Сопоставление всех критериев с файлами: docs/ARCHITECTURE.md. -## Ограничения и следующие шаги +Новые маршруты: POST /api/v1/chats/{id}/attachments, GET /api/v1/attachments/{id} +и GET /api/v1/attachments/{id}/content. Перед обработкой проверяются Bearer и +членство в чате; чужое и неизвестное вложение возвращают одинаковый 404. +Публичные метаданные не содержат object key и адрес S3. Filename никогда не +используется в пути. Случайный ключ: originals/. -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +У сообщения появился attachment_ids: 0–10 уникальных UUID из того же чата. +Пустой текст разрешён только с вложениями. Порядок ID сохраняется. Хеш +идемпотентности включает текст и массив ID. Отсутствующий массив равен []. +Запись сообщения и ключа идемпотентности остаётся одной транзакцией PostgreSQL. + +Превью запрашиваются с Bearer при приближении к видимой области, одновременно +не более двух загрузок. При уходе изображения за экран запрос отменяется, +blob URL освобождается; активный просмотр удерживает оригинал до закрытия. +При смене чата или сессии ресурсы освобождаются. Проверки интерфейса и +скачанного оригинала: evidence/image-ui.json. + +## Память, лимиты и ошибки + +Размер проверяется по Content-Length и по реально прочитанным байтам. +Предел — 10 MiB. Содержимое копируется во временный файл буфером 64 KiB. +Временный файл нужен только для проверки и PUT; он не является хранилищем +оригиналов и удаляется при закрытии. API не должен иметь этот файл для GET. +SkiaSharp определяет формат и размеры до выделения bitmap. Предел — +40 млн пикселей. После проверки выполняется полное декодирование первого кадра. +Исходные байты отправляются без перекодирования. AWS chunk encoding отключён: +SeaweedFS 3.97 должен получить именно оригинал, без служебных SigV4 chunk frames. Повреждение/неверный MIME — +415; превышение bytes/pixels — 413; опасное имя — 400. + +Одна API одновременно обслуживает одну загрузку/декодирование; остальные +ждут семафор с отменой. Общий deadline upload — 90 секунд, SDK S3 — 20 секунд, +непрозрачных retries нет. Декодированный RGBA bitmap до 160 млн байт плюс +накладные расходы. Лимит каждой API — 512 MiB; S3 — 512 MiB. +Результаты 10 одновременно начатых PNG uploads и выборочные замеры +memory.current обеих API: evidence/attachments.json. Замеры каждые 100 ms +плюс время docker exec; краткий пик между выборками может быть пропущен. + +Readiness зависит от PostgreSQL и S3; liveness проверяет процесс. При отказе +S3 HAProxy исключает API, поэтому его собственный 503 может быть без JSON +и X-Instance-Id. Ошибки, созданные API, имеют общий формат контракта. +Redis не критичен для сохранности сессии: PostgreSQL остаётся источником истины. + +## Согласованность и очистка + +201 возвращается только после успешного S3 PUT и COMMIT метаданных. +У S3 и PostgreSQL нет общей транзакции. Ошибка после PUT может оставить orphan. +При неопределённом исходе COMMIT нельзя немедленно удалять файл: COMMIT мог +состояться. Такие случаи исправляются последующей сверкой. + +Все загрузки и сообщения со ссылками получают shared advisory lock 48260104 +в PostgreSQL. Reconciler получает exclusive lock, поэтому во время сверки +публикация и новые ссылки не могут обогнать проверку. Это компромисс для +учебного стенда: длительная сверка задерживает запись, запускать её следует +в техническое окно. GET продолжает работать. Только наши writers соблюдают +протокол; прямые изменения оператором во время сверки не поддерживаются. + +```sh +make reconcile # dry-run, только показать действия +make reconcile-apply # применить действия +``` + +Grace period по умолчанию 3600 секунд, минимум 120. Учитываются время создания +метаданных и LastModified объекта. Fresh пропускаются. Старый объект без +метаданных удаляется только при отсутствии ссылки сообщения на его UUID. +Старое непривязанное вложение удаляется из обоих хранилищ. Оригинал, на который +ссылается сообщение, не удаляется. Если файл используется сообщением, но его метаданные были удалены напрямую +из БД, сверка сообщает missing_metadata и сохраняет байты. Оператор должен +восстановить метаданные из резервной копии. Если используемый оригинал пропал, запись +помечается missing: публичный GET метаданных/content возвращает 409, +сообщение и ID сохраняются. Восстановление байтов требует резервной копии. +Автоматическое восстановление отсутствующего оригинала не заявляется. + +S3 обходится страницами до 1000 объектов, PostgreSQL — до 200 записей по UUID. +Повтор удалений безопасен. Если процесс прервётся между удалением байтов и +метаданных, следующая сверка удалит оставшуюся старую непривязанную запись. +Если S3 недоступен, сверка останавливается: timeout не принимается за отсутствие. +Общий timeout команды — 5 минут. Подробный список действий требует памяти, +пропорциональной числу найденных проблем; для больших хранилищ нужен вывод потоком. + +## Проверки критериев + +| Критерий | Проверка | Доказательство | +| --- | --- | --- | +| Текстовые сообщения, сессии, идемпотентность, файлы и ACL | make test | evidence/verification.txt | +| Размер, пиксели, повреждение, MIME, filename, чужой чат и ID | make student-test | evidence/attachments.json | +| 10 параллельных upload, RAM | make student-test | evidence/attachments.json | +| Сохранность оригинала и прежней сессии после restart | make test-persistence | evidence/persistence.txt | +| Остановка загрузившей API, чтение из другой | make test-failover | evidence/failover.txt | +| Приватный bucket, ограниченные ключи | make research-grade5 | evidence/consistency.json | +| Обрыв загрузки, PUT с ошибкой БД, отказ S3 | make research-grade5 | evidence/consistency.json | +| Dry-run, repair, повтор, fresh и used, стоимость | make research-grade5 | evidence/consistency.json | + +Гипотеза исследования: при едином протоколе блокировок и grace period можно +находить и очищать старые orphan/unreferenced данные, сохраняя свежие и +используемые файлы. Методика вводит недостающий S3 объект и отказ SQL INSERT +после PUT, выполняет dry-run, apply и повтор. LastModified не подделывается: +тест действительно ждёт минимальный safety interval. Команда сообщает число +объектов, строк, S3-запросов, elapsed_ms и peak_process_bytes. + +## Результаты эксперимента + +На локальном Docker Desktop: Linux/aarch64, 8 CPU, 4106604544 байт памяти VM. +10 одновременно начатых загрузок PNG по 3147775 байт завершились без ошибок. +Пик выборок memory.current API: 220725248 и 160665600 байт при лимите 512 MiB +на каждую. Точные времена, исходные выборки и условия сохранены в attachments.json. + +После очистки три одинаковых dry-run обхода 11 объектов и 13 строк выполнили +по 12 S3-запросов. Длительности: 331.6, 891.0 и 447.3 ms, медиана 447.3 ms. +PeakWorkingSet процесса около 109 MB включает запуск CLR и SDK; это не +чистая память только алгоритма. Малый набор и один host не позволяют +экстраполировать результат на миллионы объектов. Отдельно сохранены dry-run, +apply и повтор с действиями и затратами. Проверены fresh, used, потеря +метаданных используемого файла, потеря самого объекта, SQL-ошибка после PUT, +обрыв HTTP и недоступность S3. + +## Ограничения + +Один Docker-host, PostgreSQL, HAProxy и SeaweedFS остаются точками отказа. +Это не защита от потери узла. Нет репликации S3 и резервного копирования. +Прямой presigned upload, worker и thumbnail не реализованы: это другой трек +или следующая лабораторная. История сообщений сохраняет keyset пагинацию +по (created_at,id); snapshot между HTTP-запросами не гарантируется. + +Переменные .env.example — логические имена skeleton. Фактическое соответствие: +CACHE_URL_FILE/SESSION_STORE заменены REDIS_URL + PostgreSQL session lookup; +S3_ACCESS_KEY_ID_FILE → S3_ACCESS_KEY_FILE, S3_SECRET_ACCESS_KEY_FILE → +S3_SECRET_KEY_FILE. Endpoint http://s3:8333, bucket messenger, регион us-east-1. +MAX_UPLOAD_BYTES/MAX_IMAGE_PIXELS/IDEMPOTENCY_TTL_SECONDS фиксированы контрактом +в коде: 10485760/40000000/86400. APP_ENV не меняет семантику API. + +Источники: contracts Lab4, официальная документация AWS SDK for .NET, +SeaweedFS S3 Credentials, SkiaSharp. ChatGPT использован при реализации и проверках. diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 00000000..b0a323c1 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,171 @@ +name: mtusi2026lab4 + +x-api: &api + image: messenger-lab4:local + build: . + environment: + APP_HOST: 0.0.0.0 + APP_PORT: 8080 + DATABASE_URL_FILE: /run/secrets/database_url + REDIS_URL: redis:6379 + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + DB_POOL_SIZE: ${DB_POOL_SIZE:-20} + S3_ENDPOINT: http://s3:8333 + S3_BUCKET: messenger + S3_ACCESS_KEY_FILE: /run/secrets/s3_access + S3_SECRET_KEY_FILE: /run/secrets/s3_secret + MESSAGE_BATCHING: ${MESSAGE_BATCHING:-true} + Logging__LogLevel__Default: Warning + Logging__LogLevel__Microsoft.Hosting.Lifetime: Information + secrets: + - database_url + - s3_access + - s3_secret + cpus: ${API_CPUS:-1} + mem_limit: ${API_MEMORY:-512m} + stop_grace_period: 10s + healthcheck: + test: ["CMD", "curl", "--fail", "--silent", "--max-time", "1", "http://127.0.0.1:8080/health/ready"] + interval: 2s + timeout: 2s + retries: 5 + start_period: 5s + restart: unless-stopped + depends_on: + s3-bootstrap: + condition: service_completed_successfully + migrate: + condition: service_completed_successfully + redis: + condition: service_healthy + +services: + postgres: + image: postgres:17.6 + environment: + POSTGRES_DB: messenger + POSTGRES_USER: messenger + POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password + secrets: + - postgres_password + volumes: + - postgres_data:/var/lib/postgresql/data + cpus: ${POSTGRES_CPUS:-0.5} + mem_limit: 512m + healthcheck: + test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"] + interval: 2s + timeout: 2s + retries: 30 + restart: unless-stopped + + redis: + image: redis:7.4.2-alpine + command: ["redis-server", "--save", "", "--appendonly", "no", "--maxmemory", "64mb", "--maxmemory-policy", "allkeys-lru"] + cpus: 0.25 + mem_limit: 96m + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 2s + timeout: 2s + retries: 15 + restart: unless-stopped + + migrate: + image: messenger-lab4:local + command: ["--migrate"] + environment: + DATABASE_URL_FILE: /run/secrets/database_url + secrets: + - database_url + cpus: 0.5 + mem_limit: 256m + restart: "no" + healthcheck: + disable: true + depends_on: + postgres: + condition: service_healthy + + s3: + image: chrislusf/seaweedfs:3.97 + command: ["server", "-dir=/data", "-ip=s3", "-master.volumeSizeLimitMB=100", "-volume.max=8", "-filer", "-s3", "-s3.config=/run/secrets/s3_config"] + secrets: + - s3_config + volumes: + - s3_data:/data + cpus: 0.5 + mem_limit: 512m + restart: unless-stopped + healthcheck: + test: ["CMD-SHELL", "wget -S -O /dev/null http://127.0.0.1:8333/ 2>&1 | grep -q '403'"] + interval: 2s + timeout: 2s + retries: 40 + start_period: 35s + + s3-bootstrap: + image: messenger-lab4:local + command: ["--bootstrap"] + environment: + S3_ENDPOINT: http://s3:8333 + S3_ACCESS_KEY_FILE: /run/secrets/s3_admin_access + S3_SECRET_KEY_FILE: /run/secrets/s3_admin_secret + secrets: + - s3_admin_access + - s3_admin_secret + depends_on: + s3: + condition: service_healthy + restart: on-failure + healthcheck: + disable: true + ulimits: + core: 0 + cpus: 0.25 + mem_limit: 128m + + api: + <<: *api + deploy: + replicas: ${API_REPLICAS:-2} + + lb: + image: haproxy:3.2.7-alpine + volumes: + - ./infra/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + ports: + - "127.0.0.1:${API_PORT:-18084}:8080" + cpus: 0.5 + mem_limit: 96m + stop_grace_period: 10s + healthcheck: + test: ["CMD-SHELL", "wget -q -O /dev/null http://127.0.0.1:8080/health/ready"] + interval: 2s + timeout: 2s + retries: 30 + start_period: 5s + restart: unless-stopped + depends_on: + api: + condition: service_healthy + +secrets: + s3_config: + file: ./secrets/s3_config + s3_admin_access: + file: ./secrets/s3_admin_access + s3_admin_secret: + file: ./secrets/s3_admin_secret + s3_access: + file: ./secrets/s3_access + s3_secret: + file: ./secrets/s3_secret + postgres_password: + file: ./secrets/postgres_password + database_url: + file: ./secrets/database_url + +volumes: + s3_data: + postgres_data: diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 00000000..79065658 --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -0,0 +1,38 @@ +# Переход Lab3 → Lab4 + +Цель: оценка 5, трек 2 «Согласованность двух хранилищ». + +| Критерий | Lab3 | Изменения Lab4 | +| --- | --- | --- | +| Две взаимозаменяемые API | HAProxy, общий PostgreSQL, сессии, Idempotency-Key | Сохранить; файлы доступны обеим API | +| Разделение данных | Сообщения в PostgreSQL | Метаданные Attachment в PostgreSQL, оригиналы в SeaweedFS | +| Загрузка | AttachmentIds отклоняются | Binary PNG/JPEG, до 10 MiB и 40 млн пикселей, 201 после S3 и COMMIT | +| Доступ | Bearer и членство в чате | Те же проверки перед метаданными, байтами и привязкой файла | +| Сообщения | Только текст | До 10 уникальных вложений; текст может быть пустым с вложениями | +| Идемпотентность | Хеш текста | Хеш текста и списка вложений, атомарно с сообщением | +| Проверка файлов | Отсутствует | MIME по содержимому, декодирование, опасные имена, лимиты до выделения памяти | +| Отказы | Отказ API и restart | Дополнить отказом S3, обрывом upload, сбоем COMMIT после PUT | +| Ограничение RAM | Лимиты контейнеров | Поток на временный диск, ограниченный буфер, семафор декодирования, timeout | +| Приватность bucket | Отсутствует | Идемпотентный bootstrap, отдельные credentials API, без внешних S3-портов | +| Согласованность | Одна транзакция PostgreSQL | Компенсация/сверка S3 и PostgreSQL с grace period | +| Исследование на 5 | Масштабирование API | Orphan/missing, dry-run/apply, повтор, защита свежих и используемых файлов, стоимость обхода | + +## Файлы + +- Endpoints/AttachmentEndpoints.cs: HTTP, аутентификация, доступ, валидация. +- Contracts/AttachmentDto.cs: публичные поля без object key. +- Services/AttachmentService.cs: ограниченная загрузка и проверка изображения. +- Infrastructure/S3Storage.cs: чтение и запись SeaweedFS через AWS SDK. +- Data/Attachments.cs и миграция 004: метаданные и связи. +- Services/AttachmentReconciler.cs: сверка двух хранилищ, отдельная CLI-команда. + +## Границы + +PostgreSQL и S3 не имеют общей транзакции. Загрузка держит общую блокировку +обслуживания вложений в PostgreSQL до завершения PUT и COMMIT. При обрыве +процесса после PUT останется orphan. Reconciler получает исключительную +блокировку, перечитывает метаданные и удаляет только старые неиспользуемые +объекты. Свежие файлы защищает grace period, используемые — ссылка сообщения. +Отсутствующий оригинал используемого вложения восстановить без резервной +копии невозможно: сверка фиксирует missing и сохраняет ссылки сообщения. +Один Docker-host, одна БД и один SeaweedFS остаются точками отказа. diff --git a/docs/PR.md b/docs/PR.md new file mode 100644 index 00000000..6472ac7d --- /dev/null +++ b/docs/PR.md @@ -0,0 +1,24 @@ +ЛР 4 - БВТ-2302 - Каменский - на 5 + +Автор / группа: Каменский Никита, БВТ-2302. +Целевая оценка: 5. Трек 2: согласованность двух хранилищ. + +Из Lab3 перенесены собственные API, PostgreSQL, Redis, две API-реплики за HAProxy +и интерфейс. Добавлены приватный S3 bucket SeaweedFS, загрузка и авторизованное +скачивание PNG/JPEG, метаданные и ссылки на вложения в сообщениях. + +Проверены размер, число пикселей, MIME, повреждённые файлы, чужой чат, +10 одновременных загрузок с замерами памяти, restart и переключение API. +Reconciler поддерживает dry-run/apply, grace period и повторный запуск. +Проверены orphan/missing, ошибка БД после PUT, обрыв загрузки и отказ S3; +свежие и используемые файлы сохраняются. + +Чистый запуск: make setup, make up. Проверки: make check, make validate, +make test, make student-test, make research-grade5; persistence/failover по REPORT.md. +Результаты: REPORT.md и evidence/. + +Контракт, публичные tests и README задания сохранены. PostgreSQL, S3, +балансировщик и один Docker-host остаются точками отказа. Утраченные байты +невозможно восстановить без резервной копии; missing отмечается явно. + +ChatGPT использован при реализации и проверках. diff --git a/evidence/attachments.json b/evidence/attachments.json new file mode 100644 index 00000000..0630382b --- /dev/null +++ b/evidence/attachments.json @@ -0,0 +1,68 @@ +{ + "checks": [ + "filename", + "size", + "decoded pixels", + "damaged image", + "MIME mismatch", + "private chat", + "foreign attachment", + "idempotency" + ], + "concurrency": 10, + "file_bytes": 3147775, + "decoded_pixels": 1048576, + "seconds": 1.6615432920007152, + "successful_uploads": 10, + "errors": 0, + "p95_seconds": 1.653438166998967, + "peak_api_cgroup_bytes": [ + 220725248, + 160665600 + ], + "samples": [ + { + "at": 1794257730.2808042, + "bytes": [ + 203374592, + 140251136 + ] + }, + { + "at": 1794257730.521431, + "bytes": [ + 210403328, + 146546688 + ] + }, + { + "at": 1794257730.779288, + "bytes": [ + 218071040, + 150061056 + ] + }, + { + "at": 1794257731.005748, + "bytes": [ + 217665536, + 149602304 + ] + }, + { + "at": 1794257731.277846, + "bytes": [ + 220725248, + 155983872 + ] + }, + { + "at": 1794257731.580511, + "bytes": [ + 217796608, + 160665600 + ] + } + ], + "limits": "512 MiB per API; one decoder/upload per API; 64 KiB copy buffer" +} diff --git a/evidence/consistency.json b/evidence/consistency.json new file mode 100644 index 00000000..b414d7ec --- /dev/null +++ b/evidence/consistency.json @@ -0,0 +1,343 @@ +{ + "scan_samples": [ + { + "mode": "dry-run", + "grace_seconds": 120, + "objects": 11, + "rows": 13, + "s3_requests": 12, + "elapsed_ms": 331.6122, + "peak_process_bytes": 109236224, + "actions": [ + { + "kind": "missing_metadata", + "key": "originals/d96908adeb83441eb7e01b224c82891e", + "action": "preserved_used_original" + }, + { + "kind": "missing", + "id": "2eca82ac-62ef-4e6d-b9fd-cba86685189b", + "action": "would_mark_missing" + }, + { + "kind": "missing", + "id": "8bb8a27c-fdcc-41eb-b5f5-7f18ea19674f", + "action": "would_mark_missing" + }, + { + "kind": "missing", + "id": "bdc4e3a3-7659-4ec1-8b55-60b0f16843c9", + "action": "would_mark_missing" + } + ] + }, + { + "mode": "dry-run", + "grace_seconds": 120, + "objects": 11, + "rows": 13, + "s3_requests": 12, + "elapsed_ms": 891.0122, + "peak_process_bytes": 109002752, + "actions": [ + { + "kind": "missing_metadata", + "key": "originals/d96908adeb83441eb7e01b224c82891e", + "action": "preserved_used_original" + }, + { + "kind": "missing", + "id": "2eca82ac-62ef-4e6d-b9fd-cba86685189b", + "action": "would_mark_missing" + }, + { + "kind": "missing", + "id": "8bb8a27c-fdcc-41eb-b5f5-7f18ea19674f", + "action": "would_mark_missing" + }, + { + "kind": "missing", + "id": "bdc4e3a3-7659-4ec1-8b55-60b0f16843c9", + "action": "would_mark_missing" + } + ] + }, + { + "mode": "dry-run", + "grace_seconds": 120, + "objects": 11, + "rows": 13, + "s3_requests": 12, + "elapsed_ms": 447.3227, + "peak_process_bytes": 108912640, + "actions": [ + { + "kind": "missing_metadata", + "key": "originals/d96908adeb83441eb7e01b224c82891e", + "action": "preserved_used_original" + }, + { + "kind": "missing", + "id": "2eca82ac-62ef-4e6d-b9fd-cba86685189b", + "action": "would_mark_missing" + }, + { + "kind": "missing", + "id": "8bb8a27c-fdcc-41eb-b5f5-7f18ea19674f", + "action": "would_mark_missing" + }, + { + "kind": "missing", + "id": "bdc4e3a3-7659-4ec1-8b55-60b0f16843c9", + "action": "would_mark_missing" + } + ] + } + ], + "checks": [ + "Private bucket and scoped credentials; injected missing S3 object", + "Interrupted upload not published; DB failure after PUT leaves reconcilable orphan; S3 outage recovers", + "dry-run is read-only", + "old orphan and unused data removed", + "referenced missing marked, link retained", + "fresh and referenced originals preserved, including missing metadata", + "repeat is idempotent" + ], + "dry_run": { + "mode": "dry-run", + "grace_seconds": 120, + "objects": 24, + "rows": 24, + "s3_requests": 24, + "elapsed_ms": 357.8247, + "peak_process_bytes": 110813184, + "actions": [ + { + "kind": "missing_metadata", + "key": "originals/d96908adeb83441eb7e01b224c82891e", + "action": "preserved_used_original" + }, + { + "kind": "orphan", + "key": "originals/e3a392e3f738404cba19b468fe352717", + "action": "would_delete" + }, + { + "kind": "orphan", + "key": "originals/ea6da2ae592743b5b73c50d88327c373", + "action": "would_delete" + }, + { + "kind": "unreferenced", + "id": "006bad4a-a53f-428d-ad1d-a7ba2c09d86f", + "action": "would_delete" + }, + { + "kind": "unreferenced", + "id": "02c88001-0bf8-486d-820a-801a78e69ff4", + "action": "would_delete" + }, + { + "kind": "unreferenced", + "id": "10456f24-dbcc-42f6-97d9-b436b758a8f0", + "action": "would_delete" + }, + { + "kind": "unreferenced", + "id": "2b26cc4b-027c-4edc-b9af-812165df6a08", + "action": "would_delete" + }, + { + "kind": "missing", + "id": "2eca82ac-62ef-4e6d-b9fd-cba86685189b", + "action": "would_mark_missing" + }, + { + "kind": "unreferenced", + "id": "6421d396-be20-489b-9887-f27c39572c63", + "action": "would_delete" + }, + { + "kind": "unreferenced", + "id": "71cc04ef-ee0f-4939-a080-d471e7e5c715", + "action": "would_delete" + }, + { + "kind": "unreferenced", + "id": "74975234-bbb8-42a0-99ce-53b0f40a6229", + "action": "would_delete" + }, + { + "kind": "missing", + "id": "8bb8a27c-fdcc-41eb-b5f5-7f18ea19674f", + "action": "would_mark_missing" + }, + { + "kind": "unreferenced", + "id": "9e1834dc-a0b5-45d2-97a7-5c4c3a72178a", + "action": "would_delete" + }, + { + "kind": "unreferenced", + "id": "a2d209c6-6565-4284-ba3b-4e199caf417e", + "action": "would_delete" + }, + { + "kind": "missing", + "id": "bdc4e3a3-7659-4ec1-8b55-60b0f16843c9", + "action": "would_mark_missing" + }, + { + "kind": "unreferenced", + "id": "be5bac60-6b2d-4271-9315-064734e5987b", + "action": "would_delete" + }, + { + "kind": "unreferenced", + "id": "dd176b2b-3e1a-4bd1-a25e-4be60276c2f0", + "action": "would_delete" + }, + { + "kind": "unreferenced", + "id": "ddce32cc-af2a-433e-b103-e833ca6d8945", + "action": "would_delete" + } + ] + }, + "apply": { + "mode": "apply", + "grace_seconds": 120, + "objects": 24, + "rows": 24, + "s3_requests": 38, + "elapsed_ms": 498.8064, + "peak_process_bytes": 110981120, + "actions": [ + { + "kind": "missing_metadata", + "key": "originals/d96908adeb83441eb7e01b224c82891e", + "action": "preserved_used_original" + }, + { + "kind": "orphan", + "key": "originals/e3a392e3f738404cba19b468fe352717", + "action": "deleted" + }, + { + "kind": "orphan", + "key": "originals/ea6da2ae592743b5b73c50d88327c373", + "action": "deleted" + }, + { + "kind": "unreferenced", + "id": "006bad4a-a53f-428d-ad1d-a7ba2c09d86f", + "action": "deleted" + }, + { + "kind": "unreferenced", + "id": "02c88001-0bf8-486d-820a-801a78e69ff4", + "action": "deleted" + }, + { + "kind": "unreferenced", + "id": "10456f24-dbcc-42f6-97d9-b436b758a8f0", + "action": "deleted" + }, + { + "kind": "unreferenced", + "id": "2b26cc4b-027c-4edc-b9af-812165df6a08", + "action": "deleted" + }, + { + "kind": "missing", + "id": "2eca82ac-62ef-4e6d-b9fd-cba86685189b", + "action": "marked_missing" + }, + { + "kind": "unreferenced", + "id": "6421d396-be20-489b-9887-f27c39572c63", + "action": "deleted" + }, + { + "kind": "unreferenced", + "id": "71cc04ef-ee0f-4939-a080-d471e7e5c715", + "action": "deleted" + }, + { + "kind": "unreferenced", + "id": "74975234-bbb8-42a0-99ce-53b0f40a6229", + "action": "deleted" + }, + { + "kind": "missing", + "id": "8bb8a27c-fdcc-41eb-b5f5-7f18ea19674f", + "action": "marked_missing" + }, + { + "kind": "unreferenced", + "id": "9e1834dc-a0b5-45d2-97a7-5c4c3a72178a", + "action": "deleted" + }, + { + "kind": "unreferenced", + "id": "a2d209c6-6565-4284-ba3b-4e199caf417e", + "action": "deleted" + }, + { + "kind": "missing", + "id": "bdc4e3a3-7659-4ec1-8b55-60b0f16843c9", + "action": "marked_missing" + }, + { + "kind": "unreferenced", + "id": "be5bac60-6b2d-4271-9315-064734e5987b", + "action": "deleted" + }, + { + "kind": "unreferenced", + "id": "dd176b2b-3e1a-4bd1-a25e-4be60276c2f0", + "action": "deleted" + }, + { + "kind": "unreferenced", + "id": "ddce32cc-af2a-433e-b103-e833ca6d8945", + "action": "deleted" + } + ] + }, + "repeat": { + "mode": "apply", + "grace_seconds": 120, + "objects": 11, + "rows": 13, + "s3_requests": 12, + "elapsed_ms": 346.2962, + "peak_process_bytes": 108949504, + "actions": [ + { + "kind": "missing_metadata", + "key": "originals/d96908adeb83441eb7e01b224c82891e", + "action": "preserved_used_original" + }, + { + "kind": "missing", + "id": "2eca82ac-62ef-4e6d-b9fd-cba86685189b", + "action": "marked_missing" + }, + { + "kind": "missing", + "id": "8bb8a27c-fdcc-41eb-b5f5-7f18ea19674f", + "action": "marked_missing" + }, + { + "kind": "missing", + "id": "bdc4e3a3-7659-4ec1-8b55-60b0f16843c9", + "action": "marked_missing" + } + ] + }, + "safety_wait_seconds": 111.50906662500347, + "assumption": "exclusive PostgreSQL advisory gate; all app writers use shared gate; 120s minimum grace; no automatic restore without backup", + "source_sha256": "453a3911fc23e5b218fac508073a3d93b6ace5f530a0ddec7619f153d8532d6f", + "environment": "linux aarch64 8 CPUs 4106604544 bytes RAM" +} diff --git a/evidence/failover.txt b/evidence/failover.txt new file mode 100644 index 00000000..2171601b --- /dev/null +++ b/evidence/failover.txt @@ -0,0 +1,52 @@ +.venv/bin/python tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://localhost:18084" +Executing explicit failover hook; hook output suppressed to avoid leaking secrets. +{"observed_instances_before": 2, "successful_writes": 128, "failed_attempts": 0, "first_recovery_seconds": 1.098} +PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence. +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +mtusi2026lab4-api-1 messenger-lab4:local "dotnet Messenger.Ap…" api 30 seconds ago Up 26 seconds (healthy) 8080/tcp +mtusi2026lab4-lb-1 haproxy:3.2.7-alpine "docker-entrypoint.s…" lb 10 minutes ago Up 30 seconds (healthy) 127.0.0.1:18084->8080/tcp +mtusi2026lab4-postgres-1 postgres:17.6 "docker-entrypoint.s…" postgres 10 minutes ago Up 54 seconds (healthy) 5432/tcp +mtusi2026lab4-redis-1 redis:7.4.2-alpine "docker-entrypoint.s…" redis 10 minutes ago Up 54 seconds (healthy) 6379/tcp +mtusi2026lab4-s3-1 chrislusf/seaweedfs:3.97 "/entrypoint.sh serv…" s3 9 minutes ago Up 51 seconds (healthy) 7333/tcp, 8080/tcp, 8333/tcp, 8888/tcp, 9333/tcp, 18080/tcp, 18888/tcp, 19333/tcp +./scripts/compose.sh up -d --wait api lb + Container mtusi2026lab4-api-1 Running + Container mtusi2026lab4-lb-1 Running + Container mtusi2026lab4-postgres-1 Running + Container mtusi2026lab4-redis-1 Running + Container mtusi2026lab4-s3-1 Running + Container mtusi2026lab4-postgres-1 Waiting + Container mtusi2026lab4-s3-1 Waiting + Container mtusi2026lab4-postgres-1 Healthy + Container mtusi2026lab4-migrate-1 Starting + Container mtusi2026lab4-s3-1 Healthy + Container mtusi2026lab4-s3-bootstrap-1 Starting + Container mtusi2026lab4-migrate-1 Started + Container mtusi2026lab4-s3-bootstrap-1 Started + Container mtusi2026lab4-redis-1 Waiting + Container mtusi2026lab4-s3-bootstrap-1 Waiting + Container mtusi2026lab4-migrate-1 Waiting + Container mtusi2026lab4-migrate-1 Exited + Container mtusi2026lab4-redis-1 Healthy + Container mtusi2026lab4-s3-bootstrap-1 Exited + Container mtusi2026lab4-api-2 Starting + Container mtusi2026lab4-api-2 Started + Container mtusi2026lab4-api-1 Waiting + Container mtusi2026lab4-api-2 Waiting + Container mtusi2026lab4-api-1 Healthy + Container mtusi2026lab4-api-2 Healthy + Container mtusi2026lab4-s3-bootstrap-1 Waiting + Container mtusi2026lab4-api-1 Waiting + Container mtusi2026lab4-api-2 Waiting + Container mtusi2026lab4-lb-1 Waiting + Container mtusi2026lab4-postgres-1 Waiting + Container mtusi2026lab4-redis-1 Waiting + Container mtusi2026lab4-migrate-1 Waiting + Container mtusi2026lab4-s3-1 Waiting + Container mtusi2026lab4-s3-1 Healthy + Container mtusi2026lab4-postgres-1 Healthy + Container mtusi2026lab4-redis-1 Healthy + Container mtusi2026lab4-migrate-1 Exited + Container mtusi2026lab4-lb-1 Healthy + Container mtusi2026lab4-s3-bootstrap-1 Exited + Container mtusi2026lab4-api-1 Healthy + Container mtusi2026lab4-api-2 Healthy diff --git a/evidence/image-ui-api.txt b/evidence/image-ui-api.txt new file mode 100644 index 00000000..0f0e3314 --- /dev/null +++ b/evidence/image-ui-api.txt @@ -0,0 +1,2 @@ +.venv/bin/python tests/smoke.py --base-url "http://localhost:18084" +PASS: lab4 public API scenario; infrastructure and grading evidence remain separate. diff --git a/evidence/image-ui.json b/evidence/image-ui.json new file mode 100644 index 00000000..82ef2802 --- /dev/null +++ b/evidence/image-ui.json @@ -0,0 +1,20 @@ +{ + "checks": [ + "automatic inline PNG/JPEG previews", + "filename and size", + "full-screen viewer", + "arrow-key gallery navigation", + "zoom toggle", + "Escape closes and restores focus", + "original filename and byte-identical download", + "draft thumbnail and attachment-only send", + "desktop 1280x720 without page overflow", + "mobile 319px fit and zoom" + ], + "download_sha256": "88585921771cc8ab0afac847728ab899c418c92d8d5ee2cdfeeda8b84a3c61de", + "screenshots": [ + "ui-image-previews.jpg", + "ui-image-viewer-desktop.jpg", + "ui-image-viewer-mobile.jpg" + ] +} diff --git a/evidence/persistence.txt b/evidence/persistence.txt new file mode 100644 index 00000000..f5f6aaaf --- /dev/null +++ b/evidence/persistence.txt @@ -0,0 +1,17 @@ +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +mtusi2026lab4-api-1 sha256:549dc2226f2146641dea8a7c5931a905ae1a14df4075934bdba21d34bb7ed499 "dotnet Messenger.Ap…" api About a minute ago Up About a minute (healthy) 8080/tcp +mtusi2026lab4-api-2 sha256:549dc2226f2146641dea8a7c5931a905ae1a14df4075934bdba21d34bb7ed499 "dotnet Messenger.Ap…" api About a minute ago Up About a minute (healthy) 8080/tcp +mtusi2026lab4-lb-1 haproxy:3.2.7-alpine "docker-entrypoint.s…" lb 9 minutes ago Up 7 minutes (healthy) 127.0.0.1:18084->8080/tcp +mtusi2026lab4-postgres-1 postgres:17.6 "docker-entrypoint.s…" postgres 9 minutes ago Up 9 minutes (healthy) 5432/tcp +mtusi2026lab4-redis-1 redis:7.4.2-alpine "docker-entrypoint.s…" redis 9 minutes ago Up 9 minutes (healthy) 6379/tcp +mtusi2026lab4-s3-1 chrislusf/seaweedfs:3.97 "/entrypoint.sh serv…" s3 8 minutes ago Up 2 minutes (healthy) 7333/tcp, 8080/tcp, 8333/tcp, 8888/tcp, 9333/tcp, 18080/tcp, 18888/tcp, 19333/tcp +.venv/bin/python tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://localhost:18084" +Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +mtusi2026lab4-api-1 messenger-lab4:local "dotnet Messenger.Ap…" api 9 seconds ago Up 5 seconds (healthy) 8080/tcp +mtusi2026lab4-api-2 messenger-lab4:local "dotnet Messenger.Ap…" api 9 seconds ago Up 5 seconds (healthy) 8080/tcp +mtusi2026lab4-lb-1 haproxy:3.2.7-alpine "docker-entrypoint.s…" lb 10 minutes ago Up 9 seconds (healthy) 127.0.0.1:18084->8080/tcp +mtusi2026lab4-postgres-1 postgres:17.6 "docker-entrypoint.s…" postgres 10 minutes ago Up 33 seconds (healthy) 5432/tcp +mtusi2026lab4-redis-1 redis:7.4.2-alpine "docker-entrypoint.s…" redis 10 minutes ago Up 33 seconds (healthy) 6379/tcp +mtusi2026lab4-s3-1 chrislusf/seaweedfs:3.97 "/entrypoint.sh serv…" s3 8 minutes ago Up 30 seconds (healthy) 7333/tcp, 8080/tcp, 8333/tcp, 8888/tcp, 9333/tcp, 18080/tcp, 18888/tcp, 19333/tcp diff --git a/evidence/ui-image-previews.jpg b/evidence/ui-image-previews.jpg new file mode 100644 index 00000000..da78fdf1 Binary files /dev/null and b/evidence/ui-image-previews.jpg differ diff --git a/evidence/ui-image-viewer-desktop.jpg b/evidence/ui-image-viewer-desktop.jpg new file mode 100644 index 00000000..4884a4c6 Binary files /dev/null and b/evidence/ui-image-viewer-desktop.jpg differ diff --git a/evidence/ui-image-viewer-mobile.jpg b/evidence/ui-image-viewer-mobile.jpg new file mode 100644 index 00000000..6eaeaeaf Binary files /dev/null and b/evidence/ui-image-viewer-mobile.jpg differ diff --git a/evidence/verification.txt b/evidence/verification.txt new file mode 100644 index 00000000..198bdced --- /dev/null +++ b/evidence/verification.txt @@ -0,0 +1,8 @@ +.venv/bin/python tests/smoke.py --base-url "http://localhost:18084" +PASS: lab4 public API scenario; infrastructure and grading evidence remain separate. +.venv/bin/python student-tests/attachments.py --base-url "http://localhost:18084" +PASS: attachment validation, access, replay and 10 parallel uploads +.venv/bin/python student-tests/attachments.py --base-url "http://localhost:18084" +PASS: attachment validation, access, replay and 10 parallel uploads +.venv/bin/python tests/smoke.py --base-url "http://localhost:18084" +PASS: lab4 public API scenario; infrastructure and grading evidence remain separate. diff --git a/infra/haproxy.cfg b/infra/haproxy.cfg new file mode 100644 index 00000000..752b0535 --- /dev/null +++ b/infra/haproxy.cfg @@ -0,0 +1,40 @@ +global + maxconn 2000 + stats socket ipv4@127.0.0.1:9999 level admin + hard-stop-after 8s + +defaults + mode http + timeout connect 500ms + timeout check 500ms + timeout client 15s + timeout server 12s + timeout http-request 5s + timeout http-keep-alive 5s + timeout queue 2s + retries 1 + +resolvers docker + nameserver dns 127.0.0.11:53 + accepted_payload_size 8192 + resolve_retries 2 + timeout resolve 500ms + timeout retry 500ms + hold valid 1s + hold nx 1s + hold other 1s + hold refused 1s + hold timeout 1s + hold obsolete 0s + +frontend public + bind :8080 + default_backend messenger + +backend messenger + balance roundrobin + option httpchk + http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host localhost + http-check expect status 200 + default-server check inter 500ms fastinter 250ms downinter 500ms fall 2 rise 2 + server-template api 1-8 api:8080 resolvers docker resolve-prefer ipv4 init-addr none diff --git a/scripts/compose.sh b/scripts/compose.sh new file mode 100755 index 00000000..26472c9c --- /dev/null +++ b/scripts/compose.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +root="$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)" +exec docker compose --project-name mtusi2026lab4 --project-directory "$root" "$@" diff --git a/scripts/init-secrets.py b/scripts/init-secrets.py new file mode 100644 index 00000000..e96ea437 --- /dev/null +++ b/scripts/init-secrets.py @@ -0,0 +1,19 @@ +#!/usr/bin/env python3 +from pathlib import Path +import secrets,json,os +os.umask(0o077) +p=Path(__file__).resolve().parents[1]/'secrets';p.mkdir(exist_ok=True) +def secret(name,size=24): + f=p/name + if not f.exists(): f.write_text(secrets.token_hex(size)) + return f.read_text().strip() +pw=secret('postgres_password') +f=p/'database_url' +if not f.exists(): f.write_text('Host=postgres;Port=5432;Database=messenger;Username=messenger;Password='+pw) +admin=secret('s3_admin_access',12); admin_secret=secret('s3_admin_secret') +access=secret('s3_access',12); key=secret('s3_secret') +config={'identities':[ + {'name':'bootstrap','credentials':[{'accessKey':admin,'secretKey':admin_secret}],'actions':['Admin','Read','Write','List','Tagging']}, + {'name':'messenger','credentials':[{'accessKey':access,'secretKey':key}],'actions':['Read:messenger','Write:messenger','List:messenger']}]} +(p/'s3_config').write_text(json.dumps(config)) +print('Local secrets ready') diff --git a/scripts/init-secrets.sh b/scripts/init-secrets.sh new file mode 100755 index 00000000..063eb4ac --- /dev/null +++ b/scripts/init-secrets.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +exec python3 "$(dirname "$0")/init-secrets.py" diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100755 index 00000000..d5d6510a --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,7 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +./scripts/compose.sh restart postgres redis s3 +./scripts/compose.sh up -d --wait --wait-timeout 60 postgres redis s3 +./scripts/compose.sh restart api lb +./scripts/compose.sh up -d --wait --wait-timeout 60 api lb diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh new file mode 100755 index 00000000..2a7bee58 --- /dev/null +++ b/scripts/stop-one.sh @@ -0,0 +1,13 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +test -n "${TARGET_INSTANCE_ID:-}" || { echo "TARGET_INSTANCE_ID is required" >&2; exit 1; } +for id in $(./scripts/compose.sh ps -q api); do + instance="$(docker exec "$id" curl -fsS -D - -o /dev/null http://127.0.0.1:8080/health/live | tr -d '\r' | awk 'tolower($1) == "x-instance-id:" { print $2 }')" + if [ "$instance" = "$TARGET_INSTANCE_ID" ]; then + docker stop --time 8 "$id" >/dev/null + exit 0 + fi +done +echo "Requested API instance was not found" >&2 +exit 1 diff --git a/src/Messenger.Api/Contracts/AttachmentDto.cs b/src/Messenger.Api/Contracts/AttachmentDto.cs new file mode 100644 index 00000000..ca40a661 --- /dev/null +++ b/src/Messenger.Api/Contracts/AttachmentDto.cs @@ -0,0 +1,4 @@ +namespace Messenger.Api.Contracts; +public sealed record AttachmentDto(Guid Id, Guid ChatId, Guid OwnerId, string Filename, + string ContentType, long SizeBytes, string Sha256, string Status, object[] Variants, + string? ErrorCode, string CreatedAt, string UpdatedAt); diff --git a/src/Messenger.Api/Contracts/ChatCursor.cs b/src/Messenger.Api/Contracts/ChatCursor.cs new file mode 100644 index 00000000..f8a7fb06 --- /dev/null +++ b/src/Messenger.Api/Contracts/ChatCursor.cs @@ -0,0 +1,7 @@ +namespace Messenger.Api.Contracts; + +public sealed record ChatCursor( + string Scope, + string CreatedAt, + Guid Id +); diff --git a/src/Messenger.Api/Contracts/ChatDto.cs b/src/Messenger.Api/Contracts/ChatDto.cs new file mode 100644 index 00000000..67a757a1 --- /dev/null +++ b/src/Messenger.Api/Contracts/ChatDto.cs @@ -0,0 +1,3 @@ +namespace Messenger.Api.Contracts; + +public sealed record ChatDto(Guid Id, string Title, List MemberIds, string CreatedAt); diff --git a/src/Messenger.Api/Contracts/ChatPreviewDto.cs b/src/Messenger.Api/Contracts/ChatPreviewDto.cs new file mode 100644 index 00000000..4dded210 --- /dev/null +++ b/src/Messenger.Api/Contracts/ChatPreviewDto.cs @@ -0,0 +1,4 @@ +namespace Messenger.Api.Contracts; + +public sealed record ChatPreviewDto( + Guid Id, string Title, List MemberIds, string CreatedAt, MessageDto? LastMessage); diff --git a/src/Messenger.Api/Contracts/CreateChatRequest.cs b/src/Messenger.Api/Contracts/CreateChatRequest.cs new file mode 100644 index 00000000..cd55763b --- /dev/null +++ b/src/Messenger.Api/Contracts/CreateChatRequest.cs @@ -0,0 +1,6 @@ +namespace Messenger.Api.Contracts; + +public sealed record CreateChatRequest( + string? Title, + List? MemberIds +); diff --git a/src/Messenger.Api/Contracts/CreateMessageRequest.cs b/src/Messenger.Api/Contracts/CreateMessageRequest.cs new file mode 100644 index 00000000..2d7136a8 --- /dev/null +++ b/src/Messenger.Api/Contracts/CreateMessageRequest.cs @@ -0,0 +1,8 @@ +using System.Text.Json; + +namespace Messenger.Api.Contracts; + +public sealed record CreateMessageRequest( + string? Text, + JsonElement AttachmentIds = default +); diff --git a/src/Messenger.Api/Contracts/CreateUserRequest.cs b/src/Messenger.Api/Contracts/CreateUserRequest.cs new file mode 100644 index 00000000..cd60371d --- /dev/null +++ b/src/Messenger.Api/Contracts/CreateUserRequest.cs @@ -0,0 +1,7 @@ +namespace Messenger.Api.Contracts; + +public sealed record CreateUserRequest( + string? Username, + string? DisplayName, + string? Password +); diff --git a/src/Messenger.Api/Contracts/MessageDto.cs b/src/Messenger.Api/Contracts/MessageDto.cs new file mode 100644 index 00000000..b45c9398 --- /dev/null +++ b/src/Messenger.Api/Contracts/MessageDto.cs @@ -0,0 +1,3 @@ +namespace Messenger.Api.Contracts; + +public sealed record MessageDto(Guid Id, Guid ChatId, Guid SenderId, string Text, string CreatedAt, Guid[] AttachmentIds); diff --git a/src/Messenger.Api/Contracts/SessionDto.cs b/src/Messenger.Api/Contracts/SessionDto.cs new file mode 100644 index 00000000..8e0177f0 --- /dev/null +++ b/src/Messenger.Api/Contracts/SessionDto.cs @@ -0,0 +1,3 @@ +namespace Messenger.Api.Contracts; + +public sealed record SessionDto(string Token, string TokenType, string ExpiresAt, UserDto User); diff --git a/src/Messenger.Api/Contracts/UserDto.cs b/src/Messenger.Api/Contracts/UserDto.cs new file mode 100644 index 00000000..d3ebc3c0 --- /dev/null +++ b/src/Messenger.Api/Contracts/UserDto.cs @@ -0,0 +1,3 @@ +namespace Messenger.Api.Contracts; + +public sealed record UserDto(Guid Id, string Username, string DisplayName, string CreatedAt); diff --git a/src/Messenger.Api/Data/AppDatabase.cs b/src/Messenger.Api/Data/AppDatabase.cs new file mode 100644 index 00000000..ce29d472 --- /dev/null +++ b/src/Messenger.Api/Data/AppDatabase.cs @@ -0,0 +1,206 @@ +using Messenger.Api.Data.Entities; +using System.Net.Sockets; +using Npgsql; + +namespace Messenger.Api.Data; + +public sealed partial class AppDatabase(NpgsqlDataSource dataSource, IConfiguration configuration) +{ + public async Task IsReadyAsync() + { + try + { + await using var command = dataSource.CreateCommand("SELECT 1"); + return (int)(await command.ExecuteScalarAsync())! == 1; + } + catch (Exception exception) when (exception is NpgsqlException or SocketException or TimeoutException) + { + return false; + } + } + + public async Task FindUserByUsernameAsync(string username) + { + await using var command = dataSource.CreateCommand( + "SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = @username"); + command.Parameters.AddWithValue("username", username); + await using var reader = await command.ExecuteReaderAsync(); + return await reader.ReadAsync() ? ReadUser(reader) : null; + } + + public async Task FindUserByIdAsync(Guid id) + { + await using var command = dataSource.CreateCommand( + "SELECT id, username, display_name, password_hash, created_at FROM users WHERE id = @id"); + command.Parameters.AddWithValue("id", id); + await using var reader = await command.ExecuteReaderAsync(); + return await reader.ReadAsync() ? ReadUser(reader) : null; + } + + public async Task> ListChatUsersAsync(Guid chatId) + { + await using var command = dataSource.CreateCommand(""" + SELECT u.id, u.username, u.display_name, u.password_hash, u.created_at + FROM users u JOIN chat_members m ON m.user_id = u.id + WHERE m.chat_id = @chat_id ORDER BY u.display_name, u.id + """); + command.Parameters.AddWithValue("chat_id", chatId); + await using var reader = await command.ExecuteReaderAsync(); + var result = new List(); + while (await reader.ReadAsync()) result.Add(ReadUser(reader)); + return result; + } + + public async Task CreateUserAsync(string username, string displayName, string passwordHash) + { + var user = new UserEntity(Guid.NewGuid(), username, displayName, passwordHash, UtcClock.Now()); + await using var command = dataSource.CreateCommand( + "INSERT INTO users(id, username, display_name, password_hash, created_at) VALUES (@id, @username, @display_name, @password_hash, @created_at)"); + command.Parameters.AddWithValue("id", user.Id); + command.Parameters.AddWithValue("username", user.Username); + command.Parameters.AddWithValue("display_name", user.DisplayName); + command.Parameters.AddWithValue("password_hash", user.PasswordHash); + command.Parameters.AddWithValue("created_at", user.CreatedAt); + await command.ExecuteNonQueryAsync(); + return user; + } + + public async Task CreateSessionAsync(byte[] tokenHash, Guid userId, DateTime expiresAt) + { + await using var command = dataSource.CreateCommand( + "INSERT INTO sessions(token_hash, user_id, expires_at, created_at) VALUES (@token_hash, @user_id, @expires_at, @created_at)"); + command.Parameters.AddWithValue("token_hash", tokenHash); + command.Parameters.AddWithValue("user_id", userId); + command.Parameters.AddWithValue("expires_at", expiresAt); + command.Parameters.AddWithValue("created_at", UtcClock.Now()); + await command.ExecuteNonQueryAsync(); + } + + public async Task FindActiveSessionAsync(byte[] tokenHash) + { + await using var command = dataSource.CreateCommand(""" + SELECT user_id, expires_at FROM sessions + WHERE token_hash = @token_hash AND revoked_at IS NULL AND expires_at > now() + """); + command.Parameters.AddWithValue("token_hash", tokenHash); + await using var reader = await command.ExecuteReaderAsync(); + return await reader.ReadAsync() ? new SessionEntity(reader.GetGuid(0), reader.GetDateTime(1)) : null; + } + + public async Task RevokeSessionAsync(byte[] tokenHash) + { + await using var command = dataSource.CreateCommand(""" + UPDATE sessions SET revoked_at = now() + WHERE token_hash = @token_hash AND revoked_at IS NULL AND expires_at > now() + """); + command.Parameters.AddWithValue("token_hash", tokenHash); + return await command.ExecuteNonQueryAsync() == 1; + } + + public async Task CreateChatAsync(string title, List memberIds) + { + await using var connection = await dataSource.OpenConnectionAsync(); + await using var transaction = await connection.BeginTransactionAsync(); + + await using (var membersCommand = new NpgsqlCommand( + "SELECT count(*) FROM users WHERE id = ANY(@member_ids)", connection, transaction)) + { + membersCommand.Parameters.AddWithValue("member_ids", memberIds.ToArray()); + if ((long)(await membersCommand.ExecuteScalarAsync())! != memberIds.Count) + { + await transaction.RollbackAsync(); + return null; + } + } + + var chat = new ChatEntity(Guid.NewGuid(), title, memberIds, UtcClock.Now()); + await using (var chatCommand = new NpgsqlCommand( + "INSERT INTO chats(id, title, created_at) VALUES (@id, @title, @created_at)", connection, transaction)) + { + chatCommand.Parameters.AddWithValue("id", chat.Id); + chatCommand.Parameters.AddWithValue("title", chat.Title); + chatCommand.Parameters.AddWithValue("created_at", chat.CreatedAt); + await chatCommand.ExecuteNonQueryAsync(); + } + + await using (var membershipCommand = new NpgsqlCommand( + "INSERT INTO chat_members(chat_id, user_id) SELECT @chat_id, unnest(CAST(@member_ids AS uuid[]))", connection, transaction)) + { + membershipCommand.Parameters.AddWithValue("chat_id", chat.Id); + membershipCommand.Parameters.AddWithValue("member_ids", memberIds.ToArray()); + await membershipCommand.ExecuteNonQueryAsync(); + } + + await transaction.CommitAsync(); + return chat; + } + + public async Task FindChatForMemberAsync(Guid chatId, Guid userId) + { + await using var command = dataSource.CreateCommand(""" + SELECT c.id, c.title, c.created_at, + ARRAY(SELECT m.user_id FROM chat_members m WHERE m.chat_id = c.id ORDER BY m.user_id) + FROM chats c + WHERE c.id = @chat_id AND EXISTS ( + SELECT 1 FROM chat_members m WHERE m.chat_id = c.id AND m.user_id = @user_id) + """); + command.Parameters.AddWithValue("chat_id", chatId); + command.Parameters.AddWithValue("user_id", userId); + await using var reader = await command.ExecuteReaderAsync(); + return await reader.ReadAsync() ? ReadChat(reader) : null; + } + + public async Task> ListChatsAsync(Guid userId, DateTime? cursorTime, Guid? cursorId, int count) + { + var sql = """ + SELECT c.id, c.title, c.created_at, + ARRAY(SELECT m2.user_id FROM chat_members m2 WHERE m2.chat_id = c.id ORDER BY m2.user_id) + FROM chats c JOIN chat_members m ON m.chat_id = c.id + WHERE m.user_id = @user_id + """; + if (cursorTime is not null) + sql += " AND (c.created_at, c.id) > (@cursor_time, @cursor_id)"; + sql += " ORDER BY c.created_at, c.id LIMIT @count"; + + await using var command = dataSource.CreateCommand(sql); + command.Parameters.AddWithValue("user_id", userId); + if (cursorTime is not null) + { + command.Parameters.AddWithValue("cursor_time", cursorTime.Value); + command.Parameters.AddWithValue("cursor_id", cursorId!.Value); + } + command.Parameters.AddWithValue("count", count); + await using var reader = await command.ExecuteReaderAsync(); + var result = new List(); + while (await reader.ReadAsync()) result.Add(ReadChat(reader)); + return result; + } + + public async Task> ListMessagesAsync(Guid chatId, DateTime? cursorTime, Guid? cursorId, int count, bool newestFirst = false) + { + var sql = "SELECT id, chat_id, sender_id, text, created_at, attachment_ids FROM messages WHERE chat_id = @chat_id"; + if (cursorTime is not null) + sql += newestFirst ? " AND (created_at, id) < (@cursor_time, @cursor_id)" : " AND (created_at, id) > (@cursor_time, @cursor_id)"; + sql += newestFirst ? " ORDER BY created_at DESC, id DESC LIMIT @count" : " ORDER BY created_at, id LIMIT @count"; + + await using var command = dataSource.CreateCommand(sql); + command.Parameters.AddWithValue("chat_id", chatId); + if (cursorTime is not null) + { + command.Parameters.AddWithValue("cursor_time", cursorTime.Value); + command.Parameters.AddWithValue("cursor_id", cursorId!.Value); + } + command.Parameters.AddWithValue("count", count); + await using var reader = await command.ExecuteReaderAsync(); + var result = new List(); + while (await reader.ReadAsync()) result.Add(new MessageEntity( + reader.GetGuid(0), reader.GetGuid(1), reader.GetGuid(2), reader.GetString(3), reader.GetDateTime(4), reader.GetFieldValue(5))); + return result; + } + + private static UserEntity ReadUser(NpgsqlDataReader reader) => new( + reader.GetGuid(0), reader.GetString(1), reader.GetString(2), reader.GetString(3), reader.GetDateTime(4)); + + private static ChatEntity ReadChat(NpgsqlDataReader reader) => new( + reader.GetGuid(0), reader.GetString(1), reader.GetFieldValue(3).ToList(), reader.GetDateTime(2)); +} diff --git a/src/Messenger.Api/Data/Attachments.cs b/src/Messenger.Api/Data/Attachments.cs new file mode 100644 index 00000000..c1968457 --- /dev/null +++ b/src/Messenger.Api/Data/Attachments.cs @@ -0,0 +1,22 @@ +using Messenger.Api.Contracts; +using Npgsql; +namespace Messenger.Api.Data; +public sealed partial class AppDatabase +{ + public const long AttachmentGate = 48260104; + public async Task<(AttachmentDto Dto, string Key)?> FindAttachmentAsync(Guid id, Guid actor) + { + await using var cmd = dataSource.CreateCommand(""" + SELECT a.id,a.chat_id,a.owner_id,a.filename,a.content_type,a.size_bytes,a.sha256, + a.status,a.created_at,a.updated_at,a.object_key + FROM attachments a JOIN chat_members m ON m.chat_id=a.chat_id + WHERE a.id=@id AND m.user_id=@actor + """); + cmd.Parameters.AddWithValue("id",id); cmd.Parameters.AddWithValue("actor",actor); + await using var r=await cmd.ExecuteReaderAsync(); + return await r.ReadAsync() ? (ReadAttachment(r),r.GetString(10)) : null; + } + public static AttachmentDto ReadAttachment(NpgsqlDataReader r) => new(r.GetGuid(0),r.GetGuid(1), + r.GetGuid(2),r.GetString(3),r.GetString(4),r.GetInt64(5),r.GetString(6),r.GetString(7), + [],null,r.GetDateTime(8).ToString("O"),r.GetDateTime(9).ToString("O")); +} diff --git a/src/Messenger.Api/Data/ChatPreviews.cs b/src/Messenger.Api/Data/ChatPreviews.cs new file mode 100644 index 00000000..40d63209 --- /dev/null +++ b/src/Messenger.Api/Data/ChatPreviews.cs @@ -0,0 +1,51 @@ +using Messenger.Api.Contracts; +using Npgsql; + +namespace Messenger.Api.Data; + +public sealed partial class AppDatabase +{ + public async Task> ListChatPreviewsAsync(Guid userId, DateTime? cursorTime, Guid? cursorId, int count) + { + var query = """ + WITH page AS ( + SELECT c.id, c.title, c.created_at, + ARRAY(SELECT m.user_id FROM chat_members m WHERE m.chat_id = c.id ORDER BY m.user_id) AS member_ids + FROM chats c JOIN chat_members membership ON membership.chat_id = c.id + WHERE membership.user_id = @user_id + """; + if (cursorTime is not null) query += " AND (c.created_at, c.id) > (@cursor_time, @cursor_id)"; + query += """ + ORDER BY c.created_at, c.id LIMIT @count + ) + SELECT p.id, p.title, p.created_at, p.member_ids, + latest.id, latest.sender_id, latest.text, latest.created_at, latest.attachment_ids + FROM page p + LEFT JOIN LATERAL ( + SELECT id, sender_id, text, created_at, attachment_ids + FROM messages WHERE chat_id = p.id + ORDER BY created_at DESC, id DESC LIMIT 1 + ) latest ON true + ORDER BY p.created_at, p.id + """; + await using var command = dataSource.CreateCommand(query); + command.Parameters.AddWithValue("user_id", userId); + command.Parameters.AddWithValue("count", count); + if (cursorTime is not null) + { + command.Parameters.AddWithValue("cursor_time", cursorTime.Value); + command.Parameters.AddWithValue("cursor_id", cursorId!.Value); + } + await using var reader = await command.ExecuteReaderAsync(); + var result = new List(); + while (await reader.ReadAsync()) + { + var id = reader.GetGuid(0); + var message = reader.IsDBNull(4) ? null : new MessageDto(reader.GetGuid(4), id, + reader.GetGuid(5), reader.GetString(6), reader.GetDateTime(7).ToString("O"), reader.GetFieldValue(8)); + result.Add(new ChatPreviewDto(id, reader.GetString(1), reader.GetFieldValue(3).ToList(), + reader.GetDateTime(2).ToString("O"), message)); + } + return result; + } +} diff --git a/src/Messenger.Api/Data/DatabaseMigrator.cs b/src/Messenger.Api/Data/DatabaseMigrator.cs new file mode 100644 index 00000000..91cb8068 --- /dev/null +++ b/src/Messenger.Api/Data/DatabaseMigrator.cs @@ -0,0 +1,40 @@ +using Npgsql; + +namespace Messenger.Api.Data; + +public static class DatabaseMigrator +{ + public static async Task ApplyAsync(NpgsqlDataSource dataSource) + { + await using var connection = await dataSource.OpenConnectionAsync(); + await using var transaction = await connection.BeginTransactionAsync(); + await using (var command = new NpgsqlCommand("SELECT pg_advisory_xact_lock(202602)", connection, transaction)) + await command.ExecuteNonQueryAsync(); + await using (var command = new NpgsqlCommand( + "CREATE TABLE IF NOT EXISTS schema_migrations (version integer PRIMARY KEY, applied_at timestamptz NOT NULL)", + connection, transaction)) + await command.ExecuteNonQueryAsync(); + + var assembly = typeof(DatabaseMigrator).Assembly; + var migrations = assembly.GetManifestResourceNames() + .Where(name => name.Contains(".Data.Migrations.", StringComparison.Ordinal) && name.EndsWith(".sql", StringComparison.Ordinal)) + .Order(StringComparer.Ordinal); + foreach (var name in migrations) + { + var version = int.Parse(name.Split('.')[^2].Split('_')[0]); + await using var check = new NpgsqlCommand("SELECT EXISTS (SELECT 1 FROM schema_migrations WHERE version = @version)", connection, transaction); + check.Parameters.AddWithValue("version", version); + if ((bool)(await check.ExecuteScalarAsync())!) continue; + + await using var stream = assembly.GetManifestResourceStream(name)!; + using var reader = new StreamReader(stream); + await using (var migration = new NpgsqlCommand(await reader.ReadToEndAsync(), connection, transaction)) + await migration.ExecuteNonQueryAsync(); + await using var record = new NpgsqlCommand( + "INSERT INTO schema_migrations(version, applied_at) VALUES (@version, now())", connection, transaction); + record.Parameters.AddWithValue("version", version); + await record.ExecuteNonQueryAsync(); + } + await transaction.CommitAsync(); + } +} diff --git a/src/Messenger.Api/Data/Entities/ChatEntity.cs b/src/Messenger.Api/Data/Entities/ChatEntity.cs new file mode 100644 index 00000000..9daea081 --- /dev/null +++ b/src/Messenger.Api/Data/Entities/ChatEntity.cs @@ -0,0 +1,6 @@ +namespace Messenger.Api.Data.Entities; + +public sealed record ChatEntity(Guid Id, string Title, List MemberIds, DateTime CreatedAt) +{ + public Contracts.ChatDto ToDto() => new(Id, Title, MemberIds, CreatedAt.ToString("O")); +} diff --git a/src/Messenger.Api/Data/Entities/MessageEntity.cs b/src/Messenger.Api/Data/Entities/MessageEntity.cs new file mode 100644 index 00000000..cd4614a8 --- /dev/null +++ b/src/Messenger.Api/Data/Entities/MessageEntity.cs @@ -0,0 +1,6 @@ +namespace Messenger.Api.Data.Entities; + +public sealed record MessageEntity(Guid Id, Guid ChatId, Guid SenderId, string Text, DateTime CreatedAt, Guid[]? AttachmentIds = null) +{ + public Contracts.MessageDto ToDto() => new(Id, ChatId, SenderId, Text, CreatedAt.ToString("O"), AttachmentIds ?? []); +} diff --git a/src/Messenger.Api/Data/Entities/SessionEntity.cs b/src/Messenger.Api/Data/Entities/SessionEntity.cs new file mode 100644 index 00000000..ddb29de1 --- /dev/null +++ b/src/Messenger.Api/Data/Entities/SessionEntity.cs @@ -0,0 +1,3 @@ +namespace Messenger.Api.Data.Entities; + +public sealed record SessionEntity(Guid UserId, DateTime ExpiresAt); diff --git a/src/Messenger.Api/Data/Entities/UserEntity.cs b/src/Messenger.Api/Data/Entities/UserEntity.cs new file mode 100644 index 00000000..9389ce4c --- /dev/null +++ b/src/Messenger.Api/Data/Entities/UserEntity.cs @@ -0,0 +1,6 @@ +namespace Messenger.Api.Data.Entities; + +public sealed record UserEntity(Guid Id, string Username, string DisplayName, string PasswordHash, DateTime CreatedAt) +{ + public Contracts.UserDto ToDto() => new(Id, Username, DisplayName, CreatedAt.ToString("O")); +} diff --git a/src/Messenger.Api/Data/MessageRequests.cs b/src/Messenger.Api/Data/MessageRequests.cs new file mode 100644 index 00000000..4b6a26f4 --- /dev/null +++ b/src/Messenger.Api/Data/MessageRequests.cs @@ -0,0 +1,91 @@ +using System.Security.Cryptography; +using System.Text; +using Messenger.Api.Data.Entities; +using Npgsql; + +namespace Messenger.Api.Data; + +public sealed partial class AppDatabase +{ + private bool BatchCommands => !string.Equals(configuration["MESSAGE_BATCHING"], "false", StringComparison.OrdinalIgnoreCase); + + public async Task CreateMessageOnceAsync(Guid chatId, Guid senderId, string text, string key, Guid[] attachmentIds) + { + var hash = SHA256.HashData(System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(new { text, attachment_ids = attachmentIds })); + await using var connection = await dataSource.OpenConnectionAsync(); + await using var transaction = await connection.BeginTransactionAsync(); + + await using (var gate = new NpgsqlCommand($"SELECT pg_advisory_xact_lock_shared({AttachmentGate})",connection,transaction)) + await gate.ExecuteNonQueryAsync(); + if (attachmentIds.Length>0) + { + await using var attachments = new NpgsqlCommand("SELECT id,status FROM attachments WHERE chat_id=@chat AND id=ANY(@ids)",connection,transaction); + attachments.Parameters.AddWithValue("chat",chatId); attachments.Parameters.AddWithValue("ids",attachmentIds); + await using var found = await attachments.ExecuteReaderAsync(); + var count=0; var ready=true; + while(await found.ReadAsync()) { count++; ready &= found.GetString(1)=="ready"; } + if(count!=attachmentIds.Length) throw new Services.AttachmentException(404,"not_found","Вложение не найдено"); + if(!ready) throw new Services.AttachmentException(409,"conflict","Вложение недоступно"); + } + // A transaction-scoped lock coordinates the same request across all API processes. + if (!BatchCommands) + await using (var gate = new NpgsqlCommand("SELECT pg_advisory_xact_lock(hashtextextended(@scope, 0))", connection, transaction)) + { + gate.Parameters.AddWithValue("scope", $"{senderId}:POST:/api/v1/chats/{chatId}/messages:{key}"); + await gate.ExecuteNonQueryAsync(); + } + await using (var previous = new NpgsqlCommand((BatchCommands ? "SELECT pg_advisory_xact_lock(hashtextextended(@scope, 0));" : "") + """ + SELECT r.request_hash, m.id, m.chat_id, m.sender_id, m.text, m.created_at, m.attachment_ids + FROM message_requests r JOIN messages m ON m.id = r.message_id + WHERE r.user_id = @user_id AND r.chat_id = @chat_id AND r.request_key = @key + AND r.expires_at > clock_timestamp() + """, connection, transaction)) + { + previous.Parameters.AddWithValue("scope", $"{senderId}:POST:/api/v1/chats/{chatId}/messages:{key}"); + previous.Parameters.AddWithValue("user_id", senderId); + previous.Parameters.AddWithValue("chat_id", chatId); + previous.Parameters.AddWithValue("key", key); + await using var reader = await previous.ExecuteReaderAsync(); + if (BatchCommands) await reader.NextResultAsync(); + if (await reader.ReadAsync()) + { + var same = reader.GetFieldValue(0).AsSpan().SequenceEqual(hash); + var result = same ? new MessageEntity(reader.GetGuid(1), reader.GetGuid(2), reader.GetGuid(3), reader.GetString(4), reader.GetDateTime(5), reader.GetFieldValue(6)) : null; + await reader.DisposeAsync(); + await transaction.CommitAsync(); + return result; + } + } + if (!BatchCommands) + await using (var cleanup = new NpgsqlCommand(""" + DELETE FROM message_requests + WHERE user_id = @user_id AND chat_id = @chat_id AND request_key = @key + """, connection, transaction)) + { + cleanup.Parameters.AddWithValue("user_id", senderId); + cleanup.Parameters.AddWithValue("chat_id", chatId); + cleanup.Parameters.AddWithValue("key", key); + await cleanup.ExecuteNonQueryAsync(); + } + var message = new MessageEntity(Guid.NewGuid(), chatId, senderId, text, UtcClock.Now(), attachmentIds); + await using (var insert = new NpgsqlCommand((BatchCommands ? "DELETE FROM message_requests WHERE user_id = @sender_id AND chat_id = @chat_id AND request_key = @key;" : "") + """ + INSERT INTO messages(id, chat_id, sender_id, text, created_at, attachment_ids) + VALUES (@id, @chat_id, @sender_id, @text, @created_at, @attachments); + INSERT INTO message_requests(user_id, chat_id, request_key, request_hash, message_id, expires_at) + VALUES (@sender_id, @chat_id, @key, @hash, @id, clock_timestamp() + interval '24 hours'); + """, connection, transaction)) + { + insert.Parameters.AddWithValue("attachments", attachmentIds); + insert.Parameters.AddWithValue("id", message.Id); + insert.Parameters.AddWithValue("chat_id", chatId); + insert.Parameters.AddWithValue("sender_id", senderId); + insert.Parameters.AddWithValue("text", text); + insert.Parameters.AddWithValue("created_at", message.CreatedAt); + insert.Parameters.AddWithValue("key", key); + insert.Parameters.AddWithValue("hash", hash); + await insert.ExecuteNonQueryAsync(); + } + await transaction.CommitAsync(); + return message; + } +} diff --git a/src/Messenger.Api/Data/Migrations/001_initial.sql b/src/Messenger.Api/Data/Migrations/001_initial.sql new file mode 100644 index 00000000..2cf544fc --- /dev/null +++ b/src/Messenger.Api/Data/Migrations/001_initial.sql @@ -0,0 +1,43 @@ +CREATE TABLE users ( + id uuid PRIMARY KEY, + username text NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'), + display_name text NOT NULL, + password_hash text NOT NULL, + created_at timestamptz NOT NULL +); + +CREATE TABLE chats ( + id uuid PRIMARY KEY, + title text NOT NULL, + created_at timestamptz NOT NULL +); + +CREATE TABLE chat_members ( + chat_id uuid NOT NULL REFERENCES chats(id), + user_id uuid NOT NULL REFERENCES users(id), + PRIMARY KEY (chat_id, user_id) +); + +CREATE INDEX chat_members_user_chat_idx ON chat_members (user_id, chat_id); +CREATE INDEX chats_created_id_idx ON chats (created_at, id); + +CREATE TABLE messages ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL REFERENCES chats(id), + sender_id uuid NOT NULL REFERENCES users(id), + text text NOT NULL, + created_at timestamptz NOT NULL +); + +CREATE INDEX messages_chat_created_id_idx ON messages (chat_id, created_at, id); + +CREATE TABLE sessions ( + token_hash bytea PRIMARY KEY, + user_id uuid NOT NULL REFERENCES users(id), + expires_at timestamptz NOT NULL, + revoked_at timestamptz, + created_at timestamptz NOT NULL +); + +CREATE INDEX sessions_user_id_idx ON sessions (user_id); +CREATE INDEX sessions_expires_at_idx ON sessions (expires_at); diff --git a/src/Messenger.Api/Data/Migrations/002_idempotency.sql b/src/Messenger.Api/Data/Migrations/002_idempotency.sql new file mode 100644 index 00000000..9ec17406 --- /dev/null +++ b/src/Messenger.Api/Data/Migrations/002_idempotency.sql @@ -0,0 +1,11 @@ +CREATE TABLE message_requests ( + user_id uuid NOT NULL REFERENCES users(id), + chat_id uuid NOT NULL REFERENCES chats(id), + request_key text NOT NULL, + request_hash bytea NOT NULL, + message_id uuid NOT NULL REFERENCES messages(id), + expires_at timestamptz NOT NULL, + PRIMARY KEY (user_id, chat_id, request_key) +); + +CREATE INDEX message_requests_expires_idx ON message_requests (expires_at); diff --git a/src/Messenger.Api/Data/Migrations/003_reactions.sql b/src/Messenger.Api/Data/Migrations/003_reactions.sql new file mode 100644 index 00000000..c4b1e44b --- /dev/null +++ b/src/Messenger.Api/Data/Migrations/003_reactions.sql @@ -0,0 +1,6 @@ +CREATE TABLE message_reactions ( + message_id uuid NOT NULL REFERENCES messages(id) ON DELETE CASCADE, + user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, + reaction text NOT NULL CHECK (reaction IN ('like', 'love', 'laugh', 'mushroom')), + PRIMARY KEY (message_id, user_id, reaction) +); diff --git a/src/Messenger.Api/Data/Migrations/004_attachments.sql b/src/Messenger.Api/Data/Migrations/004_attachments.sql new file mode 100644 index 00000000..ec837482 --- /dev/null +++ b/src/Messenger.Api/Data/Migrations/004_attachments.sql @@ -0,0 +1,11 @@ +CREATE TABLE attachments ( + id uuid PRIMARY KEY, chat_id uuid NOT NULL REFERENCES chats(id), + owner_id uuid NOT NULL REFERENCES users(id), filename text NOT NULL, + content_type text NOT NULL, size_bytes bigint NOT NULL CHECK (size_bytes BETWEEN 1 AND 10485760), + sha256 text NOT NULL, object_key text NOT NULL UNIQUE, + status text NOT NULL CHECK (status IN ('ready','missing')), + created_at timestamptz NOT NULL, updated_at timestamptz NOT NULL +); +CREATE INDEX attachments_created_idx ON attachments(created_at, id); +ALTER TABLE messages ADD COLUMN attachment_ids uuid[] NOT NULL DEFAULT '{}'; +CREATE INDEX messages_attachments_idx ON messages USING gin(attachment_ids); diff --git a/src/Messenger.Api/Data/Reactions.cs b/src/Messenger.Api/Data/Reactions.cs new file mode 100644 index 00000000..7d40ffce --- /dev/null +++ b/src/Messenger.Api/Data/Reactions.cs @@ -0,0 +1,48 @@ +using Npgsql; + +namespace Messenger.Api.Data; + +public sealed record ReactionDto(Guid MessageId, string Reaction, int Count, bool Mine); + +public sealed partial class AppDatabase +{ + public async Task SetReactionAsync(Guid chatId, Guid messageId, Guid userId, string reaction, bool present) + { + await using var command = dataSource.CreateCommand(present ? """ + WITH target AS (SELECT id FROM messages WHERE id = @message_id AND chat_id = @chat_id), + written AS ( + INSERT INTO message_reactions(message_id, user_id, reaction) + SELECT id, @user_id, @reaction FROM target ON CONFLICT DO NOTHING + ) SELECT EXISTS(SELECT 1 FROM target) + """ : """ + WITH target AS (SELECT id FROM messages WHERE id = @message_id AND chat_id = @chat_id), + removed AS ( + DELETE FROM message_reactions WHERE message_id IN (SELECT id FROM target) + AND user_id = @user_id AND reaction = @reaction + ) SELECT EXISTS(SELECT 1 FROM target) + """); + command.Parameters.AddWithValue("chat_id", chatId); + command.Parameters.AddWithValue("message_id", messageId); + command.Parameters.AddWithValue("user_id", userId); + command.Parameters.AddWithValue("reaction", reaction); + return (bool)(await command.ExecuteScalarAsync())!; + } + + public async Task> ListReactionsAsync(Guid chatId, Guid[] messageIds, Guid userId) + { + await using var command = dataSource.CreateCommand(""" + SELECT r.message_id, r.reaction, count(*)::integer, bool_or(r.user_id = @user_id) + FROM message_reactions r JOIN messages m ON m.id = r.message_id + WHERE m.chat_id = @chat_id AND m.id = ANY(@message_ids) + GROUP BY r.message_id, r.reaction ORDER BY r.message_id, r.reaction + """); + command.Parameters.AddWithValue("chat_id", chatId); + command.Parameters.AddWithValue("message_ids", messageIds); + command.Parameters.AddWithValue("user_id", userId); + await using var reader = await command.ExecuteReaderAsync(); + var items = new List(); + while (await reader.ReadAsync()) + items.Add(new(reader.GetGuid(0), reader.GetString(1), reader.GetInt32(2), reader.GetBoolean(3))); + return items; + } +} diff --git a/src/Messenger.Api/Data/UtcClock.cs b/src/Messenger.Api/Data/UtcClock.cs new file mode 100644 index 00000000..30f9fbf7 --- /dev/null +++ b/src/Messenger.Api/Data/UtcClock.cs @@ -0,0 +1,11 @@ +namespace Messenger.Api.Data; + +public static class UtcClock +{ + // PostgreSQL timestamptz stores microseconds; keep the response identical to the saved value. + public static DateTime Now() + { + var ticks = DateTime.UtcNow.Ticks; + return new DateTime(ticks - ticks % 10, DateTimeKind.Utc); + } +} diff --git a/src/Messenger.Api/Endpoints/AttachmentEndpoints.cs b/src/Messenger.Api/Endpoints/AttachmentEndpoints.cs new file mode 100644 index 00000000..550d44e1 --- /dev/null +++ b/src/Messenger.Api/Endpoints/AttachmentEndpoints.cs @@ -0,0 +1,51 @@ +using Messenger.Api.Data; +using Messenger.Api.Infrastructure; +using Messenger.Api.Services; +using Amazon.S3; +using Amazon.S3.Model; +using static Messenger.Api.Services.ApiSupport; +namespace Messenger.Api.Endpoints; +public static class AttachmentEndpoints +{ + public static IEndpointRouteBuilder MapAttachmentEndpoints(this IEndpointRouteBuilder app) + { + app.MapPost("/api/v1/chats/{chat_id}/attachments",async(string chat_id,HttpContext ctx, + SessionService sessions,ChatService chats,AttachmentService files)=> { + var(actor,_)=await sessions.AuthenticateAsync(ctx); if(actor is null) return Unauthorized(ctx); + if(!Guid.TryParse(chat_id,out var chat)) return ApiError(ctx,400,"invalid_request","Некорректный chat_id"); + if(await chats.FindForMemberAsync(chat,actor.Id) is null) return ApiError(ctx,404,"not_found","Чат не найден"); + var names=ctx.Request.Query["filename"]; var name=names.ToString(); + if(names.Count!=1 || string.IsNullOrWhiteSpace(name) || name.EnumerateRunes().Count()>255 || name.Any(c=>char.IsControl(c)||c is '/' or '\\')) + return ApiError(ctx,400,"invalid_request","Некорректное имя файла"); + if(ctx.Request.ContentType?.Split(';')[0].Trim() is not "image/png" and not "image/jpeg") + return ApiError(ctx,415,"unsupported_media_type","Требуется PNG или JPEG"); + return Results.Json(await files.UploadAsync(ctx.Request,chat,actor.Id,name),statusCode:201); + }); + app.MapGet("/api/v1/attachments/{attachment_id}",async(string attachment_id,HttpContext ctx, + SessionService sessions,AppDatabase db)=> { + var(actor,_)=await sessions.AuthenticateAsync(ctx); if(actor is null) return Unauthorized(ctx); + if(!Guid.TryParse(attachment_id,out var id)) return ApiError(ctx,400,"invalid_request","Некорректный ID"); + var file=await db.FindAttachmentAsync(id,actor.Id); + if(file is null) return ApiError(ctx,404,"not_found","Вложение не найдено"); + return file.Value.Dto.Status=="ready" ? Results.Ok(file.Value.Dto) : ApiError(ctx,409,"conflict","Оригинал недоступен"); + }); + app.MapGet("/api/v1/attachments/{attachment_id}/content",async(string attachment_id,HttpContext ctx, + SessionService sessions,AppDatabase db,S3Storage storage)=> { + var(actor,_)=await sessions.AuthenticateAsync(ctx); if(actor is null) return Unauthorized(ctx); + if(!Guid.TryParse(attachment_id,out var id)) return ApiError(ctx,400,"invalid_request","Некорректный ID"); + var file=await db.FindAttachmentAsync(id,actor.Id); + if(file is null) return ApiError(ctx,404,"not_found","Вложение не найдено"); + if(file.Value.Dto.Status!="ready") return ApiError(ctx,409,"conflict","Оригинал недоступен"); + if(ctx.Request.Query.TryGetValue("variant",out var variant) && variant!="original") + return ApiError(ctx,404,"not_found","Вариант не найден"); + try { + var original=await storage.Client.GetObjectAsync(storage.Bucket,file.Value.Key,ctx.RequestAborted); + return Results.Stream(async stream=> {using(original) {await original.ResponseStream.CopyToAsync(stream,ctx.RequestAborted);}}, + file.Value.Dto.ContentType,file.Value.Dto.Filename); + } catch(AmazonS3Exception ex) when(ex.StatusCode==System.Net.HttpStatusCode.NotFound) { + return ApiError(ctx,503,"unavailable","Оригинал временно недоступен"); + } + }); + return app; + } +} diff --git a/src/Messenger.Api/Endpoints/AuthEndpoints.cs b/src/Messenger.Api/Endpoints/AuthEndpoints.cs new file mode 100644 index 00000000..ebc792eb --- /dev/null +++ b/src/Messenger.Api/Endpoints/AuthEndpoints.cs @@ -0,0 +1,60 @@ +using System.Text; +using System.Text.RegularExpressions; +using Messenger.Api.Services; +using static Messenger.Api.Services.ApiSupport; + +namespace Messenger.Api.Endpoints; + +public static class AuthEndpoints +{ + private static readonly UTF8Encoding StrictUtf8 = new(false, true); + + public static IEndpointRouteBuilder MapAuthEndpoints(this IEndpointRouteBuilder app) + { + app.MapPost("/api/v1/auth/sessions", async (HttpContext context, SessionService sessions) => + { + if (!context.Request.Headers.TryGetValue("Authorization", out var header)) + return Unauthorized(context, basic: true); + + var authorization = header.ToString(); + if (!authorization.StartsWith("Basic ", StringComparison.OrdinalIgnoreCase)) + return Unauthorized(context, basic: true); + + string credentials; + try + { + credentials = StrictUtf8.GetString(Convert.FromBase64String(authorization[6..])); + } + catch (Exception exception) when (exception is FormatException or DecoderFallbackException) + { + return Unauthorized(context, basic: true); + } + + var delimiter = credentials.IndexOf(':'); + if (delimiter < 0) return Unauthorized(context, basic: true); + var username = credentials[..delimiter]; + var password = credentials[(delimiter + 1)..]; + if (!Regex.IsMatch(username, "\\A[a-z0-9_]{3,32}\\z")) + return Unauthorized(context, basic: true); + + if (context.Request.ContentLength > 0 || context.Request.Headers.ContainsKey("Transfer-Encoding")) + return ApiError(context, 400, "invalid_request", "Вход принимает Basic без тела запроса"); + + var session = await sessions.LoginAsync(username, password); + return session is null + ? Unauthorized(context, basic: true) + : Results.Json(session, statusCode: StatusCodes.Status201Created); + }); + + app.MapDelete("/api/v1/auth/sessions/current", async (HttpContext context, SessionService sessions) => + { + var (user, tokenHash) = await sessions.AuthenticateAsync(context); + if (user is null || tokenHash is null) return Unauthorized(context); + return await sessions.RevokeAsync(tokenHash) + ? Results.NoContent() + : Unauthorized(context); + }); + + return app; + } +} diff --git a/src/Messenger.Api/Endpoints/ChatEndpoints.cs b/src/Messenger.Api/Endpoints/ChatEndpoints.cs new file mode 100644 index 00000000..127feb04 --- /dev/null +++ b/src/Messenger.Api/Endpoints/ChatEndpoints.cs @@ -0,0 +1,67 @@ +using Messenger.Api.Contracts; +using Messenger.Api.Services; +using static Messenger.Api.Services.ApiSupport; + +namespace Messenger.Api.Endpoints; + +public static class ChatEndpoints +{ + public static IEndpointRouteBuilder MapChatEndpoints(this IEndpointRouteBuilder app) + { + app.MapPost("/api/v1/chats", async (HttpContext context, SessionService sessions, ChatService chats) => + { + var (actor, _) = await sessions.AuthenticateAsync(context); + if (actor is null) return Unauthorized(context); + + var (request, error) = await ReadJsonAsync(context); + if (error is not null) return error; + if (string.IsNullOrWhiteSpace(request!.Title) || request.Title.EnumerateRunes().Count() > 100) + return ApiError(context, 400, "invalid_request", "Некорректное название чата"); + if (request.MemberIds is null || request.MemberIds.Count is < 1 or > 100 || + request.MemberIds.Distinct().Count() != request.MemberIds.Count || + !request.MemberIds.Contains(actor.Id)) + return ApiError(context, 400, "invalid_request", "Некорректный список участников"); + + var chat = await chats.CreateAsync(request.Title, request.MemberIds); + return chat is null + ? ApiError(context, 400, "invalid_request", "Один из участников не существует") + : Results.Json(chat, statusCode: StatusCodes.Status201Created); + }); + + app.MapGet("/api/v1/chats", async (HttpContext context, SessionService sessions, ChatService chats) => + { + var (actor, _) = await sessions.AuthenticateAsync(context); + if (actor is null) return Unauthorized(context); + var (limit, limitError) = ParseLimit(context); + if (limitError is not null) return limitError; + var (cursor, cursorTime, cursorError) = ParseCursor(context, $"user:{actor.Id}"); + if (cursorError is not null) return cursorError; + + var page = await chats.ListAsync(actor.Id, cursorTime, cursor?.Id, limit + 1); + string? nextCursor = null; + if (page.Count > limit) + { + var last = page[limit - 1]; + nextCursor = CursorService.EncodeChatCursor(new ChatCursor($"user:{actor.Id}", last.CreatedAt, last.Id)); + page = page.Take(limit).ToList(); + } + return Results.Ok(new { items = page, next_cursor = nextCursor }); + }); + + app.MapGet("/api/v1/chats/{chat_id}", async ( + string chat_id, HttpContext context, SessionService sessions, ChatService chats) => + { + var (actor, _) = await sessions.AuthenticateAsync(context); + if (actor is null) return Unauthorized(context); + if (!Guid.TryParse(chat_id, out var chatId)) + return ApiError(context, 400, "invalid_request", "Некорректный chat_id"); + + var chat = await chats.FindForMemberAsync(chatId, actor.Id); + return chat is null + ? ApiError(context, 404, "not_found", "Чат не найден") + : Results.Ok(chat); + }); + + return app; + } +} diff --git a/src/Messenger.Api/Endpoints/HealthEndpoints.cs b/src/Messenger.Api/Endpoints/HealthEndpoints.cs new file mode 100644 index 00000000..da8f4eb0 --- /dev/null +++ b/src/Messenger.Api/Endpoints/HealthEndpoints.cs @@ -0,0 +1,18 @@ +using Messenger.Api.Data; +using Messenger.Api.Services; +using Messenger.Api.Infrastructure; + +namespace Messenger.Api.Endpoints; + +public static class HealthEndpoints +{ + public static IEndpointRouteBuilder MapHealthEndpoints(this IEndpointRouteBuilder app) + { + app.MapGet("/health/live", () => Results.Ok(new { status = "ok" })); + app.MapGet("/health/ready", async (HttpContext context, AppDatabase database, ReadinessState readiness, S3Storage storage) => + !readiness.IsStopping && await database.IsReadyAsync() && await storage.ReadyAsync() + ? Results.Ok(new { status = "ok" }) + : ApiSupport.ApiError(context, 503, "unavailable", "Хранилище недоступно")); + return app; + } +} diff --git a/src/Messenger.Api/Endpoints/MessageEndpoints.cs b/src/Messenger.Api/Endpoints/MessageEndpoints.cs new file mode 100644 index 00000000..db0b9985 --- /dev/null +++ b/src/Messenger.Api/Endpoints/MessageEndpoints.cs @@ -0,0 +1,80 @@ +using Messenger.Api.Contracts; +using Messenger.Api.Services; +using System.Text.Json; +using static Messenger.Api.Services.ApiSupport; + +namespace Messenger.Api.Endpoints; + +public static class MessageEndpoints +{ + public static IEndpointRouteBuilder MapMessageEndpoints(this IEndpointRouteBuilder app) + { + app.MapPost("/api/v1/chats/{chat_id}/messages", async ( + string chat_id, HttpContext context, SessionService sessions, ChatService chats, MessageService messages) => + { + var (actor, _) = await sessions.AuthenticateAsync(context); + if (actor is null) return Unauthorized(context); + if (!Guid.TryParse(chat_id, out var chatId)) + return ApiError(context, 400, "invalid_request", "Некорректный chat_id"); + if (await chats.FindForMemberAsync(chatId, actor.Id) is null) + return ApiError(context, 404, "not_found", "Чат не найден"); + + var keys = context.Request.Headers["Idempotency-Key"]; + var key = keys.ToString(); + if (keys.Count != 1 || key.Length is < 1 or > 128 || + key.Any(c => !char.IsAsciiLetterOrDigit(c) && c is not '.' and not '_' and not ':' and not '-')) + return ApiError(context, 400, "invalid_request", "Требуется корректный Idempotency-Key"); + + var (request, error) = await ReadJsonAsync(context); + if (error is not null) return error; + if (request!.Text is null || request.Text.EnumerateRunes().Count() > 4000) + return ApiError(context, 400, "invalid_request", "Некорректный текст сообщения"); + var ids = new List(); + if (request.AttachmentIds.ValueKind != JsonValueKind.Undefined) + { + if (request.AttachmentIds.ValueKind != JsonValueKind.Array || request.AttachmentIds.GetArrayLength()>10) + return ApiError(context,400,"invalid_request","Некорректный список вложений"); + foreach(var item in request.AttachmentIds.EnumerateArray()) + { + if(item.ValueKind!=JsonValueKind.String || !item.TryGetGuid(out var id) || ids.Contains(id)) + return ApiError(context,400,"invalid_request","Некорректный ID вложения"); + ids.Add(id); + } + } + if(string.IsNullOrWhiteSpace(request.Text) && ids.Count==0) + return ApiError(context,400,"invalid_request","Нужен текст или вложение"); + + var message = await messages.CreateAsync(chatId, actor.Id, request.Text, key, ids.ToArray()); + if (message is null) + return ApiError(context, 409, "conflict", "Этот ключ уже использован для другого сообщения"); + return Results.Json(message, statusCode: StatusCodes.Status201Created); + }); + + app.MapGet("/api/v1/chats/{chat_id}/messages", async ( + string chat_id, HttpContext context, SessionService sessions, ChatService chats, MessageService messages) => + { + var (actor, _) = await sessions.AuthenticateAsync(context); + if (actor is null) return Unauthorized(context); + if (!Guid.TryParse(chat_id, out var chatId)) + return ApiError(context, 400, "invalid_request", "Некорректный chat_id"); + if (await chats.FindForMemberAsync(chatId, actor.Id) is null) + return ApiError(context, 404, "not_found", "Чат не найден"); + var (limit, limitError) = ParseLimit(context); + if (limitError is not null) return limitError; + var (cursor, cursorTime, cursorError) = ParseCursor(context, $"chat:{chatId}"); + if (cursorError is not null) return cursorError; + + var page = await messages.ListAsync(chatId, cursorTime, cursor?.Id, limit + 1); + string? nextCursor = null; + if (page.Count > limit) + { + var last = page[limit - 1]; + nextCursor = CursorService.EncodeChatCursor(new ChatCursor($"chat:{chatId}", last.CreatedAt, last.Id)); + page = page.Take(limit).ToList(); + } + return Results.Ok(new { items = page, next_cursor = nextCursor }); + }); + + return app; + } +} diff --git a/src/Messenger.Api/Endpoints/ReactionEndpoints.cs b/src/Messenger.Api/Endpoints/ReactionEndpoints.cs new file mode 100644 index 00000000..5459a1a4 --- /dev/null +++ b/src/Messenger.Api/Endpoints/ReactionEndpoints.cs @@ -0,0 +1,39 @@ +using Messenger.Api.Data; +using Messenger.Api.Services; +using static Messenger.Api.Services.ApiSupport; + +namespace Messenger.Api.Endpoints; + +public static class ReactionEndpoints +{ + public static IEndpointRouteBuilder MapReactionEndpoints(this IEndpointRouteBuilder app) + { + app.MapGet("/api/ui/chats/{chat_id}/reactions", async ( + string chat_id, HttpContext context, SessionService sessions, ChatService chats, AppDatabase database) => + { + var (actor, _) = await sessions.AuthenticateAsync(context); + if (actor is null) return Unauthorized(context); + if (!Guid.TryParse(chat_id, out var chatId)) return ApiError(context, 400, "invalid_request", "Некорректный chat_id"); + if (await chats.FindForMemberAsync(chatId, actor.Id) is null) return ApiError(context, 404, "not_found", "Чат не найден"); + var values = context.Request.Query["message_ids"].ToString().Split(','); + if (values.Length is < 1 or > 100 || values.Any(value => !Guid.TryParse(value, out _))) + return ApiError(context, 400, "invalid_request", "Укажите от 1 до 100 ID сообщений"); + var ids = values.Select(Guid.Parse).Distinct().ToArray(); + return Results.Ok(new { items = await database.ListReactionsAsync(chatId, ids, actor.Id) }); + }); + app.MapMethods("/api/ui/chats/{chat_id}/messages/{message_id}/reactions/{reaction}", ["PUT", "DELETE"], async ( + string chat_id, string message_id, string reaction, HttpContext context, + SessionService sessions, ChatService chats, AppDatabase database) => + { + var (actor, _) = await sessions.AuthenticateAsync(context); + if (actor is null) return Unauthorized(context); + if (!Guid.TryParse(chat_id, out var chatId) || !Guid.TryParse(message_id, out var messageId) + || reaction is not ("like" or "love" or "laugh" or "mushroom")) + return ApiError(context, 400, "invalid_request", "Некорректная реакция или ID"); + if (await chats.FindForMemberAsync(chatId, actor.Id) is null) return ApiError(context, 404, "not_found", "Чат не найден"); + return await database.SetReactionAsync(chatId, messageId, actor.Id, reaction, context.Request.Method == "PUT") + ? Results.NoContent() : ApiError(context, 404, "not_found", "Сообщение не найдено"); + }); + return app; + } +} diff --git a/src/Messenger.Api/Endpoints/UiEndpoints.cs b/src/Messenger.Api/Endpoints/UiEndpoints.cs new file mode 100644 index 00000000..752d7fe0 --- /dev/null +++ b/src/Messenger.Api/Endpoints/UiEndpoints.cs @@ -0,0 +1,80 @@ +using Messenger.Api.Contracts; +using Messenger.Api.Services; +using Messenger.Api.Data; +using Messenger.Api.Infrastructure; +using static Messenger.Api.Services.ApiSupport; + +namespace Messenger.Api.Endpoints; + +public static class UiEndpoints +{ + // The required /api/v1 history stays ascending. The web client has a separate, + // optional route to open a large chat at its newest page and page backwards. + public static IEndpointRouteBuilder MapUiEndpoints(this IEndpointRouteBuilder app) + { + app.MapGet("/api/ui/cluster", async (HttpContext context, SessionService sessions, ClusterPresence presence) => + { + var (actor, _) = await sessions.AuthenticateAsync(context); + if (actor is null) return Unauthorized(context); + context.Response.Headers.CacheControl = "no-store"; + return Results.Ok(await presence.ReadAsync()); + }); + + app.MapGet("/api/ui/chats", async (HttpContext context, SessionService sessions, AppDatabase database) => + { + var (actor, _) = await sessions.AuthenticateAsync(context); + if (actor is null) return Unauthorized(context); + var (limit, limitError) = ParseLimit(context); + if (limitError is not null) return limitError; + var (cursor, cursorTime, cursorError) = ParseCursor(context, $"ui-chats:{actor.Id}"); + if (cursorError is not null) return cursorError; + var page = await database.ListChatPreviewsAsync(actor.Id, cursorTime, cursor?.Id, limit + 1); + string? nextCursor = null; + if (page.Count > limit) + { + var last = page[limit - 1]; + nextCursor = CursorService.EncodeChatCursor(new ChatCursor($"ui-chats:{actor.Id}", last.CreatedAt, last.Id)); + page = page.Take(limit).ToList(); + } + return Results.Ok(new { items = page, next_cursor = nextCursor }); + }); + + app.MapGet("/api/ui/chats/{chat_id}/members", async ( + string chat_id, HttpContext context, SessionService sessions, ChatService chats, UserService users) => + { + var (actor, _) = await sessions.AuthenticateAsync(context); + if (actor is null) return Unauthorized(context); + if (!Guid.TryParse(chat_id, out var chatId)) + return ApiError(context, 400, "invalid_request", "Некорректный chat_id"); + if (await chats.FindForMemberAsync(chatId, actor.Id) is null) + return ApiError(context, 404, "not_found", "Чат не найден"); + return Results.Ok(new { items = await users.ListForChatAsync(chatId) }); + }); + + app.MapGet("/api/ui/chats/{chat_id}/messages", async ( + string chat_id, HttpContext context, SessionService sessions, ChatService chats, MessageService messages) => + { + var (actor, _) = await sessions.AuthenticateAsync(context); + if (actor is null) return Unauthorized(context); + if (!Guid.TryParse(chat_id, out var chatId)) + return ApiError(context, 400, "invalid_request", "Некорректный chat_id"); + if (await chats.FindForMemberAsync(chatId, actor.Id) is null) + return ApiError(context, 404, "not_found", "Чат не найден"); + var (limit, limitError) = ParseLimit(context); + if (limitError is not null) return limitError; + var (cursor, cursorTime, cursorError) = ParseCursor(context, $"recent-chat:{chatId}"); + if (cursorError is not null) return cursorError; + + var page = await messages.ListAsync(chatId, cursorTime, cursor?.Id, limit + 1, newestFirst: true); + string? nextCursor = null; + if (page.Count > limit) + { + var last = page[limit - 1]; + nextCursor = CursorService.EncodeChatCursor(new ChatCursor($"recent-chat:{chatId}", last.CreatedAt, last.Id)); + page = page.Take(limit).ToList(); + } + return Results.Ok(new { items = page, next_cursor = nextCursor }); + }); + return app; + } +} diff --git a/src/Messenger.Api/Endpoints/UserEndpoints.cs b/src/Messenger.Api/Endpoints/UserEndpoints.cs new file mode 100644 index 00000000..a6725b19 --- /dev/null +++ b/src/Messenger.Api/Endpoints/UserEndpoints.cs @@ -0,0 +1,40 @@ +using System.Text.RegularExpressions; +using Messenger.Api.Contracts; +using Messenger.Api.Services; +using static Messenger.Api.Services.ApiSupport; + +namespace Messenger.Api.Endpoints; + +public static class UserEndpoints +{ + public static IEndpointRouteBuilder MapUserEndpoints(this IEndpointRouteBuilder app) + { + app.MapPost("/api/v1/users", async (HttpContext context, UserService users) => + { + var (request, error) = await ReadJsonAsync(context); + if (error is not null) return error; + + if (request!.Username is null || !Regex.IsMatch(request.Username, "\\A[a-z0-9_]{3,32}\\z")) + return ApiError(context, 400, "invalid_request", "Некорректный username"); + if (string.IsNullOrWhiteSpace(request.DisplayName) || + request.DisplayName.EnumerateRunes().Count() is < 1 or > 100) + return ApiError(context, 400, "invalid_request", "Некорректный display_name"); + if (string.IsNullOrWhiteSpace(request.Password) || + request.Password.EnumerateRunes().Count() is < 12 or > 128) + return ApiError(context, 400, "invalid_request", "Пароль должен содержать 12-128 символов"); + + var user = await users.RegisterAsync(request.Username, request.DisplayName, request.Password); + return user is null + ? ApiError(context, 409, "conflict", "Username уже занят") + : Results.Json(user, statusCode: StatusCodes.Status201Created); + }); + + app.MapGet("/api/v1/users/me", async (HttpContext context, SessionService sessions) => + { + var (user, _) = await sessions.AuthenticateAsync(context); + return user is null ? Unauthorized(context) : Results.Ok(user); + }); + + return app; + } +} diff --git a/src/Messenger.Api/Infrastructure/ClusterPresence.cs b/src/Messenger.Api/Infrastructure/ClusterPresence.cs new file mode 100644 index 00000000..adccb65b --- /dev/null +++ b/src/Messenger.Api/Infrastructure/ClusterPresence.cs @@ -0,0 +1,55 @@ +using Messenger.Api.Data; +using StackExchange.Redis; + +namespace Messenger.Api.Infrastructure; + +// Registry entries live ten minutes; an eight-second heartbeat gap means unavailable. +// A Redis outage is reported as unknown, never as proof that an API has stopped. +public sealed class ClusterPresence(IConnectionMultiplexer redis, InstanceIdentity identity, + ReadinessState readiness, AppDatabase database, ILogger logger) : BackgroundService +{ + private const string Registry = "messenger:ui:instances"; + public sealed record Node(string Id, bool Ready, long LastSeen); + public sealed record Snapshot(bool RedisAvailable, bool PostgresAvailable, long CheckedAt, List Instances); + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + using var timer = new PeriodicTimer(TimeSpan.FromSeconds(2)); + try + { + do + { + try + { + if (redis.IsConnected && !readiness.IsStopping && await database.IsReadyAsync()) + { + var db = redis.GetDatabase(); + var now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + await db.SortedSetAddAsync(Registry, identity.Id, now).WaitAsync(TimeSpan.FromSeconds(1), stoppingToken); + await db.SortedSetRemoveRangeByScoreAsync(Registry, double.NegativeInfinity, now - 600_000); + await db.KeyExpireAsync(Registry, TimeSpan.FromMinutes(15)); + } + } + catch (Exception error) when (error is RedisException or TimeoutException) + { logger.LogDebug("Cluster heartbeat unavailable"); } + } while (await timer.WaitForNextTickAsync(stoppingToken)); + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { } + } + + public async Task ReadAsync() + { + var now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + var postgres = await database.IsReadyAsync(); + try + { + if (!redis.IsConnected) return new(false, postgres, now, []); + var entries = await redis.GetDatabase().SortedSetRangeByScoreWithScoresAsync(Registry, + now - 600_000, double.PositiveInfinity).WaitAsync(TimeSpan.FromSeconds(1)); + return new(true, postgres, now, entries.Select(entry => new Node(entry.Element.ToString(), + now - entry.Score < 8000, (long)entry.Score)).ToList()); + } + catch (Exception error) when (error is RedisException or TimeoutException) + { return new(false, postgres, now, []); } + } +} diff --git a/src/Messenger.Api/Infrastructure/InstanceIdentity.cs b/src/Messenger.Api/Infrastructure/InstanceIdentity.cs new file mode 100644 index 00000000..855f4460 --- /dev/null +++ b/src/Messenger.Api/Infrastructure/InstanceIdentity.cs @@ -0,0 +1,6 @@ +namespace Messenger.Api.Infrastructure; + +public sealed class InstanceIdentity +{ + public string Id { get; } = Guid.NewGuid().ToString("N"); +} diff --git a/src/Messenger.Api/Infrastructure/ReadinessState.cs b/src/Messenger.Api/Infrastructure/ReadinessState.cs new file mode 100644 index 00000000..35981ef2 --- /dev/null +++ b/src/Messenger.Api/Infrastructure/ReadinessState.cs @@ -0,0 +1,8 @@ +namespace Messenger.Api.Infrastructure; + +public sealed class ReadinessState +{ + private int _stopping; + public bool IsStopping => Volatile.Read(ref _stopping) != 0; + public void Stop() => Interlocked.Exchange(ref _stopping, 1); +} diff --git a/src/Messenger.Api/Infrastructure/RedisSessionCache.cs b/src/Messenger.Api/Infrastructure/RedisSessionCache.cs new file mode 100644 index 00000000..09e977fa --- /dev/null +++ b/src/Messenger.Api/Infrastructure/RedisSessionCache.cs @@ -0,0 +1,58 @@ +using System.Text.Json; +using Messenger.Api.Contracts; +using StackExchange.Redis; + +namespace Messenger.Api.Infrastructure; + +// PostgreSQL validates the session on every request. This cache saves the user lookup +// and never grants access independently of the durable session row. +public sealed class RedisSessionCache(IConnectionMultiplexer connection, ILogger logger) +{ + private static readonly TimeSpan OperationBudget = TimeSpan.FromMilliseconds(750); + private static string Key(byte[] hash) => "messenger:session:" + Convert.ToHexString(hash).ToLowerInvariant(); + + public sealed record Entry(UserDto User, DateTime ExpiresAt); + + public async Task GetAsync(byte[] hash) + { + if (!connection.IsConnected) return null; + try + { + var value = await connection.GetDatabase().StringGetAsync(Key(hash)).WaitAsync(OperationBudget); + return value.IsNullOrEmpty ? null : JsonSerializer.Deserialize(value.ToString()); + } + catch (Exception exception) when (exception is RedisException or TimeoutException or OperationCanceledException or JsonException) + { + logger.LogWarning("Session cache read unavailable; using PostgreSQL"); + return null; + } + } + + public async Task SetAsync(byte[] hash, UserDto user, DateTime expiresAt) + { + var remaining = expiresAt - DateTime.UtcNow; + if (!connection.IsConnected || remaining <= TimeSpan.Zero) return; + try + { + await connection.GetDatabase().StringSetAsync(Key(hash), + JsonSerializer.Serialize(new Entry(user, expiresAt)), remaining).WaitAsync(OperationBudget); + } + catch (Exception exception) when (exception is RedisException or TimeoutException or OperationCanceledException) + { + logger.LogWarning("Session cache write unavailable; using PostgreSQL"); + } + } + + public async Task RemoveAsync(byte[] hash) + { + if (!connection.IsConnected) return; + try + { + await connection.GetDatabase().KeyDeleteAsync(Key(hash)).WaitAsync(OperationBudget); + } + catch (Exception exception) when (exception is RedisException or TimeoutException or OperationCanceledException) + { + logger.LogWarning("Session cache invalidation unavailable; PostgreSQL still enforces revocation"); + } + } +} diff --git a/src/Messenger.Api/Infrastructure/S3Storage.cs b/src/Messenger.Api/Infrastructure/S3Storage.cs new file mode 100644 index 00000000..719fb30b --- /dev/null +++ b/src/Messenger.Api/Infrastructure/S3Storage.cs @@ -0,0 +1,26 @@ +using Amazon.S3; +using Amazon.S3.Model; +using Amazon.Runtime; +namespace Messenger.Api.Infrastructure; +public sealed class S3Storage : IDisposable +{ + public AmazonS3Client Client { get; } + public string Bucket { get; } + public S3Storage(IConfiguration config) + { + Bucket=config["S3_BUCKET"] ?? "messenger"; + Client=new AmazonS3Client(new BasicAWSCredentials( + File.ReadAllText(config["S3_ACCESS_KEY_FILE"]!).Trim(), + File.ReadAllText(config["S3_SECRET_KEY_FILE"]!).Trim()),new AmazonS3Config { + ServiceURL=config["S3_ENDPOINT"] ?? "http://s3:9000", ForcePathStyle=true, + AuthenticationRegion="us-east-1", MaxErrorRetry=0, Timeout=TimeSpan.FromSeconds(20) + }); + } + public async Task ReadyAsync() + { + using var timeout=new CancellationTokenSource(TimeSpan.FromSeconds(1)); + try { await Client.ListObjectsV2Async(new ListObjectsV2Request {BucketName=Bucket,MaxKeys=1},timeout.Token); return true; } + catch { return false; } + } + public void Dispose() => Client.Dispose(); +} diff --git a/src/Messenger.Api/Messenger.Api.csproj b/src/Messenger.Api/Messenger.Api.csproj new file mode 100644 index 00000000..3985708c --- /dev/null +++ b/src/Messenger.Api/Messenger.Api.csproj @@ -0,0 +1,22 @@ + + + + net9.0 + enable + enable + + + + + + + + + + + + + + + + diff --git a/src/Messenger.Api/Middleware/ExceptionHandlingMiddleware.cs b/src/Messenger.Api/Middleware/ExceptionHandlingMiddleware.cs new file mode 100644 index 00000000..1047f952 --- /dev/null +++ b/src/Messenger.Api/Middleware/ExceptionHandlingMiddleware.cs @@ -0,0 +1,42 @@ +using Messenger.Api.Services; +using System.Net.Sockets; +using Npgsql; + +namespace Messenger.Api.Middleware; + +public sealed class ExceptionHandlingMiddleware(RequestDelegate next, ILogger logger) +{ + public async Task InvokeAsync(HttpContext context) + { + try + { + await next(context); + } + catch (AttachmentException exception) + { + if(!context.Response.HasStarted) + await ApiSupport.ApiError(context,exception.Status,exception.Code,exception.Message).ExecuteAsync(context); + } + catch (OperationCanceledException) when (!context.RequestAborted.IsCancellationRequested) + { + if(!context.Response.HasStarted) + await ApiSupport.ApiError(context,503,"unavailable","Время ожидания истекло").ExecuteAsync(context); + } + catch (BadHttpRequestException exception) when(exception.StatusCode==413) + { + await ApiSupport.ApiError(context,413,"payload_too_large","Слишком большой запрос").ExecuteAsync(context); + } + catch (Exception exception) when (exception is NpgsqlException or SocketException or TimeoutException or Amazon.S3.AmazonS3Exception or HttpRequestException) + { + logger.LogError(exception, "Database request failed"); + if (!context.Response.HasStarted) + await ApiSupport.ApiError(context, 503, "unavailable", "Сервис временно недоступен").ExecuteAsync(context); + } + catch (Exception exception) + { + logger.LogError(exception, "Request failed"); + if (!context.Response.HasStarted) + await ApiSupport.ApiError(context, 500, "internal_error", "Внутренняя ошибка").ExecuteAsync(context); + } + } +} diff --git a/src/Messenger.Api/Middleware/InstanceMiddleware.cs b/src/Messenger.Api/Middleware/InstanceMiddleware.cs new file mode 100644 index 00000000..c4b75741 --- /dev/null +++ b/src/Messenger.Api/Middleware/InstanceMiddleware.cs @@ -0,0 +1,18 @@ +using Messenger.Api.Infrastructure; +using Messenger.Api.Services; + +namespace Messenger.Api.Middleware; + +public sealed class InstanceMiddleware(RequestDelegate next) +{ + public async Task InvokeAsync(HttpContext context, InstanceIdentity identity, ReadinessState readiness) + { + context.Response.Headers["X-Instance-Id"] = identity.Id; + if (readiness.IsStopping && context.Request.Path != "/health/live") + { + await ApiSupport.ApiError(context, 503, "unavailable", "Экземпляр API останавливается").ExecuteAsync(context); + return; + } + await next(context); + } +} diff --git a/src/Messenger.Api/Middleware/RequestIdMiddleware.cs b/src/Messenger.Api/Middleware/RequestIdMiddleware.cs new file mode 100644 index 00000000..973b6373 --- /dev/null +++ b/src/Messenger.Api/Middleware/RequestIdMiddleware.cs @@ -0,0 +1,16 @@ +namespace Messenger.Api.Middleware; + +public sealed class RequestIdMiddleware +{ + private readonly RequestDelegate _next; + + public RequestIdMiddleware(RequestDelegate next) => _next = next; + + public async Task InvokeAsync(HttpContext context) + { + var requestId = Guid.NewGuid().ToString(); + context.Items["RequestId"] = requestId; + context.Response.Headers["X-Request-Id"] = requestId; + await _next(context); + } +} diff --git a/src/Messenger.Api/Middleware/RequestLoggingMiddleware.cs b/src/Messenger.Api/Middleware/RequestLoggingMiddleware.cs new file mode 100644 index 00000000..865f56d6 --- /dev/null +++ b/src/Messenger.Api/Middleware/RequestLoggingMiddleware.cs @@ -0,0 +1,25 @@ +namespace Messenger.Api.Middleware; + +public sealed class RequestLoggingMiddleware +{ + private readonly RequestDelegate _next; + + public RequestLoggingMiddleware(RequestDelegate next) => _next = next; + + public async Task InvokeAsync(HttpContext context) + { + var logger = context.RequestServices + .GetRequiredService() + .CreateLogger("Http"); + + await _next(context); + + logger.LogInformation( + "{Method} {Path} -> {StatusCode} request_id={RequestId}", + context.Request.Method, + context.Request.Path, + context.Response.StatusCode, + context.Items["RequestId"] + ); + } +} diff --git a/src/Messenger.Api/Program.cs b/src/Messenger.Api/Program.cs new file mode 100644 index 00000000..d6be52a3 --- /dev/null +++ b/src/Messenger.Api/Program.cs @@ -0,0 +1,110 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using Messenger.Api.Data; +using Messenger.Api.Endpoints; +using Messenger.Api.Infrastructure; +using Messenger.Api.Middleware; +using Messenger.Api.Services; +using Npgsql; +using StackExchange.Redis; + +ThreadPool.GetMinThreads(out var workerThreads, out var completionThreads); +ThreadPool.SetMinThreads(Math.Max(8, workerThreads), completionThreads); + +var builder = WebApplication.CreateBuilder(args); + +if(args.Contains("--bootstrap")) +{ + using var storage=new S3Storage(builder.Configuration); + try { await storage.Client.GetBucketLocationAsync(storage.Bucket); } + catch(Amazon.S3.AmazonS3Exception ex) when(ex.StatusCode==System.Net.HttpStatusCode.NotFound) + { await storage.Client.PutBucketAsync(storage.Bucket); } + Console.WriteLine("Private bucket ready"); + return; +} + +var host = Environment.GetEnvironmentVariable("APP_HOST") ?? "0.0.0.0"; +var port = Environment.GetEnvironmentVariable("APP_PORT") ?? "8080"; +builder.WebHost.UseUrls($"http://{host}:{port}"); + +builder.Services.ConfigureHttpJsonOptions(options => +{ + options.SerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower; + options.SerializerOptions.UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow; +}); + +var databaseUrlFile = Environment.GetEnvironmentVariable("DATABASE_URL_FILE"); +var databaseUrl = databaseUrlFile is not null + ? File.ReadAllText(databaseUrlFile).Trim() + : Environment.GetEnvironmentVariable("DATABASE_URL"); +if (string.IsNullOrWhiteSpace(databaseUrl)) + throw new InvalidOperationException("Set DATABASE_URL_FILE or DATABASE_URL before starting the API"); + +var connectionString = new NpgsqlConnectionStringBuilder(databaseUrl) +{ + MaxPoolSize = int.TryParse(builder.Configuration["DB_POOL_SIZE"], out var poolSize) && poolSize > 0 ? poolSize : 20, + Timeout = 5, + ApplicationName = "messenger-api", + CommandTimeout = 10 +}; +var dataSource = NpgsqlDataSource.Create(connectionString.ConnectionString); +if (args.Contains("--migrate", StringComparer.Ordinal)) +{ + await DatabaseMigrator.ApplyAsync(dataSource); + await dataSource.DisposeAsync(); + return; +} +builder.Services.AddSingleton(dataSource); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.Configure(options => options.ShutdownTimeout = TimeSpan.FromSeconds(8)); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +var redisOptions = ConfigurationOptions.Parse(builder.Configuration["REDIS_URL"] ?? "localhost:6379"); +redisOptions.AbortOnConnectFail = false; +redisOptions.ConnectTimeout = 500; +redisOptions.ConnectRetry = 0; +redisOptions.AsyncTimeout = 500; +redisOptions.SyncTimeout = 500; +redisOptions.BacklogPolicy = BacklogPolicy.FailFast; +builder.Services.AddSingleton(await ConnectionMultiplexer.ConnectAsync(redisOptions)); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddHostedService(services => services.GetRequiredService()); + +var app = builder.Build(); +if(args.Contains("--reconcile")) +{ + await app.Services.GetRequiredService().RunAsync(args.Contains("--apply")); + await app.DisposeAsync(); + return; +} +app.Lifetime.ApplicationStopping.Register(app.Services.GetRequiredService().Stop); + +app.UseMiddleware(); +app.UseMiddleware(); +app.UseMiddleware(); +app.UseMiddleware(); +app.UseDefaultFiles(); +app.UseStaticFiles(new StaticFileOptions +{ + OnPrepareResponse = context => context.Context.Response.Headers.CacheControl = "no-cache" +}); + +app.MapHealthEndpoints(); +app.MapUserEndpoints(); +app.MapAuthEndpoints(); +app.MapChatEndpoints(); +app.MapMessageEndpoints(); +app.MapAttachmentEndpoints(); +app.MapUiEndpoints(); +app.MapReactionEndpoints(); + +app.Run(); diff --git a/src/Messenger.Api/Properties/launchSettings.json b/src/Messenger.Api/Properties/launchSettings.json new file mode 100644 index 00000000..ac9df787 --- /dev/null +++ b/src/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:5052", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7253;http://localhost:5052", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/src/Messenger.Api/Services/ApiSupport.cs b/src/Messenger.Api/Services/ApiSupport.cs new file mode 100644 index 00000000..7936d712 --- /dev/null +++ b/src/Messenger.Api/Services/ApiSupport.cs @@ -0,0 +1,93 @@ +using System.Globalization; +using System.Text.Json; +using Messenger.Api.Contracts; + +namespace Messenger.Api.Services; + +public static class ApiSupport +{ + public static async Task<(T? Value, IResult? Error)> ReadJsonAsync(HttpContext context) + { + if (!context.Request.HasJsonContentType()) + return (default, ApiError(context, 400, "invalid_request", "Требуется application/json")); + + try + { + var value = await context.Request.ReadFromJsonAsync(); + return value is null + ? (default, ApiError(context, 400, "invalid_request", "Тело запроса обязательно")) + : (value, null); + } + catch (Exception exception) when (exception is JsonException or NotSupportedException or BadHttpRequestException) + { + return (default, ApiError(context, 400, "invalid_request", "Некорректный JSON")); + } + } + + public static IResult Unauthorized(HttpContext context, bool basic = false) + { + context.Response.Headers["WWW-Authenticate"] = basic + ? "Basic realm=\"messenger\", charset=\"UTF-8\"" + : "Bearer realm=\"messenger\""; + return ApiError(context, 401, "unauthorized", "Требуется действительная сессия"); + } + + public static (ChatCursor? Cursor, DateTime? Time, IResult? Error) ParseCursor( + HttpContext context, string scope) + { + if (!context.Request.Query.TryGetValue("cursor", out var value)) + return (null, null, null); + + var cursor = CursorService.DecodeChatCursor(value.ToString()); + if (cursor is null || cursor.Scope != scope || cursor.Id == Guid.Empty || + !DateTime.TryParse(cursor.CreatedAt, CultureInfo.InvariantCulture, + DateTimeStyles.RoundtripKind, out var time) || time.Kind != DateTimeKind.Utc) + return (null, null, ApiError(context, 400, "invalid_request", "Некорректный cursor")); + + return (cursor, time, null); + } + + public static (int Limit, IResult? Error) ParseLimit(HttpContext context) + { + const int defaultLimit = 50; + + if (!context.Request.Query.TryGetValue("limit", out var value)) + return (defaultLimit, null); + + if (!int.TryParse(value.ToString(), out var limit) || + limit < 1 || + limit > 100) + { + return ( + 0, + ApiError(context, 400, "invalid_request", "limit должен быть от 1 до 100") + ); + } + + return (limit, null); + } + + public static IResult ApiError( + HttpContext context, + int status, + string code, + string message) + { + var requestId = + context.Items["RequestId"]?.ToString() + ?? Guid.NewGuid().ToString(); + + return Results.Json( + new + { + error = new + { + code, + message, + request_id = requestId + } + }, + statusCode: status + ); + } +} diff --git a/src/Messenger.Api/Services/AttachmentException.cs b/src/Messenger.Api/Services/AttachmentException.cs new file mode 100644 index 00000000..cb8dc39b --- /dev/null +++ b/src/Messenger.Api/Services/AttachmentException.cs @@ -0,0 +1,6 @@ +namespace Messenger.Api.Services; +public sealed class AttachmentException(int status, string code, string message) : Exception(message) +{ + public int Status { get; } = status; + public string Code { get; } = code; +} diff --git a/src/Messenger.Api/Services/AttachmentReconciler.cs b/src/Messenger.Api/Services/AttachmentReconciler.cs new file mode 100644 index 00000000..0fa53f77 --- /dev/null +++ b/src/Messenger.Api/Services/AttachmentReconciler.cs @@ -0,0 +1,97 @@ +using System.Diagnostics; +using System.Text.Json; +using Amazon.S3.Model; +using Messenger.Api.Data; +using Messenger.Api.Infrastructure; +using Npgsql; +namespace Messenger.Api.Services; +public sealed class AttachmentReconciler(NpgsqlDataSource db, S3Storage storage, IConfiguration config) +{ + public async Task RunAsync(bool apply) + { + var timer=Stopwatch.StartNew(); + var grace=int.TryParse(config["RECONCILE_GRACE_SECONDS"],out var value) ? Math.Max(120,value) : 3600; + var cutoff=DateTime.UtcNow.AddSeconds(-grace); + var actions=new List(); long objects=0,rows=0,requests=0; + using var timeout=new CancellationTokenSource(TimeSpan.FromMinutes(5)); + var ct=timeout.Token; + await using var connection=await db.OpenConnectionAsync(ct); + await using var tx=await connection.BeginTransactionAsync(ct); + await using(var gate=new NpgsqlCommand($"SELECT pg_advisory_xact_lock({AppDatabase.AttachmentGate})",connection,tx)) + { gate.CommandTimeout=120; await gate.ExecuteNonQueryAsync(ct); } + // Excluding uploads and message attachment references makes the final recheck authoritative. + string? continuation=null; + do { + var page=await storage.Client.ListObjectsV2Async(new ListObjectsV2Request { + BucketName=storage.Bucket,Prefix="originals/",MaxKeys=1000,ContinuationToken=continuation },ct);requests++; + foreach(var obj in page.S3Objects ?? []) + { + objects++; + if(obj.LastModified is null || obj.LastModified.Value.ToUniversalTime()>cutoff) continue; + await using var lookup=new NpgsqlCommand("SELECT EXISTS(SELECT 1 FROM attachments WHERE object_key=@key), EXISTS(SELECT 1 FROM messages WHERE attachment_ids @> ARRAY[@id])",connection,tx); + lookup.Parameters.AddWithValue("key",obj.Key); + Guid.TryParse(obj.Key["originals/".Length..],out var referencedId); + lookup.Parameters.AddWithValue("id",referencedId); + bool metadata, used; + await using(var found=await lookup.ExecuteReaderAsync(ct)) + { + await found.ReadAsync(ct);metadata=found.GetBoolean(0);used=found.GetBoolean(1); + } + if(!metadata && used) actions.Add(new {kind="missing_metadata",key=obj.Key,action="preserved_used_original"}); + if(!metadata && !used) + { + actions.Add(new { kind="orphan",key=obj.Key,action=apply?"deleted":"would_delete" }); + if(apply) {await storage.Client.DeleteObjectAsync(storage.Bucket,obj.Key,ct);requests++;} + } + } + continuation=page.IsTruncated==true ? page.NextContinuationToken : null; + } while(continuation is not null); + // Keyset pages bound metadata memory; SQL checks actual message references. + Guid last=Guid.Empty; + while(true) + { + var batch=new List<(Guid Id,string Key,bool Used,DateTime Created)>(); + await using(var query=new NpgsqlCommand(""" + SELECT a.id,a.object_key,EXISTS(SELECT 1 FROM messages m WHERE m.attachment_ids @> ARRAY[a.id]),a.created_at + FROM attachments a WHERE a.id>@last ORDER BY a.id LIMIT 200 + """,connection,tx)) + { + query.Parameters.AddWithValue("last",last); + await using var reader=await query.ExecuteReaderAsync(ct); + while(await reader.ReadAsync(ct)) batch.Add((reader.GetGuid(0),reader.GetString(1),reader.GetBoolean(2),reader.GetDateTime(3))); + } + if(batch.Count==0) break; + foreach(var a in batch) + { + rows++;last=a.Id; + if(a.Created>cutoff) continue; + DateTime? modified=null; bool missing=false; + try { var head=await storage.Client.GetObjectMetadataAsync(storage.Bucket,a.Key,ct);requests++;modified=head.LastModified; } + catch(Amazon.S3.AmazonS3Exception ex) when(ex.StatusCode==System.Net.HttpStatusCode.NotFound) { requests++;missing=true; } + if(!missing && modified?.ToUniversalTime()>cutoff) continue; + if(a.Used) + { + if(missing) + { + actions.Add(new { kind="missing",id=a.Id,action=apply?"marked_missing":"would_mark_missing" }); + if(apply) { + await using var update=new NpgsqlCommand("UPDATE attachments SET status='missing',updated_at=clock_timestamp() WHERE id=@id AND status<>'missing'",connection,tx); + update.Parameters.AddWithValue("id",a.Id); await update.ExecuteNonQueryAsync(ct); + } + } + continue; + } + actions.Add(new {kind="unreferenced",id=a.Id,action=apply?"deleted":"would_delete"}); + if(apply) + { + if(!missing) {await storage.Client.DeleteObjectAsync(storage.Bucket,a.Key,ct);requests++;} + await using var delete=new NpgsqlCommand("DELETE FROM attachments WHERE id=@id",connection,tx); + delete.Parameters.AddWithValue("id",a.Id);await delete.ExecuteNonQueryAsync(ct); + } + } + } + if(apply) await tx.CommitAsync(ct); else await tx.RollbackAsync(ct); + Console.WriteLine(JsonSerializer.Serialize(new {mode=apply?"apply":"dry-run",grace_seconds=grace,objects,rows,s3_requests=requests, + elapsed_ms=timer.Elapsed.TotalMilliseconds,peak_process_bytes=Process.GetCurrentProcess().PeakWorkingSet64,actions})); + } +} diff --git a/src/Messenger.Api/Services/AttachmentService.cs b/src/Messenger.Api/Services/AttachmentService.cs new file mode 100644 index 00000000..38271a3c --- /dev/null +++ b/src/Messenger.Api/Services/AttachmentService.cs @@ -0,0 +1,76 @@ +using System.Security.Cryptography; +using Amazon.S3.Model; +using Messenger.Api.Contracts; +using Messenger.Api.Data; +using Messenger.Api.Infrastructure; +using Npgsql; +using SkiaSharp; +namespace Messenger.Api.Services; +public sealed class AttachmentService(S3Storage storage, NpgsqlDataSource db) +{ + public const long MaxBytes=10*1024*1024; + private readonly SemaphoreSlim slots=new(1,1); + public async Task UploadAsync(HttpRequest request, Guid chat, Guid actor, string name) + { + using var timeout=CancellationTokenSource.CreateLinkedTokenSource(request.HttpContext.RequestAborted); + timeout.CancelAfter(TimeSpan.FromSeconds(90)); + var ct=timeout.Token; + if (request.ContentLength>MaxBytes) throw new AttachmentException(413,"payload_too_large","Файл больше 10 MiB"); + await slots.WaitAsync(ct); + var path=Path.Combine(Path.GetTempPath(),Guid.NewGuid().ToString("N")); + try + { + 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; + using var digest=IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + while(true) + { + var count=await request.Body.ReadAsync(buffer,ct); if(count==0) break; + size+=count; + if(size>MaxBytes) throw new AttachmentException(413,"payload_too_large","Файл больше 10 MiB"); + digest.AppendData(buffer,0,count); await file.WriteAsync(buffer.AsMemory(0,count),ct); + } + if(size==0) throw new AttachmentException(415,"unsupported_media_type","Пустое изображение"); + string mime; + file.Position=0; + using (var stream=new SKManagedStream(file,false)) + using (var codec=SKCodec.Create(stream)) + { + if(codec is null) throw new AttachmentException(415,"unsupported_media_type","Повреждённое изображение"); + var info=codec.Info; + if((long)info.Width*info.Height>40_000_000) + throw new AttachmentException(413,"payload_too_large","Слишком много пикселей"); + mime=codec.EncodedFormat switch {SKEncodedImageFormat.Png=>"image/png",SKEncodedImageFormat.Jpeg=>"image/jpeg",_=>""}; + if(mime=="" || request.ContentType?.Split(';')[0].Trim()!=mime) + throw new AttachmentException(415,"unsupported_media_type","Требуется PNG или JPEG с верным MIME"); + using var bitmap=new SKBitmap(new SKImageInfo(info.Width,info.Height,SKColorType.Rgba8888,SKAlphaType.Premul)); + if(codec.GetPixels(bitmap.Info,bitmap.GetPixels())!=SKCodecResult.Success) + throw new AttachmentException(415,"unsupported_media_type","Повреждённое изображение"); + } + var id=Guid.NewGuid(); var key=$"originals/{id:N}"; var now=UtcClock.Now(); + var sha=Convert.ToHexString(digest.GetHashAndReset()).ToLowerInvariant(); + await using var connection=await db.OpenConnectionAsync(ct); + await using var transaction=await connection.BeginTransactionAsync(ct); + await using(var gate=new NpgsqlCommand($"SELECT pg_advisory_xact_lock_shared({AppDatabase.AttachmentGate})",connection,transaction)) + await gate.ExecuteNonQueryAsync(ct); + file.Position=0; + await storage.Client.PutObjectAsync(new PutObjectRequest {BucketName=storage.Bucket,Key=key, + InputStream=file,ContentType=mime,AutoCloseStream=false,UseChunkEncoding=false},ct); + await using(var insert=new NpgsqlCommand(""" + INSERT INTO attachments(id,chat_id,owner_id,filename,content_type,size_bytes,sha256,object_key,status,created_at,updated_at) + VALUES (@id,@chat,@actor,@name,@mime,@size,@sha,@key,'ready',@now,@now) + """,connection,transaction)) + { + insert.Parameters.AddWithValue("id",id);insert.Parameters.AddWithValue("chat",chat); + insert.Parameters.AddWithValue("actor",actor);insert.Parameters.AddWithValue("name",name); + insert.Parameters.AddWithValue("mime",mime);insert.Parameters.AddWithValue("size",size); + insert.Parameters.AddWithValue("sha",sha);insert.Parameters.AddWithValue("key",key);insert.Parameters.AddWithValue("now",now); + await insert.ExecuteNonQueryAsync(ct); + } + await transaction.CommitAsync(ct); + return new(id,chat,actor,name,mime,size,sha,"ready",[],null,now.ToString("O"),now.ToString("O")); + } + finally { slots.Release(); File.Delete(path); } + } +} diff --git a/src/Messenger.Api/Services/ChatService.cs b/src/Messenger.Api/Services/ChatService.cs new file mode 100644 index 00000000..38979f01 --- /dev/null +++ b/src/Messenger.Api/Services/ChatService.cs @@ -0,0 +1,16 @@ +using Messenger.Api.Contracts; +using Messenger.Api.Data; + +namespace Messenger.Api.Services; + +public sealed class ChatService(AppDatabase database) +{ + public async Task CreateAsync(string title, List memberIds) => + (await database.CreateChatAsync(title, memberIds))?.ToDto(); + + public async Task FindForMemberAsync(Guid chatId, Guid userId) => + (await database.FindChatForMemberAsync(chatId, userId))?.ToDto(); + + public async Task> ListAsync(Guid userId, DateTime? cursorTime, Guid? cursorId, int count) => + (await database.ListChatsAsync(userId, cursorTime, cursorId, count)).Select(chat => chat.ToDto()).ToList(); +} diff --git a/src/Messenger.Api/Services/CursorService.cs b/src/Messenger.Api/Services/CursorService.cs new file mode 100644 index 00000000..f260e9e7 --- /dev/null +++ b/src/Messenger.Api/Services/CursorService.cs @@ -0,0 +1,49 @@ +using System.Text; +using System.Text.Json; +using Messenger.Api.Contracts; + +namespace Messenger.Api.Services; + +public static class CursorService +{ + public static string EncodeChatCursor(ChatCursor cursor) + { + var json = JsonSerializer.Serialize(cursor); + + return Convert.ToBase64String(Encoding.UTF8.GetBytes(json)) + .TrimEnd('=') + .Replace('+', '-') + .Replace('/', '_'); + } + + public static ChatCursor? DecodeChatCursor(string cursor) + { + try + { + var base64 = cursor + .Replace('-', '+') + .Replace('_', '/'); + + switch (base64.Length % 4) + { + case 2: + base64 += "=="; + break; + case 3: + base64 += "="; + break; + case 1: + return null; + } + + var bytes = Convert.FromBase64String(base64); + var json = Encoding.UTF8.GetString(bytes); + + return JsonSerializer.Deserialize(json); + } + catch + { + return null; + } + } +} diff --git a/src/Messenger.Api/Services/MessageService.cs b/src/Messenger.Api/Services/MessageService.cs new file mode 100644 index 00000000..b36b399c --- /dev/null +++ b/src/Messenger.Api/Services/MessageService.cs @@ -0,0 +1,13 @@ +using Messenger.Api.Contracts; +using Messenger.Api.Data; + +namespace Messenger.Api.Services; + +public sealed class MessageService(AppDatabase database) +{ + public async Task CreateAsync(Guid chatId, Guid senderId, string text, string key, Guid[] attachmentIds) => + (await database.CreateMessageOnceAsync(chatId, senderId, text, key, attachmentIds))?.ToDto(); + + public async Task> ListAsync(Guid chatId, DateTime? cursorTime, Guid? cursorId, int count, bool newestFirst = false) => + (await database.ListMessagesAsync(chatId, cursorTime, cursorId, count, newestFirst)).Select(message => message.ToDto()).ToList(); +} diff --git a/src/Messenger.Api/Services/PasswordService.cs b/src/Messenger.Api/Services/PasswordService.cs new file mode 100644 index 00000000..2d1d4157 --- /dev/null +++ b/src/Messenger.Api/Services/PasswordService.cs @@ -0,0 +1,28 @@ +using System.Security.Cryptography; +using System.Text; +using Isopoh.Cryptography.Argon2; + +namespace Messenger.Api.Services; + +public sealed class PasswordService +{ + public string Hash(string password) + { + var salt = RandomNumberGenerator.GetBytes(16); + var config = new Argon2Config + { + Type = Argon2Type.HybridAddressing, + Version = Argon2Version.Nineteen, + TimeCost = 3, + MemoryCost = 32768, + Lanes = 1, + Threads = 1, + Password = Encoding.UTF8.GetBytes(password), + Salt = salt, + HashLength = 32 + }; + return Argon2.Hash(config); + } + + public bool Verify(string hash, string password) => Argon2.Verify(hash, password); +} diff --git a/src/Messenger.Api/Services/SessionService.cs b/src/Messenger.Api/Services/SessionService.cs new file mode 100644 index 00000000..d9a134fb --- /dev/null +++ b/src/Messenger.Api/Services/SessionService.cs @@ -0,0 +1,65 @@ +using System.Security.Cryptography; +using System.Text; +using Messenger.Api.Contracts; +using Messenger.Api.Data; +using Messenger.Api.Infrastructure; + +namespace Messenger.Api.Services; + +public sealed class SessionService(AppDatabase database, PasswordService passwords, RedisSessionCache cache, IConfiguration configuration) +{ + private readonly int _ttlSeconds = int.TryParse(configuration["SESSION_TTL_SECONDS"], out var ttl) && ttl > 0 + ? ttl : 3600; + + public async Task LoginAsync(string username, string password) + { + var user = await database.FindUserByUsernameAsync(username); + if (user is null || !passwords.Verify(user.PasswordHash, password)) + return null; + + var token = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32)) + .TrimEnd('=').Replace('+', '-').Replace('/', '_'); + var expiresAt = UtcClock.Now().AddSeconds(_ttlSeconds); + var hash = HashToken(token); + await database.CreateSessionAsync(hash, user.Id, expiresAt); + await cache.SetAsync(hash, user.ToDto(), expiresAt); + return new SessionDto(token, "Bearer", expiresAt.ToString("O"), user.ToDto()); + } + + public async Task<(UserDto? User, byte[]? TokenHash)> AuthenticateAsync(HttpContext context) + { + if (!context.Request.Headers.TryGetValue("Authorization", out var value)) + return (null, null); + + var authorization = value.ToString(); + if (!authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) + return (null, null); + + var token = authorization[7..]; + if (token.Length != 43 || token.Any(c => !char.IsAsciiLetterOrDigit(c) && c != '-' && c != '_')) + return (null, null); + + var hash = HashToken(token); + var session = await database.FindActiveSessionAsync(hash); + if (session is null) return (null, null); + + var cached = await cache.GetAsync(hash); + if (cached is not null && cached.User.Id == session.UserId && cached.ExpiresAt == session.ExpiresAt) + return (cached.User, hash); + + var user = await database.FindUserByIdAsync(session.UserId); + if (user is null) return (null, null); + var dto = user.ToDto(); + await cache.SetAsync(hash, dto, session.ExpiresAt); + return (dto, hash); + } + + public async Task RevokeAsync(byte[] tokenHash) + { + var revoked = await database.RevokeSessionAsync(tokenHash); + if (revoked) await cache.RemoveAsync(tokenHash); + return revoked; + } + + private static byte[] HashToken(string token) => SHA256.HashData(Encoding.ASCII.GetBytes(token)); +} diff --git a/src/Messenger.Api/Services/UserService.cs b/src/Messenger.Api/Services/UserService.cs new file mode 100644 index 00000000..6dafd366 --- /dev/null +++ b/src/Messenger.Api/Services/UserService.cs @@ -0,0 +1,24 @@ +using Messenger.Api.Contracts; +using Messenger.Api.Data; +using Npgsql; + +namespace Messenger.Api.Services; + +public sealed class UserService(AppDatabase database, PasswordService passwords) +{ + public async Task> ListForChatAsync(Guid chatId) => + (await database.ListChatUsersAsync(chatId)).Select(user => user.ToDto()).ToList(); + + public async Task RegisterAsync(string username, string displayName, string password) + { + var hash = passwords.Hash(password); + try + { + return (await database.CreateUserAsync(username, displayName, hash)).ToDto(); + } + catch (PostgresException exception) when (exception.SqlState == PostgresErrorCodes.UniqueViolation) + { + return null; + } + } +} diff --git a/src/Messenger.Api/appsettings.Development.json b/src/Messenger.Api/appsettings.Development.json new file mode 100644 index 00000000..ff66ba6b --- /dev/null +++ b/src/Messenger.Api/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/src/Messenger.Api/appsettings.json b/src/Messenger.Api/appsettings.json new file mode 100644 index 00000000..4d566948 --- /dev/null +++ b/src/Messenger.Api/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/src/Messenger.Api/wwwroot/app.css b/src/Messenger.Api/wwwroot/app.css new file mode 100644 index 00000000..7bc42308 --- /dev/null +++ b/src/Messenger.Api/wwwroot/app.css @@ -0,0 +1,438 @@ +:root { + color-scheme: dark; + --ink: #FFE135; + --muted: #b6b5aa; + --accent: #FFE135; + --accent-hover: #ffeb79; + --paper: #262626; + --surface: #303030; + --soft: #38382c; + --border: #414139; + --danger: #ffaaa0; + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; + color: var(--ink); + background: #262626; + font-size: 15px; +} +* { box-sizing: border-box; } +body { margin: 0; } +button, input, textarea { font: inherit; } +button, a, input, textarea { -webkit-tap-highlight-color: transparent; } +button { cursor: pointer; } +button:disabled { cursor: default; opacity: .5; } +button, textarea, input { outline: none; } +button:focus-visible, a:focus-visible { outline: 2px solid var(--accent); outline-offset: 4px; } +input:focus, textarea:focus { border-color: var(--accent); box-shadow: 0 0 0 3px #ffe13515; } +a { color: inherit; text-decoration: none; } +[hidden] { display: none !important; } +svg { width: 21px; height: 21px; fill: none; stroke: currentColor; stroke-width: 1.7; stroke-linecap: round; stroke-linejoin: round; flex-shrink: 0; } +.svg-sprite { position: absolute; width: 0; height: 0; overflow: hidden; } +.visually-hidden { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0,0,0,0); white-space: nowrap; border: 0; } +::selection { color: #262626; background: var(--accent); } + +/* Brand and shared controls */ +.brand { display: inline-flex; align-items: center; font-size: 30px; font-weight: 750; letter-spacing: -1.6px; gap: 10px; line-height: 1; } +.brand-dot { color: var(--accent); margin-left: -8px; } +.brand-mark { height: 36px; width: 36px; background: var(--accent); border-radius: 12px; display: flex; flex-direction: column; justify-content: center; gap: 4px; padding: 9px; } +.brand-mark i { display: block; height: 2px; border-radius: 2px; background: #262626; } +.brand-mark i:nth-child(2) { width: 75%; } +.brand-mark i:nth-child(3) { width: 45%; } +.eyebrow { display: block; color: var(--muted); font-size: 10px; font-weight: 650; letter-spacing: 2px; text-transform: uppercase; line-height: 1.6; } +.muted { color: var(--muted); font-size: 14px; line-height: 1.7; } +label { display: grid; gap: 9px; font-size: 12px; font-weight: 550; color: var(--ink); } +input, textarea { width: 100%; color: var(--ink); background: #292929; border: 1px solid #4b4b42; border-radius: 12px; padding: 14px 15px; font-size: 14px; transition: border-color .18s, box-shadow .18s; } +input::placeholder, textarea::placeholder { color: #a6a69a; } +textarea { resize: vertical; line-height: 1.5; } +.field-note { color: var(--muted); font-size: 11px; font-weight: 400; line-height: 1.7; } +.button { display: inline-flex; align-items: center; justify-content: center; gap: 10px; border-radius: 12px; border: 1px solid transparent; padding: 14px 20px; font-weight: 650; font-size: 13px; transition: background .18s, transform .18s; } +.button.primary { background: var(--accent); color: #262626; } +.button.primary:hover { background: var(--accent-hover); transform: translateY(-1px); } +.button.secondary { background: #3a3a32; border-color: var(--border); color: var(--ink); } +.button.secondary:hover { background: #454538; } +.button.wide { width: 100%; } +.icon-button { display: inline-flex; align-items: center; justify-content: center; border: 1px solid transparent; background: transparent; color: var(--muted); width: 36px; height: 36px; border-radius: 11px; flex-shrink: 0; transition: background .18s, color .18s; } +.icon-button:hover { background: #3c3c32; color: var(--accent); } +.icon-button.filled { background: var(--accent); color: #262626; } +.icon-button.filled:hover { background: var(--accent-hover); } +.text-button { background: none; border: 0; color: var(--accent); font-size: 11px; padding: 10px 14px; border-radius: 9px; } +.text-button:hover { background: #ffe1350e; } +.form-notice { color: var(--danger); font-size: 12px; line-height: 1.6; background: #452f2d; border: 1px solid #70453e; border-radius: 10px; padding: 11px 13px; } +.form-notice.success { color: var(--ink); background: var(--soft); border-color: #686032; } + +/* Entry screen */ +.auth-layout { min-height: 100svh; display: grid; grid-template-columns: 1.1fr 1fr; max-width: 1440px; margin: auto; } +.intro { position: relative; min-height: 760px; padding: 50px 64px 40px; overflow: hidden; background: radial-gradient(ellipse at 5% 95%, #ffe13508, transparent 65%), var(--paper); } +.intro::before { content: ""; position: absolute; inset: auto auto -270px -250px; width: 760px; height: 760px; border: 1px solid #ffe13520; border-radius: 50%; pointer-events: none; } +.intro::after { content: ""; position: absolute; right: -190px; top: 90px; width: 440px; height: 440px; border: 1px solid #ffe13512; border-radius: 50%; pointer-events: none; } +.intro-copy { margin-top: 82px; position: relative; z-index: 1; } +.intro-copy .eyebrow { color: var(--accent); padding-left: 22px; position: relative; } +.intro-copy .eyebrow::before { content: ""; width: 7px; height: 7px; background: var(--accent); border-radius: 50%; position: absolute; left: 0; top: 5px; } +.intro h1 { font-size: clamp(48px, 5vw, 72px); line-height: 1.04; font-weight: 700; letter-spacing: -3.5px; margin: 22px 0 26px; } +.intro em, .welcome em { font-family: Georgia, "Times New Roman", serif; font-weight: 400; color: var(--accent); } +.intro-copy p { color: var(--muted); line-height: 1.8; font-size: 15px; } +.conversation-art { position: relative; width: 330px; height: 165px; margin: 38px 0 25px 34px; z-index: 1; } +.art-bubble { position: absolute; padding: 17px 22px 13px; border-radius: 18px; font-size: 14px; box-shadow: 0 12px 30px #00000020; } +.art-bubble span { display: block; font-size: 10px; text-align: right; margin-top: 8px; opacity: .65; } +.art-bubble b { font-weight: 500; } +.art-one { background: #353530; border: 1px solid #4a4a3c; left: 0; top: 0; transform: rotate(-4deg); border-bottom-left-radius: 5px; min-width: 195px; } +.art-two { background: var(--accent); color: #262626; right: 0; top: 67px; transform: rotate(3deg); border-bottom-right-radius: 5px; min-width: 218px; } +.art-typing { position: absolute; bottom: 0; left: 15px; display: flex; gap: 5px; border-radius: 12px; background: #353530; border: 1px solid var(--border); padding: 13px 19px; } +.art-typing i { background: var(--accent); width: 5px; height: 5px; border-radius: 50%; } +.art-orbit { position: absolute; right: -45px; top: 5px; width: 11px; height: 11px; background: var(--accent); border-radius: 50%; box-shadow: 0 0 0 9px #ffe13508; } +.intro-footer { font-size: 11px; color: var(--muted); display: flex; align-items: center; gap: 9px; margin-top: 38px; position: relative; } +.status-dot { height: 6px; width: 6px; background: var(--accent); border-radius: 50%; } +.auth-side { background: #2c2c2a; border-left: 1px solid var(--border); display: flex; flex-direction: column; justify-content: center; align-items: center; padding: 50px 64px 25px; min-height: 760px; } +.auth-card { width: 100%; max-width: 360px; } +.auth-switch { display: flex; padding: 5px; background: #222222; border: 1px solid #404037; border-radius: 14px; margin-bottom: 42px; } +.auth-switch button { width: 50%; background: transparent; border: 0; border-radius: 9px; color: var(--muted); padding: 11px; font-size: 12px; font-weight: 600; } +.auth-switch .active { background: var(--accent); color: #262626; box-shadow: 0 3px 12px #00000018; } +.auth-card h2 { font-weight: 650; font-size: 40px; letter-spacing: -1.7px; line-height: 1.15; margin: 12px 0; } +.auth-card .muted { margin: 13px 0 30px; } +.auth-card form { display: grid; gap: 20px; } +.auth-card .wide { margin-top: 5px; justify-content: space-between; } +.auth-card .wide > span { font-size: 21px; line-height: 1; } +.auth-footnote { font-size: 11px; color: var(--muted); margin: 24px 0; text-align: center; } +.auth-bottom { color: var(--muted); font-size: 10px; letter-spacing: .6px; margin-top: 40px; } + +/* Conversations */ +.app-shell { display: grid; grid-template-columns: 310px minmax(0,1fr); height: calc(100svh - 44px); max-width: 1440px; margin: 22px auto; border: 1px solid #46463c; border-radius: 24px; overflow: hidden; box-shadow: 0 20px 70px #00000025; background: var(--paper); } +.sidebar { min-height: 0; background: #222222; border-right: 1px solid var(--border); display: flex; flex-direction: column; padding: 29px 19px 0; } +.sidebar-top { display: flex; align-items: center; justify-content: space-between; padding: 0 9px; } +.sidebar .brand { font-size: 28px; } +.sidebar .brand-mark { width: 32px; height: 32px; border-radius: 10px; } +.sidebar-heading { display: flex; justify-content: space-between; align-items: center; padding: 35px 9px 22px; } +.sidebar-heading .eyebrow { font-size: 9px; letter-spacing: 1.7px; } +.sidebar-heading h2 { margin: 6px 0 0; font-size: 22px; font-weight: 650; letter-spacing: -.7px; } +.count { font-size: 11px; font-weight: 600; background: #ffe13516; border: 1px solid #ffe13525; border-radius: 7px; margin-left: 9px; padding: 3px 7px; vertical-align: middle; color: var(--accent); } +.count:empty { display: none; } +.search-field { display: flex; align-items: center; background: #2d2d2b; border: 1px solid #414139; border-radius: 12px; margin: 0 9px 22px; padding: 0 11px; gap: 8px; } +.search-field > span:not(.visually-hidden) { font-size: 25px; line-height: 1; color: var(--muted); } +.search-field input { border: 0; background: transparent; padding: 12px 0; font-size: 12px; box-shadow: none; } +.search-field:focus-within { border-color: var(--accent); } +.chat-list { flex: 1; overflow: auto; min-height: 0; scrollbar-width: thin; scrollbar-color: #646451 transparent; } +.chat-row { display: flex; align-items: center; gap: 13px; position: relative; border: 1px solid transparent; background: transparent; text-align: left; padding: 15px 11px; width: 100%; border-radius: 14px; color: var(--ink); margin-bottom: 6px; transition: background .18s, border-color .18s; } +.chat-row:hover { background: #2e2e29; } +.chat-row.active { background: #ffe1350f; border-color: #ffe13540; } +.chat-row.active::after { content: ""; position: absolute; right: 11px; height: 6px; width: 6px; border-radius: 50%; background: var(--accent); box-shadow: 0 0 0 4px #ffe1350b; } +.avatar { display: flex; align-items: center; justify-content: center; width: 43px; height: 43px; border-radius: 14px; background: #45432a; color: var(--accent); font-size: 14px; font-weight: 650; flex-shrink: 0; letter-spacing: -.5px; border: 1px solid #ffe1351a; } +.avatar.tone-1 { background: #4b3e2a; color: #ffd68a; border-color: #ffd68a20; } +.avatar.tone-2 { background: #3b4032; color: #d9df9d; border-color: #d9df9d20; } +.avatar.tone-3 { background: #493b36; color: #edc5a5; border-color: #edc5a520; } +.chat-row.active .avatar { background: var(--accent); color: #262626; border-color: transparent; } +.chat-row-text { display: grid; gap: 6px; min-width: 0; flex: 1; } +.chat-row strong { font-size: 13px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; padding-right: 10px; } +.chat-row small { font-size: 11px; color: var(--muted); } +.list-empty { font-size: 12px; text-align: center; line-height: 1.7; color: var(--muted); padding: 20px 15px; } +.profile { border-top: 1px solid var(--border); display: flex; align-items: center; gap: 6px; margin-top: 12px; padding: 20px 7px; } +.profile-main { display: flex; align-items: center; gap: 11px; text-align: left; background: none; border: 0; padding: 0; min-width: 0; flex: 1; color: var(--ink); } +.profile .avatar { border-radius: 50%; background: #39392c; color: var(--accent); width: 37px; height: 37px; font-size: 12px; } +.profile-text { display: grid; gap: 5px; min-width: 0; } +.profile-text strong { font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: 600; } +.profile-text > span { font-size: 10px; color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.workspace { min-width: 0; min-height: 0; position: relative; background: var(--paper); } +.welcome { height: 100%; display: flex; align-items: center; justify-content: center; flex-direction: column; text-align: center; position: relative; padding: 35px; background: radial-gradient(ellipse at center, #ffe13505, transparent 70%); } +.welcome-symbol { width: 110px; height: 110px; background: #ffe1350b; border: 1px solid #ffe13529; border-radius: 34px; position: relative; display: flex; align-items: center; justify-content: center; margin-bottom: 34px; transform: rotate(-6deg); } +.welcome-symbol svg { width: 44px; height: 44px; color: var(--accent); stroke-width: 1.4; transform: rotate(6deg); } +.tiny-dot { position: absolute; width: 17px; height: 17px; right: -4px; top: 4px; border-radius: 50%; background: var(--accent); border: 4px solid var(--paper); } +.welcome .eyebrow { font-size: 9px; letter-spacing: 1.5px; } +.welcome h1 { font-weight: 650; font-size: 43px; letter-spacing: -1.7px; line-height: 1.2; margin: 18px 0; } +.welcome p { font-size: 13px; line-height: 1.8; color: var(--muted); margin: 0 0 27px; } +.welcome .button svg { width: 17px; height: 17px; } +.welcome-bottom { position: absolute; bottom: 30px; font-size: 10px; color: var(--muted); letter-spacing: .4px; } +.conversation { height: 100%; display: flex; flex-direction: column; } +.chat-header { display: flex; align-items: center; gap: 14px; padding: 21px 30px; border-bottom: 1px solid var(--border); min-height: 90px; background: #292929; } +.chat-header .chat-avatar { height: 43px; width: 43px; } +.chat-heading { flex: 1; min-width: 0; } +.chat-heading h2 { font-size: 17px; font-weight: 650; margin: 0 0 6px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; letter-spacing: -.3px; } +.chat-heading span { font-size: 11px; color: var(--muted); } +.message-region { position: relative; flex: 1; min-height: 0; display: flex; } +.message-scroll { flex: 1; min-height: 0; overflow: auto; padding: 12px 32px 24px; scrollbar-width: thin; scrollbar-color: #646451 transparent; scroll-behavior: auto; background: radial-gradient(ellipse at 100% 100%, #ffe13504, transparent 70%); } +.history-control { text-align: center; min-height: 18px; } +.message-list { display: flex; flex-direction: column; gap: 14px; } +.date-separator { align-self: center; background: #30302c; border: 1px solid #414139; border-radius: 20px; padding: 6px 12px; text-align: center; color: var(--muted); font-size: 10px; letter-spacing: .3px; margin: 20px 0 12px; } +.message { max-width: 76%; align-self: flex-start; display: grid; gap: 6px; } +.message.mine { align-self: flex-end; } +.message-author { font-size: 10px; color: var(--muted); padding-left: 8px; } +.message-bubble { background: #343430; border: 1px solid #46463b; border-radius: 17px 17px 17px 5px; padding: 13px 16px 10px; min-width: 90px; box-shadow: 0 4px 14px #00000008; } +.mine .message-bubble { background: var(--accent); color: #262626; border: 1px solid var(--accent); border-radius: 17px 17px 5px 17px; } +.message-text { font-size: 14px; white-space: pre-wrap; overflow-wrap: anywhere; line-height: 1.65; margin: 0; } +.message-time { font-size: 10px; display: block; text-align: right; color: var(--muted); margin-top: 7px; } +.mine .message-time { color: #5c5324; } +.empty-conversation { text-align: center; position: relative; top: 28%; font-size: 13px; color: var(--muted); line-height: 1.9; } +.composer { display: grid; grid-template-columns: minmax(0,1fr) 46px; gap: 10px; align-items: end; border-top: 1px solid var(--border); padding: 20px 29px 16px; background: #292929; } +.composer textarea { border: 1px solid #4b4b42; background: #30302d; border-radius: 13px; padding: 13px 15px; font-size: 14px; resize: none; max-height: 140px; min-height: 47px; scrollbar-width: thin; } +.send-button { display: flex; align-items: center; justify-content: center; background: var(--accent); border: 0; color: #262626; width: 46px; height: 47px; border-radius: 13px; margin-bottom: 1px; transition: background .18s; } +.send-button:hover { background: var(--accent-hover); } +.send-button:disabled { background: #444439; opacity: 1; color: #abab95; } +.send-button svg { height: 21px; width: 21px; } +.composer-note { grid-column: 1/-1; display: flex; justify-content: space-between; font-size: 9px; color: var(--muted); padding: 2px 3px; gap: 15px; } +.composer-note .over-limit { color: var(--danger); } +.mobile-only { display: none; } +.toast { position: fixed; bottom: 27px; left: 50%; transform: translateX(-50%); background: var(--accent); color: #262626; border: 1px solid #ffec7d; box-shadow: 0 8px 35px #00000030; border-radius: 13px; padding: 13px 20px; font-size: 12px; line-height: 1.5; max-width: min(90%,520px); z-index: 20; } +.toast.error { background: #452f2d; color: var(--danger); border-color: #70453e; } + +/* Dialogs */ +dialog { border: 1px solid #575744; border-radius: 22px; padding: 28px; max-width: 440px; width: calc(100% - 36px); color: var(--ink); background: #2c2c2a; box-shadow: 0 24px 100px #00000060; } +dialog::backdrop { background: #151515aa; backdrop-filter: blur(6px); } +.dialog-heading { display: flex; align-items: center; justify-content: space-between; gap: 15px; } +.dialog-heading h2 { font-size: 25px; font-weight: 650; letter-spacing: -.8px; margin: 0; } +.dialog-heading .icon-button { width: 30px; height: 30px; } +dialog .muted { font-size: 12px; margin: 14px 0 25px; } +dialog form { display: grid; gap: 20px; } +.dialog-actions { display: flex; justify-content: flex-end; gap: 10px; margin-top: 3px; } +#my-id { font-size: 12px; font-family: ui-monospace, monospace; background: #242424; } +#profile-dialog .wide { margin-top: 17px; } +.members-list { display: grid; gap: 16px; padding-top: 25px; } +.member-item { display: grid; gap: 8px; } +.member-item strong { font-size: 13px; font-weight: 550; } +.member-item code { font-size: 11px; overflow-wrap: anywhere; color: var(--muted); background: #242424; border: 1px solid var(--border); padding: 12px; border-radius: 10px; } + +/* Optional API explanation panel */ +.diagnostics-toggle { display: flex; align-items: center; justify-content: center; gap: 8px; background: transparent; border: 1px solid #515143; border-radius: 11px; padding: 11px 12px; color: var(--muted); font-size: 11px; font-weight: 550; } +.diagnostics-toggle svg { width: 15px; height: 15px; } +.diagnostics-toggle:hover, .diagnostics-toggle[aria-expanded=true] { background: #ffe1350d; border-color: #ffe13565; color: var(--accent); } +.auth-bottom .diagnostics-toggle { margin: 15px auto 0; } +.sidebar-diagnostics { margin: 10px 9px 0; flex-shrink: 0; } +.diagnostics-panel { position: fixed; z-index: 15; right: 30px; top: 108px; width: 330px; max-height: min(56svh,490px); overflow: auto; background: #2c2c2a; border: 1px solid #66603a; border-radius: 20px; box-shadow: 0 18px 55px #00000030; padding: 20px; scrollbar-width: thin; scrollbar-color: #646451 transparent; } +.diagnostics-heading { display: flex; justify-content: space-between; align-items: center; gap: 10px; margin-bottom: 18px; } +.diagnostics-heading .eyebrow { font-size: 9px; letter-spacing: 1.4px; } +.diagnostics-heading h2 { font-size: 19px; font-weight: 650; letter-spacing: -.5px; margin: 5px 0 0; } +.diagnostics-heading .icon-button { width: 30px; height: 30px; } +.diagnostics-label { display: block; font-size: 10px; color: var(--muted); margin-bottom: 6px; } +.diagnostics-summary { display: grid; grid-template-columns: minmax(0,1fr) auto; gap: 14px; background: #ffe1350c; border: 1px solid #ffe13520; border-radius: 12px; padding: 12px; } +.diagnostics-summary strong { display: block; font-size: 11px; overflow-wrap: anywhere; } +.diagnostics-history { padding: 16px 0; border-bottom: 1px solid var(--border); } +.diagnostics-history > strong { display: block; font-size: 13px; overflow-wrap: anywhere; } +.diagnostics-history > p { font-size: 11px; color: var(--muted); margin: 8px 0 0; } +.diagnostics-request { padding-top: 16px; } +.diagnostics-section-heading { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 12px; } +.diagnostics-section-heading h3 { font-size: 12px; margin: 0; font-weight: 600; } +.diagnostics-section-heading time { font-size: 10px; color: var(--muted); } +.diagnostics-request-line { display: flex; align-items: center; gap: 8px; } +.diagnostics-method, .diagnostics-status { font: 600 11px ui-monospace, monospace; padding: 6px 8px; border-radius: 6px; background: #404036; color: var(--accent); } +.diagnostics-status { background: var(--accent); color: #262626; } +.diagnostics-status.failed { background: #56332e; color: var(--danger); } +.diagnostics-path { display: block; font: 11px/1.6 ui-monospace, monospace; overflow-wrap: anywhere; color: var(--muted); margin-top: 10px; } +.diagnostics-result { font-size: 12px; line-height: 1.6; color: var(--accent); margin: 10px 0 14px; } +.diagnostics-result.failed { color: var(--danger); } +.diagnostics-metrics { display: grid; grid-template-columns: 1fr 1fr; margin: 0 0 14px; gap: 12px; } +.diagnostics-metrics dt { font-size: 10px; color: var(--muted); margin-bottom: 6px; } +.diagnostics-metrics dd { font: 550 12px ui-monospace, monospace; margin: 0; color: var(--ink); } +.diagnostics-request-id { display: block; font: 10px/1.7 ui-monospace, monospace; overflow-wrap: anywhere; color: var(--muted); } +.diagnostics-previous { list-style: none; margin: 15px 0 0; padding: 12px 0 0; border-top: 1px solid var(--border); display: grid; gap: 10px; } +.diagnostics-previous li { display: flex; gap: 8px; align-items: center; min-width: 0; } +.diagnostics-mini-status { font: 550 10px ui-monospace, monospace; color: var(--accent); min-width: 23px; } +.diagnostics-mini-status.failed { color: var(--danger); } +.diagnostics-previous code { font: 10px ui-monospace, monospace; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.diagnostics-background { font-size: 10px; color: var(--muted); margin: 12px 0 0; line-height: 1.7; } +.diagnostics-note { font-size: 11px; color: var(--muted); line-height: 1.7; margin: 0; } +.diagnostics-footnote { border-top: 1px solid var(--border); padding-top: 12px; margin-top: 14px; font-size: 10px; } + +@media (min-width: 1490px) { + .app-shell { height: calc(100svh - 64px); margin: 32px auto; } +} +@media (max-width: 1100px) { + .intro { padding: 40px 38px; } + .auth-side { padding: 40px 35px; } + .app-shell { margin: 14px; height: calc(100svh - 28px); grid-template-columns: 280px minmax(0,1fr); } + .conversation-art { margin-left: 0; width: 290px; } + .intro h1 { font-size: 56px; } + .sidebar { padding-left: 14px; padding-right: 14px; } + .message-scroll { padding-left: 24px; padding-right: 24px; } +} +@media (max-width: 720px) { + .auth-layout { display: block; } + .intro { min-height: 0; padding: 28px; } + .intro-copy { margin-top: 30px; } + .intro h1 { font-size: 42px; letter-spacing: -2px; line-height: 1.08; margin: 14px 0 0; } + .intro h1 br { display: none; } + .intro-copy .eyebrow { font-size: 9px; } + .intro-copy p, .conversation-art, .intro-footer { display: none; } + .auth-side { min-height: 0; padding: 30px 28px; align-items: center; border-left: 0; border-top: 1px solid var(--border); } + .auth-card { max-width: 440px; } + .auth-switch { margin-bottom: 28px; } + .auth-card h2 { font-size: 32px; } + .auth-card h2 br { display: none; } + .auth-card .muted { margin-bottom: 22px; } + .auth-card form { gap: 17px; } + .auth-bottom { margin-top: 20px; } + .app-shell { margin: 0; border: 0; border-radius: 0; height: 100svh; display: block; } + .sidebar { height: 100%; width: 100%; padding: 25px 18px 0; border: 0; } + .sidebar-heading { padding-top: 30px; } + .workspace { display: none; height: 100%; } + .app-shell.chat-open .sidebar { display: none; } + .app-shell.chat-open .workspace { display: block; } + .welcome { display: none; } + .mobile-only { display: flex; } + .chat-header { padding: 15px; gap: 7px; min-height: 75px; } + .chat-header .avatar { width: 35px; height: 35px; border-radius: 11px; } + .chat-heading h2 { font-size: 14px; } + .chat-header .icon-button { width: 31px; height: 31px; } + .chat-header .icon-button svg { width: 19px; height: 19px; } + .message-scroll { padding: 10px 16px 20px; } + .message { max-width: 88%; } + .composer { padding: 14px 16px max(13px, env(safe-area-inset-bottom)); } + .composer-note { font-size: 9px; } + .composer-note > span:first-child { max-width: 70%; } + .profile { padding-bottom: max(18px, env(safe-area-inset-bottom)); } + .toast { bottom: 20px; } + .diagnostics-panel { top: 83px; right: 12px; width: calc(100% - 24px); max-height: 52svh; padding: 16px; } + .sidebar-diagnostics { margin-top: 9px; } +} +@media (min-width: 721px) { + body:not(.has-session) .diagnostics-panel { right: 24px; left: auto; } +} +@media (min-width: 1100px) { + .diagnostics-open.has-session .app-shell { margin-left: 22px; margin-right: 380px; } + .diagnostics-open.has-session .diagnostics-panel { top: 22px; max-height: calc(100svh - 44px); } +} +@media (prefers-reduced-motion: reduce) { + * { transition: none !important; scroll-behavior: auto !important; } +} + +/* Password controls and the animated SVG character. */ +.password-field { position: relative; display: block; } +.password-field input { padding-right: 47px; } +.password-toggle { position: absolute; right: 7px; top: 7px; width: 33px; height: 33px; border: 0; background: transparent; border-radius: 9px; color: var(--muted); display: flex; align-items: center; justify-content: center; } +.password-toggle:hover, .password-toggle[aria-pressed=true] { color: var(--accent); background: #ffe1350c; } +.password-toggle svg { width: 18px; height: 18px; } +/* One SVG mascot; CSS handles poses and the browser handles animation frames. */ +.mascot-stage { position: relative; width: 350px; max-width: 100%; height: 280px; margin: 20px 0 0 5px; pointer-events: none; isolation: isolate; --scene-surface: #262626; --gaze-x: 0px; --gaze-y: 0px; } +.spirit-svg { stroke: none; position: absolute; left: 0; bottom: 0; width: 285px; height: 285px; overflow: visible; z-index: 2; } +.spirit-motion { animation: spirit-breathe 4.5s ease-in-out infinite; } +.spirit-lean { transform-origin: 150px 268px; transition: transform .65s cubic-bezier(.22,1,.36,1); } +.spirit-eye { transform-box: fill-box; transform-origin: center; animation: spirit-blink 7s infinite; } +.spirit-eye-right { animation-delay: .1s; } +.spirit-pupil { transform: translate(var(--gaze-x), var(--gaze-y)); transition: transform .16s ease-out; } +.spirit-hand { transform-box: view-box; transition: transform .55s cubic-bezier(.22,1,.36,1); } +.spirit-gasp { opacity: 0; } +.mascot-stage[data-mood=looking] .spirit-lean { transform: translate(8px,-3px) rotate(3deg); } +.mascot-stage.is-curious .spirit-motion { animation: spirit-step .42s ease-in-out 3; } +.mascot-stage:is([data-mood=private],[data-mood=short],[data-mood=revealed]) .spirit-lean { transform: rotate(-4deg); } +.mascot-stage:is([data-mood=private],[data-mood=short],[data-mood=revealed]) .spirit-hand-left { transform: translate(28px,-37px) rotate(3deg); } +.mascot-stage:is([data-mood=private],[data-mood=short]) .spirit-hand-right { transform: translate(-28px,-25px) rotate(-3deg); } +.mascot-stage:is([data-mood=private],[data-mood=short]) .spirit-eye { animation: none; scale: 1 .08; } +.mascot-stage[data-mood=revealed] .spirit-hand-right { transform: translate(-28px,-39px) rotate(-3deg); } +.mascot-stage[data-mood=revealed] .spirit-eye { animation: none; scale: 1 .08; } +.mascot-stage[data-mood=pending] .spirit-motion { animation: spirit-breathe 1.1s ease-in-out infinite; } +.mascot-stage[data-mood=error] .spirit-motion { animation: spirit-shake .4s ease-in-out 2; } +.mascot-stage[data-mood=success] .spirit-motion { animation: spirit-hop .65s ease-in-out; } +.mascot-stage.is-sleepy .spirit-eye { animation: none; scale: 1 .2; } +.mascot-stage.is-sleepy .spirit-lean { transform: rotate(-5deg); } +.mascot-stage.is-scared .spirit-motion { animation: spirit-shake .25s ease-in-out infinite; } +.mascot-stage.is-scared :is(.spirit-smile,.kolo-tooth) { opacity: 0; } +.mascot-stage.is-scared .spirit-gasp { opacity: 1; } +.mascot-stage:not(.is-visible) * { animation-play-state: paused; } +.mascot-conversation { position: absolute; inset: 0; z-index: 0; } +.mascot-bubble { position: absolute; border-radius: 17px; animation: spirit-float 5s ease-in-out infinite; } +.mascot-bubble-filled { left: 247px; top: 20px; width: 88px; height: 50px; background: var(--accent); display: flex; align-items: center; justify-content: center; gap: 6px; rotate: -6deg; } +.mascot-bubble-filled::after { content: ""; position: absolute; bottom: -7px; left: 18px; width: 17px; height: 17px; background: var(--accent); clip-path: polygon(0 0,100% 0,0 100%); } +.mascot-bubble-filled span { width: 5px; height: 5px; border-radius: 50%; background: #262626; animation: spirit-typing 1.8s ease-in-out infinite; } +.mascot-bubble-filled span:nth-child(2) { animation-delay: .16s; } +.mascot-bubble-filled span:nth-child(3) { animation-delay: .32s; } +.mascot-bubble-outline { left: 265px; top: 107px; width: 77px; height: 55px; border: 1.5px solid #ffe13555; background: var(--scene-surface); rotate: 7deg; animation-delay: -2.5s; padding: 18px 15px; } +.mascot-bubble-outline::after { content: ""; position: absolute; bottom: -6px; right: 16px; width: 11px; height: 11px; border-right: 1.5px solid #ffe13555; border-bottom: 1.5px solid #ffe13555; background: var(--scene-surface); rotate: 45deg; } +.mascot-bubble-outline i { display: block; height: 2px; width: 100%; margin-bottom: 8px; border-radius: 2px; background: #ffe13555; } +.mascot-bubble-outline i:last-child { width: 65%; } +@keyframes spirit-breathe { 0%,100% { transform: translateY(0); } 50% { transform: translateY(-3px); } } +@keyframes spirit-step { 0%,100% { transform: translateY(0); } 50% { transform: translateY(-6px); } } +@keyframes spirit-blink { 0%,42%,46%,100% { scale: 1 1; } 44% { scale: 1 .08; } } +@keyframes spirit-peek { 0%,20%,76%,100% { scale: 1 .12; } 30%,66% { scale: 1 1; } } +@keyframes spirit-shake { 0%,100% { transform: translateX(0); } 25% { transform: translateX(-3px); } 75% { transform: translateX(3px); } } +@keyframes spirit-hop { 0%,100% { transform: translateY(0); } 25% { transform: translateY(3px); } 60% { transform: translateY(-15px); } } +@keyframes spirit-float { 0%,100% { translate: 0 0; } 50% { translate: 0 -5px; } } +@keyframes spirit-typing { 0%,55%,100% { translate: 0 0; opacity: .4; } 28% { translate: 0 -3px; opacity: 1; } } + +.scenario-section { padding: 17px 0 15px; border-bottom: 1px solid var(--border); } +.scenario-section h3 { font-size: 13px; margin: 0 0 9px; } +.scenario-description { font-size: 10px; line-height: 1.7; color: var(--muted); margin: 0 0 12px; } +.scenario-actions { display: grid; gap: 8px; } +.scenario-actions .button { padding: 11px 10px; font-size: 11px; } +.scenario-status { font-size: 11px; line-height: 1.6; margin: 12px 0 0; color: var(--ink); } +.scenario-status.failed { color: var(--danger); } +.scenario-scope { margin: 12px 0 0; } +.scenario-steps { list-style: none; padding: 0; margin: 12px 0 0; display: grid; gap: 8px; max-height: 245px; overflow: auto; scrollbar-width: thin; scrollbar-color: #646451 transparent; } +.scenario-step { border: 1px solid var(--border); border-radius: 10px; background: #262626; padding: 10px; } +.scenario-step[data-state=failed] { border-color: #9a5b51; } +.scenario-step summary { display: flex; align-items: flex-start; gap: 8px; cursor: pointer; font-size: 11px; line-height: 1.5; list-style: none; } +.scenario-step summary::before { content: "▸"; color: var(--muted); } +.scenario-step[open] summary::before { content: "▾"; } +.scenario-step summary::-webkit-details-marker { display: none; } +.scenario-step-badge { flex-shrink: 0; color: var(--accent); font: 650 10px/1.65 ui-monospace, monospace; } +.scenario-step[data-state=failed] .scenario-step-badge { color: var(--danger); } +.scenario-step[data-state=pending] .scenario-step-badge { color: var(--muted); } +.scenario-step p { color: var(--muted); font-size: 10px; line-height: 1.7; margin: 9px 0 0; } +.scenario-step code { display: block; color: var(--muted); font: 10px/1.7 ui-monospace, monospace; overflow-wrap: anywhere; margin-top: 7px; } +@media (max-width: 720px) { + .auth-card .mascot-stage { width: 100%; height: 166px; margin: -14px auto 14px; --scene-surface: #2c2c2a; } + .spirit-svg { width: 178px; height: 178px; left: calc(50% - 105px); } + .mascot-bubble { border-radius: 13px; } + .mascot-bubble-filled { left: calc(50% + 45px); top: 9px; width: 58px; height: 34px; gap: 4px; } + .mascot-bubble-filled span { width: 4px; height: 4px; } + .mascot-bubble-filled::after { width: 12px; height: 12px; bottom: -5px; left: 13px; } + .mascot-bubble-outline { left: calc(50% + 52px); top: 66px; width: 54px; height: 40px; padding: 13px 10px; } + .mascot-bubble-outline i { margin-bottom: 6px; } + .mascot-bubble-outline::after { width: 8px; height: 8px; bottom: -5px; right: 12px; } + .intro h1 { font-size: 36px; } + .intro { padding-bottom: 18px; } + .scenario-steps { max-height: 175px; } +} +.diagnostics-origin { margin-top: 10px; } + +.auth-card form { margin-top: 24px; } +.auth-card .muted + form { margin-top: 0; } +.diagnostics-help { border-top: 1px solid var(--border); margin-top: 14px; padding-top: 12px; } +.diagnostics-help summary { color: var(--muted); font-size: 10px; cursor: pointer; } +.diagnostics-help .diagnostics-note { margin-top: 10px; font-size: 10px; } +@media (prefers-reduced-motion: reduce) { + .mascot-stage *, .mascot-stage *::before { animation: none !important; transition: none !important; } +} + +/* Keep the reader's position while messages arrive below. */ +.jump-latest { position: absolute; right: 24px; bottom: 16px; border: 1px solid #ffe13555; background: #36362d; color: var(--accent); padding: 10px 15px; border-radius: 20px; font-size: 12px; box-shadow: 0 5px 20px #0004; z-index: 2; } +.jump-latest:hover { background: #424234; } +.message.grouped { margin-top: -9px; } +.message.grouped .message-bubble { border-top-left-radius: 8px; } +.message.mine.grouped .message-bubble { border-top-left-radius: 17px; border-top-right-radius: 8px; } +@media (max-width: 720px) { .jump-latest { right: 14px; bottom: 12px; } } + +.welcome-illustration { width: 260px; max-width: 75%; height: auto; margin-bottom: 12px; } +.welcome h1 { font-size: 38px; margin: 14px 0; } +.empty-conversation { top: auto; padding: 35px 16px; color: #d6d6c9; } +.empty-conversation img { width: 165px; max-width: 70%; height: auto; } +.empty-conversation p { color: var(--ink); font-size: 16px; margin: 15px 0 8px; } +.empty-conversation span { color: var(--muted); font-size: 12px; } +.message-bubble { color: #e5e5dc; } +.mine .message-bubble { color: #262626; } +.composer-note { font-size: 10px; line-height: 1.5; } +@media (max-width: 720px) { .welcome-illustration { width: 200px; } .welcome h1 { font-size: 32px; } } +.message-scroll { background-image: url('/assets/chat-pattern.svg'); background-size: 180px 160px; } + +/* Head, ears and mushrooms remain independent of the body. */ +.kolo-head { transform-origin: 151px 202px; transition: transform .65s cubic-bezier(.22,1,.36,1); } +.kolo-ear { transform-origin: 150px 135px; transition: transform .7s ease; } +.kolo-mushrooms { transform-origin: 153px 83px; animation: kolo-sway 6s ease-in-out infinite; } +.mascot-stage[data-mood=looking] .kolo-head { transform: rotate(4deg) translate(3px,-2px); } +.mascot-stage[data-mood=looking] .kolo-ear-right { transform: rotate(-3deg); } +.mascot-stage:is([data-mood=private],[data-mood=short],[data-mood=revealed]) .kolo-head { transform: translate(-5px,2px) rotate(-9deg); } +.mascot-stage:is([data-mood=private],[data-mood=short],[data-mood=revealed]) .spirit-face { opacity: .65; } +.mascot-stage[data-mood=success] .kolo-ear { transform: rotate(-3deg); } +.mascot-stage.is-sleepy .kolo-head { transform: rotate(-6deg) translateY(3px); } +.auth-error-art { float: right; width: 66px; height: 66px; object-fit: contain; margin: 10px 0 0 10px; } +.state-error { text-align: center; padding: 28px 18px; color: var(--muted); } +.state-error img { width: 160px; max-width: 65%; height: auto; } +.state-error h2, .state-error h3 { color: var(--ink); font-size: 19px; font-weight: 600; margin: 14px 0 10px; } +.state-error p { font-size: 12px; line-height: 1.7; margin: 0 0 18px; } +.state-error .button { font-size: 12px; padding: 11px 18px; } +.welcome.state-error { height: 100%; } +@keyframes kolo-sway { 0%,100% { transform: rotate(-1deg); } 50% { transform: rotate(2deg); } } +@media (max-width: 720px) { + .state-error img { width: 130px; } + .welcome-illustration { width: 200px; max-height: 24svh; object-fit: contain; } +} +@media (prefers-reduced-motion: reduce) { + .kolo-mushrooms { animation: none; } +} + +.message-scroll:has(> :is(.empty-conversation,.state-error):not([hidden])) { display: flex; flex-direction: column; } +.message-scroll > :is(.empty-conversation,.state-error) { margin: auto 0; } diff --git a/src/Messenger.Api/wwwroot/app.js b/src/Messenger.Api/wwwroot/app.js new file mode 100644 index 00000000..2d495012 --- /dev/null +++ b/src/Messenger.Api/wwwroot/app.js @@ -0,0 +1,703 @@ +import { attachmentSession } from '/attachments.js'; +import { recordRequest, updateSessionInfo, updateHistoryInfo } from "/diagnostics.js"; + +import { setMascotMood, celebrateMascots } from "/mascots.js"; +import { MessageView } from "/message-view.js"; +import { paintAvatar } from "/avatars.js"; +import { startClusterView } from '/cluster-view.js'; + +const $ = id => document.getElementById(id); +const storageKey = "n1k0der.session"; +const messageView = new MessageView($("message-list")); +const state = { session: null, chats: [], chatsStatus: "loading", chatsCursor: null, current: null, messages: new Map(), + serverIds: new Set(), members: new Map(), olderCursor: null, historyReady: false, epoch: 0, syncing: false, sending: false, drafts: new Map() }; +let toastTimer, unseenMessages = 0; +const pendingMessages = new Map(); +const attachedDrafts = new Map(); +let uploadBusy = false; +const chatRows = new Map(); +let chatsLoading = false, lastChatRefresh = 0; +const reactions = new Map(), reactionBusy = new Set(); +let reactionVersion = 0; + +class ApiError extends Error { + constructor(message, status = 0) { super(message); this.status = status; } +} + +function notice(id, message, success = false) { + const element = $(id); + element.textContent = message; + element.hidden = !message; + element.classList.toggle("success", success); +} + +function toast(message, error = false) { + clearTimeout(toastTimer); + $("toast").textContent = message; + $("toast").classList.toggle("error", error); + $("toast").hidden = false; + toastTimer = setTimeout(() => { $("toast").hidden = true; }, error ? 6500 : 3000); +} + +async function request(path, { method = "GET", body, headers = {}, auth = true, background = false, raw } = {}) { + const started = performance.now(); + let httpStatus = null, requestId = null, instanceId = null, outcome = "network"; + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), raw ? 90000 : 12000); + // Authorization is explicit; disable the browser's implicit Basic-auth handling. + const options = { method, headers: { Accept: "application/json", ...headers }, signal: controller.signal, cache: "no-store", credentials: "omit" }; + if (auth && state.session) options.headers.Authorization = "Bearer " + state.session.token; + if (body !== undefined) { + options.body = JSON.stringify(body); + options.headers["Content-Type"] = "application/json"; + } + if (raw !== undefined) options.body = raw; + try { + const response = await fetch(path, options); + httpStatus = response.status; + requestId = response.headers.get("X-Request-Id"); + instanceId = response.headers.get("X-Instance-Id"); + outcome = "unreadable"; + const data = response.status === 204 ? null : await response.json(); + outcome = response.ok ? "success" : "http_error"; + if (!response.ok) { + if (response.status === 401 && auth) endSession("Сессия закончилась. Войдите снова."); + throw new ApiError(data?.error?.message || "Не удалось выполнить запрос.", response.status); + } + return data; + } catch (error) { + if (error instanceof ApiError) throw error; + throw new ApiError("Нет ответа от сервера. Проверьте соединение и попробуйте позже."); + } finally { + clearTimeout(timer); + recordRequest({ method, path, status: httpStatus, requestId, instanceId, outcome, background, + durationMs: Math.round(performance.now() - started), + authorization: options.headers.Authorization?.split(" ")[0] || "Без авторизации" }); + } +} + +function basic(username, password) { + const bytes = new TextEncoder().encode(username + ":" + password); + return "Basic " + btoa(Array.from(bytes, byte => String.fromCharCode(byte)).join("")); +} + +function selectAuthTab(register) { + $("register-panel").hidden = !register; + $("login-panel").hidden = register; + $("tab-register").classList.toggle("active", register); + $("tab-login").classList.toggle("active", !register); + $("tab-register").setAttribute("aria-pressed", String(register)); + $("tab-login").setAttribute("aria-pressed", String(!register)); + notice("auth-notice", ""); +} + +function setFormBusy(form, busy) { + form.querySelectorAll("input, textarea, button").forEach(element => { element.disabled = busy; }); +} + +function persistSession(session) { + try { sessionStorage.setItem(storageKey, JSON.stringify(session)); } catch { /* session still works in memory */ } +} + +async function enterSession(session) { + reactions.clear(); reactionBusy.clear(); reactionVersion++; + state.epoch++; + state.session = session; + attachmentSession(session.token); + clearAttachedDrafts(); + updateSessionInfo({ name: session.user.display_name, expiresAt: session.expires_at }); + updateHistoryInfo(null); + state.current = null; + state.messages.clear(); + state.serverIds.clear(); + state.chats = []; + chatRows.clear(); + state.chatsStatus = "loading"; + state.chatsCursor = null; + state.drafts.clear(); + state.syncing = false; + state.sending = false; + persistSession(session); + $("auth-screen").hidden = true; + $("app-screen").hidden = false; + $("app-screen").classList.remove("chat-open"); + $("welcome").hidden = false; + $("workspace-error").hidden = true; + $("conversation-error").hidden = true; + $("conversation").hidden = true; + $("profile-name").textContent = session.user.display_name; + $("profile-username").textContent = "@" + session.user.username; + paintAvatar($("profile-avatar"), session.user.id, session.user.display_name); + $("chat-search").value = ""; + renderChats(); + try { await loadChats(false, true); } catch (error) { + if (state.session?.token === session.token) { $("welcome").hidden = true; $("workspace-error").hidden = false; } + } +} + +function endSession(message = "") { + reactions.clear(); reactionBusy.clear(); reactionVersion++; + state.epoch++; + state.session = null; + attachmentSession(null); + clearAttachedDrafts(); + updateSessionInfo(null); + updateHistoryInfo(null); + state.current = null; + state.chats = []; + chatRows.clear(); + state.messages.clear(); + state.serverIds.clear(); + state.drafts.clear(); + pendingMessages.clear(); + try { sessionStorage.removeItem(storageKey); } catch { /* storage unavailable */ } + document.querySelectorAll("dialog[open]").forEach(dialog => dialog.close()); + messageView.clear(); + unseenMessages = 0; + updateJumpButton(); + $("chat-list").replaceChildren(); + $("message-input").value = ""; + $("app-screen").hidden = true; + $("auth-screen").hidden = false; + $("login-password").value = ""; + selectAuthTab(false); + notice("auth-notice", message); +} + +$("tab-login").addEventListener("click", () => selectAuthTab(false)); +$("tab-register").addEventListener("click", () => selectAuthTab(true)); + +$("login-form").addEventListener("submit", async event => { + event.preventDefault(); + const form = event.currentTarget; + const username = $("login-username").value.trim(); + const password = $("login-password").value; + setFormBusy(form, true); + setMascotMood("pending"); + notice("auth-notice", ""); + try { + const session = await request("/api/v1/auth/sessions", { method: "POST", auth: false, headers: { Authorization: basic(username, password) } }); + form.reset(); + await celebrateMascots(); + await enterSession(session); + } catch (error) { setMascotMood("error"); notice("auth-notice", error.status === 401 ? "Неверный логин или пароль." : error.message); } + finally { setFormBusy(form, false); } +}); + +$("register-form").addEventListener("submit", async event => { + event.preventDefault(); + const form = event.currentTarget; + const username = $("register-username").value.trim(); + const displayName = $("register-name").value.trim(); + const password = $("register-password").value; + if (Array.from(displayName).length > 100) return notice("auth-notice", "Имя должно содержать от 1 до 100 символов."); + if (Array.from(password).length < 12 || Array.from(password).length > 128 || !password.trim()) { + setMascotMood("short"); + return notice("auth-notice", "Пароль должен содержать от 12 до 128 символов."); + } + setFormBusy(form, true); + setMascotMood("pending"); + notice("auth-notice", ""); + let registered = false; + try { + await request("/api/v1/users", { method: "POST", auth: false, body: { username, display_name: displayName, password } }); + registered = true; + const session = await request("/api/v1/auth/sessions", { method: "POST", auth: false, headers: { Authorization: basic(username, password) } }); + form.reset(); + await celebrateMascots(); + await enterSession(session); + toast("Добро пожаловать, " + session.user.display_name + "!"); + } catch (error) { + setMascotMood("error"); + if (registered) { + form.reset(); + selectAuthTab(false); + $("login-username").value = username; + notice("auth-notice", "Аккаунт создан. Войдите, когда сервер будет доступен."); + } else notice("auth-notice", error.status === 409 ? "Это имя пользователя уже занято. Выберите другое." : error.message); + } finally { setFormBusy(form, false); } +}); + +function memberCount(count) { const n = count % 100, d = count % 10; return count + " " + (n >= 11 && n <= 14 ? "участников" : d === 1 ? "участник" : d >= 2 && d <= 4 ? "участника" : "участников"); } +function chatActivity(chat) { return chat.last_message?.created_at || chat.created_at; } +function chatTime(value) { + const date = new Date(value), now = new Date(); + return date.toDateString() === now.toDateString() + ? date.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" }) + : date.toLocaleDateString("ru-RU", { day: "numeric", month: "short" }); +} + +async function loadChats(more = false, background = false) { + if (chatsLoading) return; + chatsLoading = true; + const token = state.session?.token; + const cursor = more ? state.chatsCursor : null; + $("chat-list").setAttribute("aria-busy", "true"); + $("refresh-chats").classList.add("is-loading"); + try { + const data = await request("/api/ui/chats?limit=100" + (cursor ? "&cursor=" + encodeURIComponent(cursor) : ""), { background }); + if (token !== state.session?.token) return; + const previous = new Map(state.chats.map(chat => [chat.id, chat])); + const incoming = data.items.map(chat => { + const existing = previous.get(chat.id)?.last_message; + return existing && (!chat.last_message || compareMessages(existing, chat.last_message) > 0) + ? { ...chat, last_message: existing } : chat; + }); + state.chats = more ? [...state.chats, ...incoming.filter(chat => !previous.has(chat.id))] : incoming; + state.chatsCursor = data.next_cursor; + state.chatsStatus = "ready"; + lastChatRefresh = Date.now(); + $("workspace-error").hidden = true; + if (!state.current) $("welcome").hidden = false; + renderChats(); + } catch (error) { + if (token === state.session?.token && !state.chats.length) { + state.chatsStatus = "error"; renderChats(); + } + throw error; + } finally { + chatsLoading = false; + $("chat-list").setAttribute("aria-busy", "false"); + $("refresh-chats").classList.remove("is-loading"); + } +} + +function renderChats() { + const query = $("chat-search").value.trim().toLocaleLowerCase("ru-RU"); + const chats = [...state.chats].sort((a, b) => chatActivity(b).localeCompare(chatActivity(a)) || b.id.localeCompare(a.id)) + .filter(chat => chat.title.toLocaleLowerCase("ru-RU").includes(query)); + $("chat-count").textContent = state.chats.length || ""; + $("more-chats").hidden = !state.chatsCursor; + const nodes = chats.map(chat => { + let row = chatRows.get(chat.id); + if (!row) { + const button = document.createElement("button"); button.className = "chat-row"; + button.dataset.chatId = chat.id; + const avatar = document.createElement("span"); avatar.className = "avatar"; + const description = document.createElement("span"); description.className = "chat-row-text"; + const heading = document.createElement("span"); heading.className = "chat-row-heading"; + const title = document.createElement("strong"), time = document.createElement("time"); + const preview = document.createElement("small"); preview.className = "chat-preview"; + heading.append(title, time); description.append(heading, preview); button.append(avatar, description); + button.addEventListener("click", () => { + const current = state.chats.find(item => item.id === chat.id); + if (current) void selectChat(current); + }); + row = { button, avatar, title, time, preview }; chatRows.set(chat.id, row); + } + row.button.classList.toggle("active", chat.id === state.current?.id); + row.button.setAttribute("aria-pressed", String(chat.id === state.current?.id)); + paintAvatar(row.avatar, chat.id, chat.title); + row.title.textContent = chat.title; + row.time.dateTime = chatActivity(chat); row.time.textContent = chatTime(chatActivity(chat)); + row.time.title = new Date(chatActivity(chat)).toLocaleString("ru-RU"); + const message = chat.last_message; + row.preview.textContent = message + ? (message.sender_id === state.session?.user.id ? "Вы: " : "") + (message.text.replace(/\s+/gu, " ").trim() || "Изображение") + : "Пока без сообщений · " + memberCount(chat.member_ids.length); + return row.button; + }); + if (!nodes.length) { + const empty = document.createElement("p"); empty.className = "list-empty"; + empty.textContent = state.chatsStatus === "loading" ? "Загружаем чаты…" : state.chatsStatus === "error" ? "Не удалось загрузить чаты." : query ? "Чаты не найдены." : "Пока нет чатов."; + nodes.push(empty); + } + const list = $("chat-list"), wanted = new Set(nodes); + for (const node of [...list.children]) if (!wanted.has(node)) node.remove(); + let next = list.firstChild; + for (const node of nodes) { + if (node === next) next = next.nextSibling; + else list.insertBefore(node, next); + } +} + +function updateChatPreview(chatId, items) { + const chat = state.chats.find(item => item.id === chatId); + const last = items.reduce((latest, message) => !latest || compareMessages(message, latest) > 0 ? message : latest, null); + if (chat && last && (!chat.last_message || compareMessages(last, chat.last_message) > 0)) { + chat.last_message = last; renderChats(); + } +} + +$("retry-chats").addEventListener("click", async () => { + const button = $("retry-chats"); button.disabled = true; + try { await loadChats(); } catch (error) { toast(error.message, true); } + finally { button.disabled = false; } +}); +$("retry-messages").addEventListener("click", async () => { + const button = $("retry-messages"); button.disabled = true; + try { await syncRecent(true); } catch (error) { toast(error.message, true); } + finally { button.disabled = false; } +}); + +$("chat-search").addEventListener("input", renderChats); +$("refresh-chats").addEventListener("click", async () => { try { await loadChats(); } catch (error) { toast(error.message, true); } }); +$("more-chats").addEventListener("click", async () => { try { await loadChats(true); } catch (error) { toast(error.message, true); } }); + +async function selectChat(chat) { + if (state.current?.id === chat.id) { $("app-screen").classList.add("chat-open"); return; } + if (state.current) state.drafts.set(state.current.id, $("message-input").value); + state.epoch++; + reactions.clear(); reactionBusy.clear(); reactionVersion++; + state.current = chat; + state.members = new Map([[state.session.user.id, state.session.user]]); + renderChats(); + state.messages = new Map(); + state.serverIds = new Set(); + state.olderCursor = null; + state.historyReady = false; + updateHistoryInfo({ title: chat.title, loaded: 0, hasOlder: false, ready: false }); + state.syncing = false; + $("current-title").textContent = chat.title; + $("current-members").textContent = memberCount(chat.member_ids.length); + paintAvatar($("current-avatar"), chat.id, chat.title); + $("welcome").hidden = true; + $("workspace-error").hidden = true; + $("conversation-error").hidden = true; + $("conversation").hidden = false; + $("app-screen").classList.add("chat-open"); + $("message-input").value = state.drafts.get(chat.id) || ""; + renderAttachedDrafts(); + updateComposer(); + messageView.clear(); + unseenMessages = 0; + updateJumpButton(); + $("empty-conversation").hidden = true; + $("older-messages").hidden = true; + $("messages-loading").hidden = false; + $("message-list").setAttribute("aria-busy", "true"); + if (!matchMedia("(prefers-reduced-motion: reduce)").matches) $("conversation").animate([{ opacity: 0, transform: "translateY(5px)" }, { opacity: 1, transform: "none" }], { duration: 180, easing: "ease-out" }); + try { await Promise.all([syncRecent(true), loadMembers(state.epoch, chat.id)]); } + catch (error) { if (state.historyReady) toast(error.message, true); } +} + +async function loadMembers(epoch, chatId) { + const data = await request(`/api/ui/chats/${chatId}/members`, { background: true }); + if (epoch !== state.epoch) return; + state.members = new Map(data.items.map(user => [user.id, user])); + if (state.historyReady) renderMessages(); +} + +function mergeMessages(items) { + let changed = false; + for (const item of items) { + const previous = state.messages.get(item.id); + if (!previous || previous.text !== item.text || previous.sender_id !== item.sender_id || previous.created_at !== item.created_at) { + state.messages.set(item.id, item); + changed = true; + } + state.serverIds.add(item.id); + } + return changed; +} + +function compareMessages(a, b) { + return a.created_at.localeCompare(b.created_at) || a.id.localeCompare(b.id); +} + +async function syncRecent(initial = false, background = false) { + if (!state.current || !state.session || state.syncing) return; + const epoch = state.epoch, chatId = state.current.id; + state.syncing = true; + try { + const page = await request(`/api/ui/chats/${chatId}/messages?limit=50`, { background }); + if (epoch !== state.epoch) return; + $("conversation-error").hidden = true; + const wasReady = state.historyReady, oldCursor = state.olderCursor; + const latest = [...state.messages.values()].reduce((last, item) => !last || compareMessages(item, last) > 0 ? item : last, null); + const incoming = initial || !latest ? 0 : page.items.filter(item => !state.messages.has(item.id) && compareMessages(item, latest) > 0).length; + const overlap = page.items.some(item => state.serverIds.has(item.id)); + state.historyReady = true; + // On a large burst, the older button pages through the newly discovered gap. + if (initial || (!overlap && page.items.length === 50)) state.olderCursor = page.next_cursor; + updateChatPreview(chatId, page.items); + const changed = mergeMessages(page.items); + if (initial || changed || !wasReady || oldCursor !== state.olderCursor) { + renderMessages(initial ? "bottom" : "preserve", incoming); + } + const visible = [...document.querySelectorAll('article.message')].filter(node => { + const rect = node.getBoundingClientRect(), region = $('message-scroll').getBoundingClientRect(); + return rect.bottom >= region.top && rect.top <= region.bottom; + }).map(node => node.dataset.messageId); + await refreshReactions([...new Set([...visible, ...page.items.map(item => item.id)])].slice(0,100)); + } catch (error) { + if (epoch === state.epoch && state.session && !state.historyReady) { + $("empty-conversation").hidden = true; + $("conversation-error").hidden = false; + } + throw error; + } finally { if (epoch === state.epoch) { + state.syncing = false; + $("messages-loading").hidden = true; + $("message-list").setAttribute("aria-busy", "false"); + } } +} + +$("older-messages").addEventListener("click", async () => { + if (!state.olderCursor || !state.current) return; + const epoch = state.epoch; + $("older-messages").disabled = true; + try { + const page = await request(`/api/ui/chats/${state.current.id}/messages?limit=50&cursor=${encodeURIComponent(state.olderCursor)}`); + if (epoch !== state.epoch) return; + mergeMessages(page.items); + state.olderCursor = page.next_cursor; + renderMessages("prepend"); + await refreshReactions(page.items.map(item => item.id)); + } catch (error) { toast(error.message, true); } + finally { $("older-messages").disabled = false; } +}); + +function renderMessages(mode = "preserve", incoming = 0) { + const scroll = $("message-scroll"), oldHeight = scroll.scrollHeight, oldTop = scroll.scrollTop; + const atBottom = oldHeight - oldTop - scroll.clientHeight < 85; + const messages = [...state.messages.values()].sort(compareMessages); + messageView.render(messages, state.session?.user.id, state.members, mode === "bottom" || incoming > 0); + messageView.renderReactions(reactions, reactionBusy); + $("empty-conversation").hidden = !state.historyReady || messages.length !== 0; + $("older-messages").hidden = !state.olderCursor; + updateHistoryInfo({ title: state.current?.title, loaded: messages.length, hasOlder: Boolean(state.olderCursor), ready: state.historyReady }); + if (mode === "bottom" || (mode === "preserve" && atBottom)) { + scroll.scrollTop = scroll.scrollHeight; + unseenMessages = 0; + } else if (mode === "prepend") scroll.scrollTop = oldTop + scroll.scrollHeight - oldHeight; + else { + scroll.scrollTop = oldTop; + unseenMessages += incoming; + } + updateJumpButton(); +} + +async function refreshReactions(ids) { + if (!ids.length || !state.current) return; + const epoch = state.epoch, version = reactionVersion, chatId = state.current.id; + try { + const data = await request(`/api/ui/chats/${chatId}/reactions?message_ids=${ids.join(',')}`, {background:true}); + if (epoch !== state.epoch || version !== reactionVersion) return; + const scroll = $('message-scroll'), oldHeight = scroll.scrollHeight, oldTop = scroll.scrollTop; + const atBottom = oldHeight - oldTop - scroll.clientHeight < 85; + for (const id of ids) reactions.set(id, data.items.filter(item => item.message_id === id)); + messageView.renderReactions(reactions, reactionBusy); + scroll.scrollTop = atBottom ? scroll.scrollHeight : oldTop; + } catch { /* Message history remains usable; reaction changes show their own error. */ } +} + +$('message-list').addEventListener('reactionchange', async event => { + const {messageId, reaction, present} = event.detail; + if (!state.current || reactionBusy.has(messageId)) return; + const epoch = state.epoch, chatId = state.current.id; + reactionVersion++; reactionBusy.add(messageId); messageView.renderReactions(reactions, reactionBusy); + try { + await request(`/api/ui/chats/${chatId}/messages/${messageId}/reactions/${reaction}`, {method:present ? 'PUT' : 'DELETE'}); + if (epoch !== state.epoch) return; + reactionVersion++; + await refreshReactions([messageId]); + } catch (error) { if (epoch === state.epoch) toast('Не удалось изменить реакцию. ' + error.message, true); } + finally { if (epoch === state.epoch) { reactionBusy.delete(messageId); messageView.renderReactions(reactions, reactionBusy); } } +}); + +function updateJumpButton() { + const scroll = $("message-scroll"), button = $("jump-latest"); + const atBottom = scroll.scrollHeight - scroll.scrollTop - scroll.clientHeight < 85; + if (atBottom) unseenMessages = 0; + button.hidden = atBottom || state.messages.size === 0; + const label = unseenMessages ? `Новые сообщения: ${unseenMessages} ↓` : "К последним ↓"; + if (button.textContent !== label) button.textContent = label; +} + +$("message-scroll").addEventListener("scroll", updateJumpButton, { passive: true }); +$("jump-latest").addEventListener("click", () => { + const scroll = $("message-scroll"); + scroll.scrollTo({ top: scroll.scrollHeight, behavior: matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth" }); +}); + +function updateComposer() { + const text = $("message-input").value, count = Array.from(text).length; + $("message-count").textContent = `${count} / 4000`; + $("message-count").classList.toggle("over-limit", count > 4000); + $("pick-file").disabled = state.sending || uploadBusy; + $("send-message").disabled = state.sending || uploadBusy || (!text.trim() && !(attachedDrafts.get(state.current?.id)?.length)) || count > 4000; + $("message-input").style.height = "auto"; + const height = $("message-input").scrollHeight + 2; + $("message-input").style.height = Math.min(140, height) + "px"; + $("message-input").style.overflowY = height > 140 ? "auto" : "hidden"; + if (state.current) state.drafts.set(state.current.id, text); +} + +$("message-input").addEventListener("input", updateComposer); +$("message-input").addEventListener("keydown", event => { + if (event.key === "Enter" && !event.shiftKey && !event.isComposing) { + event.preventDefault(); + if (!$("send-message").disabled) $("message-form").requestSubmit(); + } +}); +$("message-form").addEventListener("submit", async event => { + event.preventDefault(); + if (state.sending || !state.current || $("send-message").disabled) return; + const epoch = state.epoch, chatId = state.current.id, text = $("message-input").value; + const attachment_ids = (attachedDrafts.get(chatId) || []).map(file => file.id); + const previous = pendingMessages.get(chatId); + const attempt = previous?.text === text && JSON.stringify(previous.attachment_ids) === JSON.stringify(attachment_ids) ? previous : { text, attachment_ids, key: crypto.randomUUID() }; + pendingMessages.set(chatId, attempt); + state.sending = true; updateComposer(); renderAttachedDrafts(); + try { + const message = await request(`/api/v1/chats/${chatId}/messages`, { + method: "POST", body: { text, attachment_ids }, headers: { "Idempotency-Key": attempt.key } + }); + pendingMessages.delete(chatId); + clearAttachedDrafts(chatId); + renderAttachedDrafts(); + if (state.drafts.get(chatId) === text) state.drafts.set(chatId, ""); + if (epoch !== state.epoch) return; + state.messages.set(message.id, message); + updateChatPreview(chatId, [message]); + if ($("message-input").value === text) $("message-input").value = ""; + renderMessages("bottom"); + await syncRecent(false, true); + } catch (error) { toast(error.status === 0 ? "Ответ не получен. Повторите отправку: сообщение не продублируется." : error.message, true); } + finally { state.sending = false; updateComposer(); renderAttachedDrafts(); } +}); + +function openNewChat() { + $("new-chat-form").reset(); notice("chat-dialog-notice", ""); + $("new-chat-dialog").showModal(); $("new-chat-title").focus(); +} +$("new-chat").addEventListener("click", openNewChat); +$("welcome-new-chat").addEventListener("click", openNewChat); +document.querySelectorAll("[data-close-dialog]").forEach(button => button.addEventListener("click", () => button.closest("dialog").close())); +$("new-chat-form").addEventListener("submit", async event => { + event.preventDefault(); + const form = event.currentTarget, token = state.session?.token; + const title = $("new-chat-title").value.trim(); + if (!title || Array.from(title).length > 100) return notice("chat-dialog-notice", "Название должно содержать от 1 до 100 символов."); + const ids = $("new-chat-members").value.split(/[\s,;]+/u).filter(Boolean); + if (ids.some(id => !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(id))) + return notice("chat-dialog-notice", "Проверьте ID участников: нужен полный ID из профиля."); + const members = [...new Set([state.session.user.id, ...ids.map(id => id.toLowerCase())])]; + if (members.length > 100) return notice("chat-dialog-notice", "В чате может быть не более 100 участников."); + setFormBusy(form, true); notice("chat-dialog-notice", ""); + try { + const chat = await request("/api/v1/chats", { method: "POST", body: { title, member_ids: members } }); + if (token !== state.session?.token) return; + $("new-chat-dialog").close(); state.chats.push(chat); renderChats(); + await selectChat(chat); toast("Чат создан."); + } catch (error) { notice("chat-dialog-notice", error.message); } + finally { setFormBusy(form, false); } +}); + +$("open-profile").addEventListener("click", () => { + $("profile-details").textContent = state.session.user.display_name + " · @" + state.session.user.username; + $("my-id").value = state.session.user.id; $("profile-dialog").showModal(); +}); +$("copy-id").addEventListener("click", async () => { + try { await navigator.clipboard.writeText(state.session.user.id); toast("ID скопирован."); } + catch { $("my-id").select(); toast("Выделили ID. Скопируйте его сочетанием ⌘C или Ctrl+C."); } +}); +$("show-members").addEventListener("click", () => { + $("members-list").replaceChildren(...state.current.member_ids.map(id => { + const item = document.createElement("div"); item.className = "member-item"; + const label = document.createElement("strong"); label.textContent = (state.members.get(id)?.display_name || "Участник") + (id === state.session.user.id ? " (вы)" : ""); + const avatar = document.createElement("span"); avatar.className = "avatar"; + paintAvatar(avatar, id, state.members.get(id)?.display_name || "Участник"); + const details = document.createElement("span"); details.className = "member-details"; + const code = document.createElement("code"); code.textContent = id; details.append(label, code); item.append(avatar, details); return item; + })); + $("members-dialog").showModal(); +}); +$("logout").addEventListener("click", async () => { + $("logout").disabled = true; + try { await request("/api/v1/auth/sessions/current", { method: "DELETE" }); endSession(); } + catch (error) { if (error.status !== 401) toast(error.message, true); } + finally { $("logout").disabled = false; } +}); +$("back-to-chats").addEventListener("click", () => $("app-screen").classList.remove("chat-open")); +$("refresh-messages").addEventListener("click", async () => { + try { await syncRecent(); } catch (error) { toast(error.message, true); } +}); + +setInterval(async () => { + if (!state.session || document.hidden) return; + if (new Date(state.session.expires_at).getTime() <= Date.now()) return endSession("Сессия закончилась. Войдите снова."); + if (state.current) { try { await syncRecent(false, true); } catch { /* manual actions still show errors */ } } + if (!state.chatsCursor && state.chats.length <= 100 && Date.now() - lastChatRefresh > 12000) { + try { await loadChats(false, true); } catch { /* manual refresh shows errors */ } + } +}, 4000); + +async function resume() { + try { + const stored = sessionStorage.getItem(storageKey); + if (!stored) return; + const session = JSON.parse(stored); + if (!session?.token || !session.user || !(new Date(session.expires_at).getTime() > Date.now())) return endSession(); + state.session = session; + attachmentSession(session.token); + const user = await request("/api/v1/users/me"); + await enterSession({ ...session, user }); + } catch (error) { + state.session = null; + attachmentSession(null); + clearAttachedDrafts(); + if (error instanceof ApiError) notice("auth-notice", error.message); + else { try { sessionStorage.removeItem(storageKey); } catch { /* storage unavailable */ } } + } +} + +void resume(); +startClusterView(() => request('/api/ui/cluster', {background:true}), () => state.session?.token); + +function clearAttachedDrafts(chatId) { + for (const [id, files] of attachedDrafts) { + if (chatId && id !== chatId) continue; + for (const file of files) { + file.removed = true; + if (file.previewUrl) URL.revokeObjectURL(file.previewUrl); + } + attachedDrafts.delete(id); + } +} +function renderAttachedDrafts() { + const root = $("attached-files"); root.replaceChildren(); + for (const file of attachedDrafts.get(state.current?.id) || []) { + const item = document.createElement("div"); item.className = "draft-image"; + const image = document.createElement("img"); image.src = file.previewUrl; image.alt = file.filename; + const label = document.createElement("span"); label.className="draft-image-name"; label.textContent=file.filename;label.title=file.filename; + const remove = document.createElement("button"); remove.type="button";remove.className="draft-image-remove";remove.textContent="×"; + remove.setAttribute("aria-label","Убрать " + file.filename);remove.title="Убрать изображение";remove.disabled=state.sending; + remove.addEventListener("click",()=>{ + const chat = state.current.id; + file.removed=true;URL.revokeObjectURL(file.previewUrl); + attachedDrafts.set(chat,(attachedDrafts.get(chat)||[]).filter(item=>item!==file)); + renderAttachedDrafts();updateComposer(); + }); + item.append(image,label,remove); + if(!file.id) { + const status=document.createElement("span");status.className="draft-image-loading";status.textContent="Загрузка…";status.setAttribute("role","status");item.append(status); + } + root.append(item); + } +} +$("pick-file").addEventListener("click",()=>$("image-file").click()); +$("image-file").addEventListener("change",async()=>{ + const file=$("image-file").files[0];$("image-file").value=""; + if(!file || !state.current || uploadBusy || state.sending) return; + if(file.size>10485760) {toast("Максимум 10 MiB",true);return;} + if(!["image/png","image/jpeg"].includes(file.type)) {toast("Выберите PNG или JPEG",true);return;} + if((attachedDrafts.get(state.current.id)||[]).length>=10) {toast("Максимум 10 вложений",true);return;} + const chat=state.current.id, session=state.session.token; + const draft={filename:file.name,previewUrl:URL.createObjectURL(file),id:null,removed:false}; + attachedDrafts.set(chat,[...(attachedDrafts.get(chat)||[]),draft]);renderAttachedDrafts(); + uploadBusy=true;$("pick-file").disabled=true;updateComposer(); + try { + const attachment=await request(`/api/v1/chats/${chat}/attachments?filename=${encodeURIComponent(file.name)}`,{method:"POST",raw:file,headers:{"Content-Type":file.type}}); + if(state.session?.token!==session || draft.removed) return; + Object.assign(draft,attachment);renderAttachedDrafts(); + }catch(error){ + if(!draft.removed) { + draft.removed=true;URL.revokeObjectURL(draft.previewUrl); + attachedDrafts.set(chat,(attachedDrafts.get(chat)||[]).filter(item=>item!==draft));renderAttachedDrafts(); + } + if(state.session?.token===session) toast(error.message,true); + } + finally {uploadBusy=false;$("pick-file").disabled=state.sending;updateComposer();} +}); diff --git a/src/Messenger.Api/wwwroot/assets/chat-pattern.svg b/src/Messenger.Api/wwwroot/assets/chat-pattern.svg new file mode 100644 index 00000000..27e307c1 --- /dev/null +++ b/src/Messenger.Api/wwwroot/assets/chat-pattern.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/src/Messenger.Api/wwwroot/assets/kolovertysh-empty-320.webp b/src/Messenger.Api/wwwroot/assets/kolovertysh-empty-320.webp new file mode 100644 index 00000000..567ace88 Binary files /dev/null and b/src/Messenger.Api/wwwroot/assets/kolovertysh-empty-320.webp differ diff --git a/src/Messenger.Api/wwwroot/assets/kolovertysh-error-320.webp b/src/Messenger.Api/wwwroot/assets/kolovertysh-error-320.webp new file mode 100644 index 00000000..b085ea9b Binary files /dev/null and b/src/Messenger.Api/wwwroot/assets/kolovertysh-error-320.webp differ diff --git a/src/Messenger.Api/wwwroot/assets/kolovertysh-welcome-320.webp b/src/Messenger.Api/wwwroot/assets/kolovertysh-welcome-320.webp new file mode 100644 index 00000000..7f8c3609 Binary files /dev/null and b/src/Messenger.Api/wwwroot/assets/kolovertysh-welcome-320.webp differ diff --git a/src/Messenger.Api/wwwroot/assets/kolovertysh-welcome-640.webp b/src/Messenger.Api/wwwroot/assets/kolovertysh-welcome-640.webp new file mode 100644 index 00000000..3a4e5967 Binary files /dev/null and b/src/Messenger.Api/wwwroot/assets/kolovertysh-welcome-640.webp differ diff --git a/src/Messenger.Api/wwwroot/assets/kolovertysh.svg b/src/Messenger.Api/wwwroot/assets/kolovertysh.svg new file mode 100644 index 00000000..29d1871a --- /dev/null +++ b/src/Messenger.Api/wwwroot/assets/kolovertysh.svg @@ -0,0 +1,63 @@ + diff --git a/src/Messenger.Api/wwwroot/attachments.css b/src/Messenger.Api/wwwroot/attachments.css new file mode 100644 index 00000000..e1159963 --- /dev/null +++ b/src/Messenger.Api/wwwroot/attachments.css @@ -0,0 +1,61 @@ +.attachment-card { display:grid; gap:0; width:min(320px, 58vw); max-width:100%; margin:5px 0 0; } +.attachment-preview { display:grid; position:relative; width:100%; aspect-ratio:4/3; padding:0; border:0; border-radius:12px; overflow:hidden; background:#00000016; cursor:zoom-in; color:inherit; isolation:isolate; } +.attachment-preview img { width:100%; height:100%; object-fit:cover; display:block; opacity:0; transition:opacity .18s; } +.attachment-card.is-ready .attachment-preview img { opacity:1; } +.attachment-status { position:absolute; inset:0; display:grid; place-items:center; padding:24px; font-size:12px; text-align:center; line-height:1.6; } +.is-ready .attachment-status { display:none; } +.attachment-expand { position:absolute; bottom:10px; right:10px; display:grid; place-items:center; width:30px; height:30px; background:#1616169c; color:#fff; border-radius:9px; opacity:0; transition:opacity .16s; } +.attachment-preview:hover .attachment-expand, .attachment-preview:focus-visible .attachment-expand { opacity:1; } +.attachment-info { display:flex; gap:10px; align-items:center; padding:9px 0 2px; } +.attachment-label { display:grid; flex:1; gap:3px; min-width:0; } +.attachment-name { font-size:12px; overflow:hidden; white-space:nowrap; text-overflow:ellipsis; font-weight:550; } +.attachment-size { font-size:10px; opacity:.65; } +.attachment-download { display:grid; place-items:center; width:35px; height:35px; border:1px solid #ffffff22; border-radius:10px; color:inherit; background:#ffffff08; cursor:pointer; } +.mine .attachment-download { border-color:#26262625; background:#26262608; } +.attachment-download:hover { background:#ffffff20; } +.attachment-download:disabled { opacity:.3; cursor:default; } +.attachment-card svg, .image-viewer svg { width:20px; height:20px; fill:none; stroke:currentColor; stroke-width:1.7; stroke-linecap:round; stroke-linejoin:round; } +.attachment-preview:focus-visible, .attachment-download:focus-visible, .image-viewer button:focus-visible { outline:2px solid var(--accent); outline-offset:3px; } +.mine .attachment-preview:focus-visible, .mine .attachment-download:focus-visible { outline-color:#262626; } +.composer { grid-template-columns:40px minmax(0,1fr) 46px; } +#pick-file { height:47px; width:40px; margin-bottom:1px; } +.attached-files { grid-column:1/-1; order:-1; display:flex; gap:10px; overflow-x:auto; padding:4px 2px 7px; min-width:0; } +.attached-files:empty { display:none; } +.draft-image { width:84px; flex-shrink:0; position:relative; border-radius:12px; } +.draft-image > img { width:84px; height:76px; display:block; object-fit:cover; border-radius:12px; border:1px solid #ffffff20; } +.draft-image-name { display:block; overflow:hidden; white-space:nowrap; text-overflow:ellipsis; font-size:10px; color:var(--muted); padding-top:5px; } +.draft-image-remove { position:absolute; top:3px; right:3px; display:grid; place-items:center; width:25px; height:25px; font-size:21px; line-height:1; color:white; background:#171717c9; border:1px solid #ffffff30; border-radius:50%; cursor:pointer; } +.draft-image-remove:disabled { opacity:.4; cursor:default; } +.draft-image-loading { position:absolute; top:0; height:76px; inset-inline:0; display:grid; align-items:end; padding:7px 4px; background:linear-gradient(transparent,#000b); color:white; border-radius:12px; font-size:10px; text-align:center; pointer-events:none; } +.viewing-image { overflow:hidden; } +dialog.image-viewer { position:fixed; inset:0; width:100%; height:100%; width:100dvw; height:100dvh; max-width:none; max-height:none; margin:0; padding:0; border:0; border-radius:0; background:#141414f7; color:#f4f3ed; overflow:hidden; box-shadow:none; } +.image-viewer[open] { display:grid; grid-template-rows:auto minmax(0,1fr); } +.image-viewer::backdrop { background:#141414; backdrop-filter:none; } +.image-viewer-header { display:flex; gap:20px; align-items:center; justify-content:space-between; padding:18px max(20px,env(safe-area-inset-right)) 18px max(24px,env(safe-area-inset-left)); border-bottom:1px solid #ffffff10; background:#1d1d1d; z-index:2; } +.image-viewer-label { min-width:0; display:grid; gap:5px; } +.image-viewer-label strong { font-weight:550; font-size:14px; white-space:nowrap; text-overflow:ellipsis; overflow:hidden; } +.image-viewer-label > span { font-size:11px; color:#a7a79d; } +.image-viewer-actions { display:flex; gap:8px; flex-shrink:0; } +.image-viewer button { display:grid; place-items:center; color:inherit; background:#ffffff0b; border:1px solid #ffffff14; border-radius:12px; cursor:pointer; padding:0; width:42px; height:42px; transition:background .15s; } +.image-viewer button:hover { background:#ffffff20; } +.image-viewer button:disabled { opacity:.35; cursor:default; } +.image-viewer-stage { display:grid; place-items:center; position:relative; overflow:auto; padding:24px 70px max(24px,env(safe-area-inset-bottom)); min-height:0; min-width:0; } +.image-viewer-stage > img { display:block; max-width:100%; max-height:100%; min-height:0; object-fit:contain; border-radius:3px; user-select:none; -webkit-user-drag:none; } +.image-viewer-stage > img:not([src]) { display:none; } +.image-viewer-status { position:absolute; text-align:center; font-size:13px; color:#c8c8b9; max-width:300px; padding:20px; } +.image-viewer-status:empty { display:none; } +.image-viewer.is-zoomed .image-viewer-stage { display:block; padding:24px; } +.image-viewer.is-zoomed .image-viewer-stage > img { max-width:none; max-height:none; width:auto; height:auto; margin:auto; cursor:zoom-out; } +.image-viewer .image-viewer-prev, .image-viewer .image-viewer-next { position:absolute; top:calc(50% + 35px); background:#262626cc; width:44px; height:52px; z-index:1; } +.image-viewer-prev { left:16px; } .image-viewer-next { right:16px; } +@media (max-width:600px) { + .image-viewer-header { padding:12px; gap:8px; } + .image-viewer-label strong { font-size:12px; } + .image-viewer-actions { gap:5px; } + .image-viewer-actions button { width:36px; height:38px; border-radius:10px; } + .image-viewer-stage { padding:14px 12px 68px; } + .image-viewer .image-viewer-prev, .image-viewer .image-viewer-next { top:auto; bottom:max(12px,env(safe-area-inset-bottom)); height:38px; width:44px; } + .image-viewer-prev { left:calc(50% - 52px); } .image-viewer-next { right:calc(50% - 52px); } + .attachment-expand { opacity:1; } +} +@media (prefers-reduced-motion:reduce) { .attachment-preview img, .attachment-expand, .image-viewer button { transition:none; } } diff --git a/src/Messenger.Api/wwwroot/attachments.js b/src/Messenger.Api/wwwroot/attachments.js new file mode 100644 index 00000000..73cfd5e9 --- /dev/null +++ b/src/Messenger.Api/wwwroot/attachments.js @@ -0,0 +1,191 @@ +let token = null, generation = 0, activeLoads = 0; +const cards = new Set(), waiters = []; +let active = null, viewer = null, returnFocus = null; +const observer = new IntersectionObserver(entries => { + for (const entry of entries) { + const card = entry.target.attachment; + card.visible = entry.isIntersecting; + if (card.visible) void load(card).catch(() => {}); + else if (active !== card) release(card); + } +}, { rootMargin: '400px' }); + +const paths = { + download: 'M12 3v12m-5-5 5 5 5-5M5 17v4h14v-4', + close: 'm6 6 12 12M18 6 6 18', + zoom: 'M10 4a6 6 0 1 0 0 12 6 6 0 0 0 0-12m4.5 10.5L21 21M7 10h6m-3-3v6', + left: 'm15 5-7 7 7 7', right: 'm9 5 7 7-7 7' +}; +function icon(name) { + const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + svg.setAttribute('viewBox', '0 0 24 24'); svg.setAttribute('aria-hidden', 'true'); + const path = document.createElementNS(svg.namespaceURI, 'path'); path.setAttribute('d', paths[name]); + svg.append(path); return svg; +} +function control(label, name, action) { + const button = document.createElement('button'); button.type = 'button'; + button.title = label; button.setAttribute('aria-label', label); button.append(icon(name)); + button.addEventListener('click', action); return button; +} +function bytes(size) { return size < 1048576 ? Math.max(1, Math.round(size / 1024)) + ' КБ' : (size / 1048576).toFixed(1) + ' МБ'; } + +export function attachmentSession(value) { + generation++; token = value; + if (viewer?.open) viewer.close(); + clearAttachmentCards(); +} +export function clearAttachmentCards() { + if (viewer?.open) viewer.close(); + for (const card of cards) { card.disposed = true; observer.unobserve(card.root); release(card); } + cards.clear(); +} +function release(card) { + card.controller?.abort(); + if (card.url) URL.revokeObjectURL(card.url); + card.download.disabled = true; + card.url = null; card.image.removeAttribute('src'); card.root.classList.remove('is-ready'); +} +async function load(card) { + if (card.url) return; + if (card.promise) return card.promise; + const session = token, version = generation; + if (!session || card.disposed) throw new Error('Сессия недоступна'); + card.promise = (async () => { + if (activeLoads >= 2) await new Promise(resolve => waiters.push(resolve)); + activeLoads++; + try { + if (card.disposed || version !== generation || (!card.visible && active !== card)) return; + card.root.classList.remove('has-error'); card.status.textContent = 'Загрузка изображения…'; + const controller = new AbortController(); card.controller = controller; + const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(30000)]); + const options = {headers:{Authorization:'Bearer ' + session},credentials:'omit',cache:'no-store',signal}; + if (!card.meta) { + const response = await fetch(`/api/v1/attachments/${card.id}`, options); + if (!response.ok) throw new Error('Изображение недоступно'); + card.meta = await response.json(); + card.name.textContent = card.meta.filename; + card.size.textContent = bytes(card.meta.size_bytes); + card.open.setAttribute('aria-label', 'Открыть ' + card.meta.filename + ' на весь экран'); + } + const response = await fetch(`/api/v1/attachments/${card.id}/content`, options); + if (!response.ok) throw new Error('Изображение недоступно'); + const blob = await response.blob(); + if (card.disposed || version !== generation || controller.signal.aborted) return; + card.url = URL.createObjectURL(blob); card.image.src = card.url; + card.image.alt = card.meta.filename; card.root.classList.add('is-ready'); + card.download.disabled = false; + card.status.textContent = ''; + } catch (error) { + if (error.name !== 'AbortError' && !card.disposed && version === generation) { + card.root.classList.add('has-error'); card.status.textContent = 'Не удалось загрузить. Нажмите, чтобы повторить.'; + } + throw error; + } finally { + card.promise = null; activeLoads--; waiters.shift()?.(); + if (card.controller?.signal.aborted && !card.disposed && version === generation && (card.visible || active === card)) + queueMicrotask(() => { void load(card).catch(() => {}); }); + } + })(); + return card.promise; +} + +export function attachmentCard(id) { + const root = document.createElement('div'); root.className = 'attachment-card'; + const image = document.createElement('img'); image.alt = ''; image.decoding = 'async'; + const open = document.createElement('button'); open.type = 'button'; open.className = 'attachment-preview'; + open.setAttribute('aria-label', 'Открыть изображение на весь экран'); + const status = document.createElement('span'); status.className = 'attachment-status'; status.textContent = 'Загрузка изображения…'; + const hint = document.createElement('span'); hint.className = 'attachment-expand'; hint.append(icon('zoom')); + open.append(image, status, hint); + const info = document.createElement('div'); info.className = 'attachment-info'; + const label = document.createElement('span'); label.className = 'attachment-label'; + const name = document.createElement('span'); name.className = 'attachment-name'; name.textContent = 'Изображение'; + const size = document.createElement('span'); size.className = 'attachment-size'; label.append(name, size); + const card = {id, root, open, image, status, name, size, url:null, meta:null, visible:false, disposed:false, promise:null}; + const download = control('Скачать изображение', 'download', () => save(card)); + download.className = 'attachment-download'; download.disabled = true; card.download = download; + info.append(label, download); root.append(open, info); root.attachment = card; + open.addEventListener('click', () => { if (root.classList.contains('has-error')) { void load(card).catch(() => {}); } else openViewer(card); }); + cards.add(card); observer.observe(root); return root; +} +function save(card) { + if (!card?.url) return; + const link = document.createElement('a'); link.href = card.url; link.download = card.meta?.filename || 'image'; + document.body.append(link); link.click(); link.remove(); +} +function gallery() { + return [...cards].filter(card => !card.disposed && card.root.isConnected).sort((a,b) => + a.root.compareDocumentPosition(b.root) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1); +} +function move(direction) { + const items = gallery(), index = items.indexOf(active), next = items[index + direction]; + if (next) void show(next); +} +function zoom() { + if (!active?.url) return; + viewer.classList.toggle('is-zoomed'); + viewer.zoom.setAttribute('aria-pressed', String(viewer.classList.contains('is-zoomed'))); + viewer.stage.scrollTo(0, 0); +} +function createViewer() { + const dialog = document.createElement('dialog'); dialog.className = 'image-viewer'; + dialog.setAttribute('aria-label', 'Просмотр изображения'); + const header = document.createElement('header'); header.className = 'image-viewer-header'; + const label = document.createElement('div'); label.className = 'image-viewer-label'; + const name = document.createElement('strong'), detail = document.createElement('span');label.append(name, detail); + const actions = document.createElement('div');actions.className = 'image-viewer-actions'; + const zoomButton = control('Увеличить изображение', 'zoom', zoom); zoomButton.setAttribute('aria-pressed','false'); + const download = control('Скачать оригинал', 'download', () => save(active)); + const close = control('Закрыть просмотр', 'close', () => dialog.close()); + actions.append(zoomButton, download, close); header.append(label, actions); + const stage = document.createElement('div'); stage.className = 'image-viewer-stage'; + const image = document.createElement('img'); image.alt = ''; + const status = document.createElement('p');status.className = 'image-viewer-status';status.setAttribute('role','status'); + stage.append(image, status); + const previous = control('Предыдущее изображение', 'left', () => move(-1)); previous.className = 'image-viewer-prev'; + const next = control('Следующее изображение', 'right', () => move(1)); next.className = 'image-viewer-next'; + dialog.append(header, stage, previous, next); document.body.append(dialog); + Object.assign(dialog, {picture:image, nameLabel:name, detail, status, stage, download, zoom:zoomButton, previous, next}); + dialog.addEventListener('click', event => { if (event.target === stage || event.target === dialog) dialog.close(); }); + image.addEventListener('dblclick', zoom); + dialog.addEventListener('keydown', event => { + if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') { event.preventDefault(); move(event.key === 'ArrowLeft' ? -1 : 1); } + }); + let touch = null; + stage.addEventListener('touchstart', e => {touch = e.touches.length === 1 ? [e.touches[0].clientX, e.touches[0].clientY] : null;},{passive:true}); + stage.addEventListener('touchend', e => { + if (!touch || dialog.classList.contains('is-zoomed')) return; + const dx=e.changedTouches[0].clientX-touch[0], dy=e.changedTouches[0].clientY-touch[1];touch=null; + if (Math.abs(dx)>65 && Math.abs(dx)>Math.abs(dy)*1.5) move(dx<0?1:-1); + },{passive:true}); + dialog.addEventListener('close', () => { + const previousCard=active;active=null;dialog.picture.removeAttribute('src'); + document.documentElement.classList.remove('viewing-image'); + if(previousCard && !previousCard.visible) release(previousCard); + if(returnFocus?.isConnected) returnFocus.focus({preventScroll:true}); + }); + return dialog; +} +function openViewer(card) { + if (!viewer) viewer=createViewer(); + if (!viewer.open) {returnFocus=document.activeElement;viewer.showModal();document.documentElement.classList.add('viewing-image');} + void show(card); +} +async function show(card) { + const previous=active;active=card; + if(previous && previous!==card && !previous.visible) release(previous); + viewer.classList.remove('is-zoomed');viewer.zoom.setAttribute('aria-pressed','false'); + viewer.stage.scrollTo(0,0);viewer.picture.removeAttribute('src');viewer.picture.alt=''; + viewer.nameLabel.textContent=card.meta?.filename || 'Изображение';viewer.detail.textContent=''; + viewer.status.textContent='Загрузка…';viewer.download.disabled=true;viewer.zoom.disabled=true; + const items=gallery(), index=items.indexOf(card); + viewer.previous.hidden=index<=0;viewer.next.hidden=index===items.length-1; + try { + await load(card); + if(active!==card || !viewer.open || !card.url) return; + viewer.picture.src=card.url;viewer.picture.alt=card.meta.filename; + viewer.nameLabel.textContent=card.meta.filename; + viewer.detail.textContent=`${index+1} из ${items.length} · ${bytes(card.meta.size_bytes)}`; + viewer.status.textContent='';viewer.download.disabled=false;viewer.zoom.disabled=false; + } catch {if(active===card) viewer.status.textContent='Изображение недоступно. Закройте просмотр и повторите загрузку.';} +} diff --git a/src/Messenger.Api/wwwroot/avatars.js b/src/Messenger.Api/wwwroot/avatars.js new file mode 100644 index 00000000..2b68db1d --- /dev/null +++ b/src/Messenger.Api/wwwroot/avatars.js @@ -0,0 +1,42 @@ +const svgNS = "http://www.w3.org/2000/svg"; +const palettes = [ + ["#394639", "#c2d39b"], ["#474033", "#e5c38b"], + ["#3c414d", "#b9c9e4"], ["#493b42", "#e4b6c5"], + ["#444333", "#e0d29a"], ["#354647", "#afd5ce"] +]; + +function element(tag, attributes = {}) { + const node = document.createElementNS(svgNS, tag); + for (const [key, value] of Object.entries(attributes)) node.setAttribute(key, value); + return node; +} + +export function initials(name) { + return (name.match(/[\p{L}\p{N}]+/gu) || []).slice(0, 2) + .map(part => Array.from(part)[0]).join("").toUpperCase(); +} + +export function paintAvatar(target, id, name) { + if (target.dataset.identity === id && target.dataset.name === name) return; + let hash = 2166136261; + for (const character of id) hash = Math.imul(hash ^ character.charCodeAt(0), 16777619) >>> 0; + const [background, foreground] = palettes[hash % palettes.length]; + const svg = element("svg", { viewBox: "0 0 64 64", class: "avatar-art", "aria-hidden": "true" }); + svg.append(element("rect", { width: 64, height: 64, rx: 20, fill: background })); + const patterns = [ + "M-7 18Q21-7 39 9T74 18M-8 49Q21 27 40 44T74 49", + "M-3 3 28 3 64 39M-3 21 21 21 64 64M-3 39 14 39 39 64", + "M7 59Q-6 24 25 8Q60-7 70 26M-2 42Q23 69 54 49Q75 31 52 8" + ]; + svg.append(element("path", { d: patterns[(hash >>> 4) % patterns.length], fill: "none", + stroke: foreground, "stroke-width": 6, opacity: .12 })); + svg.append(element("circle", { cx: 50, cy: 13, r: 3, fill: foreground, opacity: .5 })); + const label = element("text", { x: 32, y: 34, fill: foreground, + "text-anchor": "middle", "dominant-baseline": "middle", "font-size": 22, + "font-family": "system-ui, sans-serif", "font-weight": 650 }); + label.textContent = initials(name); + svg.append(label); + target.replaceChildren(svg); + target.dataset.identity = id; + target.dataset.name = name; +} diff --git a/src/Messenger.Api/wwwroot/cluster-view.js b/src/Messenger.Api/wwwroot/cluster-view.js new file mode 100644 index 00000000..ab9f1588 --- /dev/null +++ b/src/Messenger.Api/wwwroot/cluster-view.js @@ -0,0 +1,90 @@ +const $ = id => document.getElementById(id); +const observed = new Map(); +const cards = new Map(); +let signedIn = false, lastInstance = null, total = 0, pulseTimer; + +export function setClusterIdentity(active) { + signedIn = active; + observed.clear(); cards.clear(); total = 0; lastInstance = null; + $('cluster-instances').replaceChildren(); + $('cluster-status').textContent = active ? 'Получаем heartbeat…' : 'Схема доступна после входа'; + $('cluster-detail').textContent = 'Подсветка — реальный X-Instance-Id ответа.'; + $('cluster-copy').disabled = true; + for (const id of ['cluster-postgres', 'cluster-redis', 'cluster-balancer']) $(id).dataset.state = 'unknown'; +} + +export function observeClusterRequest(entry) { + if (!signedIn || !entry.instanceId) return; + total++; + lastInstance = entry.instanceId; + observed.set(lastInstance, (observed.get(lastInstance) || 0) + 1); + for (const [id, card] of cards) { + card.root.classList.toggle('just-served', id === lastInstance); + card.count.textContent = `${observed.get(id) || 0} / ${total} запросов`; + } + $('cluster-balancer').dataset.state = 'up'; + $('cluster-detail').textContent = `${entry.method} · ${entry.status ?? 'нет ответа'} · ${entry.durationMs} мс → ${lastInstance.slice(0, 8)}`; + clearTimeout(pulseTimer); + pulseTimer = setTimeout(() => { for (const card of cards.values()) card.root.classList.remove('just-served'); }, 1100); +} + +function render(snapshot) { + $('cluster-redis').dataset.state = snapshot.redis_available ? 'up' : 'down'; + $('cluster-postgres').dataset.state = snapshot.postgres_available ? 'up' : 'down'; + if (!snapshot.redis_available) { + $('cluster-status').textContent = 'Redis недоступен · состояние API неизвестно'; + for (const card of cards.values()) { card.root.dataset.state = 'unknown'; card.state.textContent = 'Нет heartbeat'; } + $('cluster-copy').disabled = true; + return; + } + // Keep outages witnessed by this tab, without presenting earlier deployments as new failures. + const visible = snapshot.instances.filter(node => node.ready || cards.has(node.id) || observed.has(node.id)); + const alive = visible.filter(node => node.ready), missing = visible.length - alive.length; + $('cluster-status').textContent = `${alive.length} API в сети${missing ? ` · ${missing} без heartbeat` : ''}`; + const wanted = new Set(visible.map(node => node.id)); + for (const [id, card] of cards) if (!wanted.has(id)) { card.root.remove(); cards.delete(id); } + for (const node of [...visible].sort((a,b) => a.id.localeCompare(b.id))) { + let card = cards.get(node.id); + if (!card) { + const root = document.createElement('div'); root.className = 'cluster-api cluster-node'; root.dataset.instanceId = node.id; + const heading = document.createElement('strong'); heading.textContent = `API · ${node.id.slice(0,8)}`; + const state = document.createElement('span'), count = document.createElement('small'); + root.append(heading, state, count); root.title = `X-Instance-Id: ${node.id}`; + card = {root, state, count}; cards.set(node.id, card); $('cluster-instances').append(root); + } + card.root.dataset.state = node.ready ? 'up' : 'down'; + card.state.textContent = node.ready ? 'В сети' : 'Heartbeat пропал'; + card.count.textContent = `${observed.get(node.id) || 0} / ${total} запросов`; + } + const target = alive.find(node => node.id === lastInstance) || alive[0]; + $('cluster-command').textContent = target ? `python3 scripts/demo-failover.py --instance ${target.id}` : 'Ожидаем работающие API…'; + $('cluster-copy').disabled = alive.length < 2; +} + +export function startClusterView(readSnapshot, getToken) { + let busy = false; + async function refresh() { + const token = getToken(); + if (!token || busy || document.hidden || $('diagnostics-panel').hidden) return; + busy = true; + try { const data = await readSnapshot(); if (token === getToken()) render(data); } + catch { + if (token === getToken()) { + $('cluster-status').textContent = 'Нет свежих данных о кластере'; + $('cluster-balancer').dataset.state = 'unknown'; + $('cluster-postgres').dataset.state = 'unknown'; + $('cluster-redis').dataset.state = 'unknown'; + for (const card of cards.values()) { card.root.dataset.state = 'unknown'; card.state.textContent = 'Нет свежих данных'; } + $('cluster-copy').disabled = true; + } + } finally { busy = false; } + } + new MutationObserver(refresh).observe($('diagnostics-panel'), { attributes: true, attributeFilter: ['hidden'] }); + setInterval(refresh, 2000); + $('cluster-probe').addEventListener('click', refresh); + $('cluster-copy').addEventListener('click', async () => { + try { await navigator.clipboard.writeText($('cluster-command').textContent); $('cluster-copy').textContent = 'Скопировано'; } + catch { $('cluster-copy').textContent = 'Выделите команду ниже'; } + setTimeout(() => { $('cluster-copy').textContent = 'Скопировать команду'; }, 2000); + }); +} diff --git a/src/Messenger.Api/wwwroot/diagnostics.js b/src/Messenger.Api/wwwroot/diagnostics.js new file mode 100644 index 00000000..3299a629 --- /dev/null +++ b/src/Messenger.Api/wwwroot/diagnostics.js @@ -0,0 +1,113 @@ +// Only explicitly selected HTTP metadata reaches this view. Never pass request +// headers, bodies, session objects or raw response JSON into the panel. +import { observeClusterRequest, setClusterIdentity } from '/cluster-view.js'; +const $ = id => document.getElementById(id); +const preferenceKey = "n1k0der.diagnostics"; +const requests = []; +let session = null, history = null, backgroundRequest = null, returnFocus = null; + +function setOpen(open) { + $("diagnostics-panel").hidden = !open; + document.body.classList.toggle("diagnostics-open", open); + document.querySelectorAll("[data-diagnostics-toggle]").forEach(button => button.setAttribute("aria-expanded", String(open))); + try { sessionStorage.setItem(preferenceKey, open ? "on" : "off"); } catch { /* optional preference */ } + if (open) { render(); $("diagnostics-close").focus(); } + else if (returnFocus?.isConnected) returnFocus.focus(); +} + +document.querySelectorAll("[data-diagnostics-toggle]").forEach(button => button.addEventListener("click", () => { + returnFocus = button; + setOpen($("diagnostics-panel").hidden); +})); +$("diagnostics-close").addEventListener("click", () => setOpen(false)); +document.addEventListener("keydown", event => { + if (event.key === "Escape" && !$("diagnostics-panel").hidden && !document.querySelector("dialog[open]")) { + event.preventDefault(); setOpen(false); + } +}); + +export function updateSessionInfo(value) { + setClusterIdentity(Boolean(value)); + session = value ? { name: value.name, expiresAt: value.expiresAt } : null; + document.body.classList.toggle("has-session", Boolean(session)); + if (!$("diagnostics-panel").hidden) renderSession(); +} + +export function updateHistoryInfo(value) { + history = value ? { title: value.title, loaded: value.loaded, hasOlder: value.hasOlder, ready: value.ready } : null; + if (!$("diagnostics-panel").hidden) renderHistory(); +} + +export function recordRequest(value) { + const entry = { + method: value.method, path: value.path.split("?")[0], status: value.status, + authorization: value.authorization, durationMs: value.durationMs, + requestId: value.requestId, instanceId: value.instanceId, outcome: value.outcome, source: value.source, at: new Date() + }; + observeClusterRequest(entry); + if (value.background) backgroundRequest = entry; + else { requests.unshift(entry); requests.length = Math.min(requests.length, 4); } + if (!$("diagnostics-panel").hidden) renderRequests(); +} + +function renderSession() { + $("diagnostics-user").textContent = session?.name || "Вход не выполнен"; + const seconds = session ? Math.max(0, Math.ceil((new Date(session.expiresAt).getTime() - Date.now()) / 1000)) : null; + $("diagnostics-session").textContent = seconds === null ? "-" : seconds === 0 ? "Срок истёк" : `${Math.floor(seconds / 60)} мин ${String(seconds % 60).padStart(2, "0")} с`; +} + +function renderHistory() { + $("diagnostics-chat").textContent = history?.title || "Выберите чат"; + $("diagnostics-messages").textContent = history + ? `Загружено: ${history.loaded} · ${!history.ready ? "страница ещё не получена" : history.hasOlder ? "есть старые сообщения ↑" : "старых страниц нет"}` + : "Сообщения ещё не загружены"; +} + +function result(entry) { + if (entry.status === null) return "Ответ не получен: соединение или таймаут. Результат записи может быть неизвестен."; + if (entry.outcome === "unreadable") return "HTTP-ответ получен, но его данные не удалось прочитать."; + if (entry.status === 204 && entry.method === "DELETE" && entry.path === "/api/v1/auth/sessions/current") return "Сессия отозвана. Ответ без тела."; + return ({200: "Запрос выполнен", 201: "Объект создан", 204: "Выполнено без тела ответа", + 400: "Некорректные данные", 401: "Нужен действующий вход", 404: "Ресурс отсутствует или недоступен", + 409: "Конфликт данных", 415: "Неподдерживаемый формат", 503: "Сервис временно недоступен", + 500: "Внутренняя ошибка сервера"})[entry.status] || `HTTP ${entry.status}`; +} + +function shortPath(path) { return path.replace(/\/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}(?=\/|$)/gi, "/…"); } + +function renderRequests() { + const current = requests[0]; + $("diagnostics-empty").hidden = Boolean(current); + $("diagnostics-request-details").hidden = !current; + $("diagnostics-request-time").textContent = current ? current.at.toLocaleTimeString("ru-RU") : ""; + if (current) { + const failed = current.status === null || current.status >= 400 || current.outcome === "unreadable"; + $("diagnostics-method").textContent = current.method; + $("diagnostics-status").textContent = current.status ?? "Нет ответа"; + $("diagnostics-status").classList.toggle("failed", failed); + $("diagnostics-origin").textContent = current.source || "Основной интерфейс"; + $("diagnostics-path").textContent = shortPath(current.path); + $("diagnostics-path").title = current.path; + $("diagnostics-result").textContent = result(current); + $("diagnostics-result").classList.toggle("failed", failed); + $("diagnostics-auth").textContent = current.authorization; + $("diagnostics-duration").textContent = `${current.durationMs} мс`; + $("diagnostics-request-id").textContent = current.requestId || "Не получен"; + $("diagnostics-instance-id").textContent = current.instanceId || "Не получен"; + } + const previous = requests.slice(1).map(entry => { + const item = document.createElement("li"); + const status = document.createElement("span"); status.textContent = entry.status ?? "-"; + status.className = "diagnostics-mini-status" + (entry.status === null || entry.status >= 400 ? " failed" : ""); + const route = document.createElement("code"); route.textContent = `${entry.method} ${shortPath(entry.path)}`; + route.title = entry.path; item.append(status, route); return item; + }); + $("diagnostics-previous").replaceChildren(...previous); + $("diagnostics-previous").hidden = previous.length === 0; + $("diagnostics-background").hidden = !backgroundRequest; + if (backgroundRequest) $("diagnostics-background").textContent = `Фоновый запрос: ${backgroundRequest.status ?? "нет ответа"} · ${backgroundRequest.durationMs} мс · ${backgroundRequest.at.toLocaleTimeString("ru-RU")}`; +} + +function render() { renderSession(); renderHistory(); renderRequests(); } +setInterval(() => { if (!$("diagnostics-panel").hidden) renderSession(); }, 1000); +try { if (sessionStorage.getItem(preferenceKey) === "on") setOpen(true); } catch { /* optional preference */ } diff --git a/src/Messenger.Api/wwwroot/index.html b/src/Messenger.Api/wwwroot/index.html new file mode 100644 index 00000000..226ae3fe --- /dev/null +++ b/src/Messenger.Api/wwwroot/index.html @@ -0,0 +1,169 @@ + + + + + + + + n1k0der · Мессенджер + + + + + + + + + + +
+
+ n1k0der. +

Место для
ваших
разговоров.

+ +
+
+
+
+

С возвращением.

+
+
+ + + +
+
n1k0der
+
+
+ + + + + +

Собрать чат

+

Ваш профиль

Поделитесь ID для приглашения в чат.

+

Участники чата

+ + diff --git a/src/Messenger.Api/wwwroot/mascots.js b/src/Messenger.Api/wwwroot/mascots.js new file mode 100644 index 00000000..ef6f57fa --- /dev/null +++ b/src/Messenger.Api/wwwroot/mascots.js @@ -0,0 +1,143 @@ +// Animation reads field state and password length, never password text. +const stage = document.getElementById("mascot-stage"); +const auth = document.getElementById("auth-screen"); +const reduceMotion = matchMedia("(prefers-reduced-motion: reduce)"); +const mobile = matchMedia("(max-width: 720px)"); +let pending = false, feedback = false; +let feedbackTimer, sleepTimer, approachTimer, pointerFrame = null; +let pointer = { x: 0, y: 0 }, lastWake = 0; + +function wakeUp() { + stage.classList.remove("is-sleepy"); + clearTimeout(sleepTimer); + sleepTimer = setTimeout(() => { + if (stage.dataset.mood === "idle") stage.classList.add("is-sleepy"); + }, 12000); +} + +function activeField() { + const focused = document.activeElement; + return focused?.matches("[data-password-toggle]") + ? document.getElementById(focused.dataset.passwordToggle) : focused; +} + +function focusedMood() { + if (pending || feedback) return; + const field = activeField(); + let mood = "idle"; + if (field?.matches("#login-password, #register-password")) { + mood = field.type === "text" ? "revealed" : "private"; + if (field.id === "register-password" && field.value.length > 0 && Array.from(field.value).length < 12) mood = "short"; + } else if (field?.matches("#login-username, #register-name, #register-username")) mood = "looking"; + stage.dataset.mood = mood; + document.getElementById("auth-error-art").hidden = mood !== "error"; +} + +export function setMascotMood(mood) { + clearTimeout(feedbackTimer); + pending = mood === "pending"; + feedback = ["success", "error", "short"].includes(mood); + stage.dataset.mood = mood; + document.getElementById("auth-error-art").hidden = mood !== "error"; + if (pending || feedback) stage.classList.remove("is-curious"); + if (feedback) feedbackTimer = setTimeout(() => { feedback = false; focusedMood(); }, 3500); +} + +for (const form of auth.querySelectorAll("form")) { + form.addEventListener("focusin", () => { + if (!pending) { feedback = false; clearTimeout(feedbackTimer); } + wakeUp(); focusedMood(); + }); + form.addEventListener("focusout", () => requestAnimationFrame(focusedMood)); + form.addEventListener("input", () => { + feedback = false; focusedMood(); wakeUp(); + stage.classList.add("is-curious"); + clearTimeout(approachTimer); + approachTimer = setTimeout(() => stage.classList.remove("is-curious"), 1600); + }); + form.addEventListener("invalid", () => setMascotMood("error"), true); + form.addEventListener("reset", () => { + for (const button of form.querySelectorAll("[data-password-toggle]")) { + document.getElementById(button.dataset.passwordToggle).type = "password"; + button.setAttribute("aria-pressed", "false"); + button.setAttribute("aria-label", "Показать пароль"); + button.querySelector("use").setAttribute("href", "#i-eye"); + } + }); +} + +for (const button of auth.querySelectorAll("[data-password-toggle]")) { + button.addEventListener("click", () => { + const field = document.getElementById(button.dataset.passwordToggle); + const shown = field.type === "password"; + field.type = shown ? "text" : "password"; + button.setAttribute("aria-pressed", String(shown)); + button.setAttribute("aria-label", shown ? "Скрыть пароль" : "Показать пароль"); + button.querySelector("use").setAttribute("href", shown ? "#i-eye-off" : "#i-eye"); + feedback = false; wakeUp(); focusedMood(); + }); +} +for (const button of auth.querySelectorAll(".auth-switch button")) { + button.addEventListener("click", () => { + pending = feedback = false; + clearTimeout(feedbackTimer); wakeUp(); focusedMood(); + }); +} + +// Mouse events are combined into at most one update per browser frame. +auth.addEventListener("pointermove", event => { + if (event.pointerType === "touch" || reduceMotion.matches || auth.hidden || document.hidden) return; + pointer = { x: event.clientX, y: event.clientY }; + if (performance.now() - lastWake > 1000) { wakeUp(); lastWake = performance.now(); } + if (pointerFrame !== null) return; + pointerFrame = requestAnimationFrame(() => { + pointerFrame = null; + const rect = stage.getBoundingClientRect(); + const x = Math.max(-4, Math.min(4, (pointer.x - rect.left - rect.width / 2) / 55)); + const y = Math.max(-3, Math.min(3, (pointer.y - rect.top - rect.height / 2) / 65)); + stage.style.setProperty("--gaze-x", `${x}px`); + stage.style.setProperty("--gaze-y", `${y}px`); + }); +}); +auth.addEventListener("pointerleave", () => { + stage.style.setProperty("--gaze-x", "0px"); stage.style.setProperty("--gaze-y", "0px"); +}); + +const close = document.getElementById("diagnostics-close"); +let closeHovered = false; +function reactToClose() { + stage.classList.toggle("is-scared", !close.closest("[hidden]") && + (closeHovered || close.matches(":focus-visible"))); +} +close.addEventListener("pointerenter", () => { closeHovered = true; reactToClose(); }); +close.addEventListener("pointerleave", () => { closeHovered = false; reactToClose(); }); +close.addEventListener("focus", reactToClose); +close.addEventListener("blur", reactToClose); +close.addEventListener("keydown", () => requestAnimationFrame(reactToClose)); +new MutationObserver(reactToClose).observe(document.getElementById("diagnostics-panel"), { attributes: true, attributeFilter: ["hidden"] }); + +function updateVisibility() { + const visible = !auth.hidden && !document.hidden; + stage.classList.toggle("is-visible", visible); + if (!visible) { + if (pointerFrame !== null) cancelAnimationFrame(pointerFrame); + pointerFrame = null; + clearTimeout(sleepTimer); clearTimeout(approachTimer); clearTimeout(feedbackTimer); + stage.classList.remove("is-curious", "is-sleepy"); + pending = feedback = false; + } else { wakeUp(); focusedMood(); } +} +new MutationObserver(updateVisibility).observe(auth, { attributes: true, attributeFilter: ["hidden"] }); +document.addEventListener("visibilitychange", updateVisibility); +function placeStage() { + if (mobile.matches) { + const anchor = document.getElementById("login-panel"); anchor.before(stage); + } else document.querySelector(".intro").append(stage); +} +mobile.addEventListener("change", placeStage); +placeStage(); updateVisibility(); + +export async function celebrateMascots() { + setMascotMood("success"); + if (!reduceMotion.matches) await new Promise(resolve => setTimeout(resolve, 650)); +} diff --git a/src/Messenger.Api/wwwroot/message-view.js b/src/Messenger.Api/wwwroot/message-view.js new file mode 100644 index 00000000..5c2469b7 --- /dev/null +++ b/src/Messenger.Api/wwwroot/message-view.js @@ -0,0 +1,96 @@ +// Each message keeps its own DOM element, identified by the message ID. +import { attachmentCard, clearAttachmentCards } from '/attachments.js'; +import { ReactionControls } from '/reactions.js'; +export class MessageView { + constructor(list) { + this.list = list; + this.messages = new Map(); + this.days = new Map(); + } + + clear() { + clearAttachmentCards(); + this.messages.clear(); + this.days.clear(); + this.list.replaceChildren(); + } + + render(messages, userId, members, animate = false) { + const nodes = [], entering = []; + const hadMessages = this.messages.size > 0; + let previous = null, previousDay = ""; + + for (const message of messages) { + const date = new Date(message.created_at); + const day = date.toLocaleDateString("ru-RU", { day: "numeric", month: "long", year: "numeric" }); + if (day !== previousDay) { + if (!this.days.has(day)) { + const divider = document.createElement("div"); + divider.className = "date-separator"; + divider.textContent = day; + this.days.set(day, divider); + } + nodes.push(this.days.get(day)); + } + + let entry = this.messages.get(message.id); + if (!entry) { + const article = document.createElement("article"); + article.className = "message"; + article.dataset.messageId = message.id; + const author = document.createElement("span"); + author.className = "message-author"; + const bubble = document.createElement("div"); + bubble.className = "message-bubble"; + const text = document.createElement("p"); + text.className = "message-text"; + const stamp = document.createElement("time"); + stamp.className = "message-time"; + bubble.append(text, ...((message.attachment_ids || []).map(attachmentCard)), stamp); + const reactions = new ReactionControls(message.id); + article.append(author, bubble, reactions.root); + entry = { article, author, text, stamp, reactions }; + this.messages.set(message.id, entry); + if (animate && hadMessages) entering.push(article); + } + + const mine = message.sender_id === userId; + const grouped = previousDay === day && previous?.sender_id === message.sender_id && + date.getTime() - new Date(previous.created_at).getTime() <= 5 * 60 * 1000; + entry.article.classList.toggle("mine", mine); + entry.article.classList.toggle("grouped", grouped); + entry.author.hidden = mine || grouped; + entry.author.title = message.sender_id; + setText(entry.author, members.get(message.sender_id)?.display_name || "Участник " + message.sender_id.slice(0, 8)); + setText(entry.text, message.text); + entry.text.hidden = !message.text; + entry.stamp.dateTime = message.created_at; + setText(entry.stamp, date.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" })); + nodes.push(entry.article); + previous = message; + previousDay = day; + } + + // Keep existing nodes in place. Insert only new or reordered nodes. + const wanted = new Set(nodes); + for (const node of [...this.list.children]) { + if (!wanted.has(node)) node.remove(); + } + let next = this.list.firstChild; + for (const node of nodes) { + if (node === next) next = next.nextSibling; + else this.list.insertBefore(node, next); + } + if (!matchMedia("(prefers-reduced-motion: reduce)").matches) { + for (const node of entering) node.animate([{ opacity: 0, transform: "translateY(5px)" }, { opacity: 1, transform: "none" }], { duration: 190, easing: "ease-out" }); + } + } + + renderReactions(items, busy) { + for (const [id, entry] of this.messages) entry.reactions.render(items.get(id) || [], busy.has(id)); + } +} + +function setText(element, text) { + if (element.textContent !== text) element.textContent = text; +} diff --git a/src/Messenger.Api/wwwroot/polish.css b/src/Messenger.Api/wwwroot/polish.css new file mode 100644 index 00000000..df0ae386 --- /dev/null +++ b/src/Messenger.Api/wwwroot/polish.css @@ -0,0 +1,41 @@ +/* Shared details for the chat list, generated avatars and gentle motion. */ +.avatar { overflow: hidden; background: transparent; border-color: #ffffff14; } +.avatar .avatar-art { display: block; width: 100%; height: 100%; stroke: none; } +.avatar-art text { letter-spacing: -.5px; } +.profile .avatar { background: transparent; } +.chat-row.active .avatar { background: transparent; border-color: #ffe13545; } +.chat-row { padding: 14px 11px; gap: 12px; } +.chat-row.active { background: #ffe1350b; border-color: #ffe13528; } +.chat-row.active::after { display: none; } +.chat-row-heading { display: flex; align-items: baseline; gap: 8px; min-width: 0; } +.chat-row-heading strong { flex: 1; min-width: 0; padding: 0; color: #e7e6dc; } +.chat-row-heading time { flex-shrink: 0; font-size: 10px; color: #a5a598; font-variant-numeric: tabular-nums; } +.chat-row.active .chat-row-heading strong { color: var(--accent); } +.chat-row.active .chat-row-heading time { color: #d4c878; } +.chat-preview { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; line-height: 1.5; } +.search-field > svg { width: 17px; height: 17px; color: var(--muted); } +.action-arrow { width: 20px; height: 20px; } +.member-item { grid-template-columns: 38px minmax(0, 1fr); gap: 12px; align-items: start; } +.member-item .avatar { width: 38px; height: 38px; border-radius: 12px; } +.member-details { display: grid; min-width: 0; gap: 8px; } +.member-details code { padding: 9px 10px; } +.message-scroll { background-size: 320px 280px; } +.messages-loading { display: grid; gap: 15px; padding: 22px 0; } +.messages-loading i { display: block; width: 48%; max-width: 240px; height: 53px; border-radius: 16px 16px 16px 5px; background: #ffffff06; } +.messages-loading i:nth-child(2) { justify-self: end; width: 37%; border-radius: 16px 16px 5px 16px; background: #ffe1350b; } +.messages-loading i:nth-child(3) { width: 58%; } +.send-button { transition: background .18s, transform .18s; } +.send-button:not(:disabled):active { transform: scale(.93); } +.send-button:not(:disabled):hover svg { transform: translate(1px, -1px); } +.send-button svg { transition: transform .18s; } +.icon-button.is-loading svg { animation: refresh-turn .9s linear infinite; } +.kolo-ear-left { transform-origin: 108px 135px; } +.kolo-ear-right { transform-origin: 195px 135px; } +.mascot-stage[data-mood=idle] .kolo-ear-left { animation: ear-settle 9s ease-in-out infinite; } +.spirit-svg { filter: drop-shadow(0 8px 12px #00000014); } +@keyframes refresh-turn { to { transform: rotate(360deg); } } +@keyframes ear-settle { 0%, 78%, 90%, 100% { transform: rotate(0); } 82% { transform: rotate(-3deg); } 86% { transform: rotate(2deg); } } +@media (prefers-reduced-motion: reduce) { + .mascot-stage[data-mood=idle] .kolo-ear-left, .icon-button.is-loading svg { animation: none; } + .send-button, .send-button svg { transition: none; } +} diff --git a/src/Messenger.Api/wwwroot/reactions.js b/src/Messenger.Api/wwwroot/reactions.js new file mode 100644 index 00000000..4eaa0a75 --- /dev/null +++ b/src/Messenger.Api/wwwroot/reactions.js @@ -0,0 +1,45 @@ +const choices = [['like','👍','Нравится'],['love','❤️','Сердце'],['laugh','😂','Смешно'],['mushroom','🍄','Гриб']]; + +export class ReactionControls { + constructor(messageId) { + this.root = document.createElement('div'); this.root.className = 'reaction-controls'; + this.badges = new Map(); this.items = []; + this.picker = document.createElement('button'); this.picker.type = 'button'; this.picker.className = 'reaction-picker'; + this.picker.textContent = '☺+'; this.picker.setAttribute('aria-label', 'Добавить реакцию'); this.picker.setAttribute('aria-expanded','false'); + this.menu = document.createElement('div'); this.menu.className = 'reaction-menu'; this.menu.hidden = true; + this.menu.setAttribute('role','group'); this.menu.setAttribute('aria-label','Выберите реакцию'); + this.root.append(this.picker, this.menu); + const choose = reaction => { + this.close(); + this.root.dispatchEvent(new CustomEvent('reactionchange', { bubbles: true, + detail: { messageId, reaction, present: !this.items.find(item => item.reaction === reaction)?.mine } })); + }; + for (const [reaction, emoji, label] of choices) { + const button = document.createElement('button'); button.type = 'button'; button.textContent = emoji; + button.setAttribute('aria-label',label); button.addEventListener('click',() => choose(reaction)); this.menu.append(button); + const badge = document.createElement('button'); badge.type = 'button'; badge.className = 'reaction-button'; badge.hidden = true; + badge.dataset.reaction = reaction; badge.addEventListener('click',() => choose(reaction)); + this.root.insertBefore(badge,this.picker); this.badges.set(reaction,{badge,emoji,label}); + } + this.picker.addEventListener('click',() => { + this.menu.hidden = !this.menu.hidden; this.picker.setAttribute('aria-expanded',String(!this.menu.hidden)); + if (!this.menu.hidden) this.menu.querySelector('button').focus(); + }); + this.root.addEventListener('keydown',event => { if (event.key === 'Escape') { this.close(); this.picker.focus(); event.stopPropagation(); } }); + this.root.addEventListener('focusout',event => { if (!this.root.contains(event.relatedTarget)) this.close(); }); + } + close() { this.menu.hidden = true; this.picker.setAttribute('aria-expanded','false'); } + render(items = [], busy = false) { + const signature = JSON.stringify([items,busy]); + if (signature === this.signature) return; + this.signature = signature; this.items = items; + for (const [reaction, {badge,emoji,label}] of this.badges) { + const item = items.find(item => item.reaction === reaction); + badge.hidden = !item?.count; + badge.textContent = `${emoji} ${item?.count || 0}`; + badge.setAttribute('aria-label',`${label}: ${item?.count || 0}${item?.mine ? ', ваша реакция' : ''}`); + badge.setAttribute('aria-pressed',String(Boolean(item?.mine))); + } + for (const button of this.root.querySelectorAll('button')) button.disabled = busy; + } +} diff --git a/src/Messenger.Api/wwwroot/showcase.css b/src/Messenger.Api/wwwroot/showcase.css new file mode 100644 index 00000000..f4f0e2e9 --- /dev/null +++ b/src/Messenger.Api/wwwroot/showcase.css @@ -0,0 +1,41 @@ +.cluster-section { margin-bottom: 18px; padding-bottom: 18px; border-bottom: 1px solid var(--border); } +.cluster-section h3 { margin: 0; font-size: 15px; color: #eeeadd; } +.cluster-live { display: inline-flex; align-items: center; gap: 5px; color: #b9d99f; font-size: 9px; letter-spacing: 1px; } +.cluster-live::before { content: ''; width: 5px; height: 5px; border-radius: 50%; background: currentColor; } +.cluster-status { font-size: 11px; color: var(--muted); line-height: 1.6; margin: 10px 0 14px; } +.cluster-graph { display: grid; justify-items: center; gap: 16px; position: relative; isolation: isolate; } +.cluster-graph::before { content: ''; position: absolute; top: 10px; bottom: 15px; width: 1px; background: #706b4360; z-index: -1; } +.cluster-node { background: #30312c; border: 1px solid #535447; border-radius: 11px; text-align: center; padding: 10px; transition: border-color .25s, background .25s; min-width: 0; } +.cluster-node strong { display: block; font-size: 11px; color: #ecebdc; } +.cluster-node span, .cluster-node small { display: block; font-size: 9px; margin-top: 5px; color: var(--muted); } +.cluster-browser, .cluster-balancer { width: 70%; } +.cluster-balancer[data-state=up] { border-color: #8e8552; } +.cluster-instances, .cluster-stores { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); width: 100%; gap: 8px; } +.cluster-instances, .cluster-stores { position: relative; } +.cluster-instances::before, .cluster-stores::before { content: ''; position: absolute; top: -8px; left: 25%; right: 25%; border-top: 1px solid #706b4360; } +.cluster-api, .cluster-stores .cluster-node { position: relative; } +.cluster-api::before, .cluster-stores .cluster-node::before { content: ''; position: absolute; top: -9px; left: 50%; height: 8px; border-left: 1px solid #706b4360; } +.cluster-api[data-state=up] span { color: #b9d99f; } +.cluster-node[data-state=down] { background: #3b302e; border-color: #a36154; } +.cluster-node[data-state=down] span { color: #ffb2a2; } +.cluster-node[data-state=unknown] { border-style: dashed; } +.cluster-api.just-served { border-color: var(--accent); background: #48442b; box-shadow: 0 0 0 3px #ffe1350b; } +.cluster-detail { font: 10px/1.7 ui-monospace,monospace; color: #dbd4a3; min-height: 34px; margin: 13px 0 8px; overflow-wrap: anywhere; } +.cluster-section .text-button { font-size: 11px; padding: 7px 0; } +.cluster-note { font-size: 10px; line-height: 1.65; color: var(--muted); } +.cluster-demo { border-top: 1px solid var(--border); margin-top: 10px; padding-top: 12px; } +.cluster-demo summary { color: var(--accent); font-size: 11px; cursor: pointer; } +.cluster-command { display: block; font: 10px/1.7 ui-monospace,monospace; color: #dfdabe; background: #252623; border: 1px solid var(--border); padding: 10px; border-radius: 9px; overflow-wrap: anywhere; user-select: all; margin: 10px 0; } +.reaction-controls { display: flex; gap: 4px; align-items: center; flex-wrap: wrap; min-height: 25px; } +.message.mine .reaction-controls { justify-content: flex-end; } +.reaction-button, .reaction-picker { border: 1px solid #62624b; background: #30312b; color: #e6e2cd; border-radius: 16px; font-size: 12px; min-height: 26px; min-width: 32px; padding: 3px 8px; line-height: 1.4; } +.reaction-button[aria-pressed=true] { background: #ffe1351a; border-color: #b8aa4f; color: var(--accent); } +.reaction-button:hover, .reaction-picker:hover { border-color: var(--accent); } +.reaction-picker { color: var(--muted); font-size: 15px; opacity: .35; } +.message:hover .reaction-picker, .message:focus-within .reaction-picker { opacity: 1; } +.reaction-menu { display: flex; gap: 3px; background: #292a25; border: 1px solid #62624b; border-radius: 18px; padding: 3px; } +.reaction-menu button { background: transparent; border: 0; border-radius: 12px; padding: 5px 7px; font-size: 17px; } +.reaction-menu button:hover { background: #ffe13518; } +.reaction-error { font-size: 10px; color: var(--danger); margin: 0; } +@media (hover:none) { .reaction-picker { opacity: .8; } } +@media (prefers-reduced-motion:reduce) { .cluster-node { transition:none; } } diff --git a/student-tests/attachments.py b/student-tests/attachments.py new file mode 100644 index 00000000..2d5a6061 --- /dev/null +++ b/student-tests/attachments.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python3 +import sys,uuid,json,struct,zlib,concurrent.futures,time,subprocess,threading +from pathlib import Path +sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests')) +from client import Client,arguments,check,run +ROOT=Path(__file__).resolve().parents[1] +def compose(*args,input=None): + r=subprocess.run([str(ROOT/'scripts/compose.sh'),*args],input=input,capture_output=True,cwd=ROOT) + check(r.returncode==0,'Infrastructure command failed: '+r.stderr.decode()[-600:]);return r.stdout + +def sql(text): return compose('exec','-T','postgres','psql','-U','messenger','-d','messenger','-At','-c',text).decode().strip() +def main(): + args=arguments('Attachment validation, access and parallel upload') + c=Client(args.base_url,args.ca_file,timeout=100);a,b,e,chat=c.bootstrap();path='/api/v1/chats/'+chat['id']+'/attachments?filename=' + image=(ROOT/'tests/fixtures/sample.png').read_bytes() + def upload(raw=image,name='image.png',mime='image/png',status=201,actor=a): + return c.call('POST',path+name,status,actor=actor,raw=raw,headers={'Content-Type':mime},schema='Attachment' if status==201 else None) + upload(name='../evil.png',status=400);upload(name='evil%5Cfile.png',status=400);upload(name='bad%00.png',status=400) + jpeg=(ROOT/'student-tests/fixtures/sample.jpg').read_bytes() + jpg=upload(raw=jpeg,name='photo.jpg',mime='image/jpeg')['json'] + check(c.call('GET','/api/v1/attachments/'+jpg['id']+'/content',actor=b)['bytes']==jpeg,'JPEG changed') + upload(raw=b'wrong',status=415);upload(mime='image/jpeg',status=415);upload(raw=image[:25],status=415) + upload(raw=b'x'*(10485760+1),status=413);upload(actor=e,status=404) + huge=bytearray(image);huge[16:24]=struct.pack('>II',10000,10000);huge[29:33]=struct.pack('>I',zlib.crc32(huge[12:29]));upload(raw=bytes(huge),status=413) + att=upload()['json'];content='/api/v1/attachments/'+att['id'] + c.call('GET',content,404,actor=e);c.call('GET',content+'/content',404,actor=e) + c.call('GET',content+'/content?variant=absent',404,actor=b) + other=c.call('POST','/api/v1/chats',201,actor=a,body={'title':'Other','member_ids':[a['id']]},schema='Chat')['json'] + c.call('POST','/api/v1/chats/'+other['id']+'/messages',404,actor=a,body={'text':'','attachment_ids':[att['id']]},headers={'Idempotency-Key':uuid.uuid4().hex}) + key=uuid.uuid4().hex;first=c.message(a,chat,'',attachments=[att['id']],key=key)['json'] + check(c.message(a,chat,'',attachments=[att['id']],key=key)['json']==first,'attachment replay differs') + c.call('POST','/api/v1/chats/'+chat['id']+'/messages',409,actor=a,body={'text':'changed','attachment_ids':[att['id']]},headers={'Idempotency-Key':key}) + # 10 real 1024x1024 PNG uploads, synchronized start; sample cgroup memory while running. + width=1024;raw=bytearray() + import random + rng=random.Random(104) + for _ in range(width): raw+=b'\0'+rng.randbytes(width*3) + def chunk(kind,data): return struct.pack('>I',len(data))+kind+data+struct.pack('>I',zlib.crc32(kind+data)) + medium=b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('>IIBBBBB',width,width,8,2,0,0,0))+chunk(b'IDAT',zlib.compress(bytes(raw),1))+chunk(b'IEND',b'') + ids=compose('ps','-q','api').decode().split();samples=[];stop=threading.Event() + def memory(): + while not stop.is_set(): + vals=[] + for cid in ids: + out=subprocess.check_output(['docker','exec',cid,'cat','/sys/fs/cgroup/memory.current']);vals.append(int(out)) + samples.append({'at':time.time(),'bytes':vals});stop.wait(.1) + barrier=threading.Barrier(10) + def parallel(i): + barrier.wait();t=time.monotonic();upload(raw=medium,name='parallel-'+str(i)+'.png');return time.monotonic()-t + poll=threading.Thread(target=memory);poll.start();started=time.monotonic() + try: + with concurrent.futures.ThreadPoolExecutor(max_workers=10) as ex: times=list(ex.map(parallel,range(10))) + finally:stop.set();poll.join() + report={'checks':['filename','size','decoded pixels','damaged image','MIME mismatch','private chat','foreign attachment','idempotency'], + 'concurrency':10,'file_bytes':len(medium),'decoded_pixels':width*width,'seconds':time.monotonic()-started, + 'successful_uploads':10,'errors':0,'p95_seconds':sorted(times)[-1], + 'peak_api_cgroup_bytes':[max(s['bytes'][i] for s in samples) for i in range(len(ids))], + 'samples':samples,'limits':'512 MiB per API; one decoder/upload per API; 64 KiB copy buffer'} + (ROOT/'evidence/attachments.json').write_text(json.dumps(report,indent=2)+'\n') + print('PASS: attachment validation, access, replay and 10 parallel uploads') +if __name__=='__main__':run(main) diff --git a/student-tests/consistency.py b/student-tests/consistency.py new file mode 100644 index 00000000..55e6fefc --- /dev/null +++ b/student-tests/consistency.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python3 +import sys,time,json,uuid,hashlib,subprocess,socket +from pathlib import Path +sys.path.insert(0,str(Path(__file__).resolve().parent)) +from attachments import ROOT,compose,sql +sys.path.insert(0,str(ROOT/'tests')) +from client import Client,arguments,check,run + +def s3(method,key,data=b'',signed=True,bucket='messenger'): + command='curl -sS --max-time 20 -w "\\n%{http_code}" ' + if signed: command+='--aws-sigv4 aws:amz:us-east-1:s3 --user "$(cat /run/secrets/s3_access):$(cat /run/secrets/s3_secret)" ' + command+='-H x-amz-content-sha256:'+hashlib.sha256(data).hexdigest()+' -X '+method+' ' + if method=='PUT':command+='--data-binary @- ' + command+='http://s3:8333/'+bucket+'/'+key + raw=compose('exec','-T','api','sh','-c',command,input=data) + body,status=raw.rsplit(b'\n',1);return int(status),body + +def reconcile(apply=False): + args=['exec','-T','-e','RECONCILE_GRACE_SECONDS=120','api','dotnet','Messenger.Api.dll','--reconcile'] + if apply:args.append('--apply') + out=compose(*args).decode() + return json.loads(next(line for line in out.splitlines() if line.startswith('{'))) + +def main(): + args=arguments('S3/PostgreSQL failures and reconciliation') + c=Client(args.base_url,args.ca_file,timeout=100);a,b,e,chat=c.bootstrap();events=[] + image=(ROOT/'tests/fixtures/sample.png').read_bytes() + linked,_=c.attachment(a,chat);c.message(a,chat,'keep',attachments=[linked['id']]) + abandoned,_=c.attachment(a,chat) + missing,_=c.attachment(a,chat);c.message(a,chat,'missing',attachments=[missing['id']]) + key=lambda att:sql("SELECT object_key FROM attachments WHERE id='"+att['id']+"'") + linkedkey=key(linked);missingkey=key(missing) + check(s3('GET',linkedkey,signed=False)[0]==403,'bucket permits anonymous download') + check(s3('PUT','blocked',image,bucket='other-bucket')[0] in (403,404),'API credentials can write another bucket') + check(s3('DELETE',missingkey)[0]==204,'could not inject missing object') + events.append('Private bucket and scoped credentials; injected missing S3 object') + # Fail the DB write after successful S3 PUT. No production test switch is installed. + sql("CREATE FUNCTION test_attachment_failure() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.filename='injected-db-failure.png' THEN RAISE EXCEPTION 'test'; END IF; RETURN NEW; END $$; CREATE TRIGGER test_attachment_failure BEFORE INSERT ON attachments FOR EACH ROW EXECUTE FUNCTION test_attachment_failure();") + try: + c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=injected-db-failure.png',503,actor=a,raw=image,headers={'Content-Type':'image/png'}) + finally: + sql('DROP TRIGGER test_attachment_failure ON attachments; DROP FUNCTION test_attachment_failure();') + meta_missing,_=c.attachment(a,chat);c.message(a,chat,'metadata link',attachments=[meta_missing['id']]);meta_key=key(meta_missing) + sql("DELETE FROM attachments WHERE id='"+meta_missing['id']+"'") + orphan='originals/'+uuid.uuid4().hex + check(s3('PUT',orphan,image)[0]==200,'orphan injection failed') + # Partial HTTP upload is never published. + from urllib.parse import urlsplit + target=urlsplit(args.base_url);sock=socket.create_connection((target.hostname,target.port or 80)) + head=(f"POST /api/v1/chats/{chat['id']}/attachments?filename=partial.png HTTP/1.1\r\nHost: localhost\r\nAuthorization: Bearer {a['token']}\r\nContent-Type: image/png\r\nContent-Length: 100000\r\n\r\n").encode() + sock.sendall(head+image[:20]);sock.close();time.sleep(1) + check(sql("SELECT count(*) FROM attachments WHERE filename='partial.png'")=='0','partial upload was published') + # S3 outage: metadata remains, synchronous bytes/upload path is unavailable. + compose('stop','s3') + try: + # HAProxy can itself produce 503 if both readiness checks have already failed. + import urllib.request,urllib.error + deadline=time.monotonic()+10 + while True: + try: + urllib.request.urlopen(args.base_url+'/health/ready',timeout=5) + check(time.monotonic()deadline:raise + time.sleep(1) + events.append('Interrupted upload not published; DB failure after PUT leaves reconcilable orphan; S3 outage recovers') + fresh=reconcile();check(not any(x.get('key')==orphan or x.get('id') in [linked['id'],missing['id'],abandoned['id']] for x in fresh['actions']),'fresh attachment was selected') + print('Fresh records protected; waiting for the 120-second safety interval',flush=True) + created=time.monotonic() + # Wait for server-side LastModified as well as metadata age; timestamps are not forged. + remaining=max(0,135-(time.time()-__import__('datetime').datetime.fromisoformat(linked['created_at'].replace('Z','+00:00')).timestamp())) + while remaining>0: + time.sleep(min(20,remaining));remaining-=min(20,remaining) + dry=reconcile();check(s3('GET',orphan)[0]==200,'dry-run mutated S3') + kinds={x['kind'] for x in dry['actions']};check({'orphan','missing','unreferenced'}<=kinds,'not all inconsistencies detected') + apply=reconcile(True) + check(s3('GET',orphan)[0]==404,'orphan not deleted') + check(sql("SELECT count(*) FROM attachments WHERE id='"+abandoned['id']+"'")=='0','abandoned metadata left') + check(sql("SELECT status FROM attachments WHERE id='"+missing['id']+"'")=='missing','missing original not marked') + check(s3('GET',linkedkey)[1]==image,'used original removed or changed') + check(s3('GET',meta_key)[1]==image,'used original without metadata was removed') + new,_=c.attachment(a,chat);freshkey=key(new) + again=reconcile(True) + check(s3('GET',freshkey)[0]==200,'fresh original removed') + check(sql("SELECT count(*) FROM attachments WHERE id='"+linked['id']+"'")=='1','used metadata removed') + check(not any(x['kind'] in ('orphan','unreferenced') for x in again['actions']),'second run has remaining garbage') + scan_samples=[reconcile() for _ in range(3)] + report={'scan_samples':scan_samples,'checks':events+['dry-run is read-only','old orphan and unused data removed','referenced missing marked, link retained','fresh and referenced originals preserved, including missing metadata','repeat is idempotent'], + 'dry_run':dry,'apply':apply,'repeat':again,'safety_wait_seconds':time.monotonic()-created,'assumption':'exclusive PostgreSQL advisory gate; all app writers use shared gate; 120s minimum grace; no automatic restore without backup'} + h=hashlib.sha256() + for source in sorted((ROOT/'src/Messenger.Api').rglob('*.cs')): + if 'bin' in source.parts or 'obj' in source.parts:continue + h.update(str(source.relative_to(ROOT/'src/Messenger.Api')).encode());h.update(source.read_bytes()) + report['source_sha256']=h.hexdigest() + report['environment']=subprocess.check_output(['docker','info','--format','{{.OSType}} {{.Architecture}} {{.NCPU}} CPUs {{.MemTotal}} bytes RAM']).decode().strip() + (ROOT/'evidence/consistency.json').write_text(json.dumps(report,indent=2)+'\n') + print('PASS: storage failures, dry-run, safe repair, repeat and protected files') +if __name__=='__main__':run(main) diff --git a/student-tests/fixtures/sample.jpg b/student-tests/fixtures/sample.jpg new file mode 100644 index 00000000..2b89dbf1 Binary files /dev/null and b/student-tests/fixtures/sample.jpg differ