ЛР 4 - БВТ-2302 - Каменский - на 5 #97
@@ -16,5 +16,7 @@ backups
|
||||
.venv
|
||||
__pycache__
|
||||
node_modules
|
||||
**/bin
|
||||
**/obj
|
||||
evidence
|
||||
.DS_Store
|
||||
|
||||
@@ -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/
|
||||
|
||||
@@ -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"]
|
||||
@@ -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)"
|
||||
|
||||
|
||||
@@ -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/<UUID без разделителей>.
|
||||
|
||||
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 использован при реализации и проверках.
|
||||
|
||||
@@ -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:
|
||||
@@ -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 остаются точками отказа.
|
||||
@@ -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 использован при реализации и проверках.
|
||||
@@ -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"
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
@@ -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
|
||||
@@ -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.
|
||||
@@ -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"
|
||||
]
|
||||
}
|
||||
@@ -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
|
||||
|
After Width: | Height: | Size: 53 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 15 KiB |
@@ -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.
|
||||
@@ -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
|
||||
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
root="$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)"
|
||||
exec docker compose --project-name mtusi2026lab4 --project-directory "$root" "$@"
|
||||
@@ -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')
|
||||
@@ -0,0 +1,3 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
exec python3 "$(dirname "$0")/init-secrets.py"
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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);
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace Messenger.Api.Contracts;
|
||||
|
||||
public sealed record ChatCursor(
|
||||
string Scope,
|
||||
string CreatedAt,
|
||||
Guid Id
|
||||
);
|
||||
@@ -0,0 +1,3 @@
|
||||
namespace Messenger.Api.Contracts;
|
||||
|
||||
public sealed record ChatDto(Guid Id, string Title, List<Guid> MemberIds, string CreatedAt);
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace Messenger.Api.Contracts;
|
||||
|
||||
public sealed record ChatPreviewDto(
|
||||
Guid Id, string Title, List<Guid> MemberIds, string CreatedAt, MessageDto? LastMessage);
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace Messenger.Api.Contracts;
|
||||
|
||||
public sealed record CreateChatRequest(
|
||||
string? Title,
|
||||
List<Guid>? MemberIds
|
||||
);
|
||||
@@ -0,0 +1,8 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Messenger.Api.Contracts;
|
||||
|
||||
public sealed record CreateMessageRequest(
|
||||
string? Text,
|
||||
JsonElement AttachmentIds = default
|
||||
);
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace Messenger.Api.Contracts;
|
||||
|
||||
public sealed record CreateUserRequest(
|
||||
string? Username,
|
||||
string? DisplayName,
|
||||
string? Password
|
||||
);
|
||||
@@ -0,0 +1,3 @@
|
||||
namespace Messenger.Api.Contracts;
|
||||
|
||||
public sealed record MessageDto(Guid Id, Guid ChatId, Guid SenderId, string Text, string CreatedAt, Guid[] AttachmentIds);
|
||||
@@ -0,0 +1,3 @@
|
||||
namespace Messenger.Api.Contracts;
|
||||
|
||||
public sealed record SessionDto(string Token, string TokenType, string ExpiresAt, UserDto User);
|
||||
@@ -0,0 +1,3 @@
|
||||
namespace Messenger.Api.Contracts;
|
||||
|
||||
public sealed record UserDto(Guid Id, string Username, string DisplayName, string CreatedAt);
|
||||
@@ -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<bool> 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<UserEntity?> 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<UserEntity?> 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<List<UserEntity>> 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<UserEntity>();
|
||||
while (await reader.ReadAsync()) result.Add(ReadUser(reader));
|
||||
return result;
|
||||
}
|
||||
|
||||
public async Task<UserEntity> 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<SessionEntity?> 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<bool> 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<ChatEntity?> CreateChatAsync(string title, List<Guid> 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<ChatEntity?> 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<List<ChatEntity>> 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<ChatEntity>();
|
||||
while (await reader.ReadAsync()) result.Add(ReadChat(reader));
|
||||
return result;
|
||||
}
|
||||
|
||||
public async Task<List<MessageEntity>> 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<MessageEntity>();
|
||||
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<Guid[]>(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<Guid[]>(3).ToList(), reader.GetDateTime(2));
|
||||
}
|
||||
@@ -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"));
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
using Messenger.Api.Contracts;
|
||||
using Npgsql;
|
||||
|
||||
namespace Messenger.Api.Data;
|
||||
|
||||
public sealed partial class AppDatabase
|
||||
{
|
||||
public async Task<List<ChatPreviewDto>> 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<ChatPreviewDto>();
|
||||
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<Guid[]>(8));
|
||||
result.Add(new ChatPreviewDto(id, reader.GetString(1), reader.GetFieldValue<Guid[]>(3).ToList(),
|
||||
reader.GetDateTime(2).ToString("O"), message));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace Messenger.Api.Data.Entities;
|
||||
|
||||
public sealed record ChatEntity(Guid Id, string Title, List<Guid> MemberIds, DateTime CreatedAt)
|
||||
{
|
||||
public Contracts.ChatDto ToDto() => new(Id, Title, MemberIds, CreatedAt.ToString("O"));
|
||||
}
|
||||
@@ -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 ?? []);
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
namespace Messenger.Api.Data.Entities;
|
||||
|
||||
public sealed record SessionEntity(Guid UserId, DateTime ExpiresAt);
|
||||
@@ -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"));
|
||||
}
|
||||
@@ -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<MessageEntity?> 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<byte[]>(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<Guid[]>(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;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
@@ -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);
|
||||
@@ -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)
|
||||
);
|
||||
@@ -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);
|
||||
@@ -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<bool> 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<List<ReactionDto>> 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<ReactionDto>();
|
||||
while (await reader.ReadAsync())
|
||||
items.Add(new(reader.GetGuid(0), reader.GetString(1), reader.GetInt32(2), reader.GetBoolean(3)));
|
||||
return items;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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<CreateChatRequest>(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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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<CreateMessageRequest>(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<Guid>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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<CreateUserRequest>(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;
|
||||
}
|
||||
}
|
||||
@@ -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<ClusterPresence> 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<Node> 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<Snapshot> 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, []); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace Messenger.Api.Infrastructure;
|
||||
|
||||
public sealed class InstanceIdentity
|
||||
{
|
||||
public string Id { get; } = Guid.NewGuid().ToString("N");
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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<RedisSessionCache> 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<Entry?> 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<Entry>(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");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<bool> 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();
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="Data/Migrations/*.sql" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AWSSDK.S3" Version="4.0.0" />
|
||||
<PackageReference Include="Isopoh.Cryptography.Argon2" Version="2.0.0" />
|
||||
<PackageReference Include="Npgsql" Version="9.0.5" />
|
||||
<PackageReference Include="SkiaSharp" Version="3.119.1" />
|
||||
<PackageReference Include="SkiaSharp.NativeAssets.Linux.NoDependencies" Version="3.119.1" />
|
||||
<PackageReference Include="StackExchange.Redis" Version="2.8.58" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -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<ExceptionHandlingMiddleware> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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<ILoggerFactory>()
|
||||
.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"]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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<InstanceIdentity>();
|
||||
builder.Services.AddSingleton<ReadinessState>();
|
||||
builder.Services.Configure<HostOptions>(options => options.ShutdownTimeout = TimeSpan.FromSeconds(8));
|
||||
builder.Services.AddSingleton<AppDatabase>();
|
||||
builder.Services.AddSingleton<S3Storage>();
|
||||
builder.Services.AddSingleton<AttachmentService>();
|
||||
builder.Services.AddSingleton<AttachmentReconciler>();
|
||||
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<IConnectionMultiplexer>(await ConnectionMultiplexer.ConnectAsync(redisOptions));
|
||||
builder.Services.AddSingleton<RedisSessionCache>();
|
||||
builder.Services.AddSingleton<PasswordService>();
|
||||
builder.Services.AddSingleton<UserService>();
|
||||
builder.Services.AddSingleton<SessionService>();
|
||||
builder.Services.AddSingleton<ChatService>();
|
||||
builder.Services.AddSingleton<MessageService>();
|
||||
builder.Services.AddSingleton<ClusterPresence>();
|
||||
builder.Services.AddHostedService(services => services.GetRequiredService<ClusterPresence>());
|
||||
|
||||
var app = builder.Build();
|
||||
if(args.Contains("--reconcile"))
|
||||
{
|
||||
await app.Services.GetRequiredService<AttachmentReconciler>().RunAsync(args.Contains("--apply"));
|
||||
await app.DisposeAsync();
|
||||
return;
|
||||
}
|
||||
app.Lifetime.ApplicationStopping.Register(app.Services.GetRequiredService<ReadinessState>().Stop);
|
||||
|
||||
app.UseMiddleware<RequestIdMiddleware>();
|
||||
app.UseMiddleware<InstanceMiddleware>();
|
||||
app.UseMiddleware<RequestLoggingMiddleware>();
|
||||
app.UseMiddleware<ExceptionHandlingMiddleware>();
|
||||
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();
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<T>(HttpContext context)
|
||||
{
|
||||
if (!context.Request.HasJsonContentType())
|
||||
return (default, ApiError(context, 400, "invalid_request", "Требуется application/json"));
|
||||
|
||||
try
|
||||
{
|
||||
var value = await context.Request.ReadFromJsonAsync<T>();
|
||||
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
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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<object>(); 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}));
|
||||
}
|
||||
}
|
||||
@@ -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<AttachmentDto> 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); }
|
||||
}
|
||||
}
|
||||
@@ -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<ChatDto?> CreateAsync(string title, List<Guid> memberIds) =>
|
||||
(await database.CreateChatAsync(title, memberIds))?.ToDto();
|
||||
|
||||
public async Task<ChatDto?> FindForMemberAsync(Guid chatId, Guid userId) =>
|
||||
(await database.FindChatForMemberAsync(chatId, userId))?.ToDto();
|
||||
|
||||
public async Task<List<ChatDto>> ListAsync(Guid userId, DateTime? cursorTime, Guid? cursorId, int count) =>
|
||||
(await database.ListChatsAsync(userId, cursorTime, cursorId, count)).Select(chat => chat.ToDto()).ToList();
|
||||
}
|
||||
@@ -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<ChatCursor>(json);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<MessageDto?> CreateAsync(Guid chatId, Guid senderId, string text, string key, Guid[] attachmentIds) =>
|
||||
(await database.CreateMessageOnceAsync(chatId, senderId, text, key, attachmentIds))?.ToDto();
|
||||
|
||||
public async Task<List<MessageDto>> 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();
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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<SessionDto?> 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<bool> 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));
|
||||
}
|
||||
@@ -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<List<UserDto>> ListForChatAsync(Guid chatId) =>
|
||||
(await database.ListChatUsersAsync(chatId)).Select(user => user.ToDto()).ToList();
|
||||
|
||||
public async Task<UserDto?> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
}
|
||||
@@ -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; }
|
||||
@@ -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();}
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="320" height="280" viewBox="0 0 320 280" fill="none" stroke="#FFE135" stroke-opacity=".035" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M31 32h24a7 7 0 0 1 7 7v12a7 7 0 0 1-7 7H42l-9 6 2-6h-4a7 7 0 0 1-7-7V39a7 7 0 0 1 7-7Z"/>
|
||||
<g transform="translate(224 45) rotate(12)"><path d="M-16 0Q0-26 16 0Z M-4 1v16q4 4 8 0V1"/><path d="m-5-6 2-2m8 2 2 1"/></g>
|
||||
<g transform="translate(112 161) rotate(-25)"><path d="M0 17Q-20-3 4-18Q24 2 0 17ZM1 21 4-10M3 6l9-5M3-1l-6-6"/></g>
|
||||
<path d="M235 205a9 9 0 0 1 12-9 12 12 0 0 1 23 1 8 8 0 0 1 0 16h-30a6 6 0 0 1-5-8Z"/>
|
||||
<circle cx="149" cy="59" r="2"/><circle cx="43" cy="238" r="2"/><path d="M181 234h6m-3-3v6M290 139h6m-3-3v6"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 763 B |
|
After Width: | Height: | Size: 26 KiB |
|
After Width: | Height: | Size: 31 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 55 KiB |
@@ -0,0 +1,63 @@
|
||||
<svg class="spirit-svg" viewBox="0 0 300 300" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" stroke="none" stroke-linecap="round" stroke-linejoin="round">
|
||||
<defs>
|
||||
<linearGradient id="kolo-skin" x1="0" y1="0" x2="1" y2="1"><stop stop-color="#b2b17a"/><stop offset="1" stop-color="#7b814a"/></linearGradient>
|
||||
<linearGradient id="kolo-cloth" x1="0" y1="0" x2="1" y2="1"><stop stop-color="#916c46"/><stop offset="1" stop-color="#614a34"/></linearGradient>
|
||||
</defs>
|
||||
<ellipse cx="149" cy="281" rx="91" ry="9" fill="#131710" opacity=".5"/>
|
||||
<g class="spirit-motion"><g class="spirit-lean">
|
||||
<path d="M112 209Q89 216 83 253L77 274Q106 288 149 283Q190 290 223 274L214 252Q209 218 186 209" fill="url(#kolo-cloth)" stroke="#4d432e" stroke-width="3"/>
|
||||
<path d="M106 221Q91 243 99 266L121 255L135 279L153 264L171 280L188 257L205 271L201 233" fill="#a08050" opacity=".45"/>
|
||||
<path d="M111 200Q95 207 96 233Q150 257 203 232Q200 208 185 200" fill="url(#kolo-skin)" stroke="#5d653c" stroke-width="3"/>
|
||||
<path d="M109 217L190 253" stroke="#59452f" stroke-width="12"/><path d="M109 215L190 251" stroke="#aa8557" stroke-width="4"/>
|
||||
<path d="M179 252Q169 257 177 278Q188 286 202 277L204 258Q191 249 179 252" fill="#83613e" stroke="#57442f" stroke-width="3"/>
|
||||
<path d="M90 253Q144 267 211 253" fill="none" stroke="#bc965e" stroke-width="5" stroke-linecap="round"/>
|
||||
<g class="kolo-head">
|
||||
<g class="kolo-ear kolo-ear-left">
|
||||
<path d="M108 112Q77 84 27 91L45 109L52 101L57 119Q73 156 111 157" fill="#91965b" stroke="#555d37" stroke-width="3.5"/>
|
||||
<path d="M91 123L50 106Q66 137 97 143" fill="#686f43"/><path d="M83 121L63 113" stroke="#b7b47c" stroke-width="4"/>
|
||||
<path d="M62 139C40 137 40 167 59 165C69 164 73 156 70 150" fill="none" stroke="#b48c47" stroke-width="7"/>
|
||||
<path d="M55 141Q44 147 49 157" fill="none" stroke="#e4c275" stroke-width="2.5"/>
|
||||
</g>
|
||||
<g class="kolo-ear kolo-ear-right">
|
||||
<path d="M195 112Q224 89 275 93Q279 114 263 121Q267 110 258 109L245 135Q226 158 194 155" fill="#91965b" stroke="#555d37" stroke-width="3.5"/>
|
||||
<path d="M209 124L259 102Q249 132 211 142" fill="#686f43"/><path d="M220 121L246 109" stroke="#b7b47c" stroke-width="4"/>
|
||||
</g>
|
||||
<path d="M96 120Q89 87 116 77Q151 57 188 79Q215 93 209 131L204 169Q197 209 152 216Q107 212 96 174Z" fill="url(#kolo-skin)" stroke="#555d37" stroke-width="3.5"/>
|
||||
<path d="M101 104L94 92L111 93L109 80L123 85L135 72L145 78L163 68L174 79L190 76L191 88L205 89L201 101" fill="#707c43"/>
|
||||
<path d="M112 86L116 78M129 81L134 73M179 81L180 72M193 90L201 83" stroke="#b0b57a" stroke-width="4"/>
|
||||
<g class="kolo-mushrooms" stroke="#68513a" stroke-width="3" stroke-linejoin="round">
|
||||
<path d="M121 83L112 56M152 76L155 38M181 85L193 61" fill="none" stroke="#b6a375" stroke-width="8"/>
|
||||
<path d="M98 56Q111 34 125 55Q113 61 98 56Z" fill="#bd8b51"/>
|
||||
<path d="M137 38Q154 10 174 38Q155 47 137 38Z" fill="#c49457"/>
|
||||
<path d="M179 61Q194 37 208 61Q193 66 179 61Z" fill="#b48048"/>
|
||||
<g fill="#edd2a0" stroke="none" opacity=".7"><ellipse cx="151" cy="33" rx="2.5" ry="1.8"/><circle cx="164" cy="35" r="1.7"/><circle cx="117" cy="52" r="1.5"/><ellipse cx="198" cy="57" rx="2" ry="1.5"/></g>
|
||||
<path d="M146 34Q152 26 160 29M106 52L111 47M190 56L195 51" fill="none" stroke="#e2bd7e" stroke-width="3"/>
|
||||
</g>
|
||||
<path d="M110 114Q122 99 137 109M165 109Q184 98 196 113" fill="none" stroke="#6b743f" stroke-width="10" stroke-linecap="round"/>
|
||||
<path d="M114 109Q126 102 137 107M166 107Q181 101 192 108" fill="none" stroke="#bec18a" stroke-width="3" stroke-linecap="round"/>
|
||||
<g class="spirit-face">
|
||||
<ellipse cx="116" cy="164" rx="10" ry="5" fill="#c9a277" opacity=".32"/>
|
||||
<ellipse cx="188" cy="164" rx="9" ry="5" fill="#c9a277" opacity=".32"/>
|
||||
<g class="spirit-eye spirit-eye-left"><path d="M107 131Q120 116 138 129Q133 150 119 147Q108 145 107 131" fill="#e6dab3" stroke="#687044" stroke-width="2"/><g class="spirit-pupil"><ellipse cx="125" cy="133" rx="8" ry="10" fill="#885d30"/><ellipse cx="127" cy="134" rx="4.7" ry="7" fill="#292b20"/><circle cx="129" cy="129" r="2.3" fill="#fff7df"/></g></g>
|
||||
<g class="spirit-eye spirit-eye-right"><path d="M165 129Q182 116 195 131Q194 147 181 148Q167 148 165 129" fill="#e6dab3" stroke="#687044" stroke-width="2"/><g class="spirit-pupil"><ellipse cx="179" cy="133" rx="8" ry="10" fill="#885d30"/><ellipse cx="181" cy="134" rx="4.7" ry="7" fill="#292b20"/><circle cx="183" cy="129" r="2.3" fill="#fff7df"/></g></g>
|
||||
<path d="M146 133Q141 149 138 154Q151 168 166 154L159 139" fill="#a38d52" stroke="#7f7944" stroke-width="2"/>
|
||||
<path d="M144 151Q152 146 159 152" fill="none" stroke="#d1b57b" stroke-width="4" stroke-linecap="round"/>
|
||||
<path d="M107 155Q115 162 128 158M178 160Q189 163 197 155" fill="none" stroke="#6e7843" stroke-width="2" stroke-linecap="round"/>
|
||||
<path class="spirit-smile" d="M122 179Q149 192 180 174Q168 197 144 193Q128 190 122 179" fill="#4f5935"/>
|
||||
<path class="kolo-tooth" d="M167 181L174 178L172 185L167 185Z" fill="#ede2b9"/>
|
||||
<path d="M135 201Q148 205 161 200" fill="none" stroke="#bcc18a" stroke-width="3" stroke-linecap="round"/>
|
||||
<ellipse class="spirit-gasp" cx="151" cy="183" rx="6" ry="8" fill="#4f5935"/>
|
||||
</g>
|
||||
<circle cx="111" cy="93" r="3" fill="#c0bf82"/><circle cx="188" cy="100" r="3" fill="#b1b77b"/>
|
||||
</g>
|
||||
<g class="spirit-hand spirit-hand-left" stroke="#5d653c" stroke-width="2.5" stroke-linejoin="round">
|
||||
<path d="M111 218Q89 231 77 211L70 194Q67 187 72 185Q76 183 80 193L84 199L80 179Q79 173 84 173Q89 172 91 181L94 196L95 179Q96 172 101 175L104 199Q108 192 113 194Q118 197 110 207Z" fill="#9ca56a"/>
|
||||
<path d="M79 205Q89 211 99 204" fill="none" stroke="#bfc68b" stroke-width="3"/>
|
||||
</g>
|
||||
<g class="spirit-hand spirit-hand-right" stroke="#5d653c" stroke-width="2.5" stroke-linejoin="round">
|
||||
<path d="M191 218Q213 231 225 211L232 194Q235 187 230 185Q226 183 222 193L218 199L222 179Q223 173 218 173Q213 172 211 181L208 196L207 179Q206 172 201 175L198 199Q194 192 189 194Q184 197 192 207Z" fill="#9ca56a"/>
|
||||
<path d="M203 214L220 220L215 233L198 227Z" fill="#d5c5a2" stroke="#a99b7e" stroke-width="2"/>
|
||||
<path d="M202 218L217 225M200 223L215 230" stroke="#f0dfba" stroke-width="2"/>
|
||||
</g>
|
||||
</g></g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 6.3 KiB |
@@ -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; } }
|
||||
@@ -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='Изображение недоступно. Закройте просмотр и повторите загрузку.';}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
@@ -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 */ }
|
||||
@@ -0,0 +1,169 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="theme-color" content="#262626">
|
||||
<meta name="description" content="n1k0der - место для ваших разговоров.">
|
||||
<title>n1k0der · Мессенджер</title>
|
||||
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 40 40'%3E%3Crect width='40' height='40' rx='12' fill='%23262626'/%3E%3Cpath d='M11 14h18M11 20h13M11 26h8' stroke='%23FFE135' stroke-width='3' stroke-linecap='round'/%3E%3C/svg%3E">
|
||||
<link rel="stylesheet" href="/app.css">
|
||||
<link rel="stylesheet" href="/polish.css">
|
||||
<link rel="stylesheet" href="/attachments.css">
|
||||
<link rel="stylesheet" href="/showcase.css">
|
||||
<script type="module" src="/app.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<svg class="svg-sprite" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
|
||||
<symbol id="i-plus" viewBox="0 0 24 24"><path d="M12 5v14M5 12h14"/></symbol>
|
||||
<symbol id="i-send" viewBox="0 0 24 24"><path d="m21 3-6.5 18-4-7.5L3 9.5 21 3ZM10.5 13.5 21 3"/></symbol>
|
||||
<symbol id="i-chat" viewBox="0 0 24 24"><path d="M7 4h10a4 4 0 0 1 4 4v6a4 4 0 0 1-4 4H9l-6 3V8a4 4 0 0 1 4-4Z"/><path d="M8 9h8M8 13h5"/></symbol>
|
||||
<symbol id="i-arrow" viewBox="0 0 24 24"><path d="m10 5-7 7 7 7M3 12h18"/></symbol>
|
||||
<symbol id="i-arrow-up-right" viewBox="0 0 24 24"><path d="M6 18 18 6M6 6h12v12"/></symbol>
|
||||
<symbol id="i-search" viewBox="0 0 24 24"><circle cx="10.5" cy="10.5" r="6.5"/><path d="m16 16 4.5 4.5"/></symbol>
|
||||
<symbol id="i-refresh" viewBox="0 0 24 24"><path d="M20 5v5h-5M4 19v-5h5M5.5 8a7 7 0 0 1 11.7-3L20 8M4 16l2.8 3a7 7 0 0 0 11.7-3"/></symbol>
|
||||
<symbol id="i-exit" viewBox="0 0 24 24"><path d="M9 4H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h4M10 12h11m-4-4 4 4-4 4"/></symbol>
|
||||
<symbol id="i-copy" viewBox="0 0 24 24"><rect x="8" y="8" width="12" height="12" rx="3"/><path d="M16 8V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h3"/></symbol>
|
||||
<symbol id="i-close" viewBox="0 0 24 24"><path d="m6 6 12 12M18 6 6 18"/></symbol>
|
||||
<symbol id="i-users" viewBox="0 0 24 24"><circle cx="9" cy="8" r="3"/><path d="M3 20v-2a6 6 0 0 1 12 0v2M16 5a3 3 0 0 1 0 6M18 15a5 5 0 0 1 3 5"/></symbol>
|
||||
<symbol id="i-eye" viewBox="0 0 24 24"><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/></symbol>
|
||||
<symbol id="i-eye-off" viewBox="0 0 24 24"><path d="m3 3 18 18M9.5 5.3A12 12 0 0 1 12 5c6.5 0 10 7 10 7a18 18 0 0 1-3.2 4.1M6.4 6.4A20 20 0 0 0 2 12s3.5 7 10 7a12 12 0 0 0 5.1-1.2M10 10a3 3 0 0 0 4 4"/></symbol>
|
||||
<symbol id="i-code" viewBox="0 0 24 24"><path d="m7 7-5 5 5 5m10-10 5 5-5 5M14 4l-4 16"/></symbol>
|
||||
</svg>
|
||||
|
||||
<section id="auth-screen" class="auth-layout">
|
||||
<div class="intro">
|
||||
<a class="brand" href="/" aria-label="n1k0der, главная"><span class="brand-mark"><i></i><i></i><i></i></span>n1k0der<span class="brand-dot">.</span></a>
|
||||
<div class="intro-copy"><h1>Место для<br> ваших<br> <em>разговоров.</em></h1></div>
|
||||
<div id="mascot-stage" class="mascot-stage" aria-hidden="true" data-mood="idle">
|
||||
<div class="mascot-conversation"><div class="mascot-bubble mascot-bubble-filled"><span></span><span></span><span></span></div><div class="mascot-bubble mascot-bubble-outline"><i></i><i></i></div></div>
|
||||
<svg class="spirit-svg" viewBox="0 0 300 300" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" stroke="none" stroke-linecap="round" stroke-linejoin="round">
|
||||
<defs>
|
||||
<linearGradient id="kolo-skin" x1="0" y1="0" x2="1" y2="1"><stop stop-color="#b2b17a"/><stop offset="1" stop-color="#7b814a"/></linearGradient>
|
||||
<linearGradient id="kolo-cloth" x1="0" y1="0" x2="1" y2="1"><stop stop-color="#916c46"/><stop offset="1" stop-color="#614a34"/></linearGradient>
|
||||
</defs>
|
||||
<ellipse cx="149" cy="281" rx="91" ry="9" fill="#131710" opacity=".5"/>
|
||||
<g class="spirit-motion"><g class="spirit-lean">
|
||||
<path d="M112 209Q89 216 83 253L77 274Q106 288 149 283Q190 290 223 274L214 252Q209 218 186 209" fill="url(#kolo-cloth)" stroke="#4d432e" stroke-width="3"/>
|
||||
<path d="M106 221Q91 243 99 266L121 255L135 279L153 264L171 280L188 257L205 271L201 233" fill="#a08050" opacity=".45"/>
|
||||
<path d="M111 200Q95 207 96 233Q150 257 203 232Q200 208 185 200" fill="url(#kolo-skin)" stroke="#5d653c" stroke-width="3"/>
|
||||
<path d="M109 217L190 253" stroke="#59452f" stroke-width="12"/><path d="M109 215L190 251" stroke="#aa8557" stroke-width="4"/>
|
||||
<path d="M179 252Q169 257 177 278Q188 286 202 277L204 258Q191 249 179 252" fill="#83613e" stroke="#57442f" stroke-width="3"/>
|
||||
<path d="M90 253Q144 267 211 253" fill="none" stroke="#bc965e" stroke-width="5" stroke-linecap="round"/>
|
||||
<g class="kolo-head">
|
||||
<g class="kolo-ear kolo-ear-left">
|
||||
<path d="M108 112Q77 84 27 91L45 109L52 101L57 119Q73 156 111 157" fill="#91965b" stroke="#555d37" stroke-width="3.5"/>
|
||||
<path d="M91 123L50 106Q66 137 97 143" fill="#686f43"/><path d="M83 121L63 113" stroke="#b7b47c" stroke-width="4"/>
|
||||
<path d="M62 139C40 137 40 167 59 165C69 164 73 156 70 150" fill="none" stroke="#b48c47" stroke-width="7"/>
|
||||
<path d="M55 141Q44 147 49 157" fill="none" stroke="#e4c275" stroke-width="2.5"/>
|
||||
</g>
|
||||
<g class="kolo-ear kolo-ear-right">
|
||||
<path d="M195 112Q224 89 275 93Q279 114 263 121Q267 110 258 109L245 135Q226 158 194 155" fill="#91965b" stroke="#555d37" stroke-width="3.5"/>
|
||||
<path d="M209 124L259 102Q249 132 211 142" fill="#686f43"/><path d="M220 121L246 109" stroke="#b7b47c" stroke-width="4"/>
|
||||
</g>
|
||||
<path d="M96 120Q89 87 116 77Q151 57 188 79Q215 93 209 131L204 169Q197 209 152 216Q107 212 96 174Z" fill="url(#kolo-skin)" stroke="#555d37" stroke-width="3.5"/>
|
||||
<path d="M101 104L94 92L111 93L109 80L123 85L135 72L145 78L163 68L174 79L190 76L191 88L205 89L201 101" fill="#707c43"/>
|
||||
<path d="M112 86L116 78M129 81L134 73M179 81L180 72M193 90L201 83" stroke="#b0b57a" stroke-width="4"/>
|
||||
<g class="kolo-mushrooms" stroke="#68513a" stroke-width="3" stroke-linejoin="round">
|
||||
<path d="M121 83L112 56M152 76L155 38M181 85L193 61" fill="none" stroke="#b6a375" stroke-width="8"/>
|
||||
<path d="M98 56Q111 34 125 55Q113 61 98 56Z" fill="#bd8b51"/>
|
||||
<path d="M137 38Q154 10 174 38Q155 47 137 38Z" fill="#c49457"/>
|
||||
<path d="M179 61Q194 37 208 61Q193 66 179 61Z" fill="#b48048"/>
|
||||
<g fill="#edd2a0" stroke="none" opacity=".7"><ellipse cx="151" cy="33" rx="2.5" ry="1.8"/><circle cx="164" cy="35" r="1.7"/><circle cx="117" cy="52" r="1.5"/><ellipse cx="198" cy="57" rx="2" ry="1.5"/></g>
|
||||
<path d="M146 34Q152 26 160 29M106 52L111 47M190 56L195 51" fill="none" stroke="#e2bd7e" stroke-width="3"/>
|
||||
</g>
|
||||
<path d="M110 114Q122 99 137 109M165 109Q184 98 196 113" fill="none" stroke="#6b743f" stroke-width="10" stroke-linecap="round"/>
|
||||
<path d="M114 109Q126 102 137 107M166 107Q181 101 192 108" fill="none" stroke="#bec18a" stroke-width="3" stroke-linecap="round"/>
|
||||
<g class="spirit-face">
|
||||
<ellipse cx="116" cy="164" rx="10" ry="5" fill="#c9a277" opacity=".32"/>
|
||||
<ellipse cx="188" cy="164" rx="9" ry="5" fill="#c9a277" opacity=".32"/>
|
||||
<g class="spirit-eye spirit-eye-left"><path d="M107 131Q120 116 138 129Q133 150 119 147Q108 145 107 131" fill="#e6dab3" stroke="#687044" stroke-width="2"/><g class="spirit-pupil"><ellipse cx="125" cy="133" rx="8" ry="10" fill="#885d30"/><ellipse cx="127" cy="134" rx="4.7" ry="7" fill="#292b20"/><circle cx="129" cy="129" r="2.3" fill="#fff7df"/></g></g>
|
||||
<g class="spirit-eye spirit-eye-right"><path d="M165 129Q182 116 195 131Q194 147 181 148Q167 148 165 129" fill="#e6dab3" stroke="#687044" stroke-width="2"/><g class="spirit-pupil"><ellipse cx="179" cy="133" rx="8" ry="10" fill="#885d30"/><ellipse cx="181" cy="134" rx="4.7" ry="7" fill="#292b20"/><circle cx="183" cy="129" r="2.3" fill="#fff7df"/></g></g>
|
||||
<path d="M146 133Q141 149 138 154Q151 168 166 154L159 139" fill="#a38d52" stroke="#7f7944" stroke-width="2"/>
|
||||
<path d="M144 151Q152 146 159 152" fill="none" stroke="#d1b57b" stroke-width="4" stroke-linecap="round"/>
|
||||
<path d="M107 155Q115 162 128 158M178 160Q189 163 197 155" fill="none" stroke="#6e7843" stroke-width="2" stroke-linecap="round"/>
|
||||
<path class="spirit-smile" d="M122 179Q149 192 180 174Q168 197 144 193Q128 190 122 179" fill="#4f5935"/>
|
||||
<path class="kolo-tooth" d="M167 181L174 178L172 185L167 185Z" fill="#ede2b9"/>
|
||||
<path d="M135 201Q148 205 161 200" fill="none" stroke="#bcc18a" stroke-width="3" stroke-linecap="round"/>
|
||||
<ellipse class="spirit-gasp" cx="151" cy="183" rx="6" ry="8" fill="#4f5935"/>
|
||||
</g>
|
||||
<circle cx="111" cy="93" r="3" fill="#c0bf82"/><circle cx="188" cy="100" r="3" fill="#b1b77b"/>
|
||||
</g>
|
||||
<g class="spirit-hand spirit-hand-left" stroke="#5d653c" stroke-width="2.5" stroke-linejoin="round">
|
||||
<path d="M111 218Q89 231 77 211L70 194Q67 187 72 185Q76 183 80 193L84 199L80 179Q79 173 84 173Q89 172 91 181L94 196L95 179Q96 172 101 175L104 199Q108 192 113 194Q118 197 110 207Z" fill="#9ca56a"/>
|
||||
<path d="M79 205Q89 211 99 204" fill="none" stroke="#bfc68b" stroke-width="3"/>
|
||||
</g>
|
||||
<g class="spirit-hand spirit-hand-right" stroke="#5d653c" stroke-width="2.5" stroke-linejoin="round">
|
||||
<path d="M191 218Q213 231 225 211L232 194Q235 187 230 185Q226 183 222 193L218 199L222 179Q223 173 218 173Q213 172 211 181L208 196L207 179Q206 172 201 175L198 199Q194 192 189 194Q184 197 192 207Z" fill="#9ca56a"/>
|
||||
<path d="M203 214L220 220L215 233L198 227Z" fill="#d5c5a2" stroke="#a99b7e" stroke-width="2"/>
|
||||
<path d="M202 218L217 225M200 223L215 230" stroke="#f0dfba" stroke-width="2"/>
|
||||
</g>
|
||||
</g></g>
|
||||
</svg>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
<div class="auth-side">
|
||||
<div class="auth-card">
|
||||
<div class="auth-switch" aria-label="Выберите действие"><button id="tab-login" class="active" type="button" aria-pressed="true">Вход</button><button id="tab-register" type="button" aria-pressed="false">Регистрация</button></div>
|
||||
<div id="login-panel"><h2>С возвращением.</h2>
|
||||
<form id="login-form"><label>Имя пользователя<input id="login-username" name="username" autocomplete="username" placeholder="например, n1k0der" pattern="[a-z0-9_]{3,32}" required autocapitalize="none" spellcheck="false"></label><label>Пароль<span class="password-field"><input id="login-password" aria-label="Пароль" name="password" type="password" autocomplete="current-password" placeholder="Пароль" required><button class="password-toggle" type="button" data-password-toggle="login-password" aria-label="Показать пароль" aria-pressed="false"><svg><use href="#i-eye"/></svg></button></span></label><button class="button primary wide" type="submit">Войти <svg class="action-arrow" aria-hidden="true"><use href="#i-arrow-up-right"/></svg></button></form>
|
||||
</div>
|
||||
<div id="register-panel" hidden><h2>Создайте аккаунт.</h2><p class="muted">Присоединяйтесь к разговору.</p>
|
||||
<form id="register-form"><label>Имя<input id="register-name" name="display_name" autocomplete="nickname" placeholder="Никита" required></label><label>Имя пользователя<input id="register-username" name="username" autocomplete="username" placeholder="n1k0der" pattern="[a-z0-9_]{3,32}" required autocapitalize="none" spellcheck="false"><span class="field-note">3-32 символа: a-z, цифры и _</span></label><label>Пароль<span class="password-field"><input id="register-password" aria-label="Пароль" name="password" type="password" autocomplete="new-password" placeholder="Придумайте пароль" required><button class="password-toggle" type="button" data-password-toggle="register-password" aria-label="Показать пароль" aria-pressed="false"><svg><use href="#i-eye"/></svg></button></span><span class="field-note">12-128 символов</span></label><button class="button primary wide" type="submit">Создать аккаунт <svg class="action-arrow" aria-hidden="true"><use href="#i-arrow-up-right"/></svg></button></form>
|
||||
</div>
|
||||
<img id="auth-error-art" class="auth-error-art" src="/assets/kolovertysh-error-320.webp" width="320" height="320" alt="" loading="lazy" decoding="async" hidden>
|
||||
<p id="auth-notice" class="form-notice" role="status" aria-live="polite" hidden></p>
|
||||
</div>
|
||||
<div class="auth-bottom">n1k0der<button class="diagnostics-toggle" type="button" data-diagnostics-toggle aria-controls="diagnostics-panel" aria-expanded="false"><svg><use href="#i-code"/></svg>Запросы API</button></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section id="app-screen" class="app-shell" hidden>
|
||||
<aside class="sidebar">
|
||||
<div class="sidebar-top"><a class="brand" href="/" aria-label="n1k0der"><span class="brand-mark"><i></i><i></i><i></i></span>n1k0der<span class="brand-dot">.</span></a><button class="icon-button" id="refresh-chats" title="Обновить чаты" aria-label="Обновить чаты"><svg><use href="#i-refresh"/></svg></button></div>
|
||||
<div class="sidebar-heading"><div><span class="eyebrow">На связи</span><h2>Ваши чаты<span id="chat-count" class="count"></span></h2></div><button id="new-chat" class="icon-button filled" aria-label="Создать чат" title="Создать чат"><svg><use href="#i-plus"/></svg></button></div>
|
||||
<label class="search-field"><span class="visually-hidden">Поиск среди загруженных чатов</span><svg aria-hidden="true"><use href="#i-search"/></svg><input id="chat-search" placeholder="Найти разговор" type="search" autocomplete="off"></label>
|
||||
<div id="chat-list" class="chat-list" aria-label="Список чатов"></div><button id="more-chats" class="text-button" hidden>Ещё чаты</button>
|
||||
<button class="diagnostics-toggle sidebar-diagnostics" type="button" data-diagnostics-toggle aria-controls="diagnostics-panel" aria-expanded="false"><svg><use href="#i-code"/></svg>Запросы API</button>
|
||||
<div class="profile"><button id="open-profile" class="profile-main" title="Открыть профиль"><span id="profile-avatar" class="avatar"></span><span class="profile-text"><strong id="profile-name"></strong><span id="profile-username"></span></span></button><button id="logout" class="icon-button" aria-label="Выйти" title="Выйти"><svg><use href="#i-exit"/></svg></button></div>
|
||||
</aside>
|
||||
<main class="workspace">
|
||||
<div id="welcome" class="welcome"><img class="welcome-illustration" src="/assets/kolovertysh-welcome-320.webp" srcset="/assets/kolovertysh-welcome-320.webp 320w, /assets/kolovertysh-welcome-640.webp 640w" sizes="(max-width: 720px) 200px, 260px" width="640" height="480" alt="" decoding="async"><h1>Начните<br><em>разговор.</em></h1><p>Выберите чат или создайте новый.</p><button id="welcome-new-chat" class="button primary"><svg><use href="#i-plus"/></svg>Создать чат</button></div>
|
||||
<div id="workspace-error" class="state-error welcome" hidden><img src="/assets/kolovertysh-error-320.webp" width="320" height="320" alt="" loading="lazy" decoding="async"><h2>Чаты пока не загрузились</h2><p>Проверьте соединение и попробуйте ещё раз.</p><button id="retry-chats" class="button primary" type="button">Повторить</button></div>
|
||||
<section id="conversation" class="conversation" hidden>
|
||||
<header class="chat-header"><button id="back-to-chats" class="icon-button mobile-only" aria-label="К списку чатов"><svg><use href="#i-arrow"/></svg></button><span id="current-avatar" class="avatar chat-avatar"></span><div class="chat-heading"><h2 id="current-title"></h2><span id="current-members"></span></div><button id="refresh-messages" class="icon-button" aria-label="Обновить сообщения" title="Обновить сообщения"><svg><use href="#i-refresh"/></svg></button><button id="show-members" class="icon-button" aria-label="Участники чата" title="Участники чата"><svg><use href="#i-users"/></svg></button><button class="icon-button mobile-only" type="button" data-diagnostics-toggle aria-label="Запросы API" title="Запросы API" aria-controls="diagnostics-panel" aria-expanded="false"><svg><use href="#i-code"/></svg></button></header>
|
||||
<div class="message-region"><div id="message-scroll" class="message-scroll"><div class="history-control"><button id="older-messages" class="text-button" hidden>Ранее в разговоре ↑</button></div><div id="messages-loading" class="messages-loading" aria-hidden="true" hidden><i></i><i></i><i></i></div><div id="message-list" class="message-list" aria-label="Сообщения"></div><div id="empty-conversation" class="empty-conversation" hidden><img src="/assets/kolovertysh-empty-320.webp" width="320" height="320" alt="" loading="lazy" decoding="async"><p>Здесь начинается разговор</p><span>Напишите первое сообщение.</span></div><div id="conversation-error" class="state-error" hidden><img src="/assets/kolovertysh-error-320.webp" width="320" height="320" alt="" loading="lazy" decoding="async"><h3>Не удалось загрузить сообщения</h3><p>Попробуйте обновить разговор.</p><button id="retry-messages" class="button secondary" type="button">Повторить</button></div></div><button id="jump-latest" class="jump-latest" type="button" hidden>К последним ↓</button></div>
|
||||
<form id="message-form" class="composer"><label class="visually-hidden" for="message-input">Сообщение</label><input id="image-file" type="file" accept="image/png,image/jpeg" hidden><button id="pick-file" class="icon-button" type="button" aria-label="Добавить изображение" title="Добавить изображение"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="m8 13 6-6a3 3 0 0 1 4 4l-8 8a5 5 0 0 1-7-7l9-9"/></svg></button><textarea id="message-input" rows="1" placeholder="Сообщение…" enterkeyhint="send"></textarea><button id="send-message" class="send-button" aria-label="Отправить сообщение" title="Отправить сообщение" disabled><svg><use href="#i-send"/></svg></button><div id="attached-files" class="attached-files"></div><div class="composer-note"><span>Enter - отправить · Shift + Enter - новая строка</span><span id="message-count">0 / 4000</span></div></form>
|
||||
</section>
|
||||
</main>
|
||||
</section>
|
||||
<aside id="diagnostics-panel" class="diagnostics-panel" aria-labelledby="diagnostics-title" hidden>
|
||||
<div class="diagnostics-heading"><div><span class="eyebrow">HTTP-запросы</span><h2 id="diagnostics-title">Запросы API</h2></div><button id="diagnostics-close" class="icon-button" type="button" aria-label="Закрыть панель запросов"><svg><use href="#i-close"/></svg></button></div>
|
||||
<section class="cluster-section" aria-labelledby="cluster-title">
|
||||
<div class="diagnostics-section-heading"><h3 id="cluster-title">Живая схема</h3><span class="cluster-live">LIVE</span></div>
|
||||
<p id="cluster-status" class="cluster-status" role="status">Схема доступна после входа</p>
|
||||
<div class="cluster-graph">
|
||||
<div class="cluster-node cluster-browser"><strong>Ваш браузер</strong><span>HTTP · Bearer</span></div>
|
||||
<div id="cluster-balancer" class="cluster-node cluster-balancer" data-state="unknown"><strong>HAProxy</strong><span>Round robin · health check</span></div>
|
||||
<div id="cluster-instances" class="cluster-instances" aria-label="Экземпляры API"></div>
|
||||
<div class="cluster-stores"><div id="cluster-postgres" class="cluster-node" data-state="unknown"><strong>PostgreSQL</strong><span>Сообщения · реакции · сессии</span></div><div id="cluster-redis" class="cluster-node" data-state="unknown"><strong>Redis</strong><span>Кэш сессий · heartbeat</span></div></div>
|
||||
</div>
|
||||
<p id="cluster-detail" class="cluster-detail">Подсветка — реальный X-Instance-Id ответа.</p>
|
||||
<button id="cluster-probe" class="text-button" type="button">Отправить проверочный запрос ↗</button>
|
||||
<p class="cluster-note">Счётчики — ответы в этой вкладке с момента входа. Heartbeat обновляется раз в 2 с; после 8 с тишины API отмечается недоступным. Это отдельная проверка от health check HAProxy.</p>
|
||||
<details class="cluster-demo"><summary>Показать отказоустойчивость</summary><p class="cluster-note">В терминале из папки проекта выполните команду. Она остановит один API на 15 с и автоматически запустит его снова. В это время отправляйте сообщения и следите за схемой.</p><code id="cluster-command" class="cluster-command">Ожидаем работающие API…</code><button id="cluster-copy" class="text-button" type="button" disabled>Скопировать команду</button></details>
|
||||
</section>
|
||||
<div class="diagnostics-summary"><div><span class="diagnostics-label">Пользователь</span><strong id="diagnostics-user">Вход не выполнен</strong></div><div><span class="diagnostics-label">До конца сессии</span><strong id="diagnostics-session">-</strong></div></div>
|
||||
<section class="diagnostics-history"><span class="diagnostics-label">История выбранного чата</span><strong id="diagnostics-chat">Выберите чат</strong><p id="diagnostics-messages">Сообщения ещё не загружены</p></section>
|
||||
<section class="diagnostics-request"><div class="diagnostics-section-heading"><h3>Последний запрос</h3><time id="diagnostics-request-time"></time></div><p id="diagnostics-empty" class="diagnostics-note">Войдите, откройте чат или отправьте сообщение.</p><div id="diagnostics-request-details" hidden><div class="diagnostics-request-line"><span id="diagnostics-method" class="diagnostics-method"></span><span id="diagnostics-status" class="diagnostics-status"></span></div><span id="diagnostics-origin" class="diagnostics-label diagnostics-origin"></span><code id="diagnostics-path" class="diagnostics-path"></code><p id="diagnostics-result" class="diagnostics-result" role="status" aria-live="polite"></p><dl class="diagnostics-metrics"><div><dt>Авторизация</dt><dd id="diagnostics-auth"></dd></div><div><dt>Время запроса</dt><dd id="diagnostics-duration"></dd></div></dl><span class="diagnostics-label">X-Instance-Id</span><code id="diagnostics-instance-id" class="diagnostics-request-id"></code><span class="diagnostics-label">X-Request-Id</span><code id="diagnostics-request-id" class="diagnostics-request-id"></code></div></section>
|
||||
<ol id="diagnostics-previous" class="diagnostics-previous" aria-label="Предыдущие запросы" hidden></ol>
|
||||
<p id="diagnostics-background" class="diagnostics-background" hidden></p>
|
||||
</aside>
|
||||
<div id="toast" class="toast" role="status" aria-live="polite" hidden></div>
|
||||
|
||||
<dialog id="new-chat-dialog"><div class="dialog-heading"><h2>Собрать чат</h2><button class="icon-button" data-close-dialog aria-label="Закрыть"><svg><use href="#i-close"/></svg></button></div><form id="new-chat-form"><label>Название чата<input id="new-chat-title" placeholder="Название" required></label><label>ID участников<textarea id="new-chat-members" rows="3" placeholder="Вставьте ID через запятую или с новой строки" spellcheck="false"></textarea><span class="field-note">Вы добавитесь автоматически. Для чата с собой оставьте поле пустым.</span></label><p id="chat-dialog-notice" class="form-notice" role="status" hidden></p><div class="dialog-actions"><button class="button secondary" type="button" data-close-dialog>Отмена</button><button class="button primary" type="submit">Создать чат</button></div></form></dialog>
|
||||
<dialog id="profile-dialog"><div class="dialog-heading"><h2>Ваш профиль</h2><button class="icon-button" data-close-dialog aria-label="Закрыть"><svg><use href="#i-close"/></svg></button></div><p id="profile-details" class="muted"></p><label>Ваш ID<input id="my-id" readonly spellcheck="false"></label><p class="field-note">Поделитесь ID для приглашения в чат.</p><button id="copy-id" class="button primary wide"><svg><use href="#i-copy"/></svg>Скопировать ID</button></dialog>
|
||||
<dialog id="members-dialog"><div class="dialog-heading"><h2>Участники чата</h2><button class="icon-button" data-close-dialog aria-label="Закрыть"><svg><use href="#i-close"/></svg></button></div><div id="members-list" class="members-list"></div></dialog>
|
||||
</body>
|
||||
</html>
|
||||
@@ -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));
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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; } }
|
||||