diff --git a/.env.example b/.env.example index 2b32655..75cbf59 100644 --- a/.env.example +++ b/.env.example @@ -1,30 +1,39 @@ -# Copy to .env for your LOCAL synthetic test environment; never commit .env. -# These are logical interface suggestions; map actual framework names in REPORT.md. +# Copy to .env for a LOCAL synthetic test environment; never commit .env. APP_HOST=0.0.0.0 -APP_PORT=8080 +APP_INTERNAL_PORT=8080 +PUBLIC_PORT=8080 +GRAFANA_PORT=3000 +PROMETHEUS_PORT=9090 +LOKI_PORT=3100 +TEMPO_PORT=3200 APP_ENV=lab SESSION_TTL_SECONDS=3600 -# Choose credentials locally. File paths contain no secret values. DATABASE_URL_FILE=/run/secrets/database_url -# Optional on 3, required use on 4 in lab2; Redis OR Valkey: SESSION_STORE=postgres -CACHE_URL_FILE=/run/secrets/cache_url +CACHE_URL=redis://redis:6379/0 API_REPLICAS=2 IDEMPOTENCY_TTL_SECONDS=86400 -S3_ENDPOINT=http://s3:9000 +S3_ENDPOINT=http://minio:9000 S3_REGION=us-east-1 S3_BUCKET=messenger-attachments S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key +S3_OPERATION_TIMEOUT=5s MAX_UPLOAD_BYTES=10485760 MAX_IMAGE_PIXELS=40000000 BROKER_URL_FILE=/run/secrets/broker_url WORKER_CONCURRENCY=2 JOB_MAX_ATTEMPTS=5 JOB_TIMEOUT_SECONDS=60 +JOB_RETRY_BASE=250ms +JOB_RETRY_MAX=4s +JOB_LEASE_SECONDS=75 STAGING_RETENTION_SECONDS=86400 -OTEL_SERVICE_NAME=messenger-api -# Worker must set a distinct service.name. +STAGING_CLEANUP_INTERVAL_SECONDS=30 +API_GO_MEMORY_LIMIT=220MiB +WORKER_GO_MEMORY_LIMIT=448MiB +WORKER_MEMORY_LIMIT=512M +# Both API and worker use this OTLP/HTTP endpoint; service.name is assigned in code. OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318 OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf -OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=lab +OTEL_EXPORTER_OTLP_TIMEOUT=3000 diff --git a/.github/workflows/contracts.yml b/.github/workflows/contracts.yml index 11cf289..d7da3a8 100644 --- a/.github/workflows/contracts.yml +++ b/.github/workflows/contracts.yml @@ -1,4 +1,4 @@ -name: Skeleton contracts +name: Lab 6 checks on: [push, pull_request] permissions: contents: read @@ -12,5 +12,43 @@ jobs: python-version: '3.12' - run: python -m pip install -r requirements-dev.txt - run: make check validate PYTHON=python -# This job validates the skeleton, not a student solution. -# Add build, readiness and make test in a separate application job. + + application: + runs-on: ubuntu-latest + needs: contracts + timeout-minutes: 25 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - uses: actions/setup-go@v6 + with: + go-version-file: go.mod + cache: true + - name: Audit Go code and dependencies + run: | + go mod verify + go test -race -count=1 ./... + go vet ./... + go run golang.org/x/vuln/cmd/govulncheck@v1.9.0 ./... + - name: Initialize local CI configuration + run: | + cp .env.example .env + make init-secrets + - name: Validate and start the complete stack + run: | + docker compose --env-file .env config --quiet + docker compose --env-file .env up -d --build --wait + - name: Run public API smoke test + run: make test + - name: Verify the telemetry path + run: make test-observability-grade4 + - name: Show service state and logs on failure + if: failure() + run: | + docker compose ps -a + docker compose logs --no-color --tail=300 + - name: Remove ephemeral CI resources + if: always() + run: docker compose down --volumes --remove-orphans diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..8c9473b --- /dev/null +++ b/Dockerfile @@ -0,0 +1,41 @@ +FROM golang:1.27.1-alpine@sha256:8a5910f31396cd4d89662f56c68b3ae31d374308270a1c3bd96672ee5ed43414 AS builder + +WORKDIR /build + +COPY go.mod go.sum ./ +RUN go mod download + +COPY cmd/ ./cmd/ +COPY internal/ ./internal/ + + +RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-w -s" -o /build/server ./cmd/server/main.go +RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-w -s" -o /build/reconciler ./cmd/reconciler/main.go +RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-w -s" -o /build/worker ./cmd/worker/main.go +RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-w -s" -o /build/dispatcher ./cmd/dispatcher/main.go +RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-w -s" -o /build/jobctl ./cmd/jobctl/main.go + +FROM alpine:3.24@sha256:294b683cb724975bec92580e1e685676bd4b50bda910ddb8c51d4cabeaec77e6 + +RUN addgroup -g 1000 appgroup && \ + adduser -u 1000 -G appgroup -s /bin/sh -D appuser + +WORKDIR /app + +COPY --from=builder /build/server /app/server +COPY --from=builder /build/reconciler /app/reconciler +COPY --from=builder /build/worker /app/worker +COPY --from=builder /build/dispatcher /app/dispatcher +COPY --from=builder /build/jobctl /app/jobctl + +RUN chown -R appuser:appgroup /app + +USER appuser:appgroup + +EXPOSE 8080 + +HEALTHCHECK --interval=5s --timeout=3s --start-period=5s --retries=10 \ + CMD wget -qO- http://127.0.0.1:8080/health/ready || exit 1 + + +ENTRYPOINT ["/app/server"] diff --git a/Makefile b/Makefile index 5d86d17..fa327c6 100644 --- a/Makefile +++ b/Makefile @@ -2,12 +2,20 @@ PYTHON ?= python3 BASE_URL ?= http://localhost:8080 CA_FILE ?= ACTION_SCRIPT ?= +RECONCILE_GRACE ?= 15m +PROMETHEUS_URL ?= http://localhost:9090 +LOKI_URL ?= http://localhost:3100 +TEMPO_URL ?= http://localhost:3200 +GRAFANA_URL ?= http://localhost:3000 TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) -.PHONY: help check validate test load test-persistence test-failover +.PHONY: help init-secrets check validate test load test-observability-grade3 test-observability-grade4 test-observability-retry-trace test-observability-alerts test-telemetry-backend-outage test-slo-burn-rate test-histogram-calibration test-observability-incidents test-attachment-boundaries test-attachment-memory test-storage-outage test-minio-policy test-async-resilience test-level4-resilience test-level5-idempotency jobs-failed replay-job upgrade-pipeline inject-job test-persistence test-failover test-reconcile test-reconcile-scale reconcile-dry-run reconcile-apply cleanup-lab help: - @echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes" + @echo "check: offline structure; validate: full OpenAPI; test: running API; cleanup-lab: stop lab6 and remove only its locally built images" + +init-secrets: + ./scripts/init-secrets.sh check: $(PYTHON) scripts/check_contract.py @@ -21,6 +29,69 @@ test: load: $(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS) +test-observability-grade3: + $(PYTHON) tests/observability_grade3.py --prometheus-url "$(PROMETHEUS_URL)" --loki-url "$(LOKI_URL)" --tempo-url "$(TEMPO_URL)" --grafana-url "$(GRAFANA_URL)" + +test-observability-grade4: + $(PYTHON) tests/observability_grade4.py --base-url "$(BASE_URL)" --prometheus-url "$(PROMETHEUS_URL)" --loki-url "$(LOKI_URL)" --tempo-url "$(TEMPO_URL)" --grafana-url "$(GRAFANA_URL)" + +test-observability-retry-trace: + $(PYTHON) tests/observability_retry_trace.py --base-url "$(BASE_URL)" --loki-url "$(LOKI_URL)" --tempo-url "$(TEMPO_URL)" + +test-observability-alerts: + $(PYTHON) tests/observability_alerts.py --base-url "$(BASE_URL)" --prometheus-url "$(PROMETHEUS_URL)" --loki-url "$(LOKI_URL)" --tempo-url "$(TEMPO_URL)" + +test-telemetry-backend-outage: + $(PYTHON) tests/telemetry_backend_outage.py --base-url "$(BASE_URL)" --prometheus-url "$(PROMETHEUS_URL)" --loki-url "$(LOKI_URL)" --tempo-url "$(TEMPO_URL)" + +test-slo-burn-rate: + $(PYTHON) tests/slo_burn_rate.py --base-url "$(BASE_URL)" --prometheus-url "$(PROMETHEUS_URL)" --loki-url "$(LOKI_URL)" --tempo-url "$(TEMPO_URL)" --grafana-url "$(GRAFANA_URL)" + +test-histogram-calibration: + $(PYTHON) tests/histogram_calibration.py --base-url "$(BASE_URL)" --prometheus-url "$(PROMETHEUS_URL)" + +test-observability-incidents: + $(MAKE) test-async-resilience BASE_URL="$(BASE_URL)" + $(MAKE) test-storage-outage BASE_URL="$(BASE_URL)" + $(PYTHON) tests/observability_incidents.py --prometheus-url "$(PROMETHEUS_URL)" --loki-url "$(LOKI_URL)" --tempo-url "$(TEMPO_URL)" + +test-attachment-memory: + BASE_URL="$(BASE_URL)" $(PYTHON) tests/attachment_memory.py + +test-attachment-boundaries: + BASE_URL="$(BASE_URL)" $(PYTHON) tests/attachment_boundaries.py + +test-storage-outage: + BASE_URL="$(BASE_URL)" $(PYTHON) tests/storage_outage.py + +test-minio-policy: + ./tests/minio_policy.sh + +test-async-resilience: + $(PYTHON) tests/async_resilience.py --base-url "$(BASE_URL)" $(TLS_ARGS) + +test-level4-resilience: + $(PYTHON) tests/level4_resilience.py --base-url "$(BASE_URL)" $(TLS_ARGS) + +test-level5-idempotency: + $(PYTHON) tests/level5_idempotency.py --base-url "$(BASE_URL)" $(TLS_ARGS) + +jobs-failed: + docker compose run --rm --no-deps --entrypoint /app/jobctl dispatcher list-failed + +replay-job: + @test -n "$(JOB_ID)" || (echo "Set JOB_ID to a failed attachment job UUID"; exit 2) + docker compose run --rm --no-deps --entrypoint /app/jobctl dispatcher replay "$(JOB_ID)" + +upgrade-pipeline: + @test -n "$(ATTACHMENT_ID)" || (echo "Set ATTACHMENT_ID"; exit 2) + @test -n "$(PIPELINE_VERSION)" || (echo "Set PIPELINE_VERSION=2"; exit 2) + docker compose run --rm --no-deps --entrypoint /app/jobctl worker upgrade "$(ATTACHMENT_ID)" "$(PIPELINE_VERSION)" + +inject-job: + @test -n "$(JOB_ID)" || (echo "Set JOB_ID"; exit 2) + docker compose run --rm --no-deps --entrypoint /app/jobctl dispatcher inject "$(JOB_ID)" + 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) @@ -28,3 +99,18 @@ test-persistence: test-failover: @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2) $(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) + +test-reconcile: + $(PYTHON) tests/reconcile_integration.py + +test-reconcile-scale: + $(PYTHON) tests/reconcile_scale.py + +reconcile-dry-run: + docker compose run --rm --entrypoint /app/reconciler api --grace-period "$(RECONCILE_GRACE)" + +reconcile-apply: + docker compose run --rm --entrypoint /app/reconciler api --grace-period "$(RECONCILE_GRACE)" --apply + +cleanup-lab: + ./scripts/cleanup-lab.sh diff --git a/REPORT.md b/REPORT.md index b97ae42..60761ff 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,199 @@ # Отчёт — лабораторная 6 -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- Автор, группа: Чурилин Данила, БВТ2301 +- Текущий подготовленный уровень: оценка «5», трек 2 «SLO и обнаружение инцидентов» +- Ветка: `solution/bvt2301-churilin` +- Commit/PR: не создавались +- Использованные источники, библиотеки и помощь ИИ: OpenTelemetry Go SDK 1.46.0, OpenTelemetry Collector Contrib 0.165.0, Prometheus 3.16.0, Loki 3.7.9, Tempo 2.10.5, Grafana 13.3.0; официальная документация OpenTelemetry, Prometheus и Grafana; OpenAI Codex использован для анализа требований, реализации, тестирования и оформления отчёта ## Запуск из чистого clone -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +Нужны Docker Engine с Compose v2, GNU Make, Python 3.9+ и OpenSSL. Локальный Go для запуска стенда не обязателен. -## Архитектура и решения +```sh +cp .env.example .env +make init-secrets +docker compose --env-file .env config --quiet +docker compose --env-file .env up -d --build --wait -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab5, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +make check +make test +make test-observability-grade3 +make test-observability-grade4 +make test-observability-retry-trace +make test-observability-alerts +make test-telemetry-backend-outage +make test-slo-burn-rate +``` -## Доказательства критериев +`make init-secrets` создаёт игнорируемые Git файлы в `secrets/` с mode 600 и не перезаписывает существующие значения. Миграции выполняет одноразовый `migrate`, а `minio-bootstrap` идемпотентно создаёт приватный bucket и ограниченного S3-пользователя. -| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | -| --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | +Порты по умолчанию: приложение `127.0.0.1:8080`, Grafana `:3000`, Prometheus `:9090`, Loki `:3100`, Tempo `:3200`. Они привязаны к loopback и переопределяются переменными из `.env.example`. -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +После проверки каждого уровня (3, 4, 5) и после завершения лабораторной выполняется: -## Эксперименты и отказы +```sh +make cleanup-lab +``` -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +Команда делает `docker compose down --remove-orphans` и удаляет только пять локально собранных образов с точными именами `mtusi2026lab6-*`. Именованные volumes, pulled-образы и ресурсы других лабораторных сохраняются. Намеренный полный сброс учебных данных остаётся отдельной командой `docker compose down --volumes` и в автоматическую очистку не входит. -| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | -| --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +## Архитектура и причинная связь -## Ограничения и следующие шаги +```text +client -> HAProxy -> API x2 -> PostgreSQL + staging S3 + | + W3C traceparent/tracestate + v + outbox -> dispatcher -- producer span --> RabbitMQ + | + v + consumer span + worker + -> S3 + PostgreSQL -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +API / dispatcher / worker -- OTLP --> Collector -- metrics --> Prometheus + | -- logs ----> Loki + '---------- traces ---> Tempo +Prometheus + Loki + Tempo ----------------------------------> Grafana +``` + +PostgreSQL — источник истины для metadata и outbox/job, MinIO — для объектов, RabbitMQ — persistent at-least-once transport, Redis — восстанавливаемый cache. Бизнес-ответ и обработка job не зависят от успешности экспорта телеметрии. + +API инжектирует W3C `traceparent`/`tracestate` в атомарно созданную outbox job. Dispatcher извлекает сохранённый context, создаёт `PRODUCER` span, помещает новый context в AMQP headers. Worker извлекает headers до claim и создаёт `CONSUMER` span. При retry исходный parent сохраняется, а новая producer/consumer-пара остаётся в той же трассе. S3 и PostgreSQL операции — дочерние `CLIENT` spans. `postgresql.acquire` отдельно показывает timeout выдачи соединения из pool, даже если SQL ещё не начал выполняться. + +Общие Resource attributes: `service.name`, `service.version=6.0.0`, `service.instance.id`, `deployment.environment.name=lab`. В metric labels нет user/chat/message/attachment/request ID, URL, filename и текста ошибок. Логи не содержат тела сообщений, изображения, tokens или credentials. + +## Метрики, запросы и единицы + +Provisioned dashboards: основной UID `mtusi-lab6-grade4` и SLO dashboard UID `mtusi-lab6-grade5`. Оба JSON лежат в `infrastructure/telemetry/grafana/dashboards/` и импортируются без ручной настройки. + +| Сигнал | PromQL | Единица | +| --- | --- | --- | +| API RPS | `sum(rate(messenger_http_server_requests_total[1m]))` | requests/s | +| Доля 5xx | `sum(rate(...{status_class="5xx"}[1m])) / sum(rate(...[1m]))` | доля 0..1 | +| API p50/p95/p99 | `histogram_quantile(q, sum by (le) (rate(messenger_http_server_duration_seconds_bucket[5m])))` | секунды | +| Queue depth | `max(messenger_queue_depth)` | jobs | +| Старейшая job | `max(messenger_queue_oldest_job_age_seconds)` | секунды | +| Worker saturation | `max(messenger_worker_busy) / max(messenger_worker_capacity)` | доля 0..1 | +| Time to ready p50/p95/p99 | `histogram_quantile(q, sum by (le) (rate(messenger_attachment_ready_duration_seconds_bucket[5m])))` | секунды | +| DB pool | `sum by (service_name,state) (messenger_db_pool_connections)` | connections | +| DB waits | `sum by (service_name) (rate(messenger_db_pool_waits_total[5m]))` | waits/s | +| CPU процесса | `sum by (service_name) (rate(messenger_process_cpu_time_seconds_total[5m]))` | CPU-seconds/s | +| RSS процесса | `max by (service_name) (messenger_process_memory_bytes)` | bytes | +| Collector queues | `otelcol_exporter_queue_size`, `otelcol_exporter_queue_capacity` | batches | +| Потери Collector | сумма rate `otelcol_exporter_send_failed_*` | signals/s | + +Percentiles вычисляются из histogram buckets; средние значения и усреднение готовых p99 между репликами не используются. + +Отдельная калибровка `make test-histogram-calibration` сравнила 400 клиентских измерений с Prometheus: HTTP p95 3.570 ms на клиенте и 4.910 ms по histogram (ratio 1.38), ready p95 1.013/0.946 s, worker p95 97.5 ms. Таким образом, единицы действительно секунды, а ошибка на три порядка из-за слишком крупных default buckets отсутствует. + +## SLI, SLO и alerts + +Для трека 2 заданы два request/event-based SLO с policy window 7 дней, совпадающим с `--storage.tsdb.retention.time=7d` Prometheus: + +- API availability: не менее 99% instrumented HTTP-запросов завершаются без 5xx; error budget — 1% запросов; +- attachment ready: не менее 99% успешно завершённых attachments переходят в `ready` не позднее 10 секунд после durable acceptance; error budget — 1% завершённых jobs. + +Порог 10 секунд включает очередь и обработку и потому лучше пользовательского результата, чем только worker execution time. Значение совпадает с bucket `le="10.0"`, поэтому bad events считаются без приближения percentile. + +Policy-window recording rules `messenger:slo_api_success_ratio_7d` и `messenger:slo_attachment_ready_ratio_7d` вычисляются через `increase(...[7d])`; SLO можно проверить напрямую на dashboard, а не выводить из коротких alert windows. + +Правила лежат в `infrastructure/telemetry/prometheus/rules/alerts.yaml`: + +- `MessengerAPIHighErrorRate`: более 1% 5xx при достаточном трафике за 1 минуту, `for: 10s`; +- `MessengerQueueLagGrowing`: depth > 0 и oldest age > 10 секунд, `for: 10s`. + +Для уровня 5 добавлены две policy-window и восемь burn-window recording rules по окнам 30s/1m/2m/5m, а также четыре multi-window alerts: + +- Fast: оба окна 30s и 2m превышают 14.4x burn rate, `for: 10s`, severity `page`; +- Slow: оба окна 1m и 5m превышают 6x burn rate, `for: 20s`, severity `ticket`; +- одинаковая схема применяется к API 5xx и attachment >10s; +- traffic guard исключает алерт при отсутствии запросов/jobs. + +Факторы 14.4x и 6x выражают скорость расходования 1% бюджета независимо от масштаба окна. Окна намеренно сжаты до минут для воспроизводимой лабораторной проверки; production-вариант использовал бы, например, 5m/1h и 30m/6h. Runbooks: `infrastructure/telemetry/runbooks/level4.md` и `level5.md`. + +## Collector и bounded degradation + +Обе telemetry-очереди имеют capacity 256 batches и 2 consumers. `memory_limiter`: limit 192 MiB, spike 48 MiB, проверка раз в секунду. `batch`: 256, максимум 512, timeout 1 секунда. Export timeout 3 секунды, retry ограничен 30 секундами. Container memory limit — 256 MiB. + +При остановке Loki и Tempo 400 HTTP-запросов завершились с 200, attachment перешёл в `ready`. Collector принял дополнительно 3170 log/span records; после исчерпания retry budget 75 сигналов были явно учтены как `send_failed`, а не накапливались бесконечно. Queue peak в момент измерения — 34 из 256 batches; container RSS peak — 261305139 из 268435456 bytes. После восстановления backend новый log и trace `01806671c8d2cee14dc504f63a60197b` появились снова. Бизнес-данные не потеряны; допустимая деградация — потеря части телеметрии после bounded retry. + +## Контролируемые инциденты + +### 1. Worker остановлен + +Гипотеза: queue depth и oldest age растут, бизнес-upload остаётся durable queued, затем после возврата worker job завершается. + +Методика: остановить worker, загрузить PNG, дождаться `MessengerQueueLagGrowing=firing`, запустить worker, дождаться `ready` и отсутствия активного alert. + +Результат: firing через 26.075 s, depth=1, oldest age=21.157 s; resolved через 8.009 s после восстановления. Диагностика: dashboard queue → worker saturation/logs → consumer trace. + +### 2. PostgreSQL приостановлен + +Гипотеза: API возвращает bounded 503 через DB query timeout; HTTP trace содержит error на ожидании pool, high-error alert срабатывает и снимается после восстановления. + +Методика: `docker compose pause postgres`, восемь параллельных authenticated GET, ожидание alert, `unpause`, readiness, поиск request ID в Loki и trace в Tempo. + +Результат: восемь 503; `MessengerAPIHighErrorRate=firing` через 19.044 s; trace `db176205d463b89b73c737780e58cf06` содержит `postgresql.acquire` со статусом error; resolved через 44.049 s. Это отличает DB pool timeout от медленного handler без DB child/error span. + +### Retry и единая трасса + +MinIO был остановлен после durable staging upload, worker выполнил неуспешную попытку, затем MinIO восстановлен. Attachment завершился `ready`. В trace `0df6d4041008c05e5c2c77b0c2bd2ddf` видны сервисы API/dispatcher/worker, producer attempts 1/2 и consumer attempts 1/2, всего 46 spans, включая S3 и PostgreSQL. + +## Эксперимент уровня 5: SLO и обнаружение + +Гипотеза: multi-window burn-rate не реагирует на ограниченный краткий всплеск ниже скорости расходования бюджета, но обнаруживает длительную деградацию; после восстановления и достаточного успешного трафика оба окна возвращаются ниже порога. + +Методика полностью реализована в `tests/slo_burn_rate.py`: + +1. создать 400 успешных запросов baseline; +2. кратко pause PostgreSQL и получить 4 контролируемых 503, затем 25 секунд наблюдать оба состояния alerts; +3. повторно pause PostgreSQL и поддерживать восемь concurrent error streams до firing Fast/Slow; +4. восстановить DB, создать успешный трафик, измерить resolved и найти root cause по log/trace; +5. для ready SLO создать 20 быстрых jobs, остановить worker, выдержать пять jobs более 10 секунд, восстановить worker и дождаться Fast/Slow; +6. создать 100 быстрых jobs и измерить resolved. + +Результаты API: + +- краткий burst: 4 ошибки, `pending_or_firing=0`; максимум 30s ratio 3.846%, 5m ratio 0.783%; контролируемых ложных срабатываний нет; +- длительная деградация: 136 ответов 503; +- `MessengerAPIBurnRateSlow` firing через 42.194 s, Fast через 52.212 s; +- resolved обоих правил через 38.851 s после восстановления и успешного трафика; +- trace `abac9b8b51c9b4bd3d05c26dab3e37ea`, root cause span `postgresql.acquire`. + +Результаты attachment ready: + +- 20 baseline jobs ≤10s, 5 jobs >10s, 100 recovery jobs ≤10s; +- Fast firing через 20.039 s после поступления slow observations, Slow — через 30.056 s; +- resolved через 8.016 s после recovery samples; +- итоговый 5m slow ratio 4.794%, то есть ниже 6% slow burn threshold. + +В этом локальном профиле Slow API alert обнаружился раньше Fast: длинное окно уже превысило 6%, тогда как 30s окно Fast сначала было разбавлено baseline-трафиком. Это ожидаемое следствие данных, а не гарантия порядка severity. Проверка false positive ограничена одним воспроизводимым сценарием и не является статистической оценкой реальной частоты ложных тревог. + +## Доказательства и проверки + +| Критерий | Команда | Результат | +| --- | --- | --- | +| Contract/OpenAPI | `make check`, `make validate` | PASS | +| Публичный API | `make test` | PASS | +| Уровень 3 | `make test-observability-grade3` | PASS | +| W3C chain + grade-4 metrics/dashboard | `make test-observability-grade4` | PASS, 3 services, 4 span kinds, 36 spans | +| Retry в одной трассе | `make test-observability-retry-trace` | PASS, attempts 1/2, 2 producer + 2 consumer | +| Alerts | `make test-observability-alerts` | PASS, оба firing/resolved | +| Telemetry backend outage | `make test-telemetry-backend-outage` | PASS, business ready, bounded queue/RAM/loss | +| Grade-5 SLO experiment | `make test-slo-burn-rate` | PASS, short burst filtered; API/ready Fast+Slow firing/resolved | +| Histogram calibration | `make test-histogram-calibration` | PASS, HTTP client/Prom p95 3.570/4.910 ms; ready 1.013/0.946 s | +| Collector config | Collector `validate` | PASS | +| Prometheus rules | `promtool check config/rules` | PASS, 17 rules | +| Go | `go test -race -count=1 ./...`, `go vet ./...`, `go build ./...`, `go mod verify` | PASS | +| Go dependencies | `govulncheck -show verbose ./...` | PASS, no symbol/package/module vulnerabilities found after dependency updates | +| Shell scripts | `bash -n`, ShellCheck 0.11.0 | PASS | +| Compose/dashboard | `docker compose config --quiet`, JSON parse, Grafana API | PASS | +| CI application job | `.github/workflows/contracts.yml` | race/vet/vulnerability audit, Compose build/wait, public smoke, telemetry path, failure logs, cleanup | + +Полный машинно-читаемый вывод и параметры прогонов сохранены в `evidence/lab6-grade4.md` и `evidence/lab6-grade5.md`. + +## Ограничения + +Заявлен уровень 5, трек 2. Стенд проверен на одном Docker-host, поэтому потеря host/volumes не покрыта. Окна burn-rate сжаты для лабораторной повторяемости и не заменяют многонедельное production-наблюдение. DB incident использует полную pause, а не реалистичное распределение latency. Независимый студент ещё не выполнял runbook drill; вместо этого шаги автоматически повторяет black-box сценарий, а root cause подтверждён через Loki/Tempo. Пик RSS Collector в outage-тесте близок к container limit, но не превысил его, контейнер не перезапускался, очередь оставалась bounded, а потери были измерены. Обычная очистка сохраняет named volumes; для освобождения места, занятого volumes, нужен отдельный осознанный экспорт/удаление данных. diff --git a/cmd/dispatcher/main.go b/cmd/dispatcher/main.go new file mode 100644 index 0000000..0f539f3 --- /dev/null +++ b/cmd/dispatcher/main.go @@ -0,0 +1,162 @@ +package main + +import ( + "context" + "errors" + "log" + "os" + "os/signal" + "syscall" + "time" + + "mtusi2026lab6/internal/adapter/broker" + "mtusi2026lab6/internal/adapter/postgres" + "mtusi2026lab6/internal/config" + "mtusi2026lab6/internal/database" + "mtusi2026lab6/internal/domain" + apptelemetry "mtusi2026lab6/internal/telemetry" + "mtusi2026lab6/internal/worker" +) + +const defaultBeforePublishFaultFile = "/tmp/mtusi-fault-before-publish" + +func main() { + cfg, err := config.LoadDispatcher() + if err != nil { + log.Fatalf("[FATAL] Invalid configuration: %v", err) + } + if cfg.BrokerURL == "" { + log.Fatal("[FATAL] BROKER_URL or BROKER_URL_FILE is required") + } + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + telemetryRuntime, err := apptelemetry.Start(ctx, "messenger-dispatcher", cfg.InstanceID, "lab") + if err != nil { + log.Fatalf("[FATAL] OpenTelemetry initialization failed: %v", err) + } + defer func() { + shutdownContext, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if shutdownErr := telemetryRuntime.Shutdown(shutdownContext); shutdownErr != nil { + log.Printf("[WARN] OpenTelemetry shutdown failed: %v", shutdownErr) + } + }() + pool, err := database.Open(ctx, cfg) + if err != nil { + log.Fatalf("[FATAL] PostgreSQL initialization failed: %v", err) + } + defer pool.Close() + if err = apptelemetry.RegisterDBPool(telemetryRuntime, pool); err != nil { + log.Fatalf("[FATAL] DB pool observability initialization failed: %v", err) + } + store := postgres.NewPostgreSQLStore(pool, cfg.DatabaseQueryTimeout) + queueRecorder, err := apptelemetry.NewQueueRecorder(telemetryRuntime) + if err != nil { + log.Fatalf("[FATAL] Queue observability initialization failed: %v", err) + } + client, err := broker.Open(cfg.BrokerURL, 0) + if err != nil { + log.Fatalf("[FATAL] RabbitMQ initialization failed: %v", err) + } + defer client.Close() + + faultFile := os.Getenv("DISPATCHER_FAULT_BEFORE_PUBLISH_FILE") + if faultFile == "" { + faultFile = defaultBeforePublishFaultFile + } + ticker := time.NewTicker(250 * time.Millisecond) + defer ticker.Stop() + log.Println("[INFO] Attachment job dispatcher and lease reaper started") + nextQueueObservation := time.Time{} + + for { + now := time.Now().UTC() + if !now.Before(nextQueueObservation) { + depth, ageSeconds, statsErr := store.AttachmentQueueStats(ctx, now) + if statsErr != nil { + if ctx.Err() == nil { + log.Printf("[WARN] Read queue stats failed: %v", statsErr) + } + } else { + queueRecorder.Record(ctx, depth, ageSeconds) + } + nextQueueObservation = now.Add(time.Second) + } + expired, queryErr := store.ListExpiredAttachmentJobs(ctx, now, 50) + if queryErr != nil { + if ctx.Err() != nil { + return + } + log.Printf("[WARN] List expired jobs failed: %v", queryErr) + } else { + for _, job := range expired { + delay := worker.RetryDelay( + job.JobID, + job.Attempt+1, + cfg.JobRetryBase, + cfg.JobRetryMax, + ) + recovered, final, recoverErr := store.RetryAttachmentJob( + ctx, + job.JobID, + "lease_expired", + now.Add(delay), + now, + "lease_recovered", + ) + if recoverErr != nil { + log.Printf("[WARN] Recover expired job %s failed: %v", job.JobID, recoverErr) + continue + } + if final && recovered.Status == domain.AttachmentJobFailed { + log.Printf("[WARN] Expired job %s exhausted retries", job.JobID) + } else if !final { + log.Printf("[INFO] Recovered expired job %s as attempt %d", job.JobID, recovered.Attempt) + } + } + } + + jobs, queryErr := store.ListUnpublishedAttachmentJobs(ctx, 50) + if queryErr != nil { + if ctx.Err() != nil { + return + } + log.Printf("[WARN] List unpublished jobs failed: %v", queryErr) + } else { + for _, job := range jobs { + removeErr := os.Remove(faultFile) + if removeErr == nil { + log.Printf("[FAULT] exiting after DB commit and before publish for job %s", job.JobID) + os.Exit(87) + } + if removeErr != nil && !errors.Is(removeErr, os.ErrNotExist) { + log.Printf("[WARN] Consume before-publish fault marker: %v", removeErr) + } + + publishContext, cancel := context.WithTimeout(ctx, 10*time.Second) + publishErr := client.Publish(publishContext, job) + cancel() + if publishErr != nil { + log.Fatalf("[FATAL] Publish job %s failed: %v", job.JobID, publishErr) + } + if err = store.MarkAttachmentJobPublished( + ctx, + job.JobID, + job.Attempt, + time.Now().UTC(), + ); err != nil { + // Publisher confirm proves broker acceptance. Leaving the + // marker unset intentionally causes a safe duplicate. + log.Printf("[WARN] Job %s was confirmed but publish marker failed: %v", job.JobID, err) + } + } + } + + select { + case <-ctx.Done(): + return + case <-ticker.C: + } + } +} diff --git a/cmd/jobctl/main.go b/cmd/jobctl/main.go new file mode 100644 index 0000000..c34eaa2 --- /dev/null +++ b/cmd/jobctl/main.go @@ -0,0 +1,259 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "log" + "os" + "strconv" + "time" + + "mtusi2026lab6/internal/adapter/broker" + "mtusi2026lab6/internal/adapter/objectstore" + "mtusi2026lab6/internal/adapter/postgres" + "mtusi2026lab6/internal/application" + "mtusi2026lab6/internal/config" + "mtusi2026lab6/internal/database" + "mtusi2026lab6/internal/domain" + + "github.com/google/uuid" +) + +type jobView struct { + JobID string `json:"job_id"` + AttachmentID string `json:"attachment_id"` + PipelineVersion int `json:"pipeline_version"` + Status domain.AttachmentJobStatus `json:"status"` + Attempt int `json:"attempt"` + MaxAttempts int `json:"max_attempts"` + ErrorCode *string `json:"error_code"` + ReplayCount int `json:"replay_count"` + UpdatedAt time.Time `json:"updated_at"` +} + +func main() { + if len(os.Args) < 2 { + usage() + } + switch os.Args[1] { + case "list-failed": + runListFailed() + case "replay": + runReplay() + case "inject": + runInject() + case "upgrade": + runUpgrade() + default: + usage() + } +} + +func openStore(ctx context.Context, cfg config.Config) (*postgres.PostgreSQLStore, func()) { + pool, err := database.Open(ctx, cfg) + if err != nil { + log.Fatalf("PostgreSQL initialization failed: %v", err) + } + return postgres.NewPostgreSQLStore(pool, cfg.DatabaseQueryTimeout), pool.Close +} + +func runListFailed() { + limit := 100 + if len(os.Args) == 3 { + parsed, err := strconv.Atoi(os.Args[2]) + if err != nil || parsed < 1 || parsed > 1000 { + log.Fatal("limit must be an integer between 1 and 1000") + } + limit = parsed + } else if len(os.Args) != 2 { + usage() + } + cfg, err := config.LoadDispatcher() + if err != nil { + log.Fatalf("invalid configuration: %v", err) + } + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + store, closeStore := openStore(ctx, cfg) + defer closeStore() + jobs, err := store.ListFailedAttachmentJobs(ctx, limit) + if err != nil { + log.Fatalf("list failed jobs: %v", err) + } + views := make([]jobView, 0, len(jobs)) + for _, job := range jobs { + views = append(views, view(job)) + } + writeJSON(views) +} + +func runReplay() { + if len(os.Args) != 3 { + usage() + } + jobID := requireUUID(os.Args[2], "job_id") + cfg, err := config.LoadDispatcher() + if err != nil { + log.Fatalf("invalid configuration: %v", err) + } + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + store, closeStore := openStore(ctx, cfg) + defer closeStore() + job, err := store.ReplayFailedAttachmentJob(ctx, jobID, time.Now().UTC()) + if errors.Is(err, postgres.ErrConflict) { + log.Fatal("replay rejected: job is not the active failed pipeline or retained staging is unavailable") + } + if errors.Is(err, postgres.ErrNotFound) { + log.Fatal("replay rejected: job not found") + } + if err != nil { + log.Fatalf("replay failed: %v", err) + } + writeJSON(view(job)) +} + +func runInject() { + if len(os.Args) != 3 { + usage() + } + jobID := requireUUID(os.Args[2], "job_id") + cfg, err := config.LoadDispatcher() + if err != nil { + log.Fatalf("invalid configuration: %v", err) + } + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + store, closeStore := openStore(ctx, cfg) + defer closeStore() + job, err := store.GetAttachmentJob(ctx, jobID) + if errors.Is(err, postgres.ErrNotFound) { + log.Fatal("inject rejected: job not found") + } + if err != nil { + log.Fatalf("read job for injection: %v", err) + } + client, err := broker.Open(cfg.BrokerURL, 1) + if err != nil { + log.Fatalf("RabbitMQ initialization failed: %v", err) + } + defer client.Close() + if err = client.Publish(ctx, job); err != nil { + log.Fatalf("inject broker message: %v", err) + } + writeJSON(view(job)) +} + +func runUpgrade() { + if len(os.Args) != 4 { + usage() + } + attachmentID := requireUUID(os.Args[2], "attachment_id") + targetVersion, err := strconv.Atoi(os.Args[3]) + if err != nil || targetVersion != 2 { + log.Fatal("target pipeline version must be 2") + } + cfg, err := config.LoadWorker() + if err != nil { + log.Fatalf("invalid configuration: %v", err) + } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + store, closeStore := openStore(ctx, cfg) + defer closeStore() + attachment, err := store.GetAttachmentForProcessing(ctx, attachmentID) + if errors.Is(err, postgres.ErrNotFound) { + log.Fatal("upgrade rejected: attachment not found") + } + if err != nil { + log.Fatalf("read attachment for upgrade: %v", err) + } + if attachment.PipelineVersion+1 != targetVersion { + log.Fatalf("upgrade rejected: current pipeline is v%d", attachment.PipelineVersion) + } + objects, err := objectstore.NewMinIOStore( + cfg.S3Endpoint, + cfg.S3Region, + cfg.S3Bucket, + cfg.S3AccessKeyID, + cfg.S3SecretAccessKey, + cfg.S3OperationTimeout, + ) + if err != nil { + log.Fatalf("object storage initialization failed: %v", err) + } + source, err := objects.Get(ctx, attachment.ObjectKey) + if err != nil { + log.Fatalf("upgrade source original is unavailable: %v", err) + } + defer source.Body.Close() + stagingKey := fmt.Sprintf("staging/%s/v%d/original", attachment.ID, targetVersion) + if err = objects.Put(ctx, application.ObjectPut{ + Key: stagingKey, + ContentType: attachment.ContentType, + SizeBytes: attachment.SizeBytes, + Body: source.Body, + }); err != nil { + log.Fatalf("create durable upgrade staging: %v", err) + } + now := time.Now().UTC() + job := domain.AttachmentJob{ + SchemaVersion: 1, + JobID: uuid.NewString(), + Type: domain.AttachmentJobType, + AttachmentID: attachment.ID, + PipelineVersion: targetVersion, + Attempt: 1, + MaxAttempts: cfg.JobMaxAttempts, + Status: domain.AttachmentJobQueued, + AvailableAt: now, + CreatedAt: now, + UpdatedAt: now, + } + job, err = store.UpgradeAttachmentPipeline(ctx, attachment.ID, targetVersion, stagingKey, job, now) + if errors.Is(err, postgres.ErrConflict) { + log.Fatal("upgrade rejected: attachment is not in an upgradeable state or target is not the next version") + } + if err != nil { + // Keep the copied source: a COMMIT error is ambiguous and cleanup can + // safely remove an actual orphan after the retention period. + log.Fatalf("upgrade pipeline: %v", err) + } + writeJSON(view(job)) +} + +func requireUUID(value, name string) string { + if _, err := uuid.Parse(value); err != nil { + log.Fatalf("%s must be a UUID", name) + } + return value +} + +func view(job domain.AttachmentJob) jobView { + return jobView{ + JobID: job.JobID, + AttachmentID: job.AttachmentID, + PipelineVersion: job.PipelineVersion, + Status: job.Status, + Attempt: job.Attempt, + MaxAttempts: job.MaxAttempts, + ErrorCode: job.ErrorCode, + ReplayCount: job.ReplayCount, + UpdatedAt: job.UpdatedAt, + } +} + +func writeJSON(value any) { + encoder := json.NewEncoder(os.Stdout) + encoder.SetEscapeHTML(true) + if err := encoder.Encode(value); err != nil { + log.Fatalf("encode output: %v", err) + } +} + +func usage() { + fmt.Fprintln(os.Stderr, "usage: jobctl list-failed [limit] | replay | inject | upgrade 2") + os.Exit(2) +} diff --git a/cmd/reconciler/main.go b/cmd/reconciler/main.go new file mode 100644 index 0000000..3431b36 --- /dev/null +++ b/cmd/reconciler/main.go @@ -0,0 +1,75 @@ +package main + +import ( + "context" + "encoding/json" + "flag" + "fmt" + "log" + "os" + "time" + + "mtusi2026lab6/internal/adapter/objectstore" + "mtusi2026lab6/internal/adapter/postgres" + "mtusi2026lab6/internal/config" + "mtusi2026lab6/internal/database" + "mtusi2026lab6/internal/reconcile" +) + +func main() { + apply := flag.Bool("apply", false, "apply safe repairs; default is dry-run") + gracePeriod := flag.Duration("grace-period", 15*time.Minute, + "ignore metadata and objects newer than this duration") + timeout := flag.Duration("timeout", 2*time.Minute, "maximum reconciliation runtime") + flag.Parse() + + if *gracePeriod <= 0 || *timeout <= 0 { + log.Fatal("[FATAL] grace-period and timeout must be positive") + } + cfg, err := config.Load() + if err != nil { + log.Fatalf("[FATAL] Invalid configuration: %v", err) + } + + ctx, cancel := context.WithTimeout(context.Background(), *timeout) + defer cancel() + databasePool, err := database.Open(ctx, cfg) + if err != nil { + log.Fatalf("[FATAL] PostgreSQL initialization failed: %v", err) + } + defer databasePool.Close() + metadataStore := postgres.NewPostgreSQLStore(databasePool, cfg.DatabaseQueryTimeout) + + objectStore, err := objectstore.NewMinIOStore( + cfg.S3Endpoint, + cfg.S3Region, + cfg.S3Bucket, + cfg.S3AccessKeyID, + cfg.S3SecretAccessKey, + cfg.S3OperationTimeout, + ) + if err != nil { + log.Fatalf("[FATAL] Invalid object storage configuration: %v", err) + } + if err = objectStore.Ping(ctx); err != nil { + log.Fatalf("[FATAL] Object storage unavailable: %v", err) + } + + reconciler, err := reconcile.New(metadataStore, objectStore) + if err != nil { + log.Fatalf("[FATAL] Reconciler initialization failed: %v", err) + } + result, err := reconciler.Run(ctx, *gracePeriod, *apply) + if err != nil { + log.Fatalf("[FATAL] Reconciliation failed: %v", err) + } + + encoder := json.NewEncoder(os.Stdout) + encoder.SetIndent("", " ") + if err = encoder.Encode(result); err != nil { + log.Fatalf("[FATAL] Encode reconciliation result: %v", err) + } + if !*apply && len(result.Issues) > 0 { + fmt.Fprintln(os.Stderr, "dry-run found reconciliation issues; rerun with --apply after review") + } +} diff --git a/cmd/server/main.go b/cmd/server/main.go new file mode 100644 index 0000000..17c3a76 --- /dev/null +++ b/cmd/server/main.go @@ -0,0 +1,283 @@ +package main + +import ( + "context" + "errors" + "log" + "net/http" + "os" + "os/signal" + "syscall" + "time" + + cacheadapter "mtusi2026lab6/internal/adapter/cache" + "mtusi2026lab6/internal/adapter/health" + "mtusi2026lab6/internal/adapter/objectstore" + "mtusi2026lab6/internal/adapter/postgres" + redisadapter "mtusi2026lab6/internal/adapter/redis" + "mtusi2026lab6/internal/application" + "mtusi2026lab6/internal/config" + "mtusi2026lab6/internal/database" + apptelemetry "mtusi2026lab6/internal/telemetry" + "mtusi2026lab6/internal/transport/http/handlers" + "mtusi2026lab6/internal/transport/http/middleware" +) + +func main() { + cfg, err := config.Load() + if err != nil { + log.Fatalf("[FATAL] Invalid configuration: %v", err) + } + telemetryRuntime, err := apptelemetry.Start( + context.Background(), + "messenger-api", + cfg.InstanceID, + "lab", + ) + if err != nil { + log.Fatalf("[FATAL] OpenTelemetry initialization failed: %v", err) + } + defer func() { + shutdownContext, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if shutdownErr := telemetryRuntime.Shutdown(shutdownContext); shutdownErr != nil { + log.Printf("[WARN] OpenTelemetry shutdown failed: %v", shutdownErr) + } + }() + + startupContext, startupCancel := context.WithTimeout( + context.Background(), + cfg.DatabaseConnectTimeout, + ) + + databasePool, err := database.Open(startupContext, cfg) + startupCancel() + + if err != nil { + log.Fatalf("[FATAL] PostgreSQL initialization failed: %v", err) + } + defer databasePool.Close() + if err = apptelemetry.RegisterDBPool(telemetryRuntime, databasePool); err != nil { + log.Fatalf("[FATAL] DB pool observability initialization failed: %v", err) + } + + postgresStore := postgres.NewPostgreSQLStore( + databasePool, + cfg.DatabaseQueryTimeout, + ) + minioStore, err := objectstore.NewMinIOStore( + cfg.S3Endpoint, + cfg.S3Region, + cfg.S3Bucket, + cfg.S3AccessKeyID, + cfg.S3SecretAccessKey, + cfg.S3OperationTimeout, + ) + if err != nil { + log.Fatalf("[FATAL] Invalid object storage configuration: %v", err) + } + storageContext, storageCancel := context.WithTimeout( + context.Background(), + cfg.S3OperationTimeout, + ) + if err = minioStore.Ping(storageContext); err != nil { + log.Printf("[WARN] Object storage unavailable at startup: %v", err) + } + storageCancel() + + var applicationStore application.Repository = postgresStore + + if cfg.RedisURL != "" { + redisChatCache, cacheError := redisadapter.NewRedisChatCache( + cfg.RedisURL, + cfg.RedisCacheTTL, + cfg.RedisOperationTimeout, + cfg.RedisPoolSize, + ) + if cacheError != nil { + log.Fatalf("[FATAL] Invalid Redis configuration: %v", cacheError) + } + defer func() { + if closeError := redisChatCache.Close(); closeError != nil { + log.Printf("[WARN] Redis client close failed: %v", closeError) + } + }() + + cacheContext, cacheCancel := context.WithTimeout( + context.Background(), + cfg.RedisOperationTimeout, + ) + if cacheError = redisChatCache.Ping(cacheContext); cacheError != nil { + log.Printf("[WARN] Redis unavailable at startup; PostgreSQL fallback is active: %v", cacheError) + } else { + log.Println("[INFO] Redis chat cache is available") + } + cacheCancel() + + applicationStore = cacheadapter.NewCachedRepository( + postgresStore, + redisChatCache, + log.Default(), + ) + } + + cursorCodec, err := application.NewCursorCodec(cfg.CursorSigningKey) + if err != nil { + log.Fatalf("[FATAL] Invalid cursor configuration: %v", err) + } + + service, err := application.NewService( + applicationStore, + cursorCodec, + cfg.SessionTTL, + application.WithIdempotencyTTL(cfg.IdempotencyTTL), + application.WithObjectStore(minioStore), + application.WithJobMaxAttempts(cfg.JobMaxAttempts), + ) + if err != nil { + log.Fatalf("[FATAL] Application initialization failed: %v", err) + } + + handler := handlers.NewHandler( + service, + handlers.WithReadiness( + health.NewMultiChecker(databasePool, minioStore), + cfg.ReadinessTimeout, + ), + handlers.WithSessionCookieSecure(cfg.SessionCookieSecure), + ) + + mux := http.NewServeMux() + + mux.HandleFunc("GET /health/live", handler.HealthLive) + mux.HandleFunc("GET /health/lb", handler.HealthLive) + mux.HandleFunc("GET /health/ready", handler.HealthReady) + + mux.HandleFunc( + "POST /api/v1/auth/sessions", + handler.CreateSession, + ) + + mux.HandleFunc("POST /api/v1/users", handler.CreateUser) + + requireAuth := func(next http.HandlerFunc) http.HandlerFunc { + return middleware.RequireAuth(service, next) + } + + mux.HandleFunc( + "GET /api/v1/users/me", + requireAuth(handler.GetMe), + ) + + mux.HandleFunc( + "DELETE /api/v1/auth/sessions/current", + requireAuth(handler.DeleteCurrentSession), + ) + + mux.HandleFunc( + "POST /api/v1/chats", + requireAuth(handler.CreateChat), + ) + mux.HandleFunc( + "GET /api/v1/chats", + requireAuth(handler.ListChats), + ) + mux.HandleFunc( + "GET /api/v1/chats/{chat_id}", + requireAuth(handler.GetChat), + ) + mux.HandleFunc( + "POST /api/v1/chats/{chat_id}/messages", + requireAuth(handler.CreateMessage), + ) + mux.HandleFunc( + "GET /api/v1/chats/{chat_id}/messages", + requireAuth(handler.GetMessages), + ) + mux.HandleFunc( + "POST /api/v1/chats/{chat_id}/attachments", + requireAuth(handler.UploadAttachment), + ) + mux.HandleFunc( + "GET /api/v1/attachments/{attachment_id}", + requireAuth(handler.GetAttachment), + ) + mux.HandleFunc( + "GET /api/v1/attachments/{attachment_id}/content", + requireAuth(handler.DownloadAttachment), + ) + + var rootHandler http.Handler = mux + rootHandler = middleware.Recovery(rootHandler) + rootHandler, err = middleware.Observability(telemetryRuntime, rootHandler) + if err != nil { + log.Fatalf("[FATAL] HTTP observability initialization failed: %v", err) + } + availabilityGate := middleware.NewAvailabilityGate() + rootHandler = availabilityGate.Middleware(rootHandler) + rootHandler = middleware.RequestID(rootHandler) + rootHandler = middleware.InstanceID(cfg.InstanceID, rootHandler) + + server := &http.Server{ + Addr: cfg.HTTPAddress(), + Handler: rootHandler, + ReadTimeout: 15 * time.Second, + WriteTimeout: 15 * time.Second, + IdleTimeout: 60 * time.Second, + } + + serverErrors := make(chan error, 1) + + go func() { + log.Printf( + "[INFO] Server instance %s starting on %s", + cfg.InstanceID, + server.Addr, + ) + serverErrors <- server.ListenAndServe() + }() + + shutdownSignals := make(chan os.Signal, 1) + signal.Notify( + shutdownSignals, + os.Interrupt, + syscall.SIGTERM, + ) + defer signal.Stop(shutdownSignals) + + select { + case serverError := <-serverErrors: + if !errors.Is(serverError, http.ErrServerClosed) { + log.Fatalf("[FATAL] Server crashed: %v", serverError) + } + + case signalValue := <-shutdownSignals: + log.Printf( + "[INFO] Signal %v received. Starting graceful shutdown...", + signalValue, + ) + + availabilityGate.BeginDrain() + log.Printf( + "[INFO] Readiness disabled; draining new traffic for %s", + cfg.ShutdownDrainDelay, + ) + time.Sleep(cfg.ShutdownDrainDelay) + + shutdownContext, shutdownCancel := context.WithTimeout( + context.Background(), + cfg.ShutdownTimeout, + ) + defer shutdownCancel() + + if err := server.Shutdown(shutdownContext); err != nil { + log.Printf( + "[WARN] Graceful shutdown failed: %v. Forcing close.", + err, + ) + _ = server.Close() + } + + log.Println("[INFO] Server stopped gracefully.") + } +} diff --git a/cmd/worker/main.go b/cmd/worker/main.go new file mode 100644 index 0000000..1a663ec --- /dev/null +++ b/cmd/worker/main.go @@ -0,0 +1,273 @@ +package main + +import ( + "context" + "errors" + "fmt" + "log" + "os" + "os/signal" + "sync" + "syscall" + "time" + + "mtusi2026lab6/internal/adapter/broker" + "mtusi2026lab6/internal/adapter/objectstore" + "mtusi2026lab6/internal/adapter/postgres" + "mtusi2026lab6/internal/config" + "mtusi2026lab6/internal/database" + "mtusi2026lab6/internal/domain" + apptelemetry "mtusi2026lab6/internal/telemetry" + "mtusi2026lab6/internal/worker" +) + +const ( + defaultBeforeObjectsFaultFile = "/tmp/mtusi-fault-before-objects" + defaultAfterObjectsFaultFile = "/tmp/mtusi-fault-after-objects" +) + +func main() { + cfg, err := config.LoadWorker() + if err != nil { + log.Fatalf("[FATAL] Invalid configuration: %v", err) + } + if cfg.BrokerURL == "" { + log.Fatal("[FATAL] BROKER_URL or BROKER_URL_FILE is required") + } + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + telemetryRuntime, err := apptelemetry.Start( + ctx, + "messenger-worker", + cfg.InstanceID, + "lab", + ) + if err != nil { + log.Fatalf("[FATAL] OpenTelemetry initialization failed: %v", err) + } + defer func() { + shutdownContext, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if shutdownErr := telemetryRuntime.Shutdown(shutdownContext); shutdownErr != nil { + log.Printf("[WARN] OpenTelemetry shutdown failed: %v", shutdownErr) + } + }() + jobRecorder, err := apptelemetry.NewJobRecorder(telemetryRuntime, cfg.WorkerConcurrency) + if err != nil { + log.Fatalf("[FATAL] Worker observability initialization failed: %v", err) + } + pool, err := database.Open(ctx, cfg) + if err != nil { + log.Fatalf("[FATAL] PostgreSQL initialization failed: %v", err) + } + defer pool.Close() + if err = apptelemetry.RegisterDBPool(telemetryRuntime, pool); err != nil { + log.Fatalf("[FATAL] DB pool observability initialization failed: %v", err) + } + store := postgres.NewPostgreSQLStore(pool, cfg.DatabaseQueryTimeout) + objects, err := objectstore.NewMinIOStore( + cfg.S3Endpoint, + cfg.S3Region, + cfg.S3Bucket, + cfg.S3AccessKeyID, + cfg.S3SecretAccessKey, + cfg.S3OperationTimeout, + ) + if err != nil { + log.Fatalf("[FATAL] Object storage initialization failed: %v", err) + } + + beforeFaultFile := os.Getenv("WORKER_FAULT_BEFORE_OBJECTS_FILE") + if beforeFaultFile == "" { + beforeFaultFile = defaultBeforeObjectsFaultFile + } + afterFaultFile := os.Getenv("WORKER_FAULT_AFTER_OBJECTS_FILE") + if afterFaultFile == "" { + afterFaultFile = defaultAfterObjectsFaultFile + } + processor, err := worker.NewProcessor(store, objects, worker.ProcessorHooks{ + BeforeObjects: func(job domain.AttachmentJob) error { + removeErr := os.Remove(beforeFaultFile) + if errors.Is(removeErr, os.ErrNotExist) { + return nil + } + if removeErr != nil { + return fmt.Errorf("consume before-objects fault marker: %w", removeErr) + } + log.Printf("[FAULT] exiting before object writes for job %s", job.JobID) + os.Exit(85) + return nil + }, + AfterObjects: func(job domain.AttachmentJob) error { + removeErr := os.Remove(afterFaultFile) + if errors.Is(removeErr, os.ErrNotExist) { + return nil + } + if removeErr != nil { + return fmt.Errorf("consume after-objects fault marker: %w", removeErr) + } + log.Printf("[FAULT] exiting after object writes and before DB commit for job %s", job.JobID) + os.Exit(86) + return nil + }, + }) + if err != nil { + log.Fatalf("[FATAL] Worker processor initialization failed: %v", err) + } + + cleaner, err := worker.NewStagingCleaner(store, objects, cfg.StagingRetention) + if err != nil { + log.Fatalf("[FATAL] Staging cleaner initialization failed: %v", err) + } + var maintenance sync.WaitGroup + maintenance.Add(1) + go func() { + defer maintenance.Done() + runCleanup := func() { + cleanupContext, cancel := context.WithTimeout(ctx, cfg.S3OperationTimeout+cfg.DatabaseQueryTimeout) + deleted, cleanupErr := cleaner.RunOnce(cleanupContext, time.Now().UTC()) + cancel() + if cleanupErr != nil && ctx.Err() == nil { + log.Printf("[WARN] Staging cleanup failed: %v", cleanupErr) + } else if deleted > 0 { + log.Printf("[INFO] Staging cleanup removed %d object(s)", deleted) + } + } + runCleanup() + ticker := time.NewTicker(cfg.StagingCleanupInterval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + runCleanup() + } + } + }() + + client, err := broker.Open(cfg.BrokerURL, cfg.WorkerConcurrency) + if err != nil { + log.Fatalf("[FATAL] RabbitMQ initialization failed: %v", err) + } + defer client.Close() + deliveries, err := client.Consume(cfg.InstanceID) + if err != nil { + log.Fatalf("[FATAL] RabbitMQ consume failed: %v", err) + } + + var group sync.WaitGroup + for index := 0; index < cfg.WorkerConcurrency; index++ { + group.Add(1) + go func(workerIndex int) { + defer group.Done() + workerID := fmt.Sprintf("%s-%d", cfg.InstanceID, workerIndex) + for delivery := range deliveries { + deliveryContext := broker.ContextFromDelivery(ctx, delivery) + message, decodeErr := broker.Decode(delivery) + if decodeErr != nil { + log.Printf("[WARN] Reject invalid broker message: %v", decodeErr) + _ = delivery.Reject(false) + continue + } + now := time.Now().UTC() + job, claimed, claimErr := store.ClaimAttachmentJob( + deliveryContext, + message, + workerID, + now.Add(cfg.JobLease), + ) + if errors.Is(claimErr, postgres.ErrNotFound) { + log.Printf("[INFO] Stale broker message for missing job %s acknowledged", message.JobID) + _ = delivery.Ack(false) + continue + } + if claimErr != nil { + log.Printf("[WARN] Claim job %s failed: %v", message.JobID, claimErr) + _ = delivery.Nack(false, true) + continue + } + if !claimed { + _ = delivery.Ack(false) + continue + } + + jobContext, cancel := context.WithTimeout(deliveryContext, cfg.JobTimeout) + jobContext, observedAttempt := jobRecorder.Start( + jobContext, + domain.AttachmentJobType, + broker.QueueName, + job.Attempt, + job.CreatedAt, + ) + processErr := processor.Process(jobContext, job) + observedAttempt.End(processErr) + cancel() + if processErr == nil { + _ = delivery.Ack(false) + continue + } + + var permanent *worker.PermanentError + if errors.As(processErr, &permanent) { + if failErr := store.FailAttachmentJob( + ctx, + job.JobID, + permanent.Code, + time.Now().UTC(), + ); failErr != nil { + log.Printf("[WARN] Persist permanent failure for job %s failed: %v", job.JobID, failErr) + _ = delivery.Nack(false, true) + } else { + log.Printf("[WARN] Job %s failed permanently with %s", job.JobID, permanent.Code) + _ = delivery.Ack(false) + } + continue + } + + retryAt := time.Now().UTC() + delay := worker.RetryDelay( + job.JobID, + job.Attempt+1, + cfg.JobRetryBase, + cfg.JobRetryMax, + ) + retried, final, retryErr := store.RetryAttachmentJob( + ctx, + job.JobID, + "processing_failed", + retryAt.Add(delay), + retryAt, + "retry_scheduled", + ) + if retryErr != nil { + log.Printf("[WARN] Schedule retry for job %s failed: %v", job.JobID, retryErr) + _ = delivery.Nack(false, true) + continue + } + if final && retried.Status == domain.AttachmentJobFailed { + log.Printf("[WARN] Job %s exhausted retries", job.JobID) + } else if final && retried.Status == domain.AttachmentJobSucceeded { + log.Printf("[INFO] Duplicate delivery for completed job %s acknowledged", job.JobID) + } else if final && retried.Status == domain.AttachmentJobSuperseded { + log.Printf("[INFO] Stale pipeline job %s acknowledged as superseded", job.JobID) + } else { + log.Printf("[INFO] Job %s retry %d scheduled after %s", job.JobID, retried.Attempt, delay) + } + _ = delivery.Ack(false) + } + }(index) + } + log.Printf( + "[INFO] Attachment worker started with concurrency=%d prefetch=%d lease=%s", + cfg.WorkerConcurrency, + cfg.WorkerConcurrency, + cfg.JobLease, + ) + <-ctx.Done() + _ = client.Close() + group.Wait() + maintenance.Wait() + log.Println("[INFO] Attachment worker stopped") +} diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..d74182d --- /dev/null +++ b/compose.yaml @@ -0,0 +1,614 @@ +services: + load-balancer: + build: + context: . + dockerfile: infrastructure/haproxy/Dockerfile + image: mtusi2026lab6-load-balancer + ports: + - "127.0.0.1:${PUBLIC_PORT:-8080}:8080" + depends_on: + api: + condition: service_healthy + frontend: + condition: service_healthy + healthcheck: + test: + [ + "CMD-SHELL", + "wget -qO- http://127.0.0.1:8080/health/ready || exit 1", + ] + interval: 5s + timeout: 3s + retries: 10 + start_period: 3s + stop_grace_period: 10s + restart: unless-stopped + deploy: + resources: + limits: + cpus: "0.25" + memory: 128M + + frontend: + build: + context: . + dockerfile: infrastructure/nginx/Dockerfile + image: mtusi2026lab6-web + expose: + - "8080" + healthcheck: + test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8080/ >/dev/null || exit 1"] + interval: 5s + timeout: 3s + retries: 10 + start_period: 3s + stop_grace_period: 10s + restart: unless-stopped + deploy: + resources: + limits: + cpus: "0.10" + memory: 64M + + postgres: + image: postgres:16.15-alpine3.24@sha256:721873c34ceb9f8d8fc265984940dc982404c105f19ad51be9fdc5970a6080ea + environment: + POSTGRES_USER: ${POSTGRES_USER:-messenger} + POSTGRES_DB: ${POSTGRES_DB:-messenger} + POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password + secrets: + - postgres_password + volumes: + - postgres_data:/var/lib/postgresql/data + healthcheck: + test: + [ + "CMD-SHELL", + "pg_isready -U ${POSTGRES_USER:-messenger} -d ${POSTGRES_DB:-messenger}", + ] + interval: 5s + timeout: 3s + retries: 10 + start_period: 5s + restart: unless-stopped + deploy: + resources: + limits: + cpus: "${POSTGRES_CPU_LIMIT:-1.00}" + memory: ${POSTGRES_MEMORY_LIMIT:-512M} + + redis: + image: redis:8.10.2-alpine3.23@sha256:3811787313eba226a2ef38658c6ccb91cd5e110edc89c37767de373120a0e5a0 + command: + [ + "redis-server", + "--save", + "", + "--appendonly", + "no", + "--maxmemory", + "64mb", + "--maxmemory-policy", + "allkeys-lru", + ] + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 5s + timeout: 3s + retries: 10 + start_period: 3s + stop_grace_period: 10s + restart: unless-stopped + deploy: + resources: + limits: + cpus: "0.25" + memory: 128M + + migrate: + image: migrate/migrate:v4.20.1@sha256:76cc2074cb6642631f34a898ced71e6aeaa6b1a4d78c4daa743275a22e0c5be7 + entrypoint: ["/bin/sh", "-ec"] + command: + - > + exec migrate + -path=/migrations + -database="$$(cat /run/secrets/database_url)" + up + secrets: + - database_url + volumes: + - ./migrations:/migrations:ro + depends_on: + postgres: + condition: service_healthy + restart: "no" + deploy: + resources: + limits: + cpus: "0.25" + memory: 64M + + minio: + build: + context: . + dockerfile: infrastructure/minio/Dockerfile + target: server + args: + MINIO_VERSION: RELEASE.2025-10-15T17-29-55Z + image: mtusi2026lab6-minio:RELEASE.2025-10-15T17-29-55Z + command: ["server", "/data", "--address", ":9000"] + environment: + MINIO_ROOT_USER_FILE: /run/secrets/minio_root_user + MINIO_ROOT_PASSWORD_FILE: /run/secrets/minio_root_password + MINIO_BROWSER: "off" + secrets: + - minio_root_user + - minio_root_password + volumes: + - minio_data:/data + expose: + - "9000" + healthcheck: + test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:9000/minio/health/live >/dev/null || exit 1"] + interval: 5s + timeout: 3s + retries: 20 + start_period: 10s + restart: unless-stopped + deploy: + resources: + limits: + cpus: "0.75" + memory: 512M + + minio-bootstrap: + build: + context: . + dockerfile: infrastructure/minio/Dockerfile + target: client + args: + MC_VERSION: RELEASE.2025-08-13T08-35-41Z + image: mtusi2026lab6-mc:RELEASE.2025-08-13T08-35-41Z + entrypoint: ["/bin/sh", "-ec"] + command: + - | + root_user="$$(cat /run/secrets/minio_root_user)" + root_password="$$(cat /run/secrets/minio_root_password)" + api_user="$$(cat /run/secrets/s3_access_key_id)" + api_password="$$(cat /run/secrets/s3_secret_access_key)" + mc alias set local http://minio:9000 "$$root_user" "$$root_password" --api S3v4 + mc mb --ignore-existing "local/$${S3_BUCKET}" + mc anonymous set none "local/$${S3_BUCKET}" + sed "s/__BUCKET__/$${S3_BUCKET}/g" /config/api-policy.template.json > /tmp/api-policy.json + mc admin policy create local messenger-api /tmp/api-policy.json + if ! mc admin user info local "$$api_user" >/dev/null 2>&1; then + mc admin user add local "$$api_user" "$$api_password" + fi + mc admin policy attach local messenger-api --user "$$api_user" + environment: + S3_BUCKET: ${S3_BUCKET:-messenger-attachments} + secrets: + - minio_root_user + - minio_root_password + - s3_access_key_id + - s3_secret_access_key + volumes: + - ./infrastructure/minio/api-policy.template.json:/config/api-policy.template.json:ro + depends_on: + minio: + condition: service_healthy + restart: "no" + + broker: + image: rabbitmq:4.1.4-alpine + entrypoint: ["/bin/sh", "-ec"] + command: + - | + export RABBITMQ_DEFAULT_USER=messenger + export RABBITMQ_DEFAULT_PASS="$$(cat /run/secrets/broker_password)" + exec docker-entrypoint.sh rabbitmq-server + secrets: + - broker_password + volumes: + - broker_data:/var/lib/rabbitmq + healthcheck: + test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"] + interval: 5s + timeout: 5s + retries: 20 + start_period: 10s + stop_grace_period: 20s + restart: unless-stopped + deploy: + resources: + limits: + cpus: "0.50" + memory: 256M + + dispatcher: + build: + context: . + dockerfile: Dockerfile + image: mtusi2026lab6-app + entrypoint: ["/app/dispatcher"] + environment: + DATABASE_URL_FILE: /run/secrets/database_url + BROKER_URL_FILE: /run/secrets/broker_url + DB_CONNECT_TIMEOUT: ${DB_CONNECT_TIMEOUT:-5s} + DB_QUERY_TIMEOUT: ${DB_QUERY_TIMEOUT:-3s} + JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60} + JOB_RETRY_BASE: ${JOB_RETRY_BASE:-250ms} + JOB_RETRY_MAX: ${JOB_RETRY_MAX:-4s} + JOB_LEASE_SECONDS: ${JOB_LEASE_SECONDS:-75} + DISPATCHER_FAULT_BEFORE_PUBLISH_FILE: /tmp/mtusi-fault-before-publish + OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318} + OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf + OTEL_EXPORTER_OTLP_TIMEOUT: ${OTEL_EXPORTER_OTLP_TIMEOUT:-3000} + OTEL_TRACES_SAMPLER: parentbased_always_on + secrets: + - database_url + - broker_url + depends_on: + broker: + condition: service_healthy + migrate: + condition: service_completed_successfully + restart: unless-stopped + healthcheck: + disable: true + deploy: + resources: + limits: + cpus: "0.25" + memory: 128M + + worker: + build: + context: . + dockerfile: Dockerfile + image: mtusi2026lab6-app + entrypoint: ["/app/worker"] + environment: + DATABASE_URL_FILE: /run/secrets/database_url + BROKER_URL_FILE: /run/secrets/broker_url + S3_ENDPOINT: ${S3_ENDPOINT:-http://minio:9000} + S3_REGION: ${S3_REGION:-us-east-1} + S3_BUCKET: ${S3_BUCKET:-messenger-attachments} + S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_access_key_id + S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key + S3_OPERATION_TIMEOUT: ${S3_OPERATION_TIMEOUT:-5s} + WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-2} + JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5} + JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60} + JOB_RETRY_BASE: ${JOB_RETRY_BASE:-250ms} + JOB_RETRY_MAX: ${JOB_RETRY_MAX:-4s} + JOB_LEASE_SECONDS: ${JOB_LEASE_SECONDS:-75} + STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-86400} + STAGING_CLEANUP_INTERVAL_SECONDS: ${STAGING_CLEANUP_INTERVAL_SECONDS:-30} + WORKER_FAULT_BEFORE_OBJECTS_FILE: /tmp/mtusi-fault-before-objects + WORKER_FAULT_AFTER_OBJECTS_FILE: /tmp/mtusi-fault-after-objects + DB_CONNECT_TIMEOUT: ${DB_CONNECT_TIMEOUT:-5s} + DB_QUERY_TIMEOUT: ${DB_QUERY_TIMEOUT:-3s} + GOMEMLIMIT: ${WORKER_GO_MEMORY_LIMIT:-448MiB} + OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318} + OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf + OTEL_EXPORTER_OTLP_TIMEOUT: ${OTEL_EXPORTER_OTLP_TIMEOUT:-3000} + OTEL_TRACES_SAMPLER: parentbased_always_on + secrets: + - database_url + - broker_url + - s3_access_key_id + - s3_secret_access_key + depends_on: + broker: + condition: service_healthy + migrate: + condition: service_completed_successfully + minio-bootstrap: + condition: service_completed_successfully + stop_grace_period: 70s + restart: unless-stopped + healthcheck: + disable: true + deploy: + resources: + limits: + cpus: "1.00" + memory: ${WORKER_MEMORY_LIMIT:-512M} + api: + build: + context: . + dockerfile: Dockerfile + image: mtusi2026lab6-app + environment: + APP_HOST: ${APP_HOST:-0.0.0.0} + APP_PORT: ${APP_INTERNAL_PORT:-8080} + APP_ENV: ${APP_ENV:-lab} + + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400} + JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5} + SESSION_STORE: ${SESSION_STORE:-postgres} + SESSION_COOKIE_SECURE: ${SESSION_COOKIE_SECURE:-false} + CURSOR_SIGNING_KEY_FILE: ${CURSOR_SIGNING_KEY_FILE:-/run/secrets/cursor_signing_key} + + CACHE_URL: ${CACHE_URL:-redis://redis:6379/0} + CACHE_TTL: ${CACHE_TTL:-5m} + CACHE_OPERATION_TIMEOUT: ${CACHE_OPERATION_TIMEOUT:-250ms} + CACHE_POOL_SIZE: ${CACHE_POOL_SIZE:-10} + + S3_ENDPOINT: ${S3_ENDPOINT:-http://minio:9000} + S3_REGION: ${S3_REGION:-us-east-1} + S3_BUCKET: ${S3_BUCKET:-messenger-attachments} + S3_ACCESS_KEY_ID_FILE: ${S3_ACCESS_KEY_ID_FILE:-/run/secrets/s3_access_key_id} + S3_SECRET_ACCESS_KEY_FILE: ${S3_SECRET_ACCESS_KEY_FILE:-/run/secrets/s3_secret_access_key} + S3_OPERATION_TIMEOUT: ${S3_OPERATION_TIMEOUT:-5s} + + DATABASE_URL_FILE: ${DATABASE_URL_FILE:-/run/secrets/database_url} + + DB_MAX_CONNS: ${DB_MAX_CONNS:-10} + DB_MIN_CONNS: ${DB_MIN_CONNS:-2} + DB_MAX_CONN_LIFETIME: ${DB_MAX_CONN_LIFETIME:-30m} + DB_MAX_CONN_IDLE_TIME: ${DB_MAX_CONN_IDLE_TIME:-5m} + DB_HEALTH_CHECK_PERIOD: ${DB_HEALTH_CHECK_PERIOD:-30s} + DB_CONNECT_TIMEOUT: ${DB_CONNECT_TIMEOUT:-5s} + DB_QUERY_TIMEOUT: ${DB_QUERY_TIMEOUT:-3s} + + READINESS_TIMEOUT: ${READINESS_TIMEOUT:-2s} + SHUTDOWN_DRAIN_DELAY: ${SHUTDOWN_DRAIN_DELAY:-2s} + SHUTDOWN_TIMEOUT: ${SHUTDOWN_TIMEOUT:-10s} + GOMEMLIMIT: ${API_GO_MEMORY_LIMIT:-220MiB} + OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318} + OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf + OTEL_EXPORTER_OTLP_TIMEOUT: ${OTEL_EXPORTER_OTLP_TIMEOUT:-3000} + OTEL_TRACES_SAMPLER: parentbased_always_on + secrets: + - database_url + - s3_access_key_id + - s3_secret_access_key + - cursor_signing_key + expose: + - "8080" + depends_on: + postgres: + condition: service_healthy + redis: + condition: service_healthy + migrate: + condition: service_completed_successfully + minio-bootstrap: + condition: service_completed_successfully + deploy: + replicas: ${API_REPLICAS:-2} + resources: + limits: + cpus: "${API_CPU_LIMIT:-0.50}" + memory: ${API_MEMORY_LIMIT:-256M} + healthcheck: + test: + [ + "CMD-SHELL", + "wget -qO- http://127.0.0.1:$${APP_PORT:-8080}/health/ready || exit 1", + ] + interval: 5s + timeout: 3s + retries: 10 + start_period: 5s + stop_grace_period: 15s + restart: unless-stopped + + loki: + image: grafana/loki:3.7.9 + command: ["-config.file=/etc/loki/config.yaml"] + ports: + - "127.0.0.1:${LOKI_PORT:-3100}:3100" + volumes: + - ./infrastructure/telemetry/loki/config.yaml:/etc/loki/config.yaml:ro + - loki_data:/loki + expose: + - "3100" + healthcheck: + test: ["CMD", "/usr/bin/loki", "-version"] + interval: 10s + timeout: 5s + retries: 10 + restart: unless-stopped + deploy: + resources: + limits: + cpus: "0.50" + memory: 384M + + tempo: + image: grafana/tempo:2.10.5 + command: ["-config.file=/etc/tempo/config.yaml"] + ports: + - "127.0.0.1:${TEMPO_PORT:-3200}:3200" + volumes: + - ./infrastructure/telemetry/tempo/config.yaml:/etc/tempo/config.yaml:ro + - tempo_data:/var/tempo + expose: + - "3200" + - "4318" + healthcheck: + test: ["CMD", "/tempo", "-version"] + interval: 10s + timeout: 5s + retries: 10 + restart: unless-stopped + deploy: + resources: + limits: + cpus: "0.50" + memory: 384M + + otel-collector: + image: otel/opentelemetry-collector-contrib:0.165.0 + command: ["--config=/etc/otelcol-contrib/config.yaml"] + volumes: + - ./infrastructure/telemetry/otel-collector/config.yaml:/etc/otelcol-contrib/config.yaml:ro + expose: + - "4318" + - "8888" + - "8889" + - "13133" + depends_on: + loki: + condition: service_healthy + tempo: + condition: service_healthy + healthcheck: + test: ["CMD", "/otelcol-contrib", "components"] + interval: 10s + timeout: 5s + retries: 10 + restart: unless-stopped + deploy: + resources: + limits: + cpus: "0.50" + memory: 256M + + prometheus: + image: prom/prometheus:v3.16.0 + command: + - --config.file=/etc/prometheus/prometheus.yaml + - --storage.tsdb.path=/prometheus + - --storage.tsdb.retention.time=7d + ports: + - "127.0.0.1:${PROMETHEUS_PORT:-9090}:9090" + volumes: + - ./infrastructure/telemetry/prometheus/prometheus.yaml:/etc/prometheus/prometheus.yaml:ro + - ./infrastructure/telemetry/prometheus/rules:/etc/prometheus/rules:ro + - prometheus_data:/prometheus + expose: + - "9090" + depends_on: + otel-collector: + condition: service_healthy + healthcheck: + test: ["CMD", "/bin/prometheus", "--version"] + interval: 10s + timeout: 5s + retries: 10 + restart: unless-stopped + deploy: + resources: + limits: + cpus: "0.50" + memory: 384M + + grafana: + image: grafana/grafana:13.3.0 + ports: + - "127.0.0.1:${GRAFANA_PORT:-3000}:3000" + environment: + GF_AUTH_ANONYMOUS_ENABLED: "true" + GF_AUTH_ANONYMOUS_ORG_ROLE: Viewer + GF_AUTH_DISABLE_LOGIN_FORM: "true" + GF_USERS_DEFAULT_THEME: dark + GF_ANALYTICS_CHECK_FOR_UPDATES: "false" + GF_ANALYTICS_REPORTING_ENABLED: "false" + GF_PLUGINS_PREINSTALL_DISABLED: "true" + GF_PLUGINS_PREINSTALL_AUTO_UPDATE: "false" + GF_PLUGINS_PLUGIN_ADMIN_ENABLED: "false" + GF_SECURITY_X_XSS_PROTECTION: "false" + volumes: + - grafana_data:/var/lib/grafana + - ./infrastructure/telemetry/grafana/provisioning:/etc/grafana/provisioning:ro + - ./infrastructure/telemetry/grafana/dashboards:/var/lib/grafana/dashboards:ro + depends_on: + prometheus: + condition: service_healthy + loki: + condition: service_healthy + tempo: + condition: service_healthy + healthcheck: + test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:3000/api/health >/dev/null || exit 1"] + interval: 10s + timeout: 5s + retries: 20 + start_period: 10s + restart: unless-stopped + deploy: + resources: + limits: + cpus: "0.50" + memory: 384M + + redis-insight: + image: redis/redisinsight:3.8.0@sha256:b5e19ee240abef6edb435871b90ff8a210995422e8e018ab61c0339d318a1f84 + profiles: ["tools"] + ports: + - "127.0.0.1:${REDIS_INSIGHT_PORT:-5540}:5540" + volumes: + - redis_insight_data:/data + depends_on: + redis: + condition: service_healthy + restart: unless-stopped + deploy: + resources: + limits: + cpus: "0.50" + memory: 256M + + postgres-restore: + image: postgres:16.15-alpine3.24@sha256:721873c34ceb9f8d8fc265984940dc982404c105f19ad51be9fdc5970a6080ea + profiles: ["recovery"] + environment: + POSTGRES_USER: ${POSTGRES_USER:-messenger} + POSTGRES_DB: ${POSTGRES_RESTORE_DB:-messenger_restore_admin} + POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password + secrets: + - postgres_password + volumes: + - postgres_restore_data:/var/lib/postgresql/data + healthcheck: + test: + [ + "CMD-SHELL", + "pg_isready -U ${POSTGRES_USER:-messenger} -d ${POSTGRES_RESTORE_DB:-messenger_restore_admin}", + ] + interval: 5s + timeout: 3s + retries: 10 + start_period: 5s + restart: "no" + deploy: + resources: + limits: + cpus: "1.00" + memory: 512M + +volumes: + postgres_data: + redis_insight_data: + minio_data: + broker_data: + postgres_restore_data: + prometheus_data: + loki_data: + tempo_data: + grafana_data: + +secrets: + postgres_password: + file: ./secrets/postgres_password.txt + database_url: + file: ./secrets/database_url.txt + cursor_signing_key: + file: ./secrets/cursor_signing_key.txt + minio_root_user: + file: ./secrets/minio_root_user.txt + minio_root_password: + file: ./secrets/minio_root_password.txt + s3_access_key_id: + file: ./secrets/s3_access_key_id.txt + s3_secret_access_key: + file: ./secrets/s3_secret_access_key.txt + broker_password: + file: ./secrets/broker_password.txt + broker_url: + file: ./secrets/broker_url.txt diff --git a/evidence/lab6-final-audit.md b/evidence/lab6-final-audit.md new file mode 100644 index 0000000..646aae9 --- /dev/null +++ b/evidence/lab6-final-audit.md @@ -0,0 +1,31 @@ +# Lab 6 — final audit + +Date: 2026-11-12. + +## Confirmed fixes from the audit + +1. SLO policy window previously said 30 days while Prometheus retained 7 days. The policy is now explicitly 7 days and has verifiable `messenger:slo_*_ratio_7d` recording rules. +2. The skeleton-only CI had no application job. CI now builds the complete Compose stack, waits for readiness, runs the public smoke and telemetry-path tests, prints logs on failure and removes ephemeral volumes. +3. Histogram calibration was added to guard against seconds/milliseconds and default-bucket mistakes. +4. `govulncheck` found 19 reachable vulnerabilities in the original AMQP and image dependencies. `github.com/rabbitmq/amqp091-go` was upgraded to v1.14.0 and `golang.org/x/image` to v0.45.0. Fixed transitive versions of `grpc`, `x/net`, `x/crypto` and `klauspost/compress` removed six additional non-reachable findings. + +## Verification + +- `git diff --check`: PASS. +- `git add --dry-run .`: `.env`, `secrets/`, `__pycache__` and build artifacts excluded. +- Secret scan: no committed local credential value found. +- `go test -race -count=1 ./...`: PASS. +- `go vet ./...`, `go build ./...`, `go mod verify`: PASS. +- `govulncheck -show verbose ./...`: PASS; no symbol, package or module vulnerabilities found. +- Python compileall: PASS. +- frontend `npm ci`, `npm test`, `npm run build`: PASS; npm reported 0 vulnerabilities. +- Compose config and all dashboard JSON files: PASS. +- Prometheus `promtool`: PASS, 17 rules. +- Public smoke, grade-4 telemetry regression, grade-5 SLO experiment: PASS. +- Histogram calibration: PASS; HTTP client/Prometheus p95 3.570/4.910 ms, ready p95 1.013/0.946 s, worker p95 97.5 ms. + +## Remaining limitations + +- The seven-day SLO policy is locally verifiable but the burn windows are intentionally compressed for the laboratory experiment. +- No independent human performed the runbook drill; the black-box scenario follows it automatically. +- Repository shell scripts passed `bash -n` and ShellCheck 0.11.0 after resolving four SC1007 warnings. diff --git a/evidence/lab6-grade3.md b/evidence/lab6-grade3.md new file mode 100644 index 0000000..cff87c5 --- /dev/null +++ b/evidence/lab6-grade3.md @@ -0,0 +1,132 @@ +# Lab6 — доказательства уровня 3 + +Дата прогона: 2026-11-10. Стенд: WSL2, Docker Compose, ветка `solution/bvt2301-churilin`. Чтобы не останавливать lab5, lab6 проверялась на loopback-портах 18080/13000/19090/13100/13200. + +## Сборка и базовые проверки + +```text +make check +PASS + +make validate PYTHON=/home/d1frend/HL/mtusi2026lab5/.venv/bin/python +PASS + +go test -count=1 ./... +PASS + +go vet ./... +PASS + +go build ./... +PASS + +docker compose --env-file .env config --quiet +exit 0 +``` + +После `docker compose --env-file .env up -d --build` healthy: обе API-реплики, load balancer, frontend, PostgreSQL, Redis, MinIO, RabbitMQ, Collector, Prometheus, Loki, Tempo и Grafana. Одноразовые migrate/minio-bootstrap завершились успешно. + +## Публичный smoke + +```text +make test BASE_URL=http://127.0.0.1:18080 +PASS: signup/signin/session/me/search/chats/messages/cursors/attachments/auth/error format +``` + +## Наблюдаемость + +Команда: + +```sh +python3 tests/observability_grade3.py \ + --prometheus-url http://127.0.0.1:19090 \ + --loki-url http://127.0.0.1:13100 \ + --tempo-url http://127.0.0.1:13200 \ + --grafana-url http://127.0.0.1:13000 \ + --timeout 90 +``` + +Фактический итог: + +```text +PASS: grade-3 metrics, structured logs, traces and Grafana dashboard verified. +api_metric_series=14 +worker_metric_series=2 +api_trace_id=e18612a970f7515c85473ed980f0fa12 +worker_trace_id=5af46620fe843e5448bf60562ca92b0e +dashboard_uid=mtusi-lab6-grade3 +``` + +После `make test` сценарий проверяет сохранённые сигналы: + +1. проверяет API counter/histogram и worker counter/histogram в Prometheus; +2. проверяет `service_name`, `service_version`, `service_instance_id`, `deployment_environment_name=lab`; +3. отклоняет forbidden high-cardinality labels; +4. находит структурированные API/worker events в Loki и извлекает trace ID; +5. запрашивает соответствующие traces в Tempo; +6. проверяет health Grafana и provisioned dashboard UID. + +Trace ID — диагностические идентификаторы, не секреты. В доказательства не включены credentials, токены, тела сообщений или байты вложений. + +## Проверка сохранности бизнес-функций + +Проверка выполнена после подключения instrumentation и после финального recreate сервисов. Публичный smoke прошёл повторно; Collector был перезапущен отдельно, при этом API оставался healthy. После восстановления Collector observability test снова увидел метрики, логи и трассы. Это подтверждает неблокирующий экспорт в проверенной модели кратковременной недоступности Collector. + +## Два контролируемых отказа + +Воспроизводимая команда для чистого стенда: + +```sh +make test-observability-incidents +``` + +Она последовательно запускает `test-async-resilience`, `test-storage-outage` и затем проверяет сохранённые сигналы. На стенде с альтернативными портами финальный verifier дал: + +```text +PASS +api_5xx_total=1 +worker_failed_total=5 +storage event=http_request_completed +storage route=POST /api/v1/chats/{chat_id}/attachments +storage status_code=503 +storage trace_id=7773146a1f76d4048d2eca50f54a7443 +worker event=attachment_job_failed +worker outcome=failed +worker attempt=1 +worker trace_id=6a131a33b296ca076056c08015dc2a9e +``` + +Обе trace ID запрошены через Tempo API и содержат реальные batches/spans. Диагноз первого инцидента: S3/MinIO недоступен на upload-path, потому что API route одновременно дал 503/5xx и trace. Диагноз второго: worker не завершил attachment job и дошёл до bounded failure; это одновременно видно по `outcome=failed`, warn event и consumer trace. + +Фактический fault injection MinIO: + +```text +readiness_503_seconds=2.005 +upload_503_seconds=5.009 +original_bytes_verified=111817 +PASS: MinIO outage returns bounded JSON 503 and preserves existing originals. +``` + +Фактический async resilience: + +```text +PASS: durable recovery, idempotent redelivery and bounded final failure verified. +``` + +После этих экспериментов `go test -race -count=1 ./...` прошёл для всех пакетов. + +## Контрольная нагрузка + +```text +workload=closed-loop POST messages; no automatic retries +duration=30.016 s +concurrency=4 +successful_requests=11556 +failed_requests=0 +successful_rps=384.99 +p50=7.426 ms +p95=32.466 ms +p99=51.370 ms +``` + +Percentile относятся только к успешным запросам. Closed-loop создаёт coordinated omission, результат включает client overhead и служит проверкой генерации/наблюдаемости сигналов, а не переносимым performance benchmark. diff --git a/evidence/lab6-grade4.md b/evidence/lab6-grade4.md new file mode 100644 index 0000000..997e6b8 --- /dev/null +++ b/evidence/lab6-grade4.md @@ -0,0 +1,95 @@ +# Lab 6 — evidence for grade 4 + +Environment: local Docker Compose, alternate loopback ports `18080/13000/19090/13100/13200`, 2026-11-12. + +## Static and configuration checks + +- `go test -count=1 ./...`: PASS. +- `docker compose config --quiet`: PASS. +- Collector `validate`: PASS. +- `promtool check config` and `promtool check rules`: PASS, 3 rules. +- Grafana dashboard UID `mtusi-lab6-grade4`: provisioned. + +## End-to-end W3C trace + +`make test-observability-grade4 ...`: PASS. + +```json +{ + "trace_id": "e219baae473d961c30c97857bbfb19dd", + "services": ["messenger-api", "messenger-dispatcher", "messenger-worker"], + "span_kinds": ["CLIENT", "CONSUMER", "PRODUCER", "SERVER"], + "span_count": 36, + "queue_metric_series": 2, + "db_pool_series": 12, + "dashboard_uid": "mtusi-lab6-grade4" +} +``` + +## Retry in the same trace + +`make test-observability-retry-trace ...`: PASS. + +```json +{ + "trace_id": "0df6d4041008c05e5c2c77b0c2bd2ddf", + "attachment_status": "ready", + "attempts": [1, 2], + "producer_spans": 2, + "consumer_spans": 2, + "span_count": 46 +} +``` + +The first attempt observed MinIO unavailable. After MinIO recovery, the second attempt succeeded. Both attempts, DB spans and S3 spans use the original upload trace ID. + +## Alert firing and resolution + +`make test-observability-alerts ...`: PASS. + +```json +{ + "queue_lag": { + "firing_after_seconds": 26.075, + "depth": 1, + "oldest_age_seconds": 21.156533, + "resolved_after_seconds": 8.009 + }, + "database_outage": { + "firing_after_seconds": 19.044, + "failed_requests": 8, + "trace_id": "db176205d463b89b73c737780e58cf06", + "error_span": "postgresql.acquire", + "resolved_after_seconds": 44.049 + } +} +``` + +## Telemetry backend outage + +`make test-telemetry-backend-outage ...`: PASS. + +```json +{ + "business_requests": 400, + "attachment_status": "ready", + "accepted_signal_delta": 3170, + "dropped_signal_delta": 75, + "collector_queue_size": 34, + "collector_queue_capacity": 256, + "collector_peak_memory_bytes": 261305139, + "collector_container_limit_bytes": 268435456, + "recovery_trace_id": "01806671c8d2cee14dc504f63a60197b" +} +``` + +No business request failed and the attachment reached `ready`. Telemetry loss began only after the bounded 30-second retry budget. Loki/Tempo recovery was confirmed by a fresh correlated log and Tempo trace. + +## Lifecycle cleanup + +At the end of the grade-4 work, `make cleanup-lab` completed successfully. Verified postcondition: + +- no running/stopped `mtusi2026lab6-*` Compose containers; +- no locally built `mtusi2026lab6-*` images; +- named volumes remain for an intentional later resume: `broker_data`, `grafana_data`, `loki_data`, `minio_data`, `postgres_data`, `prometheus_data`, `tempo_data`; +- pulled third-party images and other labs are untouched. diff --git a/evidence/lab6-grade5.md b/evidence/lab6-grade5.md new file mode 100644 index 0000000..9906345 --- /dev/null +++ b/evidence/lab6-grade5.md @@ -0,0 +1,97 @@ +# Lab 6 — evidence for grade 5, track 2 + +Date: 2026-11-12. Environment: local Docker Compose, alternate loopback ports `18080/13000/19090/13100/13200`. + +## Configuration + +- Track: SLO and incident detection. +- Policy window: 7 days, matching Prometheus retention. +- API SLO: 99% non-5xx, 1% error budget, recording rule `messenger:slo_api_success_ratio_7d`. +- Attachment SLO: 99% ready in no more than 10 seconds, 1% error budget, recording rule `messenger:slo_attachment_ready_ratio_7d`. +- Fast burn: 14.4x, 30s + 2m, `for: 10s`. +- Slow burn: 6x, 1m + 5m, `for: 20s`. +- Prometheus validation: PASS, 17 rules after the final audit. +- Grafana dashboard: `mtusi-lab6-grade5` provisioned. +- Runbook: `infrastructure/telemetry/runbooks/level5.md`. + +The windows are intentionally compressed for a repeatable laboratory experiment. Burn factors remain dimensionless; production windows would be substantially longer. + +## Reproducible command + +```sh +make test-slo-burn-rate \ + BASE_URL=http://127.0.0.1:18080 \ + PROMETHEUS_URL=http://127.0.0.1:19090 \ + LOKI_URL=http://127.0.0.1:13100 \ + TEMPO_URL=http://127.0.0.1:13200 \ + GRAFANA_URL=http://127.0.0.1:13000 +``` + +Result: PASS. + +```json +{ + "api_slo": { + "brief_spike_failures": 4, + "false_positive": { + "pending_or_firing": 0, + "max_30s_ratio": 0.038461538461538464, + "max_5m_ratio": 0.007827788649706457 + }, + "sustained_failures": 136, + "detection_seconds": { + "MessengerAPIBurnRateSlow": 42.194, + "MessengerAPIBurnRateFast": 52.212 + }, + "recovery_seconds": 38.851, + "trace_id": "abac9b8b51c9b4bd3d05c26dab3e37ea", + "root_cause_span": "postgresql.acquire" + }, + "attachment_ready_slo": { + "baseline_fast": 20, + "slow_over_10s": 5, + "recovery_fast": 100, + "detection_seconds": { + "MessengerAttachmentReadyBurnRateFast": 20.039, + "MessengerAttachmentReadyBurnRateSlow": 30.056 + }, + "recovery_seconds": 8.016, + "final_5m_slow_ratio": 0.04794240000000012 + } +} +``` + +## Interpretation + +The bounded four-error spike remained below both burn thresholds and produced no pending/firing state during the observation window. Sustained PostgreSQL unavailability fired both API alerts; Loki correlation and Tempo identified `postgresql.acquire`, so the runbook distinguishes pool/backend failure from handler latency. + +Five delayed jobs consumed the ready SLO budget and fired both ready alerts. One hundred fast completions reduced the five-minute slow ratio below 6%, after which both alerts resolved. + +False-positive evidence covers this controlled workload only. It is not a statistically significant production false-positive rate. No independent human runbook drill was performed; the black-box script follows the same steps automatically. + +## Histogram calibration + +`make test-histogram-calibration ...`: PASS. + +```json +{ + "samples": {"http": 400, "attachments": 12}, + "http_p95_seconds": { + "client": 0.003569880000213743, + "prometheus": 0.004909843739733048, + "ratio": 1.375352599930271 + }, + "ready_p95_seconds": { + "client_polling_upper_bound": 1.0131328810002742, + "prometheus": 0.9458333333333333, + "ratio": 0.9335728324200716 + }, + "worker_p95_seconds": 0.0975 +} +``` + +Exported HTTP buckets begin at 5 ms, worker buckets at 50 ms and ready buckets at 100 ms. The client/Prometheus values have the same order of magnitude and use seconds consistently. + +## Lifecycle cleanup + +`make cleanup-lab` completed successfully after the grade-5 regression. A Docker inventory confirmed no lab1–lab6 containers, locally built images or Compose networks remain. Lab5 and lab6 named volumes were intentionally preserved; no pulled third-party image or unrelated Docker resource was selected for removal. diff --git a/frontend/.dockerignore b/frontend/.dockerignore new file mode 100644 index 0000000..0e75fe5 --- /dev/null +++ b/frontend/.dockerignore @@ -0,0 +1,3 @@ +node_modules +dist +coverage diff --git a/frontend/index.html b/frontend/index.html new file mode 100644 index 0000000..74b8e76 --- /dev/null +++ b/frontend/index.html @@ -0,0 +1,17 @@ + + + + + + + + MTUCI Messenger + + +
+ + + diff --git a/frontend/package-lock.json b/frontend/package-lock.json new file mode 100644 index 0000000..556c03b --- /dev/null +++ b/frontend/package-lock.json @@ -0,0 +1,1688 @@ +{ + "name": "mtusi-messenger-web", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "mtusi-messenger-web", + "version": "0.1.0", + "dependencies": { + "@tanstack/react-query": "^5.104.5", + "lucide-react": "^1.61.0", + "react": "^19.3.1", + "react-dom": "^19.3.1", + "react-router-dom": "^7.18.4" + }, + "devDependencies": { + "@types/react": "^19.3.0", + "@types/react-dom": "^19.3.0", + "@vitejs/plugin-react": "^6.1.2", + "typescript": "^7.0.2", + "vite": "^8.3.5", + "vitest": "^5.0.5" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@oxc-project/types": { + "version": "0.155.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.155.0.tgz", + "integrity": "sha512-SeE8JPwW1xs1tHeNycjUtUBdhorRa8o4jlvjwk49R7/Z291i+4DQa7JJIgOm/TaYQZx+QrPQbVJ/9c8dMIZN8Q==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/oxc-project" + } + }, + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.15.tgz", + "integrity": "sha512-aLcgK9gIJ3YRvrrtfSBbRa27F5WrpiTaPulnFpsHPxpUHgFlSgnU4854MHwoRGEBhfRJDWCS2WQ7lIjskE9Olw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.15.tgz", + "integrity": "sha512-xD7DdZCrbThKuxNg7ooQmvp07ys4J/pnSEMTG3/OdOWl6daC67m/Q4fL78sRHMxTH/N4fGUbYhcPM0MF5WFHkg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.15.tgz", + "integrity": "sha512-m2WuQ6r0B4OTYxyPpNLtXaMRbRDUbG8YQV2Q3KTdSSK8Th6KHCnC8jVCJt8bvYeSB5WivkkNbc85mKadaSdOxA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.15.tgz", + "integrity": "sha512-5RtnsHM36nodM9WbMy+zip0LGS/G+y5wro5RHrpOlr4ac24+1zSi9kiV2MP1myZeZ/ifEHfulQcWjnAXzc2C2A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.15.tgz", + "integrity": "sha512-g3l09pyFqhu+135JKkbkwiKGQmwU5hUMUPJ4VdBADvuqR8d33L6H578rh8m7rtxbdp+VmX/+nzI7nvhSZlzpUQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.15.tgz", + "integrity": "sha512-nIe3VugI97nGQtspPxDqA4sXMUpeiocKIP/CqpY/u/vgbT+alX+cVxu1C/oVBPKg4feNTmYovE91v4DgXvXNwQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.15.tgz", + "integrity": "sha512-iTBjXx+B5QSvgI89lJfmqh4wTh8NabR1YZIIN3hNx4zSG0EVfVqkOvLulNpG4251pbd6/IAmZ/LefVk1Y4rPhw==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.15.tgz", + "integrity": "sha512-uN26XOnVR7rqQupG3V9oAG2EGGatWjcJHOeDOHUFCh4TBWmP2tHTFoVN13aYbwfm0aHqJAEmcwhAu6sooIjfqQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.15.tgz", + "integrity": "sha512-9nWkcdd+H+XhaA3fQIwpHnKIrfx/PQ6rO0pivr78Og07tXlUlctBBJoEYLPfhTmCR/QxEVdn6uPjHV5SymPhdw==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.15.tgz", + "integrity": "sha512-Ggh0ciFjLwIusLSLz7LZYEaGdxOAUJXI+Qu5JCbhPJJHEt8vP+IjRATTJheiJsdzzTYgUiHUiw3X1Ea3ZpMBdA==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.15.tgz", + "integrity": "sha512-FHg60rS6DBePAYZ9X9F67x+JObFdmgn6tupA1C/a3B+CufFmTD4mX+e8M75tCiAO3foR/6xwVBI0KQiI7sn/rw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.15.tgz", + "integrity": "sha512-/cvV/7v5VGz/moiz0XKRj2dE8DzsKyhIu1KpOvJGPjRywg3yscON889UGvAe8zfiJLHup7VLjBduoGWi3HusWQ==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.15.tgz", + "integrity": "sha512-MyzC5Hrv/sm+Z7TSGKP/j8001RO2xQm1zOpCNVL4j0cY/VhBZviludA2YFQ7i4lH6ZAXxQm0lcMdBzM+99mE7w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.15.tgz", + "integrity": "sha512-+PgYiS+AH5omy6L45ZLxybasauJaj3M8buoT83D+nzPmCayXlxUV9hydhciCKVyIg0B/v0BtXPDE1uGqNwCPpg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.15.tgz", + "integrity": "sha512-HFZd2QNQYn1JbIi+Hpd7H+r/lkWxcfIu28nirZ6eCn2LafuvmExMlb/P96Sfx5tf7pPArw39IdhmCF8vmV+NhQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", + "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@tanstack/query-core": { + "version": "5.104.5", + "resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.104.5.tgz", + "integrity": "sha512-Q94gI8Opd+CbdVNOdj8ZCyV8WqLYitrDq1t96Xc8WZT6lY0r5iRnJLXYDxMex7EEf2v+mXvn4FcjaBKSxXZQ9A==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + } + }, + "node_modules/@tanstack/react-query": { + "version": "5.104.5", + "resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.104.5.tgz", + "integrity": "sha512-RORgFe052U+93weaNuqg7qHq7vNVNzXN/VrXqD4bbAuQCWUqOl2lV5Ui9flWk5CVvMyL/Bh27QWhzwH0aaOx9g==", + "license": "MIT", + "dependencies": { + "@tanstack/query-core": "5.104.5" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + }, + "peerDependencies": { + "@types/react": "^18 || ^19", + "react": "^18 || ^19" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/react": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz", + "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "csstype": "^3.2.2" + } + }, + "node_modules/@types/react-dom": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.3.0.tgz", + "integrity": "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "^19.3.0" + } + }, + "node_modules/@typescript/typescript-aix-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", + "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz", + "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz", + "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz", + "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz", + "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz", + "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz", + "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-loong64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz", + "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-mips64el": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz", + "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz", + "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-riscv64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz", + "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-s390x": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz", + "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz", + "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz", + "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz", + "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz", + "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz", + "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-sunos-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz", + "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz", + "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz", + "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@vitejs/plugin-react": { + "version": "6.1.2", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-6.1.2.tgz", + "integrity": "sha512-fhJNGUdscQa4HkI0xFxwonWyhnVReCPDbXI7FH7jmzpnVCrFQI7PRrhWecO263610vOrs9tr2Y4xcf8uAdFxbw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rolldown/pluginutils": "^1.0.1" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0", + "babel-plugin-react-compiler": "^1.0.0", + "oxc-transform-react": "^0.152.0", + "vite": "^8.0.0" + }, + "peerDependenciesMeta": { + "@rolldown/plugin-babel": { + "optional": true + }, + "babel-plugin-react-compiler": { + "optional": true + }, + "oxc-transform-react": { + "optional": true + } + } + }, + "node_modules/@vitest/mocker": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.0.5.tgz", + "integrity": "sha512-xLL3lkDegJZw+MGoGaCCsFayDZthGgpAtr3Vziyfc4p7xH89K7KRPcRBBh/kEYm0Aqkt5DtTmkYpBtRV/FrHZg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.31", + "@vitest/spy": "5.0.5", + "estree-walker": "^3.0.3", + "magic-string": "^1.4.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9 || ^3.0.0", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/spy": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.0.5.tgz", + "integrity": "sha512-lwJRExuH417257Q5wv9QYugN9IMJkoxcrKrYxGPQkBzl7wlNpTUxD/5yNX4ESKVUIShKPgkGchYPFMWOOk0wzw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/chai": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz", + "integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/cookie": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz", + "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/es-module-lexer": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", + "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==", + "dev": true, + "license": "MIT" + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/expect-type": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lucide-react": { + "version": "1.61.0", + "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.61.0.tgz", + "integrity": "sha512-v2SQPPPNjnr+BlhL9Spuzmo5yR+hLkftfuE4E3jaxdNPgSH0hJKPcLJBP7yAta87jQNPsSERS59PJjCJ/CorBA==", + "license": "ISC", + "peerDependencies": { + "@types/react": "*", + "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/magic-string": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.3.tgz", + "integrity": "sha512-z12OxmaPGE0F4xlpGdjuAUckipLpQlTAuAmyGhNoD7ODpYUzvDfvtxUbjM/jwznyP178oju/KDdyi220wNJ0RQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0" + } + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/obug": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/obug/-/obug-3.0.0.tgz", + "integrity": "sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT", + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.31", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.31.tgz", + "integrity": "sha512-YUbWYCgErwnMAVkjUnYa+KlMBzGpHwiIt/DE7f0G33AuX2LH9UcTk6KgWxd3zRU+pN3u/C+Xl3EnMLM4Hea7Sg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/react": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react/-/react-19.3.1.tgz", + "integrity": "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.1.tgz", + "integrity": "sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ==", + "license": "MIT", + "dependencies": { + "scheduler": "^0.28.0" + }, + "peerDependencies": { + "react": "^19.3.1" + } + }, + "node_modules/react-router": { + "version": "7.18.4", + "resolved": "https://registry.npmjs.org/react-router/-/react-router-7.18.4.tgz", + "integrity": "sha512-PUPQcMhMGRAslLcvtlPz/kmzBEWPhLdgLFrL7pLNepBL6dX0lWj4WD2cUYVgYCuT3jxvghYFg81cDTj44DhetQ==", + "license": "MIT", + "dependencies": { + "cookie": "^1.0.1", + "set-cookie-parser": "^2.6.0" + }, + "engines": { + "node": ">=20.0.0" + }, + "peerDependencies": { + "react": ">=18", + "react-dom": ">=18" + }, + "peerDependenciesMeta": { + "react-dom": { + "optional": true + } + } + }, + "node_modules/react-router-dom": { + "version": "7.18.4", + "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.18.4.tgz", + "integrity": "sha512-yrfmJHIpDG7taCpqKjT1G5B6q3O2K+RN8/fgNf0lTjCwiPbQ0ei6vXX9ZjQR+7ld8Tr7Z5xmyMnZ8YJrphWQUw==", + "license": "MIT", + "dependencies": { + "react-router": "7.18.4" + }, + "engines": { + "node": ">=20.0.0" + }, + "peerDependencies": { + "react": ">=18", + "react-dom": ">=18" + } + }, + "node_modules/rolldown": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.15.tgz", + "integrity": "sha512-6odND+fel5zVw3I4Yc2e69gvguDnX0CAAGiNDZSq4ik5WUcaLrkD2GLuog0XcODbor31hZ5ayEMgVDno+KPV5g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@oxc-project/types": "=0.155.0", + "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm-eabi": "1.2.15", + "@rolldown/binding-android-arm64": "1.2.15", + "@rolldown/binding-darwin-arm64": "1.2.15", + "@rolldown/binding-darwin-x64": "1.2.15", + "@rolldown/binding-freebsd-x64": "1.2.15", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.15", + "@rolldown/binding-linux-arm64-gnu": "1.2.15", + "@rolldown/binding-linux-arm64-musl": "1.2.15", + "@rolldown/binding-linux-ppc64-gnu": "1.2.15", + "@rolldown/binding-linux-s390x-gnu": "1.2.15", + "@rolldown/binding-linux-x64-gnu": "1.2.15", + "@rolldown/binding-linux-x64-musl": "1.2.15", + "@rolldown/binding-openharmony-arm64": "1.2.15", + "@rolldown/binding-win32-arm64-msvc": "1.2.15", + "@rolldown/binding-win32-x64-msvc": "1.2.15" + } + }, + "node_modules/scheduler": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz", + "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==", + "license": "MIT" + }, + "node_modules/set-cookie-parser": { + "version": "2.7.2", + "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.2.tgz", + "integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==", + "license": "MIT" + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/std-env": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.3.0.tgz", + "integrity": "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinybench": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.2.tgz", + "integrity": "sha512-nIZ2N2dFpjBsg2hgitKu7mA+FvsIJuGJOwysRngmVRRmWgR/UyPjwJj8c/fT/dhm8EkHnF5EOogRf+0Z2qrimA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/tinyexec": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz", + "integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/typescript": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz", + "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc" + }, + "engines": { + "node": ">=16.20.0" + }, + "optionalDependencies": { + "@typescript/typescript-aix-ppc64": "7.0.2", + "@typescript/typescript-darwin-arm64": "7.0.2", + "@typescript/typescript-darwin-x64": "7.0.2", + "@typescript/typescript-freebsd-arm64": "7.0.2", + "@typescript/typescript-freebsd-x64": "7.0.2", + "@typescript/typescript-linux-arm": "7.0.2", + "@typescript/typescript-linux-arm64": "7.0.2", + "@typescript/typescript-linux-loong64": "7.0.2", + "@typescript/typescript-linux-mips64el": "7.0.2", + "@typescript/typescript-linux-ppc64": "7.0.2", + "@typescript/typescript-linux-riscv64": "7.0.2", + "@typescript/typescript-linux-s390x": "7.0.2", + "@typescript/typescript-linux-x64": "7.0.2", + "@typescript/typescript-netbsd-arm64": "7.0.2", + "@typescript/typescript-netbsd-x64": "7.0.2", + "@typescript/typescript-openbsd-arm64": "7.0.2", + "@typescript/typescript-openbsd-x64": "7.0.2", + "@typescript/typescript-sunos-x64": "7.0.2", + "@typescript/typescript-win32-arm64": "7.0.2", + "@typescript/typescript-win32-x64": "7.0.2" + } + }, + "node_modules/vite": { + "version": "8.3.5", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.5.tgz", + "integrity": "sha512-z1YpjieJ9g0ebTmQpLBv/oq9E3F9EIlOe+7LahW8SrE3LTiG3udBRUXQOlYXP9b+IC2q2phHeVxj9xGlw34OEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "lightningcss": "^1.33.0", + "picomatch": "^4.0.7", + "postcss": "^8.5.30", + "rolldown": "~1.2.14", + "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.7.1 || ^0.8.0", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vitest": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-5.0.5.tgz", + "integrity": "sha512-cPODOMF8YnkiiYtDdHo6n4wWmBrOBBbOIYH2d33M4l3CdNn72h+qMmO6uXffUN6A5AZFXNND/d+krS9mgkXRfg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/mocker": "5.0.5", + "chai": "^6.3.0", + "es-module-lexer": "^2.3.2", + "expect-type": "^1.4.0", + "magic-string": "^1.4.3", + "obug": "^3.0.0", + "picomatch": "^4.0.7", + "std-env": "^4.3.0", + "tinybench": "^6.2.2", + "tinyexec": "^1.3.1", + "tinyglobby": "^0.2.17", + "why-is-node-running": "3.2.1" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^22.12.0 || ^24.0.0 || >=26.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "5.0.5", + "@vitest/browser-preview": "5.0.5", + "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0", + "@vitest/coverage-istanbul": "5.0.5", + "@vitest/coverage-v8": "5.0.5", + "@vitest/ui": "5.0.5", + "happy-dom": "*", + "jsdom": "*", + "vite": "^6.4.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/coverage-istanbul": { + "optional": true + }, + "@vitest/coverage-v8": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + }, + "vite": { + "optional": false + } + } + }, + "node_modules/why-is-node-running": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-3.2.1.tgz", + "integrity": "sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==", + "dev": true, + "license": "MIT", + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=20.11" + } + } + } +} diff --git a/frontend/package.json b/frontend/package.json new file mode 100644 index 0000000..8f151c3 --- /dev/null +++ b/frontend/package.json @@ -0,0 +1,27 @@ +{ + "name": "mtusi-messenger-web", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "dev": "vite --host 0.0.0.0", + "build": "tsc -b && vite build", + "test": "vitest run", + "test:watch": "vitest" + }, + "dependencies": { + "@tanstack/react-query": "^5.104.5", + "lucide-react": "^1.61.0", + "react": "^19.3.1", + "react-dom": "^19.3.1", + "react-router-dom": "^7.18.4" + }, + "devDependencies": { + "@types/react": "^19.3.0", + "@types/react-dom": "^19.3.0", + "@vitejs/plugin-react": "^6.1.2", + "typescript": "^7.0.2", + "vite": "^8.3.5", + "vitest": "^5.0.5" + } +} diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts new file mode 100644 index 0000000..1e95a48 --- /dev/null +++ b/frontend/src/api/client.ts @@ -0,0 +1,163 @@ +import type { + ApiErrorBody, + Chat, + CreateChatInput, + LoginInput, + Message, + Page, + RegisterInput, + Session, + User, +} from "./types"; + +const publicApi = "/api/v1"; +const browserApi = "/web-api/v1"; + +export class ApiError extends Error { + readonly status: number; + readonly code?: string; + readonly requestId?: string; + + constructor(status: number, body: ApiErrorBody) { + super(body.error?.message || `HTTP ${status}`); + this.name = "ApiError"; + this.status = status; + this.code = body.error?.code; + this.requestId = body.error?.request_id; + } +} + +type RequestOptions = Omit & { + body?: unknown; +}; + +async function request(path: string, options: RequestOptions = {}): Promise { + const headers = new Headers(options.headers); + if (options.body !== undefined) { + headers.set("Content-Type", "application/json"); + } + + const response = await fetch(path, { + ...options, + headers, + credentials: "same-origin", + body: options.body === undefined ? undefined : JSON.stringify(options.body), + }); + + if (!response.ok) { + let body: ApiErrorBody = {}; + try { + body = (await response.json()) as ApiErrorBody; + } catch { + // Preserve a useful HTTP-level error when a proxy returned non-JSON. + } + throw new ApiError(response.status, body); + } + + if (response.status === 204) { + return undefined as T; + } + return (await response.json()) as T; +} + +function encodeBasic({ username, password }: LoginInput): string { + const bytes = new TextEncoder().encode(`${username}:${password}`); + let binary = ""; + for (const byte of bytes) { + binary += String.fromCharCode(byte); + } + return btoa(binary); +} + +async function collectPages(path: string): Promise { + const items: T[] = []; + let cursor: string | null = null; + + for (let pageIndex = 0; pageIndex < 100; pageIndex += 1) { + const search = new URLSearchParams({ limit: "100" }); + if (cursor) { + search.set("cursor", cursor); + } + const page = await request>(`${path}?${search.toString()}`); + items.push(...page.items); + cursor = page.next_cursor; + if (!cursor) { + return items; + } + } + throw new Error("pagination safety limit exceeded"); +} + +export const api = { + register(input: RegisterInput): Promise { + return request(`${publicApi}/users`, { + method: "POST", + body: { + username: input.username, + display_name: input.displayName, + password: input.password, + }, + }); + }, + + login(input: LoginInput): Promise { + return request(`${publicApi}/auth/sessions`, { + method: "POST", + headers: { + Authorization: `Basic ${encodeBasic(input)}`, + }, + }); + }, + + logout(): Promise { + return request(`${browserApi}/auth/sessions/current`, { + method: "DELETE", + }); + }, + + me(): Promise { + return request(`${browserApi}/users/me`); + }, + + chats(): Promise { + return collectPages(`${browserApi}/chats`); + }, + + chat(chatID: string): Promise { + return request(`${browserApi}/chats/${encodeURIComponent(chatID)}`); + }, + + createChat(input: CreateChatInput): Promise { + return request(`${browserApi}/chats`, { + method: "POST", + body: { + title: input.title, + member_ids: input.memberIds, + }, + }); + }, + + messages(chatID: string): Promise { + return collectPages( + `${browserApi}/chats/${encodeURIComponent(chatID)}/messages`, + ); + }, + + sendMessage( + chatID: string, + text: string, + idempotencyKey: string, + attachmentIDs: string[] = [], + ): Promise { + return request( + `${browserApi}/chats/${encodeURIComponent(chatID)}/messages`, + { + method: "POST", + headers: { + "Idempotency-Key": idempotencyKey, + }, + body: { text, attachment_ids: attachmentIDs }, + }, + ); + }, +}; diff --git a/frontend/src/api/types.ts b/frontend/src/api/types.ts new file mode 100644 index 0000000..0f7110a --- /dev/null +++ b/frontend/src/api/types.ts @@ -0,0 +1,58 @@ +export type User = { + id: string; + username: string; + display_name: string; + created_at: string; +}; + +export type Session = { + token: string; + token_type: "Bearer"; + expires_at: string; + user: User; +}; + +export type Chat = { + id: string; + title: string; + member_ids: string[]; + created_at: string; +}; + +export type Message = { + id: string; + chat_id: string; + sender_id: string; + text: string; + attachment_ids: string[]; + created_at: string; +}; + +export type Page = { + items: T[]; + next_cursor: string | null; +}; + +export type ApiErrorBody = { + error?: { + code?: string; + message?: string; + request_id?: string; + }; +}; + +export type RegisterInput = { + username: string; + displayName: string; + password: string; +}; + +export type CreateChatInput = { + title: string; + memberIds: string[]; +}; + +export type LoginInput = { + username: string; + password: string; +}; diff --git a/frontend/src/app/App.tsx b/frontend/src/app/App.tsx new file mode 100644 index 0000000..c6aa7ae --- /dev/null +++ b/frontend/src/app/App.tsx @@ -0,0 +1,51 @@ +import { Navigate, Outlet, Route, Routes, useLocation } from "react-router-dom"; + +import { useAuth } from "../auth/AuthProvider"; +import { LoadingScreen } from "../components/LoadingScreen"; +import { AuthPage } from "../pages/AuthPage"; +import { MessengerPage } from "../pages/MessengerPage"; + +function ProtectedRoute() { + const { user, isLoading } = useAuth(); + const location = useLocation(); + + if (isLoading) { + return ; + } + if (!user) { + return ; + } + return ; +} + +function PublicOnlyRoute() { + const { user, isLoading } = useAuth(); + + if (isLoading) { + return ; + } + if (user) { + return ; + } + return ; +} + +export function App() { + return ( + + }> + } /> + } /> + + + }> + } /> + } /> + } /> + + + } /> + } /> + + ); +} diff --git a/frontend/src/assets/chat-background.jpg b/frontend/src/assets/chat-background.jpg new file mode 100644 index 0000000..899884b Binary files /dev/null and b/frontend/src/assets/chat-background.jpg differ diff --git a/frontend/src/auth/AuthProvider.tsx b/frontend/src/auth/AuthProvider.tsx new file mode 100644 index 0000000..5154fad --- /dev/null +++ b/frontend/src/auth/AuthProvider.tsx @@ -0,0 +1,90 @@ +import { useQuery, useQueryClient } from "@tanstack/react-query"; +import { + createContext, + useCallback, + useContext, + type PropsWithChildren, +} from "react"; + +import { api, ApiError } from "../api/client"; +import type { LoginInput, RegisterInput, User } from "../api/types"; + +type AuthContextValue = { + user: User | null; + isLoading: boolean; + login: (input: LoginInput) => Promise; + register: (input: RegisterInput) => Promise; + logout: () => Promise; +}; + +const AuthContext = createContext(null); +const meQueryKey = ["current-user"] as const; + +async function loadCurrentUser(): Promise { + try { + return await api.me(); + } catch (error) { + if (error instanceof ApiError && error.status === 401) { + return null; + } + throw error; + } +} + +export function AuthProvider({ children }: PropsWithChildren) { + const queryClient = useQueryClient(); + const meQuery = useQuery({ + queryKey: meQueryKey, + queryFn: loadCurrentUser, + retry: false, + staleTime: 30_000, + }); + + const login = useCallback( + async (input: LoginInput) => { + const session = await api.login(input); + queryClient.setQueryData(meQueryKey, session.user); + }, + [queryClient], + ); + + const register = useCallback( + async (input: RegisterInput) => { + await api.register(input); + const session = await api.login({ + username: input.username, + password: input.password, + }); + queryClient.setQueryData(meQueryKey, session.user); + }, + [queryClient], + ); + + const logout = useCallback(async () => { + await api.logout(); + queryClient.setQueryData(meQueryKey, null); + queryClient.removeQueries({ queryKey: ["chats"] }); + }, [queryClient]); + + return ( + + {children} + + ); +} + +export function useAuth(): AuthContextValue { + const context = useContext(AuthContext); + if (!context) { + throw new Error("useAuth must be used within AuthProvider"); + } + return context; +} diff --git a/frontend/src/components/Avatar.tsx b/frontend/src/components/Avatar.tsx new file mode 100644 index 0000000..6fd07fb --- /dev/null +++ b/frontend/src/components/Avatar.tsx @@ -0,0 +1,26 @@ +import { initials } from "../lib/format"; + +type AvatarProps = { + label: string; + seed?: string; + size?: "small" | "medium" | "large"; +}; + +function tone(seed: string): number { + let hash = 0; + for (const character of seed) { + hash = (hash * 31 + character.codePointAt(0)!) >>> 0; + } + return hash % 5; +} + +export function Avatar({ label, seed = label, size = "medium" }: AvatarProps) { + return ( + + ); +} diff --git a/frontend/src/components/ChatList.tsx b/frontend/src/components/ChatList.tsx new file mode 100644 index 0000000..1426d01 --- /dev/null +++ b/frontend/src/components/ChatList.tsx @@ -0,0 +1,121 @@ +import { MessageSquarePlus, Search, UsersRound, X } from "lucide-react"; +import { useMemo, useState } from "react"; +import { useNavigate } from "react-router-dom"; + +import type { Chat, User } from "../api/types"; +import { formatMemberCount } from "../lib/format"; +import { Avatar } from "./Avatar"; + +type ChatListProps = { + chats: Chat[]; + currentUser: User; + error: boolean; + isLoading: boolean; + selectedChatID?: string; + onCreateChat: () => void; +}; + +export function ChatList({ + chats, + currentUser, + error, + isLoading, + selectedChatID, + onCreateChat, +}: ChatListProps) { + const navigate = useNavigate(); + const [search, setSearch] = useState(""); + + const filteredChats = useMemo(() => { + const normalized = search.trim().toLocaleLowerCase("ru"); + if (!normalized) { + return chats; + } + return chats.filter((chat) => + chat.title.toLocaleLowerCase("ru").includes(normalized), + ); + }, [chats, search]); + + return ( + + ); +} diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx new file mode 100644 index 0000000..64ffaad --- /dev/null +++ b/frontend/src/components/ChatView.tsx @@ -0,0 +1,236 @@ +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { + ArrowLeft, + CheckCheck, + RefreshCcw, + Send, + ShieldCheck, + UsersRound, +} from "lucide-react"; +import { + useEffect, + useMemo, + useRef, + useState, + type FormEvent, + type KeyboardEvent, +} from "react"; + +import { api } from "../api/client"; +import type { Chat, Message, User } from "../api/types"; +import { + dayKey, + formatDay, + formatMemberCount, + formatMessageTime, + shortID, +} from "../lib/format"; +import { createIdempotencyKey } from "../lib/idempotency"; +import { Avatar } from "./Avatar"; + +type ChatViewProps = { + chat: Chat; + currentUser: User; + onBack: () => void; +}; + +type SendEnvelope = { + text: string; + idempotencyKey: string; +}; + +export function ChatView({ chat, currentUser, onBack }: ChatViewProps) { + const queryClient = useQueryClient(); + const messagesEnd = useRef(null); + const [draft, setDraft] = useState(""); + const [failedEnvelope, setFailedEnvelope] = useState(null); + + const messagesQuery = useQuery({ + queryKey: ["messages", chat.id], + queryFn: () => api.messages(chat.id), + refetchInterval: 3_000, + staleTime: 1_000, + }); + + const messages = messagesQuery.data ?? []; + + useEffect(() => { + messagesEnd.current?.scrollIntoView({ + behavior: messages.length > 1 ? "smooth" : "auto", + block: "end", + }); + }, [chat.id, messages.length]); + + const mutation = useMutation({ + mutationFn: (envelope: SendEnvelope) => + api.sendMessage(chat.id, envelope.text, envelope.idempotencyKey), + onSuccess: (message) => { + setFailedEnvelope(null); + queryClient.setQueryData( + ["messages", chat.id], + (current = []) => { + if (current.some((item) => item.id === message.id)) { + return current; + } + return [...current, message]; + }, + ); + }, + onError: (_error, envelope) => { + setFailedEnvelope(envelope); + }, + }); + + const groups = useMemo(() => { + const result: Array<{ key: string; label: string; messages: Message[] }> = []; + for (const message of messages) { + const key = dayKey(message.created_at); + const current = result.at(-1); + if (!current || current.key !== key) { + result.push({ + key, + label: formatDay(message.created_at), + messages: [message], + }); + } else { + current.messages.push(message); + } + } + return result; + }, [messages]); + + function send(envelope: SendEnvelope) { + if (!mutation.isPending) { + mutation.mutate(envelope); + } + } + + function submit(event: FormEvent) { + event.preventDefault(); + const text = draft.trim(); + if (!text || Array.from(text).length > 4_000) { + return; + } + const envelope = { text, idempotencyKey: createIdempotencyKey() }; + setDraft(""); + setFailedEnvelope(null); + send(envelope); + } + + function handleKeyDown(event: KeyboardEvent) { + if (event.key === "Enter" && !event.shiftKey) { + event.preventDefault(); + event.currentTarget.form?.requestSubmit(); + } + } + + return ( +
+
+ + +
+ {chat.title} + {formatMemberCount(chat.member_ids.length)} +
+
+
+
+ +
+
+
+ {messagesQuery.isLoading && ( +
+ + Загружаем историю +
+ )} + + {messagesQuery.isError && ( +
+

История временно недоступна

+ +
+ )} + + {!messagesQuery.isLoading && !messagesQuery.isError && messages.length === 0 && ( +
+
+ )} + + {groups.map((group) => ( +
+
{group.label}
+ {group.messages.map((message) => { + const own = message.sender_id === currentUser.id; + return ( +
+ + {own ? "Вы" : shortID(message.sender_id)} + +

{message.text}

+ + {formatMessageTime(message.created_at)} + {own && } + +
+ ); + })} +
+ ))} +
+
+
+ +