ЛР 3 - БВТ-2302 - Каменский - на 5 #87
@@ -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/
|
||||
|
||||
@@ -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,7 @@
|
||||
PYTHON ?= python3
|
||||
BASE_URL ?= http://localhost:8080
|
||||
-include .env
|
||||
API_PORT ?= 18080
|
||||
PYTHON ?= $(if $(wildcard .venv/bin/python),.venv/bin/python,python3)
|
||||
BASE_URL = http://127.0.0.1:$(API_PORT)
|
||||
CA_FILE ?=
|
||||
ACTION_SCRIPT ?=
|
||||
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
||||
@@ -8,6 +10,11 @@ TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
||||
|
||||
help:
|
||||
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
|
||||
@echo "setup: Python dependencies; up/down: start/stop mtusi2026lab3; build: C# build"
|
||||
@echo "student-test: concurrent idempotency; test-auth/test-ui: authentication and web history"
|
||||
@echo "test-persistence/test-failover: restart/stop-one; restore-api: bring back replicas"
|
||||
@echo "test-grade4: each replica failure and sequential replacement under traffic"
|
||||
@echo "research-grade5: 1/2/4 replicas and resource limits; verify-grade5: full sequence"
|
||||
|
||||
check:
|
||||
$(PYTHON) scripts/check_contract.py
|
||||
@@ -21,10 +28,68 @@ test:
|
||||
load:
|
||||
$(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
test-persistence: ACTION_SCRIPT = scripts/restart.sh
|
||||
test-persistence:
|
||||
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2)
|
||||
$(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
$(PYTHON) student-tests/persistence_checks.py --base-url "$(BASE_URL)"
|
||||
|
||||
test-failover: ACTION_SCRIPT = scripts/stop-one.sh
|
||||
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: plots up down build setup student-test test-ui test-auth test-expiry test-idempotency-modes test-grade4 research-grade5 verify-grade5 rolling-update restore-api
|
||||
|
||||
up:
|
||||
./scripts/init-secrets.sh
|
||||
./scripts/compose.sh build api
|
||||
./scripts/compose.sh up -d --wait --wait-timeout 90
|
||||
|
||||
down:
|
||||
./scripts/compose.sh down
|
||||
|
||||
build:
|
||||
dotnet build src/Messenger.Api/Messenger.Api.csproj --nologo
|
||||
|
||||
setup:
|
||||
python3 -m venv .venv
|
||||
.venv/bin/python -m pip install -r requirements-dev.txt
|
||||
.venv/bin/python -m pip install -r requirements-research.txt
|
||||
|
||||
student-test:
|
||||
$(PYTHON) student-tests/lab3_tests.py --base-url "$(BASE_URL)"
|
||||
|
||||
test-ui:
|
||||
$(PYTHON) student-tests/ui_api_tests.py --base-url "$(BASE_URL)"
|
||||
|
||||
.PHONY: test-showcase
|
||||
test-showcase:
|
||||
$(PYTHON) student-tests/showcase_tests.py --base-url "$(BASE_URL)"
|
||||
|
||||
restore-api:
|
||||
./scripts/compose.sh up -d --wait --wait-timeout 60 api lb
|
||||
|
||||
rolling-update:
|
||||
$(PYTHON) scripts/rolling_update.py --base-url "$(BASE_URL)"
|
||||
|
||||
test-grade4:
|
||||
$(PYTHON) student-tests/availability_tests.py --base-url "$(BASE_URL)"
|
||||
|
||||
test-auth:
|
||||
$(PYTHON) student-tests/lab2_tests.py --base-url "$(BASE_URL)"
|
||||
|
||||
test-expiry:
|
||||
$(PYTHON) student-tests/mode_tests.py --base-url "$(BASE_URL)" --expiry
|
||||
|
||||
test-idempotency-modes:
|
||||
$(PYTHON) student-tests/mode_tests.py --base-url "$(BASE_URL)"
|
||||
|
||||
research-grade5:
|
||||
$(PYTHON) student-tests/scaling_research.py --base-url "$(BASE_URL)"
|
||||
|
||||
plots:
|
||||
$(PYTHON) scripts/plot_results.py
|
||||
|
||||
verify-grade5:
|
||||
BASE_URL="$(BASE_URL)" PYTHON="$(PYTHON)" ./scripts/verify.sh
|
||||
|
||||
@@ -1,37 +1,196 @@
|
||||
# Отчёт — лабораторная 3
|
||||
# Лабораторная 3
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
Автор: Каменский Никита, БВТ2302.
|
||||
Целевая оценка: 5. Трек 1, цена масштабирования.
|
||||
|
||||
## Запуск из чистого clone
|
||||
## Запуск
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
Нужны Docker Desktop, Python 3.9+ и .NET SDK 9 для локального make build.
|
||||
Сборка и работа контейнеров не требуют установленного .NET на хосте.
|
||||
|
||||
## Архитектура и решения
|
||||
make setup
|
||||
make up
|
||||
make test
|
||||
make student-test
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab2, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
Адрес: http://localhost:18080/. Настройка порта: API_PORT в локальном .env
|
||||
или аргумент make up API_PORT=18080.
|
||||
|
||||
## Доказательства критериев
|
||||
scripts/init-secrets.sh создаёт новые credentials в secrets/ только если их ещё нет.
|
||||
Файлы .env, secrets/, volumes и сборочные каталоги исключены из Git.
|
||||
scripts/compose.sh всегда использует один проект mtusi2026lab3 независимо от
|
||||
COMPOSE_PROJECT_NAME в терминале. Повторный make up не создаёт новые стенды.
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
Остановка с сохранением данных:
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
make down
|
||||
|
||||
## Эксперименты и отказы
|
||||
Намеренное удаление учебной базы:
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
./scripts/compose.sh down --volumes
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
Версии образов: .NET SDK 9.0.306, ASP.NET 9.0.10, PostgreSQL 17.6,
|
||||
Redis 7.4.2-alpine, HAProxy 3.2.7-alpine.
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
## Архитектура
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
Браузер или HTTP-клиент обращается к HAProxy. Он распределяет запросы
|
||||
между двумя экземплярами одного Compose-service api по round-robin.
|
||||
API используют одну PostgreSQL и один Redis. Публикуется только порт LB
|
||||
на 127.0.0.1. У API, БД и Redis внешних портов нет; container_name не используется.
|
||||
|
||||
Из Lab2 перенесены C#-исходники, миграция, парольный KDF, общие сессии,
|
||||
кэш пользователя, пагинация и веб-клиент с изображениями. Перенос выполнен
|
||||
из рабочей папки с её текущими исправлениями. Контракты, публичные tests,
|
||||
README.md и COURSE.md взяты из skeleton Lab3.
|
||||
|
||||
PostgreSQL остаётся источником истины для пользователей, чатов, сообщений,
|
||||
сессий и результатов идемпотентных запросов. Redis содержит восстанавливаемый
|
||||
кэш пользователя с TTL до исходного expires_at. Каждый запрос проверяет
|
||||
действительность сессии в PostgreSQL, поэтому потеря кэша не отменяет logout.
|
||||
|
||||
## Миграции
|
||||
|
||||
Одноразовый service migrate выполняет Messenger.Api.dll --migrate до запуска API.
|
||||
Обычные API-процессы не применяют миграции. PostgreSQL advisory transaction lock
|
||||
дополнительно защищает одновременный запуск мигратора.
|
||||
|
||||
001_initial.sql создаёт схему Lab2. 002_idempotency.sql добавляет
|
||||
message_requests, не меняя формат прежних таблиц. Переход Lab2 в Lab3 выполняется отдельным запуском.
|
||||
При проверенной поочерёдной замене используется один контракт Lab3 и
|
||||
совместимая схема; смешивание API Lab2 и Lab3 не проверялось. Для будущей несовместимой миграции требуется отдельный
|
||||
план expand/contract; текущий rolling script не делает любую миграцию безопасной.
|
||||
|
||||
## Идемпотентность
|
||||
|
||||
POST сообщения требует ASCII Idempotency-Key длиной 1-128 символов.
|
||||
Endpoint сначала проверяет сессию, участие в чате, ключ и JSON.
|
||||
|
||||
Область ключа: пользователь, POST сообщения конкретного чата и ключ.
|
||||
Таблица message_requests хранит hash содержимого, message_id и expires_at.
|
||||
В транзакции берётся advisory lock для этой области, затем читается результат.
|
||||
|
||||
- Тот же валидный текст и отсутствующие attachment_ids либо [] возвращают
|
||||
прежнее Message и код 201.
|
||||
- Другой текст с тем же действующим ключом получает 409.
|
||||
- Сообщение и запись результата фиксируются одним COMMIT. При ошибке
|
||||
откатываются обе записи; 5xx не сохраняется как окончательный результат.
|
||||
- Ключ действует 24 часа. Просроченный ключ можно использовать снова.
|
||||
- Сессия и членство проверяются также при повторе.
|
||||
- Коллизия hash advisory lock может только сериализовать независимые запросы;
|
||||
точная уникальность обеспечена составным первичным ключом таблицы.
|
||||
|
||||
MESSAGE_BATCHING=true объединяет пары SQL-команд в один сетевой обмен,
|
||||
сохраняя отдельные SQL statements и транзакционную блокировку.
|
||||
Режим false оставлен для воспроизводимого сравнения.
|
||||
Собственные проверки конкуренции выполняются в обоих режимах.
|
||||
|
||||
Клиент сохраняет ключ неудачной отправки в памяти до успешного ответа.
|
||||
Повтор того же текста в том же чате использует прежний ключ. После успеха
|
||||
новое сообщение получает новый ключ. Создание чата и регистрация автоматически
|
||||
не повторяются. После перезагрузки страницы память неудачной отправки теряется.
|
||||
|
||||
Просроченные строки ключей удаляются при повторном использовании того же ключа.
|
||||
Периодическая очистка остальных старых строк не реализована.
|
||||
|
||||
## Готовность и остановка
|
||||
|
||||
X-Instance-Id содержит случайный alias, неизменный в течение жизни процесса.
|
||||
Заголовок добавляется ко всем ответам API, включая ошибки, health и статику.
|
||||
|
||||
HAProxy проверяет /health/ready каждые 500 ms: fall=2, rise=2,
|
||||
таймаут проверки 500 ms, fastinter=250 ms. Для уже известного backend расчётный бюджет исключения составляет до 3 секунд:
|
||||
500 ms до проверки, два неудачных connect/check до 1s каждый и fastinter 250 ms.
|
||||
Это отдельная величина от времени первой успешной записи после начала action.
|
||||
Требование восстановления записи за 10 секунд проверяется измерением.
|
||||
|
||||
Docker DNS опрашивается через 127.0.0.11, hold valid=1s. server-template
|
||||
поддерживает до восьми адресов API. Изменение IP и числа реплик подхватывается
|
||||
без ручного списка адресов.
|
||||
|
||||
При SIGTERM readiness помечается как остановленная, новые прикладные запросы
|
||||
не принимаются. Host shutdown timeout равен 8 секундам, Docker grace period 10.
|
||||
scripts/stop-one.sh сопоставляет TARGET_INSTANCE_ID реальному процессу и
|
||||
оставляет только выбранный контейнер остановленным.
|
||||
|
||||
При поочерёдной замене сначала запускается одна новая реплика, затем HAProxy
|
||||
переводит старую в drain, ожидается завершение активных соединений, старая
|
||||
останавливается и удаляется. Замена повторяется для каждого прежнего контейнера.
|
||||
Это один дополнительный API на время обновления. Образ получает новую revision
|
||||
метку; в результатах есть реальные ID контейнеров и образов до/после.
|
||||
|
||||
Таймауты LB: connect/check 500 ms, queue 2s, server 12s, client 15s.
|
||||
Автоматического повтора POST после неизвестного результата в LB нет.
|
||||
Клиент повторяет сообщение с исходным ключом.
|
||||
|
||||
## Проверки
|
||||
|
||||
make check
|
||||
make validate
|
||||
make test
|
||||
make student-test
|
||||
make test-auth
|
||||
make test-ui
|
||||
make test-persistence
|
||||
make restore-api
|
||||
make test-failover
|
||||
make restore-api
|
||||
make test-idempotency-modes
|
||||
make test-expiry
|
||||
make test-grade4
|
||||
make research-grade5
|
||||
|
||||
Полная последовательность с логом: make verify-grade5.
|
||||
Результаты записываются в evidence/checks.txt.
|
||||
|
||||
| Критерий | Проверка | Результат |
|
||||
| --- | --- | --- |
|
||||
| Контракт и прежний API | make test, test-auth, test-ui | Статусы, JSON, авторизация, пагинация |
|
||||
| Две реальные API с одной сессией | student-test | Разные X-Instance-Id и контейнеры |
|
||||
| Общий ключ между репликами | test-idempotency-modes | 32 одновременных запроса, одно сообщение |
|
||||
| Повтор, конфликт и scopes | student-test | 201 / 409, независимые пользователь и чат |
|
||||
| Атомарность ключа и сообщения | student-test | Внедрённая ошибка откатывает обе записи |
|
||||
| Истечение и отзыв | test-auth, test-expiry | 401, исчезновение записи Redis по TTL |
|
||||
| Полный restart | test-persistence | Прежний токен и подтверждённые данные |
|
||||
| Остановка выбранной реплики | test-failover | Восстановление за ≤10s, подсчёт ошибок |
|
||||
| Последовательный отказ каждой API | test-grade4 | graceful/immediate, RPS и сохранность |
|
||||
| Поочерёдная замена под нагрузкой | test-grade4 | Новые контейнеры/образ, ошибки и сообщения |
|
||||
| CPU/RAM и закрытые порты API | test-grade4 | Реальные HostConfig и PortBindings |
|
||||
| Масштабирование 1/2/4 | research-grade5 | Фиксированные и растущие бюджеты |
|
||||
| Проверенное изменение | research-grade5 | SQL batching и отдельная проверка CPU БД |
|
||||
|
||||
Полные результаты: evidence/idempotency.json, evidence/idempotency-separate.json,
|
||||
evidence/idempotency-batched.json, evidence/persistence.json,
|
||||
evidence/availability.json, evidence/scaling.json.
|
||||
Поведение переходных ошибок учитывается, нулевая доля ошибок при остановке
|
||||
или замене заранее не предполагается.
|
||||
|
||||
## Исследование
|
||||
|
||||
Методика, таблицы и графики: docs/SCALING.md.
|
||||
Исходные HTTP-измерения без credentials: evidence/scaling-requests.csv.gz.
|
||||
|
||||
Измерения проведены до добавления UI-списка чатов с последними сообщениями.
|
||||
Обязательные маршруты отправки сообщений, использованные в исследовании,
|
||||
после измерений не менялись; хеш исходников текущей версии отличается.
|
||||
|
||||
Сравниваются фиксированные суммарные CPU/RAM API и увеличение ресурсов вместе
|
||||
с числом API. RPS, ошибки, p50/p95/p99, ресурсы cgroup, очереди LB и состояния
|
||||
соединений PostgreSQL сохраняются по отдельным прогонам. Точка насыщения
|
||||
обсуждается по измеренным кривым и ресурсным ограничениям.
|
||||
|
||||
## Ограничения
|
||||
|
||||
Один Docker-host, HAProxy и PostgreSQL остаются точками отказа.
|
||||
Это проверка отказа API-процесса, не отказоустойчивость физического узла.
|
||||
Redis не содержит единственную копию сессий и может быть заполнен заново.
|
||||
|
||||
Нагрузочный клиент работает на том же компьютере и использует closed-loop.
|
||||
Он не доказывает абсолютную максимальную пропускную способность.
|
||||
HTTP используется только на локальном стенде с синтетическими данными.
|
||||
|
||||
## Источники и инструменты
|
||||
|
||||
Реализация Lab2 этого проекта, skeleton и контракт Lab3, документация
|
||||
HAProxy, Npgsql и ASP.NET Core. ChatGPT использован при реализации и проверках.
|
||||
Конкретные измерения получены выполнением команд из этого репозитория.
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
name: mtusi2026lab3
|
||||
|
||||
x-api: &api
|
||||
image: messenger-lab3: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}
|
||||
MESSAGE_BATCHING: ${MESSAGE_BATCHING:-true}
|
||||
Logging__LogLevel__Default: Warning
|
||||
Logging__LogLevel__Microsoft.Hosting.Lifetime: Information
|
||||
secrets:
|
||||
- database_url
|
||||
cpus: ${API_CPUS:-1}
|
||||
mem_limit: ${API_MEMORY:-384m}
|
||||
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:
|
||||
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-lab3: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
|
||||
|
||||
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:-18080}: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:
|
||||
postgres_password:
|
||||
file: ./secrets/postgres_password
|
||||
database_url:
|
||||
file: ./secrets/database_url
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
@@ -0,0 +1,20 @@
|
||||
ЛР 3 - БВТ2302 - Каменский - на 5, трек 1
|
||||
|
||||
Добавлены две API-реплики за HAProxy, общие сессии и идемпотентность отправки
|
||||
сообщений в PostgreSQL. Миграции выполняет отдельный одноразовый сервис.
|
||||
Проверяются остановка каждой реплики и поочерёдная замена контейнеров под нагрузкой.
|
||||
|
||||
Исследование сравнивает 1/2/4 API при фиксированном суммарном CPU/RAM и при
|
||||
увеличении бюджета. Измерены RPS, ошибки, задержки, CPU/throttling и очереди.
|
||||
Отдельно сравниваются SQL batching и увеличение CPU PostgreSQL.
|
||||
|
||||
Запуск: make setup, make up. Полная проверка: make verify-grade5.
|
||||
Результаты: REPORT.md, docs/SCALING.md, evidence/checks.txt,
|
||||
evidence/availability.json и evidence/scaling.json.
|
||||
|
||||
Контракт и публичные tests сохранены. PostgreSQL, LB и один Docker-host
|
||||
остаются точками отказа. Нагрузочный генератор closed-loop работает на том же
|
||||
компьютере, поэтому результаты не являются абсолютным пределом сервера.
|
||||
|
||||
Из Lab2 перенесены собственные исходники и интерфейс. ChatGPT использован
|
||||
при реализации и проверках.
|
||||
@@ -0,0 +1,140 @@
|
||||
# Масштабирование API
|
||||
|
||||
Проверено: 2026-11-01T23:43:46Z. Трек 1, Lab3.
|
||||
|
||||
## Гипотеза
|
||||
|
||||
Несколько API при одном суммарном бюджете CPU/RAM не обязаны быть быстрее одного.
|
||||
При увеличении суммарного бюджета предел задаётся общей БД, балансировщиком, пулами
|
||||
соединений или клиентом. Объединение последовательных SQL-команд уменьшает число
|
||||
обменов API с PostgreSQL.
|
||||
|
||||
## Запуск
|
||||
|
||||
make up
|
||||
make research-grade5
|
||||
|
||||
Исходные результаты: evidence/scaling.json.
|
||||
Данные каждого HTTP-запроса: evidence/scaling-requests.csv.gz.
|
||||
Графики: evidence/scaling.png и evidence/scaling.svg.
|
||||
|
||||
## Методика
|
||||
|
||||
Один Docker Desktop на macOS, 8 виртуальных CPU,
|
||||
3.82 GiB RAM.
|
||||
Основные версии и ограничения контейнеров записаны в JSON.
|
||||
|
||||
Нагрузка: 50% чтений первой страницы из 50 сообщений, 50% отправок новых сообщений.
|
||||
Одна действующая сессия, отдельный чат каждого замера, 250 начальных сообщений.
|
||||
Регистрация, Argon2id и подготовка набора не входят в измерение.
|
||||
Клиент использует постоянные HTTP/1.1-соединения, без повторов запросов.
|
||||
Неподтверждённая запись могла попасть в БД, поэтому RPS означает успешные HTTP-ответы.
|
||||
Латентность всех попыток и успешных ответов записана отдельно.
|
||||
Полное время учитывает завершение начатых запросов и сбор наблюдений.
|
||||
Медиана доли ошибок может быть нулевой при сбое в одном из трёх прогонов,
|
||||
поэтому отдельно приведено суммарное число ошибок и диапазон RPS.
|
||||
|
||||
Серия fixed: всего 1 CPU и 768 MiB для API, делённые между 1/2/4 репликами.
|
||||
Серия growing: каждой API даётся 1 CPU и 384 MiB.
|
||||
БД: 0.5 CPU, 512 MiB; HAProxy: 0.5 CPU, 96 MiB; Redis: 0.25 CPU, 96 MiB.
|
||||
Пул Npgsql: 20 соединений на реплику, суммарно 20/40/80.
|
||||
Есть отдельная проверка увеличения CPU PostgreSQL до 1.
|
||||
|
||||
Перед конфигурацией прогрев 3 секунды, перед каждой concurrency ещё 2 секунды.
|
||||
Concurrency: 4/16/64. Каждая точка: 3 прогона по
|
||||
8 секунд, приведены медианы.
|
||||
Порядок concurrency чередуется между конфигурациями; варианты batching чередуются.
|
||||
|
||||
CPU и throttling измерены по cgroup cpu.stat до/после прогона. Это окно включает
|
||||
накладные расходы сбора счётчиков. RAM отражает memory.current в конце окна,
|
||||
а не исторический пик. Для каждого прогона есть успешные RPS, ошибки, p50/p95/p99,
|
||||
распределение реплик и счётчики HAProxy/БД.
|
||||
|
||||
## Результаты
|
||||
|
||||
| Серия | Реплики | CPU API всего | MiB API всего | Клиенты | RPS | p95 ms | Медиана доли ошибок | Ошибок всего |
|
||||
| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
|
||||
| fixed | 1 | 1.0 | 768 | 4 | 227.971 | 69.017 | 0.0 | 0 |
|
||||
| fixed | 1 | 1.0 | 768 | 16 | 275.06 | 103.552 | 0.0 | 0 |
|
||||
| fixed | 1 | 1.0 | 768 | 64 | 302.941 | 307.507 | 0.0 | 0 |
|
||||
| fixed | 2 | 1.0 | 768 | 4 | 232.474 | 68.443 | 0.0 | 0 |
|
||||
| fixed | 2 | 1.0 | 768 | 16 | 267.997 | 106.101 | 0.0 | 0 |
|
||||
| fixed | 2 | 1.0 | 768 | 64 | 275.592 | 456.591 | 0.0 | 0 |
|
||||
| fixed | 4 | 1.0 | 768 | 4 | 124.453 | 102.574 | 0.0 | 0 |
|
||||
| fixed | 4 | 1.0 | 768 | 16 | 227.163 | 221.725 | 0.0 | 0 |
|
||||
| fixed | 4 | 1.0 | 768 | 64 | 234.342 | 577.561 | 0.0 | 0 |
|
||||
| growing | 1 | 1 | 384 | 4 | 250.297 | 63.995 | 0.0 | 0 |
|
||||
| growing | 1 | 1 | 384 | 16 | 292.921 | 102.186 | 0.0 | 0 |
|
||||
| growing | 1 | 1 | 384 | 64 | 296.505 | 386.697 | 0.0 | 0 |
|
||||
| growing | 2 | 2 | 768 | 4 | 260.993 | 65.864 | 0.0 | 0 |
|
||||
| growing | 2 | 2 | 768 | 16 | 261.656 | 107.965 | 0.0 | 0 |
|
||||
| growing | 2 | 2 | 768 | 64 | 269.672 | 410.645 | 0.0 | 0 |
|
||||
| growing | 4 | 4 | 1536 | 4 | 245.033 | 51.051 | 0.0 | 0 |
|
||||
| growing | 4 | 4 | 1536 | 16 | 236.934 | 111.575 | 0.0 | 0 |
|
||||
| growing | 4 | 4 | 1536 | 64 | 182.5 | 894.66 | 0.0 | 21 |
|
||||
|
||||

|
||||
|
||||
## Проверенные изменения
|
||||
|
||||
SQL-команды не меняют транзакционную границу: блокировка, проверка ключа,
|
||||
запись сообщения и результата остаются согласованными. MESSAGE_BATCHING=false
|
||||
отправляет команды отдельно; true объединяет пары команд в один сетевой обмен.
|
||||
Конкурентная проверка обоих режимов входит в собственные тесты.
|
||||
|
||||
| Вариант | Медиана RPS | Диапазон RPS | p95 ms | Ошибок всего |
|
||||
| --- | ---: | --- | ---: | ---: |
|
||||
| Отдельные SQL-команды | 144.195 | 90.853 - 244.459 | 109.924 | 984 |
|
||||
| SQL batching | 219.126 | 179.536 - 272.021 | 112.969 | 0 |
|
||||
|
||||
Изменение медианных RPS: +52.0%. Эти значения относятся только к этому
|
||||
профилю и конфигурации из JSON; это не универсальная оценка скорости.
|
||||
|
||||
Увеличение PostgreSQL с 0.5 до 1 CPU при четырёх API: изменение медианных RPS
|
||||
+81.5%. В JSON сохранены оба набора CPU/throttling и латентностей,
|
||||
поэтому причинное объяснение можно проверить по ресурсным ограничениям.
|
||||
|
||||
## Анализ насыщения
|
||||
|
||||
У одной API в growing увеличение concurrency с 16 до 64 изменило медиану
|
||||
RPS с 292.921 до 296.505 (+1.2%), а p95 вырос
|
||||
с 102.186 до 386.697 ms. В этом профиле плато начинается
|
||||
около 300 успешных запросов/с.
|
||||
|
||||
На этой точке среднее потребление CPU по окну cgroup: API 0.321
|
||||
из 1, PostgreSQL 0.448 из 0.5, HAProxy 0.073 из 0.5.
|
||||
База близка к своей квоте, тогда как у API и LB остаётся запас. Дополнительный
|
||||
эксперимент с 1 CPU PostgreSQL дал 395.521 против
|
||||
217.905 RPS при прежних четырёх API. Это подтверждает
|
||||
существенное влияние общей БД в выбранной конфигурации.
|
||||
|
||||
Коды неуспешных попыток за всю серию: {'0': 61, '503': 968, '500': 16}; 0 означает отсутствие
|
||||
полного HTTP-ответа. Ошибки на перегрузке не исключались из исходных данных.
|
||||
Число SQL-соединений растёт вместе с репликами, поэтому здесь исследуется
|
||||
полный эффект конфигурации API, а не изолированное действие числа процессов.
|
||||
|
||||
Насыщение оценивается по кривым RPS и p95 при увеличении concurrency.
|
||||
Рост задержки без сопоставимого роста RPS означает накопление очереди.
|
||||
Распределение использованных CPU, throttling, очередей HAProxy и активных
|
||||
соединений PostgreSQL сохранено по каждому прогону. Высокая утилизация БД
|
||||
при свободном CPU API указывает на общий предел хранилища; загруженный API
|
||||
при свободной БД указывает на ограничение API.
|
||||
|
||||
## Ограничения
|
||||
|
||||
Closed-loop генератор замедляет поступление запросов при росте задержки
|
||||
и имеет coordinated omission. Клиент работает на том же физическом компьютере.
|
||||
Не измерены производственные arrival rates, сетевые задержки между узлами
|
||||
и предел отдельного выделенного генератора. Приведённые числа не являются
|
||||
заявлением о максимальной производительности сервера.
|
||||
|
||||
Таблицы растут между прогонами, buffers прогреты; это влияет на сравнение.
|
||||
Один LB, PostgreSQL и один Docker-host остаются точками отказа.
|
||||
Redis является восстанавливаемым кэшем; сессии проверяются в PostgreSQL.
|
||||
Добавление API не обеспечивает отказоустойчивость узла или базы.
|
||||
|
||||
## Источники
|
||||
|
||||
- https://www.haproxy.com/documentation/haproxy-configuration-tutorials/reliability/health-checks/
|
||||
- https://www.haproxy.com/documentation/haproxy-configuration-tutorials/proxying-essentials/dns-resolution/
|
||||
- https://www.npgsql.org/doc/performance.html
|
||||
@@ -0,0 +1,180 @@
|
||||
.venv/bin/python student-tests/availability_tests.py --base-url "http://127.0.0.1:18080"
|
||||
Testing graceful stop of 532e774b3f3a
|
||||
Testing immediate stop of 154be9bc5b03
|
||||
Building replacement image
|
||||
Testing sequential replacement under mixed traffic
|
||||
{
|
||||
"verified_at": "2026-11-01T22:57:16Z",
|
||||
"failures": [
|
||||
{
|
||||
"duration_seconds": 16.0791,
|
||||
"requested_seconds": 16,
|
||||
"concurrency": 8,
|
||||
"successful_requests": 5002,
|
||||
"failed_requests": 16,
|
||||
"successful_rps": 311.088,
|
||||
"error_ratio": 0.003189,
|
||||
"successful_latency_ms": {
|
||||
"p50": 7.92,
|
||||
"p95": 80.79,
|
||||
"p99": 91.746
|
||||
},
|
||||
"all_attempt_latency_ms": {
|
||||
"p50": 7.931,
|
||||
"p95": 81.213,
|
||||
"p99": 94.761
|
||||
},
|
||||
"status_counts": {
|
||||
"200": 2494,
|
||||
"201": 2508,
|
||||
"503": 16
|
||||
},
|
||||
"instance_counts": {
|
||||
"8dd6e05328154854818c0526596de617": 328,
|
||||
"7247c997acc94e32854eecea90b64f19": 4674
|
||||
},
|
||||
"actions": [
|
||||
{
|
||||
"started_after_seconds": 2.00741333301994,
|
||||
"finished_after_seconds": 2.9904547500191256,
|
||||
"result": {
|
||||
"container": "532e774b3f3a7b5f39e88e27486c67d61ae738abbe59c245537f038334cc6b00",
|
||||
"instance": "8dd6e05328154854818c0526596de617",
|
||||
"running_after_action": false
|
||||
}
|
||||
}
|
||||
],
|
||||
"mode": "graceful",
|
||||
"recovery_seconds": 1.579,
|
||||
"integrity": {
|
||||
"confirmed_writes": 2508,
|
||||
"stored_messages": 2508,
|
||||
"no_duplicate_text": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"duration_seconds": 16.0226,
|
||||
"requested_seconds": 16,
|
||||
"concurrency": 8,
|
||||
"successful_requests": 2954,
|
||||
"failed_requests": 8,
|
||||
"successful_rps": 184.365,
|
||||
"error_ratio": 0.002701,
|
||||
"successful_latency_ms": {
|
||||
"p50": 24.682,
|
||||
"p95": 99.191,
|
||||
"p99": 291.869
|
||||
},
|
||||
"all_attempt_latency_ms": {
|
||||
"p50": 24.75,
|
||||
"p95": 100.611,
|
||||
"p99": 362.389
|
||||
},
|
||||
"status_counts": {
|
||||
"200": 1473,
|
||||
"201": 1481,
|
||||
"0": 3,
|
||||
"503": 5
|
||||
},
|
||||
"instance_counts": {
|
||||
"f4e50cb08dff4b4e912526d109af80a8": 2885,
|
||||
"7247c997acc94e32854eecea90b64f19": 69
|
||||
},
|
||||
"actions": [
|
||||
{
|
||||
"started_after_seconds": 2.0046655840124004,
|
||||
"finished_after_seconds": 4.294007374992361,
|
||||
"result": {
|
||||
"container": "154be9bc5b03d841f2e94423e86ede15e1d9d89155f80aebfb6f26939d09ea0b",
|
||||
"instance": "7247c997acc94e32854eecea90b64f19",
|
||||
"running_after_action": false
|
||||
}
|
||||
}
|
||||
],
|
||||
"mode": "immediate",
|
||||
"recovery_seconds": 2.303,
|
||||
"integrity": {
|
||||
"confirmed_writes": 1481,
|
||||
"stored_messages": 1481,
|
||||
"no_duplicate_text": true
|
||||
}
|
||||
}
|
||||
],
|
||||
"rolling_update": {
|
||||
"duration_seconds": 45.0098,
|
||||
"requested_seconds": 45,
|
||||
"concurrency": 8,
|
||||
"successful_requests": 7800,
|
||||
"failed_requests": 10,
|
||||
"successful_rps": 173.296,
|
||||
"error_ratio": 0.00128,
|
||||
"successful_latency_ms": {
|
||||
"p50": 28.192,
|
||||
"p95": 120.345,
|
||||
"p99": 208.105
|
||||
},
|
||||
"all_attempt_latency_ms": {
|
||||
"p50": 28.231,
|
||||
"p95": 121.312,
|
||||
"p99": 218.139
|
||||
},
|
||||
"status_counts": {
|
||||
"200": 3895,
|
||||
"201": 3905,
|
||||
"503": 10
|
||||
},
|
||||
"instance_counts": {
|
||||
"a020d1919aed4cbcab27bd49c3363717": 941,
|
||||
"f4e50cb08dff4b4e912526d109af80a8": 494,
|
||||
"9fdec641bc0e42358028fbf02a547750": 3419,
|
||||
"c23fe78cf209434fb08541058e1fe83a": 2946
|
||||
},
|
||||
"actions": [
|
||||
{
|
||||
"started_after_seconds": 2.001473125012126,
|
||||
"finished_after_seconds": 19.158305874996586,
|
||||
"result": [
|
||||
{
|
||||
"old_container": "532e774b3f3a7b5f39e88e27486c67d61ae738abbe59c245537f038334cc6b00",
|
||||
"old_instance": "f4e50cb08dff4b4e912526d109af80a8",
|
||||
"old_image": "sha256:d011d9b6d508badefd8ce4d974fba93f2cb5fd16fe2bc22f814b0df2a720b16d",
|
||||
"new_container": "fd6343f590fd942987e9689d03156de3d376940aae922a48955fd14199deb5d3",
|
||||
"new_instance": "9fdec641bc0e42358028fbf02a547750",
|
||||
"new_image": "sha256:7b23b7960daa18fb8416fc5373c808a14dc27975528e5394fa83363f25b4c42c"
|
||||
},
|
||||
{
|
||||
"old_container": "154be9bc5b03d841f2e94423e86ede15e1d9d89155f80aebfb6f26939d09ea0b",
|
||||
"old_instance": "a020d1919aed4cbcab27bd49c3363717",
|
||||
"old_image": "sha256:d011d9b6d508badefd8ce4d974fba93f2cb5fd16fe2bc22f814b0df2a720b16d",
|
||||
"new_container": "8829f09045d9c4e8284dbce533bda78e1bcf4aad605142f4de0a5d1285db7226",
|
||||
"new_instance": "c23fe78cf209434fb08541058e1fe83a",
|
||||
"new_image": "sha256:7b23b7960daa18fb8416fc5373c808a14dc27975528e5394fa83363f25b4c42c"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"integrity": {
|
||||
"confirmed_writes": 3905,
|
||||
"stored_messages": 3905,
|
||||
"no_duplicate_text": true
|
||||
}
|
||||
},
|
||||
"infrastructure": {
|
||||
"api_ports_published": false,
|
||||
"api_containers": [
|
||||
{
|
||||
"id": "fd6343f590fd942987e9689d03156de3d376940aae922a48955fd14199deb5d3",
|
||||
"image": "sha256:7b23b7960daa18fb8416fc5373c808a14dc27975528e5394fa83363f25b4c42c",
|
||||
"cpu_limit": 1.0,
|
||||
"memory_limit": 402653184
|
||||
},
|
||||
{
|
||||
"id": "8829f09045d9c4e8284dbce533bda78e1bcf4aad605142f4de0a5d1285db7226",
|
||||
"image": "sha256:7b23b7960daa18fb8416fc5373c808a14dc27975528e5394fa83363f25b4c42c",
|
||||
"cpu_limit": 1.0,
|
||||
"memory_limit": 402653184
|
||||
}
|
||||
],
|
||||
"migrations": "1,2"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
{
|
||||
"verified_at": "2026-11-01T23:10:36Z",
|
||||
"failures": [
|
||||
{
|
||||
"duration_seconds": 16.0121,
|
||||
"requested_seconds": 16,
|
||||
"concurrency": 8,
|
||||
"successful_requests": 4700,
|
||||
"failed_requests": 8,
|
||||
"successful_rps": 293.528,
|
||||
"error_ratio": 0.001699,
|
||||
"successful_latency_ms": {
|
||||
"p50": 9.802,
|
||||
"p95": 80.053,
|
||||
"p99": 93.193
|
||||
},
|
||||
"all_attempt_latency_ms": {
|
||||
"p50": 9.81,
|
||||
"p95": 80.242,
|
||||
"p99": 94.732
|
||||
},
|
||||
"status_counts": {
|
||||
"200": 2346,
|
||||
"201": 2354,
|
||||
"503": 8
|
||||
},
|
||||
"instance_counts": {
|
||||
"3a26b3036963466ea997dc665b565926": 297,
|
||||
"33f1c8ae80d145809bfba32f4e5fd3a3": 4403
|
||||
},
|
||||
"actions": [
|
||||
{
|
||||
"started_after_seconds": 2.004297334002331,
|
||||
"finished_after_seconds": 2.3088578750030138,
|
||||
"result": {
|
||||
"container": "7fc11b71698d4aa93a2e58a38c671b16f7566f9290b83c965c5f430461ad96b9",
|
||||
"instance": "3a26b3036963466ea997dc665b565926",
|
||||
"running_after_action": false
|
||||
}
|
||||
}
|
||||
],
|
||||
"observations": [],
|
||||
"mode": "graceful",
|
||||
"recovery_seconds": 1.117,
|
||||
"integrity": {
|
||||
"confirmed_writes": 2354,
|
||||
"stored_messages": 2354,
|
||||
"no_duplicate_text": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"duration_seconds": 16.0367,
|
||||
"requested_seconds": 16,
|
||||
"concurrency": 8,
|
||||
"successful_requests": 4730,
|
||||
"failed_requests": 11,
|
||||
"successful_rps": 294.948,
|
||||
"error_ratio": 0.00232,
|
||||
"successful_latency_ms": {
|
||||
"p50": 9.718,
|
||||
"p95": 78.168,
|
||||
"p99": 90.788
|
||||
},
|
||||
"all_attempt_latency_ms": {
|
||||
"p50": 9.732,
|
||||
"p95": 78.319,
|
||||
"p99": 91.752
|
||||
},
|
||||
"status_counts": {
|
||||
"200": 2359,
|
||||
"201": 2371,
|
||||
"0": 6,
|
||||
"503": 5
|
||||
},
|
||||
"instance_counts": {
|
||||
"03a65831924146bf98b9c8beabd73235": 4403,
|
||||
"33f1c8ae80d145809bfba32f4e5fd3a3": 327
|
||||
},
|
||||
"actions": [
|
||||
{
|
||||
"started_after_seconds": 2.002569542004494,
|
||||
"finished_after_seconds": 2.2908867499791086,
|
||||
"result": {
|
||||
"container": "8ff0d3425d061df5856f28e93605421c22d64f07cfa48379444f73583be84b8f",
|
||||
"instance": "33f1c8ae80d145809bfba32f4e5fd3a3",
|
||||
"running_after_action": false
|
||||
}
|
||||
}
|
||||
],
|
||||
"observations": [],
|
||||
"mode": "immediate",
|
||||
"recovery_seconds": 0.304,
|
||||
"integrity": {
|
||||
"confirmed_writes": 2371,
|
||||
"stored_messages": 2371,
|
||||
"no_duplicate_text": true
|
||||
}
|
||||
}
|
||||
],
|
||||
"rolling_update": {
|
||||
"duration_seconds": 45.0733,
|
||||
"requested_seconds": 45,
|
||||
"concurrency": 8,
|
||||
"successful_requests": 12960,
|
||||
"failed_requests": 0,
|
||||
"successful_rps": 287.532,
|
||||
"error_ratio": 0.0,
|
||||
"successful_latency_ms": {
|
||||
"p50": 11.354,
|
||||
"p95": 80.201,
|
||||
"p99": 103.951
|
||||
},
|
||||
"all_attempt_latency_ms": {
|
||||
"p50": 11.354,
|
||||
"p95": 80.201,
|
||||
"p99": 103.951
|
||||
},
|
||||
"status_counts": {
|
||||
"200": 6480,
|
||||
"201": 6480
|
||||
},
|
||||
"instance_counts": {
|
||||
"854205519c6a49eaba8112473f0050e2": 1032,
|
||||
"03a65831924146bf98b9c8beabd73235": 635,
|
||||
"5215daa9aa9e48b193bdf64ff314ff2d": 5823,
|
||||
"3983ae67ecf94704a04dce24f8174384": 5470
|
||||
},
|
||||
"actions": [
|
||||
{
|
||||
"started_after_seconds": 2.0046813749941066,
|
||||
"finished_after_seconds": 11.803809415985597,
|
||||
"result": [
|
||||
{
|
||||
"old_container": "7fc11b71698d4aa93a2e58a38c671b16f7566f9290b83c965c5f430461ad96b9",
|
||||
"old_instance": "03a65831924146bf98b9c8beabd73235",
|
||||
"old_image": "sha256:7d07e2377a2c575fa2db59d2cee807c2e24a2e8c37a54c8df6b3714a58b0516f",
|
||||
"new_container": "8b7f4d1da142af7d0af4cbc6d2c2b85dff74e46c2e9c86c1be2ee99524ecc748",
|
||||
"new_instance": "5215daa9aa9e48b193bdf64ff314ff2d",
|
||||
"new_image": "sha256:9498c2a6ccbbd5ed5b31a80ea7bfe8c8d4e477a5b667f8cd93b1d8947876ed0c"
|
||||
},
|
||||
{
|
||||
"old_container": "8ff0d3425d061df5856f28e93605421c22d64f07cfa48379444f73583be84b8f",
|
||||
"old_instance": "854205519c6a49eaba8112473f0050e2",
|
||||
"old_image": "sha256:7d07e2377a2c575fa2db59d2cee807c2e24a2e8c37a54c8df6b3714a58b0516f",
|
||||
"new_container": "d23b99a781064bdd4221cbdcab862b83ab6f1928f41ba0fa18c3ad25a4c6400d",
|
||||
"new_instance": "3983ae67ecf94704a04dce24f8174384",
|
||||
"new_image": "sha256:9498c2a6ccbbd5ed5b31a80ea7bfe8c8d4e477a5b667f8cd93b1d8947876ed0c"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"observations": [],
|
||||
"integrity": {
|
||||
"confirmed_writes": 6480,
|
||||
"stored_messages": 6480,
|
||||
"no_duplicate_text": true
|
||||
}
|
||||
},
|
||||
"infrastructure": {
|
||||
"api_ports_published": false,
|
||||
"api_containers": [
|
||||
{
|
||||
"id": "8b7f4d1da142af7d0af4cbc6d2c2b85dff74e46c2e9c86c1be2ee99524ecc748",
|
||||
"image": "sha256:9498c2a6ccbbd5ed5b31a80ea7bfe8c8d4e477a5b667f8cd93b1d8947876ed0c",
|
||||
"cpu_limit": 1.0,
|
||||
"memory_limit": 402653184
|
||||
},
|
||||
{
|
||||
"id": "d23b99a781064bdd4221cbdcab862b83ab6f1928f41ba0fa18c3ad25a4c6400d",
|
||||
"image": "sha256:9498c2a6ccbbd5ed5b31a80ea7bfe8c8d4e477a5b667f8cd93b1d8947876ed0c",
|
||||
"cpu_limit": 1.0,
|
||||
"memory_limit": 402653184
|
||||
}
|
||||
],
|
||||
"migrations": "1,2"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,635 @@
|
||||
Verified: 2026-11-01 23:08:44 UTC
|
||||
|
||||
$ make build
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
mtusi2026lab3-api-5 messenger-lab3:local "dotnet Messenger.Ap…" api 2 minutes ago Up 2 minutes (healthy) 8080/tcp
|
||||
mtusi2026lab3-api-6 messenger-lab3:local "dotnet Messenger.Ap…" api 2 minutes ago Up 2 minutes (healthy) 8080/tcp
|
||||
mtusi2026lab3-lb-1 haproxy:3.2.7-alpine "docker-entrypoint.s…" lb 20 minutes ago Up 8 minutes (healthy) 127.0.0.1:18080->8080/tcp
|
||||
mtusi2026lab3-migrate-1 sha256:7b23b7960daa18fb8416fc5373c808a14dc27975528e5394fa83363f25b4c42c "dotnet Messenger.Ap…" migrate 8 minutes ago Exited (0) 7 minutes ago
|
||||
mtusi2026lab3-postgres-1 postgres:17.6 "docker-entrypoint.s…" postgres 20 minutes ago Up 8 minutes (healthy) 5432/tcp
|
||||
mtusi2026lab3-redis-1 redis:7.4.2-alpine "docker-entrypoint.s…" redis 20 minutes ago Up 8 minutes (healthy) 6379/tcp
|
||||
dotnet build src/Messenger.Api/Messenger.Api.csproj --nologo
|
||||
Определение проектов для восстановления...
|
||||
Все проекты обновлены для восстановления.
|
||||
Messenger.Api -> /Users/nikitakamensky/Documents/mtusi2026lab3/src/Messenger.Api/bin/Debug/net9.0/Messenger.Api.dll
|
||||
|
||||
Сборка успешно завершена.
|
||||
Предупреждений: 0
|
||||
Ошибок: 0
|
||||
|
||||
Прошло времени 00:00:01.58
|
||||
|
||||
$ make check
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
mtusi2026lab3-api-5 messenger-lab3:local "dotnet Messenger.Ap…" api 2 minutes ago Up 2 minutes (healthy) 8080/tcp
|
||||
mtusi2026lab3-api-6 messenger-lab3:local "dotnet Messenger.Ap…" api 2 minutes ago Up 2 minutes (healthy) 8080/tcp
|
||||
mtusi2026lab3-lb-1 haproxy:3.2.7-alpine "docker-entrypoint.s…" lb 20 minutes ago Up 8 minutes (healthy) 127.0.0.1:18080->8080/tcp
|
||||
mtusi2026lab3-migrate-1 sha256:7b23b7960daa18fb8416fc5373c808a14dc27975528e5394fa83363f25b4c42c "dotnet Messenger.Ap…" migrate 8 minutes ago Exited (0) 7 minutes ago
|
||||
mtusi2026lab3-postgres-1 postgres:17.6 "docker-entrypoint.s…" postgres 20 minutes ago Up 8 minutes (healthy) 5432/tcp
|
||||
mtusi2026lab3-redis-1 redis:7.4.2-alpine "docker-entrypoint.s…" redis 20 minutes ago Up 8 minutes (healthy) 6379/tcp
|
||||
.venv/bin/python scripts/check_contract.py
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
|
||||
$ make validate
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
mtusi2026lab3-api-5 messenger-lab3:local "dotnet Messenger.Ap…" api 2 minutes ago Up 2 minutes (healthy) 8080/tcp
|
||||
mtusi2026lab3-api-6 messenger-lab3:local "dotnet Messenger.Ap…" api 2 minutes ago Up 2 minutes (healthy) 8080/tcp
|
||||
mtusi2026lab3-lb-1 haproxy:3.2.7-alpine "docker-entrypoint.s…" lb 20 minutes ago Up 8 minutes (healthy) 127.0.0.1:18080->8080/tcp
|
||||
mtusi2026lab3-migrate-1 sha256:7b23b7960daa18fb8416fc5373c808a14dc27975528e5394fa83363f25b4c42c "dotnet Messenger.Ap…" migrate 8 minutes ago Exited (0) 7 minutes ago
|
||||
mtusi2026lab3-postgres-1 postgres:17.6 "docker-entrypoint.s…" postgres 20 minutes ago Up 8 minutes (healthy) 5432/tcp
|
||||
mtusi2026lab3-redis-1 redis:7.4.2-alpine "docker-entrypoint.s…" redis 20 minutes ago Up 8 minutes (healthy) 6379/tcp
|
||||
.venv/bin/python scripts/validate_openapi.py
|
||||
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
|
||||
|
||||
$ make test
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
mtusi2026lab3-api-5 messenger-lab3:local "dotnet Messenger.Ap…" api 2 minutes ago Up 2 minutes (healthy) 8080/tcp
|
||||
mtusi2026lab3-api-6 messenger-lab3:local "dotnet Messenger.Ap…" api 2 minutes ago Up 2 minutes (healthy) 8080/tcp
|
||||
mtusi2026lab3-lb-1 haproxy:3.2.7-alpine "docker-entrypoint.s…" lb 20 minutes ago Up 8 minutes (healthy) 127.0.0.1:18080->8080/tcp
|
||||
mtusi2026lab3-migrate-1 sha256:7b23b7960daa18fb8416fc5373c808a14dc27975528e5394fa83363f25b4c42c "dotnet Messenger.Ap…" migrate 8 minutes ago Exited (0) 7 minutes ago
|
||||
mtusi2026lab3-postgres-1 postgres:17.6 "docker-entrypoint.s…" postgres 20 minutes ago Up 8 minutes (healthy) 5432/tcp
|
||||
mtusi2026lab3-redis-1 redis:7.4.2-alpine "docker-entrypoint.s…" redis 20 minutes ago Up 8 minutes (healthy) 6379/tcp
|
||||
.venv/bin/python tests/smoke.py --base-url "http://127.0.0.1:18080"
|
||||
PASS: lab3 public API scenario; infrastructure and grading evidence remain separate.
|
||||
|
||||
$ make student-test
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
mtusi2026lab3-api-5 messenger-lab3:local "dotnet Messenger.Ap…" api 2 minutes ago Up 2 minutes (healthy) 8080/tcp
|
||||
mtusi2026lab3-api-6 messenger-lab3:local "dotnet Messenger.Ap…" api 2 minutes ago Up 2 minutes (healthy) 8080/tcp
|
||||
mtusi2026lab3-lb-1 haproxy:3.2.7-alpine "docker-entrypoint.s…" lb 20 minutes ago Up 8 minutes (healthy) 127.0.0.1:18080->8080/tcp
|
||||
mtusi2026lab3-migrate-1 sha256:7b23b7960daa18fb8416fc5373c808a14dc27975528e5394fa83363f25b4c42c "dotnet Messenger.Ap…" migrate 8 minutes ago Exited (0) 7 minutes ago
|
||||
mtusi2026lab3-postgres-1 postgres:17.6 "docker-entrypoint.s…" postgres 20 minutes ago Up 8 minutes (healthy) 5432/tcp
|
||||
mtusi2026lab3-redis-1 redis:7.4.2-alpine "docker-entrypoint.s…" redis 20 minutes ago Up 8 minutes (healthy) 6379/tcp
|
||||
.venv/bin/python student-tests/lab3_tests.py --base-url "http://127.0.0.1:18080"
|
||||
{
|
||||
"verified_at": "2026-11-01T23:08:59Z",
|
||||
"instances": [
|
||||
"d7b86414b8104e6782be3b6f7d9dea18",
|
||||
"e27c40b331264ec4b4b12e5dffcb7aec"
|
||||
],
|
||||
"replay_instances": [
|
||||
"d7b86414b8104e6782be3b6f7d9dea18",
|
||||
"e27c40b331264ec4b4b12e5dffcb7aec"
|
||||
],
|
||||
"api_containers": [
|
||||
"006e17da13b0f44c04abed1613fce9a598d1960278da706a92bd9f387ce2986f",
|
||||
"f810cb8ed89777f14708c94390f6533acee9eb2af8dd86889f26f93ef3dcd01f"
|
||||
],
|
||||
"checks": [
|
||||
"one session served by at least two API processes",
|
||||
"32 concurrent requests across replicas create one message; absent attachments equals []",
|
||||
"changed body conflicts; user/chat scopes are independent; access rechecked",
|
||||
"24-hour expiry stored in PostgreSQL; expired key can be reused",
|
||||
"5xx rolls back message and key together; retry succeeds",
|
||||
"revoked token cannot replay an existing result"
|
||||
]
|
||||
}
|
||||
|
||||
$ make test-auth
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
mtusi2026lab3-api-5 messenger-lab3:local "dotnet Messenger.Ap…" api 2 minutes ago Up 2 minutes (healthy) 8080/tcp
|
||||
mtusi2026lab3-api-6 messenger-lab3:local "dotnet Messenger.Ap…" api 2 minutes ago Up 2 minutes (healthy) 8080/tcp
|
||||
mtusi2026lab3-lb-1 haproxy:3.2.7-alpine "docker-entrypoint.s…" lb 20 minutes ago Up 8 minutes (healthy) 127.0.0.1:18080->8080/tcp
|
||||
mtusi2026lab3-migrate-1 sha256:7b23b7960daa18fb8416fc5373c808a14dc27975528e5394fa83363f25b4c42c "dotnet Messenger.Ap…" migrate 8 minutes ago Exited (0) 7 minutes ago
|
||||
mtusi2026lab3-postgres-1 postgres:17.6 "docker-entrypoint.s…" postgres 20 minutes ago Up 8 minutes (healthy) 5432/tcp
|
||||
mtusi2026lab3-redis-1 redis:7.4.2-alpine "docker-entrypoint.s…" redis 20 minutes ago Up 8 minutes (healthy) 6379/tcp
|
||||
.venv/bin/python student-tests/lab2_tests.py --base-url "http://127.0.0.1:18080"
|
||||
PASS: Lab2 password, Basic, Bearer, input validation and session lifecycle
|
||||
|
||||
$ make test-ui
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
mtusi2026lab3-api-5 messenger-lab3:local "dotnet Messenger.Ap…" api 2 minutes ago Up 2 minutes (healthy) 8080/tcp
|
||||
mtusi2026lab3-api-6 messenger-lab3:local "dotnet Messenger.Ap…" api 2 minutes ago Up 2 minutes (healthy) 8080/tcp
|
||||
mtusi2026lab3-lb-1 haproxy:3.2.7-alpine "docker-entrypoint.s…" lb 20 minutes ago Up 8 minutes (healthy) 127.0.0.1:18080->8080/tcp
|
||||
mtusi2026lab3-migrate-1 sha256:7b23b7960daa18fb8416fc5373c808a14dc27975528e5394fa83363f25b4c42c "dotnet Messenger.Ap…" migrate 8 minutes ago Exited (0) 7 minutes ago
|
||||
mtusi2026lab3-postgres-1 postgres:17.6 "docker-entrypoint.s…" postgres 20 minutes ago Up 8 minutes (healthy) 5432/tcp
|
||||
mtusi2026lab3-redis-1 redis:7.4.2-alpine "docker-entrypoint.s…" redis 20 minutes ago Up 8 minutes (healthy) 6379/tcp
|
||||
.venv/bin/python student-tests/ui_api_tests.py --base-url "http://127.0.0.1:18080"
|
||||
PASS: UI authentication, privacy, newest page, backwards pagination, cursor isolation; required API stays ascending
|
||||
|
||||
$ make test-persistence
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
mtusi2026lab3-api-5 messenger-lab3:local "dotnet Messenger.Ap…" api 2 minutes ago Up 2 minutes (healthy) 8080/tcp
|
||||
mtusi2026lab3-api-6 messenger-lab3:local "dotnet Messenger.Ap…" api 2 minutes ago Up 2 minutes (healthy) 8080/tcp
|
||||
mtusi2026lab3-lb-1 haproxy:3.2.7-alpine "docker-entrypoint.s…" lb 20 minutes ago Up 8 minutes (healthy) 127.0.0.1:18080->8080/tcp
|
||||
mtusi2026lab3-migrate-1 sha256:7b23b7960daa18fb8416fc5373c808a14dc27975528e5394fa83363f25b4c42c "dotnet Messenger.Ap…" migrate 8 minutes ago Exited (0) 7 minutes ago
|
||||
mtusi2026lab3-postgres-1 postgres:17.6 "docker-entrypoint.s…" postgres 20 minutes ago Up 8 minutes (healthy) 5432/tcp
|
||||
mtusi2026lab3-redis-1 redis:7.4.2-alpine "docker-entrypoint.s…" redis 20 minutes ago Up 8 minutes (healthy) 6379/tcp
|
||||
.venv/bin/python tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://127.0.0.1:18080"
|
||||
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
|
||||
$ make restore-api
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
mtusi2026lab3-api-5 messenger-lab3:local "dotnet Messenger.Ap…" api 3 minutes ago Up 6 seconds (healthy) 8080/tcp
|
||||
mtusi2026lab3-api-6 messenger-lab3:local "dotnet Messenger.Ap…" api 3 minutes ago Up 6 seconds (healthy) 8080/tcp
|
||||
mtusi2026lab3-lb-1 haproxy:3.2.7-alpine "docker-entrypoint.s…" lb 20 minutes ago Up 6 seconds (healthy) 127.0.0.1:18080->8080/tcp
|
||||
mtusi2026lab3-migrate-1 messenger-lab3:local "dotnet Messenger.Ap…" migrate 5 seconds ago Exited (0) 3 seconds ago
|
||||
mtusi2026lab3-postgres-1 postgres:17.6 "docker-entrypoint.s…" postgres 20 minutes ago Up 8 seconds (healthy) 5432/tcp
|
||||
mtusi2026lab3-redis-1 redis:7.4.2-alpine "docker-entrypoint.s…" redis 20 minutes ago Up 9 seconds (healthy) 6379/tcp
|
||||
./scripts/compose.sh up -d --wait --wait-timeout 60 api lb
|
||||
Container mtusi2026lab3-redis-1 Running
|
||||
Container mtusi2026lab3-api-5 Running
|
||||
Container mtusi2026lab3-api-6 Running
|
||||
Container mtusi2026lab3-lb-1 Running
|
||||
Container mtusi2026lab3-postgres-1 Running
|
||||
Container mtusi2026lab3-postgres-1 Waiting
|
||||
Container mtusi2026lab3-postgres-1 Healthy
|
||||
Container mtusi2026lab3-migrate-1 Starting
|
||||
Container mtusi2026lab3-migrate-1 Started
|
||||
Container mtusi2026lab3-redis-1 Waiting
|
||||
Container mtusi2026lab3-migrate-1 Waiting
|
||||
Container mtusi2026lab3-redis-1 Healthy
|
||||
Container mtusi2026lab3-migrate-1 Exited
|
||||
Container mtusi2026lab3-api-5 Waiting
|
||||
Container mtusi2026lab3-api-6 Waiting
|
||||
Container mtusi2026lab3-api-5 Healthy
|
||||
Container mtusi2026lab3-api-6 Healthy
|
||||
Container mtusi2026lab3-postgres-1 Waiting
|
||||
Container mtusi2026lab3-redis-1 Waiting
|
||||
Container mtusi2026lab3-migrate-1 Waiting
|
||||
Container mtusi2026lab3-api-5 Waiting
|
||||
Container mtusi2026lab3-api-6 Waiting
|
||||
Container mtusi2026lab3-lb-1 Waiting
|
||||
Container mtusi2026lab3-migrate-1 Exited
|
||||
Container mtusi2026lab3-lb-1 Healthy
|
||||
Container mtusi2026lab3-postgres-1 Healthy
|
||||
Container mtusi2026lab3-redis-1 Healthy
|
||||
Container mtusi2026lab3-api-5 Healthy
|
||||
Container mtusi2026lab3-api-6 Healthy
|
||||
|
||||
$ make test-failover
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
mtusi2026lab3-api-5 messenger-lab3:local "dotnet Messenger.Ap…" api 3 minutes ago Up 9 seconds (healthy) 8080/tcp
|
||||
mtusi2026lab3-api-6 messenger-lab3:local "dotnet Messenger.Ap…" api 3 minutes ago Up 9 seconds (healthy) 8080/tcp
|
||||
mtusi2026lab3-lb-1 haproxy:3.2.7-alpine "docker-entrypoint.s…" lb 20 minutes ago Up 9 seconds (healthy) 127.0.0.1:18080->8080/tcp
|
||||
mtusi2026lab3-migrate-1 messenger-lab3:local "dotnet Messenger.Ap…" migrate 8 seconds ago Exited (0) 1 second ago
|
||||
mtusi2026lab3-postgres-1 postgres:17.6 "docker-entrypoint.s…" postgres 20 minutes ago Up 12 seconds (healthy) 5432/tcp
|
||||
mtusi2026lab3-redis-1 redis:7.4.2-alpine "docker-entrypoint.s…" redis 20 minutes ago Up 12 seconds (healthy) 6379/tcp
|
||||
.venv/bin/python tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://127.0.0.1:18080"
|
||||
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||
{"observed_instances_before": 2, "successful_writes": 124, "failed_attempts": 1, "first_recovery_seconds": 1.497}
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
|
||||
$ make restore-api
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
mtusi2026lab3-api-5 messenger-lab3:local "dotnet Messenger.Ap…" api 3 minutes ago Up 33 seconds (healthy) 8080/tcp
|
||||
mtusi2026lab3-api-6 messenger-lab3:local "dotnet Messenger.Ap…" api 3 minutes ago Exited (0) 14 seconds ago
|
||||
mtusi2026lab3-lb-1 haproxy:3.2.7-alpine "docker-entrypoint.s…" lb 21 minutes ago Up 33 seconds (healthy) 127.0.0.1:18080->8080/tcp
|
||||
mtusi2026lab3-migrate-1 messenger-lab3:local "dotnet Messenger.Ap…" migrate 33 seconds ago Exited (0) 25 seconds ago
|
||||
mtusi2026lab3-postgres-1 postgres:17.6 "docker-entrypoint.s…" postgres 21 minutes ago Up 36 seconds (healthy) 5432/tcp
|
||||
mtusi2026lab3-redis-1 redis:7.4.2-alpine "docker-entrypoint.s…" redis 21 minutes ago Up 36 seconds (healthy) 6379/tcp
|
||||
./scripts/compose.sh up -d --wait --wait-timeout 60 api lb
|
||||
Container mtusi2026lab3-postgres-1 Running
|
||||
Container mtusi2026lab3-redis-1 Running
|
||||
Container mtusi2026lab3-api-5 Running
|
||||
Container mtusi2026lab3-lb-1 Running
|
||||
Container mtusi2026lab3-postgres-1 Waiting
|
||||
Container mtusi2026lab3-postgres-1 Healthy
|
||||
Container mtusi2026lab3-migrate-1 Starting
|
||||
Container mtusi2026lab3-migrate-1 Started
|
||||
Container mtusi2026lab3-redis-1 Waiting
|
||||
Container mtusi2026lab3-migrate-1 Waiting
|
||||
Container mtusi2026lab3-redis-1 Healthy
|
||||
Container mtusi2026lab3-migrate-1 Exited
|
||||
Container mtusi2026lab3-api-6 Starting
|
||||
Container mtusi2026lab3-api-6 Started
|
||||
Container mtusi2026lab3-api-5 Waiting
|
||||
Container mtusi2026lab3-api-6 Waiting
|
||||
Container mtusi2026lab3-api-5 Healthy
|
||||
Container mtusi2026lab3-api-6 Healthy
|
||||
Container mtusi2026lab3-redis-1 Waiting
|
||||
Container mtusi2026lab3-migrate-1 Waiting
|
||||
Container mtusi2026lab3-api-5 Waiting
|
||||
Container mtusi2026lab3-api-6 Waiting
|
||||
Container mtusi2026lab3-lb-1 Waiting
|
||||
Container mtusi2026lab3-postgres-1 Waiting
|
||||
Container mtusi2026lab3-lb-1 Healthy
|
||||
Container mtusi2026lab3-postgres-1 Healthy
|
||||
Container mtusi2026lab3-redis-1 Healthy
|
||||
Container mtusi2026lab3-migrate-1 Exited
|
||||
Container mtusi2026lab3-api-5 Healthy
|
||||
Container mtusi2026lab3-api-6 Healthy
|
||||
|
||||
$ make test-idempotency-modes
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
mtusi2026lab3-api-5 messenger-lab3:local "dotnet Messenger.Ap…" api 3 minutes ago Up 40 seconds (healthy) 8080/tcp
|
||||
mtusi2026lab3-api-6 messenger-lab3:local "dotnet Messenger.Ap…" api 3 minutes ago Up 5 seconds (healthy) 8080/tcp
|
||||
mtusi2026lab3-lb-1 haproxy:3.2.7-alpine "docker-entrypoint.s…" lb 21 minutes ago Up 41 seconds (healthy) 127.0.0.1:18080->8080/tcp
|
||||
mtusi2026lab3-migrate-1 messenger-lab3:local "dotnet Messenger.Ap…" migrate 40 seconds ago Exited (0) 6 seconds ago
|
||||
mtusi2026lab3-postgres-1 postgres:17.6 "docker-entrypoint.s…" postgres 21 minutes ago Up 43 seconds (healthy) 5432/tcp
|
||||
mtusi2026lab3-redis-1 redis:7.4.2-alpine "docker-entrypoint.s…" redis 21 minutes ago Up 44 seconds (healthy) 6379/tcp
|
||||
.venv/bin/python student-tests/mode_tests.py --base-url "http://127.0.0.1:18080"
|
||||
{
|
||||
"verified_at": "2026-11-01T23:10:04Z",
|
||||
"instances": [
|
||||
"a73011a405974f049c4657cd9012353c",
|
||||
"f31a70a93690433f800e24ab887fadcc"
|
||||
],
|
||||
"replay_instances": [
|
||||
"a73011a405974f049c4657cd9012353c",
|
||||
"f31a70a93690433f800e24ab887fadcc"
|
||||
],
|
||||
"api_containers": [
|
||||
"fba3c592906dee4a49eb13dadcc8f5312774b867174ac16affa2667942bdf8c4",
|
||||
"251c4a8ff6aca5e1a37f6e2201e47e8c7da9ecef47c3484d63ee52dd892fa440"
|
||||
],
|
||||
"checks": [
|
||||
"one session served by at least two API processes",
|
||||
"32 concurrent requests across replicas create one message; absent attachments equals []",
|
||||
"changed body conflicts; user/chat scopes are independent; access rechecked",
|
||||
"24-hour expiry stored in PostgreSQL; expired key can be reused",
|
||||
"5xx rolls back message and key together; retry succeeds",
|
||||
"revoked token cannot replay an existing result"
|
||||
]
|
||||
}
|
||||
{
|
||||
"verified_at": "2026-11-01T23:10:18Z",
|
||||
"instances": [
|
||||
"a57245197fc24e26bfb9c3a7ec513ca3",
|
||||
"cc49c15f31074b10b0011dc1efad2340"
|
||||
],
|
||||
"replay_instances": [
|
||||
"a57245197fc24e26bfb9c3a7ec513ca3",
|
||||
"cc49c15f31074b10b0011dc1efad2340"
|
||||
],
|
||||
"api_containers": [
|
||||
"57e71884095f659c5717368a4cc583391c4bfff12193916a6494de4ccb29372f",
|
||||
"02b139a5546a98631290e8c341d129dabbf47cc67e0fa4079eb0ac76a34d63b1"
|
||||
],
|
||||
"checks": [
|
||||
"one session served by at least two API processes",
|
||||
"32 concurrent requests across replicas create one message; absent attachments equals []",
|
||||
"changed body conflicts; user/chat scopes are independent; access rechecked",
|
||||
"24-hour expiry stored in PostgreSQL; expired key can be reused",
|
||||
"5xx rolls back message and key together; retry succeeds",
|
||||
"revoked token cannot replay an existing result"
|
||||
]
|
||||
}
|
||||
Container mtusi2026lab3-api-5 Recreate
|
||||
Container mtusi2026lab3-api-6 Recreate
|
||||
Container mtusi2026lab3-api-5 Recreated
|
||||
Container mtusi2026lab3-api-6 Recreated
|
||||
Container mtusi2026lab3-api-6 Starting
|
||||
Container mtusi2026lab3-api-6 Started
|
||||
Container mtusi2026lab3-api-5 Starting
|
||||
Container mtusi2026lab3-api-5 Started
|
||||
|
||||
$ make test-expiry
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
mtusi2026lab3-api-5 messenger-lab3:local "dotnet Messenger.Ap…" api 3 seconds ago Up 2 seconds (health: starting) 8080/tcp
|
||||
mtusi2026lab3-api-6 messenger-lab3:local "dotnet Messenger.Ap…" api 3 seconds ago Up 2 seconds (health: starting) 8080/tcp
|
||||
mtusi2026lab3-lb-1 haproxy:3.2.7-alpine "docker-entrypoint.s…" lb 22 minutes ago Up About a minute (healthy) 127.0.0.1:18080->8080/tcp
|
||||
mtusi2026lab3-migrate-1 messenger-lab3:local "dotnet Messenger.Ap…" migrate About a minute ago Exited (0) 37 seconds ago
|
||||
mtusi2026lab3-postgres-1 postgres:17.6 "docker-entrypoint.s…" postgres 22 minutes ago Up About a minute (healthy) 5432/tcp
|
||||
mtusi2026lab3-redis-1 redis:7.4.2-alpine "docker-entrypoint.s…" redis 22 minutes ago Up About a minute (healthy) 6379/tcp
|
||||
.venv/bin/python student-tests/mode_tests.py --base-url "http://127.0.0.1:18080" --expiry
|
||||
Container mtusi2026lab3-api-5 Recreate
|
||||
Container mtusi2026lab3-api-6 Recreate
|
||||
Container mtusi2026lab3-api-5 Recreated
|
||||
Container mtusi2026lab3-api-6 Recreated
|
||||
Container mtusi2026lab3-api-6 Starting
|
||||
Container mtusi2026lab3-api-6 Started
|
||||
Container mtusi2026lab3-api-5 Starting
|
||||
Container mtusi2026lab3-api-5 Started
|
||||
PASS: TTL=2 expires in PostgreSQL authentication and Redis cache
|
||||
PASS: Lab2 password, Basic, Bearer, input validation and session lifecycle
|
||||
Container mtusi2026lab3-api-6 Recreate
|
||||
Container mtusi2026lab3-api-5 Recreate
|
||||
Container mtusi2026lab3-api-5 Recreated
|
||||
Container mtusi2026lab3-api-6 Recreated
|
||||
Container mtusi2026lab3-api-5 Starting
|
||||
Container mtusi2026lab3-api-5 Started
|
||||
Container mtusi2026lab3-api-6 Starting
|
||||
Container mtusi2026lab3-api-6 Started
|
||||
|
||||
$ make test-grade4
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
mtusi2026lab3-api-5 messenger-lab3:local "dotnet Messenger.Ap…" api 3 seconds ago Up 1 second (health: starting) 8080/tcp
|
||||
mtusi2026lab3-api-6 messenger-lab3:local "dotnet Messenger.Ap…" api 3 seconds ago Up 1 second (health: starting) 8080/tcp
|
||||
mtusi2026lab3-lb-1 haproxy:3.2.7-alpine "docker-entrypoint.s…" lb 22 minutes ago Up About a minute (healthy) 127.0.0.1:18080->8080/tcp
|
||||
mtusi2026lab3-migrate-1 messenger-lab3:local "dotnet Messenger.Ap…" migrate About a minute ago Exited (0) 51 seconds ago
|
||||
mtusi2026lab3-postgres-1 postgres:17.6 "docker-entrypoint.s…" postgres 22 minutes ago Up About a minute (healthy) 5432/tcp
|
||||
mtusi2026lab3-redis-1 redis:7.4.2-alpine "docker-entrypoint.s…" redis 22 minutes ago Up About a minute (healthy) 6379/tcp
|
||||
.venv/bin/python student-tests/availability_tests.py --base-url "http://127.0.0.1:18080"
|
||||
Testing graceful stop of 7fc11b71698d
|
||||
Testing immediate stop of 8ff0d3425d06
|
||||
Building replacement image
|
||||
Testing sequential replacement under mixed traffic
|
||||
{
|
||||
"verified_at": "2026-11-01T23:10:36Z",
|
||||
"failures": [
|
||||
{
|
||||
"duration_seconds": 16.0121,
|
||||
"requested_seconds": 16,
|
||||
"concurrency": 8,
|
||||
"successful_requests": 4700,
|
||||
"failed_requests": 8,
|
||||
"successful_rps": 293.528,
|
||||
"error_ratio": 0.001699,
|
||||
"successful_latency_ms": {
|
||||
"p50": 9.802,
|
||||
"p95": 80.053,
|
||||
"p99": 93.193
|
||||
},
|
||||
"all_attempt_latency_ms": {
|
||||
"p50": 9.81,
|
||||
"p95": 80.242,
|
||||
"p99": 94.732
|
||||
},
|
||||
"status_counts": {
|
||||
"200": 2346,
|
||||
"201": 2354,
|
||||
"503": 8
|
||||
},
|
||||
"instance_counts": {
|
||||
"3a26b3036963466ea997dc665b565926": 297,
|
||||
"33f1c8ae80d145809bfba32f4e5fd3a3": 4403
|
||||
},
|
||||
"actions": [
|
||||
{
|
||||
"started_after_seconds": 2.004297334002331,
|
||||
"finished_after_seconds": 2.3088578750030138,
|
||||
"result": {
|
||||
"container": "7fc11b71698d4aa93a2e58a38c671b16f7566f9290b83c965c5f430461ad96b9",
|
||||
"instance": "3a26b3036963466ea997dc665b565926",
|
||||
"running_after_action": false
|
||||
}
|
||||
}
|
||||
],
|
||||
"observations": [],
|
||||
"mode": "graceful",
|
||||
"recovery_seconds": 1.117,
|
||||
"integrity": {
|
||||
"confirmed_writes": 2354,
|
||||
"stored_messages": 2354,
|
||||
"no_duplicate_text": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"duration_seconds": 16.0367,
|
||||
"requested_seconds": 16,
|
||||
"concurrency": 8,
|
||||
"successful_requests": 4730,
|
||||
"failed_requests": 11,
|
||||
"successful_rps": 294.948,
|
||||
"error_ratio": 0.00232,
|
||||
"successful_latency_ms": {
|
||||
"p50": 9.718,
|
||||
"p95": 78.168,
|
||||
"p99": 90.788
|
||||
},
|
||||
"all_attempt_latency_ms": {
|
||||
"p50": 9.732,
|
||||
"p95": 78.319,
|
||||
"p99": 91.752
|
||||
},
|
||||
"status_counts": {
|
||||
"200": 2359,
|
||||
"201": 2371,
|
||||
"0": 6,
|
||||
"503": 5
|
||||
},
|
||||
"instance_counts": {
|
||||
"03a65831924146bf98b9c8beabd73235": 4403,
|
||||
"33f1c8ae80d145809bfba32f4e5fd3a3": 327
|
||||
},
|
||||
"actions": [
|
||||
{
|
||||
"started_after_seconds": 2.002569542004494,
|
||||
"finished_after_seconds": 2.2908867499791086,
|
||||
"result": {
|
||||
"container": "8ff0d3425d061df5856f28e93605421c22d64f07cfa48379444f73583be84b8f",
|
||||
"instance": "33f1c8ae80d145809bfba32f4e5fd3a3",
|
||||
"running_after_action": false
|
||||
}
|
||||
}
|
||||
],
|
||||
"observations": [],
|
||||
"mode": "immediate",
|
||||
"recovery_seconds": 0.304,
|
||||
"integrity": {
|
||||
"confirmed_writes": 2371,
|
||||
"stored_messages": 2371,
|
||||
"no_duplicate_text": true
|
||||
}
|
||||
}
|
||||
],
|
||||
"rolling_update": {
|
||||
"duration_seconds": 45.0733,
|
||||
"requested_seconds": 45,
|
||||
"concurrency": 8,
|
||||
"successful_requests": 12960,
|
||||
"failed_requests": 0,
|
||||
"successful_rps": 287.532,
|
||||
"error_ratio": 0.0,
|
||||
"successful_latency_ms": {
|
||||
"p50": 11.354,
|
||||
"p95": 80.201,
|
||||
"p99": 103.951
|
||||
},
|
||||
"all_attempt_latency_ms": {
|
||||
"p50": 11.354,
|
||||
"p95": 80.201,
|
||||
"p99": 103.951
|
||||
},
|
||||
"status_counts": {
|
||||
"200": 6480,
|
||||
"201": 6480
|
||||
},
|
||||
"instance_counts": {
|
||||
"854205519c6a49eaba8112473f0050e2": 1032,
|
||||
"03a65831924146bf98b9c8beabd73235": 635,
|
||||
"5215daa9aa9e48b193bdf64ff314ff2d": 5823,
|
||||
"3983ae67ecf94704a04dce24f8174384": 5470
|
||||
},
|
||||
"actions": [
|
||||
{
|
||||
"started_after_seconds": 2.0046813749941066,
|
||||
"finished_after_seconds": 11.803809415985597,
|
||||
"result": [
|
||||
{
|
||||
"old_container": "7fc11b71698d4aa93a2e58a38c671b16f7566f9290b83c965c5f430461ad96b9",
|
||||
"old_instance": "03a65831924146bf98b9c8beabd73235",
|
||||
"old_image": "sha256:7d07e2377a2c575fa2db59d2cee807c2e24a2e8c37a54c8df6b3714a58b0516f",
|
||||
"new_container": "8b7f4d1da142af7d0af4cbc6d2c2b85dff74e46c2e9c86c1be2ee99524ecc748",
|
||||
"new_instance": "5215daa9aa9e48b193bdf64ff314ff2d",
|
||||
"new_image": "sha256:9498c2a6ccbbd5ed5b31a80ea7bfe8c8d4e477a5b667f8cd93b1d8947876ed0c"
|
||||
},
|
||||
{
|
||||
"old_container": "8ff0d3425d061df5856f28e93605421c22d64f07cfa48379444f73583be84b8f",
|
||||
"old_instance": "854205519c6a49eaba8112473f0050e2",
|
||||
"old_image": "sha256:7d07e2377a2c575fa2db59d2cee807c2e24a2e8c37a54c8df6b3714a58b0516f",
|
||||
"new_container": "d23b99a781064bdd4221cbdcab862b83ab6f1928f41ba0fa18c3ad25a4c6400d",
|
||||
"new_instance": "3983ae67ecf94704a04dce24f8174384",
|
||||
"new_image": "sha256:9498c2a6ccbbd5ed5b31a80ea7bfe8c8d4e477a5b667f8cd93b1d8947876ed0c"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"observations": [],
|
||||
"integrity": {
|
||||
"confirmed_writes": 6480,
|
||||
"stored_messages": 6480,
|
||||
"no_duplicate_text": true
|
||||
}
|
||||
},
|
||||
"infrastructure": {
|
||||
"api_ports_published": false,
|
||||
"api_containers": [
|
||||
{
|
||||
"id": "8b7f4d1da142af7d0af4cbc6d2c2b85dff74e46c2e9c86c1be2ee99524ecc748",
|
||||
"image": "sha256:9498c2a6ccbbd5ed5b31a80ea7bfe8c8d4e477a5b667f8cd93b1d8947876ed0c",
|
||||
"cpu_limit": 1.0,
|
||||
"memory_limit": 402653184
|
||||
},
|
||||
{
|
||||
"id": "d23b99a781064bdd4221cbdcab862b83ab6f1928f41ba0fa18c3ad25a4c6400d",
|
||||
"image": "sha256:9498c2a6ccbbd5ed5b31a80ea7bfe8c8d4e477a5b667f8cd93b1d8947876ed0c",
|
||||
"cpu_limit": 1.0,
|
||||
"memory_limit": 402653184
|
||||
}
|
||||
],
|
||||
"migrations": "1,2"
|
||||
}
|
||||
}
|
||||
|
||||
$ make research-grade5
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
mtusi2026lab3-api-7 messenger-lab3:local "dotnet Messenger.Ap…" api 45 seconds ago Up 43 seconds (healthy) 8080/tcp
|
||||
mtusi2026lab3-api-8 messenger-lab3:local "dotnet Messenger.Ap…" api 40 seconds ago Up 39 seconds (healthy) 8080/tcp
|
||||
mtusi2026lab3-lb-1 haproxy:3.2.7-alpine "docker-entrypoint.s…" lb 24 minutes ago Up 3 minutes (healthy) 127.0.0.1:18080->8080/tcp
|
||||
mtusi2026lab3-migrate-1 sha256:7d07e2377a2c575fa2db59d2cee807c2e24a2e8c37a54c8df6b3714a58b0516f "dotnet Messenger.Ap…" migrate 3 minutes ago Exited (0) 2 minutes ago
|
||||
mtusi2026lab3-postgres-1 postgres:17.6 "docker-entrypoint.s…" postgres 24 minutes ago Up 3 minutes (healthy) 5432/tcp
|
||||
mtusi2026lab3-redis-1 redis:7.4.2-alpine "docker-entrypoint.s…" redis 24 minutes ago Up 3 minutes (healthy) 6379/tcp
|
||||
.venv/bin/python student-tests/scaling_research.py --base-url "http://127.0.0.1:18080"
|
||||
Configuring fixed: 1 API, 1.0 CPU/768 MiB each
|
||||
fixed-1, C=4, trial=1: 218.93 RPS, p95=71.57 ms, errors=0
|
||||
fixed-1, C=4, trial=2: 227.971 RPS, p95=64.744 ms, errors=0
|
||||
fixed-1, C=4, trial=3: 244.862 RPS, p95=69.017 ms, errors=0
|
||||
fixed-1, C=16, trial=4: 274.184 RPS, p95=103.592 ms, errors=0
|
||||
fixed-1, C=16, trial=5: 282.779 RPS, p95=100.604 ms, errors=0
|
||||
fixed-1, C=16, trial=6: 275.06 RPS, p95=103.552 ms, errors=0
|
||||
fixed-1, C=64, trial=7: 308.337 RPS, p95=303.245 ms, errors=0
|
||||
fixed-1, C=64, trial=8: 287.415 RPS, p95=391.411 ms, errors=0
|
||||
fixed-1, C=64, trial=9: 302.941 RPS, p95=307.507 ms, errors=0
|
||||
Configuring fixed: 2 API, 0.5 CPU/384 MiB each
|
||||
fixed-2, C=64, trial=10: 296.067 RPS, p95=406.547 ms, errors=0
|
||||
fixed-2, C=64, trial=11: 275.592 RPS, p95=456.591 ms, errors=0
|
||||
fixed-2, C=64, trial=12: 270.695 RPS, p95=493.392 ms, errors=0
|
||||
fixed-2, C=16, trial=13: 251.76 RPS, p95=161.718 ms, errors=0
|
||||
fixed-2, C=16, trial=14: 267.997 RPS, p95=106.101 ms, errors=0
|
||||
fixed-2, C=16, trial=15: 284.831 RPS, p95=101.227 ms, errors=0
|
||||
fixed-2, C=4, trial=16: 259.315 RPS, p95=65.439 ms, errors=0
|
||||
fixed-2, C=4, trial=17: 232.474 RPS, p95=68.486 ms, errors=0
|
||||
fixed-2, C=4, trial=18: 220.536 RPS, p95=68.443 ms, errors=0
|
||||
Configuring fixed: 4 API, 0.25 CPU/192 MiB each
|
||||
fixed-4, C=4, trial=19: 146.161 RPS, p95=87.818 ms, errors=0
|
||||
fixed-4, C=4, trial=20: 116.282 RPS, p95=102.574 ms, errors=0
|
||||
fixed-4, C=4, trial=21: 124.453 RPS, p95=102.817 ms, errors=0
|
||||
fixed-4, C=16, trial=22: 197.706 RPS, p95=226.847 ms, errors=0
|
||||
fixed-4, C=16, trial=23: 227.163 RPS, p95=202.483 ms, errors=0
|
||||
fixed-4, C=16, trial=24: 231.947 RPS, p95=221.725 ms, errors=0
|
||||
fixed-4, C=64, trial=25: 234.342 RPS, p95=577.561 ms, errors=0
|
||||
fixed-4, C=64, trial=26: 232.131 RPS, p95=682.007 ms, errors=0
|
||||
fixed-4, C=64, trial=27: 247.101 RPS, p95=501.88 ms, errors=0
|
||||
Configuring growing: 1 API, 1 CPU/384 MiB each
|
||||
growing-1, C=4, trial=28: 258.723 RPS, p95=62.134 ms, errors=0
|
||||
growing-1, C=4, trial=29: 239.539 RPS, p95=63.995 ms, errors=0
|
||||
growing-1, C=4, trial=30: 250.297 RPS, p95=65.691 ms, errors=0
|
||||
growing-1, C=16, trial=31: 299.464 RPS, p95=101.129 ms, errors=0
|
||||
growing-1, C=16, trial=32: 292.921 RPS, p95=102.186 ms, errors=0
|
||||
growing-1, C=16, trial=33: 282.668 RPS, p95=104.612 ms, errors=0
|
||||
growing-1, C=64, trial=34: 303.063 RPS, p95=390.498 ms, errors=0
|
||||
growing-1, C=64, trial=35: 285.691 RPS, p95=312.428 ms, errors=0
|
||||
growing-1, C=64, trial=36: 296.505 RPS, p95=386.697 ms, errors=0
|
||||
Configuring growing: 2 API, 1 CPU/384 MiB each
|
||||
growing-2, C=64, trial=37: 269.672 RPS, p95=410.645 ms, errors=0
|
||||
growing-2, C=64, trial=38: 282.83 RPS, p95=396.819 ms, errors=0
|
||||
growing-2, C=64, trial=39: 268.931 RPS, p95=488.041 ms, errors=0
|
||||
growing-2, C=16, trial=40: 258.069 RPS, p95=109.077 ms, errors=0
|
||||
growing-2, C=16, trial=41: 261.656 RPS, p95=107.965 ms, errors=0
|
||||
growing-2, C=16, trial=42: 273.803 RPS, p95=103.887 ms, errors=0
|
||||
growing-2, C=4, trial=43: 250.42 RPS, p95=67.655 ms, errors=0
|
||||
growing-2, C=4, trial=44: 269.121 RPS, p95=63.087 ms, errors=0
|
||||
growing-2, C=4, trial=45: 260.993 RPS, p95=65.864 ms, errors=0
|
||||
Configuring growing: 4 API, 1 CPU/384 MiB each
|
||||
growing-4, C=4, trial=46: 250.31 RPS, p95=46.464 ms, errors=0
|
||||
growing-4, C=4, trial=47: 245.033 RPS, p95=51.051 ms, errors=0
|
||||
growing-4, C=4, trial=48: 185.652 RPS, p95=70.995 ms, errors=0
|
||||
growing-4, C=16, trial=49: 223.252 RPS, p95=176.455 ms, errors=0
|
||||
growing-4, C=16, trial=50: 236.934 RPS, p95=108.311 ms, errors=0
|
||||
growing-4, C=16, trial=51: 249.622 RPS, p95=111.575 ms, errors=0
|
||||
growing-4, C=64, trial=52: 91.187 RPS, p95=1715.727 ms, errors=21
|
||||
growing-4, C=64, trial=53: 182.5 RPS, p95=894.66 ms, errors=0
|
||||
growing-4, C=64, trial=54: 229.551 RPS, p95=592.614 ms, errors=0
|
||||
separate, C=16, trial=55: 144.195 RPS, p95=205.051 ms, errors=0
|
||||
batched, C=16, trial=56: 179.536 RPS, p95=195.014 ms, errors=0
|
||||
batched, C=16, trial=57: 219.126 RPS, p95=111.847 ms, errors=0
|
||||
separate, C=16, trial=58: 244.459 RPS, p95=108.102 ms, errors=0
|
||||
separate, C=16, trial=59: 90.853 RPS, p95=109.924 ms, errors=984
|
||||
batched, C=16, trial=60: 272.021 RPS, p95=112.969 ms, errors=0
|
||||
postgres-half_cpu, C=64, trial=61: 217.905 RPS, p95=611.418 ms, errors=0
|
||||
postgres-one_cpu, C=64, trial=62: 313.186 RPS, p95=700.798 ms, errors=0
|
||||
postgres-one_cpu, C=64, trial=63: 395.521 RPS, p95=333.666 ms, errors=0
|
||||
postgres-half_cpu, C=64, trial=64: 143.112 RPS, p95=1622.857 ms, errors=40
|
||||
postgres-half_cpu, C=64, trial=65: 289.64 RPS, p95=482.532 ms, errors=0
|
||||
postgres-one_cpu, C=64, trial=66: 528.555 RPS, p95=249.648 ms, errors=0
|
||||
PASS: scaling research saved to evidence/scaling.json and docs/SCALING.md
|
||||
|
||||
$ make test
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
mtusi2026lab3-api-7 messenger-lab3:local "dotnet Messenger.Ap…" api 7 seconds ago Up 5 seconds (healthy) 8080/tcp
|
||||
mtusi2026lab3-api-8 messenger-lab3:local "dotnet Messenger.Ap…" api 7 seconds ago Up 5 seconds (healthy) 8080/tcp
|
||||
mtusi2026lab3-lb-1 haproxy:3.2.7-alpine "docker-entrypoint.s…" lb 55 minutes ago Up 34 minutes (healthy) 127.0.0.1:18080->8080/tcp
|
||||
mtusi2026lab3-migrate-1 sha256:7d07e2377a2c575fa2db59d2cee807c2e24a2e8c37a54c8df6b3714a58b0516f "dotnet Messenger.Ap…" migrate 34 minutes ago Exited (0) 34 minutes ago
|
||||
mtusi2026lab3-postgres-1 postgres:17.6 "docker-entrypoint.s…" postgres 55 minutes ago Up 34 minutes (healthy) 5432/tcp
|
||||
mtusi2026lab3-redis-1 redis:7.4.2-alpine "docker-entrypoint.s…" redis 55 minutes ago Up 34 minutes (healthy) 6379/tcp
|
||||
.venv/bin/python tests/smoke.py --base-url "http://127.0.0.1:18080"
|
||||
PASS: lab3 public API scenario; infrastructure and grading evidence remain separate.
|
||||
|
||||
$ make student-test
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
mtusi2026lab3-api-7 messenger-lab3:local "dotnet Messenger.Ap…" api 18 seconds ago Up 16 seconds (healthy) 8080/tcp
|
||||
mtusi2026lab3-api-8 messenger-lab3:local "dotnet Messenger.Ap…" api 18 seconds ago Up 15 seconds (healthy) 8080/tcp
|
||||
mtusi2026lab3-lb-1 haproxy:3.2.7-alpine "docker-entrypoint.s…" lb 55 minutes ago Up 34 minutes (healthy) 127.0.0.1:18080->8080/tcp
|
||||
mtusi2026lab3-migrate-1 sha256:7d07e2377a2c575fa2db59d2cee807c2e24a2e8c37a54c8df6b3714a58b0516f "dotnet Messenger.Ap…" migrate 34 minutes ago Exited (0) 34 minutes ago
|
||||
mtusi2026lab3-postgres-1 postgres:17.6 "docker-entrypoint.s…" postgres 55 minutes ago Up 34 minutes (healthy) 5432/tcp
|
||||
mtusi2026lab3-redis-1 redis:7.4.2-alpine "docker-entrypoint.s…" redis 55 minutes ago Up 34 minutes (healthy) 6379/tcp
|
||||
.venv/bin/python student-tests/lab3_tests.py --base-url "http://127.0.0.1:18080"
|
||||
{
|
||||
"verified_at": "2026-11-01T23:44:11Z",
|
||||
"instances": [
|
||||
"7da2ce5fbaef4b6ab454444dede336a4",
|
||||
"827df2496f144a13acef36f7874bd549"
|
||||
],
|
||||
"replay_instances": [
|
||||
"7da2ce5fbaef4b6ab454444dede336a4",
|
||||
"827df2496f144a13acef36f7874bd549"
|
||||
],
|
||||
"api_containers": [
|
||||
"1b44a4bde083782dc07960bb4c1f30ecb3cdb02c39f61ac694b736660cdcf1ab",
|
||||
"1693de1f22081acc2fc8c24b7eb2f9d7696d3c5589f7b287c28aad2abfbdab21"
|
||||
],
|
||||
"checks": [
|
||||
"one session served by at least two API processes",
|
||||
"32 concurrent requests across replicas create one message; absent attachments equals []",
|
||||
"changed body conflicts; user/chat scopes are independent; access rechecked",
|
||||
"24-hour expiry stored in PostgreSQL; expired key can be reused",
|
||||
"5xx rolls back message and key together; retry succeeds",
|
||||
"revoked token cannot replay an existing result"
|
||||
]
|
||||
}
|
||||
|
||||
$ make test-ui
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
mtusi2026lab3-api-7 messenger-lab3:local "dotnet Messenger.Ap…" api 28 seconds ago Up 26 seconds (healthy) 8080/tcp
|
||||
mtusi2026lab3-api-8 messenger-lab3:local "dotnet Messenger.Ap…" api 28 seconds ago Up 25 seconds (healthy) 8080/tcp
|
||||
mtusi2026lab3-lb-1 haproxy:3.2.7-alpine "docker-entrypoint.s…" lb 55 minutes ago Up 35 minutes (healthy) 127.0.0.1:18080->8080/tcp
|
||||
mtusi2026lab3-migrate-1 sha256:7d07e2377a2c575fa2db59d2cee807c2e24a2e8c37a54c8df6b3714a58b0516f "dotnet Messenger.Ap…" migrate 35 minutes ago Exited (0) 34 minutes ago
|
||||
mtusi2026lab3-postgres-1 postgres:17.6 "docker-entrypoint.s…" postgres 55 minutes ago Up 35 minutes (healthy) 5432/tcp
|
||||
mtusi2026lab3-redis-1 redis:7.4.2-alpine "docker-entrypoint.s…" redis 55 minutes ago Up 35 minutes (healthy) 6379/tcp
|
||||
.venv/bin/python student-tests/ui_api_tests.py --base-url "http://127.0.0.1:18080"
|
||||
PASS: UI authentication, privacy, newest page, backwards pagination, cursor isolation; required API stays ascending
|
||||
|
||||
PASS: Lab3 checks completed
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"verified_at": "2026-11-01T23:10:18Z",
|
||||
"instances": [
|
||||
"a57245197fc24e26bfb9c3a7ec513ca3",
|
||||
"cc49c15f31074b10b0011dc1efad2340"
|
||||
],
|
||||
"replay_instances": [
|
||||
"a57245197fc24e26bfb9c3a7ec513ca3",
|
||||
"cc49c15f31074b10b0011dc1efad2340"
|
||||
],
|
||||
"api_containers": [
|
||||
"57e71884095f659c5717368a4cc583391c4bfff12193916a6494de4ccb29372f",
|
||||
"02b139a5546a98631290e8c341d129dabbf47cc67e0fa4079eb0ac76a34d63b1"
|
||||
],
|
||||
"checks": [
|
||||
"one session served by at least two API processes",
|
||||
"32 concurrent requests across replicas create one message; absent attachments equals []",
|
||||
"changed body conflicts; user/chat scopes are independent; access rechecked",
|
||||
"24-hour expiry stored in PostgreSQL; expired key can be reused",
|
||||
"5xx rolls back message and key together; retry succeeds",
|
||||
"revoked token cannot replay an existing result"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"verified_at": "2026-11-01T23:10:04Z",
|
||||
"instances": [
|
||||
"a73011a405974f049c4657cd9012353c",
|
||||
"f31a70a93690433f800e24ab887fadcc"
|
||||
],
|
||||
"replay_instances": [
|
||||
"a73011a405974f049c4657cd9012353c",
|
||||
"f31a70a93690433f800e24ab887fadcc"
|
||||
],
|
||||
"api_containers": [
|
||||
"fba3c592906dee4a49eb13dadcc8f5312774b867174ac16affa2667942bdf8c4",
|
||||
"251c4a8ff6aca5e1a37f6e2201e47e8c7da9ecef47c3484d63ee52dd892fa440"
|
||||
],
|
||||
"checks": [
|
||||
"one session served by at least two API processes",
|
||||
"32 concurrent requests across replicas create one message; absent attachments equals []",
|
||||
"changed body conflicts; user/chat scopes are independent; access rechecked",
|
||||
"24-hour expiry stored in PostgreSQL; expired key can be reused",
|
||||
"5xx rolls back message and key together; retry succeeds",
|
||||
"revoked token cannot replay an existing result"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"verified_at": "2026-11-02T15:55:17Z",
|
||||
"instances": [
|
||||
"a90e2f2fe96c4709966c68fa58e30a02",
|
||||
"f7bb77e4b20b497899f2a19da390afa1"
|
||||
],
|
||||
"replay_instances": [
|
||||
"a90e2f2fe96c4709966c68fa58e30a02",
|
||||
"f7bb77e4b20b497899f2a19da390afa1"
|
||||
],
|
||||
"api_containers": [
|
||||
"df9cf46dbd370689d41f904dd4e2a452d71b6c0cac1eb67d02251e4d410c446b",
|
||||
"72b18d455e884343b8fa54ae9e52da344e5012b461a26014ad7bed8184edd98d"
|
||||
],
|
||||
"checks": [
|
||||
"one session served by at least two API processes",
|
||||
"32 concurrent requests across replicas create one message; absent attachments equals []",
|
||||
"changed body conflicts; user/chat scopes are independent; access rechecked",
|
||||
"24-hour expiry stored in PostgreSQL; expired key can be reused",
|
||||
"5xx rolls back message and key together; retry succeeds",
|
||||
"revoked token cannot replay an existing result"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
Container mtusi2026lab3-postgres-1 Restarting
|
||||
Container mtusi2026lab3-redis-1 Restarting
|
||||
Container mtusi2026lab3-redis-1 Started
|
||||
Container mtusi2026lab3-postgres-1 Started
|
||||
Container mtusi2026lab3-postgres-1 Running
|
||||
Container mtusi2026lab3-redis-1 Running
|
||||
Container mtusi2026lab3-postgres-1 Waiting
|
||||
Container mtusi2026lab3-redis-1 Waiting
|
||||
Container mtusi2026lab3-redis-1 Healthy
|
||||
Container mtusi2026lab3-postgres-1 Healthy
|
||||
Container mtusi2026lab3-api-8 Restarting
|
||||
Container mtusi2026lab3-api-7 Restarting
|
||||
Container mtusi2026lab3-lb-1 Restarting
|
||||
Container mtusi2026lab3-lb-1 Started
|
||||
Container mtusi2026lab3-api-8 Started
|
||||
Container mtusi2026lab3-api-7 Started
|
||||
Container mtusi2026lab3-api-7 Running
|
||||
Container mtusi2026lab3-api-8 Running
|
||||
Container mtusi2026lab3-lb-1 Running
|
||||
Container mtusi2026lab3-postgres-1 Running
|
||||
Container mtusi2026lab3-redis-1 Running
|
||||
Container mtusi2026lab3-migrate-1 Recreate
|
||||
Container mtusi2026lab3-migrate-1 Recreated
|
||||
Container mtusi2026lab3-postgres-1 Waiting
|
||||
Container mtusi2026lab3-postgres-1 Healthy
|
||||
Container mtusi2026lab3-migrate-1 Starting
|
||||
Container mtusi2026lab3-migrate-1 Started
|
||||
Container mtusi2026lab3-redis-1 Waiting
|
||||
Container mtusi2026lab3-migrate-1 Waiting
|
||||
Container mtusi2026lab3-redis-1 Healthy
|
||||
Container mtusi2026lab3-migrate-1 Exited
|
||||
Container mtusi2026lab3-api-7 Waiting
|
||||
Container mtusi2026lab3-api-8 Waiting
|
||||
Container mtusi2026lab3-api-7 Healthy
|
||||
Container mtusi2026lab3-api-8 Healthy
|
||||
Container mtusi2026lab3-postgres-1 Waiting
|
||||
Container mtusi2026lab3-redis-1 Waiting
|
||||
Container mtusi2026lab3-migrate-1 Waiting
|
||||
Container mtusi2026lab3-api-7 Waiting
|
||||
Container mtusi2026lab3-api-8 Waiting
|
||||
Container mtusi2026lab3-lb-1 Waiting
|
||||
Container mtusi2026lab3-redis-1 Healthy
|
||||
Container mtusi2026lab3-lb-1 Healthy
|
||||
Container mtusi2026lab3-migrate-1 Exited
|
||||
Container mtusi2026lab3-postgres-1 Healthy
|
||||
Container mtusi2026lab3-api-7 Healthy
|
||||
Container mtusi2026lab3-api-8 Healthy
|
||||
PASS: all services restarted, original token and key replayed, one message, logout 401
|
||||
@@ -0,0 +1,85 @@
|
||||
{
|
||||
"verified_at": "2026-11-02T00:34:26Z",
|
||||
"before": {
|
||||
"postgres": [
|
||||
{
|
||||
"container": "7686673cedd3ea53ff051dc21d1da6b12b7d3657c0a9f71f9cc4e9ef47f38573",
|
||||
"started_at": "2026-11-01T23:09:06.905000722Z",
|
||||
"volumes": [
|
||||
"mtusi2026lab3_postgres_data"
|
||||
]
|
||||
}
|
||||
],
|
||||
"redis": [
|
||||
{
|
||||
"container": "521be7d42d5dc72bfb94127f11fff1f36bcd68e5bb6313485920fe5af95855f5",
|
||||
"started_at": "2026-11-01T23:09:06.614997138Z",
|
||||
"volumes": [
|
||||
"127d454245a4f45010007d5a45966b3edb660f38f82206b8362ce356e3309b8c"
|
||||
]
|
||||
}
|
||||
],
|
||||
"api": [
|
||||
{
|
||||
"container": "1b44a4bde083782dc07960bb4c1f30ecb3cdb02c39f61ac694b736660cdcf1ab",
|
||||
"started_at": "2026-11-01T23:43:44.988315088Z",
|
||||
"volumes": []
|
||||
},
|
||||
{
|
||||
"container": "1693de1f22081acc2fc8c24b7eb2f9d7696d3c5589f7b287c28aad2abfbdab21",
|
||||
"started_at": "2026-11-01T23:43:45.279696796Z",
|
||||
"volumes": []
|
||||
}
|
||||
],
|
||||
"lb": [
|
||||
{
|
||||
"container": "a1944ce6b67510a37014bff5ac0ea33abf867d01270ae72c2a2d987c0c2b57d8",
|
||||
"started_at": "2026-11-01T23:09:09.663459167Z",
|
||||
"volumes": []
|
||||
}
|
||||
]
|
||||
},
|
||||
"after": {
|
||||
"postgres": [
|
||||
{
|
||||
"container": "7686673cedd3ea53ff051dc21d1da6b12b7d3657c0a9f71f9cc4e9ef47f38573",
|
||||
"started_at": "2026-11-02T00:34:17.2162673Z",
|
||||
"volumes": [
|
||||
"mtusi2026lab3_postgres_data"
|
||||
]
|
||||
}
|
||||
],
|
||||
"redis": [
|
||||
{
|
||||
"container": "521be7d42d5dc72bfb94127f11fff1f36bcd68e5bb6313485920fe5af95855f5",
|
||||
"started_at": "2026-11-02T00:34:17.077376384Z",
|
||||
"volumes": [
|
||||
"127d454245a4f45010007d5a45966b3edb660f38f82206b8362ce356e3309b8c"
|
||||
]
|
||||
}
|
||||
],
|
||||
"api": [
|
||||
{
|
||||
"container": "1b44a4bde083782dc07960bb4c1f30ecb3cdb02c39f61ac694b736660cdcf1ab",
|
||||
"started_at": "2026-11-02T00:34:20.232257302Z",
|
||||
"volumes": []
|
||||
},
|
||||
{
|
||||
"container": "1693de1f22081acc2fc8c24b7eb2f9d7696d3c5589f7b287c28aad2abfbdab21",
|
||||
"started_at": "2026-11-02T00:34:20.185168635Z",
|
||||
"volumes": []
|
||||
}
|
||||
],
|
||||
"lb": [
|
||||
{
|
||||
"container": "a1944ce6b67510a37014bff5ac0ea33abf867d01270ae72c2a2d987c0c2b57d8",
|
||||
"started_at": "2026-11-02T00:34:20.159904968Z",
|
||||
"volumes": []
|
||||
}
|
||||
]
|
||||
},
|
||||
"same_token": true,
|
||||
"same_message": true,
|
||||
"replay_without_duplicates": true,
|
||||
"logout_status": 401
|
||||
}
|
||||
|
After Width: | Height: | Size: 187 KiB |
|
After Width: | Height: | Size: 82 KiB |
@@ -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 @@
|
||||
matplotlib==3.11.2
|
||||
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
root="$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)"
|
||||
exec docker compose --project-name mtusi2026lab3 --project-directory "$root" "$@"
|
||||
@@ -0,0 +1,57 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Stop one actual API container, show surviving responses, then always restore it."""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import signal
|
||||
import sys
|
||||
import time
|
||||
from urllib.request import urlopen
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "student-tests"))
|
||||
from cluster import alias, api_ids, docker, wait_api
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--instance", required=True)
|
||||
parser.add_argument("--seconds", type=int, default=15)
|
||||
parser.add_argument("--base-url", default="http://127.0.0.1:18080")
|
||||
args = parser.parse_args()
|
||||
if not re.fullmatch(r"[a-f0-9]{32}", args.instance) or not 8 <= args.seconds <= 60:
|
||||
parser.error("instance must be a 32-character API ID; seconds must be 8–60")
|
||||
containers = api_ids()
|
||||
if len(containers) < 2:
|
||||
parser.error("At least two running API replicas are required")
|
||||
identities = {alias(container): container for container in containers}
|
||||
if args.instance not in identities:
|
||||
parser.error("This API instance is no longer running; copy a fresh command from the panel")
|
||||
wait_api(args.base_url, len(containers))
|
||||
target = identities[args.instance]
|
||||
print("Останавливаем API " + args.instance[:8] + ". Откройте схему и отправляйте сообщения.", flush=True)
|
||||
try:
|
||||
docker("stop", "--time", "2", target)
|
||||
until = time.monotonic() + args.seconds
|
||||
while time.monotonic() < until:
|
||||
started = time.monotonic()
|
||||
try:
|
||||
with urlopen(args.base_url + "/health/ready", timeout=2) as response:
|
||||
print(json.dumps({"status": response.status,
|
||||
"instance": response.headers.get("X-Instance-Id"),
|
||||
"duration_ms": round((time.monotonic() - started) * 1000)}), flush=True)
|
||||
except OSError:
|
||||
print('{"status":"no_response"}', flush=True)
|
||||
time.sleep(min(1, max(0, until - time.monotonic())))
|
||||
finally:
|
||||
print("Восстанавливаем остановленный контейнер…", flush=True)
|
||||
docker("start", target)
|
||||
wait_api(args.base_url, len(containers))
|
||||
print("Готово. Оба API доступны. Новый ID восстановленного процесса: " + alias(target), flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
def interrupted(*_):
|
||||
raise KeyboardInterrupt
|
||||
signal.signal(signal.SIGTERM, interrupted)
|
||||
main()
|
||||
@@ -0,0 +1,19 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
umask 077
|
||||
mkdir -p secrets
|
||||
|
||||
if [ -e secrets/postgres_password ] || [ -e secrets/database_url ]; then
|
||||
if [ ! -s secrets/postgres_password ] || [ ! -s secrets/database_url ]; then
|
||||
printf '%s\n' 'Incomplete secrets directory; repair it manually without replacing an existing database password.' >&2
|
||||
exit 1
|
||||
fi
|
||||
exit 0
|
||||
fi
|
||||
|
||||
password="$(openssl rand -hex 24)"
|
||||
printf '%s' "$password" > secrets/postgres_password
|
||||
printf 'Host=postgres;Port=5432;Database=messenger;Username=messenger;Password=%s' "$password" > secrets/database_url
|
||||
printf '%s\n' 'Created local database secrets in ignored secrets/ directory.'
|
||||
@@ -0,0 +1,16 @@
|
||||
#!/usr/bin/env python3
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(root / "student-tests"))
|
||||
from scaling_research import summarize, make_chart, write_report
|
||||
|
||||
path = root / "evidence/scaling.json"
|
||||
evidence = json.loads(path.read_text())
|
||||
summarize(evidence)
|
||||
path.write_text(json.dumps(evidence, ensure_ascii=False, indent=2) + "\n")
|
||||
make_chart(evidence)
|
||||
write_report(evidence)
|
||||
print("Updated evidence/scaling.png, evidence/scaling.svg and docs/SCALING.md")
|
||||
@@ -0,0 +1,7 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
./scripts/compose.sh restart postgres redis
|
||||
./scripts/compose.sh up -d --wait --wait-timeout 60 postgres redis
|
||||
./scripts/compose.sh restart api lb
|
||||
./scripts/compose.sh up -d --wait --wait-timeout 60 api lb
|
||||
@@ -0,0 +1,13 @@
|
||||
#!/usr/bin/env python3
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "student-tests"))
|
||||
from cluster import rolling_replace
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--base-url", default="http://127.0.0.1:18080")
|
||||
args = parser.parse_args()
|
||||
print(json.dumps(rolling_replace(args.base_url), indent=2))
|
||||
@@ -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,19 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
mkdir -p evidence
|
||||
exec 3>&1
|
||||
exec > evidence/checks.txt 2>&1
|
||||
date -u '+Verified: %Y-%m-%d %H:%M:%S UTC'
|
||||
for target in build check validate test student-test test-auth test-ui test-persistence restore-api test-failover restore-api test-idempotency-modes test-expiry test-grade4 research-grade5 test student-test test-ui; do
|
||||
printf '\n$ make %s\n' "$target"
|
||||
printf 'Running: %s\n' "$target" >&3
|
||||
./scripts/compose.sh ps --all
|
||||
if ! make "$target" BASE_URL="${BASE_URL:-http://127.0.0.1:18080}"; then
|
||||
tail -n 35 evidence/checks.txt >&3
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
git diff --exit-code -- contracts tests README.md COURSE.md
|
||||
printf '\nPASS: Lab3 checks completed\n'
|
||||
printf 'PASS: evidence/checks.txt\n' >&3
|
||||
@@ -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);
|
||||
@@ -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 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)));
|
||||
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,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
|
||||
FROM page p
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT id, sender_id, text, created_at
|
||||
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"));
|
||||
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)
|
||||
{
|
||||
public Contracts.MessageDto ToDto() => new(Id, ChatId, SenderId, Text, CreatedAt.ToString("O"));
|
||||
}
|
||||
@@ -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,78 @@
|
||||
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)
|
||||
{
|
||||
var hash = SHA256.HashData(Encoding.UTF8.GetBytes(text));
|
||||
await using var connection = await dataSource.OpenConnectionAsync();
|
||||
await using var transaction = await connection.BeginTransactionAsync();
|
||||
|
||||
// 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
|
||||
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)) : 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());
|
||||
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)
|
||||
VALUES (@id, @chat_id, @sender_id, @text, @created_at);
|
||||
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("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,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,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) =>
|
||||
!readiness.IsStopping && await database.IsReadyAsync()
|
||||
? Results.Ok(new { status = "ok" })
|
||||
: ApiSupport.ApiError(context, 503, "unavailable", "База данных недоступна"));
|
||||
return app;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
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 (string.IsNullOrWhiteSpace(request!.Text) || request.Text.EnumerateRunes().Count() > 4000)
|
||||
return ApiError(context, 400, "invalid_request", "Некорректный текст сообщения");
|
||||
if (request.AttachmentIds.ValueKind != JsonValueKind.Undefined &&
|
||||
(request.AttachmentIds.ValueKind != JsonValueKind.Array || request.AttachmentIds.GetArrayLength() != 0))
|
||||
return ApiError(context, 400, "invalid_request", "Вложения в этой версии не поддерживаются");
|
||||
|
||||
var message = await messages.CreateAsync(chatId, actor.Id, request.Text, key);
|
||||
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,19 @@
|
||||
<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="Isopoh.Cryptography.Argon2" Version="2.0.0" />
|
||||
<PackageReference Include="Npgsql" Version="9.0.5" />
|
||||
<PackageReference Include="StackExchange.Redis" Version="2.8.58" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,28 @@
|
||||
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 (Exception exception) when (exception is NpgsqlException or SocketException or TimeoutException)
|
||||
{
|
||||
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,90 @@
|
||||
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);
|
||||
|
||||
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>();
|
||||
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();
|
||||
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.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,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) =>
|
||||
(await database.CreateMessageOnceAsync(chatId, senderId, text, key))?.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,631 @@
|
||||
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 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 } = {}) {
|
||||
const started = performance.now();
|
||||
let httpStatus = null, requestId = null, instanceId = null, outcome = "network";
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), 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";
|
||||
}
|
||||
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;
|
||||
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;
|
||||
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, " ")
|
||||
: "Пока без сообщений · " + 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) || "";
|
||||
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);
|
||||
$("send-message").disabled = state.sending || !text.trim() || 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 previous = pendingMessages.get(chatId);
|
||||
const attempt = previous?.text === text ? previous : { text, key: crypto.randomUUID() };
|
||||
pendingMessages.set(chatId, attempt);
|
||||
state.sending = true; updateComposer();
|
||||
try {
|
||||
const message = await request(`/api/v1/chats/${chatId}/messages`, {
|
||||
method: "POST", body: { text }, headers: { "Idempotency-Key": attempt.key }
|
||||
});
|
||||
pendingMessages.delete(chatId);
|
||||
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(); }
|
||||
});
|
||||
|
||||
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;
|
||||
const user = await request("/api/v1/users/me");
|
||||
await enterSession({ ...session, user });
|
||||
} catch (error) {
|
||||
state.session = null;
|
||||
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);
|
||||
@@ -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,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,168 @@
|
||||
<!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="/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><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 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,93 @@
|
||||
// Each message keeps its own DOM element, identified by the message ID.
|
||||
import { ReactionControls } from '/reactions.js';
|
||||
export class MessageView {
|
||||
constructor(list) {
|
||||
this.list = list;
|
||||
this.messages = new Map();
|
||||
this.days = new Map();
|
||||
}
|
||||
|
||||
clear() {
|
||||
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, 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.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; } }
|
||||
@@ -0,0 +1,87 @@
|
||||
"""Replica failures and sequential replacement under a continuous mixed workload."""
|
||||
import argparse
|
||||
import json
|
||||
import time
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
from cluster import alias, api_ids, docker, inspect, rolling_replace, wait_api
|
||||
from compose_helpers import ROOT, compose, sql
|
||||
from client import Client, check, run
|
||||
from traffic import traffic, public_report
|
||||
|
||||
|
||||
def verify_messages(chat, confirmations):
|
||||
rows = json.loads(sql("SELECT coalesce(json_agg(json_build_object('id', id, 'text', text)), '[]') FROM messages WHERE chat_id = '" + chat["id"] + "';"))
|
||||
saved = {row["id"]: row["text"] for row in rows}
|
||||
check(all(saved.get(identifier) == text for identifier, text in confirmations), "confirmed message lost or changed")
|
||||
check(len({row["text"] for row in rows}) == len(rows), "uncertain retry created duplicate text")
|
||||
return {"confirmed_writes": len(confirmations), "stored_messages": len(rows), "no_duplicate_text": True}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--base-url", default="http://127.0.0.1:18080")
|
||||
args = parser.parse_args()
|
||||
wait_api(args.base_url, 2)
|
||||
c = Client(args.base_url)
|
||||
report = {"verified_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "failures": []}
|
||||
try:
|
||||
for position, mode in enumerate(("graceful", "immediate")):
|
||||
targets = api_ids()
|
||||
target = targets[position]
|
||||
target_alias = alias(target)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
|
||||
def stop():
|
||||
docker("stop", "--time", "8" if mode == "graceful" else "0", target)
|
||||
return {"container": target, "instance": target_alias, "running_after_action": inspect(target)["State"]["Running"]}
|
||||
|
||||
print("Testing " + mode + " stop of " + target[:12], flush=True)
|
||||
measured = traffic(args.base_url, alice, chat, duration=16, concurrency=8,
|
||||
action=stop, retry_uncertain=True)
|
||||
action = measured["actions"][0]
|
||||
check(not action["result"]["running_after_action"], "selected process was not stopped")
|
||||
after = [row for row in measured["_samples"] if row[0] >= action["finished_after_seconds"] and row[1] == "write" and row[2] == 201]
|
||||
check(after, "no confirmed writes after replica stopped")
|
||||
recovery = after[0][0] - action["started_after_seconds"]
|
||||
check(recovery <= 10, "writes did not recover in 10 seconds")
|
||||
check(all(row[4] != target_alias for row in after[-5:]), "stopped replica still observed")
|
||||
integrity = verify_messages(chat, measured["_confirmed"])
|
||||
report["failures"].append({**public_report(measured), "mode": mode,
|
||||
"recovery_seconds": round(recovery, 3), "integrity": integrity})
|
||||
compose("start", "api")
|
||||
wait_api(args.base_url, 2)
|
||||
|
||||
print("Building replacement image", flush=True)
|
||||
compose("build", "--build-arg", "BUILD_REVISION=rolling-" + str(time.time_ns()), "api", timeout=180)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
print("Testing sequential replacement under mixed traffic", flush=True)
|
||||
measured = traffic(args.base_url, alice, chat, duration=45, concurrency=8,
|
||||
action=lambda: rolling_replace(args.base_url, build=False), retry_uncertain=True)
|
||||
replacements = measured["actions"][0]["result"]
|
||||
check(len(replacements) == 2, "not every replica was replaced")
|
||||
check(all(row["old_container"] != row["new_container"] and row["old_image"] != row["new_image"]
|
||||
for row in replacements), "replacement did not deploy a new image")
|
||||
check(measured["actions"][0]["finished_after_seconds"] < 43, "replacement outlasted load window")
|
||||
report["rolling_update"] = {**public_report(measured), "integrity": verify_messages(chat, measured["_confirmed"])}
|
||||
c.call("GET", "/api/v1/users/me", actor=alice, schema="User")
|
||||
|
||||
containers = [inspect(container) for container in api_ids()]
|
||||
check(all(not info["HostConfig"]["PortBindings"] for info in containers), "API ports published outside LB")
|
||||
check(all(info["HostConfig"]["NanoCpus"] > 0 and info["HostConfig"]["Memory"] > 0 for info in containers), "missing API resource limit")
|
||||
report["infrastructure"] = {
|
||||
"api_ports_published": False,
|
||||
"api_containers": [{"id": info["Id"], "image": info["Image"],
|
||||
"cpu_limit": info["HostConfig"]["NanoCpus"] / 1e9,
|
||||
"memory_limit": info["HostConfig"]["Memory"]} for info in containers],
|
||||
"migrations": sql("SELECT string_agg(version::text, ',' ORDER BY version) FROM schema_migrations;")
|
||||
}
|
||||
(ROOT / "evidence" / "availability.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
|
||||
print(json.dumps(report, ensure_ascii=False, indent=2))
|
||||
finally:
|
||||
compose("start", "api")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,135 @@
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
import subprocess
|
||||
import time
|
||||
from urllib.request import urlopen
|
||||
|
||||
from compose_helpers import ROOT, compose
|
||||
|
||||
|
||||
def docker(*args, input=None, timeout=90):
|
||||
return subprocess.run(["docker", *args], input=input, text=True, capture_output=True,
|
||||
check=True, timeout=timeout).stdout.strip()
|
||||
|
||||
|
||||
def api_ids():
|
||||
return compose("ps", "-q", "api").splitlines()
|
||||
|
||||
|
||||
def inspect(container):
|
||||
return json.loads(docker("inspect", container))[0]
|
||||
|
||||
|
||||
def alias(container):
|
||||
headers = docker("exec", container, "curl", "-fsS", "-D", "-", "-o", "/dev/null",
|
||||
"http://127.0.0.1:8080/health/live")
|
||||
return next(line.split(":", 1)[1].strip() for line in headers.splitlines()
|
||||
if line.lower().startswith("x-instance-id:"))
|
||||
|
||||
|
||||
def runtime(command):
|
||||
lb = compose("ps", "-q", "lb")
|
||||
return docker("exec", "-i", lb, "nc", "-w", "2", "127.0.0.1", "9999",
|
||||
input=command + "\n", timeout=5)
|
||||
|
||||
|
||||
def stats():
|
||||
return list(csv.DictReader(io.StringIO(runtime("show stat").lstrip("# "))))
|
||||
|
||||
|
||||
def servers():
|
||||
return [row for row in stats() if row["pxname"] == "messenger" and row["svname"].startswith("api")]
|
||||
|
||||
|
||||
def wait_api(base_url, expected, timeout=45):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
rows = servers()
|
||||
up = [row for row in rows if row["status"] == "UP"]
|
||||
if len(up) == expected:
|
||||
with urlopen(base_url + "/health/ready", timeout=2) as response:
|
||||
if response.status == 200:
|
||||
return
|
||||
except (OSError, subprocess.SubprocessError, StopIteration):
|
||||
pass
|
||||
time.sleep(.25)
|
||||
raise RuntimeError("API replicas did not become ready")
|
||||
|
||||
|
||||
def recreate(replicas=2, cpus=1, memory="384m", pool=20, batching=True, database_cpus=.5):
|
||||
import os
|
||||
environment = dict(os.environ, API_REPLICAS=str(replicas), API_CPUS=str(cpus),
|
||||
API_MEMORY=memory, DB_POOL_SIZE=str(pool), MESSAGE_BATCHING=str(batching).lower(),
|
||||
POSTGRES_CPUS=str(database_cpus))
|
||||
subprocess.run([str(ROOT / "scripts/compose.sh"), "up", "-d", "--no-deps",
|
||||
"--scale", "api=" + str(replicas), "--force-recreate", "api"],
|
||||
cwd=ROOT, env=environment, capture_output=True, text=True, check=True, timeout=90)
|
||||
|
||||
|
||||
def counters():
|
||||
result = {}
|
||||
for service in ("api", "postgres", "lb", "redis"):
|
||||
for container in compose("ps", "-q", service).splitlines():
|
||||
info = inspect(container)
|
||||
data = docker("exec", container, "cat", "/sys/fs/cgroup/cpu.stat",
|
||||
"/sys/fs/cgroup/memory.current").splitlines()
|
||||
values = dict(line.split() for line in data[:-1])
|
||||
result[container] = {
|
||||
"service": service, "name": info["Name"].lstrip("/"),
|
||||
"cpu_seconds": int(values["usage_usec"]) / 1e6,
|
||||
"throttled_seconds": int(values["throttled_usec"]) / 1e6,
|
||||
"throttled_periods": int(values["nr_throttled"]),
|
||||
"memory_bytes": int(data[-1]),
|
||||
"cpu_limit": info["HostConfig"]["NanoCpus"] / 1e9,
|
||||
"memory_limit": info["HostConfig"]["Memory"],
|
||||
}
|
||||
return result
|
||||
|
||||
|
||||
def counter_delta(before, after, seconds):
|
||||
result = []
|
||||
for container, current in after.items():
|
||||
old = before.get(container, current)
|
||||
row = {key: current[key] for key in ("service", "name", "cpu_limit", "memory_limit", "memory_bytes")}
|
||||
row["used_cpu_cores"] = round((current["cpu_seconds"] - old["cpu_seconds"]) / seconds, 3)
|
||||
row["throttled_seconds"] = round(current["throttled_seconds"] - old["throttled_seconds"], 3)
|
||||
row["throttled_periods"] = current["throttled_periods"] - old["throttled_periods"]
|
||||
result.append(row)
|
||||
return result
|
||||
|
||||
|
||||
def rolling_replace(base_url="http://127.0.0.1:18080", build=True):
|
||||
originals = api_ids()
|
||||
if len(originals) < 2:
|
||||
raise RuntimeError("Rolling replacement requires at least two API replicas")
|
||||
if build:
|
||||
compose("build", "--build-arg", "BUILD_REVISION=rolling-" + str(time.time_ns()), "api", timeout=180)
|
||||
records = []
|
||||
for old in originals:
|
||||
before = set(api_ids())
|
||||
old_info = inspect(old)
|
||||
old_alias = alias(old)
|
||||
old_ip = next(iter(old_info["NetworkSettings"]["Networks"].values()))["IPAddress"]
|
||||
compose("up", "-d", "--no-deps", "--no-recreate", "--scale", "api=" + str(len(originals) + 1), "api")
|
||||
wait_api(base_url, len(originals) + 1)
|
||||
added = (set(api_ids()) - before).pop()
|
||||
slot = next(row["svname"] for row in servers() if row.get("addr", "").split(":")[0] == old_ip)
|
||||
runtime("set server messenger/" + slot + " state drain")
|
||||
deadline = time.monotonic() + 8
|
||||
while time.monotonic() < deadline:
|
||||
active = next(row for row in servers() if row["svname"] == slot)
|
||||
if int(active["scur"]) == 0:
|
||||
break
|
||||
time.sleep(.1)
|
||||
else:
|
||||
raise RuntimeError("Backend did not drain")
|
||||
docker("stop", "--time", "8", old)
|
||||
docker("rm", old)
|
||||
runtime("set server messenger/" + slot + " state ready")
|
||||
wait_api(base_url, len(originals))
|
||||
records.append({"old_container": old, "old_instance": old_alias,
|
||||
"old_image": old_info["Image"], "new_container": added,
|
||||
"new_instance": alias(added), "new_image": inspect(added)["Image"]})
|
||||
return records
|
||||
@@ -0,0 +1,20 @@
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
|
||||
|
||||
def compose(*args, timeout=90):
|
||||
result = subprocess.run([str(ROOT / "scripts/compose.sh"), *args], cwd=ROOT,
|
||||
text=True, capture_output=True, check=True, timeout=timeout)
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def sql(query):
|
||||
return compose("exec", "-T", "postgres", "psql", "-X", "-U", "messenger", "-d", "messenger", "-Atc", query)
|
||||
|
||||
|
||||
def redis(*args):
|
||||
return compose("exec", "-T", "redis", "redis-cli", "--raw", *args)
|
||||
@@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Additional black-box checks for the Lab2 authentication boundary."""
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client, check, run # noqa: E402
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
parser.add_argument("--check-expiry", action="store_true")
|
||||
args = parser.parse_args()
|
||||
client = Client(args.base_url)
|
||||
|
||||
username = "student_" + uuid.uuid4().hex[:12]
|
||||
password = "Длинный пароль с двоеточием: " + uuid.uuid4().hex
|
||||
registration = {"username": username, "display_name": "Проверка Lab2", "password": password}
|
||||
user = client.call("POST", "/api/v1/users", 201, body=registration, schema="User")["json"]
|
||||
check("password" not in user and "password_hash" not in user, "password leaked in User")
|
||||
client.call("POST", "/api/v1/users", 409, body=registration)
|
||||
client.call("POST", "/api/v1/users", 400, body={**registration, "unexpected": True})
|
||||
client.call("POST", "/api/v1/users", 400, body={**registration, "username": username + "\n"})
|
||||
client.call("POST", "/api/v1/users", 400, body={**registration, "password": "short"})
|
||||
client.call("POST", "/api/v1/users", 400, raw=b'{"username":',
|
||||
headers={"Content-Type": "application/json"})
|
||||
client.call("POST", "/api/v1/users", 400, raw=b'{}',
|
||||
headers={"Content-Type": "text/plain"})
|
||||
|
||||
def basic(secret):
|
||||
encoded = base64.b64encode((username + ":" + secret).encode("utf-8")).decode("ascii")
|
||||
return {"Authorization": "Basic " + encoded}
|
||||
|
||||
client.call("POST", "/api/v1/auth/sessions", 401, headers=basic("wrong password"))
|
||||
client.call("POST", "/api/v1/auth/sessions", 400, headers=basic(password), body={})
|
||||
session = client.call("POST", "/api/v1/auth/sessions", 201,
|
||||
headers=basic(password), schema="Session")["json"]
|
||||
token = session["token"]
|
||||
check(token != password and username not in token, "token contains credentials")
|
||||
client.call("GET", "/api/v1/users/me", 401, headers={"X-User-Id": user["id"]})
|
||||
client.call("GET", "/api/v1/users/me", 401, headers=basic(password))
|
||||
|
||||
actor = {"id": user["id"], "token": token}
|
||||
me = client.call("GET", "/api/v1/users/me", actor=actor, schema="User")["json"]
|
||||
check(me == user, "Bearer session resolved to a different user")
|
||||
client.call("POST", "/api/v1/chats", 400, actor=actor,
|
||||
body={"title": "Bad members", "member_ids": [user["id"], str(uuid.uuid4())]})
|
||||
|
||||
if args.check_expiry:
|
||||
from compose_helpers import redis
|
||||
key = "messenger:session:" + hashlib.sha256(token.encode("ascii")).hexdigest()
|
||||
check(0 < int(redis("PTTL", key)) <= 2000, "short-TTL session missing cache expiry")
|
||||
time.sleep(3)
|
||||
client.call("GET", "/api/v1/users/me", 401, actor=actor)
|
||||
check(redis("EXISTS", key) == "0", "expired session remained in Redis")
|
||||
print("PASS: TTL=2 expires in PostgreSQL authentication and Redis cache")
|
||||
else:
|
||||
client.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=actor)
|
||||
client.call("GET", "/api/v1/users/me", 401, actor=actor)
|
||||
|
||||
print("PASS: Lab2 password, Basic, Bearer, input validation and session lifecycle")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||