diff --git a/.dockerignore b/.dockerignore index bc16e556..781f0450 100644 --- a/.dockerignore +++ b/.dockerignore @@ -16,5 +16,7 @@ backups .venv __pycache__ node_modules +**/bin +**/obj evidence .DS_Store diff --git a/.gitignore b/.gitignore index b5a71896..b1c323ef 100644 --- a/.gitignore +++ b/.gitignore @@ -11,7 +11,7 @@ certs/private/ *.pem *.tfstate* volumes/ -data/ +/data/ backups/ # Runtime/build artifacts .venv/ diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..162159c5 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,39 @@ +FROM mcr.microsoft.com/dotnet/sdk:9.0.306 AS build + +WORKDIR /src + +COPY src/Messenger.Api/Messenger.Api.csproj src/Messenger.Api/ +RUN dotnet restore src/Messenger.Api/Messenger.Api.csproj + +COPY src/Messenger.Api/ src/Messenger.Api/ + +RUN dotnet publish src/Messenger.Api/Messenger.Api.csproj \ + -c Release \ + --no-restore \ + -o /app/publish + + +FROM mcr.microsoft.com/dotnet/aspnet:9.0.10 AS runtime + +RUN apt-get update \ + && apt-get install -y --no-install-recommends curl \ + && rm -rf /var/lib/apt/lists/* + +WORKDIR /app +ARG BUILD_REVISION=local +LABEL org.opencontainers.image.revision=$BUILD_REVISION + +COPY --from=build /app/publish . + +ENV APP_HOST=0.0.0.0 +ENV APP_PORT=8080 +ENV APP_ENV=lab + +EXPOSE 8080 + +USER app + +HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \ + CMD curl --fail --silent http://127.0.0.1:8080/health/ready > /dev/null || exit 1 + +ENTRYPOINT ["dotnet", "Messenger.Api.dll"] diff --git a/Makefile b/Makefile index 5d86d171..4fc4bc31 100644 --- a/Makefile +++ b/Makefile @@ -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 diff --git a/REPORT.md b/REPORT.md index c2679005..01c818f5 100644 --- a/REPORT.md +++ b/REPORT.md @@ -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 использован при реализации и проверках. +Конкретные измерения получены выполнением команд из этого репозитория. diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 00000000..73e6383d --- /dev/null +++ b/compose.yaml @@ -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: diff --git a/docs/PR.md b/docs/PR.md new file mode 100644 index 00000000..706021ab --- /dev/null +++ b/docs/PR.md @@ -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 использован +при реализации и проверках. diff --git a/docs/SCALING.md b/docs/SCALING.md new file mode 100644 index 00000000..2924861c --- /dev/null +++ b/docs/SCALING.md @@ -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 | + +![Масштабирование](../evidence/scaling.png) + +## Проверенные изменения + +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 diff --git a/evidence/availability-checks.txt b/evidence/availability-checks.txt new file mode 100644 index 00000000..15ec37c3 --- /dev/null +++ b/evidence/availability-checks.txt @@ -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" + } +} diff --git a/evidence/availability.json b/evidence/availability.json new file mode 100644 index 00000000..444d78a1 --- /dev/null +++ b/evidence/availability.json @@ -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" + } +} diff --git a/evidence/checks.txt b/evidence/checks.txt new file mode 100644 index 00000000..1628b648 --- /dev/null +++ b/evidence/checks.txt @@ -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 diff --git a/evidence/idempotency-batched.json b/evidence/idempotency-batched.json new file mode 100644 index 00000000..b1362792 --- /dev/null +++ b/evidence/idempotency-batched.json @@ -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" + ] +} diff --git a/evidence/idempotency-separate.json b/evidence/idempotency-separate.json new file mode 100644 index 00000000..74a5e6a3 --- /dev/null +++ b/evidence/idempotency-separate.json @@ -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" + ] +} diff --git a/evidence/idempotency.json b/evidence/idempotency.json new file mode 100644 index 00000000..ff41c550 --- /dev/null +++ b/evidence/idempotency.json @@ -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" + ] +} diff --git a/evidence/persistence-checks.txt b/evidence/persistence-checks.txt new file mode 100644 index 00000000..aa7d5dfc --- /dev/null +++ b/evidence/persistence-checks.txt @@ -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 diff --git a/evidence/persistence.json b/evidence/persistence.json new file mode 100644 index 00000000..e0c2de12 --- /dev/null +++ b/evidence/persistence.json @@ -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 +} diff --git a/evidence/scaling-requests.csv.gz b/evidence/scaling-requests.csv.gz new file mode 100644 index 00000000..2bd6429c Binary files /dev/null and b/evidence/scaling-requests.csv.gz differ diff --git a/evidence/scaling.json b/evidence/scaling.json new file mode 100644 index 00000000..cfff108b --- /dev/null +++ b/evidence/scaling.json @@ -0,0 +1,15787 @@ +{ + "verified_at": "2026-11-01T23:43:46Z", + "track": 1, + "seconds_per_run": 8, + "repeats": 3, + "host": { + "cpus": 8, + "memory_bytes": 4106604544, + "docker_version": "29.8.2", + "os": "Docker Desktop" + }, + "configurations": [ + { + "series": "fixed", + "replicas": 1, + "per_api_cpus": 1.0, + "per_api_memory_mib": 768, + "total_api_cpus": 1.0, + "total_api_memory_mib": 768, + "curves": { + "4": { + "rps": 227.971, + "p95_ms": 69.017, + "error_ratio": 0.0, + "failed_requests_total": 0, + "error_ratio_max": 0.0, + "rps_min": 218.93, + "rps_max": 244.862 + }, + "16": { + "rps": 275.06, + "p95_ms": 103.552, + "error_ratio": 0.0, + "failed_requests_total": 0, + "error_ratio_max": 0.0, + "rps_min": 274.184, + "rps_max": 282.779 + }, + "64": { + "rps": 302.941, + "p95_ms": 307.507, + "error_ratio": 0.0, + "failed_requests_total": 0, + "error_ratio_max": 0.0, + "rps_min": 287.415, + "rps_max": 308.337 + } + } + }, + { + "series": "fixed", + "replicas": 2, + "per_api_cpus": 0.5, + "per_api_memory_mib": 384, + "total_api_cpus": 1.0, + "total_api_memory_mib": 768, + "curves": { + "4": { + "rps": 232.474, + "p95_ms": 68.443, + "error_ratio": 0.0, + "failed_requests_total": 0, + "error_ratio_max": 0.0, + "rps_min": 220.536, + "rps_max": 259.315 + }, + "16": { + "rps": 267.997, + "p95_ms": 106.101, + "error_ratio": 0.0, + "failed_requests_total": 0, + "error_ratio_max": 0.0, + "rps_min": 251.76, + "rps_max": 284.831 + }, + "64": { + "rps": 275.592, + "p95_ms": 456.591, + "error_ratio": 0.0, + "failed_requests_total": 0, + "error_ratio_max": 0.0, + "rps_min": 270.695, + "rps_max": 296.067 + } + } + }, + { + "series": "fixed", + "replicas": 4, + "per_api_cpus": 0.25, + "per_api_memory_mib": 192, + "total_api_cpus": 1.0, + "total_api_memory_mib": 768, + "curves": { + "4": { + "rps": 124.453, + "p95_ms": 102.574, + "error_ratio": 0.0, + "failed_requests_total": 0, + "error_ratio_max": 0.0, + "rps_min": 116.282, + "rps_max": 146.161 + }, + "16": { + "rps": 227.163, + "p95_ms": 221.725, + "error_ratio": 0.0, + "failed_requests_total": 0, + "error_ratio_max": 0.0, + "rps_min": 197.706, + "rps_max": 231.947 + }, + "64": { + "rps": 234.342, + "p95_ms": 577.561, + "error_ratio": 0.0, + "failed_requests_total": 0, + "error_ratio_max": 0.0, + "rps_min": 232.131, + "rps_max": 247.101 + } + } + }, + { + "series": "growing", + "replicas": 1, + "per_api_cpus": 1, + "per_api_memory_mib": 384, + "total_api_cpus": 1, + "total_api_memory_mib": 384, + "curves": { + "4": { + "rps": 250.297, + "p95_ms": 63.995, + "error_ratio": 0.0, + "failed_requests_total": 0, + "error_ratio_max": 0.0, + "rps_min": 239.539, + "rps_max": 258.723 + }, + "16": { + "rps": 292.921, + "p95_ms": 102.186, + "error_ratio": 0.0, + "failed_requests_total": 0, + "error_ratio_max": 0.0, + "rps_min": 282.668, + "rps_max": 299.464 + }, + "64": { + "rps": 296.505, + "p95_ms": 386.697, + "error_ratio": 0.0, + "failed_requests_total": 0, + "error_ratio_max": 0.0, + "rps_min": 285.691, + "rps_max": 303.063 + } + } + }, + { + "series": "growing", + "replicas": 2, + "per_api_cpus": 1, + "per_api_memory_mib": 384, + "total_api_cpus": 2, + "total_api_memory_mib": 768, + "curves": { + "4": { + "rps": 260.993, + "p95_ms": 65.864, + "error_ratio": 0.0, + "failed_requests_total": 0, + "error_ratio_max": 0.0, + "rps_min": 250.42, + "rps_max": 269.121 + }, + "16": { + "rps": 261.656, + "p95_ms": 107.965, + "error_ratio": 0.0, + "failed_requests_total": 0, + "error_ratio_max": 0.0, + "rps_min": 258.069, + "rps_max": 273.803 + }, + "64": { + "rps": 269.672, + "p95_ms": 410.645, + "error_ratio": 0.0, + "failed_requests_total": 0, + "error_ratio_max": 0.0, + "rps_min": 268.931, + "rps_max": 282.83 + } + } + }, + { + "series": "growing", + "replicas": 4, + "per_api_cpus": 1, + "per_api_memory_mib": 384, + "total_api_cpus": 4, + "total_api_memory_mib": 1536, + "curves": { + "4": { + "rps": 245.033, + "p95_ms": 51.051, + "error_ratio": 0.0, + "failed_requests_total": 0, + "error_ratio_max": 0.0, + "rps_min": 185.652, + "rps_max": 250.31 + }, + "16": { + "rps": 236.934, + "p95_ms": 111.575, + "error_ratio": 0.0, + "failed_requests_total": 0, + "error_ratio_max": 0.0, + "rps_min": 223.252, + "rps_max": 249.622 + }, + "64": { + "rps": 182.5, + "p95_ms": 894.66, + "error_ratio": 0.0, + "failed_requests_total": 21, + "error_ratio_max": 0.025332, + "rps_min": 91.187, + "rps_max": 229.551 + } + } + } + ], + "runs": [ + { + "duration_seconds": 8.1167, + "requested_seconds": 8, + "concurrency": 4, + "successful_requests": 1777, + "failed_requests": 0, + "successful_rps": 218.93, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 7.632, + "p95": 71.57, + "p99": 91.864 + }, + "all_attempt_latency_ms": { + "p50": 7.632, + "p95": 71.57, + "p99": 91.864 + }, + "status_counts": { + "200": 888, + "201": 889 + }, + "instance_counts": { + "b0da54fcd44244f49b44f7078827ba92": 1777 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.001, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 3 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "4", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.519, + "data": { + "postgres_activity": [ + { + "state": "idle in transaction", + "wait_event_type": null, + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 3 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "4", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 7.563, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 3 + }, + { + "state": "active", + "wait_event_type": null, + "count": 2 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 805306368, + "memory_bytes": 55844864, + "used_cpu_cores": 0.801, + "throttled_seconds": 5.272, + "throttled_periods": 61 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 71827456, + "used_cpu_cores": 0.384, + "throttled_seconds": 6.195, + "throttled_periods": 29 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 25595904, + "used_cpu_cores": 0.058, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 18112512, + "used_cpu_cores": 0.028, + "throttled_seconds": 0.0, + "throttled_periods": 0 + } + ], + "run": 1, + "label": "fixed-1", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 5 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.0844, + "requested_seconds": 8, + "concurrency": 4, + "successful_requests": 1843, + "failed_requests": 0, + "successful_rps": 227.971, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 7.841, + "p95": 64.744, + "p99": 84.107 + }, + "all_attempt_latency_ms": { + "p50": 7.841, + "p95": 64.744, + "p99": 84.107 + }, + "status_counts": { + "200": 921, + "201": 922 + }, + "instance_counts": { + "b0da54fcd44244f49b44f7078827ba92": 1843 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.001, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 4 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "3", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.774, + "data": { + "postgres_activity": [ + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 4 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 7.453, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 4 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 805306368, + "memory_bytes": 51310592, + "used_cpu_cores": 0.809, + "throttled_seconds": 5.571, + "throttled_periods": 58 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 70160384, + "used_cpu_cores": 0.404, + "throttled_seconds": 4.464, + "throttled_periods": 31 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 27197440, + "used_cpu_cores": 0.07, + "throttled_seconds": 0.045, + "throttled_periods": 1 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 17797120, + "used_cpu_cores": 0.035, + "throttled_seconds": 0.072, + "throttled_periods": 1 + } + ], + "run": 2, + "label": "fixed-1", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 5 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.1025, + "requested_seconds": 8, + "concurrency": 4, + "successful_requests": 1984, + "failed_requests": 0, + "successful_rps": 244.862, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 6.979, + "p95": 69.017, + "p99": 83.795 + }, + "all_attempt_latency_ms": { + "p50": 6.979, + "p95": 69.017, + "p99": 83.795 + }, + "status_counts": { + "201": 992, + "200": 992 + }, + "instance_counts": { + "b0da54fcd44244f49b44f7078827ba92": 1984 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.004, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 3 + }, + { + "state": "active", + "wait_event_type": null, + "count": 2 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "3", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.681, + "data": { + "postgres_activity": [ + { + "state": "idle in transaction", + "wait_event_type": null, + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 3 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "2", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 7.325, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 3 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 805306368, + "memory_bytes": 64634880, + "used_cpu_cores": 0.8, + "throttled_seconds": 6.033, + "throttled_periods": 62 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 67080192, + "used_cpu_cores": 0.408, + "throttled_seconds": 4.644, + "throttled_periods": 43 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 27832320, + "used_cpu_cores": 0.067, + "throttled_seconds": 0.025, + "throttled_periods": 1 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 17756160, + "used_cpu_cores": 0.034, + "throttled_seconds": 0.115, + "throttled_periods": 2 + } + ], + "run": 3, + "label": "fixed-1", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 5 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.4651, + "requested_seconds": 8, + "concurrency": 16, + "successful_requests": 2321, + "failed_requests": 0, + "successful_rps": 274.184, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 81.53, + "p95": 103.592, + "p99": 185.974 + }, + "all_attempt_latency_ms": { + "p50": 81.53, + "p95": 103.592, + "p99": 185.974 + }, + "status_counts": { + "201": 1162, + "200": 1159 + }, + "instance_counts": { + "b0da54fcd44244f49b44f7078827ba92": 2321 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.005, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": null, + "count": 1 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 9 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 5 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "16", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.808, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 4 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 1 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 2 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 7 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 2 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "16", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 7.801, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 17 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 805306368, + "memory_bytes": 65155072, + "used_cpu_cores": 0.468, + "throttled_seconds": 0.423, + "throttled_periods": 14 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 101961728, + "used_cpu_cores": 0.446, + "throttled_seconds": 35.263, + "throttled_periods": 83 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 27455488, + "used_cpu_cores": 0.066, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 19861504, + "used_cpu_cores": 0.029, + "throttled_seconds": 0.0, + "throttled_periods": 1 + } + ], + "run": 4, + "label": "fixed-1", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 17 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.3139, + "requested_seconds": 8, + "concurrency": 16, + "successful_requests": 2351, + "failed_requests": 0, + "successful_rps": 282.779, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 78.461, + "p95": 100.604, + "p99": 189.112 + }, + "all_attempt_latency_ms": { + "p50": 78.461, + "p95": 100.604, + "p99": 189.112 + }, + "status_counts": { + "200": 1176, + "201": 1175 + }, + "instance_counts": { + "b0da54fcd44244f49b44f7078827ba92": 2351 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.001, + "data": { + "postgres_activity": [ + { + "state": "idle in transaction", + "wait_event_type": null, + "count": 1 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 2 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 2 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 11 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "16", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.84, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 6 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 9 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "16", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 7.742, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 17 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 805306368, + "memory_bytes": 67809280, + "used_cpu_cores": 0.371, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 103743488, + "used_cpu_cores": 0.444, + "throttled_seconds": 35.006, + "throttled_periods": 81 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 26079232, + "used_cpu_cores": 0.07, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 17551360, + "used_cpu_cores": 0.031, + "throttled_seconds": 0.069, + "throttled_periods": 1 + } + ], + "run": 5, + "label": "fixed-1", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 17 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.6272, + "requested_seconds": 8, + "concurrency": 16, + "successful_requests": 2373, + "failed_requests": 0, + "successful_rps": 275.06, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 79.416, + "p95": 103.552, + "p99": 193.552 + }, + "all_attempt_latency_ms": { + "p50": 79.416, + "p95": 103.552, + "p99": 193.552 + }, + "status_counts": { + "200": 1186, + "201": 1187 + }, + "instance_counts": { + "b0da54fcd44244f49b44f7078827ba92": 2373 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.006, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 2 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 1 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 11 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "16", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 5.001, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 1 + }, + { + "state": "active", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 13 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "14", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 7.952, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 18 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 805306368, + "memory_bytes": 67481600, + "used_cpu_cores": 0.343, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 108204032, + "used_cpu_cores": 0.465, + "throttled_seconds": 36.895, + "throttled_periods": 87 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 27238400, + "used_cpu_cores": 0.068, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 17453056, + "used_cpu_cores": 0.03, + "throttled_seconds": 0.07, + "throttled_periods": 1 + } + ], + "run": 6, + "label": "fixed-1", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 18 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.4323, + "requested_seconds": 8, + "concurrency": 64, + "successful_requests": 2600, + "failed_requests": 0, + "successful_rps": 308.337, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 198.047, + "p95": 303.245, + "p99": 395.637 + }, + "all_attempt_latency_ms": { + "p50": 198.047, + "p95": 303.245, + "p99": 395.637 + }, + "status_counts": { + "201": 1300, + "200": 1300 + }, + "instance_counts": { + "b0da54fcd44244f49b44f7078827ba92": 2600 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.005, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 8 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 2 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 8 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "64", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.936, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 5 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 2 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 5 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 7 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "64", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 7.876, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 20 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 805306368, + "memory_bytes": 73887744, + "used_cpu_cores": 0.333, + "throttled_seconds": 0.056, + "throttled_periods": 1 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 115404800, + "used_cpu_cores": 0.439, + "throttled_seconds": 39.011, + "throttled_periods": 82 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 22036480, + "used_cpu_cores": 0.067, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 16084992, + "used_cpu_cores": 0.03, + "throttled_seconds": 0.023, + "throttled_periods": 2 + } + ], + "run": 7, + "label": "fixed-1", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 20 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.2424, + "requested_seconds": 8, + "concurrency": 64, + "successful_requests": 2369, + "failed_requests": 0, + "successful_rps": 287.415, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 201.109, + "p95": 391.411, + "p99": 502.964 + }, + "all_attempt_latency_ms": { + "p50": 201.109, + "p95": 391.411, + "p99": 502.964 + }, + "status_counts": { + "200": 1181, + "201": 1188 + }, + "instance_counts": { + "b0da54fcd44244f49b44f7078827ba92": 2369 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.007, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "Client", + "count": 2 + }, + { + "state": "active", + "wait_event_type": "LWLock", + "count": 5 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 3 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 7 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "64", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 5.496, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 3 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 13 + }, + { + "state": "active", + "wait_event_type": null, + "count": 3 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "64", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 805306368, + "memory_bytes": 71860224, + "used_cpu_cores": 0.336, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 116785152, + "used_cpu_cores": 0.465, + "throttled_seconds": 42.171, + "throttled_periods": 85 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 28381184, + "used_cpu_cores": 0.066, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 18128896, + "used_cpu_cores": 0.03, + "throttled_seconds": 0.071, + "throttled_periods": 1 + } + ], + "run": 8, + "label": "fixed-1", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 20 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.4538, + "requested_seconds": 8, + "concurrency": 64, + "successful_requests": 2561, + "failed_requests": 0, + "successful_rps": 302.941, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 197.032, + "p95": 307.507, + "p99": 500.923 + }, + "all_attempt_latency_ms": { + "p50": 197.032, + "p95": 307.507, + "p99": 500.923 + }, + "status_counts": { + "200": 1281, + "201": 1280 + }, + "instance_counts": { + "b0da54fcd44244f49b44f7078827ba92": 2561 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.003, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 9 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 7 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 2 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "65", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 5.047, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "active", + "wait_event_type": "LWLock", + "count": 7 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 2 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 8 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "59", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 8.037, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 20 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 805306368, + "memory_bytes": 74457088, + "used_cpu_cores": 0.307, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 117055488, + "used_cpu_cores": 0.45, + "throttled_seconds": 40.11, + "throttled_periods": 83 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 28323840, + "used_cpu_cores": 0.068, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 11145216, + "used_cpu_cores": 0.029, + "throttled_seconds": 0.0, + "throttled_periods": 0 + } + ], + "run": 9, + "label": "fixed-1", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 20 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.1806, + "requested_seconds": 8, + "concurrency": 64, + "successful_requests": 2422, + "failed_requests": 0, + "successful_rps": 296.067, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 198.793, + "p95": 406.547, + "p99": 506.058 + }, + "all_attempt_latency_ms": { + "p50": 198.793, + "p95": 406.547, + "p99": 506.058 + }, + "status_counts": { + "200": 1210, + "201": 1212 + }, + "instance_counts": { + "a2529627732f4f9f90cf646991ab5670": 1211, + "16aafe01ce5e416f9c1bcdaa68f1079c": 1211 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.003, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 15 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 2 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 2 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 18 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 2 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "26", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "38", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 5.085, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "Client", + "count": 2 + }, + { + "state": "active", + "wait_event_type": "LWLock", + "count": 13 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 7 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 16 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "32", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "32", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 0.5, + "memory_limit": 402653184, + "memory_bytes": 56172544, + "used_cpu_cores": 0.382, + "throttled_seconds": 4.267, + "throttled_periods": 35 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 0.5, + "memory_limit": 402653184, + "memory_bytes": 61358080, + "used_cpu_cores": 0.369, + "throttled_seconds": 3.172, + "throttled_periods": 36 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 166567936, + "used_cpu_cores": 0.442, + "throttled_seconds": 40.985, + "throttled_periods": 82 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 28835840, + "used_cpu_cores": 0.07, + "throttled_seconds": 0.047, + "throttled_periods": 1 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 11358208, + "used_cpu_cores": 0.031, + "throttled_seconds": 0.091, + "throttled_periods": 3 + } + ], + "run": 10, + "label": "fixed-2", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 40 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.157, + "requested_seconds": 8, + "concurrency": 64, + "successful_requests": 2248, + "failed_requests": 0, + "successful_rps": 275.592, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 202.678, + "p95": 456.591, + "p99": 596.849 + }, + "all_attempt_latency_ms": { + "p50": 202.678, + "p95": 456.591, + "p99": 596.849 + }, + "status_counts": { + "200": 1119, + "201": 1129 + }, + "instance_counts": { + "16aafe01ce5e416f9c1bcdaa68f1079c": 1124, + "a2529627732f4f9f90cf646991ab5670": 1124 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.005, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 16 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 3 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 19 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "39", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "25", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 5.604, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 6 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 3 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 27 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 3 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "41", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "23", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 0.5, + "memory_limit": 402653184, + "memory_bytes": 66019328, + "used_cpu_cores": 0.358, + "throttled_seconds": 2.349, + "throttled_periods": 29 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 0.5, + "memory_limit": 402653184, + "memory_bytes": 66416640, + "used_cpu_cores": 0.354, + "throttled_seconds": 1.303, + "throttled_periods": 19 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 167759872, + "used_cpu_cores": 0.461, + "throttled_seconds": 44.976, + "throttled_periods": 84 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 26554368, + "used_cpu_cores": 0.067, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 18092032, + "used_cpu_cores": 0.03, + "throttled_seconds": 0.002, + "throttled_periods": 1 + } + ], + "run": 11, + "label": "fixed-2", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 40 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.1088, + "requested_seconds": 8, + "concurrency": 64, + "successful_requests": 2195, + "failed_requests": 0, + "successful_rps": 270.695, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 203.004, + "p95": 493.392, + "p99": 606.731 + }, + "all_attempt_latency_ms": { + "p50": 203.004, + "p95": 493.392, + "p99": 606.731 + }, + "status_counts": { + "200": 1089, + "201": 1106 + }, + "instance_counts": { + "16aafe01ce5e416f9c1bcdaa68f1079c": 1097, + "a2529627732f4f9f90cf646991ab5670": 1098 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.004, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "active", + "wait_event_type": "LWLock", + "count": 6 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 2 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 27 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 3 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "35", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "23", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 5.325, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 1 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 7 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 29 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "57", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "7", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 0.5, + "memory_limit": 402653184, + "memory_bytes": 65044480, + "used_cpu_cores": 0.358, + "throttled_seconds": 5.672, + "throttled_periods": 36 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 0.5, + "memory_limit": 402653184, + "memory_bytes": 65130496, + "used_cpu_cores": 0.366, + "throttled_seconds": 2.1, + "throttled_periods": 33 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 167723008, + "used_cpu_cores": 0.458, + "throttled_seconds": 39.742, + "throttled_periods": 83 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 26206208, + "used_cpu_cores": 0.069, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 17874944, + "used_cpu_cores": 0.035, + "throttled_seconds": 0.264, + "throttled_periods": 3 + } + ], + "run": 12, + "label": "fixed-2", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 40 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.1109, + "requested_seconds": 8, + "concurrency": 16, + "successful_requests": 2042, + "failed_requests": 0, + "successful_rps": 251.76, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 55.226, + "p95": 161.718, + "p99": 261.271 + }, + "all_attempt_latency_ms": { + "p50": 55.226, + "p95": 161.718, + "p99": 261.271 + }, + "status_counts": { + "201": 1023, + "200": 1019 + }, + "instance_counts": { + "a2529627732f4f9f90cf646991ab5670": 1021, + "16aafe01ce5e416f9c1bcdaa68f1079c": 1021 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.002, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 1 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 3 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 34 + }, + { + "state": "active", + "wait_event_type": null, + "count": 2 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "7", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "9", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.706, + "data": { + "postgres_activity": [ + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 5 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 35 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "15", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 7.327, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 2 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 2 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 32 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 2 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "7", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 0.5, + "memory_limit": 402653184, + "memory_bytes": 70402048, + "used_cpu_cores": 0.39, + "throttled_seconds": 5.469, + "throttled_periods": 46 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 0.5, + "memory_limit": 402653184, + "memory_bytes": 65527808, + "used_cpu_cores": 0.389, + "throttled_seconds": 2.328, + "throttled_periods": 39 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 178831360, + "used_cpu_cores": 0.45, + "throttled_seconds": 20.602, + "throttled_periods": 80 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 30068736, + "used_cpu_cores": 0.066, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 11280384, + "used_cpu_cores": 0.035, + "throttled_seconds": 0.116, + "throttled_periods": 4 + } + ], + "run": 13, + "label": "fixed-2", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 40 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.3471, + "requested_seconds": 8, + "concurrency": 16, + "successful_requests": 2237, + "failed_requests": 0, + "successful_rps": 267.997, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 55.175, + "p95": 106.101, + "p99": 193.546 + }, + "all_attempt_latency_ms": { + "p50": 55.175, + "p95": 106.101, + "p99": 193.546 + }, + "status_counts": { + "200": 1119, + "201": 1118 + }, + "instance_counts": { + "16aafe01ce5e416f9c1bcdaa68f1079c": 1121, + "a2529627732f4f9f90cf646991ab5670": 1116 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.007, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 1 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 35 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 2 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "7", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "9", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.891, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 3 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 2 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 2 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 31 + }, + { + "state": "active", + "wait_event_type": null, + "count": 2 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "8", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "8", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 7.711, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 40 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 0.5, + "memory_limit": 402653184, + "memory_bytes": 71966720, + "used_cpu_cores": 0.298, + "throttled_seconds": 0.647, + "throttled_periods": 10 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 0.5, + "memory_limit": 402653184, + "memory_bytes": 72990720, + "used_cpu_cores": 0.315, + "throttled_seconds": 2.245, + "throttled_periods": 27 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 172445696, + "used_cpu_cores": 0.456, + "throttled_seconds": 28.314, + "throttled_periods": 85 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 28237824, + "used_cpu_cores": 0.063, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 15876096, + "used_cpu_cores": 0.029, + "throttled_seconds": 0.0, + "throttled_periods": 0 + } + ], + "run": 14, + "label": "fixed-2", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 40 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.2786, + "requested_seconds": 8, + "concurrency": 16, + "successful_requests": 2358, + "failed_requests": 0, + "successful_rps": 284.831, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 80.357, + "p95": 101.227, + "p99": 107.895 + }, + "all_attempt_latency_ms": { + "p50": 80.357, + "p95": 101.227, + "p99": 107.895 + }, + "status_counts": { + "201": 1181, + "200": 1177 + }, + "instance_counts": { + "16aafe01ce5e416f9c1bcdaa68f1079c": 1180, + "a2529627732f4f9f90cf646991ab5670": 1178 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.001, + "data": { + "postgres_activity": [ + { + "state": "idle in transaction", + "wait_event_type": null, + "count": 1 + }, + { + "state": "active", + "wait_event_type": "LWLock", + "count": 4 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 32 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "7", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "9", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.807, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 33 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 5 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "4", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "4", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 7.502, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "active", + "wait_event_type": "LWLock", + "count": 2 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 2 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 31 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 3 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 0.5, + "memory_limit": 402653184, + "memory_bytes": 67211264, + "used_cpu_cores": 0.26, + "throttled_seconds": 0.061, + "throttled_periods": 3 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 0.5, + "memory_limit": 402653184, + "memory_bytes": 70938624, + "used_cpu_cores": 0.266, + "throttled_seconds": 0.085, + "throttled_periods": 3 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 174981120, + "used_cpu_cores": 0.444, + "throttled_seconds": 30.515, + "throttled_periods": 82 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 26329088, + "used_cpu_cores": 0.067, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 17338368, + "used_cpu_cores": 0.033, + "throttled_seconds": 0.256, + "throttled_periods": 2 + } + ], + "run": 15, + "label": "fixed-2", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 40 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.0288, + "requested_seconds": 8, + "concurrency": 4, + "successful_requests": 2082, + "failed_requests": 0, + "successful_rps": 259.315, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 6.774, + "p95": 65.439, + "p99": 85.531 + }, + "all_attempt_latency_ms": { + "p50": 6.774, + "p95": 65.439, + "p99": 85.531 + }, + "status_counts": { + "201": 1041, + "200": 1041 + }, + "instance_counts": { + "16aafe01ce5e416f9c1bcdaa68f1079c": 1041, + "a2529627732f4f9f90cf646991ab5670": 1041 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.01, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 38 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "2", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.625, + "data": { + "postgres_activity": [ + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 3 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 37 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "2", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 7.397, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 39 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 0.5, + "memory_limit": 402653184, + "memory_bytes": 71471104, + "used_cpu_cores": 0.395, + "throttled_seconds": 2.281, + "throttled_periods": 52 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 0.5, + "memory_limit": 402653184, + "memory_bytes": 74948608, + "used_cpu_cores": 0.402, + "throttled_seconds": 3.152, + "throttled_periods": 56 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 177508352, + "used_cpu_cores": 0.426, + "throttled_seconds": 5.945, + "throttled_periods": 51 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 28581888, + "used_cpu_cores": 0.068, + "throttled_seconds": 0.038, + "throttled_periods": 1 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 15683584, + "used_cpu_cores": 0.031, + "throttled_seconds": 0.0, + "throttled_periods": 1 + } + ], + "run": 16, + "label": "fixed-2", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 40 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.0052, + "requested_seconds": 8, + "concurrency": 4, + "successful_requests": 1861, + "failed_requests": 0, + "successful_rps": 232.474, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 6.926, + "p95": 68.486, + "p99": 91.403 + }, + "all_attempt_latency_ms": { + "p50": 6.926, + "p95": 68.486, + "p99": 91.403 + }, + "status_counts": { + "200": 930, + "201": 931 + }, + "instance_counts": { + "16aafe01ce5e416f9c1bcdaa68f1079c": 931, + "a2529627732f4f9f90cf646991ab5670": 930 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.001, + "data": { + "postgres_activity": [ + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 37 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "3", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.563, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 39 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "2", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "2", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 7.273, + "data": { + "postgres_activity": [ + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 3 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 36 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "2", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "2", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 0.5, + "memory_limit": 402653184, + "memory_bytes": 71540736, + "used_cpu_cores": 0.384, + "throttled_seconds": 1.995, + "throttled_periods": 43 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 0.5, + "memory_limit": 402653184, + "memory_bytes": 71401472, + "used_cpu_cores": 0.393, + "throttled_seconds": 2.796, + "throttled_periods": 50 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 176488448, + "used_cpu_cores": 0.432, + "throttled_seconds": 7.931, + "throttled_periods": 65 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 28217344, + "used_cpu_cores": 0.068, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 17887232, + "used_cpu_cores": 0.033, + "throttled_seconds": 0.049, + "throttled_periods": 3 + } + ], + "run": 17, + "label": "fixed-2", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 40 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.0077, + "requested_seconds": 8, + "concurrency": 4, + "successful_requests": 1766, + "failed_requests": 0, + "successful_rps": 220.536, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 8.023, + "p95": 68.443, + "p99": 89.8 + }, + "all_attempt_latency_ms": { + "p50": 8.023, + "p95": 68.443, + "p99": 89.8 + }, + "status_counts": { + "201": 883, + "200": 883 + }, + "instance_counts": { + "16aafe01ce5e416f9c1bcdaa68f1079c": 884, + "a2529627732f4f9f90cf646991ab5670": 882 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.001, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 38 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "3", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.659, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 40 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "2", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "2", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 7.39, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 40 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 0.5, + "memory_limit": 402653184, + "memory_bytes": 71581696, + "used_cpu_cores": 0.391, + "throttled_seconds": 1.562, + "throttled_periods": 50 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 0.5, + "memory_limit": 402653184, + "memory_bytes": 74350592, + "used_cpu_cores": 0.391, + "throttled_seconds": 1.368, + "throttled_periods": 44 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 177885184, + "used_cpu_cores": 0.442, + "throttled_seconds": 8.902, + "throttled_periods": 74 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 28168192, + "used_cpu_cores": 0.076, + "throttled_seconds": 0.003, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 17768448, + "used_cpu_cores": 0.035, + "throttled_seconds": 0.104, + "throttled_periods": 3 + } + ], + "run": 18, + "label": "fixed-2", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 40 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.0254, + "requested_seconds": 8, + "concurrency": 4, + "successful_requests": 1173, + "failed_requests": 0, + "successful_rps": 146.161, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 9.771, + "p95": 87.818, + "p99": 154.749 + }, + "all_attempt_latency_ms": { + "p50": 9.771, + "p95": 87.818, + "p99": 154.749 + }, + "status_counts": { + "200": 586, + "201": 587 + }, + "instance_counts": { + "f8c3c52bacb143dbae056d29e852c58f": 293, + "f50df8a0f4d840bb82a8090904532c88": 294, + "132604cb4ded4de0b7091e0dec79774d": 294, + "c0e978a1a90243beac979f3244c346f2": 292 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.008, + "data": { + "postgres_activity": [ + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 15 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "3", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.505, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 13 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 2 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "2", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 7.093, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 15 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-10", + "cpu_limit": 0.25, + "memory_limit": 201326592, + "memory_bytes": 49577984, + "used_cpu_cores": 0.204, + "throttled_seconds": 6.656, + "throttled_periods": 69 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 0.25, + "memory_limit": 201326592, + "memory_bytes": 45322240, + "used_cpu_cores": 0.215, + "throttled_seconds": 4.703, + "throttled_periods": 63 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 0.25, + "memory_limit": 201326592, + "memory_bytes": 46743552, + "used_cpu_cores": 0.228, + "throttled_seconds": 5.443, + "throttled_periods": 73 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-9", + "cpu_limit": 0.25, + "memory_limit": 201326592, + "memory_bytes": 45322240, + "used_cpu_cores": 0.212, + "throttled_seconds": 4.63, + "throttled_periods": 71 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 128356352, + "used_cpu_cores": 0.274, + "throttled_seconds": 0.821, + "throttled_periods": 12 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 28549120, + "used_cpu_cores": 0.054, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 18006016, + "used_cpu_cores": 0.03, + "throttled_seconds": 0.029, + "throttled_periods": 2 + } + ], + "run": 19, + "label": "fixed-4", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 16 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.0408, + "requested_seconds": 8, + "concurrency": 4, + "successful_requests": 935, + "failed_requests": 0, + "successful_rps": 116.282, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 11.733, + "p95": 102.574, + "p99": 192.195 + }, + "all_attempt_latency_ms": { + "p50": 11.733, + "p95": 102.574, + "p99": 192.195 + }, + "status_counts": { + "200": 468, + "201": 467 + }, + "instance_counts": { + "132604cb4ded4de0b7091e0dec79774d": 234, + "f50df8a0f4d840bb82a8090904532c88": 234, + "f8c3c52bacb143dbae056d29e852c58f": 232, + "c0e978a1a90243beac979f3244c346f2": 235 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.003, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 16 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.595, + "data": { + "postgres_activity": [ + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 14 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "2", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "2", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 7.167, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 15 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "2", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-10", + "cpu_limit": 0.25, + "memory_limit": 201326592, + "memory_bytes": 51970048, + "used_cpu_cores": 0.202, + "throttled_seconds": 6.883, + "throttled_periods": 58 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 0.25, + "memory_limit": 201326592, + "memory_bytes": 53575680, + "used_cpu_cores": 0.196, + "throttled_seconds": 4.917, + "throttled_periods": 48 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 0.25, + "memory_limit": 201326592, + "memory_bytes": 54820864, + "used_cpu_cores": 0.199, + "throttled_seconds": 5.667, + "throttled_periods": 58 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-9", + "cpu_limit": 0.25, + "memory_limit": 201326592, + "memory_bytes": 52969472, + "used_cpu_cores": 0.201, + "throttled_seconds": 6.098, + "throttled_periods": 57 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 123510784, + "used_cpu_cores": 0.281, + "throttled_seconds": 2.304, + "throttled_periods": 21 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 28594176, + "used_cpu_cores": 0.052, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 15577088, + "used_cpu_cores": 0.031, + "throttled_seconds": 0.04, + "throttled_periods": 4 + } + ], + "run": 20, + "label": "fixed-4", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 16 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.0834, + "requested_seconds": 8, + "concurrency": 4, + "successful_requests": 1006, + "failed_requests": 0, + "successful_rps": 124.453, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 9.399, + "p95": 102.817, + "p99": 207.364 + }, + "all_attempt_latency_ms": { + "p50": 9.399, + "p95": 102.817, + "p99": 207.364 + }, + "status_counts": { + "200": 503, + "201": 503 + }, + "instance_counts": { + "f8c3c52bacb143dbae056d29e852c58f": 252, + "f50df8a0f4d840bb82a8090904532c88": 252, + "c0e978a1a90243beac979f3244c346f2": 250, + "132604cb4ded4de0b7091e0dec79774d": 252 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.001, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 18 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "2", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.629, + "data": { + "postgres_activity": [ + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 17 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 7.12, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 18 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "2", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-10", + "cpu_limit": 0.25, + "memory_limit": 201326592, + "memory_bytes": 56365056, + "used_cpu_cores": 0.197, + "throttled_seconds": 6.282, + "throttled_periods": 56 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 0.25, + "memory_limit": 201326592, + "memory_bytes": 52113408, + "used_cpu_cores": 0.191, + "throttled_seconds": 3.948, + "throttled_periods": 43 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 0.25, + "memory_limit": 201326592, + "memory_bytes": 56442880, + "used_cpu_cores": 0.193, + "throttled_seconds": 6.44, + "throttled_periods": 55 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-9", + "cpu_limit": 0.25, + "memory_limit": 201326592, + "memory_bytes": 51122176, + "used_cpu_cores": 0.216, + "throttled_seconds": 7.399, + "throttled_periods": 65 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 133124096, + "used_cpu_cores": 0.252, + "throttled_seconds": 1.063, + "throttled_periods": 13 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 28254208, + "used_cpu_cores": 0.05, + "throttled_seconds": 0.008, + "throttled_periods": 1 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 11403264, + "used_cpu_cores": 0.03, + "throttled_seconds": 0.061, + "throttled_periods": 3 + } + ], + "run": 21, + "label": "fixed-4", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 18 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.0928, + "requested_seconds": 8, + "concurrency": 16, + "successful_requests": 1600, + "failed_requests": 0, + "successful_rps": 197.706, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 64.7, + "p95": 226.847, + "p99": 352.49 + }, + "all_attempt_latency_ms": { + "p50": 64.7, + "p95": 226.847, + "p99": 352.49 + }, + "status_counts": { + "200": 800, + "201": 800 + }, + "instance_counts": { + "f8c3c52bacb143dbae056d29e852c58f": 399, + "f50df8a0f4d840bb82a8090904532c88": 401, + "c0e978a1a90243beac979f3244c346f2": 400, + "132604cb4ded4de0b7091e0dec79774d": 400 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.004, + "data": { + "postgres_activity": [ + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 5 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 36 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "5", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "2", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "8", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.736, + "data": { + "postgres_activity": [ + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 3 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 39 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "6", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "6", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "4", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 7.189, + "data": { + "postgres_activity": [ + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 41 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "2", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "9", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "5", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-10", + "cpu_limit": 0.25, + "memory_limit": 201326592, + "memory_bytes": 56180736, + "used_cpu_cores": 0.225, + "throttled_seconds": 11.195, + "throttled_periods": 79 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 0.25, + "memory_limit": 201326592, + "memory_bytes": 55296000, + "used_cpu_cores": 0.219, + "throttled_seconds": 11.353, + "throttled_periods": 82 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 0.25, + "memory_limit": 201326592, + "memory_bytes": 61288448, + "used_cpu_cores": 0.216, + "throttled_seconds": 12.929, + "throttled_periods": 80 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-9", + "cpu_limit": 0.25, + "memory_limit": 201326592, + "memory_bytes": 56655872, + "used_cpu_cores": 0.227, + "throttled_seconds": 13.882, + "throttled_periods": 85 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 189661184, + "used_cpu_cores": 0.371, + "throttled_seconds": 3.125, + "throttled_periods": 31 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 28176384, + "used_cpu_cores": 0.058, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 17248256, + "used_cpu_cores": 0.027, + "throttled_seconds": 0.0, + "throttled_periods": 0 + } + ], + "run": 22, + "label": "fixed-4", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 43 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.2188, + "requested_seconds": 8, + "concurrency": 16, + "successful_requests": 1867, + "failed_requests": 0, + "successful_rps": 227.163, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 55.992, + "p95": 202.483, + "p99": 369.595 + }, + "all_attempt_latency_ms": { + "p50": 55.992, + "p95": 202.483, + "p99": 369.595 + }, + "status_counts": { + "200": 932, + "201": 935 + }, + "instance_counts": { + "f50df8a0f4d840bb82a8090904532c88": 466, + "132604cb4ded4de0b7091e0dec79774d": 468, + "f8c3c52bacb143dbae056d29e852c58f": 467, + "c0e978a1a90243beac979f3244c346f2": 466 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.0, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": null, + "count": 1 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 2 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 39 + }, + { + "state": "active", + "wait_event_type": null, + "count": 3 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "7", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "7", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.602, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 40 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 3 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "4", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "12", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 7.187, + "data": { + "postgres_activity": [ + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 5 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 40 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "16", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-10", + "cpu_limit": 0.25, + "memory_limit": 201326592, + "memory_bytes": 57782272, + "used_cpu_cores": 0.209, + "throttled_seconds": 9.919, + "throttled_periods": 73 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 0.25, + "memory_limit": 201326592, + "memory_bytes": 60919808, + "used_cpu_cores": 0.233, + "throttled_seconds": 10.119, + "throttled_periods": 81 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 0.25, + "memory_limit": 201326592, + "memory_bytes": 58204160, + "used_cpu_cores": 0.24, + "throttled_seconds": 10.798, + "throttled_periods": 84 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-9", + "cpu_limit": 0.25, + "memory_limit": 201326592, + "memory_bytes": 64253952, + "used_cpu_cores": 0.219, + "throttled_seconds": 6.021, + "throttled_periods": 68 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 203624448, + "used_cpu_cores": 0.389, + "throttled_seconds": 9.752, + "throttled_periods": 62 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 28700672, + "used_cpu_cores": 0.062, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 17461248, + "used_cpu_cores": 0.028, + "throttled_seconds": 0.0, + "throttled_periods": 0 + } + ], + "run": 23, + "label": "fixed-4", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 48 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.2605, + "requested_seconds": 8, + "concurrency": 16, + "successful_requests": 1916, + "failed_requests": 0, + "successful_rps": 231.947, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 38.615, + "p95": 221.725, + "p99": 361.35 + }, + "all_attempt_latency_ms": { + "p50": 38.615, + "p95": 221.725, + "p99": 361.35 + }, + "status_counts": { + "200": 957, + "201": 959 + }, + "instance_counts": { + "f8c3c52bacb143dbae056d29e852c58f": 480, + "c0e978a1a90243beac979f3244c346f2": 479, + "132604cb4ded4de0b7091e0dec79774d": 478, + "f50df8a0f4d840bb82a8090904532c88": 479 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.01, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 1 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 5 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 40 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "15", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.792, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 2 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 50 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "3", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "10", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "2", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 7.416, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 3 + }, + { + "state": "active", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 3 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 45 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-10", + "cpu_limit": 0.25, + "memory_limit": 201326592, + "memory_bytes": 58359808, + "used_cpu_cores": 0.224, + "throttled_seconds": 4.836, + "throttled_periods": 67 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 0.25, + "memory_limit": 201326592, + "memory_bytes": 57327616, + "used_cpu_cores": 0.224, + "throttled_seconds": 12.436, + "throttled_periods": 78 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 0.25, + "memory_limit": 201326592, + "memory_bytes": 65925120, + "used_cpu_cores": 0.217, + "throttled_seconds": 9.944, + "throttled_periods": 78 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-9", + "cpu_limit": 0.25, + "memory_limit": 201326592, + "memory_bytes": 64847872, + "used_cpu_cores": 0.214, + "throttled_seconds": 7.746, + "throttled_periods": 77 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 218763264, + "used_cpu_cores": 0.429, + "throttled_seconds": 7.962, + "throttled_periods": 72 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 28504064, + "used_cpu_cores": 0.064, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 15712256, + "used_cpu_cores": 0.032, + "throttled_seconds": 0.02, + "throttled_periods": 2 + } + ], + "run": 24, + "label": "fixed-4", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 53 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.1505, + "requested_seconds": 8, + "concurrency": 64, + "successful_requests": 1910, + "failed_requests": 0, + "successful_rps": 234.342, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 214.484, + "p95": 577.561, + "p99": 817.818 + }, + "all_attempt_latency_ms": { + "p50": 214.484, + "p95": 577.561, + "p99": 817.818 + }, + "status_counts": { + "200": 947, + "201": 963 + }, + "instance_counts": { + "132604cb4ded4de0b7091e0dec79774d": 478, + "f50df8a0f4d840bb82a8090904532c88": 479, + "f8c3c52bacb143dbae056d29e852c58f": 477, + "c0e978a1a90243beac979f3244c346f2": 476 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.006, + "data": { + "postgres_activity": [ + { + "state": "idle in transaction", + "wait_event_type": "LWLock", + "count": 2 + }, + { + "state": "active", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "active", + "wait_event_type": "LWLock", + "count": 32 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 7 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 34 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "13", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "15", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "18", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "18", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 5.589, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 23 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 4 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "idle in transaction", + "wait_event_type": null, + "count": 3 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 5 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 42 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "17", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "14", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "15", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "18", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-10", + "cpu_limit": 0.25, + "memory_limit": 201326592, + "memory_bytes": 63619072, + "used_cpu_cores": 0.176, + "throttled_seconds": 1.819, + "throttled_periods": 24 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 0.25, + "memory_limit": 201326592, + "memory_bytes": 62709760, + "used_cpu_cores": 0.182, + "throttled_seconds": 2.369, + "throttled_periods": 26 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 0.25, + "memory_limit": 201326592, + "memory_bytes": 65241088, + "used_cpu_cores": 0.172, + "throttled_seconds": 1.357, + "throttled_periods": 17 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-9", + "cpu_limit": 0.25, + "memory_limit": 201326592, + "memory_bytes": 65331200, + "used_cpu_cores": 0.178, + "throttled_seconds": 0.794, + "throttled_periods": 24 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 275537920, + "used_cpu_cores": 0.439, + "throttled_seconds": 49.715, + "throttled_periods": 82 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 28221440, + "used_cpu_cores": 0.068, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 15794176, + "used_cpu_cores": 0.03, + "throttled_seconds": 0.085, + "throttled_periods": 2 + } + ], + "run": 25, + "label": "fixed-4", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 79 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.1118, + "requested_seconds": 8, + "concurrency": 64, + "successful_requests": 1883, + "failed_requests": 0, + "successful_rps": 232.131, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 204.751, + "p95": 682.007, + "p99": 1115.534 + }, + "all_attempt_latency_ms": { + "p50": 204.751, + "p95": 682.007, + "p99": 1115.534 + }, + "status_counts": { + "200": 941, + "201": 942 + }, + "instance_counts": { + "132604cb4ded4de0b7091e0dec79774d": 472, + "f8c3c52bacb143dbae056d29e852c58f": 471, + "c0e978a1a90243beac979f3244c346f2": 468, + "f50df8a0f4d840bb82a8090904532c88": 472 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.015, + "data": { + "postgres_activity": [ + { + "state": "idle in transaction", + "wait_event_type": "LWLock", + "count": 1 + }, + { + "state": "active", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "active", + "wait_event_type": "LWLock", + "count": 30 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 2 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 4 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 3 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 38 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "15", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "14", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "17", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "18", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 5.765, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 18 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 1 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 6 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 50 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 2 + }, + { + "state": "active", + "wait_event_type": null, + "count": 3 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "14", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "17", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "16", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "17", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-10", + "cpu_limit": 0.25, + "memory_limit": 201326592, + "memory_bytes": 66449408, + "used_cpu_cores": 0.165, + "throttled_seconds": 1.703, + "throttled_periods": 22 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 0.25, + "memory_limit": 201326592, + "memory_bytes": 65081344, + "used_cpu_cores": 0.179, + "throttled_seconds": 2.455, + "throttled_periods": 28 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 0.25, + "memory_limit": 201326592, + "memory_bytes": 64249856, + "used_cpu_cores": 0.17, + "throttled_seconds": 1.284, + "throttled_periods": 24 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-9", + "cpu_limit": 0.25, + "memory_limit": 201326592, + "memory_bytes": 65757184, + "used_cpu_cores": 0.162, + "throttled_seconds": 0.495, + "throttled_periods": 19 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 273428480, + "used_cpu_cores": 0.442, + "throttled_seconds": 49.778, + "throttled_periods": 83 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 28913664, + "used_cpu_cores": 0.071, + "throttled_seconds": 0.094, + "throttled_periods": 1 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 17821696, + "used_cpu_cores": 0.031, + "throttled_seconds": 0.101, + "throttled_periods": 3 + } + ], + "run": 26, + "label": "fixed-4", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 80 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.1869, + "requested_seconds": 8, + "concurrency": 64, + "successful_requests": 2023, + "failed_requests": 0, + "successful_rps": 247.101, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 211.199, + "p95": 501.88, + "p99": 696.456 + }, + "all_attempt_latency_ms": { + "p50": 211.199, + "p95": 501.88, + "p99": 696.456 + }, + "status_counts": { + "200": 1006, + "201": 1017 + }, + "instance_counts": { + "c0e978a1a90243beac979f3244c346f2": 506, + "132604cb4ded4de0b7091e0dec79774d": 506, + "f8c3c52bacb143dbae056d29e852c58f": 505, + "f50df8a0f4d840bb82a8090904532c88": 506 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.012, + "data": { + "postgres_activity": [ + { + "state": "idle in transaction", + "wait_event_type": "LWLock", + "count": 1 + }, + { + "state": "active", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "active", + "wait_event_type": "LWLock", + "count": 30 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 4 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 4 + }, + { + "state": "idle in transaction", + "wait_event_type": null, + "count": 1 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 4 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 34 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "17", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "18", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "16", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "13", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 6.061, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "active", + "wait_event_type": "LWLock", + "count": 10 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 2 + }, + { + "state": "active", + "wait_event_type": null, + "count": 5 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "idle in transaction", + "wait_event_type": null, + "count": 1 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 8 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 52 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "11", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "12", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "15", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "17", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-10", + "cpu_limit": 0.25, + "memory_limit": 201326592, + "memory_bytes": 66428928, + "used_cpu_cores": 0.17, + "throttled_seconds": 1.658, + "throttled_periods": 21 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 0.25, + "memory_limit": 201326592, + "memory_bytes": 65232896, + "used_cpu_cores": 0.173, + "throttled_seconds": 1.949, + "throttled_periods": 22 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 0.25, + "memory_limit": 201326592, + "memory_bytes": 66805760, + "used_cpu_cores": 0.166, + "throttled_seconds": 1.55, + "throttled_periods": 19 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-9", + "cpu_limit": 0.25, + "memory_limit": 201326592, + "memory_bytes": 66412544, + "used_cpu_cores": 0.167, + "throttled_seconds": 0.644, + "throttled_periods": 21 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 281210880, + "used_cpu_cores": 0.44, + "throttled_seconds": 48.847, + "throttled_periods": 82 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 28733440, + "used_cpu_cores": 0.072, + "throttled_seconds": 0.001, + "throttled_periods": 1 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 17629184, + "used_cpu_cores": 0.026, + "throttled_seconds": 0.054, + "throttled_periods": 1 + } + ], + "run": 27, + "label": "fixed-4", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 80 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.0202, + "requested_seconds": 8, + "concurrency": 4, + "successful_requests": 2075, + "failed_requests": 0, + "successful_rps": 258.723, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 7.27, + "p95": 62.134, + "p99": 71.325 + }, + "all_attempt_latency_ms": { + "p50": 7.27, + "p95": 62.134, + "p99": 71.325 + }, + "status_counts": { + "200": 1037, + "201": 1038 + }, + "instance_counts": { + "987ac32f4e1246bc93dd3f726ba673f1": 2075 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.005, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 5 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "2", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.533, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 4 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "4", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 7.016, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 2 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "3", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 53387264, + "used_cpu_cores": 0.883, + "throttled_seconds": 5.078, + "throttled_periods": 74 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 116109312, + "used_cpu_cores": 0.41, + "throttled_seconds": 2.894, + "throttled_periods": 31 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 28827648, + "used_cpu_cores": 0.063, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 17653760, + "used_cpu_cores": 0.03, + "throttled_seconds": 0.0, + "throttled_periods": 0 + } + ], + "run": 28, + "label": "growing-1", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 6 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.0029, + "requested_seconds": 8, + "concurrency": 4, + "successful_requests": 1917, + "failed_requests": 0, + "successful_rps": 239.539, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 7.572, + "p95": 63.995, + "p99": 88.446 + }, + "all_attempt_latency_ms": { + "p50": 7.572, + "p95": 63.995, + "p99": 88.446 + }, + "status_counts": { + "200": 958, + "201": 959 + }, + "instance_counts": { + "987ac32f4e1246bc93dd3f726ba673f1": 1917 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.011, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 6 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "2", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.773, + "data": { + "postgres_activity": [ + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 4 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "4", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 7.296, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 6 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "4", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 57774080, + "used_cpu_cores": 0.843, + "throttled_seconds": 4.63, + "throttled_periods": 67 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 117977088, + "used_cpu_cores": 0.412, + "throttled_seconds": 5.106, + "throttled_periods": 43 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 28327936, + "used_cpu_cores": 0.061, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 15659008, + "used_cpu_cores": 0.031, + "throttled_seconds": 0.06, + "throttled_periods": 1 + } + ], + "run": 29, + "label": "growing-1", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 6 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.0065, + "requested_seconds": 8, + "concurrency": 4, + "successful_requests": 2004, + "failed_requests": 0, + "successful_rps": 250.297, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 7.085, + "p95": 65.691, + "p99": 83.834 + }, + "all_attempt_latency_ms": { + "p50": 7.085, + "p95": 65.691, + "p99": 83.834 + }, + "status_counts": { + "201": 1002, + "200": 1002 + }, + "instance_counts": { + "987ac32f4e1246bc93dd3f726ba673f1": 2004 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.001, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 5 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "4", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.5, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 6 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "4", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 7.106, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 6 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "4", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 65028096, + "used_cpu_cores": 0.86, + "throttled_seconds": 5.399, + "throttled_periods": 63 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 112017408, + "used_cpu_cores": 0.403, + "throttled_seconds": 5.529, + "throttled_periods": 41 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 29159424, + "used_cpu_cores": 0.064, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 17747968, + "used_cpu_cores": 0.032, + "throttled_seconds": 0.154, + "throttled_periods": 2 + } + ], + "run": 30, + "label": "growing-1", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 6 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.2581, + "requested_seconds": 8, + "concurrency": 16, + "successful_requests": 2473, + "failed_requests": 0, + "successful_rps": 299.464, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 51.641, + "p95": 101.129, + "p99": 169.605 + }, + "all_attempt_latency_ms": { + "p50": 51.641, + "p95": 101.129, + "p99": 169.605 + }, + "status_counts": { + "201": 1236, + "200": 1237 + }, + "instance_counts": { + "987ac32f4e1246bc93dd3f726ba673f1": 2473 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.0, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 3 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 4 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 8 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "13", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.783, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 1 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 12 + }, + { + "state": "active", + "wait_event_type": null, + "count": 3 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "16", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 7.498, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 17 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 67903488, + "used_cpu_cores": 0.529, + "throttled_seconds": 1.312, + "throttled_periods": 16 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 146280448, + "used_cpu_cores": 0.452, + "throttled_seconds": 31.742, + "throttled_periods": 82 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 29503488, + "used_cpu_cores": 0.067, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 17879040, + "used_cpu_cores": 0.032, + "throttled_seconds": 0.008, + "throttled_periods": 1 + } + ], + "run": 31, + "label": "growing-1", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 18 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.2616, + "requested_seconds": 8, + "concurrency": 16, + "successful_requests": 2420, + "failed_requests": 0, + "successful_rps": 292.921, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 78.396, + "p95": 102.186, + "p99": 113.526 + }, + "all_attempt_latency_ms": { + "p50": 78.396, + "p95": 102.186, + "p99": 113.526 + }, + "status_counts": { + "200": 1208, + "201": 1212 + }, + "instance_counts": { + "987ac32f4e1246bc93dd3f726ba673f1": 2420 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.002, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 2 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 2 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 10 + }, + { + "state": "active", + "wait_event_type": null, + "count": 3 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "16", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.902, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 15 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "16", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 7.676, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 18 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 68038656, + "used_cpu_cores": 0.372, + "throttled_seconds": 0.02, + "throttled_periods": 1 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 146882560, + "used_cpu_cores": 0.455, + "throttled_seconds": 35.099, + "throttled_periods": 81 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 31232000, + "used_cpu_cores": 0.074, + "throttled_seconds": 0.365, + "throttled_periods": 1 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 18079744, + "used_cpu_cores": 0.031, + "throttled_seconds": 0.01, + "throttled_periods": 1 + } + ], + "run": 32, + "label": "growing-1", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 18 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.3243, + "requested_seconds": 8, + "concurrency": 16, + "successful_requests": 2353, + "failed_requests": 0, + "successful_rps": 282.668, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 76.844, + "p95": 104.612, + "p99": 191.127 + }, + "all_attempt_latency_ms": { + "p50": 76.844, + "p95": 104.612, + "p99": 191.127 + }, + "status_counts": { + "201": 1175, + "200": 1178 + }, + "instance_counts": { + "987ac32f4e1246bc93dd3f726ba673f1": 2353 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.002, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 5 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 11 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "16", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.768, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": null, + "count": 2 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 14 + }, + { + "state": "active", + "wait_event_type": null, + "count": 2 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "16", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 7.46, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 18 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 66011136, + "used_cpu_cores": 0.366, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 167428096, + "used_cpu_cores": 0.447, + "throttled_seconds": 35.541, + "throttled_periods": 81 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 28921856, + "used_cpu_cores": 0.064, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 17231872, + "used_cpu_cores": 0.027, + "throttled_seconds": 0.0, + "throttled_periods": 0 + } + ], + "run": 33, + "label": "growing-1", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 18 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.4306, + "requested_seconds": 8, + "concurrency": 64, + "successful_requests": 2555, + "failed_requests": 0, + "successful_rps": 303.063, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 195.927, + "p95": 390.498, + "p99": 413.029 + }, + "all_attempt_latency_ms": { + "p50": 195.927, + "p95": 390.498, + "p99": 413.029 + }, + "status_counts": { + "200": 1277, + "201": 1278 + }, + "instance_counts": { + "987ac32f4e1246bc93dd3f726ba673f1": 2555 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.009, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 2 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 2 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 13 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 2 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "64", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.86, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 5 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 1 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 8 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 4 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "64", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 7.861, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 20 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 77922304, + "used_cpu_cores": 0.326, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 175390720, + "used_cpu_cores": 0.439, + "throttled_seconds": 39.809, + "throttled_periods": 82 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 26894336, + "used_cpu_cores": 0.076, + "throttled_seconds": 0.93, + "throttled_periods": 2 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 17981440, + "used_cpu_cores": 0.029, + "throttled_seconds": 0.0, + "throttled_periods": 0 + } + ], + "run": 34, + "label": "growing-1", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 20 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.5022, + "requested_seconds": 8, + "concurrency": 64, + "successful_requests": 2429, + "failed_requests": 0, + "successful_rps": 285.691, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 200.603, + "p95": 312.428, + "p99": 497.152 + }, + "all_attempt_latency_ms": { + "p50": 200.603, + "p95": 312.428, + "p99": 497.152 + }, + "status_counts": { + "200": 1208, + "201": 1221 + }, + "instance_counts": { + "987ac32f4e1246bc93dd3f726ba673f1": 2429 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.001, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 3 + }, + { + "state": "active", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + }, + { + "state": "idle in transaction", + "wait_event_type": null, + "count": 1 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 12 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "64", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.939, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "active", + "wait_event_type": "LWLock", + "count": 4 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 7 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 6 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "64", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 8.103, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 20 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 69509120, + "used_cpu_cores": 0.322, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 176488448, + "used_cpu_cores": 0.448, + "throttled_seconds": 40.656, + "throttled_periods": 83 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 29253632, + "used_cpu_cores": 0.072, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 15859712, + "used_cpu_cores": 0.028, + "throttled_seconds": 0.0, + "throttled_periods": 0 + } + ], + "run": 35, + "label": "growing-1", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 20 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.1381, + "requested_seconds": 8, + "concurrency": 64, + "successful_requests": 2413, + "failed_requests": 0, + "successful_rps": 296.505, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 200.612, + "p95": 386.697, + "p99": 405.375 + }, + "all_attempt_latency_ms": { + "p50": 200.612, + "p95": 386.697, + "p99": 405.375 + }, + "status_counts": { + "201": 1212, + "200": 1201 + }, + "instance_counts": { + "987ac32f4e1246bc93dd3f726ba673f1": 2413 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.011, + "data": { + "postgres_activity": [ + { + "state": "idle in transaction", + "wait_event_type": null, + "count": 1 + }, + { + "state": "active", + "wait_event_type": "LWLock", + "count": 14 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 2 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "64", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 5.28, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 1 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 2 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 13 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 2 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "64", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 74268672, + "used_cpu_cores": 0.315, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 176439296, + "used_cpu_cores": 0.458, + "throttled_seconds": 38.844, + "throttled_periods": 82 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 26804224, + "used_cpu_cores": 0.071, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 17788928, + "used_cpu_cores": 0.025, + "throttled_seconds": 0.0, + "throttled_periods": 0 + } + ], + "run": 36, + "label": "growing-1", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 20 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.1803, + "requested_seconds": 8, + "concurrency": 64, + "successful_requests": 2206, + "failed_requests": 0, + "successful_rps": 269.672, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 204.499, + "p95": 410.645, + "p99": 688.284 + }, + "all_attempt_latency_ms": { + "p50": 204.499, + "p95": 410.645, + "p99": 688.284 + }, + "status_counts": { + "200": 1099, + "201": 1107 + }, + "instance_counts": { + "f5bfe63066cc4afe970e97152eb61f1b": 1102, + "a863ecb81ea0454f9a0707ef5be71a46": 1104 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.01, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 8 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 2 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 2 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 25 + }, + { + "state": "active", + "wait_event_type": null, + "count": 2 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "40", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "24", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 5.626, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": "LWLock", + "count": 5 + }, + { + "state": "active", + "wait_event_type": "Client", + "count": 7 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 2 + }, + { + "state": "active", + "wait_event_type": null, + "count": 5 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 3 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 17 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "30", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "34", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 60522496, + "used_cpu_cores": 0.386, + "throttled_seconds": 0.121, + "throttled_periods": 3 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 59142144, + "used_cpu_cores": 0.38, + "throttled_seconds": 0.132, + "throttled_periods": 5 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 224038912, + "used_cpu_cores": 0.449, + "throttled_seconds": 46.051, + "throttled_periods": 83 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 27660288, + "used_cpu_cores": 0.064, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 18194432, + "used_cpu_cores": 0.028, + "throttled_seconds": 0.0, + "throttled_periods": 0 + } + ], + "run": 37, + "label": "growing-2", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 40 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.2665, + "requested_seconds": 8, + "concurrency": 64, + "successful_requests": 2338, + "failed_requests": 0, + "successful_rps": 282.83, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 203.814, + "p95": 396.819, + "p99": 497.637 + }, + "all_attempt_latency_ms": { + "p50": 203.814, + "p95": 396.819, + "p99": 497.637 + }, + "status_counts": { + "201": 1175, + "200": 1163 + }, + "instance_counts": { + "a863ecb81ea0454f9a0707ef5be71a46": 1170, + "f5bfe63066cc4afe970e97152eb61f1b": 1168 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.005, + "data": { + "postgres_activity": [ + { + "state": "idle in transaction", + "wait_event_type": null, + "count": 1 + }, + { + "state": "active", + "wait_event_type": "LWLock", + "count": 11 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 3 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 4 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 20 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "35", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "29", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 5.422, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "active", + "wait_event_type": "LWLock", + "count": 11 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 4 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 17 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 6 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "28", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "36", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 65773568, + "used_cpu_cores": 0.371, + "throttled_seconds": 0.011, + "throttled_periods": 2 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 62545920, + "used_cpu_cores": 0.388, + "throttled_seconds": 0.1, + "throttled_periods": 6 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 226037760, + "used_cpu_cores": 0.463, + "throttled_seconds": 46.285, + "throttled_periods": 86 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 29593600, + "used_cpu_cores": 0.082, + "throttled_seconds": 0.772, + "throttled_periods": 3 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 18190336, + "used_cpu_cores": 0.029, + "throttled_seconds": 0.0, + "throttled_periods": 0 + } + ], + "run": 38, + "label": "growing-2", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 40 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.1917, + "requested_seconds": 8, + "concurrency": 64, + "successful_requests": 2203, + "failed_requests": 0, + "successful_rps": 268.931, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 203.239, + "p95": 488.041, + "p99": 683.952 + }, + "all_attempt_latency_ms": { + "p50": 203.239, + "p95": 488.041, + "p99": 683.952 + }, + "status_counts": { + "200": 1097, + "201": 1106 + }, + "instance_counts": { + "a863ecb81ea0454f9a0707ef5be71a46": 1103, + "f5bfe63066cc4afe970e97152eb61f1b": 1100 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.004, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 9 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 3 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + }, + { + "state": "idle in transaction", + "wait_event_type": null, + "count": 1 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 7 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 18 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "42", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "22", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 5.243, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 11 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 2 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 8 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 17 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "26", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "29", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 68943872, + "used_cpu_cores": 0.344, + "throttled_seconds": 0.29, + "throttled_periods": 6 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 71454720, + "used_cpu_cores": 0.358, + "throttled_seconds": 0.203, + "throttled_periods": 7 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 230572032, + "used_cpu_cores": 0.463, + "throttled_seconds": 46.755, + "throttled_periods": 85 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 29429760, + "used_cpu_cores": 0.069, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 17805312, + "used_cpu_cores": 0.028, + "throttled_seconds": 0.0, + "throttled_periods": 0 + } + ], + "run": 39, + "label": "growing-2", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 40 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.3272, + "requested_seconds": 8, + "concurrency": 16, + "successful_requests": 2149, + "failed_requests": 0, + "successful_rps": 258.069, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 82.016, + "p95": 109.077, + "p99": 179.51 + }, + "all_attempt_latency_ms": { + "p50": 82.016, + "p95": 109.077, + "p99": 179.51 + }, + "status_counts": { + "200": 1072, + "201": 1077 + }, + "instance_counts": { + "f5bfe63066cc4afe970e97152eb61f1b": 1073, + "a863ecb81ea0454f9a0707ef5be71a46": 1076 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.007, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 2 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 35 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "8", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "8", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.857, + "data": { + "postgres_activity": [ + { + "state": "idle in transaction", + "wait_event_type": "LWLock", + "count": 1 + }, + { + "state": "active", + "wait_event_type": "LWLock", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 3 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 32 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "7", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "9", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 7.633, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 40 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 72892416, + "used_cpu_cores": 0.316, + "throttled_seconds": 0.315, + "throttled_periods": 6 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 72708096, + "used_cpu_cores": 0.312, + "throttled_seconds": 0.108, + "throttled_periods": 1 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 234295296, + "used_cpu_cores": 0.441, + "throttled_seconds": 28.87, + "throttled_periods": 82 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 29351936, + "used_cpu_cores": 0.063, + "throttled_seconds": 0.005, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 18415616, + "used_cpu_cores": 0.034, + "throttled_seconds": 0.222, + "throttled_periods": 2 + } + ], + "run": 40, + "label": "growing-2", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 40 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.4309, + "requested_seconds": 8, + "concurrency": 16, + "successful_requests": 2206, + "failed_requests": 0, + "successful_rps": 261.656, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 80.281, + "p95": 107.965, + "p99": 193.789 + }, + "all_attempt_latency_ms": { + "p50": 80.281, + "p95": 107.965, + "p99": 193.789 + }, + "status_counts": { + "200": 1102, + "201": 1104 + }, + "instance_counts": { + "a863ecb81ea0454f9a0707ef5be71a46": 1103, + "f5bfe63066cc4afe970e97152eb61f1b": 1103 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.013, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 1 + }, + { + "state": "active", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 37 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "9", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "7", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.946, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "Client", + "count": 2 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 2 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 36 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "8", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "8", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 7.792, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 40 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 71532544, + "used_cpu_cores": 0.263, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 70541312, + "used_cpu_cores": 0.267, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 236388352, + "used_cpu_cores": 0.441, + "throttled_seconds": 30.521, + "throttled_periods": 83 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 27295744, + "used_cpu_cores": 0.063, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 17997824, + "used_cpu_cores": 0.03, + "throttled_seconds": 0.011, + "throttled_periods": 1 + } + ], + "run": 41, + "label": "growing-2", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 40 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.3819, + "requested_seconds": 8, + "concurrency": 16, + "successful_requests": 2295, + "failed_requests": 0, + "successful_rps": 273.803, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 80.446, + "p95": 103.887, + "p99": 113.349 + }, + "all_attempt_latency_ms": { + "p50": 80.446, + "p95": 103.887, + "p99": 113.349 + }, + "status_counts": { + "200": 1147, + "201": 1148 + }, + "instance_counts": { + "f5bfe63066cc4afe970e97152eb61f1b": 1148, + "a863ecb81ea0454f9a0707ef5be71a46": 1147 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.002, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": null, + "count": 1 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 2 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 35 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "8", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "7", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.927, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 3 + }, + { + "state": "active", + "wait_event_type": "Client", + "count": 2 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 2 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 30 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 2 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "5", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "9", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 7.797, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 40 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 74137600, + "used_cpu_cores": 0.264, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 72757248, + "used_cpu_cores": 0.264, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 228986880, + "used_cpu_cores": 0.443, + "throttled_seconds": 31.224, + "throttled_periods": 83 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 29552640, + "used_cpu_cores": 0.07, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 18018304, + "used_cpu_cores": 0.028, + "throttled_seconds": 0.0, + "throttled_periods": 0 + } + ], + "run": 42, + "label": "growing-2", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 40 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.0425, + "requested_seconds": 8, + "concurrency": 4, + "successful_requests": 2014, + "failed_requests": 0, + "successful_rps": 250.42, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 7.067, + "p95": 67.655, + "p99": 83.309 + }, + "all_attempt_latency_ms": { + "p50": 7.067, + "p95": 67.655, + "p99": 83.309 + }, + "status_counts": { + "201": 1008, + "200": 1006 + }, + "instance_counts": { + "f5bfe63066cc4afe970e97152eb61f1b": 1006, + "a863ecb81ea0454f9a0707ef5be71a46": 1008 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.002, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 40 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "2", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.606, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": null, + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 38 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "2", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "2", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 7.217, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": null, + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 38 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 73777152, + "used_cpu_cores": 0.421, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 72142848, + "used_cpu_cores": 0.422, + "throttled_seconds": 0.0, + "throttled_periods": 1 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 252903424, + "used_cpu_cores": 0.465, + "throttled_seconds": 12.759, + "throttled_periods": 82 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 27402240, + "used_cpu_cores": 0.068, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 17489920, + "used_cpu_cores": 0.035, + "throttled_seconds": 0.0, + "throttled_periods": 1 + } + ], + "run": 43, + "label": "growing-2", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 40 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.093, + "requested_seconds": 8, + "concurrency": 4, + "successful_requests": 2178, + "failed_requests": 0, + "successful_rps": 269.121, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 6.694, + "p95": 63.087, + "p99": 83.604 + }, + "all_attempt_latency_ms": { + "p50": 6.694, + "p95": 63.087, + "p99": 83.604 + }, + "status_counts": { + "200": 1089, + "201": 1089 + }, + "instance_counts": { + "f5bfe63066cc4afe970e97152eb61f1b": 1089, + "a863ecb81ea0454f9a0707ef5be71a46": 1089 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.004, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 36 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 3 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "2", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.74, + "data": { + "postgres_activity": [ + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 38 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "2", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "2", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 7.464, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 39 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 73375744, + "used_cpu_cores": 0.427, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 72134656, + "used_cpu_cores": 0.416, + "throttled_seconds": 0.005, + "throttled_periods": 1 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 256921600, + "used_cpu_cores": 0.456, + "throttled_seconds": 11.8, + "throttled_periods": 82 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 29220864, + "used_cpu_cores": 0.072, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 16203776, + "used_cpu_cores": 0.032, + "throttled_seconds": 0.009, + "throttled_periods": 1 + } + ], + "run": 44, + "label": "growing-2", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 40 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.05, + "requested_seconds": 8, + "concurrency": 4, + "successful_requests": 2101, + "failed_requests": 0, + "successful_rps": 260.993, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 6.748, + "p95": 65.864, + "p99": 83.796 + }, + "all_attempt_latency_ms": { + "p50": 6.748, + "p95": 65.864, + "p99": 83.796 + }, + "status_counts": { + "200": 1050, + "201": 1051 + }, + "instance_counts": { + "f5bfe63066cc4afe970e97152eb61f1b": 1050, + "a863ecb81ea0454f9a0707ef5be71a46": 1051 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.005, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 38 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "3", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.605, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 40 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "2", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 7.2, + "data": { + "postgres_activity": [ + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 39 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 71471104, + "used_cpu_cores": 0.414, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 70336512, + "used_cpu_cores": 0.409, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 258179072, + "used_cpu_cores": 0.453, + "throttled_seconds": 12.433, + "throttled_periods": 82 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 29188096, + "used_cpu_cores": 0.069, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 18259968, + "used_cpu_cores": 0.033, + "throttled_seconds": 0.072, + "throttled_periods": 2 + } + ], + "run": 45, + "label": "growing-2", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 40 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.1539, + "requested_seconds": 8, + "concurrency": 4, + "successful_requests": 2041, + "failed_requests": 0, + "successful_rps": 250.31, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 9.988, + "p95": 46.464, + "p99": 81.058 + }, + "all_attempt_latency_ms": { + "p50": 9.988, + "p95": 46.464, + "p99": 81.058 + }, + "status_counts": { + "200": 1021, + "201": 1020 + }, + "instance_counts": { + "40787c3552d541a0a0c06adae3633bd6": 510, + "eae60a5820614657a3c6e0e4a8e5d9d9": 510, + "a42b4977c3b7495d9483124bd7015856": 511, + "8650bb2b9d7541c3ad2ae8e84d155675": 510 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.002, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 11 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.829, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 12 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 7.528, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 11 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-10", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 52543488, + "used_cpu_cores": 0.381, + "throttled_seconds": 0.199, + "throttled_periods": 3 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 53891072, + "used_cpu_cores": 0.377, + "throttled_seconds": 0.001, + "throttled_periods": 1 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 54755328, + "used_cpu_cores": 0.399, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-9", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 55201792, + "used_cpu_cores": 0.417, + "throttled_seconds": 0.129, + "throttled_periods": 2 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 196538368, + "used_cpu_cores": 0.434, + "throttled_seconds": 8.02, + "throttled_periods": 79 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 29085696, + "used_cpu_cores": 0.069, + "throttled_seconds": 0.055, + "throttled_periods": 1 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 17444864, + "used_cpu_cores": 0.034, + "throttled_seconds": 0.064, + "throttled_periods": 1 + } + ], + "run": 46, + "label": "growing-4", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 12 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.0071, + "requested_seconds": 8, + "concurrency": 4, + "successful_requests": 1962, + "failed_requests": 0, + "successful_rps": 245.033, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 9.887, + "p95": 51.051, + "p99": 78.901 + }, + "all_attempt_latency_ms": { + "p50": 9.887, + "p95": 51.051, + "p99": 78.901 + }, + "status_counts": { + "200": 981, + "201": 981 + }, + "instance_counts": { + "8650bb2b9d7541c3ad2ae8e84d155675": 489, + "40787c3552d541a0a0c06adae3633bd6": 490, + "a42b4977c3b7495d9483124bd7015856": 492, + "eae60a5820614657a3c6e0e4a8e5d9d9": 491 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.005, + "data": { + "postgres_activity": [ + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 2 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 10 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.647, + "data": { + "postgres_activity": [ + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 10 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 7.254, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 12 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-10", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 53936128, + "used_cpu_cores": 0.361, + "throttled_seconds": 0.152, + "throttled_periods": 3 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 61222912, + "used_cpu_cores": 0.349, + "throttled_seconds": 0.376, + "throttled_periods": 9 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 56430592, + "used_cpu_cores": 0.367, + "throttled_seconds": 0.172, + "throttled_periods": 5 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-9", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 54128640, + "used_cpu_cores": 0.341, + "throttled_seconds": 0.135, + "throttled_periods": 3 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 194781184, + "used_cpu_cores": 0.436, + "throttled_seconds": 7.272, + "throttled_periods": 74 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 27627520, + "used_cpu_cores": 0.072, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 17285120, + "used_cpu_cores": 0.039, + "throttled_seconds": 0.063, + "throttled_periods": 2 + } + ], + "run": 47, + "label": "growing-4", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 13 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.0042, + "requested_seconds": 8, + "concurrency": 4, + "successful_requests": 1486, + "failed_requests": 0, + "successful_rps": 185.652, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 12.121, + "p95": 70.995, + "p99": 107.966 + }, + "all_attempt_latency_ms": { + "p50": 12.121, + "p95": 70.995, + "p99": 107.966 + }, + "status_counts": { + "200": 744, + "201": 742 + }, + "instance_counts": { + "8650bb2b9d7541c3ad2ae8e84d155675": 370, + "eae60a5820614657a3c6e0e4a8e5d9d9": 372, + "40787c3552d541a0a0c06adae3633bd6": 373, + "a42b4977c3b7495d9483124bd7015856": 371 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.004, + "data": { + "postgres_activity": [ + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 11 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 5.204, + "data": { + "postgres_activity": [ + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 12 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "1", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-10", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 60497920, + "used_cpu_cores": 0.497, + "throttled_seconds": 0.789, + "throttled_periods": 19 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 62857216, + "used_cpu_cores": 0.363, + "throttled_seconds": 0.078, + "throttled_periods": 6 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 62709760, + "used_cpu_cores": 0.33, + "throttled_seconds": 0.457, + "throttled_periods": 9 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-9", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 62681088, + "used_cpu_cores": 0.277, + "throttled_seconds": 0.054, + "throttled_periods": 3 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 205053952, + "used_cpu_cores": 0.411, + "throttled_seconds": 8.823, + "throttled_periods": 75 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 22552576, + "used_cpu_cores": 0.087, + "throttled_seconds": 0.058, + "throttled_periods": 3 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 11415552, + "used_cpu_cores": 0.044, + "throttled_seconds": 0.224, + "throttled_periods": 4 + } + ], + "run": 48, + "label": "growing-4", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 15 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.5374, + "requested_seconds": 8, + "concurrency": 16, + "successful_requests": 1906, + "failed_requests": 0, + "successful_rps": 223.252, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 82.423, + "p95": 176.455, + "p99": 223.973 + }, + "all_attempt_latency_ms": { + "p50": 82.423, + "p95": 176.455, + "p99": 223.973 + }, + "status_counts": { + "200": 953, + "201": 953 + }, + "instance_counts": { + "40787c3552d541a0a0c06adae3633bd6": 476, + "a42b4977c3b7495d9483124bd7015856": 476, + "eae60a5820614657a3c6e0e4a8e5d9d9": 477, + "8650bb2b9d7541c3ad2ae8e84d155675": 477 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.002, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 28 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "3", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "3", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "4", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "4", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.918, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 4 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 27 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "4", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "3", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "5", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "4", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 8.004, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 32 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-10", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 61276160, + "used_cpu_cores": 0.211, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 60919808, + "used_cpu_cores": 0.2, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 64585728, + "used_cpu_cores": 0.216, + "throttled_seconds": 0.044, + "throttled_periods": 1 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-9", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 63770624, + "used_cpu_cores": 0.207, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 247250944, + "used_cpu_cores": 0.428, + "throttled_seconds": 30.199, + "throttled_periods": 83 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 27119616, + "used_cpu_cores": 0.078, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 19636224, + "used_cpu_cores": 0.031, + "throttled_seconds": 0.019, + "throttled_periods": 1 + } + ], + "run": 49, + "label": "growing-4", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 32 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.5382, + "requested_seconds": 8, + "concurrency": 16, + "successful_requests": 2023, + "failed_requests": 0, + "successful_rps": 236.934, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 82.569, + "p95": 108.311, + "p99": 195.723 + }, + "all_attempt_latency_ms": { + "p50": 82.569, + "p95": 108.311, + "p99": 195.723 + }, + "status_counts": { + "200": 1011, + "201": 1012 + }, + "instance_counts": { + "40787c3552d541a0a0c06adae3633bd6": 505, + "eae60a5820614657a3c6e0e4a8e5d9d9": 507, + "8650bb2b9d7541c3ad2ae8e84d155675": 505, + "a42b4977c3b7495d9483124bd7015856": 506 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.002, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 4 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 25 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 2 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "4", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "3", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "5", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "4", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.703, + "data": { + "postgres_activity": [ + { + "state": "idle in transaction", + "wait_event_type": null, + "count": 2 + }, + { + "state": "active", + "wait_event_type": "LWLock", + "count": 2 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 3 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 2 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 22 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "5", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "5", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "3", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "3", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 7.525, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 32 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-10", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 62242816, + "used_cpu_cores": 0.204, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 61140992, + "used_cpu_cores": 0.202, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 65261568, + "used_cpu_cores": 0.196, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-9", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 64307200, + "used_cpu_cores": 0.199, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 248320000, + "used_cpu_cores": 0.427, + "throttled_seconds": 28.988, + "throttled_periods": 83 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 29224960, + "used_cpu_cores": 0.08, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 17883136, + "used_cpu_cores": 0.038, + "throttled_seconds": 0.194, + "throttled_periods": 5 + } + ], + "run": 50, + "label": "growing-4", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 32 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.0482, + "requested_seconds": 8, + "concurrency": 16, + "successful_requests": 2009, + "failed_requests": 0, + "successful_rps": 249.622, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 82.109, + "p95": 111.575, + "p99": 194.732 + }, + "all_attempt_latency_ms": { + "p50": 82.109, + "p95": 111.575, + "p99": 194.732 + }, + "status_counts": { + "201": 1005, + "200": 1004 + }, + "instance_counts": { + "eae60a5820614657a3c6e0e4a8e5d9d9": 502, + "8650bb2b9d7541c3ad2ae8e84d155675": 503, + "40787c3552d541a0a0c06adae3633bd6": 502, + "a42b4977c3b7495d9483124bd7015856": 502 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.001, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 2 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 2 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 24 + }, + { + "state": "active", + "wait_event_type": null, + "count": 2 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "3", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "5", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "3", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "5", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.885, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 6 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 1 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 2 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 18 + }, + { + "state": "active", + "wait_event_type": null, + "count": 5 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "3", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "3", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "5", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "5", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-10", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 57733120, + "used_cpu_cores": 0.2, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 56741888, + "used_cpu_cores": 0.203, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 62746624, + "used_cpu_cores": 0.206, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-9", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 64221184, + "used_cpu_cores": 0.213, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 247980032, + "used_cpu_cores": 0.43, + "throttled_seconds": 30.415, + "throttled_periods": 82 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 29585408, + "used_cpu_cores": 0.081, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 18202624, + "used_cpu_cores": 0.04, + "throttled_seconds": 0.074, + "throttled_periods": 3 + } + ], + "run": 51, + "label": "growing-4", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 32 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.8609, + "requested_seconds": 8, + "concurrency": 64, + "successful_requests": 808, + "failed_requests": 21, + "successful_rps": 91.187, + "error_ratio": 0.025332, + "successful_latency_ms": { + "p50": 400.469, + "p95": 1715.727, + "p99": 2630.65 + }, + "all_attempt_latency_ms": { + "p50": 402.245, + "p95": 2196.693, + "p99": 3008.815 + }, + "status_counts": { + "200": 403, + "201": 405, + "0": 21 + }, + "instance_counts": { + "40787c3552d541a0a0c06adae3633bd6": 204, + "a42b4977c3b7495d9483124bd7015856": 199, + "eae60a5820614657a3c6e0e4a8e5d9d9": 203, + "8650bb2b9d7541c3ad2ae8e84d155675": 202 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.003, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 20 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 3 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 7 + }, + { + "state": "idle in transaction", + "wait_event_type": null, + "count": 4 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 5 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 40 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "17", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "16", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "17", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "14", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 7.8, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 80 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-10", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 64749568, + "used_cpu_cores": 0.17, + "throttled_seconds": 0.038, + "throttled_periods": 1 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 64032768, + "used_cpu_cores": 0.18, + "throttled_seconds": 0.216, + "throttled_periods": 2 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 65650688, + "used_cpu_cores": 0.168, + "throttled_seconds": 0.034, + "throttled_periods": 2 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-9", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 67551232, + "used_cpu_cores": 0.163, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 355500032, + "used_cpu_cores": 0.454, + "throttled_seconds": 52.875, + "throttled_periods": 91 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 28774400, + "used_cpu_cores": 0.066, + "throttled_seconds": 0.045, + "throttled_periods": 1 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 15405056, + "used_cpu_cores": 0.038, + "throttled_seconds": 0.115, + "throttled_periods": 3 + } + ], + "run": 52, + "label": "growing-4", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 80 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.1973, + "requested_seconds": 8, + "concurrency": 64, + "successful_requests": 1496, + "failed_requests": 0, + "successful_rps": 182.5, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 288.474, + "p95": 894.66, + "p99": 1605.506 + }, + "all_attempt_latency_ms": { + "p50": 288.474, + "p95": 894.66, + "p99": 1605.506 + }, + "status_counts": { + "201": 754, + "200": 742 + }, + "instance_counts": { + "8650bb2b9d7541c3ad2ae8e84d155675": 385, + "40787c3552d541a0a0c06adae3633bd6": 337, + "eae60a5820614657a3c6e0e4a8e5d9d9": 387, + "a42b4977c3b7495d9483124bd7015856": 387 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.005, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 11 + }, + { + "state": "active", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 2 + }, + { + "state": "active", + "wait_event_type": null, + "count": 6 + }, + { + "state": "idle in transaction", + "wait_event_type": null, + "count": 1 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 5 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 54 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "17", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "15", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "17", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "15", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 6.067, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 5 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 5 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 9 + }, + { + "state": "idle in transaction", + "wait_event_type": null, + "count": 1 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 4 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 55 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "10", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "8", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "10", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "10", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-10", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 65036288, + "used_cpu_cores": 0.157, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 62382080, + "used_cpu_cores": 0.174, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 67170304, + "used_cpu_cores": 0.18, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-9", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 65531904, + "used_cpu_cores": 0.185, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 361177088, + "used_cpu_cores": 0.437, + "throttled_seconds": 49.589, + "throttled_periods": 82 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 29908992, + "used_cpu_cores": 0.079, + "throttled_seconds": 0.177, + "throttled_periods": 2 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 17772544, + "used_cpu_cores": 0.036, + "throttled_seconds": 0.252, + "throttled_periods": 6 + } + ], + "run": 53, + "label": "growing-4", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 80 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.3467, + "requested_seconds": 8, + "concurrency": 64, + "successful_requests": 1916, + "failed_requests": 0, + "successful_rps": 229.551, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 215.756, + "p95": 592.614, + "p99": 848.003 + }, + "all_attempt_latency_ms": { + "p50": 215.756, + "p95": 592.614, + "p99": 848.003 + }, + "status_counts": { + "200": 946, + "201": 970 + }, + "instance_counts": { + "eae60a5820614657a3c6e0e4a8e5d9d9": 478, + "8650bb2b9d7541c3ad2ae8e84d155675": 480, + "40787c3552d541a0a0c06adae3633bd6": 479, + "a42b4977c3b7495d9483124bd7015856": 479 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.005, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 30 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 1 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 3 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 42 + }, + { + "state": "active", + "wait_event_type": null, + "count": 3 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "16", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "17", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "14", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "17", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 5.818, + "data": { + "postgres_activity": [ + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 43 + }, + { + "state": "idle in transaction", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "idle in transaction", + "wait_event_type": "LWLock", + "count": 5 + }, + { + "state": "active", + "wait_event_type": "LWLock", + "count": 8 + }, + { + "state": "active", + "wait_event_type": "Client", + "count": 13 + }, + { + "state": "idle", + "wait_event_type": "LWLock", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 4 + }, + { + "state": "active", + "wait_event_type": null, + "count": 4 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "16", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "15", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "18", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "15", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-10", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 67686400, + "used_cpu_cores": 0.182, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 64471040, + "used_cpu_cores": 0.182, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 65552384, + "used_cpu_cores": 0.181, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-9", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 65503232, + "used_cpu_cores": 0.182, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 362528768, + "used_cpu_cores": 0.449, + "throttled_seconds": 50.64, + "throttled_periods": 85 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 29720576, + "used_cpu_cores": 0.07, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 16162816, + "used_cpu_cores": 0.029, + "throttled_seconds": 0.0, + "throttled_periods": 0 + } + ], + "run": 54, + "label": "growing-4", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 80 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 9.7576, + "requested_seconds": 8, + "concurrency": 16, + "successful_requests": 1407, + "failed_requests": 0, + "successful_rps": 144.195, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 91.214, + "p95": 205.051, + "p99": 496.489 + }, + "all_attempt_latency_ms": { + "p50": 91.214, + "p95": 205.051, + "p99": 496.489 + }, + "status_counts": { + "200": 701, + "201": 706 + }, + "instance_counts": { + "3a4bfde5ff99441094ada661c6f57def": 703, + "328468e70991424ea9dcb39204ff86f7": 704 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.005, + "data": { + "postgres_activity": [ + { + "state": "idle in transaction", + "wait_event_type": "LWLock", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 1 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 18 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "10", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "6", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 5.018, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 20 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "8", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "8", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 8.292, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 22 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 55795712, + "used_cpu_cores": 0.415, + "throttled_seconds": 0.623, + "throttled_periods": 7 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 49016832, + "used_cpu_cores": 0.4, + "throttled_seconds": 0.568, + "throttled_periods": 7 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 232001536, + "used_cpu_cores": 0.417, + "throttled_seconds": 34.794, + "throttled_periods": 89 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 27197440, + "used_cpu_cores": 0.093, + "throttled_seconds": 0.77, + "throttled_periods": 6 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 11370496, + "used_cpu_cores": 0.043, + "throttled_seconds": 0.256, + "throttled_periods": 7 + } + ], + "run": 55, + "label": "separate", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 22 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.6835, + "requested_seconds": 8, + "concurrency": 16, + "successful_requests": 1559, + "failed_requests": 0, + "successful_rps": 179.536, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 84.73, + "p95": 195.014, + "p99": 810.332 + }, + "all_attempt_latency_ms": { + "p50": 84.73, + "p95": 195.014, + "p99": 810.332 + }, + "status_counts": { + "200": 776, + "201": 783 + }, + "instance_counts": { + "6f2e1d1b30fc4a1882db87c716554a0d": 780, + "c35ba912d6ff48139d3cd36cd6148cd7": 779 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.0, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 1 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 2 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 14 + }, + { + "state": "active", + "wait_event_type": null, + "count": 2 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "8", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "8", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.732, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 19 + }, + { + "state": "active", + "wait_event_type": null, + "count": 2 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "6", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "10", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 7.699, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 22 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 55197696, + "used_cpu_cores": 0.384, + "throttled_seconds": 0.077, + "throttled_periods": 3 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 56975360, + "used_cpu_cores": 0.399, + "throttled_seconds": 0.188, + "throttled_periods": 4 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 233967616, + "used_cpu_cores": 0.435, + "throttled_seconds": 35.042, + "throttled_periods": 84 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 26853376, + "used_cpu_cores": 0.079, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 18034688, + "used_cpu_cores": 0.059, + "throttled_seconds": 2.149, + "throttled_periods": 13 + } + ], + "run": 56, + "label": "batched", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 22 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.47, + "requested_seconds": 8, + "concurrency": 16, + "successful_requests": 1856, + "failed_requests": 0, + "successful_rps": 219.126, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 79.422, + "p95": 111.847, + "p99": 296.486 + }, + "all_attempt_latency_ms": { + "p50": 79.422, + "p95": 111.847, + "p99": 296.486 + }, + "status_counts": { + "200": 927, + "201": 929 + }, + "instance_counts": { + "7b7612b2b73e4bdf9047593bcda90858": 927, + "fd62c650386445c3948899d83ccbc6fb": 929 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.006, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 17 + }, + { + "state": "active", + "wait_event_type": null, + "count": 2 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "8", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "8", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.967, + "data": { + "postgres_activity": [ + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 4 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 17 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "8", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "7", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 7.638, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 22 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 55984128, + "used_cpu_cores": 0.399, + "throttled_seconds": 0.015, + "throttled_periods": 1 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 55111680, + "used_cpu_cores": 0.395, + "throttled_seconds": 0.026, + "throttled_periods": 1 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 236662784, + "used_cpu_cores": 0.44, + "throttled_seconds": 34.308, + "throttled_periods": 82 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 28999680, + "used_cpu_cores": 0.062, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 17514496, + "used_cpu_cores": 0.031, + "throttled_seconds": 0.039, + "throttled_periods": 1 + } + ], + "run": 57, + "label": "batched", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 22 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.2304, + "requested_seconds": 8, + "concurrency": 16, + "successful_requests": 2012, + "failed_requests": 0, + "successful_rps": 244.459, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 82.521, + "p95": 108.102, + "p99": 276.746 + }, + "all_attempt_latency_ms": { + "p50": 82.521, + "p95": 108.102, + "p99": 276.746 + }, + "status_counts": { + "201": 1005, + "200": 1007 + }, + "instance_counts": { + "c3d31f6f5ada4116a3d2a7009f2aeb89": 1006, + "9e009f728e7946b8846ffb59c8117d5c": 1006 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.005, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 2 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 1 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 11 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 4 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "7", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "9", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.772, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 4 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 15 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "9", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "7", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 7.48, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "active", + "wait_event_type": "LWLock", + "count": 2 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 2 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 14 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 55435264, + "used_cpu_cores": 0.39, + "throttled_seconds": 0.003, + "throttled_periods": 1 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 55214080, + "used_cpu_cores": 0.415, + "throttled_seconds": 0.003, + "throttled_periods": 1 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 236830720, + "used_cpu_cores": 0.435, + "throttled_seconds": 29.912, + "throttled_periods": 79 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 27463680, + "used_cpu_cores": 0.083, + "throttled_seconds": 0.869, + "throttled_periods": 3 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 11022336, + "used_cpu_cores": 0.03, + "throttled_seconds": 0.071, + "throttled_periods": 1 + } + ], + "run": 58, + "label": "separate", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 22 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 10.4565, + "requested_seconds": 8, + "concurrency": 16, + "successful_requests": 950, + "failed_requests": 984, + "successful_rps": 90.853, + "error_ratio": 0.50879, + "successful_latency_ms": { + "p50": 78.719, + "p95": 109.924, + "p99": 191.888 + }, + "all_attempt_latency_ms": { + "p50": 14.784, + "p95": 110.761, + "p99": 292.377 + }, + "status_counts": { + "200": 478, + "201": 472, + "0": 16, + "503": 968 + }, + "instance_counts": { + "788c3772c3244e56b6553038797c17cf": 474, + "d1c6ed2002394674bce7b0e2c369b1f7": 476 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.002, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 2 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 3 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 15 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "4", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "6", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.695, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 29 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "DOWN 1/2", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api2", + "status": "DOWN 1/2", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 52342784, + "used_cpu_cores": 0.386, + "throttled_seconds": 8.428, + "throttled_periods": 32 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 56705024, + "used_cpu_cores": 0.352, + "throttled_seconds": 3.808, + "throttled_periods": 22 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 251154432, + "used_cpu_cores": 0.397, + "throttled_seconds": 67.262, + "throttled_periods": 138 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 27344896, + "used_cpu_cores": 0.11, + "throttled_seconds": 3.161, + "throttled_periods": 27 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 16277504, + "used_cpu_cores": 0.043, + "throttled_seconds": 0.65, + "throttled_periods": 10 + } + ], + "run": 59, + "label": "separate", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 29 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.3449, + "requested_seconds": 8, + "concurrency": 16, + "successful_requests": 2270, + "failed_requests": 0, + "successful_rps": 272.021, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 70.816, + "p95": 112.969, + "p99": 192.951 + }, + "all_attempt_latency_ms": { + "p50": 70.816, + "p95": 112.969, + "p99": 192.951 + }, + "status_counts": { + "200": 1135, + "201": 1135 + }, + "instance_counts": { + "39e40d4e32124344a6f703e6960cad86": 1136, + "810e1196b8804dfeaceb8bcc65dde506": 1134 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.005, + "data": { + "postgres_activity": [ + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 16 + }, + { + "state": "active", + "wait_event_type": null, + "count": 3 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "8", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "8", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.664, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": null, + "count": 2 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 19 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "6", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "9", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 7.495, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 24 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 53071872, + "used_cpu_cores": 0.413, + "throttled_seconds": 0.091, + "throttled_periods": 2 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 54534144, + "used_cpu_cores": 0.414, + "throttled_seconds": 0.123, + "throttled_periods": 3 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 246329344, + "used_cpu_cores": 0.445, + "throttled_seconds": 28.878, + "throttled_periods": 82 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 29184000, + "used_cpu_cores": 0.069, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 11354112, + "used_cpu_cores": 0.03, + "throttled_seconds": 0.003, + "throttled_periods": 1 + } + ], + "run": 60, + "label": "batched", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 24 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.2421, + "requested_seconds": 8, + "concurrency": 64, + "successful_requests": 1796, + "failed_requests": 0, + "successful_rps": 217.905, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 217.157, + "p95": 611.418, + "p99": 1425.105 + }, + "all_attempt_latency_ms": { + "p50": 217.157, + "p95": 611.418, + "p99": 1425.105 + }, + "status_counts": { + "200": 888, + "201": 908 + }, + "instance_counts": { + "b5aa8f47af934f70ab5f8d3aaa2c24fd": 448, + "538483f110ef45e489c10f593def9383": 450, + "3e390aa28a804a2aa742cbf7a8d7d7dd": 449, + "f02cd6f8116e490eab45e369b2c4849b": 449 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.011, + "data": { + "postgres_activity": [ + { + "state": "idle in transaction", + "wait_event_type": "LWLock", + "count": 1 + }, + { + "state": "active", + "wait_event_type": "Client", + "count": 4 + }, + { + "state": "active", + "wait_event_type": "LWLock", + "count": 25 + }, + { + "state": "idle", + "wait_event_type": "LWLock", + "count": 2 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 5 + }, + { + "state": "idle in transaction", + "wait_event_type": null, + "count": 1 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 5 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 35 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "15", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "13", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "19", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "17", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 5.98, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 10 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 10 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 7 + }, + { + "state": "idle in transaction", + "wait_event_type": null, + "count": 1 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 4 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 47 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-10", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 53850112, + "used_cpu_cores": 0.26, + "throttled_seconds": 0.095, + "throttled_periods": 2 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 50425856, + "used_cpu_cores": 0.252, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 50606080, + "used_cpu_cores": 0.235, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-9", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 50176000, + "used_cpu_cores": 0.244, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 373432320, + "used_cpu_cores": 0.44, + "throttled_seconds": 46.786, + "throttled_periods": 83 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 29757440, + "used_cpu_cores": 0.07, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 17477632, + "used_cpu_cores": 0.029, + "throttled_seconds": 0.0, + "throttled_periods": 0 + } + ], + "run": 61, + "label": "postgres-half_cpu", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 80 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.471, + "requested_seconds": 8, + "concurrency": 64, + "successful_requests": 2653, + "failed_requests": 0, + "successful_rps": 313.186, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 114.798, + "p95": 700.798, + "p99": 1117.064 + }, + "all_attempt_latency_ms": { + "p50": 114.798, + "p95": 700.798, + "p99": 1117.064 + }, + "status_counts": { + "200": 1327, + "201": 1326 + }, + "instance_counts": { + "d947308f3c6c46f195679db4812873b5": 664, + "50199089958a4e22bce56586f397b569": 664, + "c1846db8dbd644d5b5f9cdec17cb2230": 662, + "a8d677a465f243dda2203c359fee3eb8": 663 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.003, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 3 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 2 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 73 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "11", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "17", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "23", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "14", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 7.889, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 80 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-10", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 51523584, + "used_cpu_cores": 0.448, + "throttled_seconds": 0.451, + "throttled_periods": 5 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 53673984, + "used_cpu_cores": 0.405, + "throttled_seconds": 0.105, + "throttled_periods": 4 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 55533568, + "used_cpu_cores": 0.507, + "throttled_seconds": 0.066, + "throttled_periods": 6 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-9", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 51339264, + "used_cpu_cores": 0.472, + "throttled_seconds": 1.041, + "throttled_periods": 13 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 1.0, + "memory_limit": 536870912, + "memory_bytes": 379068416, + "used_cpu_cores": 0.826, + "throttled_seconds": 31.045, + "throttled_periods": 82 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 29306880, + "used_cpu_cores": 0.138, + "throttled_seconds": 0.74, + "throttled_periods": 7 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 18280448, + "used_cpu_cores": 0.054, + "throttled_seconds": 0.812, + "throttled_periods": 7 + } + ], + "run": 62, + "label": "postgres-one_cpu", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 80 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.4243, + "requested_seconds": 8, + "concurrency": 64, + "successful_requests": 3332, + "failed_requests": 0, + "successful_rps": 395.521, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 125.037, + "p95": 333.666, + "p99": 561.684 + }, + "all_attempt_latency_ms": { + "p50": 125.037, + "p95": 333.666, + "p99": 561.684 + }, + "status_counts": { + "201": 1673, + "200": 1659 + }, + "instance_counts": { + "5c3bb71cf6374850b04a936a86aa2beb": 833, + "ed7c198f3d3f4286b453769a5298ce50": 833, + "f048f11d42dc41b6b1a34d7c8f167e03": 833, + "6bf7454d87a64930bd765618753a7ef4": 833 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.002, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 2 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 4 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 71 + }, + { + "state": "active", + "wait_event_type": null, + "count": 2 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "15", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "16", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "17", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "16", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 4.942, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 2 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 5 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 69 + }, + { + "state": "active", + "wait_event_type": null, + "count": 2 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "13", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "22", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "16", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "13", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 8.044, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 80 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-10", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 49795072, + "used_cpu_cores": 0.455, + "throttled_seconds": 0.019, + "throttled_periods": 3 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 56000512, + "used_cpu_cores": 0.455, + "throttled_seconds": 0.001, + "throttled_periods": 1 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 54792192, + "used_cpu_cores": 0.465, + "throttled_seconds": 0.04, + "throttled_periods": 3 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-9", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 50909184, + "used_cpu_cores": 0.452, + "throttled_seconds": 0.015, + "throttled_periods": 1 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 1.0, + "memory_limit": 536870912, + "memory_bytes": 378380288, + "used_cpu_cores": 0.853, + "throttled_seconds": 28.504, + "throttled_periods": 80 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 32260096, + "used_cpu_cores": 0.138, + "throttled_seconds": 0.066, + "throttled_periods": 3 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 18030592, + "used_cpu_cores": 0.048, + "throttled_seconds": 0.182, + "throttled_periods": 3 + } + ], + "run": 63, + "label": "postgres-one_cpu", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 80 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.1405, + "requested_seconds": 8, + "concurrency": 64, + "successful_requests": 1165, + "failed_requests": 40, + "successful_rps": 143.112, + "error_ratio": 0.033195, + "successful_latency_ms": { + "p50": 207.786, + "p95": 1622.857, + "p99": 2735.69 + }, + "all_attempt_latency_ms": { + "p50": 211.049, + "p95": 1999.682, + "p99": 3005.532 + }, + "status_counts": { + "200": 578, + "0": 24, + "201": 587, + "500": 16 + }, + "instance_counts": { + "7ab53639981c4cc4a69b0239beb2a38b": 282, + "e01e6b53bb634ac398ecf47d0095e3eb": 298, + "7371ce2836724ea0986c921dd3a8878d": 303, + "ec95115c4f1b4a29a080a0ef2fd5612f": 282 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.012, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 1 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 73 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "26", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "24", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "21", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "2", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 6.339, + "data": { + "postgres_activity": [ + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 4 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 46 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 2 + }, + { + "state": "idle in transaction", + "wait_event_type": null, + "count": 2 + }, + { + "state": "active", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "active", + "wait_event_type": "LWLock", + "count": 24 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "15", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "18", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "16", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "15", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-10", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 53301248, + "used_cpu_cores": 0.238, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 51331072, + "used_cpu_cores": 0.222, + "throttled_seconds": 0.008, + "throttled_periods": 1 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 53579776, + "used_cpu_cores": 0.23, + "throttled_seconds": 0.039, + "throttled_periods": 2 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-9", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 58388480, + "used_cpu_cores": 0.249, + "throttled_seconds": 0.079, + "throttled_periods": 2 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 382308352, + "used_cpu_cores": 0.407, + "throttled_seconds": 44.804, + "throttled_periods": 79 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 30121984, + "used_cpu_cores": 0.079, + "throttled_seconds": 0.418, + "throttled_periods": 4 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 11145216, + "used_cpu_cores": 0.096, + "throttled_seconds": 5.314, + "throttled_periods": 35 + } + ], + "run": 64, + "label": "postgres-half_cpu", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 80 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.1515, + "requested_seconds": 8, + "concurrency": 64, + "successful_requests": 2361, + "failed_requests": 0, + "successful_rps": 289.64, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 193.793, + "p95": 482.532, + "p99": 958.542 + }, + "all_attempt_latency_ms": { + "p50": 193.793, + "p95": 482.532, + "p99": 958.542 + }, + "status_counts": { + "200": 1179, + "201": 1182 + }, + "instance_counts": { + "7f46fd6a155a4597b957d5b801a770d4": 589, + "8148a40e1efe44faae9a3ca91ffa50da": 591, + "233e2bc986cc48b6b91083848bc4adc6": 590, + "5099d6c67867445fb88264ab87ab5df7": 591 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.001, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "Client", + "count": 3 + }, + { + "state": "active", + "wait_event_type": "LWLock", + "count": 19 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 2 + }, + { + "state": "idle in transaction", + "wait_event_type": null, + "count": 2 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 2 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 49 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "15", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "13", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "15", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "21", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 5.323, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 12 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 4 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 8 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 50 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 5 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "13", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "17", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "11", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "20", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-10", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 52572160, + "used_cpu_cores": 0.26, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 52850688, + "used_cpu_cores": 0.266, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 51953664, + "used_cpu_cores": 0.263, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-9", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 52752384, + "used_cpu_cores": 0.271, + "throttled_seconds": 0.023, + "throttled_periods": 1 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 0.5, + "memory_limit": 536870912, + "memory_bytes": 383909888, + "used_cpu_cores": 0.444, + "throttled_seconds": 45.5, + "throttled_periods": 82 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 29261824, + "used_cpu_cores": 0.079, + "throttled_seconds": 0.0, + "throttled_periods": 0 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 17465344, + "used_cpu_cores": 0.032, + "throttled_seconds": 0.0, + "throttled_periods": 0 + } + ], + "run": 65, + "label": "postgres-half_cpu", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 80 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + }, + { + "duration_seconds": 8.3605, + "requested_seconds": 8, + "concurrency": 64, + "successful_requests": 4419, + "failed_requests": 0, + "successful_rps": 528.555, + "error_ratio": 0.0, + "successful_latency_ms": { + "p50": 102.653, + "p95": 249.648, + "p99": 345.152 + }, + "all_attempt_latency_ms": { + "p50": 102.653, + "p95": 249.648, + "p99": 345.152 + }, + "status_counts": { + "200": 2200, + "201": 2219 + }, + "instance_counts": { + "76a4cc1099714c61a9e62156e822d184": 1103, + "73fe431d7a7a4a7ab305e673a28751d6": 1106, + "e98926c3143645958de4f6bb032835d1": 1104, + "fbf258484eee4c3c9e993f33542914e8": 1106 + }, + "actions": [], + "observations": [ + { + "offset_seconds": 2.009, + "data": { + "postgres_activity": [ + { + "state": "idle in transaction", + "wait_event_type": "LWLock", + "count": 1 + }, + { + "state": "active", + "wait_event_type": "Client", + "count": 1 + }, + { + "state": "active", + "wait_event_type": "LWLock", + "count": 15 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 2 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 4 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 13 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 42 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "13", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "8", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "23", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "12", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 5.064, + "data": { + "postgres_activity": [ + { + "state": "active", + "wait_event_type": "LWLock", + "count": 9 + }, + { + "state": "idle", + "wait_event_type": null, + "count": 1 + }, + { + "state": "active", + "wait_event_type": "IO", + "count": 1 + }, + { + "state": "active", + "wait_event_type": null, + "count": 5 + }, + { + "state": "idle in transaction", + "wait_event_type": null, + "count": 1 + }, + { + "state": "idle in transaction", + "wait_event_type": "Client", + "count": 5 + }, + { + "state": "idle", + "wait_event_type": "Client", + "count": 58 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "12", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "16", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "18", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "18", + "qmax": "0" + } + ] + } + }, + { + "offset_seconds": 7.93, + "data": { + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 80 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "scur": "0", + "qmax": "0" + } + ] + } + } + ], + "resources": [ + { + "service": "api", + "name": "mtusi2026lab3-api-10", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 55717888, + "used_cpu_cores": 0.468, + "throttled_seconds": 0.339, + "throttled_periods": 4 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-7", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 53141504, + "used_cpu_cores": 0.448, + "throttled_seconds": 0.003, + "throttled_periods": 1 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-8", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 57221120, + "used_cpu_cores": 0.496, + "throttled_seconds": 0.03, + "throttled_periods": 4 + }, + { + "service": "api", + "name": "mtusi2026lab3-api-9", + "cpu_limit": 1.0, + "memory_limit": 402653184, + "memory_bytes": 53125120, + "used_cpu_cores": 0.496, + "throttled_seconds": 0.121, + "throttled_periods": 4 + }, + { + "service": "postgres", + "name": "mtusi2026lab3-postgres-1", + "cpu_limit": 1.0, + "memory_limit": 536870912, + "memory_bytes": 393195520, + "used_cpu_cores": 0.864, + "throttled_seconds": 25.584, + "throttled_periods": 80 + }, + { + "service": "lb", + "name": "mtusi2026lab3-lb-1", + "cpu_limit": 0.5, + "memory_limit": 100663296, + "memory_bytes": 29757440, + "used_cpu_cores": 0.136, + "throttled_seconds": 0.062, + "throttled_periods": 1 + }, + { + "service": "redis", + "name": "mtusi2026lab3-redis-1", + "cpu_limit": 0.25, + "memory_limit": 100663296, + "memory_bytes": 17551360, + "used_cpu_cores": 0.044, + "throttled_seconds": 0.0, + "throttled_periods": 0 + } + ], + "run": 66, + "label": "postgres-one_cpu", + "postgres_activity": [ + { + "state": "idle", + "wait_event_type": "Client", + "count": 80 + } + ], + "lb_queues": [ + { + "svname": "api1", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api2", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api3", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + }, + { + "svname": "api4", + "status": "UP", + "qcur": "0", + "qmax": "0", + "qtime_max": "0" + } + ] + } + ], + "source_sha256": "67fa27c5736b688907a59abd8fe6b49d114a14709bc8ffd80670909438eece85", + "batching_comparison": { + "separate": { + "rps": 144.195, + "p95_ms": 109.924, + "error_ratio": 0.0, + "failed_requests_total": 984, + "error_ratio_max": 0.50879, + "rps_min": 90.853, + "rps_max": 244.459 + }, + "batched": { + "rps": 219.126, + "p95_ms": 112.969, + "error_ratio": 0.0, + "failed_requests_total": 0, + "error_ratio_max": 0.0, + "rps_min": 179.536, + "rps_max": 272.021 + } + }, + "database_capacity_comparison": { + "half_cpu": { + "rps": 217.905, + "p95_ms": 611.418, + "error_ratio": 0.0, + "failed_requests_total": 40, + "error_ratio_max": 0.033195, + "rps_min": 143.112, + "rps_max": 289.64 + }, + "one_cpu": { + "rps": 395.521, + "p95_ms": 333.666, + "error_ratio": 0.0, + "failed_requests_total": 0, + "error_ratio_max": 0.0, + "rps_min": 313.186, + "rps_max": 528.555 + } + }, + "confirmed_improvements": [ + "SQL command batching increased median successful RPS", + "Additional PostgreSQL CPU increased median successful RPS" + ] +} diff --git a/evidence/scaling.png b/evidence/scaling.png new file mode 100644 index 00000000..3271aaa7 Binary files /dev/null and b/evidence/scaling.png differ diff --git a/evidence/scaling.svg b/evidence/scaling.svg new file mode 100644 index 00000000..cd15166a --- /dev/null +++ b/evidence/scaling.svg @@ -0,0 +1,2474 @@ + + + + + + + + 2026-11-02T04:28:22.115354 + image/svg+xml + + + Matplotlib v3.11.2, https://matplotlib.org/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/infra/haproxy.cfg b/infra/haproxy.cfg new file mode 100644 index 00000000..752b0535 --- /dev/null +++ b/infra/haproxy.cfg @@ -0,0 +1,40 @@ +global + maxconn 2000 + stats socket ipv4@127.0.0.1:9999 level admin + hard-stop-after 8s + +defaults + mode http + timeout connect 500ms + timeout check 500ms + timeout client 15s + timeout server 12s + timeout http-request 5s + timeout http-keep-alive 5s + timeout queue 2s + retries 1 + +resolvers docker + nameserver dns 127.0.0.11:53 + accepted_payload_size 8192 + resolve_retries 2 + timeout resolve 500ms + timeout retry 500ms + hold valid 1s + hold nx 1s + hold other 1s + hold refused 1s + hold timeout 1s + hold obsolete 0s + +frontend public + bind :8080 + default_backend messenger + +backend messenger + balance roundrobin + option httpchk + http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host localhost + http-check expect status 200 + default-server check inter 500ms fastinter 250ms downinter 500ms fall 2 rise 2 + server-template api 1-8 api:8080 resolvers docker resolve-prefer ipv4 init-addr none diff --git a/requirements-research.txt b/requirements-research.txt new file mode 100644 index 00000000..71363ac8 --- /dev/null +++ b/requirements-research.txt @@ -0,0 +1 @@ +matplotlib==3.11.2 diff --git a/scripts/compose.sh b/scripts/compose.sh new file mode 100755 index 00000000..9bf7a105 --- /dev/null +++ b/scripts/compose.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +root="$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)" +exec docker compose --project-name mtusi2026lab3 --project-directory "$root" "$@" diff --git a/scripts/demo-failover.py b/scripts/demo-failover.py new file mode 100644 index 00000000..5a2fd594 --- /dev/null +++ b/scripts/demo-failover.py @@ -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() diff --git a/scripts/init-secrets.sh b/scripts/init-secrets.sh new file mode 100755 index 00000000..0c9b61af --- /dev/null +++ b/scripts/init-secrets.sh @@ -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.' diff --git a/scripts/plot_results.py b/scripts/plot_results.py new file mode 100644 index 00000000..bf0a7792 --- /dev/null +++ b/scripts/plot_results.py @@ -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") diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100755 index 00000000..e2baef96 --- /dev/null +++ b/scripts/restart.sh @@ -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 diff --git a/scripts/rolling_update.py b/scripts/rolling_update.py new file mode 100644 index 00000000..8fa62a5c --- /dev/null +++ b/scripts/rolling_update.py @@ -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)) diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh new file mode 100755 index 00000000..2a7bee58 --- /dev/null +++ b/scripts/stop-one.sh @@ -0,0 +1,13 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +test -n "${TARGET_INSTANCE_ID:-}" || { echo "TARGET_INSTANCE_ID is required" >&2; exit 1; } +for id in $(./scripts/compose.sh ps -q api); do + instance="$(docker exec "$id" curl -fsS -D - -o /dev/null http://127.0.0.1:8080/health/live | tr -d '\r' | awk 'tolower($1) == "x-instance-id:" { print $2 }')" + if [ "$instance" = "$TARGET_INSTANCE_ID" ]; then + docker stop --time 8 "$id" >/dev/null + exit 0 + fi +done +echo "Requested API instance was not found" >&2 +exit 1 diff --git a/scripts/verify.sh b/scripts/verify.sh new file mode 100755 index 00000000..fc50522b --- /dev/null +++ b/scripts/verify.sh @@ -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 diff --git a/src/Messenger.Api/Contracts/ChatCursor.cs b/src/Messenger.Api/Contracts/ChatCursor.cs new file mode 100644 index 00000000..f8a7fb06 --- /dev/null +++ b/src/Messenger.Api/Contracts/ChatCursor.cs @@ -0,0 +1,7 @@ +namespace Messenger.Api.Contracts; + +public sealed record ChatCursor( + string Scope, + string CreatedAt, + Guid Id +); diff --git a/src/Messenger.Api/Contracts/ChatDto.cs b/src/Messenger.Api/Contracts/ChatDto.cs new file mode 100644 index 00000000..67a757a1 --- /dev/null +++ b/src/Messenger.Api/Contracts/ChatDto.cs @@ -0,0 +1,3 @@ +namespace Messenger.Api.Contracts; + +public sealed record ChatDto(Guid Id, string Title, List MemberIds, string CreatedAt); diff --git a/src/Messenger.Api/Contracts/ChatPreviewDto.cs b/src/Messenger.Api/Contracts/ChatPreviewDto.cs new file mode 100644 index 00000000..4dded210 --- /dev/null +++ b/src/Messenger.Api/Contracts/ChatPreviewDto.cs @@ -0,0 +1,4 @@ +namespace Messenger.Api.Contracts; + +public sealed record ChatPreviewDto( + Guid Id, string Title, List MemberIds, string CreatedAt, MessageDto? LastMessage); diff --git a/src/Messenger.Api/Contracts/CreateChatRequest.cs b/src/Messenger.Api/Contracts/CreateChatRequest.cs new file mode 100644 index 00000000..cd55763b --- /dev/null +++ b/src/Messenger.Api/Contracts/CreateChatRequest.cs @@ -0,0 +1,6 @@ +namespace Messenger.Api.Contracts; + +public sealed record CreateChatRequest( + string? Title, + List? MemberIds +); diff --git a/src/Messenger.Api/Contracts/CreateMessageRequest.cs b/src/Messenger.Api/Contracts/CreateMessageRequest.cs new file mode 100644 index 00000000..2d7136a8 --- /dev/null +++ b/src/Messenger.Api/Contracts/CreateMessageRequest.cs @@ -0,0 +1,8 @@ +using System.Text.Json; + +namespace Messenger.Api.Contracts; + +public sealed record CreateMessageRequest( + string? Text, + JsonElement AttachmentIds = default +); diff --git a/src/Messenger.Api/Contracts/CreateUserRequest.cs b/src/Messenger.Api/Contracts/CreateUserRequest.cs new file mode 100644 index 00000000..cd60371d --- /dev/null +++ b/src/Messenger.Api/Contracts/CreateUserRequest.cs @@ -0,0 +1,7 @@ +namespace Messenger.Api.Contracts; + +public sealed record CreateUserRequest( + string? Username, + string? DisplayName, + string? Password +); diff --git a/src/Messenger.Api/Contracts/MessageDto.cs b/src/Messenger.Api/Contracts/MessageDto.cs new file mode 100644 index 00000000..5c7006f3 --- /dev/null +++ b/src/Messenger.Api/Contracts/MessageDto.cs @@ -0,0 +1,3 @@ +namespace Messenger.Api.Contracts; + +public sealed record MessageDto(Guid Id, Guid ChatId, Guid SenderId, string Text, string CreatedAt); diff --git a/src/Messenger.Api/Contracts/SessionDto.cs b/src/Messenger.Api/Contracts/SessionDto.cs new file mode 100644 index 00000000..8e0177f0 --- /dev/null +++ b/src/Messenger.Api/Contracts/SessionDto.cs @@ -0,0 +1,3 @@ +namespace Messenger.Api.Contracts; + +public sealed record SessionDto(string Token, string TokenType, string ExpiresAt, UserDto User); diff --git a/src/Messenger.Api/Contracts/UserDto.cs b/src/Messenger.Api/Contracts/UserDto.cs new file mode 100644 index 00000000..d3ebc3c0 --- /dev/null +++ b/src/Messenger.Api/Contracts/UserDto.cs @@ -0,0 +1,3 @@ +namespace Messenger.Api.Contracts; + +public sealed record UserDto(Guid Id, string Username, string DisplayName, string CreatedAt); diff --git a/src/Messenger.Api/Data/AppDatabase.cs b/src/Messenger.Api/Data/AppDatabase.cs new file mode 100644 index 00000000..0d3e697e --- /dev/null +++ b/src/Messenger.Api/Data/AppDatabase.cs @@ -0,0 +1,206 @@ +using Messenger.Api.Data.Entities; +using System.Net.Sockets; +using Npgsql; + +namespace Messenger.Api.Data; + +public sealed partial class AppDatabase(NpgsqlDataSource dataSource, IConfiguration configuration) +{ + public async Task IsReadyAsync() + { + try + { + await using var command = dataSource.CreateCommand("SELECT 1"); + return (int)(await command.ExecuteScalarAsync())! == 1; + } + catch (Exception exception) when (exception is NpgsqlException or SocketException or TimeoutException) + { + return false; + } + } + + public async Task FindUserByUsernameAsync(string username) + { + await using var command = dataSource.CreateCommand( + "SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = @username"); + command.Parameters.AddWithValue("username", username); + await using var reader = await command.ExecuteReaderAsync(); + return await reader.ReadAsync() ? ReadUser(reader) : null; + } + + public async Task FindUserByIdAsync(Guid id) + { + await using var command = dataSource.CreateCommand( + "SELECT id, username, display_name, password_hash, created_at FROM users WHERE id = @id"); + command.Parameters.AddWithValue("id", id); + await using var reader = await command.ExecuteReaderAsync(); + return await reader.ReadAsync() ? ReadUser(reader) : null; + } + + public async Task> ListChatUsersAsync(Guid chatId) + { + await using var command = dataSource.CreateCommand(""" + SELECT u.id, u.username, u.display_name, u.password_hash, u.created_at + FROM users u JOIN chat_members m ON m.user_id = u.id + WHERE m.chat_id = @chat_id ORDER BY u.display_name, u.id + """); + command.Parameters.AddWithValue("chat_id", chatId); + await using var reader = await command.ExecuteReaderAsync(); + var result = new List(); + while (await reader.ReadAsync()) result.Add(ReadUser(reader)); + return result; + } + + public async Task CreateUserAsync(string username, string displayName, string passwordHash) + { + var user = new UserEntity(Guid.NewGuid(), username, displayName, passwordHash, UtcClock.Now()); + await using var command = dataSource.CreateCommand( + "INSERT INTO users(id, username, display_name, password_hash, created_at) VALUES (@id, @username, @display_name, @password_hash, @created_at)"); + command.Parameters.AddWithValue("id", user.Id); + command.Parameters.AddWithValue("username", user.Username); + command.Parameters.AddWithValue("display_name", user.DisplayName); + command.Parameters.AddWithValue("password_hash", user.PasswordHash); + command.Parameters.AddWithValue("created_at", user.CreatedAt); + await command.ExecuteNonQueryAsync(); + return user; + } + + public async Task CreateSessionAsync(byte[] tokenHash, Guid userId, DateTime expiresAt) + { + await using var command = dataSource.CreateCommand( + "INSERT INTO sessions(token_hash, user_id, expires_at, created_at) VALUES (@token_hash, @user_id, @expires_at, @created_at)"); + command.Parameters.AddWithValue("token_hash", tokenHash); + command.Parameters.AddWithValue("user_id", userId); + command.Parameters.AddWithValue("expires_at", expiresAt); + command.Parameters.AddWithValue("created_at", UtcClock.Now()); + await command.ExecuteNonQueryAsync(); + } + + public async Task FindActiveSessionAsync(byte[] tokenHash) + { + await using var command = dataSource.CreateCommand(""" + SELECT user_id, expires_at FROM sessions + WHERE token_hash = @token_hash AND revoked_at IS NULL AND expires_at > now() + """); + command.Parameters.AddWithValue("token_hash", tokenHash); + await using var reader = await command.ExecuteReaderAsync(); + return await reader.ReadAsync() ? new SessionEntity(reader.GetGuid(0), reader.GetDateTime(1)) : null; + } + + public async Task RevokeSessionAsync(byte[] tokenHash) + { + await using var command = dataSource.CreateCommand(""" + UPDATE sessions SET revoked_at = now() + WHERE token_hash = @token_hash AND revoked_at IS NULL AND expires_at > now() + """); + command.Parameters.AddWithValue("token_hash", tokenHash); + return await command.ExecuteNonQueryAsync() == 1; + } + + public async Task CreateChatAsync(string title, List memberIds) + { + await using var connection = await dataSource.OpenConnectionAsync(); + await using var transaction = await connection.BeginTransactionAsync(); + + await using (var membersCommand = new NpgsqlCommand( + "SELECT count(*) FROM users WHERE id = ANY(@member_ids)", connection, transaction)) + { + membersCommand.Parameters.AddWithValue("member_ids", memberIds.ToArray()); + if ((long)(await membersCommand.ExecuteScalarAsync())! != memberIds.Count) + { + await transaction.RollbackAsync(); + return null; + } + } + + var chat = new ChatEntity(Guid.NewGuid(), title, memberIds, UtcClock.Now()); + await using (var chatCommand = new NpgsqlCommand( + "INSERT INTO chats(id, title, created_at) VALUES (@id, @title, @created_at)", connection, transaction)) + { + chatCommand.Parameters.AddWithValue("id", chat.Id); + chatCommand.Parameters.AddWithValue("title", chat.Title); + chatCommand.Parameters.AddWithValue("created_at", chat.CreatedAt); + await chatCommand.ExecuteNonQueryAsync(); + } + + await using (var membershipCommand = new NpgsqlCommand( + "INSERT INTO chat_members(chat_id, user_id) SELECT @chat_id, unnest(CAST(@member_ids AS uuid[]))", connection, transaction)) + { + membershipCommand.Parameters.AddWithValue("chat_id", chat.Id); + membershipCommand.Parameters.AddWithValue("member_ids", memberIds.ToArray()); + await membershipCommand.ExecuteNonQueryAsync(); + } + + await transaction.CommitAsync(); + return chat; + } + + public async Task FindChatForMemberAsync(Guid chatId, Guid userId) + { + await using var command = dataSource.CreateCommand(""" + SELECT c.id, c.title, c.created_at, + ARRAY(SELECT m.user_id FROM chat_members m WHERE m.chat_id = c.id ORDER BY m.user_id) + FROM chats c + WHERE c.id = @chat_id AND EXISTS ( + SELECT 1 FROM chat_members m WHERE m.chat_id = c.id AND m.user_id = @user_id) + """); + command.Parameters.AddWithValue("chat_id", chatId); + command.Parameters.AddWithValue("user_id", userId); + await using var reader = await command.ExecuteReaderAsync(); + return await reader.ReadAsync() ? ReadChat(reader) : null; + } + + public async Task> ListChatsAsync(Guid userId, DateTime? cursorTime, Guid? cursorId, int count) + { + var sql = """ + SELECT c.id, c.title, c.created_at, + ARRAY(SELECT m2.user_id FROM chat_members m2 WHERE m2.chat_id = c.id ORDER BY m2.user_id) + FROM chats c JOIN chat_members m ON m.chat_id = c.id + WHERE m.user_id = @user_id + """; + if (cursorTime is not null) + sql += " AND (c.created_at, c.id) > (@cursor_time, @cursor_id)"; + sql += " ORDER BY c.created_at, c.id LIMIT @count"; + + await using var command = dataSource.CreateCommand(sql); + command.Parameters.AddWithValue("user_id", userId); + if (cursorTime is not null) + { + command.Parameters.AddWithValue("cursor_time", cursorTime.Value); + command.Parameters.AddWithValue("cursor_id", cursorId!.Value); + } + command.Parameters.AddWithValue("count", count); + await using var reader = await command.ExecuteReaderAsync(); + var result = new List(); + while (await reader.ReadAsync()) result.Add(ReadChat(reader)); + return result; + } + + public async Task> ListMessagesAsync(Guid chatId, DateTime? cursorTime, Guid? cursorId, int count, bool newestFirst = false) + { + var sql = "SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = @chat_id"; + if (cursorTime is not null) + sql += newestFirst ? " AND (created_at, id) < (@cursor_time, @cursor_id)" : " AND (created_at, id) > (@cursor_time, @cursor_id)"; + sql += newestFirst ? " ORDER BY created_at DESC, id DESC LIMIT @count" : " ORDER BY created_at, id LIMIT @count"; + + await using var command = dataSource.CreateCommand(sql); + command.Parameters.AddWithValue("chat_id", chatId); + if (cursorTime is not null) + { + command.Parameters.AddWithValue("cursor_time", cursorTime.Value); + command.Parameters.AddWithValue("cursor_id", cursorId!.Value); + } + command.Parameters.AddWithValue("count", count); + await using var reader = await command.ExecuteReaderAsync(); + var result = new List(); + while (await reader.ReadAsync()) result.Add(new MessageEntity( + reader.GetGuid(0), reader.GetGuid(1), reader.GetGuid(2), reader.GetString(3), reader.GetDateTime(4))); + return result; + } + + private static UserEntity ReadUser(NpgsqlDataReader reader) => new( + reader.GetGuid(0), reader.GetString(1), reader.GetString(2), reader.GetString(3), reader.GetDateTime(4)); + + private static ChatEntity ReadChat(NpgsqlDataReader reader) => new( + reader.GetGuid(0), reader.GetString(1), reader.GetFieldValue(3).ToList(), reader.GetDateTime(2)); +} diff --git a/src/Messenger.Api/Data/ChatPreviews.cs b/src/Messenger.Api/Data/ChatPreviews.cs new file mode 100644 index 00000000..960ec0a8 --- /dev/null +++ b/src/Messenger.Api/Data/ChatPreviews.cs @@ -0,0 +1,51 @@ +using Messenger.Api.Contracts; +using Npgsql; + +namespace Messenger.Api.Data; + +public sealed partial class AppDatabase +{ + public async Task> ListChatPreviewsAsync(Guid userId, DateTime? cursorTime, Guid? cursorId, int count) + { + var query = """ + WITH page AS ( + SELECT c.id, c.title, c.created_at, + ARRAY(SELECT m.user_id FROM chat_members m WHERE m.chat_id = c.id ORDER BY m.user_id) AS member_ids + FROM chats c JOIN chat_members membership ON membership.chat_id = c.id + WHERE membership.user_id = @user_id + """; + if (cursorTime is not null) query += " AND (c.created_at, c.id) > (@cursor_time, @cursor_id)"; + query += """ + ORDER BY c.created_at, c.id LIMIT @count + ) + SELECT p.id, p.title, p.created_at, p.member_ids, + latest.id, latest.sender_id, latest.text, latest.created_at + 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(); + 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(3).ToList(), + reader.GetDateTime(2).ToString("O"), message)); + } + return result; + } +} diff --git a/src/Messenger.Api/Data/DatabaseMigrator.cs b/src/Messenger.Api/Data/DatabaseMigrator.cs new file mode 100644 index 00000000..91cb8068 --- /dev/null +++ b/src/Messenger.Api/Data/DatabaseMigrator.cs @@ -0,0 +1,40 @@ +using Npgsql; + +namespace Messenger.Api.Data; + +public static class DatabaseMigrator +{ + public static async Task ApplyAsync(NpgsqlDataSource dataSource) + { + await using var connection = await dataSource.OpenConnectionAsync(); + await using var transaction = await connection.BeginTransactionAsync(); + await using (var command = new NpgsqlCommand("SELECT pg_advisory_xact_lock(202602)", connection, transaction)) + await command.ExecuteNonQueryAsync(); + await using (var command = new NpgsqlCommand( + "CREATE TABLE IF NOT EXISTS schema_migrations (version integer PRIMARY KEY, applied_at timestamptz NOT NULL)", + connection, transaction)) + await command.ExecuteNonQueryAsync(); + + var assembly = typeof(DatabaseMigrator).Assembly; + var migrations = assembly.GetManifestResourceNames() + .Where(name => name.Contains(".Data.Migrations.", StringComparison.Ordinal) && name.EndsWith(".sql", StringComparison.Ordinal)) + .Order(StringComparer.Ordinal); + foreach (var name in migrations) + { + var version = int.Parse(name.Split('.')[^2].Split('_')[0]); + await using var check = new NpgsqlCommand("SELECT EXISTS (SELECT 1 FROM schema_migrations WHERE version = @version)", connection, transaction); + check.Parameters.AddWithValue("version", version); + if ((bool)(await check.ExecuteScalarAsync())!) continue; + + await using var stream = assembly.GetManifestResourceStream(name)!; + using var reader = new StreamReader(stream); + await using (var migration = new NpgsqlCommand(await reader.ReadToEndAsync(), connection, transaction)) + await migration.ExecuteNonQueryAsync(); + await using var record = new NpgsqlCommand( + "INSERT INTO schema_migrations(version, applied_at) VALUES (@version, now())", connection, transaction); + record.Parameters.AddWithValue("version", version); + await record.ExecuteNonQueryAsync(); + } + await transaction.CommitAsync(); + } +} diff --git a/src/Messenger.Api/Data/Entities/ChatEntity.cs b/src/Messenger.Api/Data/Entities/ChatEntity.cs new file mode 100644 index 00000000..9daea081 --- /dev/null +++ b/src/Messenger.Api/Data/Entities/ChatEntity.cs @@ -0,0 +1,6 @@ +namespace Messenger.Api.Data.Entities; + +public sealed record ChatEntity(Guid Id, string Title, List MemberIds, DateTime CreatedAt) +{ + public Contracts.ChatDto ToDto() => new(Id, Title, MemberIds, CreatedAt.ToString("O")); +} diff --git a/src/Messenger.Api/Data/Entities/MessageEntity.cs b/src/Messenger.Api/Data/Entities/MessageEntity.cs new file mode 100644 index 00000000..3f69c86e --- /dev/null +++ b/src/Messenger.Api/Data/Entities/MessageEntity.cs @@ -0,0 +1,6 @@ +namespace Messenger.Api.Data.Entities; + +public sealed record MessageEntity(Guid Id, Guid ChatId, Guid SenderId, string Text, DateTime CreatedAt) +{ + public Contracts.MessageDto ToDto() => new(Id, ChatId, SenderId, Text, CreatedAt.ToString("O")); +} diff --git a/src/Messenger.Api/Data/Entities/SessionEntity.cs b/src/Messenger.Api/Data/Entities/SessionEntity.cs new file mode 100644 index 00000000..ddb29de1 --- /dev/null +++ b/src/Messenger.Api/Data/Entities/SessionEntity.cs @@ -0,0 +1,3 @@ +namespace Messenger.Api.Data.Entities; + +public sealed record SessionEntity(Guid UserId, DateTime ExpiresAt); diff --git a/src/Messenger.Api/Data/Entities/UserEntity.cs b/src/Messenger.Api/Data/Entities/UserEntity.cs new file mode 100644 index 00000000..9389ce4c --- /dev/null +++ b/src/Messenger.Api/Data/Entities/UserEntity.cs @@ -0,0 +1,6 @@ +namespace Messenger.Api.Data.Entities; + +public sealed record UserEntity(Guid Id, string Username, string DisplayName, string PasswordHash, DateTime CreatedAt) +{ + public Contracts.UserDto ToDto() => new(Id, Username, DisplayName, CreatedAt.ToString("O")); +} diff --git a/src/Messenger.Api/Data/MessageRequests.cs b/src/Messenger.Api/Data/MessageRequests.cs new file mode 100644 index 00000000..74a7b8f4 --- /dev/null +++ b/src/Messenger.Api/Data/MessageRequests.cs @@ -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 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(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; + } +} diff --git a/src/Messenger.Api/Data/Migrations/001_initial.sql b/src/Messenger.Api/Data/Migrations/001_initial.sql new file mode 100644 index 00000000..2cf544fc --- /dev/null +++ b/src/Messenger.Api/Data/Migrations/001_initial.sql @@ -0,0 +1,43 @@ +CREATE TABLE users ( + id uuid PRIMARY KEY, + username text NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'), + display_name text NOT NULL, + password_hash text NOT NULL, + created_at timestamptz NOT NULL +); + +CREATE TABLE chats ( + id uuid PRIMARY KEY, + title text NOT NULL, + created_at timestamptz NOT NULL +); + +CREATE TABLE chat_members ( + chat_id uuid NOT NULL REFERENCES chats(id), + user_id uuid NOT NULL REFERENCES users(id), + PRIMARY KEY (chat_id, user_id) +); + +CREATE INDEX chat_members_user_chat_idx ON chat_members (user_id, chat_id); +CREATE INDEX chats_created_id_idx ON chats (created_at, id); + +CREATE TABLE messages ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL REFERENCES chats(id), + sender_id uuid NOT NULL REFERENCES users(id), + text text NOT NULL, + created_at timestamptz NOT NULL +); + +CREATE INDEX messages_chat_created_id_idx ON messages (chat_id, created_at, id); + +CREATE TABLE sessions ( + token_hash bytea PRIMARY KEY, + user_id uuid NOT NULL REFERENCES users(id), + expires_at timestamptz NOT NULL, + revoked_at timestamptz, + created_at timestamptz NOT NULL +); + +CREATE INDEX sessions_user_id_idx ON sessions (user_id); +CREATE INDEX sessions_expires_at_idx ON sessions (expires_at); diff --git a/src/Messenger.Api/Data/Migrations/002_idempotency.sql b/src/Messenger.Api/Data/Migrations/002_idempotency.sql new file mode 100644 index 00000000..9ec17406 --- /dev/null +++ b/src/Messenger.Api/Data/Migrations/002_idempotency.sql @@ -0,0 +1,11 @@ +CREATE TABLE message_requests ( + user_id uuid NOT NULL REFERENCES users(id), + chat_id uuid NOT NULL REFERENCES chats(id), + request_key text NOT NULL, + request_hash bytea NOT NULL, + message_id uuid NOT NULL REFERENCES messages(id), + expires_at timestamptz NOT NULL, + PRIMARY KEY (user_id, chat_id, request_key) +); + +CREATE INDEX message_requests_expires_idx ON message_requests (expires_at); diff --git a/src/Messenger.Api/Data/Migrations/003_reactions.sql b/src/Messenger.Api/Data/Migrations/003_reactions.sql new file mode 100644 index 00000000..c4b1e44b --- /dev/null +++ b/src/Messenger.Api/Data/Migrations/003_reactions.sql @@ -0,0 +1,6 @@ +CREATE TABLE message_reactions ( + message_id uuid NOT NULL REFERENCES messages(id) ON DELETE CASCADE, + user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, + reaction text NOT NULL CHECK (reaction IN ('like', 'love', 'laugh', 'mushroom')), + PRIMARY KEY (message_id, user_id, reaction) +); diff --git a/src/Messenger.Api/Data/Reactions.cs b/src/Messenger.Api/Data/Reactions.cs new file mode 100644 index 00000000..7d40ffce --- /dev/null +++ b/src/Messenger.Api/Data/Reactions.cs @@ -0,0 +1,48 @@ +using Npgsql; + +namespace Messenger.Api.Data; + +public sealed record ReactionDto(Guid MessageId, string Reaction, int Count, bool Mine); + +public sealed partial class AppDatabase +{ + public async Task SetReactionAsync(Guid chatId, Guid messageId, Guid userId, string reaction, bool present) + { + await using var command = dataSource.CreateCommand(present ? """ + WITH target AS (SELECT id FROM messages WHERE id = @message_id AND chat_id = @chat_id), + written AS ( + INSERT INTO message_reactions(message_id, user_id, reaction) + SELECT id, @user_id, @reaction FROM target ON CONFLICT DO NOTHING + ) SELECT EXISTS(SELECT 1 FROM target) + """ : """ + WITH target AS (SELECT id FROM messages WHERE id = @message_id AND chat_id = @chat_id), + removed AS ( + DELETE FROM message_reactions WHERE message_id IN (SELECT id FROM target) + AND user_id = @user_id AND reaction = @reaction + ) SELECT EXISTS(SELECT 1 FROM target) + """); + command.Parameters.AddWithValue("chat_id", chatId); + command.Parameters.AddWithValue("message_id", messageId); + command.Parameters.AddWithValue("user_id", userId); + command.Parameters.AddWithValue("reaction", reaction); + return (bool)(await command.ExecuteScalarAsync())!; + } + + public async Task> ListReactionsAsync(Guid chatId, Guid[] messageIds, Guid userId) + { + await using var command = dataSource.CreateCommand(""" + SELECT r.message_id, r.reaction, count(*)::integer, bool_or(r.user_id = @user_id) + FROM message_reactions r JOIN messages m ON m.id = r.message_id + WHERE m.chat_id = @chat_id AND m.id = ANY(@message_ids) + GROUP BY r.message_id, r.reaction ORDER BY r.message_id, r.reaction + """); + command.Parameters.AddWithValue("chat_id", chatId); + command.Parameters.AddWithValue("message_ids", messageIds); + command.Parameters.AddWithValue("user_id", userId); + await using var reader = await command.ExecuteReaderAsync(); + var items = new List(); + while (await reader.ReadAsync()) + items.Add(new(reader.GetGuid(0), reader.GetString(1), reader.GetInt32(2), reader.GetBoolean(3))); + return items; + } +} diff --git a/src/Messenger.Api/Data/UtcClock.cs b/src/Messenger.Api/Data/UtcClock.cs new file mode 100644 index 00000000..30f9fbf7 --- /dev/null +++ b/src/Messenger.Api/Data/UtcClock.cs @@ -0,0 +1,11 @@ +namespace Messenger.Api.Data; + +public static class UtcClock +{ + // PostgreSQL timestamptz stores microseconds; keep the response identical to the saved value. + public static DateTime Now() + { + var ticks = DateTime.UtcNow.Ticks; + return new DateTime(ticks - ticks % 10, DateTimeKind.Utc); + } +} diff --git a/src/Messenger.Api/Endpoints/AuthEndpoints.cs b/src/Messenger.Api/Endpoints/AuthEndpoints.cs new file mode 100644 index 00000000..ebc792eb --- /dev/null +++ b/src/Messenger.Api/Endpoints/AuthEndpoints.cs @@ -0,0 +1,60 @@ +using System.Text; +using System.Text.RegularExpressions; +using Messenger.Api.Services; +using static Messenger.Api.Services.ApiSupport; + +namespace Messenger.Api.Endpoints; + +public static class AuthEndpoints +{ + private static readonly UTF8Encoding StrictUtf8 = new(false, true); + + public static IEndpointRouteBuilder MapAuthEndpoints(this IEndpointRouteBuilder app) + { + app.MapPost("/api/v1/auth/sessions", async (HttpContext context, SessionService sessions) => + { + if (!context.Request.Headers.TryGetValue("Authorization", out var header)) + return Unauthorized(context, basic: true); + + var authorization = header.ToString(); + if (!authorization.StartsWith("Basic ", StringComparison.OrdinalIgnoreCase)) + return Unauthorized(context, basic: true); + + string credentials; + try + { + credentials = StrictUtf8.GetString(Convert.FromBase64String(authorization[6..])); + } + catch (Exception exception) when (exception is FormatException or DecoderFallbackException) + { + return Unauthorized(context, basic: true); + } + + var delimiter = credentials.IndexOf(':'); + if (delimiter < 0) return Unauthorized(context, basic: true); + var username = credentials[..delimiter]; + var password = credentials[(delimiter + 1)..]; + if (!Regex.IsMatch(username, "\\A[a-z0-9_]{3,32}\\z")) + return Unauthorized(context, basic: true); + + if (context.Request.ContentLength > 0 || context.Request.Headers.ContainsKey("Transfer-Encoding")) + return ApiError(context, 400, "invalid_request", "Вход принимает Basic без тела запроса"); + + var session = await sessions.LoginAsync(username, password); + return session is null + ? Unauthorized(context, basic: true) + : Results.Json(session, statusCode: StatusCodes.Status201Created); + }); + + app.MapDelete("/api/v1/auth/sessions/current", async (HttpContext context, SessionService sessions) => + { + var (user, tokenHash) = await sessions.AuthenticateAsync(context); + if (user is null || tokenHash is null) return Unauthorized(context); + return await sessions.RevokeAsync(tokenHash) + ? Results.NoContent() + : Unauthorized(context); + }); + + return app; + } +} diff --git a/src/Messenger.Api/Endpoints/ChatEndpoints.cs b/src/Messenger.Api/Endpoints/ChatEndpoints.cs new file mode 100644 index 00000000..127feb04 --- /dev/null +++ b/src/Messenger.Api/Endpoints/ChatEndpoints.cs @@ -0,0 +1,67 @@ +using Messenger.Api.Contracts; +using Messenger.Api.Services; +using static Messenger.Api.Services.ApiSupport; + +namespace Messenger.Api.Endpoints; + +public static class ChatEndpoints +{ + public static IEndpointRouteBuilder MapChatEndpoints(this IEndpointRouteBuilder app) + { + app.MapPost("/api/v1/chats", async (HttpContext context, SessionService sessions, ChatService chats) => + { + var (actor, _) = await sessions.AuthenticateAsync(context); + if (actor is null) return Unauthorized(context); + + var (request, error) = await ReadJsonAsync(context); + if (error is not null) return error; + if (string.IsNullOrWhiteSpace(request!.Title) || request.Title.EnumerateRunes().Count() > 100) + return ApiError(context, 400, "invalid_request", "Некорректное название чата"); + if (request.MemberIds is null || request.MemberIds.Count is < 1 or > 100 || + request.MemberIds.Distinct().Count() != request.MemberIds.Count || + !request.MemberIds.Contains(actor.Id)) + return ApiError(context, 400, "invalid_request", "Некорректный список участников"); + + var chat = await chats.CreateAsync(request.Title, request.MemberIds); + return chat is null + ? ApiError(context, 400, "invalid_request", "Один из участников не существует") + : Results.Json(chat, statusCode: StatusCodes.Status201Created); + }); + + app.MapGet("/api/v1/chats", async (HttpContext context, SessionService sessions, ChatService chats) => + { + var (actor, _) = await sessions.AuthenticateAsync(context); + if (actor is null) return Unauthorized(context); + var (limit, limitError) = ParseLimit(context); + if (limitError is not null) return limitError; + var (cursor, cursorTime, cursorError) = ParseCursor(context, $"user:{actor.Id}"); + if (cursorError is not null) return cursorError; + + var page = await chats.ListAsync(actor.Id, cursorTime, cursor?.Id, limit + 1); + string? nextCursor = null; + if (page.Count > limit) + { + var last = page[limit - 1]; + nextCursor = CursorService.EncodeChatCursor(new ChatCursor($"user:{actor.Id}", last.CreatedAt, last.Id)); + page = page.Take(limit).ToList(); + } + return Results.Ok(new { items = page, next_cursor = nextCursor }); + }); + + app.MapGet("/api/v1/chats/{chat_id}", async ( + string chat_id, HttpContext context, SessionService sessions, ChatService chats) => + { + var (actor, _) = await sessions.AuthenticateAsync(context); + if (actor is null) return Unauthorized(context); + if (!Guid.TryParse(chat_id, out var chatId)) + return ApiError(context, 400, "invalid_request", "Некорректный chat_id"); + + var chat = await chats.FindForMemberAsync(chatId, actor.Id); + return chat is null + ? ApiError(context, 404, "not_found", "Чат не найден") + : Results.Ok(chat); + }); + + return app; + } +} diff --git a/src/Messenger.Api/Endpoints/HealthEndpoints.cs b/src/Messenger.Api/Endpoints/HealthEndpoints.cs new file mode 100644 index 00000000..c9a071cc --- /dev/null +++ b/src/Messenger.Api/Endpoints/HealthEndpoints.cs @@ -0,0 +1,18 @@ +using Messenger.Api.Data; +using Messenger.Api.Services; +using Messenger.Api.Infrastructure; + +namespace Messenger.Api.Endpoints; + +public static class HealthEndpoints +{ + public static IEndpointRouteBuilder MapHealthEndpoints(this IEndpointRouteBuilder app) + { + app.MapGet("/health/live", () => Results.Ok(new { status = "ok" })); + app.MapGet("/health/ready", async (HttpContext context, AppDatabase database, ReadinessState readiness) => + !readiness.IsStopping && await database.IsReadyAsync() + ? Results.Ok(new { status = "ok" }) + : ApiSupport.ApiError(context, 503, "unavailable", "База данных недоступна")); + return app; + } +} diff --git a/src/Messenger.Api/Endpoints/MessageEndpoints.cs b/src/Messenger.Api/Endpoints/MessageEndpoints.cs new file mode 100644 index 00000000..63479afb --- /dev/null +++ b/src/Messenger.Api/Endpoints/MessageEndpoints.cs @@ -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(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; + } +} diff --git a/src/Messenger.Api/Endpoints/ReactionEndpoints.cs b/src/Messenger.Api/Endpoints/ReactionEndpoints.cs new file mode 100644 index 00000000..5459a1a4 --- /dev/null +++ b/src/Messenger.Api/Endpoints/ReactionEndpoints.cs @@ -0,0 +1,39 @@ +using Messenger.Api.Data; +using Messenger.Api.Services; +using static Messenger.Api.Services.ApiSupport; + +namespace Messenger.Api.Endpoints; + +public static class ReactionEndpoints +{ + public static IEndpointRouteBuilder MapReactionEndpoints(this IEndpointRouteBuilder app) + { + app.MapGet("/api/ui/chats/{chat_id}/reactions", async ( + string chat_id, HttpContext context, SessionService sessions, ChatService chats, AppDatabase database) => + { + var (actor, _) = await sessions.AuthenticateAsync(context); + if (actor is null) return Unauthorized(context); + if (!Guid.TryParse(chat_id, out var chatId)) return ApiError(context, 400, "invalid_request", "Некорректный chat_id"); + if (await chats.FindForMemberAsync(chatId, actor.Id) is null) return ApiError(context, 404, "not_found", "Чат не найден"); + var values = context.Request.Query["message_ids"].ToString().Split(','); + if (values.Length is < 1 or > 100 || values.Any(value => !Guid.TryParse(value, out _))) + return ApiError(context, 400, "invalid_request", "Укажите от 1 до 100 ID сообщений"); + var ids = values.Select(Guid.Parse).Distinct().ToArray(); + return Results.Ok(new { items = await database.ListReactionsAsync(chatId, ids, actor.Id) }); + }); + app.MapMethods("/api/ui/chats/{chat_id}/messages/{message_id}/reactions/{reaction}", ["PUT", "DELETE"], async ( + string chat_id, string message_id, string reaction, HttpContext context, + SessionService sessions, ChatService chats, AppDatabase database) => + { + var (actor, _) = await sessions.AuthenticateAsync(context); + if (actor is null) return Unauthorized(context); + if (!Guid.TryParse(chat_id, out var chatId) || !Guid.TryParse(message_id, out var messageId) + || reaction is not ("like" or "love" or "laugh" or "mushroom")) + return ApiError(context, 400, "invalid_request", "Некорректная реакция или ID"); + if (await chats.FindForMemberAsync(chatId, actor.Id) is null) return ApiError(context, 404, "not_found", "Чат не найден"); + return await database.SetReactionAsync(chatId, messageId, actor.Id, reaction, context.Request.Method == "PUT") + ? Results.NoContent() : ApiError(context, 404, "not_found", "Сообщение не найдено"); + }); + return app; + } +} diff --git a/src/Messenger.Api/Endpoints/UiEndpoints.cs b/src/Messenger.Api/Endpoints/UiEndpoints.cs new file mode 100644 index 00000000..752d7fe0 --- /dev/null +++ b/src/Messenger.Api/Endpoints/UiEndpoints.cs @@ -0,0 +1,80 @@ +using Messenger.Api.Contracts; +using Messenger.Api.Services; +using Messenger.Api.Data; +using Messenger.Api.Infrastructure; +using static Messenger.Api.Services.ApiSupport; + +namespace Messenger.Api.Endpoints; + +public static class UiEndpoints +{ + // The required /api/v1 history stays ascending. The web client has a separate, + // optional route to open a large chat at its newest page and page backwards. + public static IEndpointRouteBuilder MapUiEndpoints(this IEndpointRouteBuilder app) + { + app.MapGet("/api/ui/cluster", async (HttpContext context, SessionService sessions, ClusterPresence presence) => + { + var (actor, _) = await sessions.AuthenticateAsync(context); + if (actor is null) return Unauthorized(context); + context.Response.Headers.CacheControl = "no-store"; + return Results.Ok(await presence.ReadAsync()); + }); + + app.MapGet("/api/ui/chats", async (HttpContext context, SessionService sessions, AppDatabase database) => + { + var (actor, _) = await sessions.AuthenticateAsync(context); + if (actor is null) return Unauthorized(context); + var (limit, limitError) = ParseLimit(context); + if (limitError is not null) return limitError; + var (cursor, cursorTime, cursorError) = ParseCursor(context, $"ui-chats:{actor.Id}"); + if (cursorError is not null) return cursorError; + var page = await database.ListChatPreviewsAsync(actor.Id, cursorTime, cursor?.Id, limit + 1); + string? nextCursor = null; + if (page.Count > limit) + { + var last = page[limit - 1]; + nextCursor = CursorService.EncodeChatCursor(new ChatCursor($"ui-chats:{actor.Id}", last.CreatedAt, last.Id)); + page = page.Take(limit).ToList(); + } + return Results.Ok(new { items = page, next_cursor = nextCursor }); + }); + + app.MapGet("/api/ui/chats/{chat_id}/members", async ( + string chat_id, HttpContext context, SessionService sessions, ChatService chats, UserService users) => + { + var (actor, _) = await sessions.AuthenticateAsync(context); + if (actor is null) return Unauthorized(context); + if (!Guid.TryParse(chat_id, out var chatId)) + return ApiError(context, 400, "invalid_request", "Некорректный chat_id"); + if (await chats.FindForMemberAsync(chatId, actor.Id) is null) + return ApiError(context, 404, "not_found", "Чат не найден"); + return Results.Ok(new { items = await users.ListForChatAsync(chatId) }); + }); + + app.MapGet("/api/ui/chats/{chat_id}/messages", async ( + string chat_id, HttpContext context, SessionService sessions, ChatService chats, MessageService messages) => + { + var (actor, _) = await sessions.AuthenticateAsync(context); + if (actor is null) return Unauthorized(context); + if (!Guid.TryParse(chat_id, out var chatId)) + return ApiError(context, 400, "invalid_request", "Некорректный chat_id"); + if (await chats.FindForMemberAsync(chatId, actor.Id) is null) + return ApiError(context, 404, "not_found", "Чат не найден"); + var (limit, limitError) = ParseLimit(context); + if (limitError is not null) return limitError; + var (cursor, cursorTime, cursorError) = ParseCursor(context, $"recent-chat:{chatId}"); + if (cursorError is not null) return cursorError; + + var page = await messages.ListAsync(chatId, cursorTime, cursor?.Id, limit + 1, newestFirst: true); + string? nextCursor = null; + if (page.Count > limit) + { + var last = page[limit - 1]; + nextCursor = CursorService.EncodeChatCursor(new ChatCursor($"recent-chat:{chatId}", last.CreatedAt, last.Id)); + page = page.Take(limit).ToList(); + } + return Results.Ok(new { items = page, next_cursor = nextCursor }); + }); + return app; + } +} diff --git a/src/Messenger.Api/Endpoints/UserEndpoints.cs b/src/Messenger.Api/Endpoints/UserEndpoints.cs new file mode 100644 index 00000000..a6725b19 --- /dev/null +++ b/src/Messenger.Api/Endpoints/UserEndpoints.cs @@ -0,0 +1,40 @@ +using System.Text.RegularExpressions; +using Messenger.Api.Contracts; +using Messenger.Api.Services; +using static Messenger.Api.Services.ApiSupport; + +namespace Messenger.Api.Endpoints; + +public static class UserEndpoints +{ + public static IEndpointRouteBuilder MapUserEndpoints(this IEndpointRouteBuilder app) + { + app.MapPost("/api/v1/users", async (HttpContext context, UserService users) => + { + var (request, error) = await ReadJsonAsync(context); + if (error is not null) return error; + + if (request!.Username is null || !Regex.IsMatch(request.Username, "\\A[a-z0-9_]{3,32}\\z")) + return ApiError(context, 400, "invalid_request", "Некорректный username"); + if (string.IsNullOrWhiteSpace(request.DisplayName) || + request.DisplayName.EnumerateRunes().Count() is < 1 or > 100) + return ApiError(context, 400, "invalid_request", "Некорректный display_name"); + if (string.IsNullOrWhiteSpace(request.Password) || + request.Password.EnumerateRunes().Count() is < 12 or > 128) + return ApiError(context, 400, "invalid_request", "Пароль должен содержать 12-128 символов"); + + var user = await users.RegisterAsync(request.Username, request.DisplayName, request.Password); + return user is null + ? ApiError(context, 409, "conflict", "Username уже занят") + : Results.Json(user, statusCode: StatusCodes.Status201Created); + }); + + app.MapGet("/api/v1/users/me", async (HttpContext context, SessionService sessions) => + { + var (user, _) = await sessions.AuthenticateAsync(context); + return user is null ? Unauthorized(context) : Results.Ok(user); + }); + + return app; + } +} diff --git a/src/Messenger.Api/Infrastructure/ClusterPresence.cs b/src/Messenger.Api/Infrastructure/ClusterPresence.cs new file mode 100644 index 00000000..adccb65b --- /dev/null +++ b/src/Messenger.Api/Infrastructure/ClusterPresence.cs @@ -0,0 +1,55 @@ +using Messenger.Api.Data; +using StackExchange.Redis; + +namespace Messenger.Api.Infrastructure; + +// Registry entries live ten minutes; an eight-second heartbeat gap means unavailable. +// A Redis outage is reported as unknown, never as proof that an API has stopped. +public sealed class ClusterPresence(IConnectionMultiplexer redis, InstanceIdentity identity, + ReadinessState readiness, AppDatabase database, ILogger logger) : BackgroundService +{ + private const string Registry = "messenger:ui:instances"; + public sealed record Node(string Id, bool Ready, long LastSeen); + public sealed record Snapshot(bool RedisAvailable, bool PostgresAvailable, long CheckedAt, List Instances); + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + using var timer = new PeriodicTimer(TimeSpan.FromSeconds(2)); + try + { + do + { + try + { + if (redis.IsConnected && !readiness.IsStopping && await database.IsReadyAsync()) + { + var db = redis.GetDatabase(); + var now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + await db.SortedSetAddAsync(Registry, identity.Id, now).WaitAsync(TimeSpan.FromSeconds(1), stoppingToken); + await db.SortedSetRemoveRangeByScoreAsync(Registry, double.NegativeInfinity, now - 600_000); + await db.KeyExpireAsync(Registry, TimeSpan.FromMinutes(15)); + } + } + catch (Exception error) when (error is RedisException or TimeoutException) + { logger.LogDebug("Cluster heartbeat unavailable"); } + } while (await timer.WaitForNextTickAsync(stoppingToken)); + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { } + } + + public async Task ReadAsync() + { + var now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + var postgres = await database.IsReadyAsync(); + try + { + if (!redis.IsConnected) return new(false, postgres, now, []); + var entries = await redis.GetDatabase().SortedSetRangeByScoreWithScoresAsync(Registry, + now - 600_000, double.PositiveInfinity).WaitAsync(TimeSpan.FromSeconds(1)); + return new(true, postgres, now, entries.Select(entry => new Node(entry.Element.ToString(), + now - entry.Score < 8000, (long)entry.Score)).ToList()); + } + catch (Exception error) when (error is RedisException or TimeoutException) + { return new(false, postgres, now, []); } + } +} diff --git a/src/Messenger.Api/Infrastructure/InstanceIdentity.cs b/src/Messenger.Api/Infrastructure/InstanceIdentity.cs new file mode 100644 index 00000000..855f4460 --- /dev/null +++ b/src/Messenger.Api/Infrastructure/InstanceIdentity.cs @@ -0,0 +1,6 @@ +namespace Messenger.Api.Infrastructure; + +public sealed class InstanceIdentity +{ + public string Id { get; } = Guid.NewGuid().ToString("N"); +} diff --git a/src/Messenger.Api/Infrastructure/ReadinessState.cs b/src/Messenger.Api/Infrastructure/ReadinessState.cs new file mode 100644 index 00000000..35981ef2 --- /dev/null +++ b/src/Messenger.Api/Infrastructure/ReadinessState.cs @@ -0,0 +1,8 @@ +namespace Messenger.Api.Infrastructure; + +public sealed class ReadinessState +{ + private int _stopping; + public bool IsStopping => Volatile.Read(ref _stopping) != 0; + public void Stop() => Interlocked.Exchange(ref _stopping, 1); +} diff --git a/src/Messenger.Api/Infrastructure/RedisSessionCache.cs b/src/Messenger.Api/Infrastructure/RedisSessionCache.cs new file mode 100644 index 00000000..09e977fa --- /dev/null +++ b/src/Messenger.Api/Infrastructure/RedisSessionCache.cs @@ -0,0 +1,58 @@ +using System.Text.Json; +using Messenger.Api.Contracts; +using StackExchange.Redis; + +namespace Messenger.Api.Infrastructure; + +// PostgreSQL validates the session on every request. This cache saves the user lookup +// and never grants access independently of the durable session row. +public sealed class RedisSessionCache(IConnectionMultiplexer connection, ILogger logger) +{ + private static readonly TimeSpan OperationBudget = TimeSpan.FromMilliseconds(750); + private static string Key(byte[] hash) => "messenger:session:" + Convert.ToHexString(hash).ToLowerInvariant(); + + public sealed record Entry(UserDto User, DateTime ExpiresAt); + + public async Task GetAsync(byte[] hash) + { + if (!connection.IsConnected) return null; + try + { + var value = await connection.GetDatabase().StringGetAsync(Key(hash)).WaitAsync(OperationBudget); + return value.IsNullOrEmpty ? null : JsonSerializer.Deserialize(value.ToString()); + } + catch (Exception exception) when (exception is RedisException or TimeoutException or OperationCanceledException or JsonException) + { + logger.LogWarning("Session cache read unavailable; using PostgreSQL"); + return null; + } + } + + public async Task SetAsync(byte[] hash, UserDto user, DateTime expiresAt) + { + var remaining = expiresAt - DateTime.UtcNow; + if (!connection.IsConnected || remaining <= TimeSpan.Zero) return; + try + { + await connection.GetDatabase().StringSetAsync(Key(hash), + JsonSerializer.Serialize(new Entry(user, expiresAt)), remaining).WaitAsync(OperationBudget); + } + catch (Exception exception) when (exception is RedisException or TimeoutException or OperationCanceledException) + { + logger.LogWarning("Session cache write unavailable; using PostgreSQL"); + } + } + + public async Task RemoveAsync(byte[] hash) + { + if (!connection.IsConnected) return; + try + { + await connection.GetDatabase().KeyDeleteAsync(Key(hash)).WaitAsync(OperationBudget); + } + catch (Exception exception) when (exception is RedisException or TimeoutException or OperationCanceledException) + { + logger.LogWarning("Session cache invalidation unavailable; PostgreSQL still enforces revocation"); + } + } +} diff --git a/src/Messenger.Api/Messenger.Api.csproj b/src/Messenger.Api/Messenger.Api.csproj new file mode 100644 index 00000000..857475de --- /dev/null +++ b/src/Messenger.Api/Messenger.Api.csproj @@ -0,0 +1,19 @@ + + + + net9.0 + enable + enable + + + + + + + + + + + + + diff --git a/src/Messenger.Api/Middleware/ExceptionHandlingMiddleware.cs b/src/Messenger.Api/Middleware/ExceptionHandlingMiddleware.cs new file mode 100644 index 00000000..db4caccd --- /dev/null +++ b/src/Messenger.Api/Middleware/ExceptionHandlingMiddleware.cs @@ -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 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); + } + } +} diff --git a/src/Messenger.Api/Middleware/InstanceMiddleware.cs b/src/Messenger.Api/Middleware/InstanceMiddleware.cs new file mode 100644 index 00000000..c4b75741 --- /dev/null +++ b/src/Messenger.Api/Middleware/InstanceMiddleware.cs @@ -0,0 +1,18 @@ +using Messenger.Api.Infrastructure; +using Messenger.Api.Services; + +namespace Messenger.Api.Middleware; + +public sealed class InstanceMiddleware(RequestDelegate next) +{ + public async Task InvokeAsync(HttpContext context, InstanceIdentity identity, ReadinessState readiness) + { + context.Response.Headers["X-Instance-Id"] = identity.Id; + if (readiness.IsStopping && context.Request.Path != "/health/live") + { + await ApiSupport.ApiError(context, 503, "unavailable", "Экземпляр API останавливается").ExecuteAsync(context); + return; + } + await next(context); + } +} diff --git a/src/Messenger.Api/Middleware/RequestIdMiddleware.cs b/src/Messenger.Api/Middleware/RequestIdMiddleware.cs new file mode 100644 index 00000000..973b6373 --- /dev/null +++ b/src/Messenger.Api/Middleware/RequestIdMiddleware.cs @@ -0,0 +1,16 @@ +namespace Messenger.Api.Middleware; + +public sealed class RequestIdMiddleware +{ + private readonly RequestDelegate _next; + + public RequestIdMiddleware(RequestDelegate next) => _next = next; + + public async Task InvokeAsync(HttpContext context) + { + var requestId = Guid.NewGuid().ToString(); + context.Items["RequestId"] = requestId; + context.Response.Headers["X-Request-Id"] = requestId; + await _next(context); + } +} diff --git a/src/Messenger.Api/Middleware/RequestLoggingMiddleware.cs b/src/Messenger.Api/Middleware/RequestLoggingMiddleware.cs new file mode 100644 index 00000000..865f56d6 --- /dev/null +++ b/src/Messenger.Api/Middleware/RequestLoggingMiddleware.cs @@ -0,0 +1,25 @@ +namespace Messenger.Api.Middleware; + +public sealed class RequestLoggingMiddleware +{ + private readonly RequestDelegate _next; + + public RequestLoggingMiddleware(RequestDelegate next) => _next = next; + + public async Task InvokeAsync(HttpContext context) + { + var logger = context.RequestServices + .GetRequiredService() + .CreateLogger("Http"); + + await _next(context); + + logger.LogInformation( + "{Method} {Path} -> {StatusCode} request_id={RequestId}", + context.Request.Method, + context.Request.Path, + context.Response.StatusCode, + context.Items["RequestId"] + ); + } +} diff --git a/src/Messenger.Api/Program.cs b/src/Messenger.Api/Program.cs new file mode 100644 index 00000000..e98a5225 --- /dev/null +++ b/src/Messenger.Api/Program.cs @@ -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(); +builder.Services.AddSingleton(); +builder.Services.Configure(options => options.ShutdownTimeout = TimeSpan.FromSeconds(8)); +builder.Services.AddSingleton(); +var redisOptions = ConfigurationOptions.Parse(builder.Configuration["REDIS_URL"] ?? "localhost:6379"); +redisOptions.AbortOnConnectFail = false; +redisOptions.ConnectTimeout = 500; +redisOptions.ConnectRetry = 0; +redisOptions.AsyncTimeout = 500; +redisOptions.SyncTimeout = 500; +redisOptions.BacklogPolicy = BacklogPolicy.FailFast; +builder.Services.AddSingleton(await ConnectionMultiplexer.ConnectAsync(redisOptions)); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddHostedService(services => services.GetRequiredService()); + +var app = builder.Build(); +app.Lifetime.ApplicationStopping.Register(app.Services.GetRequiredService().Stop); + +app.UseMiddleware(); +app.UseMiddleware(); +app.UseMiddleware(); +app.UseMiddleware(); +app.UseDefaultFiles(); +app.UseStaticFiles(new StaticFileOptions +{ + OnPrepareResponse = context => context.Context.Response.Headers.CacheControl = "no-cache" +}); + +app.MapHealthEndpoints(); +app.MapUserEndpoints(); +app.MapAuthEndpoints(); +app.MapChatEndpoints(); +app.MapMessageEndpoints(); +app.MapUiEndpoints(); +app.MapReactionEndpoints(); + +app.Run(); diff --git a/src/Messenger.Api/Properties/launchSettings.json b/src/Messenger.Api/Properties/launchSettings.json new file mode 100644 index 00000000..ac9df787 --- /dev/null +++ b/src/Messenger.Api/Properties/launchSettings.json @@ -0,0 +1,23 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5052", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7253;http://localhost:5052", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/src/Messenger.Api/Services/ApiSupport.cs b/src/Messenger.Api/Services/ApiSupport.cs new file mode 100644 index 00000000..7936d712 --- /dev/null +++ b/src/Messenger.Api/Services/ApiSupport.cs @@ -0,0 +1,93 @@ +using System.Globalization; +using System.Text.Json; +using Messenger.Api.Contracts; + +namespace Messenger.Api.Services; + +public static class ApiSupport +{ + public static async Task<(T? Value, IResult? Error)> ReadJsonAsync(HttpContext context) + { + if (!context.Request.HasJsonContentType()) + return (default, ApiError(context, 400, "invalid_request", "Требуется application/json")); + + try + { + var value = await context.Request.ReadFromJsonAsync(); + return value is null + ? (default, ApiError(context, 400, "invalid_request", "Тело запроса обязательно")) + : (value, null); + } + catch (Exception exception) when (exception is JsonException or NotSupportedException or BadHttpRequestException) + { + return (default, ApiError(context, 400, "invalid_request", "Некорректный JSON")); + } + } + + public static IResult Unauthorized(HttpContext context, bool basic = false) + { + context.Response.Headers["WWW-Authenticate"] = basic + ? "Basic realm=\"messenger\", charset=\"UTF-8\"" + : "Bearer realm=\"messenger\""; + return ApiError(context, 401, "unauthorized", "Требуется действительная сессия"); + } + + public static (ChatCursor? Cursor, DateTime? Time, IResult? Error) ParseCursor( + HttpContext context, string scope) + { + if (!context.Request.Query.TryGetValue("cursor", out var value)) + return (null, null, null); + + var cursor = CursorService.DecodeChatCursor(value.ToString()); + if (cursor is null || cursor.Scope != scope || cursor.Id == Guid.Empty || + !DateTime.TryParse(cursor.CreatedAt, CultureInfo.InvariantCulture, + DateTimeStyles.RoundtripKind, out var time) || time.Kind != DateTimeKind.Utc) + return (null, null, ApiError(context, 400, "invalid_request", "Некорректный cursor")); + + return (cursor, time, null); + } + + public static (int Limit, IResult? Error) ParseLimit(HttpContext context) + { + const int defaultLimit = 50; + + if (!context.Request.Query.TryGetValue("limit", out var value)) + return (defaultLimit, null); + + if (!int.TryParse(value.ToString(), out var limit) || + limit < 1 || + limit > 100) + { + return ( + 0, + ApiError(context, 400, "invalid_request", "limit должен быть от 1 до 100") + ); + } + + return (limit, null); + } + + public static IResult ApiError( + HttpContext context, + int status, + string code, + string message) + { + var requestId = + context.Items["RequestId"]?.ToString() + ?? Guid.NewGuid().ToString(); + + return Results.Json( + new + { + error = new + { + code, + message, + request_id = requestId + } + }, + statusCode: status + ); + } +} diff --git a/src/Messenger.Api/Services/ChatService.cs b/src/Messenger.Api/Services/ChatService.cs new file mode 100644 index 00000000..38979f01 --- /dev/null +++ b/src/Messenger.Api/Services/ChatService.cs @@ -0,0 +1,16 @@ +using Messenger.Api.Contracts; +using Messenger.Api.Data; + +namespace Messenger.Api.Services; + +public sealed class ChatService(AppDatabase database) +{ + public async Task CreateAsync(string title, List memberIds) => + (await database.CreateChatAsync(title, memberIds))?.ToDto(); + + public async Task FindForMemberAsync(Guid chatId, Guid userId) => + (await database.FindChatForMemberAsync(chatId, userId))?.ToDto(); + + public async Task> ListAsync(Guid userId, DateTime? cursorTime, Guid? cursorId, int count) => + (await database.ListChatsAsync(userId, cursorTime, cursorId, count)).Select(chat => chat.ToDto()).ToList(); +} diff --git a/src/Messenger.Api/Services/CursorService.cs b/src/Messenger.Api/Services/CursorService.cs new file mode 100644 index 00000000..f260e9e7 --- /dev/null +++ b/src/Messenger.Api/Services/CursorService.cs @@ -0,0 +1,49 @@ +using System.Text; +using System.Text.Json; +using Messenger.Api.Contracts; + +namespace Messenger.Api.Services; + +public static class CursorService +{ + public static string EncodeChatCursor(ChatCursor cursor) + { + var json = JsonSerializer.Serialize(cursor); + + return Convert.ToBase64String(Encoding.UTF8.GetBytes(json)) + .TrimEnd('=') + .Replace('+', '-') + .Replace('/', '_'); + } + + public static ChatCursor? DecodeChatCursor(string cursor) + { + try + { + var base64 = cursor + .Replace('-', '+') + .Replace('_', '/'); + + switch (base64.Length % 4) + { + case 2: + base64 += "=="; + break; + case 3: + base64 += "="; + break; + case 1: + return null; + } + + var bytes = Convert.FromBase64String(base64); + var json = Encoding.UTF8.GetString(bytes); + + return JsonSerializer.Deserialize(json); + } + catch + { + return null; + } + } +} diff --git a/src/Messenger.Api/Services/MessageService.cs b/src/Messenger.Api/Services/MessageService.cs new file mode 100644 index 00000000..34d3fb44 --- /dev/null +++ b/src/Messenger.Api/Services/MessageService.cs @@ -0,0 +1,13 @@ +using Messenger.Api.Contracts; +using Messenger.Api.Data; + +namespace Messenger.Api.Services; + +public sealed class MessageService(AppDatabase database) +{ + public async Task CreateAsync(Guid chatId, Guid senderId, string text, string key) => + (await database.CreateMessageOnceAsync(chatId, senderId, text, key))?.ToDto(); + + public async Task> ListAsync(Guid chatId, DateTime? cursorTime, Guid? cursorId, int count, bool newestFirst = false) => + (await database.ListMessagesAsync(chatId, cursorTime, cursorId, count, newestFirst)).Select(message => message.ToDto()).ToList(); +} diff --git a/src/Messenger.Api/Services/PasswordService.cs b/src/Messenger.Api/Services/PasswordService.cs new file mode 100644 index 00000000..2d1d4157 --- /dev/null +++ b/src/Messenger.Api/Services/PasswordService.cs @@ -0,0 +1,28 @@ +using System.Security.Cryptography; +using System.Text; +using Isopoh.Cryptography.Argon2; + +namespace Messenger.Api.Services; + +public sealed class PasswordService +{ + public string Hash(string password) + { + var salt = RandomNumberGenerator.GetBytes(16); + var config = new Argon2Config + { + Type = Argon2Type.HybridAddressing, + Version = Argon2Version.Nineteen, + TimeCost = 3, + MemoryCost = 32768, + Lanes = 1, + Threads = 1, + Password = Encoding.UTF8.GetBytes(password), + Salt = salt, + HashLength = 32 + }; + return Argon2.Hash(config); + } + + public bool Verify(string hash, string password) => Argon2.Verify(hash, password); +} diff --git a/src/Messenger.Api/Services/SessionService.cs b/src/Messenger.Api/Services/SessionService.cs new file mode 100644 index 00000000..d9a134fb --- /dev/null +++ b/src/Messenger.Api/Services/SessionService.cs @@ -0,0 +1,65 @@ +using System.Security.Cryptography; +using System.Text; +using Messenger.Api.Contracts; +using Messenger.Api.Data; +using Messenger.Api.Infrastructure; + +namespace Messenger.Api.Services; + +public sealed class SessionService(AppDatabase database, PasswordService passwords, RedisSessionCache cache, IConfiguration configuration) +{ + private readonly int _ttlSeconds = int.TryParse(configuration["SESSION_TTL_SECONDS"], out var ttl) && ttl > 0 + ? ttl : 3600; + + public async Task LoginAsync(string username, string password) + { + var user = await database.FindUserByUsernameAsync(username); + if (user is null || !passwords.Verify(user.PasswordHash, password)) + return null; + + var token = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32)) + .TrimEnd('=').Replace('+', '-').Replace('/', '_'); + var expiresAt = UtcClock.Now().AddSeconds(_ttlSeconds); + var hash = HashToken(token); + await database.CreateSessionAsync(hash, user.Id, expiresAt); + await cache.SetAsync(hash, user.ToDto(), expiresAt); + return new SessionDto(token, "Bearer", expiresAt.ToString("O"), user.ToDto()); + } + + public async Task<(UserDto? User, byte[]? TokenHash)> AuthenticateAsync(HttpContext context) + { + if (!context.Request.Headers.TryGetValue("Authorization", out var value)) + return (null, null); + + var authorization = value.ToString(); + if (!authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) + return (null, null); + + var token = authorization[7..]; + if (token.Length != 43 || token.Any(c => !char.IsAsciiLetterOrDigit(c) && c != '-' && c != '_')) + return (null, null); + + var hash = HashToken(token); + var session = await database.FindActiveSessionAsync(hash); + if (session is null) return (null, null); + + var cached = await cache.GetAsync(hash); + if (cached is not null && cached.User.Id == session.UserId && cached.ExpiresAt == session.ExpiresAt) + return (cached.User, hash); + + var user = await database.FindUserByIdAsync(session.UserId); + if (user is null) return (null, null); + var dto = user.ToDto(); + await cache.SetAsync(hash, dto, session.ExpiresAt); + return (dto, hash); + } + + public async Task RevokeAsync(byte[] tokenHash) + { + var revoked = await database.RevokeSessionAsync(tokenHash); + if (revoked) await cache.RemoveAsync(tokenHash); + return revoked; + } + + private static byte[] HashToken(string token) => SHA256.HashData(Encoding.ASCII.GetBytes(token)); +} diff --git a/src/Messenger.Api/Services/UserService.cs b/src/Messenger.Api/Services/UserService.cs new file mode 100644 index 00000000..6dafd366 --- /dev/null +++ b/src/Messenger.Api/Services/UserService.cs @@ -0,0 +1,24 @@ +using Messenger.Api.Contracts; +using Messenger.Api.Data; +using Npgsql; + +namespace Messenger.Api.Services; + +public sealed class UserService(AppDatabase database, PasswordService passwords) +{ + public async Task> ListForChatAsync(Guid chatId) => + (await database.ListChatUsersAsync(chatId)).Select(user => user.ToDto()).ToList(); + + public async Task RegisterAsync(string username, string displayName, string password) + { + var hash = passwords.Hash(password); + try + { + return (await database.CreateUserAsync(username, displayName, hash)).ToDto(); + } + catch (PostgresException exception) when (exception.SqlState == PostgresErrorCodes.UniqueViolation) + { + return null; + } + } +} diff --git a/src/Messenger.Api/appsettings.Development.json b/src/Messenger.Api/appsettings.Development.json new file mode 100644 index 00000000..ff66ba6b --- /dev/null +++ b/src/Messenger.Api/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/src/Messenger.Api/appsettings.json b/src/Messenger.Api/appsettings.json new file mode 100644 index 00000000..4d566948 --- /dev/null +++ b/src/Messenger.Api/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/src/Messenger.Api/wwwroot/app.css b/src/Messenger.Api/wwwroot/app.css new file mode 100644 index 00000000..7bc42308 --- /dev/null +++ b/src/Messenger.Api/wwwroot/app.css @@ -0,0 +1,438 @@ +:root { + color-scheme: dark; + --ink: #FFE135; + --muted: #b6b5aa; + --accent: #FFE135; + --accent-hover: #ffeb79; + --paper: #262626; + --surface: #303030; + --soft: #38382c; + --border: #414139; + --danger: #ffaaa0; + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; + color: var(--ink); + background: #262626; + font-size: 15px; +} +* { box-sizing: border-box; } +body { margin: 0; } +button, input, textarea { font: inherit; } +button, a, input, textarea { -webkit-tap-highlight-color: transparent; } +button { cursor: pointer; } +button:disabled { cursor: default; opacity: .5; } +button, textarea, input { outline: none; } +button:focus-visible, a:focus-visible { outline: 2px solid var(--accent); outline-offset: 4px; } +input:focus, textarea:focus { border-color: var(--accent); box-shadow: 0 0 0 3px #ffe13515; } +a { color: inherit; text-decoration: none; } +[hidden] { display: none !important; } +svg { width: 21px; height: 21px; fill: none; stroke: currentColor; stroke-width: 1.7; stroke-linecap: round; stroke-linejoin: round; flex-shrink: 0; } +.svg-sprite { position: absolute; width: 0; height: 0; overflow: hidden; } +.visually-hidden { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0,0,0,0); white-space: nowrap; border: 0; } +::selection { color: #262626; background: var(--accent); } + +/* Brand and shared controls */ +.brand { display: inline-flex; align-items: center; font-size: 30px; font-weight: 750; letter-spacing: -1.6px; gap: 10px; line-height: 1; } +.brand-dot { color: var(--accent); margin-left: -8px; } +.brand-mark { height: 36px; width: 36px; background: var(--accent); border-radius: 12px; display: flex; flex-direction: column; justify-content: center; gap: 4px; padding: 9px; } +.brand-mark i { display: block; height: 2px; border-radius: 2px; background: #262626; } +.brand-mark i:nth-child(2) { width: 75%; } +.brand-mark i:nth-child(3) { width: 45%; } +.eyebrow { display: block; color: var(--muted); font-size: 10px; font-weight: 650; letter-spacing: 2px; text-transform: uppercase; line-height: 1.6; } +.muted { color: var(--muted); font-size: 14px; line-height: 1.7; } +label { display: grid; gap: 9px; font-size: 12px; font-weight: 550; color: var(--ink); } +input, textarea { width: 100%; color: var(--ink); background: #292929; border: 1px solid #4b4b42; border-radius: 12px; padding: 14px 15px; font-size: 14px; transition: border-color .18s, box-shadow .18s; } +input::placeholder, textarea::placeholder { color: #a6a69a; } +textarea { resize: vertical; line-height: 1.5; } +.field-note { color: var(--muted); font-size: 11px; font-weight: 400; line-height: 1.7; } +.button { display: inline-flex; align-items: center; justify-content: center; gap: 10px; border-radius: 12px; border: 1px solid transparent; padding: 14px 20px; font-weight: 650; font-size: 13px; transition: background .18s, transform .18s; } +.button.primary { background: var(--accent); color: #262626; } +.button.primary:hover { background: var(--accent-hover); transform: translateY(-1px); } +.button.secondary { background: #3a3a32; border-color: var(--border); color: var(--ink); } +.button.secondary:hover { background: #454538; } +.button.wide { width: 100%; } +.icon-button { display: inline-flex; align-items: center; justify-content: center; border: 1px solid transparent; background: transparent; color: var(--muted); width: 36px; height: 36px; border-radius: 11px; flex-shrink: 0; transition: background .18s, color .18s; } +.icon-button:hover { background: #3c3c32; color: var(--accent); } +.icon-button.filled { background: var(--accent); color: #262626; } +.icon-button.filled:hover { background: var(--accent-hover); } +.text-button { background: none; border: 0; color: var(--accent); font-size: 11px; padding: 10px 14px; border-radius: 9px; } +.text-button:hover { background: #ffe1350e; } +.form-notice { color: var(--danger); font-size: 12px; line-height: 1.6; background: #452f2d; border: 1px solid #70453e; border-radius: 10px; padding: 11px 13px; } +.form-notice.success { color: var(--ink); background: var(--soft); border-color: #686032; } + +/* Entry screen */ +.auth-layout { min-height: 100svh; display: grid; grid-template-columns: 1.1fr 1fr; max-width: 1440px; margin: auto; } +.intro { position: relative; min-height: 760px; padding: 50px 64px 40px; overflow: hidden; background: radial-gradient(ellipse at 5% 95%, #ffe13508, transparent 65%), var(--paper); } +.intro::before { content: ""; position: absolute; inset: auto auto -270px -250px; width: 760px; height: 760px; border: 1px solid #ffe13520; border-radius: 50%; pointer-events: none; } +.intro::after { content: ""; position: absolute; right: -190px; top: 90px; width: 440px; height: 440px; border: 1px solid #ffe13512; border-radius: 50%; pointer-events: none; } +.intro-copy { margin-top: 82px; position: relative; z-index: 1; } +.intro-copy .eyebrow { color: var(--accent); padding-left: 22px; position: relative; } +.intro-copy .eyebrow::before { content: ""; width: 7px; height: 7px; background: var(--accent); border-radius: 50%; position: absolute; left: 0; top: 5px; } +.intro h1 { font-size: clamp(48px, 5vw, 72px); line-height: 1.04; font-weight: 700; letter-spacing: -3.5px; margin: 22px 0 26px; } +.intro em, .welcome em { font-family: Georgia, "Times New Roman", serif; font-weight: 400; color: var(--accent); } +.intro-copy p { color: var(--muted); line-height: 1.8; font-size: 15px; } +.conversation-art { position: relative; width: 330px; height: 165px; margin: 38px 0 25px 34px; z-index: 1; } +.art-bubble { position: absolute; padding: 17px 22px 13px; border-radius: 18px; font-size: 14px; box-shadow: 0 12px 30px #00000020; } +.art-bubble span { display: block; font-size: 10px; text-align: right; margin-top: 8px; opacity: .65; } +.art-bubble b { font-weight: 500; } +.art-one { background: #353530; border: 1px solid #4a4a3c; left: 0; top: 0; transform: rotate(-4deg); border-bottom-left-radius: 5px; min-width: 195px; } +.art-two { background: var(--accent); color: #262626; right: 0; top: 67px; transform: rotate(3deg); border-bottom-right-radius: 5px; min-width: 218px; } +.art-typing { position: absolute; bottom: 0; left: 15px; display: flex; gap: 5px; border-radius: 12px; background: #353530; border: 1px solid var(--border); padding: 13px 19px; } +.art-typing i { background: var(--accent); width: 5px; height: 5px; border-radius: 50%; } +.art-orbit { position: absolute; right: -45px; top: 5px; width: 11px; height: 11px; background: var(--accent); border-radius: 50%; box-shadow: 0 0 0 9px #ffe13508; } +.intro-footer { font-size: 11px; color: var(--muted); display: flex; align-items: center; gap: 9px; margin-top: 38px; position: relative; } +.status-dot { height: 6px; width: 6px; background: var(--accent); border-radius: 50%; } +.auth-side { background: #2c2c2a; border-left: 1px solid var(--border); display: flex; flex-direction: column; justify-content: center; align-items: center; padding: 50px 64px 25px; min-height: 760px; } +.auth-card { width: 100%; max-width: 360px; } +.auth-switch { display: flex; padding: 5px; background: #222222; border: 1px solid #404037; border-radius: 14px; margin-bottom: 42px; } +.auth-switch button { width: 50%; background: transparent; border: 0; border-radius: 9px; color: var(--muted); padding: 11px; font-size: 12px; font-weight: 600; } +.auth-switch .active { background: var(--accent); color: #262626; box-shadow: 0 3px 12px #00000018; } +.auth-card h2 { font-weight: 650; font-size: 40px; letter-spacing: -1.7px; line-height: 1.15; margin: 12px 0; } +.auth-card .muted { margin: 13px 0 30px; } +.auth-card form { display: grid; gap: 20px; } +.auth-card .wide { margin-top: 5px; justify-content: space-between; } +.auth-card .wide > span { font-size: 21px; line-height: 1; } +.auth-footnote { font-size: 11px; color: var(--muted); margin: 24px 0; text-align: center; } +.auth-bottom { color: var(--muted); font-size: 10px; letter-spacing: .6px; margin-top: 40px; } + +/* Conversations */ +.app-shell { display: grid; grid-template-columns: 310px minmax(0,1fr); height: calc(100svh - 44px); max-width: 1440px; margin: 22px auto; border: 1px solid #46463c; border-radius: 24px; overflow: hidden; box-shadow: 0 20px 70px #00000025; background: var(--paper); } +.sidebar { min-height: 0; background: #222222; border-right: 1px solid var(--border); display: flex; flex-direction: column; padding: 29px 19px 0; } +.sidebar-top { display: flex; align-items: center; justify-content: space-between; padding: 0 9px; } +.sidebar .brand { font-size: 28px; } +.sidebar .brand-mark { width: 32px; height: 32px; border-radius: 10px; } +.sidebar-heading { display: flex; justify-content: space-between; align-items: center; padding: 35px 9px 22px; } +.sidebar-heading .eyebrow { font-size: 9px; letter-spacing: 1.7px; } +.sidebar-heading h2 { margin: 6px 0 0; font-size: 22px; font-weight: 650; letter-spacing: -.7px; } +.count { font-size: 11px; font-weight: 600; background: #ffe13516; border: 1px solid #ffe13525; border-radius: 7px; margin-left: 9px; padding: 3px 7px; vertical-align: middle; color: var(--accent); } +.count:empty { display: none; } +.search-field { display: flex; align-items: center; background: #2d2d2b; border: 1px solid #414139; border-radius: 12px; margin: 0 9px 22px; padding: 0 11px; gap: 8px; } +.search-field > span:not(.visually-hidden) { font-size: 25px; line-height: 1; color: var(--muted); } +.search-field input { border: 0; background: transparent; padding: 12px 0; font-size: 12px; box-shadow: none; } +.search-field:focus-within { border-color: var(--accent); } +.chat-list { flex: 1; overflow: auto; min-height: 0; scrollbar-width: thin; scrollbar-color: #646451 transparent; } +.chat-row { display: flex; align-items: center; gap: 13px; position: relative; border: 1px solid transparent; background: transparent; text-align: left; padding: 15px 11px; width: 100%; border-radius: 14px; color: var(--ink); margin-bottom: 6px; transition: background .18s, border-color .18s; } +.chat-row:hover { background: #2e2e29; } +.chat-row.active { background: #ffe1350f; border-color: #ffe13540; } +.chat-row.active::after { content: ""; position: absolute; right: 11px; height: 6px; width: 6px; border-radius: 50%; background: var(--accent); box-shadow: 0 0 0 4px #ffe1350b; } +.avatar { display: flex; align-items: center; justify-content: center; width: 43px; height: 43px; border-radius: 14px; background: #45432a; color: var(--accent); font-size: 14px; font-weight: 650; flex-shrink: 0; letter-spacing: -.5px; border: 1px solid #ffe1351a; } +.avatar.tone-1 { background: #4b3e2a; color: #ffd68a; border-color: #ffd68a20; } +.avatar.tone-2 { background: #3b4032; color: #d9df9d; border-color: #d9df9d20; } +.avatar.tone-3 { background: #493b36; color: #edc5a5; border-color: #edc5a520; } +.chat-row.active .avatar { background: var(--accent); color: #262626; border-color: transparent; } +.chat-row-text { display: grid; gap: 6px; min-width: 0; flex: 1; } +.chat-row strong { font-size: 13px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; padding-right: 10px; } +.chat-row small { font-size: 11px; color: var(--muted); } +.list-empty { font-size: 12px; text-align: center; line-height: 1.7; color: var(--muted); padding: 20px 15px; } +.profile { border-top: 1px solid var(--border); display: flex; align-items: center; gap: 6px; margin-top: 12px; padding: 20px 7px; } +.profile-main { display: flex; align-items: center; gap: 11px; text-align: left; background: none; border: 0; padding: 0; min-width: 0; flex: 1; color: var(--ink); } +.profile .avatar { border-radius: 50%; background: #39392c; color: var(--accent); width: 37px; height: 37px; font-size: 12px; } +.profile-text { display: grid; gap: 5px; min-width: 0; } +.profile-text strong { font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: 600; } +.profile-text > span { font-size: 10px; color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.workspace { min-width: 0; min-height: 0; position: relative; background: var(--paper); } +.welcome { height: 100%; display: flex; align-items: center; justify-content: center; flex-direction: column; text-align: center; position: relative; padding: 35px; background: radial-gradient(ellipse at center, #ffe13505, transparent 70%); } +.welcome-symbol { width: 110px; height: 110px; background: #ffe1350b; border: 1px solid #ffe13529; border-radius: 34px; position: relative; display: flex; align-items: center; justify-content: center; margin-bottom: 34px; transform: rotate(-6deg); } +.welcome-symbol svg { width: 44px; height: 44px; color: var(--accent); stroke-width: 1.4; transform: rotate(6deg); } +.tiny-dot { position: absolute; width: 17px; height: 17px; right: -4px; top: 4px; border-radius: 50%; background: var(--accent); border: 4px solid var(--paper); } +.welcome .eyebrow { font-size: 9px; letter-spacing: 1.5px; } +.welcome h1 { font-weight: 650; font-size: 43px; letter-spacing: -1.7px; line-height: 1.2; margin: 18px 0; } +.welcome p { font-size: 13px; line-height: 1.8; color: var(--muted); margin: 0 0 27px; } +.welcome .button svg { width: 17px; height: 17px; } +.welcome-bottom { position: absolute; bottom: 30px; font-size: 10px; color: var(--muted); letter-spacing: .4px; } +.conversation { height: 100%; display: flex; flex-direction: column; } +.chat-header { display: flex; align-items: center; gap: 14px; padding: 21px 30px; border-bottom: 1px solid var(--border); min-height: 90px; background: #292929; } +.chat-header .chat-avatar { height: 43px; width: 43px; } +.chat-heading { flex: 1; min-width: 0; } +.chat-heading h2 { font-size: 17px; font-weight: 650; margin: 0 0 6px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; letter-spacing: -.3px; } +.chat-heading span { font-size: 11px; color: var(--muted); } +.message-region { position: relative; flex: 1; min-height: 0; display: flex; } +.message-scroll { flex: 1; min-height: 0; overflow: auto; padding: 12px 32px 24px; scrollbar-width: thin; scrollbar-color: #646451 transparent; scroll-behavior: auto; background: radial-gradient(ellipse at 100% 100%, #ffe13504, transparent 70%); } +.history-control { text-align: center; min-height: 18px; } +.message-list { display: flex; flex-direction: column; gap: 14px; } +.date-separator { align-self: center; background: #30302c; border: 1px solid #414139; border-radius: 20px; padding: 6px 12px; text-align: center; color: var(--muted); font-size: 10px; letter-spacing: .3px; margin: 20px 0 12px; } +.message { max-width: 76%; align-self: flex-start; display: grid; gap: 6px; } +.message.mine { align-self: flex-end; } +.message-author { font-size: 10px; color: var(--muted); padding-left: 8px; } +.message-bubble { background: #343430; border: 1px solid #46463b; border-radius: 17px 17px 17px 5px; padding: 13px 16px 10px; min-width: 90px; box-shadow: 0 4px 14px #00000008; } +.mine .message-bubble { background: var(--accent); color: #262626; border: 1px solid var(--accent); border-radius: 17px 17px 5px 17px; } +.message-text { font-size: 14px; white-space: pre-wrap; overflow-wrap: anywhere; line-height: 1.65; margin: 0; } +.message-time { font-size: 10px; display: block; text-align: right; color: var(--muted); margin-top: 7px; } +.mine .message-time { color: #5c5324; } +.empty-conversation { text-align: center; position: relative; top: 28%; font-size: 13px; color: var(--muted); line-height: 1.9; } +.composer { display: grid; grid-template-columns: minmax(0,1fr) 46px; gap: 10px; align-items: end; border-top: 1px solid var(--border); padding: 20px 29px 16px; background: #292929; } +.composer textarea { border: 1px solid #4b4b42; background: #30302d; border-radius: 13px; padding: 13px 15px; font-size: 14px; resize: none; max-height: 140px; min-height: 47px; scrollbar-width: thin; } +.send-button { display: flex; align-items: center; justify-content: center; background: var(--accent); border: 0; color: #262626; width: 46px; height: 47px; border-radius: 13px; margin-bottom: 1px; transition: background .18s; } +.send-button:hover { background: var(--accent-hover); } +.send-button:disabled { background: #444439; opacity: 1; color: #abab95; } +.send-button svg { height: 21px; width: 21px; } +.composer-note { grid-column: 1/-1; display: flex; justify-content: space-between; font-size: 9px; color: var(--muted); padding: 2px 3px; gap: 15px; } +.composer-note .over-limit { color: var(--danger); } +.mobile-only { display: none; } +.toast { position: fixed; bottom: 27px; left: 50%; transform: translateX(-50%); background: var(--accent); color: #262626; border: 1px solid #ffec7d; box-shadow: 0 8px 35px #00000030; border-radius: 13px; padding: 13px 20px; font-size: 12px; line-height: 1.5; max-width: min(90%,520px); z-index: 20; } +.toast.error { background: #452f2d; color: var(--danger); border-color: #70453e; } + +/* Dialogs */ +dialog { border: 1px solid #575744; border-radius: 22px; padding: 28px; max-width: 440px; width: calc(100% - 36px); color: var(--ink); background: #2c2c2a; box-shadow: 0 24px 100px #00000060; } +dialog::backdrop { background: #151515aa; backdrop-filter: blur(6px); } +.dialog-heading { display: flex; align-items: center; justify-content: space-between; gap: 15px; } +.dialog-heading h2 { font-size: 25px; font-weight: 650; letter-spacing: -.8px; margin: 0; } +.dialog-heading .icon-button { width: 30px; height: 30px; } +dialog .muted { font-size: 12px; margin: 14px 0 25px; } +dialog form { display: grid; gap: 20px; } +.dialog-actions { display: flex; justify-content: flex-end; gap: 10px; margin-top: 3px; } +#my-id { font-size: 12px; font-family: ui-monospace, monospace; background: #242424; } +#profile-dialog .wide { margin-top: 17px; } +.members-list { display: grid; gap: 16px; padding-top: 25px; } +.member-item { display: grid; gap: 8px; } +.member-item strong { font-size: 13px; font-weight: 550; } +.member-item code { font-size: 11px; overflow-wrap: anywhere; color: var(--muted); background: #242424; border: 1px solid var(--border); padding: 12px; border-radius: 10px; } + +/* Optional API explanation panel */ +.diagnostics-toggle { display: flex; align-items: center; justify-content: center; gap: 8px; background: transparent; border: 1px solid #515143; border-radius: 11px; padding: 11px 12px; color: var(--muted); font-size: 11px; font-weight: 550; } +.diagnostics-toggle svg { width: 15px; height: 15px; } +.diagnostics-toggle:hover, .diagnostics-toggle[aria-expanded=true] { background: #ffe1350d; border-color: #ffe13565; color: var(--accent); } +.auth-bottom .diagnostics-toggle { margin: 15px auto 0; } +.sidebar-diagnostics { margin: 10px 9px 0; flex-shrink: 0; } +.diagnostics-panel { position: fixed; z-index: 15; right: 30px; top: 108px; width: 330px; max-height: min(56svh,490px); overflow: auto; background: #2c2c2a; border: 1px solid #66603a; border-radius: 20px; box-shadow: 0 18px 55px #00000030; padding: 20px; scrollbar-width: thin; scrollbar-color: #646451 transparent; } +.diagnostics-heading { display: flex; justify-content: space-between; align-items: center; gap: 10px; margin-bottom: 18px; } +.diagnostics-heading .eyebrow { font-size: 9px; letter-spacing: 1.4px; } +.diagnostics-heading h2 { font-size: 19px; font-weight: 650; letter-spacing: -.5px; margin: 5px 0 0; } +.diagnostics-heading .icon-button { width: 30px; height: 30px; } +.diagnostics-label { display: block; font-size: 10px; color: var(--muted); margin-bottom: 6px; } +.diagnostics-summary { display: grid; grid-template-columns: minmax(0,1fr) auto; gap: 14px; background: #ffe1350c; border: 1px solid #ffe13520; border-radius: 12px; padding: 12px; } +.diagnostics-summary strong { display: block; font-size: 11px; overflow-wrap: anywhere; } +.diagnostics-history { padding: 16px 0; border-bottom: 1px solid var(--border); } +.diagnostics-history > strong { display: block; font-size: 13px; overflow-wrap: anywhere; } +.diagnostics-history > p { font-size: 11px; color: var(--muted); margin: 8px 0 0; } +.diagnostics-request { padding-top: 16px; } +.diagnostics-section-heading { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 12px; } +.diagnostics-section-heading h3 { font-size: 12px; margin: 0; font-weight: 600; } +.diagnostics-section-heading time { font-size: 10px; color: var(--muted); } +.diagnostics-request-line { display: flex; align-items: center; gap: 8px; } +.diagnostics-method, .diagnostics-status { font: 600 11px ui-monospace, monospace; padding: 6px 8px; border-radius: 6px; background: #404036; color: var(--accent); } +.diagnostics-status { background: var(--accent); color: #262626; } +.diagnostics-status.failed { background: #56332e; color: var(--danger); } +.diagnostics-path { display: block; font: 11px/1.6 ui-monospace, monospace; overflow-wrap: anywhere; color: var(--muted); margin-top: 10px; } +.diagnostics-result { font-size: 12px; line-height: 1.6; color: var(--accent); margin: 10px 0 14px; } +.diagnostics-result.failed { color: var(--danger); } +.diagnostics-metrics { display: grid; grid-template-columns: 1fr 1fr; margin: 0 0 14px; gap: 12px; } +.diagnostics-metrics dt { font-size: 10px; color: var(--muted); margin-bottom: 6px; } +.diagnostics-metrics dd { font: 550 12px ui-monospace, monospace; margin: 0; color: var(--ink); } +.diagnostics-request-id { display: block; font: 10px/1.7 ui-monospace, monospace; overflow-wrap: anywhere; color: var(--muted); } +.diagnostics-previous { list-style: none; margin: 15px 0 0; padding: 12px 0 0; border-top: 1px solid var(--border); display: grid; gap: 10px; } +.diagnostics-previous li { display: flex; gap: 8px; align-items: center; min-width: 0; } +.diagnostics-mini-status { font: 550 10px ui-monospace, monospace; color: var(--accent); min-width: 23px; } +.diagnostics-mini-status.failed { color: var(--danger); } +.diagnostics-previous code { font: 10px ui-monospace, monospace; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.diagnostics-background { font-size: 10px; color: var(--muted); margin: 12px 0 0; line-height: 1.7; } +.diagnostics-note { font-size: 11px; color: var(--muted); line-height: 1.7; margin: 0; } +.diagnostics-footnote { border-top: 1px solid var(--border); padding-top: 12px; margin-top: 14px; font-size: 10px; } + +@media (min-width: 1490px) { + .app-shell { height: calc(100svh - 64px); margin: 32px auto; } +} +@media (max-width: 1100px) { + .intro { padding: 40px 38px; } + .auth-side { padding: 40px 35px; } + .app-shell { margin: 14px; height: calc(100svh - 28px); grid-template-columns: 280px minmax(0,1fr); } + .conversation-art { margin-left: 0; width: 290px; } + .intro h1 { font-size: 56px; } + .sidebar { padding-left: 14px; padding-right: 14px; } + .message-scroll { padding-left: 24px; padding-right: 24px; } +} +@media (max-width: 720px) { + .auth-layout { display: block; } + .intro { min-height: 0; padding: 28px; } + .intro-copy { margin-top: 30px; } + .intro h1 { font-size: 42px; letter-spacing: -2px; line-height: 1.08; margin: 14px 0 0; } + .intro h1 br { display: none; } + .intro-copy .eyebrow { font-size: 9px; } + .intro-copy p, .conversation-art, .intro-footer { display: none; } + .auth-side { min-height: 0; padding: 30px 28px; align-items: center; border-left: 0; border-top: 1px solid var(--border); } + .auth-card { max-width: 440px; } + .auth-switch { margin-bottom: 28px; } + .auth-card h2 { font-size: 32px; } + .auth-card h2 br { display: none; } + .auth-card .muted { margin-bottom: 22px; } + .auth-card form { gap: 17px; } + .auth-bottom { margin-top: 20px; } + .app-shell { margin: 0; border: 0; border-radius: 0; height: 100svh; display: block; } + .sidebar { height: 100%; width: 100%; padding: 25px 18px 0; border: 0; } + .sidebar-heading { padding-top: 30px; } + .workspace { display: none; height: 100%; } + .app-shell.chat-open .sidebar { display: none; } + .app-shell.chat-open .workspace { display: block; } + .welcome { display: none; } + .mobile-only { display: flex; } + .chat-header { padding: 15px; gap: 7px; min-height: 75px; } + .chat-header .avatar { width: 35px; height: 35px; border-radius: 11px; } + .chat-heading h2 { font-size: 14px; } + .chat-header .icon-button { width: 31px; height: 31px; } + .chat-header .icon-button svg { width: 19px; height: 19px; } + .message-scroll { padding: 10px 16px 20px; } + .message { max-width: 88%; } + .composer { padding: 14px 16px max(13px, env(safe-area-inset-bottom)); } + .composer-note { font-size: 9px; } + .composer-note > span:first-child { max-width: 70%; } + .profile { padding-bottom: max(18px, env(safe-area-inset-bottom)); } + .toast { bottom: 20px; } + .diagnostics-panel { top: 83px; right: 12px; width: calc(100% - 24px); max-height: 52svh; padding: 16px; } + .sidebar-diagnostics { margin-top: 9px; } +} +@media (min-width: 721px) { + body:not(.has-session) .diagnostics-panel { right: 24px; left: auto; } +} +@media (min-width: 1100px) { + .diagnostics-open.has-session .app-shell { margin-left: 22px; margin-right: 380px; } + .diagnostics-open.has-session .diagnostics-panel { top: 22px; max-height: calc(100svh - 44px); } +} +@media (prefers-reduced-motion: reduce) { + * { transition: none !important; scroll-behavior: auto !important; } +} + +/* Password controls and the animated SVG character. */ +.password-field { position: relative; display: block; } +.password-field input { padding-right: 47px; } +.password-toggle { position: absolute; right: 7px; top: 7px; width: 33px; height: 33px; border: 0; background: transparent; border-radius: 9px; color: var(--muted); display: flex; align-items: center; justify-content: center; } +.password-toggle:hover, .password-toggle[aria-pressed=true] { color: var(--accent); background: #ffe1350c; } +.password-toggle svg { width: 18px; height: 18px; } +/* One SVG mascot; CSS handles poses and the browser handles animation frames. */ +.mascot-stage { position: relative; width: 350px; max-width: 100%; height: 280px; margin: 20px 0 0 5px; pointer-events: none; isolation: isolate; --scene-surface: #262626; --gaze-x: 0px; --gaze-y: 0px; } +.spirit-svg { stroke: none; position: absolute; left: 0; bottom: 0; width: 285px; height: 285px; overflow: visible; z-index: 2; } +.spirit-motion { animation: spirit-breathe 4.5s ease-in-out infinite; } +.spirit-lean { transform-origin: 150px 268px; transition: transform .65s cubic-bezier(.22,1,.36,1); } +.spirit-eye { transform-box: fill-box; transform-origin: center; animation: spirit-blink 7s infinite; } +.spirit-eye-right { animation-delay: .1s; } +.spirit-pupil { transform: translate(var(--gaze-x), var(--gaze-y)); transition: transform .16s ease-out; } +.spirit-hand { transform-box: view-box; transition: transform .55s cubic-bezier(.22,1,.36,1); } +.spirit-gasp { opacity: 0; } +.mascot-stage[data-mood=looking] .spirit-lean { transform: translate(8px,-3px) rotate(3deg); } +.mascot-stage.is-curious .spirit-motion { animation: spirit-step .42s ease-in-out 3; } +.mascot-stage:is([data-mood=private],[data-mood=short],[data-mood=revealed]) .spirit-lean { transform: rotate(-4deg); } +.mascot-stage:is([data-mood=private],[data-mood=short],[data-mood=revealed]) .spirit-hand-left { transform: translate(28px,-37px) rotate(3deg); } +.mascot-stage:is([data-mood=private],[data-mood=short]) .spirit-hand-right { transform: translate(-28px,-25px) rotate(-3deg); } +.mascot-stage:is([data-mood=private],[data-mood=short]) .spirit-eye { animation: none; scale: 1 .08; } +.mascot-stage[data-mood=revealed] .spirit-hand-right { transform: translate(-28px,-39px) rotate(-3deg); } +.mascot-stage[data-mood=revealed] .spirit-eye { animation: none; scale: 1 .08; } +.mascot-stage[data-mood=pending] .spirit-motion { animation: spirit-breathe 1.1s ease-in-out infinite; } +.mascot-stage[data-mood=error] .spirit-motion { animation: spirit-shake .4s ease-in-out 2; } +.mascot-stage[data-mood=success] .spirit-motion { animation: spirit-hop .65s ease-in-out; } +.mascot-stage.is-sleepy .spirit-eye { animation: none; scale: 1 .2; } +.mascot-stage.is-sleepy .spirit-lean { transform: rotate(-5deg); } +.mascot-stage.is-scared .spirit-motion { animation: spirit-shake .25s ease-in-out infinite; } +.mascot-stage.is-scared :is(.spirit-smile,.kolo-tooth) { opacity: 0; } +.mascot-stage.is-scared .spirit-gasp { opacity: 1; } +.mascot-stage:not(.is-visible) * { animation-play-state: paused; } +.mascot-conversation { position: absolute; inset: 0; z-index: 0; } +.mascot-bubble { position: absolute; border-radius: 17px; animation: spirit-float 5s ease-in-out infinite; } +.mascot-bubble-filled { left: 247px; top: 20px; width: 88px; height: 50px; background: var(--accent); display: flex; align-items: center; justify-content: center; gap: 6px; rotate: -6deg; } +.mascot-bubble-filled::after { content: ""; position: absolute; bottom: -7px; left: 18px; width: 17px; height: 17px; background: var(--accent); clip-path: polygon(0 0,100% 0,0 100%); } +.mascot-bubble-filled span { width: 5px; height: 5px; border-radius: 50%; background: #262626; animation: spirit-typing 1.8s ease-in-out infinite; } +.mascot-bubble-filled span:nth-child(2) { animation-delay: .16s; } +.mascot-bubble-filled span:nth-child(3) { animation-delay: .32s; } +.mascot-bubble-outline { left: 265px; top: 107px; width: 77px; height: 55px; border: 1.5px solid #ffe13555; background: var(--scene-surface); rotate: 7deg; animation-delay: -2.5s; padding: 18px 15px; } +.mascot-bubble-outline::after { content: ""; position: absolute; bottom: -6px; right: 16px; width: 11px; height: 11px; border-right: 1.5px solid #ffe13555; border-bottom: 1.5px solid #ffe13555; background: var(--scene-surface); rotate: 45deg; } +.mascot-bubble-outline i { display: block; height: 2px; width: 100%; margin-bottom: 8px; border-radius: 2px; background: #ffe13555; } +.mascot-bubble-outline i:last-child { width: 65%; } +@keyframes spirit-breathe { 0%,100% { transform: translateY(0); } 50% { transform: translateY(-3px); } } +@keyframes spirit-step { 0%,100% { transform: translateY(0); } 50% { transform: translateY(-6px); } } +@keyframes spirit-blink { 0%,42%,46%,100% { scale: 1 1; } 44% { scale: 1 .08; } } +@keyframes spirit-peek { 0%,20%,76%,100% { scale: 1 .12; } 30%,66% { scale: 1 1; } } +@keyframes spirit-shake { 0%,100% { transform: translateX(0); } 25% { transform: translateX(-3px); } 75% { transform: translateX(3px); } } +@keyframes spirit-hop { 0%,100% { transform: translateY(0); } 25% { transform: translateY(3px); } 60% { transform: translateY(-15px); } } +@keyframes spirit-float { 0%,100% { translate: 0 0; } 50% { translate: 0 -5px; } } +@keyframes spirit-typing { 0%,55%,100% { translate: 0 0; opacity: .4; } 28% { translate: 0 -3px; opacity: 1; } } + +.scenario-section { padding: 17px 0 15px; border-bottom: 1px solid var(--border); } +.scenario-section h3 { font-size: 13px; margin: 0 0 9px; } +.scenario-description { font-size: 10px; line-height: 1.7; color: var(--muted); margin: 0 0 12px; } +.scenario-actions { display: grid; gap: 8px; } +.scenario-actions .button { padding: 11px 10px; font-size: 11px; } +.scenario-status { font-size: 11px; line-height: 1.6; margin: 12px 0 0; color: var(--ink); } +.scenario-status.failed { color: var(--danger); } +.scenario-scope { margin: 12px 0 0; } +.scenario-steps { list-style: none; padding: 0; margin: 12px 0 0; display: grid; gap: 8px; max-height: 245px; overflow: auto; scrollbar-width: thin; scrollbar-color: #646451 transparent; } +.scenario-step { border: 1px solid var(--border); border-radius: 10px; background: #262626; padding: 10px; } +.scenario-step[data-state=failed] { border-color: #9a5b51; } +.scenario-step summary { display: flex; align-items: flex-start; gap: 8px; cursor: pointer; font-size: 11px; line-height: 1.5; list-style: none; } +.scenario-step summary::before { content: "▸"; color: var(--muted); } +.scenario-step[open] summary::before { content: "▾"; } +.scenario-step summary::-webkit-details-marker { display: none; } +.scenario-step-badge { flex-shrink: 0; color: var(--accent); font: 650 10px/1.65 ui-monospace, monospace; } +.scenario-step[data-state=failed] .scenario-step-badge { color: var(--danger); } +.scenario-step[data-state=pending] .scenario-step-badge { color: var(--muted); } +.scenario-step p { color: var(--muted); font-size: 10px; line-height: 1.7; margin: 9px 0 0; } +.scenario-step code { display: block; color: var(--muted); font: 10px/1.7 ui-monospace, monospace; overflow-wrap: anywhere; margin-top: 7px; } +@media (max-width: 720px) { + .auth-card .mascot-stage { width: 100%; height: 166px; margin: -14px auto 14px; --scene-surface: #2c2c2a; } + .spirit-svg { width: 178px; height: 178px; left: calc(50% - 105px); } + .mascot-bubble { border-radius: 13px; } + .mascot-bubble-filled { left: calc(50% + 45px); top: 9px; width: 58px; height: 34px; gap: 4px; } + .mascot-bubble-filled span { width: 4px; height: 4px; } + .mascot-bubble-filled::after { width: 12px; height: 12px; bottom: -5px; left: 13px; } + .mascot-bubble-outline { left: calc(50% + 52px); top: 66px; width: 54px; height: 40px; padding: 13px 10px; } + .mascot-bubble-outline i { margin-bottom: 6px; } + .mascot-bubble-outline::after { width: 8px; height: 8px; bottom: -5px; right: 12px; } + .intro h1 { font-size: 36px; } + .intro { padding-bottom: 18px; } + .scenario-steps { max-height: 175px; } +} +.diagnostics-origin { margin-top: 10px; } + +.auth-card form { margin-top: 24px; } +.auth-card .muted + form { margin-top: 0; } +.diagnostics-help { border-top: 1px solid var(--border); margin-top: 14px; padding-top: 12px; } +.diagnostics-help summary { color: var(--muted); font-size: 10px; cursor: pointer; } +.diagnostics-help .diagnostics-note { margin-top: 10px; font-size: 10px; } +@media (prefers-reduced-motion: reduce) { + .mascot-stage *, .mascot-stage *::before { animation: none !important; transition: none !important; } +} + +/* Keep the reader's position while messages arrive below. */ +.jump-latest { position: absolute; right: 24px; bottom: 16px; border: 1px solid #ffe13555; background: #36362d; color: var(--accent); padding: 10px 15px; border-radius: 20px; font-size: 12px; box-shadow: 0 5px 20px #0004; z-index: 2; } +.jump-latest:hover { background: #424234; } +.message.grouped { margin-top: -9px; } +.message.grouped .message-bubble { border-top-left-radius: 8px; } +.message.mine.grouped .message-bubble { border-top-left-radius: 17px; border-top-right-radius: 8px; } +@media (max-width: 720px) { .jump-latest { right: 14px; bottom: 12px; } } + +.welcome-illustration { width: 260px; max-width: 75%; height: auto; margin-bottom: 12px; } +.welcome h1 { font-size: 38px; margin: 14px 0; } +.empty-conversation { top: auto; padding: 35px 16px; color: #d6d6c9; } +.empty-conversation img { width: 165px; max-width: 70%; height: auto; } +.empty-conversation p { color: var(--ink); font-size: 16px; margin: 15px 0 8px; } +.empty-conversation span { color: var(--muted); font-size: 12px; } +.message-bubble { color: #e5e5dc; } +.mine .message-bubble { color: #262626; } +.composer-note { font-size: 10px; line-height: 1.5; } +@media (max-width: 720px) { .welcome-illustration { width: 200px; } .welcome h1 { font-size: 32px; } } +.message-scroll { background-image: url('/assets/chat-pattern.svg'); background-size: 180px 160px; } + +/* Head, ears and mushrooms remain independent of the body. */ +.kolo-head { transform-origin: 151px 202px; transition: transform .65s cubic-bezier(.22,1,.36,1); } +.kolo-ear { transform-origin: 150px 135px; transition: transform .7s ease; } +.kolo-mushrooms { transform-origin: 153px 83px; animation: kolo-sway 6s ease-in-out infinite; } +.mascot-stage[data-mood=looking] .kolo-head { transform: rotate(4deg) translate(3px,-2px); } +.mascot-stage[data-mood=looking] .kolo-ear-right { transform: rotate(-3deg); } +.mascot-stage:is([data-mood=private],[data-mood=short],[data-mood=revealed]) .kolo-head { transform: translate(-5px,2px) rotate(-9deg); } +.mascot-stage:is([data-mood=private],[data-mood=short],[data-mood=revealed]) .spirit-face { opacity: .65; } +.mascot-stage[data-mood=success] .kolo-ear { transform: rotate(-3deg); } +.mascot-stage.is-sleepy .kolo-head { transform: rotate(-6deg) translateY(3px); } +.auth-error-art { float: right; width: 66px; height: 66px; object-fit: contain; margin: 10px 0 0 10px; } +.state-error { text-align: center; padding: 28px 18px; color: var(--muted); } +.state-error img { width: 160px; max-width: 65%; height: auto; } +.state-error h2, .state-error h3 { color: var(--ink); font-size: 19px; font-weight: 600; margin: 14px 0 10px; } +.state-error p { font-size: 12px; line-height: 1.7; margin: 0 0 18px; } +.state-error .button { font-size: 12px; padding: 11px 18px; } +.welcome.state-error { height: 100%; } +@keyframes kolo-sway { 0%,100% { transform: rotate(-1deg); } 50% { transform: rotate(2deg); } } +@media (max-width: 720px) { + .state-error img { width: 130px; } + .welcome-illustration { width: 200px; max-height: 24svh; object-fit: contain; } +} +@media (prefers-reduced-motion: reduce) { + .kolo-mushrooms { animation: none; } +} + +.message-scroll:has(> :is(.empty-conversation,.state-error):not([hidden])) { display: flex; flex-direction: column; } +.message-scroll > :is(.empty-conversation,.state-error) { margin: auto 0; } diff --git a/src/Messenger.Api/wwwroot/app.js b/src/Messenger.Api/wwwroot/app.js new file mode 100644 index 00000000..3d6788a8 --- /dev/null +++ b/src/Messenger.Api/wwwroot/app.js @@ -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); diff --git a/src/Messenger.Api/wwwroot/assets/chat-pattern.svg b/src/Messenger.Api/wwwroot/assets/chat-pattern.svg new file mode 100644 index 00000000..27e307c1 --- /dev/null +++ b/src/Messenger.Api/wwwroot/assets/chat-pattern.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/src/Messenger.Api/wwwroot/assets/kolovertysh-empty-320.webp b/src/Messenger.Api/wwwroot/assets/kolovertysh-empty-320.webp new file mode 100644 index 00000000..567ace88 Binary files /dev/null and b/src/Messenger.Api/wwwroot/assets/kolovertysh-empty-320.webp differ diff --git a/src/Messenger.Api/wwwroot/assets/kolovertysh-error-320.webp b/src/Messenger.Api/wwwroot/assets/kolovertysh-error-320.webp new file mode 100644 index 00000000..b085ea9b Binary files /dev/null and b/src/Messenger.Api/wwwroot/assets/kolovertysh-error-320.webp differ diff --git a/src/Messenger.Api/wwwroot/assets/kolovertysh-welcome-320.webp b/src/Messenger.Api/wwwroot/assets/kolovertysh-welcome-320.webp new file mode 100644 index 00000000..7f8c3609 Binary files /dev/null and b/src/Messenger.Api/wwwroot/assets/kolovertysh-welcome-320.webp differ diff --git a/src/Messenger.Api/wwwroot/assets/kolovertysh-welcome-640.webp b/src/Messenger.Api/wwwroot/assets/kolovertysh-welcome-640.webp new file mode 100644 index 00000000..3a4e5967 Binary files /dev/null and b/src/Messenger.Api/wwwroot/assets/kolovertysh-welcome-640.webp differ diff --git a/src/Messenger.Api/wwwroot/assets/kolovertysh.svg b/src/Messenger.Api/wwwroot/assets/kolovertysh.svg new file mode 100644 index 00000000..29d1871a --- /dev/null +++ b/src/Messenger.Api/wwwroot/assets/kolovertysh.svg @@ -0,0 +1,63 @@ + diff --git a/src/Messenger.Api/wwwroot/avatars.js b/src/Messenger.Api/wwwroot/avatars.js new file mode 100644 index 00000000..2b68db1d --- /dev/null +++ b/src/Messenger.Api/wwwroot/avatars.js @@ -0,0 +1,42 @@ +const svgNS = "http://www.w3.org/2000/svg"; +const palettes = [ + ["#394639", "#c2d39b"], ["#474033", "#e5c38b"], + ["#3c414d", "#b9c9e4"], ["#493b42", "#e4b6c5"], + ["#444333", "#e0d29a"], ["#354647", "#afd5ce"] +]; + +function element(tag, attributes = {}) { + const node = document.createElementNS(svgNS, tag); + for (const [key, value] of Object.entries(attributes)) node.setAttribute(key, value); + return node; +} + +export function initials(name) { + return (name.match(/[\p{L}\p{N}]+/gu) || []).slice(0, 2) + .map(part => Array.from(part)[0]).join("").toUpperCase(); +} + +export function paintAvatar(target, id, name) { + if (target.dataset.identity === id && target.dataset.name === name) return; + let hash = 2166136261; + for (const character of id) hash = Math.imul(hash ^ character.charCodeAt(0), 16777619) >>> 0; + const [background, foreground] = palettes[hash % palettes.length]; + const svg = element("svg", { viewBox: "0 0 64 64", class: "avatar-art", "aria-hidden": "true" }); + svg.append(element("rect", { width: 64, height: 64, rx: 20, fill: background })); + const patterns = [ + "M-7 18Q21-7 39 9T74 18M-8 49Q21 27 40 44T74 49", + "M-3 3 28 3 64 39M-3 21 21 21 64 64M-3 39 14 39 39 64", + "M7 59Q-6 24 25 8Q60-7 70 26M-2 42Q23 69 54 49Q75 31 52 8" + ]; + svg.append(element("path", { d: patterns[(hash >>> 4) % patterns.length], fill: "none", + stroke: foreground, "stroke-width": 6, opacity: .12 })); + svg.append(element("circle", { cx: 50, cy: 13, r: 3, fill: foreground, opacity: .5 })); + const label = element("text", { x: 32, y: 34, fill: foreground, + "text-anchor": "middle", "dominant-baseline": "middle", "font-size": 22, + "font-family": "system-ui, sans-serif", "font-weight": 650 }); + label.textContent = initials(name); + svg.append(label); + target.replaceChildren(svg); + target.dataset.identity = id; + target.dataset.name = name; +} diff --git a/src/Messenger.Api/wwwroot/cluster-view.js b/src/Messenger.Api/wwwroot/cluster-view.js new file mode 100644 index 00000000..ab9f1588 --- /dev/null +++ b/src/Messenger.Api/wwwroot/cluster-view.js @@ -0,0 +1,90 @@ +const $ = id => document.getElementById(id); +const observed = new Map(); +const cards = new Map(); +let signedIn = false, lastInstance = null, total = 0, pulseTimer; + +export function setClusterIdentity(active) { + signedIn = active; + observed.clear(); cards.clear(); total = 0; lastInstance = null; + $('cluster-instances').replaceChildren(); + $('cluster-status').textContent = active ? 'Получаем heartbeat…' : 'Схема доступна после входа'; + $('cluster-detail').textContent = 'Подсветка — реальный X-Instance-Id ответа.'; + $('cluster-copy').disabled = true; + for (const id of ['cluster-postgres', 'cluster-redis', 'cluster-balancer']) $(id).dataset.state = 'unknown'; +} + +export function observeClusterRequest(entry) { + if (!signedIn || !entry.instanceId) return; + total++; + lastInstance = entry.instanceId; + observed.set(lastInstance, (observed.get(lastInstance) || 0) + 1); + for (const [id, card] of cards) { + card.root.classList.toggle('just-served', id === lastInstance); + card.count.textContent = `${observed.get(id) || 0} / ${total} запросов`; + } + $('cluster-balancer').dataset.state = 'up'; + $('cluster-detail').textContent = `${entry.method} · ${entry.status ?? 'нет ответа'} · ${entry.durationMs} мс → ${lastInstance.slice(0, 8)}`; + clearTimeout(pulseTimer); + pulseTimer = setTimeout(() => { for (const card of cards.values()) card.root.classList.remove('just-served'); }, 1100); +} + +function render(snapshot) { + $('cluster-redis').dataset.state = snapshot.redis_available ? 'up' : 'down'; + $('cluster-postgres').dataset.state = snapshot.postgres_available ? 'up' : 'down'; + if (!snapshot.redis_available) { + $('cluster-status').textContent = 'Redis недоступен · состояние API неизвестно'; + for (const card of cards.values()) { card.root.dataset.state = 'unknown'; card.state.textContent = 'Нет heartbeat'; } + $('cluster-copy').disabled = true; + return; + } + // Keep outages witnessed by this tab, without presenting earlier deployments as new failures. + const visible = snapshot.instances.filter(node => node.ready || cards.has(node.id) || observed.has(node.id)); + const alive = visible.filter(node => node.ready), missing = visible.length - alive.length; + $('cluster-status').textContent = `${alive.length} API в сети${missing ? ` · ${missing} без heartbeat` : ''}`; + const wanted = new Set(visible.map(node => node.id)); + for (const [id, card] of cards) if (!wanted.has(id)) { card.root.remove(); cards.delete(id); } + for (const node of [...visible].sort((a,b) => a.id.localeCompare(b.id))) { + let card = cards.get(node.id); + if (!card) { + const root = document.createElement('div'); root.className = 'cluster-api cluster-node'; root.dataset.instanceId = node.id; + const heading = document.createElement('strong'); heading.textContent = `API · ${node.id.slice(0,8)}`; + const state = document.createElement('span'), count = document.createElement('small'); + root.append(heading, state, count); root.title = `X-Instance-Id: ${node.id}`; + card = {root, state, count}; cards.set(node.id, card); $('cluster-instances').append(root); + } + card.root.dataset.state = node.ready ? 'up' : 'down'; + card.state.textContent = node.ready ? 'В сети' : 'Heartbeat пропал'; + card.count.textContent = `${observed.get(node.id) || 0} / ${total} запросов`; + } + const target = alive.find(node => node.id === lastInstance) || alive[0]; + $('cluster-command').textContent = target ? `python3 scripts/demo-failover.py --instance ${target.id}` : 'Ожидаем работающие API…'; + $('cluster-copy').disabled = alive.length < 2; +} + +export function startClusterView(readSnapshot, getToken) { + let busy = false; + async function refresh() { + const token = getToken(); + if (!token || busy || document.hidden || $('diagnostics-panel').hidden) return; + busy = true; + try { const data = await readSnapshot(); if (token === getToken()) render(data); } + catch { + if (token === getToken()) { + $('cluster-status').textContent = 'Нет свежих данных о кластере'; + $('cluster-balancer').dataset.state = 'unknown'; + $('cluster-postgres').dataset.state = 'unknown'; + $('cluster-redis').dataset.state = 'unknown'; + for (const card of cards.values()) { card.root.dataset.state = 'unknown'; card.state.textContent = 'Нет свежих данных'; } + $('cluster-copy').disabled = true; + } + } finally { busy = false; } + } + new MutationObserver(refresh).observe($('diagnostics-panel'), { attributes: true, attributeFilter: ['hidden'] }); + setInterval(refresh, 2000); + $('cluster-probe').addEventListener('click', refresh); + $('cluster-copy').addEventListener('click', async () => { + try { await navigator.clipboard.writeText($('cluster-command').textContent); $('cluster-copy').textContent = 'Скопировано'; } + catch { $('cluster-copy').textContent = 'Выделите команду ниже'; } + setTimeout(() => { $('cluster-copy').textContent = 'Скопировать команду'; }, 2000); + }); +} diff --git a/src/Messenger.Api/wwwroot/diagnostics.js b/src/Messenger.Api/wwwroot/diagnostics.js new file mode 100644 index 00000000..3299a629 --- /dev/null +++ b/src/Messenger.Api/wwwroot/diagnostics.js @@ -0,0 +1,113 @@ +// Only explicitly selected HTTP metadata reaches this view. Never pass request +// headers, bodies, session objects or raw response JSON into the panel. +import { observeClusterRequest, setClusterIdentity } from '/cluster-view.js'; +const $ = id => document.getElementById(id); +const preferenceKey = "n1k0der.diagnostics"; +const requests = []; +let session = null, history = null, backgroundRequest = null, returnFocus = null; + +function setOpen(open) { + $("diagnostics-panel").hidden = !open; + document.body.classList.toggle("diagnostics-open", open); + document.querySelectorAll("[data-diagnostics-toggle]").forEach(button => button.setAttribute("aria-expanded", String(open))); + try { sessionStorage.setItem(preferenceKey, open ? "on" : "off"); } catch { /* optional preference */ } + if (open) { render(); $("diagnostics-close").focus(); } + else if (returnFocus?.isConnected) returnFocus.focus(); +} + +document.querySelectorAll("[data-diagnostics-toggle]").forEach(button => button.addEventListener("click", () => { + returnFocus = button; + setOpen($("diagnostics-panel").hidden); +})); +$("diagnostics-close").addEventListener("click", () => setOpen(false)); +document.addEventListener("keydown", event => { + if (event.key === "Escape" && !$("diagnostics-panel").hidden && !document.querySelector("dialog[open]")) { + event.preventDefault(); setOpen(false); + } +}); + +export function updateSessionInfo(value) { + setClusterIdentity(Boolean(value)); + session = value ? { name: value.name, expiresAt: value.expiresAt } : null; + document.body.classList.toggle("has-session", Boolean(session)); + if (!$("diagnostics-panel").hidden) renderSession(); +} + +export function updateHistoryInfo(value) { + history = value ? { title: value.title, loaded: value.loaded, hasOlder: value.hasOlder, ready: value.ready } : null; + if (!$("diagnostics-panel").hidden) renderHistory(); +} + +export function recordRequest(value) { + const entry = { + method: value.method, path: value.path.split("?")[0], status: value.status, + authorization: value.authorization, durationMs: value.durationMs, + requestId: value.requestId, instanceId: value.instanceId, outcome: value.outcome, source: value.source, at: new Date() + }; + observeClusterRequest(entry); + if (value.background) backgroundRequest = entry; + else { requests.unshift(entry); requests.length = Math.min(requests.length, 4); } + if (!$("diagnostics-panel").hidden) renderRequests(); +} + +function renderSession() { + $("diagnostics-user").textContent = session?.name || "Вход не выполнен"; + const seconds = session ? Math.max(0, Math.ceil((new Date(session.expiresAt).getTime() - Date.now()) / 1000)) : null; + $("diagnostics-session").textContent = seconds === null ? "-" : seconds === 0 ? "Срок истёк" : `${Math.floor(seconds / 60)} мин ${String(seconds % 60).padStart(2, "0")} с`; +} + +function renderHistory() { + $("diagnostics-chat").textContent = history?.title || "Выберите чат"; + $("diagnostics-messages").textContent = history + ? `Загружено: ${history.loaded} · ${!history.ready ? "страница ещё не получена" : history.hasOlder ? "есть старые сообщения ↑" : "старых страниц нет"}` + : "Сообщения ещё не загружены"; +} + +function result(entry) { + if (entry.status === null) return "Ответ не получен: соединение или таймаут. Результат записи может быть неизвестен."; + if (entry.outcome === "unreadable") return "HTTP-ответ получен, но его данные не удалось прочитать."; + if (entry.status === 204 && entry.method === "DELETE" && entry.path === "/api/v1/auth/sessions/current") return "Сессия отозвана. Ответ без тела."; + return ({200: "Запрос выполнен", 201: "Объект создан", 204: "Выполнено без тела ответа", + 400: "Некорректные данные", 401: "Нужен действующий вход", 404: "Ресурс отсутствует или недоступен", + 409: "Конфликт данных", 415: "Неподдерживаемый формат", 503: "Сервис временно недоступен", + 500: "Внутренняя ошибка сервера"})[entry.status] || `HTTP ${entry.status}`; +} + +function shortPath(path) { return path.replace(/\/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}(?=\/|$)/gi, "/…"); } + +function renderRequests() { + const current = requests[0]; + $("diagnostics-empty").hidden = Boolean(current); + $("diagnostics-request-details").hidden = !current; + $("diagnostics-request-time").textContent = current ? current.at.toLocaleTimeString("ru-RU") : ""; + if (current) { + const failed = current.status === null || current.status >= 400 || current.outcome === "unreadable"; + $("diagnostics-method").textContent = current.method; + $("diagnostics-status").textContent = current.status ?? "Нет ответа"; + $("diagnostics-status").classList.toggle("failed", failed); + $("diagnostics-origin").textContent = current.source || "Основной интерфейс"; + $("diagnostics-path").textContent = shortPath(current.path); + $("diagnostics-path").title = current.path; + $("diagnostics-result").textContent = result(current); + $("diagnostics-result").classList.toggle("failed", failed); + $("diagnostics-auth").textContent = current.authorization; + $("diagnostics-duration").textContent = `${current.durationMs} мс`; + $("diagnostics-request-id").textContent = current.requestId || "Не получен"; + $("diagnostics-instance-id").textContent = current.instanceId || "Не получен"; + } + const previous = requests.slice(1).map(entry => { + const item = document.createElement("li"); + const status = document.createElement("span"); status.textContent = entry.status ?? "-"; + status.className = "diagnostics-mini-status" + (entry.status === null || entry.status >= 400 ? " failed" : ""); + const route = document.createElement("code"); route.textContent = `${entry.method} ${shortPath(entry.path)}`; + route.title = entry.path; item.append(status, route); return item; + }); + $("diagnostics-previous").replaceChildren(...previous); + $("diagnostics-previous").hidden = previous.length === 0; + $("diagnostics-background").hidden = !backgroundRequest; + if (backgroundRequest) $("diagnostics-background").textContent = `Фоновый запрос: ${backgroundRequest.status ?? "нет ответа"} · ${backgroundRequest.durationMs} мс · ${backgroundRequest.at.toLocaleTimeString("ru-RU")}`; +} + +function render() { renderSession(); renderHistory(); renderRequests(); } +setInterval(() => { if (!$("diagnostics-panel").hidden) renderSession(); }, 1000); +try { if (sessionStorage.getItem(preferenceKey) === "on") setOpen(true); } catch { /* optional preference */ } diff --git a/src/Messenger.Api/wwwroot/index.html b/src/Messenger.Api/wwwroot/index.html new file mode 100644 index 00000000..c456e400 --- /dev/null +++ b/src/Messenger.Api/wwwroot/index.html @@ -0,0 +1,168 @@ + + + + + + + + n1k0der · Мессенджер + + + + + + + + + +
+
+ n1k0der. +

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

+ +
+
+
+
+

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

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

Собрать чат

+

Ваш профиль

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

+

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

+ + diff --git a/src/Messenger.Api/wwwroot/mascots.js b/src/Messenger.Api/wwwroot/mascots.js new file mode 100644 index 00000000..ef6f57fa --- /dev/null +++ b/src/Messenger.Api/wwwroot/mascots.js @@ -0,0 +1,143 @@ +// Animation reads field state and password length, never password text. +const stage = document.getElementById("mascot-stage"); +const auth = document.getElementById("auth-screen"); +const reduceMotion = matchMedia("(prefers-reduced-motion: reduce)"); +const mobile = matchMedia("(max-width: 720px)"); +let pending = false, feedback = false; +let feedbackTimer, sleepTimer, approachTimer, pointerFrame = null; +let pointer = { x: 0, y: 0 }, lastWake = 0; + +function wakeUp() { + stage.classList.remove("is-sleepy"); + clearTimeout(sleepTimer); + sleepTimer = setTimeout(() => { + if (stage.dataset.mood === "idle") stage.classList.add("is-sleepy"); + }, 12000); +} + +function activeField() { + const focused = document.activeElement; + return focused?.matches("[data-password-toggle]") + ? document.getElementById(focused.dataset.passwordToggle) : focused; +} + +function focusedMood() { + if (pending || feedback) return; + const field = activeField(); + let mood = "idle"; + if (field?.matches("#login-password, #register-password")) { + mood = field.type === "text" ? "revealed" : "private"; + if (field.id === "register-password" && field.value.length > 0 && Array.from(field.value).length < 12) mood = "short"; + } else if (field?.matches("#login-username, #register-name, #register-username")) mood = "looking"; + stage.dataset.mood = mood; + document.getElementById("auth-error-art").hidden = mood !== "error"; +} + +export function setMascotMood(mood) { + clearTimeout(feedbackTimer); + pending = mood === "pending"; + feedback = ["success", "error", "short"].includes(mood); + stage.dataset.mood = mood; + document.getElementById("auth-error-art").hidden = mood !== "error"; + if (pending || feedback) stage.classList.remove("is-curious"); + if (feedback) feedbackTimer = setTimeout(() => { feedback = false; focusedMood(); }, 3500); +} + +for (const form of auth.querySelectorAll("form")) { + form.addEventListener("focusin", () => { + if (!pending) { feedback = false; clearTimeout(feedbackTimer); } + wakeUp(); focusedMood(); + }); + form.addEventListener("focusout", () => requestAnimationFrame(focusedMood)); + form.addEventListener("input", () => { + feedback = false; focusedMood(); wakeUp(); + stage.classList.add("is-curious"); + clearTimeout(approachTimer); + approachTimer = setTimeout(() => stage.classList.remove("is-curious"), 1600); + }); + form.addEventListener("invalid", () => setMascotMood("error"), true); + form.addEventListener("reset", () => { + for (const button of form.querySelectorAll("[data-password-toggle]")) { + document.getElementById(button.dataset.passwordToggle).type = "password"; + button.setAttribute("aria-pressed", "false"); + button.setAttribute("aria-label", "Показать пароль"); + button.querySelector("use").setAttribute("href", "#i-eye"); + } + }); +} + +for (const button of auth.querySelectorAll("[data-password-toggle]")) { + button.addEventListener("click", () => { + const field = document.getElementById(button.dataset.passwordToggle); + const shown = field.type === "password"; + field.type = shown ? "text" : "password"; + button.setAttribute("aria-pressed", String(shown)); + button.setAttribute("aria-label", shown ? "Скрыть пароль" : "Показать пароль"); + button.querySelector("use").setAttribute("href", shown ? "#i-eye-off" : "#i-eye"); + feedback = false; wakeUp(); focusedMood(); + }); +} +for (const button of auth.querySelectorAll(".auth-switch button")) { + button.addEventListener("click", () => { + pending = feedback = false; + clearTimeout(feedbackTimer); wakeUp(); focusedMood(); + }); +} + +// Mouse events are combined into at most one update per browser frame. +auth.addEventListener("pointermove", event => { + if (event.pointerType === "touch" || reduceMotion.matches || auth.hidden || document.hidden) return; + pointer = { x: event.clientX, y: event.clientY }; + if (performance.now() - lastWake > 1000) { wakeUp(); lastWake = performance.now(); } + if (pointerFrame !== null) return; + pointerFrame = requestAnimationFrame(() => { + pointerFrame = null; + const rect = stage.getBoundingClientRect(); + const x = Math.max(-4, Math.min(4, (pointer.x - rect.left - rect.width / 2) / 55)); + const y = Math.max(-3, Math.min(3, (pointer.y - rect.top - rect.height / 2) / 65)); + stage.style.setProperty("--gaze-x", `${x}px`); + stage.style.setProperty("--gaze-y", `${y}px`); + }); +}); +auth.addEventListener("pointerleave", () => { + stage.style.setProperty("--gaze-x", "0px"); stage.style.setProperty("--gaze-y", "0px"); +}); + +const close = document.getElementById("diagnostics-close"); +let closeHovered = false; +function reactToClose() { + stage.classList.toggle("is-scared", !close.closest("[hidden]") && + (closeHovered || close.matches(":focus-visible"))); +} +close.addEventListener("pointerenter", () => { closeHovered = true; reactToClose(); }); +close.addEventListener("pointerleave", () => { closeHovered = false; reactToClose(); }); +close.addEventListener("focus", reactToClose); +close.addEventListener("blur", reactToClose); +close.addEventListener("keydown", () => requestAnimationFrame(reactToClose)); +new MutationObserver(reactToClose).observe(document.getElementById("diagnostics-panel"), { attributes: true, attributeFilter: ["hidden"] }); + +function updateVisibility() { + const visible = !auth.hidden && !document.hidden; + stage.classList.toggle("is-visible", visible); + if (!visible) { + if (pointerFrame !== null) cancelAnimationFrame(pointerFrame); + pointerFrame = null; + clearTimeout(sleepTimer); clearTimeout(approachTimer); clearTimeout(feedbackTimer); + stage.classList.remove("is-curious", "is-sleepy"); + pending = feedback = false; + } else { wakeUp(); focusedMood(); } +} +new MutationObserver(updateVisibility).observe(auth, { attributes: true, attributeFilter: ["hidden"] }); +document.addEventListener("visibilitychange", updateVisibility); +function placeStage() { + if (mobile.matches) { + const anchor = document.getElementById("login-panel"); anchor.before(stage); + } else document.querySelector(".intro").append(stage); +} +mobile.addEventListener("change", placeStage); +placeStage(); updateVisibility(); + +export async function celebrateMascots() { + setMascotMood("success"); + if (!reduceMotion.matches) await new Promise(resolve => setTimeout(resolve, 650)); +} diff --git a/src/Messenger.Api/wwwroot/message-view.js b/src/Messenger.Api/wwwroot/message-view.js new file mode 100644 index 00000000..1c92a425 --- /dev/null +++ b/src/Messenger.Api/wwwroot/message-view.js @@ -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; +} diff --git a/src/Messenger.Api/wwwroot/polish.css b/src/Messenger.Api/wwwroot/polish.css new file mode 100644 index 00000000..df0ae386 --- /dev/null +++ b/src/Messenger.Api/wwwroot/polish.css @@ -0,0 +1,41 @@ +/* Shared details for the chat list, generated avatars and gentle motion. */ +.avatar { overflow: hidden; background: transparent; border-color: #ffffff14; } +.avatar .avatar-art { display: block; width: 100%; height: 100%; stroke: none; } +.avatar-art text { letter-spacing: -.5px; } +.profile .avatar { background: transparent; } +.chat-row.active .avatar { background: transparent; border-color: #ffe13545; } +.chat-row { padding: 14px 11px; gap: 12px; } +.chat-row.active { background: #ffe1350b; border-color: #ffe13528; } +.chat-row.active::after { display: none; } +.chat-row-heading { display: flex; align-items: baseline; gap: 8px; min-width: 0; } +.chat-row-heading strong { flex: 1; min-width: 0; padding: 0; color: #e7e6dc; } +.chat-row-heading time { flex-shrink: 0; font-size: 10px; color: #a5a598; font-variant-numeric: tabular-nums; } +.chat-row.active .chat-row-heading strong { color: var(--accent); } +.chat-row.active .chat-row-heading time { color: #d4c878; } +.chat-preview { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; line-height: 1.5; } +.search-field > svg { width: 17px; height: 17px; color: var(--muted); } +.action-arrow { width: 20px; height: 20px; } +.member-item { grid-template-columns: 38px minmax(0, 1fr); gap: 12px; align-items: start; } +.member-item .avatar { width: 38px; height: 38px; border-radius: 12px; } +.member-details { display: grid; min-width: 0; gap: 8px; } +.member-details code { padding: 9px 10px; } +.message-scroll { background-size: 320px 280px; } +.messages-loading { display: grid; gap: 15px; padding: 22px 0; } +.messages-loading i { display: block; width: 48%; max-width: 240px; height: 53px; border-radius: 16px 16px 16px 5px; background: #ffffff06; } +.messages-loading i:nth-child(2) { justify-self: end; width: 37%; border-radius: 16px 16px 5px 16px; background: #ffe1350b; } +.messages-loading i:nth-child(3) { width: 58%; } +.send-button { transition: background .18s, transform .18s; } +.send-button:not(:disabled):active { transform: scale(.93); } +.send-button:not(:disabled):hover svg { transform: translate(1px, -1px); } +.send-button svg { transition: transform .18s; } +.icon-button.is-loading svg { animation: refresh-turn .9s linear infinite; } +.kolo-ear-left { transform-origin: 108px 135px; } +.kolo-ear-right { transform-origin: 195px 135px; } +.mascot-stage[data-mood=idle] .kolo-ear-left { animation: ear-settle 9s ease-in-out infinite; } +.spirit-svg { filter: drop-shadow(0 8px 12px #00000014); } +@keyframes refresh-turn { to { transform: rotate(360deg); } } +@keyframes ear-settle { 0%, 78%, 90%, 100% { transform: rotate(0); } 82% { transform: rotate(-3deg); } 86% { transform: rotate(2deg); } } +@media (prefers-reduced-motion: reduce) { + .mascot-stage[data-mood=idle] .kolo-ear-left, .icon-button.is-loading svg { animation: none; } + .send-button, .send-button svg { transition: none; } +} diff --git a/src/Messenger.Api/wwwroot/reactions.js b/src/Messenger.Api/wwwroot/reactions.js new file mode 100644 index 00000000..4eaa0a75 --- /dev/null +++ b/src/Messenger.Api/wwwroot/reactions.js @@ -0,0 +1,45 @@ +const choices = [['like','👍','Нравится'],['love','❤️','Сердце'],['laugh','😂','Смешно'],['mushroom','🍄','Гриб']]; + +export class ReactionControls { + constructor(messageId) { + this.root = document.createElement('div'); this.root.className = 'reaction-controls'; + this.badges = new Map(); this.items = []; + this.picker = document.createElement('button'); this.picker.type = 'button'; this.picker.className = 'reaction-picker'; + this.picker.textContent = '☺+'; this.picker.setAttribute('aria-label', 'Добавить реакцию'); this.picker.setAttribute('aria-expanded','false'); + this.menu = document.createElement('div'); this.menu.className = 'reaction-menu'; this.menu.hidden = true; + this.menu.setAttribute('role','group'); this.menu.setAttribute('aria-label','Выберите реакцию'); + this.root.append(this.picker, this.menu); + const choose = reaction => { + this.close(); + this.root.dispatchEvent(new CustomEvent('reactionchange', { bubbles: true, + detail: { messageId, reaction, present: !this.items.find(item => item.reaction === reaction)?.mine } })); + }; + for (const [reaction, emoji, label] of choices) { + const button = document.createElement('button'); button.type = 'button'; button.textContent = emoji; + button.setAttribute('aria-label',label); button.addEventListener('click',() => choose(reaction)); this.menu.append(button); + const badge = document.createElement('button'); badge.type = 'button'; badge.className = 'reaction-button'; badge.hidden = true; + badge.dataset.reaction = reaction; badge.addEventListener('click',() => choose(reaction)); + this.root.insertBefore(badge,this.picker); this.badges.set(reaction,{badge,emoji,label}); + } + this.picker.addEventListener('click',() => { + this.menu.hidden = !this.menu.hidden; this.picker.setAttribute('aria-expanded',String(!this.menu.hidden)); + if (!this.menu.hidden) this.menu.querySelector('button').focus(); + }); + this.root.addEventListener('keydown',event => { if (event.key === 'Escape') { this.close(); this.picker.focus(); event.stopPropagation(); } }); + this.root.addEventListener('focusout',event => { if (!this.root.contains(event.relatedTarget)) this.close(); }); + } + close() { this.menu.hidden = true; this.picker.setAttribute('aria-expanded','false'); } + render(items = [], busy = false) { + const signature = JSON.stringify([items,busy]); + if (signature === this.signature) return; + this.signature = signature; this.items = items; + for (const [reaction, {badge,emoji,label}] of this.badges) { + const item = items.find(item => item.reaction === reaction); + badge.hidden = !item?.count; + badge.textContent = `${emoji} ${item?.count || 0}`; + badge.setAttribute('aria-label',`${label}: ${item?.count || 0}${item?.mine ? ', ваша реакция' : ''}`); + badge.setAttribute('aria-pressed',String(Boolean(item?.mine))); + } + for (const button of this.root.querySelectorAll('button')) button.disabled = busy; + } +} diff --git a/src/Messenger.Api/wwwroot/showcase.css b/src/Messenger.Api/wwwroot/showcase.css new file mode 100644 index 00000000..f4f0e2e9 --- /dev/null +++ b/src/Messenger.Api/wwwroot/showcase.css @@ -0,0 +1,41 @@ +.cluster-section { margin-bottom: 18px; padding-bottom: 18px; border-bottom: 1px solid var(--border); } +.cluster-section h3 { margin: 0; font-size: 15px; color: #eeeadd; } +.cluster-live { display: inline-flex; align-items: center; gap: 5px; color: #b9d99f; font-size: 9px; letter-spacing: 1px; } +.cluster-live::before { content: ''; width: 5px; height: 5px; border-radius: 50%; background: currentColor; } +.cluster-status { font-size: 11px; color: var(--muted); line-height: 1.6; margin: 10px 0 14px; } +.cluster-graph { display: grid; justify-items: center; gap: 16px; position: relative; isolation: isolate; } +.cluster-graph::before { content: ''; position: absolute; top: 10px; bottom: 15px; width: 1px; background: #706b4360; z-index: -1; } +.cluster-node { background: #30312c; border: 1px solid #535447; border-radius: 11px; text-align: center; padding: 10px; transition: border-color .25s, background .25s; min-width: 0; } +.cluster-node strong { display: block; font-size: 11px; color: #ecebdc; } +.cluster-node span, .cluster-node small { display: block; font-size: 9px; margin-top: 5px; color: var(--muted); } +.cluster-browser, .cluster-balancer { width: 70%; } +.cluster-balancer[data-state=up] { border-color: #8e8552; } +.cluster-instances, .cluster-stores { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); width: 100%; gap: 8px; } +.cluster-instances, .cluster-stores { position: relative; } +.cluster-instances::before, .cluster-stores::before { content: ''; position: absolute; top: -8px; left: 25%; right: 25%; border-top: 1px solid #706b4360; } +.cluster-api, .cluster-stores .cluster-node { position: relative; } +.cluster-api::before, .cluster-stores .cluster-node::before { content: ''; position: absolute; top: -9px; left: 50%; height: 8px; border-left: 1px solid #706b4360; } +.cluster-api[data-state=up] span { color: #b9d99f; } +.cluster-node[data-state=down] { background: #3b302e; border-color: #a36154; } +.cluster-node[data-state=down] span { color: #ffb2a2; } +.cluster-node[data-state=unknown] { border-style: dashed; } +.cluster-api.just-served { border-color: var(--accent); background: #48442b; box-shadow: 0 0 0 3px #ffe1350b; } +.cluster-detail { font: 10px/1.7 ui-monospace,monospace; color: #dbd4a3; min-height: 34px; margin: 13px 0 8px; overflow-wrap: anywhere; } +.cluster-section .text-button { font-size: 11px; padding: 7px 0; } +.cluster-note { font-size: 10px; line-height: 1.65; color: var(--muted); } +.cluster-demo { border-top: 1px solid var(--border); margin-top: 10px; padding-top: 12px; } +.cluster-demo summary { color: var(--accent); font-size: 11px; cursor: pointer; } +.cluster-command { display: block; font: 10px/1.7 ui-monospace,monospace; color: #dfdabe; background: #252623; border: 1px solid var(--border); padding: 10px; border-radius: 9px; overflow-wrap: anywhere; user-select: all; margin: 10px 0; } +.reaction-controls { display: flex; gap: 4px; align-items: center; flex-wrap: wrap; min-height: 25px; } +.message.mine .reaction-controls { justify-content: flex-end; } +.reaction-button, .reaction-picker { border: 1px solid #62624b; background: #30312b; color: #e6e2cd; border-radius: 16px; font-size: 12px; min-height: 26px; min-width: 32px; padding: 3px 8px; line-height: 1.4; } +.reaction-button[aria-pressed=true] { background: #ffe1351a; border-color: #b8aa4f; color: var(--accent); } +.reaction-button:hover, .reaction-picker:hover { border-color: var(--accent); } +.reaction-picker { color: var(--muted); font-size: 15px; opacity: .35; } +.message:hover .reaction-picker, .message:focus-within .reaction-picker { opacity: 1; } +.reaction-menu { display: flex; gap: 3px; background: #292a25; border: 1px solid #62624b; border-radius: 18px; padding: 3px; } +.reaction-menu button { background: transparent; border: 0; border-radius: 12px; padding: 5px 7px; font-size: 17px; } +.reaction-menu button:hover { background: #ffe13518; } +.reaction-error { font-size: 10px; color: var(--danger); margin: 0; } +@media (hover:none) { .reaction-picker { opacity: .8; } } +@media (prefers-reduced-motion:reduce) { .cluster-node { transition:none; } } diff --git a/student-tests/availability_tests.py b/student-tests/availability_tests.py new file mode 100644 index 00000000..1d9e4147 --- /dev/null +++ b/student-tests/availability_tests.py @@ -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) diff --git a/student-tests/cluster.py b/student-tests/cluster.py new file mode 100644 index 00000000..4984feaf --- /dev/null +++ b/student-tests/cluster.py @@ -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 diff --git a/student-tests/compose_helpers.py b/student-tests/compose_helpers.py new file mode 100644 index 00000000..c6cc81bf --- /dev/null +++ b/student-tests/compose_helpers.py @@ -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) diff --git a/student-tests/lab2_tests.py b/student-tests/lab2_tests.py new file mode 100644 index 00000000..cf3cec77 --- /dev/null +++ b/student-tests/lab2_tests.py @@ -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) diff --git a/student-tests/lab3_tests.py b/student-tests/lab3_tests.py new file mode 100644 index 00000000..58d9da75 --- /dev/null +++ b/student-tests/lab3_tests.py @@ -0,0 +1,100 @@ +"""Cross-replica message retries, authorization, expiry and transaction rollback.""" +import argparse +from concurrent.futures import ThreadPoolExecutor +import json +import time +import uuid + +from compose_helpers import ROOT, compose, sql +from client import Client, check, run + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--base-url", default="http://127.0.0.1:18080") + args = parser.parse_args() + c = Client(args.base_url) + alice, bob, eve, chat = c.bootstrap() + path = "/api/v1/chats/" + chat["id"] + "/messages" + key = uuid.uuid4().hex + checks = [] + + instances = {c.call("GET", "/api/v1/users/me", actor=alice, schema="User")["headers"]["X-Instance-Id"] for _ in range(30)} + containers = compose("ps", "-q", "api").splitlines() + check(len(instances) >= 2 and len(containers) >= 2, "two real API processes must be available") + checks.append("one session served by at least two API processes") + + for invalid in ["", "bad key", "a" * 129, "a,b"]: + c.call("POST", path, 400, actor=alice, body={"text": "invalid"}, headers={"Idempotency-Key": invalid}) + c.call("POST", path, 400, actor=alice, body={"text": "missing"}) + c.call("POST", path, 401, body={"text": "anonymous"}, headers={"Idempotency-Key": key}) + + def submit(number): + local = Client(args.base_url) + body = {"text": "Одно сообщение 👋", "attachment_ids": []} if number % 2 else {"text": "Одно сообщение 👋"} + return local.call("POST", path, 201, actor=alice, body=body, + headers={"Idempotency-Key": key}, schema="Message") + with ThreadPoolExecutor(max_workers=16) as pool: + results = list(pool.map(submit, range(32))) + message = results[0]["json"] + check(all(result["json"] == message for result in results), "concurrent replay changed Message") + replay_instances = sorted({result["headers"]["X-Instance-Id"] for result in results}) + check(len(replay_instances) >= 2, "replay did not pass through different API processes") + count = int(sql("SELECT count(*) FROM messages WHERE chat_id = '" + chat["id"] + "';")) + check(count == 1, "same key created duplicate message") + checks.append("32 concurrent requests across replicas create one message; absent attachments equals []") + + c.call("POST", path, 409, actor=alice, body={"text": "Different"}, + headers={"Idempotency-Key": key}) + c.call("POST", path, 404, actor=eve, body={"text": message["text"]}, + headers={"Idempotency-Key": key}) + second = c.message(bob, chat, message["text"], key=key)["json"] + check(second["id"] != message["id"], "key incorrectly shared between users") + other_chat = c.call("POST", "/api/v1/chats", 201, actor=alice, + body={"title": "Scope", "member_ids": [alice["id"]]}, schema="Chat")["json"] + third = c.message(alice, other_chat, message["text"], key=key)["json"] + check(third["id"] != message["id"], "key incorrectly shared between chats") + checks.append("changed body conflicts; user/chat scopes are independent; access rechecked") + + remaining = float(sql("SELECT extract(epoch FROM expires_at - clock_timestamp()) FROM message_requests WHERE message_id = '" + message["id"] + "';")) + check(86300 < remaining <= 86400, "request retention is not 24 hours") + sql("UPDATE message_requests SET expires_at = now() - interval '1 second' WHERE message_id = '" + message["id"] + "';") + renewed = c.message(alice, chat, "After expiry", key=key)["json"] + check(renewed["id"] != message["id"], "expired key cannot be reused") + checks.append("24-hour expiry stored in PostgreSQL; expired key can be reused") + + name = "rollback_" + uuid.uuid4().hex + failed_key = uuid.uuid4().hex + sql(f""" + CREATE FUNCTION {name}() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN + IF NEW.request_key = '{failed_key}' THEN RAISE EXCEPTION 'injected request failure'; END IF; + RETURN NEW; + END $$; + CREATE TRIGGER {name} BEFORE INSERT ON message_requests FOR EACH ROW EXECUTE FUNCTION {name}(); + """) + before = int(sql("SELECT count(*) FROM messages WHERE chat_id = '" + chat["id"] + "';")) + try: + c.call("POST", path, 503, actor=alice, body={"text": "Atomic retry"}, + headers={"Idempotency-Key": failed_key}) + after = int(sql("SELECT count(*) FROM messages WHERE chat_id = '" + chat["id"] + "';")) + check(before == after, "failed idempotency record left a message committed") + finally: + sql(f"DROP TRIGGER {name} ON message_requests; DROP FUNCTION {name}();") + c.message(alice, chat, "Atomic retry", key=failed_key) + checks.append("5xx rolls back message and key together; retry succeeds") + + c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice) + c.call("POST", path, 401, actor=alice, body={"text": "Atomic retry"}, + headers={"Idempotency-Key": failed_key}) + checks.append("revoked token cannot replay an existing result") + + evidence = {"verified_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + "instances": sorted(instances), "replay_instances": replay_instances, + "api_containers": containers, "checks": checks} + (ROOT / "evidence" / "idempotency.json").write_text(json.dumps(evidence, ensure_ascii=False, indent=2) + "\n") + print(json.dumps(evidence, ensure_ascii=False, indent=2)) + + +if __name__ == "__main__": + run(main) diff --git a/student-tests/mode_tests.py b/student-tests/mode_tests.py new file mode 100644 index 00000000..e278e1e7 --- /dev/null +++ b/student-tests/mode_tests.py @@ -0,0 +1,42 @@ +"""Run idempotency checks with and without SQL batching, then test short sessions.""" +import argparse +import json +import os +import subprocess +import sys +from pathlib import Path + +from cluster import recreate, wait_api +from compose_helpers import ROOT + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--base-url", default="http://127.0.0.1:18080") + parser.add_argument("--expiry", action="store_true") + args = parser.parse_args() + try: + if args.expiry: + environment = dict(os.environ, SESSION_TTL_SECONDS="2") + subprocess.run([str(ROOT / "scripts/compose.sh"), "up", "-d", "--no-deps", "--force-recreate", "api"], + env=environment, check=True, timeout=90) + wait_api(args.base_url, 2) + subprocess.run([sys.executable, str(ROOT / "student-tests/lab2_tests.py"), + "--base-url", args.base_url, "--check-expiry"], check=True) + else: + for batching in (False, True): + recreate(batching=batching) + wait_api(args.base_url, 2) + subprocess.run([sys.executable, str(ROOT / "student-tests/lab3_tests.py"), "--base-url", args.base_url], check=True) + report = (ROOT / "evidence/idempotency.json").read_text() + suffix = "batched" if batching else "separate" + (ROOT / ("evidence/idempotency-" + suffix + ".json")).write_text(report) + finally: + environment = dict(os.environ, SESSION_TTL_SECONDS="3600", MESSAGE_BATCHING="true") + subprocess.run([str(ROOT / "scripts/compose.sh"), "up", "-d", "--no-deps", "--force-recreate", "api"], + env=environment, check=True, timeout=90) + wait_api(args.base_url, 2) + + +if __name__ == "__main__": + main() diff --git a/student-tests/persistence_checks.py b/student-tests/persistence_checks.py new file mode 100644 index 00000000..049c43a3 --- /dev/null +++ b/student-tests/persistence_checks.py @@ -0,0 +1,51 @@ +"""Restart storage and processes, then replay the original request with the original token.""" +import argparse +import json +import subprocess +import time + +from cluster import inspect +from compose_helpers import ROOT, compose, sql +from client import Client, check, run +import uuid + + +def state(): + result = {} + for service in ("postgres", "redis", "api", "lb"): + result[service] = [{"container": row["Id"], "started_at": row["State"]["StartedAt"], + "volumes": [mount["Name"] for mount in row["Mounts"] if mount["Type"] == "volume"]} + for row in (inspect(container) for container in compose("ps", "-q", service).splitlines())] + return result + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--base-url", default="http://127.0.0.1:18080") + args = parser.parse_args() + c = Client(args.base_url) + alice, bob, eve, chat = c.bootstrap() + key = uuid.uuid4().hex + original = c.message(alice, chat, "Persistent request " + key, key=key)["json"] + before = state() + subprocess.run([str(ROOT / "scripts/restart.sh")], check=True, timeout=90, stdout=subprocess.DEVNULL) + after = state() + for service in before: + check({row["started_at"] for row in before[service]} != {row["started_at"] for row in after[service]}, + service + " was not restarted") + check(before["postgres"][0]["volumes"] == after["postgres"][0]["volumes"], "database volume changed") + c.call("GET", "/api/v1/users/me", actor=alice, schema="User") + replay = c.message(alice, chat, original["text"], key=key)["json"] + check(replay == original, "original key/token did not replay after full restart") + check(sql("SELECT count(*) FROM messages WHERE chat_id = '" + chat["id"] + "';") == "1", "restart replay duplicated message") + c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice) + c.call("GET", "/api/v1/users/me", 401, actor=alice) + report = {"verified_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + "before": before, "after": after, "same_token": True, "same_message": True, + "replay_without_duplicates": True, "logout_status": 401} + (ROOT / "evidence/persistence.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n") + print("PASS: all services restarted, original token and key replayed, one message, logout 401") + + +if __name__ == "__main__": + run(main) diff --git a/student-tests/scaling_research.py b/student-tests/scaling_research.py new file mode 100644 index 00000000..c7032fc8 --- /dev/null +++ b/student-tests/scaling_research.py @@ -0,0 +1,336 @@ +"""Track 1: fixed/growing API budgets, saturation curves and SQL batching.""" +import argparse +import csv +import gzip +import hashlib +import json +import statistics +import time +from pathlib import Path + +import matplotlib +matplotlib.use("Agg") +import matplotlib.pyplot as plt + +from cluster import api_ids, counters, counter_delta, docker, recreate, wait_api, inspect, servers +from compose_helpers import ROOT, compose, sql +from client import Client, check, run +from traffic import traffic, public_report + + +def median_row(rows): + return { + "rps": round(statistics.median(row["successful_rps"] for row in rows), 3), + "p95_ms": round(statistics.median(row["successful_latency_ms"]["p95"] for row in rows), 3), + "error_ratio": round(statistics.median(row["error_ratio"] for row in rows), 6), + "failed_requests_total": sum(row["failed_requests"] for row in rows), + "error_ratio_max": max(row["error_ratio"] for row in rows), + "rps_min": min(row["successful_rps"] for row in rows), + "rps_max": max(row["successful_rps"] for row in rows), + } + + +def summarize(evidence): + for configuration in evidence["configurations"]: + label = configuration["series"] + "-" + str(configuration["replicas"]) + for concurrency in configuration["curves"]: + configuration["curves"][concurrency] = median_row([row for row in evidence["runs"] if row["label"] == label and row["concurrency"] == int(concurrency)]) + evidence["batching_comparison"] = {label: median_row([row for row in evidence["runs"] if row["label"] == label]) for label in ("separate", "batched")} + evidence["database_capacity_comparison"] = {label: median_row([row for row in evidence["runs"] if row["label"] == "postgres-" + label]) for label in ("half_cpu", "one_cpu")} + + +def make_chart(evidence): + figure, axes = plt.subplots(1, 3, figsize=(15, 4.5)) + for series, color in (("fixed", "#436b4f"), ("growing", "#b37b24")): + selected = [row for row in evidence["configurations"] if row["series"] == series] + for concurrency, style in ((4, ":"), (16, "--"), (64, "-")): + ys = [row["curves"][str(concurrency)]["rps"] for row in selected] + axes[0].plot([row["replicas"] for row in selected], ys, marker="o", + linestyle=style, color=color, label=f"{series}, C={concurrency}") + row = selected[-1] + xs = [int(value) for value in row["curves"]] + axes[1].plot(xs, [row["curves"][str(value)]["rps"] for value in xs], + marker="o", color=color, label=f"{series}, 4 replicas") + axes[2].plot(xs, [row["curves"][str(value)]["p95_ms"] for value in xs], + marker="o", color=color, label=f"{series}, 4 replicas") + axes[0].set(xlabel="API replicas", ylabel="Successful requests/s", title="Fixed vs growing API budget", xticks=[1, 2, 4]) + axes[1].set(xlabel="Concurrent clients", ylabel="Successful requests/s", title="Throughput saturation") + axes[2].set(xlabel="Concurrent clients", ylabel="Successful latency p95, ms", title="Queueing cost") + for axis in axes: + axis.grid(alpha=.2) + axis.legend(fontsize=8) + figure.tight_layout() + figure.savefig(ROOT / "evidence/scaling.png", dpi=160) + figure.savefig(ROOT / "evidence/scaling.svg") + plt.close(figure) + + +def write_report(evidence): + table = [] + for row in evidence["configurations"]: + for concurrency, measured in row["curves"].items(): + table.append("| " + " | ".join(str(value) for value in + (row["series"], row["replicas"], row["total_api_cpus"], row["total_api_memory_mib"], + concurrency, measured["rps"], measured["p95_ms"], measured["error_ratio"], measured["failed_requests_total"])) + " |") + comparison = evidence["batching_comparison"] + before, after = comparison["separate"], comparison["batched"] + gain = (after["rps"] / before["rps"] - 1) * 100 + recovery = evidence["database_capacity_comparison"] + db_gain = (recovery["one_cpu"]["rps"] / recovery["half_cpu"]["rps"] - 1) * 100 + one = next(row for row in evidence["configurations"] if row["series"] == "growing" and row["replicas"] == 1) + low, high = one["curves"]["16"], one["curves"]["64"] + throughput_change = (high["rps"] / low["rps"] - 1) * 100 + base_runs = [row for row in evidence["runs"] if row["label"] == "growing-1" and row["concurrency"] == 64] + cpu = {service: statistics.mean(sum(item["used_cpu_cores"] for item in row["resources"] if item["service"] == service) for row in base_runs) for service in ("api", "postgres", "lb")} + statuses = {} + for row in evidence["runs"]: + for status, count in row["status_counts"].items(): + if status not in ("200", "201"): + statuses[status] = statuses.get(status, 0) + count + text = f"""# Масштабирование API + +Проверено: {evidence['verified_at']}. Трек 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, {evidence['host']['cpus']} виртуальных CPU, +{round(evidence['host']['memory_bytes'] / 1024**3, 2)} 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. Каждая точка: {evidence['repeats']} прогона по +{evidence['seconds_per_run']} секунд, приведены медианы. +Порядок concurrency чередуется между конфигурациями; варианты batching чередуются. + +CPU и throttling измерены по cgroup cpu.stat до/после прогона. Это окно включает +накладные расходы сбора счётчиков. RAM отражает memory.current в конце окна, +а не исторический пик. Для каждого прогона есть успешные RPS, ошибки, p50/p95/p99, +распределение реплик и счётчики HAProxy/БД. + +## Результаты + +| Серия | Реплики | CPU API всего | MiB API всего | Клиенты | RPS | p95 ms | Медиана доли ошибок | Ошибок всего | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +{chr(10).join(table)} + +![Масштабирование](../evidence/scaling.png) + +## Проверенные изменения + +SQL-команды не меняют транзакционную границу: блокировка, проверка ключа, +запись сообщения и результата остаются согласованными. MESSAGE_BATCHING=false +отправляет команды отдельно; true объединяет пары команд в один сетевой обмен. +Конкурентная проверка обоих режимов входит в собственные тесты. + +| Вариант | Медиана RPS | Диапазон RPS | p95 ms | Ошибок всего | +| --- | ---: | --- | ---: | ---: | +| Отдельные SQL-команды | {before['rps']} | {before['rps_min']} - {before['rps_max']} | {before['p95_ms']} | {before['failed_requests_total']} | +| SQL batching | {after['rps']} | {after['rps_min']} - {after['rps_max']} | {after['p95_ms']} | {after['failed_requests_total']} | + +Изменение медианных RPS: {gain:+.1f}%. Эти значения относятся только к этому +профилю и конфигурации из JSON; это не универсальная оценка скорости. + +Увеличение PostgreSQL с 0.5 до 1 CPU при четырёх API: изменение медианных RPS +{db_gain:+.1f}%. В JSON сохранены оба набора CPU/throttling и латентностей, +поэтому причинное объяснение можно проверить по ресурсным ограничениям. + +## Анализ насыщения + +У одной API в growing увеличение concurrency с 16 до 64 изменило медиану +RPS с {low['rps']} до {high['rps']} ({throughput_change:+.1f}%), а p95 вырос +с {low['p95_ms']} до {high['p95_ms']} ms. В этом профиле плато начинается +около {round(high['rps'] / 50) * 50} успешных запросов/с. + +На этой точке среднее потребление CPU по окну cgroup: API {cpu['api']:.3f} +из 1, PostgreSQL {cpu['postgres']:.3f} из 0.5, HAProxy {cpu['lb']:.3f} из 0.5. +База близка к своей квоте, тогда как у API и LB остаётся запас. Дополнительный +эксперимент с 1 CPU PostgreSQL дал {recovery['one_cpu']['rps']} против +{recovery['half_cpu']['rps']} RPS при прежних четырёх API. Это подтверждает +существенное влияние общей БД в выбранной конфигурации. + +Коды неуспешных попыток за всю серию: {statuses}; 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 +""" + (ROOT / "docs").mkdir(exist_ok=True) + (ROOT / "docs/SCALING.md").write_text(text) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--base-url", default="http://127.0.0.1:18080") + parser.add_argument("--seconds", type=int, default=8) + parser.add_argument("--repeats", type=int, default=3) + args = parser.parse_args() + check(args.seconds >= 5 and args.repeats >= 2, "use at least 5 seconds and two repeats") + wait_api(args.base_url, 2) + c = Client(args.base_url, timeout=20) + actor = c.user("scaling") + host = json.loads(docker("info", "--format", '{{json .}}')) + evidence = {"verified_at": "", "track": 1, "seconds_per_run": args.seconds, "repeats": args.repeats, + "host": {"cpus": host["NCPU"], "memory_bytes": host["MemTotal"], + "docker_version": host["ServerVersion"], "os": host["OperatingSystem"]}, + "configurations": [], "runs": []} + evidence["source_sha256"] = hashlib.sha256(b"".join(path.read_bytes() for path in sorted((ROOT / "src").rglob("*.cs")) if "obj" not in path.parts)).hexdigest() + pg = compose("ps", "-q", "postgres") + run_number = 0 + raw_path = ROOT / "evidence/scaling-requests.csv.gz" + + def fixture(): + chat = c.call("POST", "/api/v1/chats", 201, actor=actor, + body={"title": "Scaling " + str(time.time_ns()), "member_ids": [actor["id"]]}, schema="Chat")["json"] + sql("INSERT INTO messages(id, chat_id, sender_id, text, created_at) SELECT md5('" + chat["id"] + ":' || n::text)::uuid, '" + chat["id"] + "', '" + actor["id"] + "', 'fixture ' || n, now() + n * interval '1 microsecond' FROM generate_series(1,250) n;") + return chat + + def measured(label, concurrency): + nonlocal run_number + run_number += 1 + chat = fixture() + before = counters() + begin = time.monotonic() + def observe(): + return { + "postgres_activity": json.loads(sql("SELECT coalesce(json_agg(t), '[]') FROM (SELECT state, wait_event_type, count(*) FROM pg_stat_activity WHERE application_name = 'messenger-api' GROUP BY state, wait_event_type) t;")), + "lb_queues": [{key: row[key] for key in ("svname", "status", "qcur", "scur", "qmax")} for row in servers() if row["addr"]] + } + result = traffic(args.base_url, actor, chat, args.seconds, concurrency, observer=observe) + check(bool(result["observations"]) and all("error" not in item for item in result["observations"]), "resource observer failed") + after = counters() + result["resources"] = counter_delta(before, after, time.monotonic() - begin) + result["run"] = run_number + result["label"] = label + result["postgres_activity"] = json.loads(sql("SELECT coalesce(json_agg(t), '[]') FROM (SELECT state, wait_event_type, count(*) FROM pg_stat_activity WHERE application_name = 'messenger-api' GROUP BY state, wait_event_type) t;")) + result["lb_queues"] = [] # Filled from the runtime API below without request bodies. + result["lb_queues"] = [{key: row[key] for key in ("svname", "status", "qcur", "qmax", "qtime_max")} for row in servers() if row["addr"]] + for sample in result["_samples"]: + raw.writerow((run_number, label, *sample)) + report = public_report(result) + evidence["runs"].append(report) + print(f"{label}, C={concurrency}, trial={run_number}: {report['successful_rps']} RPS, p95={report['successful_latency_ms']['p95']} ms, errors={report['failed_requests']}", flush=True) + (ROOT / "evidence/scaling-progress.json").write_text(json.dumps(evidence, ensure_ascii=False, indent=2) + "\n") + check(result["successful_requests"] > 0, "no successful requests") + return report + + def configure(replicas, cpus, memory, batching=True, database_cpus=.5): + docker("update", "--cpus", str(database_cpus), pg) + recreate(replicas, cpus, memory, batching=batching) + wait_api(args.base_url, replicas) + actual = [inspect(container)["HostConfig"] for container in api_ids()] + check(len(actual) == replicas, "replica count differs from requested configuration") + check(all(item["NanoCpus"] == int(cpus * 1e9) and item["Memory"] == int(memory[:-1]) * 1024**2 for item in actual), "CPU/RAM limits differ from requested budget") + traffic(args.base_url, actor, fixture(), duration=3, concurrency=4) + + try: + with gzip.open(raw_path, "wt", newline="") as destination: + raw = csv.writer(destination) + raw.writerow(("run", "configuration", "offset_seconds", "operation", "http_status", "latency_ms", "instance_id")) + for series in ("fixed", "growing"): + for replicas in (1, 2, 4): + cpu = 1 / replicas if series == "fixed" else 1 + memory = 768 // replicas if series == "fixed" else 384 + print(f"Configuring {series}: {replicas} API, {cpu} CPU/{memory} MiB each", flush=True) + configure(replicas, cpu, str(memory) + "m") + row = {"series": series, "replicas": replicas, "per_api_cpus": cpu, + "per_api_memory_mib": memory, "total_api_cpus": cpu * replicas, + "total_api_memory_mib": memory * replicas, "curves": {}} + order = (4, 16, 64) if replicas != 2 else (64, 16, 4) + for concurrency in order: + traffic(args.base_url, actor, fixture(), duration=2, concurrency=concurrency) + trials = [measured(series + "-" + str(replicas), concurrency) for _ in range(args.repeats)] + row["curves"][str(concurrency)] = median_row(trials) + row["curves"] = dict(sorted(row["curves"].items(), key=lambda item: int(item[0]))) + evidence["configurations"].append(row) + + comparison = {"separate": [], "batched": []} + for trial in range(args.repeats): + for batching in ((False, True) if trial % 2 == 0 else (True, False)): + configure(2, 1, "384m", batching=batching) + label = "batched" if batching else "separate" + comparison[label].append(measured(label, 16)) + evidence["batching_comparison"] = {key: median_row(rows) for key, rows in comparison.items()} + + comparison = {"half_cpu": [], "one_cpu": []} + for trial in range(args.repeats): + for label, cpu in (("half_cpu", .5), ("one_cpu", 1)) if trial % 2 == 0 else (("one_cpu", 1), ("half_cpu", .5)): + configure(4, 1, "384m", database_cpus=cpu) + comparison[label].append(measured("postgres-" + label, 64)) + evidence["database_capacity_comparison"] = {key: median_row(rows) for key, rows in comparison.items()} + finally: + docker("update", "--cpus", ".5", pg) + recreate() + wait_api(args.base_url, 2) + + evidence["verified_at"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) + evidence["confirmed_improvements"] = [] + if evidence["batching_comparison"]["batched"]["rps"] >= 1.05 * evidence["batching_comparison"]["separate"]["rps"]: + evidence["confirmed_improvements"].append("SQL command batching increased median successful RPS") + if evidence["database_capacity_comparison"]["one_cpu"]["rps"] >= 1.05 * evidence["database_capacity_comparison"]["half_cpu"]["rps"]: + evidence["confirmed_improvements"].append("Additional PostgreSQL CPU increased median successful RPS") + check(evidence["confirmed_improvements"], "no throughput improvement confirmed; inspect measurements") + (ROOT / "evidence/scaling.json").write_text(json.dumps(evidence, ensure_ascii=False, indent=2) + "\n") + make_chart(evidence) + write_report(evidence) + print("PASS: scaling research saved to evidence/scaling.json and docs/SCALING.md") + + +if __name__ == "__main__": + run(main) diff --git a/student-tests/showcase_tests.py b/student-tests/showcase_tests.py new file mode 100644 index 00000000..aab67321 --- /dev/null +++ b/student-tests/showcase_tests.py @@ -0,0 +1,59 @@ +"""Reactions are durable, private and idempotent across the actual API replicas.""" +import argparse +import json +import uuid + +from compose_helpers import sql +from client import Client, check, run + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--base-url", default="http://127.0.0.1:18080") + args = parser.parse_args() + client = Client(args.base_url) + alice, bob, eve, chat = client.bootstrap() + message = client.call("POST", f"/api/v1/chats/{chat['id']}/messages", 201, actor=alice, + body={"text": "Реакции через разные API"}, headers={"Idempotency-Key": str(uuid.uuid4())}, schema="Message")["json"] + route = f"/api/ui/chats/{chat['id']}/messages/{message['id']}/reactions/like" + summary = f"/api/ui/chats/{chat['id']}/reactions?message_ids={message['id']}" + + def items(actor): + return json.loads(client.call("GET", summary, actor=actor)["bytes"])["items"] + + client.call("PUT", route, 401) + client.call("GET", summary, 401) + client.call("PUT", route, 404, actor=eve) + client.call("GET", summary, 404, actor=eve) + instances = set() + for _ in range(8): + response = client.call("PUT", route, 204, actor=alice) + instances.add(response["headers"]["X-Instance-Id"]) + check(len(instances) >= 2, "writes did not reach two API instances") + check(items(alice)[0]["count"] == 1 and items(alice)[0]["mine"], "repeated PUT counted twice") + check(not items(bob)[0]["mine"], "mine flag leaked between users") + client.call("PUT", route, 204, actor=bob) + check(items(alice)[0]["count"] == 2, "two users did not aggregate") + check(int(sql(f"SELECT count(*) FROM message_reactions WHERE message_id = '{message['id']}';")) == 2, + "reactions were not persisted") + client.call("DELETE", route, 204, actor=alice) + client.call("DELETE", route, 204, actor=alice) + check(items(alice)[0]["count"] == 1 and not items(alice)[0]["mine"], "DELETE affected another user's reaction") + client.call("PUT", route.rsplit('/', 1)[0] + "/invalid", 400, actor=alice) + missing = route.replace(message["id"], str(uuid.uuid4())) + client.call("PUT", missing, 404, actor=alice) + other = client.call("POST", "/api/v1/chats", 201, actor=alice, + body={"title": "Другая комната", "member_ids": [alice["id"]]}, schema="Chat")["json"] + client.call("PUT", route.replace(chat["id"], other["id"]), 404, actor=alice) + mixed = json.loads(client.call("GET", summary.replace(chat["id"], other["id"]), actor=alice)["bytes"]) + check(mixed["items"] == [], "foreign message reaction escaped its chat") + client.call("GET", summary.rsplit('=',1)[0] + '=bad', 400, actor=alice) + client.call("GET", "/api/ui/cluster", 401) + cluster = json.loads(client.call("GET", "/api/ui/cluster", actor=alice)["bytes"]) + check(cluster["redis_available"] and cluster["postgres_available"], "cluster dependency snapshot failed") + check(sum(node["ready"] for node in cluster["instances"]) >= 2, "missing actual cluster heartbeats") + print("PASS: two-replica reaction writes, idempotency, user isolation, chat privacy, PostgreSQL persistence, cluster heartbeat") + + +if __name__ == "__main__": + run(main) diff --git a/student-tests/traffic.py b/student-tests/traffic.py new file mode 100644 index 00000000..8a6f7a90 --- /dev/null +++ b/student-tests/traffic.py @@ -0,0 +1,135 @@ +"""Persistent HTTP/1.1 workers; closed-loop measurements include client overhead.""" +from concurrent.futures import ThreadPoolExecutor +from collections import Counter +import http.client +import json +import math +import threading +import time +from urllib.parse import urlsplit +import uuid + + +def percentile(values, fraction): + return round(sorted(values)[max(0, math.ceil(len(values) * fraction) - 1)], 3) if values else None + + +def traffic(base_url, actor, chat, duration=10, concurrency=16, action=None, retry_uncertain=False, observer=None): + address = urlsplit(base_url) + barrier = threading.Barrier(concurrency + 1) + actions = [] + action_error = [] + observations = [] + sample_stop = threading.Event() + started = 0 + + def worker(number): + connection = http.client.HTTPConnection(address.hostname, address.port, timeout=3) + records, confirmed = [], [] + pending = None + index = number + barrier.wait() + deadline = started + duration + try: + while time.monotonic() < deadline: + operation = "write" if pending or index % 2 else "read" + headers = {"Authorization": "Bearer " + actor["token"], "Content-Type": "application/json"} + path = "/api/v1/chats/" + chat["id"] + "/messages" + payload = None + if operation == "write": + if pending is None: + pending = (uuid.uuid4().hex, uuid.uuid4().hex) + headers["Idempotency-Key"] = pending[0] + payload = json.dumps({"text": pending[1]}).encode() + else: + path += "?limit=50" + begin = time.monotonic() + status, instance, message_id = 0, "", None + try: + connection.request("POST" if operation == "write" else "GET", path, body=payload, headers=headers) + response = connection.getresponse() + status = response.status + instance = response.getheader("X-Instance-Id", "") + content = response.read() + if status == (201 if operation == "write" else 200): + if operation == "write": + message_id = json.loads(content)["id"] + confirmed.append((message_id, pending[1])) + pending = None + else: + connection.close() + except (OSError, http.client.HTTPException, ValueError): + connection.close() + status = 0 + elapsed = (time.monotonic() - begin) * 1000 + records.append((round(begin - started, 6), operation, status, round(elapsed, 4), instance)) + if not retry_uncertain: + pending = None + index += 1 + finally: + connection.close() + return records, confirmed + + def run_action(): + try: + time.sleep(2) + begin = time.monotonic() + result = action() + actions.append({"started_after_seconds": begin - started, + "finished_after_seconds": time.monotonic() - started, "result": result}) + except Exception as error: + action_error.append(error) + + def sample(): + while not sample_stop.wait(2): + try: + observations.append({"offset_seconds": round(time.monotonic() - started, 3), "data": observer()}) + except Exception as error: + observations.append({"error": type(error).__name__}) + + with ThreadPoolExecutor(max_workers=concurrency) as pool: + futures = [pool.submit(worker, n) for n in range(concurrency)] + started = time.monotonic() + barrier.wait() + sampler = threading.Thread(target=sample) if observer else None + if sampler: + sampler.start() + thread = threading.Thread(target=run_action) if action else None + if thread: + thread.start() + try: + outcomes = [future.result() for future in futures] + finally: + sample_stop.set() + if sampler: + sampler.join() + if thread: + thread.join() + ended = time.monotonic() + if action_error: + raise action_error[0] + samples = sorted([row for records, _ in outcomes for row in records]) + successes = [row for row in samples if row[2] == (201 if row[1] == "write" else 200)] + failed = [row for row in samples if row[2] != (201 if row[1] == "write" else 200)] + latencies = [row[3] for row in successes] + report = { + "duration_seconds": round(ended - started, 4), "requested_seconds": duration, + "concurrency": concurrency, "successful_requests": len(successes), "failed_requests": len(failed), + "successful_rps": round(len(successes) / (ended - started), 3), + "error_ratio": round(len(failed) / len(samples), 6) if samples else None, + "successful_latency_ms": {name: percentile(latencies, fraction) + for name, fraction in (("p50", .5), ("p95", .95), ("p99", .99))}, + "all_attempt_latency_ms": {name: percentile([row[3] for row in samples], fraction) + for name, fraction in (("p50", .5), ("p95", .95), ("p99", .99))}, + "status_counts": dict(Counter(str(row[2]) for row in samples)), + "instance_counts": dict(Counter(row[4] for row in successes)), + "actions": actions, + "observations": observations, + "_samples": samples, + "_confirmed": [row for _, confirmations in outcomes for row in confirmations], + } + return report + + +def public_report(report): + return {key: value for key, value in report.items() if not key.startswith("_")} diff --git a/student-tests/ui_api_tests.py b/student-tests/ui_api_tests.py new file mode 100644 index 00000000..ed327bba --- /dev/null +++ b/student-tests/ui_api_tests.py @@ -0,0 +1,66 @@ +"""UI history must page backwards while the required API keeps ascending semantics.""" +import argparse +import json +import uuid + +from compose_helpers import sql +from client import Client, check, run, shape + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--base-url", default="http://localhost:8080") + args = parser.parse_args() + client = Client(args.base_url) + alice, bob, eve, chat = client.bootstrap() + previews_path = "/api/ui/chats?limit=1" + client.call("GET", previews_path, 401) + empty_previews = json.loads(client.call("GET", previews_path, actor=eve)["bytes"]) + check(not any(item["id"] == chat["id"] for item in empty_previews["items"]), "UI chat preview leaked a private chat") + initial = json.loads(client.call("GET", previews_path, actor=alice)["bytes"]) + check(initial["items"][0]["last_message"] is None, "empty chat has a phantom preview") + path = "/api/ui/chats/" + chat["id"] + "/messages" + client.call("GET", path, 401) + client.call("GET", path, 404, actor=eve) + members_path = "/api/ui/chats/" + chat["id"] + "/members" + client.call("GET", members_path, 401) + client.call("GET", members_path, 404, actor=eve) + members = json.loads(client.call("GET", members_path, actor=bob)["bytes"])["items"] + check({user["id"] for user in members} == {alice["id"], bob["id"]}, "wrong UI member list") + for member in members: + shape(member, "User") # rejects any password/hash fields in this projection + prefix = uuid.uuid4().hex[:20] + # Equal timestamps exercise the UUID tie-breaker in both directions. + sql(f""" + INSERT INTO messages(id, chat_id, sender_id, text, created_at) + SELECT ('{prefix}' || lpad(n::text, 12, '0'))::uuid, + '{chat['id']}'::uuid, '{alice['id']}'::uuid, 'UI pagination ' || n, + '2026-02-01T00:00:00Z'::timestamptz + FROM generate_series(1, 75) fixture(n); + """) + check(int(sql(f"SELECT count(*) FROM messages WHERE chat_id = '{chat['id']}';")) == 75, "UI fixture mismatch") + ascending = client.call("GET", "/api/v1/chats/" + chat["id"] + "/messages?limit=50", actor=alice, schema="MessagePage")["json"] + recent = client.call("GET", path + "?limit=50", actor=bob, schema="MessagePage")["json"] + older = client.call("GET", path + "?limit=50&cursor=" + recent["next_cursor"], actor=bob, schema="MessagePage")["json"] + previews = json.loads(client.call("GET", previews_path, actor=alice)["bytes"]) + check(previews["items"][0]["last_message"] == recent["items"][0], "preview did not use the latest UUID for equal-time messages") + second_chat = client.call("POST", "/api/v1/chats", 201, actor=alice, + body={"title": "Preview pagination", "member_ids": [alice["id"]]}, schema="Chat")["json"] + first = json.loads(client.call("GET", previews_path, actor=alice)["bytes"]) + second = json.loads(client.call("GET", previews_path + "&cursor=" + first["next_cursor"], actor=alice)["bytes"]) + check({first["items"][0]["id"], second["items"][0]["id"]} == {chat["id"], second_chat["id"]} + and second["next_cursor"] is None, "chat preview pagination lost or repeated chats") + client.call("GET", previews_path + "&cursor=" + first["next_cursor"], 400, actor=bob) + client.call("GET", "/api/v1/chats?cursor=" + first["next_cursor"], 400, actor=alice) + check([item["id"] for item in ascending["items"]] == sorted(item["id"] for item in ascending["items"]), "required history changed order") + check([item["id"] for item in recent["items"]] == sorted((item["id"] for item in recent["items"]), reverse=True), "UI history is not newest first") + all_items = recent["items"] + older["items"] + check(len(all_items) == 75 and len({item["id"] for item in all_items}) == 75 and older["next_cursor"] is None, + "UI pagination lost or repeated equal-time messages") + client.call("GET", path + "?cursor=" + ascending["next_cursor"], 400, actor=alice) + client.call("GET", "/api/v1/chats/" + chat["id"] + "/messages?cursor=" + recent["next_cursor"], 400, actor=alice) + print("PASS: UI authentication, privacy, newest page, backwards pagination, cursor isolation; required API stays ascending") + + +if __name__ == "__main__": + run(main) diff --git a/student-tests/ui_rendering.cjs b/student-tests/ui_rendering.cjs new file mode 100644 index 00000000..4f41a980 --- /dev/null +++ b/student-tests/ui_rendering.cjs @@ -0,0 +1,296 @@ +// Optional browser regression test. The application itself has no npm dependencies. +const { chromium, request } = require('playwright'); +const assert = require('node:assert/strict'); +const fs = require('node:fs/promises'); +const path = require('node:path'); +const { randomUUID } = require('node:crypto'); + +const baseURL = process.env.MESSENGER_TEST_URL || 'http://localhost:18080'; +const evidence = path.resolve(__dirname, '../evidence'); +const results = { verified_at: new Date().toISOString(), checks: [] }; +let browser, api; +const sessions = []; + +async function call(method, route, body, actor) { + const response = await api.fetch(route, { + method, data: body, + headers: { ...(actor ? { Authorization: 'Bearer ' + actor.token } : {}), ...(method === 'POST' && route.endsWith('/messages') ? { 'Idempotency-Key': randomUUID() } : {}) } + }); + assert(response.ok(), `${method} ${route}: HTTP ${response.status()}`); + return response.status() === 204 ? null : response.json(); +} + +async function account(suffix, name) { + const username = 'ui_' + suffix + '_' + randomUUID().slice(0, 8); + const password = randomUUID(); + await call('POST', '/api/v1/users', { username, display_name: name, password }); + const response = await api.post('/api/v1/auth/sessions', { + headers: { Authorization: 'Basic ' + Buffer.from(username + ':' + password).toString('base64') } + }); + assert.equal(response.status(), 201); + const actor = await response.json(); + sessions.push(actor); + return { ...actor, username, password }; +} + +async function login(page, actor) { + await page.goto(baseURL); + await page.locator('#login-username').fill(actor.username); + await page.locator('#login-password').fill(actor.password); + await page.locator('#login-form button[type=submit]').click(); + await page.locator('#app-screen').waitFor({ state: 'visible' }); +} + +async function decodeVisibleImage(page, selector) { + await page.waitForFunction(selector => { + const img = document.querySelector(selector); + return img?.complete && img.naturalWidth > 0; + }, selector); + await page.locator(selector).evaluate(img => img.decode()); +} + +async function openHistory(page, chat) { + await page.getByRole('button', { name: new RegExp(chat.title) }).click(); + await page.waitForFunction(() => document.querySelectorAll('article.message').length === 50); + await page.waitForFunction(() => [...document.querySelectorAll('.message-author')].some(e => e.textContent === 'Собеседник')); + await page.locator('#older-messages').click(); + await page.waitForFunction(() => document.querySelectorAll('article.message').length === 75); +} + +async function pollOnce(page, chat) { + await page.waitForResponse(r => r.url().includes(`/api/ui/chats/${chat.id}/messages?limit=50`) && r.status() === 200); + await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))); +} + +async function observeList(page) { + await page.evaluate(() => { + const list = document.querySelector('#message-list'); + const first = list.querySelector('article'); + const text = first.querySelector('.message-text').firstChild; + const selection = getSelection(); + const range = document.createRange(); + range.setStart(text, 0); range.setEnd(text, Math.min(10, text.length)); + selection.removeAllRanges(); selection.addRange(range); + window.uiAudit = { first, selection: selection.toString(), added: 0, removed: 0, records: 0 }; + window.uiAudit.observer = new MutationObserver(records => { + window.uiAudit.records += records.length; + for (const record of records) { + window.uiAudit.added += record.addedNodes.length; + window.uiAudit.removed += record.removedNodes.length; + } + }); + window.uiAudit.observer.observe(list, { childList: true, subtree: true, characterData: true }); + }); +} + +async function audit(page) { + return page.evaluate(() => ({ + added: window.uiAudit.added, removed: window.uiAudit.removed, records: window.uiAudit.records, + sameNode: window.uiAudit.first === document.querySelector('#message-list article'), + selectionPreserved: getSelection().toString() === window.uiAudit.selection + })); +} + +(async () => { + await fs.mkdir(evidence, { recursive: true }); + api = await request.newContext({ baseURL, timeout: 15000 }); + browser = await chromium.launch({ + executablePath: process.env.MESSENGER_BROWSER_PATH || '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', + headless: true + }); + const page = await browser.newPage({ viewport: { width: 1280, height: 850 }, deviceScaleFactor: 1 }); + const errors = []; + page.on('pageerror', error => errors.push(error.message)); + await page.goto(baseURL); + await page.locator('.spirit-svg').waitFor(); + await page.screenshot({ path: path.join(evidence, 'ui-kolovertysh-login.png') }); + await page.locator('#login-username').fill('mascot_preview'); + await page.waitForFunction(() => document.querySelector('#mascot-stage').dataset.mood === 'looking'); + await page.mouse.move(850, 400); + await page.waitForFunction(() => document.querySelector('#mascot-stage').style.getPropertyValue('--gaze-x') !== ''); + await page.route('**/api/v1/auth/sessions', route => route.fulfill({ status: 401, contentType: 'application/json', body: JSON.stringify({error:{message:'Invalid credentials'}}) })); + await page.locator('#login-password').fill('invalid_preview'); + await page.locator('#login-form button[type=submit]').click(); + await page.locator('#auth-error-art').waitFor({ state: 'visible' }); + assert.equal(await page.locator('#mascot-stage').getAttribute('data-mood'), 'error'); + await page.unroute('**/api/v1/auth/sessions'); + results.checks.push('mascot: input reaction, event-driven gaze, authentication-error illustration'); + + const mobile = await browser.newPage({ viewport: { width: 320, height: 844 }, deviceScaleFactor: 1 }); + mobile.on('pageerror', error => errors.push(error.message)); + await mobile.goto(baseURL); + await mobile.locator('#login-password').fill('preview_password'); + await mobile.waitForFunction(() => document.querySelector('#mascot-stage').dataset.mood === 'private'); + await mobile.waitForFunction(() => { + const m = getComputedStyle(document.querySelector('.spirit-hand-left')).transform; + return m !== 'none' && Number(m.match(/matrix\((.*)\)/)?.[1].split(',')[4]) > 20; + }); + assert(await mobile.evaluate(() => document.documentElement.scrollWidth <= document.documentElement.clientWidth)); + await mobile.screenshot({ path: path.join(evidence, 'ui-kolovertysh-mobile.png'), fullPage: true }); + await mobile.locator('[data-password-toggle=login-password]').click(); + assert.equal(await mobile.locator('#login-password').getAttribute('type'), 'text'); + await mobile.emulateMedia({ reducedMotion: 'reduce' }); + assert.equal(await mobile.locator('.spirit-motion').evaluate(e => getComputedStyle(e).animationName), 'none'); + results.checks.push('mobile 320px: no horizontal overflow, private/revealed password, reduced motion'); + await mobile.locator('#tab-register').click(); + await mobile.locator('#register-password').fill('short'); + await mobile.waitForFunction(() => document.querySelector('#mascot-stage').dataset.mood === 'short'); + await mobile.locator('#register-password').fill('long_preview_password'); + await mobile.waitForFunction(() => document.querySelector('#mascot-stage').dataset.mood === 'private'); + await mobile.setViewportSize({ width: 390, height: 844 }); + assert(await mobile.evaluate(() => document.documentElement.scrollWidth <= document.documentElement.clientWidth)); + results.checks.push('registration: short-password/private states, 390px without overflow'); + await mobile.close(); + + const alice = await account('alice', 'Проверка интерфейса'); + const bob = await account('bob', 'Собеседник'); + const chat = await call('POST', '/api/v1/chats', { + title: 'Проверка интерфейса ' + randomUUID().slice(0, 4), member_ids: [alice.user.id, bob.user.id] + }, alice); + const seeded = []; + const phrases = ['Привет! Проверяю обновлённый чат.', 'Теперь сообщения собраны аккуратнее.', 'Старую историю можно читать без скачков.', 'Да, и выделенный текст сохраняется.', 'Новые сообщения появляются внизу.', 'К ним можно перейти отдельной кнопкой.']; + for (let n = 0; n < 75; n++) { + seeded.push(await call('POST', `/api/v1/chats/${chat.id}/messages`, { + text: phrases[n % phrases.length] + (n % 10 === 0 ? ' Проверка длинного сообщения: строка должна переноситься внутри пузырька и оставаться читаемой на телефоне.' : '') + }, Math.floor(n / 3) % 2 ? bob : alice)); + } + + if (process.env.MESSENGER_BASELINE_APP) { + const baseline = await browser.newPage({ viewport: { width: 1280, height: 850 } }); + await baseline.route('**/app.js', route => route.fulfill({ contentType: 'text/javascript', path: process.env.MESSENGER_BASELINE_APP })); + await login(baseline, alice); await openHistory(baseline, chat); + await observeList(baseline); await pollOnce(baseline, chat); + results.before = await audit(baseline); + assert(results.before.removed > 0 && !results.before.sameNode); + await baseline.locator("#logout").click(); + await baseline.locator("#auth-screen").waitFor({ state: "visible" }); + await baseline.close(); + } + + await page.route('**/api/ui/chats?limit=100', route => route.fulfill({ status: 503, contentType: 'application/json', body: JSON.stringify({error:{message:'Сервис временно недоступен'}}) })); + await login(page, alice); + await page.locator('#workspace-error').waitFor({state:'visible'}); + await decodeVisibleImage(page, '#workspace-error img'); + await page.screenshot({path:path.join(evidence,'ui-kolovertysh-error.png')}); + await page.unroute('**/api/ui/chats?limit=100'); + await page.locator('#retry-chats').click(); + await page.locator('#welcome').waitFor({state:'visible'}); + const chatRow = page.locator(`[data-chat-id="${chat.id}"]`); + await chatRow.waitFor(); + assert.equal(await chatRow.locator('.chat-preview').textContent(), 'Вы: ' + seeded.at(-1).text); + assert.equal(await chatRow.locator('time').getAttribute('datetime'), seeded.at(-1).created_at); + const avatar = await chatRow.locator('.avatar svg').evaluate(e => e.outerHTML); + await page.locator('#refresh-chats').click(); + await page.waitForFunction(() => !document.querySelector('#refresh-chats').classList.contains('is-loading')); + assert.equal(await chatRow.locator('.avatar svg').evaluate(e => e.outerHTML), avatar); + assert.equal(await chatRow.locator('.avatar svg').evaluate(e => getComputedStyle(e).stroke), 'none'); + results.checks.push('chat previews: latest text and timestamp, deterministic SVG avatar survives refresh without inherited icon stroke'); + assert(await page.locator('#workspace-error').isHidden()); + assert.equal(await page.locator('#mascot-stage').evaluate(e => e.classList.contains('is-visible')), false); + results.checks.push('initial chat-list failure: illustrated retry state, successful recovery, hidden mascot paused'); + const emptyChat = await call('POST', '/api/v1/chats', {title:'Пустой разговор ' + randomUUID().slice(0,4), member_ids:[alice.user.id]}, alice); + await page.locator('#refresh-chats').click(); + await page.getByRole('button', {name:new RegExp(emptyChat.title)}).waitFor(); + const messageRoute = `**/api/ui/chats/${emptyChat.id}/messages?limit=50`; + await page.route(messageRoute, route => route.fulfill({status:503,contentType:'application/json',body:JSON.stringify({error:{message:'Сервис временно недоступен'}})})); + await page.getByRole('button', {name:new RegExp(emptyChat.title)}).click(); + await page.locator('#conversation-error').waitFor({state:'visible'}); + assert(await page.locator('#empty-conversation').isHidden()); + await page.unroute(messageRoute); + await page.locator('#retry-messages').click(); + await page.locator('#empty-conversation').waitFor({state:'visible'}); + assert(await page.locator('#conversation-error').isHidden()); + await decodeVisibleImage(page, '#empty-conversation img'); + await page.screenshot({path:path.join(evidence,'ui-kolovertysh-empty.png')}); + results.checks.push('message-load failure does not look empty; retry recovers to illustrated empty conversation'); + await page.reload(); + await page.locator('#welcome').waitFor({state:'visible'}); + await decodeVisibleImage(page, '.welcome-illustration'); + await page.screenshot({ path: path.join(evidence, 'ui-illustration-welcome.png') }); + await openHistory(page, chat); + const expected = [...seeded].sort((a, b) => a.created_at.localeCompare(b.created_at) || a.id.localeCompare(b.id)).map(m => m.id); + assert.deepEqual(await page.locator('article.message').evaluateAll(nodes => nodes.map(n => n.dataset.messageId)), expected); + assert(await page.locator('article.message.grouped').count() > 0); + await observeList(page); await pollOnce(page, chat); + results.after = await audit(page); + assert.equal(results.after.records, 0, 'unchanged poll mutated message list'); + assert(results.after.sameNode && results.after.selectionPreserved); + results.checks.push('75 messages across two pages: order, unique IDs, grouping'); + results.checks.push('unchanged poll: zero message-list mutations, original node and selection preserved'); + + await page.locator('#message-scroll').evaluate(e => { e.scrollTop = 0; }); + const beforeScroll = await page.locator('#message-scroll').evaluate(e => e.scrollTop); + const arrival = await call('POST', `/api/v1/chats/${chat.id}/messages`, { text: 'Новое сообщение пришло, пока вы читали историю.' }, bob); + await page.locator(`article[data-message-id="${arrival.id}"]`).waitFor(); + assert.equal(await page.locator('#message-scroll').evaluate(e => e.scrollTop), beforeScroll); + await page.waitForFunction(() => document.querySelector('#jump-latest').textContent.includes('Новые сообщения: 1')); + assert((await audit(page)).sameNode && (await audit(page)).selectionPreserved); + await page.locator('#jump-latest').click(); + await page.waitForFunction(() => document.querySelector('#jump-latest').hidden); + results.checks.push('incoming message: original nodes/selection/scroll preserved, new-message button returns to bottom'); + + await page.locator('#message-input').fill('Сообщение отправлено из браузера.'); + await page.locator('#send-message').click(); + await page.waitForFunction(() => document.querySelectorAll('article.message').length === 77); + assert.equal(await chatRow.locator('.chat-preview').textContent(), 'Вы: Сообщение отправлено из браузера.'); + const ids = await page.locator('article.message').evaluateAll(nodes => nodes.map(n => n.dataset.messageId)); + assert.equal(new Set(ids).size, ids.length); + await pollOnce(page, chat); + assert.equal(await page.locator('article.message').count(), 77); + results.checks.push('own send followed by poll: no duplicate messages'); + + const retryKeys = []; + const retryRoute = `**/api/v1/chats/${chat.id}/messages`; + await page.route(retryRoute, async route => { + retryKeys.push(route.request().headers()['idempotency-key']); + if (retryKeys.length === 1) { + const committed = await route.fetch(); + assert.equal(committed.status(), 201); + await route.abort('failed'); + } else await route.continue(); + }); + await page.locator('#message-input').fill('Повтор после потерянного ответа.'); + await page.locator('#send-message').click(); + await page.getByText('Ответ не получен. Повторите отправку: сообщение не продублируется.', {exact:true}).waitFor(); + await page.locator('#send-message').click(); + await page.waitForFunction(() => document.querySelector('#message-input').value === ''); + await pollOnce(page, chat); + assert.equal(retryKeys.length, 2); + assert(retryKeys[0] && retryKeys[0] === retryKeys[1]); + assert.equal(await page.locator('article.message').count(), 78); + await page.unroute(retryRoute); + results.checks.push('lost response after COMMIT: manual retry preserves key and creates one message'); + + await page.locator('#toast').waitFor({ state: 'hidden' }); + await page.locator('#message-scroll').evaluate(e => { e.scrollTop = e.scrollHeight; }); + await page.locator('#conversation').evaluate(e => Promise.all(e.getAnimations({ subtree: true }).map(a => a.finished))); + await page.screenshot({ path: path.join(evidence, 'ui-optimized-chat.png') }); + + await page.setViewportSize({ width: 390, height: 844 }); + await page.waitForFunction(() => document.documentElement.clientWidth === 390); + await page.locator('#message-scroll').evaluate(e => { e.scrollTop = e.scrollHeight; }); + assert(await page.evaluate(() => document.documentElement.scrollWidth <= document.documentElement.clientWidth)); + await page.screenshot({ path: path.join(evidence, 'ui-optimized-chat-mobile.png') }); + await page.locator('#show-members').click(); + assert.equal(await page.locator('#members-list .avatar svg').count(), 2); + assert(await page.locator('#members-dialog').evaluate(e => e.scrollWidth <= e.clientWidth)); + await page.locator('#members-dialog [data-close-dialog]').click(); + results.checks.push('mobile conversation 390px: no horizontal overflow'); + await page.locator('#back-to-chats').click(); + await page.locator('#logout').click(); + await page.locator('#auth-screen').waitFor({ state: 'visible' }); + results.checks.push('welcome, empty-conversation and error illustrations decoded when shown'); + assert.deepEqual(errors, []); + results.checks.push('no uncaught browser errors'); + results.fixture = { chat_id: chat.id, messages: 78 }; + await fs.writeFile(path.join(evidence, 'ui-optimization.json'), JSON.stringify(results, null, 2) + '\n'); + console.log(JSON.stringify(results, null, 2)); +})().catch(error => { + console.error(error.stack || error.message); + process.exitCode = 1; +}).finally(async () => { + for (const actor of sessions) { + try { await call('DELETE', '/api/v1/auth/sessions/current', undefined, actor); } catch {} + } + await browser?.close(); await api?.dispose(); +}); diff --git a/student-tests/ui_showcase.cjs b/student-tests/ui_showcase.cjs new file mode 100644 index 00000000..c49d70d9 --- /dev/null +++ b/student-tests/ui_showcase.cjs @@ -0,0 +1,111 @@ +// Integration test against the real cluster; includes a real, automatically restored container stop. +const { chromium, request } = require('playwright'); +const assert = require('node:assert/strict'); +const { randomUUID } = require('node:crypto'); +const { spawn } = require('node:child_process'); +const fs = require('node:fs/promises'); +const path = require('node:path'); +const baseURL = process.env.MESSENGER_TEST_URL || 'http://127.0.0.1:18080'; +const evidence = path.resolve(__dirname, '../evidence'); +const actors = [], errors = [], checks = []; +let api, browser, demo; + +async function call(method, route, actor, data) { + const response = await api.fetch(route, {method, data, + headers:{...(actor ? {Authorization:'Bearer '+actor.token} : {}), ...(method==='POST' && route.endsWith('/messages') ? {'Idempotency-Key':randomUUID()} : {})}}); + assert(response.ok(), `${method} ${route.split('?')[0]}: ${response.status()}`); + return response.status()===204 ? null : response.json(); +} +async function actor(name) { + const username = 'show_' + randomUUID().replaceAll('-','').slice(0,16), password = randomUUID(); + await call('POST','/api/v1/users',null,{username,password,display_name:name}); + const response = await api.post('/api/v1/auth/sessions',{headers:{Authorization:'Basic '+Buffer.from(username+':'+password).toString('base64')}}); + assert.equal(response.status(),201); const value=await response.json(); actors.push(value); return value; +} +async function pageFor(actor, chat) { + const page=await browser.newPage({viewport:{width:1440,height:1000}}); + page.on('pageerror',error=>errors.push(error.message)); + await page.addInitScript(session=>sessionStorage.setItem('n1k0der.session',JSON.stringify(session)),actor); + await page.goto(baseURL); await page.locator(`[data-chat-id="${chat.id}"]`).click(); + await page.locator('article.message').first().waitFor(); return page; +} +const row=(page,id)=>page.locator(`article[data-message-id="${id}"]`); + +(async()=>{ + await fs.mkdir(evidence,{recursive:true}); + api=await request.newContext({baseURL,timeout:15000}); + browser=await chromium.launch({executablePath:process.env.MESSENGER_BROWSER_PATH || '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',headless:true}); + const alice=await actor('Никита'), bob=await actor('Собеседник'); + const chat=await call('POST','/api/v1/chats',alice,{title:'Защита · живой мессенджер',member_ids:[alice.user.id,bob.user.id]}); + const message=await call('POST',`/api/v1/chats/${chat.id}/messages`,bob,{text:'Привет! Проверим реакции и работу двух API 🍄'}); + await call('POST',`/api/v1/chats/${chat.id}/messages`,alice,{text:'Да! Сейчас отключим один экземпляр. Переписка продолжит работать.'}); + const a=await pageFor(alice,chat), b=await pageFor(bob,chat); + await row(a,message.id).locator('.reaction-picker').click(); + await row(a,message.id).getByRole('button',{name:'Гриб',exact:true}).click(); + await a.waitForFunction(id=>document.querySelector(`article[data-message-id="${id}"] [data-reaction=mushroom]`)?.getAttribute('aria-pressed')==='true',message.id); + await b.waitForFunction(id=>document.querySelector(`article[data-message-id="${id}"] [data-reaction=mushroom]`)?.textContent==='🍄 1',message.id); + assert.equal(await row(b,message.id).locator('[data-reaction=mushroom]').getAttribute('aria-pressed'),'false'); + await row(b,message.id).locator('[data-reaction=mushroom]').click(); + await a.waitForFunction(id=>document.querySelector(`article[data-message-id="${id}"] [data-reaction=mushroom]`)?.textContent==='🍄 2',message.id); + checks.push('real two-window reactions: shared count, per-user mine state'); + await a.locator('.sidebar-diagnostics').click(); + await a.waitForFunction(()=>document.querySelectorAll('.cluster-api[data-state=up]').length>=2); + await a.locator('#cluster-probe').click(); + await a.waitForFunction(()=>document.querySelector('#cluster-detail').textContent.includes('200')); + const liveResponse=await api.get('/health/ready'); + assert.equal(liveResponse.status(),200); + const target=liveResponse.headers()['x-instance-id']; + await a.locator(`.cluster-api[data-instance-id="${target}"][data-state=up]`).waitFor(); + assert.match(target,/^[a-f0-9]{32}$/); + checks.push('live diagram: actual Redis heartbeats, real X-Instance-Id response and counters'); + await a.locator('.cluster-demo summary').click(); + await a.screenshot({path:path.join(evidence,'ui-showcase-live.png')}); + let output=''; + demo=spawn('python3',['scripts/demo-failover.py','--instance',target,'--seconds','22','--base-url',baseURL],{cwd:path.resolve(__dirname,'..'),stdio:['ignore','pipe','pipe']}); + demo.stdout.on('data',chunk=>{output+=chunk.toString()}); demo.stderr.on('data',chunk=>{output+=chunk.toString()}); + const completion=new Promise((resolve,reject)=>{demo.on('error',reject); demo.on('close',code=>code===0 ? resolve() : reject(new Error('Failover demo failed: '+output)));}); + // Attach a handler immediately so an early script failure is not an unhandled rejection. + completion.catch(()=>{}); + await a.waitForFunction(id=>document.querySelector(`[data-instance-id="${id}"]`)?.dataset.state==='down',target,{timeout:25000}); + await a.locator('#message-input').fill('Один API отключён, а сообщение всё равно доставлено ✓'); + await a.locator('#send-message').click(); + await b.locator('#message-list').getByText('Один API отключён, а сообщение всё равно доставлено ✓',{exact:true}).waitFor(); + const during=await call('GET','/api/ui/cluster',alice); + assert.equal(during.instances.filter(node=>node.ready).length,1); + await row(b,message.id).locator('.reaction-picker').click(); + await row(b,message.id).getByRole('button',{name:'Сердце',exact:true}).click(); + await a.waitForFunction(id=>document.querySelector(`article[data-message-id="${id}"] [data-reaction=love]`)?.textContent==='❤️ 1',message.id); + assert.equal((await call('GET','/api/ui/cluster',alice)).instances.filter(node=>node.ready).length,1); + await a.screenshot({path:path.join(evidence,'ui-showcase-failover.png')}); + await completion; demo=null; + await a.waitForFunction(()=>document.querySelectorAll('.cluster-api[data-state=up]').length>=2,{},{timeout:20000}); + assert(output.includes('Восстанавливаем') && output.includes('Готово.')); + checks.push('real Docker stop: heartbeat disappears, browser sends message and reaction via surviving API, script restores replicas'); + const cluster=await call('GET','/api/ui/cluster',alice); + assert(cluster.instances.some(node=>node.id===target && !node.ready)); + assert(cluster.instances.filter(node=>node.ready).length>=2); + checks.push('restart is shown with new process ID; old missing heartbeat is not mislabelled as recovery'); + await a.route('**/api/ui/cluster',route=>route.fulfill({status:200,contentType:'application/json',body:JSON.stringify({redis_available:false,postgres_available:true,checked_at:Date.now(),instances:[]})})); + await a.locator('#cluster-probe').click(); + await a.waitForFunction(()=>document.querySelector('#cluster-status').textContent.includes('неизвестно')); + assert.equal(await a.locator('.cluster-api[data-state=down]').count(),0); + assert(await a.locator('#cluster-copy').isDisabled()); + await a.unroute('**/api/ui/cluster'); + await a.locator('#cluster-probe').click(); + await a.waitForFunction(()=>document.querySelectorAll('.cluster-api[data-state=up]').length>=2); + checks.push('missing Redis telemetry is shown as unknown, rather than a false API outage'); + await a.setViewportSize({width:390,height:844}); + assert(await a.evaluate(()=>document.documentElement.scrollWidth<=document.documentElement.clientWidth)); + assert(await a.locator('#diagnostics-panel').evaluate(e=>e.scrollWidth<=e.clientWidth)); + await a.screenshot({path:path.join(evidence,'ui-showcase-mobile.png')}); + await a.emulateMedia({reducedMotion:'reduce'}); + assert.equal(await a.locator('.cluster-api').first().evaluate(e=>getComputedStyle(e).transitionDuration),'0s'); + checks.push('390px diagram: no horizontal overflow; reduced motion supported'); + assert.deepEqual(errors,[]); + await fs.writeFile(path.join(evidence,'ui-showcase.json'),JSON.stringify({checks,errors,failover:output},null,2)+'\n'); + console.log(JSON.stringify({checks,errors},null,2)); +})().catch(error=>{console.error(error.stack);process.exitCode=1;}).finally(async()=>{ + if(demo && demo.exitCode===null && demo.signalCode===null){demo.kill('SIGTERM');await new Promise(resolve=>demo.once('close',resolve));} + for(const value of actors){try{await call('DELETE','/api/v1/auth/sessions/current',value)}catch{}} + await browser?.close();await api?.dispose(); +});