diff --git a/.env.example b/.env.example index 2b326558..dbd2b240 100644 --- a/.env.example +++ b/.env.example @@ -28,3 +28,56 @@ OTEL_SERVICE_NAME=messenger-api OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318 OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=lab +# --- реализация lab5–6 (см. REPORT.md, «Соответствие переменных») --- +# Порты LB на хосте (только 127.0.0.1): API, api-ttl (профиль ttl), api-fault (профиль fault), статистика. +API_PORT=8080 +API_TTL_PORT=8081 +API_FAULT_PORT=8082 +LB_STATS_PORT=8404 +API_CPUS=1.0 +API_MEMORY=512M +PG_CPUS=1.0 +PG_MAX_CONNECTIONS=100 +SESSION_CACHE=redis +SESSION_CACHE_TTL_SECONDS=60 +DB_POOL_MAX=10 +KDF_CONCURRENCY=4 +SHUTDOWN_DRAIN_SECONDS=3 +LB_SERVER_MAXCONN=10 +LB_QUEUE_TIMEOUT=2s +UPLOAD_CONCURRENCY=16 +UPLOAD_GRACE_SECONDS=900 +# Worker и очередь (NATS JetStream). Аренда задания = BROKER_ACK_WAIT_SECONDS (брокер) и +# JOB_LEASE_SECONDS (БД); worker продлевает обе каждые ¼ срока, пока жив. +WORKER_REPLICAS=2 +WORKER_CPUS=1.0 +WORKER_MEMORY=1G +WORKER_PIPELINES=1,2 +PIPELINE_VERSION=1 +JOB_LEASE_SECONDS=20 +BROKER_ACK_WAIT_SECONDS=20 +BROKER_MAX_ACK_PENDING=16 +JOB_RETRY_BASE_SECONDS=2 +JOB_RETRY_MAX_SECONDS=60 +JOB_STUCK_SECONDS=600 +WORKER_PROCESS_MEMORY_MB=768 +# Учебные хуки отказов worker по маркеру в имени файла (fault-crash-after-s3 и т. п.): «lab» — включены +# на учебном стенде для тестов отказов; в боевой конфигурации — пусто. +FAULT_HOOKS=lab +# --- lab6: наблюдаемость (см. REPORT.md, «Соответствие переменных»). service.name задаётся в compose +# отдельно для API (messenger-api) и worker (messenger-worker); OTEL_SERVICE_NAME выше — значение API. +# Telemetry выключается целиком (эксперимент «off», трек 1): +OTEL_SDK_DISABLED=false +# Head sampling в SDK: доля новых trace (1.0 — все; дочерние spans наследуют решение родителя). +OTEL_TRACES_SAMPLER=parentbased_traceidratio +OTEL_TRACES_SAMPLER_ARG=1.0 +# Период экспорта метрик SDK, мс (= разрешение графиков; алерты рассчитаны на 10 с). +OTEL_METRIC_EXPORT_INTERVAL=10000 +# Предел очередей SDK (spans/logs) при недоступном Collector: лишнее отбрасывается и считается. +OTEL_BSP_MAX_QUEUE_SIZE=2048 +OTEL_BLRP_MAX_QUEUE_SIZE=2048 +# Конфигурация Collector: collector.yaml (хранить все trace) или collector-tail.yaml (tail sampling, трек 1). +OTEL_COLLECTOR_CONFIG=collector.yaml +COLLECTOR_CPUS=0.5 +# Grafana — единственный UI наблюдаемости, только 127.0.0.1. Логин admin, пароль — secrets/grafana_admin_password. +GRAFANA_PORT=3000 diff --git a/.github/workflows/app.yml b/.github/workflows/app.yml new file mode 100644 index 00000000..21e575eb --- /dev/null +++ b/.github/workflows/app.yml @@ -0,0 +1,47 @@ +name: Application stack +# Отдельный job решения: сборка образа (API и worker), Compose-стенд (LB + 2 API + 2 worker + migrate + +# s3-init + broker-init + PostgreSQL + Redis + SeaweedFS S3 + NATS JetStream + OTel Collector + Prometheus + +# Loki + Tempo + Grafana), публичные smoke/persistence/failover при включённой telemetry, проверки +# наблюдаемости (provisioning, корреляция, секреты), инциденты с алертами firing→resolved, регрессия lab2–5. +# Секреты синтетические, генерируются на лету. +on: [push, pull_request] +permissions: + contents: read +jobs: + stack: + runs-on: ubuntu-24.04 + timeout-minutes: 90 + steps: + - uses: actions/checkout@v4 + - name: Secrets and env (synthetic; FAULT_HOOKS=lab for the failure tests) + run: ./scripts/init-secrets.sh + - name: Compose config + run: docker compose --env-file .env config --quiet + - name: Build and start + run: docker compose --env-file .env --profile ttl up -d --build --wait + - name: Public smoke via LB (202 → ready, original + JPEG thumbnail 256×160) + run: make test BASE_URL=http://127.0.0.1:8080 + - name: Observability (provisioning, signals, request→log→trace, upload→worker, retry, no secrets) + run: make test-observability + - name: Telemetry history survives restart of all stores + run: make test-telemetry-persistence + - name: Incidents (worker stop, slow DB vs slow handler, DB down, telemetry backend/collector down) + run: make incidents + - name: Defense scenario (worker down → 202 → 409 → restart API+broker → worker → ready) + run: python3 student-tests/defense_demo.py + - name: Failover (stop one API replica), then restore + run: | + make test-failover ACTION_SCRIPT=scripts/stop-one.sh BASE_URL=http://127.0.0.1:8080 + ./scripts/start-replicas.sh + - name: Persistence (restart LB, API, worker, all stores incl. telemetry; volumes kept) + run: make test-persistence ACTION_SCRIPT=scripts/restart.sh BASE_URL=http://127.0.0.1:8080 + - name: Student tests (pipeline, variants, crash windows, outbox, retry/DLQ/replay, lab2–4 regression) + run: make test-student + - name: Track 1 (cost of observability), short run + run: python3 research/telemetry_cost.py --reps 1 --window 30 --out evidence/track1-ci + - name: Logs on failure + if: failure() + run: docker compose --env-file .env --profile ttl --profile fault logs --no-color --tail=200 + - name: Stop + if: always() + run: docker compose --env-file .env --profile ttl --profile fault down -v diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..4a643ca6 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,34 @@ +# API и worker мессенджера lab6 (один образ, разные команды; OpenTelemetry SDK в requirements.txt). Python 3.13, зависимости — в venv отдельной стадии. +ARG PYTHON_IMAGE=python:3.13.5-slim-bookworm + +FROM ${PYTHON_IMAGE} AS deps +ENV PIP_NO_CACHE_DIR=1 PIP_DISABLE_PIP_VERSION_CHECK=1 +WORKDIR /build +COPY requirements.txt ./ +RUN python -m venv /opt/venv \ + && /opt/venv/bin/pip install --require-virtualenv --no-compile -r requirements.txt + +FROM ${PYTHON_IMAGE} +ARG APP_VERSION=dev +LABEL org.opencontainers.image.version=$APP_VERSION +ENV PATH=/opt/venv/bin:$PATH \ + PYTHONPATH=/app/src \ + PYTHONUNBUFFERED=1 \ + PYTHONDONTWRITEBYTECODE=1 \ + APP_VERSION=$APP_VERSION \ + APP_HOST=0.0.0.0 \ + APP_PORT=8080 +RUN groupadd --system --gid 10001 app \ + && useradd --system --uid 10001 --gid app --home-dir /app --shell /usr/sbin/nologin app +COPY --from=deps /opt/venv /opt/venv +WORKDIR /app +COPY migrations ./migrations +COPY src ./src +USER 10001:10001 +EXPOSE 8080 +STOPSIGNAL SIGTERM +HEALTHCHECK --interval=5s --timeout=3s --start-period=30s --retries=6 \ + CMD ["python", "-m", "messenger", "healthcheck"] +# PID 1 — сам HTTP-процесс (exec-форма), SIGTERM даёт graceful shutdown uvicorn. +ENTRYPOINT ["python", "-m", "messenger"] +CMD ["serve"] diff --git a/Makefile b/Makefile index 5d86d171..19b04cd2 100644 --- a/Makefile +++ b/Makefile @@ -28,3 +28,138 @@ 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) + +# --------------------------------------------------------------------------------------------- +# Цели решения (lab6, включая цели lab2–lab5). Публичные цели выше не изменены. +# --------------------------------------------------------------------------------------------- +COMPOSE ?= docker compose --env-file .env +IN_WORKER = $(COMPOSE) run --rm --no-deps -T -v "$(CURDIR)/student-tests:/app/student-tests:ro" --entrypoint python worker +IN_API = $(COMPOSE) run --rm --no-deps -T -v "$(CURDIR)/student-tests:/app/student-tests:ro" --entrypoint python api + +.PHONY: secrets up down ps logs destroy-data restore stop-worker start-worker restart-api-broker s3-check \ + jobs-failed jobs-invariants test-student test-pipeline test-imgproc test-jobs-failures test-track2 \ + chaos test-attachments test-storage-failures test-api test-idempotency test-expiry test-cache-race \ + test-failures upload-memory evidence test-observability test-telemetry-persistence incidents \ + incident-worker-stop incident-db-slow incident-handler-slow incident-db-down incident-telemetry-down \ + incident-collector-down telemetry-cost grafana + +secrets: + ./scripts/init-secrets.sh + +# Единая команда запуска: LB + 2 API + 2 worker + migrate/s3-init/broker-init (one-shot) + PostgreSQL + Redis + S3 + NATS +# + OTel Collector + Prometheus + Loki + Tempo + Grafana (provisioning из infra/grafana). +up: secrets + $(COMPOSE) --profile ttl up -d --build --wait + +ps: + $(COMPOSE) --profile ttl --profile fault ps -a + +logs: + $(COMPOSE) logs --tail=100 lb api worker nats otel-collector + +# Безопасная остановка: контейнеры удаляются, volumes (данные и история telemetry) сохраняются. +down: + $(COMPOSE) --profile ttl --profile fault down + +# НАМЕРЕННОЕ удаление учебных данных (pgdata, s3data, natsdata и история promdata/lokidata/tempodata/grafanadata). +destroy-data: + @echo "This deletes ALL lab6 volumes (PostgreSQL, S3, NATS, Prometheus, Loki, Tempo, Grafana). Type 'yes' to continue:"; read ans; [ "$$ans" = yes ] + $(COMPOSE) --profile ttl --profile fault down -v + +# Вернуть реплики API после make test-failover ACTION_SCRIPT=scripts/stop-one.sh +restore: + ./scripts/start-replicas.sh + +# Сценарий защиты: остановить/запустить worker; перезапустить API и брокер (volumes сохраняются). +stop-worker: + ./scripts/stop-worker.sh + +start-worker: + ./scripts/start-worker.sh + +restart-api-broker: + ./scripts/restart-api-broker.sh + +s3-check: + $(COMPOSE) exec -T api python -m messenger s3-check + +# Реестр failed (DLQ) и проверка инвариантов pipeline. +jobs-failed: + $(COMPOSE) exec -T api python -m messenger jobs failed + +jobs-invariants: + $(COMPOSE) exec -T api python -m messenger jobs invariants --settled --verify-bytes + +test-pipeline: + $(PYTHON) student-tests/test_pipeline.py + +# Правила вариантов и лимиты worker — внутри образа (нужен Pillow). +test-imgproc: + $(IN_WORKER) student-tests/test_imgproc.py + +# Останавливает/запускает worker, брокер и реплики API, профиль fault. Volumes не трогает. ≈ 6 мин. +test-jobs-failures: + $(PYTHON) student-tests/test_jobs_failures.py + +# Трек 2: автоматическая инъекция отказов (дубли, reorder, crash, версии) + инварианты. ≈ 3 мин. +test-track2: + $(PYTHON) student-tests/test_pipeline_idempotency.py + +# Трек 2: рандомизированный хаос-прогон (три seed). +chaos: + mkdir -p evidence/track2 + for s in 1 2 3; do $(PYTHON) research/track2_chaos.py --seed $$s --uploads 60 --output evidence/track2/chaos-seed$$s.json || exit 1; done + +test-attachments: + $(PYTHON) student-tests/test_attachments.py + +test-storage-failures: + $(PYTHON) student-tests/test_storage_failures.py + +test-api: + $(PYTHON) student-tests/test_api.py + +test-idempotency: + $(PYTHON) student-tests/test_idempotency.py + +test-expiry: + $(PYTHON) student-tests/test_expiry.py + +test-cache-race: + $(IN_API) student-tests/test_cache_race.py + +test-failures: + $(PYTHON) student-tests/test_failures.py + +test-student: test-pipeline test-imgproc test-attachments test-api test-idempotency test-expiry test-cache-race \ + test-jobs-failures test-storage-failures test-failures test-track2 + +upload-memory: + $(PYTHON) research/upload_memory.py --output evidence/upload-memory.json + +evidence: + ./scripts/collect-evidence.sh + +# ----------------------------------------------------------------------------------------- lab6: наблюдаемость +grafana: + @echo "Grafana: http://127.0.0.1:3000 (admin / пароль в secrets/grafana_admin_password)" + +# Уровни 3–4: provisioning, сигналы, корреляция запрос→лог→trace, upload→worker, retry, отсутствие секретов. +test-observability: + $(PYTHON) student-tests/test_observability.py + +# История telemetry переживает перезапуск всех хранилищ (scripts/restart.sh). +test-telemetry-persistence: + $(PYTHON) student-tests/test_telemetry_persistence.py + +# Контролируемые инциденты под нагрузкой: firing → resolved (≈ 20 мин все). Вывод — evidence/incidents. +incidents: + $(PYTHON) research/incidents.py all --out evidence/incidents + +incident-worker-stop incident-db-slow incident-handler-slow incident-db-down incident-telemetry-down incident-collector-down: + $(PYTHON) research/incidents.py $(@:incident-%=%) --out evidence/incidents + +# Трек 1: цена наблюдаемости (off / full / head10 / tail), 3 повтора × 4 конфигурации ≈ 35 мин. +telemetry-cost: + $(PYTHON) research/telemetry_cost.py --reps 3 --rate 60 --window 60 --out evidence/track1 + diff --git a/REPORT.md b/REPORT.md index b97ae42d..d81749f8 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,284 @@ # Отчёт — лабораторная 6 -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO +- Автор, группа: **Лебедев Дмитрий Алексеевич, БВТ2302** +- Целевая оценка; выбранный трек 5: **5, трек 1 «Цена наблюдаемости»** - Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- Использованные источники, библиотеки и помощь ИИ: + - библиотеки приложения: Starlette 1.7.0, uvicorn 0.54.0, psycopg 3.2.10 + psycopg_pool 3.2.6, redis-py 5.2.1, httpx 0.28.1, nats-py 2.11.0, Pillow 12.3.0; **OpenTelemetry Python 1.45.0** (api, sdk, OTLP/HTTP exporter; semantic conventions 0.66b0), protobuf 7.36.1. Автоинструментация (contrib) не используется: spans и метрики написаны вручную — так видно и контролируется каждый атрибут (нет риска утечки заголовков/тела); + - компоненты наблюдаемости: **OTel Collector contrib 0.130.0, Prometheus 3.5.0 (LTS), Loki 3.5.3, Tempo 2.8.2, Grafana 13.3.1**; инфраструктура lab5: HAProxy 3.0, PostgreSQL 16, Redis 7, SeaweedFS 4.52, NATS 2.11.9; + - документация: OTel Collector configuration (memory_limiter, batch, exporterhelper sending_queue/retry_on_failure, tail_sampling), OTel context propagation и W3C Trace Context, OTel semantic conventions (HTTP, DB, messaging, OTel SDK self-metrics), Prometheus (histograms and summaries, OTLP receiver, recording/alerting rules), Loki OTLP ingestion и structured metadata, Tempo (TraceQL, metrics-generator), Grafana provisioning; Google SRE Workbook (SLO, alerting on SLOs); + - **ИИ:** реализация, тесты, эксперименты и этот отчёт подготовлены с помощью ИИ-ассистента Claude (Anthropic). Код других студентов не использовался. ## Запуск из чистого clone -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +**Вариант: Docker Compose.** Prerequisites: Docker Engine 24+ с Compose v2 (Docker Desktop на Windows), Python 3.9+ на хосте (все тесты — stdlib), `make` (Linux/macOS; для Windows — PowerShell-команды ниже), ≈ 4 ГБ свободной RAM для стенда. Порты на хосте — только `127.0.0.1`: `8080` (API через LB), `8081` (api-ttl), `8082` (api-fault), `8404` (статистика HAProxy), **`3000` (Grafana)**. OTLP, Prometheus, Loki, Tempo, S3 и брокер на хост **не публикуются**. + +**Образы (закреплены тегами):** `haproxy:3.0.5-alpine`, `python:3.13.5-slim-bookworm` (база API и worker, собираются из исходников), `postgres:16.10-alpine`, `redis:7.4.2-alpine`, `chrislusf/seaweedfs:4.52`, `nats:2.11.9-alpine`, **`otel/opentelemetry-collector-contrib:0.130.0`, `prom/prometheus:v3.5.0`, `grafana/loki:3.5.3`, `grafana/tempo:2.8.2`, `grafana/grafana:13.3.1`**. + +```sh +./scripts/init-secrets.sh # secrets/* (БД, Redis, S3, NATS, пароль admin Grafana) и .env +docker compose --env-file .env config --quiet +docker compose --env-file .env --profile ttl up -d --build --wait # = make up +# порядок: postgres, redis, s3, nats (healthy) → migrate + s3-init + broker-init (one-shot) → api ×2, worker ×2 → lb; +# otel-collector, prometheus, loki, tempo-init → tempo, grafana — параллельно (API от них НЕ зависит) +# Grafana: http://127.0.0.1:3000, логин admin, пароль — secrets/grafana_admin_password; +# dashboard «Messenger → Messenger — обзор (lab6)» и datasources импортируются сами (provisioning). + +make test BASE_URL=http://127.0.0.1:8080 # публичный smoke при включённой telemetry +make test-observability # уровни 3–4: provisioning, сигналы, запрос→лог→trace, upload→worker, retry, секреты +make test-telemetry-persistence # история метрик/логов/трасс переживает рестарт всех хранилищ +make incidents # 6 инцидентов под нагрузкой: firing → resolved (≈ 20 мин); по одному: make incident-worker-stop … +make telemetry-cost # трек 1: off / full / head10 / tail × 3 повтора (≈ 35 мин) +python3 tests/load.py --base-url http://127.0.0.1:8080 --duration 30 --concurrency 4 --output evidence/load.json +make test-failover ACTION_SCRIPT=scripts/stop-one.sh BASE_URL=http://127.0.0.1:8080 && ./scripts/start-replicas.sh +make test-persistence ACTION_SCRIPT=scripts/restart.sh BASE_URL=http://127.0.0.1:8080 +make test-student # регрессия lab2–lab5 +./scripts/collect-evidence.sh # всё сразу, вывод в evidence/ (≈ 90 мин; SKIP_REGRESSION=1 / SKIP_RESEARCH=1 короче) + +make down # безопасно: контейнеры удаляются, ВСЕ volumes (данные и история telemetry) сохраняются +make destroy-data # НАМЕРЕННОЕ удаление данных и истории telemetry (down -v), с подтверждением +``` + +**Windows (PowerShell 5.1, без make/WSL).** Docker Desktop запущен, Python с python.org. Адрес — `127.0.0.1` (не `localhost`), команды — по одной строке: + +```powershell +powershell -NoProfile -ExecutionPolicy Bypass -File scripts\init-secrets.ps1 +docker compose --env-file .env --profile ttl up -d --build --wait +$env:NO_PROXY = '127.0.0.1,localhost' +py -3 tests\smoke.py --base-url http://127.0.0.1:8080 +py -3 student-tests\test_observability.py +py -3 student-tests\test_telemetry_persistence.py +py -3 research\incidents.py worker-stop # и db-slow, handler-slow, db-down, telemetry-down, collector-down +py -3 research\telemetry_cost.py --reps 3 --rate 60 --window 60 --out evidence\track1 +Get-Content secrets\grafana_admin_password # пароль admin для http://127.0.0.1:3000 +powershell -NoProfile -ExecutionPolicy Bypass -File scripts\collect-evidence.ps1 # всё сразу +``` + +**Действия оператора:** только создание secrets. Миграции (в т. ч. новая `0006_observability`) применяет one-shot `migrate`; bucket — `s3-init`; stream и consumer — `broker-init`; datasources и dashboards Grafana — provisioning при старте; права на volume Tempo — one-shot `tempo-init`. Повторы безопасны. `FAULT_HOOKS=lab` в `.env` включает учебные отказы (нужны инцидентам и треку 1); в боевой конфигурации переменная пуста. + +> **Где собраны доказательства.** В среде разработки Docker daemon работал, но Docker Hub и PyPI были закрыты политикой сети. Поэтому `evidence/` получены на **том же `compose.yaml`** с локальными образами-заменителями: **OTel Collector contrib 0.130.0, Prometheus 3.5.0, Loki 3.5.3, Tempo 2.8.2, NATS 2.11.9, SeaweedFS 4.52 — официальные бинарники релизов с GitHub, Grafana 13.3.1 — официальный пакет (.deb) с GitHub-релиза**, PostgreSQL 16/Redis 7 — пакеты хоста, HAProxy 3.0.0 — из исходников, Python 3.13 с теми же версиями библиотек (OpenTelemetry 1.45.0 — из исходников тега `v1.45.0`). Подмена — только `image`/сборка в override-файле вне репозитория; топология, сети, лимиты, конфиги Collector/Prometheus/Loki/Tempo/Grafana, правила алертов и тесты — те же. Хост сборки — cgroup v1 (Docker Desktop — cgroup v2): код CPU/RAM контейнера поддерживает обе версии. Перед защитой выполните `make up && ./scripts/collect-evidence.sh` (Windows: `scripts\collect-evidence.ps1`), чтобы `evidence/` содержал вывод официальных образов; тот же сценарий гоняет `.github/workflows/app.yml`. ## Архитектура и решения -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab5, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +``` + 127.0.0.1:8080/8081/8082/8404 127.0.0.1:3000 + клиент ─HTTP─► lb: HAProxy ─(app)─► api ×2 ──(data/objects/broker)──► PostgreSQL, Redis, S3, NATS ◄── worker ×2 + │ OTLP/HTTP :4318 (сеть telemetry) │ + └──────────────────────► otel-collector ◄────────────────────┘ + memory_limiter → scrub → [tail_sampling] → batch + ┌──────────────── (сеть observability) ───────────────┐ + ▼ metrics (OTLP) ▼ logs (OTLP) ▼ traces (OTLP) + prometheus [promdata] loki [lokidata] tempo [tempodata] + правила SLI + алертов structured metadata metrics-generator ─┐ + ▲ scrape :8888/3100/3200 (сам Collector, Loki, Tempo) │ remote write + └──────────────────────────────────────────────────────────┘ + ▲ ▲ ▲ + └────────── grafana [grafanadata] ┘ ← provisioning из infra/grafana + Trace задания: POST /attachments (SERVER) → create (PRODUCER, в транзакции upload; контекст → payload outbox) + → send (PRODUCER, relay; контекст → заголовки NATS) → process (CONSUMER, worker) → S3/DB spans; + повтор: process#1 → job.finish_error → новая строка outbox → send → process#2 (тот же trace). +``` + +| Роль | Service | Образ | Health/readiness | Volume | Сеть / порт | Credentials | +| --- | --- | --- | --- | --- | --- | --- | +| api (≥2), worker (×2), lb, postgres, redis, s3, broker, one-shot bootstrap | как в lab5 | | API ready = PostgreSQL (telemetry/Grafana в readiness **не входят**) | `pgdata`, `s3data`, `natsdata` | + сеть `telemetry` у api/worker | как в lab5 | +| otel_collector | `otel-collector` | `otel/opentelemetry-collector-contrib:0.130.0` | `health_check` :13133 (внутри); состояние — scrape `up{job="otel-collector"}` и алерт `OtelCollectorDown` (образ без shell — без Docker healthcheck) | — (очереди в памяти, ограничены) | telemetry + observability; :4318 только внутри | — | +| metrics store | `prometheus` | `prom/prometheus:v3.5.0` | `/-/ready` | `promdata` (7 дней / 1 ГБ) | observability | — | +| logs store | `loki` | `grafana/loki:3.5.3` | datasource health в Grafana | `lokidata` (7 дней) | observability | — (auth_enabled: false во внутренней сети) | +| traces store | `tempo` (+ one-shot `tempo-init`: chown volume) | `grafana/tempo:2.8.2` | datasource health в Grafana | `tempodata` (7 дней) | observability | — | +| grafana | `grafana` | `grafana/grafana:13.3.1` | `/api/health` | `grafanadata` (БД настроек; dashboards — из Git) | observability + ui; `127.0.0.1:3000` | `grafana_admin_password` (secret, `GF_SECURITY_ADMIN_PASSWORD__FILE`); анонимный доступ и регистрация выключены | + +### Зачем каждое хранилище + +- **Prometheus — метрики** (числовые ряды): *сколько* и *как быстро* — RPS, доля ошибок, перцентили из histogram, глубина и возраст очереди, насыщение пулов/worker, CPU/RAM; на них же правила SLI и алерты (локальное состояние firing/resolved). Дёшево хранить долго, нельзя хранить высокую кардинальность. +- **Loki — логи** (события с контекстом): *почему* — текст ошибки, тип исключения, параметры попытки задания. Индексирует только ресурсные labels (`service_name`, `service_instance_id`, `deployment_environment_name`, `service_namespace`), а `event`, `request_id`, `job_id`, `trace_id`, `span_id` хранит как structured metadata — по ним можно фильтровать, не раздувая индекс. +- **Tempo — трассы**: *где* внутри конкретного запроса/задания тратится время или возникает ошибка, причинная связь API → брокер → worker. Поиск TraceQL (`{ span.messenger.attachment.id = "…" }`). +- **OTel Collector** — не хранилище: приём OTLP, защита памяти, вычистка запрещённых атрибутов, (в треке 1 — tail sampling), батчинг и **ограниченная** очередь к каждому backend. Одна точка смены backend без изменения кода. +- **Grafana** — только интерфейс и запросы (dashboards, Explore, переходы лог ⇄ trace ⇄ метрики); данные не хранит. Её недоступность не влияет ни на API, ни на сбор telemetry. + +### Схема сигналов (contracts/observability.md → фактические имена) + +Имена Prometheus получаются из OTel-имени переводом `UnderscoreEscapingWithSuffixes` (точки → `_`, единица `s` → `_seconds`, `By` → `_bytes`, counter → `_total`). Ресурсные атрибуты становятся labels каждой серии: `service_name` (messenger-api / messenger-worker), `service_instance_id` (= `X-Instance-Id` реплики / id worker), `service_namespace=messenger`, `deployment_environment_name=lab`; `service.version` — в `target_info` и ресурсе логов/трасс. + +| Сигнал контракта | Инструмент OTel → имя в Prometheus | Тип, единица | Измерения (labels) | Источник | +| --- | --- | --- | --- | --- | +| HTTP requests (counter) | `http.server.request.duration` → `http_server_request_duration_seconds_count` (count histogram — это и есть счётчик; второй инструмент не заводится) | counter | `http_request_method`, `http_route` (**шаблон**, `unmatched` для 404 роутера), `http_response_status_code`, `http_response_status_class` (2xx…5xx) | API middleware | +| HTTP duration | `http.server.request.duration` → `…_bucket/_sum/_count` | histogram, **секунды**; buckets 5 мс…10 с (semconv) | те же | API | +| Saturation API | `http.server.active_requests` | up-down counter, запросы | `http_request_method` | API | +| Jobs processed / failed | `messenger.jobs.processed` → `messenger_jobs_processed_total` | counter | `job_type=attachment.process.v1`, `outcome` (ready, retry, failed, superseded, duplicate, stale, nak, rejected, lease_lost, claim_error, invalid), `messenger_pipeline_version` | worker | +| Job processing duration | `messenger.job.duration` → `messenger_job_duration_seconds_*` | histogram, с; 50 мс…120 с | `job_type`, `outcome` | worker | +| Queue depth / oldest job age | `messenger.queue.depth`, `messenger.queue.lag`, `messenger.queue.oldest_age` → `messenger_queue_depth`, `messenger_queue_lag_seconds`, `messenger_queue_oldest_age_seconds` | gauge: задания / с | `queue=attachments.process.v1`, у depth — `state` (ready, retry_wait, processing, failed) | **API** (раз в 5 с из PostgreSQL — работает и при остановленных worker); реплики сообщают одно значение → `max()` | +| Broker / outbox backlog | `messenger.broker.pending`, `messenger.broker.ack_pending`, `messenger.outbox.pending`, `messenger.outbox.lag`, `messenger.outbox.publish` | gauge / counter | `queue`; у publish — `outcome` | API (consumer info JetStream, outbox) | +| Ожидание в очереди (≠ backlog) | `messenger.job.queue_wait` | histogram, с | `job_type` | worker (от доступности попытки до захвата) | +| End-to-end time to ready | `messenger.attachment.time_to_ready` → `messenger_attachment_time_to_ready_seconds_*` | histogram, с; 0.25 с…10 мин | `job_type` | worker: от `attachments.created_at` (COMMIT upload, после которого 202) до COMMIT ready (только первая публикация) | +| DB pool used/waiting | `db.client.connection.count` (`state`=used/idle), `.max`, `.pending_requests`, `.timeouts`; `messenger.db.pool.wait_time` | up-down counter / counter | `db_client_connection_pool_name` (api/worker) | psycopg_pool.get_stats() | +| DB latency (отличить БД от обработчика) | `db.client.operation.duration` → `db_client_operation_duration_seconds_*` | histogram, с; 0.5 мс…5 с | `db_system_name=postgresql`, `db_operation_name` (SELECT/INSERT/…/CHECK), `error_type` | курсор psycopg (все запросы) | +| Worker busy/capacity | `messenger.worker.busy`, `messenger.worker.capacity` | up-down counter / gauge, слоты | — | worker | +| Process/container CPU/RAM | `process.cpu.time` (`cpu_mode`), `process.memory.usage` (RSS), `container.cpu.time`, `container.memory.usage` (cgroup usage − inactive_file), `messenger.container.memory.limit`, `messenger.container.cpu.limit` | counter с / gauge байты | — | /proc и cgroup v2/v1 внутри контейнера | +| Потери telemetry | `otel.sdk.processor.span.processed`, `otel.sdk.exporter.span.exported`, `…log…` (self-метрики SDK), `otelcol_*` Collector | counter | `error_type` (`queue_full`, `MaxRetryError`) | SDK, Collector | +| Logs | OTLP logs: `timestamp`, `severity_text/number`, ресурс `service.name`, атрибуты `event`, `logger`, поля события; `trace_id`/`span_id` активного span | — | — | Loki; тот же JSON — в stdout | +| Traces | server spans `POST /api/v1/chats/{chat_id}/messages` …; client spans PostgreSQL (`INSERT messages`, `pool.check`, `pool.acquire`), Redis (`GET`), S3 (`S3.PutObject`), KDF (`password.verify`); producer `create`/`send`, consumer `process`; `job.execute`, `imgproc.run`, `job.commit` | — | статус ERROR + `error.type` у 5xx и неудачных попыток | Tempo | + +**Не labels метрик:** user_id, chat_id, message_id, attachment_id, request_id, URL, filename, текст — проверяется тестом по всем сериям (`test_observability.py`: «метрики контракта»). Технические UUID учебных данных есть **только** в spans/логах: `messenger.request_id` (связь ответа с trace), `messenger.attachment.id`/`messenger.job.id` (поиск trace загрузки) — без них не найти конкретную загрузку; паролей, токенов, Authorization, текста сообщений, байтов, ключей S3 нет (проверено тестом). + +**Error ratio:** числитель — ответы **5xx** бизнес-запросов, знаменатель — все бизнес-запросы; `/health/*` и `/internal/*` исключены. 4xx (неверный пароль, чужой чат, валидация) — ошибки клиента, в бюджет не входят. **Перцентили** считаются `histogram_quantile` из buckets, **сложенных по всем репликам** (`sum by (le)`), — не среднее p95 реплик (усреднять перцентили нельзя: среднее двух p95 не является p95 объединённого потока). + +### Трассировка и перенос контекста через очередь + +- Публичный вход **не принимает** внешний `traceparent`: каждый запрос — новый trace (клиент не навязывает нам trace/sampling). Связь «ответ → лог → trace» — по `X-Request-Id` (поле `request_id` лога, атрибут `messenger.request_id` server span); тесты используют именно этот путь. +- **Producer:** в транзакции upload `create_job` открывает span `create attachments.process.v1` (PRODUCER, `messaging.operation.type=create`) и кладёт его W3C-контекст в **payload** строки outbox (`traceparent`/`tracestate` — поля `jobs.schema.json`) и в `attachment_jobs.trace_context` (миграция 0006). Контекст надёжен, как и сама работа: переживает падение API, рестарт брокера и повторы. +- **Relay** (любой процесс, позже): span `send attachments.process.v1` (PRODUCER) — **дочерний** к контексту из payload; его контекст уходит в **native headers NATS** (`traceparent`/`tracestate`) вместе с `Nats-Msg-Id`. +- **Consumer:** worker берёт родителя из заголовков NATS (нет — из payload) и создаёт `process attachments.process.v1` (CONSUMER) с атрибутами `messaging.*`, `messenger.job.*`, числом доставок; **link** на контекст payload. Выбрана связь parent-child (а не только link): одна загрузка = один trace от HTTP до S3/DB результата, включая повторы. +- **Retry:** `finish_error` → новая строка outbox с контекстом текущего span (`job.finish_error`, потомок неудачной попытки) → следующий `send` → `process` попытки 2. Restore истёкшего lease (maintenance) — span `job.requeue_expired_lease` с родителем из `attachment_jobs.trace_context`. Дубли/устаревшие сообщения видны в том же trace (outcome duplicate/stale). +- Spans БД/S3/Redis создаются **только внутри существующего trace**: фоновые циклы (relay каждую секунду, maintenance, health checks LB) не порождают тысячи одиночных trace; их стоимость видна в метриках (`db.client.operation.duration`). + +### Логи + +Один `logging`-конвейер: JSON в stdout (для `docker logs`, когда Loki недоступен) и OTLP-handler → Collector → Loki. Поля: `ts`, `level`/`severity_text`, `service`, `event` (стабильное имя: `http.request`, `dependency.unavailable`, `http.unhandled_error`, `attachment.accepted`, `job.claimed`, `job.finished`, `job.attempt_failed`, `job.lease_lost` …), `trace_id`/`span_id` активного span, поля события (`request_id`, `route`, `status`, `duration_ms`, `job_id`, `attempt`, `outcome`, `error`, `error_code`). Access-log пишет **шаблон маршрута**, а не URL. Успешные `/health/*` не логируются (проверки LB каждую секунду). Защита от утечек — три слоя: в коде поля с именами `password|token|authorization|cookie|secret|text|body` отбрасываются при форматировании (`telemetry.SCRUB`), атрибуты задаются вручную (нет автоинструментации заголовков), Collector `attributes/scrub` удаляет такие ключи и `http.request.header.authorization|cookie`. + +### SLI / SLO и алерты + +Окна сжаты под учебный стенд (минуты вместо 28–30 дней): цель — проверяемо увидеть firing → resolved за время защиты. Правила — `infra/prometheus/rules/messenger.yml` (recording `sli:*` и alerting), runbook для каждого — [`docs/runbooks.md`](docs/runbooks.md); состояние видно в Grafana (Alerting → Data source-managed; панель «Алерты» dashboard) и в `ALERTS` Prometheus. + +| SLI | Определение | SLO (окно) | +| --- | --- | --- | +| Доступность API | доля не-5xx бизнес-запросов | 99.5% за 1 ч | +| Задержка API | доля бизнес-запросов ≤ 250 мс (bucket `le="0.25"`); без upload (передача файла клиентом) и регистрации/входа (scrypt намеренно ~0.1–0.3 с) | 95% за 1 ч (на dashboard — 5 мин) | +| Time to ready | доля вложений, ставших ready ≤ 10 с после 202 | 95% за 15 мин | + +| Алерт | Условие и окно | Порог / for | Что проверено | +| --- | --- | --- | --- | +| ApiHighErrorRate | доля 5xx за 1 мин при трафике > 0.2 запроса/с | > 5% / 30 с | db-down | +| ApiLatencyHigh | p95 (histogram, все реплики) за 1 мин | > 250 мс (= SLO) / 1 мин | db-slow, handler-slow | +| DbSlowQueries | p95 `db.client.operation.duration` за 1 мин | > 50 мс / 30 с | db-slow (и НЕ срабатывает в handler-slow) | +| DbPoolSaturated | ждущие соединения пула (последние 30 с) | > 0 / 30 с | db-down | +| JobQueueLagGrowing | queue lag (самое старое доступное задание ждёт worker) | > 30 с / 20 с | worker-stop | +| WorkerHeartbeatMissing | нет свежих метрик ни одного worker | > 45 с / 15 с | worker-stop | +| JobsFailing | failed-задания за 5 мин | > 0 | регрессия (invalid_image) | +| TelemetryExportFailing | send/enqueue failed Collector или очередь экспортёра > 20 батчей | / 30 с | telemetry-down | +| OtelCollectorDown | `up{job="otel-collector"} == 0` | / 20 с | collector-down | +| TelemetryLostInSdk | потери spans/logs в SDK за 5 мин (видно после восстановления канала) | > 0 | collector-down | + +Почему queue **lag**, а не глубина: глубина растёт и при нормальной пиковой нагрузке; lag (сколько ждёт самое старое задание, уже доступное worker — без ожидания backoff) растёт только когда разбор не успевает. Backlog и время обработки — разные метрики (`messenger_queue_depth` / `messenger_job_queue_wait_seconds` / `messenger_job_duration_seconds`). + +### Collector: память, батчи, недоступный backend + +`memory_limiter` (первым в каждой pipeline: limit 200 MiB, spike 50 MiB при лимите контейнера 256 MiB + `GOMEMLIMIT=180MiB`) → `attributes/scrub` → `batch` (1024/2048, 2 с) → `otlphttp` с `sending_queue` (**200 батчей**, 2 потребителя) и `retry_on_failure` (1 → 10 с, не дольше **120 с**). Backend недоступен: батчи ждут в ограниченной очереди и повторяются; переполнение — `enqueue_failed`, истечение 120 с — `send_failed` (счётчики, алерт). Память ограничена очередью и memory_limiter. Collector недоступен: SDK держит не больше `OTEL_BSP_MAX_QUEUE_SIZE=2048` spans и `OTEL_BLRP_MAX_QUEUE_SIZE=2048` записей на процесс, экспорт — в фоновом потоке с таймаутом 5 с; неудачный пакет отбрасывается и считается (`otel_sdk_exporter_*_exported_total{error_type}`), RAM API не растёт, запросы не ждут telemetry. Метрики при простое теряют только точки (кумулятивные счётчики при восстановлении дают верный `increase`). + +### Что перенесено из lab5 и что изменено + +Весь минимум lab5 (LB + 2 API + 2 worker, PostgreSQL, Redis-кэш, S3 SeaweedFS, NATS JetStream, outbox, retry/DLQ, варианты) — без изменений поведения; публичный smoke и регрессия lab2–lab5 проходят **при включённой telemetry**. Изменено/добавлено: + +- `src/messenger/telemetry.py` — инициализация SDK (resource, OTLP/HTTP, self-метрики), инструменты, курсор psycopg с client spans и histogram, метрики пулов и CPU/RAM (cgroup v2/v1), OTLP-handler логов, утилиты контекста; `OTEL_SDK_DISABLED=true` выключает всё (stdout-лог остаётся); +- API: server spans/RED в ASGI middleware (шаблон маршрута), `error.type` у 5xx, метрики очереди/outbox/брокера; worker: consumer span, jobs/duration/queue_wait/time_to_ready, busy/capacity; spans S3, Redis, KDF, `pool.acquire`; +- `jobs.py`: producer spans `create`/`send`, контекст в payload и заголовках NATS; миграция **0006_observability** (expand-only: `attachment_jobs.trace_context`, индекс незавершённых работ по `created_at`); +- учебные отказы обработчика `fault-api-error` / `fault-api-slow-<мс>` (только `FAULT_HOOKS=lab`, см. `contracts/EXTENSIONS.md`); +- инфраструктура: `infra/otel/collector.yaml` (+ `collector-tail.yaml` трека 1), `infra/prometheus/{prometheus.yml,rules/messenger.yml}`, `infra/loki/loki.yaml`, `infra/tempo/tempo.yaml`, `infra/grafana/provisioning/*`, `infra/grafana/dashboards/messenger-overview.json`, `docs/runbooks.md`; restart-hook перезапускает и хранилища telemetry. + +### Соответствие переменных `.env.example` + +`OTEL_SERVICE_NAME=messenger-api` — значение API; worker в compose получает `messenger-worker` (отдельный `service.name`). `OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318`, `OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf`, `OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=lab` — как названы. Дополнительно: `OTEL_SDK_DISABLED`, `OTEL_TRACES_SAMPLER=parentbased_traceidratio` + `OTEL_TRACES_SAMPLER_ARG` (head sampling), `OTEL_METRIC_EXPORT_INTERVAL=10000`, `OTEL_BSP_MAX_QUEUE_SIZE`/`OTEL_BLRP_MAX_QUEUE_SIZE=2048`, `OTEL_EXPORTER_OTLP_TIMEOUT=5` (**секунды** — так читает Python SDK, хотя спецификация говорит о мс), `OTEL_PYTHON_SDK_INTERNAL_METRICS_ENABLED=true`, `OTEL_COLLECTOR_CONFIG` (collector.yaml / collector-tail.yaml), `COLLECTOR_CPUS`, `GRAFANA_PORT`. Переменные lab2–lab5 — как раньше. ## Доказательства критериев -| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | -| --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | +Все файлы — в `evidence/`; полный прогон `scripts/collect-evidence.sh` на **пустых volumes** (все 7 volumes — данные и история telemetry — созданы заново). Стенд — см. примечание выше; версии и контейнеры — `evidence/stack.txt`. Хост: 2 vCPU, Docker 29.10, Compose 5.7.1. -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл | +| --- | --- | --- | --- | +| Публичный smoke при включённой telemetry | `tests/smoke.py --base-url http://127.0.0.1:8080` | `PASS: lab6 public API scenario` (202 → ready, SHA-256, JPEG thumbnail 256×160) | `smoke.txt` | +| 3: весь минимум lab5 работает | регрессия lab2–lab5 | API 18/18, идемпотентность 9/9, TTL 3/3, гонка кэша, вложения 13/13, pipeline 8/8, обработка изображений 8/8, окна отказов pipeline 14/14, отказы S3 5/5, Redis/PostgreSQL 2/2, трек 2 lab5 7/7, хаос 60 загрузок — инварианты `ok`; failover ×2, persistence — PASS; сценарий защиты lab5 — PASS; повтор миграций `applied: []` | `test-*.txt`, `failover-*.txt`, `persistence.txt`, `defense-demo.txt`, `track2-chaos-seed1.txt`, `jobs-invariants.txt` | +| 3: Collector, три хранилища и Grafana в общем стенде; конфиги и provisioning в Git; volumes | `compose.yaml`, `infra/*`, `collector-config-validate.txt`, `observability.txt` | 5 сервисов + `tempo-init`; datasources `prometheus`/`loki`/`tempo` (readOnly, health OK), dashboard `messenger-overview` provisioned (33 панели); volumes `promdata`, `lokidata`, `tempodata`, `grafanadata`; на хост — только `127.0.0.1:3000` Grafana | `observability.txt`, `published-ports.txt` | +| 3: история сохраняется (persistent volumes) | `test_telemetry_persistence.py`: контрольный запрос → restart-hook (все сервисы и хранилища) | после рестарта тот же лог (по request_id), тот же trace и **то же** историческое значение метрики; новые данные снова доходят во все три хранилища | `test-telemetry-persistence.txt` (4/4), `restart-hook.txt` | +| 3: API и worker → OTLP → Collector; RPS/errors/duration API, jobs ok/failed и duration worker | `test_observability.py` «метрики контракта», «метрики отражают обработку» | 20 обязательных метрик есть, `service_name` = messenger-api/worker, `deployment_environment_name=lab`; ready=76, retry=2, time_to_ready count=76, p95 HTTP 41 мс, p95 time-to-ready 2.6 с | `test-observability-final.txt` | +| 3: структурные логи и реальные трассы API и worker; на запросе — trace и лог; на job — worker trace и лог | «HTTP: X-Request-Id → лог → trace», «upload → … → process» | лог с `trace_id`/`span_id`/`severity_text`/`event`/`route`; его `span_id` = server span `POST /api/v1/chats/{chat_id}/messages` (+ DB spans); лог worker `job.finished` того же trace, `span_id` = consumer span | `test-observability*.txt`, `grafana-trace-db-slow.png` | +| 3: импортируемый dashboard (не только screenshot) | `infra/grafana/dashboards/messenger-overview.json` + provisioning | все 60 запросов 33 панелей выполняются через Grafana `/api/ds/query` без ошибок | `test-observability*.txt`, `grafana-dashboard.png` | +| 3: низкокардинальные labels; нет содержимого, паролей, токенов | «метрики контракта», «безопасность» | ни одной серии с user_id/chat_id/message_id/attachment_id/request_id/URL/filename/текстом; маршруты — шаблоны (12); пароль, токен, текст сообщения и `Bearer` не найдены ни в Loki, ни в trace входа и сообщения | `test-observability*.txt` | +| 3: make test при включённой telemetry; назначение хранилищ | smoke + регрессия; раздел «Зачем каждое хранилище» | PASS | `smoke.txt` | +| 4: W3C context API → broker → worker; producer/consumer spans; цепочка до S3/DB, включая retry | «upload → create → send → process», «retry», `research/trace_demo.py` | `create` (PRODUCER, родитель — server span) → `send` (PRODUCER) → `process` (CONSUMER, worker) → `S3.PutObject` ×4, `imgproc.run`, `job.commit`/`COMMIT`; 55 spans в одном trace; retry: попытки 1→2→3 = retry, retry, ready, неудачные — ERROR `error.type=processing_failed`, каждая следующая — потомок предыдущей; паузы backoff 1.7 и 3.7 с | `test-observability*.txt` | +| 4: p50/p95/p99, доля ошибок, queue depth/возраст, DB pool, saturation worker; запросы и единицы | dashboard; раздел «Схема сигналов» | перцентили — `histogram_quantile` из buckets всех реплик; у каждой панели описание запроса и единиц | `grafana-dashboard.png`, JSON dashboard | +| 4: SLI/SLO и окно; alert rules для error rate и queue lag; проверены отказом; firing → resolved | `research/incidents.py` (6 сценариев) | см. «Эксперименты и отказы»: ApiHighErrorRate, JobQueueLagGrowing, WorkerHeartbeatMissing, DbSlowQueries, ApiLatencyHigh, DbPoolSaturated, TelemetryExportFailing, OtelCollectorDown, TelemetryLostInSdk — каждое firing и resolved; 18 правил вычисляются без ошибок; по `ALERTS` за прогон срабатывали все 10 алертов (JobsFailing — на failed `invalid_image` регрессии) | `incident-*.txt`, `incidents/*.json` | +| 4: Collector — memory limiter/batch, ограниченная буферизация; остановка хранилища не ломает сообщения и RAM не растёт бесконечно | `telemetry-down`, `collector-down` | Tempo+Loki остановлены 128 с: 772/772 сообщений и 42/42 загрузки успешны, RSS Collector 50 → 55 МиБ, очередь ≤ 64 из 200 батчей; Collector остановлен 93 с: 748/748 успешны, p95 40 мс, RSS API +6 МиБ; потери посчитаны | `incident-telemetry-down.txt`, `incident-collector-down.txt` | +| 4: разбор двух инцидентов и шаги диагностики | разделы ниже, `docs/runbooks.md` | остановка worker; медленная БД против медленного обработчика (+ недоступная БД) | этот отчёт | +| 5, трек 1 | `research/telemetry_cost.py --reps 3` | см. раздел «Трек 1» | `track1/summary.json`, `track1/runs.json`, `track1-telemetry-cost.txt` | +| Нагрузка (регрессия, telemetry включена) | `tests/load.py --duration 30 --concurrency 4` | 180.9 успешных RPS, 0 ошибок, p50/p95/p99 = 16.9/53.1/107.2 мс (в lab5 без telemetry, другой прогон: 253.6 RPS, 13.4/33.1/53.7 мс; цену telemetry честно сравнивает трек 1) | `load.json` | ## Эксперименты и отказы -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +Нагрузка во время инцидентов — `research/incidents.py`: 3–8 сообщений/с (4 потока) и, где нужно, upload раз в 2–3 с. Обнаружение — **только** по сохранённым наблюдениям: состояние алертов Prometheus, метрики, TraceQL-поиск в Tempo и логи Loki через Grafana API (сценарий не читает stdout контейнеров). Время — от воздействия; правила вычисляются каждые 10 с, метрики SDK экспортируются каждые 10 с. -| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | +| Воздействие | Что ожидаем | Что наблюдали | Обнаружение / восстановление, потери | | --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +| **Все worker остановлены** 93 с под нагрузкой | 202 продолжаются, растёт queue lag; алерты; после старта backlog разбирается | 78 загрузок — 202 (API 276/276 успешных, p95 37 мс); `messenger_queue_depth{state=ready}` и `messenger_broker_pending` растут до 48/46, `outbox pending` = 0; после `worker stopped` логов worker в Loki нет | JobQueueLagGrowing и WorkerHeartbeatMissing **firing через 78 с**; resolved через 25 с (heartbeat) и 45 с (lag, после разбора backlog); все 78 вложений ready — потерь 0 | +| **Медленная БД**: PostgreSQL ограничен 0.03 CPU | растёт p95 БД и API; trace показывает время в PostgreSQL | p95 запросов к БД 3.5 → 222 мс, p95 API 42 → 717 мс, ошибок 0 (516/516); самый медленный trace 702 мс: **99%** — spans PostgreSQL (`pool.check` 192, `DELETE` 94, `INSERT messages` 301, `COMMIT` 106 мс) | DbSlowQueries firing через **57 с**, ApiLatencyHigh через 87 с; после снятия лимита resolved через 56 и 66 с | +| **Медленный обработчик** (контраст): 50% сообщений с `fault-api-slow-400` | p95 API растёт, БД — нет | p95 API 475 мс, p95 БД **2.6 мс**; trace 422 мс: БД 12 мс (**3%**), 409 мс — в server span вне дочерних spans | ApiLatencyHigh firing через 88 с, **DbSlowQueries — нет**; resolved ≈ через 70 с после снятия нагрузки | +| **БД недоступна** (`docker compose pause postgres`, 82 с) | 503, алерт ошибок, причина в trace | 136/136 сообщений → 503 (таймаут пула 2 с); все trace ошибок — `error.type=PoolTimeout`; в Loki 136 записей `dependency.unavailable` (`error`: PoolTimeout/TimeoutError) | DbPoolSaturated через 46 с, ApiHighErrorRate через 82 с; после unpause resolved через 10 и 72 с | +| **Tempo и Loki остановлены** 128 с | API работает; очередь Collector ограничена; алерт; после возврата данные дослать | 772/772 сообщений и 42/42 загрузки успешны (p95 40 мс); RSS Collector 50 → 55 МиБ; очередь экспортёров ≤ 64 из 200 батчей; trace периода простоя найдены в Tempo после восстановления | TelemetryExportFailing через 67 с, resolved через 17 с после старта; не доставлено **275 spans и 30 записей** из 9 907 принятых (батчи старше `max_elapsed_time` 120 с) — посчитаны `otelcol_exporter_send_failed_*` | +| **Collector остановлен** 93 с | API не замедляется, RAM SDK ограничена, потери считаются | 748/748 сообщений успешны, p95 40 мс (до — 44 мс); RSS API 47 → 54 МиБ; новых данных нет | OtelCollectorDown через 36 с; после старта — resolved и **TelemetryLostInSdk** firing: потеряно 5 712 spans и 715 записей лога (`error_type=MaxRetryError`), очередь SDK не переполнялась (`queue_full` = 0) | + +### Разбор инцидента 1: остановлены все worker + +1. **Симптом** (dashboard «SLO и алерты», затем «Очередь заданий»): firing `JobQueueLagGrowing` (lag > 30 с) и `WorkerHeartbeatMissing`. Ошибок HTTP нет (`ApiHighErrorRate` молчит) — пользователи получают 202, но вложения не становятся ready. +2. **Где застряло:** «Глубина очереди»: `ready` растёт (до 48), `processing` = 0; «Брокер и outbox»: `outbox: не опубликовано` ≈ 0 (relay публикует), а `NATS: не выдано` растёт до 46 — сообщения есть в JetStream, их никто не забирает. Значит, не разрыв DB→broker, а отсутствие consumer. +3. **Почему:** «Worker: занятые слоты / ёмкость» — capacity пропала (метрик worker нет 45+ с); Loki `{service_name="messenger-worker"}` — последние записи `worker stopping; draining in-flight jobs` / `worker stopped`. Вывод: worker остановлены штатно (не упали от ошибки). +4. **Действие и проверка:** `make start-worker` → busy = capacity (разбор backlog на полной ёмкости), lag падает, через 25–45 с оба алерта resolved; `make jobs-invariants` — ничего не потеряно. + +### Разбор инцидента 2: «медленно» — это БД или обработчик? + +1. **Симптом:** `ApiLatencyHigh` (p95 > 250 мс = цель SLO). Ошибок нет. +2. **Метрики:** «PostgreSQL: p95 по операции» — в db-slow вырос с 3.5 до 222 мс **вместе** с HTTP p95, сработал `DbSlowQueries`; в handler-slow p95 БД остался 2.6 мс при HTTP p95 475 мс, `DbSlowQueries` не сработал → проблема не в БД. +3. **Trace** (панель «Медленные запросы API > 250 мс» → trace): в db-slow весь запрос состоит из spans PostgreSQL — даже пустая проверка соединения `pool.check` 192 мс, `COMMIT` 106 мс (сервер БД не успевает), `pool.acquire` ≈ `pool.check` (соединения есть — не исчерпание пула); в handler-slow DB spans — 3% длительности, 409 мс «ничьих» — время внутри кода обработчика. +4. **Различие с недоступной БД:** в db-down запросы получают 503, в trace `error.type=PoolTimeout`, раньше всего срабатывает `DbPoolSaturated` (waiting > 0), логи `dependency.unavailable`. +5. **Действие:** для БД — ресурсы/запрос/блокировки (runbook `DbSlowQueries`); для обработчика — профилировать код маршрута из «p95 по маршруту». + +## Трек 1. Цена наблюдаемости + +**Гипотеза.** (H1) Основная цена telemetry для API — создание и экспорт spans в процессе (CPU SDK), она пропорциональна числу spans и не зависит от того, что потом сохранит backend; (H2) head sampling 10% снижает и CPU, и объём хранения примерно в 10 раз, но теряет ≈ 90% редких ошибок и медленных запросов — решение принимается до того, как исход известен; (H3) tail sampling в Collector сохраняет все ошибки и медленные запросы при объёме хранения трасс ≈ 15–20% от полного, но не снижает CPU SDK; (H4) RED-метрики SDK точны при любом sampling, а метрики, построенные из сохранённых spans, — нет. + +**Методика** (`research/telemetry_cost.py`, повторяемо одной командой). 4 конфигурации, переключаются пересозданием `api`, `worker`, `otel-collector` с переменными окружения Compose: `off` (`OTEL_SDK_DISABLED=true`), `full` (100%), `head10` (`parentbased_traceidratio` 0.1), `tail` (SDK 100% → `collector-tail.yaml`: ошибки, > 250 мс, trace pipeline вложений, 10% остальных). Нагрузка одинаковая: **open-loop 60 запросов/с** (латентность от запланированного момента — без coordinated omission), 85% POST сообщения / 15% GET истории, **1% намеренных ошибок** (`fault-api-error` → 500) и **1% намеренно медленных** (`fault-api-slow-300`), upload раз в 2 с (spans worker). Прогрев 15 с, окно 60 с, **3 повтора с чередованием** конфигураций (off, full, head10, tail, off, …), медиана по повторам. CPU/RAM — `docker stats` раз в ~1 с (среднее), ingest — счётчики Collector/Tempo/Loki/Prometheus за прогон, потери — self-метрики SDK и Collector, сохранность редких событий — поиск каждого намеренного запроса в Tempo по `messenger.request_id`. Хост: 2 vCPU, все ~20 контейнеров стенда на них же; лимиты — как в `compose.yaml`. + +| Конфигурация | p50 / p95 / p99, мс | p95 по повторам | CPU API, % ядра (2 реплики) | RAM API, МиБ | Collector CPU / RAM | spans → Collector, /с | spans в Tempo, /с | Tempo, КБ/с | Loki, строк/с (КБ/с) | Prometheus, samples/с | Потери spans | Ошибки в Tempo | Медленные в Tempo | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | +| off | 6.2 / **21.5** / 41.5 | 27.2, 21.5, 18.7 | **30.5** | 106 | 0.1% / 31 МиБ | — | — | — | — | — | — | — | — | +| full | 8.7 / **43.2** / 113.0 | 43.2, 50.5, 42.8 | **43.4** | 124 | 1.3% / 46 МиБ | 483 | 483 | **147** | 62 (18.8) | 1 275 | 0 | 135/135 | 135/135 | +| head10 | 6.7 / **24.6** / 53.6 | 29.2, 24.6, 22.2 | **32.2** | 116 | 0.6% / 51 МиБ | 48 | 48 | **15** | 62 (18.8) | 1 254 | 0 | **5/135** | **9/135** | +| tail | 9.1 / **55.7** / 140.1 | 67.0, 55.7, 37.8 | **42.8** | 124 | 1.4% / 50 МиБ | 483 | **80** | **28** | 62 (18.8) | 1 269 | 0 | **135/135** | **135/135** | + +Успешных запросов во всех прогонах 58.8/с (план 60/с минус 2% намеренных), неожиданных ошибок 0. + +**Результаты.** + +- **H1 подтверждена.** Telemetry `full` против `off`: p95 21.5 → 43.2 мс, p99 41 → 113 мс; CPU двух API 30.5 → 43.4% ядра, т. е. **≈ 2.2 мс CPU на запрос** (≈ 8 spans на запрос сообщения: server, Redis, `pool.acquire`/`pool.check`, 3–4 SQL, COMMIT; плюс запись лога и метрики — ≈ 0.25 мс на span). RAM API +18 МиБ (очереди SDK, состояние метрик). Collector — 1.3% ядра и 46 МиБ. На 2-vCPU-хосте часть роста латентности — конкуренция за CPU с Collector/Tempo/Loki/Prometheus, работающими на тех же ядрах (при `off` они простаивают). +- **H2 подтверждена.** `head10`: CPU API 32.2% (+1.7 п. п. от `off` — почти бесплатно), p95 24.6 мс, Tempo 15 КБ/с (−90%). Но из 135 намеренных ошибок в Tempo нашлись **5 (3.7%)**, из 135 медленных — **9 (6.7%)**: ≈ 10% с биномиальным разбросом. Ошибку или задержку, которую «не повезло» сэмплировать, по trace не разобрать. +- **H3 подтверждена.** `tail`: сохраняются **все** 135 ошибок и 135 медленных запросов при объёме Tempo **28 КБ/с = 19%** от `full` (80 spans/с = 16.5%). CPU SDK — как у `full` (42.8%): SDK по-прежнему создаёт и экспортирует 100% spans, отбрасывает Collector. Медиана p95 55.7 мс с большим разбросом (37.8–67 мс) — в пределах шума `full` на этом хосте; дополнительная цена tail — память Collector (буфер trace на `decision_wait` 10 с, ограничен `num_traces: 20000`; здесь +4 МиБ). +- **H4 подтверждена.** Счётчик 5xx SDK во всех «on»-прогонах = числу намеренных ошибок (45 = 45). Span-метрики Tempo (metrics-generator, из *сохранённых* spans) при `full` = 4 500 = SDK, а при `head10` ≈ 430 (**9.6%**), при `tail` ≈ 550 (**12%**) — RED нельзя строить из сэмплированных trace, поэтому dashboard и алерты используют только метрики SDK. +- **Объём по сигналам:** при `full` трассы — 147 КБ/с, логи — 18.8 КБ/с (13% от трасс), метрики — ≈ 1.3 тыс. samples/с; sampling трасс не меняет логи и метрики. Потерь spans нет ни в одной конфигурации (очереди SDK/Collector не переполнялись). + +**Какие события теряются и почему.** Head sampling решает в момент **начала** trace (по trace_id), когда неизвестно, будет ли ошибка или задержка: редкие события теряются пропорционально доле отбрасываемых (здесь ≈ 90–96%). Особенно опасно для редких, но важных случаев — единичный 500, медленный запрос из-за блокировки, сбой одной попытки задания. Tail sampling решает **после** завершения trace, но видит только то, что попало в trace: из 34 запросов, медленных **по мнению клиента** (> 250 мс), `tail` сохранил 15 — у остальных время ушло вне сервера (очередь LB, соединение, клиент), server span был короче порога. Задержки до сервера ловятся метриками/логами LB, не трассами. + +**Сбалансированная конфигурация (предложена и проверена) — `tail`:** SDK 100% → Collector tail sampling (ошибки + > 250 мс + все trace pipeline вложений + 10% остальных) + RED/SLO из метрик SDK (не из trace). Проверено: 100% ошибок и медленных запросов, все trace заданий; хранение трасс в 5 раз меньше, чем `full`; метрики точны; потерь нет. Цена: CPU SDK как у `full` (≈ 2 мс CPU на запрос на этом хосте) и единственный Collector (для нескольких — `loadbalancing` exporter по trace_id, иначе spans одного trace попадут в разные tail-samplers). Если CPU приложения дороже хранения, следующий шаг — уменьшить число spans на запрос (например, не создавать `pool.check`/`pool.acquire`/Redis spans, перенеся время ожидания пула в атрибут server span) — это **гипотеза**, в эксперименте не проверялась. + +**Ограничения измерения.** Один 2-vCPU-хост, на котором работают и приложение, и все backends; `docker stats` — среднее по ~1-секундным выборкам; 3 повтора — разброс p95 ±10–15 мс (видно в таблице); Python-генератор open-loop ограничен ~60–80 запросами/с. Память backends не сравнивается между конфигурациями: в каждом `tail`-прогоне RSS Tempo вырастал до 400–520 МиБ (в остальных 160–210 МиБ) — причина не установлена (гипотеза — приём целых trace пакетами после `decision_wait`), нужна отдельная проверка. В первом повторе `head10` счётчик 5xx за прогон занижен (7 из 45) — артефакт подсчёта: «устаревшие» серии пересозданных контейнеров выпали из суммы; исправлено (дельты считаются по экземплярам), в остальных прогонах 45/45. + +## Сценарий защиты (README) — что показывать + +1. **С нуля:** `make destroy-data` (или `docker compose --env-file .env down -v`), затем `make up` → Grafana `http://127.0.0.1:3000`: datasources Prometheus/Loki/Tempo и dashboard «Messenger — обзор (lab6)» уже есть (ничего не набирается руками). `make test` и нагрузка `python3 tests/load.py --duration 30 --concurrency 4`. +2. **Свои метрики, trace и лог:** `python3 research/trace_demo.py` — делает upload, ждёт ready и печатает дерево spans (`POST …/attachments` → `create` → `send` → `process` в worker → `S3.PutObject` ×4 → `job.commit`), логи API и worker того же `trace_id` и ссылку на trace в Grafana Explore. В Explore: Loki `{service_name="messenger-api"} | event="http.request"` → кнопка «Открыть trace» у `trace_id`; Prometheus `sum by (http_route) (rate(http_server_request_duration_seconds_count{service_name="messenger-api"}[1m]))`. Это данные своего приложения: `service_name=messenger-api/worker`, `service_instance_id` = `X-Instance-Id` ответа. +3. **Уровень 4:** `python3 research/trace_demo.py --retry` — две попытки в одном trace; `python3 research/incidents.py worker-stop` (на dashboard растёт «Queue lag», панель «Алерты»: JobQueueLagGrowing и WorkerHeartbeatMissing firing → после старта worker resolved); `python3 research/incidents.py db-slow` и `handler-slow` — как отличить медленную БД от медленного обработчика (runbook `ApiLatencyHigh`). +4. **Отказ telemetry:** `python3 research/incidents.py telemetry-down` (Tempo+Loki остановлены: API — 0 ошибок, очередь Collector ограничена, TelemetryExportFailing firing → resolved) и `collector-down`; трек 1 повторяется `python3 research/telemetry_cost.py --reps 1`. + +## Ответы на вопросы защиты + +- **Чем лог, метрика и trace отвечают на разные вопросы об одном инциденте?** Метрика — *что и насколько* (доля 5xx 12%, p95 870 мс, lag 40 с) и *с какого момента*: дёшево, по всем запросам, основа алертов, но без деталей отдельного запроса. Trace — *где* в конкретном запросе/задании: в db-slow 99% времени внутри spans PostgreSQL, в handler-slow 1% — значит, обработчик; в db-down `error.type=PoolTimeout`. Лог — *почему*: текст/тип ошибки, параметры попытки (`error_code`, `attempt`), связанный с trace по `trace_id`. Порядок разбора: алерт (метрика) → медленный/ошибочный trace → его логи. +- **Почему chat_id в labels может исчерпать хранилище?** Каждое уникальное сочетание labels — отдельная серия (в TSDB — индекс, head chunks в RAM). С `chat_id` число серий растёт с числом чатов × маршрутов × кодов × buckets histogram (×14 у нас): 10⁵ чатов → ~10⁷ серий — память Prometheus/индекс Loki заканчиваются, запросы замедляются. Поэтому в labels — только ограниченные множества (шаблон маршрута, класс статуса, outcome), а конкретный чат/вложение ищется в trace/логах. +- **Как очередь переносит причинную связь между процессами?** Контекст W3C (`traceparent`: trace_id + id родительского span + флаги) едет вместе с сообщением: у нас — в payload строки outbox (span `create`, переживает рестарты) и в native headers NATS (span `send`). Worker извлекает его и делает свой `process` span дочерним (плюс link на контекст payload) — трасса процесса API и процесса worker становится одной. +- **Почему среднее latency не заменяет p99 и почему нельзя усреднять p99 реплик?** Распределение задержек тяжелохвостое: среднее 30 мс может скрывать 1% запросов по 2 с (каждый сотый пользователь страдает) — p99 это показывает. Перцентиль не аддитивен: p99 объединённого потока ≠ среднему p99 реплик (реплика с малым трафиком и плохим p99 исказит среднее; реальный p99 зависит от долей трафика). Поэтому складываем **buckets** histogram всех реплик (`sum by (le)`) и уже из суммы считаем `histogram_quantile` (точность — в пределах границ bucket). ## Ограничения и следующие шаги -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +- **Выдерживается:** недоступность Grafana, Collector или любого хранилища telemetry — бизнес-API продолжает работать, память ограничена очередями (проверено); потери telemetry считаются. Перезапуск всех хранилищ с volumes — история сохраняется. +- **Не выдерживается / упрощения:** один экземпляр Collector, Prometheus, Loki и Tempo (нет HA и репликации; при потере volume история теряется); алерты локальные (без Alertmanager и доставки наружу — по заданию не нужно); окна SLO сжаты до минут/часа (в эксплуатации — 28–30 дней с multi-window burn-rate, см. трек 2 курса); PostgreSQL, Redis, NATS и HAProxy не экспортируют собственные метрики (их состояние видно косвенно — клиентскими spans и метриками пула), экспортеры postgres/nats/haproxy — следующий шаг. +- Метрики очереди считает API раз в 5 с (одинаково на каждой реплике, в запросах `max`); при недоступной БД они пропадают («нет данных» вместо устаревших значений). +- `service.instance.id` — случайный alias процесса: при частых пересозданиях контейнеров (эксперимент трека 1) число серий растёт за счёт «ушедших» экземпляров (до выхода из окна хранения); в обычной работе — 2 API + 2 worker. +- Логи пишутся и в stdout, и в OTLP (двойной объём ради диагностики при недоступном Loki). +- Учебные отказы (`FAULT_HOOKS=lab`) включены в `.env.example` для тестов; в боевой конфигурации переменная пуста. +- Трек 1: снижение CPU SDK уменьшением числа spans — гипотеза, не проверена; рост памяти Tempo при tail sampling не объяснён. diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 00000000..b0f10fe9 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,556 @@ +# Учебный стенд lab6: HAProxy (единственная точка входа) → API × N → PostgreSQL (метаданные, jobs, outbox) +# + приватный S3 bucket в SeaweedFS (staging, оригиналы, варианты) + Redis (кэш сессий) +# + NATS JetStream (durable очередь заданий) → worker × N (обработка изображений) +# + наблюдаемость: API/worker → OTLP/HTTP → OTel Collector → Prometheus (метрики), Loki (логи), +# Tempo (трассы) → Grafana (provisioning из Git; единственный UI, 127.0.0.1:3000). +# Запуск: ./scripts/init-secrets.sh && docker compose --env-file .env up -d --build --wait +name: mtusi-lab6 + +x-api-common: &api-common + build: + context: . + dockerfile: Dockerfile + image: mtusi-lab6-api:local + environment: &api-env + APP_HOST: 0.0.0.0 + APP_PORT: "8080" + APP_ENV: ${APP_ENV:-lab} + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + SESSION_STORE: postgres + SESSION_CACHE: ${SESSION_CACHE:-redis} + SESSION_CACHE_TTL_SECONDS: ${SESSION_CACHE_TTL_SECONDS:-60} + IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400} + DATABASE_URL_FILE: /run/secrets/database_url + CACHE_URL_FILE: /run/secrets/cache_url + DB_POOL_MIN: "1" + DB_POOL_MAX: ${DB_POOL_MAX:-10} + DB_POOL_TIMEOUT_SECONDS: "2" + KDF_CONCURRENCY: ${KDF_CONCURRENCY:-4} # каждый scrypt ≈ 32 MiB RAM: учитывайте в API_MEMORY + DB_STATEMENT_TIMEOUT_MS: "5000" + CACHE_TIMEOUT_SECONDS: "0.2" + REQUEST_TIMEOUT_SECONDS: "10" + SHUTDOWN_DRAIN_SECONDS: ${SHUTDOWN_DRAIN_SECONDS:-3} + MIGRATE_ON_START: "false" # миграции — только сервис migrate + # S3: отдельная identity API с правами Read/Write/List ТОЛЬКО на свой bucket (не admin). + S3_ENDPOINT: http://s3: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 + MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760} + MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000} + UPLOAD_CONCURRENCY: ${UPLOAD_CONCURRENCY:-16} + UPLOAD_TIMEOUT_SECONDS: "120" + UPLOAD_GRACE_SECONDS: ${UPLOAD_GRACE_SECONDS:-900} + JANITOR_INTERVAL_SECONDS: "60" + # lab5: задания — через transactional outbox в NATS JetStream (учётные данные — в файле-секрете). + BROKER_URL_FILE: /run/secrets/broker_url + BROKER_ACK_WAIT_SECONDS: ${BROKER_ACK_WAIT_SECONDS:-20} + BROKER_MAX_ACK_PENDING: ${BROKER_MAX_ACK_PENDING:-16} + PIPELINE_VERSION: ${PIPELINE_VERSION:-1} + JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5} + JOB_LEASE_SECONDS: ${JOB_LEASE_SECONDS:-20} + RELAY_INTERVAL_SECONDS: "1" + FAULT_HOOKS: ${FAULT_HOOKS:-} # «lab»: учебные отказы (fault-api-* в тексте, fault-* в имени файла) + # lab6: OpenTelemetry SDK → Collector (OTLP/HTTP, сеть telemetry). Telemetry не блокирует запросы: + # экспорт фоновый, очереди ограничены (OTEL_BSP/BLRP_MAX_QUEUE_SIZE), лишнее отбрасывается и считается. + OTEL_SERVICE_NAME: messenger-api + OTEL_SDK_DISABLED: ${OTEL_SDK_DISABLED:-false} + OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318} + OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf + OTEL_EXPORTER_OTLP_TIMEOUT: "5" # Python SDK: секунды (а не мс, как в спецификации) + OTEL_RESOURCE_ATTRIBUTES: deployment.environment.name=${APP_ENV:-lab} + OTEL_TRACES_SAMPLER: ${OTEL_TRACES_SAMPLER:-parentbased_traceidratio} + OTEL_TRACES_SAMPLER_ARG: ${OTEL_TRACES_SAMPLER_ARG:-1.0} + OTEL_METRIC_EXPORT_INTERVAL: ${OTEL_METRIC_EXPORT_INTERVAL:-10000} + OTEL_BSP_MAX_QUEUE_SIZE: ${OTEL_BSP_MAX_QUEUE_SIZE:-2048} + OTEL_BSP_SCHEDULE_DELAY: "1000" + OTEL_BLRP_MAX_QUEUE_SIZE: ${OTEL_BLRP_MAX_QUEUE_SIZE:-2048} + OTEL_BLRP_SCHEDULE_DELAY: "1000" + OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT: "1024" + OTEL_PYTHON_SDK_INTERNAL_METRICS_ENABLED: "true" + secrets: [database_url, cache_url, s3_access_key_id, s3_secret_access_key, broker_url] + depends_on: + migrate: + condition: service_completed_successfully + s3-init: + condition: service_completed_successfully + broker-init: + condition: service_completed_successfully + redis: + condition: service_started # Redis — кэш: реплики работают и без него + networks: [app, data, objects, broker, telemetry] # НЕТ ports: API доступен только через LB + read_only: true + tmpfs: [/tmp] + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] + restart: unless-stopped + stop_signal: SIGTERM + stop_grace_period: 15s # drain 3 с + завершение запросов в полёте (≤10 с) + +services: + lb: + image: haproxy:3.0.5-alpine + volumes: + - ./infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + environment: + LB_SERVER_MAXCONN: ${LB_SERVER_MAXCONN:-10} + LB_QUEUE_TIMEOUT: ${LB_QUEUE_TIMEOUT:-2s} + ports: + - "127.0.0.1:${API_PORT:-8080}:8080" # публичный API + - "127.0.0.1:${API_TTL_PORT:-8081}:8081" # api-ttl (профиль ttl), тоже только через LB + - "127.0.0.1:${API_FAULT_PORT:-8082}:8082" # api-fault (профиль fault): только для теста компенсации + - "127.0.0.1:${LB_STATS_PORT:-8404}:8404" # статистика HAProxy (только чтение) + healthcheck: + test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8404/stats"] + interval: 5s + timeout: 2s + retries: 3 + networks: [edge, app] + restart: unless-stopped + stop_grace_period: 5s + deploy: + resources: + limits: {cpus: "0.5", memory: 128M} + + # One-shot: миграции применяются ОДИН раз до запуска реплик (не гонкой реплик). + # Повторный запуск (docker compose run --rm migrate) — no-op. Реплики не становятся ready, + # пока схема не содержит все известные им миграции. + migrate: + <<: *api-common + command: ["migrate"] + depends_on: + postgres: + condition: service_healthy + networks: [data] + restart: "no" + secrets: [database_url] + environment: + <<: *api-env + SESSION_CACHE: "off" + S3_ACCESS_KEY_ID_FILE: "" # migrate не работает с S3 и брокером + S3_SECRET_ACCESS_KEY_FILE: "" + BROKER_URL_FILE: "" + deploy: + resources: + limits: {cpus: "0.5", memory: 256M} + + api: + <<: *api-common + deploy: + replicas: ${API_REPLICAS:-2} + resources: + limits: {cpus: "${API_CPUS:-1.0}", memory: "${API_MEMORY:-512M}"} + + # Экземпляр с коротким TTL — только для теста истечения; доступен через LB на :8081. + api-ttl: + <<: *api-common + profiles: [ttl] + environment: + <<: *api-env + SESSION_TTL_SECONDS: "2" + deploy: + resources: + limits: {cpus: "0.5", memory: 256M} + + # ТОЛЬКО для тестов отказов (уровень 4), доступен через LB :8082. Точка отказа — API_FAULT_INJECT: + # crash_after_commit_before_publish (по умолчанию) — процесс умирает между COMMIT задания и publish; + # crash_after_publish_before_mark — между publish ack и отметкой строки outbox; + # crash_after_s3_put — между записью staging и COMMIT (компенсация lab4). + api-fault: + <<: *api-common + profiles: [fault] + environment: + <<: *api-env + FAULT_INJECT: ${API_FAULT_INJECT:-crash_after_commit_before_publish} + UPLOAD_GRACE_SECONDS: "10" + UPLOAD_TIMEOUT_SECONDS: "5" # intent «брошен» не раньше max(grace, timeout+5) = 10 с + JANITOR_INTERVAL_SECONDS: "2" + deploy: + resources: + limits: {cpus: "0.5", memory: 256M} + + # Worker: отдельный процесс/сервис (тот же образ, команда worker). Портов нет, в сеть LB не входит. + # Обработка каждого файла — в подпроцессе с RLIMIT_AS/RLIMIT_CPU и таймаутом; конкуренция — + # WORKER_CONCURRENCY слотов на процесс (столько же сообщений берётся из брокера, не больше). + worker: + <<: *api-common + command: ["worker"] + environment: + <<: *api-env + SESSION_CACHE: "off" + WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-2} + WORKER_PIPELINES: ${WORKER_PIPELINES:-1,2} + JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60} + JOB_RETRY_BASE_SECONDS: ${JOB_RETRY_BASE_SECONDS:-2} + JOB_RETRY_MAX_SECONDS: ${JOB_RETRY_MAX_SECONDS:-60} + JOB_STUCK_SECONDS: ${JOB_STUCK_SECONDS:-600} + WORKER_PROCESS_MEMORY_MB: ${WORKER_PROCESS_MEMORY_MB:-768} + STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-86400} + MAINTENANCE_INTERVAL_SECONDS: "5" + WORKER_DRAIN_SECONDS: "20" + OTEL_SERVICE_NAME: messenger-worker + secrets: [database_url, s3_access_key_id, s3_secret_access_key, broker_url] + depends_on: + migrate: + condition: service_completed_successfully + s3-init: + condition: service_completed_successfully + broker-init: + condition: service_completed_successfully + networks: [data, objects, broker, telemetry] + healthcheck: + test: ["CMD", "python", "-m", "messenger", "worker-healthcheck"] + interval: 5s + timeout: 3s + retries: 6 + start_period: 20s + stop_grace_period: 30s # дорабатывает текущие задания ≤ 20 с, остальное вернёт брокер + deploy: + replicas: ${WORKER_REPLICAS:-2} + resources: + # WORKER_CONCURRENCY × пик RSS одной обработки (≈ 250 МиБ на 40 Мп) + сам процесс ≤ лимита. + limits: {cpus: "${WORKER_CPUS:-1.0}", memory: "${WORKER_MEMORY:-1G}"} + + # Брокер: NATS JetStream. Stream на диске (volume natsdata, fsync каждой записи), доступ по паролю + # (конфигурация с учётными данными — secret). Порт 4222 — только во внутренней сети broker, + # мониторинг :8222 — только 127.0.0.1 внутри контейнера (для healthcheck). На хост ничего не публикуется. + nats: + image: nats:2.11.9-alpine + entrypoint: ["nats-server"] + command: ["--config", "/run/secrets/nats_config"] + secrets: [nats_config] + volumes: + - natsdata:/data + healthcheck: + test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8222/healthz?js-enabled-only=true"] + interval: 2s + timeout: 2s + retries: 30 + start_period: 5s + networks: [broker] + restart: unless-stopped + stop_grace_period: 10s + deploy: + resources: + limits: {cpus: "0.5", memory: 256M} + + # One-shot bootstrap брокера: идемпотентно создаёт stream и durable consumer (повтор — no-op). + broker-init: + <<: *api-common + command: ["broker-bootstrap"] + environment: + <<: *api-env + SESSION_CACHE: "off" + S3_ACCESS_KEY_ID_FILE: "" # broker-init работает только с брокером + S3_SECRET_ACCESS_KEY_FILE: "" + secrets: [database_url, broker_url] + depends_on: + nats: + condition: service_healthy + networks: [broker] + restart: "no" + deploy: + resources: + limits: {cpus: "0.25", memory: 128M} + + # S3-совместимое хранилище: SeaweedFS (master+volume+filer+S3 в одном процессе). + # master/volume/filer (и их web-консоли) слушают только 127.0.0.1 внутри контейнера; наружу + # контейнера — только S3 API :9000, и только во внутренней сети objects. Порты на хост не публикуются. + s3: + image: chrislusf/seaweedfs:4.52 + entrypoint: ["/usr/bin/weed"] + # Быстрая остановка: SIGINT + preStopSeconds=1 (иначе restart s3 занимает ~10 с впустую) + stop_signal: SIGINT + stop_grace_period: 5s + command: + - -logtostderr=true + - server + - -dir=/data + - -ip=127.0.0.1 + - -ip.bind=127.0.0.1 + - -s3 + - -s3.port=9000 + - -s3.ip.bind=0.0.0.0 + - -s3.config=/run/secrets/s3_config + - -master.volumeSizeLimitMB=1024 + - -master.electionTimeout=2s # единственный master: быстрее становится лидером после рестарта + - -volume.max=0 + - -volume.preStopSeconds=1 # по умолчанию 10 с ожидания при остановке (рассчитано на кластер) + # Без лимитов weed буферизует все одновременные загрузки и при 10×10 МиБ был убит OOM (512M). + # С лимитами лишние загрузки ждут очереди внутри S3, а не роняют его (см. REPORT.md, эксперимент). + - -s3.concurrentFileUploadLimit=8 + - -s3.concurrentUploadLimitMB=96 + - -filer.concurrentUploadLimitMB=96 + - -volume.concurrentUploadLimitMB=96 + - -s3.cacheCapacityMB=32 + - -master.telemetry=false # не отправлять статистику во внешний интернет + environment: + # Мягкий лимит кучи Go: GC держит weed ниже ~640 МиБ при лимите контейнера 1 ГиБ (без него + # куча после пика не отдаётся и под нагрузкой процесс убивает OOM). + GOMEMLIMIT: 640MiB + secrets: [s3_config] + volumes: + - s3data:/data + healthcheck: + # healthy = S3-шлюз жив, master — лидер И запись возможна. После рестарта SeaweedFS 4.52 ~15 с + # «прогревает» топологию (pulse 5 с × 3, в коде не настраивается): чтение уже работает, а запись + # ждёт. /dir/assign отдаёт fid только по окончании прогрева, поэтому хуки ждут именно его. + test: ["CMD-SHELL", "wget -q -O /dev/null http://127.0.0.1:9000/healthz && wget -q -O /dev/null http://127.0.0.1:9333/cluster/healthz && wget -q -O - http://127.0.0.1:9333/dir/assign | grep -q fid"] + interval: 2s + timeout: 2s + retries: 30 + start_period: 10s + networks: [objects] + restart: unless-stopped + deploy: + resources: + limits: {cpus: "1.0", memory: 1G} + + # One-shot bootstrap S3: идемпотентно создаёт приватный bucket ключом администратора и проверяет, + # что анонимный доступ запрещён, а ключи API не могут создавать бакеты. Admin-ключи есть только здесь. + s3-init: + <<: *api-common # тот же образ (сборка из исходников), свои env/secrets/сеть + command: ["s3-bootstrap"] + environment: + S3_ENDPOINT: http://s3:9000 + S3_REGION: ${S3_REGION:-us-east-1} + S3_BUCKET: ${S3_BUCKET:-messenger-attachments} + S3_ADMIN_ACCESS_KEY_ID_FILE: /run/secrets/s3_admin_access_key_id + S3_ADMIN_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_admin_secret_access_key + S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_access_key_id + S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key + secrets: [s3_admin_access_key_id, s3_admin_secret_access_key, s3_access_key_id, s3_secret_access_key] + depends_on: + s3: + condition: service_healthy + networks: [objects] + restart: "no" + deploy: + resources: + limits: {cpus: "0.25", memory: 128M} + + postgres: + image: postgres:16.10-alpine + environment: + POSTGRES_USER: messenger + POSTGRES_DB: messenger + POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password + POSTGRES_INITDB_ARGS: "--auth-host=scram-sha-256 --data-checksums" + command: ["postgres", "-c", "max_connections=${PG_MAX_CONNECTIONS:-100}"] + secrets: [postgres_password] + volumes: + - pgdata:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U messenger -d messenger -h 127.0.0.1"] + interval: 2s + timeout: 3s + retries: 30 + start_period: 10s + networks: [data] + shm_size: 256m + restart: unless-stopped + stop_grace_period: 30s + deploy: + resources: + limits: {cpus: "${PG_CPUS:-1.0}", memory: 1G} + + # Redis — общий кэш сессий без persistence; источник истины сессий — PostgreSQL. + redis: + image: redis:7.4.2-alpine + command: + - sh + - -c + - | + umask 077 + printf 'requirepass %s\n' "$$(cat /run/secrets/redis_password)" > /tmp/redis.conf + exec redis-server /tmp/redis.conf --save '' --appendonly no --maxmemory 64mb --maxmemory-policy allkeys-lru + user: redis + secrets: [redis_password] + healthcheck: + test: ["CMD-SHELL", "REDISCLI_AUTH=\"$$(cat /run/secrets/redis_password)\" redis-cli ping | grep -q PONG"] + interval: 2s + timeout: 2s + retries: 15 + networks: [data] + restart: unless-stopped + deploy: + resources: + limits: {cpus: "0.25", memory: 128M} + + # ===================================================================================== наблюдаемость (lab6) + # OTel Collector: приём OTLP/HTTP от API/worker (сеть telemetry), обработка (memory_limiter, scrub, batch) + # и экспорт в три хранилища (сеть observability). Ничего не публикуется на хост. Не хранит данные сам. + # API/worker от Collector НЕ зависят (depends_on нет): без него бизнес-путь работает, telemetry теряется. + otel-collector: + image: otel/opentelemetry-collector-contrib:0.130.0 + command: ["--config=/etc/otelcol-contrib/${OTEL_COLLECTOR_CONFIG:-collector.yaml}"] + volumes: + - ./infra/otel:/etc/otelcol-contrib:ro + environment: + GOMEMLIMIT: 180MiB # мягкий лимит кучи Go ниже memory_limiter и лимита контейнера + networks: [telemetry, observability] + restart: unless-stopped + stop_grace_period: 10s # успеть отправить накопленные батчи + deploy: + resources: + limits: {cpus: "${COLLECTOR_CPUS:-0.5}", memory: 256M} + + # Метрики: Prometheus 3.5 LTS. Приложение — push через Collector на OTLP receiver; компоненты + # наблюдаемости — scrape. Правила SLI и алертов — infra/prometheus/rules (локальное firing/resolved). + prometheus: + image: prom/prometheus:v3.5.0 + command: + - --config.file=/etc/prometheus/prometheus.yml + - --storage.tsdb.path=/prometheus + - --storage.tsdb.retention.time=7d + - --storage.tsdb.retention.size=1GB + - --web.enable-otlp-receiver # POST /api/v1/otlp/v1/metrics (только сеть observability) + - --web.enable-remote-write-receiver # span-метрики/service graph от Tempo + - --web.enable-lifecycle + volumes: + - ./infra/prometheus:/etc/prometheus:ro + - promdata:/prometheus + healthcheck: + test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:9090/-/ready"] + interval: 5s + timeout: 3s + retries: 20 + start_period: 10s + networks: [observability] + restart: unless-stopped + deploy: + resources: + limits: {cpus: "0.5", memory: 512M} + + # Логи: Loki 3.5 (single binary, native OTLP). Volume lokidata, retention 7 дней. + loki: + image: grafana/loki:3.5.3 + command: ["-config.file=/etc/loki/loki.yaml"] + volumes: + - ./infra/loki/loki.yaml:/etc/loki/loki.yaml:ro + - lokidata:/loki + networks: [observability] + restart: unless-stopped + deploy: + resources: + limits: {cpus: "0.5", memory: 512M} + + # Трассы: Tempo 2.8 (monolithic). Образ работает от uid 10001 — one-shot tempo-init выдаёт права на volume. + tempo-init: + image: grafana/tempo:2.8.2 + user: root + entrypoint: ["chown", "-R", "10001:10001", "/var/tempo"] + volumes: + - tempodata:/var/tempo + network_mode: none + restart: "no" + tempo: + image: grafana/tempo:2.8.2 + command: ["-config.file=/etc/tempo/tempo.yaml"] + volumes: + - ./infra/tempo/tempo.yaml:/etc/tempo/tempo.yaml:ro + - tempodata:/var/tempo + depends_on: + tempo-init: + condition: service_completed_successfully + networks: [observability] + restart: unless-stopped + deploy: + resources: + limits: {cpus: "0.5", memory: 512M} + + # Grafana — интерфейс и запросы (данные не хранит, кроме своей БД настроек на volume grafanadata). + # Datasources и dashboards импортируются из Git (provisioning); анонимного доступа нет; пароль admin — + # secret. Опубликована только на 127.0.0.1. Недоступность Grafana не влияет на API (нет зависимостей). + grafana: + image: grafana/grafana:13.3.1 + environment: + GF_SECURITY_ADMIN_USER: admin + GF_SECURITY_ADMIN_PASSWORD__FILE: /run/secrets/grafana_admin_password + GF_SECURITY_DISABLE_GRAVATAR: "true" + GF_AUTH_ANONYMOUS_ENABLED: "false" + GF_USERS_ALLOW_SIGN_UP: "false" + GF_ANALYTICS_REPORTING_ENABLED: "false" + GF_ANALYTICS_CHECK_FOR_UPDATES: "false" + GF_ANALYTICS_CHECK_FOR_PLUGIN_UPDATES: "false" + GF_PLUGINS_PREINSTALL_DISABLED: "true" # без загрузки плагинов из интернета + GF_NEWS_NEWS_FEED_ENABLED: "false" + GF_SERVER_ROOT_URL: http://127.0.0.1:${GRAFANA_PORT:-3000}/ + GF_LOG_LEVEL: warn + secrets: [grafana_admin_password] + volumes: + - ./infra/grafana/provisioning:/etc/grafana/provisioning:ro + - ./infra/grafana/dashboards:/etc/grafana/dashboards:ro + - grafanadata:/var/lib/grafana + ports: + - "127.0.0.1:${GRAFANA_PORT:-3000}:3000" + healthcheck: + test: ["CMD-SHELL", "wget -q -O /dev/null http://127.0.0.1:3000/api/health || curl -fsS -o /dev/null http://127.0.0.1:3000/api/health"] + interval: 5s + timeout: 3s + retries: 30 + start_period: 20s + depends_on: + prometheus: + condition: service_started + loki: + condition: service_started + tempo: + condition: service_started + networks: [observability, ui] + restart: unless-stopped + deploy: + resources: + limits: {cpus: "0.5", memory: 512M} + +networks: + edge: {} # только LB: публикация портов на 127.0.0.1 + app: + internal: true # LB ↔ API + data: + internal: true # API ↔ PostgreSQL/Redis + objects: + internal: true # API/worker ↔ S3 (SeaweedFS); PostgreSQL/Redis отсюда недоступны + broker: + internal: true # API/worker ↔ NATS + telemetry: + internal: true # API/worker → OTel Collector (OTLP :4318) + observability: + internal: true # Collector ↔ Prometheus/Loki/Tempo ↔ Grafana + ui: {} # только Grafana: публикация 127.0.0.1:3000 + +volumes: + pgdata: {} + s3data: {} # объекты вложений (persistent) + natsdata: {} # JetStream: принятые, но не подтверждённые задания (persistent) + promdata: {} # метрики (TSDB, retention 7 дней / 1 ГБ) + lokidata: {} # логи (retention 7 дней) + tempodata: {} # трассы (retention 7 дней) + grafanadata: {} # БД Grafana (пользователи/настройки; dashboards — из Git) + +secrets: + postgres_password: + file: ./secrets/postgres_password + redis_password: + file: ./secrets/redis_password + database_url: + file: ./secrets/database_url + cache_url: + file: ./secrets/cache_url + s3_config: # identities SeaweedFS: admin и api (права только на bucket) + file: ./secrets/s3_config.json + s3_admin_access_key_id: + file: ./secrets/s3_admin_access_key_id + s3_admin_secret_access_key: + file: ./secrets/s3_admin_secret_access_key + s3_access_key_id: + file: ./secrets/s3_access_key_id + s3_secret_access_key: + file: ./secrets/s3_secret_access_key + broker_url: # nats://messenger:<пароль>@nats:4222 + file: ./secrets/broker_url + nats_config: # конфигурация nats-server с учётными данными + file: ./secrets/nats.conf + grafana_admin_password: # пароль пользователя admin Grafana + file: ./secrets/grafana_admin_password diff --git a/contracts/EXTENSIONS.md b/contracts/EXTENSIONS.md new file mode 100644 index 00000000..1f766af8 --- /dev/null +++ b/contracts/EXTENSIONS.md @@ -0,0 +1,23 @@ +# Расширения решения (обратно совместимые) + +Обязательный контракт (`openapi.json`, `README.md`) не изменён. Дополнительно реализовано: + +| Что | Где | Семантика | +| --- | --- | --- | +| Заголовок ответа `Idempotent-Replayed: true` | `POST /api/v1/chats/{chat_id}/messages` | Ответ 201 — повтор ранее сохранённого результата по тому же `Idempotency-Key` (тело и код совпадают с первым ответом). Клиент может игнорировать. | +| `GET /internal/stats` | только изнутри контейнера реплики (`127.0.0.1`); LB отвечает на `/internal/*` 404 в формате ошибок API | Диагностика для исследования: alias реплики, версия, счётчики запросов, кэша сессий и пула соединений psycopg. `python -m messenger stats` в контейнере. | +| `GET /internal/stats` (lab4): `memory.rss_kib`/`peak_rss_kib` (VmRSS/VmHWM), `uploads_in_flight`, счётчики `uploads_*`, `compensations`, `janitor_removed`; `?reset_peak=1` сбрасывает VmHWM | изнутри контейнера: `python -m messenger stats [--reset-peak]` | Измерение пика памяти в эксперименте с одновременными загрузками. | +| Ответ на `GET /api/v1/attachments/{id}/content`, если объект ready-вложения утрачен в S3 | API | `500 internal` «Содержимое вложения утрачено» (не маскируется под 404: метаданные есть, байтов нет). Пока S3 недоступен — `503 unavailable`. Для queued/processing/failed — `409 conflict` по контракту. | +| `GET /internal/stats` (lab5): `broker` — подключение, сообщений в stream, pending/ack_pending/redelivered consumer'а; `app.outbox_published` | изнутри контейнера API | Наблюдение за очередью и relay. | +| Заголовки ответа download | API | `Content-Type` из метаданных (проверен по содержимому), `Content-Length`, `ETag: ""`, `X-Content-Type-Options: nosniff`, `Cache-Control: private, no-store`, `Content-Disposition: inline; filename*=UTF-8''…` (filename только для отображения). | +| Операционные команды (не HTTP) | `python -m messenger s3-bootstrap \| s3-check \| broker-bootstrap \| worker \| jobs status\|failed\|replay\|reprocess\|invariants` | Bootstrap bucket и stream/consumer (one-shot сервисы, идемпотентно), процесс worker, операторские команды: журнал работы, реестр failed (DLQ), явный replay failed (ready — no-op), новая версия pipeline (трек 2), проверка инвариантов. Тестовые инструменты `jobs publish-raw` (дубли/reorder) и `jobs purge-stream` (потеря сообщений) — только для учебного стенда. | +| Ответы, созданные самим LB (502/503/504/404 для `/internal/*`) | HAProxy | Тело в формате ошибок API с `request_id` = `X-Request-Id` (случайный uuid). `X-Instance-Id` у них нет — контракт это допускает. | + +Область ключа идемпотентности: пользователь + `POST` + `/api/v1/chats/{chat_id}/messages` + ключ. Других +идемпотентных endpoint в обязательном API нет, поэтому хранится тройка `(user_id, chat_id, key)`. +Срок хранения — `IDEMPOTENCY_TTL_SECONDS` (по умолчанию 86 400 с = 24 ч). +| Сообщение задания (jobs.schema.json) | NATS JetStream, subject `attachments.process.v1`, stream `ATTACHMENT_JOBS` | Поля строго по схеме v1 (`schema_version, job_id, type, attachment_id, pipeline_version, attempt, created_at` и необязательные `traceparent`/`tracestate`); заголовок `Nats-Msg-Id: outbox-` — дедупликация повторной публикации. Байтов, URL и credentials нет. | +| Trace context задания (lab6) | payload + native headers NATS | `traceparent`/`tracestate` в payload — контекст span «create» (сохраняется в outbox в транзакции upload, переживает рестарты и повторы); заголовки NATS `traceparent`/`tracestate` — контекст span «send» relay. Worker берёт родителя из заголовков (если нет — из payload) и ставит link на контекст payload. Отображение: W3C carrier ↔ поля payload/headers с теми же именами. | +| Учебные отказы API (lab6) | `POST /api/v1/chats/{chat_id}/messages`, только при `FAULT_HOOKS=lab` | Маркер `fault-api-error` в тексте → 500 (ничего не записано), `fault-api-slow-<мс>` → задержка обработчика (≤ 5 с). Нужны для трека 1 и разбора инцидентов; в боевой конфигурации `FAULT_HOOKS` пуст и маркеры — обычный текст. | +| Входящий `traceparent` клиента | публичный API | Не принимается: каждый внешний запрос начинает новый trace (клиент не может навязать trace/sampling). Связь запроса с логом — `X-Request-Id` (поле `request_id` лога и атрибут `messenger.request_id` server span). | +| Состояние `superseded` работы | только в БД (`attachment_jobs.status`), не в публичном API | Работа старой версии pipeline, обогнанная новой (трек 2): результат не публикуется, указатель версии не откатывается. | diff --git a/docs/runbooks.md b/docs/runbooks.md new file mode 100644 index 00000000..9ed1b040 --- /dev/null +++ b/docs/runbooks.md @@ -0,0 +1,112 @@ +# Runbooks алертов мессенджера (lab6) + +Как найти причину **только по сохранённым наблюдениям** (Grafana → Prometheus/Loki/Tempo), не заходя в контейнеры. +Все ссылки ниже — в Grafana `http://127.0.0.1:3000` (логин `admin`, пароль — `secrets/grafana_admin_password`), +dashboard **Messenger → «Messenger — обзор (lab6)»**. Правила — `infra/prometheus/rules/messenger.yml`, +состояние — Grafana → Alerting → Alert rules (Data source-managed, Prometheus) или панель «Алерты» dashboard. + +Общий порядок: **метрика** говорит, *что* и *насколько* плохо (и с какого момента) → **trace** — *где* в запросе +тратится время или возникает ошибка → **лог** (по `trace_id`/`request_id`) — *почему* (текст ошибки, параметры). + +| Алерт | Что означает | Первый вопрос | +| --- | --- | --- | +| ApiHighErrorRate | > 5% бизнес-запросов — 5xx | какая зависимость: `error.type` в trace | +| ApiLatencyHigh | p95 > 250 мс (цель SLO) | БД или обработчик? | +| DbSlowQueries | p95 запросов к PostgreSQL > 50 мс | БД медленная сама или перегружена? | +| DbPoolSaturated | запросы ждут соединения пула | мало соединений или долгие запросы? | +| JobQueueLagGrowing | доступное задание ждёт worker > 30 с | worker живы? заняты? | +| WorkerHeartbeatMissing | нет метрик ни одного worker > 45 с | worker остановлены/упали? | +| JobsFailing | финальные ошибки обработки | какие error_code? | +| TelemetryExportFailing | Collector не может отправить в backend | какой backend недоступен? | +| OtelCollectorDown | Collector не отвечает | telemetry не принимается | +| TelemetryLostInSdk | SDK потерял spans/logs (после восстановления) | за какой интервал пробел в trace/логах | + +## ApiHighErrorRate + +1. Dashboard → «Ответы по классу статуса»: 5xx растут на всех маршрутах (зависимость) или на одном (код маршрута)? +2. Панель «Трассы с ошибками» (TraceQL `{ resource.service.name =~ "messenger-.*" && status = error }`) → + открыть trace → атрибут `error.type` server span: `PoolTimeout`/`TooManyRequests` — пул БД не выдаёт + соединение (БД недоступна/медленная), `OperationalError`/`QueryCanceled` — ошибка/таймаут запроса, + `S3Unavailable` — S3, `RuntimeError` и др. — ошибка кода. +3. Loki: `{service_name="messenger-api"} | event="dependency.unavailable"` — поле `error` даёт то же по каждому + запросу; `| event="http.unhandled_error"` — необработанные исключения (тип в `exception.type`). +4. Проверить зависимость: «Пул БД: занято/максимум/ждут», «PostgreSQL: p95 по операции». +5. После устранения 5xx пропадают за ≈ 1 мин (окно rate), алерт — resolved. + +## ApiLatencyHigh + +Главный вопрос — **медленная БД или медленный обработчик**: + +| Наблюдение | Медленная БД | Медленный обработчик (CPU/код) | +| --- | --- | --- | +| «PostgreSQL: p95 по операции» | растёт вместе с HTTP p95 | без изменений (единицы мс) | +| Алерт DbSlowQueries | firing | нет | +| Trace медленного запроса | время внутри spans `INSERT …`/`SELECT …`/`pool.check` (db.system.name=postgresql) | время в server span **вне** дочерних spans | +| Пул БД | used растёт, могут появиться waiting | без изменений | + +Дальше: «p95 по маршруту» — какой маршрут; в trace — самый длинный дочерний span. `password.verify`/`password.hash` +(scrypt, ~0.1–0.3 с) — норма для входа/регистрации, они в SLI задержки не входят. Атрибут `messenger.kdf.wait_ms` +показывает очередь к KDF (KDF_CONCURRENCY). + +## DbSlowQueries + +1. «PostgreSQL: p95 по операции»: замедлились все операции (ресурсы БД: CPU/диск/блокировки) или одна (план запроса). +2. «CPU контейнеров»/«Память контейнеров» не покрывают PostgreSQL (у него нет SDK) — смотрите `docker stats` + или лимиты (`docker inspect … NanoCpus`); на учебном стенде инцидент воспроизводится `docker update --cpus 0.03`. +3. Trace медленного запроса: какие именно statements (`db.query.summary`) долгие; `pool.check` долгий — + даже пустой запрос медленный → проблема сервера БД, а не SQL. +4. Если растут только `UPDATE/SELECT … FOR UPDATE` — блокировки (lock_timeout 2 с даст 503 с `LockNotAvailable`). + +## DbPoolSaturated + +1. «Пул БД»: used = max и waiting > 0 → соединений не хватает. Вместе с DbSlowQueries — запросы долгие (лечить БД); + без него — мало соединений для нагрузки (DB_POOL_MAX, но не больше PG max_connections / реплики). +2. «Ожидание соединения пула и таймауты»: таймауты → клиенты получают 503 (см. ApiHighErrorRate). +3. В trace — span `pool.acquire`: сколько запрос ждал соединение. + +## JobQueueLagGrowing + +1. «Глубина очереди по состоянию»: `ready` растёт — задания есть, но их не забирают. +2. «Worker: занятые слоты / ёмкость»: capacity = 0 — worker нет (см. WorkerHeartbeatMissing); busy = capacity — + worker перегружены (медленная обработка: «Длительность попытки», trace `imgproc.run`) → масштабировать worker. +3. «Брокер и outbox»: `outbox: не опубликовано` растёт — разрыв DB→broker (NATS недоступен; лог + `event="outbox publish failed; will retry"` в Loki); `NATS: не выдано` растёт при живых worker — проблема consumer. +4. Восстановление: после возврата worker backlog уменьшается, lag → 0, алерт resolved. Потерь нет: задания в + PostgreSQL/JetStream (проверка — `make jobs-invariants`). + +## WorkerHeartbeatMissing + +1. Метрики worker не приходят: `docker compose ps worker` (остановлен/перезапускается?), логи + `{service_name="messenger-worker"}` — последний `worker stopping`/ошибка конфигурации. +2. Если worker работают, а метрик нет — проблема экспорта telemetry (см. OtelCollectorDown). +3. `make start-worker` — запустить; backlog разберётся автоматически. + +## JobsFailing + +1. `python -m messenger jobs failed` (или `make jobs-failed`) — реестр failed с error_code. +2. Loki: `{service_name="messenger-worker"} | event="job.attempt_failed"` — по каким `error_code`; trace задания + (`{ span.messenger.attachment.id = "" }`) показывает все попытки и где упала каждая. +3. `invalid_image` — данные клиента (норма); `retry_exhausted`/`storage_unavailable` — зависимость; после + устранения — `python -m messenger jobs replay --all-failed --error-code retry_exhausted --reason "…"`. + +## TelemetryExportFailing + +1. Dashboard → «Collector: принято/отправлено/ошибки» и «Очереди экспортёров»: у какого экспортёра + (`otlphttp/tempo`, `otlphttp/loki`, `otlphttp/prometheus`) растёт очередь. +2. Проверить backend: Grafana → Connections → Data sources → Test. +3. Пока backend недоступен, батчи ждут в ограниченной очереди (200 батчей) и повторяются до 120 с; дальше — + отбрасываются (`otelcol_exporter_send_failed_*`). Бизнес-API не затронут. После восстановления очередь + опустошается, алерт resolved; потерянное за интервал перечислено счётчиками. + +## OtelCollectorDown + +1. `docker compose ps otel-collector`, его логи (stdout контейнера). +2. Пока Collector недоступен, SDK отбрасывает пакеты экспорта (очереди 2048 spans/logs на процесс) — память + API/worker не растёт, запросы не замедляются (экспорт в фоновом потоке). +3. После `docker compose start otel-collector` сработает TelemetryLostInSdk — количество потерянного. + +## TelemetryLostInSdk + +Информационный: за последние 5 мин SDK не смог экспортировать или отбросил spans/logs (`error_type`: +`MaxRetryError` — Collector недоступен, `queue_full` — очередь SDK переполнена). Trace/логи этого интервала +неполны; метрики RED не потеряны (кумулятивные счётчики восстановятся при следующем экспорте). diff --git a/evidence/broker-bootstrap.txt b/evidence/broker-bootstrap.txt new file mode 100644 index 00000000..d3d9e265 --- /dev/null +++ b/evidence/broker-bootstrap.txt @@ -0,0 +1,5 @@ +# 2026-11-21T18:58:11Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +$ dc logs --no-log-prefix broker-init +{"ts": "2026-11-21T18:57:54.272Z", "level": "warning", "service": "messenger", "logger": "messenger.broker", "event": "broker disconnected", "msg": "broker disconnected"} +{"created": {"stream": true, "consumer": true}, "stream": {"name": "ATTACHMENT_JOBS", "subjects": ["attachments.process.v1"], "storage": "file", "retention": "workqueue", "duplicate_window_s": 120.0, "max_msgs": 100000, "messages": 0}, "consumer": {"durable": "attachment-workers", "ack_policy": "explicit", "ack_wait_s": 20.0, "max_ack_pending": 16, "max_deliver": -1}} +exit=0 diff --git a/evidence/collector-config-validate.txt b/evidence/collector-config-validate.txt new file mode 100644 index 00000000..aa516080 --- /dev/null +++ b/evidence/collector-config-validate.txt @@ -0,0 +1,5 @@ +# 2026-11-21T18:58:16Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +$ dc run --rm --no-deps otel-collector validate --config=/etc/otelcol-contrib/collector.yaml + Container mtusi-lab6-otel-collector-run-305dad94c299 Creating + Container mtusi-lab6-otel-collector-run-305dad94c299 Created +exit=0 diff --git a/evidence/defense-demo.txt b/evidence/defense-demo.txt new file mode 100644 index 00000000..a80c058a --- /dev/null +++ b/evidence/defense-demo.txt @@ -0,0 +1,33 @@ +# 2026-11-21T20:04:22Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +$ python3 student-tests/defense_demo.py +20:04:24.055 0 chat 4e63a603-914c-4f47-84d9-6f71057ad639, users alice/bob (tokens not shown) +20:04:24.835 0 mtusi-lab6-api-1 running started=2026-11-21T19:59:25.880108847Z pid=2790 +20:04:24.835 0 mtusi-lab6-api-2 running started=2026-11-21T19:59:26.237488123Z pid=2867 +20:04:24.835 0 mtusi-lab6-worker-1 running started=2026-11-21T19:59:26.716469278Z pid=2986 +20:04:24.835 0 mtusi-lab6-worker-2 running started=2026-11-21T19:59:27.326051972Z pid=3041 +20:04:24.835 0 mtusi-lab6-nats-1 running started=2026-11-21T19:22:35.290602429Z pid=17585 +20:04:24.835 2 stop worker: docker compose --env-file .env stop worker +20:04:25.804 2 mtusi-lab6-worker-1 exited started=2026-11-21T19:59:26.716469278Z pid=0 +20:04:25.804 2 mtusi-lab6-worker-2 exited started=2026-11-21T19:59:27.326051972Z pid=0 +20:04:25.844 2 POST /chats/4e63a603-914c-4f47-84d9-6f71057ad639/attachments → 202, attachment_id=5b856079-7c1e-4ee6-af16-55ea0fb2ecd4 status=queued +20:04:26.655 2 job_id=f921ca14-cc40-4095-b8e2-947cda3536c7 pipeline_version=1 attempt=1 status=queued +20:04:26.660 2 GET /attachments/5b856079-7c1e-4ee6-af16-55ea0fb2ecd4/content → 409 (conflict) +20:04:26.669 2 POST message with queued attachment → 201, message_id=b5591933-2e47-4a34-ac47-3fc0e74efa09 +20:04:26.676 2 POST plain message (bob) → 201, message_id=997c604c-7e4e-4905-b77b-1cb751db2d6f; history works while worker is down +20:04:27.372 2 job published to JetStream: stream_seq=786 (outbox → relay → publish ack) +20:04:27.372 3 restart broker (volume natsdata kept) and API replicas: restart nats; restart api +20:04:33.763 3 mtusi-lab6-api-1 running started=2026-11-21T20:04:31.946056134Z pid=25862 +20:04:33.763 3 mtusi-lab6-api-2 running started=2026-11-21T20:04:31.715486281Z pid=25806 +20:04:33.763 3 mtusi-lab6-nats-1 running started=2026-11-21T20:04:27.663048481Z pid=25426 +20:04:33.771 3 after restart: attachment 5b856079-7c1e-4ee6-af16-55ea0fb2ecd4 status=queued (job survived in PostgreSQL + JetStream) +20:04:33.771 3 start worker: docker compose --env-file .env start worker +20:04:43.551 3 attachment 5b856079-7c1e-4ee6-af16-55ea0fb2ecd4 status=ready 1.6s after worker start; variants=['crop 128x128', 'optimized 320x200', 'thumbnail 256x160'] +20:04:43.710 3 original sha256=8355144458298115… (= uploaded), thumbnail JPEG (256, 160) +20:04:44.426 log 20:04:25.840 enqueued attempt=1 token=None {'outbox_id': 744} +20:04:44.426 log 20:04:25.847 published attempt=1 token=None {'relay': 'api-api-a0e7e8a8', 'duplicate': False, 'outbox_id': 744, 'stream_seq': 786} +20:04:44.426 log 20:04:43.087 claimed attempt=1 token=779 {'claims': 1} +20:04:44.426 log 20:04:43.463 committed attempt=1 token=779 {'variants': ['crop', 'optimized', 'thumbnail']} +20:04:44.426 log 20:04:43.463 published_version_changed attempt=1 token=779 {'to': 1, 'from': None} +20:04:44.426 log 20:04:43.469 staging_cleaned attempt=1 token=None {'after': 'ready'} +PASS: defense scenario (worker down → 202 → 409 → restart API+broker → worker → ready) +exit=0 diff --git a/evidence/failover-1.txt b/evidence/failover-1.txt new file mode 100644 index 00000000..3d3e0ce1 --- /dev/null +++ b/evidence/failover-1.txt @@ -0,0 +1,6 @@ +# 2026-11-21T19:19:16Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +$ python3 tests/resilience.py --mode failover --action-script scripts/stop-one.sh --base-url http://127.0.0.1:8080 +Executing explicit failover hook; hook output suppressed to avoid leaking secrets. +{"observed_instances_before": 2, "successful_writes": 131, "failed_attempts": 0, "first_recovery_seconds": 6.14} +PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence. +exit=0 diff --git a/evidence/failover-2.txt b/evidence/failover-2.txt new file mode 100644 index 00000000..4b50c0b6 --- /dev/null +++ b/evidence/failover-2.txt @@ -0,0 +1,6 @@ +# 2026-11-21T19:19:41Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +$ python3 tests/resilience.py --mode failover --action-script scripts/stop-one.sh --base-url http://127.0.0.1:8080 +Executing explicit failover hook; hook output suppressed to avoid leaking secrets. +{"observed_instances_before": 2, "successful_writes": 134, "failed_attempts": 0, "first_recovery_seconds": 6.155} +PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence. +exit=0 diff --git a/evidence/failover-hook.txt b/evidence/failover-hook.txt new file mode 100644 index 00000000..dbc7ebe2 --- /dev/null +++ b/evidence/failover-hook.txt @@ -0,0 +1,80 @@ +== 2026-11-21T19:19:19Z stop-one target=api-e4ae9e90 container=mtusi-lab6-api-2 +api mtusi-lab6-api-1 status=running started=2026-11-21T18:59:39.635658169Z pid=11662 +api mtusi-lab6-api-2 status=running started=2026-11-21T18:59:39.827025415Z pid=11715 +api-ttl mtusi-lab6-api-ttl-1 status=running started=2026-11-21T18:59:43.740476992Z pid=12265 +broker-init mtusi-lab6-broker-init-1 status=exited started=2026-11-21T19:01:47.611250271Z pid=0 +grafana mtusi-lab6-grafana-1 status=running started=2026-11-21T18:59:16.762720587Z pid=9695 +lb mtusi-lab6-lb-1 status=running started=2026-11-21T18:59:47.866767668Z pid=12973 +loki mtusi-lab6-loki-1 status=running started=2026-11-21T19:13:42.511623661Z pid=4940 +migrate mtusi-lab6-migrate-1 status=exited started=2026-11-21T19:01:47.4337162Z pid=0 +nats mtusi-lab6-nats-1 status=running started=2026-11-21T18:59:16.3703735Z pid=9466 +otel-collector mtusi-lab6-otel-collector-1 status=running started=2026-11-21T19:15:52.258053507Z pid=14597 +postgres mtusi-lab6-postgres-1 status=running started=2026-11-21T18:59:16.571171922Z pid=9614 +prometheus mtusi-lab6-prometheus-1 status=running started=2026-11-21T18:59:16.516798581Z pid=9552 +redis mtusi-lab6-redis-1 status=running started=2026-11-21T18:59:16.497489889Z pid=9550 +s3 mtusi-lab6-s3-1 status=running started=2026-11-21T18:59:17.609330359Z pid=9960 +s3-init mtusi-lab6-s3-init-1 status=exited started=2026-11-21T19:01:47.210074838Z pid=0 +tempo mtusi-lab6-tempo-1 status=running started=2026-11-21T19:13:43.331107648Z pid=5112 +tempo-init mtusi-lab6-tempo-init-1 status=exited started=2026-11-21T19:13:42.682492554Z pid=0 +worker mtusi-lab6-worker-1 status=running started=2026-11-21T19:01:50.433806313Z pid=21409 +worker mtusi-lab6-worker-2 status=running started=2026-11-21T19:01:50.6995321Z pid=21486 +== 2026-11-21T19:19:24Z after stop +api mtusi-lab6-api-1 status=running started=2026-11-21T18:59:39.635658169Z pid=11662 +api mtusi-lab6-api-2 status=exited started=2026-11-21T18:59:39.827025415Z pid=0 +api-ttl mtusi-lab6-api-ttl-1 status=running started=2026-11-21T18:59:43.740476992Z pid=12265 +broker-init mtusi-lab6-broker-init-1 status=exited started=2026-11-21T19:01:47.611250271Z pid=0 +grafana mtusi-lab6-grafana-1 status=running started=2026-11-21T18:59:16.762720587Z pid=9695 +lb mtusi-lab6-lb-1 status=running started=2026-11-21T18:59:47.866767668Z pid=12973 +loki mtusi-lab6-loki-1 status=running started=2026-11-21T19:13:42.511623661Z pid=4940 +migrate mtusi-lab6-migrate-1 status=exited started=2026-11-21T19:01:47.4337162Z pid=0 +nats mtusi-lab6-nats-1 status=running started=2026-11-21T18:59:16.3703735Z pid=9466 +otel-collector mtusi-lab6-otel-collector-1 status=running started=2026-11-21T19:15:52.258053507Z pid=14597 +postgres mtusi-lab6-postgres-1 status=running started=2026-11-21T18:59:16.571171922Z pid=9614 +prometheus mtusi-lab6-prometheus-1 status=running started=2026-11-21T18:59:16.516798581Z pid=9552 +redis mtusi-lab6-redis-1 status=running started=2026-11-21T18:59:16.497489889Z pid=9550 +s3 mtusi-lab6-s3-1 status=running started=2026-11-21T18:59:17.609330359Z pid=9960 +s3-init mtusi-lab6-s3-init-1 status=exited started=2026-11-21T19:01:47.210074838Z pid=0 +tempo mtusi-lab6-tempo-1 status=running started=2026-11-21T19:13:43.331107648Z pid=5112 +tempo-init mtusi-lab6-tempo-init-1 status=exited started=2026-11-21T19:13:42.682492554Z pid=0 +worker mtusi-lab6-worker-1 status=running started=2026-11-21T19:01:50.433806313Z pid=21409 +worker mtusi-lab6-worker-2 status=running started=2026-11-21T19:01:50.6995321Z pid=21486 +== 2026-11-21T19:19:44Z stop-one target=api-351cef98 container=mtusi-lab6-api-2 +api mtusi-lab6-api-1 status=running started=2026-11-21T18:59:39.635658169Z pid=11662 +api mtusi-lab6-api-2 status=running started=2026-11-21T19:19:34.682252358Z pid=30558 +api-ttl mtusi-lab6-api-ttl-1 status=running started=2026-11-21T18:59:43.740476992Z pid=12265 +broker-init mtusi-lab6-broker-init-1 status=exited started=2026-11-21T19:01:47.611250271Z pid=0 +grafana mtusi-lab6-grafana-1 status=running started=2026-11-21T18:59:16.762720587Z pid=9695 +lb mtusi-lab6-lb-1 status=running started=2026-11-21T18:59:47.866767668Z pid=12973 +loki mtusi-lab6-loki-1 status=running started=2026-11-21T19:13:42.511623661Z pid=4940 +migrate mtusi-lab6-migrate-1 status=exited started=2026-11-21T19:01:47.4337162Z pid=0 +nats mtusi-lab6-nats-1 status=running started=2026-11-21T18:59:16.3703735Z pid=9466 +otel-collector mtusi-lab6-otel-collector-1 status=running started=2026-11-21T19:15:52.258053507Z pid=14597 +postgres mtusi-lab6-postgres-1 status=running started=2026-11-21T18:59:16.571171922Z pid=9614 +prometheus mtusi-lab6-prometheus-1 status=running started=2026-11-21T18:59:16.516798581Z pid=9552 +redis mtusi-lab6-redis-1 status=running started=2026-11-21T18:59:16.497489889Z pid=9550 +s3 mtusi-lab6-s3-1 status=running started=2026-11-21T18:59:17.609330359Z pid=9960 +s3-init mtusi-lab6-s3-init-1 status=exited started=2026-11-21T19:01:47.210074838Z pid=0 +tempo mtusi-lab6-tempo-1 status=running started=2026-11-21T19:13:43.331107648Z pid=5112 +tempo-init mtusi-lab6-tempo-init-1 status=exited started=2026-11-21T19:13:42.682492554Z pid=0 +worker mtusi-lab6-worker-1 status=running started=2026-11-21T19:01:50.433806313Z pid=21409 +worker mtusi-lab6-worker-2 status=running started=2026-11-21T19:01:50.6995321Z pid=21486 +== 2026-11-21T19:19:49Z after stop +api mtusi-lab6-api-1 status=running started=2026-11-21T18:59:39.635658169Z pid=11662 +api mtusi-lab6-api-2 status=exited started=2026-11-21T19:19:34.682252358Z pid=0 +api-ttl mtusi-lab6-api-ttl-1 status=running started=2026-11-21T18:59:43.740476992Z pid=12265 +broker-init mtusi-lab6-broker-init-1 status=exited started=2026-11-21T19:01:47.611250271Z pid=0 +grafana mtusi-lab6-grafana-1 status=running started=2026-11-21T18:59:16.762720587Z pid=9695 +lb mtusi-lab6-lb-1 status=running started=2026-11-21T18:59:47.866767668Z pid=12973 +loki mtusi-lab6-loki-1 status=running started=2026-11-21T19:13:42.511623661Z pid=4940 +migrate mtusi-lab6-migrate-1 status=exited started=2026-11-21T19:01:47.4337162Z pid=0 +nats mtusi-lab6-nats-1 status=running started=2026-11-21T18:59:16.3703735Z pid=9466 +otel-collector mtusi-lab6-otel-collector-1 status=running started=2026-11-21T19:15:52.258053507Z pid=14597 +postgres mtusi-lab6-postgres-1 status=running started=2026-11-21T18:59:16.571171922Z pid=9614 +prometheus mtusi-lab6-prometheus-1 status=running started=2026-11-21T18:59:16.516798581Z pid=9552 +redis mtusi-lab6-redis-1 status=running started=2026-11-21T18:59:16.497489889Z pid=9550 +s3 mtusi-lab6-s3-1 status=running started=2026-11-21T18:59:17.609330359Z pid=9960 +s3-init mtusi-lab6-s3-init-1 status=exited started=2026-11-21T19:01:47.210074838Z pid=0 +tempo mtusi-lab6-tempo-1 status=running started=2026-11-21T19:13:43.331107648Z pid=5112 +tempo-init mtusi-lab6-tempo-init-1 status=exited started=2026-11-21T19:13:42.682492554Z pid=0 +worker mtusi-lab6-worker-1 status=running started=2026-11-21T19:01:50.433806313Z pid=21409 +worker mtusi-lab6-worker-2 status=running started=2026-11-21T19:01:50.6995321Z pid=21486 diff --git a/evidence/grafana-dashboard.png b/evidence/grafana-dashboard.png new file mode 100644 index 00000000..d13c9782 Binary files /dev/null and b/evidence/grafana-dashboard.png differ diff --git a/evidence/grafana-trace-db-slow.png b/evidence/grafana-trace-db-slow.png new file mode 100644 index 00000000..1d1daa2d Binary files /dev/null and b/evidence/grafana-trace-db-slow.png differ diff --git a/evidence/incident-collector-down.txt b/evidence/incident-collector-down.txt new file mode 100644 index 00000000..3cb7253a --- /dev/null +++ b/evidence/incident-collector-down.txt @@ -0,0 +1,63 @@ +# 2026-11-21T20:10:18Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +$ python3 research/incidents.py collector-down --out evidence/incidents +[23:10:32] collector-down: otel-collector stopped (t=13.9s) +[23:11:08] FIRING OtelCollectorDown at t=50.3s +[23:11:08] collector-down: OtelCollectorDown firing (t=50.3s) +[23:12:05] collector-down: otel-collector started (t=107.1s) +[23:12:21] FIRING TelemetryLostInSdk at t=122.9s +[23:12:21] resolved OtelCollectorDown at t=122.9s +[23:12:21] collector-down: collector back; SDK losses reported (t=122.9s) +{ + "scenario": "collector-down", + "marks_s": { + "otel-collector stopped": 13.9, + "OtelCollectorDown firing": 50.3, + "otel-collector started": 107.1, + "collector back; SDK losses reported": 122.9 + }, + "alerts_first_firing_s": { + "OtelCollectorDown": 50.3, + "TelemetryLostInSdk": 122.9 + }, + "alerts_resolved_s": { + "OtelCollectorDown": 122.9 + }, + "http_before": { + "requests": 108, + "ok": 108, + "errors": 0, + "error_statuses": [], + "p50_ms": 18.2, + "p95_ms": 44.3, + "p99_ms": 76.5 + }, + "http_during": { + "requests": 748, + "ok": 748, + "errors": 0, + "error_statuses": [], + "p50_ms": 12.5, + "p95_ms": 40.4, + "p99_ms": 64.8 + }, + "api_mem_before": { + "8ebba9c6afb2": "46.98MiB", + "5444178a6fc3": "47.37MiB" + }, + "api_mem_during": { + "8ebba9c6afb2": "53.61MiB", + "5444178a6fc3": "54.21MiB" + }, + "sdk_delta": { + "spans_export_failed": 5712, + "spans_queue_dropped": 0, + "logs_export_failed": 715, + "logs_queue_dropped": 0, + "spans_started": 8311 + }, + "sdk_export_errors_by_type_total": { + "MaxRetryError": 5712 + }, + "detection_s": 36.4 +} +exit=0 diff --git a/evidence/incident-db-down.txt b/evidence/incident-db-down.txt new file mode 100644 index 00000000..dbd50090 --- /dev/null +++ b/evidence/incident-db-down.txt @@ -0,0 +1,53 @@ +# 2026-11-21T19:08:20Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +$ python3 research/incidents.py db-down --out evidence/incidents +[22:08:37] db-down: postgres paused (t=16.0s) +[22:09:23] FIRING DbPoolSaturated at t=62.2s +[22:09:59] FIRING ApiHighErrorRate at t=98.0s +[22:09:59] db-down: ApiHighErrorRate firing (t=98.0s) +[22:09:59] db-down: postgres unpaused (t=98.0s) +[22:10:09] resolved DbPoolSaturated at t=108.5s +[22:10:29] FIRING ApiLatencyHigh at t=128.9s +[22:11:10] resolved ApiHighErrorRate at t=169.8s +[22:11:10] resolved ApiLatencyHigh at t=169.8s +[22:11:10] db-down: resolved (t=169.8s) +{ + "scenario": "db-down", + "marks_s": { + "postgres paused": 16.0, + "ApiHighErrorRate firing": 98.0, + "postgres unpaused": 98.0, + "resolved": 169.8 + }, + "alerts_first_firing_s": { + "DbPoolSaturated": 62.2, + "ApiHighErrorRate": 98.0, + "ApiLatencyHigh": 128.9 + }, + "alerts_resolved_s": { + "DbPoolSaturated": 108.5, + "ApiHighErrorRate": 169.8, + "ApiLatencyHigh": 169.8 + }, + "http_during": { + "requests": 136, + "ok": 0, + "errors": 136, + "error_statuses": [ + -1, + 503 + ], + "p50_ms": null, + "p95_ms": null, + "p99_ms": null + }, + "error_traces_error_type": { + "PoolTimeout": 20 + }, + "dependency_unavailable_logs": 136, + "logged_errors": [ + "PoolTimeout", + "TimeoutError" + ], + "detection_s": 82.0 +} +exit=0 diff --git a/evidence/incident-db-slow.txt b/evidence/incident-db-slow.txt new file mode 100644 index 00000000..7f080073 --- /dev/null +++ b/evidence/incident-db-slow.txt @@ -0,0 +1,83 @@ +# 2026-11-21T19:02:34Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +$ python3 research/incidents.py db-slow --out evidence/incidents +[22:03:05] db-slow: postgres limited to 0.03 CPU (t=31.1s) +[22:04:02] FIRING DbSlowQueries at t=87.6s +[22:04:02] db-slow: DbSlowQueries firing (t=87.6s) +[22:04:33] FIRING ApiLatencyHigh at t=118.5s +[22:04:34] db-slow: postgres restored to 1.0 CPU (t=119.2s) +[22:05:30] resolved DbSlowQueries at t=175.5s +[22:05:40] resolved ApiLatencyHigh at t=185.7s +[22:05:40] db-slow: resolved (t=185.7s) +{ + "scenario": "db-slow", + "marks_s": { + "postgres limited to 0.03 CPU": 31.1, + "DbSlowQueries firing": 87.6, + "postgres restored to 1.0 CPU": 119.2, + "resolved": 185.7 + }, + "alerts_first_firing_s": { + "DbSlowQueries": 87.6, + "ApiLatencyHigh": 118.5 + }, + "alerts_resolved_s": { + "DbSlowQueries": 175.5, + "ApiLatencyHigh": 185.7 + }, + "metrics_before": { + "error_ratio": 0.0, + "api_p95_s": 0.0425, + "db_p95_s": 0.0035, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 175.6914 + }, + "metrics_during": { + "error_ratio": 0.0, + "api_p95_s": 0.717, + "db_p95_s": 0.222, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 176.6094 + }, + "slow_trace": { + "trace_id": "0a0efea457d22fb0b498b9fe612a9696", + "duration_ms": 702.1, + "db_ms": 694.4, + "pool_wait_ms": 192.0, + "db_share": 0.99, + "db_or_pool_share": 1.26, + "not_in_child_spans_ms": 7.1, + "error_type": null, + "slowest_child": [ + "INSERT messages", + 300.8 + ] + }, + "http_before": { + "requests": 180, + "ok": 180, + "errors": 0, + "error_statuses": [], + "p50_ms": 11.8, + "p95_ms": 37.6, + "p99_ms": 80.0 + }, + "http_during": { + "requests": 516, + "ok": 516, + "errors": 0, + "error_statuses": [], + "p50_ms": 132.6, + "p95_ms": 698.8, + "p99_ms": 964.9 + }, + "detection_s": 56.5 +} +exit=0 diff --git a/evidence/incident-handler-slow.txt b/evidence/incident-handler-slow.txt new file mode 100644 index 00000000..1bd73dff --- /dev/null +++ b/evidence/incident-handler-slow.txt @@ -0,0 +1,58 @@ +# 2026-11-21T19:05:40Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +$ python3 research/incidents.py handler-slow --out evidence/incidents +[22:05:41] handler-slow: 50% of messages carry fault-api-slow-400 (sleep in handler) (t=0.6s) +[22:07:08] FIRING ApiLatencyHigh at t=87.8s +[22:07:08] handler-slow: ApiLatencyHigh firing (t=87.8s) +[22:08:20] resolved ApiLatencyHigh at t=160.2s +[22:08:20] handler-slow: resolved (t=160.2s) +{ + "scenario": "handler-slow", + "marks_s": { + "50% of messages carry fault-api-slow-400 (sleep in handler)": 0.6, + "ApiLatencyHigh firing": 87.8, + "resolved": 160.2 + }, + "alerts_first_firing_s": { + "ApiLatencyHigh": 87.8 + }, + "alerts_resolved_s": { + "ApiLatencyHigh": 160.2 + }, + "metrics_during": { + "error_ratio": 0.0, + "api_p95_s": 0.475, + "db_p95_s": 0.0026, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.0938 + }, + "db_alert_fired": false, + "slow_trace": { + "trace_id": "2aa39fd46f97f6a25232626dcb3aa263", + "duration_ms": 421.9, + "db_ms": 12.2, + "pool_wait_ms": 3.8, + "db_share": 0.03, + "db_or_pool_share": 0.04, + "not_in_child_spans_ms": 409.2, + "error_type": null, + "slowest_child": [ + "INSERT messages", + 6.6 + ] + }, + "http_during": { + "requests": 526, + "ok": 526, + "errors": 0, + "error_statuses": [], + "p50_ms": 66.4, + "p95_ms": 421.4, + "p99_ms": 440.7 + }, + "detection_s": 87.8 +} +exit=0 diff --git a/evidence/incident-telemetry-down.txt b/evidence/incident-telemetry-down.txt new file mode 100644 index 00000000..1c15c423 --- /dev/null +++ b/evidence/incident-telemetry-down.txt @@ -0,0 +1,59 @@ +# 2026-11-21T19:11:11Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +$ python3 research/incidents.py telemetry-down --out evidence/incidents +[22:11:33] telemetry-down: tempo and loki stopped (t=21.8s) +[22:12:40] FIRING TelemetryExportFailing at t=89.0s +[22:12:40] telemetry-down: TelemetryExportFailing firing (t=89.0s) +[22:13:42] telemetry-down: tempo and loki started (t=150.2s) +[22:13:59] resolved TelemetryExportFailing at t=167.2s +[22:14:04] telemetry-down: resolved, queue drained (t=172.3s) +{ + "scenario": "telemetry-down", + "marks_s": { + "tempo and loki stopped": 21.8, + "TelemetryExportFailing firing": 89.0, + "tempo and loki started": 150.2, + "resolved, queue drained": 172.3 + }, + "alerts_first_firing_s": { + "TelemetryExportFailing": 89.0 + }, + "alerts_resolved_s": { + "TelemetryExportFailing": 167.2 + }, + "http_during": { + "requests": 772, + "ok": 772, + "errors": 0, + "error_statuses": [], + "p50_ms": 13.1, + "p95_ms": 40.2, + "p99_ms": 76.7 + }, + "uploads_during": { + "requests": 42, + "ok": 42, + "errors": 0, + "error_statuses": [], + "p50_ms": 26.6, + "p95_ms": 48.3, + "p99_ms": 217.8 + }, + "collector_mem_before": { + "ac5a65d675df": "50.21MiB" + }, + "collector_mem_during": { + "ac5a65d675df": "54.82MiB" + }, + "exporter_queue_max": 64.0, + "exporter_queue_capacity": 200.0, + "telemetry_delta": { + "accepted_spans": 9907, + "send_failed_spans": 275, + "enqueue_failed_spans": 0, + "send_failed_logs": 30, + "enqueue_failed_logs": 0 + }, + "traces_from_outage_window_found_after_recovery": 200, + "detection_s": 67.2 +} +exit=0 diff --git a/evidence/incident-worker-stop.txt b/evidence/incident-worker-stop.txt new file mode 100644 index 00000000..82305e5f --- /dev/null +++ b/evidence/incident-worker-stop.txt @@ -0,0 +1,50 @@ +# 2026-11-21T18:59:53Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +$ python3 research/incidents.py worker-stop --out evidence/incidents +[22:00:14] worker-stop: worker stopped (t=20.7s) +[22:01:31] FIRING JobQueueLagGrowing at t=98.3s +[22:01:31] FIRING WorkerHeartbeatMissing at t=98.3s +[22:01:31] worker-stop: both alerts firing (t=98.3s) +[22:01:46] worker-stop: worker started (t=113.3s) +[22:02:11] resolved WorkerHeartbeatMissing at t=138.0s +[22:02:32] resolved JobQueueLagGrowing at t=158.5s +[22:02:32] worker-stop: alerts resolved, backlog empty (t=158.5s) +{ + "scenario": "worker-stop", + "marks_s": { + "worker stopped": 20.7, + "both alerts firing": 98.3, + "worker started": 113.3, + "alerts resolved, backlog empty": 158.5 + }, + "alerts_first_firing_s": { + "JobQueueLagGrowing": 98.3, + "WorkerHeartbeatMissing": 98.3 + }, + "alerts_resolved_s": { + "WorkerHeartbeatMissing": 138.0, + "JobQueueLagGrowing": 158.5 + }, + "uploads_accepted": 78, + "uploads_not_ready_after_recovery": 0, + "queue_ready_peak": 34.0, + "api_accepted_logs_during_outage": 46, + "worker_logs_during_outage": 0, + "detection_s": { + "JobQueueLagGrowing": 77.6, + "WorkerHeartbeatMissing": 77.6 + }, + "recovery_s": { + "JobQueueLagGrowing": 45.2, + "WorkerHeartbeatMissing": 24.7 + }, + "http_during_outage": { + "requests": 276, + "ok": 276, + "errors": 0, + "error_statuses": [], + "p50_ms": 15.4, + "p95_ms": 37.4, + "p99_ms": 75.3 + } +} +exit=0 diff --git a/evidence/incidents/collector-down.json b/evidence/incidents/collector-down.json new file mode 100644 index 00000000..d9542965 --- /dev/null +++ b/evidence/incidents/collector-down.json @@ -0,0 +1,240 @@ +{ + "scenario": "collector-down", + "marks_s": { + "otel-collector stopped": 13.9, + "OtelCollectorDown firing": 50.3, + "otel-collector started": 107.1, + "collector back; SDK losses reported": 122.9 + }, + "alerts_first_firing_s": { + "OtelCollectorDown": 50.3, + "TelemetryLostInSdk": 122.9 + }, + "alerts_resolved_s": { + "OtelCollectorDown": 122.9 + }, + "http_before": { + "requests": 108, + "ok": 108, + "errors": 0, + "error_statuses": [], + "p50_ms": 18.2, + "p95_ms": 44.3, + "p99_ms": 76.5 + }, + "http_during": { + "requests": 748, + "ok": 748, + "errors": 0, + "error_statuses": [], + "p50_ms": 12.5, + "p95_ms": 40.4, + "p99_ms": 64.8 + }, + "api_mem_before": { + "8ebba9c6afb2": "46.98MiB", + "5444178a6fc3": "47.37MiB" + }, + "api_mem_during": { + "8ebba9c6afb2": "53.61MiB", + "5444178a6fc3": "54.21MiB" + }, + "sdk_delta": { + "spans_export_failed": 5712, + "spans_queue_dropped": 0, + "logs_export_failed": 715, + "logs_queue_dropped": 0, + "spans_started": 8311 + }, + "sdk_export_errors_by_type_total": { + "MaxRetryError": 5712 + }, + "detection_s": 36.4, + "timeline": [ + { + "t": 0.6, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": 0.0228, + "db_p95_s": 0.0041, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 183.6406 + }, + { + "t": 14.5, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": 0.0231, + "db_p95_s": 0.0043, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 183.6523 + }, + { + "t": 19.6, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": 0.0231, + "db_p95_s": 0.0043, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 183.6523 + }, + { + "t": 24.7, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": 0.0235, + "db_p95_s": 0.0042, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": null, + "collector_rss_mib": null + }, + { + "t": 29.8, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": 0.0235, + "db_p95_s": 0.0043, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": null, + "collector_rss_mib": null + }, + { + "t": 34.9, + "alerts": { + "OtelCollectorDown": "pending" + }, + "error_ratio": 0.0, + "api_p95_s": 0.0213, + "db_p95_s": 0.0043, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": null, + "db_pool_waiting_api": 0.0, + "collector_queue": null, + "collector_rss_mib": null + }, + { + "t": 40.0, + "alerts": { + "OtelCollectorDown": "pending" + }, + "error_ratio": 0.0, + "api_p95_s": 0.0213, + "db_p95_s": 0.0044, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": null, + "db_pool_waiting_api": 0.0, + "collector_queue": null, + "collector_rss_mib": null + }, + { + "t": 45.1, + "alerts": { + "OtelCollectorDown": "pending" + }, + "error_ratio": 0.0, + "api_p95_s": 0.0235, + "db_p95_s": 0.0044, + "queue_lag_s": 0.0, + "queue_ready": null, + "workers_capacity": null, + "db_pool_waiting_api": null, + "collector_queue": null, + "collector_rss_mib": null + }, + { + "t": 50.3, + "alerts": { + "OtelCollectorDown": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.0235, + "db_p95_s": 0.0046, + "queue_lag_s": 0.0, + "queue_ready": null, + "workers_capacity": null, + "db_pool_waiting_api": null, + "collector_queue": null, + "collector_rss_mib": null + }, + { + "t": 107.6, + "alerts": { + "OtelCollectorDown": "firing" + }, + "error_ratio": null, + "api_p95_s": null, + "db_p95_s": null, + "queue_lag_s": null, + "queue_ready": null, + "workers_capacity": null, + "db_pool_waiting_api": null, + "collector_queue": null, + "collector_rss_mib": null + }, + { + "t": 112.7, + "alerts": { + "OtelCollectorDown": "firing" + }, + "error_ratio": null, + "api_p95_s": null, + "db_p95_s": null, + "queue_lag_s": null, + "queue_ready": 0.0, + "workers_capacity": null, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 159.4648 + }, + { + "t": 117.8, + "alerts": { + "OtelCollectorDown": "firing" + }, + "error_ratio": null, + "api_p95_s": null, + "db_p95_s": null, + "queue_lag_s": null, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 159.4648 + }, + { + "t": 122.9, + "alerts": { + "TelemetryLostInSdk": "firing" + }, + "error_ratio": null, + "api_p95_s": null, + "db_p95_s": 0.0043, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 163.0742 + } + ] +} \ No newline at end of file diff --git a/evidence/incidents/db-down.json b/evidence/incidents/db-down.json new file mode 100644 index 00000000..2c242157 --- /dev/null +++ b/evidence/incidents/db-down.json @@ -0,0 +1,559 @@ +{ + "scenario": "db-down", + "marks_s": { + "postgres paused": 16.0, + "ApiHighErrorRate firing": 98.0, + "postgres unpaused": 98.0, + "resolved": 169.8 + }, + "alerts_first_firing_s": { + "DbPoolSaturated": 62.2, + "ApiHighErrorRate": 98.0, + "ApiLatencyHigh": 128.9 + }, + "alerts_resolved_s": { + "DbPoolSaturated": 108.5, + "ApiHighErrorRate": 169.8, + "ApiLatencyHigh": 169.8 + }, + "http_during": { + "requests": 136, + "ok": 0, + "errors": 136, + "error_statuses": [ + -1, + 503 + ], + "p50_ms": null, + "p95_ms": null, + "p99_ms": null + }, + "error_traces_error_type": { + "PoolTimeout": 20 + }, + "dependency_unavailable_logs": 136, + "logged_errors": [ + "PoolTimeout", + "TimeoutError" + ], + "detection_s": 82.0, + "timeline": [ + { + "t": 1.0, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": null, + "db_p95_s": 0.0022, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.2734 + }, + { + "t": 16.3, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": 0.0236, + "db_p95_s": 0.0036, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.3008 + }, + { + "t": 21.4, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": 0.0534, + "db_p95_s": 0.0036, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.3008 + }, + { + "t": 26.5, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": 0.0534, + "db_p95_s": 0.0038, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 13.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.3008 + }, + { + "t": 31.6, + "alerts": { + "DbPoolSaturated": "pending" + }, + "error_ratio": 0.0, + "api_p95_s": 0.0459, + "db_p95_s": 0.0039, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 13.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.3008 + }, + { + "t": 36.7, + "alerts": { + "DbPoolSaturated": "pending" + }, + "error_ratio": 0.0, + "api_p95_s": 0.0459, + "db_p95_s": 0.0041, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 40.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.3008 + }, + { + "t": 41.8, + "alerts": { + "DbPoolSaturated": "pending" + }, + "error_ratio": 0.0, + "api_p95_s": 0.0459, + "db_p95_s": 0.0042, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 40.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.3203 + }, + { + "t": 46.9, + "alerts": { + "DbPoolSaturated": "pending" + }, + "error_ratio": 0.0, + "api_p95_s": 0.0459, + "db_p95_s": 0.0043, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 81.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.3203 + }, + { + "t": 52.0, + "alerts": { + "DbPoolSaturated": "pending" + }, + "error_ratio": 0.0, + "api_p95_s": 0.0459, + "db_p95_s": 0.0044, + "queue_lag_s": 0.0, + "queue_ready": null, + "workers_capacity": 4.0, + "db_pool_waiting_api": 81.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.3281 + }, + { + "t": 57.1, + "alerts": { + "DbPoolSaturated": "pending" + }, + "error_ratio": 0.0, + "api_p95_s": 0.0459, + "db_p95_s": 0.0045, + "queue_lag_s": 0.0, + "queue_ready": null, + "workers_capacity": 4.0, + "db_pool_waiting_api": 123.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.3281 + }, + { + "t": 62.2, + "alerts": { + "DbPoolSaturated": "firing" + }, + "error_ratio": 0.2997, + "api_p95_s": 2.2498, + "db_p95_s": 0.0044, + "queue_lag_s": null, + "queue_ready": null, + "workers_capacity": 4.0, + "db_pool_waiting_api": 123.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.3359 + }, + { + "t": 67.3, + "alerts": { + "ApiHighErrorRate": "pending", + "ApiLatencyHigh": "pending", + "DbPoolSaturated": "firing" + }, + "error_ratio": 0.2997, + "api_p95_s": 2.2498, + "db_p95_s": 0.0046, + "queue_lag_s": null, + "queue_ready": null, + "workers_capacity": 4.0, + "db_pool_waiting_api": 165.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.3359 + }, + { + "t": 72.4, + "alerts": { + "ApiHighErrorRate": "pending", + "ApiLatencyHigh": "pending", + "DbPoolSaturated": "firing" + }, + "error_ratio": 0.6868, + "api_p95_s": 2.3908, + "db_p95_s": 5.0, + "queue_lag_s": null, + "queue_ready": null, + "workers_capacity": 4.0, + "db_pool_waiting_api": 197.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.3438 + }, + { + "t": 77.5, + "alerts": { + "ApiHighErrorRate": "pending", + "ApiLatencyHigh": "pending", + "DbSlowQueries": "pending", + "DbPoolSaturated": "firing" + }, + "error_ratio": 0.6868, + "api_p95_s": 2.3908, + "db_p95_s": 5.0, + "queue_lag_s": null, + "queue_ready": null, + "workers_capacity": 4.0, + "db_pool_waiting_api": 205.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.3438 + }, + { + "t": 82.7, + "alerts": { + "ApiHighErrorRate": "pending", + "ApiLatencyHigh": "pending", + "DbSlowQueries": "pending", + "DbPoolSaturated": "firing" + }, + "error_ratio": 1.0, + "api_p95_s": 2.425, + "db_p95_s": 5.0, + "queue_lag_s": null, + "queue_ready": null, + "workers_capacity": 4.0, + "db_pool_waiting_api": 240.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.4102 + }, + { + "t": 87.8, + "alerts": { + "ApiHighErrorRate": "pending", + "ApiLatencyHigh": "pending", + "DbPoolSaturated": "firing" + }, + "error_ratio": 1.0, + "api_p95_s": 2.425, + "db_p95_s": null, + "queue_lag_s": null, + "queue_ready": null, + "workers_capacity": 4.0, + "db_pool_waiting_api": 247.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.4102 + }, + { + "t": 92.9, + "alerts": { + "ApiHighErrorRate": "pending", + "ApiLatencyHigh": "pending", + "DbPoolSaturated": "firing" + }, + "error_ratio": 1.0, + "api_p95_s": 2.425, + "db_p95_s": null, + "queue_lag_s": null, + "queue_ready": null, + "workers_capacity": 4.0, + "db_pool_waiting_api": 285.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.4141 + }, + { + "t": 98.0, + "alerts": { + "ApiHighErrorRate": "firing", + "ApiLatencyHigh": "pending", + "DbPoolSaturated": "firing" + }, + "error_ratio": 1.0, + "api_p95_s": 2.425, + "db_p95_s": null, + "queue_lag_s": null, + "queue_ready": null, + "workers_capacity": 4.0, + "db_pool_waiting_api": 294.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.4141 + }, + { + "t": 98.3, + "alerts": { + "ApiHighErrorRate": "firing", + "ApiLatencyHigh": "pending", + "DbPoolSaturated": "firing" + }, + "error_ratio": 1.0, + "api_p95_s": 2.425, + "db_p95_s": null, + "queue_lag_s": null, + "queue_ready": null, + "workers_capacity": 4.0, + "db_pool_waiting_api": 294.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.4805 + }, + { + "t": 103.4, + "alerts": { + "ApiHighErrorRate": "firing", + "ApiLatencyHigh": "pending", + "DbPoolSaturated": "firing" + }, + "error_ratio": 1.0, + "api_p95_s": 2.425, + "db_p95_s": 5.0, + "queue_lag_s": null, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 60.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.4805 + }, + { + "t": 108.5, + "alerts": { + "ApiHighErrorRate": "firing", + "ApiLatencyHigh": "pending" + }, + "error_ratio": 0.7833, + "api_p95_s": 2.4348, + "db_p95_s": 0.0444, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.4883 + }, + { + "t": 113.6, + "alerts": { + "ApiHighErrorRate": "firing", + "ApiLatencyHigh": "pending" + }, + "error_ratio": 0.7833, + "api_p95_s": 2.4348, + "db_p95_s": 0.0057, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.4883 + }, + { + "t": 118.7, + "alerts": { + "ApiHighErrorRate": "firing", + "ApiLatencyHigh": "pending" + }, + "error_ratio": 0.4654, + "api_p95_s": 2.376, + "db_p95_s": 0.005, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.5039 + }, + { + "t": 123.8, + "alerts": { + "ApiHighErrorRate": "firing", + "ApiLatencyHigh": "pending" + }, + "error_ratio": 0.4654, + "api_p95_s": 2.376, + "db_p95_s": 0.0048, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.5039 + }, + { + "t": 128.9, + "alerts": { + "ApiHighErrorRate": "firing", + "ApiLatencyHigh": "firing" + }, + "error_ratio": 0.2822, + "api_p95_s": 2.2791, + "db_p95_s": 0.0048, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.5078 + }, + { + "t": 134.0, + "alerts": { + "ApiHighErrorRate": "firing", + "ApiLatencyHigh": "firing" + }, + "error_ratio": 0.2822, + "api_p95_s": 2.2791, + "db_p95_s": 0.0046, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.5078 + }, + { + "t": 139.1, + "alerts": { + "ApiHighErrorRate": "firing", + "ApiLatencyHigh": "firing" + }, + "error_ratio": 0.1529, + "api_p95_s": 2.0672, + "db_p95_s": 0.0045, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.5117 + }, + { + "t": 144.2, + "alerts": { + "ApiHighErrorRate": "firing", + "ApiLatencyHigh": "firing" + }, + "error_ratio": 0.1529, + "api_p95_s": 2.0672, + "db_p95_s": 0.0042, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.5117 + }, + { + "t": 149.3, + "alerts": { + "ApiHighErrorRate": "firing", + "ApiLatencyHigh": "firing" + }, + "error_ratio": 0.0636, + "api_p95_s": 1.361, + "db_p95_s": 0.0042, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.5781 + }, + { + "t": 154.5, + "alerts": { + "ApiHighErrorRate": "firing", + "ApiLatencyHigh": "firing" + }, + "error_ratio": 0.0636, + "api_p95_s": 1.361, + "db_p95_s": 0.0037, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.5781 + }, + { + "t": 159.6, + "alerts": { + "ApiHighErrorRate": "firing", + "ApiLatencyHigh": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.0376, + "db_p95_s": 0.0036, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.582 + }, + { + "t": 164.7, + "alerts": { + "ApiHighErrorRate": "firing", + "ApiLatencyHigh": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.0376, + "db_p95_s": 0.0034, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.582 + }, + { + "t": 169.8, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": 0.025, + "db_p95_s": 0.0034, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.5898 + } + ] +} \ No newline at end of file diff --git a/evidence/incidents/db-slow.json b/evidence/incidents/db-slow.json new file mode 100644 index 00000000..faac5df0 --- /dev/null +++ b/evidence/incidents/db-slow.json @@ -0,0 +1,595 @@ +{ + "scenario": "db-slow", + "marks_s": { + "postgres limited to 0.03 CPU": 31.1, + "DbSlowQueries firing": 87.6, + "postgres restored to 1.0 CPU": 119.2, + "resolved": 185.7 + }, + "alerts_first_firing_s": { + "DbSlowQueries": 87.6, + "ApiLatencyHigh": 118.5 + }, + "alerts_resolved_s": { + "DbSlowQueries": 175.5, + "ApiLatencyHigh": 185.7 + }, + "metrics_before": { + "error_ratio": 0.0, + "api_p95_s": 0.0425, + "db_p95_s": 0.0035, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 175.6914 + }, + "metrics_during": { + "error_ratio": 0.0, + "api_p95_s": 0.717, + "db_p95_s": 0.222, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 176.6094 + }, + "slow_trace": { + "trace_id": "0a0efea457d22fb0b498b9fe612a9696", + "duration_ms": 702.1, + "db_ms": 694.4, + "pool_wait_ms": 192.0, + "db_share": 0.99, + "db_or_pool_share": 1.26, + "not_in_child_spans_ms": 7.1, + "error_type": null, + "slowest_child": [ + "INSERT messages", + 300.8 + ] + }, + "http_before": { + "requests": 180, + "ok": 180, + "errors": 0, + "error_statuses": [], + "p50_ms": 11.8, + "p95_ms": 37.6, + "p99_ms": 80.0 + }, + "http_during": { + "requests": 516, + "ok": 516, + "errors": 0, + "error_statuses": [], + "p50_ms": 132.6, + "p95_ms": 698.8, + "p99_ms": 964.9 + }, + "detection_s": 56.5, + "timeline": [ + { + "t": 1.0, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": 0.0544, + "db_p95_s": 0.005, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 175.4531 + }, + { + "t": 31.2, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": 0.0425, + "db_p95_s": 0.0035, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 175.6914 + }, + { + "t": 36.4, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": 0.0269, + "db_p95_s": 0.0035, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 175.7148 + }, + { + "t": 41.5, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": 0.0269, + "db_p95_s": 0.0047, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 175.7148 + }, + { + "t": 46.6, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": 0.2729, + "db_p95_s": 0.005, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 175.7266 + }, + { + "t": 51.9, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": 0.2729, + "db_p95_s": 0.0726, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 175.7266 + }, + { + "t": 57.0, + "alerts": { + "ApiLatencyHigh": "pending", + "DbSlowQueries": "pending" + }, + "error_ratio": 0.0, + "api_p95_s": 0.5339, + "db_p95_s": 0.0791, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 175.8438 + }, + { + "t": 62.1, + "alerts": { + "ApiLatencyHigh": "pending", + "DbSlowQueries": "pending" + }, + "error_ratio": 0.0, + "api_p95_s": 0.5339, + "db_p95_s": 0.1444, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 175.8438 + }, + { + "t": 67.2, + "alerts": { + "ApiLatencyHigh": "pending", + "DbSlowQueries": "pending" + }, + "error_ratio": 0.0, + "api_p95_s": 0.6597, + "db_p95_s": 0.1504, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 175.9023 + }, + { + "t": 72.3, + "alerts": { + "ApiLatencyHigh": "pending", + "DbSlowQueries": "pending" + }, + "error_ratio": 0.0, + "api_p95_s": 0.6597, + "db_p95_s": 0.1842, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 175.9023 + }, + { + "t": 77.4, + "alerts": { + "ApiLatencyHigh": "pending", + "DbSlowQueries": "pending" + }, + "error_ratio": 0.0, + "api_p95_s": 0.6884, + "db_p95_s": 0.1885, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 176.2773 + }, + { + "t": 82.5, + "alerts": { + "ApiLatencyHigh": "pending", + "DbSlowQueries": "pending" + }, + "error_ratio": 0.0, + "api_p95_s": 0.6884, + "db_p95_s": 0.2102, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 176.2773 + }, + { + "t": 87.6, + "alerts": { + "ApiLatencyHigh": "pending", + "DbSlowQueries": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.7136, + "db_p95_s": 0.2115, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 176.2969 + }, + { + "t": 87.7, + "alerts": { + "ApiLatencyHigh": "pending", + "DbSlowQueries": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.7136, + "db_p95_s": 0.2145, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 176.2969 + }, + { + "t": 92.8, + "alerts": { + "ApiLatencyHigh": "pending", + "DbSlowQueries": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.7136, + "db_p95_s": 0.2277, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 176.2969 + }, + { + "t": 97.9, + "alerts": { + "ApiLatencyHigh": "pending", + "DbSlowQueries": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.7451, + "db_p95_s": 0.2309, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 176.3086 + }, + { + "t": 103.0, + "alerts": { + "ApiLatencyHigh": "pending", + "DbSlowQueries": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.7451, + "db_p95_s": 0.2263, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 176.3086 + }, + { + "t": 108.1, + "alerts": { + "ApiLatencyHigh": "pending", + "DbSlowQueries": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.7562, + "db_p95_s": 0.2251, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 176.3164 + }, + { + "t": 113.2, + "alerts": { + "ApiLatencyHigh": "pending", + "DbSlowQueries": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.7562, + "db_p95_s": 0.2219, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 176.3164 + }, + { + "t": 118.5, + "alerts": { + "ApiLatencyHigh": "firing", + "DbSlowQueries": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.717, + "db_p95_s": 0.2241, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 176.6094 + }, + { + "t": 119.3, + "alerts": { + "ApiLatencyHigh": "firing", + "DbSlowQueries": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.717, + "db_p95_s": 0.222, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 176.6094 + }, + { + "t": 124.4, + "alerts": { + "ApiLatencyHigh": "firing", + "DbSlowQueries": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.717, + "db_p95_s": 0.2215, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 179.6484 + }, + { + "t": 129.5, + "alerts": { + "ApiLatencyHigh": "firing", + "DbSlowQueries": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.7344, + "db_p95_s": 0.208, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 179.6484 + }, + { + "t": 134.6, + "alerts": { + "ApiLatencyHigh": "firing", + "DbSlowQueries": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.7082, + "db_p95_s": 0.2056, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 180.0391 + }, + { + "t": 139.7, + "alerts": { + "ApiLatencyHigh": "firing", + "DbSlowQueries": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.7082, + "db_p95_s": 0.1648, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 180.0391 + }, + { + "t": 144.8, + "alerts": { + "ApiLatencyHigh": "firing", + "DbSlowQueries": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.5781, + "db_p95_s": 0.1538, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 180.0508 + }, + { + "t": 149.9, + "alerts": { + "ApiLatencyHigh": "firing", + "DbSlowQueries": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.5781, + "db_p95_s": 0.1125, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 180.0508 + }, + { + "t": 155.1, + "alerts": { + "ApiLatencyHigh": "firing", + "DbSlowQueries": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.55, + "db_p95_s": 0.0996, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 180.0703 + }, + { + "t": 160.2, + "alerts": { + "ApiLatencyHigh": "firing", + "DbSlowQueries": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.55, + "db_p95_s": 0.0728, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 180.0703 + }, + { + "t": 165.3, + "alerts": { + "ApiLatencyHigh": "firing", + "DbSlowQueries": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.425, + "db_p95_s": 0.0652, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 180.0703 + }, + { + "t": 170.4, + "alerts": { + "ApiLatencyHigh": "firing", + "DbSlowQueries": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.425, + "db_p95_s": 0.0035, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 180.0703 + }, + { + "t": 175.5, + "alerts": { + "ApiLatencyHigh": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.0273, + "db_p95_s": 0.0031, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 180.168 + }, + { + "t": 180.6, + "alerts": { + "ApiLatencyHigh": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.0273, + "db_p95_s": 0.0028, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 180.168 + }, + { + "t": 185.7, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": 0.0241, + "db_p95_s": 0.0028, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 180.4141 + } + ] +} \ No newline at end of file diff --git a/evidence/incidents/handler-slow.json b/evidence/incidents/handler-slow.json new file mode 100644 index 00000000..606e5849 --- /dev/null +++ b/evidence/incidents/handler-slow.json @@ -0,0 +1,533 @@ +{ + "scenario": "handler-slow", + "marks_s": { + "50% of messages carry fault-api-slow-400 (sleep in handler)": 0.6, + "ApiLatencyHigh firing": 87.8, + "resolved": 160.2 + }, + "alerts_first_firing_s": { + "ApiLatencyHigh": 87.8 + }, + "alerts_resolved_s": { + "ApiLatencyHigh": 160.2 + }, + "metrics_during": { + "error_ratio": 0.0, + "api_p95_s": 0.475, + "db_p95_s": 0.0026, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.0938 + }, + "db_alert_fired": false, + "slow_trace": { + "trace_id": "2aa39fd46f97f6a25232626dcb3aa263", + "duration_ms": 421.9, + "db_ms": 12.2, + "pool_wait_ms": 3.8, + "db_share": 0.03, + "db_or_pool_share": 0.04, + "not_in_child_spans_ms": 409.2, + "error_type": null, + "slowest_child": [ + "INSERT messages", + 6.6 + ] + }, + "http_during": { + "requests": 526, + "ok": 526, + "errors": 0, + "error_statuses": [], + "p50_ms": 66.4, + "p95_ms": 421.4, + "p99_ms": 440.7 + }, + "detection_s": 87.8, + "timeline": [ + { + "t": 0.8, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": 0.0241, + "db_p95_s": 0.0028, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 180.4141 + }, + { + "t": 5.9, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": 0.0241, + "db_p95_s": 0.003, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 180.4141 + }, + { + "t": 11.0, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": 0.0252, + "db_p95_s": 0.003, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 180.4219 + }, + { + "t": 16.2, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": 0.0252, + "db_p95_s": 0.0031, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 180.4219 + }, + { + "t": 21.2, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": 0.3904, + "db_p95_s": 0.0031, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 180.4922 + }, + { + "t": 26.3, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": 0.3904, + "db_p95_s": 0.0031, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 180.4922 + }, + { + "t": 31.4, + "alerts": { + "ApiLatencyHigh": "pending" + }, + "error_ratio": 0.0, + "api_p95_s": 0.4418, + "db_p95_s": 0.0031, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 180.5508 + }, + { + "t": 36.5, + "alerts": { + "ApiLatencyHigh": "pending" + }, + "error_ratio": 0.0, + "api_p95_s": 0.4418, + "db_p95_s": 0.0028, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 180.5508 + }, + { + "t": 41.6, + "alerts": { + "ApiLatencyHigh": "pending" + }, + "error_ratio": 0.0, + "api_p95_s": 0.4604, + "db_p95_s": 0.0028, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 180.6172 + }, + { + "t": 46.7, + "alerts": { + "ApiLatencyHigh": "pending" + }, + "error_ratio": 0.0, + "api_p95_s": 0.4604, + "db_p95_s": 0.0028, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 180.6172 + }, + { + "t": 51.8, + "alerts": { + "ApiLatencyHigh": "pending" + }, + "error_ratio": 0.0, + "api_p95_s": 0.47, + "db_p95_s": 0.0029, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 180.707 + }, + { + "t": 56.9, + "alerts": { + "ApiLatencyHigh": "pending" + }, + "error_ratio": 0.0, + "api_p95_s": 0.47, + "db_p95_s": 0.0026, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 180.707 + }, + { + "t": 62.1, + "alerts": { + "ApiLatencyHigh": "pending" + }, + "error_ratio": 0.0, + "api_p95_s": 0.475, + "db_p95_s": 0.0025, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 1.0, + "collector_rss_mib": 181.0078 + }, + { + "t": 67.1, + "alerts": { + "ApiLatencyHigh": "pending" + }, + "error_ratio": 0.0, + "api_p95_s": 0.475, + "db_p95_s": 0.0028, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 1.0, + "collector_rss_mib": 181.0078 + }, + { + "t": 72.2, + "alerts": { + "ApiLatencyHigh": "pending" + }, + "error_ratio": 0.0, + "api_p95_s": 0.475, + "db_p95_s": 0.0027, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 1.0, + "collector_rss_mib": 181.0234 + }, + { + "t": 77.4, + "alerts": { + "ApiLatencyHigh": "pending" + }, + "error_ratio": 0.0, + "api_p95_s": 0.475, + "db_p95_s": 0.0026, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 1.0, + "collector_rss_mib": 181.0234 + }, + { + "t": 82.6, + "alerts": { + "ApiLatencyHigh": "pending" + }, + "error_ratio": 0.0, + "api_p95_s": 0.475, + "db_p95_s": 0.0026, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.0938 + }, + { + "t": 87.8, + "alerts": { + "ApiLatencyHigh": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.475, + "db_p95_s": 0.0026, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.0938 + }, + { + "t": 88.5, + "alerts": { + "ApiLatencyHigh": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.475, + "db_p95_s": 0.0026, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.0938 + }, + { + "t": 93.6, + "alerts": { + "ApiLatencyHigh": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.475, + "db_p95_s": 0.0025, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 1.0, + "collector_rss_mib": 181.1016 + }, + { + "t": 98.7, + "alerts": { + "ApiLatencyHigh": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.4752, + "db_p95_s": 0.0025, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.1055 + }, + { + "t": 103.8, + "alerts": { + "ApiLatencyHigh": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.4752, + "db_p95_s": 0.0025, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.1055 + }, + { + "t": 108.9, + "alerts": { + "ApiLatencyHigh": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.4752, + "db_p95_s": 0.0025, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.1055 + }, + { + "t": 114.0, + "alerts": { + "ApiLatencyHigh": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.4752, + "db_p95_s": 0.0024, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.1055 + }, + { + "t": 119.2, + "alerts": { + "ApiLatencyHigh": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.4753, + "db_p95_s": 0.0023, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.1055 + }, + { + "t": 124.3, + "alerts": { + "ApiLatencyHigh": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.4753, + "db_p95_s": 0.0023, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.1055 + }, + { + "t": 129.4, + "alerts": { + "ApiLatencyHigh": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.4755, + "db_p95_s": 0.0023, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.1094 + }, + { + "t": 134.5, + "alerts": { + "ApiLatencyHigh": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.4755, + "db_p95_s": 0.0022, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.1094 + }, + { + "t": 139.6, + "alerts": { + "ApiLatencyHigh": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.4762, + "db_p95_s": 0.0021, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.1133 + }, + { + "t": 144.7, + "alerts": { + "ApiLatencyHigh": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.4762, + "db_p95_s": 0.0021, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.1133 + }, + { + "t": 149.8, + "alerts": { + "ApiLatencyHigh": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": null, + "db_p95_s": 0.002, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.1289 + }, + { + "t": 155.1, + "alerts": { + "ApiLatencyHigh": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": null, + "db_p95_s": 0.0021, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.1289 + }, + { + "t": 160.2, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": null, + "db_p95_s": 0.0022, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 181.2734 + } + ] +} \ No newline at end of file diff --git a/evidence/incidents/telemetry-down.json b/evidence/incidents/telemetry-down.json new file mode 100644 index 00000000..d84d1143 --- /dev/null +++ b/evidence/incidents/telemetry-down.json @@ -0,0 +1,306 @@ +{ + "scenario": "telemetry-down", + "marks_s": { + "tempo and loki stopped": 21.8, + "TelemetryExportFailing firing": 89.0, + "tempo and loki started": 150.2, + "resolved, queue drained": 172.3 + }, + "alerts_first_firing_s": { + "TelemetryExportFailing": 89.0 + }, + "alerts_resolved_s": { + "TelemetryExportFailing": 167.2 + }, + "http_during": { + "requests": 772, + "ok": 772, + "errors": 0, + "error_statuses": [], + "p50_ms": 13.1, + "p95_ms": 40.2, + "p99_ms": 76.7 + }, + "uploads_during": { + "requests": 42, + "ok": 42, + "errors": 0, + "error_statuses": [], + "p50_ms": 26.6, + "p95_ms": 48.3, + "p99_ms": 217.8 + }, + "collector_mem_before": { + "ac5a65d675df": "50.21MiB" + }, + "collector_mem_during": { + "ac5a65d675df": "54.82MiB" + }, + "exporter_queue_max": 64.0, + "exporter_queue_capacity": 200.0, + "telemetry_delta": { + "accepted_spans": 9907, + "send_failed_spans": 275, + "enqueue_failed_spans": 0, + "send_failed_logs": 30, + "enqueue_failed_logs": 0 + }, + "traces_from_outage_window_found_after_recovery": 200, + "detection_s": 67.2, + "timeline": [ + { + "t": 27.5, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": 0.0384, + "db_p95_s": 0.0041, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 4.0, + "collector_rss_mib": 181.6172 + }, + { + "t": 32.6, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": 0.0384, + "db_p95_s": 0.0043, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 4.0, + "collector_rss_mib": 181.6172 + }, + { + "t": 37.7, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": 0.0388, + "db_p95_s": 0.0043, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 14.0, + "collector_rss_mib": 181.6875 + }, + { + "t": 42.8, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": 0.0388, + "db_p95_s": 0.0044, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 14.0, + "collector_rss_mib": 181.6875 + }, + { + "t": 47.9, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": 0.0403, + "db_p95_s": 0.0044, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 24.0, + "collector_rss_mib": 181.7656 + }, + { + "t": 53.0, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": 0.0403, + "db_p95_s": 0.0046, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 24.0, + "collector_rss_mib": 181.7656 + }, + { + "t": 58.1, + "alerts": { + "TelemetryExportFailing": "pending" + }, + "error_ratio": 0.0, + "api_p95_s": 0.0423, + "db_p95_s": 0.0046, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 34.0, + "collector_rss_mib": 181.7695 + }, + { + "t": 63.2, + "alerts": { + "TelemetryExportFailing": "pending" + }, + "error_ratio": 0.0, + "api_p95_s": 0.0423, + "db_p95_s": 0.0048, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 34.0, + "collector_rss_mib": 181.7695 + }, + { + "t": 68.4, + "alerts": { + "TelemetryExportFailing": "pending" + }, + "error_ratio": 0.0, + "api_p95_s": 0.0458, + "db_p95_s": 0.0048, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 44.0, + "collector_rss_mib": 181.7695 + }, + { + "t": 73.7, + "alerts": { + "TelemetryExportFailing": "pending" + }, + "error_ratio": 0.0, + "api_p95_s": 0.0458, + "db_p95_s": 0.0046, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 44.0, + "collector_rss_mib": 181.7695 + }, + { + "t": 78.8, + "alerts": { + "TelemetryExportFailing": "pending" + }, + "error_ratio": 0.0, + "api_p95_s": 0.0435, + "db_p95_s": 0.0046, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 54.0, + "collector_rss_mib": 181.7695 + }, + { + "t": 83.9, + "alerts": { + "TelemetryExportFailing": "pending" + }, + "error_ratio": 0.0, + "api_p95_s": 0.0435, + "db_p95_s": 0.0044, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 54.0, + "collector_rss_mib": 181.7695 + }, + { + "t": 89.0, + "alerts": { + "TelemetryExportFailing": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.0406, + "db_p95_s": 0.0044, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 64.0, + "collector_rss_mib": 182.1641 + }, + { + "t": 151.9, + "alerts": { + "TelemetryExportFailing": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.0423, + "db_p95_s": 0.0042, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 120.0, + "collector_rss_mib": 186.1523 + }, + { + "t": 157.0, + "alerts": { + "TelemetryExportFailing": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.0423, + "db_p95_s": 0.0042, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 120.0, + "collector_rss_mib": 186.1523 + }, + { + "t": 162.1, + "alerts": { + "TelemetryExportFailing": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.042, + "db_p95_s": 0.0046, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 1.0, + "collector_rss_mib": 190.9453 + }, + { + "t": 167.2, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": 0.042, + "db_p95_s": 0.0047, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 1.0, + "collector_rss_mib": 190.9453 + }, + { + "t": 172.3, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": 0.0435, + "db_p95_s": 0.0046, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 192.2148 + } + ] +} \ No newline at end of file diff --git a/evidence/incidents/worker-stop.json b/evidence/incidents/worker-stop.json new file mode 100644 index 00000000..90287b7b --- /dev/null +++ b/evidence/incidents/worker-stop.json @@ -0,0 +1,414 @@ +{ + "scenario": "worker-stop", + "marks_s": { + "worker stopped": 20.7, + "both alerts firing": 98.3, + "worker started": 113.3, + "alerts resolved, backlog empty": 158.5 + }, + "alerts_first_firing_s": { + "JobQueueLagGrowing": 98.3, + "WorkerHeartbeatMissing": 98.3 + }, + "alerts_resolved_s": { + "WorkerHeartbeatMissing": 138.0, + "JobQueueLagGrowing": 158.5 + }, + "uploads_accepted": 78, + "uploads_not_ready_after_recovery": 0, + "queue_ready_peak": 34.0, + "api_accepted_logs_during_outage": 46, + "worker_logs_during_outage": 0, + "detection_s": { + "JobQueueLagGrowing": 77.6, + "WorkerHeartbeatMissing": 77.6 + }, + "recovery_s": { + "JobQueueLagGrowing": 45.2, + "WorkerHeartbeatMissing": 24.7 + }, + "http_during_outage": { + "requests": 276, + "ok": 276, + "errors": 0, + "error_statuses": [], + "p50_ms": 15.4, + "p95_ms": 37.4, + "p99_ms": 75.3 + }, + "timeline": [ + { + "t": 0.7, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": null, + "db_p95_s": 0.0025, + "queue_lag_s": null, + "queue_ready": 0.0, + "workers_capacity": null, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 159.8984 + }, + { + "t": 21.6, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": 0.131, + "db_p95_s": 0.0049, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 166.1602 + }, + { + "t": 26.6, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": 0.0483, + "db_p95_s": 0.0049, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 167.8047 + }, + { + "t": 31.7, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": 0.0483, + "db_p95_s": 0.0047, + "queue_lag_s": 0.0, + "queue_ready": 2.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 167.8047 + }, + { + "t": 36.8, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": 0.0436, + "db_p95_s": 0.0047, + "queue_lag_s": 7.0425, + "queue_ready": 4.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 168.8203 + }, + { + "t": 41.9, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": 0.0436, + "db_p95_s": 0.0045, + "queue_lag_s": 7.0425, + "queue_ready": 7.0, + "workers_capacity": null, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 168.8203 + }, + { + "t": 47.0, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": 0.0433, + "db_p95_s": 0.0045, + "queue_lag_s": 17.0557, + "queue_ready": 9.0, + "workers_capacity": null, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 169.0859 + }, + { + "t": 52.1, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": 0.0433, + "db_p95_s": 0.0045, + "queue_lag_s": 17.0557, + "queue_ready": 12.0, + "workers_capacity": null, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 169.0859 + }, + { + "t": 57.2, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": 0.0408, + "db_p95_s": 0.0045, + "queue_lag_s": 27.0656, + "queue_ready": 14.0, + "workers_capacity": null, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 171.043 + }, + { + "t": 62.3, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": 0.0408, + "db_p95_s": 0.004, + "queue_lag_s": 27.0656, + "queue_ready": 17.0, + "workers_capacity": null, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 171.043 + }, + { + "t": 67.6, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": 0.0393, + "db_p95_s": 0.004, + "queue_lag_s": 37.0758, + "queue_ready": 19.0, + "workers_capacity": null, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 173.8867 + }, + { + "t": 72.8, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": 0.0393, + "db_p95_s": 0.0037, + "queue_lag_s": 37.0758, + "queue_ready": 22.0, + "workers_capacity": null, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 173.8867 + }, + { + "t": 77.9, + "alerts": { + "JobQueueLagGrowing": "pending", + "WorkerHeartbeatMissing": "pending" + }, + "error_ratio": 0.0, + "api_p95_s": 0.0342, + "db_p95_s": 0.0037, + "queue_lag_s": 47.1036, + "queue_ready": 24.0, + "workers_capacity": null, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 174.7188 + }, + { + "t": 83.0, + "alerts": { + "JobQueueLagGrowing": "pending", + "WorkerHeartbeatMissing": "pending" + }, + "error_ratio": 0.0, + "api_p95_s": 0.0342, + "db_p95_s": 0.0044, + "queue_lag_s": 47.1036, + "queue_ready": 27.0, + "workers_capacity": null, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 174.7188 + }, + { + "t": 88.1, + "alerts": { + "JobQueueLagGrowing": "pending", + "WorkerHeartbeatMissing": "pending" + }, + "error_ratio": 0.0, + "api_p95_s": 0.045, + "db_p95_s": 0.0044, + "queue_lag_s": 57.1166, + "queue_ready": 29.0, + "workers_capacity": null, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 174.9297 + }, + { + "t": 93.2, + "alerts": { + "JobQueueLagGrowing": "pending", + "WorkerHeartbeatMissing": "pending" + }, + "error_ratio": 0.0, + "api_p95_s": 0.045, + "db_p95_s": 0.0046, + "queue_lag_s": 57.1166, + "queue_ready": 32.0, + "workers_capacity": null, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 174.9297 + }, + { + "t": 98.3, + "alerts": { + "JobQueueLagGrowing": "firing", + "WorkerHeartbeatMissing": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.0488, + "db_p95_s": 0.0045, + "queue_lag_s": 67.1494, + "queue_ready": 34.0, + "workers_capacity": null, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 174.9727 + }, + { + "t": 117.5, + "alerts": { + "JobQueueLagGrowing": "firing", + "WorkerHeartbeatMissing": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.0491, + "db_p95_s": 0.0047, + "queue_lag_s": 87.1689, + "queue_ready": 43.0, + "workers_capacity": null, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 175.1758 + }, + { + "t": 122.6, + "alerts": { + "JobQueueLagGrowing": "firing", + "WorkerHeartbeatMissing": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.0491, + "db_p95_s": 0.0048, + "queue_lag_s": 87.1689, + "queue_ready": 46.0, + "workers_capacity": null, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 175.1758 + }, + { + "t": 127.7, + "alerts": { + "JobQueueLagGrowing": "firing", + "WorkerHeartbeatMissing": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.0557, + "db_p95_s": 0.0048, + "queue_lag_s": 97.1806, + "queue_ready": 48.0, + "workers_capacity": null, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 175.3164 + }, + { + "t": 132.8, + "alerts": { + "JobQueueLagGrowing": "firing", + "WorkerHeartbeatMissing": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.0557, + "db_p95_s": 0.0054, + "queue_lag_s": 97.1806, + "queue_ready": 48.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 175.3164 + }, + { + "t": 138.0, + "alerts": { + "JobQueueLagGrowing": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.055, + "db_p95_s": 0.0054, + "queue_lag_s": 56.1344, + "queue_ready": 28.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 175.3711 + }, + { + "t": 143.2, + "alerts": { + "JobQueueLagGrowing": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.055, + "db_p95_s": 0.0068, + "queue_lag_s": 56.1344, + "queue_ready": 14.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 175.3711 + }, + { + "t": 148.3, + "alerts": { + "JobQueueLagGrowing": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.055, + "db_p95_s": 0.007, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 175.4375 + }, + { + "t": 153.4, + "alerts": { + "JobQueueLagGrowing": "firing" + }, + "error_ratio": 0.0, + "api_p95_s": 0.055, + "db_p95_s": 0.0061, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 175.4375 + }, + { + "t": 158.5, + "alerts": {}, + "error_ratio": 0.0, + "api_p95_s": 0.0544, + "db_p95_s": 0.0061, + "queue_lag_s": 0.0, + "queue_ready": 0.0, + "workers_capacity": 4.0, + "db_pool_waiting_api": 0.0, + "collector_queue": 0.0, + "collector_rss_mib": 175.4531 + } + ] +} \ No newline at end of file diff --git a/evidence/jobs-failed.txt b/evidence/jobs-failed.txt new file mode 100644 index 00000000..67e4c59c --- /dev/null +++ b/evidence/jobs-failed.txt @@ -0,0 +1,44 @@ +# 2026-11-21T20:01:39Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +$ dc exec -T api python -m messenger jobs failed --limit 20 +{ + "failed": [ + { + "job_id": "7e27c9a9-3142-404f-9bcb-2a10665b3aec", + "attachment_id": "ba26c359-2438-45eb-a463-68caec1cff88", + "pipeline_version": 1, + "error_code": "invalid_image", + "error_detail": "OSError: broken data stream when reading image file", + "attempt": 1, + "claims": 1, + "replays": 0, + "failed_at": "2026-11-21 19:27:10.802973+00:00", + "replayable": false + }, + { + "job_id": "00a3a193-62a9-4bd4-8f88-8af124640677", + "attachment_id": "901dd139-d599-4177-bad1-afd7bae63828", + "pipeline_version": 1, + "error_code": "invalid_image", + "error_detail": "OSError: broken data stream when reading image file", + "attempt": 2, + "claims": 1, + "replays": 1, + "failed_at": "2026-11-21 19:21:16.636634+00:00", + "replayable": true + }, + { + "job_id": "da0acd1e-ac00-40e5-9351-0a5abd717d40", + "attachment_id": "fee90bba-4e47-4779-98ce-c506f351f6f7", + "pipeline_version": 1, + "error_code": "invalid_image", + "error_detail": "OSError: broken data stream when reading image file", + "attempt": 1, + "claims": 1, + "replays": 0, + "failed_at": "2026-11-21 19:21:04.496141+00:00", + "replayable": true + } + ], + "count": 3 +} +exit=0 diff --git a/evidence/jobs-invariants.txt b/evidence/jobs-invariants.txt new file mode 100644 index 00000000..30c46435 --- /dev/null +++ b/evidence/jobs-invariants.txt @@ -0,0 +1,24 @@ +# 2026-11-21T20:01:40Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +$ dc exec -T api python -m messenger jobs invariants --settled --verify-bytes +{ + "ok": true, + "violations": {}, + "violation_counts": {}, + "stats": { + "attachments": 696, + "jobs": 701, + "variants": 2091, + "events": 4394, + "job_status": { + "failed": 3, + "ready": 696, + "superseded": 2 + }, + "attachment_status": { + "failed": 3, + "ready": 693 + }, + "s3_objects": 2786 + } +} +exit=0 diff --git a/evidence/load.json b/evidence/load.json new file mode 100644 index 00000000..a1079a3a --- /dev/null +++ b/evidence/load.json @@ -0,0 +1,17 @@ +{ + "lab": 6, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.062, + "concurrency": 4, + "successful_requests": 5438, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 180.893, + "successful_latency_ms": { + "p50": 16.941, + "p95": 53.059, + "p99": 107.154 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/load.txt b/evidence/load.txt new file mode 100644 index 00000000..6f11257e --- /dev/null +++ b/evidence/load.txt @@ -0,0 +1,20 @@ +# 2026-11-21T20:01:49Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +$ python3 tests/load.py --base-url http://127.0.0.1:8080 --duration 30 --concurrency 4 --output evidence/load.json +{ + "lab": 6, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.062, + "concurrency": 4, + "successful_requests": 5438, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 180.893, + "successful_latency_ms": { + "p50": 16.941, + "p95": 53.059, + "p99": 107.154 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} +exit=0 diff --git a/evidence/make-check.txt b/evidence/make-check.txt new file mode 100644 index 00000000..e9f5f56f --- /dev/null +++ b/evidence/make-check.txt @@ -0,0 +1,5 @@ +# 2026-11-21T18:58:12Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +$ make check +python3 scripts/check_contract.py +PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. +exit=0 diff --git a/evidence/migrations-rerun.txt b/evidence/migrations-rerun.txt new file mode 100644 index 00000000..d80fcdf6 --- /dev/null +++ b/evidence/migrations-rerun.txt @@ -0,0 +1,6 @@ +# 2026-11-21T20:01:47Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +$ dc run --rm --no-deps migrate + Container mtusi-lab6-migrate-run-08460db58929 Creating + Container mtusi-lab6-migrate-run-08460db58929 Created +{"applied": []} +exit=0 diff --git a/evidence/migrations.txt b/evidence/migrations.txt new file mode 100644 index 00000000..080cfc6b --- /dev/null +++ b/evidence/migrations.txt @@ -0,0 +1,20 @@ +# 2026-11-21T18:58:11Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +$ sh -c docker compose --env-file .env exec -T postgres psql -U messenger -d messenger -c 'SELECT version, left(checksum,12) AS checksum, applied_at FROM schema_migrations ORDER BY version'; docker compose --env-file .env logs --no-log-prefix migrate + version | checksum | applied_at +--------------------------------+--------------+------------------------------- + 0001_init | 64c1576d88cc | 2026-11-21 18:57:54.841805+00 + 0002_cache_invalidation_outbox | fcebf1c9345a | 2026-11-21 18:57:54.850032+00 + 0003_idempotency_keys | e2564612d780 | 2026-11-21 18:57:54.856713+00 + 0004_attachments | 52090521af1b | 2026-11-21 18:57:54.880215+00 + 0005_jobs | 34e5b9a70f4d | 2026-11-21 18:57:54.906048+00 + 0006_observability | b56c84655e84 | 2026-11-21 18:57:54.909758+00 +(6 rows) + +{"ts": "2026-11-21T18:57:54.844Z", "level": "info", "service": "messenger", "logger": "messenger.db", "event": "migration applied", "msg": "migration applied", "version": "0001_init"} +{"ts": "2026-11-21T18:57:54.850Z", "level": "info", "service": "messenger", "logger": "messenger.db", "event": "migration applied", "msg": "migration applied", "version": "0002_cache_invalidation_outbox"} +{"ts": "2026-11-21T18:57:54.858Z", "level": "info", "service": "messenger", "logger": "messenger.db", "event": "migration applied", "msg": "migration applied", "version": "0003_idempotency_keys"} +{"ts": "2026-11-21T18:57:54.881Z", "level": "info", "service": "messenger", "logger": "messenger.db", "event": "migration applied", "msg": "migration applied", "version": "0004_attachments"} +{"ts": "2026-11-21T18:57:54.907Z", "level": "info", "service": "messenger", "logger": "messenger.db", "event": "migration applied", "msg": "migration applied", "version": "0005_jobs"} +{"ts": "2026-11-21T18:57:54.910Z", "level": "info", "service": "messenger", "logger": "messenger.db", "event": "migration applied", "msg": "migration applied", "version": "0006_observability"} +{"applied": ["0001_init", "0002_cache_invalidation_outbox", "0003_idempotency_keys", "0004_attachments", "0005_jobs", "0006_observability"]} +exit=0 diff --git a/evidence/no-local-files.txt b/evidence/no-local-files.txt new file mode 100644 index 00000000..1c091216 --- /dev/null +++ b/evidence/no-local-files.txt @@ -0,0 +1,7 @@ +# 2026-11-21T18:58:11Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +$ sh -c for c in $(docker compose --env-file .env ps -q api worker); do docker inspect -f '{{.Name}} ReadonlyRootfs={{.HostConfig.ReadonlyRootfs}} Tmpfs={{json .HostConfig.Tmpfs}} Mounts={{range .Mounts}}{{.Type}}:{{.Destination}} {{end}}' $c; done +/mtusi-lab6-api-1 ReadonlyRootfs=true Tmpfs={"/tmp":""} Mounts=bind:/run/secrets/broker_url bind:/run/secrets/cache_url bind:/run/secrets/database_url bind:/run/secrets/s3_access_key_id bind:/run/secrets/s3_secret_access_key +/mtusi-lab6-api-2 ReadonlyRootfs=true Tmpfs={"/tmp":""} Mounts=bind:/run/secrets/broker_url bind:/run/secrets/cache_url bind:/run/secrets/database_url bind:/run/secrets/s3_access_key_id bind:/run/secrets/s3_secret_access_key +/mtusi-lab6-worker-1 ReadonlyRootfs=true Tmpfs={"/tmp":""} Mounts=bind:/run/secrets/broker_url bind:/run/secrets/database_url bind:/run/secrets/s3_access_key_id bind:/run/secrets/s3_secret_access_key +/mtusi-lab6-worker-2 ReadonlyRootfs=true Tmpfs={"/tmp":""} Mounts=bind:/run/secrets/broker_url bind:/run/secrets/database_url bind:/run/secrets/s3_access_key_id bind:/run/secrets/s3_secret_access_key +exit=0 diff --git a/evidence/observability-final.txt b/evidence/observability-final.txt new file mode 100644 index 00000000..0cdf79ee --- /dev/null +++ b/evidence/observability-final.txt @@ -0,0 +1,79 @@ +# 2026-11-21T20:13:05Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +$ python3 research/obs_snapshot.py +== Grafana 13.3.1 +datasource uid=loki type=loki url=http://loki:3100 readOnly=True health=OK +datasource uid=prometheus type=prometheus url=http://prometheus:9090 readOnly=True health=OK +datasource uid=tempo type=tempo url=http://tempo:3200 readOnly=True health=OK +dashboard uid=messenger-overview provisioned=True panels=33 folder=Messenger + +== Prometheus: правила и состояние +alerting ApiHighErrorRate health=ok state=inactive +alerting ApiLatencyHigh health=ok state=inactive +alerting DbSlowQueries health=ok state=inactive +alerting DbPoolSaturated health=ok state=inactive +alerting JobQueueLagGrowing health=ok state=inactive +alerting WorkerHeartbeatMissing health=ok state=inactive +alerting JobsFailing health=ok state=inactive +alerting TelemetryExportFailing health=ok state=inactive +alerting OtelCollectorDown health=ok state=inactive +alerting TelemetryLostInSdk health=ok state=firing +recording sli:api_requests:rate1m health=ok state=- +recording sli:api_errors:rate1m health=ok state=- +recording sli:api_error_ratio:rate1m health=ok state=- +recording sli:api_latency_p95:1m health=ok state=- +recording sli:api_fast_ratio:rate5m health=ok state=- +recording sli:time_to_ready_fast_ratio:rate15m health=ok state=- +recording sli:queue_lag_seconds:max health=ok state=- +recording sli:queue_oldest_age_seconds:max health=ok state=- + +== Метрики приложения (Prometheus, имя → labels кроме ресурсных) +container_cpu_time_seconds_total series=90 labels= +container_memory_usage_bytes series=90 labels= +db_client_connection_max series=90 labels=db_client_connection_pool_name +db_client_connection_pending_requests series=90 labels=db_client_connection_pool_name +db_client_connection_timeouts_total series=90 labels=db_client_connection_pool_name +db_client_operation_duration_seconds_bucket series=8148 labels=db_operation_name,db_system_name,error_type +http_server_active_requests series=77 labels=http_request_method +http_server_request_duration_seconds_bucket series=5325 labels=http_request_method,http_response_status_class,http_response_status_code,http_route +messenger_attachment_time_to_ready_seconds_bucket series=630 labels=job_type +messenger_broker_ack_pending series=39 labels=queue +messenger_broker_pending series=39 labels=queue +messenger_container_cpu_limit series=90 labels= +messenger_container_memory_limit_bytes series=90 labels= +messenger_db_pool_wait_time_seconds_total series=90 labels=db_client_connection_pool_name +messenger_job_duration_seconds_bucket series=804 labels=job_type,outcome +messenger_job_queue_wait_seconds_bucket series=644 labels=job_type +messenger_jobs_processed_total series=93 labels=job_type,messenger_pipeline_version,outcome +messenger_outbox_lag_seconds series=39 labels=queue +messenger_outbox_pending series=39 labels=queue +messenger_outbox_publish_total series=46 labels=messaging_destination_name,outcome +messenger_queue_depth series=156 labels=queue,state +messenger_queue_lag_seconds series=39 labels=queue +messenger_queue_oldest_age_seconds series=39 labels=queue +messenger_uploads_total series=34 labels=outcome +messenger_worker_busy series=48 labels= +messenger_worker_capacity series=51 labels= +otel_sdk_exporter_span_exported_total series=86 labels=error_type,otel_component_name,otel_component_type,server_address,server_port +otel_sdk_exporter_span_inflight series=82 labels=otel_component_name,otel_component_type,server_address,server_port +otel_sdk_processor_log_processed_total series=90 labels=otel_component_name,otel_component_type +otel_sdk_processor_log_queue_capacity series=90 labels=otel_component_name,otel_component_type +otel_sdk_processor_log_queue_size series=90 labels=otel_component_name,otel_component_type +otel_sdk_processor_span_processed_total series=82 labels=otel_component_name,otel_component_type +otel_sdk_processor_span_queue_capacity series=90 labels=otel_component_name,otel_component_type +otel_sdk_processor_span_queue_size series=90 labels=otel_component_name,otel_component_type +otel_sdk_span_live series=82 labels=otel_span_sampling_result +otel_sdk_span_started_total series=212 labels=otel_span_parent_origin,otel_span_sampling_result +process_cpu_time_seconds_total series=180 labels=cpu_mode +process_memory_usage_bytes series=90 labels= + +== Loki labels (index): deployment_environment_name,service_instance_id,service_name,service_namespace +пример записи messenger-api: поля=deployment_environment_name,detected_level,duration_ms,event,flags,logger,method,observed_timestamp,request_id,route,scope_name,service_instance_id,service_name,service_namespace,service_version,severity_number,severity_text,span_id,status,telemetry_sdk_language,telemetry_sdk_name,telemetry_sdk_version,trace_id +пример записи messenger-worker: поля=attachment_id,attempt,claims,deployment_environment_name,detected_level,duration_ms,event,flags,job_id,lease_token,logger,observed_timestamp,outcome,pipeline_version,scope_name,service_instance_id,service_name,service_namespace,service_version,severity_number,severity_text,span_id,telemetry_sdk_language,telemetry_sdk_name,telemetry_sdk_version,trace_id + +== Tempo +{ resource.service.name = "messenger-api" && kind = server } traces(1h, limit 20)=20 +{ span.messaging.operation.type = "process" } traces(1h, limit 20)=20 +{ status = error } traces(1h, limit 20)=20 + +== Активные алерты: [["TelemetryLostInSdk", "firing"]] +exit=0 diff --git a/evidence/observability.txt b/evidence/observability.txt new file mode 100644 index 00000000..3a50ab13 --- /dev/null +++ b/evidence/observability.txt @@ -0,0 +1,79 @@ +# 2026-11-21T18:58:47Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +$ python3 research/obs_snapshot.py +== Grafana 13.3.1 +datasource uid=loki type=loki url=http://loki:3100 readOnly=True health=OK +datasource uid=prometheus type=prometheus url=http://prometheus:9090 readOnly=True health=OK +datasource uid=tempo type=tempo url=http://tempo:3200 readOnly=True health=OK +dashboard uid=messenger-overview provisioned=True panels=33 folder=Messenger + +== Prometheus: правила и состояние +alerting ApiHighErrorRate health=ok state=inactive +alerting ApiLatencyHigh health=ok state=inactive +alerting DbSlowQueries health=ok state=inactive +alerting DbPoolSaturated health=ok state=inactive +alerting JobQueueLagGrowing health=ok state=inactive +alerting WorkerHeartbeatMissing health=ok state=inactive +alerting JobsFailing health=ok state=inactive +alerting TelemetryExportFailing health=ok state=inactive +alerting OtelCollectorDown health=ok state=inactive +alerting TelemetryLostInSdk health=ok state=inactive +recording sli:api_requests:rate1m health=ok state=- +recording sli:api_errors:rate1m health=ok state=- +recording sli:api_error_ratio:rate1m health=ok state=- +recording sli:api_latency_p95:1m health=ok state=- +recording sli:api_fast_ratio:rate5m health=ok state=- +recording sli:time_to_ready_fast_ratio:rate15m health=ok state=- +recording sli:queue_lag_seconds:max health=ok state=- +recording sli:queue_oldest_age_seconds:max health=ok state=- + +== Метрики приложения (Prometheus, имя → labels кроме ресурсных) +container_cpu_time_seconds_total series=5 labels= +container_memory_usage_bytes series=5 labels= +db_client_connection_max series=5 labels=db_client_connection_pool_name +db_client_connection_pending_requests series=5 labels=db_client_connection_pool_name +db_client_connection_timeouts_total series=5 labels=db_client_connection_pool_name +db_client_operation_duration_seconds_bucket series=406 labels=db_operation_name,db_system_name +http_server_active_requests series=6 labels=http_request_method +http_server_request_duration_seconds_bucket series=525 labels=http_request_method,http_response_status_class,http_response_status_code,http_route +messenger_attachment_time_to_ready_seconds_bucket series=14 labels=job_type +messenger_broker_ack_pending series=3 labels=queue +messenger_broker_pending series=3 labels=queue +messenger_container_cpu_limit series=5 labels= +messenger_container_memory_limit_bytes series=5 labels= +messenger_db_pool_wait_time_seconds_total series=5 labels=db_client_connection_pool_name +messenger_job_duration_seconds_bucket series=36 labels=job_type,outcome +messenger_job_queue_wait_seconds_bucket series=28 labels=job_type +messenger_jobs_processed_total series=3 labels=job_type,messenger_pipeline_version,outcome +messenger_outbox_lag_seconds series=3 labels=queue +messenger_outbox_pending series=3 labels=queue +messenger_outbox_publish_total series=1 labels=messaging_destination_name,outcome +messenger_queue_depth series=12 labels=queue,state +messenger_queue_lag_seconds series=3 labels=queue +messenger_queue_oldest_age_seconds series=3 labels=queue +messenger_uploads_total series=1 labels=outcome +messenger_worker_busy series=2 labels= +messenger_worker_capacity series=2 labels= +otel_sdk_exporter_span_exported_total series=4 labels=otel_component_name,otel_component_type,server_address,server_port +otel_sdk_exporter_span_inflight series=4 labels=otel_component_name,otel_component_type,server_address,server_port +otel_sdk_processor_log_processed_total series=5 labels=otel_component_name,otel_component_type +otel_sdk_processor_log_queue_capacity series=5 labels=otel_component_name,otel_component_type +otel_sdk_processor_log_queue_size series=5 labels=otel_component_name,otel_component_type +otel_sdk_processor_span_processed_total series=4 labels=otel_component_name,otel_component_type +otel_sdk_processor_span_queue_capacity series=5 labels=otel_component_name,otel_component_type +otel_sdk_processor_span_queue_size series=5 labels=otel_component_name,otel_component_type +otel_sdk_span_live series=4 labels=otel_span_sampling_result +otel_sdk_span_started_total series=9 labels=otel_span_parent_origin,otel_span_sampling_result +process_cpu_time_seconds_total series=10 labels=cpu_mode +process_memory_usage_bytes series=5 labels= + +== Loki labels (index): deployment_environment_name,service_instance_id,service_name,service_namespace +пример записи messenger-api: поля=deployment_environment_name,detected_level,duration_ms,event,flags,logger,method,observed_timestamp,request_id,route,scope_name,service_instance_id,service_name,service_namespace,service_version,severity_number,severity_text,span_id,status,telemetry_sdk_language,telemetry_sdk_name,telemetry_sdk_version,trace_id +пример записи messenger-worker: поля=attachment_id,attempt,claims,deployment_environment_name,detected_level,duration_ms,event,flags,job_id,lease_token,logger,observed_timestamp,outcome,pipeline_version,scope_name,service_instance_id,service_name,service_namespace,service_version,severity_number,severity_text,span_id,telemetry_sdk_language,telemetry_sdk_name,telemetry_sdk_version,trace_id + +== Tempo +{ resource.service.name = "messenger-api" && kind = server } traces(1h, limit 20)=20 +{ span.messaging.operation.type = "process" } traces(1h, limit 20)=3 +{ status = error } traces(1h, limit 20)=1 + +== Активные алерты: [] +exit=0 diff --git a/evidence/persistence.txt b/evidence/persistence.txt new file mode 100644 index 00000000..038a8eef --- /dev/null +++ b/evidence/persistence.txt @@ -0,0 +1,5 @@ +# 2026-11-21T19:20:06Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +$ python3 tests/resilience.py --mode persistence --action-script scripts/restart.sh --base-url http://127.0.0.1:8080 +Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. +exit=0 diff --git a/evidence/published-ports.txt b/evidence/published-ports.txt new file mode 100644 index 00000000..30cb5499 --- /dev/null +++ b/evidence/published-ports.txt @@ -0,0 +1,16 @@ +# 2026-11-21T18:58:12Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +$ sh -c docker compose --env-file .env ps --format '{{.Service}} {{.Ports}}' | sort -u +api 8080/tcp +api-ttl 8080/tcp +grafana 127.0.0.1:3000->3000/tcp +lb 127.0.0.1:8080-8082->8080-8082/tcp, 127.0.0.1:8404->8404/tcp +loki +nats +otel-collector +postgres +prometheus +redis +s3 +tempo +worker 8080/tcp +exit=0 diff --git a/evidence/restart-hook.txt b/evidence/restart-hook.txt new file mode 100644 index 00000000..935c8346 --- /dev/null +++ b/evidence/restart-hook.txt @@ -0,0 +1,54 @@ +== 2026-11-21T19:20:09Z before restart +api mtusi-lab6-api-1 status=running started=2026-11-21T18:59:39.635658169Z pid=11662 +api mtusi-lab6-api-2 status=running started=2026-11-21T19:19:59.867932045Z pid=1029 +api-ttl mtusi-lab6-api-ttl-1 status=running started=2026-11-21T18:59:43.740476992Z pid=12265 +broker-init mtusi-lab6-broker-init-1 status=exited started=2026-11-21T19:01:47.611250271Z pid=0 +grafana mtusi-lab6-grafana-1 status=running started=2026-11-21T18:59:16.762720587Z pid=9695 +lb mtusi-lab6-lb-1 status=running started=2026-11-21T18:59:47.866767668Z pid=12973 +loki mtusi-lab6-loki-1 status=running started=2026-11-21T19:13:42.511623661Z pid=4940 +migrate mtusi-lab6-migrate-1 status=exited started=2026-11-21T19:01:47.4337162Z pid=0 +nats mtusi-lab6-nats-1 status=running started=2026-11-21T18:59:16.3703735Z pid=9466 +otel-collector mtusi-lab6-otel-collector-1 status=running started=2026-11-21T19:15:52.258053507Z pid=14597 +postgres mtusi-lab6-postgres-1 status=running started=2026-11-21T18:59:16.571171922Z pid=9614 +prometheus mtusi-lab6-prometheus-1 status=running started=2026-11-21T18:59:16.516798581Z pid=9552 +redis mtusi-lab6-redis-1 status=running started=2026-11-21T18:59:16.497489889Z pid=9550 +s3 mtusi-lab6-s3-1 status=running started=2026-11-21T18:59:17.609330359Z pid=9960 +s3-init mtusi-lab6-s3-init-1 status=exited started=2026-11-21T19:01:47.210074838Z pid=0 +tempo mtusi-lab6-tempo-1 status=running started=2026-11-21T19:13:43.331107648Z pid=5112 +tempo-init mtusi-lab6-tempo-init-1 status=exited started=2026-11-21T19:13:42.682492554Z pid=0 +worker mtusi-lab6-worker-1 status=running started=2026-11-21T19:01:50.433806313Z pid=21409 +worker mtusi-lab6-worker-2 status=running started=2026-11-21T19:01:50.6995321Z pid=21486 +volume mtusi-lab6_grafanadata +volume mtusi-lab6_lokidata +volume mtusi-lab6_natsdata +volume mtusi-lab6_pgdata +volume mtusi-lab6_promdata +volume mtusi-lab6_s3data +volume mtusi-lab6_tempodata +== 2026-11-21T19:20:55Z after restart +api mtusi-lab6-api-1 status=running started=2026-11-21T19:20:45.594915217Z pid=5946 +api mtusi-lab6-api-2 status=running started=2026-11-21T19:20:45.815634018Z pid=6024 +api-ttl mtusi-lab6-api-ttl-1 status=running started=2026-11-21T19:20:50.234402807Z pid=6546 +broker-init mtusi-lab6-broker-init-1 status=exited started=2026-11-21T19:20:51.342250944Z pid=0 +grafana mtusi-lab6-grafana-1 status=running started=2026-11-21T19:20:19.771295996Z pid=3701 +lb mtusi-lab6-lb-1 status=running started=2026-11-21T19:20:55.229584398Z pid=7289 +loki mtusi-lab6-loki-1 status=running started=2026-11-21T19:20:19.87079258Z pid=3749 +migrate mtusi-lab6-migrate-1 status=exited started=2026-11-21T19:20:51.055582073Z pid=0 +nats mtusi-lab6-nats-1 status=running started=2026-11-21T19:20:19.345071566Z pid=3471 +otel-collector mtusi-lab6-otel-collector-1 status=running started=2026-11-21T19:20:19.600339631Z pid=3638 +postgres mtusi-lab6-postgres-1 status=running started=2026-11-21T19:20:19.616612332Z pid=3639 +prometheus mtusi-lab6-prometheus-1 status=running started=2026-11-21T19:20:19.559626741Z pid=3550 +redis mtusi-lab6-redis-1 status=running started=2026-11-21T19:20:19.354224044Z pid=3469 +s3 mtusi-lab6-s3-1 status=running started=2026-11-21T19:20:20.685593694Z pid=3974 +s3-init mtusi-lab6-s3-init-1 status=exited started=2026-11-21T19:20:50.778768419Z pid=0 +tempo mtusi-lab6-tempo-1 status=running started=2026-11-21T19:20:24.235289508Z pid=4214 +tempo-init mtusi-lab6-tempo-init-1 status=exited started=2026-11-21T19:13:42.682492554Z pid=0 +worker mtusi-lab6-worker-1 status=running started=2026-11-21T19:20:54.082584884Z pid=7103 +worker mtusi-lab6-worker-2 status=running started=2026-11-21T19:20:54.275306102Z pid=7184 +volume mtusi-lab6_grafanadata +volume mtusi-lab6_lokidata +volume mtusi-lab6_natsdata +volume mtusi-lab6_pgdata +volume mtusi-lab6_promdata +volume mtusi-lab6_s3data +volume mtusi-lab6_tempodata diff --git a/evidence/restore-1.txt b/evidence/restore-1.txt new file mode 100644 index 00000000..305ac388 --- /dev/null +++ b/evidence/restore-1.txt @@ -0,0 +1,5 @@ +# 2026-11-21T19:19:34Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +$ ./scripts/start-replicas.sh +api mtusi-lab6-api-1 status=running started=2026-11-21T18:59:39.635658169Z pid=11662 +api mtusi-lab6-api-2 status=running started=2026-11-21T19:19:34.682252358Z pid=30558 +exit=0 diff --git a/evidence/restore-2.txt b/evidence/restore-2.txt new file mode 100644 index 00000000..94820fc6 --- /dev/null +++ b/evidence/restore-2.txt @@ -0,0 +1,5 @@ +# 2026-11-21T19:19:59Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +$ ./scripts/start-replicas.sh +api mtusi-lab6-api-1 status=running started=2026-11-21T18:59:39.635658169Z pid=11662 +api mtusi-lab6-api-2 status=running started=2026-11-21T19:19:59.867932045Z pid=1029 +exit=0 diff --git a/evidence/s3-bootstrap.txt b/evidence/s3-bootstrap.txt new file mode 100644 index 00000000..e8c9c4ba --- /dev/null +++ b/evidence/s3-bootstrap.txt @@ -0,0 +1,4 @@ +# 2026-11-21T18:58:11Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +$ dc logs --no-log-prefix s3-init +{"bucket": "messenger-attachments", "created": true, "checks": {"anonymous ListObjects": ["403", 403, true], "anonymous GetObject": ["403", 403, true], "anonymous PutObject": ["403", 403, true], "anonymous ListBuckets": ["403", 403, true], "api ListObjects own bucket": ["allowed", "allowed", true], "api CreateBucket": ["AccessDenied", "AccessDenied", true]}} +exit=0 diff --git a/evidence/smoke.txt b/evidence/smoke.txt new file mode 100644 index 00000000..73570097 --- /dev/null +++ b/evidence/smoke.txt @@ -0,0 +1,4 @@ +# 2026-11-21T18:58:12Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +$ python3 tests/smoke.py --base-url http://127.0.0.1:8080 +PASS: lab6 public API scenario; infrastructure and grading evidence remain separate. +exit=0 diff --git a/evidence/stack.txt b/evidence/stack.txt new file mode 100644 index 00000000..bbeb696e --- /dev/null +++ b/evidence/stack.txt @@ -0,0 +1,62 @@ +# 2026-11-21T18:58:09Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +docker 29.10.0 +Docker Compose version v5.7.1 +CONTAINER REPOSITORY TAG PLATFORM IMAGE ID SIZE CREATED +mtusi-lab6-api-1 mtusi-lab6-api local linux/amd64 757903805f05 224MB 4 minutes ago +mtusi-lab6-api-2 mtusi-lab6-api local linux/amd64 757903805f05 224MB 4 minutes ago +mtusi-lab6-api-ttl-1 mtusi-lab6-api local linux/amd64 757903805f05 224MB 4 minutes ago +mtusi-lab6-broker-init-1 mtusi-lab6-api local linux/amd64 757903805f05 224MB 4 minutes ago +mtusi-lab6-grafana-1 mtusi-local/grafana 13.3.1 linux/amd64 e5dc6fd6c2e0 2.03GB About an hour ago +mtusi-lab6-lb-1 mtusi-local/haproxy 3.0 linux/amd64 4e29ffb6122e 76.2MB About an hour ago +mtusi-lab6-loki-1 mtusi-local/loki 3.5.3 linux/amd64 4249c0ad0211 208MB About an hour ago +mtusi-lab6-migrate-1 mtusi-lab6-api local linux/amd64 757903805f05 224MB 4 minutes ago +mtusi-lab6-nats-1 mtusi-local/nats 2.11.9 linux/amd64 03b922ee87f1 75MB About an hour ago +mtusi-lab6-otel-collector-1 mtusi-local/otelcol-contrib 0.130.0 linux/amd64 03c06afb86eb 439MB About an hour ago +mtusi-lab6-postgres-1 mtusi-local/postgres 16 linux/amd64 c0a1aa3931fd 595MB About an hour ago +mtusi-lab6-prometheus-1 mtusi-local/prometheus v3.5.0 linux/amd64 b78824a4b58b 487MB About an hour ago +mtusi-lab6-redis-1 mtusi-local/redis 7 linux/amd64 5c0e94c0d499 68.8MB About an hour ago +mtusi-lab6-s3-1 mtusi-local/seaweedfs 4.52 linux/amd64 cec1afdfce84 258MB About an hour ago +mtusi-lab6-s3-init-1 mtusi-lab6-api local linux/amd64 757903805f05 224MB 4 minutes ago +mtusi-lab6-tempo-1 mtusi-local/tempo 2.8.2 linux/amd64 68657d08d39e 183MB About an hour ago +mtusi-lab6-tempo-init-1 mtusi-local/tempo 2.8.2 linux/amd64 68657d08d39e 183MB About an hour ago +mtusi-lab6-worker-1 mtusi-lab6-api local linux/amd64 757903805f05 224MB 4 minutes ago +mtusi-lab6-worker-2 mtusi-lab6-api local linux/amd64 757903805f05 224MB 4 minutes ago +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +mtusi-lab6-api-1 mtusi-lab6-api:local "python -m messenger…" api 23 seconds ago Up 8 seconds (healthy) 8080/tcp +mtusi-lab6-api-2 mtusi-lab6-api:local "python -m messenger…" api 23 seconds ago Up 8 seconds (healthy) 8080/tcp +mtusi-lab6-api-ttl-1 mtusi-lab6-api:local "python -m messenger…" api-ttl 23 seconds ago Up 7 seconds (healthy) 8080/tcp +mtusi-lab6-broker-init-1 mtusi-lab6-api:local "python -m messenger…" broker-init 23 seconds ago Exited (0) 15 seconds ago +mtusi-lab6-grafana-1 mtusi-local/grafana:13.3.1 "/run.sh" grafana 23 seconds ago Up 20 seconds (healthy) 127.0.0.1:3000->3000/tcp +mtusi-lab6-lb-1 mtusi-local/haproxy:3.0 "haproxy -W -db -f /…" lb 23 seconds ago Up 21 seconds (healthy) 127.0.0.1:8080-8082->8080-8082/tcp, 127.0.0.1:8404->8404/tcp +mtusi-lab6-loki-1 mtusi-local/loki:3.5.3 "/usr/bin/loki -conf…" loki 23 seconds ago Up 22 seconds +mtusi-lab6-migrate-1 mtusi-lab6-api:local "python -m messenger…" migrate 23 seconds ago Exited (0) 15 seconds ago +mtusi-lab6-nats-1 mtusi-local/nats:2.11.9 "nats-server --confi…" nats 23 seconds ago Up 22 seconds (healthy) +mtusi-lab6-otel-collector-1 mtusi-local/otelcol-contrib:0.130.0 "/otelcol-contrib --…" otel-collector 23 seconds ago Up 22 seconds +mtusi-lab6-postgres-1 mtusi-local/postgres:16 "docker-entrypoint.s…" postgres 23 seconds ago Up 21 seconds (healthy) +mtusi-lab6-prometheus-1 mtusi-local/prometheus:v3.5.0 "/bin/prometheus --c…" prometheus 23 seconds ago Up 21 seconds (healthy) +mtusi-lab6-redis-1 mtusi-local/redis:7 "sh -c 'umask 077\npr…" redis 23 seconds ago Up 21 seconds (healthy) +mtusi-lab6-s3-1 mtusi-local/seaweedfs:4.52 "/usr/bin/weed -logt…" s3 23 seconds ago Up 21 seconds (healthy) +mtusi-lab6-s3-init-1 mtusi-lab6-api:local "python -m messenger…" s3-init 23 seconds ago Exited (0) 8 seconds ago +mtusi-lab6-tempo-1 mtusi-local/tempo:2.8.2 "/tempo -config.file…" tempo 23 seconds ago Up 20 seconds +mtusi-lab6-tempo-init-1 mtusi-local/tempo:2.8.2 "chown -R 10001:1000…" tempo-init 23 seconds ago Exited (0) 20 seconds ago +mtusi-lab6-worker-1 mtusi-lab6-api:local "python -m messenger…" worker 23 seconds ago Up 7 seconds (healthy) 8080/tcp +mtusi-lab6-worker-2 mtusi-lab6-api:local "python -m messenger…" worker 23 seconds ago Up 7 seconds (healthy) 8080/tcp +api mtusi-lab6-api-1 status=running started=2026-11-21T18:58:01.681543345Z pid=2776 +api mtusi-lab6-api-2 status=running started=2026-11-21T18:58:01.947852642Z pid=2855 +api-ttl mtusi-lab6-api-ttl-1 status=running started=2026-11-21T18:58:02.666248948Z pid=2971 +broker-init mtusi-lab6-broker-init-1 status=exited started=2026-11-21T18:57:53.028494218Z pid=0 +grafana mtusi-lab6-grafana-1 status=running started=2026-11-21T18:57:49.836736597Z pid=1843 +lb mtusi-lab6-lb-1 status=running started=2026-11-21T18:57:49.184169334Z pid=1608 +loki mtusi-lab6-loki-1 status=running started=2026-11-21T18:57:47.68953579Z pid=1092 +migrate mtusi-lab6-migrate-1 status=exited started=2026-11-21T18:57:53.925170786Z pid=0 +nats mtusi-lab6-nats-1 status=running started=2026-11-21T18:57:47.848213347Z pid=1158 +otel-collector mtusi-lab6-otel-collector-1 status=running started=2026-11-21T18:57:48.026547716Z pid=1224 +postgres mtusi-lab6-postgres-1 status=running started=2026-11-21T18:57:48.243808659Z pid=1284 +prometheus mtusi-lab6-prometheus-1 status=running started=2026-11-21T18:57:48.434191714Z pid=1353 +redis mtusi-lab6-redis-1 status=running started=2026-11-21T18:57:48.594620877Z pid=1422 +s3 mtusi-lab6-s3-1 status=running started=2026-11-21T18:57:48.791431799Z pid=1488 +s3-init mtusi-lab6-s3-init-1 status=exited started=2026-11-21T18:57:58.961524292Z pid=0 +tempo mtusi-lab6-tempo-1 status=running started=2026-11-21T18:57:49.684613781Z pid=1776 +tempo-init mtusi-lab6-tempo-init-1 status=exited started=2026-11-21T18:57:48.960422533Z pid=0 +worker mtusi-lab6-worker-1 status=running started=2026-11-21T18:58:02.221002868Z pid=2912 +worker mtusi-lab6-worker-2 status=running started=2026-11-21T18:58:03.071993847Z pid=3046 diff --git a/evidence/test-api.txt b/evidence/test-api.txt new file mode 100644 index 00000000..080f2d64 --- /dev/null +++ b/evidence/test-api.txt @@ -0,0 +1,23 @@ +# 2026-11-21T19:21:35Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +$ python3 student-tests/test_api.py +## API, auth, validation, ACL, transactions (http://127.0.0.1:8080) +PASS password stored only as scrypt KDF hash; User has no secret fields 0.81s +PASS wrong password and unknown user: identical 401 + Basic challenge 0.79s +PASS malformed Basic / Bearer on /auth/sessions / body on login 0.04s +PASS password with ':' and non-ASCII UTF-8 works (RFC 7617) 0.71s +PASS opaque 256-bit token, unique per login, DB stores only SHA-256 1.19s +PASS only Bearer accepted; Basic and X-User-Id never authenticate 0.02s +PASS logout revokes only the current session; repeat -> 401 1.22s +PASS strict JSON validation -> 400 0.03s +PASS message text: 4000 code points OK, 4001 / whitespace / sender_id -> 400 0.03s +PASS SQL is parameterized: injection payloads stored verbatim 0.02s +PASS ACL: outsider gets 404 everywhere (even for invalid body) 0.03s +PASS create chat validation: duplicates, caller missing, unknown member 0.01s +PASS compound create-chat rolls back on FK failure (no orphan chat) 0.84s chats before=16, failed insert left 0 rows +PASS registration race: 20 parallel same username -> exactly one 201 3.90s 201x1, 409x19, rows=1 +PASS keyset pagination: 120 msgs, varying limit, no gaps/duplicates 1.03s 4 pages +PASS chat list: only own chats, ordered, cursor bound to user 0.55s +PASS read-after-write: confirmed message visible to next read 0.01s +PASS unknown route 404 / wrong method 405 in error format 0.00s +summary: 18 passed, 0 failed +exit=0 diff --git a/evidence/test-attachments.txt b/evidence/test-attachments.txt new file mode 100644 index 00000000..ef9b858c --- /dev/null +++ b/evidence/test-attachments.txt @@ -0,0 +1,18 @@ +# 2026-11-21T20:04:44Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +$ python3 student-tests/test_attachments.py +## attachments (http://127.0.0.1:8080) +PASS valid PNG and JPEG: 202 queued → ready, byte-exact download by other member 0.74s +PASS exactly-near limit (~10 MiB) accepted, Content-Length > limit -> 413 0.54s 10.00 MiB accepted +PASS oversize rejected BEFORE body is read (early 413, socket) 0.02s HTTP/1.1 413 Content Too Large in 0.016s, 50 MiB never sent +PASS pixel limit: 8000x6000 header -> 413 without decoding 0.09s 0.092s +PASS decompression bomb: IDAT inflates beyond declared size -> 415 0.32s 65295-byte file claiming 64 MiB raw, rejected in 0.046s +PASS corrupted images -> 415 (truncated, bad CRC, no EOI, garbage, empty) 0.29s 9 variants +PASS MIME spoofing by Content-Type/filename -> 415 0.37s +PASS dangerous/invalid filenames -> 400; filename never becomes a path 0.19s +PASS missing/invalid Content-Length -> 400 (chunked upload is not accepted) 0.00s HTTP/1.1 400 Bad Request +PASS ACL: outsider gets 404 for upload/metadata/content; anonymous 401 0.47s outsider 10 MiB upload rejected in 0.33s +PASS variants (lab5): original/thumbnail/crop/optimized OK after ready, unknown -> 400 0.76s +PASS message: foreign/unknown attachment_id -> 404, file of other chat -> 404, limits -> 400 0.15s +PASS idempotency includes attachment_ids (replay same, conflict on change) 0.19s +summary: 13 passed, 0 failed +exit=0 diff --git a/evidence/test-cache-race.txt b/evidence/test-cache-race.txt new file mode 100644 index 00000000..91066cc0 --- /dev/null +++ b/evidence/test-cache-race.txt @@ -0,0 +1,15 @@ +# 2026-11-21T19:22:05Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +$ dc run --rm --no-deps -T -v /home/claude/work6/mtusi2026lab6/student-tests:/app/student-tests:ro --entrypoint python api student-tests/test_cache_race.py + Container mtusi-lab6-api-run-b1fb72351b97 Creating + Container mtusi-lab6-api-run-b1fb72351b97 Created +PASS read-through put makes entry readable +PASS entry TTL capped by SESSION_CACHE_TTL_SECONDS pttl=60000ms +PASS invalidate removes entry +PASS late put after logout is refused by tombstone +PASS tombstone outlives any cache entry pttl=75000ms +PASS entry never outlives session expiry pttl=1199ms +PASS expired session not served from cache +cache unavailable; falling back to PostgreSQL +PASS degraded mode: cache is not read until outbox drained +summary: all passed +exit=0 diff --git a/evidence/test-expiry.txt b/evidence/test-expiry.txt new file mode 100644 index 00000000..bfdc2c2c --- /dev/null +++ b/evidence/test-expiry.txt @@ -0,0 +1,8 @@ +# 2026-11-21T19:21:55Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +$ python3 student-tests/test_expiry.py +## session expiry, SESSION_TTL_SECONDS=2 (http://127.0.0.1:8081) +PASS expires_at = now + SESSION_TTL_SECONDS 0.97s remaining 2.00s +PASS token valid before expiry, 401 Bearer after (cache warmed) 4.50s +PASS re-login after expiry issues a new valid session 4.60s +summary: 3 passed, 0 failed +exit=0 diff --git a/evidence/test-failures.txt b/evidence/test-failures.txt new file mode 100644 index 00000000..55126b49 --- /dev/null +++ b/evidence/test-failures.txt @@ -0,0 +1,7 @@ +# 2026-11-21T19:28:40Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +$ python3 student-tests/test_failures.py +## dependency failures (http://127.0.0.1:8080) +PASS Redis down: API bypasses cache via PostgreSQL, no anonymous trust 6.96s fallback latency 0.013s; outbox rows during outage=1, drained after recovery +PASS PostgreSQL down: bounded 503 in error format; anonymous still 401 14.93s latency(s)={'ready': 1.51, 'post_message': 2.02, 'history': 2.02, 'login': 2.02, 'register': 2.02}; ready again in 2.2s +summary: 2 passed, 0 failed +exit=0 diff --git a/evidence/test-idempotency.txt b/evidence/test-idempotency.txt new file mode 100644 index 00000000..23e0a083 --- /dev/null +++ b/evidence/test-idempotency.txt @@ -0,0 +1,14 @@ +# 2026-11-21T19:21:49Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +$ python3 student-tests/test_idempotency.py +## idempotency across replicas (http://127.0.0.1:8080) +PASS sequential replays: same 201 + same Message from different replicas 0.39s replicas=2, rows=1 +PASS 30 concurrent POSTs, same key + body, via LB -> exactly one message 1.76s per-replica responses {'api-778c97df': 16, 'api-7c6946d6': 14}, rows=1 +PASS concurrent same key, two different bodies -> one message, others 201-same or 409 1.05s 201x10, 409x10 +PASS after commit: different body -> 409; reordered/whitespace JSON -> replay 0.03s +PASS scope: user + chat + key (same key elsewhere is independent) 0.03s +PASS key format: missing/empty/129 chars/invalid -> 400; 128 chars ok 0.04s +PASS failed attempt does not claim the key (400/404 not recorded) 0.03s +PASS replay re-checks session and access 0.36s +PASS key older than IDEMPOTENCY_TTL_SECONDS is reusable (24 h window) 0.59s +summary: 9 passed, 0 failed +exit=0 diff --git a/evidence/test-imgproc.txt b/evidence/test-imgproc.txt new file mode 100644 index 00000000..779dafb8 --- /dev/null +++ b/evidence/test-imgproc.txt @@ -0,0 +1,14 @@ +# 2026-11-21T19:21:17Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +$ dc run --rm --no-deps -T -v /home/claude/work6/mtusi2026lab6/student-tests:/app/student-tests:ro --entrypoint python worker student-tests/test_imgproc.py + Container mtusi-lab6-worker-run-9cf4e4401d71 Creating + Container mtusi-lab6-worker-run-9cf4e4401d71 Created +PASS fixture 320×200 → thumbnail 256×160, crop 128×128, optimized WebP 320×200 0.81s +PASS rounding down and minimum 1 px: 3000×10 → 256×1, 1280×4 0.26s +PASS EXIF orientation 6 applied (400×200 stored → 128×256); orientation tag not copied 0.26s +PASS alpha composited on white for JPEG variants; WebP keeps alpha 0.26s +PASS metadata removed: EXIF/XMP/ICC of the source are not in any variant 0.29s +PASS deterministic output (same bytes on re-run) — basis of idempotent effect; v2 differs 0.98s +PASS limits: pixels by header (413-class), memory (RLIMIT_AS), undecodable → permanent 0.78s too_large / resource_limit / invalid_image +PASS worker wall-clock timeout kills the subprocess → transient (retry), not a hang 0.25s killed after 0.05s; undecodable → Permanent(invalid_image) +summary: 8 passed, 0 failed +exit=0 diff --git a/evidence/test-jobs-failures.txt b/evidence/test-jobs-failures.txt new file mode 100644 index 00000000..6fe98296 --- /dev/null +++ b/evidence/test-jobs-failures.txt @@ -0,0 +1,19 @@ +# 2026-11-21T20:04:50Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +$ python3 student-tests/test_jobs_failures.py +## pipeline failures (http://127.0.0.1:8080) +PASS defense: worker stopped → 202 → 409 → message ok → restart API+broker (volumes kept) → worker → ready 28.39s attachment 8fdfa0e4: stream held 1→1 msgs across restart; ready 1.9s after worker start +PASS broker down: upload still 202 (job durable in outbox), ready after broker returns 10.26s 202 with broker stopped; events ['enqueued', 'published', 'claimed'] +PASS crash between COMMIT and publish: relay of another process publishes, job reaches ready 23.31s api-fault (api-876964dc) died after COMMIT; published by relay api-api-2ba718cd; events ['enqueued', 'published', 'claimed', 'committed', 'published_version_changed', 'staging_cleaned'] +PASS crash between publish ack and outbox mark: duplicate publish dropped by Nats-Msg-Id 24.24s second publish: duplicate=true, stream_seq=800; processed once +PASS worker crash after claim, before any side effect → lease takeover → ready 23.62s ['enqueued', 'published', 'claimed', 'lease_takeover', 'committed', 'published_version_changed', 'staging_cleaned'] in 23.6s +PASS worker crash after S3 writes, before COMMIT → takeover rewrites the same keys, one result 24.04s ['enqueued', 'published', 'claimed', 'lease_takeover', 'committed', 'published_version_changed', 'staging_cleaned'] in 23.6s; keys deterministic: ['crop.jpg', 'optimized.webp', 'thumbnail.jpg'] +PASS worker crash after COMMIT, before ack → redelivery is a no-op (duplicate_ignored) 22.52s ['enqueued', 'published', 'claimed', 'committed', 'published_version_changed', 'staging_cleaned', 'duplicate_ignored'] +PASS hung worker (event loop blocked 45 s) loses lease; takeover commits; zombie commit is fenced 47.14s claimed t799 → takeover t800 → committed t800; zombie (t799) → lease_lost +PASS long but alive job (35 s > lease 20 s): heartbeat keeps the lease, no takeover, no duplicate 36.32s ready after 36.3s, ['enqueued', 'published', 'claimed', 'committed', 'published_version_changed', 'staging_cleaned'] +PASS transient errors: retry with backoff + jitter (2 failures), then ready 7.10s delays 1.56s, 3.97s (windows [1,2], [2,4]); actual gaps [1.7, 4.01]; attempts [1, 2, 3] +PASS retries exhausted → failed retry_exhausted (in registry) → operator replay → ready 28.29s 5 attempts → retry_exhausted; replay (attempt 6) → ready +PASS processing with expired lease and LOST message → reaper requeues → ready 15.50s purged 1 stream msgs; ['claimed', 'committed', 'published_version_changed', 'staging_cleaned'] +PASS bounded concurrency: never more than replicas × WORKER_CONCURRENCY jobs in processing 18.46s 8 jobs × ~4 s: peak concurrency 4 (limit 4), wall 10.0s +PASS staging removed after ready; failed staging kept until retention, then replay refuses honestly 17.37s ready: staging gone, originals/ present; failed: staging kept, removed after retention; replay refused +summary: 14 passed, 0 failed +exit=0 diff --git a/evidence/test-observability-final.txt b/evidence/test-observability-final.txt new file mode 100644 index 00000000..5850daa6 --- /dev/null +++ b/evidence/test-observability-final.txt @@ -0,0 +1,15 @@ +# 2026-11-21T20:12:41Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +$ python3 student-tests/test_observability.py +## lab6: наблюдаемость — provisioning, сигналы, корреляция, безопасность telemetry +PASS provisioning: Prometheus/Loki/Tempo из Git, health OK 0.05s health OK: prometheus, loki, tempo +PASS provisioning: dashboard импортирован, все запросы панелей выполняются 3.08s 33 панелей, 60 запросов без ошибок, с данными 57 +PASS HTTP: X-Request-Id → структурный лог → trace (server + DB spans) 1.69s request_id → trace 28b17ed52654…, 8 spans (5 DB) +PASS безопасность: пароль, токен, тело сообщения не попадают в логи/трассы 3.81s проверено в Loki и 2 trace: пароль, токен, текст сообщения, Authorization +PASS upload → create → send → process → S3/DB: один trace; лог worker с тем же trace_id 5.56s 55 spans: SERVER→create→send→process(messenger-worker)→S3×4; queue -0.00 с +PASS retry: 2 временные ошибки + успех — три попытки в одном trace 9.66s попытки 1→2→3: ['retry', 'retry', 'ready']; паузы backoff 1.7 с и 3.7 с +PASS метрики контракта: имена, низкая кардинальность, шаблоны маршрутов 0.23s 20 метрик; серий 5254 (HTTP count — 100); маршрутов 12; запрещённых labels нет +PASS метрики отражают обработку: jobs, retry, time-to-ready, p95 из histogram 0.04s ready=16 retry=8 time_to_ready count=16; p95 HTTP 37 мс, p95 ready 2.77 с +PASS алерты: правила загружены и вычисляются без ошибок 0.01s 18 правил (10 алертов), firing сейчас: ['TelemetryLostInSdk'] +PASS SDK: spans/logs не отбрасываются при работающем Collector 0.02s обработано spans 13125, отброшено 0 +summary: 10 passed, 0 failed +exit=0 diff --git a/evidence/test-observability.txt b/evidence/test-observability.txt new file mode 100644 index 00000000..5e47187e --- /dev/null +++ b/evidence/test-observability.txt @@ -0,0 +1,15 @@ +# 2026-11-21T18:58:16Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +$ python3 student-tests/test_observability.py +## lab6: наблюдаемость — provisioning, сигналы, корреляция, безопасность telemetry +PASS provisioning: Prometheus/Loki/Tempo из Git, health OK 0.07s health OK: prometheus, loki, tempo +PASS provisioning: dashboard импортирован, все запросы панелей выполняются 1.23s 33 панелей, 60 запросов без ошибок, с данными 3 +PASS HTTP: X-Request-Id → структурный лог → trace (server + DB spans) 2.75s request_id → trace 2e5e8df8dff7…, 8 spans (5 DB) +PASS безопасность: пароль, токен, тело сообщения не попадают в логи/трассы 2.42s проверено в Loki и 2 trace: пароль, токен, текст сообщения, Authorization +PASS upload → create → send → process → S3/DB: один trace; лог worker с тем же trace_id 11.88s 55 spans: SERVER→create→send→process(messenger-worker)→S3×4; queue 0.00 с +PASS retry: 2 временные ошибки + успех — три попытки в одном trace 9.72s попытки 1→2→3: ['retry', 'retry', 'ready']; паузы backoff 2.0 с и 3.0 с +PASS метрики контракта: имена, низкая кардинальность, шаблоны маршрутов 0.24s 20 метрик; серий 1180 (HTTP count — 35); маршрутов 12; запрещённых labels нет +PASS метрики отражают обработку: jobs, retry, time-to-ready, p95 из histogram 2.12s ready=3 retry=2 time_to_ready count=3; p95 HTTP 466 мс, p95 ready 9.75 с +PASS алерты: правила загружены и вычисляются без ошибок 0.02s 18 правил (10 алертов), firing сейчас: нет +PASS SDK: spans/logs не отбрасываются при работающем Collector 0.02s обработано spans 577, отброшено 0 +summary: 10 passed, 0 failed +exit=0 diff --git a/evidence/test-pipeline.txt b/evidence/test-pipeline.txt new file mode 100644 index 00000000..69cb9ee9 --- /dev/null +++ b/evidence/test-pipeline.txt @@ -0,0 +1,13 @@ +# 2026-11-21T19:20:57Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +$ python3 student-tests/test_pipeline.py +## attachment pipeline (http://127.0.0.1:8080) +PASS upload → 202 queued snapshot, then ready; original byte-exact; three variants by contract 1.20s ready 0.94s after 202; thumbnail 256×160, crop 128×128, optimized 320×200 WebP +PASS big image: optimized fits 1280 without upscale, thumbnail rounds down 1.15s thumbnail 256x170, optimized 1280x852 +PASS EXIF orientation applied (stored 400×200, orientation 6 → 200×400); tiny image not upscaled 2.10s +PASS variant parameter: unknown → 400; default original; outsider → 404 0.67s +PASS undecodable image → failed with safe error_code, no retries; content 409; cannot attach (409) 2.54s events ['enqueued', 'published', 'claimed', 'failed']; listed in failed registry +PASS queued/processing attachment can be attached to a message right away 0.69s +PASS duplicate deliveries of a finished job are no-ops (5 raw duplicates) 6.57s committed ×1, duplicate_ignored ×5, metadata unchanged +PASS replay is safe: ready → noop; failed (permanent) → re-executed once, failed again 3.48s ready: noop; failed: replayed (audit by student) → failed again (permanent error) +summary: 8 passed, 0 failed +exit=0 diff --git a/evidence/test-storage-failures.txt b/evidence/test-storage-failures.txt new file mode 100644 index 00000000..541c78ab --- /dev/null +++ b/evidence/test-storage-failures.txt @@ -0,0 +1,10 @@ +# 2026-11-21T19:27:17Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +$ python3 student-tests/test_storage_failures.py +## object storage failures (http://127.0.0.1:8080) +PASS bucket is private outside API: anonymous GET/LIST/PUT denied, API key limited 5.14s anon GET 403; s3-check 6/6 PASS +PASS S3 down: upload/download 503 fast, text messages and readiness keep working 30.19s 503 in 0.03s/0.02s; after start: reads 4.3s, writes 23.5s +PASS interrupted upload: no object and no intent left behind 10.15s objects 2, intents 1 — unchanged +PASS uploads rejected at the very end (truncated PNG) leave no staging object (race regression) 9.18s 30 × 415 at finish(); staging objects 2 → 2 +PASS crash between staging PUT and DB COMMIT: intent recorded, janitor removes object after grace 26.63s orphan staging/a0244d5cebee… removed 11.2s after crash (grace 10 s) +summary: 5 passed, 0 failed +exit=0 diff --git a/evidence/test-telemetry-persistence.txt b/evidence/test-telemetry-persistence.txt new file mode 100644 index 00000000..2cbc25d8 --- /dev/null +++ b/evidence/test-telemetry-persistence.txt @@ -0,0 +1,9 @@ +# 2026-11-21T18:58:48Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +$ python3 student-tests/test_telemetry_persistence.py +## lab6: сохранность истории telemetry после перезапуска +PASS до рестарта: лог, trace и метрика контрольного запроса сохранены 17.70s request_id → trace e7fcbc6308a9…, счётчик POST messages = 13 +PASS перезапуск всех сервисов и хранилищ (volumes сохраняются) 43.11s hook scripts/restart.sh + готовность за 43 с +PASS после рестарта: тот же лог, тот же trace, то же значение метрики в прошлом 0.19s лог, trace (8 spans), метрика (13) и dashboard на месте +PASS после рестарта: новые данные доходят во все три хранилища 3.82s новый trace 1bd7c465a6c1…, текущий RPS API 0.98 +summary: 4 passed, 0 failed +exit=0 diff --git a/evidence/test-track2-lab5.txt b/evidence/test-track2-lab5.txt new file mode 100644 index 00000000..66eb8831 --- /dev/null +++ b/evidence/test-track2-lab5.txt @@ -0,0 +1,12 @@ +# 2026-11-21T19:29:03Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +$ python3 student-tests/test_pipeline_idempotency.py +## track 2: pipeline idempotency (http://127.0.0.1:8080) +PASS D: 8 duplicate copies of one job delivered concurrently → one claim, one commit 32.45s 9 deliveries: claimed 1, committed 1, duplicate_ignored 8 +PASS R: reorder — stale attempts (1, 2) and a future one arrive DURING attempt 3 → ignored 22.85s during attempt 3: attempts 2, 1 → stale_ignored; 9 → stale_ignored(future) + term; one commit +PASS C: crash before/after side effect, after COMMIT, hung worker — all reach one result 46.64s {'crash-before-s3': 'takeover', 'crash-after-s3': 'takeover', 'crash-after-commit': 'dup_ignored', 'hang-40': 'takeover'} +PASS V1: stale v1 job after v2 is published → superseded, no v1 side effects 22.25s v2 ready first; v1 → superseded at claim; variants only v2, pointer 2 +PASS V2: version race — slow v1 commits after v2 → pointer stays on v2 (no overwrite by older) 16.43s v1 finished after v2 → superseded at commit; pointer history [(None, 2)] +PASS V3: redelivered v1 after v2 rollout and repeated reprocess are no-ops 7.65s v1 ready → v2 ready (pointer 1→2); 3 v1 duplicates ignored; reprocess v1/v2 again → noop +PASS invariants I1–I7 hold for everything this suite produced (settled, bytes verified) 3.37s attachments 9, jobs 12 {'ready': 10, 'superseded': 2}, variants 33, events 91 +summary: 7 passed, 0 failed +exit=0 diff --git a/evidence/track1-telemetry-cost.txt b/evidence/track1-telemetry-cost.txt new file mode 100644 index 00000000..95405ec5 --- /dev/null +++ b/evidence/track1-telemetry-cost.txt @@ -0,0 +1,283 @@ +# 2026-11-21T19:33:37Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +$ python3 research/telemetry_cost.py --reps 3 --rate 60 --window 60 --out evidence/track1 +[22:33:37] run off: apply config +[22:35:47] run off: {"ok_rps": 58.8, "lat_p50_ms": 6.3, "lat_p95_ms": 27.2, "lat_p99_ms": 56.5} +[22:35:47] run full: apply config +[22:38:01] run full: {"ok_rps": 58.8, "lat_p50_ms": 8.6, "lat_p95_ms": 43.2, "lat_p99_ms": 106.8, "errors_found_in_tempo": [45, 45], "slow_found_in_tempo": [45, 45]} +[22:38:01] run head10: apply config +[22:40:16] run head10: {"ok_rps": 58.8, "lat_p50_ms": 7.1, "lat_p95_ms": 29.2, "lat_p99_ms": 68.5, "errors_found_in_tempo": [2, 45], "slow_found_in_tempo": [2, 45]} +[22:40:16] run tail: apply config +[22:42:44] run tail: {"ok_rps": 58.8, "lat_p50_ms": 9.7, "lat_p95_ms": 67.0, "lat_p99_ms": 243.0, "errors_found_in_tempo": [45, 45], "slow_found_in_tempo": [45, 45]} +[22:42:44] run off: apply config +[22:45:07] run off: {"ok_rps": 58.8, "lat_p50_ms": 6.2, "lat_p95_ms": 21.5, "lat_p99_ms": 41.5} +[22:45:07] run full: apply config +[22:47:22] run full: {"ok_rps": 58.8, "lat_p50_ms": 9.8, "lat_p95_ms": 50.5, "lat_p99_ms": 113.0, "errors_found_in_tempo": [45, 45], "slow_found_in_tempo": [45, 45]} +[22:47:22] run head10: apply config +[22:49:40] run head10: {"ok_rps": 58.8, "lat_p50_ms": 6.7, "lat_p95_ms": 24.6, "lat_p99_ms": 53.6, "errors_found_in_tempo": [1, 45], "slow_found_in_tempo": [4, 45]} +[22:49:40] run tail: apply config +[22:52:07] run tail: {"ok_rps": 58.8, "lat_p50_ms": 9.1, "lat_p95_ms": 55.7, "lat_p99_ms": 140.1, "errors_found_in_tempo": [45, 45], "slow_found_in_tempo": [45, 45]} +[22:52:07] run off: apply config +[22:54:29] run off: {"ok_rps": 58.8, "lat_p50_ms": 5.5, "lat_p95_ms": 18.7, "lat_p99_ms": 40.4} +[22:54:29] run full: apply config +[22:56:45] run full: {"ok_rps": 58.8, "lat_p50_ms": 8.7, "lat_p95_ms": 42.8, "lat_p99_ms": 132.1, "errors_found_in_tempo": [45, 45], "slow_found_in_tempo": [45, 45]} +[22:56:45] run head10: apply config +[22:59:01] run head10: {"ok_rps": 58.8, "lat_p50_ms": 5.9, "lat_p95_ms": 22.2, "lat_p99_ms": 51.5, "errors_found_in_tempo": [2, 45], "slow_found_in_tempo": [3, 45]} +[22:59:01] run tail: apply config +[23:01:31] run tail: {"ok_rps": 58.8, "lat_p50_ms": 7.6, "lat_p95_ms": 37.8, "lat_p99_ms": 97.0, "errors_found_in_tempo": [45, 45], "slow_found_in_tempo": [45, 45]} +[23:01:31] restore config full +{ + "meta": { + "rate_rps": 60.0, + "window_s": 60, + "warmup_s": 15, + "reps": 3, + "configs": { + "off": { + "OTEL_SDK_DISABLED": "true", + "OTEL_TRACES_SAMPLER_ARG": "1.0", + "OTEL_COLLECTOR_CONFIG": "collector.yaml" + }, + "full": { + "OTEL_SDK_DISABLED": "false", + "OTEL_TRACES_SAMPLER_ARG": "1.0", + "OTEL_COLLECTOR_CONFIG": "collector.yaml" + }, + "head10": { + "OTEL_SDK_DISABLED": "false", + "OTEL_TRACES_SAMPLER_ARG": "0.1", + "OTEL_COLLECTOR_CONFIG": "collector.yaml" + }, + "tail": { + "OTEL_SDK_DISABLED": "false", + "OTEL_TRACES_SAMPLER_ARG": "1.0", + "OTEL_COLLECTOR_CONFIG": "collector-tail.yaml" + } + }, + "host_cpus": 2, + "date": "2026-11-21T20:01:39Z" + }, + "table": { + "off": { + "runs": 3, + "ok_rps": 58.8, + "p50_ms": 6.2, + "p95_ms": 21.5, + "p99_ms": 41.5, + "p95_ms_runs": [ + 27.2, + 21.5, + 18.7 + ], + "unexpected_errors": 0, + "cpu_api_pct": 30.5, + "mem_api_mib": 106.4, + "cpu_worker_pct": 52.3, + "mem_worker_mib": 87.2, + "cpu_collector_pct": 0.1, + "mem_collector_mib": 31.2, + "cpu_backends_pct": 2.5, + "mem_backends_mib": 362.6, + "cpu_postgres_pct": 8.0, + "mem_postgres_mib": 73.1 + }, + "full": { + "runs": 3, + "ok_rps": 58.8, + "p50_ms": 8.7, + "p95_ms": 43.2, + "p99_ms": 113.0, + "p95_ms_runs": [ + 43.2, + 50.5, + 42.8 + ], + "unexpected_errors": 0, + "cpu_api_pct": 43.4, + "mem_api_mib": 124.0, + "cpu_worker_pct": 39.0, + "mem_worker_mib": 97.1, + "cpu_collector_pct": 1.3, + "mem_collector_mib": 45.8, + "cpu_backends_pct": 4.6, + "mem_backends_mib": 373.4, + "cpu_postgres_pct": 8.7, + "mem_postgres_mib": 89.1, + "col_spans_in_per_s": 482.8, + "col_spans_out_per_s": 482.8, + "tempo_bytes_per_s": 147204.9, + "tempo_spans_per_s": 482.8, + "loki_bytes_per_s": 18815.5, + "loki_lines_per_s": 62.2, + "col_points_in_per_s": 35.8, + "prom_samples_per_s": 1274.8, + "sdk_lost": 0, + "col_refused": 0, + "col_send_failed": 0, + "sdk_sampled_share": 1.0, + "red_5xx_vs_injected": [ + [ + 45.0, + 45 + ], + [ + 45.0, + 45 + ], + [ + 45.0, + 45 + ] + ], + "spanmetrics_vs_sdk_calls": [ + [ + 4500.0, + 4500.0 + ], + [ + 4500.0, + 4500.0 + ], + [ + 4500.0, + 4500.0 + ] + ], + "errors_found_in_tempo": "135/135", + "slow_found_in_tempo": "135/135", + "natural_slow_found_in_tempo": "12/12" + }, + "head10": { + "runs": 3, + "ok_rps": 58.8, + "p50_ms": 6.7, + "p95_ms": 24.6, + "p99_ms": 53.6, + "p95_ms_runs": [ + 29.2, + 24.6, + 22.2 + ], + "unexpected_errors": 0, + "cpu_api_pct": 32.2, + "mem_api_mib": 116.0, + "cpu_worker_pct": 28.1, + "mem_worker_mib": 97.5, + "cpu_collector_pct": 0.6, + "mem_collector_mib": 51.4, + "cpu_backends_pct": 3.4, + "mem_backends_mib": 349.7, + "cpu_postgres_pct": 7.7, + "mem_postgres_mib": 78.7, + "col_spans_in_per_s": 48.2, + "col_spans_out_per_s": 48.2, + "tempo_bytes_per_s": 15248.0, + "tempo_spans_per_s": 48.2, + "loki_bytes_per_s": 18812.7, + "loki_lines_per_s": 62.3, + "col_points_in_per_s": 36.6, + "prom_samples_per_s": 1253.6, + "sdk_lost": 0, + "col_refused": 0, + "col_send_failed": 0, + "sdk_sampled_share": 0.4533439069521544, + "red_5xx_vs_injected": [ + [ + 7.0, + 45 + ], + [ + 45.0, + 45 + ], + [ + 45.0, + 45 + ] + ], + "spanmetrics_vs_sdk_calls": [ + [ + 406.0, + 4492.0 + ], + [ + 483.0, + 4500.0 + ], + [ + 431.0, + 4500.0 + ] + ], + "errors_found_in_tempo": "5/135", + "slow_found_in_tempo": "9/135", + "natural_slow_found_in_tempo": "0/3" + }, + "tail": { + "runs": 3, + "ok_rps": 58.8, + "p50_ms": 9.1, + "p95_ms": 55.7, + "p99_ms": 140.1, + "p95_ms_runs": [ + 67.0, + 55.7, + 37.8 + ], + "unexpected_errors": 0, + "cpu_api_pct": 42.8, + "mem_api_mib": 123.5, + "cpu_worker_pct": 30.2, + "mem_worker_mib": 97.3, + "cpu_collector_pct": 1.4, + "mem_collector_mib": 50.2, + "cpu_backends_pct": 5.4, + "mem_backends_mib": 574.7, + "cpu_postgres_pct": 8.6, + "mem_postgres_mib": 91.3, + "col_spans_in_per_s": 482.8, + "col_spans_out_per_s": 79.6, + "tempo_bytes_per_s": 27868.7, + "tempo_spans_per_s": 79.6, + "loki_bytes_per_s": 18806.3, + "loki_lines_per_s": 62.2, + "col_points_in_per_s": 36.1, + "prom_samples_per_s": 1269.0, + "sdk_lost": 0, + "col_refused": 0, + "col_send_failed": 0, + "sdk_sampled_share": 1.0, + "red_5xx_vs_injected": [ + [ + 45.0, + 45 + ], + [ + 45.0, + 45 + ], + [ + 45.0, + 45 + ] + ], + "spanmetrics_vs_sdk_calls": [ + [ + 539.0, + 4500.0 + ], + [ + 543.0, + 4500.0 + ], + [ + 584.0, + 4500.0 + ] + ], + "errors_found_in_tempo": "135/135", + "slow_found_in_tempo": "135/135", + "natural_slow_found_in_tempo": "15/34" + } + } +} +exit=0 diff --git a/evidence/track1/runs.json b/evidence/track1/runs.json new file mode 100644 index 00000000..de07cbf2 --- /dev/null +++ b/evidence/track1/runs.json @@ -0,0 +1,857 @@ +[ + { + "config": "off", + "window_s": 60.0, + "requests": 3600, + "ok_rps": 58.8, + "unexpected_errors": 0, + "injected_errors": 45, + "lat_p50_ms": 6.3, + "lat_p95_ms": 27.2, + "lat_p99_ms": 56.5, + "resources": { + "api": { + "cpu_pct_avg": 31.1, + "mem_mib_avg": 107.4, + "mem_mib_max": 152.6 + }, + "worker": { + "cpu_pct_avg": 52.3, + "mem_mib_avg": 87.2, + "mem_mib_max": 119.8 + }, + "collector": { + "cpu_pct_avg": 0.1, + "mem_mib_avg": 50.3, + "mem_mib_max": 50.7 + }, + "backends": { + "cpu_pct_avg": 2.4, + "mem_mib_avg": 406.2, + "mem_mib_max": 510.0 + }, + "postgres": { + "cpu_pct_avg": 8.8, + "mem_mib_avg": 64.5, + "mem_mib_max": 66.7 + } + }, + "rep": 1 + }, + { + "config": "full", + "window_s": 60.0, + "requests": 3600, + "ok_rps": 58.8, + "unexpected_errors": 0, + "injected_errors": 45, + "lat_p50_ms": 8.6, + "lat_p95_ms": 43.2, + "lat_p99_ms": 106.8, + "resources": { + "api": { + "cpu_pct_avg": 43.4, + "mem_mib_avg": 124.0, + "mem_mib_max": 166.6 + }, + "worker": { + "cpu_pct_avg": 36.6, + "mem_mib_avg": 97.1, + "mem_mib_max": 116.1 + }, + "collector": { + "cpu_pct_avg": 1.3, + "mem_mib_avg": 52.3, + "mem_mib_max": 53.1 + }, + "backends": { + "cpu_pct_avg": 4.6, + "mem_mib_avg": 355.3, + "mem_mib_max": 450.9 + }, + "postgres": { + "cpu_pct_avg": 8.3, + "mem_mib_avg": 71.1, + "mem_mib_max": 81.3 + } + }, + "telemetry_delta": { + "col_spans_in": 36443.0, + "col_spans_out": 36443.0, + "col_logs_in": 4696.0, + "col_points_in": 2681.0, + "col_refused": 0.0, + "col_send_failed": 0.0, + "tempo_bytes": 11113140.0, + "tempo_spans": 36443.0, + "loki_bytes": 1420263.0, + "loki_lines": 4696.0, + "prom_samples": 96969.0, + "sdk_started": 35147.0, + "sdk_sampled": 35147.0, + "sdk_lost": 0.0, + "red_5xx": 45.0, + "red_all": 4500.0, + "spanmetrics_calls": 4500.0 + }, + "per_second": { + "col_spans_in": 482.8, + "col_spans_out": 482.8, + "col_logs_in": 62.2, + "col_points_in": 35.5, + "tempo_bytes": 147225.6, + "tempo_spans": 482.8, + "loki_bytes": 18815.5, + "loki_lines": 62.2, + "prom_samples": 1284.6 + }, + "errors_found_in_tempo": [ + 45, + 45 + ], + "slow_found_in_tempo": [ + 45, + 45 + ], + "natural_slow_requests": 0, + "natural_slow_found_in_tempo": [ + 0, + 0 + ], + "rep": 1 + }, + { + "config": "head10", + "window_s": 60.0, + "requests": 3600, + "ok_rps": 58.8, + "unexpected_errors": 0, + "injected_errors": 45, + "lat_p50_ms": 7.1, + "lat_p95_ms": 29.2, + "lat_p99_ms": 68.5, + "resources": { + "api": { + "cpu_pct_avg": 34.2, + "mem_mib_avg": 116.7, + "mem_mib_max": 147.4 + }, + "worker": { + "cpu_pct_avg": 39.0, + "mem_mib_avg": 97.5, + "mem_mib_max": 150.7 + }, + "collector": { + "cpu_pct_avg": 0.6, + "mem_mib_avg": 52.9, + "mem_mib_max": 53.1 + }, + "backends": { + "cpu_pct_avg": 3.4, + "mem_mib_avg": 326.1, + "mem_mib_max": 329.5 + }, + "postgres": { + "cpu_pct_avg": 7.7, + "mem_mib_avg": 72.9, + "mem_mib_max": 82.3 + } + }, + "telemetry_delta": { + "col_spans_in": 3487.0, + "col_spans_out": 3487.0, + "col_logs_in": 4696.0, + "col_points_in": 2765.0, + "col_refused": 0.0, + "col_send_failed": 0.0, + "tempo_bytes": 1106907.0, + "tempo_spans": 3487.0, + "loki_bytes": 1418988.0, + "loki_lines": 4696.0, + "prom_samples": 99872.0, + "sdk_started": 1637.0, + "sdk_sampled": -2521.0, + "sdk_lost": 0.0, + "red_5xx": 7.0, + "red_all": 4492.0, + "spanmetrics_calls": 406.0 + }, + "per_second": { + "col_spans_in": 46.2, + "col_spans_out": 46.2, + "col_logs_in": 62.2, + "col_points_in": 36.6, + "tempo_bytes": 14664.2, + "tempo_spans": 46.2, + "loki_bytes": 18798.6, + "loki_lines": 62.2, + "prom_samples": 1323.1 + }, + "errors_found_in_tempo": [ + 2, + 45 + ], + "slow_found_in_tempo": [ + 2, + 45 + ], + "natural_slow_requests": 3, + "natural_slow_found_in_tempo": [ + 0, + 3 + ], + "rep": 1 + }, + { + "config": "tail", + "window_s": 60.0, + "requests": 3600, + "ok_rps": 58.8, + "unexpected_errors": 0, + "injected_errors": 45, + "lat_p50_ms": 9.7, + "lat_p95_ms": 67.0, + "lat_p99_ms": 243.0, + "resources": { + "api": { + "cpu_pct_avg": 43.4, + "mem_mib_avg": 124.0, + "mem_mib_max": 165.8 + }, + "worker": { + "cpu_pct_avg": 30.2, + "mem_mib_avg": 97.3, + "mem_mib_max": 134.9 + }, + "collector": { + "cpu_pct_avg": 1.5, + "mem_mib_avg": 49.7, + "mem_mib_max": 56.8 + }, + "backends": { + "cpu_pct_avg": 5.4, + "mem_mib_avg": 576.7, + "mem_mib_max": 599.4 + }, + "postgres": { + "cpu_pct_avg": 8.6, + "mem_mib_avg": 89.9, + "mem_mib_max": 101.1 + } + }, + "telemetry_delta": { + "col_spans_in": 36443.0, + "col_spans_out": 5964.0, + "col_logs_in": 4696.0, + "col_points_in": 2696.0, + "col_refused": 0.0, + "col_send_failed": 0.0, + "tempo_bytes": 2095361.0, + "tempo_spans": 5964.0, + "loki_bytes": 1420629.0, + "loki_lines": 4696.0, + "prom_samples": 108641.0, + "sdk_started": 35147.0, + "sdk_sampled": 35147.0, + "sdk_lost": 0.0, + "red_5xx": 45.0, + "red_all": 4500.0, + "spanmetrics_calls": 539.0 + }, + "per_second": { + "col_spans_in": 482.8, + "col_spans_out": 79.0, + "col_logs_in": 62.2, + "col_points_in": 35.7, + "tempo_bytes": 27759.1, + "tempo_spans": 79.0, + "loki_bytes": 18820.3, + "loki_lines": 62.2, + "prom_samples": 1439.3 + }, + "errors_found_in_tempo": [ + 45, + 45 + ], + "slow_found_in_tempo": [ + 45, + 45 + ], + "natural_slow_requests": 35, + "natural_slow_found_in_tempo": [ + 15, + 30 + ], + "rep": 1 + }, + { + "config": "off", + "window_s": 60.0, + "requests": 3600, + "ok_rps": 58.8, + "unexpected_errors": 0, + "injected_errors": 45, + "lat_p50_ms": 6.2, + "lat_p95_ms": 21.5, + "lat_p99_ms": 41.5, + "resources": { + "api": { + "cpu_pct_avg": 30.5, + "mem_mib_avg": 106.4, + "mem_mib_max": 128.4 + }, + "worker": { + "cpu_pct_avg": 54.2, + "mem_mib_avg": 88.9, + "mem_mib_max": 128.2 + }, + "collector": { + "cpu_pct_avg": 0.1, + "mem_mib_avg": 30.7, + "mem_mib_max": 32.1 + }, + "backends": { + "cpu_pct_avg": 2.5, + "mem_mib_avg": 322.0, + "mem_mib_max": 323.7 + }, + "postgres": { + "cpu_pct_avg": 8.0, + "mem_mib_avg": 73.1, + "mem_mib_max": 75.3 + } + }, + "rep": 2 + }, + { + "config": "full", + "window_s": 60.0, + "requests": 3600, + "ok_rps": 58.8, + "unexpected_errors": 0, + "injected_errors": 45, + "lat_p50_ms": 9.8, + "lat_p95_ms": 50.5, + "lat_p99_ms": 113.0, + "resources": { + "api": { + "cpu_pct_avg": 43.4, + "mem_mib_avg": 122.4, + "mem_mib_max": 146.8 + }, + "worker": { + "cpu_pct_avg": 39.0, + "mem_mib_avg": 98.3, + "mem_mib_max": 138.6 + }, + "collector": { + "cpu_pct_avg": 1.3, + "mem_mib_avg": 45.5, + "mem_mib_max": 50.6 + }, + "backends": { + "cpu_pct_avg": 4.6, + "mem_mib_avg": 373.4, + "mem_mib_max": 478.6 + }, + "postgres": { + "cpu_pct_avg": 9.6, + "mem_mib_avg": 89.1, + "mem_mib_max": 98.7 + } + }, + "telemetry_delta": { + "col_spans_in": 36443.0, + "col_spans_out": 36443.0, + "col_logs_in": 4696.0, + "col_points_in": 2701.0, + "col_refused": 0.0, + "col_send_failed": 0.0, + "tempo_bytes": 11111565.0, + "tempo_spans": 36443.0, + "loki_bytes": 1420353.0, + "loki_lines": 4696.0, + "prom_samples": 96223.0, + "sdk_started": 35147.0, + "sdk_sampled": 35147.0, + "sdk_lost": 0.0, + "red_5xx": 45.0, + "red_all": 4500.0, + "spanmetrics_calls": 4500.0 + }, + "per_second": { + "col_spans_in": 482.8, + "col_spans_out": 482.8, + "col_logs_in": 62.2, + "col_points_in": 35.8, + "tempo_bytes": 147204.9, + "tempo_spans": 482.8, + "loki_bytes": 18816.7, + "loki_lines": 62.2, + "prom_samples": 1274.8 + }, + "errors_found_in_tempo": [ + 45, + 45 + ], + "slow_found_in_tempo": [ + 45, + 45 + ], + "natural_slow_requests": 9, + "natural_slow_found_in_tempo": [ + 9, + 9 + ], + "rep": 2 + }, + { + "config": "head10", + "window_s": 60.0, + "requests": 3600, + "ok_rps": 58.8, + "unexpected_errors": 0, + "injected_errors": 45, + "lat_p50_ms": 6.7, + "lat_p95_ms": 24.6, + "lat_p99_ms": 53.6, + "resources": { + "api": { + "cpu_pct_avg": 32.2, + "mem_mib_avg": 116.0, + "mem_mib_max": 157.4 + }, + "worker": { + "cpu_pct_avg": 28.1, + "mem_mib_avg": 98.5, + "mem_mib_max": 129.1 + }, + "collector": { + "cpu_pct_avg": 0.7, + "mem_mib_avg": 50.6, + "mem_mib_max": 50.9 + }, + "backends": { + "cpu_pct_avg": 3.4, + "mem_mib_avg": 349.7, + "mem_mib_max": 358.4 + }, + "postgres": { + "cpu_pct_avg": 8.1, + "mem_mib_avg": 78.7, + "mem_mib_max": 85.7 + } + }, + "telemetry_delta": { + "col_spans_in": 3777.0, + "col_spans_out": 3777.0, + "col_logs_in": 4701.0, + "col_points_in": 2761.0, + "col_refused": 0.0, + "col_send_failed": 0.0, + "tempo_bytes": 1183927.0, + "tempo_spans": 3777.0, + "loki_bytes": 1421285.0, + "loki_lines": 4701.0, + "prom_samples": 94630.0, + "sdk_started": 7835.0, + "sdk_sampled": 3742.0, + "sdk_lost": 0.0, + "red_5xx": 45.0, + "red_all": 4500.0, + "spanmetrics_calls": 483.0 + }, + "per_second": { + "col_spans_in": 50.0, + "col_spans_out": 50.0, + "col_logs_in": 62.3, + "col_points_in": 36.6, + "tempo_bytes": 15684.5, + "tempo_spans": 50.0, + "loki_bytes": 18829.0, + "loki_lines": 62.3, + "prom_samples": 1253.6 + }, + "errors_found_in_tempo": [ + 1, + 45 + ], + "slow_found_in_tempo": [ + 4, + 45 + ], + "natural_slow_requests": 0, + "natural_slow_found_in_tempo": [ + 0, + 0 + ], + "rep": 2 + }, + { + "config": "tail", + "window_s": 60.0, + "requests": 3600, + "ok_rps": 58.8, + "unexpected_errors": 0, + "injected_errors": 45, + "lat_p50_ms": 9.1, + "lat_p95_ms": 55.7, + "lat_p99_ms": 140.1, + "resources": { + "api": { + "cpu_pct_avg": 42.8, + "mem_mib_avg": 123.5, + "mem_mib_max": 147.6 + }, + "worker": { + "cpu_pct_avg": 42.0, + "mem_mib_avg": 98.3, + "mem_mib_max": 148.3 + }, + "collector": { + "cpu_pct_avg": 1.3, + "mem_mib_avg": 50.2, + "mem_mib_max": 56.9 + }, + "backends": { + "cpu_pct_avg": 4.8, + "mem_mib_avg": 574.7, + "mem_mib_max": 623.5 + }, + "postgres": { + "cpu_pct_avg": 8.3, + "mem_mib_avg": 91.3, + "mem_mib_max": 98.9 + } + }, + "telemetry_delta": { + "col_spans_in": 36443.0, + "col_spans_out": 6008.0, + "col_logs_in": 4696.0, + "col_points_in": 2790.0, + "col_refused": 0.0, + "col_send_failed": 0.0, + "tempo_bytes": 2103644.0, + "tempo_spans": 6008.0, + "loki_bytes": 1419168.0, + "loki_lines": 4696.0, + "prom_samples": 95678.0, + "sdk_started": 35148.0, + "sdk_sampled": 35148.0, + "sdk_lost": 0.0, + "red_5xx": 45.0, + "red_all": 4500.0, + "spanmetrics_calls": 543.0 + }, + "per_second": { + "col_spans_in": 482.8, + "col_spans_out": 79.6, + "col_logs_in": 62.2, + "col_points_in": 37.0, + "tempo_bytes": 27868.7, + "tempo_spans": 79.6, + "loki_bytes": 18800.9, + "loki_lines": 62.2, + "prom_samples": 1267.5 + }, + "errors_found_in_tempo": [ + 45, + 45 + ], + "slow_found_in_tempo": [ + 45, + 45 + ], + "natural_slow_requests": 4, + "natural_slow_found_in_tempo": [ + 0, + 4 + ], + "rep": 2 + }, + { + "config": "off", + "window_s": 60.0, + "requests": 3600, + "ok_rps": 58.8, + "unexpected_errors": 0, + "injected_errors": 45, + "lat_p50_ms": 5.5, + "lat_p95_ms": 18.7, + "lat_p99_ms": 40.4, + "resources": { + "api": { + "cpu_pct_avg": 26.3, + "mem_mib_avg": 106.4, + "mem_mib_max": 128.5 + }, + "worker": { + "cpu_pct_avg": 35.0, + "mem_mib_avg": 85.7, + "mem_mib_max": 128.9 + }, + "collector": { + "cpu_pct_avg": 0.1, + "mem_mib_avg": 31.2, + "mem_mib_max": 33.3 + }, + "backends": { + "cpu_pct_avg": 2.5, + "mem_mib_avg": 362.6, + "mem_mib_max": 364.8 + }, + "postgres": { + "cpu_pct_avg": 7.6, + "mem_mib_avg": 79.3, + "mem_mib_max": 82.8 + } + }, + "rep": 3 + }, + { + "config": "full", + "window_s": 60.0, + "requests": 3600, + "ok_rps": 58.8, + "unexpected_errors": 0, + "injected_errors": 45, + "lat_p50_ms": 8.7, + "lat_p95_ms": 42.8, + "lat_p99_ms": 132.1, + "resources": { + "api": { + "cpu_pct_avg": 43.2, + "mem_mib_avg": 125.1, + "mem_mib_max": 165.3 + }, + "worker": { + "cpu_pct_avg": 39.2, + "mem_mib_avg": 93.4, + "mem_mib_max": 149.7 + }, + "collector": { + "cpu_pct_avg": 1.3, + "mem_mib_avg": 45.8, + "mem_mib_max": 51.2 + }, + "backends": { + "cpu_pct_avg": 4.7, + "mem_mib_avg": 377.6, + "mem_mib_max": 541.6 + }, + "postgres": { + "cpu_pct_avg": 8.7, + "mem_mib_avg": 93.0, + "mem_mib_max": 103.1 + } + }, + "telemetry_delta": { + "col_spans_in": 36443.0, + "col_spans_out": 36443.0, + "col_logs_in": 4696.0, + "col_points_in": 2781.0, + "col_refused": 0.0, + "col_send_failed": 0.0, + "tempo_bytes": 11109054.0, + "tempo_spans": 36443.0, + "loki_bytes": 1418209.0, + "loki_lines": 4693.0, + "prom_samples": 94986.0, + "sdk_started": 35148.0, + "sdk_sampled": 35148.0, + "sdk_lost": 0.0, + "red_5xx": 45.0, + "red_all": 4500.0, + "spanmetrics_calls": 4500.0 + }, + "per_second": { + "col_spans_in": 482.8, + "col_spans_out": 482.8, + "col_logs_in": 62.2, + "col_points_in": 36.8, + "tempo_bytes": 147171.3, + "tempo_spans": 482.8, + "loki_bytes": 18788.2, + "loki_lines": 62.2, + "prom_samples": 1258.4 + }, + "errors_found_in_tempo": [ + 45, + 45 + ], + "slow_found_in_tempo": [ + 45, + 45 + ], + "natural_slow_requests": 3, + "natural_slow_found_in_tempo": [ + 3, + 3 + ], + "rep": 3 + }, + { + "config": "head10", + "window_s": 60.0, + "requests": 3600, + "ok_rps": 58.8, + "unexpected_errors": 0, + "injected_errors": 45, + "lat_p50_ms": 5.9, + "lat_p95_ms": 22.2, + "lat_p99_ms": 51.5, + "resources": { + "api": { + "cpu_pct_avg": 31.2, + "mem_mib_avg": 115.8, + "mem_mib_max": 136.8 + }, + "worker": { + "cpu_pct_avg": 21.6, + "mem_mib_avg": 93.7, + "mem_mib_max": 123.9 + }, + "collector": { + "cpu_pct_avg": 0.6, + "mem_mib_avg": 51.4, + "mem_mib_max": 52.0 + }, + "backends": { + "cpu_pct_avg": 3.3, + "mem_mib_avg": 391.0, + "mem_mib_max": 396.0 + }, + "postgres": { + "cpu_pct_avg": 7.4, + "mem_mib_avg": 86.1, + "mem_mib_max": 93.3 + } + }, + "telemetry_delta": { + "col_spans_in": 3640.0, + "col_spans_out": 3640.0, + "col_logs_in": 4700.0, + "col_points_in": 2745.0, + "col_refused": 0.0, + "col_send_failed": 0.0, + "tempo_bytes": 1150983.0, + "tempo_spans": 3640.0, + "loki_bytes": 1420061.0, + "loki_lines": 4700.0, + "prom_samples": 94420.0, + "sdk_started": 7566.0, + "sdk_sampled": 3430.0, + "sdk_lost": 0.0, + "red_5xx": 45.0, + "red_all": 4500.0, + "spanmetrics_calls": 431.0 + }, + "per_second": { + "col_spans_in": 48.2, + "col_spans_out": 48.2, + "col_logs_in": 62.3, + "col_points_in": 36.4, + "tempo_bytes": 15248.0, + "tempo_spans": 48.2, + "loki_bytes": 18812.7, + "loki_lines": 62.3, + "prom_samples": 1250.9 + }, + "errors_found_in_tempo": [ + 2, + 45 + ], + "slow_found_in_tempo": [ + 3, + 45 + ], + "natural_slow_requests": 0, + "natural_slow_found_in_tempo": [ + 0, + 0 + ], + "rep": 3 + }, + { + "config": "tail", + "window_s": 60.0, + "requests": 3600, + "ok_rps": 58.8, + "unexpected_errors": 0, + "injected_errors": 45, + "lat_p50_ms": 7.6, + "lat_p95_ms": 37.8, + "lat_p99_ms": 97.0, + "resources": { + "api": { + "cpu_pct_avg": 37.6, + "mem_mib_avg": 123.3, + "mem_mib_max": 157.3 + }, + "worker": { + "cpu_pct_avg": 25.5, + "mem_mib_avg": 86.5, + "mem_mib_max": 107.2 + }, + "collector": { + "cpu_pct_avg": 1.4, + "mem_mib_avg": 50.7, + "mem_mib_max": 57.6 + }, + "backends": { + "cpu_pct_avg": 6.0, + "mem_mib_avg": 496.0, + "mem_mib_max": 703.4 + }, + "postgres": { + "cpu_pct_avg": 9.6, + "mem_mib_avg": 97.7, + "mem_mib_max": 102.6 + } + }, + "telemetry_delta": { + "col_spans_in": 36451.0, + "col_spans_out": 6298.0, + "col_logs_in": 4696.0, + "col_points_in": 2728.0, + "col_refused": 0.0, + "col_send_failed": 0.0, + "tempo_bytes": 2200416.0, + "tempo_spans": 6298.0, + "loki_bytes": 1419574.0, + "loki_lines": 4696.0, + "prom_samples": 95786.0, + "sdk_started": 35155.0, + "sdk_sampled": 35155.0, + "sdk_lost": 0.0, + "red_5xx": 45.0, + "red_all": 4500.0, + "spanmetrics_calls": 584.0 + }, + "per_second": { + "col_spans_in": 482.9, + "col_spans_out": 83.4, + "col_logs_in": 62.2, + "col_points_in": 36.1, + "tempo_bytes": 29150.7, + "tempo_spans": 83.4, + "loki_bytes": 18806.3, + "loki_lines": 62.2, + "prom_samples": 1269.0 + }, + "errors_found_in_tempo": [ + 45, + 45 + ], + "slow_found_in_tempo": [ + 45, + 45 + ], + "natural_slow_requests": 0, + "natural_slow_found_in_tempo": [ + 0, + 0 + ], + "rep": 3 + } +] \ No newline at end of file diff --git a/evidence/track1/summary.json b/evidence/track1/summary.json new file mode 100644 index 00000000..080090f9 --- /dev/null +++ b/evidence/track1/summary.json @@ -0,0 +1,255 @@ +{ + "meta": { + "rate_rps": 60.0, + "window_s": 60, + "warmup_s": 15, + "reps": 3, + "configs": { + "off": { + "OTEL_SDK_DISABLED": "true", + "OTEL_TRACES_SAMPLER_ARG": "1.0", + "OTEL_COLLECTOR_CONFIG": "collector.yaml" + }, + "full": { + "OTEL_SDK_DISABLED": "false", + "OTEL_TRACES_SAMPLER_ARG": "1.0", + "OTEL_COLLECTOR_CONFIG": "collector.yaml" + }, + "head10": { + "OTEL_SDK_DISABLED": "false", + "OTEL_TRACES_SAMPLER_ARG": "0.1", + "OTEL_COLLECTOR_CONFIG": "collector.yaml" + }, + "tail": { + "OTEL_SDK_DISABLED": "false", + "OTEL_TRACES_SAMPLER_ARG": "1.0", + "OTEL_COLLECTOR_CONFIG": "collector-tail.yaml" + } + }, + "host_cpus": 2, + "date": "2026-11-21T20:01:39Z" + }, + "table": { + "off": { + "runs": 3, + "ok_rps": 58.8, + "p50_ms": 6.2, + "p95_ms": 21.5, + "p99_ms": 41.5, + "p95_ms_runs": [ + 27.2, + 21.5, + 18.7 + ], + "unexpected_errors": 0, + "cpu_api_pct": 30.5, + "mem_api_mib": 106.4, + "cpu_worker_pct": 52.3, + "mem_worker_mib": 87.2, + "cpu_collector_pct": 0.1, + "mem_collector_mib": 31.2, + "cpu_backends_pct": 2.5, + "mem_backends_mib": 362.6, + "cpu_postgres_pct": 8.0, + "mem_postgres_mib": 73.1 + }, + "full": { + "runs": 3, + "ok_rps": 58.8, + "p50_ms": 8.7, + "p95_ms": 43.2, + "p99_ms": 113.0, + "p95_ms_runs": [ + 43.2, + 50.5, + 42.8 + ], + "unexpected_errors": 0, + "cpu_api_pct": 43.4, + "mem_api_mib": 124.0, + "cpu_worker_pct": 39.0, + "mem_worker_mib": 97.1, + "cpu_collector_pct": 1.3, + "mem_collector_mib": 45.8, + "cpu_backends_pct": 4.6, + "mem_backends_mib": 373.4, + "cpu_postgres_pct": 8.7, + "mem_postgres_mib": 89.1, + "col_spans_in_per_s": 482.8, + "col_spans_out_per_s": 482.8, + "tempo_bytes_per_s": 147204.9, + "tempo_spans_per_s": 482.8, + "loki_bytes_per_s": 18815.5, + "loki_lines_per_s": 62.2, + "col_points_in_per_s": 35.8, + "prom_samples_per_s": 1274.8, + "sdk_lost": 0, + "col_refused": 0, + "col_send_failed": 0, + "sdk_sampled_share": 1.0, + "red_5xx_vs_injected": [ + [ + 45.0, + 45 + ], + [ + 45.0, + 45 + ], + [ + 45.0, + 45 + ] + ], + "spanmetrics_vs_sdk_calls": [ + [ + 4500.0, + 4500.0 + ], + [ + 4500.0, + 4500.0 + ], + [ + 4500.0, + 4500.0 + ] + ], + "errors_found_in_tempo": "135/135", + "slow_found_in_tempo": "135/135", + "natural_slow_found_in_tempo": "12/12" + }, + "head10": { + "runs": 3, + "ok_rps": 58.8, + "p50_ms": 6.7, + "p95_ms": 24.6, + "p99_ms": 53.6, + "p95_ms_runs": [ + 29.2, + 24.6, + 22.2 + ], + "unexpected_errors": 0, + "cpu_api_pct": 32.2, + "mem_api_mib": 116.0, + "cpu_worker_pct": 28.1, + "mem_worker_mib": 97.5, + "cpu_collector_pct": 0.6, + "mem_collector_mib": 51.4, + "cpu_backends_pct": 3.4, + "mem_backends_mib": 349.7, + "cpu_postgres_pct": 7.7, + "mem_postgres_mib": 78.7, + "col_spans_in_per_s": 48.2, + "col_spans_out_per_s": 48.2, + "tempo_bytes_per_s": 15248.0, + "tempo_spans_per_s": 48.2, + "loki_bytes_per_s": 18812.7, + "loki_lines_per_s": 62.3, + "col_points_in_per_s": 36.6, + "prom_samples_per_s": 1253.6, + "sdk_lost": 0, + "col_refused": 0, + "col_send_failed": 0, + "sdk_sampled_share": 0.4533439069521544, + "red_5xx_vs_injected": [ + [ + 7.0, + 45 + ], + [ + 45.0, + 45 + ], + [ + 45.0, + 45 + ] + ], + "spanmetrics_vs_sdk_calls": [ + [ + 406.0, + 4492.0 + ], + [ + 483.0, + 4500.0 + ], + [ + 431.0, + 4500.0 + ] + ], + "errors_found_in_tempo": "5/135", + "slow_found_in_tempo": "9/135", + "natural_slow_found_in_tempo": "0/3" + }, + "tail": { + "runs": 3, + "ok_rps": 58.8, + "p50_ms": 9.1, + "p95_ms": 55.7, + "p99_ms": 140.1, + "p95_ms_runs": [ + 67.0, + 55.7, + 37.8 + ], + "unexpected_errors": 0, + "cpu_api_pct": 42.8, + "mem_api_mib": 123.5, + "cpu_worker_pct": 30.2, + "mem_worker_mib": 97.3, + "cpu_collector_pct": 1.4, + "mem_collector_mib": 50.2, + "cpu_backends_pct": 5.4, + "mem_backends_mib": 574.7, + "cpu_postgres_pct": 8.6, + "mem_postgres_mib": 91.3, + "col_spans_in_per_s": 482.8, + "col_spans_out_per_s": 79.6, + "tempo_bytes_per_s": 27868.7, + "tempo_spans_per_s": 79.6, + "loki_bytes_per_s": 18806.3, + "loki_lines_per_s": 62.2, + "col_points_in_per_s": 36.1, + "prom_samples_per_s": 1269.0, + "sdk_lost": 0, + "col_refused": 0, + "col_send_failed": 0, + "sdk_sampled_share": 1.0, + "red_5xx_vs_injected": [ + [ + 45.0, + 45 + ], + [ + 45.0, + 45 + ], + [ + 45.0, + 45 + ] + ], + "spanmetrics_vs_sdk_calls": [ + [ + 539.0, + 4500.0 + ], + [ + 543.0, + 4500.0 + ], + [ + 584.0, + 4500.0 + ] + ], + "errors_found_in_tempo": "135/135", + "slow_found_in_tempo": "135/135", + "natural_slow_found_in_tempo": "15/34" + } + } +} \ No newline at end of file diff --git a/evidence/track2-chaos-seed1.txt b/evidence/track2-chaos-seed1.txt new file mode 100644 index 00000000..9cdf10d7 --- /dev/null +++ b/evidence/track2-chaos-seed1.txt @@ -0,0 +1,72 @@ +# 2026-11-21T19:31:36Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2 +$ python3 research/track2_chaos.py --seed 1 --uploads 60 --output evidence/track2/chaos-seed1.json +{ + "seed": 1, + "uploads_requested": 60, + "counters": { + "uploads_202": 60, + "upload_errors": 0, + "kills": 2, + "duplicates_sent": 19, + "stale_sent": 0, + "reprocess_v2": 2, + "v1_after_v2_sent": 4 + }, + "planned_faults": { + "fault-crash-after-commit": 4, + "fault-crash-after-s3": 6, + "fault-crash-before-s3": 7, + "fault-hang-30": 3, + "fault-slow-3": 2, + "fault-transient-1": 7, + "fault-transient-2": 8, + "none": 23 + }, + "chaos_seconds": 50.4, + "settle_seconds": 46.9, + "accepted_202": 60, + "accepted_not_terminal": 0, + "attachment_status": { + "ready": "60" + }, + "job_status": { + "1:ready": "60", + "2:ready": "2" + }, + "events": { + "claimed": "87", + "committed": "62", + "duplicate_ignored": "26", + "enqueued": "62", + "lease_lost": "2", + "lease_takeover": "29", + "published": "87", + "published_version_changed": "62", + "retry_scheduled": "25", + "staging_cleaned": "60" + }, + "enqueue_to_commit_seconds_v1": { + "p50": 44.09, + "p95": 64.59, + "max": 79.28 + }, + "invariants": { + "ok": true, + "violations": {}, + "violation_counts": {}, + "stats": { + "attachments": 60, + "jobs": 62, + "variants": 186, + "events": 502, + "job_status": { + "ready": 62 + }, + "attachment_status": { + "ready": 60 + }, + "s3_objects": 990 + } + } +} +exit=0 diff --git a/evidence/track2/chaos-seed1.json b/evidence/track2/chaos-seed1.json new file mode 100644 index 00000000..6c09b7ca --- /dev/null +++ b/evidence/track2/chaos-seed1.json @@ -0,0 +1,69 @@ +{ + "seed": 1, + "uploads_requested": 60, + "counters": { + "uploads_202": 60, + "upload_errors": 0, + "kills": 2, + "duplicates_sent": 19, + "stale_sent": 0, + "reprocess_v2": 2, + "v1_after_v2_sent": 4 + }, + "planned_faults": { + "fault-crash-after-commit": 4, + "fault-crash-after-s3": 6, + "fault-crash-before-s3": 7, + "fault-hang-30": 3, + "fault-slow-3": 2, + "fault-transient-1": 7, + "fault-transient-2": 8, + "none": 23 + }, + "chaos_seconds": 50.4, + "settle_seconds": 46.9, + "accepted_202": 60, + "accepted_not_terminal": 0, + "attachment_status": { + "ready": "60" + }, + "job_status": { + "1:ready": "60", + "2:ready": "2" + }, + "events": { + "claimed": "87", + "committed": "62", + "duplicate_ignored": "26", + "enqueued": "62", + "lease_lost": "2", + "lease_takeover": "29", + "published": "87", + "published_version_changed": "62", + "retry_scheduled": "25", + "staging_cleaned": "60" + }, + "enqueue_to_commit_seconds_v1": { + "p50": 44.09, + "p95": 64.59, + "max": 79.28 + }, + "invariants": { + "ok": true, + "violations": {}, + "violation_counts": {}, + "stats": { + "attachments": 60, + "jobs": 62, + "variants": 186, + "events": 502, + "job_status": { + "ready": 62 + }, + "attachment_status": { + "ready": 60 + }, + "s3_objects": 990 + } + } +} diff --git a/infra/grafana/dashboards/messenger-overview.json b/infra/grafana/dashboards/messenger-overview.json new file mode 100644 index 00000000..45ad2658 --- /dev/null +++ b/infra/grafana/dashboards/messenger-overview.json @@ -0,0 +1,2019 @@ +{ + "uid": "messenger-overview", + "title": "Messenger — обзор (lab6)", + "tags": [ + "messenger", + "lab6" + ], + "timezone": "browser", + "schemaVersion": 39, + "version": 1, + "editable": false, + "graphTooltip": 1, + "refresh": "10s", + "time": { + "from": "now-30m", + "to": "now" + }, + "description": "RED API, jobs, очередь, saturation, SLO/алерты, конвейер telemetry, логи и трассы. Источник — Git (infra/grafana/dashboards).", + "links": [], + "annotations": { + "list": [ + { + "builtIn": 1, + "datasource": { + "type": "grafana", + "uid": "-- Grafana --" + }, + "enable": true, + "hide": true, + "iconColor": "rgba(0, 211, 255, 1)", + "name": "Annotations & Alerts", + "type": "dashboard" + } + ] + }, + "templating": { + "list": [] + }, + "panels": [ + { + "type": "row", + "title": "SLO и алерты (окна учебного стенда; обоснование — REPORT.md)", + "id": 1, + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 0 + }, + "panels": [] + }, + { + "type": "stat", + "title": "Доступность API, 1 ч (SLO 99.5%)", + "id": 2, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "SLI: доля НЕ-5xx среди бизнес-запросов (без /health, /internal) за 1 ч. 4xx — ошибки клиента, в бюджет не входят. Единицы: доля (%).", + "gridPos": { + "h": 4, + "w": 5, + "x": 0, + "y": 1 + }, + "fieldConfig": { + "defaults": { + "unit": "percentunit", + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "red", + "value": null + }, + { + "color": "orange", + "value": 0.99 + }, + { + "color": "green", + "value": 0.995 + } + ] + }, + "decimals": 3 + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ] + }, + "colorMode": "value", + "graphMode": "area" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "A", + "expr": "1 - (sum(increase(http_server_request_duration_seconds_count{service_name=\"messenger-api\",http_route!~\"/health/.*|/internal/.*\",http_response_status_class=\"5xx\"}[1h])) or vector(0)) / sum(increase(http_server_request_duration_seconds_count{service_name=\"messenger-api\",http_route!~\"/health/.*|/internal/.*\"}[1h]))", + "instant": false, + "range": true + } + ] + }, + { + "type": "stat", + "title": "Быстрые запросы ≤250 мс, 5 мин (SLO 95%)", + "id": 3, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "SLI задержки: доля бизнес-запросов (кроме upload) с длительностью ≤ 0.25 с по bucket le=0.25 histogram. Единицы: доля.", + "gridPos": { + "h": 4, + "w": 5, + "x": 5, + "y": 1 + }, + "fieldConfig": { + "defaults": { + "unit": "percentunit", + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "red", + "value": null + }, + { + "color": "orange", + "value": 0.9 + }, + { + "color": "green", + "value": 0.95 + } + ] + }, + "decimals": 3 + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ] + }, + "colorMode": "value", + "graphMode": "area" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "A", + "expr": "sli:api_fast_ratio:rate5m", + "instant": false, + "range": true + } + ] + }, + { + "type": "stat", + "title": "Ready ≤10 с, 15 мин (SLO 95%)", + "id": 4, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "SLI time-to-ready: доля вложений, ставших ready не позже 10 с после durable acceptance (202). Единицы: доля.", + "gridPos": { + "h": 4, + "w": 5, + "x": 10, + "y": 1 + }, + "fieldConfig": { + "defaults": { + "unit": "percentunit", + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "red", + "value": null + }, + { + "color": "orange", + "value": 0.9 + }, + { + "color": "green", + "value": 0.95 + } + ] + }, + "decimals": 3 + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ] + }, + "colorMode": "value", + "graphMode": "area" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "A", + "expr": "sli:time_to_ready_fast_ratio:rate15m", + "instant": false, + "range": true + } + ] + }, + { + "type": "table", + "title": "Алерты в состоянии firing/pending (Prometheus)", + "id": 5, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "ALERTS — состояние правил Prometheus (infra/prometheus/rules/messenger.yml). Runbook: docs/runbooks.md.", + "gridPos": { + "h": 8, + "w": 9, + "x": 15, + "y": 1 + }, + "fieldConfig": { + "defaults": {}, + "overrides": [] + }, + "options": { + "showHeader": true + }, + "transformations": [ + { + "id": "labelsToFields", + "options": { + "mode": "columns" + } + }, + { + "id": "organize", + "options": { + "excludeByName": { + "Time": true, + "Value": true, + "__name__": true + } + } + } + ], + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "A", + "expr": "ALERTS{alertstate=~\"firing|pending\"}", + "instant": true, + "format": "table" + } + ] + }, + { + "type": "stat", + "title": "Доля 5xx, 1 мин", + "id": 6, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "Числитель: 5xx бизнес-запросов; знаменатель: все бизнес-запросы (без health). Алерт ApiHighErrorRate: > 5% 30 с.", + "gridPos": { + "h": 4, + "w": 5, + "x": 0, + "y": 5 + }, + "fieldConfig": { + "defaults": { + "unit": "percentunit", + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + }, + { + "color": "red", + "value": 0.05 + } + ] + }, + "decimals": 2 + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ] + }, + "colorMode": "value", + "graphMode": "area" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "A", + "expr": "sli:api_error_ratio:rate1m", + "instant": false, + "range": true + } + ] + }, + { + "type": "stat", + "title": "Queue lag", + "id": 7, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "Сколько ждёт самое старое задание, уже доступное worker (без ожидания backoff). Алерт JobQueueLagGrowing: > 30 с.", + "gridPos": { + "h": 4, + "w": 5, + "x": 5, + "y": 5 + }, + "fieldConfig": { + "defaults": { + "unit": "s", + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + }, + { + "color": "orange", + "value": 10 + }, + { + "color": "red", + "value": 30 + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ] + }, + "colorMode": "value", + "graphMode": "area" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "A", + "expr": "sli:queue_lag_seconds:max", + "instant": false, + "range": true + } + ] + }, + { + "type": "stat", + "title": "Worker: занято / слотов", + "id": 8, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "Saturation worker: занятые слоты обработки / WORKER_CONCURRENCY × реплики (метрики за последние 30 с).", + "gridPos": { + "h": 4, + "w": 5, + "x": 10, + "y": 5 + }, + "fieldConfig": { + "defaults": { + "unit": "percentunit", + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + }, + { + "color": "orange", + "value": 0.8 + }, + { + "color": "red", + "value": 1 + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ] + }, + "colorMode": "value", + "graphMode": "area" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "A", + "expr": "sum(last_over_time(messenger_worker_busy[30s])) / sum(last_over_time(messenger_worker_capacity[30s]))", + "instant": false, + "range": true + } + ] + }, + { + "type": "row", + "title": "API — RED (метрики SDK по ВСЕМ запросам; sampling трасс на них не влияет)", + "id": 9, + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 9 + }, + "panels": [] + }, + { + "type": "timeseries", + "title": "RPS по маршруту", + "id": 10, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "Счётчик = _count histogram http.server.request.duration. Маршрут — шаблон (/api/v1/chats/{chat_id}/messages), не URL. Единицы: запросов/с.", + "gridPos": { + "h": 8, + "w": 8, + "x": 0, + "y": 10 + }, + "fieldConfig": { + "defaults": { + "unit": "reqps", + "custom": { + "lineWidth": 1, + "fillOpacity": 10, + "stacking": { + "mode": "normal" + } + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "A", + "expr": "sum by (http_route) (rate(http_server_request_duration_seconds_count{service_name=\"messenger-api\",http_route!~\"/health/.*|/internal/.*\"}[$__rate_interval]))", + "legendFormat": "{{http_route}}", + "range": true + } + ] + }, + { + "type": "timeseries", + "title": "Ответы по классу статуса", + "id": 11, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "2xx/4xx/5xx бизнес-запросов. 4xx (неверный пароль, 404) — не отказ сервиса. Единицы: запросов/с.", + "gridPos": { + "h": 8, + "w": 8, + "x": 8, + "y": 10 + }, + "fieldConfig": { + "defaults": { + "unit": "reqps", + "custom": { + "lineWidth": 1, + "fillOpacity": 10, + "stacking": { + "mode": "normal" + } + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "A", + "expr": "sum by (http_response_status_class) (rate(http_server_request_duration_seconds_count{service_name=\"messenger-api\",http_route!~\"/health/.*|/internal/.*\"}[$__rate_interval]))", + "legendFormat": "{{http_response_status_class}}", + "range": true + } + ] + }, + { + "type": "timeseries", + "title": "Латентность API p50 / p95 / p99", + "id": 12, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "Перцентили из buckets histogram, сложенных по ВСЕМ репликам (sum by le), а не среднее p95 реплик. Единицы: секунды.", + "gridPos": { + "h": 8, + "w": 8, + "x": 16, + "y": 10 + }, + "fieldConfig": { + "defaults": { + "unit": "s", + "custom": { + "lineWidth": 1, + "fillOpacity": 10, + "stacking": { + "mode": "none" + } + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "A", + "expr": "histogram_quantile(0.5, sum by (le) (rate(http_server_request_duration_seconds_bucket{service_name=\"messenger-api\",http_route!~\"/health/.*|/internal/.*\"}[$__rate_interval])))", + "legendFormat": "p50", + "range": true + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "B", + "expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{service_name=\"messenger-api\",http_route!~\"/health/.*|/internal/.*\"}[$__rate_interval])))", + "legendFormat": "p95", + "range": true + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "C", + "expr": "histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket{service_name=\"messenger-api\",http_route!~\"/health/.*|/internal/.*\"}[$__rate_interval])))", + "legendFormat": "p99", + "range": true + } + ] + }, + { + "type": "timeseries", + "title": "p95 по маршруту", + "id": 13, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "Какой маршрут медленный. Upload включает передачу файла клиентом — его задержка выше по природе.", + "gridPos": { + "h": 8, + "w": 8, + "x": 0, + "y": 18 + }, + "fieldConfig": { + "defaults": { + "unit": "s", + "custom": { + "lineWidth": 1, + "fillOpacity": 10, + "stacking": { + "mode": "none" + } + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "A", + "expr": "histogram_quantile(0.95, sum by (le, http_route) (rate(http_server_request_duration_seconds_bucket{service_name=\"messenger-api\",http_route!~\"/health/.*|/internal/.*\"}[$__rate_interval])))", + "legendFormat": "{{http_route}}", + "range": true + } + ] + }, + { + "type": "timeseries", + "title": "PostgreSQL: p95 по операции (все сервисы)", + "id": 14, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "db.client.operation.duration — время execute в PostgreSQL. Растёт вместе с HTTP p95 → медленная БД; HTTP растёт, а это нет → обработчик/CPU API.", + "gridPos": { + "h": 8, + "w": 8, + "x": 8, + "y": 18 + }, + "fieldConfig": { + "defaults": { + "unit": "s", + "custom": { + "lineWidth": 1, + "fillOpacity": 10, + "stacking": { + "mode": "none" + } + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "A", + "expr": "histogram_quantile(0.95, sum by (le, db_operation_name) (rate(db_client_operation_duration_seconds_bucket{}[$__rate_interval])))", + "legendFormat": "{{db_operation_name}}", + "range": true + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "B", + "expr": "histogram_quantile(0.95, sum by (le) (rate(db_client_operation_duration_seconds_bucket{}[$__rate_interval])))", + "legendFormat": "все операции", + "range": true + } + ] + }, + { + "type": "timeseries", + "title": "Запросы в обработке (saturation API)", + "id": 15, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "http.server.active_requests по реплике (включая health). Единицы: запросов одновременно.", + "gridPos": { + "h": 8, + "w": 8, + "x": 16, + "y": 18 + }, + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 1, + "fillOpacity": 10, + "stacking": { + "mode": "none" + } + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "A", + "expr": "sum by (service_instance_id) (last_over_time(http_server_active_requests{service_name=\"messenger-api\"}[30s]))", + "legendFormat": "{{service_instance_id}}", + "range": true + } + ] + }, + { + "type": "row", + "title": "Фоновая обработка — jobs, time to ready", + "id": 16, + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 26 + }, + "panels": [] + }, + { + "type": "timeseries", + "title": "Jobs по исходу", + "id": 17, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "messenger.jobs.processed: ready/retry/failed — попытки обработки; duplicate/stale/nak — повторные/ранние доставки без работы. Единицы: сообщений/с.", + "gridPos": { + "h": 8, + "w": 8, + "x": 0, + "y": 27 + }, + "fieldConfig": { + "defaults": { + "unit": "ops", + "custom": { + "lineWidth": 1, + "fillOpacity": 10, + "stacking": { + "mode": "normal" + } + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "A", + "expr": "sum by (outcome) (rate(messenger_jobs_processed_total[$__rate_interval]))", + "legendFormat": "{{outcome}}", + "range": true + } + ] + }, + { + "type": "timeseries", + "title": "Длительность попытки p50 / p95 / p99", + "id": 18, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "messenger.job.duration: от захвата задания до COMMIT результата/ошибки. Единицы: секунды.", + "gridPos": { + "h": 8, + "w": 8, + "x": 8, + "y": 27 + }, + "fieldConfig": { + "defaults": { + "unit": "s", + "custom": { + "lineWidth": 1, + "fillOpacity": 10, + "stacking": { + "mode": "none" + } + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "A", + "expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_job_duration_seconds_bucket{outcome=\"ready\"}[$__rate_interval])))", + "legendFormat": "p50 ready", + "range": true + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "B", + "expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_duration_seconds_bucket{outcome=\"ready\"}[$__rate_interval])))", + "legendFormat": "p95 ready", + "range": true + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "C", + "expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_job_duration_seconds_bucket{outcome=\"ready\"}[$__rate_interval])))", + "legendFormat": "p99 ready", + "range": true + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "D", + "expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_duration_seconds_bucket{outcome!=\"ready\"}[$__rate_interval])))", + "legendFormat": "p95 ошибки/повторы", + "range": true + } + ] + }, + { + "type": "timeseries", + "title": "Time to ready p50 / p95 / p99 и ожидание в очереди", + "id": 19, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "time_to_ready: от durable acceptance (202) до публикации ready (histogram). queue_wait: от доступности попытки до захвата worker. Backlog (глубина) — отдельная метрика ниже.", + "gridPos": { + "h": 8, + "w": 8, + "x": 16, + "y": 27 + }, + "fieldConfig": { + "defaults": { + "unit": "s", + "custom": { + "lineWidth": 1, + "fillOpacity": 10, + "stacking": { + "mode": "none" + } + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "A", + "expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket{}[$__rate_interval])))", + "legendFormat": "ready p50", + "range": true + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "B", + "expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket{}[$__rate_interval])))", + "legendFormat": "ready p95", + "range": true + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "C", + "expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket{}[$__rate_interval])))", + "legendFormat": "ready p99", + "range": true + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "D", + "expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_queue_wait_seconds_bucket{}[$__rate_interval])))", + "legendFormat": "queue wait p95", + "range": true + } + ] + }, + { + "type": "row", + "title": "Очередь заданий (outbox → NATS JetStream → worker)", + "id": 20, + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 35 + }, + "panels": [] + }, + { + "type": "timeseries", + "title": "Глубина очереди по состоянию", + "id": 21, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "ready — ждут worker; retry_wait — в backoff; processing — в аренде; failed — реестр DLQ. Источник истины — PostgreSQL. Единицы: заданий.", + "gridPos": { + "h": 8, + "w": 8, + "x": 0, + "y": 36 + }, + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 1, + "fillOpacity": 10, + "stacking": { + "mode": "none" + } + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "A", + "expr": "max by (state) (last_over_time(messenger_queue_depth{queue=\"attachments.process.v1\"}[30s]))", + "legendFormat": "{{state}}", + "range": true + } + ] + }, + { + "type": "timeseries", + "title": "Queue lag и возраст старейшего задания", + "id": 22, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "lag — сколько самое старое ДОСТУПНОЕ задание ждёт worker (растёт, если worker стоит); oldest_age — с момента постановки (включая backoff). Единицы: секунды.", + "gridPos": { + "h": 8, + "w": 8, + "x": 8, + "y": 36 + }, + "fieldConfig": { + "defaults": { + "unit": "s", + "custom": { + "lineWidth": 1, + "fillOpacity": 10, + "stacking": { + "mode": "none" + } + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "A", + "expr": "sli:queue_lag_seconds:max", + "legendFormat": "lag (ждёт worker)", + "range": true + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "B", + "expr": "sli:queue_oldest_age_seconds:max", + "legendFormat": "старейшее незавершённое", + "range": true + } + ] + }, + { + "type": "timeseries", + "title": "Брокер и outbox", + "id": 23, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "Разрыв DB→broker виден по outbox pending; worker не забирает — по NATS pending. Единицы: сообщений.", + "gridPos": { + "h": 8, + "w": 8, + "x": 16, + "y": 36 + }, + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 1, + "fillOpacity": 10, + "stacking": { + "mode": "none" + } + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "A", + "expr": "max(last_over_time(messenger_broker_pending{queue=\"attachments.process.v1\"}[30s]))", + "legendFormat": "NATS: не выдано", + "range": true + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "B", + "expr": "max(last_over_time(messenger_broker_ack_pending{queue=\"attachments.process.v1\"}[30s]))", + "legendFormat": "NATS: ждут ack", + "range": true + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "C", + "expr": "max(last_over_time(messenger_outbox_pending{queue=\"attachments.process.v1\"}[30s]))", + "legendFormat": "outbox: не опубликовано", + "range": true + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "D", + "expr": "sum by (outcome) (rate(messenger_outbox_publish_total[$__rate_interval])) * 60", + "legendFormat": "публикаций/мин {{outcome}}", + "range": true + } + ] + }, + { + "type": "row", + "title": "Насыщение ресурсов — пулы БД, worker, CPU/RAM", + "id": 24, + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 44 + }, + "panels": [] + }, + { + "type": "timeseries", + "title": "Пул БД: занято / максимум / ждут", + "id": 25, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "psycopg_pool по всем репликам сервиса. waiting > 0 — запросы ждут соединения (алерт DbPoolSaturated). Единицы: соединений/запросов.", + "gridPos": { + "h": 8, + "w": 8, + "x": 0, + "y": 45 + }, + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 1, + "fillOpacity": 10, + "stacking": { + "mode": "none" + } + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "A", + "expr": "sum by (service_name) (last_over_time(db_client_connection_count{db_client_connection_state=\"used\"}[30s]))", + "legendFormat": "used {{service_name}}", + "range": true + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "B", + "expr": "sum by (service_name) (last_over_time(db_client_connection_max[30s]))", + "legendFormat": "max {{service_name}}", + "range": true + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "C", + "expr": "sum by (service_name) (last_over_time(db_client_connection_pending_requests[30s]))", + "legendFormat": "waiting {{service_name}}", + "range": true + } + ] + }, + { + "type": "timeseries", + "title": "Worker: занятые слоты / ёмкость", + "id": 26, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "Обрабатываемые задания и WORKER_CONCURRENCY × число живых worker. Единицы: слотов.", + "gridPos": { + "h": 8, + "w": 8, + "x": 8, + "y": 45 + }, + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 1, + "fillOpacity": 10, + "stacking": { + "mode": "none" + } + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "A", + "expr": "sum(last_over_time(messenger_worker_busy[30s]))", + "legendFormat": "busy", + "range": true + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "B", + "expr": "sum(last_over_time(messenger_worker_capacity[30s]))", + "legendFormat": "capacity", + "range": true + } + ] + }, + { + "type": "timeseries", + "title": "CPU контейнеров", + "id": 27, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "container.cpu.time из cgroup (worker — вместе с подпроцессом обработки). Единицы: ядер (1 = одно ядро CPU).", + "gridPos": { + "h": 8, + "w": 8, + "x": 16, + "y": 45 + }, + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 1, + "fillOpacity": 10, + "stacking": { + "mode": "none" + } + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "A", + "expr": "sum by (service_name, service_instance_id) (rate(container_cpu_time_seconds_total[$__rate_interval]))", + "legendFormat": "{{service_name}} {{service_instance_id}}", + "range": true + } + ] + }, + { + "type": "timeseries", + "title": "Память контейнеров (рабочий набор) и лимит", + "id": 28, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "cgroup usage − inactive_file. Единицы: байты.", + "gridPos": { + "h": 8, + "w": 8, + "x": 0, + "y": 53 + }, + "fieldConfig": { + "defaults": { + "unit": "bytes", + "custom": { + "lineWidth": 1, + "fillOpacity": 10, + "stacking": { + "mode": "none" + } + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "A", + "expr": "sum by (service_name, service_instance_id) (last_over_time(container_memory_usage_bytes[30s]))", + "legendFormat": "{{service_name}} {{service_instance_id}}", + "range": true + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "B", + "expr": "max by (service_name) (last_over_time(messenger_container_memory_limit_bytes[30s]))", + "legendFormat": "лимит {{service_name}}", + "range": true + } + ] + }, + { + "type": "timeseries", + "title": "RSS процессов", + "id": 29, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "process.memory.usage (RSS основного процесса). Единицы: байты.", + "gridPos": { + "h": 8, + "w": 8, + "x": 8, + "y": 53 + }, + "fieldConfig": { + "defaults": { + "unit": "bytes", + "custom": { + "lineWidth": 1, + "fillOpacity": 10, + "stacking": { + "mode": "none" + } + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "A", + "expr": "sum by (service_name, service_instance_id) (last_over_time(process_memory_usage_bytes[30s]))", + "legendFormat": "{{service_name}} {{service_instance_id}}", + "range": true + } + ] + }, + { + "type": "timeseries", + "title": "Ожидание соединения пула и таймауты", + "id": 30, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "Суммарное время ожидания соединения в секунду (≈ среднее число ждущих) и неудачные получения соединения.", + "gridPos": { + "h": 8, + "w": 8, + "x": 16, + "y": 53 + }, + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 1, + "fillOpacity": 10, + "stacking": { + "mode": "none" + } + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "A", + "expr": "sum by (service_name) (rate(messenger_db_pool_wait_time_seconds_total[$__rate_interval]))", + "legendFormat": "ожидание с/с {{service_name}}", + "range": true + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "B", + "expr": "sum by (service_name) (rate(db_client_connection_timeouts_total[$__rate_interval]))", + "legendFormat": "таймауты/с {{service_name}}", + "range": true + } + ] + }, + { + "type": "row", + "title": "Конвейер telemetry — Collector и SDK (потери считаются)", + "id": 31, + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 61 + }, + "panels": [] + }, + { + "type": "timeseries", + "title": "Collector: принято / отправлено / ошибки", + "id": 32, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "Единицы: элементов/с. Алерт TelemetryExportFailing.", + "gridPos": { + "h": 8, + "w": 8, + "x": 0, + "y": 62 + }, + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 1, + "fillOpacity": 10, + "stacking": { + "mode": "none" + } + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "A", + "expr": "sum(rate(otelcol_receiver_accepted_spans_total[$__rate_interval]))", + "legendFormat": "spans принято", + "range": true + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "B", + "expr": "sum(rate(otelcol_exporter_sent_spans_total[$__rate_interval]))", + "legendFormat": "spans отправлено", + "range": true + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "C", + "expr": "sum(rate(otelcol_receiver_accepted_log_records_total[$__rate_interval]))", + "legendFormat": "logs принято", + "range": true + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "D", + "expr": "sum(rate(otelcol_exporter_sent_log_records_total[$__rate_interval]))", + "legendFormat": "logs отправлено", + "range": true + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "E", + "expr": "sum(rate(otelcol_receiver_refused_spans_total[$__rate_interval])) + sum(rate(otelcol_receiver_refused_log_records_total[$__rate_interval]))", + "legendFormat": "отклонено (memory_limiter)", + "range": true + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "F", + "expr": "sum(rate(otelcol_exporter_send_failed_spans_total[$__rate_interval])) + sum(rate(otelcol_exporter_send_failed_log_records_total[$__rate_interval]))", + "legendFormat": "не доставлено", + "range": true + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "G", + "expr": "sum(rate(otelcol_exporter_enqueue_failed_spans_total[$__rate_interval])) + sum(rate(otelcol_exporter_enqueue_failed_log_records_total[$__rate_interval]))", + "legendFormat": "очередь полна", + "range": true + } + ] + }, + { + "type": "timeseries", + "title": "Очереди экспортёров Collector", + "id": 33, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "Ограниченная очередь sending_queue (батчей). При недоступном backend растёт до ёмкости, затем данные отбрасываются.", + "gridPos": { + "h": 8, + "w": 8, + "x": 8, + "y": 62 + }, + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 1, + "fillOpacity": 10, + "stacking": { + "mode": "none" + } + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "A", + "expr": "sum by (exporter) (otelcol_exporter_queue_size)", + "legendFormat": "{{exporter}} размер", + "range": true + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "B", + "expr": "max(otelcol_exporter_queue_capacity)", + "legendFormat": "ёмкость", + "range": true + } + ] + }, + { + "type": "timeseries", + "title": "SDK: отброшено (очередь полна) / ошибки экспорта", + "id": 34, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "Self-метрики SDK (OTEL_PYTHON_SDK_INTERNAL_METRICS_ENABLED): при недоступном Collector очередь BatchSpanProcessor ограничена — лишнее отбрасывается и считается.", + "gridPos": { + "h": 8, + "w": 8, + "x": 16, + "y": 62 + }, + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 1, + "fillOpacity": 10, + "stacking": { + "mode": "none" + } + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "A", + "expr": "sum by (service_name, otel_component_type) (rate(otel_sdk_processor_span_processed_total{error_type!=\"\"}[$__rate_interval]))", + "legendFormat": "spans drop {{service_name}}", + "range": true + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "B", + "expr": "sum by (service_name) (rate(otel_sdk_processor_log_processed_total{error_type!=\"\"}[$__rate_interval]))", + "legendFormat": "logs drop {{service_name}}", + "range": true + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "refId": "C", + "expr": "sum by (service_name) (rate(otel_sdk_exporter_span_exported_total{error_type!=\"\"}[$__rate_interval]))", + "legendFormat": "spans export error {{service_name}}", + "range": true + } + ] + }, + { + "type": "row", + "title": "Логи (Loki) и трассы (Tempo)", + "id": 35, + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 70 + }, + "panels": [] + }, + { + "type": "logs", + "title": "Предупреждения и ошибки API/worker", + "id": 36, + "datasource": { + "type": "loki", + "uid": "loki" + }, + "description": "Структурные логи по OTLP: service_name — label; event, request_id, trace_id, job_id — structured metadata. Кнопка trace_id открывает trace в Tempo.", + "gridPos": { + "h": 10, + "w": 14, + "x": 0, + "y": 71 + }, + "options": { + "showTime": true, + "wrapLogMessage": true, + "enableLogDetails": true, + "sortOrder": "Descending" + }, + "targets": [ + { + "datasource": { + "type": "loki", + "uid": "loki" + }, + "refId": "A", + "expr": "{service_name=~\"messenger-api|messenger-worker\"} | severity_text=~\"WARN|ERROR|FATAL\"" + } + ] + }, + { + "type": "timeseries", + "title": "Объём логов по сервису и уровню", + "id": 37, + "datasource": { + "type": "loki", + "uid": "loki" + }, + "gridPos": { + "h": 10, + "w": 10, + "x": 14, + "y": 71 + }, + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "stacking": { + "mode": "normal" + }, + "fillOpacity": 30 + } + }, + "overrides": [] + }, + "targets": [ + { + "datasource": { + "type": "loki", + "uid": "loki" + }, + "refId": "A", + "expr": "sum by (service_name, severity_text) (count_over_time({service_name=~\"messenger-api|messenger-worker\"} [1m]))", + "legendFormat": "{{service_name}} {{severity_text}}" + } + ] + }, + { + "type": "table", + "title": "Трассы с ошибками", + "id": 38, + "datasource": { + "type": "tempo", + "uid": "tempo" + }, + "gridPos": { + "h": 9, + "w": 8, + "x": 0, + "y": 81 + }, + "targets": [ + { + "datasource": { + "type": "tempo", + "uid": "tempo" + }, + "refId": "A", + "queryType": "traceql", + "query": "{ resource.service.name =~ \"messenger-.*\" && status = error }", + "limit": 20, + "tableType": "traces" + } + ] + }, + { + "type": "table", + "title": "Медленные запросы API > 250 мс", + "id": 39, + "datasource": { + "type": "tempo", + "uid": "tempo" + }, + "gridPos": { + "h": 9, + "w": 8, + "x": 8, + "y": 81 + }, + "targets": [ + { + "datasource": { + "type": "tempo", + "uid": "tempo" + }, + "refId": "A", + "queryType": "traceql", + "query": "{ resource.service.name = \"messenger-api\" && kind = server && duration > 250ms }", + "limit": 20, + "tableType": "traces" + } + ] + }, + { + "type": "table", + "title": "Загрузка → worker (pipeline вложений)", + "id": 40, + "datasource": { + "type": "tempo", + "uid": "tempo" + }, + "gridPos": { + "h": 9, + "w": 8, + "x": 16, + "y": 81 + }, + "targets": [ + { + "datasource": { + "type": "tempo", + "uid": "tempo" + }, + "refId": "A", + "queryType": "traceql", + "query": "{ span.messaging.operation.type = \"process\" }", + "limit": 20, + "tableType": "traces" + } + ] + } + ] +} \ No newline at end of file diff --git a/infra/grafana/provisioning/alerting/README.md b/infra/grafana/provisioning/alerting/README.md new file mode 100644 index 00000000..4e5dd740 --- /dev/null +++ b/infra/grafana/provisioning/alerting/README.md @@ -0,0 +1 @@ +# Grafana-managed alert rules не используются: алерты — правила Prometheus (infra/prometheus/rules). diff --git a/infra/grafana/provisioning/dashboards/dashboards.yaml b/infra/grafana/provisioning/dashboards/dashboards.yaml new file mode 100644 index 00000000..889b8870 --- /dev/null +++ b/infra/grafana/provisioning/dashboards/dashboards.yaml @@ -0,0 +1,16 @@ +# Dashboards из Git: файлы JSON в /etc/grafana/dashboards импортируются автоматически +# (ручной набор не нужен; изменения в UI не сохраняются поверх файла). +apiVersion: 1 + +providers: + - name: messenger + orgId: 1 + folder: Messenger + folderUid: messenger + type: file + disableDeletion: true + allowUiUpdates: false + updateIntervalSeconds: 30 + options: + path: /etc/grafana/dashboards + foldersFromFilesStructure: false diff --git a/infra/grafana/provisioning/datasources/datasources.yaml b/infra/grafana/provisioning/datasources/datasources.yaml new file mode 100644 index 00000000..a46b4fbd --- /dev/null +++ b/infra/grafana/provisioning/datasources/datasources.yaml @@ -0,0 +1,75 @@ +# Источники данных Grafana (импортируются при старте; править в UI нельзя — источник истины в Git). +# Grafana — только интерфейс и запросы; данные хранят Prometheus, Loki и Tempo. +apiVersion: 1 + +deleteDatasources: [] + +datasources: + - name: Prometheus + uid: prometheus + type: prometheus + access: proxy + url: http://prometheus:9090 + isDefault: true + editable: false + jsonData: + httpMethod: POST + prometheusType: Prometheus + prometheusVersion: 3.5.0 + timeInterval: 10s # = scrape/экспорт метрик: минимальный шаг $__rate_interval + manageAlerts: true # правила Prometheus из Git видны в Grafana Alerting (Data source-managed, read-only) + + - name: Loki + uid: loki + type: loki + access: proxy + url: http://loki:3100 + editable: false + jsonData: + maxLines: 1000 + # trace_id хранится в structured metadata записи → ссылка «открыть trace» прямо из строки лога. + derivedFields: + - name: trace_id + matcherType: label + matcherRegex: trace_id + datasourceUid: tempo + url: '$${__value.raw}' + urlDisplayLabel: Открыть trace + + - name: Tempo + uid: tempo + type: tempo + access: proxy + url: http://tempo:3200 + editable: false + jsonData: + # Из span — к логам того же trace (structured metadata trace_id в Loki). + tracesToLogsV2: + datasourceUid: loki + spanStartTimeShift: '-5m' + spanEndTimeShift: '5m' + filterByTraceID: false + filterBySpanID: false + customQuery: true + query: '{service_name="$${__span.tags["service.name"]}"} | trace_id="$${__trace.traceId}"' + tracesToMetrics: + datasourceUid: prometheus + spanStartTimeShift: '-5m' + spanEndTimeShift: '5m' + tags: + - {key: service.name, value: service_name} + queries: + - name: p95 HTTP по сервису + query: 'histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{$$__tags}[1m])))' + serviceMap: + datasourceUid: prometheus + nodeGraph: + enabled: true + search: + hide: false + lokiSearch: + datasourceUid: loki + traceQuery: + timeShiftEnabled: true + spanStartTimeShift: '-30m' + spanEndTimeShift: '30m' diff --git a/infra/grafana/provisioning/plugins/README.md b/infra/grafana/provisioning/plugins/README.md new file mode 100644 index 00000000..c7c7f838 --- /dev/null +++ b/infra/grafana/provisioning/plugins/README.md @@ -0,0 +1 @@ +# Плагины не устанавливаются (стенд без доступа в интернет; GF_PLUGINS_PREINSTALL_DISABLED=true). diff --git a/infra/haproxy/haproxy.cfg b/infra/haproxy/haproxy.cfg new file mode 100644 index 00000000..07c28067 --- /dev/null +++ b/infra/haproxy/haproxy.cfg @@ -0,0 +1,100 @@ +# HAProxy 3.0 — единственная публичная точка входа lab3. +# Бэкенды находятся через DNS Docker (имя сервиса `api` → IP всех реплик), без sticky sessions. +# +# Обнаружение отказа реплики: +# * активная проверка GET /health/ready: inter 1s, после первой ошибки fastinter 500ms, fall 2, +# timeout check 300ms → худший случай обнаружения ≈ 1 + 0.3 + 0.5 + 0.3 ≈ 2.1 с; +# * пассивно: соединение отвергнуто → retry-on conn-failure + redispatch на другую реплику +# (только если запрос ещё не отправлен — безопасно и для неидемпотентных POST). +# * graceful shutdown реплики: SIGTERM → /health/ready = 503 на SHUTDOWN_DRAIN_SECONDS=3 с +# (> fall × fastinter) → LB выводит реплику до того, как она закроет listener. + +global + log stdout format raw local0 info + maxconn 4096 + +defaults + mode http + log global + option httplog + option dontlognull + timeout connect 300ms # сеть Docker: connect < 1 мс; к «мёртвому» IP (kill) нет RST — ждём не дольше 300 мс + timeout check 300ms # проверка не висит 1 с на убитой реплике → быстрее fall + timeout client 60s # lab4: загрузка до 10 МиБ медленным клиентом + timeout server 60s # бездействие сервера; > REQUEST_TIMEOUT_SECONDS (10 с); upload/download — потоки + timeout http-request 10s + timeout http-keep-alive 10s + timeout queue "${LB_QUEUE_TIMEOUT}" # сколько запрос может ждать свободный слот maxconn в очереди LB + retries 2 + option redispatch 1 + retry-on conn-failure # НЕ empty-response/response-timeout: иначе возможен повтор выполненного POST + unique-id-format %[uuid()] # request_id ответов самого LB: случайный, без IP/портов + default-server inter 1s fastinter 500ms downinter 2s fall 2 rise 2 init-addr none resolvers docker + # Ответы, созданные самим LB, — в формате ошибок API (X-Instance-Id у них нет, это допустимо). + http-error status 503 content-type application/json lf-string '{"error":{"code":"unavailable","message":"Нет доступных реплик API","request_id":"%[unique-id]"}}' hdr X-Request-Id %[unique-id] hdr Retry-After 1 + http-error status 502 content-type application/json lf-string '{"error":{"code":"unavailable","message":"Реплика API недоступна","request_id":"%[unique-id]"}}' hdr X-Request-Id %[unique-id] + http-error status 504 content-type application/json lf-string '{"error":{"code":"unavailable","message":"Таймаут реплики API","request_id":"%[unique-id]"}}' hdr X-Request-Id %[unique-id] + +resolvers docker + nameserver dns 127.0.0.11:53 + resolve_retries 3 + timeout resolve 1s + timeout retry 1s + hold valid 2s + hold obsolete 5s # исчезнувший из DNS контейнер убирается из слота через 5 с + accepted_payload_size 8192 + +frontend api + bind :8080 + # Внутренняя диагностика реплик снаружи недоступна. + http-request return status 404 content-type application/json lf-string '{"error":{"code":"not_found","message":"Объект не найден","request_id":"%[unique-id]"}}' hdr X-Request-Id %[unique-id] if { path_beg /internal } + default_backend api + +frontend api_ttl + bind :8081 + http-request return status 404 content-type application/json lf-string '{"error":{"code":"not_found","message":"Объект не найден","request_id":"%[unique-id]"}}' hdr X-Request-Id %[unique-id] if { path_beg /internal } + default_backend api_ttl + +frontend api_fault + bind :8082 + http-request return status 404 content-type application/json lf-string '{"error":{"code":"not_found","message":"Объект не найден","request_id":"%[unique-id]"}}' hdr X-Request-Id %[unique-id] if { path_beg /internal } + default_backend api_fault + +frontend stats + bind :8404 + stats enable + stats uri /stats + stats refresh 2s + stats show-legends + +backend api + balance roundrobin # без stickiness: состояние не хранится в реплике + option httpchk + http-check send meth GET uri /health/ready + http-check expect status 200 + http-reuse safe + # maxconn: не больше LB_SERVER_MAXCONN одновременных запросов на реплику, излишек ждёт в очереди LB + # (0 = без ограничения). Обоснование значения — трек 5.1 в REPORT.md. + server-template api 8 api:8080 check maxconn "${LB_SERVER_MAXCONN}" + # «Panic mode»: если readiness не проходит НИ У ОДНОЙ реплики (например, упала БД), запросы всё + # равно идут в живые процессы, и клиент получает ответ приложения (401 анониму, 503 unavailable + # в формате API, /health/live = 200), а не безликий 503 LB. Мёртвый процесс → conn-failure → 503 LB. + option allbackups + server-template apibk 8 api:8080 backup resolve-opts allow-dup-ip + +backend api_ttl + balance roundrobin + option httpchk + http-check send meth GET uri /health/ready + http-check expect status 200 + server-template ttl 2 api-ttl:8080 check + option allbackups + server-template ttlbk 2 api-ttl:8080 backup resolve-opts allow-dup-ip + +# Только для теста компенсации (профиль fault). Без сервиса api-fault слоты пусты — бэкенд DOWN. +backend api_fault + balance roundrobin + option httpchk + http-check send meth GET uri /health/ready + http-check expect status 200 + server-template fault 1 api-fault:8080 check diff --git a/infra/loki/loki.yaml b/infra/loki/loki.yaml new file mode 100644 index 00000000..24a739a1 --- /dev/null +++ b/infra/loki/loki.yaml @@ -0,0 +1,66 @@ +# Loki 3.5 — хранилище логов (single binary, файловая система на volume lokidata). +# Логи приходят по native OTLP (/otlp/v1/logs) из Collector. Ресурсные атрибуты service.name, +# service.instance.id, deployment.environment.name → index labels (низкая кардинальность); +# атрибуты записи (event, request_id, job_id, trace_id, span_id …) → structured metadata +# (не индексируются как labels, но фильтруются: {service_name="messenger-api"} | request_id="…"). +auth_enabled: false + +server: + http_listen_port: 3100 + grpc_listen_port: 9096 + log_level: warn + +common: + instance_addr: 127.0.0.1 + path_prefix: /loki + storage: + filesystem: + chunks_directory: /loki/chunks + rules_directory: /loki/rules + replication_factor: 1 + ring: + kvstore: + store: inmemory + +schema_config: + configs: + - from: 2024-01-01 + store: tsdb + object_store: filesystem + schema: v13 + index: + prefix: index_ + period: 24h + +limits_config: + allow_structured_metadata: true + volume_enabled: true + retention_period: 168h # 7 дней учебной истории + ingestion_rate_mb: 8 + ingestion_burst_size_mb: 16 + max_label_names_per_series: 15 + otlp_config: + resource_attributes: + attributes_config: + - action: index_label + attributes: [deployment.environment.name] + +compactor: + working_directory: /loki/compactor + retention_enabled: true + delete_request_store: filesystem + compaction_interval: 10m + +ingester: + chunk_idle_period: 5m + max_chunk_age: 1h + +query_range: + results_cache: + cache: + embedded_cache: + enabled: true + max_size_mb: 50 + +analytics: + reporting_enabled: false # без отправки статистики во внешний интернет diff --git a/infra/otel/collector-tail.yaml b/infra/otel/collector-tail.yaml new file mode 100644 index 00000000..69a9d915 --- /dev/null +++ b/infra/otel/collector-tail.yaml @@ -0,0 +1,122 @@ +# OpenTelemetry Collector (contrib 0.130.0) — получатель/обработчик/экспортёр, НЕ хранилище. +# API и worker → OTLP/HTTP :4318 (сеть telemetry, наружу не публикуется) → три pipeline: +# traces → Tempo (OTLP/HTTP http://tempo:4318) +# metrics → Prometheus (OTLP receiver http://prometheus:9090/api/v1/otlp) +# logs → Loki (native OTLP http://loki:3100/otlp) +# Защита памяти и поведение при недоступном backend: +# * memory_limiter — первым в каждой pipeline: при росте RAM выше limit-spike Collector отклоняет приём +# (SDK получает 503/429, повторяет и затем отбрасывает — потери считаются на стороне SDK); +# * sending_queue каждого экспортёра — ограниченная очередь в памяти (queue_size батчей); при переполнении +# новые данные отбрасываются (otelcol_exporter_enqueue_failed_*), а не накапливаются бесконечно; +# * retry_on_failure — повтор с экспоненциальной паузой, не дольше max_elapsed_time, затем батч отбрасывается +# (otelcol_exporter_send_failed_*). Telemetry — «best effort»: бизнес-запросы от неё не зависят. +# ВАРИАНТ ТРЕКА 1 «сбалансированный»: SDK отправляет 100% spans, решение о хранении trace принимает +# Collector ПОСЛЕ завершения trace (tail sampling): все ошибки, все медленные, все trace pipeline вложений +# и 10% остальных. Метрики RED считаются в SDK по всем запросам и от sampling не зависят. +# Ограничение: один экземпляр Collector (все spans trace приходят в один процесс); для нескольких — +# loadbalancing exporter по trace_id. Включение: OTEL_COLLECTOR_CONFIG=collector-tail.yaml. + +extensions: + health_check: + endpoint: 0.0.0.0:13133 # внутренняя сеть observability; на хост не публикуется + +receivers: + otlp: + protocols: + http: + endpoint: 0.0.0.0:4318 + max_request_body_size: 8388608 # 8 MiB на запрос экспорта + +processors: + memory_limiter: + check_interval: 1s + limit_mib: 200 # контейнер ограничен 256 MiB + spike_limit_mib: 50 # мягкий порог 150 MiB: дальше приём отклоняется + tail_sampling: + decision_wait: 10s # ждать spans trace (worker завершает задание через секунды) + num_traces: 20000 # предел trace в памяти; старые решения вытесняются + expected_new_traces_per_sec: 200 + decision_cache: + sampled_cache_size: 20000 # поздние spans (повтор задания) получают то же решение + non_sampled_cache_size: 20000 + policies: + - name: errors + type: status_code + status_code: {status_codes: [ERROR]} + - name: slow + type: latency + latency: {threshold_ms: 250} + - name: attachment-pipeline # upload → worker: редкие и дорогие операции храним все + type: string_attribute + string_attribute: {key: messaging.system, values: [nats]} + - name: baseline + type: probabilistic + probabilistic: {sampling_percentage: 10} + batch: + send_batch_size: 1024 + send_batch_max_size: 2048 + timeout: 2s + # Защита «в глубину»: даже если код по ошибке положит такой атрибут, в хранилища он не уйдёт. + attributes/scrub: + actions: + - pattern: '(?i)^(.*\.)?(password|passwd|token|access_token|session_token|authorization|cookie|secret|api_key)$' + action: delete + - pattern: '(?i)^http\.request\.header\.(authorization|cookie|x-api-key)$' + action: delete + - key: db.query.parameters + action: delete + +exporters: + otlphttp/tempo: + endpoint: http://tempo:4318 + compression: gzip + timeout: 5s + sending_queue: &queue + enabled: true + num_consumers: 2 + queue_size: 200 # батчей (≤ 2048 элементов каждый) — предел RAM очереди + retry_on_failure: &retry + enabled: true + initial_interval: 1s + max_interval: 10s + max_elapsed_time: 120s + otlphttp/loki: + endpoint: http://loki:3100/otlp + compression: gzip + timeout: 5s + sending_queue: *queue + retry_on_failure: *retry + otlphttp/prometheus: + endpoint: http://prometheus:9090/api/v1/otlp + compression: gzip + timeout: 5s + sending_queue: *queue + retry_on_failure: *retry + +service: + extensions: [health_check] + telemetry: + logs: + level: info + metrics: + level: detailed # otelcol_* метрики самого Collector: принято/отклонено/отправлено/очереди + readers: + - pull: + exporter: + prometheus: + host: 0.0.0.0 + port: 8888 # скрейпит Prometheus (сеть observability) + without_units: true # классические имена: otelcol_exporter_sent_spans_total (без «_{spans}») + pipelines: + traces: + receivers: [otlp] + processors: [memory_limiter, attributes/scrub, tail_sampling, batch] + exporters: [otlphttp/tempo] + metrics: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [otlphttp/prometheus] + logs: + receivers: [otlp] + processors: [memory_limiter, attributes/scrub, batch] + exporters: [otlphttp/loki] diff --git a/infra/otel/collector.yaml b/infra/otel/collector.yaml new file mode 100644 index 00000000..d0fab6f8 --- /dev/null +++ b/infra/otel/collector.yaml @@ -0,0 +1,98 @@ +# OpenTelemetry Collector (contrib 0.130.0) — получатель/обработчик/экспортёр, НЕ хранилище. +# API и worker → OTLP/HTTP :4318 (сеть telemetry, наружу не публикуется) → три pipeline: +# traces → Tempo (OTLP/HTTP http://tempo:4318) +# metrics → Prometheus (OTLP receiver http://prometheus:9090/api/v1/otlp) +# logs → Loki (native OTLP http://loki:3100/otlp) +# Защита памяти и поведение при недоступном backend: +# * memory_limiter — первым в каждой pipeline: при росте RAM выше limit-spike Collector отклоняет приём +# (SDK получает 503/429, повторяет и затем отбрасывает — потери считаются на стороне SDK); +# * sending_queue каждого экспортёра — ограниченная очередь в памяти (queue_size батчей); при переполнении +# новые данные отбрасываются (otelcol_exporter_enqueue_failed_*), а не накапливаются бесконечно; +# * retry_on_failure — повтор с экспоненциальной паузой, не дольше max_elapsed_time, затем батч отбрасывается +# (otelcol_exporter_send_failed_*). Telemetry — «best effort»: бизнес-запросы от неё не зависят. +# Конфигурация трека 1 со сбалансированным tail sampling — collector-tail.yaml (OTEL_COLLECTOR_CONFIG). + +extensions: + health_check: + endpoint: 0.0.0.0:13133 # внутренняя сеть observability; на хост не публикуется + +receivers: + otlp: + protocols: + http: + endpoint: 0.0.0.0:4318 + max_request_body_size: 8388608 # 8 MiB на запрос экспорта + +processors: + memory_limiter: + check_interval: 1s + limit_mib: 200 # контейнер ограничен 256 MiB + spike_limit_mib: 50 # мягкий порог 150 MiB: дальше приём отклоняется + batch: + send_batch_size: 1024 + send_batch_max_size: 2048 + timeout: 2s + # Защита «в глубину»: даже если код по ошибке положит такой атрибут, в хранилища он не уйдёт. + attributes/scrub: + actions: + - pattern: '(?i)^(.*\.)?(password|passwd|token|access_token|session_token|authorization|cookie|secret|api_key)$' + action: delete + - pattern: '(?i)^http\.request\.header\.(authorization|cookie|x-api-key)$' + action: delete + - key: db.query.parameters + action: delete + +exporters: + otlphttp/tempo: + endpoint: http://tempo:4318 + compression: gzip + timeout: 5s + sending_queue: &queue + enabled: true + num_consumers: 2 + queue_size: 200 # батчей (≤ 2048 элементов каждый) — предел RAM очереди + retry_on_failure: &retry + enabled: true + initial_interval: 1s + max_interval: 10s + max_elapsed_time: 120s + otlphttp/loki: + endpoint: http://loki:3100/otlp + compression: gzip + timeout: 5s + sending_queue: *queue + retry_on_failure: *retry + otlphttp/prometheus: + endpoint: http://prometheus:9090/api/v1/otlp + compression: gzip + timeout: 5s + sending_queue: *queue + retry_on_failure: *retry + +service: + extensions: [health_check] + telemetry: + logs: + level: info + metrics: + level: detailed # otelcol_* метрики самого Collector: принято/отклонено/отправлено/очереди + readers: + - pull: + exporter: + prometheus: + host: 0.0.0.0 + port: 8888 # скрейпит Prometheus (сеть observability) + without_units: true # классические имена: otelcol_exporter_sent_spans_total (без «_{spans}») + pipelines: + traces: + receivers: [otlp] + processors: [memory_limiter, attributes/scrub, batch] + exporters: [otlphttp/tempo] + metrics: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [otlphttp/prometheus] + logs: + receivers: [otlp] + processors: [memory_limiter, attributes/scrub, batch] + exporters: [otlphttp/loki] diff --git a/infra/prometheus/prometheus.yml b/infra/prometheus/prometheus.yml new file mode 100644 index 00000000..565e2da6 --- /dev/null +++ b/infra/prometheus/prometheus.yml @@ -0,0 +1,34 @@ +# Prometheus 3.5 LTS — хранилище метрик. Метрики приложения приходят PUSH через Collector на OTLP receiver +# (--web.enable-otlp-receiver); метрики самих компонентов наблюдаемости — обычный scrape. +global: + scrape_interval: 10s + evaluation_interval: 10s # правила алертов/записи проверяются каждые 10 с + +# Ресурсные атрибуты OTel → labels каждой серии (иначе они только в target_info). +# service.instance.id — низкокардинальный: число реплик × перезапуски (случайный alias процесса). +otlp: + promote_resource_attributes: + - service.name + - service.namespace + - service.instance.id + - deployment.environment.name + translation_strategy: UnderscoreEscapingWithSuffixes # http.server.request.duration → http_server_request_duration_seconds + +storage: + tsdb: + out_of_order_time_window: 10m # повторная отправка Collector после восстановления backend + +rule_files: + - /etc/prometheus/rules/*.yml + +scrape_configs: + - job_name: prometheus + static_configs: [{targets: ['localhost:9090']}] + - job_name: otel-collector # otelcol_*: принято/отклонено/отправлено/очереди экспортёров + static_configs: [{targets: ['otel-collector:8888']}] + - job_name: loki + static_configs: [{targets: ['loki:3100']}] + - job_name: tempo + static_configs: [{targets: ['tempo:3200']}] + - job_name: grafana + static_configs: [{targets: ['grafana:3000']}] diff --git a/infra/prometheus/rules/messenger.yml b/infra/prometheus/rules/messenger.yml new file mode 100644 index 00000000..93fabd5a --- /dev/null +++ b/infra/prometheus/rules/messenger.yml @@ -0,0 +1,138 @@ +# Правила записи (SLI) и алерты мессенджера. Окна сжаты под учебный стенд (минуты вместо часов/дней): +# цель — проверяемо увидеть firing → resolved за время защиты. Runbook: docs/runbooks.md. +# +# SLI/SLO (обоснование — REPORT.md, раздел «SLI/SLO»): +# * доступность API: доля НЕ-5xx среди бизнес-запросов (без /health/* и /internal/*), SLO 99.5% за 1 ч; +# 4xx (неверный пароль, 404 чужого чата) — ошибки клиента и в бюджет НЕ входят; +# * задержка API: доля бизнес-запросов быстрее 250 мс, SLO 95% за 1 ч. Не входят upload (время передачи +# файла клиентом) и регистрация/вход (KDF scrypt намеренно медленный, ~0.1–0.3 с); +# * time to ready: доля вложений, ставших ready быстрее 10 с после 202, SLO 95% за 1 ч. +groups: + - name: messenger-sli + interval: 10s + rules: + - record: sli:api_requests:rate1m + expr: sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api",http_route!~"/health/.*|/internal/.*"}[1m])) + - record: sli:api_errors:rate1m + expr: sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api",http_route!~"/health/.*|/internal/.*",http_response_status_class="5xx"}[1m])) or vector(0) + - record: sli:api_error_ratio:rate1m + expr: sli:api_errors:rate1m / clamp_min(sli:api_requests:rate1m, 1e-9) + - record: sli:api_latency_p95:1m + expr: histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{service_name="messenger-api",http_route!~"/health/.*|/internal/.*|/api/v1/chats/\\{chat_id\\}/attachments|/api/v1/users|/api/v1/auth/sessions"}[1m]))) + - record: sli:api_fast_ratio:rate5m + expr: | + sum(rate(http_server_request_duration_seconds_bucket{service_name="messenger-api",le="0.25",http_route!~"/health/.*|/internal/.*|/api/v1/chats/\\{chat_id\\}/attachments|/api/v1/users|/api/v1/auth/sessions"}[5m])) + / clamp_min(sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api",http_route!~"/health/.*|/internal/.*|/api/v1/chats/\\{chat_id\\}/attachments|/api/v1/users|/api/v1/auth/sessions"}[5m])), 1e-9) + - record: sli:time_to_ready_fast_ratio:rate15m + expr: | + sum(rate(messenger_attachment_time_to_ready_seconds_bucket{le="10"}[15m])) + / clamp_min(sum(rate(messenger_attachment_time_to_ready_seconds_count[15m])), 1e-9) + - record: sli:queue_lag_seconds:max + expr: max(last_over_time(messenger_queue_lag_seconds{queue="attachments.process.v1"}[30s])) + - record: sli:queue_oldest_age_seconds:max + expr: max(last_over_time(messenger_queue_oldest_age_seconds{queue="attachments.process.v1"}[30s])) + + - name: messenger-alerts + interval: 10s + rules: + - alert: ApiHighErrorRate + # Условие: > 5% ответов 5xx за 1 мин при ≥ 0.2 запроса/с (иначе один сбой из 3 запросов = 33%). + expr: sli:api_error_ratio:rate1m > 0.05 and sli:api_requests:rate1m > 0.2 + for: 30s + labels: {severity: critical, service: messenger-api} + annotations: + summary: "Доля 5xx API {{ $value | humanizePercentage }} > 5% (окно 1 мин)" + description: "Бизнес-запросы (без /health, /internal) завершаются 5xx. Сначала — trace с error.type в Tempo и логи event=dependency.unavailable в Loki." + runbook_url: "docs/runbooks.md#apihigherrorrate" + - alert: ApiLatencyHigh + # Порог = цель SLO задержки (250 мс): p95 выше — SLO нарушается прямо сейчас. + expr: sli:api_latency_p95:1m > 0.25 and sli:api_requests:rate1m > 0.2 + for: 1m + labels: {severity: warning, service: messenger-api} + annotations: + summary: "p95 API {{ $value | humanizeDuration }} > 250 мс (окно 1 мин)" + description: "Медленный API. Сравните p95 db.client.operation.duration (БД) с HTTP p95 (обработчик/CPU)." + runbook_url: "docs/runbooks.md#apilatencyhigh" + - alert: DbSlowQueries + # Обычно p95 запроса ≈ 2–5 мс: 50 мс — на порядок медленнее нормы. + expr: histogram_quantile(0.95, sum by (le) (rate(db_client_operation_duration_seconds_bucket[1m]))) > 0.05 + for: 30s + labels: {severity: warning, service: postgres} + annotations: + summary: "p95 запросов к PostgreSQL {{ $value | humanizeDuration }} > 50 мс" + description: "Медленная БД (не обработчик): растёт время execute по client spans/метрике всех сервисов." + runbook_url: "docs/runbooks.md#dbslowqueries" + - alert: DbPoolSaturated + expr: max by (service_name) (last_over_time(db_client_connection_pending_requests[30s])) > 0 + for: 30s + labels: {severity: warning} + annotations: + summary: "{{ $labels.service_name }}: запросы ждут соединения пула БД" + description: "Все соединения заняты: БД медленная или пул мал. Смотрите db_client_connection_count{state=used} и p95 БД." + runbook_url: "docs/runbooks.md#dbpoolsaturated" + - alert: JobQueueLagGrowing + # queue lag = сколько ждёт самое старое задание, уже доступное worker (backoff повторов не считается). + expr: sli:queue_lag_seconds:max > 30 + for: 20s + labels: {severity: critical, service: messenger-worker} + annotations: + summary: "Задания ждут worker уже {{ $value | humanizeDuration }} (> 30 с)" + description: "Backlog не разбирается: worker остановлены/перегружены/не получают сообщения. Сравните messenger_queue_depth{state=ready} и messenger_worker_busy/capacity." + runbook_url: "docs/runbooks.md#jobqueuelaggrowing" + - alert: WorkerHeartbeatMissing + # Метрики worker приходят каждые 10 с. Нет свежих — ни один worker не работает (или не экспортирует). + # Подавляется, если Collector был недоступен последние 2 мин: тогда метрик нет у ВСЕХ сервисов — + # это OtelCollectorDown, а не смерть worker. + expr: ((time() - max(timestamp(messenger_worker_capacity))) > 45 or absent(messenger_worker_capacity)) + unless on() (min_over_time(up{job="otel-collector"}[2m]) == 0) + for: 15s + labels: {severity: critical, service: messenger-worker} + annotations: + summary: "Нет метрик ни одного worker дольше 45 с" + description: "Все worker остановлены, упали или не могут экспортировать telemetry. Проверьте docker compose ps worker и логи." + runbook_url: "docs/runbooks.md#workerheartbeatmissing" + - alert: JobsFailing + expr: sum(increase(messenger_jobs_processed_total{outcome="failed"}[5m])) > 0 + labels: {severity: warning, service: messenger-worker} + annotations: + summary: "За 5 мин {{ $value }} заданий завершились failed" + description: "Финальные ошибки обработки (invalid_image/retry_exhausted…). Реестр: python -m messenger jobs failed." + runbook_url: "docs/runbooks.md#jobsfailing" + - alert: TelemetryExportFailing + # Мета-мониторинг: Collector не может отправить данные в backend (или отбрасывает из-за очереди). + expr: | + sum(rate(otelcol_exporter_send_failed_spans_total[1m])) + sum(rate(otelcol_exporter_send_failed_log_records_total[1m])) + + sum(rate(otelcol_exporter_enqueue_failed_spans_total[1m])) + sum(rate(otelcol_exporter_enqueue_failed_log_records_total[1m])) > 0 + or sum(otelcol_exporter_queue_size) > 20 + for: 30s + labels: {severity: warning, service: otel-collector} + annotations: + summary: "Collector не доставляет telemetry в backend" + description: "Tempo/Loki/Prometheus недоступен: очередь экспортёра растёт или батчи отбрасываются. Бизнес-API от этого не зависит." + runbook_url: "docs/runbooks.md#telemetryexportfailing" + - alert: OtelCollectorDown + # Collector не отвечает на scrape: telemetry всех сервисов не принимается (SDK отбрасывает и считает). + expr: up{job="otel-collector"} == 0 + for: 20s + labels: {severity: warning, service: otel-collector} + annotations: + summary: "OTel Collector недоступен" + description: "Новые метрики/логи/трассы приложения не поступают; API работает. Потери видны после восстановления в otel_sdk_exporter_*_exported_total{error_type}." + runbook_url: "docs/runbooks.md#otelcollectordown" + - alert: TelemetryLostInSdk + # Сообщает ПОСЛЕ восстановления канала (счётчики SDK доставляются тем же Collector): сколько spans/logs + # не удалось экспортировать или пришлось отбросить из-за переполнения очереди SDK. Серия с error_type + # появляется впервые уже со значением N, поэтому не increase() (он не видит первого значения новой + # серии), а разность «сейчас − 5 мин назад» (отсутствие серии = 0). + expr: | + ((sum(otel_sdk_exporter_span_exported_total{error_type!=""}) or vector(0)) + - (sum(otel_sdk_exporter_span_exported_total{error_type!=""} offset 5m) or vector(0))) + + ((sum(otel_sdk_processor_span_processed_total{error_type!=""}) or vector(0)) + - (sum(otel_sdk_processor_span_processed_total{error_type!=""} offset 5m) or vector(0))) + + ((sum(otel_sdk_exporter_log_exported_total{error_type!=""}) or vector(0)) + - (sum(otel_sdk_exporter_log_exported_total{error_type!=""} offset 5m) or vector(0))) > 0 + labels: {severity: info, service: telemetry} + annotations: + summary: "SDK потерял {{ $value | humanize }} spans/logs за 5 мин" + description: "Collector был недоступен или очередь SDK переполнилась. В trace/логах за этот интервал есть пропуски; метрики RED не потеряны (кумулятивные счётчики)." + runbook_url: "docs/runbooks.md#telemetrylostinsdk" diff --git a/infra/tempo/tempo.yaml b/infra/tempo/tempo.yaml new file mode 100644 index 00000000..507460c9 --- /dev/null +++ b/infra/tempo/tempo.yaml @@ -0,0 +1,58 @@ +# Tempo 2.8 — хранилище трасс (monolithic, локальный диск на volume tempodata). +# Spans приходят по OTLP/HTTP из Collector. metrics_generator строит из spans service graph и +# span-метрики и пишет их в Prometheus (remote write) — для карты сервисов в Grafana. +# ВАЖНО (трек 1): span-метрики считаются по СОХРАНЁННЫМ spans и при sampling занижены; RED API берётся +# из метрик SDK, которые от sampling не зависят. +stream_over_http_enabled: true +server: + http_listen_port: 3200 + grpc_listen_port: 9097 + log_level: warn + +distributor: + receivers: + otlp: + protocols: + http: + endpoint: 0.0.0.0:4318 + +ingester: + max_block_duration: 5m # блоки чаще сбрасываются на диск (учебная нагрузка невелика) + trace_idle_period: 10s + +compactor: + compaction: + block_retention: 168h # 7 дней + +metrics_generator: + registry: + external_labels: + source: tempo + storage: + path: /var/tempo/generator/wal + remote_write: + - url: http://prometheus:9090/api/v1/write + send_exemplars: false + traces_storage: + path: /var/tempo/generator/traces + processor: + service_graphs: + dimensions: [] + span_metrics: + dimensions: [] + +storage: + trace: + backend: local + wal: + path: /var/tempo/wal + local: + path: /var/tempo/blocks + +overrides: + defaults: + metrics_generator: + processors: [service-graphs, span-metrics] + +usage_report: + reporting_enabled: false diff --git a/migrations/0001_init.sql b/migrations/0001_init.sql new file mode 100644 index 00000000..bf743f6b --- /dev/null +++ b/migrations/0001_init.sql @@ -0,0 +1,63 @@ +-- 0001: базовая схема lab2. Источник истины — PostgreSQL. +-- Миграция выполняется раннером в одной транзакции и регистрируется в schema_migrations. + +CREATE TABLE users ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + username text NOT NULL, + display_name text NOT NULL, + password_hash text NOT NULL, + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + CONSTRAINT users_username_key UNIQUE (username), + CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'), + CONSTRAINT users_display_name_len CHECK (char_length(display_name) BETWEEN 1 AND 100), + CONSTRAINT users_password_hash_kdf CHECK (password_hash LIKE '$scrypt$%') +); + +CREATE TABLE chats ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + title text NOT NULL, + created_by uuid NOT NULL REFERENCES users (id), + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + CONSTRAINT chats_title_len CHECK (char_length(title) BETWEEN 1 AND 100) +); + +-- Состав участников неизменен в обязательном API; position сохраняет порядок member_ids из запроса. +CREATE TABLE chat_members ( + chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE, + user_id uuid NOT NULL REFERENCES users (id), + position smallint NOT NULL, + PRIMARY KEY (chat_id, user_id), + CONSTRAINT chat_members_position_key UNIQUE (chat_id, position), + CONSTRAINT chat_members_position_range CHECK (position BETWEEN 0 AND 99) +); +-- GET /chats: «чаты пользователя» — поиск по user_id. +CREATE INDEX chat_members_user_idx ON chat_members (user_id, chat_id); + +CREATE TABLE messages ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + chat_id uuid NOT NULL, + sender_id uuid NOT NULL, + text text NOT NULL, + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + -- Отправитель обязан быть участником этого чата: инвариант защищён на уровне БД. + CONSTRAINT messages_sender_is_member FOREIGN KEY (chat_id, sender_id) + REFERENCES chat_members (chat_id, user_id), + CONSTRAINT messages_text_len CHECK (char_length(text) BETWEEN 1 AND 4000) +); +-- История: WHERE chat_id = $1 AND (created_at, id) > ($2, $3) ORDER BY created_at, id LIMIT n. +-- Обоснование и EXPLAIN — REPORT.md и evidence/track2/. +CREATE INDEX messages_chat_created_id_idx ON messages (chat_id, created_at, id); + +-- Серверные сессии. Хранится только SHA-256 от токена (токен — 256 бит случайности), +-- поэтому утечка дампа не даёт готовых Bearer-токенов. +CREATE TABLE sessions ( + token_hash bytea PRIMARY KEY, + user_id uuid NOT NULL REFERENCES users (id), + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + expires_at timestamptz NOT NULL, + revoked_at timestamptz, + CONSTRAINT sessions_token_hash_len CHECK (octet_length(token_hash) = 32), + CONSTRAINT sessions_expiry_after_creation CHECK (expires_at > created_at) +); +CREATE INDEX sessions_user_idx ON sessions (user_id); +CREATE INDEX sessions_expires_idx ON sessions (expires_at); diff --git a/migrations/0002_cache_invalidation_outbox.sql b/migrations/0002_cache_invalidation_outbox.sql new file mode 100644 index 00000000..5a6a496f --- /dev/null +++ b/migrations/0002_cache_invalidation_outbox.sql @@ -0,0 +1,8 @@ +-- 0002: транзакционный outbox инвалидации кэша сессий (уровень 4). +-- Строка пишется в той же транзакции, что и revoked_at. Если Redis недоступен в момент logout, +-- фоновый процесс API повторит инвалидацию после восстановления Redis и только затем снова +-- начнёт читать сессии из кэша. +CREATE TABLE session_cache_invalidations ( + token_hash bytea PRIMARY KEY REFERENCES sessions (token_hash) ON DELETE CASCADE, + created_at timestamptz NOT NULL DEFAULT clock_timestamp() +); diff --git a/migrations/0003_idempotency_keys.sql b/migrations/0003_idempotency_keys.sql new file mode 100644 index 00000000..bd5e0dbd --- /dev/null +++ b/migrations/0003_idempotency_keys.sql @@ -0,0 +1,17 @@ +-- 0003 (lab3): общая идемпотентность POST /chats/{chat_id}/messages. +-- Область ключа = пользователь + метод + путь чата + ключ. Единственный идемпотентный endpoint +-- обязательного API — POST сообщения, поэтому метод и шаблон пути фиксированы, а «путь» = chat_id. +-- Миграция аддитивна (expand): код lab2 её не использует и продолжает работать при rolling update. +CREATE TABLE idempotency_keys ( + user_id uuid NOT NULL REFERENCES users (id), + chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE, + key text NOT NULL, + request_hash bytea NOT NULL, + message_id uuid NOT NULL REFERENCES messages (id) ON DELETE CASCADE, + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + PRIMARY KEY (user_id, chat_id, key), + CONSTRAINT idempotency_key_format CHECK (key ~ '^[A-Za-z0-9._:-]{1,128}$'), + CONSTRAINT idempotency_request_hash_len CHECK (octet_length(request_hash) = 32) +); +-- Очистка ключей старше IDEMPOTENCY_TTL_SECONDS. +CREATE INDEX idempotency_keys_created_idx ON idempotency_keys (created_at); diff --git a/migrations/0004_attachments.sql b/migrations/0004_attachments.sql new file mode 100644 index 00000000..de1d53db --- /dev/null +++ b/migrations/0004_attachments.sql @@ -0,0 +1,62 @@ +-- 0004 (lab4): вложения. Метаданные — здесь, байты — в приватном S3 bucket (ключ назначает сервер). + +-- С lab4 текст может быть пустым, если у сообщения есть вложения (правило «пустой текст только с +-- вложениями» проверяет приложение: связь в другой таблице). Expand-изменение: старый код его не нарушает. +ALTER TABLE messages DROP CONSTRAINT messages_text_len; +ALTER TABLE messages ADD CONSTRAINT messages_text_len CHECK (char_length(text) <= 4000); +CREATE TABLE attachments ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE, + owner_id uuid NOT NULL REFERENCES users (id), + filename text NOT NULL, -- только для отображения, НЕ путь и НЕ ключ + content_type text NOT NULL, + size_bytes bigint NOT NULL, + sha256 text NOT NULL, + width integer NOT NULL, + height integer NOT NULL, + object_key text NOT NULL, + status text NOT NULL DEFAULT 'ready', + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + updated_at timestamptz NOT NULL DEFAULT clock_timestamp(), + CONSTRAINT attachments_object_key_key UNIQUE (object_key), + CONSTRAINT attachments_filename_len CHECK (char_length(filename) BETWEEN 1 AND 255), + CONSTRAINT attachments_content_type CHECK (content_type IN ('image/png', 'image/jpeg')), + CONSTRAINT attachments_size CHECK (size_bytes BETWEEN 1 AND 10485760), + CONSTRAINT attachments_sha256 CHECK (sha256 ~ '^[a-f0-9]{64}$'), + CONSTRAINT attachments_dims CHECK (width > 0 AND height > 0 AND width::bigint * height <= 40000000), + CONSTRAINT attachments_status CHECK (status IN ('ready')) -- lab5 расширит (queued/processing/failed) +); +CREATE INDEX attachments_chat_idx ON attachments (chat_id, created_at); +CREATE INDEX attachments_created_idx ON attachments (created_at); + +-- Связь сообщение ↔ вложения (порядок attachment_ids из запроса сохраняется). +CREATE TABLE message_attachments ( + message_id uuid NOT NULL REFERENCES messages (id) ON DELETE CASCADE, + attachment_id uuid NOT NULL REFERENCES attachments (id), + position smallint NOT NULL, + PRIMARY KEY (message_id, attachment_id), + CONSTRAINT message_attachments_position_key UNIQUE (message_id, position), + CONSTRAINT message_attachments_position_range CHECK (position BETWEEN 0 AND 9) +); +CREATE INDEX message_attachments_attachment_idx ON message_attachments (attachment_id); + +-- Журнал намерений загрузки (компенсация S3 ↔ PostgreSQL). Строка фиксируется ДО записи в S3 и +-- удаляется в той же транзакции, что создаёт attachments. Осталась дольше grace period — значит, +-- процесс упал между S3 PUT и COMMIT (или во время загрузки): объект по ключу удаляется очисткой. +CREATE TABLE upload_intents ( + object_key text PRIMARY KEY, + attachment_id uuid NOT NULL, + chat_id uuid NOT NULL, + owner_id uuid NOT NULL, + created_at timestamptz NOT NULL DEFAULT clock_timestamp() +); +CREATE INDEX upload_intents_created_idx ON upload_intents (created_at); + +-- Результаты проверки целостности (reconciler): проблемы, которые нельзя безопасно исправить +-- автоматически (например, утрачен объект вложения, на которое ссылаются сообщения). +CREATE TABLE attachment_integrity ( + attachment_id uuid PRIMARY KEY REFERENCES attachments (id) ON DELETE CASCADE, + problem text NOT NULL, + detected_at timestamptz NOT NULL DEFAULT clock_timestamp(), + CONSTRAINT attachment_integrity_problem CHECK (problem IN ('missing_object', 'size_mismatch', 'checksum_mismatch')) +); diff --git a/migrations/0005_jobs.sql b/migrations/0005_jobs.sql new file mode 100644 index 00000000..c97f933d --- /dev/null +++ b/migrations/0005_jobs.sql @@ -0,0 +1,118 @@ +-- 0005 (lab5): асинхронная обработка вложений. Expand-only: код lab4 продолжает работать со схемой +-- (новые столбцы допускают NULL/имеют DEFAULT, старые значения ограничений по-прежнему допустимы). + +-- Вложение: статусы queued/processing/ready/failed. object_key — КОНЕЧНЫЙ ключ оригинала +-- (originals/), он заполняется заранее, но объект появляется там только при переходе в ready. +-- staging_key — ключ устойчивого staging (staging/): полный проверенный оригинал, записанный ДО 202. +-- published_version — версия pipeline, чьи варианты отдаёт API; меняется только вверх. +ALTER TABLE attachments DROP CONSTRAINT attachments_status; +ALTER TABLE attachments ADD CONSTRAINT attachments_status + CHECK (status IN ('queued', 'processing', 'ready', 'failed')); +ALTER TABLE attachments ADD COLUMN staging_key text; +ALTER TABLE attachments ADD COLUMN error_code text; +ALTER TABLE attachments ADD COLUMN published_version integer; +ALTER TABLE attachments ADD CONSTRAINT attachments_staging_key_key UNIQUE (staging_key); +ALTER TABLE attachments ADD CONSTRAINT attachments_published_version CHECK (published_version IS NULL OR published_version >= 1); +ALTER TABLE attachments ADD CONSTRAINT attachments_error_code + CHECK (error_code IS NULL OR error_code ~ '^[a-z_]{1,40}$'); +CREATE INDEX attachments_status_idx ON attachments (status, updated_at) WHERE status <> 'ready'; + +-- Логическая работа: одна на (вложение, версия pipeline). job_id не меняется при redelivery. +-- attempt — управляемая попытка (поле attempt сообщения); растёт при retry/replay/восстановлении +-- после истёкшего lease. Сообщение с attempt < текущего — устаревшее (ack без действий). +-- claims — сколько раз работу захватывали на выполнение (включая перехват после смерти worker); +-- ограничено max_attempts — так ограничен и «немой» цикл падений на ядовитом файле. +-- lease_token — fencing-токен: растёт при каждом захвате; результат фиксируется, только если токен +-- в БД всё ещё мой (ожившая «зомби»-попытка не перезапишет состояние). +CREATE SEQUENCE job_lease_token_seq; +CREATE TABLE attachment_jobs ( + job_id uuid PRIMARY KEY, + attachment_id uuid NOT NULL REFERENCES attachments (id) ON DELETE CASCADE, + pipeline_version integer NOT NULL, + status text NOT NULL DEFAULT 'queued', + attempt integer NOT NULL DEFAULT 1, + claims integer NOT NULL DEFAULT 0, + max_attempts integer NOT NULL, + lease_owner text, + lease_token bigint NOT NULL DEFAULT 0, + lease_until timestamptz, + next_attempt_at timestamptz NOT NULL DEFAULT clock_timestamp(), + error_code text, + error_detail text, + replays integer NOT NULL DEFAULT 0, + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + updated_at timestamptz NOT NULL DEFAULT clock_timestamp(), + finished_at timestamptz, + CONSTRAINT attachment_jobs_effect_key UNIQUE (attachment_id, pipeline_version), + CONSTRAINT attachment_jobs_status CHECK (status IN ('queued', 'processing', 'ready', 'failed', 'superseded')), + CONSTRAINT attachment_jobs_version CHECK (pipeline_version >= 1), + CONSTRAINT attachment_jobs_attempt CHECK (attempt >= 1 AND claims >= 0 AND max_attempts BETWEEN 1 AND 100), + CONSTRAINT attachment_jobs_error_code CHECK (error_code IS NULL OR error_code ~ '^[a-z_]{1,40}$'), + CONSTRAINT attachment_jobs_detail_len CHECK (char_length(error_detail) <= 300) +); +CREATE INDEX attachment_jobs_processing_idx ON attachment_jobs (lease_until) WHERE status = 'processing'; +CREATE INDEX attachment_jobs_queued_idx ON attachment_jobs (next_attempt_at) WHERE status = 'queued'; +CREATE INDEX attachment_jobs_failed_idx ON attachment_jobs (updated_at) WHERE status = 'failed'; + +-- Transactional outbox: строка пишется в ТОЙ ЖЕ транзакции, что и изменение состояния job. Relay +-- публикует её в JetStream (Nats-Msg-Id = outbox-: повторная публикация после сбоя relay +-- отбрасывается брокером в окне дедупликации) и только после publish ack отмечает published_at. +-- available_at — не раньше этого момента (backoff повторов реализован здесь, а не в брокере). +CREATE TABLE job_outbox ( + id bigserial PRIMARY KEY, + job_id uuid NOT NULL REFERENCES attachment_jobs (job_id) ON DELETE CASCADE, + subject text NOT NULL, + payload jsonb NOT NULL, + available_at timestamptz NOT NULL DEFAULT clock_timestamp(), + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + published_at timestamptz, + publish_attempts integer NOT NULL DEFAULT 0, + last_error text +); +CREATE INDEX job_outbox_pending_idx ON job_outbox (available_at, id) WHERE published_at IS NULL; +CREATE INDEX job_outbox_job_idx ON job_outbox (job_id); + +-- Результат обработки. Первичный ключ = ключ эффекта (attachment_id, pipeline_version, variant): +-- повтор той же работы не может создать второй набор вариантов. object_key детерминирован тем же +-- ключом (variants//v/.), поэтому и в S3 повтор перезаписывает тот же объект. +CREATE TABLE attachment_variants ( + attachment_id uuid NOT NULL REFERENCES attachments (id) ON DELETE CASCADE, + pipeline_version integer NOT NULL, + name text NOT NULL, + object_key text NOT NULL, + content_type text NOT NULL, + size_bytes bigint NOT NULL, + width integer NOT NULL, + height integer NOT NULL, + sha256 text NOT NULL, + job_id uuid NOT NULL, + lease_token bigint NOT NULL, + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + PRIMARY KEY (attachment_id, pipeline_version, name), + CONSTRAINT attachment_variants_object_key_key UNIQUE (object_key), + CONSTRAINT attachment_variants_name CHECK (name IN ('thumbnail', 'crop', 'optimized')), + CONSTRAINT attachment_variants_type CHECK (content_type IN ('image/jpeg', 'image/png', 'image/webp')), + CONSTRAINT attachment_variants_size CHECK (size_bytes >= 1 AND width >= 1 AND height >= 1), + CONSTRAINT attachment_variants_sha256 CHECK (sha256 ~ '^[a-f0-9]{64}$') +); + +-- Журнал переходов: аудит (кто/когда/почему), реестр failed для оператора и данные для проверки +-- инвариантов (трек 2). Без секретов: только ID, коды и короткие безопасные пояснения. +CREATE TABLE job_events ( + id bigserial PRIMARY KEY, + job_id uuid NOT NULL, + attachment_id uuid NOT NULL, + pipeline_version integer NOT NULL, + event text NOT NULL, + attempt integer, + lease_token bigint, + worker text, + detail jsonb, + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + CONSTRAINT job_events_event CHECK (event IN ( + 'enqueued', 'published', 'claimed', 'lease_takeover', 'lease_lost', 'retry_scheduled', 'committed', + 'failed', 'replayed', 'superseded', 'duplicate_ignored', 'stale_ignored', 'requeued_expired_lease', + 'republished_stuck', 'staging_cleaned', 'published_version_changed', 'deferred')) +); +CREATE INDEX job_events_job_idx ON job_events (job_id, id); +CREATE INDEX job_events_attachment_idx ON job_events (attachment_id, id); diff --git a/migrations/0006_observability.sql b/migrations/0006_observability.sql new file mode 100644 index 00000000..158a0d1e --- /dev/null +++ b/migrations/0006_observability.sql @@ -0,0 +1,14 @@ +-- 0006 (lab6): наблюдаемость. Expand-only: код lab5 продолжает работать (новый столбец допускает NULL, +-- индексы не меняют семантику). + +-- W3C trace context последней попытки задания ({"traceparent": "...", "tracestate": "..."}). Нужен, +-- чтобы восстановление (истёкший lease, «застрявшее» задание, операторский replay) продолжало trace +-- исходной загрузки, а не начинало новый. Это технические идентификаторы трассировки, не секреты. +ALTER TABLE attachment_jobs ADD COLUMN trace_context jsonb; +ALTER TABLE attachment_jobs ADD CONSTRAINT attachment_jobs_trace_context_size + CHECK (trace_context IS NULL OR pg_column_size(trace_context) <= 1024); + +-- Метрики очереди (messenger.queue.oldest_age) раз в несколько секунд ищут самое старое незавершённое +-- задание: частичный индекс по created_at незавершённых работ держит этот запрос дешёвым. +CREATE INDEX attachment_jobs_unfinished_created_idx ON attachment_jobs (created_at) + WHERE status IN ('queued', 'processing'); diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 00000000..6a6d9267 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,30 @@ +# Runtime-зависимости API (точные версии, проверенные на стенде; см. REPORT.md). +starlette==1.7.0 +anyio==4.15.1 +idna==3.20 +typing_extensions==4.16.0 +uvicorn==0.54.0 +h11==0.16.0 +click==8.5.0 +psycopg[binary]==3.2.10 +psycopg-binary==3.2.10 +psycopg-pool==3.2.6 +redis==5.2.1 +# lab4: асинхронный HTTP-клиент для S3 (SigV4 реализован в src/messenger/s3.py) +httpx==0.28.1 +httpcore==1.0.9 +certifi==2026.10.18 +# lab5: клиент NATS JetStream (чистый Python, без обязательных зависимостей) и обработка изображений +nats-py==2.11.0 +Pillow==12.3.0 +# lab6: OpenTelemetry SDK и OTLP/HTTP-экспортёр (protobuf). Версии SDK/semconv/proto согласованы (1.45.0 / 0.66b0). +opentelemetry-api==1.45.0 +opentelemetry-sdk==1.45.0 +opentelemetry-semantic-conventions==0.66b0 +opentelemetry-proto==1.45.0 +opentelemetry-exporter-otlp-proto-common==1.45.0 +opentelemetry-exporter-otlp-common==0.66b0 +opentelemetry-exporter-http-transport==0.66b0 +opentelemetry-exporter-otlp-proto-http==1.45.0 +googleapis-common-protos==1.75.5 +protobuf==7.36.1 diff --git a/research/incidents.py b/research/incidents.py new file mode 100644 index 00000000..0cec8e76 --- /dev/null +++ b/research/incidents.py @@ -0,0 +1,459 @@ +#!/usr/bin/env python3 +"""Контролируемые инциденты lab6 (уровень 4): воздействие под нагрузкой → обнаружение ТОЛЬКО по сохранённым +наблюдениям (Prometheus/Loki/Tempo через Grafana API) → восстановление → resolved. + + python3 research/incidents.py worker-stop # остановка worker: растёт queue lag, алерты, затем backlog разбирается + python3 research/incidents.py db-slow # PostgreSQL ограничен 0.03 CPU: медленная БД + python3 research/incidents.py handler-slow # медленный обработчик (fault-api-slow) при быстрой БД — контраст + python3 research/incidents.py db-down # PostgreSQL заморожен (pause): 503, error.type в trace + python3 research/incidents.py telemetry-down # Tempo+Loki остановлены: API работает, очередь Collector ограничена + python3 research/incidents.py collector-down # Collector остановлен: SDK ограничивает очередь и считает потери + python3 research/incidents.py all --out evidence/incidents + +Вывод: таймлайн (время от воздействия до firing/resolved), значения метрик, найденные trace/логи. +Требует FAULT_HOOKS=lab для handler-slow. Volumes не трогаются. +""" +import argparse +import json +import os +import shlex +import subprocess +import sys +import threading +import time +import uuid +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "student-tests")) +from common import BASE_URL, Client, Failure, login, make_png, new_user # noqa: E402 +from obs import Grafana, ObsError # noqa: E402 + +DC = shlex.split(os.environ.get("COMPOSE", "docker compose --env-file .env")) +g = Grafana() +DB_SLOW_CPUS = os.environ.get("DB_SLOW_CPUS", "0.03") # «медленная БД»: квота CPU контейнера PostgreSQL + + +def dc(*args, check=True, timeout=180): + return subprocess.run(DC + list(args), cwd=ROOT, check=check, timeout=timeout, capture_output=True, text=True).stdout + + +def container_ids(service): + return dc("ps", "-q", service).split() + + +def docker(*args): + return subprocess.run(["docker"] + list(args), check=True, capture_output=True, text=True, timeout=60).stdout + + +def log(msg): + print("[%s] %s" % (time.strftime("%H:%M:%S"), msg), flush=True) + + +# ---------------------------------------------------------------------------------------------- нагрузка +class Load: + """Фоновая нагрузка: сообщения (rate/с) и, опционально, загрузки картинок (раз в upload_every с).""" + + def __init__(self, rate=6.0, upload_every=None, slow_share=0.0, threads=4): + self.c = Client(BASE_URL, timeout=15) + self.actor = new_user(self.c, "inc") + login(self.c, self.actor) + self.chat = self.c.call("POST", "/api/v1/chats", 201, actor=self.actor, schema="Chat", + body={"title": "incident", "member_ids": [self.actor["id"]]})["json"] + self.rate, self.upload_every, self.slow_share, self.threads = rate, upload_every, slow_share, threads + self.stop = threading.Event() + self.results = [] # (t, kind, status, latency_s) + self.uploads = [] # attachment ids + self.lock = threading.Lock() + self._n = 0 + + def _msg(self): + period = self.threads / self.rate + while not self.stop.is_set(): + t0 = time.monotonic() + with self.lock: + self._n += 1 + n = self._n + slow = self.slow_share and (n % round(1 / self.slow_share) == 0) + text = "incident load %d%s" % (n, " fault-api-slow-400" if slow else "") + status = 0 + try: + r = self.c.call("POST", "/api/v1/chats/%s/messages" % self.chat["id"], [201, 500, 502, 503, 504], + actor=self.actor, body={"text": text}, headers={"Idempotency-Key": uuid.uuid4().hex}) + status = r["status"] + except Failure: + status = -1 + with self.lock: + self.results.append((time.time(), "msg", status, time.monotonic() - t0)) + self.stop.wait(max(0.0, period - (time.monotonic() - t0))) + + def _upload(self): + while not self.stop.is_set(): + t0 = time.monotonic() + try: + r = self.c.call("POST", "/api/v1/chats/%s/attachments?filename=inc.png" % self.chat["id"], [202, 503], + actor=self.actor, raw=make_png(), headers={"Content-Type": "image/png"}) + if r["status"] == 202: + self.uploads.append(json.loads(r["bytes"])["id"]) + status = r["status"] + except Failure: + status = -1 + with self.lock: + self.results.append((time.time(), "upload", status, time.monotonic() - t0)) + self.stop.wait(self.upload_every) + + def __enter__(self): + self.ts = [threading.Thread(target=self._msg, daemon=True) for _ in range(self.threads)] + if self.upload_every: + self.ts.append(threading.Thread(target=self._upload, daemon=True)) + for t in self.ts: + t.start() + return self + + def __exit__(self, *a): + self.stop.set() + for t in self.ts: + t.join(20) + + def window(self, t0, t1, kind="msg"): + with self.lock: + rows = [r for r in self.results if t0 <= r[0] < t1 and r[1] == kind] + ok = [r for r in rows if r[2] in (201, 202)] + lat = sorted(r[3] for r in ok) + pct = lambda p: round(lat[min(len(lat) - 1, int(p * len(lat)))] * 1000, 1) if lat else None # noqa: E731 + return {"requests": len(rows), "ok": len(ok), "errors": len(rows) - len(ok), + "error_statuses": sorted({r[2] for r in rows if r[2] not in (201, 202)}), + "p50_ms": pct(0.5), "p95_ms": pct(0.95), "p99_ms": pct(0.99)} + + +# ---------------------------------------------------------------------------------------------- наблюдение +WATCH = { + "error_ratio": "sli:api_error_ratio:rate1m", + "api_p95_s": "sli:api_latency_p95:1m", + "db_p95_s": "histogram_quantile(0.95, sum by (le) (rate(db_client_operation_duration_seconds_bucket[1m])))", + "queue_lag_s": "sli:queue_lag_seconds:max", + "queue_ready": 'max(last_over_time(messenger_queue_depth{state="ready"}[30s]))', + "workers_capacity": "sum(last_over_time(messenger_worker_capacity[20s]))", + "db_pool_waiting_api": 'sum(last_over_time(db_client_connection_pending_requests{service_name="messenger-api"}[30s]))', + "collector_queue": "sum(otelcol_exporter_queue_size)", + "collector_rss_mib": "max(otelcol_process_memory_rss) / 1048576", +} + + +def snapshot(): + out = {} + for k, q in WATCH.items(): + try: + v = g.prom_value(q) + out[k] = None if v is None or v != v else round(v, 4) + except ObsError: + out[k] = None + return out + + +def firing(): + try: + return {a["labels"]["alertname"]: a["state"] for a in g.alerts()} + except ObsError: + return None + + +class Timeline: + def __init__(self, name): + self.name, self.t0, self.rows, self.marks = name, time.time(), [], {} + self.first = {} # alert -> первое время firing (с от t0) + self.resolved = {} + + def mark(self, label): + self.marks[label] = round(time.time() - self.t0, 1) + log("%s: %s (t=%.1fs)" % (self.name, label, self.marks[label])) + + def poll(self): + a = firing() + s = snapshot() + t = round(time.time() - self.t0, 1) + self.rows.append({"t": t, "alerts": a, **s}) + for name, st in (a or {}).items(): + if st == "firing" and name not in self.first: + self.first[name] = t + log(" FIRING %s at t=%.1fs" % (name, t)) + for name in list(self.first): + if a is not None and name not in a and name not in self.resolved: + self.resolved[name] = t + log(" resolved %s at t=%.1fs" % (name, t)) + return a or {}, s + + def wait(self, cond, timeout, every=5): + deadline = time.time() + timeout + while time.time() < deadline: + a, s = self.poll() + if cond(a, s): + return True + time.sleep(every) + return False + + def summary(self, extra=None): + return {"scenario": self.name, "marks_s": self.marks, "alerts_first_firing_s": self.first, + "alerts_resolved_s": self.resolved, **(extra or {}), "timeline": self.rows} + + +def quiet(a, _s, names): + return not any(n in a for n in names) + + +# ---------------------------------------------------------------------------------------------- сценарии +def worker_stop(): + tl = Timeline("worker-stop") + names = ("JobQueueLagGrowing", "WorkerHeartbeatMissing") + with Load(rate=3, upload_every=2) as load: + tl.wait(lambda a, s: quiet(a, s, names), 120) + time.sleep(20) + tl.mark("worker stopped") + stop_at = time.time() + dc("stop", "worker") + ok = tl.wait(lambda a, s: all(a.get(n) == "firing" for n in names), 240) + tl.mark("both alerts firing" if ok else "alerts NOT firing in time") + peak = max((r.get("queue_ready") or 0) for r in tl.rows) + time.sleep(15) + tl.mark("worker started") + start_at = time.time() + dc("start", "worker") + ok2 = tl.wait(lambda a, s: quiet(a, s, names) and (s.get("queue_ready") or 0) == 0, 300) + tl.mark("alerts resolved, backlog empty" if ok2 else "NOT recovered in time") + load.stop.set() + # все принятые во время остановки загрузки обработаны (без потерь) + c, actor = load.c, load.actor + deadline = time.time() + 120 + pending = list(load.uploads) + while pending and time.time() < deadline: + pending = [a for a in pending if c.call("GET", "/api/v1/attachments/" + a, actor=actor, schema="Attachment")["json"]["status"] != "ready"] + time.sleep(2) + logs = g.loki('{service_name="messenger-api"} | event="attachment.accepted"', start=stop_at, end=start_at, limit=1000) + wlogs = g.loki('{service_name="messenger-worker"}', start=stop_at + 15, end=start_at, limit=50) + res = tl.summary({"uploads_accepted": len(load.uploads), "uploads_not_ready_after_recovery": len(pending), + "queue_ready_peak": peak, "api_accepted_logs_during_outage": len(logs), + "worker_logs_during_outage": len(wlogs), + "detection_s": {n: round(tl.first.get(n, -1) - tl.marks["worker stopped"], 1) for n in names}, + "recovery_s": {n: round(tl.resolved.get(n, -1) - tl.marks["worker started"], 1) for n in names}, + "http_during_outage": load.window(stop_at, start_at)}) + return res + + +def _slow_trace(route, since=240, min_ms=150): + """Самый медленный server span маршрута за окно; доля времени в DB spans внутри него.""" + traces = g.search('{ span.http.route = "%s" && kind = server && duration > %dms }' % (route, min_ms), since=since, limit=20) + best = None + for tr in traces[:10]: + spans = g.trace(tr["traceID"]) or [] + srv = [s for s in spans if s["kind"] == "SERVER"] + if not srv: + continue + sv = srv[0] + dur = sv["end"] - sv["start"] + db = sum(s["end"] - s["start"] for s in spans if s["attrs"].get("db.system.name") == "postgresql") + pool_ids = {s["span_id"] for s in spans if s["name"] == "pool.acquire"} + pool = sum(s["end"] - s["start"] for s in spans if s["name"] == "pool.acquire") + # pool.check внутри pool.acquire уже учтён в db — не считать дважды + pool -= sum(s["end"] - s["start"] for s in spans if s["parent"] in pool_ids and s["attrs"].get("db.system.name")) + other = dur - sum(s["end"] - s["start"] for s in spans if s["parent"] == sv["span_id"]) + item = {"trace_id": sv["trace_id"], "duration_ms": round(dur * 1000, 1), "db_ms": round(db * 1000, 1), + "pool_wait_ms": round(pool * 1000, 1), + "db_share": round(db / dur, 2) if dur else None, + "db_or_pool_share": round((db + pool) / dur, 2) if dur else None, + "not_in_child_spans_ms": round(other * 1000, 1), + "error_type": sv["attrs"].get("error.type"), + "slowest_child": max(((s["name"], round((s["end"] - s["start"]) * 1000, 1)) for s in spans + if s["parent"] == sv["span_id"]), key=lambda x: x[1], default=None)} + if best is None or item["duration_ms"] > best["duration_ms"]: + best = item + return best + + +def db_slow(): + tl = Timeline("db-slow") + names = ("DbSlowQueries",) + pg = container_ids("postgres")[0] + with Load(rate=6) as load: + tl.wait(lambda a, s: quiet(a, s, names + ("ApiLatencyHigh",)), 120) + time.sleep(30) + base = dict(snapshot()) + tl.mark("postgres limited to %s CPU" % DB_SLOW_CPUS) + t1 = time.time() + docker("update", "--cpus", DB_SLOW_CPUS, pg) + ok = tl.wait(lambda a, s: a.get("DbSlowQueries") == "firing", 240) + tl.mark("DbSlowQueries firing" if ok else "DbSlowQueries NOT firing") + # держим деградацию, пока не сработает и пользовательский симптом (p95 API > SLO), не дольше 2 мин + tl.wait(lambda a, s: a.get("ApiLatencyHigh") == "firing", 120) + during = dict(snapshot()) + trace = _slow_trace("/api/v1/chats/{chat_id}/messages", since=int(time.time() - t1) + 30) + tl.mark("postgres restored to 1.0 CPU") + t2 = time.time() + docker("update", "--cpus", os.environ.get("PG_CPUS", "1.0"), pg) + ok2 = tl.wait(lambda a, s: quiet(a, s, names + ("ApiLatencyHigh", "ApiHighErrorRate")), 300) + tl.mark("resolved" if ok2 else "NOT resolved in time") + load.stop.set() + return tl.summary({"metrics_before": base, "metrics_during": during, "slow_trace": trace, + "http_before": load.window(t1 - 30, t1), "http_during": load.window(t1, t2), + "detection_s": round(tl.first.get("DbSlowQueries", -1) - tl.marks["postgres limited to %s CPU" % DB_SLOW_CPUS], 1)}) + + +def handler_slow(): + tl = Timeline("handler-slow") + with Load(rate=6, slow_share=0.5) as load: + t1 = time.time() + tl.mark("50% of messages carry fault-api-slow-400 (sleep in handler)") + ok = tl.wait(lambda a, s: a.get("ApiLatencyHigh") == "firing", 240) + tl.mark("ApiLatencyHigh firing" if ok else "ApiLatencyHigh NOT firing") + during = dict(snapshot()) + db_alert = "DbSlowQueries" in (firing() or {}) + trace = _slow_trace("/api/v1/chats/{chat_id}/messages", since=int(time.time() - t1) + 30, min_ms=350) + t2 = time.time() + load.stop.set() + ok2 = tl.wait(lambda a, s: quiet(a, s, ("ApiLatencyHigh",)), 300) + tl.mark("resolved" if ok2 else "NOT resolved in time") + return tl.summary({"metrics_during": during, "db_alert_fired": db_alert, "slow_trace": trace, + "http_during": load.window(t1, t2), + "detection_s": round(tl.first.get("ApiLatencyHigh", -1), 1)}) + + +def db_down(): + tl = Timeline("db-down") + with Load(rate=6) as load: + tl.wait(lambda a, s: quiet(a, s, ("ApiHighErrorRate",)), 120) + time.sleep(15) + tl.mark("postgres paused") + t1 = time.time() + dc("pause", "postgres") + ok = tl.wait(lambda a, s: a.get("ApiHighErrorRate") == "firing", 180) + tl.mark("ApiHighErrorRate firing" if ok else "ApiHighErrorRate NOT firing") + tl.mark("postgres unpaused") + t2 = time.time() + dc("unpause", "postgres") + ok2 = tl.wait(lambda a, s: quiet(a, s, ("ApiHighErrorRate",)), 300) + tl.mark("resolved" if ok2 else "NOT resolved in time") + load.stop.set() + errs = g.search('{ resource.service.name = "messenger-api" && kind = server && status = error }', since=int(time.time() - t1) + 30) + etypes = {} + for tr in errs[:20]: + for s in g.trace(tr["traceID"]) or []: + if s["kind"] == "SERVER": + etypes[s["attrs"].get("error.type")] = etypes.get(s["attrs"].get("error.type"), 0) + 1 + logs = g.loki('{service_name="messenger-api"} | event="dependency.unavailable"', start=t1, end=t2 + 30, limit=1000) + return tl.summary({"http_during": load.window(t1, t2), "error_traces_error_type": etypes, + "dependency_unavailable_logs": len(logs), + "logged_errors": sorted({r.get("error") for r in logs}), + "detection_s": round(tl.first.get("ApiHighErrorRate", -1) - tl.marks["postgres paused"], 1)}) + + +def _cstats(service): + out = {} + for cid in container_ids(service): + line = docker("stats", "--no-stream", "--format", "{{.MemUsage}}", cid).strip() + out[cid[:12]] = line.split("/")[0].strip() + return out + + +def telemetry_down(): + tl = Timeline("telemetry-down") + q = lambda e: g.prom_value(e, 0) # noqa: E731 + with Load(rate=6, upload_every=3) as load: + time.sleep(20) + before = {"accepted_spans": q("sum(otelcol_receiver_accepted_spans_total)"), + "send_failed_spans": q("sum(otelcol_exporter_send_failed_spans_total)"), + "enqueue_failed_spans": q("sum(otelcol_exporter_enqueue_failed_spans_total)"), + "send_failed_logs": q("sum(otelcol_exporter_send_failed_log_records_total)"), + "enqueue_failed_logs": q("sum(otelcol_exporter_enqueue_failed_log_records_total)")} + rss0 = _cstats("otel-collector") + tl.mark("tempo and loki stopped") + t1 = time.time() + dc("stop", "tempo", "loki") + ok = tl.wait(lambda a, s: a.get("TelemetryExportFailing") == "firing", 180) + tl.mark("TelemetryExportFailing firing" if ok else "TelemetryExportFailing NOT firing") + time.sleep(60) + rss1 = _cstats("otel-collector") + qmax = max((r.get("collector_queue") or 0) for r in tl.rows) + cap = q("max(otelcol_exporter_queue_capacity)") + tl.mark("tempo and loki started") + t2 = time.time() + dc("start", "tempo", "loki") + ok2 = tl.wait(lambda a, s: quiet(a, s, ("TelemetryExportFailing",)) and (s.get("collector_queue") or 0) == 0, 360) + tl.mark("resolved, queue drained" if ok2 else "NOT resolved in time") + load.stop.set() + after = {k: q(e) for k, e in (("accepted_spans", "sum(otelcol_receiver_accepted_spans_total)"), + ("send_failed_spans", "sum(otelcol_exporter_send_failed_spans_total)"), + ("enqueue_failed_spans", "sum(otelcol_exporter_enqueue_failed_spans_total)"), + ("send_failed_logs", "sum(otelcol_exporter_send_failed_log_records_total)"), + ("enqueue_failed_logs", "sum(otelcol_exporter_enqueue_failed_log_records_total)"))} + lost = {k: round(after[k] - before[k]) for k in before} + # trace, начатый во время простоя Tempo, но доставленный после восстановления из очереди Collector + during_traces = g.search('{ resource.service.name = "messenger-api" && kind = server }', since=int(time.time() - t1) + 10, limit=200) + in_outage = [t for t in during_traces if t1 * 1e9 <= int(t.get("startTimeUnixNano", 0)) <= t2 * 1e9] + return tl.summary({"http_during": load.window(t1, t2), "uploads_during": load.window(t1, t2, "upload"), + "collector_mem_before": rss0, "collector_mem_during": rss1, "exporter_queue_max": qmax, + "exporter_queue_capacity": cap, "telemetry_delta": lost, + "traces_from_outage_window_found_after_recovery": len(in_outage), + "detection_s": round(tl.first.get("TelemetryExportFailing", -1) - tl.marks["tempo and loki stopped"], 1)}) + + +def collector_down(): + tl = Timeline("collector-down") + q = lambda e: g.prom_value(e, 0) # noqa: E731 + lost_q = {"spans_export_failed": 'sum(otel_sdk_exporter_span_exported_total{error_type!=""})', + "spans_queue_dropped": 'sum(otel_sdk_processor_span_processed_total{error_type!=""})', + "logs_export_failed": 'sum(otel_sdk_exporter_log_exported_total{error_type!=""})', + "logs_queue_dropped": 'sum(otel_sdk_processor_log_processed_total{error_type!=""})', + "spans_started": 'sum(otel_sdk_span_started_total)'} + with Load(rate=8) as load: + tl.wait(lambda a, s: quiet(a, s, ("OtelCollectorDown", "TelemetryLostInSdk")), 400) + time.sleep(10) + before = {k: q(e) for k, e in lost_q.items()} + mem0 = _cstats("api") + tl.mark("otel-collector stopped") + t1 = time.time() + dc("stop", "otel-collector") + ok = tl.wait(lambda a, s: a.get("OtelCollectorDown") == "firing", 120) + tl.mark("OtelCollectorDown firing" if ok else "OtelCollectorDown NOT firing") + time.sleep(max(0, 90 - (time.time() - t1))) + mem1 = _cstats("api") + tl.mark("otel-collector started") + t2 = time.time() + dc("start", "otel-collector") + ok2 = tl.wait(lambda a, s: "OtelCollectorDown" not in a and a.get("TelemetryLostInSdk") == "firing", 180) + tl.mark("collector back; SDK losses reported" if ok2 else "SDK losses NOT reported") + time.sleep(20) + load.stop.set() + after = {k: q(e) for k, e in lost_q.items()} + delta = {k: round(after[k] - before[k]) for k in lost_q} + by_type = {r["metric"].get("error_type"): round(float(r["value"][1])) for r in + g.prom('sum by (error_type) (otel_sdk_exporter_span_exported_total{error_type!=""})')} + return tl.summary({"http_before": load.window(t1 - 20, t1), "http_during": load.window(t1, t2), + "api_mem_before": mem0, "api_mem_during": mem1, "sdk_delta": delta, + "sdk_export_errors_by_type_total": by_type, + "detection_s": round(tl.first.get("OtelCollectorDown", -1) - tl.marks["otel-collector stopped"], 1)}) + + +SCENARIOS = {"worker-stop": worker_stop, "db-slow": db_slow, "handler-slow": handler_slow, "db-down": db_down, + "telemetry-down": telemetry_down, "collector-down": collector_down} + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("scenario", choices=list(SCENARIOS) + ["all"]) + ap.add_argument("--out", help="каталог для JSON-результатов") + a = ap.parse_args() + names = list(SCENARIOS) if a.scenario == "all" else [a.scenario] + rc = 0 + for n in names: + res = SCENARIOS[n]() + short = {k: v for k, v in res.items() if k != "timeline"} + print(json.dumps(short, ensure_ascii=False, indent=1)) + if a.out: + Path(a.out).mkdir(parents=True, exist_ok=True) + (Path(a.out) / (n + ".json")).write_text(json.dumps(res, ensure_ascii=False, indent=1)) + if any("NOT" in k for k in res["marks_s"]): + rc = 1 + return rc + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/research/obs_snapshot.py b/research/obs_snapshot.py new file mode 100644 index 00000000..40351561 --- /dev/null +++ b/research/obs_snapshot.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python3 +"""Снимок конфигурации и состояния наблюдаемости (для evidence/observability.txt): datasources, dashboard, +правила/алерты Prometheus, фактические имена метрик приложения с labels, labels Loki, примеры TraceQL. +Секретов не выводит (пароль Grafana читается из файла и не печатается).""" +import json +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "student-tests")) +from obs import Grafana # noqa: E402 + +g = Grafana() + + +def main(): + print("== Grafana", g.get("/api/health").get("version")) + for d in g.get("/api/datasources"): + h = g.get("/api/datasources/uid/%s/health" % d["uid"]) + print("datasource uid=%-10s type=%-10s url=%-24s readOnly=%s health=%s" % ( + d["uid"], d["type"], d["url"], d["readOnly"], h.get("status"))) + dash = g.get("/api/dashboards/uid/messenger-overview") + panels = [p for p in dash["dashboard"]["panels"] if p.get("type") != "row"] + print("dashboard uid=messenger-overview provisioned=%s panels=%d folder=%s" % ( + dash["meta"].get("provisioned"), len(panels), dash["meta"].get("folderTitle"))) + print("\n== Prometheus: правила и состояние") + for grp in g.rules(): + for r in grp["rules"]: + print("%-9s %-26s health=%-3s state=%s" % (r["type"], r["name"], r.get("health"), r.get("state", "-"))) + print("\n== Метрики приложения (Prometheus, имя → labels кроме ресурсных)") + names = g.get("/api/datasources/proxy/uid/prometheus/api/v1/label/__name__/values")["data"] + res_labels = {"__name__", "service_name", "service_namespace", "service_instance_id", "deployment_environment_name", + "job", "instance", "otel_scope_name", "otel_scope_version", "le", "otel_scope_schema_url"} + for n in names: + if not n.startswith(("http_server_", "db_client_", "messenger_", "container_", "process_cpu_time", + "process_memory_usage", "otel_sdk_processor", "otel_sdk_exporter_span", "otel_sdk_span")): + continue + if n.endswith(("_sum", "_count")): + continue + ser = g.series(n, since=3600) + labels = sorted(set().union(*(s.keys() for s in ser)) - res_labels) if ser else [] + print("%-58s series=%-4d labels=%s" % (n, len(ser), ",".join(labels))) + print("\n== Loki labels (index):", ",".join(g.get("/api/datasources/proxy/uid/loki/loki/api/v1/labels")["data"])) + for svc in ("messenger-api", "messenger-worker"): + recs = g.loki('{service_name="%s"}' % svc, since=3600, limit=1) + if recs: + rec = {k: v for k, v in recs[-1].items() if k not in ("line", "ts")} + print("пример записи %s: поля=%s" % (svc, ",".join(sorted(rec)))) + print("\n== Tempo") + for q in ('{ resource.service.name = "messenger-api" && kind = server }', + '{ span.messaging.operation.type = "process" }', '{ status = error }'): + print("%-62s traces(1h, limit 20)=%d" % (q, len(g.search(q, since=3600, limit=20)))) + print("\n== Активные алерты:", json.dumps([(a["labels"]["alertname"], a["state"]) for a in g.alerts()], ensure_ascii=False)) + + +if __name__ == "__main__": + main() diff --git a/research/telemetry_cost.py b/research/telemetry_cost.py new file mode 100644 index 00000000..816213e9 --- /dev/null +++ b/research/telemetry_cost.py @@ -0,0 +1,355 @@ +#!/usr/bin/env python3 +"""Трек 1 «Цена наблюдаемости»: одинаковая open-loop нагрузка при разных настройках telemetry. + +Конфигурации (переключаются пересозданием api/worker/otel-collector с переменными окружения Compose): + off OTEL_SDK_DISABLED=true — telemetry выключена целиком (база) + full SDK 100% trace, Collector хранит всё — максимум данных + head10 SDK head sampling 10% (parentbased_traceidratio) — дёшево, но решение принято ДО исхода запроса + tail SDK 100% → Collector tail sampling (collector-tail.yaml): все ошибки, все > 250 мс, + все trace pipeline вложений и 10% остальных — предлагаемая сбалансированная конфигурация +Метрики RED во всех «on»-вариантах считаются SDK по всем запросам (sampling на них не влияет). + +Нагрузка (одинакова для всех): open-loop R запросов/с (латентность от ЗАПЛАНИРОВАННОГО момента — без +coordinated omission): 85% POST сообщения, 15% GET истории; 1% запросов — редкие ошибки (fault-api-error → +500), 1% — редкие медленные (fault-api-slow-300); upload картинки раз в 2 с (spans worker). Прогрев 15 с, +измерение WINDOW с, повторы — чередованием конфигураций (A B C D A B C D …). + +Измеряется: успешные RPS, p50/p95/p99 (без намеренно медленных), CPU/RAM контейнеров (docker stats, среднее +и максимум), ingest (spans/logs/metric points в Collector; байты и spans в Tempo, байты и строки в Loki; +samples в Prometheus), потери spans (SDK: очередь/экспорт; Collector: отказ/ошибки отправки) и доля +найденных в Tempo trace редких ошибок и медленных запросов (по request_id). + + python3 research/telemetry_cost.py --reps 3 --rate 60 --window 60 --out evidence/track1 +Требует FAULT_HOOKS=lab. Стенд в конце возвращается к конфигурации full. +""" +import argparse +import json +import os +import shlex +import statistics +import subprocess +import sys +import threading +import time +import uuid +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "student-tests")) +from common import BASE_URL, Client, Failure, login, make_png, new_user # noqa: E402 +from obs import Grafana, ObsError # noqa: E402 + +DC = shlex.split(os.environ.get("COMPOSE", "docker compose --env-file .env")) +CONFIGS = { + "off": {"OTEL_SDK_DISABLED": "true", "OTEL_TRACES_SAMPLER_ARG": "1.0", "OTEL_COLLECTOR_CONFIG": "collector.yaml"}, + "full": {"OTEL_SDK_DISABLED": "false", "OTEL_TRACES_SAMPLER_ARG": "1.0", "OTEL_COLLECTOR_CONFIG": "collector.yaml"}, + "head10": {"OTEL_SDK_DISABLED": "false", "OTEL_TRACES_SAMPLER_ARG": "0.1", "OTEL_COLLECTOR_CONFIG": "collector.yaml"}, + "tail": {"OTEL_SDK_DISABLED": "false", "OTEL_TRACES_SAMPLER_ARG": "1.0", "OTEL_COLLECTOR_CONFIG": "collector-tail.yaml"}, +} +GROUPS = {"api": ["api"], "worker": ["worker"], "collector": ["otel-collector"], + "backends": ["prometheus", "loki", "tempo"], "postgres": ["postgres"]} +g = Grafana() + + +def log(msg): + print("[%s] %s" % (time.strftime("%H:%M:%S"), msg), flush=True) + + +def dc(*args, env=None, timeout=300): + e = dict(os.environ, **(env or {})) + return subprocess.run(DC + list(args), cwd=ROOT, env=e, check=True, capture_output=True, text=True, timeout=timeout).stdout + + +def apply(name): + dc("up", "-d", "--wait", "api", "worker", "otel-collector", env=CONFIGS[name], timeout=600) + # все реплики за LB снова ready + c = Client(BASE_URL) + deadline = time.time() + 120 + while time.time() < deadline: + try: + if c.call("GET", "/health/ready", [200, 503])["status"] == 200: + break + except Failure: + pass + time.sleep(1) + + +# --------------------------------------------------------------------------------------------- ресурсы +def _mem(s): + v, unit = s.strip(), 1 + for suf, mul in (("GiB", 1024 ** 3), ("MiB", 1024 ** 2), ("KiB", 1024), ("kB", 1000), ("MB", 1e6), ("GB", 1e9), ("B", 1)): + if v.endswith(suf): + return float(v[:-len(suf)]) * mul + return float(v) * unit + + +class Stats(threading.Thread): + """Сэмплы docker stats (CPU %, память) по группам сервисов каждые ~2 с.""" + + def __init__(self): + super().__init__(daemon=True) + self.ids = {} + for gname, svcs in GROUPS.items(): + for s in svcs: + for cid in dc("ps", "-q", s).split(): + self.ids[cid[:12]] = gname + self.samples = {k: [] for k in GROUPS} + self.stop = threading.Event() + + def run(self): + while not self.stop.is_set(): + out = subprocess.run(["docker", "stats", "--no-stream", "--format", "{{.ID}};{{.CPUPerc}};{{.MemUsage}}"] + + list(self.ids), capture_output=True, text=True, timeout=30).stdout + agg = {k: [0.0, 0.0] for k in GROUPS} + for line in out.splitlines(): + cid, cpu, mem = line.split(";") + gname = self.ids.get(cid[:12]) + if gname: + agg[gname][0] += float(cpu.rstrip("%") or 0) + agg[gname][1] += _mem(mem.split("/")[0]) + for k, (cpu, mem) in agg.items(): + self.samples[k].append((cpu, mem)) + self.stop.wait(1.0) + + def summary(self): + out = {} + for k, v in self.samples.items(): + if v: + out[k] = {"cpu_pct_avg": round(statistics.mean(c for c, _ in v), 1), + "mem_mib_avg": round(statistics.mean(m for _, m in v) / 2 ** 20, 1), + "mem_mib_max": round(max(m for _, m in v) / 2 ** 20, 1)} + return out + + +# --------------------------------------------------------------------------------------------- нагрузка +class OpenLoop: + def __init__(self, rate, seconds, warmup): + self.c = Client(BASE_URL, timeout=15) + self.actor = new_user(self.c, "cost") + login(self.c, self.actor) + self.chat = self.c.call("POST", "/api/v1/chats", 201, actor=self.actor, schema="Chat", + body={"title": "cost", "member_ids": [self.actor["id"]]})["json"] + self.rate, self.seconds, self.warmup = rate, seconds, warmup + self.rows = [] + self.lock = threading.Lock() + + def one(self, i, sched, measured): + kind = "error" if i % 100 == 37 else "slow" if i % 100 == 73 else "read" if i % 100 < 15 else "write" + start = time.monotonic() + status, rid = 0, None + try: + if kind == "read": + r = self.c.call("GET", "/api/v1/chats/%s/messages?limit=20" % self.chat["id"], [200, 500, 502, 503, 504], + actor=self.actor) + else: + text = "cost %d%s" % (i, {"error": " fault-api-error", "slow": " fault-api-slow-300"}.get(kind, "")) + r = self.c.call("POST", "/api/v1/chats/%s/messages" % self.chat["id"], [201, 500, 502, 503, 504], + actor=self.actor, body={"text": text}, headers={"Idempotency-Key": uuid.uuid4().hex}) + status, rid = r["status"], r["headers"].get("X-Request-Id") + except Failure: + status = -1 + end = time.monotonic() + with self.lock: + self.rows.append({"kind": kind, "status": status, "rid": rid, "lat": end - sched, "measured": measured, + "svc": end - start, "t": time.time()}) + + def uploads(self, stop): + while not stop.is_set(): + try: + self.c.call("POST", "/api/v1/chats/%s/attachments?filename=cost.png" % self.chat["id"], [202, 503], + actor=self.actor, raw=make_png(), headers={"Content-Type": "image/png"}) + except Failure: + pass + stop.wait(2.0) + + def run(self): + stop = threading.Event() + up = threading.Thread(target=self.uploads, args=(stop,), daemon=True) + up.start() + total = self.warmup + self.seconds + n = int(total * self.rate) + t0 = time.monotonic() + 0.5 + self.window = None + with ThreadPoolExecutor(max_workers=64) as ex: + for i in range(n): + sched = t0 + i / self.rate + delay = sched - time.monotonic() + if delay > 0: + time.sleep(delay) + measured = i >= self.warmup * self.rate + if measured and self.window is None: + self.window = [time.time(), None] + ex.submit(self.one, i, sched, measured) + self.window[1] = time.time() + stop.set() + up.join(5) + return self.window + + +def pct(xs, p): + xs = sorted(xs) + return round(xs[min(len(xs) - 1, int(p * len(xs)))] * 1000, 1) if xs else None + + +# --------------------------------------------------------------------------------------------- telemetry +COUNTERS = { # селекторы счётчиков; суммы — по экземплярам (см. counters()) + "col_spans_in": "otelcol_receiver_accepted_spans_total", + "col_spans_out": "otelcol_exporter_sent_spans_total", + "col_logs_in": "otelcol_receiver_accepted_log_records_total", + "col_points_in": "otelcol_receiver_accepted_metric_points_total", + "col_refused": "otelcol_receiver_refused_spans_total", + "col_send_failed": '{__name__=~"otelcol_exporter_send_failed_spans_total|otelcol_exporter_enqueue_failed_spans_total"}', + "tempo_bytes": "tempo_distributor_bytes_received_total", + "tempo_spans": "tempo_distributor_spans_received_total", + "loki_bytes": "loki_distributor_bytes_received_total", + "loki_lines": "loki_distributor_lines_received_total", + "prom_samples": "prometheus_tsdb_head_samples_appended_total", + "sdk_started": 'otel_sdk_span_started_total{service_name="messenger-api"}', + "sdk_sampled": 'otel_sdk_span_started_total{service_name="messenger-api",otel_span_sampling_result="RECORD_AND_SAMPLE"}', + "sdk_lost": '{__name__=~"otel_sdk_processor_span_processed_total|otel_sdk_exporter_span_exported_total",error_type!=""}', + "red_5xx": 'http_server_request_duration_seconds_count{service_name="messenger-api",http_response_status_class="5xx"}', + "red_all": 'http_server_request_duration_seconds_count{service_name="messenger-api",http_route="/api/v1/chats/{chat_id}/messages"}', + "spanmetrics_calls": 'traces_spanmetrics_calls_total{service="messenger-api",span_kind="SPAN_KIND_SERVER",span_name=~".*/messages"}', +} + + +def counters(at): + """Значения счётчиков в момент at ПО ЭКЗЕМПЛЯРАМ (instance / service_instance_id). Дельта считается только + по экземплярам, живым в конце прогона: «устаревшие» серии пересозданных контейнеров (Prometheus держит их + 5 мин) не искажают сумму, а новый экземпляр без значения в начале считается от 0.""" + out = {} + for k, q in COUNTERS.items(): + try: + res = g.prom("sum by (instance, service_instance_id) (%s)" % q, at=at) + out[k] = {(r["metric"].get("instance", ""), r["metric"].get("service_instance_id", "")): float(r["value"][1]) + for r in res} + except ObsError: + out[k] = None + return out + + +def delta(a, b): + if a is None or b is None: + return None + return sum(v - a.get(key, 0.0) for key, v in b.items()) + + +def found_in_tempo(rows, kind): + rids = [r["rid"] for r in rows if r["kind"] == kind and r["rid"]] + found = 0 + for rid in rids: + try: + if g.search('{ span.messenger.request_id = "%s" }' % rid, since=1200, limit=1): + found += 1 + except ObsError: + pass + return found, len(rids) + + +def one_run(name, rate, window, warmup): + log("run %s: apply config" % name) + apply(name) + time.sleep(10) + load = OpenLoop(rate, window, warmup) + st = Stats() + st.start() + a = counters(time.time()) if name != "off" else None # до нагрузки: дельты счётчиков покрывают весь прогон + t_start = time.time() + w0, w1 = load.run() + st.stop.set() + st.join(10) + time.sleep(25) # экспорт SDK (10 с) + batch Collector + scrape (10 с) + all_rows = load.rows + rows = [r for r in all_rows if r["measured"]] + normal = [r for r in rows if r["kind"] in ("write", "read") and r["status"] in (200, 201)] + res = {"config": name, "window_s": round(w1 - w0, 1), "requests": len(rows), + "ok_rps": round(len(normal) / (w1 - w0), 1), + "unexpected_errors": sum(1 for r in rows if r["kind"] in ("write", "read", "slow") and r["status"] not in (200, 201)), + "injected_errors": sum(1 for r in all_rows if r["kind"] == "error"), + "lat_p50_ms": pct([r["lat"] for r in normal], 0.5), "lat_p95_ms": pct([r["lat"] for r in normal], 0.95), + "lat_p99_ms": pct([r["lat"] for r in normal], 0.99), "resources": st.summary()} + if name != "off": + b = counters(time.time()) + d = {k: (round(delta(a[k], b[k]), 1) if delta(a[k], b[k]) is not None else None) for k in COUNTERS} + span = w1 - t_start # прогрев + окно (дельты — за весь прогон) + res["telemetry_delta"] = d + res["per_second"] = {k: (round(v / span, 1) if v is not None else None) for k, v in d.items() + if k in ("col_spans_in", "col_spans_out", "col_logs_in", "col_points_in", "tempo_bytes", + "tempo_spans", "loki_bytes", "loki_lines", "prom_samples")} + res["errors_found_in_tempo"] = found_in_tempo(all_rows, "error") + res["slow_found_in_tempo"] = found_in_tempo(all_rows, "slow") + natural_slow = [r for r in normal if r["svc"] > 0.25] + res["natural_slow_requests"] = len(natural_slow) + res["natural_slow_found_in_tempo"] = found_in_tempo([dict(r, kind="nat") for r in natural_slow[:30]], "nat") + log("run %s: %s" % (name, json.dumps({k: v for k, v in res.items() if k in ("ok_rps", "lat_p50_ms", "lat_p95_ms", "lat_p99_ms", + "errors_found_in_tempo", "slow_found_in_tempo")}))) + return res + + +def aggregate(results): + by = {} + for r in results: + by.setdefault(r["config"], []).append(r) + table = {} + for name, runs in by.items(): + med = lambda f: statistics.median([f(r) for r in runs if f(r) is not None]) if any(f(r) is not None for r in runs) else None # noqa: E731 + row = {"runs": len(runs), "ok_rps": med(lambda r: r["ok_rps"]), "p50_ms": med(lambda r: r["lat_p50_ms"]), + "p95_ms": med(lambda r: r["lat_p95_ms"]), "p99_ms": med(lambda r: r["lat_p99_ms"]), + "p95_ms_runs": [r["lat_p95_ms"] for r in runs], + "unexpected_errors": sum(r["unexpected_errors"] for r in runs)} + for grp in GROUPS: + row["cpu_%s_pct" % grp] = med(lambda r, gg=grp: r["resources"].get(gg, {}).get("cpu_pct_avg")) + row["mem_%s_mib" % grp] = med(lambda r, gg=grp: r["resources"].get(gg, {}).get("mem_mib_avg")) + if name != "off": + for k in ("col_spans_in", "col_spans_out", "tempo_bytes", "tempo_spans", "loki_bytes", "loki_lines", + "col_points_in", "prom_samples"): + row[k + "_per_s"] = med(lambda r, kk=k: r["per_second"].get(kk)) + for k in ("sdk_lost", "col_refused", "col_send_failed"): + row[k] = sum((r["telemetry_delta"].get(k) or 0) for r in runs) + row["sdk_sampled_share"] = med(lambda r: (r["telemetry_delta"]["sdk_sampled"] / r["telemetry_delta"]["sdk_started"]) + if r["telemetry_delta"].get("sdk_started") else None) + row["red_5xx_vs_injected"] = [(r["telemetry_delta"].get("red_5xx"), r["injected_errors"]) for r in runs] + row["spanmetrics_vs_sdk_calls"] = [(r["telemetry_delta"].get("spanmetrics_calls"), r["telemetry_delta"].get("red_all")) + for r in runs] + for k in ("errors_found_in_tempo", "slow_found_in_tempo", "natural_slow_found_in_tempo"): + f = sum(r[k][0] for r in runs) + n = sum(r[k][1] for r in runs) + row[k] = "%d/%d" % (f, n) + table[name] = row + return table + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--reps", type=int, default=3) + ap.add_argument("--rate", type=float, default=60) + ap.add_argument("--window", type=int, default=60) + ap.add_argument("--warmup", type=int, default=15) + ap.add_argument("--configs", default="off,full,head10,tail") + ap.add_argument("--out", default="evidence/track1") + a = ap.parse_args() + out = Path(a.out) + out.mkdir(parents=True, exist_ok=True) + names = a.configs.split(",") + results = [] + try: + for rep in range(a.reps): + for name in names: + r = one_run(name, a.rate, a.window, a.warmup) + r["rep"] = rep + 1 + results.append(r) + (out / "runs.json").write_text(json.dumps(results, ensure_ascii=False, indent=1)) + finally: + log("restore config full") + apply("full") + table = aggregate(results) + meta = {"rate_rps": a.rate, "window_s": a.window, "warmup_s": a.warmup, "reps": a.reps, "configs": CONFIGS, + "host_cpus": os.cpu_count(), "date": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())} + (out / "summary.json").write_text(json.dumps({"meta": meta, "table": table}, ensure_ascii=False, indent=1)) + print(json.dumps({"meta": meta, "table": table}, ensure_ascii=False, indent=1)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/research/trace_demo.py b/research/trace_demo.py new file mode 100644 index 00000000..71eb672b --- /dev/null +++ b/research/trace_demo.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python3 +"""Демонстрация на защите: один upload → trace от HTTP до worker/S3/DB, логи API и worker того же trace, +ссылка для Grafana Explore. С --retry имя файла содержит fault-transient-1 (FAULT_HOOKS=lab): первая попытка +падает «временно», вторая проходит — обе в одном trace. + + python3 research/trace_demo.py [--retry] +""" +import argparse +import json +import sys +import time +import urllib.parse +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "student-tests")) +from common import BASE_URL, Client, login, new_user, upload, wait_status # noqa: E402 +from obs import GRAFANA_URL, Grafana, wait_for # noqa: E402 + + +def explore_link(trace_id): + panes = {"a": {"datasource": "tempo", "queries": [{"refId": "A", "datasource": {"type": "tempo", "uid": "tempo"}, + "queryType": "traceql", "query": trace_id}], + "range": {"from": "now-6h", "to": "now"}}} + return GRAFANA_URL + "/explore?schemaVersion=1&orgId=1&panes=" + urllib.parse.quote(json.dumps(panes, separators=(",", ":"))) + + +def tree(spans): + kids = {} + for s in spans: + kids.setdefault(s["parent"], []).append(s) + ids = {s["span_id"] for s in spans} + lines = [] + + def walk(pid, d): + for s in sorted(kids.get(pid, []), key=lambda x: x["start"]): + extra = [] + for k in ("messenger.job.attempt", "messenger.job.outcome", "error.type", "http.response.status_code"): + if k in s["attrs"]: + extra.append("%s=%s" % (k.split(".")[-1], s["attrs"][k])) + lines.append("%s%-40s %-17s %-8s %8.1f мс %s" % (" " * d, s["name"][:40], s["service"], s["kind"], + (s["end"] - s["start"]) * 1000, " ".join(extra))) + walk(s["span_id"], d + 1) + for root in [p for p in kids if p not in ids]: + walk(root, 0) + return lines + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--retry", action="store_true") + a = ap.parse_args() + c, g = Client(BASE_URL), Grafana() + u = new_user(c, "demo") + login(c, u) + chat = c.call("POST", "/api/v1/chats", 201, actor=u, schema="Chat", body={"title": "demo", "member_ids": [u["id"]]})["json"] + t0 = time.time() + att, _ = upload(c, u, chat, filename="demo-fault-transient-1.png" if a.retry else "demo.png") + print("upload: 202, attachment_id=%s, status=%s" % (att["id"], att["status"])) + ready = wait_status(c, u, att["id"], "ready", timeout=90) + print("ready через %.1f с, варианты: %s" % (time.time() - t0, [v["name"] for v in ready["variants"]])) + + def find(): + tr = g.search('{ span.messenger.attachment.id = "%s" }' % att["id"], since=900) + spans = g.trace(tr[0]["traceID"]) if tr else None + return spans if spans and any(s["attrs"].get("messenger.job.outcome") == "ready" for s in spans) else None + spans = wait_for(find, 60, what="trace") + tid = spans[0]["trace_id"] + print("\nTraceQL: { span.messenger.attachment.id = \"%s\" }\ntrace_id: %s (%d spans)\n" % (att["id"], tid, len(spans))) + print("\n".join(tree(spans))) + print("\nЛоги того же trace (Loki: {service_name=~\"messenger-.*\"} | trace_id=\"%s\"):" % tid) + q = '{service_name=~"messenger-api|messenger-worker"} | trace_id="%s"' % tid + # логи доходят батчами (SDK 1 с + Collector 2 с): ждём записи обоих сервисов, не дольше 20 с + recs = wait_for(lambda: (lambda rs: rs if {r["service_name"] for r in rs} >= {"messenger-api", "messenger-worker"} + else None)(g.loki(q, since=900)), 20, what="logs of both services") + for r in recs: + fields = {k: r[k] for k in ("event", "attempt", "outcome", "error_code", "route", "status") if k in r} + print(" %s %-16s %-5s %s" % (time.strftime("%H:%M:%S", time.localtime(r["ts"])), r["service_name"], + r.get("severity_text", ""), json.dumps(fields, ensure_ascii=False))) + print("\nGrafana Explore (после входа admin):\n" + explore_link(tid)) + + +if __name__ == "__main__": + main() diff --git a/research/track2_chaos.py b/research/track2_chaos.py new file mode 100644 index 00000000..cfbf4843 --- /dev/null +++ b/research/track2_chaos.py @@ -0,0 +1,195 @@ +#!/usr/bin/env python3 +"""Трек 2: рандомизированный хаос-прогон pipeline с проверкой инвариантов (повторяемо по --seed). + +Гипотеза: при at-least-once доставке, повторах, переупорядочивании, падениях worker в любой точке +(до/после побочного эффекта, после COMMIT до ack), зависаниях и выкатке новой версии pipeline +(а) ни одна принятая (202) работа не теряется, (б) у каждой пары (вложение, версия) ровно один +набор вариантов и ровно один COMMIT, (в) опубликованная версия не откатывается назад. + +Во время прогона одновременно работают: + uploader — N загрузок; каждой с вероятностью задаётся точка отказа (маркер в имени файла); + duplicator — каждые ~2 с публикует 1–3 копии сообщения случайной работы (текущая/устаревшая попытка); + killer — каждые --kill-every с SIGKILL случайного worker (docker kill) и старт через 2–5 с; + versioner — для части готовых вложений ставит pipeline v2, затем снова шлёт им сообщения v1. +После — ждёт завершения всех работ и запускает `jobs invariants --settled --verify-bytes`. + + python3 research/track2_chaos.py --seed 1 --uploads 60 --output evidence/track2/chaos-seed1.json +""" +import argparse +import json +import os +import random +import shlex +import statistics +import subprocess +import sys +import threading +import time +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "student-tests")) +from common import DC, Client, Failure, jobs_cli, login, make_png, new_user, sql, upload # noqa: E402 + +FAULTS = [("", 45), ("fault-crash-before-s3", 10), ("fault-crash-after-s3", 10), ("fault-crash-after-commit", 10), + ("fault-transient-1", 10), ("fault-transient-2", 5), ("fault-slow-3", 5), ("fault-hang-30", 5)] + + +def worker_containers(): + out = subprocess.run(shlex.split(DC) + ["ps", "-a", "-q", "worker"], cwd=ROOT, capture_output=True, text=True) + return out.stdout.split() + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--base-url", default=os.environ.get("BASE_URL", "http://127.0.0.1:8080")) + ap.add_argument("--seed", type=int, default=1) + ap.add_argument("--uploads", type=int, default=60) + ap.add_argument("--kill-every", type=float, default=12.0) + ap.add_argument("--settle-timeout", type=float, default=300) + ap.add_argument("--output") + a = ap.parse_args() + rnd = random.Random(a.seed) + c = Client(a.base_url, timeout=30) + actor = new_user(c, "chaos") + login(c, actor) + chat = c.call("POST", "/api/v1/chats", 201, actor=actor, schema="Chat", + body={"title": "chaos %d" % a.seed, "member_ids": [actor["id"]]})["json"] + start = sql("SELECT to_char(clock_timestamp() AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"')")[0] + accepted, lock, stop = [], threading.Lock(), threading.Event() + counters = {"uploads_202": 0, "upload_errors": 0, "kills": 0, "duplicates_sent": 0, "stale_sent": 0, + "reprocess_v2": 0, "v1_after_v2_sent": 0} + planned = {} + + def uploader(): + names, weights = zip(*FAULTS) + for i in range(a.uploads): + fault = rnd.choices(names, weights)[0] + fname = "%s-chaos-%d.png" % (fault or "clean", i) + try: + att, _ = upload(c, actor, chat, make_png(40 + i % 50, 30 + i % 40), filename=fname) + with lock: + accepted.append(att["id"]) + planned[att["id"]] = fault or "none" + counters["uploads_202"] += 1 + except Failure: + counters["upload_errors"] += 1 # отказ ДО 202 — работа не принята, это не потеря + time.sleep(rnd.uniform(0.2, 0.8)) + + def duplicator(): + while not stop.is_set(): + time.sleep(rnd.uniform(1.0, 3.0)) + with lock: + if not accepted: + continue + aid = rnd.choice(accepted) + try: + jobs = jobs_cli("status", aid)["jobs"] + job = rnd.choice(jobs) + attempt = job["attempt"] if rnd.random() < 0.6 or job["attempt"] == 1 else rnd.randint(1, job["attempt"] - 1) + n = rnd.randint(1, 3) + jobs_cli("publish-raw", "--job", job["job_id"], "--attempt", attempt, "--count", n) + counters["duplicates_sent" if attempt == job["attempt"] else "stale_sent"] += n + except Failure: + pass + + def killer(): + while not stop.is_set(): + time.sleep(rnd.uniform(a.kill_every * 0.5, a.kill_every * 1.5)) + if stop.is_set(): + break + ids = worker_containers() + if not ids: + continue + victim = rnd.choice(ids) + subprocess.run(["docker", "kill", "-s", "KILL", victim], capture_output=True) + counters["kills"] += 1 + time.sleep(rnd.uniform(2, 5)) # «супервизор» поднимает процесс заново + subprocess.run(["docker", "start", victim], capture_output=True) + + def versioner(): + done = set() + while not stop.is_set(): + time.sleep(rnd.uniform(3, 6)) + with lock: + cands = [x for x in accepted if x not in done] + if not cands: + continue + aid = rnd.choice(cands) + try: + st = jobs_cli("status", aid) + if st["attachment"]["status"] != "ready": + continue + if jobs_cli("reprocess", "--attachment", aid, "--pipeline-version", 2)["result"] == "enqueued": + counters["reprocess_v2"] += 1 + done.add(aid) + time.sleep(rnd.uniform(0.5, 4)) + v1 = [j for j in jobs_cli("status", aid)["jobs"] if j["pipeline_version"] == 1][0] + jobs_cli("publish-raw", "--job", v1["job_id"], "--count", 2) + counters["v1_after_v2_sent"] += 2 + except Failure: + pass + + t0 = time.monotonic() + threads = [threading.Thread(target=f, daemon=True) for f in (duplicator, killer, versioner)] + for t in threads: + t.start() + up = threading.Thread(target=uploader) + up.start() + up.join() + time.sleep(10) # хаос продолжается ещё немного после последней загрузки + stop.set() + for t in threads: + t.join(timeout=60) + for cid in worker_containers(): # все worker'ы снова в строю + subprocess.run(["docker", "start", cid], capture_output=True) + chaos_seconds = time.monotonic() - t0 + + deadline = time.monotonic() + a.settle_timeout + inv = None + while time.monotonic() < deadline: + inv = jobs_cli("invariants", "--settled", "--since", start, expect=(0, 1)) + if inv["ok"]: + break + time.sleep(3) + settle_seconds = time.monotonic() - t0 - chaos_seconds + inv = jobs_cli("invariants", "--settled", "--verify-bytes", "--since", start, expect=(0, 1)) + + def q(query): + return sql(query.replace("{S}", "'%s'" % start)) + events = dict(r.split("|") for r in q( + "SELECT event, count(*) FROM job_events e JOIN attachments a ON a.id = e.attachment_id" + " WHERE a.created_at >= {S} GROUP BY event ORDER BY event")) + statuses = dict(r.split("|") for r in q( + "SELECT j.pipeline_version || ':' || j.status, count(*) FROM attachment_jobs j JOIN attachments a" + " ON a.id = j.attachment_id WHERE a.created_at >= {S} GROUP BY 1 ORDER BY 1")) + latency = [float(x) for x in q( + "SELECT extract(epoch FROM (c.created_at - e.created_at)) FROM job_events e JOIN job_events c" + " ON c.job_id = e.job_id AND c.event = 'committed' JOIN attachments a ON a.id = e.attachment_id" + " WHERE e.event = 'enqueued' AND a.created_at >= {S} AND e.pipeline_version = 1")] + att_status = dict(r.split("|") for r in q( + "SELECT status, count(*) FROM attachments WHERE created_at >= {S} GROUP BY status")) + lost = [x for x in accepted if x not in set(q("SELECT id FROM attachments WHERE created_at >= {S}" + " AND status IN ('ready', 'failed')"))] + report = { + "seed": a.seed, "uploads_requested": a.uploads, "counters": counters, + "planned_faults": {k: list(planned.values()).count(k) for k in sorted(set(planned.values()))}, + "chaos_seconds": round(chaos_seconds, 1), "settle_seconds": round(settle_seconds, 1), + "accepted_202": len(accepted), "accepted_not_terminal": len(lost), "attachment_status": att_status, + "job_status": statuses, "events": events, + "enqueue_to_commit_seconds_v1": { + "p50": round(statistics.median(latency), 2) if latency else None, + "p95": round(sorted(latency)[int(0.95 * (len(latency) - 1))], 2) if latency else None, + "max": round(max(latency), 2) if latency else None}, + "invariants": inv, + } + text = json.dumps(report, ensure_ascii=False, indent=1) + print(text) + if a.output: + Path(a.output).parent.mkdir(parents=True, exist_ok=True) + Path(a.output).write_text(text + "\n", encoding="utf-8") + sys.exit(0 if inv["ok"] and not lost else 1) + + +if __name__ == "__main__": + main() diff --git a/research/upload_memory.py b/research/upload_memory.py new file mode 100644 index 00000000..e6be3a0c --- /dev/null +++ b/research/upload_memory.py @@ -0,0 +1,153 @@ +#!/usr/bin/env python3 +"""Эксперимент (уровень 4): пик RSS API при N одновременных загрузках ~10 МиБ. + +Гипотеза: upload потоковый (кусок ≈64 КиБ → валидатор/SHA-256 → S3 PUT), поэтому пик RSS реплики +растёт на O(N × буфер), а не на O(N × размер файла). Если бы тело буферизовалось целиком, 20 загрузок +по 10 МиБ на одной реплике дали бы ≥ +200 МиБ (и упёрлись бы в лимит контейнера 256 МиБ). + +Методика (повторяемая): для каждого сценария сбрасываем VmHWM обеих API-реплик +(`python -m messenger stats --reset-peak` внутри контейнера), запускаем N параллельных загрузок +несжимаемого PNG через LB, затем читаем VmHWM/VmRSS. Сценарии: fast (клиент шлёт без пауз) и slow +(клиент шлёт кусками по 64 КиБ со скоростью ~2 МиБ/с — соединения долго держат слот). + + python3 research/upload_memory.py --output evidence/upload-memory.json +""" +import argparse +import json +import os +import shlex +import socket +import subprocess +import sys +import threading +import time +import zlib +from pathlib import Path +from urllib.parse import quote, urlsplit + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "student-tests")) +from common import DC, Client, login, new_user # noqa: E402 + + +def big_png(target): + side = int(((target - 4096) / 3) ** 0.5) + rows = b"".join(b"\x00" + os.urandom(side * 3) for _ in range(side)) + + def chunk(t, d): + return len(d).to_bytes(4, "big") + t + d + zlib.crc32(t + d).to_bytes(4, "big") + ihdr = side.to_bytes(4, "big") + side.to_bytes(4, "big") + bytes([8, 2, 0, 0, 0]) + return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(rows, 1)) + chunk(b"IEND", b"") + + +def replicas(): + out = subprocess.run(shlex.split(DC + " ps -q api"), cwd=ROOT, capture_output=True, text=True, check=True) + return [c for c in out.stdout.split() if c] + + +def stats(cid, reset=False): + cmd = ["docker", "exec", cid, "python", "-m", "messenger", "stats"] + (["--reset-peak"] if reset else []) + return json.loads(subprocess.run(cmd, capture_output=True, text=True, check=True, timeout=30).stdout) + + +def send(base, token, chat_id, data, rate, results): + u = urlsplit(base) + head = ("POST /api/v1/chats/%s/attachments?filename=%s HTTP/1.1\r\nHost: %s\r\nAuthorization: Bearer %s\r\n" + "Content-Type: image/png\r\nContent-Length: %d\r\nConnection: close\r\n\r\n" + % (chat_id, quote("mem.png"), u.netloc, token, len(data))).encode() + t = time.monotonic() + try: + s = socket.create_connection((u.hostname, u.port or 80), timeout=120) + s.sendall(head) + step = 65536 + for i in range(0, len(data), step): + s.sendall(data[i:i + step]) + if rate: + time.sleep(step / rate) + resp = b"" + while b"\r\n" not in resp: + part = s.recv(4096) + if not part: + break + resp += part + s.close() + status = int(resp.split(b" ", 2)[1]) if resp else 0 + except OSError as exc: + status = type(exc).__name__ + results.append({"status": status, "seconds": round(time.monotonic() - t, 3)}) + + +def s3_memory_sampler(stop, samples): + """Пик анонимной памяти контейнера s3 (cgroup memory.stat) — опрос каждые 0.2 с во время сценария.""" + cid = subprocess.run(shlex.split(DC + " ps -q s3"), cwd=ROOT, capture_output=True, text=True).stdout.strip() + while not stop.is_set() and cid: + # cgroup v2 (Docker Desktop) или v1 (старые Linux-хосты) + # Анонимная память (без page cache): cgroup v2 memory.stat «anon» (Docker Desktop) или v1 «total_rss». + r = subprocess.run(["docker", "exec", cid, "sh", "-c", "cat /sys/fs/cgroup/memory.stat 2>/dev/null" + " || cat /sys/fs/cgroup/memory/memory.stat"], capture_output=True, text=True) + for line in r.stdout.splitlines(): + name, _, value = line.partition(" ") + if name in ("anon", "total_rss") and value.strip().isdigit(): + samples.append(int(value)) + break + time.sleep(0.2) + + +def scenario(base, actor, chat, data, n, rate): + ids = replicas() + stop, s3mem = threading.Event(), [] + sampler = threading.Thread(target=s3_memory_sampler, args=(stop, s3mem)) + sampler.start() + before = {cid[:12]: stats(cid, reset=True)["memory"] for cid in ids} + results, threads = [], [] + for _ in range(n): + threads.append(threading.Thread(target=send, args=(base, actor["token"], chat["id"], data, rate, results))) + t = time.monotonic() + for th in threads: + th.start() + for th in threads: + th.join() + wall = time.monotonic() - t + stop.set(); sampler.join() + after = {cid[:12]: stats(cid)["memory"] for cid in ids} + per = {k: {"rss_before_kib": before[k]["rss_kib"], "peak_kib": after[k]["peak_rss_kib"], + "peak_delta_mib": round((after[k]["peak_rss_kib"] - before[k]["rss_kib"]) / 1024, 1)} for k in after} + ok = sum(1 for r in results if r["status"] == 202) # lab5: upload → 202 + return {"concurrency": n, "client_rate_bytes_per_s": rate or "unlimited", "file_bytes": len(data), + "ok_202": ok, "statuses": sorted({str(r["status"]) for r in results}), "wall_seconds": round(wall, 2), + "upload_seconds_max": max(r["seconds"] for r in results), "replicas": per, + "max_peak_delta_mib": max(v["peak_delta_mib"] for v in per.values()), + "s3_anon_peak_mib": round(max(s3mem) / 2**20, 1) if s3mem else None, + "if_buffered_mib_per_replica": round(n / max(1, len(per)) * len(data) / 2**20, 1)} + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--base-url", default=os.environ.get("BASE_URL", "http://127.0.0.1:8080")) + ap.add_argument("--size", type=int, default=10 * 2**20 - 64 * 1024) + ap.add_argument("--levels", default="1,10,20,32") + ap.add_argument("--slow-levels", default="10,20") + ap.add_argument("--slow-rate", type=int, default=2 * 2**20) + ap.add_argument("--output") + a = ap.parse_args() + c = Client(a.base_url, timeout=30) + actor = new_user(c, "mem"); login(c, actor) + chat = c.call("POST", "/api/v1/chats", 201, actor=actor, schema="Chat", + body={"title": "memory", "member_ids": [actor["id"]]})["json"] + data = big_png(a.size) + runs = [] + for n in [int(x) for x in a.levels.split(",") if x]: + runs.append(scenario(a.base_url, actor, chat, data, n, 0)) + print(json.dumps(runs[-1], ensure_ascii=False)) + for n in [int(x) for x in a.slow_levels.split(",") if x]: + runs.append(scenario(a.base_url, actor, chat, data, n, a.slow_rate)) + print(json.dumps(runs[-1], ensure_ascii=False)) + report = {"hypothesis": "peak RSS grows by O(N*chunk), not O(N*file)", "file_mib": round(len(data) / 2**20, 2), + "limits": {"UPLOAD_CONCURRENCY_per_replica": 16, "api_memory_limit": "256M", "s3_memory_limit": "1G", + "s3_concurrentUploadLimitMB": 96}, "runs": runs} + if a.output: + Path(a.output).write_text(json.dumps(report, ensure_ascii=False, indent=1) + "\n", encoding="utf-8") + + +if __name__ == "__main__": + main() diff --git a/scripts/collect-evidence.ps1 b/scripts/collect-evidence.ps1 new file mode 100644 index 00000000..3e6d5e61 --- /dev/null +++ b/scripts/collect-evidence.ps1 @@ -0,0 +1,140 @@ +# Windows PowerShell 5.1+ equivalent of scripts/collect-evidence.sh (lab6). +# Starts the Compose stand (LB + API replicas + workers + one-shot bootstrap + PostgreSQL + Redis + SeaweedFS S3 + +# NATS JetStream + OTel Collector + Prometheus + Loki + Tempo + Grafana), runs every check and writes outputs to +# evidence\ (no tokens/passwords/keys). Stops/restarts containers (worker, DB, Collector, Tempo, Loki, API +# replicas); volumes are never removed. Takes ~90 minutes (-SkipRegression: ~60, -SkipResearch: -35 more). +# powershell -NoProfile -ExecutionPolicy Bypass -File scripts\collect-evidence.ps1 [-SkipRegression] [-SkipResearch] +param([switch]$SkipRegression, [switch]$SkipResearch) +$ErrorActionPreference = 'Continue' +$root = Split-Path -Parent $PSScriptRoot +Set-Location $root +$env:PYTHONUTF8 = '1' +$env:PYTHONIOENCODING = 'utf-8' +# IPv4 explicitly: on Windows 'localhost' resolves to ::1 first; the LB listens on 127.0.0.1 only. +$env:NO_PROXY = '127.0.0.1,localhost' +$B = 'http://127.0.0.1:8080' +$env:BASE_URL = $B +$env:TTL_BASE_URL = 'http://127.0.0.1:8081' +$ev = Join-Path $root 'evidence' +New-Item -ItemType Directory -Force -Path $ev, (Join-Path $ev 'track1'), (Join-Path $ev 'track2'), (Join-Path $ev 'incidents') | Out-Null + +# Full path of the Python APPLICATION: a bare 'py' would resolve to a PowerShell function first. +$pyApp = Get-Command py -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1 +$pythonApp = Get-Command python -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1 +if ($pyApp) { $script:PyExe = $pyApp.Source; $script:PyPre = @('-3') } +elseif ($pythonApp) { $script:PyExe = $pythonApp.Source; $script:PyPre = @() } +else { throw 'Python 3.9+ not found (install from python.org, enable "Add to PATH")' } +function Invoke-Python { & $script:PyExe @script:PyPre @args } +function Dc { & docker compose --env-file .env @args } +$hookStop = if ($IsLinux -or $IsMacOS) { 'scripts/stop-one.sh' } else { 'scripts\stop-one.cmd' } +$hookRestart = if ($IsLinux -or $IsMacOS) { 'scripts/restart.sh' } else { 'scripts\restart.cmd' } +$startReplicas = Join-Path $PSScriptRoot 'start-replicas.ps1' + +function Get-Stamp { + $commit = 'n/a' + if (Get-Command git -ErrorAction SilentlyContinue) { + $c = (& git rev-parse --short HEAD 2>$null) + if ($LASTEXITCODE -eq 0 -and $c) { $commit = $c } + } + '# ' + (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ') + ' commit=' + $commit + ' host=' + [Environment]::OSVersion.VersionString + ' cpus=' + [Environment]::ProcessorCount +} +function Invoke-Step([string]$name, [string]$title, [scriptblock]$block) { + Write-Host ('>>> ' + $name) -ForegroundColor Cyan + $global:LASTEXITCODE = 0 + $lines = @(& $block 2>&1 | ForEach-Object { "$_" }) + $code = $global:LASTEXITCODE + Set-Content -Path (Join-Path $ev ($name + '.txt')) -Encoding UTF8 -Value (@((Get-Stamp), ('$ ' + $title)) + $lines + @('exit=' + $code)) + $lines | Select-Object -Last 2 | ForEach-Object { Write-Host (' ' + $_) } + if ($code -ne 0) { Write-Host (' exit=' + $code + ' (see evidence\' + $name + '.txt)') -ForegroundColor Yellow } +} + +& docker version --format '{{.Server.Version}}' *> $null +if ($LASTEXITCODE -ne 0) { throw 'Docker is not running: start Docker Desktop first' } +& (Join-Path $PSScriptRoot 'init-secrets.ps1') +Set-Location $root +Write-Host '>>> docker compose up (build, wait for healthchecks)' -ForegroundColor Cyan +Dc --profile ttl up -d --build --wait +if ($LASTEXITCODE -ne 0) { Dc logs --tail=80; throw 'docker compose up failed' } +$mount = (Join-Path $root 'student-tests') + ':/app/student-tests:ro' + +Invoke-Step 'stack' 'docker version; compose images; ps' { & docker version --format 'docker {{.Server.Version}}'; Dc version; Dc --profile ttl images; Dc --profile ttl ps -a } +Invoke-Step 'migrations' 'schema_migrations; docker compose logs migrate' { + Dc exec -T postgres psql -U messenger -d messenger -c 'SELECT version, left(checksum,12) AS checksum, applied_at FROM schema_migrations ORDER BY version' + Dc logs --no-log-prefix migrate +} +Invoke-Step 'broker-bootstrap' 'docker compose logs broker-init' { Dc logs --no-log-prefix broker-init } +Invoke-Step 's3-bootstrap' 'docker compose logs s3-init' { Dc logs --no-log-prefix s3-init } +Invoke-Step 'no-local-files' 'docker inspect api/worker: ReadonlyRootfs, tmpfs, mounts' { + foreach ($cid in @(Dc ps -q api worker)) { + & docker inspect -f '{{.Name}} ReadonlyRootfs={{.HostConfig.ReadonlyRootfs}} Tmpfs={{json .HostConfig.Tmpfs}} Mounts={{range .Mounts}}{{.Type}}:{{.Destination}} {{end}}' $cid + } +} +Invoke-Step 'published-ports' 'docker compose ps: published ports' { Dc ps --format '{{.Service}} {{.Ports}}' | Sort-Object -Unique } +Invoke-Step 'make-check' 'python scripts/check_contract.py' { Invoke-Python scripts/check_contract.py } +Invoke-Step 'smoke' "python tests/smoke.py --base-url $B" { Invoke-Python tests/smoke.py --base-url $B } +# ---------------------------------------------------------------- lab6: observability +Invoke-Step 'collector-config-validate' 'otelcol-contrib validate --config=collector.yaml' { + Dc run --rm --no-deps otel-collector validate --config=/etc/otelcol-contrib/collector.yaml +} +Invoke-Step 'test-observability' 'python student-tests/test_observability.py' { Invoke-Python student-tests/test_observability.py } +Invoke-Step 'observability' 'python research/obs_snapshot.py' { Invoke-Python research/obs_snapshot.py } +Set-Content -Path (Join-Path $ev 'restart-hook.txt') -Encoding UTF8 -Value @() +Invoke-Step 'test-telemetry-persistence' 'python student-tests/test_telemetry_persistence.py # restarts everything' { + Invoke-Python student-tests/test_telemetry_persistence.py +} +foreach ($sc in 'worker-stop', 'db-slow', 'handler-slow', 'db-down', 'telemetry-down', 'collector-down') { + Invoke-Step ('incident-' + $sc) ('python research/incidents.py ' + $sc) { + Invoke-Python research/incidents.py $sc --out evidence/incidents + } +} +# ---------------------------------------------------------------- public failover / persistence checks +Set-Content -Path (Join-Path $ev 'failover-hook.txt') -Encoding UTF8 -Value @() +foreach ($i in 1, 2) { + Invoke-Step ('failover-' + $i) ('python tests/resilience.py --mode failover --action-script ' + $hookStop) { + Invoke-Python tests/resilience.py --mode failover --action-script $hookStop --base-url $B + } + Invoke-Step ('restore-' + $i) 'scripts\start-replicas.ps1' { & $startReplicas } +} +Set-Content -Path (Join-Path $ev 'restart-hook.txt') -Encoding UTF8 -Value @() +Invoke-Step 'persistence' ('python tests/resilience.py --mode persistence --action-script ' + $hookRestart) { + Invoke-Python tests/resilience.py --mode persistence --action-script $hookRestart --base-url $B +} +# ---------------------------------------------------------------- lab2-lab5 regression with telemetry enabled +if (-not $SkipRegression) { + Invoke-Step 'test-pipeline' 'python student-tests/test_pipeline.py' { Invoke-Python student-tests/test_pipeline.py } + Invoke-Step 'test-imgproc' 'docker compose run worker: python student-tests/test_imgproc.py' { + Dc run --rm --no-deps -T -v $mount --entrypoint python worker student-tests/test_imgproc.py + } + Invoke-Step 'defense-demo' 'python student-tests/defense_demo.py' { Invoke-Python student-tests/defense_demo.py } + Invoke-Step 'test-attachments' 'python student-tests/test_attachments.py' { Invoke-Python student-tests/test_attachments.py } + Invoke-Step 'test-api' 'python student-tests/test_api.py' { Invoke-Python student-tests/test_api.py } + Invoke-Step 'test-idempotency' 'python student-tests/test_idempotency.py' { Invoke-Python student-tests/test_idempotency.py } + Invoke-Step 'test-expiry' 'python student-tests/test_expiry.py # api-ttl via LB :8081' { Invoke-Python student-tests/test_expiry.py } + Invoke-Step 'test-cache-race' 'docker compose run api: python student-tests/test_cache_race.py' { + Dc run --rm --no-deps -T -v $mount --entrypoint python api student-tests/test_cache_race.py + } + Invoke-Step 'test-jobs-failures' 'python student-tests/test_jobs_failures.py' { Invoke-Python student-tests/test_jobs_failures.py } + Invoke-Step 'test-storage-failures' 'python student-tests/test_storage_failures.py' { Invoke-Python student-tests/test_storage_failures.py } + Invoke-Step 'test-failures' 'python student-tests/test_failures.py' { Invoke-Python student-tests/test_failures.py } + Invoke-Step 'test-track2-lab5' 'python student-tests/test_pipeline_idempotency.py' { Invoke-Python student-tests/test_pipeline_idempotency.py } + Invoke-Step 'track2-chaos-seed1' 'python research/track2_chaos.py --seed 1' { + Invoke-Python research/track2_chaos.py --seed 1 --uploads 60 --output evidence/track2/chaos-seed1.json + } +} +# ---------------------------------------------------------------- track 1 +if (-not $SkipResearch) { + Invoke-Step 'track1-telemetry-cost' 'python research/telemetry_cost.py --reps 3 --rate 60 --window 60' { + Invoke-Python research/telemetry_cost.py --reps 3 --rate 60 --window 60 --out evidence/track1 + } +} +Invoke-Step 'jobs-failed' 'docker compose exec api python -m messenger jobs failed --limit 20' { Dc exec -T api python -m messenger jobs failed --limit 20 } +Invoke-Step 'jobs-invariants' 'docker compose exec api python -m messenger jobs invariants --settled --verify-bytes' { + Dc exec -T api python -m messenger jobs invariants --settled --verify-bytes +} +Invoke-Step 'migrations-rerun' 'docker compose run --rm --no-deps migrate' { Dc run --rm --no-deps migrate } +Invoke-Step 'load' 'python tests/load.py --duration 30 --concurrency 4' { + Invoke-Python tests/load.py --base-url $B --duration 30 --concurrency 4 --output evidence/load.json +} +Invoke-Step 'test-observability-final' 'python student-tests/test_observability.py' { Invoke-Python student-tests/test_observability.py } +Invoke-Step 'observability-final' 'python research/obs_snapshot.py' { Invoke-Python research/obs_snapshot.py } +Write-Host 'Done: evidence collected in evidence\' -ForegroundColor Green diff --git a/scripts/collect-evidence.sh b/scripts/collect-evidence.sh new file mode 100644 index 00000000..15787e3c --- /dev/null +++ b/scripts/collect-evidence.sh @@ -0,0 +1,71 @@ +#!/bin/sh +# Полный прогон доказательств lab6 на Compose-стенде; вывод — evidence/ (без токенов, паролей и ключей). +# Останавливает/перезапускает контейнеры стенда (worker, БД, Collector, Tempo, Loki, реплики API …). +# Volumes не удаляются. Длительность ≈ 90 мин; SKIP_REGRESSION=1 (без тестов lab2–lab5) — ≈ 60 мин, +# SKIP_RESEARCH=1 (без трека 1) — ещё −35 мин. +set -eu +cd "$(dirname "$0")/.." +. scripts/lib.sh +PY=${PYTHON:-python3} +B=${BASE_URL:-http://127.0.0.1:8080} +export BASE_URL=$B TTL_BASE_URL=${TTL_BASE_URL:-http://127.0.0.1:8081} NO_PROXY=127.0.0.1,localhost no_proxy=127.0.0.1,localhost +mkdir -p evidence evidence/incidents evidence/track1 evidence/track2 +stamp() { echo "# $(now) commit=$(git rev-parse --short HEAD 2>/dev/null || echo n/a) host=$(uname -srm) cpus=$(getconf _NPROCESSORS_ONLN)"; } +run() { name=$1; shift; { stamp; echo "\$ $*"; "$@" 2>&1; echo "exit=$?"; } > "evidence/$name.txt" || true; tail -2 "evidence/$name.txt"; } +IN_WORKER="dc run --rm --no-deps -T -v $PWD/student-tests:/app/student-tests:ro --entrypoint python worker" +IN_API="dc run --rm --no-deps -T -v $PWD/student-tests:/app/student-tests:ro --entrypoint python api" + +./scripts/init-secrets.sh +dc --profile ttl up -d --build --wait +{ stamp; docker version --format 'docker {{.Server.Version}}'; dc version; dc --profile ttl images; dc --profile ttl ps -a; state; } > evidence/stack.txt 2>&1 +run migrations sh -c "docker compose --env-file .env exec -T postgres psql -U messenger -d messenger -c 'SELECT version, left(checksum,12) AS checksum, applied_at FROM schema_migrations ORDER BY version'; docker compose --env-file .env logs --no-log-prefix migrate" +run broker-bootstrap dc logs --no-log-prefix broker-init +run s3-bootstrap dc logs --no-log-prefix s3-init +run no-local-files sh -c "for c in \$(docker compose --env-file .env ps -q api worker); do docker inspect -f '{{.Name}} ReadonlyRootfs={{.HostConfig.ReadonlyRootfs}} Tmpfs={{json .HostConfig.Tmpfs}} Mounts={{range .Mounts}}{{.Type}}:{{.Destination}} {{end}}' \$c; done" +run published-ports sh -c "docker compose --env-file .env ps --format '{{.Service}} {{.Ports}}' | sort -u" +run make-check make check +run smoke $PY tests/smoke.py --base-url "$B" +# ---------------------------------------------------------------- lab6: наблюдаемость +run collector-config-validate dc run --rm --no-deps otel-collector validate --config=/etc/otelcol-contrib/collector.yaml +run test-observability $PY student-tests/test_observability.py +run observability $PY research/obs_snapshot.py +: > evidence/restart-hook.txt +run test-telemetry-persistence $PY student-tests/test_telemetry_persistence.py +for s in worker-stop db-slow handler-slow db-down telemetry-down collector-down; do + run incident-$s $PY research/incidents.py $s --out evidence/incidents +done +# ---------------------------------------------------------------- публичные проверки отказа и сохранности +: > evidence/failover-hook.txt +run failover-1 $PY tests/resilience.py --mode failover --action-script scripts/stop-one.sh --base-url "$B" +run restore-1 ./scripts/start-replicas.sh +run failover-2 $PY tests/resilience.py --mode failover --action-script scripts/stop-one.sh --base-url "$B" +run restore-2 ./scripts/start-replicas.sh +: > evidence/restart-hook.txt +run persistence $PY tests/resilience.py --mode persistence --action-script scripts/restart.sh --base-url "$B" +# ---------------------------------------------------------------- регрессия lab2–lab5 (make test при включённой telemetry) +if [ "${SKIP_REGRESSION:-0}" != 1 ]; then + run test-pipeline $PY student-tests/test_pipeline.py + run test-imgproc $IN_WORKER student-tests/test_imgproc.py + run defense-demo $PY student-tests/defense_demo.py + run test-attachments $PY student-tests/test_attachments.py + run test-api $PY student-tests/test_api.py + run test-idempotency $PY student-tests/test_idempotency.py + run test-expiry $PY student-tests/test_expiry.py + run test-cache-race $IN_API student-tests/test_cache_race.py + run test-jobs-failures $PY student-tests/test_jobs_failures.py + run test-storage-failures $PY student-tests/test_storage_failures.py + run test-failures $PY student-tests/test_failures.py + run test-track2-lab5 $PY student-tests/test_pipeline_idempotency.py + run track2-chaos-seed1 $PY research/track2_chaos.py --seed 1 --uploads 60 --output evidence/track2/chaos-seed1.json +fi +# ---------------------------------------------------------------- трек 1 +if [ "${SKIP_RESEARCH:-0}" != 1 ]; then + run track1-telemetry-cost $PY research/telemetry_cost.py --reps 3 --rate 60 --window 60 --out evidence/track1 +fi +run jobs-failed dc exec -T api python -m messenger jobs failed --limit 20 +run jobs-invariants dc exec -T api python -m messenger jobs invariants --settled --verify-bytes +run migrations-rerun dc run --rm --no-deps migrate +run load $PY tests/load.py --base-url "$B" --duration 30 --concurrency 4 --output evidence/load.json +run test-observability-final $PY student-tests/test_observability.py +run observability-final $PY research/obs_snapshot.py +echo "evidence collected in evidence/" diff --git a/scripts/init-secrets.ps1 b/scripts/init-secrets.ps1 new file mode 100644 index 00000000..25c4b1fe --- /dev/null +++ b/scripts/init-secrets.ps1 @@ -0,0 +1,88 @@ +# Windows PowerShell 5.1+ version of scripts/init-secrets.sh. +# Creates local synthetic secrets in secrets\ and .env (both git-ignored). +# Idempotent: existing files are NOT overwritten. Values are never printed. +$ErrorActionPreference = 'Stop' +$root = Split-Path -Parent $PSScriptRoot +Set-Location $root +New-Item -ItemType Directory -Force -Path (Join-Path $root 'secrets'), (Join-Path $root 'backups') | Out-Null +$ascii = New-Object System.Text.ASCIIEncoding + +function New-Hex { + $bytes = New-Object byte[] 24 + $rng = [System.Security.Cryptography.RandomNumberGenerator]::Create() + $rng.GetBytes($bytes) + ($bytes | ForEach-Object { $_.ToString('x2') }) -join '' +} +function Set-SecretFile([string]$name, [string]$value) { + $path = Join-Path (Join-Path $root 'secrets') $name + if (-not (Test-Path $path)) { + # No BOM, no trailing CR/LF: the value is read verbatim inside Linux containers. + [System.IO.File]::WriteAllText($path, $value, $ascii) + } +} +function Get-SecretFile([string]$name) { + ([System.IO.File]::ReadAllText((Join-Path (Join-Path $root 'secrets') $name))).Trim() +} + +Set-SecretFile 'postgres_password' (New-Hex) +Set-SecretFile 'redis_password' (New-Hex) +$pg = Get-SecretFile 'postgres_password' +$rd = Get-SecretFile 'redis_password' +Set-SecretFile 'database_url' ("postgresql://messenger:" + $pg + "@postgres:5432/messenger") +Set-SecretFile 'cache_url' ("redis://:" + $rd + "@redis:6379/0") +# S3 (SeaweedFS): two identities. admin - only for bucket bootstrap (s3-init service); +# messenger-api - Read/Write/List ONLY on the attachments bucket (cannot create/delete buckets). +function New-KeyId { + $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' + $bytes = New-Object byte[] 20 + [System.Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($bytes) + ($bytes | ForEach-Object { $chars[$_ % $chars.Length] }) -join '' +} +Set-SecretFile 's3_admin_access_key_id' (New-KeyId) +Set-SecretFile 's3_admin_secret_access_key' (New-Hex) +Set-SecretFile 's3_access_key_id' (New-KeyId) +Set-SecretFile 's3_secret_access_key' (New-Hex) +$bucket = 'messenger-attachments' +$envPath = Join-Path $root '.env' +if (Test-Path $envPath) { + $line = Select-String -Path $envPath -Pattern '^S3_BUCKET=(.+)$' | Select-Object -First 1 + if ($line) { $bucket = $line.Matches[0].Groups[1].Value.Trim() } +} +$cfgPath = Join-Path (Join-Path $root 'secrets') 's3_config.json' +if (-not (Test-Path $cfgPath)) { + $cfg = [ordered]@{ identities = @( + [ordered]@{ name = 'admin'; credentials = @([ordered]@{ accessKey = (Get-SecretFile 's3_admin_access_key_id'); secretKey = (Get-SecretFile 's3_admin_secret_access_key') }); + actions = @('Admin', 'Read', 'List', 'Tagging', 'Write') }, + [ordered]@{ name = 'messenger-api'; credentials = @([ordered]@{ accessKey = (Get-SecretFile 's3_access_key_id'); secretKey = (Get-SecretFile 's3_secret_access_key') }); + actions = @(('Read:' + $bucket), ('Write:' + $bucket), ('List:' + $bucket)) } + ) } + [System.IO.File]::WriteAllText($cfgPath, ($cfg | ConvertTo-Json -Depth 6), $ascii) +} +# NATS JetStream: service password (API, worker, bootstrap) and the server config that holds it. +Set-SecretFile 'nats_password' (New-Hex) +$np = Get-SecretFile 'nats_password' +Set-SecretFile 'broker_url' ('nats://messenger:' + $np + '@nats:4222') +$natsConf = @( + '# nats-server (lab5): JetStream on disk with fsync on every write, password auth,', + '# monitoring (healthcheck) only on 127.0.0.1 inside the container.', + 'server_name: nats-lab6', + 'listen: "0.0.0.0:4222"', + 'http: "127.0.0.1:8222"', + 'max_payload: 65536', + 'jetstream {', + ' store_dir: "/data"', + ' max_memory_store: 64MB', + ' max_file_store: 2GB', + ' sync_interval: always', + '}', + 'authorization {', + (' users = [ { user: "messenger", password: "' + $np + '" } ]'), + '}' +) -join "`n" +Set-SecretFile 'nats.conf' ($natsConf + "`n") +# lab6: Grafana admin password (UI on 127.0.0.1:3000; tests read it locally and never print it). +Set-SecretFile 'grafana_admin_password' (New-Hex) +if (-not (Test-Path (Join-Path $root '.env'))) { + Copy-Item (Join-Path $root '.env.example') (Join-Path $root '.env') +} +Write-Output 'secrets\ and .env are ready (values not shown).' diff --git a/scripts/init-secrets.sh b/scripts/init-secrets.sh new file mode 100644 index 00000000..e9fbfe55 --- /dev/null +++ b/scripts/init-secrets.sh @@ -0,0 +1,63 @@ +#!/bin/sh +# Создаёт локальные синтетические secrets для стенда (каталог secrets/ в .gitignore). +# Идемпотентно: существующие файлы НЕ перезаписываются (иначе пароль разойдётся с уже +# инициализированным volume PostgreSQL). Значения не печатаются. +set -eu +cd "$(dirname "$0")/.." +umask 077 +mkdir -p secrets backups +chmod 700 secrets +gen() { python3 -c 'import secrets; print(secrets.token_hex(24))'; } +if [ ! -f secrets/postgres_password ]; then gen > secrets/postgres_password; fi +if [ ! -f secrets/redis_password ]; then gen > secrets/redis_password; fi +PG=$(cat secrets/postgres_password) +RD=$(cat secrets/redis_password) +[ -f secrets/database_url ] || printf 'postgresql://messenger:%s@postgres:5432/messenger\n' "$PG" > secrets/database_url +[ -f secrets/cache_url ] || printf 'redis://:%s@redis:6379/0\n' "$RD" > secrets/cache_url +# S3 (SeaweedFS): две identity. admin — только для bootstrap bucket (сервис s3-init); +# api — права Read/Write/List ТОЛЬКО на bucket вложений (не может создавать/удалять бакеты). +keyid() { python3 -c 'import secrets,string; print("".join(secrets.choice(string.ascii_uppercase+string.digits) for _ in range(20)))'; } +[ -f secrets/s3_admin_access_key_id ] || keyid > secrets/s3_admin_access_key_id +[ -f secrets/s3_admin_secret_access_key ] || gen > secrets/s3_admin_secret_access_key +[ -f secrets/s3_access_key_id ] || keyid > secrets/s3_access_key_id +[ -f secrets/s3_secret_access_key ] || gen > secrets/s3_secret_access_key +BUCKET=$(grep -E '^S3_BUCKET=' .env 2>/dev/null | cut -d= -f2); BUCKET=${BUCKET:-messenger-attachments} +[ -f secrets/s3_config.json ] || python3 - "$BUCKET" > secrets/s3_config.json <<'PY' +import json, sys +b = sys.argv[1] +r = lambda n: open("secrets/" + n).read().strip() +print(json.dumps({"identities": [ + {"name": "admin", "credentials": [{"accessKey": r("s3_admin_access_key_id"), "secretKey": r("s3_admin_secret_access_key")}], + "actions": ["Admin", "Read", "List", "Tagging", "Write"]}, + {"name": "messenger-api", "credentials": [{"accessKey": r("s3_access_key_id"), "secretKey": r("s3_secret_access_key")}], + "actions": ["Read:" + b, "Write:" + b, "List:" + b]}]}, indent=1)) +PY +# NATS JetStream: пароль сервисов (API, worker, bootstrap) и конфигурация сервера с ним. +[ -f secrets/nats_password ] || gen > secrets/nats_password +NP=$(cat secrets/nats_password) +[ -f secrets/broker_url ] || printf 'nats://messenger:%s@nats:4222\n' "$NP" > secrets/broker_url +[ -f secrets/nats.conf ] || cat > secrets/nats.conf < secrets/grafana_admin_password +# Файлы монтируются в контейнеры как /run/secrets/*; процесс API работает под uid 10001, +# поэтому файл должен быть читаем внутри контейнера. Каталог secrets/ закрыт (700) на хосте. +chmod 644 secrets/* +[ -f .env ] || cp .env.example .env +mkdir -p backups +echo "secrets/ and .env are ready (values not shown)." diff --git a/scripts/lib.sh b/scripts/lib.sh new file mode 100644 index 00000000..b68d13c3 --- /dev/null +++ b/scripts/lib.sh @@ -0,0 +1,26 @@ +# Общие функции хуков (POSIX sh). Подключается: . "$(dirname "$0")/lib.sh" +cd "$(dirname "$0")/.." +ENV_FILE=${ENV_FILE:-.env} +dc() { docker compose --env-file "$ENV_FILE" "$@"; } +now() { date -u +%FT%TZ; } +# Состояние всех контейнеров проекта: сервис, имя, статус, StartedAt, PID, alias реплики API. +state() { + for cid in $(dc ps -a -q); do + docker inspect -f '{{index .Config.Labels "com.docker.compose.service"}} {{.Name}} status={{.State.Status}} started={{.State.StartedAt}} pid={{.State.Pid}}' "$cid" | + sed 's# /# #' + done | sort +} +# Контейнер API-реплики по её X-Instance-Id (alias пишется репликой в /tmp/instance-id). +container_of() { + for cid in $(dc ps -q api); do + if [ "$(docker exec "$cid" cat /tmp/instance-id 2>/dev/null)" = "$1" ]; then echo "$cid"; return 0; fi + done + return 1 +} +# Ждать healthy у всех контейнеров сервиса (не дольше 60 с). +wait_healthy() { + for cid in $(dc ps -q "$1"); do + i=0 + until [ "$(docker inspect -f '{{.State.Health.Status}}' "$cid")" = healthy ] || [ $i -ge 120 ]; do i=$((i + 1)); sleep 0.5; done + done +} diff --git a/scripts/restart-api-broker.ps1 b/scripts/restart-api-broker.ps1 new file mode 100644 index 00000000..e3546374 --- /dev/null +++ b/scripts/restart-api-broker.ps1 @@ -0,0 +1,18 @@ +# Defense scenario step 3: restart NATS (volume natsdata kept) and all API replicas; workers are NOT started. +$ErrorActionPreference = 'Continue' +$root = Split-Path -Parent $PSScriptRoot +Set-Location $root +$envFile = if ($env:ENV_FILE) { $env:ENV_FILE } else { '.env' } +function Wait-Healthy([string]$svc) { + foreach ($cid in (& docker compose --env-file $envFile ps -q $svc)) { + for ($i = 0; $i -lt 120; $i++) { + if ((& docker inspect -f '{{.State.Health.Status}}' $cid) -eq 'healthy') { break } + Start-Sleep -Milliseconds 500 + } + } +} +& docker compose --env-file $envFile restart nats 2>$null | Out-Null +Wait-Healthy 'nats' +& docker compose --env-file $envFile restart api 2>$null | Out-Null +Wait-Healthy 'api' +& docker compose --env-file $envFile ps -a nats api --format '{{.Name}} {{.State}} {{.Health}}' diff --git a/scripts/restart-api-broker.sh b/scripts/restart-api-broker.sh new file mode 100644 index 00000000..b77bdba0 --- /dev/null +++ b/scripts/restart-api-broker.sh @@ -0,0 +1,11 @@ +#!/bin/sh +# Сценарий защиты, шаг 3: перезапустить брокер (NATS, volume natsdata сохраняется) и все реплики API. +# Worker НЕ запускает (если остановлены — остаются остановленными). Volumes не удаляются. +set -eu +. "$(dirname "$0")/lib.sh" +{ echo "== $(now) before"; state; } | grep -E '^(==|nats|api) ' +dc restart nats >/dev/null 2>&1 +wait_healthy nats +dc restart api >/dev/null 2>&1 +wait_healthy api +{ echo "== $(now) after"; state; } | grep -E '^(==|nats|api) ' diff --git a/scripts/restart.cmd b/scripts/restart.cmd new file mode 100644 index 00000000..8226b992 --- /dev/null +++ b/scripts/restart.cmd @@ -0,0 +1,4 @@ +@echo off +rem Windows wrapper: tests\resilience.py starts the hook directly; .cmd runs without a shell. +powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0restart.ps1" +exit /b %ERRORLEVEL% diff --git a/scripts/restart.ps1 b/scripts/restart.ps1 new file mode 100644 index 00000000..ba3abd82 --- /dev/null +++ b/scripts/restart.ps1 @@ -0,0 +1,41 @@ +# Windows PowerShell version of scripts/restart.sh (persistence hook): restart LB, ALL API replicas, workers, +# PostgreSQL, Redis, S3, NATS JetStream and observability (Collector, Prometheus, Loki, Tempo, Grafana) keeping volumes. State before/after -> evidence\restart-hook.txt +$ErrorActionPreference = 'Continue' +$root = Split-Path -Parent $PSScriptRoot +Set-Location $root +$envFile = if ($env:ENV_FILE) { $env:ENV_FILE } else { '.env' } +$log = Join-Path $root 'evidence\restart-hook.txt' +function Dc { & docker compose --env-file $envFile @args 2>$null | Out-Null; if ($LASTEXITCODE -ne 0) { throw ('docker compose ' + ($args -join ' ') + ' failed') } } +function Get-State { + foreach ($cid in (& docker compose --env-file $envFile ps -a -q)) { + & docker inspect -f '{{index .Config.Labels "com.docker.compose.service"}} {{.Name}} status={{.State.Status}} started={{.State.StartedAt}} pid={{.State.Pid}}' $cid + } + & docker volume ls --filter label=com.docker.compose.project=mtusi-lab6 --format 'volume {{.Name}}' +} +try { + Add-Content -Path $log -Encoding UTF8 -Value ('== ' + (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ') + ' before restart') + Add-Content -Path $log -Encoding UTF8 -Value (Get-State) + $ttl = @(& docker compose --env-file $envFile ps -q api-ttl 2>$null).Count -gt 0 + $workers = @(& docker compose --env-file $envFile ps -q worker 2>$null).Count -gt 0 + Dc stop lb api worker + if ($ttl) { Dc stop api-ttl } + Dc restart postgres redis s3 nats otel-collector prometheus loki tempo grafana + # Wait for healthy storages (S3: gateway + master leader + writes; NATS: JetStream) before API/worker/LB. + foreach ($svc in 'postgres', 'redis', 's3', 'nats', 'prometheus') { + $cid = (& docker compose --env-file $envFile ps -q $svc | Select-Object -First 1) + for ($i = 0; $i -lt 120; $i++) { + if ((& docker inspect -f '{{.State.Health.Status}}' $cid) -eq 'healthy') { break } + Start-Sleep -Milliseconds 500 + } + } + Dc start api + if ($ttl) { Dc start api-ttl } + if ($workers) { Dc start worker } + Dc start lb + Add-Content -Path $log -Encoding UTF8 -Value ('== ' + (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ') + ' after restart') + Add-Content -Path $log -Encoding UTF8 -Value (Get-State) + exit 0 +} catch { + [Console]::Error.WriteLine($_.Exception.Message) + exit 1 +} diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100644 index 00000000..d85c25c2 --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,21 @@ +#!/bin/sh +# Persistence hook: перезапускает LB, ВСЕ API-реплики, worker и все хранилища (PostgreSQL, Redis, S3, +# NATS JetStream) и всю наблюдаемость (Collector, Prometheus, Loki, Tempo, Grafana), сохраняя volumes. Никаких down -v / FLUSH / повторного seed. Миграции повторно не нужны. +# Состояние контейнеров до/после (StartedAt, PID) — в evidence/restart-hook.txt. +set -eu +. "$(dirname "$0")/lib.sh" +LOG=${RESTART_EVIDENCE:-evidence/restart-hook.txt} +vols() { docker volume ls --filter label=com.docker.compose.project=mtusi-lab6 --format 'volume {{.Name}}'; } +{ echo "== $(now) before restart"; state; vols; } >> "$LOG" +running_ttl=$(dc ps -q api-ttl 2>/dev/null || true) +running_worker=$(dc ps -q worker 2>/dev/null || true) +dc stop lb api worker >/dev/null 2>&1 +[ -z "$running_ttl" ] || dc stop api-ttl >/dev/null 2>&1 +dc restart postgres redis s3 nats otel-collector prometheus loki tempo grafana >/dev/null 2>&1 +# Дождаться healthy хранилищ (S3: шлюз + лидер master + запись; NATS: JetStream), затем API/worker/LB. +for svc in postgres redis s3 nats prometheus; do wait_healthy "$svc"; done +dc start api >/dev/null 2>&1 +[ -z "$running_ttl" ] || dc start api-ttl >/dev/null 2>&1 +[ -z "$running_worker" ] || dc start worker >/dev/null 2>&1 +dc start lb >/dev/null 2>&1 +{ echo "== $(now) after restart"; state; vols; } >> "$LOG" diff --git a/scripts/rolling-update.sh b/scripts/rolling-update.sh new file mode 100644 index 00000000..62c228e6 --- /dev/null +++ b/scripts/rolling-update.sh @@ -0,0 +1,35 @@ +#!/bin/sh +# Rolling update API-реплик без остановки сервиса (Compose). +# 1. собрать новый образ (старые контейнеры продолжают работать на старом image id); +# 2. применить миграции ОДИН раз (one-shot migrate). Миграции обязаны быть expand-only +# (совместимы с работающей версией), см. REPORT.md; +# 3. для каждой старой реплики: поднять одну новую (--scale N+1 --no-recreate), дождаться +# healthy, затем остановить старую через SIGTERM (drain 3 с, LB выводит её) и удалить. +# Число готовых реплик во время замены не опускается ниже N. Журнал — evidence/rolling-update.txt. +set -eu +. "$(dirname "$0")/lib.sh" +LOG=${ROLLING_EVIDENCE:-evidence/rolling-update.txt} +VERSION=${APP_VERSION:-$(date -u +%Y%m%d%H%M%S)} +BUILD_CMD=${BUILD_CMD:-"docker compose --env-file $ENV_FILE build --build-arg APP_VERSION=$VERSION api"} +wait_healthy() { # $1 = container id + i=0 + while [ "$(docker inspect -f '{{.State.Health.Status}}' "$1")" != healthy ]; do + i=$((i + 1)); [ $i -le 120 ] || { echo "replica $1 not healthy" >&2; return 1; } + sleep 0.5 + done +} +old=$(dc ps -q api) +n=$(echo "$old" | wc -w) +{ echo "== $(now) rolling update start: $n replicas, new version $VERSION"; for c in $old; do docker inspect -f 'old {{.Name}} image={{.Image}}' "$c"; done; } >> "$LOG" +$BUILD_CMD >/dev/null +dc run --rm --no-deps migrate >> "$LOG" 2>&1 +for c in $old; do + before=$(dc ps -q api) + dc up -d --no-deps --no-recreate --scale api=$((n + 1)) api >/dev/null 2>&1 + new=$(for x in $(dc ps -q api); do echo "$before" | grep -q "$x" || echo "$x"; done) + wait_healthy "$new" + echo "$(now) new $(docker inspect -f '{{.Name}} image={{.Image}}' "$new") healthy; stopping old $(docker inspect -f '{{.Name}}' "$c")" >> "$LOG" + docker stop -t 15 "$c" >/dev/null + docker rm "$c" >/dev/null +done +{ echo "== $(now) rolling update done"; for c in $(dc ps -q api); do docker inspect -f 'now {{.Name}} image={{.Image}} health={{.State.Health.Status}}' "$c"; done; } >> "$LOG" diff --git a/scripts/start-replicas.ps1 b/scripts/start-replicas.ps1 new file mode 100644 index 00000000..bb6a5fa0 --- /dev/null +++ b/scripts/start-replicas.ps1 @@ -0,0 +1,14 @@ +# Windows PowerShell version of scripts/start-replicas.sh: start stopped API replicas, wait for healthy. +$ErrorActionPreference = 'Continue' +$root = Split-Path -Parent $PSScriptRoot +Set-Location $root +$envFile = if ($env:ENV_FILE) { $env:ENV_FILE } else { '.env' } +$ids = @(& docker compose --env-file $envFile ps -a -q api) +foreach ($cid in $ids) { & docker start $cid | Out-Null } +for ($i = 0; $i -lt 120; $i++) { + $bad = @($ids | Where-Object { (& docker inspect -f '{{.State.Health.Status}}' $_) -ne 'healthy' }).Count + if ($bad -eq 0) { break } + Start-Sleep -Milliseconds 500 +} +foreach ($cid in $ids) { & docker inspect -f '{{.Name}} {{.State.Status}} {{.State.Health.Status}}' $cid } +if ($bad -ne 0) { exit 1 } diff --git a/scripts/start-replicas.sh b/scripts/start-replicas.sh new file mode 100644 index 00000000..233eac12 --- /dev/null +++ b/scripts/start-replicas.sh @@ -0,0 +1,16 @@ +#!/bin/sh +# Восстанавливает остановленные API-реплики (после stop-one) и ждёт их healthcheck (≤60 с). +set -eu +. "$(dirname "$0")/lib.sh" +for cid in $(dc ps -a -q api); do docker start "$cid" >/dev/null; done +i=0 +while [ $i -lt 120 ]; do + bad=0 + for cid in $(dc ps -a -q api); do + [ "$(docker inspect -f '{{.State.Health.Status}}' "$cid")" = healthy ] || bad=1 + done + [ $bad -eq 0 ] && break + i=$((i + 1)); sleep 0.5 +done +state | grep '^api ' +[ $bad -eq 0 ] diff --git a/scripts/start-worker.ps1 b/scripts/start-worker.ps1 new file mode 100644 index 00000000..edb9f0f4 --- /dev/null +++ b/scripts/start-worker.ps1 @@ -0,0 +1,16 @@ +# Start stopped workers and wait until healthy. +$ErrorActionPreference = 'Continue' +$root = Split-Path -Parent $PSScriptRoot +Set-Location $root +$envFile = if ($env:ENV_FILE) { $env:ENV_FILE } else { '.env' } +function Wait-Healthy([string]$svc) { + foreach ($cid in (& docker compose --env-file $envFile ps -q $svc)) { + for ($i = 0; $i -lt 120; $i++) { + if ((& docker inspect -f '{{.State.Health.Status}}' $cid) -eq 'healthy') { break } + Start-Sleep -Milliseconds 500 + } + } +} +& docker compose --env-file $envFile start worker 2>$null | Out-Null +Wait-Healthy 'worker' +& docker compose --env-file $envFile ps -a worker --format '{{.Name}} {{.State}} {{.Health}}' diff --git a/scripts/start-worker.sh b/scripts/start-worker.sh new file mode 100644 index 00000000..c1ca58ef --- /dev/null +++ b/scripts/start-worker.sh @@ -0,0 +1,7 @@ +#!/bin/sh +# Запустить остановленные worker и дождаться healthy. +set -eu +. "$(dirname "$0")/lib.sh" +dc start worker >/dev/null 2>&1 +wait_healthy worker +echo "$(now) workers started:"; dc ps -a worker --format '{{.Name}} {{.State}} {{.Health}}' diff --git a/scripts/stop-one.cmd b/scripts/stop-one.cmd new file mode 100644 index 00000000..141ec220 --- /dev/null +++ b/scripts/stop-one.cmd @@ -0,0 +1,4 @@ +@echo off +rem Windows wrapper: tests\resilience.py starts the hook directly; .cmd runs without a shell. +powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0stop-one.ps1" +exit /b %ERRORLEVEL% diff --git a/scripts/stop-one.ps1 b/scripts/stop-one.ps1 new file mode 100644 index 00000000..850cad2c --- /dev/null +++ b/scripts/stop-one.ps1 @@ -0,0 +1,30 @@ +# Windows PowerShell version of scripts/stop-one.sh (failover hook). Stops EXACTLY ONE API replica whose +# X-Instance-Id is in $env:TARGET_INSTANCE_ID and leaves it stopped. DB/Redis/LB/volumes untouched. +# Restore afterwards: scripts\start-replicas.ps1 +$ErrorActionPreference = 'Continue' +$root = Split-Path -Parent $PSScriptRoot +Set-Location $root +$envFile = if ($env:ENV_FILE) { $env:ENV_FILE } else { '.env' } +$log = Join-Path $root 'evidence\failover-hook.txt' +if (-not $env:TARGET_INSTANCE_ID) { [Console]::Error.WriteLine('TARGET_INSTANCE_ID is required'); exit 2 } +function Get-State { + foreach ($cid in (& docker compose --env-file $envFile ps -a -q)) { + & docker inspect -f '{{index .Config.Labels "com.docker.compose.service"}} {{.Name}} status={{.State.Status}} started={{.State.StartedAt}} pid={{.State.Pid}}' $cid + } +} +$target = $null +foreach ($cid in (& docker compose --env-file $envFile ps -q api)) { + $id = (& docker exec $cid cat /tmp/instance-id 2>$null) + if ($id -and $id.Trim() -eq $env:TARGET_INSTANCE_ID) { $target = $cid } +} +if (-not $target) { [Console]::Error.WriteLine('no running api replica with this id'); exit 1 } +$name = (& docker inspect -f '{{.Name}}' $target).TrimStart('/') +$stamp = (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ') +Add-Content -Path $log -Encoding UTF8 -Value ("== $stamp stop-one target=" + $env:TARGET_INSTANCE_ID + " container=$name") +Add-Content -Path $log -Encoding UTF8 -Value (Get-State) +& docker stop -t 15 $target | Out-Null +if ($LASTEXITCODE -ne 0) { exit 1 } +$stamp = (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ') +Add-Content -Path $log -Encoding UTF8 -Value ("== $stamp after stop") +Add-Content -Path $log -Encoding UTF8 -Value (Get-State) +exit 0 diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh new file mode 100644 index 00000000..486b6408 --- /dev/null +++ b/scripts/stop-one.sh @@ -0,0 +1,14 @@ +#!/bin/sh +# Failover hook: останавливает РОВНО ОДНУ API-реплику — ту, чей X-Instance-Id передан тестом в +# TARGET_INSTANCE_ID, — и оставляет её остановленной. БД, Redis, LB и volumes не трогает. +# docker stop → SIGTERM → реплика 3 с отвечает 503 на /health/ready (LB выводит её), затем закрывает +# listener и дожидается запросов в полёте. Возврат ≈ 4 с (< 10 с). Восстановление: scripts/start-replicas.sh +set -eu +: "${TARGET_INSTANCE_ID:?test provides target API instance alias}" +. "$(dirname "$0")/lib.sh" +LOG=${FAILOVER_EVIDENCE:-evidence/failover-hook.txt} +cid=$(container_of "$TARGET_INSTANCE_ID") || { echo "no running api replica with id $TARGET_INSTANCE_ID" >&2; exit 1; } +name=$(docker inspect -f '{{.Name}}' "$cid" | tr -d /) +{ echo "== $(now) stop-one target=$TARGET_INSTANCE_ID container=$name"; state; } >> "$LOG" +docker stop -t 15 "$cid" >/dev/null +{ echo "== $(now) after stop"; state; } >> "$LOG" diff --git a/scripts/stop-worker.ps1 b/scripts/stop-worker.ps1 new file mode 100644 index 00000000..b2446f75 --- /dev/null +++ b/scripts/stop-worker.ps1 @@ -0,0 +1,15 @@ +# Defense scenario: stop ALL workers and leave them stopped (API, broker, storages untouched). +$ErrorActionPreference = 'Continue' +$root = Split-Path -Parent $PSScriptRoot +Set-Location $root +$envFile = if ($env:ENV_FILE) { $env:ENV_FILE } else { '.env' } +function Wait-Healthy([string]$svc) { + foreach ($cid in (& docker compose --env-file $envFile ps -q $svc)) { + for ($i = 0; $i -lt 120; $i++) { + if ((& docker inspect -f '{{.State.Health.Status}}' $cid) -eq 'healthy') { break } + Start-Sleep -Milliseconds 500 + } + } +} +& docker compose --env-file $envFile stop worker 2>$null | Out-Null +& docker compose --env-file $envFile ps -a worker --format '{{.Name}} {{.State}}' diff --git a/scripts/stop-worker.sh b/scripts/stop-worker.sh new file mode 100644 index 00000000..7f3a325a --- /dev/null +++ b/scripts/stop-worker.sh @@ -0,0 +1,7 @@ +#!/bin/sh +# Сценарий защиты: остановить ВСЕ worker (SIGTERM → дорабатывают текущее ≤ 20 с, остальное вернёт брокер) +# и оставить их остановленными. API, брокер, хранилища и volumes не трогает. +set -eu +. "$(dirname "$0")/lib.sh" +dc stop worker >/dev/null 2>&1 +echo "$(now) workers stopped:"; dc ps -a worker --format '{{.Name}} {{.State}}' diff --git a/src/messenger/__init__.py b/src/messenger/__init__.py new file mode 100644 index 00000000..0c25b608 --- /dev/null +++ b/src/messenger/__init__.py @@ -0,0 +1,2 @@ +"""MTUSI messenger API + worker, lab5.""" +__version__ = "5.0.0" diff --git a/src/messenger/__main__.py b/src/messenger/__main__.py new file mode 100644 index 00000000..b67d2903 --- /dev/null +++ b/src/messenger/__main__.py @@ -0,0 +1,398 @@ +"""Точка входа: python -m messenger [serve|worker|migrate|healthcheck|worker-healthcheck|stats| +s3-bootstrap|s3-check|broker-bootstrap|jobs …].""" +from __future__ import annotations + +import asyncio +import json +import logging +import os +import sys +import time +import urllib.request + +class JsonFormatter(logging.Formatter): + """Структурированный лог в stdout (тот же, что уходит по OTLP в Loki): ts, level, service, event, + trace_id/span_id активного span и поля extra. Токены, пароли, Authorization, тела запросов и + сообщений не логируются (поля с такими именами отбрасываются — telemetry.SCRUB).""" + + def format(self, record: logging.LogRecord) -> str: + from .telemetry import event_name, log_fields + data = {"ts": time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(record.created)) + ".%03dZ" % record.msecs, + "level": record.levelname.lower(), "service": getattr(record, "service", None), + "logger": record.name, "event": event_name(record), "msg": record.getMessage()} + if getattr(record, "trace_id", None): + data["trace_id"], data["span_id"] = record.trace_id, record.span_id + data.update(log_fields(record)) + if record.exc_info: + data["exc"] = self.formatException(record.exc_info).splitlines()[-1] + return json.dumps(data, ensure_ascii=False, default=str) + + +def setup_logging() -> None: + from .telemetry import TraceContextFilter + handler = logging.StreamHandler(sys.stdout) + handler.setFormatter(JsonFormatter()) + handler.addFilter(TraceContextFilter()) + logging.basicConfig(level=os.environ.get("LOG_LEVEL", "INFO").upper(), handlers=[handler], force=True) + # httpx пишет INFO на каждый запрос к S3 (URL с ключами объектов) — шум; оставляем предупреждения. + logging.getLogger("httpx").setLevel(logging.WARNING) + logging.getLogger("httpcore").setLevel(logging.WARNING) + logging.getLogger("uvicorn.access").disabled = True # свой access-log без query-строк + # Ошибки экспорта OTLP (Collector недоступен) — не чаще одного предупреждения на попытку экспортёра. + logging.getLogger("opentelemetry").setLevel(logging.ERROR) + + +def serve() -> int: + import uvicorn + + from .app import build_app + from .config import load + + from . import telemetry + settings = load() + telemetry.setup("api", settings.instance_id) + app = build_app(settings) + state = app.state.messenger + log = logging.getLogger("messenger.shutdown") + + class DrainingServer(uvicorn.Server): + """Graceful shutdown для работы за LB. + 1-й SIGTERM/SIGINT: readiness → 503 и `Connection: close`, запросы ещё обслуживаются; + через SHUTDOWN_DRAIN_SECONDS (≥ времени обнаружения LB) uvicorn перестаёт принимать + соединения и дожидается запросов в полёте. Повторный сигнал — немедленный выход.""" + + drain_started = None + + def handle_exit(self, sig, frame): + if self.drain_started is None and settings.shutdown_drain_seconds > 0 and not self.should_exit: + self.drain_started = time.monotonic() + state.draining = True + log.info("drain started", extra={"signal": sig, "instance_id": settings.instance_id, + "drain_seconds": settings.shutdown_drain_seconds}) + return + super().handle_exit(sig, frame) + + async def on_tick(self, counter): + if (self.drain_started is not None and not self.should_exit + and time.monotonic() - self.drain_started >= settings.shutdown_drain_seconds): + log.info("drain finished; closing listener", extra={"instance_id": settings.instance_id}) + self.should_exit = True + return await super().on_tick(counter) + + config = uvicorn.Config(app, host=settings.host, port=settings.port, log_config=None, + access_log=False, server_header=False, proxy_headers=False, + # keep-alive дольше, чем idle-пул HAProxy: соединение первым закрывает LB, + # а не реплика (иначе гонка «LB шлёт запрос в закрываемое соединение»). + timeout_keep_alive=int(os.environ.get("KEEPALIVE_SECONDS", "30")), + timeout_graceful_shutdown=10, lifespan="on", + backlog=int(os.environ.get("BACKLOG", "2048"))) + server = DrainingServer(config) + try: + server.run() + finally: + telemetry.shutdown() + return 0 if server.started else 1 + + +def migrate() -> int: + from .config import load + from .db import migrate_with_wait + + applied = asyncio.run(migrate_with_wait(load())) + print(json.dumps({"applied": applied})) + return 0 + + +def healthcheck() -> int: + port = os.environ.get("APP_PORT", "8080") + path = sys.argv[2] if len(sys.argv) > 2 else "/health/ready" + try: + with urllib.request.urlopen(f"http://127.0.0.1:{port}{path}", timeout=2) as resp: + return 0 if resp.status == 200 else 1 + except Exception: # noqa: BLE001 + return 1 + + +def worker() -> int: + from .worker import main as worker_main + return worker_main() + + +def worker_healthcheck() -> int: + """Жив ли цикл worker: файл-маркер обновляется каждую итерацию (fetch ждёт не дольше 2 с).""" + from .worker import ALIVE_FILE + try: + return 0 if time.time() - os.stat(ALIVE_FILE).st_mtime < 30 else 1 + except OSError: + return 1 + + +def broker_bootstrap() -> int: + """Идемпотентно создать stream и durable consumer (one-shot сервис broker-init). Повтор — no-op.""" + from .broker import Broker, BrokerUnavailable + from .config import load + settings = load() + + async def run(): + b = Broker(settings, "broker-init") + deadline = time.monotonic() + 60 + while True: + try: + created = await b.ensure_topology() + break + except BrokerUnavailable: + if time.monotonic() > deadline: + raise + await asyncio.sleep(1) + si = await b.js.stream_info(settings.broker_stream) + ci = await b.js.consumer_info(settings.broker_stream, settings.broker_consumer) + await b.close() + return {"created": created, "stream": {"name": si.config.name, "subjects": si.config.subjects, + "storage": str(si.config.storage), "retention": str(si.config.retention), + "duplicate_window_s": si.config.duplicate_window, + "max_msgs": si.config.max_msgs, "messages": si.state.messages}, + "consumer": {"durable": ci.config.durable_name, "ack_policy": str(ci.config.ack_policy), + "ack_wait_s": ci.config.ack_wait, "max_ack_pending": ci.config.max_ack_pending, + "max_deliver": ci.config.max_deliver}} + print(json.dumps(asyncio.run(run()), ensure_ascii=False)) + return 0 + + +def jobs_cmd() -> int: + """Операторские команды (stdout — JSON): status | failed | replay | reprocess | invariants | publish-raw.""" + import argparse + import uuid as _uuid + + logging.getLogger().handlers[0].setStream(sys.stderr) + from . import db + from .config import load + ap = argparse.ArgumentParser(prog="python -m messenger jobs") + sub = ap.add_subparsers(dest="cmd", required=True) + p = sub.add_parser("status", help="работы и журнал событий вложения") + p.add_argument("attachment_id") + p = sub.add_parser("failed", help="реестр failed (DLQ): финально неуспешные работы") + p.add_argument("--limit", type=int, default=50) + p = sub.add_parser("replay", help="явный повтор failed (ready/queued/processing — no-op)") + g = p.add_mutually_exclusive_group(required=True) + g.add_argument("--attachment") + g.add_argument("--job") + g.add_argument("--all-failed", action="store_true") + p.add_argument("--error-code", help="с --all-failed: только с этим кодом") + p.add_argument("--reason", required=True) + p.add_argument("--operator", default=os.environ.get("USER", "operator")) + p = sub.add_parser("reprocess", help="поставить новую версию pipeline (трек 2)") + p.add_argument("--attachment", required=True) + p.add_argument("--pipeline-version", type=int, required=True) + p = sub.add_parser("invariants", help="проверка инвариантов pipeline (трек 2)") + p.add_argument("--settled", action="store_true", help="все работы должны быть завершены") + p.add_argument("--verify-bytes", action="store_true", help="сверить SHA-256 объектов вариантов") + p.add_argument("--since", help="только вложения, созданные начиная с (ISO время)") + p = sub.add_parser("publish-raw", help="ТЕСТ: опубликовать сообщение работы в обход outbox (дубли, reorder)") + p.add_argument("--job", required=True) + p.add_argument("--attempt", type=int) + p.add_argument("--count", type=int, default=1) + sub.add_parser("purge-stream", help="ТЕСТ: удалить все сообщения stream (имитация потери сообщений брокером)") + a = ap.parse_args(sys.argv[2:]) + settings = load() + + async def run(): + pool = db.make_pool(settings) + await pool.open(wait=True, timeout=10) + try: + return await _jobs(a, settings, pool, _uuid) + finally: + await pool.close() + result = asyncio.run(run()) + print(json.dumps(result, ensure_ascii=False, default=str, indent=1)) + return 0 if result.get("ok", True) else 1 + + +async def _jobs(a, settings, pool, _uuid): + from . import jobs + if a.cmd == "status": + async with pool.connection() as conn: + att = await (await conn.execute( + "SELECT id, status, error_code, published_version, staging_key IS NOT NULL AS has_staging" + " FROM attachments WHERE id = %s", (_uuid.UUID(a.attachment_id),))).fetchone() + js = await (await conn.execute( + "SELECT job_id, pipeline_version, status, attempt, claims, max_attempts, lease_token, lease_owner," + " error_code, replays, next_attempt_at, finished_at FROM attachment_jobs WHERE attachment_id = %s" + " ORDER BY pipeline_version", (_uuid.UUID(a.attachment_id),))).fetchall() + ev = await (await conn.execute( + "SELECT created_at, job_id, pipeline_version, event, attempt, lease_token, worker, detail FROM job_events" + " WHERE attachment_id = %s ORDER BY id", (_uuid.UUID(a.attachment_id),))).fetchall() + return {"attachment": att, "jobs": js, "events": ev} + if a.cmd == "failed": + async with pool.connection() as conn: + rows = await (await conn.execute( + "SELECT j.job_id, j.attachment_id, j.pipeline_version, j.error_code, j.error_detail, j.attempt, j.claims," + " j.replays, j.updated_at AS failed_at, a.staging_key IS NOT NULL AS replayable" + " FROM attachment_jobs j JOIN attachments a ON a.id = j.attachment_id WHERE j.status = 'failed'" + " ORDER BY j.updated_at DESC LIMIT %s", (a.limit,))).fetchall() + return {"failed": rows, "count": len(rows)} + if a.cmd == "replay": + if a.all_failed: + async with pool.connection() as conn: + ids = [r["job_id"] for r in await (await conn.execute( + "SELECT job_id FROM attachment_jobs WHERE status = 'failed' AND (%s::text IS NULL OR error_code = %s)", + (a.error_code, a.error_code))).fetchall()] + results = [await jobs.replay_failed(pool, settings, job_id=j, operator=a.operator, reason=a.reason) for j in ids] + return {"replayed": sum(r["result"] == "replayed" for r in results), "results": results} + return await jobs.replay_failed(pool, settings, attachment_id=_uuid.UUID(a.attachment) if a.attachment else None, + job_id=_uuid.UUID(a.job) if a.job else None, operator=a.operator, reason=a.reason) + if a.cmd == "reprocess": + return await jobs.reprocess(pool, settings, _uuid.UUID(a.attachment), a.pipeline_version, + os.environ.get("USER", "operator")) + if a.cmd == "invariants": + from .invariants import check + from .s3 import S3Client + s3 = S3Client(settings.s3_endpoint, settings.s3_region, settings.s3_access_key, settings.s3_secret_key) + try: + import datetime as _dt + since = _dt.datetime.fromisoformat(a.since.replace("Z", "+00:00")) if a.since else None + return await check(pool, s3, settings, settled=a.settled, verify_bytes=a.verify_bytes, since=since) + finally: + await s3.aclose() + if a.cmd == "publish-raw": + from .broker import Broker + async with pool.connection() as conn: + job = await (await conn.execute("SELECT * FROM attachment_jobs WHERE job_id = %s", + (_uuid.UUID(a.job),))).fetchone() + if job is None: + return {"ok": False, "error": "job not found"} + b = Broker(settings, "publish-raw") + seqs = [] + for _ in range(a.count): + # trace_context задания: дубли видны в trace исходной загрузки (outcome=duplicate/stale) + payload = jobs.job_message(job["job_id"], job["attachment_id"], job["pipeline_version"], + a.attempt or job["attempt"], job.get("trace_context")) + # Уникальный Nats-Msg-Id: дубль должен ДОЙТИ до worker (проверяется идемпотентность обработки). + seqs.append((await b.publish(json.dumps(payload).encode(), "raw-" + _uuid.uuid4().hex))[0]) + await b.close() + return {"published": len(seqs), "stream_seq": seqs, "attempt": a.attempt or job["attempt"]} + if a.cmd == "purge-stream": + from .broker import Broker + b = Broker(settings, "purge-stream") + await b.connect() + before = (await b.js.stream_info(settings.broker_stream)).state.messages + await b.js.purge_stream(settings.broker_stream) + await b.close() + return {"purged": before} + return {"ok": False} + + +def stats() -> int: + port = os.environ.get("APP_PORT", "8080") + query = "?reset_peak=1" if "--reset-peak" in sys.argv[2:] else "" + with urllib.request.urlopen(f"http://127.0.0.1:{port}/internal/stats{query}", timeout=2) as resp: + print(resp.read().decode()) + return 0 + + +def _s3(prefix: str): + from .config import _secret + from .s3 import S3Client + endpoint = os.environ.get("S3_ENDPOINT", "http://s3:9000") + access = _secret(prefix + "ACCESS_KEY_ID", required=False) + secret = _secret(prefix + "SECRET_ACCESS_KEY", required=False) + if not access or not secret: + return None + return S3Client(endpoint, os.environ.get("S3_REGION", "us-east-1"), access, secret, timeout=10) + + +async def _s3_checks(bucket: str) -> dict: + """Проверки «вне API»: bucket не отдаёт объекты/листинг анонимно, ключи API не могут создавать + бакеты и читать чужие бакеты. Возвращает словарь проверка → (ожидание, факт, ok).""" + import httpx + + from .s3 import S3Error + endpoint = os.environ.get("S3_ENDPOINT", "http://s3:9000").rstrip("/") + res = {} + async with httpx.AsyncClient(timeout=5) as anon: + r = await anon.get(f"{endpoint}/{bucket}?list-type=2") + res["anonymous ListObjects"] = ("403", r.status_code, r.status_code == 403) + r = await anon.get(f"{endpoint}/{bucket}/originals/any-object") + res["anonymous GetObject"] = ("403", r.status_code, r.status_code == 403) + r = await anon.put(f"{endpoint}/{bucket}/staging/anon-write", content=b"x") + res["anonymous PutObject"] = ("403", r.status_code, r.status_code == 403) + r = await anon.get(f"{endpoint}/") + res["anonymous ListBuckets"] = ("403", r.status_code, r.status_code == 403) + api = _s3("S3_") + if api is not None: + try: + keys = [o async for o in api.list_objects(bucket, "originals/", page_size=1)] + res["api ListObjects own bucket"] = ("allowed", "allowed", True) + except S3Error as exc: + res["api ListObjects own bucket"] = ("allowed", exc.code, False) + for name, coro in (("api CreateBucket", api.create_bucket("forbidden-" + bucket)),): + try: + await coro + res[name] = ("AccessDenied", "allowed", False) + except S3Error as exc: + res[name] = ("AccessDenied", exc.code, exc.status == 403) + await api.aclose() + return res + + +def s3_bootstrap() -> int: + """Идемпотентный bootstrap: создать приватный bucket admin-ключом (повтор — no-op) и проверить + права. Запускается one-shot сервисом s3-init до старта реплик API.""" + import time as _t + + from .s3 import S3Unavailable + bucket = os.environ.get("S3_BUCKET", "messenger-attachments") + admin = _s3("S3_ADMIN_") + if admin is None: + print("S3_ADMIN_ACCESS_KEY_ID[_FILE]/S3_ADMIN_SECRET_ACCESS_KEY[_FILE] required", file=sys.stderr) + return 2 + + async def run(): + deadline = _t.monotonic() + 60 + while True: + try: + created = await admin.create_bucket(bucket) + break + except S3Unavailable: + if _t.monotonic() > deadline: + raise + await asyncio.sleep(1) + checks = await _s3_checks(bucket) + await admin.aclose() + return created, checks + + created, checks = asyncio.run(run()) + print(json.dumps({"bucket": bucket, "created": created, "checks": {k: list(v) for k, v in checks.items()}}, + ensure_ascii=False)) + return 0 if all(v[2] for v in checks.values()) else 1 + + +def s3_check() -> int: + bucket = os.environ.get("S3_BUCKET", "messenger-attachments") + checks = asyncio.run(_s3_checks(bucket)) + for k, (want, got, ok) in checks.items(): + print("%-4s %-28s expected=%-12s got=%s" % ("PASS" if ok else "FAIL", k, want, got)) + return 0 if all(v[2] for v in checks.values()) else 1 + + +def main() -> int: + setup_logging() + command = sys.argv[1] if len(sys.argv) > 1 else "serve" + commands = {"serve": serve, "worker": worker, "migrate": migrate, "healthcheck": healthcheck, + "worker-healthcheck": worker_healthcheck, "stats": stats, "s3-bootstrap": s3_bootstrap, + "s3-check": s3_check, "broker-bootstrap": broker_bootstrap, "jobs": jobs_cmd} + if command not in commands: + print("usage: python -m messenger [serve|worker|migrate|healthcheck|worker-healthcheck|stats|" + "s3-bootstrap|s3-check|broker-bootstrap|jobs]", file=sys.stderr) + return 2 + try: + return commands[command]() + except Exception as exc: # noqa: BLE001 + from .config import ConfigError + if isinstance(exc, ConfigError): + logging.getLogger("messenger").error("configuration error: %s", exc) + return 2 + raise + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/messenger/app.py b/src/messenger/app.py new file mode 100644 index 00000000..628795b7 --- /dev/null +++ b/src/messenger/app.py @@ -0,0 +1,1176 @@ +"""HTTP API мессенджера (lab6): Starlette + psycopg 3 (async pool) + Redis/Valkey-кэш сессий, +S3 (SeaweedFS) для файлов и NATS JetStream для заданий обработки (через transactional outbox); +lab6 — OpenTelemetry: server spans, RED-метрики, метрики очереди/пулов, структурные логи с trace_id. + +Реплика stateless: всё, от чего зависит корректность (сессии, идемпотентность, данные), лежит +в PostgreSQL; Redis — только кэш. Любую реплику можно остановить или заменить.""" +from __future__ import annotations + +import asyncio +import base64 +import binascii +import contextlib +import hashlib +import json +import os +import re +import logging +import time +import uuid +from urllib.parse import quote +from pathlib import Path + +from opentelemetry import context as otel_context +from opentelemetry import trace +from opentelemetry.context import Context +from opentelemetry.trace import SpanKind +from psycopg import errors as pg_errors +from starlette.applications import Starlette +from starlette.exceptions import HTTPException +from starlette.requests import ClientDisconnect, Request +from starlette.responses import JSONResponse, Response, StreamingResponse +from starlette.routing import Route + +from . import db, telemetry +from .broker import Broker +from .config import Settings +from .errors import ApiError, invalid, not_found, unauthorized_basic, unauthorized_bearer, unavailable +from .imagecheck import ImageRejected, sniff, validator_for +from .jobs import create_job, relay_pass +from .s3 import S3Client, S3Error, S3Unavailable +from .security import PasswordHasher, looks_like_token, new_token, token_hash +from .sessions import Principal, SessionCache +from .validation import (USERNAME_RE, decode_cursor, encode_cursor, parse_json_object, parse_limit, + parse_uuid, single_param, text_field) + +log = logging.getLogger("messenger.http") + + +# -------------------------------------------------------------------------------------------- +# Ответы и обвязка +# -------------------------------------------------------------------------------------------- + +def request_id(request: Request) -> str: + rid = getattr(request.state, "request_id", None) + if not rid: + rid = uuid.uuid4().hex + request.state.request_id = rid + return rid + + +def json_response(request: Request, payload, status: int = 200, headers: dict | None = None) -> JSONResponse: + h = {"X-Request-Id": request_id(request), "Cache-Control": "no-store"} + h.update(headers or {}) + return JSONResponse(payload, status_code=status, headers=h) + + +def error_response(request: Request, err: ApiError) -> JSONResponse: + rid = request_id(request) + body = {"error": {"code": err.public_code, "message": err.message, "request_id": rid}} + return json_response(request, body, err.status, err.headers) + + +_UNTRACED = ("/health/", "/internal/") # проверки LB/Docker каждые 1–5 с: метрики есть, spans/логи успеха — нет + + +class RequestContextMiddleware: + """Чистый ASGI middleware: X-Request-Id в каждом ответе (включая 404/405 роутера), server span + (новый trace: заголовок traceparent внешнего клиента не принимается — публичный вход не даёт + навязывать нам trace/sampling), RED-метрики по шаблону маршрута и access-log без URL/тела.""" + + def __init__(self, app, instance_id: str = "api", state=None): + self.app = app + self.instance_id = instance_id.encode() + self.state = state + + async def __call__(self, scope, receive, send): + if scope["type"] != "http": + return await self.app(scope, receive, send) + rid = uuid.uuid4().hex + scope.setdefault("state", {})["request_id"] = rid + started = time.monotonic() + status_holder = {} + method = scope.get("method", "") + untraced = scope.get("path", "").startswith(_UNTRACED) + + async def send_wrapper(message): + if message["type"] == "http.response.start": + status_holder["status"] = message["status"] + headers = list(message.get("headers", [])) + if not any(k.lower() == b"x-request-id" for k, _ in headers): + headers.append((b"x-request-id", rid.encode())) + headers.append((b"x-instance-id", self.instance_id)) + if self.state is not None and self.state.draining: + # Во время drain просим клиента/LB не переиспользовать соединение с этой репликой. + headers.append((b"connection", b"close")) + message["headers"] = headers + await send(message) + + span = token = None + if telemetry.ENABLED and not untraced: + span = telemetry.TRACER.start_span(method, context=Context(), kind=SpanKind.SERVER, attributes={ + "http.request.method": method, "url.scheme": scope.get("scheme", "http"), + "network.protocol.version": scope.get("http_version", "1.1"), "messenger.request_id": rid}) + token = otel_context.attach(trace.set_span_in_context(span)) + active = {"http.request.method": method} + telemetry.http_active.add(1, active) + try: + await self.app(scope, receive, send_wrapper) + except BaseException as exc: + status_holder.setdefault("status", 500) + telemetry.mark_error(span, exc) + raise + finally: + duration = time.monotonic() - started + route = getattr(scope.get("route"), "path", None) or "unmatched" + status = status_holder.get("status", 499) # 499: клиент ушёл до начала ответа + telemetry.http_active.add(-1, active) + telemetry.http_duration.record(duration, { + "http.request.method": method, "http.route": route, "http.response.status_code": status, + "http.response.status_class": telemetry.status_class(status)}) + if self.state is not None: + self.state.stats["requests"] += 1 + if span is not None: + span.update_name("%s %s" % (method, route)) + span.set_attribute("http.route", route) + span.set_attribute("http.response.status_code", status) + if status >= 500 and span.is_recording(): + span.set_status(trace.Status(trace.StatusCode.ERROR)) + if "error.type" not in (getattr(span, "attributes", None) or {}): + span.set_attribute("error.type", str(status)) + if not untraced or status >= 500: + log.info("request", extra={"event": "http.request", "request_id": rid, "method": method, + "route": route, "status": status, + "duration_ms": round(duration * 1000, 2)}) + if span is not None: + span.end() + otel_context.detach(token) + + +def endpoint(handler, timeout_setting: str = "request_timeout_seconds"): + """Единая обработка ошибок и общий таймаут запроса (для upload — UPLOAD_TIMEOUT_SECONDS).""" + async def wrapper(request: Request): + state: AppState = request.app.state.messenger + try: + async with asyncio.timeout(getattr(state.settings, timeout_setting)): + return await handler(request, state) + except ApiError as err: + if err.status >= 500: + telemetry.mark_error(trace.get_current_span(), error_type=err.public_code) + return error_response(request, err) + except Exception as exc: # noqa: BLE001 + # error.type = класс исключения (PoolTimeout, QueryCanceled, S3Unavailable…): по нему в trace + # видно, ЧТО именно отказало, хотя клиент получает только безопасный код ошибки. + telemetry.mark_error(trace.get_current_span(), exc) + if db.is_unavailable(exc) or isinstance(exc, (TimeoutError, S3Unavailable)): + log.warning("dependency unavailable", extra={"event": "dependency.unavailable", + "request_id": request_id(request), + "error": type(exc).__name__}) + return error_response(request, unavailable()) + log.exception("unhandled error", extra={"event": "http.unhandled_error", "request_id": request_id(request)}) + return error_response(request, ApiError("internal_error")) + wrapper.__name__ = handler.__name__ + return wrapper + + +async def read_body(request: Request, limit: int) -> bytes: + declared = request.headers.get("content-length") + if declared is not None: + if not declared.isdigit(): + raise invalid("Некорректный Content-Length") + if int(declared) > limit: + raise ApiError("payload_too_large") + chunks, size = [], 0 + async for chunk in request.stream(): + size += len(chunk) + if size > limit: + raise ApiError("payload_too_large") + chunks.append(chunk) + return b"".join(chunks) + + +async def read_json(request: Request, state: "AppState", allowed: set[str], required: set[str]) -> dict: + ctype = request.headers.get("content-type", "").split(";")[0].strip().lower() + body = await read_body(request, state.settings.max_body_bytes) + if ctype != "application/json": + raise invalid("Ожидается Content-Type: application/json") + return parse_json_object(body, allowed, required) + + +def user_json(row) -> dict: + return {"id": str(row["id"]), "username": row["username"], "display_name": row["display_name"], + "created_at": db.iso(row["created_at"])} + + +def chat_json(row) -> dict: + return {"id": str(row["id"]), "title": row["title"], + "member_ids": [str(m) for m in row["member_ids"]], "created_at": db.iso(row["created_at"])} + + +def message_json(row) -> dict: + return {"id": str(row["id"]), "chat_id": str(row["chat_id"]), "sender_id": str(row["sender_id"]), + "text": row["text"], "created_at": db.iso(row["created_at"]), + "attachment_ids": [str(a) for a in (row.get("attachment_ids") or [])]} + + +def attachment_json(row, variants=()) -> dict: + """size_bytes/sha256/content_type всегда описывают оригинал; варианты — опубликованной версии.""" + return {"id": str(row["id"]), "chat_id": str(row["chat_id"]), "owner_id": str(row["owner_id"]), + "filename": row["filename"], "content_type": row["content_type"], "size_bytes": row["size_bytes"], + "sha256": row["sha256"], "status": row["status"], + "variants": [{"name": v["name"], "content_type": v["content_type"], "size_bytes": v["size_bytes"], + "width": v["width"], "height": v["height"], "sha256": v["sha256"]} for v in variants], + "error_code": row.get("error_code") if row["status"] == "failed" else None, + "created_at": db.iso(row["created_at"]), "updated_at": db.iso(row["updated_at"])} + + +_VARIANTS_SQL = ("SELECT name, content_type, size_bytes, width, height, sha256, object_key FROM attachment_variants" + " WHERE attachment_id = %s AND pipeline_version = %s ORDER BY name") + + +async def load_variants(conn, row) -> list: + if row["status"] != "ready" or row.get("published_version") is None: + return [] + return await (await conn.execute(_VARIANTS_SQL, (row["id"], row["published_version"]))).fetchall() + + +# -------------------------------------------------------------------------------------------- +# Состояние приложения и аутентификация +# -------------------------------------------------------------------------------------------- + +class AppState: + def __init__(self, settings: Settings): + self.settings = settings + self.pool = db.make_pool(settings) + self.cache = SessionCache(settings) + self.hasher = PasswordHasher(settings.scrypt_log2_n, settings.scrypt_r, settings.scrypt_p, + settings.kdf_concurrency) + self.ready = False # схема проверена, пул открыт + self.draining = False # получен SIGTERM: readiness = 503, LB выводит реплику + self.stop = asyncio.Event() + self.tasks: list[asyncio.Task] = [] + self.stats = {"requests": 0, "inflight": 0, "idempotent_replays": 0, "idempotency_conflicts": 0, + "uploads_ok": 0, "uploads_rejected": 0, "uploads_failed": 0, "compensations": 0, + "janitor_removed": 0} + self.s3 = None + if settings.s3_endpoint and settings.s3_access_key and settings.s3_secret_key: + self.s3 = S3Client(settings.s3_endpoint, settings.s3_region, settings.s3_access_key, + settings.s3_secret_key, timeout=settings.s3_timeout_seconds) + # Одновременных загрузок на реплику не больше UPLOAD_CONCURRENCY (RAM и соединения к S3 ограничены). + self.upload_slots = asyncio.Semaphore(settings.upload_concurrency) + # lab5: публикация заданий из outbox (relay). Брокер не нужен для 202: задание уже в PostgreSQL. + self.broker = Broker(settings, "api-" + settings.instance_id) if settings.broker_url else None + self.relay_kick = asyncio.Event() + self.stats.update({"outbox_published": 0}) + + +async def authenticate(request: Request, state: AppState) -> Principal: + """Только Authorization: Bearer . X-User-Id и Basic игнорируются/отклоняются.""" + header = request.headers.get("authorization", "") + scheme, _, token = header.partition(" ") + token = token.strip() + if scheme.lower() != "bearer" or not looks_like_token(token): + raise unauthorized_bearer() + th = token_hash(token) + principal = await state.cache.get(th) + if principal is not None: + return principal + async with state.pool.connection() as conn: + row = await (await conn.execute( + "SELECT u.id, u.username, u.display_name, u.created_at, s.expires_at" + " FROM sessions s JOIN users u ON u.id = s.user_id" + " WHERE s.token_hash = %s AND s.revoked_at IS NULL AND s.expires_at > clock_timestamp()", + (th,))).fetchone() + if row is None: + raise unauthorized_bearer() + principal = Principal(user=user_json(row), expires_at=row["expires_at"].timestamp(), token_hash=th) + await state.cache.put(principal) + return principal + + +def parse_basic(header: str) -> tuple[str, str]: + scheme, _, value = header.partition(" ") + if scheme.lower() != "basic" or not value.strip(): + raise unauthorized_basic() + try: + decoded = base64.b64decode(value.strip(), validate=True).decode("utf-8") + except (binascii.Error, ValueError, UnicodeDecodeError): + raise unauthorized_basic() from None + username, sep, password = decoded.partition(":") # двоеточие допустимо только в пароле + if not sep or not username.isascii() or not USERNAME_RE.fullmatch(username) or not 12 <= len(password) <= 128: + raise unauthorized_basic() + return username, password + + +# -------------------------------------------------------------------------------------------- +# Handlers +# -------------------------------------------------------------------------------------------- + +@endpoint +async def live(request: Request, state: AppState): + return json_response(request, {"status": "ok"}) + + +@endpoint +async def ready(request: Request, state: AppState): + # Критичная зависимость синхронного пути — только PostgreSQL. Redis — кэш: при его потере + # API продолжает работу через источник истины, поэтому readiness от него не зависит. + # S3 тоже не входит в readiness: без него недоступны только вложения (503), текстовые сообщения + # работают — иначе отказ S3 вывел бы из LB все реплики и уронил весь мессенджер. + if not state.ready or state.draining: + raise unavailable() + try: + async with asyncio.timeout(1.5): + async with state.pool.connection() as conn: + await conn.execute("SELECT 1") + except Exception: # noqa: BLE001 + raise unavailable() from None + return json_response(request, {"status": "ok"}) + + +@endpoint +async def internal_stats(request: Request, state: AppState): + """Только для исследования/диагностики изнутри контейнера; LB отдаёт 404 на /internal/*.""" + if request.client is None or request.client.host not in {"127.0.0.1", "::1"}: + raise not_found() + pool = state.pool.get_stats() + if request.query_params.get("reset_peak") == "1": + # Сброс VmHWM (пик RSS) — для измерения пика памяти в конкретном эксперименте. + with contextlib.suppress(OSError): + with open("/proc/self/clear_refs", "w") as fh: + fh.write("5") + return json_response(request, {"instance_id": state.settings.instance_id, + "version": os.environ.get("APP_VERSION", "dev"), "ready": state.ready, + "draining": state.draining, "app": state.stats, "memory": _proc_memory(), + "uploads_in_flight": state.settings.upload_concurrency - state.upload_slots._value, + "cache": state.cache.stats, "pool": pool, + "broker": await state.broker.stats() if state.broker else None}) + + +def _proc_memory() -> dict: + out = {} + try: + with open("/proc/self/status") as fh: + for line in fh: + if line.startswith(("VmRSS:", "VmHWM:")): + name, value = line.split(":", 1) + out[{"VmRSS": "rss_kib", "VmHWM": "peak_rss_kib"}[name]] = int(value.split()[0]) + except OSError: + pass + return out + + +@endpoint +async def create_user(request: Request, state: AppState): + data = await read_json(request, state, {"username", "display_name", "password"}, + {"username", "display_name", "password"}) + username = data["username"] + if not isinstance(username, str) or not USERNAME_RE.fullmatch(username): + raise invalid("username должен соответствовать [a-z0-9_]{3,32}") + display_name = text_field(data, "display_name", 1, 100) + password = text_field(data, "password", 12, 128) + async with state.pool.connection() as conn: + taken = await (await conn.execute("SELECT 1 FROM users WHERE username = %s", (username,))).fetchone() + if taken: + raise ApiError("conflict", "username уже занят") + password_hash = await state.hasher.hash(password) + try: + async with state.pool.connection() as conn: + row = await (await conn.execute( + "INSERT INTO users (username, display_name, password_hash) VALUES (%s, %s, %s)" + " RETURNING id, username, display_name, created_at", + (username, display_name, password_hash))).fetchone() + except pg_errors.UniqueViolation: + # Гонка регистрации: проверку выше прошли оба запроса, уникальный индекс пропустил один. + log.info("registration race resolved by unique constraint", extra={"request_id": request_id(request)}) + raise ApiError("conflict", "username уже занят") from None + return json_response(request, user_json(row), 201) + + +@endpoint +async def me(request: Request, state: AppState): + principal = await authenticate(request, state) + return json_response(request, principal.user) + + +@endpoint +async def create_session(request: Request, state: AppState): + username, password = parse_basic(request.headers.get("authorization", "")) + body = await read_body(request, 1024) + if body: + raise invalid("POST /auth/sessions не принимает тело") + async with state.pool.connection() as conn: + row = await (await conn.execute( + "SELECT id, username, display_name, created_at, password_hash FROM users WHERE username = %s", + (username,))).fetchone() + ok = await state.hasher.verify(password, row["password_hash"] if row else None) + if not ok: + raise unauthorized_basic() + token = new_token() + th = token_hash(token) + async with state.pool.connection() as conn: + srow = await (await conn.execute( + "INSERT INTO sessions (token_hash, user_id, expires_at)" + " VALUES (%s, %s, clock_timestamp() + make_interval(secs => %s)) RETURNING expires_at", + (th, row["id"], state.settings.session_ttl_seconds))).fetchone() + user = user_json(row) + await state.cache.put(Principal(user=user, expires_at=srow["expires_at"].timestamp(), token_hash=th)) + return json_response(request, {"token": token, "token_type": "Bearer", + "expires_at": db.iso(srow["expires_at"]), "user": user}, 201) + + +@endpoint +async def delete_session(request: Request, state: AppState): + principal = await authenticate(request, state) + th = principal.token_hash + async with state.pool.connection() as conn: + async with conn.transaction(): + revoked = await (await conn.execute( + "UPDATE sessions SET revoked_at = clock_timestamp()" + " WHERE token_hash = %s AND revoked_at IS NULL RETURNING 1", (th,))).fetchone() + if revoked is None: + raise unauthorized_bearer() + if state.cache.enabled: + await conn.execute( + "INSERT INTO session_cache_invalidations (token_hash) VALUES (%s) ON CONFLICT DO NOTHING", + (th,)) + # COMMIT в PostgreSQL уже сделал отзыв окончательным; Redis лишь догоняет источник истины. + if state.cache.enabled and await state.cache.invalidate(th): + with contextlib.suppress(Exception): + async with state.pool.connection() as conn: + await conn.execute("DELETE FROM session_cache_invalidations WHERE token_hash = %s", (th,)) + return Response(status_code=204, headers={"X-Request-Id": request_id(request)}) + + +@endpoint +async def create_chat(request: Request, state: AppState): + principal = await authenticate(request, state) + data = await read_json(request, state, {"title", "member_ids"}, {"title", "member_ids"}) + title = text_field(data, "title", 1, 100) + raw_members = data["member_ids"] + if not isinstance(raw_members, list) or not 1 <= len(raw_members) <= 100: + raise invalid("member_ids: массив из 1–100 UUID") + members = [parse_uuid(m, "member_id") for m in raw_members] + if len(set(members)) != len(members): + raise invalid("member_ids содержит дубликаты") + caller = uuid.UUID(principal.user["id"]) + if caller not in members: + raise invalid("member_ids должен содержать создателя чата") + async with state.pool.connection() as conn: + try: + async with conn.transaction(): # атомарно: чат и весь состав или ничего + chat = await (await conn.execute( + "INSERT INTO chats (title, created_by) VALUES (%s, %s) RETURNING id, title, created_at", + (title, caller))).fetchone() + await conn.execute( + "INSERT INTO chat_members (chat_id, user_id, position)" + " SELECT %s, m.user_id, m.ord - 1 FROM unnest(%s::uuid[]) WITH ORDINALITY AS m(user_id, ord)", + (chat["id"], members)) + except pg_errors.ForeignKeyViolation: + raise invalid("member_ids содержит неизвестного пользователя") from None + chat["member_ids"] = members + return json_response(request, chat_json(chat), 201) + + +_CHAT_LIST_SQL = ( + "SELECT c.id, c.title, c.created_at," + " (SELECT array_agg(x.user_id ORDER BY x.position) FROM chat_members x WHERE x.chat_id = c.id) AS member_ids" + " FROM chat_members m JOIN chats c ON c.id = m.chat_id" + " WHERE m.user_id = %s {after}" + " ORDER BY c.created_at, c.id LIMIT %s") + + +@endpoint +async def list_chats(request: Request, state: AppState): + principal = await authenticate(request, state) + caller = uuid.UUID(principal.user["id"]) + limit = parse_limit(request.query_params) + cursor = single_param(request.query_params, "cursor") + async with state.pool.connection() as conn: + if cursor is not None: + ts, last_id = decode_cursor(cursor, "chats", caller) + rows = await (await conn.execute(_CHAT_LIST_SQL.format(after="AND (c.created_at, c.id) > (%s, %s)"), + (caller, ts, last_id, limit + 1))).fetchall() + else: + rows = await (await conn.execute(_CHAT_LIST_SQL.format(after=""), (caller, limit + 1))).fetchall() + items = rows[:limit] + next_cursor = (encode_cursor("chats", caller, items[-1]["created_at"], items[-1]["id"]) + if len(rows) > limit else None) + return json_response(request, {"items": [chat_json(r) for r in items], "next_cursor": next_cursor}) + + +@endpoint +async def get_chat(request: Request, state: AppState): + principal = await authenticate(request, state) + chat_id = parse_uuid(request.path_params["chat_id"], "chat_id") + async with state.pool.connection() as conn: + row = await (await conn.execute( + "SELECT c.id, c.title, c.created_at, array_agg(m.user_id ORDER BY m.position) AS member_ids" + " FROM chats c JOIN chat_members m ON m.chat_id = c.id" + " WHERE c.id = %s AND EXISTS (SELECT 1 FROM chat_members a WHERE a.chat_id = c.id AND a.user_id = %s)" + " GROUP BY c.id", (chat_id, uuid.UUID(principal.user["id"])))).fetchone() + if row is None: + raise not_found() # нет или чужой — одинаковый ответ + return json_response(request, chat_json(row)) + + +async def _is_member(conn, chat_id: uuid.UUID, user_id: uuid.UUID) -> bool: + row = await (await conn.execute("SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s", + (chat_id, user_id))).fetchone() + return row is not None + + +# Вложения сообщения в порядке attachment_ids запроса (m — алиас messages). +_ATTACHMENT_IDS = (" (SELECT coalesce(array_agg(ma.attachment_id ORDER BY ma.position), '{}')" + " FROM message_attachments ma WHERE ma.message_id = m.id) AS attachment_ids") + +IDEMPOTENCY_KEY_RE = re.compile(r"[A-Za-z0-9._:-]{1,128}") + + +def idempotency_key(request: Request) -> str: + values = request.headers.getlist("idempotency-key") + if len(values) != 1 or not IDEMPOTENCY_KEY_RE.fullmatch(values[0]): + raise invalid("Требуется заголовок Idempotency-Key: [A-Za-z0-9._:-]{1,128}") + return values[0] + + +def request_fingerprint(body: dict) -> bytes: + """SHA-256 канонического JSON: порядок ключей и пробелы не влияют на равенство запросов.""" + canonical = json.dumps(body, sort_keys=True, ensure_ascii=False, separators=(",", ":")) + return hashlib.sha256(canonical.encode("utf-8")).digest() + + +_API_FAULT_RE = re.compile(r"fault-api-(error|slow)(?:-(\d+))?") + + +async def _api_fault_hook(state: "AppState", text: str) -> None: + """Учебные отказы обработчика для трека 1 и разбора инцидентов (только FAULT_HOOKS=lab): + маркер fault-api-error в тексте → необработанное исключение (500, ничего не записано); + fault-api-slow-<мс> → медленный обработчик (sleep в handler, БД при этом быстрая).""" + if state.settings.fault_hooks != "lab" or "fault-api-" not in text: + return + m = _API_FAULT_RE.search(text) + if m is None: + return + if m.group(1) == "error": + raise RuntimeError("injected handler failure (fault-api-error)") + await asyncio.sleep(min(int(m.group(2) or 300), 5000) / 1000) + + +class _Replay(Exception): + """Ключ уже занят: откатить свою вставку и прочитать сохранённый результат.""" + + +@endpoint +async def create_message(request: Request, state: AppState): + principal = await authenticate(request, state) + chat_id = parse_uuid(request.path_params["chat_id"], "chat_id") + sender = uuid.UUID(principal.user["id"]) + try: + key = idempotency_key(request) + data = await read_json(request, state, {"text", "attachment_ids"}, {"text"}) + raw_ids = data.get("attachment_ids", []) + if not isinstance(raw_ids, list) or len(raw_ids) > 10: + raise invalid("attachment_ids: массив из 0–10 UUID") + att_ids = [parse_uuid(x, "attachment_id") for x in raw_ids] + if len(set(att_ids)) != len(att_ids): + raise invalid("attachment_ids содержит дубликаты") + # С вложениями текст может быть пустым; без вложений — 1–4000 непробельных символов. + text = text_field(data, "text", 0 if att_ids else 1, 4000) + except ApiError as err: + if err.status == 400: + # Посторонний не должен по 400/404 узнавать о существовании чата. + async with state.pool.connection() as conn: + if not await _is_member(conn, chat_id, sender): + raise not_found() from None + raise + await _api_fault_hook(state, text) + # Отсутствующий attachment_ids и [] семантически равны (контракт), порядок ID значим. + fingerprint = request_fingerprint({"text": text, "attachment_ids": [str(a) for a in att_ids]}) + ttl = state.settings.idempotency_ttl_seconds + async with state.pool.connection() as conn: + try: + # Одна транзакция: сообщение и запись ключа фиксируются вместе или не фиксируются вовсе. + # Конкурентный INSERT того же ключа (любая реплика) ждёт COMMIT/ROLLBACK первого на + # уникальном индексе: после COMMIT получает конфликт, после ROLLBACK — проходит сам. + async with conn.transaction(): + await conn.execute( + "DELETE FROM idempotency_keys WHERE user_id = %s AND chat_id = %s AND key = %s" + " AND created_at < clock_timestamp() - make_interval(secs => %s)", + (sender, chat_id, key, ttl)) + row = await (await conn.execute( + "INSERT INTO messages (chat_id, sender_id, text)" + " SELECT %(c)s, %(u)s, %(t)s" + " WHERE EXISTS (SELECT 1 FROM chat_members WHERE chat_id = %(c)s AND user_id = %(u)s)" + " RETURNING id, chat_id, sender_id, text, created_at", + {"c": chat_id, "u": sender, "t": text})).fetchone() + if row is None: + raise not_found() # откат: ошибка доступа не фиксируется как результат ключа + if att_ids: + # Все вложения обязаны принадлежать ЭТОМУ чату; чужое/неизвестное — 404 (откат). + # FOR KEY SHARE: параллельный reconciler не удалит строку между проверкой и INSERT. + found = await (await conn.execute( + "SELECT count(*) AS n, count(*) FILTER (WHERE status = 'failed') AS failed" + " FROM (SELECT status FROM attachments WHERE id = ANY(%s) AND chat_id = %s" + " FOR KEY SHARE) s", (att_ids, chat_id))).fetchone() + if found["n"] != len(att_ids): + raise not_found() + if found["failed"]: + # queued/processing прикреплять можно (lab5), failed — нельзя (откат, ключ не фиксируется). + raise ApiError("conflict", "Нельзя прикрепить вложение, обработка которого завершилась ошибкой") + await conn.execute( + "INSERT INTO message_attachments (message_id, attachment_id, position)" + " SELECT %s, a.id, a.ord - 1 FROM unnest(%s::uuid[]) WITH ORDINALITY AS a(id, ord)", + (row["id"], att_ids)) + row["attachment_ids"] = att_ids + claimed = await (await conn.execute( + "INSERT INTO idempotency_keys (user_id, chat_id, key, request_hash, message_id)" + " VALUES (%s, %s, %s, %s, %s) ON CONFLICT DO NOTHING RETURNING 1", + (sender, chat_id, key, fingerprint, row["id"]))).fetchone() + if claimed is None: + raise _Replay() + except _Replay: + # Повтор: снова проверены сессия (authenticate) и доступ (членство), затем — сохранённый ответ. + stored = await (await conn.execute( + "SELECT k.request_hash, m.id, m.chat_id, m.sender_id, m.text, m.created_at," + _ATTACHMENT_IDS + + " FROM idempotency_keys k JOIN messages m ON m.id = k.message_id" + " WHERE k.user_id = %s AND k.chat_id = %s AND k.key = %s" + " AND EXISTS (SELECT 1 FROM chat_members a WHERE a.chat_id = k.chat_id AND a.user_id = k.user_id)", + (sender, chat_id, key))).fetchone() + if stored is None: + raise not_found() from None + if bytes(stored["request_hash"]) != fingerprint: + state.stats["idempotency_conflicts"] += 1 + raise ApiError("conflict", "Idempotency-Key уже использован с другим запросом") from None + state.stats["idempotent_replays"] += 1 + return json_response(request, message_json(stored), 201, {"Idempotent-Replayed": "true"}) + return json_response(request, message_json(row), 201) + + +_HISTORY_SQL = ( + "SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at," + "{atts}" + " FROM messages m" + " WHERE m.chat_id = %s {after} ORDER BY m.created_at, m.id LIMIT %s") + + +@endpoint +async def list_messages(request: Request, state: AppState): + principal = await authenticate(request, state) + chat_id = parse_uuid(request.path_params["chat_id"], "chat_id") + async with state.pool.connection() as conn: + if not await _is_member(conn, chat_id, uuid.UUID(principal.user["id"])): + raise not_found() + limit = parse_limit(request.query_params) + cursor = single_param(request.query_params, "cursor") + if cursor is not None: + ts, last_id = decode_cursor(cursor, "messages", chat_id) + rows = await (await conn.execute(_HISTORY_SQL.format(atts=_ATTACHMENT_IDS, after="AND (m.created_at, m.id) > (%s, %s)"), + (chat_id, ts, last_id, limit + 1))).fetchall() + else: + rows = await (await conn.execute(_HISTORY_SQL.format(atts=_ATTACHMENT_IDS, after=""), (chat_id, limit + 1))).fetchall() + items = rows[:limit] + next_cursor = (encode_cursor("messages", chat_id, items[-1]["created_at"], items[-1]["id"]) + if len(rows) > limit else None) + return json_response(request, {"items": [message_json(r) for r in items], "next_cursor": next_cursor}) + + + +# -------------------------------------------------------------------------------------------- +# Вложения (lab4) +# -------------------------------------------------------------------------------------------- + +# / \ NUL, управляющие C0/C1, bidi-override (U+202A–202E, U+2066–2069, U+200E/F: «evil\u202egnp.exe»), +# разделители строк/абзацев U+2028/2029, BOM. +_BAD_FILENAME = re.compile(r"[/\\\x00-\x1f\x7f-\x9f\u200e\u200f\u202a-\u202e\u2066-\u2069\u2028\u2029\ufeff]") +_IMAGE_TYPES = ("image/png", "image/jpeg") +_VARIANTS = ("original", "thumbnail", "crop", "optimized") + + +class _ClientGone(Exception): + """Клиент оборвал загрузку (меньше байт, чем в Content-Length, или разрыв соединения).""" + + +def _filename(request: Request) -> str: + name = single_param(request.query_params, "filename") + if name is None or not 1 <= len(name) <= 255 or not name.strip() or _BAD_FILENAME.search(name) \ + or not name.strip(". "): # «.», «..», «...» — не имена файлов + raise invalid("filename: 1–255 символов, без / \\ NUL и управляющих символов") + try: + name.encode("utf-8") + except UnicodeEncodeError: + raise invalid("filename: некорректный Unicode") from None + return name + + +async def _drain(it, limit: int) -> None: + """Дочитать (и выбросить) остаток тела, не больше limit байт и 10 с: клиент получит ответ, + а не разрыв соединения посреди отправки. Память не растёт — куски сразу отбрасываются.""" + read = 0 + try: + async with asyncio.timeout(10): + async for chunk in it: + read += len(chunk) + if read > limit: + return + except (Exception, asyncio.CancelledError): # noqa: BLE001 + return + + +async def _compensate(state: AppState, key: str) -> None: + """Немедленная компенсация неуспешной загрузки: удалить объект (если успел появиться) и намерение. + Если S3 недоступен — намерение остаётся, объект уберёт фоновая очистка после grace period.""" + state.stats["compensations"] += 1 + try: + await state.s3.delete_object(state.settings.s3_bucket, key) + except (S3Error, S3Unavailable): + log.warning("compensation deferred to janitor", extra={"object_key": key}) + return + with contextlib.suppress(Exception): + async with state.pool.connection() as conn: + await conn.execute("DELETE FROM upload_intents WHERE object_key = %s", (key,)) + + +async def upload_attachment(request: Request, state: AppState): + principal = await authenticate(request, state) + chat_id = parse_uuid(request.path_params["chat_id"], "chat_id") + owner = uuid.UUID(principal.user["id"]) + async with state.pool.connection() as conn: + if not await _is_member(conn, chat_id, owner): + raise not_found() # до чтения тела: посторонний не заставит читать 10 МиБ + filename = _filename(request) + declared = request.headers.get("content-type", "").split(";")[0].strip().lower() + if declared not in _IMAGE_TYPES: + raise ApiError("unsupported_media_type", "Принимаются только image/png и image/jpeg") + length_header = request.headers.get("content-length") + if length_header is None: + raise invalid("Требуется Content-Length (сырые байты одного файла)") + if not length_header.isdigit(): + raise invalid("Некорректный Content-Length") + length = int(length_header) + if length > state.settings.max_upload_bytes: + raise ApiError("payload_too_large", "Файл больше %d байт" % state.settings.max_upload_bytes) + if length == 0: + raise ApiError("unsupported_media_type", "Пустое тело — не изображение") + if state.s3 is None: + raise unavailable() + try: + await asyncio.wait_for(state.upload_slots.acquire(), timeout=5) + except asyncio.TimeoutError: + raise unavailable() from None + try: + return await _store_upload(request, state, chat_id, owner, filename, declared, length) + except ApiError as err: + telemetry.uploads.add(1, {"outcome": "rejected" if err.status < 500 else "failed"}) + raise + except BaseException: + telemetry.uploads.add(1, {"outcome": "failed"}) + raise + finally: + state.upload_slots.release() + + +async def _store_upload(request, state, chat_id, owner, filename, declared, length): + s = state.settings + att_id = uuid.uuid4() + span = trace.get_current_span() + if span.is_recording(): + # Технический UUID учебных данных — в span (не в label метрики): по нему ищется trace загрузки. + span.set_attribute("messenger.attachment.id", str(att_id)) + span.set_attribute("messenger.upload.size_bytes", length) + # Ключи назначает сервер; filename в них не участвует. Байты сначала попадают в staging (приватный + # prefix того же bucket), конечный оригинал originals/ публикует worker при переходе в ready. + key = "staging/" + att_id.hex + final_key = "originals/" + att_id.hex + # 1) Намерение фиксируется ДО записи в S3 (отдельная транзакция). + async with state.pool.connection() as conn: + await conn.execute("INSERT INTO upload_intents (object_key, attachment_id, chat_id, owner_id)" + " VALUES (%s, %s, %s, %s)", (key, att_id, chat_id, owner)) + it = request.stream().__aiter__() + sha, received = hashlib.sha256(), 0 + dims = {} + try: + head = b"" + try: + while len(head) < 16: + head += await it.__anext__() + except StopAsyncIteration: + pass + detected = sniff(head) + if detected is None: + raise ImageRejected("invalid", "содержимое не PNG/JPEG") + if detected != declared: + raise ImageRejected("invalid", "Content-Type не совпадает с содержимым (%s)" % detected) + validator = validator_for(detected, s.max_image_pixels) + + async def body(): + # Последний кусок придерживается, пока validator.finish() не подтвердит файл: иначе S3 + # получил бы весь Content-Length и мог зафиксировать объект уже ПОСЛЕ компенсирующего + # DELETE (гонка найдена инвариантом I7). Оборванный PUT S3 не фиксирует никогда. + nonlocal received + pending = [head] + held = None + while True: + if pending: + piece = pending.pop() + else: + try: + piece = await it.__anext__() + except StopAsyncIteration: + break + except ClientDisconnect: + raise _ClientGone() from None + if not piece: + continue + received += len(piece) + if received > length: + raise ApiError("payload_too_large", "Тело длиннее Content-Length") + validator.feed(piece) # 413/415 — до того, как S3 получит весь объект + sha.update(piece) + if held is not None: + yield held + held = piece + if received != length: + raise _ClientGone() + dims["wh"] = validator.finish() # ошибка здесь обрывает PUT до последнего байта + if held is not None: + yield held + + # 2) Потоковый PUT: в RAM держится только текущий кусок (≈64 КиБ), не весь файл. + await state.s3.put_object_stream(s.s3_bucket, key, body(), length, detected) + if s.fault_inject == "crash_after_s3_put": + log.error("FAULT INJECTION: process exits between S3 PUT and DB COMMIT", extra={"object_key": key}) + os._exit(137) + # 3) Одна транзакция: метаданные (queued) + задание + строка outbox + снятие намерения. + # COMMIT = полный проверенный оригинал в staging И намерение обработки сохранены → можно 202. + width, height = dims["wh"] + async with state.pool.connection() as conn: + async with conn.transaction(): + row = await (await conn.execute( + "INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256," + " width, height, object_key, staging_key, status)" + " VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, 'queued') RETURNING *", + (att_id, chat_id, owner, filename, detected, received, sha.hexdigest(), width, height, + final_key, key))).fetchone() + await create_job(conn, s, att_id, s.pipeline_version) + await conn.execute("DELETE FROM upload_intents WHERE object_key = %s", (key,)) + if s.fault_inject == "crash_after_commit_before_publish": + log.error("FAULT INJECTION: process exits between DB COMMIT and broker publish", + extra={"attachment_id": str(att_id)}) + os._exit(137) + state.relay_kick.set() # опубликовать сразу; при сбое — relay любой реплики/worker + except ImageRejected as exc: + state.stats["uploads_rejected"] += 1 + await _drain(it, s.max_upload_bytes + 65536) + await _compensate(state, key) + if exc.kind == "too_large": + raise ApiError("payload_too_large", "Слишком много пикселей: максимум %d" % s.max_image_pixels) from None + raise ApiError("unsupported_media_type", "Файл не является корректным PNG/JPEG: " + str(exc)) from None + except ApiError: + state.stats["uploads_rejected"] += 1 + await _drain(it, s.max_upload_bytes + 65536) + await _compensate(state, key) + raise + except (_ClientGone, ClientDisconnect): + state.stats["uploads_failed"] += 1 + await _compensate(state, key) + raise invalid("Загрузка прервана: получено %d из %d байт" % (received, length)) from None + except BaseException: + # S3/БД недоступны, таймаут, отмена: компенсация (или отложенная — через намерение). + state.stats["uploads_failed"] += 1 + with contextlib.suppress(Exception): + await asyncio.shield(_compensate(state, key)) + raise + state.stats["uploads_ok"] += 1 + telemetry.uploads.add(1, {"outcome": "accepted"}) + log.info("attachment accepted", extra={"event": "attachment.accepted", "request_id": request_id(request), + "attachment_id": str(att_id), "size_bytes": received}) + return json_response(request, attachment_json(row), 202) + + +_ATTACHMENT_SQL = ("SELECT a.* FROM attachments a WHERE a.id = %s AND EXISTS (SELECT 1 FROM chat_members m" + " WHERE m.chat_id = a.chat_id AND m.user_id = %s)") + + +@endpoint +async def get_attachment(request: Request, state: AppState): + principal = await authenticate(request, state) + att_id = parse_uuid(request.path_params["attachment_id"], "attachment_id") + async with state.pool.connection() as conn: + row = await (await conn.execute(_ATTACHMENT_SQL, (att_id, uuid.UUID(principal.user["id"])))).fetchone() + if row is None: + raise not_found() + variants = await load_variants(conn, row) + return json_response(request, attachment_json(row, variants)) + + +async def download_attachment(request: Request, state: AppState): + principal = await authenticate(request, state) + att_id = parse_uuid(request.path_params["attachment_id"], "attachment_id") + variant = single_param(request.query_params, "variant") or "original" + if variant not in _VARIANTS: + raise invalid("variant: original, thumbnail, crop или optimized") + async with state.pool.connection() as conn: + row = await (await conn.execute(_ATTACHMENT_SQL, (att_id, uuid.UUID(principal.user["id"])))).fetchone() + if row is None: + raise not_found() + if row["status"] != "ready": + # queued/processing — ещё не готово; failed — готово не будет. Оба — 409 по контракту. + raise ApiError("conflict", "Вложение ещё обрабатывается" if row["status"] != "failed" + else "Обработка вложения завершилась ошибкой") + if variant == "original": + key, ctype, size, digest = row["object_key"], row["content_type"], row["size_bytes"], row["sha256"] + else: + found = [v for v in await load_variants(conn, row) if v["name"] == variant] + if not found: + raise not_found() # отсутствующий вариант ready-объекта + v = found[0] + key, ctype, size, digest = v["object_key"], v["content_type"], v["size_bytes"], v["sha256"] + if state.s3 is None: + raise unavailable() + try: + resp = await state.s3.get_object_stream(state.settings.s3_bucket, key) + except S3Error as exc: + if exc.status == 404: + log.error("attachment object missing in S3", extra={"attachment_id": str(att_id)}) + raise ApiError("internal_error", "Содержимое вложения утрачено") from None + raise unavailable() from None + + async def stream(): + try: + async for chunk in resp.aiter_bytes(65536): + yield chunk + finally: + await resp.aclose() + + return StreamingResponse(stream(), media_type=ctype, headers={ + "Content-Length": str(size), "ETag": '"%s"' % digest, + "Cache-Control": "private, no-store", "X-Content-Type-Options": "nosniff", + "Content-Disposition": "inline; filename*=UTF-8''" + quote(row["filename"], safe=""), + "X-Request-Id": request_id(request)}) + + +JANITOR_LOCK_ID = 2026_0404 + + +def intent_grace_seconds(settings) -> float: + """Intent нельзя считать брошенным, пока загрузка ещё может законно идти (UPLOAD_TIMEOUT_SECONDS): + иначе очистка удалила бы объект между S3 PUT и COMMIT живого запроса.""" + return max(float(settings.upload_grace_seconds), settings.upload_timeout_seconds + 5) + + +async def upload_janitor(state: AppState) -> None: + """Фоновая очистка намерений старше UPLOAD_GRACE_SECONDS: процесс упал между S3 PUT и COMMIT или + во время загрузки. Объект по ключу удаляется (если метаданных нет), намерение снимается. + Одновременно работает одна реплика (pg_try_advisory_lock); повтор безопасен (идемпотентно).""" + while not state.stop.is_set(): + try: + if state.s3 is not None and state.ready: + async with state.pool.connection() as conn: + got = await (await conn.execute("SELECT pg_try_advisory_lock(%s) AS ok", (JANITOR_LOCK_ID,))).fetchone() + if got["ok"]: + try: + removed = await janitor_pass(state, conn) + if removed: + log.info("janitor removed stale uploads", extra={"count": removed}) + finally: + await conn.execute("SELECT pg_advisory_unlock(%s)", (JANITOR_LOCK_ID,)) + except Exception as exc: # noqa: BLE001 + log.warning("janitor pass failed", extra={"error": type(exc).__name__}) + with contextlib.suppress(asyncio.TimeoutError): + await asyncio.wait_for(state.stop.wait(), timeout=state.settings.janitor_interval_seconds) + + +async def janitor_pass(state: AppState, conn) -> int: + rows = await (await conn.execute( + "SELECT i.object_key, EXISTS (SELECT 1 FROM attachments a WHERE a.id = i.attachment_id) AS committed" + " FROM upload_intents i WHERE i.created_at < clock_timestamp() - make_interval(secs => %s)" + " ORDER BY i.created_at LIMIT 200", (intent_grace_seconds(state.settings),))).fetchall() + removed = 0 + for r in rows: + if not r["committed"]: + await state.s3.delete_object(state.settings.s3_bucket, r["object_key"]) # 204 и при отсутствии + removed += 1 + await conn.execute("DELETE FROM upload_intents WHERE object_key = %s", (r["object_key"],)) + state.stats["janitor_removed"] += removed + return removed + +# -------------------------------------------------------------------------------------------- +# Фоновые задачи и сборка приложения +# -------------------------------------------------------------------------------------------- + +async def outbox_relay(state: AppState) -> None: + """Публикация заданий из outbox. Будится сразу после upload (relay_kick) и раз в + RELAY_INTERVAL_SECONDS — так строки, оставшиеся после падения любой реплики между COMMIT и + publish, публикуются без ручного вмешательства. Брокер недоступен — строки ждут в PostgreSQL.""" + while not state.stop.is_set(): + try: + if state.ready: + n = await relay_pass(state.pool, state.broker, state.settings, fault=state.settings.fault_inject) + state.stats["outbox_published"] += n + if n: + continue # возможно, есть ещё — без паузы + except Exception as exc: # noqa: BLE001 + log.warning("outbox relay pass failed", extra={"error": type(exc).__name__}) + state.relay_kick.clear() + with contextlib.suppress(asyncio.TimeoutError): + await asyncio.wait_for(state.relay_kick.wait(), timeout=state.settings.relay_interval_seconds) + + +_QUEUE_SQL = ( + "SELECT count(*) FILTER (WHERE status = 'queued' AND next_attempt_at <= clock_timestamp()) AS ready," + " count(*) FILTER (WHERE status = 'queued' AND next_attempt_at > clock_timestamp()) AS retry_wait," + " count(*) FILTER (WHERE status = 'processing') AS processing," + " extract(epoch FROM clock_timestamp() - min(next_attempt_at)" + " FILTER (WHERE status = 'queued' AND next_attempt_at <= clock_timestamp()))::float8 AS lag," + " extract(epoch FROM clock_timestamp() - min(created_at))::float8 AS oldest_age" + " FROM attachment_jobs WHERE status IN ('queued', 'processing')") +_OUTBOX_SQL = ( + "SELECT count(*) AS n, extract(epoch FROM clock_timestamp() - min(available_at))::float8 AS lag" + " FROM job_outbox WHERE published_at IS NULL AND available_at <= clock_timestamp()") + + +async def queue_metrics_loop(state: AppState) -> None: + """Метрики очереди считает API (а не worker): при остановленных worker именно они должны показать + растущий backlog. Каждая реплика сообщает одно и то же значение — в запросах берётся max().""" + q = {"queue": state.settings.broker_subject} + while not state.stop.is_set(): + if state.ready: + try: + async with state.pool.connection() as conn: + r = await (await conn.execute(_QUEUE_SQL)).fetchone() + f = await (await conn.execute("SELECT count(*) AS n FROM attachment_jobs WHERE status = 'failed'")).fetchone() + o = await (await conn.execute(_OUTBOX_SQL)).fetchone() + telemetry.set_gauge("messenger.queue.depth", [(r[k], dict(q, state=k)) for k in ("ready", "retry_wait", "processing")] + + [(f["n"], dict(q, state="failed"))]) + telemetry.set_gauge("messenger.queue.lag", [(r["lag"] or 0.0, q)]) + telemetry.set_gauge("messenger.queue.oldest_age", [(r["oldest_age"] or 0.0, q)]) + telemetry.set_gauge("messenger.outbox.pending", [(o["n"], q)]) + telemetry.set_gauge("messenger.outbox.lag", [(o["lag"] or 0.0, q)]) + except Exception as exc: # noqa: BLE001 — БД недоступна: лучше «нет данных», чем устаревшие + for name in ("messenger.queue.depth", "messenger.queue.lag", "messenger.queue.oldest_age", + "messenger.outbox.pending", "messenger.outbox.lag"): + telemetry.set_gauge(name, []) + log.debug("queue metrics skipped", extra={"error": type(exc).__name__}) + if state.broker is not None: + st = await state.broker.stats() + if st.get("connected"): + telemetry.set_gauge("messenger.broker.pending", [(st["consumer_pending"], q)]) + telemetry.set_gauge("messenger.broker.ack_pending", [(st["ack_pending"], q)]) + else: + telemetry.set_gauge("messenger.broker.pending", []) + telemetry.set_gauge("messenger.broker.ack_pending", []) + with contextlib.suppress(asyncio.TimeoutError): + await asyncio.wait_for(state.stop.wait(), timeout=5) + + +async def wait_for_schema(state: AppState) -> None: + """Реплика не мигрирует схему сама (это делает one-shot сервис migrate) и не становится ready, + пока в БД не применены все миграции, которые знает этот код.""" + delay = 0.5 + while not state.stop.is_set(): + try: + ok, missing = await db.schema_status(state.pool) + if ok: + state.ready = True + log.info("schema compatible; replica ready", extra={"instance_id": state.settings.instance_id}) + return + log.warning("schema is behind this code; waiting for migrate", extra={"missing": missing}) + except Exception as exc: # noqa: BLE001 — БД ещё недоступна или нет schema_migrations + log.warning("schema check failed; retrying", extra={"error": type(exc).__name__}) + with contextlib.suppress(asyncio.TimeoutError): + await asyncio.wait_for(state.stop.wait(), timeout=delay) + delay = min(delay * 2, 5) + + +async def expired_sessions_cleanup(state: AppState) -> None: + """Удаляет сессии, истёкшие более суток назад, пачками (не держит долгих блокировок).""" + while not state.stop.is_set(): + with contextlib.suppress(Exception): + async with state.pool.connection() as conn: + await conn.execute( + "DELETE FROM sessions WHERE token_hash IN (SELECT token_hash FROM sessions" + " WHERE expires_at < clock_timestamp() - interval '1 day' LIMIT 1000)") + await conn.execute( + "DELETE FROM idempotency_keys WHERE ctid IN (SELECT ctid FROM idempotency_keys" + " WHERE created_at < clock_timestamp() - make_interval(secs => %s) LIMIT 5000)", + (state.settings.idempotency_ttl_seconds,)) + with contextlib.suppress(asyncio.TimeoutError): + await asyncio.wait_for(state.stop.wait(), timeout=300) + + +def build_app(settings: Settings) -> Starlette: + state = AppState(settings) + + @contextlib.asynccontextmanager + async def lifespan(app: Starlette): + if settings.migrate_on_start: + applied = await db.migrate_with_wait(settings) + log.info("migrations checked", extra={"applied": applied}) + await state.pool.open(wait=False) + with contextlib.suppress(OSError): + Path(settings.instance_id_file).write_text(settings.instance_id + "\n") + state.tasks.append(asyncio.create_task(wait_for_schema(state))) + if state.cache.enabled: + state.tasks.append(asyncio.create_task(state.cache.maintenance_loop(state.pool, state.stop))) + state.tasks.append(asyncio.create_task(expired_sessions_cleanup(state))) + state.tasks.append(asyncio.create_task(upload_janitor(state))) + if state.broker is not None: + state.tasks.append(asyncio.create_task(outbox_relay(state))) + if telemetry.ENABLED: + telemetry.register_pool(state.pool, "api") + telemetry.register_gauges(telemetry.QUEUE_GAUGES) + state.tasks.append(asyncio.create_task(queue_metrics_loop(state))) + log.info("api started", extra={"instance_id": settings.instance_id, "version": os.environ.get("APP_VERSION", "dev"), + "cache": state.cache.enabled, + "session_ttl_seconds": settings.session_ttl_seconds}) + try: + yield + finally: + state.ready = False + state.stop.set() + for task in state.tasks: + task.cancel() + await asyncio.gather(*state.tasks, return_exceptions=True) + await state.cache.close() + if state.broker is not None: + await state.broker.close() + if state.s3 is not None: + await state.s3.aclose() + await state.pool.close() + + async def http_exception(request: Request, exc: HTTPException): + if exc.status_code == 405: + err = ApiError("method_not_allowed", "Метод не поддерживается", headers=dict(exc.headers or {})) + elif exc.status_code == 404: + err = ApiError("not_found") + else: + err = ApiError("invalid_request") + return error_response(request, err) + + async def server_error(request: Request, exc: Exception): + return error_response(request, ApiError("internal_error")) + + routes = [ + Route("/health/live", live, methods=["GET"]), + Route("/health/ready", ready, methods=["GET"]), + Route("/internal/stats", internal_stats, methods=["GET"]), + Route("/api/v1/users", create_user, methods=["POST"]), + Route("/api/v1/users/me", me, methods=["GET"]), + Route("/api/v1/auth/sessions", create_session, methods=["POST"]), + Route("/api/v1/auth/sessions/current", delete_session, methods=["DELETE"]), + Route("/api/v1/chats", create_chat, methods=["POST"]), + Route("/api/v1/chats", list_chats, methods=["GET"]), + Route("/api/v1/chats/{chat_id}", get_chat, methods=["GET"]), + Route("/api/v1/chats/{chat_id}/messages", create_message, methods=["POST"]), + Route("/api/v1/chats/{chat_id}/messages", list_messages, methods=["GET"]), + Route("/api/v1/chats/{chat_id}/attachments", endpoint(upload_attachment, "upload_timeout_seconds"), methods=["POST"]), + Route("/api/v1/attachments/{attachment_id}", get_attachment, methods=["GET"]), + Route("/api/v1/attachments/{attachment_id}/content", endpoint(download_attachment), methods=["GET"]), + ] + app = Starlette(routes=routes, lifespan=lifespan, + exception_handlers={HTTPException: http_exception, Exception: server_error}) + app.add_middleware(RequestContextMiddleware, instance_id=settings.instance_id, state=state) + app.state.messenger = state + return app + + +__all__ = ["build_app"] diff --git a/src/messenger/broker.py b/src/messenger/broker.py new file mode 100644 index 00000000..70490435 --- /dev/null +++ b/src/messenger/broker.py @@ -0,0 +1,153 @@ +"""Брокер заданий: NATS JetStream (stream на диске, explicit ack, pull consumer). + +Границы надёжности (они разные и не заменяют друг друга): + * publish ack (аналог publisher confirm RabbitMQ): JetStream отвечает на publish только после + записи сообщения в stream (file storage, sync_interval: always — fsync). Пока ack не получен, + relay не отмечает строку outbox опубликованной; + * consumer ack: worker подтверждает сообщение только после устойчивого эффекта (S3 + COMMIT в БД) + или после устойчивого решения «повторять незачем» (ready/устаревшее/дубль). Без ack сообщение + вернётся через ack_wait — это и есть at-least-once. +Nats-Msg-Id = outbox-: повторная публикация той же строки outbox (relay упал между publish и +отметкой) отбрасывается брокером в окне дедупликации; за окном её поглощает идемпотентность worker. +В сообщении только ID и служебные поля (jobs.schema.json): ни байтов файла, ни URL, ни credentials. +""" +from __future__ import annotations + +import asyncio +import logging + +import nats +from nats.js.api import (AckPolicy, ConsumerConfig, DeliverPolicy, DiscardPolicy, RetentionPolicy, + StorageType, StreamConfig) +from nats.js.errors import NotFoundError + +from .config import Settings + +log = logging.getLogger("messenger.broker") + + +class BrokerUnavailable(Exception): + """Брокер недоступен или не подтвердил публикацию.""" + + +def stream_config(s: Settings) -> StreamConfig: + return StreamConfig( + name=s.broker_stream, subjects=[s.broker_subject], storage=StorageType.FILE, + # WorkQueue: сообщение удаляется из stream после ack — очередь не растёт бесконечно. + retention=RetentionPolicy.WORK_QUEUE, num_replicas=1, + # Ограничение принятой брокером работы: при переполнении publish отклоняется (DiscardPolicy.NEW), + # строки остаются в outbox PostgreSQL и публикуются позже — backpressure, а не потеря. + max_msgs=s.broker_max_msgs, discard=DiscardPolicy.NEW, + max_age=7 * 24 * 3600, duplicate_window=s.broker_duplicate_window_seconds) + + +def consumer_config(s: Settings) -> ConsumerConfig: + return ConsumerConfig( + durable_name=s.broker_consumer, ack_policy=AckPolicy.EXPLICIT, deliver_policy=DeliverPolicy.ALL, + filter_subject=s.broker_subject, + ack_wait=s.broker_ack_wait_seconds, # аренда сообщения; продлевается in_progress() + max_deliver=-1, # предел попыток ведёт БД (claims ≤ JOB_MAX_ATTEMPTS) + max_ack_pending=s.broker_max_ack_pending) # глобальный предел «взятой в работу» очереди + + +class Broker: + def __init__(self, settings: Settings, name: str): + self.s, self.name = settings, name + self.nc = None + self.js = None + self._lock = asyncio.Lock() + + @property + def connected(self) -> bool: + return self.nc is not None and self.nc.is_connected + + async def connect(self) -> None: + """Подключиться (повторно — no-op). Ошибка первичного подключения — BrokerUnavailable.""" + if self.nc is not None and not self.nc.is_closed: + return + if not self.s.broker_url: + raise BrokerUnavailable("BROKER_URL is not configured") + async with self._lock: + if self.nc is not None and not self.nc.is_closed: + return + + async def on_error(exc): + log.warning("broker connection error", extra={"error": type(exc).__name__}) + + async def on_disconnect(): + log.warning("broker disconnected") + + async def on_reconnect(): + log.info("broker reconnected") + try: + self.nc = await nats.connect( + self.s.broker_url, name=self.name, connect_timeout=2, reconnect_time_wait=1, + max_reconnect_attempts=-1, allow_reconnect=True, ping_interval=10, + error_cb=on_error, disconnected_cb=on_disconnect, reconnected_cb=on_reconnect) + except Exception as exc: # noqa: BLE001 — NoServersError, ConnectionRefused, auth + self.nc = None + raise BrokerUnavailable(type(exc).__name__) from exc + self.js = self.nc.jetstream(timeout=5) + + async def ensure_topology(self) -> dict: + """Идемпотентно создать/обновить stream и durable consumer. Повтор — no-op.""" + await self.connect() + created = {"stream": False, "consumer": False} + try: + await self.js.stream_info(self.s.broker_stream) + await self.js.update_stream(stream_config(self.s)) + except NotFoundError: + await self.js.add_stream(stream_config(self.s)) + created["stream"] = True + try: + await self.js.consumer_info(self.s.broker_stream, self.s.broker_consumer) + except NotFoundError: + created["consumer"] = True + # add_consumer с тем же durable и совместимой конфигурацией — создание или обновление. + await self.js.add_consumer(self.s.broker_stream, consumer_config(self.s)) + return created + + async def publish(self, payload: bytes, msg_id: str, extra_headers: dict | None = None) -> tuple[int, bool]: + """Публикация с ожиданием publish ack. Возвращает (sequence в stream, дубль ли). Дубль по + Nats-Msg-Id в окне дедупликации брокер не сохраняет повторно и отвечает исходным seq. + extra_headers — W3C trace context (traceparent/tracestate) span «send» (lab6).""" + headers = {k: v for k, v in (extra_headers or {}).items() if k in ("traceparent", "tracestate")} + headers["Nats-Msg-Id"] = msg_id + try: + await self.connect() + ack = await self.js.publish(self.s.broker_subject, payload, timeout=5, + stream=self.s.broker_stream, headers=headers) + except BrokerUnavailable: + raise + except Exception as exc: # noqa: BLE001 — timeout, no responders, stream full, разрыв + raise BrokerUnavailable(type(exc).__name__) from exc + return ack.seq, bool(ack.duplicate) + + async def pull_subscription(self): + await self.connect() + return await self.js.pull_subscribe_bind(self.s.broker_consumer, self.s.broker_stream) + + async def stats(self) -> dict: + try: + await self.connect() + si = await self.js.stream_info(self.s.broker_stream) + ci = await self.js.consumer_info(self.s.broker_stream, self.s.broker_consumer) + return {"connected": True, "stream_messages": si.state.messages, "consumer_pending": ci.num_pending, + "ack_pending": ci.num_ack_pending, "redelivered": ci.num_redelivered} + except Exception as exc: # noqa: BLE001 + return {"connected": False, "error": type(exc).__name__} + + async def close(self) -> None: + if self.nc is not None: + # Не drain(): он ждёт закрытия pull-подписки до 30 с. Неподтверждённых публикаций нет — + # каждая publish ждёт ack, а невыполненные сообщения worker вернёт брокер по ack_wait. + try: + await asyncio.wait_for(self.nc.flush(), timeout=1) + except Exception: # noqa: BLE001 + pass + try: + await self.nc.close() + except Exception: # noqa: BLE001 + pass + self.nc = None + self.js = None diff --git a/src/messenger/config.py b/src/messenger/config.py new file mode 100644 index 00000000..1420b0f2 --- /dev/null +++ b/src/messenger/config.py @@ -0,0 +1,214 @@ +"""Конфигурация из окружения. Секреты читаются из *_FILE (Docker/Compose secrets).""" +from __future__ import annotations + +import os +import secrets +from dataclasses import dataclass +from pathlib import Path + + +class ConfigError(RuntimeError): + pass + + +def _secret(name: str, required: bool) -> str | None: + """Значение NAME или содержимое файла NAME_FILE (приоритет у файла).""" + path = os.environ.get(name + "_FILE") + if path: + try: + value = Path(path).read_text(encoding="utf-8").strip() + except OSError as exc: + raise ConfigError(f"cannot read {name}_FILE") from exc + if not value: + raise ConfigError(f"{name}_FILE is empty") + return value + value = os.environ.get(name, "").strip() + if value: + return value + if required: + raise ConfigError(f"{name} or {name}_FILE is required") + return None + + +def _int(name: str, default: int, lo: int, hi: int) -> int: + raw = os.environ.get(name) + if raw is None or raw == "": + return default + try: + value = int(raw) + except ValueError as exc: + raise ConfigError(f"{name} must be an integer") from exc + if not lo <= value <= hi: + raise ConfigError(f"{name} must be in [{lo}, {hi}]") + return value + + +def _float(name: str, default: float, lo: float, hi: float) -> float: + raw = os.environ.get(name) + if raw is None or raw == "": + return default + try: + value = float(raw) + except ValueError as exc: + raise ConfigError(f"{name} must be a number") from exc + if not lo <= value <= hi: + raise ConfigError(f"{name} must be in [{lo}, {hi}]") + return value + + +@dataclass(frozen=True) +class Settings: + host: str + port: int + env: str + database_url: str + cache_url: str | None + session_ttl_seconds: int + session_cache_ttl_seconds: int + cache_timeout_seconds: float + cache_retry_seconds: float + db_pool_min: int + db_pool_max: int + db_pool_timeout_seconds: float + db_connect_timeout_seconds: int + db_statement_timeout_ms: int + request_timeout_seconds: float + max_body_bytes: int + kdf_concurrency: int + scrypt_log2_n: int + scrypt_r: int + scrypt_p: int + migrate_on_start: bool + migrate_wait_seconds: int + instance_id: str + instance_id_file: str + idempotency_ttl_seconds: int + shutdown_drain_seconds: float + s3_endpoint: str | None + s3_region: str + s3_bucket: str + s3_access_key: str | None + s3_secret_key: str | None + s3_timeout_seconds: float + max_upload_bytes: int + max_image_pixels: int + upload_concurrency: int + upload_timeout_seconds: float + upload_grace_seconds: int + janitor_interval_seconds: float + fault_inject: str + # lab5: брокер (NATS JetStream) и фоновая обработка + broker_url: str | None + broker_stream: str + broker_subject: str + broker_consumer: str + broker_ack_wait_seconds: float + broker_max_ack_pending: int + broker_duplicate_window_seconds: float + broker_max_msgs: int + pipeline_version: int + worker_pipelines: tuple + worker_concurrency: int + job_max_attempts: int + job_timeout_seconds: float + job_lease_seconds: float + job_retry_base_seconds: float + job_retry_max_seconds: float + job_stuck_seconds: float + worker_process_memory_mb: int + staging_retention_seconds: int + relay_interval_seconds: float + maintenance_interval_seconds: float + staging_sweep_seconds: float + fault_hooks: str + worker_id: str + + @property + def cache_enabled(self) -> bool: + return self.cache_url is not None + + +def load() -> Settings: + store = os.environ.get("SESSION_STORE", "postgres").strip() + if store != "postgres": + # Источник истины сессий — всегда PostgreSQL; Redis/Valkey — только кэш (см. REPORT.md). + raise ConfigError("SESSION_STORE must be 'postgres' (Redis/Valkey is a cache via CACHE_URL)") + cache_mode = os.environ.get("SESSION_CACHE", "auto").strip() + if cache_mode not in {"auto", "redis", "off"}: + raise ConfigError("SESSION_CACHE must be auto, redis or off") + cache_url = None if cache_mode == "off" else _secret("CACHE_URL", required=cache_mode == "redis") + pool_max = _int("DB_POOL_MAX", 10, 1, 100) + return Settings( + host=os.environ.get("APP_HOST", "0.0.0.0"), + port=_int("APP_PORT", 8080, 1, 65535), + env=os.environ.get("APP_ENV", "lab"), + database_url=_secret("DATABASE_URL", required=True) or "", + cache_url=cache_url, + session_ttl_seconds=_int("SESSION_TTL_SECONDS", 3600, 1, 30 * 24 * 3600), + session_cache_ttl_seconds=_int("SESSION_CACHE_TTL_SECONDS", 60, 1, 3600), + cache_timeout_seconds=_float("CACHE_TIMEOUT_SECONDS", 0.2, 0.01, 5), + cache_retry_seconds=_float("CACHE_RETRY_SECONDS", 2.0, 0.1, 60), + db_pool_min=min(_int("DB_POOL_MIN", 1, 0, 100), pool_max), + db_pool_max=pool_max, + db_pool_timeout_seconds=_float("DB_POOL_TIMEOUT_SECONDS", 2.0, 0.1, 60), + db_connect_timeout_seconds=_int("DB_CONNECT_TIMEOUT_SECONDS", 3, 1, 60), + db_statement_timeout_ms=_int("DB_STATEMENT_TIMEOUT_MS", 5000, 100, 600000), + request_timeout_seconds=_float("REQUEST_TIMEOUT_SECONDS", 10.0, 1, 120), + max_body_bytes=_int("MAX_BODY_BYTES", 65536, 1024, 1048576), + kdf_concurrency=_int("KDF_CONCURRENCY", 4, 1, 64), + scrypt_log2_n=_int("SCRYPT_LOG2_N", 15, 14, 20), + scrypt_r=_int("SCRYPT_R", 8, 1, 32), + scrypt_p=_int("SCRYPT_P", 3, 1, 16), + # lab3: миграции выполняет отдельный one-shot сервис `migrate`; реплики их только проверяют. + migrate_on_start=os.environ.get("MIGRATE_ON_START", "false").lower() in {"1", "true", "yes"}, + migrate_wait_seconds=_int("MIGRATE_WAIT_SECONDS", 60, 0, 600), + # Непрозрачный alias реплики: случайный на каждый запуск процесса, без hostname/IP. + instance_id=os.environ.get("INSTANCE_ID") or "api-" + secrets.token_hex(4), + instance_id_file=os.environ.get("INSTANCE_ID_FILE", "/tmp/instance-id"), + idempotency_ttl_seconds=_int("IDEMPOTENCY_TTL_SECONDS", 86400, 60, 30 * 24 * 3600), + shutdown_drain_seconds=_float("SHUTDOWN_DRAIN_SECONDS", 3.0, 0, 60), + # lab4: S3 (SeaweedFS). Ключи API — отдельная identity с правами только на свой bucket. + s3_endpoint=os.environ.get("S3_ENDPOINT") or None, + s3_region=os.environ.get("S3_REGION", "us-east-1"), + s3_bucket=os.environ.get("S3_BUCKET", "messenger-attachments"), + s3_access_key=_secret("S3_ACCESS_KEY_ID", required=False), + s3_secret_key=_secret("S3_SECRET_ACCESS_KEY", required=False), + s3_timeout_seconds=_float("S3_TIMEOUT_SECONDS", 30.0, 1, 300), + max_upload_bytes=_int("MAX_UPLOAD_BYTES", 10485760, 1024, 10485760), + max_image_pixels=_int("MAX_IMAGE_PIXELS", 40000000, 1, 40000000), + upload_concurrency=_int("UPLOAD_CONCURRENCY", 16, 1, 256), + upload_timeout_seconds=_float("UPLOAD_TIMEOUT_SECONDS", 120.0, 5, 600), + # Grace period очистки: намерение/объект моложе него не трогаются (загрузка может ещё идти). + upload_grace_seconds=_int("UPLOAD_GRACE_SECONDS", 900, 1, 7 * 24 * 3600), + janitor_interval_seconds=_float("JANITOR_INTERVAL_SECONDS", 60.0, 0.5, 3600), + # Только для тестового сервиса api-fault: внедрение отказа (crash_after_s3_put, + # crash_after_commit_before_publish). + fault_inject=os.environ.get("FAULT_INJECT", ""), + # lab5. URL брокера содержит учётные данные — только из файла-секрета. + broker_url=_secret("BROKER_URL", required=False), + broker_stream=os.environ.get("BROKER_STREAM", "ATTACHMENT_JOBS"), + broker_subject=os.environ.get("BROKER_SUBJECT", "attachments.process.v1"), + broker_consumer=os.environ.get("BROKER_CONSUMER", "attachment-workers"), + # ack_wait брокера = срок аренды сообщения; worker продлевает его (in_progress) каждые ack_wait/4. + broker_ack_wait_seconds=_float("BROKER_ACK_WAIT_SECONDS", 20.0, 2, 600), + broker_max_ack_pending=_int("BROKER_MAX_ACK_PENDING", 16, 1, 10000), + broker_duplicate_window_seconds=_float("BROKER_DUPLICATE_WINDOW_SECONDS", 120.0, 1, 86400), + broker_max_msgs=_int("BROKER_MAX_MSGS", 100000, 100, 10**8), + pipeline_version=_int("PIPELINE_VERSION", 1, 1, 100), + worker_pipelines=tuple(int(x) for x in os.environ.get("WORKER_PIPELINES", "1,2").split(",") if x.strip()), + worker_concurrency=_int("WORKER_CONCURRENCY", 2, 1, 64), + job_max_attempts=_int("JOB_MAX_ATTEMPTS", 5, 1, 100), + job_timeout_seconds=_float("JOB_TIMEOUT_SECONDS", 60.0, 1, 3600), + job_lease_seconds=_float("JOB_LEASE_SECONDS", 20.0, 2, 3600), + job_retry_base_seconds=_float("JOB_RETRY_BASE_SECONDS", 2.0, 0.1, 3600), + job_retry_max_seconds=_float("JOB_RETRY_MAX_SECONDS", 60.0, 0.1, 86400), + job_stuck_seconds=_float("JOB_STUCK_SECONDS", 600.0, 5, 86400), + worker_process_memory_mb=_int("WORKER_PROCESS_MEMORY_MB", 768, 128, 16384), + staging_retention_seconds=_int("STAGING_RETENTION_SECONDS", 86400, 60, 30 * 24 * 3600), + relay_interval_seconds=_float("RELAY_INTERVAL_SECONDS", 1.0, 0.05, 60), + maintenance_interval_seconds=_float("MAINTENANCE_INTERVAL_SECONDS", 5.0, 0.5, 3600), + staging_sweep_seconds=_float("STAGING_SWEEP_SECONDS", 300.0, 5, 86400), + # Учебные хуки отказов worker по маркеру в имени файла (только FAULT_HOOKS=lab; см. REPORT.md). + fault_hooks=os.environ.get("FAULT_HOOKS", ""), + worker_id=os.environ.get("WORKER_ID") or "worker-" + secrets.token_hex(4), + ) diff --git a/src/messenger/db.py b/src/messenger/db.py new file mode 100644 index 00000000..6e321ffb --- /dev/null +++ b/src/messenger/db.py @@ -0,0 +1,146 @@ +"""Пул соединений PostgreSQL, версионируемые миграции и классификация ошибок БД.""" +from __future__ import annotations + +import asyncio +import hashlib +import logging +import time +from datetime import datetime, timezone +from pathlib import Path + +import psycopg +from psycopg import errors as pg_errors +from psycopg.rows import dict_row +from psycopg_pool import AsyncConnectionPool, PoolTimeout + +from . import telemetry +from .config import Settings + +log = logging.getLogger("messenger.db") + +MIGRATIONS_DIR = Path(__file__).resolve().parents[2] / "migrations" +MIGRATION_LOCK_ID = 2026_0202 # pg_advisory_lock: параллельные реплики не применяют миграции дважды + + +_TRACED_CURSOR = telemetry.make_traced_cursor() +_TRACED_CONNECTION = telemetry.make_traced_connection() + + +def connection_kwargs(settings: Settings) -> dict: + options = ( + f"-c statement_timeout={settings.db_statement_timeout_ms} " + "-c lock_timeout=2000 " + "-c idle_in_transaction_session_timeout=10000 " + "-c TimeZone=UTC" + ) + return { + "connect_timeout": settings.db_connect_timeout_seconds, + "application_name": "messenger-api", + "options": options, + "row_factory": dict_row, + # lab6: client span (если есть родительский span) и histogram db.client.operation.duration + "cursor_factory": _TRACED_CURSOR, + } + + +class TracedPool(AsyncConnectionPool): + """Пул с span «pool.acquire» (внутри trace): ожидание свободного соединения видно отдельно от + времени запросов — так в trace различаются «БД медленно отвечает» и «пул БД исчерпан».""" + + async def getconn(self, timeout=None): + with telemetry.child_span("pool.acquire", attributes={"db.client.connection.pool.name": self.name}): + return await super().getconn(timeout) + + +def make_pool(settings: Settings) -> AsyncConnectionPool: + return TracedPool( + conninfo=settings.database_url, + connection_class=_TRACED_CONNECTION, # COMMIT — отдельный span/операция в histogram + kwargs=connection_kwargs(settings), + min_size=settings.db_pool_min, + max_size=settings.db_pool_max, + timeout=settings.db_pool_timeout_seconds, # ожидание свободного соединения + max_waiting=200, # очередь ожидания ограничена + max_idle=300, + reconnect_timeout=30, + check=AsyncConnectionPool.check_connection, # после рестарта PG битые соединения отбрасываются + open=False, + name="messenger", + ) + + +def is_unavailable(exc: BaseException) -> bool: + """Ошибки, означающие «зависимость недоступна/перегружена», а не баг приложения.""" + if isinstance(exc, (PoolTimeout, psycopg.OperationalError, asyncio.TimeoutError, ConnectionError)): + return True + return isinstance(exc, (pg_errors.QueryCanceled, pg_errors.LockNotAvailable, + pg_errors.AdminShutdown, pg_errors.CannotConnectNow)) + + +def iso(ts: datetime) -> str: + """RFC 3339 UTC с микросекундами и суффиксом Z (точность timestamptz в PostgreSQL).""" + return ts.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ") + + +def _migration_files() -> list[tuple[str, str, str]]: + result = [] + for path in sorted(MIGRATIONS_DIR.glob("[0-9][0-9][0-9][0-9]_*.sql")): + sql = path.read_text(encoding="utf-8") + result.append((path.stem, sql, hashlib.sha256(sql.encode()).hexdigest())) + return result + + +async def migrate(settings: Settings) -> list[str]: + """Применяет недостающие миграции. Повторный запуск — no-op; изменённая применённая миграция — + ошибка (миграции неизменяемы, исправления — новой версией).""" + applied_now: list[str] = [] + async with await psycopg.AsyncConnection.connect( + settings.database_url, autocommit=True, **connection_kwargs(settings)) as conn: + await conn.execute("SELECT pg_advisory_lock(%s)", (MIGRATION_LOCK_ID,)) + try: + await conn.execute( + "CREATE TABLE IF NOT EXISTS schema_migrations (" + " version text PRIMARY KEY, checksum text NOT NULL," + " applied_at timestamptz NOT NULL DEFAULT clock_timestamp())") + rows = await (await conn.execute("SELECT version, checksum FROM schema_migrations")).fetchall() + done = {r["version"]: r["checksum"] for r in rows} + for version, sql, checksum in _migration_files(): + if version in done: + if done[version] != checksum: + raise RuntimeError(f"applied migration {version} was modified") + continue + async with conn.transaction(): + await conn.execute(sql) + await conn.execute( + "INSERT INTO schema_migrations (version, checksum) VALUES (%s, %s)", + (version, checksum)) + applied_now.append(version) + log.info("migration applied", extra={"version": version}) + finally: + await conn.execute("SELECT pg_advisory_unlock(%s)", (MIGRATION_LOCK_ID,)) + return applied_now + + +async def schema_status(pool) -> tuple[bool, list[str]]: + """Совместима ли схема с этим кодом: применены все известные ему миграции с теми же checksum. + Более новые миграции (expand-фаза следующей версии) допустимы.""" + async with pool.connection() as conn: + rows = await (await conn.execute( + "SELECT version, checksum FROM schema_migrations")).fetchall() + done = {r["version"]: r["checksum"] for r in rows} + missing = [v for v, _, c in _migration_files() if done.get(v) != c] + return not missing, missing + + +async def migrate_with_wait(settings: Settings) -> list[str]: + deadline = time.monotonic() + settings.migrate_wait_seconds + delay = 0.5 + while True: + try: + return await migrate(settings) + except psycopg.OperationalError: + if time.monotonic() >= deadline: + raise + log.warning("database not reachable yet; retrying migrations") + await asyncio.sleep(delay) + delay = min(delay * 2, 5) diff --git a/src/messenger/errors.py b/src/messenger/errors.py new file mode 100644 index 00000000..856d98fd --- /dev/null +++ b/src/messenger/errors.py @@ -0,0 +1,67 @@ +"""Единый формат ошибок API: {"error":{"code","message","request_id"}}.""" +from __future__ import annotations + +BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"' +BEARER_CHALLENGE = 'Bearer realm="messenger"' + +_STATUS = { + "invalid_request": 400, + "unauthorized": 401, + "not_found": 404, + "method_not_allowed": 405, + "conflict": 409, + "payload_too_large": 413, + "unsupported_media_type": 415, + "rate_limited": 429, + "internal_error": 500, + "unavailable": 503, +} + +_DEFAULT_MESSAGE = { + "invalid_request": "Некорректный запрос", + "unauthorized": "Требуется действительная аутентификация", + "not_found": "Объект не найден", + "conflict": "Конфликт состояния", + "payload_too_large": "Слишком большой запрос", + "unsupported_media_type": "Неподдерживаемый тип содержимого", + "rate_limited": "Слишком много запросов", + "internal_error": "Внутренняя ошибка", + "unavailable": "Сервис временно недоступен", +} + + +class ApiError(Exception): + def __init__(self, code: str, message: str | None = None, *, challenge: str | None = None, + headers: dict[str, str] | None = None): + super().__init__(code) + self.code = code + self.status = _STATUS[code] + self.message = message or _DEFAULT_MESSAGE.get(code, "Ошибка") + self.headers = dict(headers or {}) + if challenge: + self.headers["WWW-Authenticate"] = challenge + + @property + def public_code(self) -> str: + # 405 не входит в enum контракта: отдаём invalid_request с корректным HTTP-статусом. + return "invalid_request" if self.code == "method_not_allowed" else self.code + + +def invalid(message: str) -> ApiError: + return ApiError("invalid_request", message) + + +def unauthorized_bearer() -> ApiError: + return ApiError("unauthorized", challenge=BEARER_CHALLENGE) + + +def unauthorized_basic() -> ApiError: + return ApiError("unauthorized", "Неверные учётные данные", challenge=BASIC_CHALLENGE) + + +def not_found() -> ApiError: + return ApiError("not_found") + + +def unavailable() -> ApiError: + return ApiError("unavailable", headers={"Retry-After": "1"}) diff --git a/src/messenger/imagecheck.py b/src/messenger/imagecheck.py new file mode 100644 index 00000000..f5c2a194 --- /dev/null +++ b/src/messenger/imagecheck.py @@ -0,0 +1,307 @@ +"""Потоковая проверка PNG/JPEG без декодирования в память. + +Валидатор получает байты кусками (как они приходят от клиента), держит O(64 КиБ) состояния и +бросает ImageRejected как можно раньше: + * формат определяется по содержимому (magic), а не по Content-Type/filename; + * размеры берутся из IHDR (PNG) / SOF (JPEG): превышение MAX_IMAGE_PIXELS → 413 ещё до чтения + пиксельных данных — «бомба» не распаковывается; + * PNG: проверяются CRC всех чанков, порядок IHDR…IDAT…IEND, допустимые bit depth/color type, + поток IDAT реально распаковывается zlib по частям (вывод выбрасывается), объём распакованных + данных обязан совпасть с ожидаемым по размерам — повреждение и «бомбы» отсекаются; + * JPEG: структура маркеров до SOS, entropy-coded данные сканируются до EOI (RST/stuffing), + обязателен SOF с ненулевыми размерами и EOI в конце. Полное Huffman-декодирование не выполняется: + «заведомо повреждённые» (обрезанные, мусор, неверные сегменты) отклоняются, тонкие ошибки внутри + entropy-потока — нет (ограничение описано в REPORT.md). +""" +from __future__ import annotations + +import struct +import zlib + +PNG_SIG = b"\x89PNG\r\n\x1a\n" +PNG_COLOR = {0: (1, {1, 2, 4, 8, 16}), 2: (3, {8, 16}), 3: (1, {1, 2, 4, 8}), 4: (2, {8, 16}), 6: (4, {8, 16})} +JPEG_SOF = {0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF} +MAX_SEGMENT = 1 << 24 + + +class ImageRejected(Exception): + def __init__(self, kind: str, message: str): + super().__init__(message) + self.kind = kind # "too_large" → 413, "invalid" → 415 + + +def sniff(head: bytes) -> str | None: + if head.startswith(PNG_SIG): + return "image/png" + if head.startswith(b"\xff\xd8\xff"): + return "image/jpeg" + return None + + +def _bad(msg): + return ImageRejected("invalid", msg) + + +class _Buf: + """Маленький буфер «нужно N байт»; крупные данные проходят мимо через take_upto().""" + + def __init__(self): + self.data = bytearray() + + def feed(self, b): + self.data += b + + def take(self, n): + if len(self.data) < n: + return None + out = bytes(self.data[:n]) + del self.data[:n] + return out + + def take_upto(self, n): + out = bytes(self.data[:n]) + del self.data[:len(out)] + return out + + +class PngValidator: + def __init__(self, max_pixels: int): + self.max_pixels, self.buf = max_pixels, _Buf() + self.state, self.width, self.height = "sig", None, None + self.chunk_type, self.remaining, self.crc = None, 0, 0 + self.seen_idat = self.seen_iend = self.seen_plte = False + self.idat_done = False + self.expected_raw = 0 + self.decompressed = 0 + self.z = zlib.decompressobj() + + def _ihdr(self, data): + if len(data) != 13: + raise _bad("bad IHDR") + w, h, depth, ctype, comp, flt, interlace = struct.unpack(">IIBBBBB", data) + if not (0 < w < 2**31 and 0 < h < 2**31) or ctype not in PNG_COLOR or depth not in PNG_COLOR[ctype][1] \ + or comp != 0 or flt != 0 or interlace not in (0, 1): + raise _bad("bad IHDR fields") + if w * h > self.max_pixels: + raise ImageRejected("too_large", "image has %d pixels" % (w * h)) + self.width, self.height, self.ctype = w, h, ctype + bpp = PNG_COLOR[ctype][0] * depth + rowbytes = lambda width: (width * bpp + 7) // 8 # noqa: E731 + if interlace == 0: + self.expected_raw = h * (1 + rowbytes(w)) + else: + total = 0 + for xs, ys, dx, dy in ((0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4), (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2)): + pw, ph = (w - xs + dx - 1) // dx, (h - ys + dy - 1) // dy + if pw > 0 and ph > 0: + total += ph * (1 + rowbytes(pw)) + self.expected_raw = total + + def _inflate(self, data): + if self.idat_done: + raise _bad("IDAT chunks are not contiguous") + pending = data + while pending: + out = self.z.decompress(pending, 1 << 20) # не больше 1 МиБ за шаг — RAM ограничена + self.decompressed += len(out) + if self.decompressed > self.expected_raw: + raise _bad("image data larger than declared dimensions") + pending = self.z.unconsumed_tail + if self.z.eof and (pending or self.z.unused_data): + raise _bad("trailing data after zlib stream") + + def feed(self, chunk: bytes): + self.buf.feed(chunk) + while True: + if self.state == "sig": + sig = self.buf.take(8) + if sig is None: + return + if sig != PNG_SIG: + raise _bad("not a PNG") + self.state = "hdr" + elif self.state == "hdr": + hdr = self.buf.take(8) + if hdr is None: + return + if self.seen_iend: + raise _bad("data after IEND") + length, ctype = struct.unpack(">I4s", hdr) + if length > MAX_SEGMENT or not ctype.isalpha(): + raise _bad("bad chunk header") + if self.width is None and ctype != b"IHDR": + raise _bad("IHDR must be first") + if ctype != b"IDAT" and self.seen_idat: + self.idat_done = True + self.chunk_type, self.remaining, self.crc = ctype, length, zlib.crc32(ctype) + self.small = bytearray() if ctype in (b"IHDR", b"PLTE") else None + self.state = "data" + elif self.state == "data": + piece = self.buf.take_upto(self.remaining) + if not piece and self.remaining: + return + self.remaining -= len(piece) + self.crc = zlib.crc32(piece, self.crc) + if self.small is not None: + self.small += piece + if self.chunk_type == b"IDAT": + if self.width is None or (self.ctype == 3 and not self.seen_plte): + raise _bad("IDAT before IHDR/PLTE") + self.seen_idat = True + self._inflate(piece) + if self.remaining == 0: + self.state = "crc" + elif self.state == "crc": + crc = self.buf.take(4) + if crc is None: + return + if struct.unpack(">I", crc)[0] != self.crc & 0xFFFFFFFF: + raise _bad("chunk CRC mismatch") + if self.chunk_type == b"IHDR": + if self.width is not None: + raise _bad("duplicate IHDR") + self._ihdr(bytes(self.small)) + elif self.chunk_type == b"PLTE": + self.seen_plte = True + elif self.chunk_type == b"IEND": + self.seen_iend = True + self.state = "hdr" + + def finish(self): + if self.buf.data or self.state != "hdr" or not self.seen_iend: + raise _bad("truncated PNG") + if not self.seen_idat or not self.z.eof or self.decompressed != self.expected_raw: + raise _bad("incomplete or corrupt image data") + return self.width, self.height + + +class JpegValidator: + def __init__(self, max_pixels: int): + self.max_pixels, self.buf = max_pixels, _Buf() + self.state, self.width, self.height = "soi", None, None + self.remaining, self.marker, self.seg = 0, None, None + self.seen_eoi = False + self.prev_ff = False + self.trailing = 0 + + def _sof(self, data): + if len(data) < 6: + raise _bad("bad SOF") + _prec, h, w, ncomp = struct.unpack(">BHHB", data[:6]) + if h == 0 or w == 0 or ncomp not in (1, 3, 4) or len(data) < 6 + 3 * ncomp: + raise _bad("bad SOF fields") + if w * h > self.max_pixels: + raise ImageRejected("too_large", "image has %d pixels" % (w * h)) + self.width, self.height = w, h + + def feed(self, chunk: bytes): + self.buf.feed(chunk) + while True: + if self.state == "soi": + b = self.buf.take(2) + if b is None: + return + if b != b"\xff\xd8": + raise _bad("not a JPEG") + self.state = "marker" + elif self.state == "marker": + d = self.buf.data + i = 0 + while i < len(d) and d[i] == 0xFF and i + 1 < len(d) and d[i + 1] == 0xFF: + i += 1 # fill bytes + del d[:i] + b = self.buf.take(2) + if b is None: + return + if b[0] != 0xFF: + raise _bad("marker expected") + m = b[1] + if m == 0xD9: + if self.width is None: + raise _bad("EOI before SOF") + self.seen_eoi, self.state = True, "trailing" + elif m in (0x01,) or 0xD0 <= m <= 0xD7: + continue + elif m in (0xD8, 0x00): + raise _bad("unexpected marker") + else: + self.marker, self.state = m, "len" + elif self.state == "len": + b = self.buf.take(2) + if b is None: + return + length = struct.unpack(">H", b)[0] + if length < 2: + raise _bad("bad segment length") + self.remaining = length - 2 + keep = self.marker in JPEG_SOF or self.marker == 0xDA + self.seg = bytearray() if keep else None + self.state = "seg" + elif self.state == "seg": + piece = self.buf.take_upto(self.remaining) + if not piece and self.remaining: + return + self.remaining -= len(piece) + if self.seg is not None: + self.seg += piece + if self.remaining == 0: + if self.marker in JPEG_SOF: + if self.width is not None: + raise _bad("duplicate SOF") + self._sof(bytes(self.seg)) + self.state = "marker" + elif self.marker == 0xDA: + if self.width is None: + raise _bad("SOS before SOF") + self.state, self.prev_ff = "scan", False + else: + self.state = "marker" + elif self.state == "scan": + d = self.buf.data + if not d: + return + i = 0 + n = len(d) + while i < n: + if self.prev_ff: + x = d[i] + self.prev_ff = False + if x == 0x00 or 0xD0 <= x <= 0xD7: + i += 1 + continue + if x == 0xFF: + self.prev_ff = True + i += 1 + continue + # конец entropy-данных: вернуть "FF xx" для разбора маркера + del d[:i - 1] + self.state = "marker" + break + j = d.find(b"\xff", i) + if j < 0: + i = n + break + self.prev_ff, i = True, j + 1 + else: + pass + if self.state == "scan": + keep = 1 if self.prev_ff else 0 + del d[:n - keep] + if keep: + self.prev_ff = False # байт FF оставлен в буфере, разберём при следующей порции + return + elif self.state == "trailing": + self.trailing += len(self.buf.data) + self.buf.data.clear() + if self.trailing > 1 << 20: + raise _bad("too much data after EOI") + return + + def finish(self): + if not self.seen_eoi: + raise _bad("truncated JPEG (no EOI)") + return self.width, self.height + + +def validator_for(content_type: str, max_pixels: int): + return PngValidator(max_pixels) if content_type == "image/png" else JpegValidator(max_pixels) diff --git a/src/messenger/imgproc.py b/src/messenger/imgproc.py new file mode 100644 index 00000000..f5be0ae1 --- /dev/null +++ b/src/messenger/imgproc.py @@ -0,0 +1,156 @@ +"""Обработка одного изображения в ОТДЕЛЬНОМ процессе с жёсткими лимитами ядра. + + python -m messenger.imgproc + stdin — байты оригинала (≤ MAX_UPLOAD_BYTES; размер и SHA-256 уже проверены worker) + stdout — строка JSON-заголовка, затем байты вариантов подряд (длины — в заголовке) + exit 0 — успех; 3 — изображение отвергнуто (JSON с kind); иное/сигнал — сбой процесса + +Лимиты: RLIMIT_AS (память процесса), RLIMIT_CPU (процессорное время), число пикселей — по заголовку +ДО декодирования; worker дополнительно ограничивает время на стене (kill по таймауту). Поэтому +«бомба» или зависший декодер не роняют и не блокируют сам worker. + +Правила вариантов (contracts/README.md), pipeline v1: + thumbnail — JPEG, вписан в 256×256 без увеличения, размеры округляются вниз (min 1 px), + EXIF orientation применяется, alpha компонуется на белый; quality 85; + crop — JPEG, центрированный квадрат 128×128 (маленькие исходники увеличиваются); quality 85; + optimized — WebP, вписан в 1280×1280 без увеличения, quality 80, method 4; alpha сохраняется. +Во все варианты не копируются EXIF/XMP/ICC (метаданные удаляются). Версия 2 (трек 2) отличается +параметрами качества и лёгким повышением резкости thumbnail — другой ключ эффекта, другие объекты. +""" +from __future__ import annotations + +import hashlib +import io +import json +import resource +import sys + +PIPELINES = { + 1: {"thumb_quality": 85, "crop_quality": 85, "webp_quality": 80, "sharpen": False}, + 2: {"thumb_quality": 90, "crop_quality": 88, "webp_quality": 75, "sharpen": True}, +} +VARIANT_EXT = {"thumbnail": "jpg", "crop": "jpg", "optimized": "webp"} +ROTATING = {5, 6, 7, 8} # EXIF orientation с поворотом на 90°: ширина и высота меняются местами + + +class Rejected(Exception): + def __init__(self, kind: str, detail: str): + super().__init__(detail) + self.kind = kind + + +def fit(w: int, h: int, box: int) -> tuple[int, int]: + """Вписать в квадрат box без увеличения; округление вниз, минимум 1 px (целочисленно, без + ошибок плавающей точки): 320×200 → 256×160.""" + m = max(w, h) + if m <= box: + return w, h + return max(1, w * box // m), max(1, h * box // m) + + +def _flatten_on_white(im): + from PIL import Image + if im.mode in ("RGBA", "LA") or (im.mode == "P" and "transparency" in im.info): + rgba = im.convert("RGBA") + bg = Image.new("RGB", rgba.size, (255, 255, 255)) + bg.paste(rgba, mask=rgba.getchannel("A")) + return bg + return im.convert("RGB") + + +def _normalize_mode(im): + """16-битные/целочисленные режимы PNG → 8 бит (convert('L') их бы просто обрезал).""" + if im.mode in ("I;16", "I;16B", "I;16L", "I"): + return im.point(lambda v: v * (1 / 256)).convert("L") + return im + + +def process(data: bytes, max_pixels: int, version: int) -> list[tuple[dict, bytes]]: + from PIL import Image, ImageFilter, ImageOps, UnidentifiedImageError + params = PIPELINES[version] + Image.MAX_IMAGE_PIXELS = max_pixels # Pillow: > 2× — DecompressionBombError + try: + im = Image.open(io.BytesIO(data)) + if im.format not in ("PNG", "JPEG"): + raise Rejected("invalid_image", "unsupported format") + w, h = im.size + if w * h > max_pixels: # по заголовку, до декодирования пикселей + raise Rejected("too_large", "image has %d pixels" % (w * h)) + orientation = im.getexif().get(0x0112, 1) + lw, lh = (h, w) if orientation in ROTATING else (w, h) # логический размер после поворота + if im.format == "JPEG": + # Декодировать сразу в уменьшенном масштабе (1/2…1/8), если хватает для крупнейшего варианта: + # меньше памяти и времени на больших фото. + im.draft("RGB", (1280, 1280)) + im.load() + im = ImageOps.exif_transpose(im) + im = _normalize_mode(im) + except Rejected: + raise + except Image.DecompressionBombError as exc: + raise Rejected("too_large", str(exc)[:120]) from exc + except (UnidentifiedImageError, OSError, SyntaxError, ValueError, EOFError, IndexError, TypeError) as exc: + raise Rejected("invalid_image", "%s: %s" % (type(exc).__name__, str(exc)[:100])) from exc + + has_alpha = im.mode in ("RGBA", "LA", "PA") or (im.mode == "P" and "transparency" in im.info) + # Рабочая копия ≤ 1280 по большей стороне; исходный большой кадр сразу освобождается. + ow, oh = fit(lw, lh, 1280) + work = im.convert("RGBA" if has_alpha else "RGB") + if work.size != (ow, oh): + work = work.resize((ow, oh), Image.LANCZOS, reducing_gap=3.0) + del im + results = [] + + # optimized: WebP, alpha сохраняется, метаданные не передаются + buf = io.BytesIO() + work.save(buf, "WEBP", quality=params["webp_quality"], method=4) + results.append(({"name": "optimized", "content_type": "image/webp", "width": ow, "height": oh}, buf.getvalue())) + + flat = _flatten_on_white(work) + # thumbnail: размеры — от логического размера оригинала (не от уменьшенной draft-копии) + tw, th = fit(lw, lh, 256) + thumb = flat.resize((tw, th), Image.LANCZOS) if flat.size != (tw, th) else flat.copy() + if params["sharpen"]: + thumb = thumb.filter(ImageFilter.UnsharpMask(radius=1, percent=60, threshold=2)) + buf = io.BytesIO() + thumb.save(buf, "JPEG", quality=params["thumb_quality"], optimize=True) + results.append(({"name": "thumbnail", "content_type": "image/jpeg", "width": tw, "height": th}, buf.getvalue())) + + # crop: центрированный квадрат 128×128 (увеличение маленьких исходников допускается) + crop = ImageOps.fit(flat, (128, 128), Image.LANCZOS, centering=(0.5, 0.5)) + buf = io.BytesIO() + crop.save(buf, "JPEG", quality=params["crop_quality"], optimize=True) + results.append(({"name": "crop", "content_type": "image/jpeg", "width": 128, "height": 128}, buf.getvalue())) + + for meta, body in results: + meta["size_bytes"] = len(body) + meta["sha256"] = hashlib.sha256(body).hexdigest() + return results + + +def main(argv) -> int: + max_pixels, memory_mb, cpu_seconds, version = (int(x) for x in argv[:4]) + # Лимиты ставятся ДО чтения данных и импорта Pillow — действуют на весь процесс обработки. + resource.setrlimit(resource.RLIMIT_AS, (memory_mb << 20, memory_mb << 20)) + resource.setrlimit(resource.RLIMIT_CPU, (cpu_seconds, cpu_seconds + 1)) + out = sys.stdout.buffer + try: + if version not in PIPELINES: + raise Rejected("unsupported_pipeline", "pipeline %d unknown" % version) + data = sys.stdin.buffer.read() + results = process(data, max_pixels, version) + except Rejected as exc: + out.write(json.dumps({"ok": False, "kind": exc.kind, "detail": str(exc)[:200]}).encode() + b"\n") + return 3 + except MemoryError: + out.write(json.dumps({"ok": False, "kind": "resource_limit", "detail": "memory limit exceeded"}).encode() + b"\n") + return 3 + out.write(json.dumps({"ok": True, "variants": [m for m, _ in results]}).encode() + b"\n") + for _, body in results: + out.write(body) + out.flush() + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/src/messenger/invariants.py b/src/messenger/invariants.py new file mode 100644 index 00000000..1761e4f8 --- /dev/null +++ b/src/messenger/invariants.py @@ -0,0 +1,142 @@ +"""Проверка инвариантов pipeline (трек 2): python -m messenger jobs invariants [--settled] [--verify-bytes]. + +Инварианты проверяются по состоянию PostgreSQL, журналу job_events и содержимому S3: + I1 принятая работа не теряется: у каждого вложения есть работа; при --settled нет незавершённых + (queued/processing) работ и вложений — каждая дошла до ready/failed/superseded; + I2 один набор вариантов на ключ эффекта: у ready-работы ровно {thumbnail, crop, optimized} её версии, + каждый S3-объект существует с тем же размером (и SHA-256 при --verify-bytes); + I3 результат фиксировался ровно один раз: на каждую ready-работу — ровно одно событие committed, + у superseded/failed/queued — ни одного; + I4 указатель опубликованной версии монотонен: последовательность published_version_changed по + вложению строго возрастает, а текущий published_version = максимум версий ready-работ; + I5 ready не откатывается: после committed по работе нет claimed/lease_takeover/retry_scheduled/failed; + у вложения с published_version статус ready; + I6 fencing: варианты записаны тем lease_token, с которым зафиксирован committed, и это последний + выданный работе токен; + I7 нет «осиротевших» результатов: каждый объект под originals/ и variants/ известен БД; при --settled + staging готовых вложений удалён. +""" +from __future__ import annotations + +from collections import defaultdict + +EXPECTED_VARIANTS = {"thumbnail", "crop", "optimized"} + + +async def check(pool, s3, settings, *, settled: bool, verify_bytes: bool, since=None) -> dict: + v = defaultdict(list) # нарушение → примеры + stats = {} + where = " WHERE a.created_at >= %s" if since else "" + args = (since,) if since else () + async with pool.connection() as conn: + atts = {r["id"]: r for r in await (await conn.execute( + "SELECT a.* FROM attachments a" + where, args)).fetchall()} + jobs = await (await conn.execute( + "SELECT j.* FROM attachment_jobs j JOIN attachments a ON a.id = j.attachment_id" + where, args)).fetchall() + variants = await (await conn.execute( + "SELECT v.* FROM attachment_variants v JOIN attachments a ON a.id = v.attachment_id" + where, args)).fetchall() + events = await (await conn.execute( + "SELECT e.* FROM job_events e JOIN attachments a ON a.id = e.attachment_id" + where + " ORDER BY e.id", + args)).fetchall() + intents = {r["object_key"] for r in await (await conn.execute("SELECT object_key FROM upload_intents")).fetchall()} + stats.update(attachments=len(atts), jobs=len(jobs), variants=len(variants), events=len(events)) + by_job = defaultdict(list) + for e in events: + by_job[e["job_id"]].append(e) + jobs_by_att = defaultdict(list) + for j in jobs: + jobs_by_att[j["attachment_id"]].append(j) + var_by_effect = defaultdict(dict) + for x in variants: + var_by_effect[(x["attachment_id"], x["pipeline_version"])][x["name"]] = x + + # I1 + for aid, a in atts.items(): + if aid not in jobs_by_att and a["object_key"].startswith("originals/"): + v["I1_accepted_without_job"].append(str(aid)) + if settled and a["status"] in ("queued", "processing"): + v["I1_attachment_not_terminal"].append(str(aid)) + for j in jobs: + if settled and j["status"] in ("queued", "processing"): + v["I1_job_not_terminal"].append(str(j["job_id"])) + stats["job_status"] = dict(_count(j["status"] for j in jobs)) + stats["attachment_status"] = dict(_count(a["status"] for a in atts.values())) + + # I2 + I3 + I5 + I6 + for j in jobs: + evs = by_job[j["job_id"]] + commits = [e for e in evs if e["event"] == "committed"] + if j["status"] == "ready": + if len(commits) != 1: + v["I3_ready_commit_count_not_1"].append("%s:%d" % (j["job_id"], len(commits))) + got = var_by_effect.get((j["attachment_id"], j["pipeline_version"]), {}) + if set(got) != EXPECTED_VARIANTS: + v["I2_variant_set_mismatch"].append("%s:%s" % (j["job_id"], sorted(got))) + if commits: + tok = commits[0]["lease_token"] + if any(x["lease_token"] != tok for x in got.values()): + v["I6_variant_token_mismatch"].append(str(j["job_id"])) + if tok != j["lease_token"]: + v["I6_commit_not_last_token"].append(str(j["job_id"])) + after = [e["event"] for e in evs if e["id"] > commits[0]["id"]] + bad = [x for x in after if x in ("claimed", "lease_takeover", "retry_scheduled", "failed")] + if bad: + v["I5_activity_after_commit"].append("%s:%s" % (j["job_id"], bad)) + elif commits: + v["I3_commit_on_non_ready_job"].append("%s:%s" % (j["job_id"], j["status"])) + + # I4 + I5 (уровень вложения) + for aid, a in atts.items(): + changes = [e["detail"]["to"] for e in events if e["attachment_id"] == aid and e["event"] == "published_version_changed"] + if any(b <= x for x, b in zip(changes, changes[1:])): + v["I4_published_version_not_monotonic"].append("%s:%s" % (aid, changes)) + ready_versions = [j["pipeline_version"] for j in jobs_by_att[aid] if j["status"] == "ready"] + if ready_versions and a["published_version"] != max(ready_versions): + v["I4_pointer_not_max_ready"].append("%s:%s/%s" % (aid, a["published_version"], max(ready_versions))) + if a["published_version"] is not None and a["status"] != "ready": + v["I5_published_but_not_ready"].append(str(aid)) + + # I2 (S3) + I7 + if s3 is not None: + bucket = settings.s3_bucket + known = {a["object_key"] for a in atts.values()} | {x["object_key"] for x in variants} + all_known = known | {a["staging_key"] for a in atts.values() if a["staging_key"]} | intents + listed = {} + for prefix in ("originals/", "variants/", "staging/"): + async for o in s3.list_objects(bucket, prefix): + listed[o.key] = o.size + stats["s3_objects"] = len(listed) + if since is None: + for key in listed: + if key.startswith(("originals/", "variants/")) and key not in known: + v["I7_orphan_object"].append(key) + for x in variants: + if x["object_key"] not in listed: + v["I2_variant_object_missing"].append(x["object_key"]) + elif listed[x["object_key"]] != x["size_bytes"]: + v["I2_variant_size_mismatch"].append(x["object_key"]) + elif verify_bytes: + import hashlib + resp = await s3.get_object_stream(bucket, x["object_key"]) + h = hashlib.sha256(await resp.aread()) + await resp.aclose() + if h.hexdigest() != x["sha256"]: + v["I2_variant_checksum_mismatch"].append(x["object_key"]) + for a in atts.values(): + if a["status"] == "ready" and a["object_key"] not in listed: + v["I2_original_missing"].append(str(a["id"])) + if settled and a["status"] == "ready" and a["staging_key"]: + v["I7_staging_not_cleaned"].append(str(a["id"])) + if settled and since is None: + for key in listed: + if key.startswith("staging/") and key not in all_known: + v["I7_orphan_staging"].append(key) + return {"ok": not v, "violations": {k: vals[:10] for k, vals in v.items()}, + "violation_counts": {k: len(vals) for k, vals in v.items()}, "stats": stats} + + +def _count(it): + out = defaultdict(int) + for x in it: + out[x] += 1 + return sorted(out.items()) diff --git a/src/messenger/jobs.py b/src/messenger/jobs.py new file mode 100644 index 00000000..b56e6070 --- /dev/null +++ b/src/messenger/jobs.py @@ -0,0 +1,392 @@ +"""Задания обработки вложений: схема сообщения, transactional outbox, relay, retry/backoff, replay, +обслуживание (истёкшие lease, «застрявшие» задания, очистка staging). Общая часть для API и worker. + +Источник истины о работе — PostgreSQL (attachment_jobs). Брокер — транспорт с at-least-once +доставкой: потерянное/повторное/устаревшее сообщение не меняет результата, потому что каждое решение +worker принимает по состоянию job в БД под блокировкой строки. +""" +from __future__ import annotations + +import datetime as dt +import json +import logging +import random +import re +import time +import uuid + +from opentelemetry.trace import SpanKind + +from . import telemetry +from .broker import BrokerUnavailable + +log = logging.getLogger("messenger.jobs") + +JOB_TYPE = "attachment.process.v1" +SCHEMA_VERSION = 1 +MAINTENANCE_LOCK_ID = 2026_0505 +UUID_FIELDS = ("job_id", "attachment_id") + + +# ------------------------------------------------------------------------------------- сообщения +def job_message(job_id, attachment_id, pipeline_version: int, attempt: int, trace_context: dict | None = None) -> dict: + """Сообщение по contracts/jobs.schema.json: только идентификаторы и служебные поля. + traceparent/tracestate (W3C) — контекст span «create» в trace загрузки (lab6): так задание и его + повторы остаются в trace исходного upload. Нет активного trace (telemetry выключена) — поля нет.""" + msg = {"schema_version": SCHEMA_VERSION, "job_id": str(job_id), "type": JOB_TYPE, + "attachment_id": str(attachment_id), "pipeline_version": int(pipeline_version), + "attempt": int(attempt), + "created_at": dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")} + for k in ("traceparent", "tracestate"): + v = (trace_context or {}).get(k) + if v and (k != "traceparent" or _TRACEPARENT.fullmatch(v)) and len(v) <= 512: + msg[k] = v + return msg + + +_TRACEPARENT = re.compile(r"00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}") + + +class InvalidMessage(ValueError): + pass + + +def parse_message(raw: bytes) -> dict: + """Строгая проверка по jobs.schema.json (без внешних библиотек). Ошибка → InvalidMessage.""" + try: + data = json.loads(raw) + except (ValueError, UnicodeDecodeError) as exc: + raise InvalidMessage("not JSON") from exc + if not isinstance(data, dict): + raise InvalidMessage("not an object") + required = {"schema_version", "job_id", "type", "attachment_id", "pipeline_version", "attempt", "created_at"} + allowed = required | {"traceparent", "tracestate"} + if not required <= data.keys() or not data.keys() <= allowed: + raise InvalidMessage("unexpected or missing fields") + if data["schema_version"] != SCHEMA_VERSION or data["type"] != JOB_TYPE: + raise InvalidMessage("unsupported schema/type") + for f in UUID_FIELDS: + try: + uuid.UUID(str(data[f])) + except (ValueError, TypeError) as exc: + raise InvalidMessage(f + " is not a UUID") from exc + for f in ("pipeline_version", "attempt"): + if not isinstance(data[f], int) or isinstance(data[f], bool) or data[f] < 1: + raise InvalidMessage(f + " must be integer >= 1") + if not isinstance(data["created_at"], str): + raise InvalidMessage("created_at must be a string") + if "traceparent" in data and not (isinstance(data["traceparent"], str) and _TRACEPARENT.fullmatch(data["traceparent"])): + raise InvalidMessage("traceparent must match W3C format") + if "tracestate" in data and not (isinstance(data["tracestate"], str) and len(data["tracestate"]) <= 512): + raise InvalidMessage("tracestate must be a string <= 512") + return data + + +def backoff_delay(attempt: int, base: float, cap: float) -> float: + """Экспоненциальный backoff с «equal jitter»: половина окна гарантирована, половина случайна. + Повтор 1 → [b/2, b], 2 → [b, 2b], 3 → [2b, 4b] …, не больше cap. Jitter разносит повторы + многих заданий, упавших одновременно (например, при недоступности S3), во времени.""" + window = min(cap, base * (2 ** max(0, attempt - 1))) + return window / 2 + random.uniform(0, window / 2) + + +# ------------------------------------------------------------------------------------- события +async def add_event(conn, job: dict, event: str, *, attempt=None, token=None, worker=None, detail=None) -> None: + await conn.execute( + "INSERT INTO job_events (job_id, attachment_id, pipeline_version, event, attempt, lease_token, worker, detail)" + " VALUES (%s, %s, %s, %s, %s, %s, %s, %s)", + (job["job_id"], job["attachment_id"], job["pipeline_version"], event, + attempt if attempt is not None else job.get("attempt"), token, worker, + json.dumps(detail, ensure_ascii=False) if detail is not None else None)) + + +async def add_outbox(conn, settings, job: dict, attempt: int, delay_seconds: float = 0.0) -> int: + """Строка outbox новой попытки. Контекст trace — текущий span (create/retry/requeue) или, если его + нет (операторская команда без telemetry), сохранённый в job контекст прежней попытки.""" + ctx = telemetry.inject() or (job.get("trace_context") or {}) + payload = job_message(job["job_id"], job["attachment_id"], job["pipeline_version"], attempt, ctx) + row = await (await conn.execute( + "INSERT INTO job_outbox (job_id, subject, payload, available_at)" + " VALUES (%s, %s, %s, clock_timestamp() + make_interval(secs => %s)) RETURNING id", + (job["job_id"], settings.broker_subject, json.dumps(payload), delay_seconds))).fetchone() + if ctx: + await conn.execute("UPDATE attachment_jobs SET trace_context = %s WHERE job_id = %s", + (json.dumps(ctx), job["job_id"])) + return row["id"] + + +async def create_job(conn, settings, attachment_id, pipeline_version: int, *, detail=None) -> dict | None: + """Новая работа + строка outbox в текущей транзакции. Для уже существующей пары + (attachment_id, pipeline_version) — None (ключ эффекта: второй работы не будет).""" + job = await (await conn.execute( + "INSERT INTO attachment_jobs (job_id, attachment_id, pipeline_version, max_attempts)" + " VALUES (%s, %s, %s, %s) ON CONFLICT ON CONSTRAINT attachment_jobs_effect_key DO NOTHING RETURNING *", + (uuid.uuid4(), attachment_id, pipeline_version, settings.job_max_attempts))).fetchone() + if job is None: + return None + # Producer span «create»: момент, когда сообщение задания создано (в транзакции upload). Его контекст + # уходит в payload outbox — по нему relay и worker продолжают этот же trace. + with telemetry.child_span("create " + settings.broker_subject, SpanKind.PRODUCER, { + "messaging.system": "nats", "messaging.operation.type": "create", "messaging.operation.name": "create", + "messaging.destination.name": settings.broker_subject, "messenger.job.id": str(job["job_id"]), + "messenger.attachment.id": str(attachment_id), "messenger.pipeline.version": pipeline_version}): + outbox_id = await add_outbox(conn, settings, job, 1) + await add_event(conn, job, "enqueued", attempt=1, detail=dict(detail or {}, outbox_id=outbox_id)) + return job + + +# ------------------------------------------------------------------------------------- relay +async def relay_pass(pool, broker, settings, limit: int = 100, fault: str = "") -> int: + """Опубликовать готовые строки outbox. FOR UPDATE SKIP LOCKED: несколько relay (реплики API и + worker) не берут одну строку одновременно. Строка отмечается опубликованной только после publish + ack; падение между publish и COMMIT даст повторную публикацию с тем же Nats-Msg-Id (дубль + отбросит брокер, а за окном дедупликации — идемпотентность worker).""" + published = 0 + async with pool.connection() as conn: + async with conn.transaction(): + rows = await (await conn.execute( + "SELECT o.id, o.payload, j.job_id, j.attachment_id, j.pipeline_version" + " FROM job_outbox o JOIN attachment_jobs j ON j.job_id = o.job_id" + " WHERE o.published_at IS NULL AND o.available_at <= clock_timestamp()" + " ORDER BY o.available_at, o.id LIMIT %s FOR UPDATE OF o SKIP LOCKED", (limit,))).fetchall() + for r in rows: + payload = r["payload"] if isinstance(r["payload"], dict) else json.loads(r["payload"]) + # Producer span «send» — дочерний к «create» из payload (тот же trace загрузки/попытки); + # его контекст уходит в native headers NATS (traceparent/tracestate) для consumer. + parent = telemetry.extract(payload) + span = None + if telemetry.ENABLED: + span = telemetry.TRACER.start_span("send " + settings.broker_subject, context=parent, + kind=SpanKind.PRODUCER, attributes={ + "messaging.system": "nats", "messaging.operation.type": "send", + "messaging.operation.name": "publish", "messaging.destination.name": settings.broker_subject, + "messaging.message.id": "outbox-%d" % r["id"], "messenger.job.id": str(r["job_id"]), + "messenger.attachment.id": str(r["attachment_id"]), "messenger.job.attempt": payload["attempt"], + "messenger.relay": broker.name}) + headers = telemetry.inject(span) if span is not None else {} + try: + seq, duplicate = await broker.publish(json.dumps(payload, separators=(",", ":")).encode(), + "outbox-%d" % r["id"], headers) + except BrokerUnavailable as exc: + telemetry.mark_error(span, exc) + if span is not None: + span.end() + telemetry.outbox_publish.add(1, {"outcome": "error", "messaging.destination.name": settings.broker_subject}) + await conn.execute( + "UPDATE job_outbox SET publish_attempts = publish_attempts + 1, last_error = %s WHERE id = %s", + (str(exc)[:200], r["id"])) + log.warning("outbox publish failed; will retry", extra={"outbox_id": r["id"], "error": str(exc)[:100]}) + break + if span is not None: + span.set_attribute("messaging.nats.stream_sequence", seq) + span.set_attribute("messaging.nats.duplicate", duplicate) + span.end() + telemetry.outbox_publish.add(1, {"outcome": "duplicate" if duplicate else "ok", + "messaging.destination.name": settings.broker_subject}) + if fault == "crash_after_publish_before_mark": + log.error("FAULT INJECTION: exit after broker publish ack, before outbox COMMIT") + import os + os._exit(137) + await conn.execute("UPDATE job_outbox SET published_at = clock_timestamp()," + " publish_attempts = publish_attempts + 1 WHERE id = %s", (r["id"],)) + await add_event(conn, r, "published", attempt=payload["attempt"], + detail={"outbox_id": r["id"], "stream_seq": seq, "duplicate": duplicate, + "relay": broker.name}) + published += 1 + return published + + +# ------------------------------------------------------------------------------------- операторские команды +async def replay_failed(pool, settings, *, attachment_id=None, job_id=None, operator: str, reason: str) -> dict: + """failed → queued по явной команде оператора. Безопасно: для ready/processing/queued — no-op + с объяснением (повтор не означает исполнение дубля успешной работы); прежний эффект защищён + ключом (attachment_id, pipeline_version, variant).""" + async with pool.connection() as conn: + async with conn.transaction(): + if job_id is not None: + cond, arg = "j.job_id = %s", job_id + else: + cond, arg = ("j.attachment_id = %s AND j.pipeline_version = (SELECT max(pipeline_version)" + " FROM attachment_jobs WHERE attachment_id = %s)"), attachment_id + args = (arg,) if job_id is not None else (arg, arg) + job = await (await conn.execute( + "SELECT j.*, a.status AS att_status, a.staging_key, a.published_version FROM attachment_jobs j" + " JOIN attachments a ON a.id = j.attachment_id WHERE " + cond + " FOR UPDATE OF j, a", args)).fetchone() + if job is None: + return {"result": "not_found"} + if job["status"] != "failed": + return {"result": "noop", "job_id": str(job["job_id"]), "status": job["status"], + "why": "replay applies only to failed jobs; ready results are never re-executed"} + if job["staging_key"] is None and job["att_status"] != "ready": + return {"result": "refused", "job_id": str(job["job_id"]), + "why": "source removed by STAGING_RETENTION_SECONDS; upload the file again"} + attempt = job["attempt"] + 1 + job = await (await conn.execute( + "UPDATE attachment_jobs SET status = 'queued', attempt = %s, claims = 0, replays = replays + 1," + " error_code = NULL, error_detail = NULL, lease_owner = NULL, lease_until = NULL," + " next_attempt_at = clock_timestamp(), finished_at = NULL, updated_at = clock_timestamp()" + " WHERE job_id = %s RETURNING *", (attempt, job["job_id"]))).fetchone() + await conn.execute( + "UPDATE attachments SET status = 'queued', error_code = NULL, updated_at = clock_timestamp()" + " WHERE id = %s AND published_version IS NULL", (job["attachment_id"],)) + outbox_id = await add_outbox(conn, settings, job, attempt) + await add_event(conn, job, "replayed", attempt=attempt, + detail={"operator": operator[:64], "reason": reason[:200], "outbox_id": outbox_id}) + return {"result": "replayed", "job_id": str(job["job_id"]), "attempt": attempt} + + +async def reprocess(pool, settings, attachment_id, pipeline_version: int, operator: str) -> dict: + """Новая версия pipeline для существующего вложения (трек 2). Повтор команды — no-op.""" + async with pool.connection() as conn: + async with conn.transaction(): + att = await (await conn.execute( + "SELECT id, status, staging_key, published_version FROM attachments WHERE id = %s FOR UPDATE", + (attachment_id,))).fetchone() + if att is None: + return {"result": "not_found"} + if att["status"] != "ready" and att["staging_key"] is None: + return {"result": "refused", "why": "no source object (not ready, staging removed)"} + job = await create_job(conn, settings, attachment_id, pipeline_version, + detail={"operator": operator[:64], "reason": "reprocess"}) + if job is None: + existing = await (await conn.execute( + "SELECT job_id, status FROM attachment_jobs WHERE attachment_id = %s AND pipeline_version = %s", + (attachment_id, pipeline_version))).fetchone() + return {"result": "noop", "job_id": str(existing["job_id"]), "status": existing["status"]} + return {"result": "enqueued", "job_id": str(job["job_id"]), "pipeline_version": pipeline_version} + + +# ------------------------------------------------------------------------------------- обслуживание +async def fail_job(conn, job: dict, code: str, detail: str, *, worker=None, token=None) -> None: + """processing/queued → failed (финально). Вложение помечается failed, только если ни одна версия + ещё не опубликована (ошибка новой версии не ломает уже готовое вложение).""" + await conn.execute( + "UPDATE attachment_jobs SET status = 'failed', error_code = %s, error_detail = %s, lease_owner = NULL," + " lease_until = NULL, finished_at = clock_timestamp(), updated_at = clock_timestamp() WHERE job_id = %s", + (code, detail[:300], job["job_id"])) + await conn.execute( + "UPDATE attachments SET status = 'failed', error_code = %s, updated_at = clock_timestamp()" + " WHERE id = %s AND published_version IS NULL", (code, job["attachment_id"])) + await add_event(conn, job, "failed", token=token, worker=worker, detail={"error_code": code, "detail": detail[:200]}) + + +async def requeue(conn, settings, job: dict, *, event: str, delay: float, code=None, detail=None, + worker=None, token=None) -> int: + """→ queued с новой управляемой попыткой (attempt+1) и новым сообщением через outbox. + Старые сообщения этой работы становятся устаревшими (attempt меньше текущего).""" + attempt = job["attempt"] + 1 + await conn.execute( + "UPDATE attachment_jobs SET status = 'queued', attempt = %s, lease_owner = NULL, lease_until = NULL," + " next_attempt_at = clock_timestamp() + make_interval(secs => %s), error_code = %s, error_detail = %s," + " updated_at = clock_timestamp() WHERE job_id = %s", + (attempt, delay, code, (detail or "")[:300] or None, job["job_id"])) + await conn.execute( + "UPDATE attachments SET status = 'queued', updated_at = clock_timestamp()" + " WHERE id = %s AND published_version IS NULL AND status <> 'failed'", (job["attachment_id"],)) + outbox_id = await add_outbox(conn, settings, job, attempt, delay) + await add_event(conn, job, event, attempt=attempt, token=token, worker=worker, + detail={"delay_seconds": round(delay, 3), "error_code": code, "outbox_id": outbox_id}) + return attempt + + +_last_sweep = [float("-inf")] + + +async def _sweep_orphan_staging(conn, s3, settings) -> int: + grace = dt.timedelta(seconds=max(float(settings.upload_grace_seconds), settings.upload_timeout_seconds + 5)) + now = (await (await conn.execute("SELECT clock_timestamp() AS t")).fetchone())["t"] + candidates = [o.key async for o in s3.list_objects(settings.s3_bucket, "staging/") if now - o.last_modified > grace] + removed = 0 + for key in candidates: + # Перепроверка в БД непосредственно перед удалением (загрузка могла как раз зафиксироваться). + used = await (await conn.execute( + "SELECT EXISTS (SELECT 1 FROM attachments WHERE staging_key = %s)" + " OR EXISTS (SELECT 1 FROM upload_intents WHERE object_key = %s) AS used", (key, key))).fetchone() + if not used["used"]: + await s3.delete_object(settings.s3_bucket, key) + removed += 1 + log.info("orphan staging object removed", extra={"object_key": key}) + return removed + + +async def maintenance_pass(pool, s3, settings) -> dict: + """Один проход обслуживания под advisory lock (одновременно — один процесс в системе).""" + out = {"requeued": 0, "exhausted": 0, "republished": 0, "staging_cleaned": 0, "orphan_staging_removed": 0, + "outbox_purged": 0} + async with pool.connection() as conn: + got = await (await conn.execute("SELECT pg_try_advisory_lock(%s) AS ok", (MAINTENANCE_LOCK_ID,))).fetchone() + if not got["ok"]: + return out + try: + # 1) processing с давно истёкшим lease: worker умер, а брокер сообщение не вернул (оно могло + # быть подтверждено/потеряно). Обычно раньше срабатывает redelivery по ack_wait — тогда + # перехват делает worker; это вторая, независимая от брокера линия защиты. + grace = settings.job_lease_seconds + settings.broker_ack_wait_seconds + async with conn.transaction(): + rows = await (await conn.execute( + "SELECT * FROM attachment_jobs WHERE status = 'processing'" + " AND lease_until < clock_timestamp() - make_interval(secs => %s)" + " ORDER BY lease_until LIMIT 100 FOR UPDATE SKIP LOCKED", (grace,))).fetchall() + for job in rows: + # Восстановление — часть trace задания: span продолжает сохранённый контекст попытки. + with telemetry.span_in(job.get("trace_context"), "job.requeue_expired_lease", attributes={ + "messenger.job.id": str(job["job_id"]), "messenger.attachment.id": str(job["attachment_id"]), + "messenger.job.attempt": job["attempt"], "messenger.lease.owner": job["lease_owner"] or ""}): + if job["claims"] >= job["max_attempts"]: + await fail_job(conn, job, "retry_exhausted", "lease expired after the last allowed attempt") + out["exhausted"] += 1 + else: + await requeue(conn, settings, job, event="requeued_expired_lease", delay=0.0, + code="lease_expired", detail="worker lease expired") + out["requeued"] += 1 + # 2) queued без неопубликованной строки outbox и без движения дольше JOB_STUCK_SECONDS: + # сообщение утрачено вне PostgreSQL (например, потерян volume брокера) — публикуем заново. + async with conn.transaction(): + rows = await (await conn.execute( + "SELECT * FROM attachment_jobs j WHERE status = 'queued'" + " AND next_attempt_at < clock_timestamp() - make_interval(secs => %(s)s)" + " AND updated_at < clock_timestamp() - make_interval(secs => %(s)s)" + " AND NOT EXISTS (SELECT 1 FROM job_outbox o WHERE o.job_id = j.job_id AND o.published_at IS NULL)" + " LIMIT 100 FOR UPDATE SKIP LOCKED", {"s": settings.job_stuck_seconds})).fetchall() + for job in rows: + outbox_id = await add_outbox(conn, settings, job, job["attempt"]) + await conn.execute("UPDATE attachment_jobs SET updated_at = clock_timestamp() WHERE job_id = %s", + (job["job_id"],)) + await add_event(conn, job, "republished_stuck", detail={"outbox_id": outbox_id}) + out["republished"] += 1 + # 3) staging: после ready (оригинал опубликован, COMMIT сделан) — удалить; после failed — + # хранить STAGING_RETENTION_SECONDS (для replay), затем удалить. Текущую работу не трогаем. + if s3 is not None: + rows = await (await conn.execute( + "SELECT a.id, a.staging_key, a.status FROM attachments a WHERE a.staging_key IS NOT NULL" + " AND (a.status = 'ready' OR (a.status = 'failed'" + " AND a.updated_at < clock_timestamp() - make_interval(secs => %s)))" + " AND NOT EXISTS (SELECT 1 FROM attachment_jobs j WHERE j.attachment_id = a.id" + " AND j.status IN ('queued', 'processing'))" + " LIMIT 100", (settings.staging_retention_seconds,))).fetchall() + for r in rows: + await s3.delete_object(settings.s3_bucket, r["staging_key"]) + async with conn.transaction(): + cur = await conn.execute( + "UPDATE attachments SET staging_key = NULL WHERE id = %s AND staging_key = %s", + (r["id"], r["staging_key"])) + if cur.rowcount: + job = await (await conn.execute( + "SELECT job_id, attachment_id, pipeline_version, attempt FROM attachment_jobs" + " WHERE attachment_id = %s ORDER BY pipeline_version DESC LIMIT 1", (r["id"],))).fetchone() + if job: + await add_event(conn, job, "staging_cleaned", detail={"after": r["status"]}) + out["staging_cleaned"] += 1 + # 4) «осиротевшие» объекты staging: нет ни вложения, ни intent, старше grace загрузки. + # Вторая линия защиты для компенсации загрузки (раз в STAGING_SWEEP_SECONDS). + if s3 is not None and time.monotonic() - _last_sweep[0] >= settings.staging_sweep_seconds: + _last_sweep[0] = time.monotonic() + out["orphan_staging_removed"] = await _sweep_orphan_staging(conn, s3, settings) + # 5) опубликованные строки outbox старше недели больше не нужны. + cur = await conn.execute( + "DELETE FROM job_outbox WHERE id IN (SELECT id FROM job_outbox WHERE published_at" + " < clock_timestamp() - interval '7 days' LIMIT 5000)") + out["outbox_purged"] = cur.rowcount + finally: + await conn.execute("SELECT pg_advisory_unlock(%s)", (MAINTENANCE_LOCK_ID,)) + return out diff --git a/src/messenger/s3.py b/src/messenger/s3.py new file mode 100644 index 00000000..a70953a0 --- /dev/null +++ b/src/messenger/s3.py @@ -0,0 +1,212 @@ +"""Минимальный асинхронный S3-клиент (AWS Signature V4, path-style) поверх httpx. + +Почему свой, а не boto3: нужен потоковый PUT с известным Content-Length без буферизации файла в RAM +и асинхронный стрим GET → HTTP-ответ. Операции — ровно те, что использует сервис: +PUT/GET/HEAD/DELETE объекта, ListObjectsV2, multipart (list/abort), HEAD/PUT bucket (bootstrap). +""" +from __future__ import annotations + +import datetime as dt +import hashlib +import hmac +import xml.etree.ElementTree as ET +from dataclasses import dataclass +from urllib.parse import quote, urlsplit + +import httpx + +from . import telemetry + +EMPTY_SHA256 = hashlib.sha256(b"").hexdigest() +UNSIGNED = "UNSIGNED-PAYLOAD" +NS = "{http://s3.amazonaws.com/doc/2006-03-01/}" + + +class S3Error(Exception): + """Ответ S3 с ошибкой (status, code из XML).""" + + def __init__(self, status: int, code: str, message: str = ""): + super().__init__(f"S3 {status} {code}: {message}"[:300]) + self.status, self.code = status, code + + +class S3Unavailable(Exception): + """S3 недоступен (соединение, таймаут, 5xx).""" + + +@dataclass +class S3Object: + key: str + size: int + last_modified: dt.datetime + etag: str = "" + + +def _sign(key: bytes, msg: str) -> bytes: + return hmac.new(key, msg.encode(), hashlib.sha256).digest() + + +def _q(s: str, safe: str = "-_.~") -> str: + return quote(s, safe=safe) + + +def _operation(method: str, has_key: bool, query: dict) -> str: + if has_key: + if "uploadId" in query: + return "AbortMultipartUpload" + return {"PUT": "PutObject", "GET": "GetObject", "HEAD": "HeadObject", "DELETE": "DeleteObject"}.get(method, method) + if "uploads" in query: + return "ListMultipartUploads" + return {"PUT": "CreateBucket", "GET": "ListObjectsV2", "HEAD": "HeadBucket"}.get(method, method) + + +class S3Client: + def __init__(self, endpoint: str, region: str, access_key: str, secret_key: str, + timeout: float = 30.0, connect_timeout: float = 2.0, max_connections: int = 50): + self.endpoint = endpoint.rstrip("/") + self.host = urlsplit(self.endpoint).netloc + self.region, self.access_key, self.secret_key = region, access_key, secret_key + self.client = httpx.AsyncClient( + timeout=httpx.Timeout(timeout, connect=connect_timeout), + limits=httpx.Limits(max_connections=max_connections, max_keepalive_connections=20), + follow_redirects=False) + self.requests = 0 + + async def aclose(self): + await self.client.aclose() + + # ---------------------------------------------------------------- signing + def _headers(self, method: str, path: str, query: dict, payload_hash: str, extra: dict | None = None) -> dict: + now = dt.datetime.now(dt.timezone.utc) + amz_date, day = now.strftime("%Y%m%dT%H%M%SZ"), now.strftime("%Y%m%d") + headers = {"host": self.host, "x-amz-date": amz_date, "x-amz-content-sha256": payload_hash} + for k, v in (extra or {}).items(): + headers[k.lower()] = str(v) + signed = sorted(headers) + canonical_query = "&".join(f"{_q(k)}={_q(str(v))}" for k, v in sorted(query.items())) + canonical = "\n".join([method, _q(path, safe="/-_.~"), canonical_query, + "".join(f"{k}:{headers[k].strip()}\n" for k in signed), ";".join(signed), payload_hash]) + scope = f"{day}/{self.region}/s3/aws4_request" + to_sign = "\n".join(["AWS4-HMAC-SHA256", amz_date, scope, hashlib.sha256(canonical.encode()).hexdigest()]) + k = _sign(_sign(_sign(_sign(("AWS4" + self.secret_key).encode(), day), self.region), "s3"), "aws4_request") + signature = hmac.new(k, to_sign.encode(), hashlib.sha256).hexdigest() + headers["authorization"] = (f"AWS4-HMAC-SHA256 Credential={self.access_key}/{scope}, " + f"SignedHeaders={';'.join(signed)}, Signature={signature}") + del headers["host"] + return headers + + async def _request(self, method, path, query=None, content=None, payload_hash=EMPTY_SHA256, extra=None, + stream=False): + query = query or {} + headers = self._headers(method, path, query, payload_hash, extra) + url = self.endpoint + _q(path, safe="/-_.~") + self.requests += 1 + bucket, _, key = path.lstrip("/").partition("/") + op = _operation(method, bool(key), query) + # Client span: операция и bucket, без ключа объекта (в нём ID вложения) и без подписи/credentials. + with telemetry.child_span("S3." + op, telemetry.SpanKind.CLIENT, { + "rpc.system": "aws-api", "rpc.service": "S3", "rpc.method": op, "aws.s3.bucket": bucket, + "server.address": self.host.split(":")[0]}) as span: + try: + req = self.client.build_request(method, url, params=query or None, headers=headers, content=content) + resp = await self.client.send(req, stream=stream) + except (httpx.TransportError, httpx.TimeoutException) as exc: + telemetry.mark_error(span, error_type=type(exc).__name__) + raise S3Unavailable(type(exc).__name__) from exc + if span is not None: + span.set_attribute("http.response.status_code", resp.status_code) + if resp.status_code >= 500: + telemetry.mark_error(span, error_type=str(resp.status_code)) + if resp.status_code >= 500: + await resp.aclose() + raise S3Unavailable(f"HTTP {resp.status_code}") + if resp.status_code >= 300 and not (method == "HEAD" and resp.status_code == 404): + body = await resp.aread() + await resp.aclose() + code = "" + try: + code = ET.fromstring(body).findtext("Code") or "" + except ET.ParseError: + pass + raise S3Error(resp.status_code, code or str(resp.status_code), body[:200].decode(errors="replace")) + return resp + + # ---------------------------------------------------------------- objects + async def put_object_stream(self, bucket: str, key: str, body, length: int, content_type: str) -> str: + """Потоковый PUT: тело — async-итератор, длина известна заранее. Подпись UNSIGNED-PAYLOAD + (целостность проверяется самим сервисом по SHA-256 после загрузки и HEAD size).""" + resp = await self._request("PUT", f"/{bucket}/{key}", content=body, payload_hash=UNSIGNED, + extra={"content-length": length, "content-type": content_type}) + await resp.aclose() + return resp.headers.get("etag", "") + + async def put_object(self, bucket: str, key: str, data: bytes, content_type: str = "application/octet-stream"): + resp = await self._request("PUT", f"/{bucket}/{key}", content=data, + payload_hash=hashlib.sha256(data).hexdigest(), + extra={"content-length": len(data), "content-type": content_type}) + await resp.aclose() + + async def head_object(self, bucket: str, key: str) -> dict | None: + resp = await self._request("HEAD", f"/{bucket}/{key}") + await resp.aclose() + if resp.status_code == 404: + return None + return {"size": int(resp.headers.get("content-length", 0)), "etag": resp.headers.get("etag", ""), + "content_type": resp.headers.get("content-type", "")} + + async def get_object_stream(self, bucket: str, key: str) -> httpx.Response: + """Возвращает потоковый ответ; вызывающий обязан закрыть его (aclose).""" + return await self._request("GET", f"/{bucket}/{key}", stream=True) + + async def delete_object(self, bucket: str, key: str) -> None: + resp = await self._request("DELETE", f"/{bucket}/{key}") + await resp.aclose() + + async def list_objects(self, bucket: str, prefix: str = "", page_size: int = 1000): + """ListObjectsV2 с пагинацией; генератор S3Object.""" + token = None + while True: + q = {"list-type": "2", "prefix": prefix, "max-keys": str(page_size)} + if token: + q["continuation-token"] = token + resp = await self._request("GET", f"/{bucket}", query=q) + root = ET.fromstring(await resp.aread()) + for c in root.iter(NS + "Contents"): + yield S3Object(key=c.findtext(NS + "Key"), size=int(c.findtext(NS + "Size") or 0), + last_modified=dt.datetime.fromisoformat(c.findtext(NS + "LastModified").replace("Z", "+00:00")), + etag=(c.findtext(NS + "ETag") or "").strip('"')) + if (root.findtext(NS + "IsTruncated") or "false").lower() != "true": + return + token = root.findtext(NS + "NextContinuationToken") + if not token: + return + + async def list_multipart_uploads(self, bucket: str, prefix: str = ""): + resp = await self._request("GET", f"/{bucket}", query={"uploads": "", "prefix": prefix}) + root = ET.fromstring(await resp.aread()) + out = [] + for u in root.iter(NS + "Upload"): + out.append({"key": u.findtext(NS + "Key"), "upload_id": u.findtext(NS + "UploadId"), + "initiated": u.findtext(NS + "Initiated")}) + return out + + async def abort_multipart(self, bucket: str, key: str, upload_id: str) -> None: + resp = await self._request("DELETE", f"/{bucket}/{key}", query={"uploadId": upload_id}) + await resp.aclose() + + # ---------------------------------------------------------------- buckets + async def head_bucket(self, bucket: str) -> bool: + resp = await self._request("HEAD", f"/{bucket}") + await resp.aclose() + return resp.status_code != 404 + + async def create_bucket(self, bucket: str) -> bool: + """True — создан, False — уже существовал (идемпотентно).""" + try: + resp = await self._request("PUT", f"/{bucket}") + await resp.aclose() + return True + except S3Error as exc: + if exc.code in ("BucketAlreadyOwnedByYou", "BucketAlreadyExists"): + return False + raise diff --git a/src/messenger/security.py b/src/messenger/security.py new file mode 100644 index 00000000..90b82b83 --- /dev/null +++ b/src/messenger/security.py @@ -0,0 +1,102 @@ +"""Password KDF (scrypt из OpenSSL через hashlib) и opaque-токены сессий. + +Пароль хешируется медленным memory-hard KDF с солью: цель — сделать перебор украденных +hash дорогим. Токен сессии уже содержит 256 бит случайности, перебирать его бессмысленно, +поэтому для индекса в БД/кэше достаточно быстрого SHA-256 — это разные задачи. +""" +from __future__ import annotations + +import asyncio +import base64 +import hashlib +import hmac +import secrets +import time + +from . import telemetry + +_PREFIX = "$scrypt$" + + +def _b64(data: bytes) -> str: + return base64.b64encode(data).decode("ascii").rstrip("=") + + +def _unb64(text: str) -> bytes: + return base64.b64decode(text + "=" * (-len(text) % 4), validate=True) + + +class PasswordHasher: + """Формат PHC-подобный: $scrypt$ln=15,r=8,p=3$$. Параметры хранятся в строке, + поэтому их можно усилить позднее без потери старых hash.""" + + def __init__(self, log2_n: int, r: int, p: int, concurrency: int): + self.log2_n, self.r, self.p = log2_n, r, p + # Ограничиваем одновременные KDF: каждый вызов занимает 128*r*N байт RAM (32 MiB при ln=15). + self._slots = asyncio.Semaphore(concurrency) + self._dummy: str | None = None + + def _maxmem(self, log2_n: int, r: int, p: int) -> int: + return 128 * r * (2 ** log2_n) * 2 + 1024 * 1024 * p + + def _derive(self, password: str, salt: bytes, log2_n: int, r: int, p: int) -> bytes: + return hashlib.scrypt(password.encode("utf-8"), salt=salt, n=2 ** log2_n, r=r, p=p, + maxmem=self._maxmem(log2_n, r, p), dklen=32) + + def hash_sync(self, password: str) -> str: + salt = secrets.token_bytes(16) + digest = self._derive(password, salt, self.log2_n, self.r, self.p) + return f"{_PREFIX}ln={self.log2_n},r={self.r},p={self.p}${_b64(salt)}${_b64(digest)}" + + def verify_sync(self, password: str, encoded: str) -> bool: + try: + if not encoded.startswith(_PREFIX): + return False + params, salt_b64, hash_b64 = encoded[len(_PREFIX):].split("$") + fields = dict(item.split("=", 1) for item in params.split(",")) + log2_n, r, p = int(fields["ln"]), int(fields["r"]), int(fields["p"]) + if not (10 <= log2_n <= 22 and 1 <= r <= 32 and 1 <= p <= 16): + return False + expected = _unb64(hash_b64) + actual = self._derive(password, _unb64(salt_b64), log2_n, r, p) + except (ValueError, KeyError): + return False + return hmac.compare_digest(actual, expected) + + async def _run(self, op: str, fn, *args): + """KDF в пуле потоков под семафором; span показывает и ожидание слота (saturation KDF).""" + with telemetry.child_span("password." + op, attributes={"messenger.kdf": "scrypt"}) as span: + queued = time.perf_counter() + async with self._slots: + if span is not None: + span.set_attribute("messenger.kdf.wait_ms", round((time.perf_counter() - queued) * 1000, 2)) + return await asyncio.to_thread(fn, *args) + + async def hash(self, password: str) -> str: + return await self._run("hash", self.hash_sync, password) + + async def verify(self, password: str, encoded: str | None) -> bool: + """Для неизвестного пользователя проверяем фиктивный hash: время ответа не выдаёт, + существует ли username.""" + if encoded is None: + if self._dummy is None: + self._dummy = await self.hash("dummy-password-for-timing") + encoded, password = self._dummy, password + "\x00never" + await self._run("verify", self.verify_sync, password, encoded) + return False + return await self._run("verify", self.verify_sync, password, encoded) + + +TOKEN_BYTES = 32 # 256 бит энтропии + + +def new_token() -> str: + return secrets.token_urlsafe(TOKEN_BYTES) # 43 символа base64url + + +def token_hash(token: str) -> bytes: + return hashlib.sha256(token.encode("ascii")).digest() + + +def looks_like_token(token: str) -> bool: + return len(token) == 43 and all(c.isascii() and (c.isalnum() or c in "-_") for c in token) diff --git a/src/messenger/sessions.py b/src/messenger/sessions.py new file mode 100644 index 00000000..7a57f595 --- /dev/null +++ b/src/messenger/sessions.py @@ -0,0 +1,192 @@ +"""Сессии: PostgreSQL — источник истины, Redis/Valkey — read-through кэш с TTL. + +Политика (подробно — REPORT.md): +* ключ sess:v1: хранит {user, expires_at}; TTL = min(SESSION_CACHE_TTL_SECONDS, + остаток жизни сессии) — кэш никогда не переживает срок сессии; +* logout: revoked_at + строка outbox в одной транзакции PostgreSQL, затем в Redis атомарно + «надгробие» sess:v1:revoked: и DEL ключа. Заполнение кэша — Lua SET … только если + надгробия нет, поэтому конкурентный read-through не вернёт отозванную сессию в кэш; +* Redis недоступен → аутентификация идёт в PostgreSQL (fail-open только к источнику истины, + не к анонимному доступу); после ошибки кэш не читается, пока фоновый цикл не проверит Redis + и не дообработает outbox инвалидаций; +* flush/restart Redis = холодный кэш: сессии остаются в PostgreSQL. +""" +from __future__ import annotations + +import asyncio +import json +import logging +import time +from dataclasses import dataclass + +from psycopg_pool import AsyncConnectionPool +from redis import asyncio as aioredis +from redis.exceptions import RedisError + +from . import telemetry +from .config import Settings + +log = logging.getLogger("messenger.sessions") + +KEY = "sess:v1:" +_REDIS = {"db.system.name": "redis", "server.address": "redis"} # ключ (hash токена) в span не пишется +TOMBSTONE = "sess:v1:revoked:" + +# KEYS[1]=session key, KEYS[2]=tombstone; ARGV[1]=value, ARGV[2]=ttl ms +_SET_IF_NOT_REVOKED = """ +if redis.call('EXISTS', KEYS[2]) == 1 then return 0 end +redis.call('SET', KEYS[1], ARGV[1], 'PX', ARGV[2]) +return 1 +""" +# KEYS[1]=session key, KEYS[2]=tombstone; ARGV[1]=tombstone ttl ms +_INVALIDATE = """ +redis.call('SET', KEYS[2], '1', 'PX', ARGV[1]) +redis.call('DEL', KEYS[1]) +return 1 +""" + + +@dataclass +class Principal: + user: dict + expires_at: float # epoch seconds + token_hash: bytes + + +class SessionCache: + def __init__(self, settings: Settings): + self.settings = settings + self.client: aioredis.Redis | None = None + self._set_script = None + self._invalidate_script = None + # degraded=True: кэш не читаем (было исключение Redis или есть недообработанный outbox). + self.degraded = True + self._next_probe = 0.0 + self.stats = {"hits": 0, "misses": 0, "errors": 0} + if settings.cache_url: + t = settings.cache_timeout_seconds + self.client = aioredis.from_url( + settings.cache_url, socket_timeout=t, socket_connect_timeout=t, + retry_on_timeout=False, health_check_interval=0, max_connections=50, + decode_responses=False) + self._set_script = self.client.register_script(_SET_IF_NOT_REVOKED) + self._invalidate_script = self.client.register_script(_INVALIDATE) + + @property + def enabled(self) -> bool: + return self.client is not None + + def _tombstone_ms(self) -> int: + # Надгробие живёт дольше любой записи кэша и любого запроса в полёте. + return int((self.settings.session_cache_ttl_seconds + self.settings.request_timeout_seconds + 5) * 1000) + + def _fail(self, op: str, exc: Exception) -> None: + self.stats["errors"] += 1 + if not self.degraded: + log.warning("cache unavailable; falling back to PostgreSQL", + extra={"op": op, "error": type(exc).__name__}) + self.degraded = True + self._next_probe = time.monotonic() + self.settings.cache_retry_seconds + + async def get(self, th: bytes) -> Principal | None: + if not self.client or self.degraded: + return None + try: + with telemetry.child_span("GET", telemetry.SpanKind.CLIENT, _REDIS) as span: + raw = await self.client.get(KEY + th.hex()) + if span is not None: + span.set_attribute("messenger.cache.hit", raw is not None) + except (RedisError, OSError, asyncio.TimeoutError) as exc: + self._fail("get", exc) + return None + if raw is None: + self.stats["misses"] += 1 + return None + try: + data = json.loads(raw) + principal = Principal(user=data["user"], expires_at=float(data["exp"]), token_hash=th) + except (ValueError, KeyError, TypeError): + return None + if principal.expires_at <= time.time(): + return None + self.stats["hits"] += 1 + return principal + + async def put(self, p: Principal) -> None: + if not self.client or self.degraded: + return + ttl_ms = int(min(self.settings.session_cache_ttl_seconds, p.expires_at - time.time()) * 1000) + if ttl_ms < 1: + return + value = json.dumps({"user": p.user, "exp": p.expires_at}, separators=(",", ":")) + try: + with telemetry.child_span("EVALSHA set_if_not_revoked", telemetry.SpanKind.CLIENT, _REDIS): + await self._set_script(keys=[KEY + p.token_hash.hex(), TOMBSTONE + p.token_hash.hex()], + args=[value, ttl_ms]) + except (RedisError, OSError, asyncio.TimeoutError) as exc: + self._fail("put", exc) + + async def invalidate(self, th: bytes) -> bool: + if not self.client: + return True + try: + with telemetry.child_span("EVALSHA invalidate", telemetry.SpanKind.CLIENT, _REDIS): + await self._invalidate_script(keys=[KEY + th.hex(), TOMBSTONE + th.hex()], + args=[self._tombstone_ms()]) + return True + except (RedisError, OSError, asyncio.TimeoutError) as exc: + self._fail("invalidate", exc) + return False + + async def ping(self) -> bool: + if not self.client: + return False + try: + return bool(await self.client.ping()) + except (RedisError, OSError, asyncio.TimeoutError): + return False + + async def drain_outbox(self, pool: AsyncConnectionPool) -> int: + """Повторяет инвалидации из session_cache_invalidations. True-результат: outbox пуст.""" + drained = 0 + while True: + async with pool.connection() as conn: + rows = await (await conn.execute( + "SELECT token_hash FROM session_cache_invalidations ORDER BY created_at LIMIT 500" + )).fetchall() + if not rows: + return drained + done = [] + for row in rows: + th = bytes(row["token_hash"]) + if not await self.invalidate(th): + raise ConnectionError("cache still unavailable") + done.append(th) + async with pool.connection() as conn: + await conn.execute("DELETE FROM session_cache_invalidations WHERE token_hash = ANY(%s)", (done,)) + drained += len(done) + + async def maintenance_loop(self, pool: AsyncConnectionPool, stop: asyncio.Event) -> None: + """Возвращает кэш в работу только после успешного PING и пустого outbox.""" + while not stop.is_set(): + if self.client and time.monotonic() >= self._next_probe: + try: + if await self.ping(): + drained = await self.drain_outbox(pool) + if self.degraded: + log.info("cache available again", extra={"replayed_invalidations": drained}) + self.degraded = False + else: + self._fail("probe", ConnectionError("ping failed")) + except ConnectionError as exc: + self._fail("drain", exc) + except Exception as exc: # noqa: BLE001 — БД недоступна: состояние кэша не меняем + log.warning("outbox drain skipped", extra={"error": type(exc).__name__}) + try: + await asyncio.wait_for(stop.wait(), timeout=1.0) + except asyncio.TimeoutError: + pass + + async def close(self) -> None: + if self.client: + await self.client.aclose() diff --git a/src/messenger/telemetry.py b/src/messenger/telemetry.py new file mode 100644 index 00000000..36a33a0e --- /dev/null +++ b/src/messenger/telemetry.py @@ -0,0 +1,544 @@ +"""Наблюдаемость (lab6): OpenTelemetry SDK → OTLP/HTTP → OTel Collector → Prometheus/Loki/Tempo. + +Один модуль для API и worker: + * traces — server spans HTTP, client spans PostgreSQL/Redis/S3, producer/consumer spans задания + (W3C trace context переносится через outbox → NATS → worker); + * metrics — RED HTTP (histogram, секунды), jobs, очередь, пулы БД, saturation worker, CPU/RAM + процесса и контейнера (cgroup), self-метрики SDK (сколько spans/logs отброшено очередью); + * logs — тот же структурный JSON в stdout + OTLP-экспорт с trace_id/span_id активного span. + +Правила (contracts/observability.md): + * labels метрик только низкокардинальные: method, route template, status, outcome, state, pool; + НЕ user_id/chat_id/message_id/attachment_id/request_id/URL/filename/текст; + * в spans/logs допустимы технические UUID учебных данных (attachment_id, job_id, request_id) — + по ним оператор находит trace конкретной загрузки; пароли, Authorization, токены, тела сообщений, + байты изображений и ключи S3 в telemetry не попадают (SCRUB + attributes processor Collector); + * telemetry не должна ломать бизнес-путь: экспорт асинхронный (batch-очереди фиксированного размера), + при недоступном Collector данные отбрасываются и считаются (otel.sdk.processor.*.processed{error.type}). + +OTEL_SDK_DISABLED=true выключает экспорт полностью (эксперимент «telemetry off», трек 1): API работает +с no-op провайдерами, структурный лог в stdout остаётся. +""" +from __future__ import annotations + +import logging +import os +import re +import threading +import time +from contextlib import contextmanager, nullcontext + +from opentelemetry import metrics, propagate, trace +from opentelemetry.context import Context +from opentelemetry.trace import Link, SpanKind, Status, StatusCode # noqa: F401 (реэкспорт SpanKind) + +log = logging.getLogger("messenger.telemetry") + +TRACER = trace.get_tracer("messenger", "6.0.0") +METER = metrics.get_meter("messenger", "6.0.0") + +ENABLED = False +SERVICE = {"name": "messenger", "instance": "", "version": "dev"} +_providers: dict = {} + +# --------------------------------------------------------------------------------------------- buckets +# Границы под ожидаемые задержки (секунды): HTTP — рекомендованные semconv; БД — от долей миллисекунды; +# jobs — от 50 мс (маленькая картинка) до минут (повторы с backoff); time-to-ready — до 10 минут. +HTTP_BUCKETS = (0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10) +DB_BUCKETS = (0.0005, 0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5) +JOB_BUCKETS = (0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60, 120) +READY_BUCKETS = (0.25, 0.5, 1, 2, 3, 5, 10, 20, 30, 60, 120, 300, 600) + +JOB_TYPE = "attachment.process.v1" + +# --------------------------------------------------------------------------------------------- instruments +# Создаются через proxy-meter при импорте и «оживают» после setup(); до setup() и при выключенном +# SDK это no-op без затрат на экспорт. +http_duration = METER.create_histogram( + "http.server.request.duration", unit="s", explicit_bucket_boundaries_advisory=HTTP_BUCKETS, + description="Длительность HTTP-запросов API (count этого histogram — счётчик запросов)") +http_active = METER.create_up_down_counter( + "http.server.active_requests", unit="{request}", description="HTTP-запросы в обработке (saturation)") +db_duration = METER.create_histogram( + "db.client.operation.duration", unit="s", explicit_bucket_boundaries_advisory=DB_BUCKETS, + description="Длительность запросов к PostgreSQL (execute, без ожидания соединения пула)") +jobs_processed = METER.create_counter( + "messenger.jobs.processed", unit="{job}", + description="Сообщения заданий, обработанные worker, по исходу (ready/retry/failed/duplicate/…)") +job_duration = METER.create_histogram( + "messenger.job.duration", unit="s", explicit_bucket_boundaries_advisory=JOB_BUCKETS, + description="Длительность попытки обработки задания (claim → commit/ошибка)") +job_queue_wait = METER.create_histogram( + "messenger.job.queue_wait", unit="s", explicit_bucket_boundaries_advisory=READY_BUCKETS, + description="Ожидание в очереди: с момента, когда попытка стала доступна, до захвата worker") +time_to_ready = METER.create_histogram( + "messenger.attachment.time_to_ready", unit="s", explicit_bucket_boundaries_advisory=READY_BUCKETS, + description="От durable acceptance (COMMIT upload, 202) до публикации ready") +worker_busy = METER.create_up_down_counter( + "messenger.worker.busy", unit="{slot}", description="Занятые слоты worker (обрабатываемые задания)") +uploads = METER.create_counter( + "messenger.uploads", unit="{upload}", description="Загрузки вложений по исходу (accepted/rejected/failed)") +outbox_publish = METER.create_counter( + "messenger.outbox.publish", unit="{message}", description="Публикации outbox в брокер по исходу") + +# Значения для observable-инструментов, обновляемые фоновыми циклами (читаются потоком экспортёра). +_gauges: dict[str, list] = {} +_gauge_lock = threading.Lock() + + +def set_gauge(name: str, points: list[tuple[float, dict]]) -> None: + with _gauge_lock: + _gauges[name] = list(points) + + +def _gauge_cb(name: str): + def cb(_options): + with _gauge_lock: + points = list(_gauges.get(name, ())) + return [metrics.Observation(v, a) for v, a in points] + return cb + + +def register_gauges(specs: list[tuple[str, str, str]]) -> None: + """specs: (имя, unit, описание) — observable gauge, значения задаёт set_gauge().""" + for name, unit, desc in specs: + METER.create_observable_gauge(name, callbacks=[_gauge_cb(name)], unit=unit, description=desc) + + +QUEUE_GAUGES = [ + ("messenger.queue.depth", "{job}", "Задания по состоянию: ready (ждут worker), retry_wait (backoff), " + "processing (в аренде), failed (реестр DLQ)"), + ("messenger.queue.lag", "s", "Сколько ждёт самое старое задание, уже доступное worker (queue lag)"), + ("messenger.queue.oldest_age", "s", "Возраст самого старого незавершённого задания (с момента постановки)"), + ("messenger.outbox.pending", "{message}", "Строки outbox, готовые к публикации, но ещё не опубликованные"), + ("messenger.outbox.lag", "s", "Возраст самой старой неопубликованной строки outbox"), + ("messenger.broker.pending", "{message}", "Сообщения в stream, ещё не выданные consumer (num_pending)"), + ("messenger.broker.ack_pending", "{message}", "Выданные, но не подтверждённые сообщения (num_ack_pending)"), +] + + +# --------------------------------------------------------------------------------------------- setup +def _env_true(name: str) -> bool: + return os.environ.get(name, "").strip().lower() in {"1", "true", "yes", "on"} + + +def setup(role: str, instance_id: str) -> bool: + """Инициализирует провайдеры OTel. role: api | worker. Возвращает True, если экспорт включён.""" + global ENABLED + SERVICE.update(name=os.environ.get("OTEL_SERVICE_NAME") or "messenger-" + role, + instance=instance_id, version=os.environ.get("APP_VERSION", "dev")) + if _env_true("OTEL_SDK_DISABLED") or not os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT"): + log.info("telemetry export disabled", extra={"reason": "OTEL_SDK_DISABLED" if _env_true("OTEL_SDK_DISABLED") + else "no OTEL_EXPORTER_OTLP_ENDPOINT"}) + return False + from opentelemetry._logs import set_logger_provider + from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter + from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter + from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter + from opentelemetry.sdk._logs import LoggerProvider + from opentelemetry.sdk._logs.export import BatchLogRecordProcessor + from opentelemetry.sdk.metrics import MeterProvider + from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader + from opentelemetry.sdk.resources import Resource + from opentelemetry.sdk.trace import TracerProvider + from opentelemetry.sdk.trace.export import BatchSpanProcessor + + # OTEL_RESOURCE_ATTRIBUTES (deployment.environment.name=lab) объединяется с явными атрибутами. + resource = Resource.create({"service.name": SERVICE["name"], "service.namespace": "messenger", + "service.version": SERVICE["version"], "service.instance.id": instance_id}) + # Порядок важен: MeterProvider первым — BatchSpanProcessor/экспортёры регистрируют на нём + # self-метрики (otel.sdk.*: отброшенные из-за переполнения очереди spans/logs, ошибки экспорта). + reader = PeriodicExportingMetricReader(OTLPMetricExporter(), + export_interval_millis=float(os.environ.get("OTEL_METRIC_EXPORT_INTERVAL", "10000"))) + mp = MeterProvider(resource=resource, metric_readers=[reader]) + metrics.set_meter_provider(mp) + tp = TracerProvider(resource=resource) # sampler — из OTEL_TRACES_SAMPLER/OTEL_TRACES_SAMPLER_ARG + tp.add_span_processor(BatchSpanProcessor(OTLPSpanExporter())) # очередь OTEL_BSP_MAX_QUEUE_SIZE + trace.set_tracer_provider(tp) + lp = LoggerProvider(resource=resource) + lp.add_log_record_processor(BatchLogRecordProcessor(OTLPLogExporter())) # очередь OTEL_BLRP_MAX_QUEUE_SIZE + set_logger_provider(lp) + handler = OtlpLogHandler(lp) + handler.setLevel(logging.INFO) + logging.getLogger().addHandler(handler) + _providers.update(meter=mp, tracer=tp, logger=lp) + ENABLED = True + _register_runtime_metrics() + log.info("telemetry enabled", extra={"endpoint": os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT"), + "sampler": os.environ.get("OTEL_TRACES_SAMPLER", "parentbased_always_on"), + "sampler_arg": os.environ.get("OTEL_TRACES_SAMPLER_ARG", "")}) + return True + + +def shutdown(timeout_ms: int = 3000) -> None: + """Сбросить буферы при штатной остановке (не дольше timeout_ms на провайдер).""" + for key in ("tracer", "logger", "meter"): + p = _providers.get(key) + if p is None: + continue + try: + p.force_flush(timeout_ms) + p.shutdown() + except Exception: # noqa: BLE001 — Collector недоступен: данные будут потеряны, остановку не задерживаем + pass + + +# --------------------------------------------------------------------------------------------- logs +SCRUB = re.compile(r"(?i)^(password|passwd|token|access_token|session_token|authorization|cookie|" + r"secret|secret_key|api_key|text|body)$") +_STD = set(vars(logging.LogRecord("", 0, "", 0, "", (), None))) | {"message", "asctime"} +_STD_OTEL = _STD | {"trace_id", "span_id", "trace_flags", "service", "event"} + + +def log_fields(record: logging.LogRecord) -> dict: + """Пользовательские поля записи (extra=…) без секретов; не-примитивы приводятся к строке.""" + out = {} + for k, v in vars(record).items(): + if k in _STD_OTEL or k.startswith("_") or SCRUB.match(k): + continue + out[k] = v if isinstance(v, (str, bool, int, float)) or v is None else str(v) + return out + + +def event_name(record: logging.LogRecord) -> str: + """Стабильное имя события: extra event=… или сам шаблон сообщения (без подстановок).""" + ev = getattr(record, "event", None) + return str(ev) if ev else str(record.msg) + + +class TraceContextFilter(logging.Filter): + """Добавляет trace_id/span_id активного span и имя сервиса в каждую запись (stdout JSON).""" + + def filter(self, record: logging.LogRecord) -> bool: + ctx = trace.get_current_span().get_span_context() + if ctx.is_valid: + record.trace_id = format(ctx.trace_id, "032x") + record.span_id = format(ctx.span_id, "016x") + record.service = SERVICE["name"] + return True + + +_SEVERITY = {logging.DEBUG: 5, logging.INFO: 9, logging.WARNING: 13, logging.ERROR: 17, logging.CRITICAL: 21} + + +class OtlpLogHandler(logging.Handler): + """logging → OTel Logs API. Контекст (trace_id/span_id) берётся из активного span автоматически. + Атрибуты: event, logger, пользовательские поля без секретов; stack trace — только тип/сообщение.""" + + def __init__(self, provider): + super().__init__() + self.provider = provider + self._loggers = {} + + def emit(self, record: logging.LogRecord) -> None: + if record.name.startswith(("opentelemetry", "urllib3")): + return # не экспортировать ошибки самого экспорта (петля) + try: + logger = self._loggers.get(record.name) + if logger is None: + logger = self._loggers[record.name] = self.provider.get_logger(record.name) + attrs = log_fields(record) + attrs["event"] = event_name(record) + attrs["logger"] = record.name + if record.exc_info and record.exc_info[0] is not None: + attrs["exception.type"] = record.exc_info[0].__name__ + level = "WARN" if record.levelname == "WARNING" else record.levelname + logger.emit(timestamp=int(record.created * 1e9), severity_number=_severity(record.levelno), + severity_text=level, body=record.getMessage(), attributes=attrs, + event_name=attrs["event"]) + except Exception: # noqa: BLE001 — логирование не должно ронять запрос + pass + + +def _severity(levelno: int): + from opentelemetry._logs import SeverityNumber + best = max((lv for lv in _SEVERITY if lv <= levelno), default=logging.DEBUG) + return SeverityNumber(_SEVERITY[best]) + + +# --------------------------------------------------------------------------------------------- context +def inject(span=None) -> dict: + """W3C carrier {traceparent, tracestate?} текущего (или заданного) span; {} если span нет.""" + carrier: dict = {} + if span is not None: + ctx = trace.set_span_in_context(span) + propagate.inject(carrier, context=ctx) + else: + propagate.inject(carrier) + return {k: v for k, v in carrier.items() if k in ("traceparent", "tracestate")} + + +def extract(carrier: dict | None) -> Context: + return propagate.extract(carrier or {}, context=Context()) + + +def has_parent() -> bool: + return trace.get_current_span().get_span_context().is_valid + + +@contextmanager +def child_span(name: str, kind=SpanKind.INTERNAL, attributes: dict | None = None): + """Span только внутри уже существующего trace (фоновые циклы без родителя не плодят мелкие trace).""" + if not ENABLED or not trace.get_current_span().is_recording(): + yield None + return + with TRACER.start_as_current_span(name, kind=kind, attributes=attributes or {}) as span: + try: + yield span + except Exception as exc: + mark_error(span, exc) + raise + + +@contextmanager +def span_in(carrier: dict | None, name: str, kind=SpanKind.INTERNAL, attributes: dict | None = None): + """Span-продолжение сохранённого контекста (например, trace задания в maintenance). Без контекста — no-op.""" + parent = extract(carrier) + if not ENABLED or not trace.get_current_span(parent).get_span_context().is_valid: + yield None + return + with TRACER.start_as_current_span(name, context=parent, kind=kind, attributes=attributes or {}) as span: + try: + yield span + except Exception as exc: + mark_error(span, exc) + raise + + +def mark_error(span, exc: BaseException | None = None, error_type: str | None = None) -> None: + if span is None or not span.is_recording(): + return + et = error_type or (type(exc).__name__ if exc is not None else "error") + span.set_attribute("error.type", et) + span.set_status(Status(StatusCode.ERROR, et)) + if exc is not None: + span.record_exception(exc, attributes={"exception.escaped": False}) + + +def links_from(carrier: dict | None) -> list: + ctx = trace.get_current_span(extract(carrier)).get_span_context() + return [Link(ctx)] if ctx.is_valid else [] + + +# --------------------------------------------------------------------------------------------- PostgreSQL +_SUMMARY_RE = re.compile(r"\b(?:INSERT\s+INTO|UPDATE|DELETE\s+FROM|FROM)\s+([a-z_][a-z0-9_]*)", re.I) +_summary_cache: dict[str, tuple[str, str]] = {} + + +def sql_summary(query) -> tuple[str, str]: + """(операция, краткое описание «SELECT attachment_jobs») по тексту SQL с плейсхолдерами (без значений).""" + text = query if isinstance(query, str) else query.decode() if isinstance(query, bytes) else "" + hit = _summary_cache.get(text) + if hit: + return hit + words = text.lstrip("( \n").split(None, 1) + if not words: # psycopg_pool.check_connection: пустой запрос-проверка + return ("CHECK", "pool.check") + op = words[0].upper() + m = _SUMMARY_RE.search(text) + res = (op, "%s %s" % (op, m.group(1).lower()) if m else op) + if len(_summary_cache) < 2000: + _summary_cache[text] = res + return res + + +def make_traced_cursor(): + """Курсор psycopg, который пишет client span (если есть родительский) и histogram длительности.""" + from psycopg import AsyncCursor + + class TracedCursor(AsyncCursor): + async def execute(self, query, params=None, **kwargs): + op, summary = sql_summary(query) + attrs = {"db.system.name": "postgresql", "db.operation.name": op} + start = time.perf_counter() + error = None + span_cm = (TRACER.start_as_current_span(summary, kind=SpanKind.CLIENT, attributes={ + **attrs, "db.namespace": "messenger", "db.query.summary": summary, + "db.query.text": (query if isinstance(query, str) else str(summary))[:400], + "server.address": "postgres"}) if ENABLED and trace.get_current_span().is_recording() + else nullcontext()) + with span_cm as span: + try: + return await super().execute(query, params, **kwargs) + except Exception as exc: + error = type(exc).__name__ + mark_error(span, exc) + raise + finally: + if error: + attrs["error.type"] = error + db_duration.record(time.perf_counter() - start, attrs) + + return TracedCursor + + +def make_traced_connection(): + """Соединение psycopg, у которого COMMIT транзакции — отдельный client span и точка histogram БД. + Без этого в trace при медленной БД заметная часть времени (фиксация, fsync) была бы «ничьей».""" + from contextlib import asynccontextmanager + + from psycopg import AsyncConnection, AsyncTransaction + + class TracedTransaction(AsyncTransaction): + async def __aexit__(self, exc_type, exc_val, exc_tb): + if exc_type is not None or self.force_rollback: + return await super().__aexit__(exc_type, exc_val, exc_tb) + op = "RELEASE" if self.savepoint_name else "COMMIT" + attrs = {"db.system.name": "postgresql", "db.operation.name": op} + start, error = time.perf_counter(), None + span_cm = (TRACER.start_as_current_span(op, kind=SpanKind.CLIENT, attributes=dict( + attrs, **{"db.namespace": "messenger", "server.address": "postgres"})) + if ENABLED and trace.get_current_span().is_recording() else nullcontext()) + with span_cm as span: + try: + return await super().__aexit__(exc_type, exc_val, exc_tb) + except Exception as exc: + error = type(exc).__name__ + mark_error(span, exc) + raise + finally: + if error: + attrs["error.type"] = error + db_duration.record(time.perf_counter() - start, attrs) + + class TracedConnection(AsyncConnection): + @asynccontextmanager + async def transaction(self, savepoint_name=None, force_rollback=False): + if self._pipeline: # pipeline-режим не используется — исходное поведение + async with super().transaction(savepoint_name, force_rollback) as tx: + yield tx + return + tx = TracedTransaction(self, savepoint_name, force_rollback) + async with tx: + yield tx + + return TracedConnection + + +def register_pool(pool, name: str) -> None: + """DB pool saturation: used/idle/max/ожидающие запросы, таймауты получения соединения, время ожидания.""" + base = {"db.client.connection.pool.name": name} + + def counts(_o): + s = pool.get_stats() + size, avail = s.get("pool_size", 0), s.get("pool_available", 0) + return [metrics.Observation(size - avail, dict(base, **{"db.client.connection.state": "used"})), + metrics.Observation(avail, dict(base, **{"db.client.connection.state": "idle"}))] + + def mx(_o): + return [metrics.Observation(pool.get_stats().get("pool_max", 0), base)] + + def pending(_o): + return [metrics.Observation(pool.get_stats().get("requests_waiting", 0), base)] + + def timeouts(_o): + return [metrics.Observation(pool.get_stats().get("requests_errors", 0), base)] + + def wait(_o): + return [metrics.Observation(pool.get_stats().get("requests_wait_ms", 0) / 1000.0, base)] + + METER.create_observable_up_down_counter("db.client.connection.count", callbacks=[counts], unit="{connection}", + description="Соединения пула по состоянию (used/idle)") + METER.create_observable_up_down_counter("db.client.connection.max", callbacks=[mx], unit="{connection}", + description="Максимум соединений пула") + METER.create_observable_up_down_counter("db.client.connection.pending_requests", callbacks=[pending], + unit="{request}", description="Запросы, ждущие свободного соединения") + METER.create_observable_counter("db.client.connection.timeouts", callbacks=[timeouts], unit="{timeout}", + description="Неудачные получения соединения (таймаут/переполнение очереди пула)") + METER.create_observable_counter("messenger.db.pool.wait_time", callbacks=[wait], unit="s", + description="Суммарное время ожидания соединения пула") + + +# --------------------------------------------------------------------------------------------- CPU/RAM +def _read(path: str) -> str | None: + try: + with open(path) as fh: + return fh.read().strip() + except OSError: + return None + + +def _cgroup() -> dict: + """Использование контейнера из cgroup v2 (Docker Desktop) или v1 (старые Linux-хосты).""" + out = {} + v2 = _read("/sys/fs/cgroup/cpu.stat") + if v2 is not None: + for line in v2.splitlines(): + k, _, v = line.partition(" ") + if k == "usage_usec": + out["cpu"] = int(v) / 1e6 + cur = _read("/sys/fs/cgroup/memory.current") + stat = _read("/sys/fs/cgroup/memory.stat") or "" + inactive = next((int(l.split()[1]) for l in stat.splitlines() if l.startswith("inactive_file ")), 0) + if cur is not None: + out["mem"] = max(0, int(cur) - inactive) + mx = _read("/sys/fs/cgroup/memory.max") + if mx and mx != "max": + out["mem_limit"] = int(mx) + cpumax = (_read("/sys/fs/cgroup/cpu.max") or "max").split() + if cpumax and cpumax[0] != "max": + out["cpu_limit"] = int(cpumax[0]) / int(cpumax[1]) + return out + for p in ("/sys/fs/cgroup/cpuacct/cpuacct.usage", "/sys/fs/cgroup/cpu,cpuacct/cpuacct.usage"): + v = _read(p) + if v is not None: + out["cpu"] = int(v) / 1e9 + break + cur = _read("/sys/fs/cgroup/memory/memory.usage_in_bytes") + stat = _read("/sys/fs/cgroup/memory/memory.stat") or "" + inactive = next((int(l.split()[1]) for l in stat.splitlines() if l.startswith("total_inactive_file ")), 0) + if cur is not None: + out["mem"] = max(0, int(cur) - inactive) + lim = _read("/sys/fs/cgroup/memory/memory.limit_in_bytes") + if lim and int(lim) < 1 << 60: + out["mem_limit"] = int(lim) + for d in ("/sys/fs/cgroup/cpu", "/sys/fs/cgroup/cpu,cpuacct"): + q, per = _read(d + "/cpu.cfs_quota_us"), _read(d + "/cpu.cfs_period_us") + if q is not None and per and int(q) > 0: + out["cpu_limit"] = int(q) / int(per) + break + return out + + +def _register_runtime_metrics() -> None: + page = os.sysconf("SC_PAGE_SIZE") + + def cpu(_o): + t = os.times() + return [metrics.Observation(t.user, {"cpu.mode": "user"}), metrics.Observation(t.system, {"cpu.mode": "system"})] + + def rss(_o): + v = _read("/proc/self/statm") + return [metrics.Observation(int(v.split()[1]) * page, {})] if v else [] + + def ccpu(_o): + c = _cgroup() + return [metrics.Observation(c["cpu"], {})] if "cpu" in c else [] + + def cmem(_o): + c = _cgroup() + return [metrics.Observation(c["mem"], {})] if "mem" in c else [] + + def cmem_limit(_o): + c = _cgroup() + return [metrics.Observation(c["mem_limit"], {})] if "mem_limit" in c else [] + + def ccpu_limit(_o): + c = _cgroup() + return [metrics.Observation(c["cpu_limit"], {})] if "cpu_limit" in c else [] + + METER.create_observable_counter("process.cpu.time", callbacks=[cpu], unit="s", description="CPU процесса") + METER.create_observable_up_down_counter("process.memory.usage", callbacks=[rss], unit="By", description="RSS процесса") + METER.create_observable_counter("container.cpu.time", callbacks=[ccpu], unit="s", + description="CPU всего контейнера (cgroup, включая подпроцессы worker)") + METER.create_observable_up_down_counter("container.memory.usage", callbacks=[cmem], unit="By", + description="Рабочий набор памяти контейнера (cgroup usage − inactive_file)") + METER.create_observable_gauge("messenger.container.memory.limit", callbacks=[cmem_limit], unit="By", + description="Лимит памяти контейнера") + METER.create_observable_gauge("messenger.container.cpu.limit", callbacks=[ccpu_limit], unit="{cpu}", + description="Лимит CPU контейнера (ядер)") + + +# --------------------------------------------------------------------------------------------- HTTP helpers +def status_class(code: int) -> str: + return "%dxx" % (code // 100) if 100 <= code < 600 else "unknown" diff --git a/src/messenger/validation.py b/src/messenger/validation.py new file mode 100644 index 00000000..c6cd17d7 --- /dev/null +++ b/src/messenger/validation.py @@ -0,0 +1,119 @@ +"""Строгая валидация входа: лишние поля, неверные типы и malformed JSON — 400.""" +from __future__ import annotations + +import base64 +import json +import re +import uuid +from datetime import datetime + +from .errors import ApiError, invalid + +USERNAME_RE = re.compile(r"[a-z0-9_]{3,32}") + + +def _no_duplicates(pairs): + obj = {} + for key, value in pairs: + if key in obj: + raise ValueError("duplicate key") + obj[key] = value + return obj + + +def _reject_constant(name): + raise ValueError("non-standard JSON constant " + name) + + +def parse_json_object(raw: bytes, allowed: set[str], required: set[str]) -> dict: + if not raw: + raise invalid("Ожидается JSON-объект") + try: + data = json.loads(raw.decode("utf-8"), object_pairs_hook=_no_duplicates, + parse_constant=_reject_constant) + except (UnicodeDecodeError, ValueError, RecursionError): + raise invalid("Некорректный JSON") from None + if not isinstance(data, dict): + raise invalid("Ожидается JSON-объект") + extra = set(data) - allowed + if extra: + raise invalid("Лишние поля: " + ", ".join(sorted(extra))[:200]) + missing = required - set(data) + if missing: + raise invalid("Отсутствуют поля: " + ", ".join(sorted(missing))) + return data + + +def text_field(data: dict, name: str, lo: int, hi: int) -> str: + value = data.get(name) + if not isinstance(value, str): + raise invalid(f"Поле {name} должно быть строкой") + if not lo <= len(value) <= hi: # len() в Python — число Unicode code points + raise invalid(f"Поле {name}: длина {lo}–{hi} символов") + if lo > 0 and not value.strip(): + raise invalid(f"Поле {name} не может состоять только из пробелов") + if "\x00" in value: + raise invalid(f"Поле {name} содержит недопустимый символ") + try: + value.encode("utf-8") + except UnicodeEncodeError: # одиночные суррогаты из \uD800-escape + raise invalid(f"Поле {name} содержит некорректный Unicode") from None + return value + + +def parse_uuid(value, what: str = "UUID") -> uuid.UUID: + if not isinstance(value, str): + raise invalid(f"Некорректный {what}") + try: + parsed = uuid.UUID(value) + except ValueError: + raise invalid(f"Некорректный {what}") from None + # Принимаем только каноническую 36-символьную запись (без {} и urn:). + if len(value) != 36: + raise invalid(f"Некорректный {what}") + return parsed + + +def parse_limit(params) -> int: + values = params.getlist("limit") + if not values: + return 50 + if len(values) > 1 or not values[0].isascii() or not values[0].isdigit() or len(values[0]) > 3: + raise invalid("limit должен быть целым 1–100") + limit = int(values[0]) + if not 1 <= limit <= 100: + raise invalid("limit должен быть целым 1–100") + return limit + + +def single_param(params, name: str) -> str | None: + values = params.getlist(name) + if len(values) > 1: + raise invalid(f"Параметр {name} указан несколько раз") + return values[0] if values else None + + +# --- keyset cursor ------------------------------------------------------------------------- +# Курсор непрозрачен для клиента: base64url(JSON) с видом списка и областью (чат/пользователь). +# Подделка курсора не даёт доступа: область всё равно проверяется, а позиция лишь фильтр. + +def encode_cursor(kind: str, scope: uuid.UUID, created_at: datetime, item_id: uuid.UUID) -> str: + payload = json.dumps({"v": 1, "k": kind, "s": str(scope), "t": created_at.isoformat(), "i": str(item_id)}, + separators=(",", ":")).encode() + return base64.urlsafe_b64encode(payload).decode().rstrip("=") + + +def decode_cursor(cursor: str, kind: str, scope: uuid.UUID) -> tuple[datetime, uuid.UUID]: + try: + if not cursor or len(cursor) > 512 or not cursor.isascii(): + raise ValueError + raw = base64.urlsafe_b64decode(cursor + "=" * (-len(cursor) % 4)) + data = json.loads(raw) + if data.get("v") != 1 or data.get("k") != kind or data.get("s") != str(scope): + raise ValueError + ts = datetime.fromisoformat(data["t"]) + if ts.tzinfo is None: + raise ValueError + return ts, uuid.UUID(data["i"]) + except (ValueError, KeyError, TypeError, AttributeError, UnicodeError): + raise ApiError("invalid_request", "Некорректный cursor") from None diff --git a/src/messenger/worker.py b/src/messenger/worker.py new file mode 100644 index 00000000..0d7b44dd --- /dev/null +++ b/src/messenger/worker.py @@ -0,0 +1,654 @@ +"""Worker обработки вложений (отдельный процесс/сервис): python -m messenger worker. + +Цикл: pull из JetStream не больше свободных слотов (WORKER_CONCURRENCY) → решение по состоянию job +в PostgreSQL под блокировкой строки → обработка в подпроцессе с лимитами → запись объектов в S3 по +детерминированным ключам → COMMIT результата с проверкой fencing-токена → consumer ack. + +Почему повторная доставка безопасна: + * ключ эффекта (attachment_id, pipeline_version, variant) — первичный ключ attachment_variants и + часть S3-ключа: повтор перезаписывает те же объекты теми же байтами (обработка детерминирована) + и не может создать второй набор вариантов; + * решение «выполнять или нет» принимается по job в БД: ready/superseded/failed и устаревший attempt — + ack без действий; чужая живая аренда — nak с задержкой; истёкшая аренда — перехват (claims+1); + * результат фиксируется, только если lease_token в БД всё ещё мой: ожившая после зависания попытка + (её аренду уже перехватили) ничего не перезапишет. +Зависший worker отличается от долгого heartbeat'ом: долгий каждые lease/4 продлевает аренду в БД и +ack_wait в брокере (in_progress); зависший перестаёт — аренда истекает, работу перехватывают. +""" +from __future__ import annotations + +import asyncio +import contextlib +import hashlib +import json +import logging +import os +import re +import signal +import sys +import time +from pathlib import Path + +from opentelemetry import context as otel_context +from opentelemetry import trace +from opentelemetry.trace import SpanKind + +from . import db, telemetry +from .broker import Broker, BrokerUnavailable +from .config import Settings +from .imgproc import VARIANT_EXT +from .jobs import (InvalidMessage, add_event, backoff_delay, fail_job, maintenance_pass, parse_message, + relay_pass, requeue) +from .s3 import S3Client, S3Error, S3Unavailable + +log = logging.getLogger("messenger.worker") +ALIVE_FILE = "/tmp/worker-alive" + + +class Transient(Exception): + """Временная ошибка: повторить с backoff, если остались попытки.""" + + def __init__(self, code: str, detail: str = ""): + super().__init__(detail or code) + self.code = code + + +class Permanent(Exception): + """Постоянная ошибка: повтор не поможет → failed с безопасным error_code.""" + + def __init__(self, code: str, detail: str = ""): + super().__init__(detail or code) + self.code = code + + +class LeaseLost(Exception): + """Аренду перехватили (heartbeat не прошёл) — результат этой попытки не фиксируется.""" + + +def variant_key(attachment_id, version: int, name: str) -> str: + return "variants/%s/v%d/%s.%s" % (attachment_id.hex, version, name, VARIANT_EXT[name]) + + +# ------------------------------------------------------------------------- учебные хуки отказов +_HOOK_RE = re.compile(r"fault-(transient|permanent|crash-before-s3|crash-after-s3|crash-after-commit|hang|slow)" + r"(?:-(\d+))?(?:-v(\d+))?") + + +def hook(settings: Settings, filename: str, name: str, version: int | None = None): + """Маркер вида fault-[-N][-vV] в отображаемом имени файла (-vV — только для pipeline_version V). + Работает только при FAULT_HOOKS=lab (учебный стенд); в боевой конфигурации переменная пуста.""" + if settings.fault_hooks != "lab": + return None + for m in _HOOK_RE.finditer(filename): + if m.group(1) == name and (m.group(3) is None or version is None or int(m.group(3)) == version): + return int(m.group(2)) if m.group(2) else 0 + return None + + +def crash(reason: str) -> None: + log.error("FAULT INJECTION: worker process exits", extra={"point": reason}) + sys.stdout.flush() + os._exit(137) + + +# ------------------------------------------------------------------------- worker +class Worker: + def __init__(self, settings: Settings): + self.s = settings + self.pool = db.make_pool(settings) + self.s3 = S3Client(settings.s3_endpoint, settings.s3_region, settings.s3_access_key, + settings.s3_secret_key, timeout=settings.s3_timeout_seconds) + self.broker = Broker(settings, settings.worker_id) + self.stop = asyncio.Event() + self.slots = asyncio.Semaphore(settings.worker_concurrency) + self.inflight: set[asyncio.Task] = set() + self.relay_kick = asyncio.Event() + self.stats = {"processed": 0, "ready": 0, "retried": 0, "failed": 0, "acked_noop": 0, "naked": 0, + "lease_lost": 0, "invalid_messages": 0} + + # ---- решения по сообщению ------------------------------------------------------------- + async def claim(self, data: dict): + """Одна транзакция под FOR UPDATE строки job. Возвращает ('process', job) или ('ack'|'nak'|'term', …).""" + job_id, att_id = data["job_id"], data["attachment_id"] + async with self.pool.connection() as conn: + async with conn.transaction(): + job = await (await conn.execute( + "SELECT j.*, extract(epoch FROM (j.lease_until - clock_timestamp())) AS lease_left," + " extract(epoch FROM (j.next_attempt_at - clock_timestamp())) AS not_before," + " extract(epoch FROM (clock_timestamp() - j.next_attempt_at))::float8 AS waited," + " a.status AS att_status, a.published_version, a.staging_key, a.object_key," + " a.filename, a.size_bytes, a.sha256, a.content_type" + " FROM attachment_jobs j JOIN attachments a ON a.id = j.attachment_id" + " WHERE j.job_id = %s FOR UPDATE OF j", (job_id,))).fetchone() + if job is None: + return ("ack", "unknown_job") + if str(job["attachment_id"]) != att_id or job["pipeline_version"] != data["pipeline_version"]: + return ("term", "message does not match job") + if job["pipeline_version"] not in self.s.worker_pipelines: + # Эта версия worker не умеет такой pipeline (rolling deploy) — отдать другому, попытку не тратить. + return ("nak", 10.0) + if job["status"] in ("ready", "superseded"): + await add_event(conn, job, "duplicate_ignored", attempt=data["attempt"], worker=self.s.worker_id) + return ("ack", "already " + job["status"]) + if job["status"] == "failed" or data["attempt"] < job["attempt"]: + await add_event(conn, job, "stale_ignored", attempt=data["attempt"], worker=self.s.worker_id, + detail={"current_attempt": job["attempt"], "status": job["status"]}) + return ("ack", "stale") + if data["attempt"] > job["attempt"]: + # Такой попытки не назначала БД (поддельное/искажённое сообщение) — не исполнять. + await add_event(conn, job, "stale_ignored", attempt=data["attempt"], worker=self.s.worker_id, + detail={"current_attempt": job["attempt"], "future": True}) + return ("term", "attempt from the future") + if job["published_version"] is not None and job["published_version"] > job["pipeline_version"]: + # Устаревшая работа: уже опубликована более новая версия pipeline — не выполнять вовсе. + await conn.execute("UPDATE attachment_jobs SET status = 'superseded', finished_at = clock_timestamp()," + " updated_at = clock_timestamp() WHERE job_id = %s", (job_id,)) + await add_event(conn, job, "superseded", worker=self.s.worker_id, + detail={"published_version": job["published_version"]}) + return ("ack", "superseded") + takeover = False + if job["status"] == "queued": + if job["not_before"] is not None and job["not_before"] > 0.5: + return ("nak", float(job["not_before"])) + elif job["status"] == "processing": + if job["lease_left"] is not None and job["lease_left"] > 0: + # Чужая живая аренда: второй неконтролируемый исполнитель не нужен. + return ("nak", float(job["lease_left"]) + 1.0) + takeover = True + if job["claims"] >= job["max_attempts"]: + await fail_job(conn, job, "retry_exhausted", "attempt limit reached (%d)" % job["max_attempts"], + worker=self.s.worker_id) + return ("ack", "exhausted") + claimed = await (await conn.execute( + "UPDATE attachment_jobs SET status = 'processing', claims = claims + 1," + " lease_token = nextval('job_lease_token_seq'), lease_owner = %s," + " lease_until = clock_timestamp() + make_interval(secs => %s), updated_at = clock_timestamp()" + " WHERE job_id = %s RETURNING claims, lease_token", + (self.s.worker_id, self.s.job_lease_seconds, job_id))).fetchone() + await conn.execute( + "UPDATE attachments SET status = 'processing', updated_at = clock_timestamp()" + " WHERE id = %s AND published_version IS NULL AND status IN ('queued', 'processing')", + (job["attachment_id"],)) + job = dict(job, **claimed) + await add_event(conn, job, "lease_takeover" if takeover else "claimed", token=job["lease_token"], + worker=self.s.worker_id, detail={"claims": job["claims"]}) + if not takeover and job["waited"] is not None: + telemetry.job_queue_wait.record(max(0.0, job["waited"]), {"job.type": telemetry.JOB_TYPE}) + job["takeover"] = takeover + return ("process", job) + + # ---- аренда --------------------------------------------------------------------------- + async def heartbeat(self, msg, job: dict, lost: asyncio.Event) -> None: + interval = max(0.5, min(self.s.job_lease_seconds, self.s.broker_ack_wait_seconds) / 4) + while True: + await asyncio.sleep(interval) + with contextlib.suppress(Exception): + await msg.in_progress() # продлить ack_wait брокера + try: + async with self.pool.connection() as conn: + cur = await conn.execute( + "UPDATE attachment_jobs SET lease_until = clock_timestamp() + make_interval(secs => %s)" + " WHERE job_id = %s AND lease_token = %s AND status = 'processing'", + (self.s.job_lease_seconds, job["job_id"], job["lease_token"])) + if cur.rowcount == 0: + lost.set() + return + except Exception as exc: # noqa: BLE001 — БД кратко недоступна: аренда может истечь, это безопасно + log.warning("lease heartbeat failed", extra={"job_id": str(job["job_id"]), "error": type(exc).__name__}) + + # ---- выполнение ----------------------------------------------------------------------- + async def read_source(self, job: dict) -> bytes: + if job["staging_key"]: + key = job["staging_key"] + elif job["att_status"] == "ready": + key = job["object_key"] # повторная обработка новой версией: исходник — опубликованный оригинал + else: + raise Permanent("source_missing", "no staging object and original not published") + try: + resp = await self.s3.get_object_stream(self.s.s3_bucket, key) + except S3Error as exc: + if exc.status == 404: + raise Permanent("source_missing", "source object not found") from None + raise Transient("storage_unavailable", "S3 %s" % exc.status) from None + except S3Unavailable as exc: + raise Transient("storage_unavailable", str(exc)) from None + sha, chunks, size = hashlib.sha256(), [], 0 + try: + async for chunk in resp.aiter_bytes(65536): + size += len(chunk) + if size > self.s.max_upload_bytes: + raise Permanent("source_corrupt", "source larger than limit") + sha.update(chunk) + chunks.append(chunk) + except Exception as exc: # noqa: BLE001 + if isinstance(exc, Permanent): + raise + raise Transient("storage_unavailable", type(exc).__name__) from None + finally: + await resp.aclose() + if size != job["size_bytes"] or sha.hexdigest() != job["sha256"]: + raise Permanent("source_corrupt", "source checksum mismatch") + return b"".join(chunks) + + async def run_pipeline(self, data: bytes, version: int) -> list[tuple[dict, bytes]]: + """Подпроцесс с RLIMIT_AS/RLIMIT_CPU и таймаутом на стене.""" + s = self.s + proc = await asyncio.create_subprocess_exec( + sys.executable, "-m", "messenger.imgproc", str(s.max_image_pixels), str(s.worker_process_memory_mb), + str(int(s.job_timeout_seconds) + 1), str(version), + stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) + try: + out, err = await asyncio.wait_for(proc.communicate(data), timeout=s.job_timeout_seconds) + except (asyncio.TimeoutError, TimeoutError): + with contextlib.suppress(ProcessLookupError): + proc.kill() + await proc.wait() + raise Transient("processing_timeout", "image processing exceeded %.0fs" % s.job_timeout_seconds) from None + head, _, rest = out.partition(b"\n") + if proc.returncode == 3: + info = json.loads(head) + if info["kind"] == "unsupported_pipeline": + raise Permanent("processing_failed", info["detail"]) + raise Permanent("invalid_image" if info["kind"] in ("invalid_image", "too_large") else "processing_failed", + info["detail"]) + if proc.returncode != 0: + # Сигнал (SIGXCPU/SIGKILL/SIGSEGV) или сбой интерпретатора: недетерминированный сбой — повторяем. + raise Transient("processing_crashed", "exit %s" % proc.returncode) + info = json.loads(head) + result, off = [], 0 + for meta in info["variants"]: + body = rest[off:off + meta["size_bytes"]] + off += meta["size_bytes"] + if hashlib.sha256(body).hexdigest() != meta["sha256"]: + raise Transient("processing_crashed", "variant checksum mismatch") + result.append((meta, body)) + return result + + async def put(self, key: str, body: bytes, content_type: str) -> None: + try: + await self.s3.put_object(self.s.s3_bucket, key, body, content_type) + except S3Unavailable as exc: + raise Transient("storage_unavailable", str(exc)) from None + except S3Error as exc: + raise Transient("storage_unavailable", "S3 %s" % exc.status) from None + + async def execute(self, job: dict, lost: asyncio.Event) -> list[dict]: + s, first = self.s, job["claims"] == 1 + fn, ver = job["filename"], job["pipeline_version"] + if first and hook(s, fn, "crash-before-s3", ver) is not None: + crash("after claim, before any side effect") + n = hook(s, fn, "transient", ver) + if n is not None and job["attempt"] <= max(1, n): + # Управляемые попытки 1..N падают «временно»; после replay (attempt > N) обработка проходит. + raise Transient("processing_failed", "injected transient failure (attempt %d)" % job["attempt"]) + if hook(s, fn, "permanent", ver) is not None: + raise Permanent("processing_failed", "injected permanent failure") + data = await self.read_source(job) + with telemetry.child_span("imgproc.run", attributes={ + "messenger.pipeline.version": job["pipeline_version"], "messenger.image.bytes": len(data), + "messenger.image.content_type": job["content_type"]}) as span: + variants = await self.run_pipeline(data, job["pipeline_version"]) + if span is not None: + span.set_attribute("messenger.variants", ",".join(m["name"] for m, _ in variants)) + slow = hook(s, fn, "slow", ver) + if slow: + await asyncio.sleep(slow) # долгая, но живая работа: heartbeat продолжается + if lost.is_set(): + raise LeaseLost() + # Побочные эффекты: оригинал в конечный prefix (если ещё не опубликован) и варианты — по ключам, + # детерминированным ключом эффекта. Повтор перезаписывает те же объекты теми же байтами. + if job["att_status"] != "ready": + await self.put(job["object_key"], data, job["content_type"]) + out = [] + for meta, body in variants: + key = variant_key(job["attachment_id"], job["pipeline_version"], meta["name"]) + await self.put(key, body, meta["content_type"]) + out.append(dict(meta, object_key=key)) + if first and hook(s, fn, "crash-after-s3", ver) is not None: + crash("after S3 writes, before result COMMIT") + hang = hook(s, fn, "hang", ver) + if first and hang: + log.error("FAULT INJECTION: event loop blocked (hung worker)", extra={"seconds": hang}) + time.sleep(hang) # heartbeat не идёт — аренду перехватят + return out + + async def commit(self, job: dict, variants: list[dict]) -> str: + """Атомарная публикация результата с проверкой fencing-токена.""" + async with self.pool.connection() as conn: + async with conn.transaction(): + cur = await (await conn.execute( + "SELECT status, lease_token FROM attachment_jobs WHERE job_id = %s FOR UPDATE", + (job["job_id"],))).fetchone() + if cur["status"] != "processing" or cur["lease_token"] != job["lease_token"]: + raise LeaseLost() + att = await (await conn.execute( + "SELECT published_version, staging_key," + " extract(epoch FROM (clock_timestamp() - created_at))::float8 AS age" + " FROM attachments WHERE id = %s FOR NO KEY UPDATE", + (job["attachment_id"],))).fetchone() + for v in variants: + await conn.execute( + "INSERT INTO attachment_variants (attachment_id, pipeline_version, name, object_key, content_type," + " size_bytes, width, height, sha256, job_id, lease_token)" + " VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)" + " ON CONFLICT (attachment_id, pipeline_version, name) DO NOTHING", + (job["attachment_id"], job["pipeline_version"], v["name"], v["object_key"], v["content_type"], + v["size_bytes"], v["width"], v["height"], v["sha256"], job["job_id"], job["lease_token"])) + old = att["published_version"] + if old is not None and old > job["pipeline_version"]: + # Пока шла эта (старая) версия, опубликовали более новую: указатель назад не двигаем. + await conn.execute("UPDATE attachment_jobs SET status = 'superseded', lease_owner = NULL," + " lease_until = NULL, finished_at = clock_timestamp(), updated_at = clock_timestamp()" + " WHERE job_id = %s", (job["job_id"],)) + await add_event(conn, job, "superseded", token=job["lease_token"], worker=self.s.worker_id, + detail={"published_version": old, "at": "commit"}) + return "superseded" + await conn.execute( + "UPDATE attachment_jobs SET status = 'ready', error_code = NULL, error_detail = NULL," + " lease_owner = NULL, lease_until = NULL, finished_at = clock_timestamp()," + " updated_at = clock_timestamp() WHERE job_id = %s", (job["job_id"],)) + await conn.execute( + "UPDATE attachments SET status = 'ready', error_code = NULL, published_version = %s," + " updated_at = clock_timestamp() WHERE id = %s", (job["pipeline_version"], job["attachment_id"])) + await add_event(conn, job, "committed", token=job["lease_token"], worker=self.s.worker_id, + detail={"variants": sorted(v["name"] for v in variants)}) + if old != job["pipeline_version"]: + await add_event(conn, job, "published_version_changed", token=job["lease_token"], + worker=self.s.worker_id, detail={"from": old, "to": job["pipeline_version"]}) + if old is None: + # Время до ready: от durable acceptance (created_at строки, COMMIT upload) до публикации. + job["time_to_ready"] = att["age"] + return "ready" + + async def finish_error(self, job: dict, exc: Exception) -> str: + """Ошибка попытки: retry с backoff или failed. Тоже под проверкой fencing-токена.""" + async with self.pool.connection() as conn: + async with conn.transaction(): + cur = await (await conn.execute( + "SELECT * FROM attachment_jobs WHERE job_id = %s FOR UPDATE", (job["job_id"],))).fetchone() + if cur["status"] != "processing" or cur["lease_token"] != job["lease_token"]: + raise LeaseLost() + detail = str(exc)[:200] + if isinstance(exc, Permanent): + await fail_job(conn, cur, exc.code, detail, worker=self.s.worker_id, token=job["lease_token"]) + return "failed" + if cur["claims"] >= cur["max_attempts"]: + await fail_job(conn, cur, "retry_exhausted", "%s: %s" % (exc.code, detail), + worker=self.s.worker_id, token=job["lease_token"]) + return "failed" + delay = backoff_delay(cur["attempt"], self.s.job_retry_base_seconds, self.s.job_retry_max_seconds) + await requeue(conn, self.s, cur, event="retry_scheduled", delay=delay, code=exc.code, detail=detail, + worker=self.s.worker_id, token=job["lease_token"]) + return "retry" + + async def cleanup_staging(self, job: dict) -> None: + """После COMMIT ready оригинал опубликован — staging больше не нужен (best effort; иначе уберёт + maintenance). Удаляется только если активных работ по вложению нет.""" + with contextlib.suppress(Exception): + async with self.pool.connection() as conn: + row = await (await conn.execute( + "SELECT staging_key FROM attachments a WHERE id = %s AND status = 'ready' AND staging_key IS NOT NULL" + " AND NOT EXISTS (SELECT 1 FROM attachment_jobs j WHERE j.attachment_id = a.id" + " AND j.status IN ('queued', 'processing'))", (job["attachment_id"],))).fetchone() + if row is None: + return + await self.s3.delete_object(self.s.s3_bucket, row["staging_key"]) + async with conn.transaction(): + cur = await conn.execute("UPDATE attachments SET staging_key = NULL WHERE id = %s AND staging_key = %s", + (job["attachment_id"], row["staging_key"])) + if cur.rowcount: + await add_event(conn, job, "staging_cleaned", worker=self.s.worker_id, detail={"after": "ready"}) + + async def handle(self, msg) -> None: + """Обработка одного сообщения в consumer span «process». Родитель — span «send» relay из native + headers NATS (traceparent); если заголовков нет (старое/сырое сообщение) — контекст из payload. + Так upload → create → send → process (и все повторы) — один trace.""" + try: + data = parse_message(msg.data) + except InvalidMessage as exc: + self.stats["invalid_messages"] += 1 + telemetry.jobs_processed.add(1, {"job.type": telemetry.JOB_TYPE, "outcome": "invalid"}) + log.error("invalid job message terminated", extra={"event": "job.invalid_message", "error": str(exc)}) + await msg.term() # «ядовитое» сообщение: повтор не поможет + return + headers = msg.headers or {} + span = token = None + if telemetry.ENABLED: + carrier = headers if headers.get("traceparent") else data + links = telemetry.links_from(data) if carrier is headers and data.get("traceparent") else [] + try: + delivered = msg.metadata.num_delivered + except Exception: # noqa: BLE001 + delivered = None + span = telemetry.TRACER.start_span( + "process " + self.s.broker_subject, context=telemetry.extract(carrier), kind=SpanKind.CONSUMER, + links=links, attributes={ + "messaging.system": "nats", "messaging.operation.type": "process", + "messaging.operation.name": "process", "messaging.destination.name": self.s.broker_subject, + "messaging.consumer.group.name": self.s.broker_consumer, + "messaging.message.id": headers.get("Nats-Msg-Id", ""), + "messaging.nats.delivered": delivered or 0, "messenger.job.id": data["job_id"], + "messenger.attachment.id": data["attachment_id"], "messenger.job.attempt": data["attempt"], + "messenger.pipeline.version": data["pipeline_version"], "messenger.worker.id": self.s.worker_id}) + token = otel_context.attach(trace.set_span_in_context(span)) + outcome = "error" + try: + outcome = await self._handle(msg, data, span) + finally: + telemetry.jobs_processed.add(1, {"job.type": telemetry.JOB_TYPE, "outcome": outcome, + "messenger.pipeline.version": data["pipeline_version"]}) + if span is not None: + span.set_attribute("messenger.job.outcome", outcome) + span.end() + otel_context.detach(token) + + async def _handle(self, msg, data: dict, span) -> str: + try: + decision = await self.claim(data) + except Exception as exc: # noqa: BLE001 — БД недоступна: сообщение вернётся позже + telemetry.mark_error(span, exc) + log.warning("claim failed; nak", extra={"event": "job.claim_failed", "job_id": data["job_id"], + "error": type(exc).__name__}) + with contextlib.suppress(Exception): + await msg.nak(delay=5) + return "claim_error" + kind = decision[0] + if kind == "ack": + self.stats["acked_noop"] += 1 + await msg.ack_sync() + reason = decision[1] + return {"stale": "stale", "superseded": "superseded", "exhausted": "failed", + "unknown_job": "unknown_job"}.get(reason, "duplicate") + if kind == "nak": + self.stats["naked"] += 1 + await msg.nak(delay=decision[1]) + return "nak" + if kind == "term": + log.error("job message terminated", extra={"event": "job.terminated", "job_id": data["job_id"], + "why": decision[1]}) + await msg.term() + return "rejected" + job = decision[1] + self.stats["processed"] += 1 + lost = asyncio.Event() + hb = asyncio.create_task(self.heartbeat(msg, job, lost)) + log_extra = {"job_id": str(job["job_id"]), "attachment_id": str(job["attachment_id"]), + "attempt": job["attempt"], "claims": job["claims"], "lease_token": job["lease_token"], + "pipeline_version": job["pipeline_version"]} + log.info("job claimed", extra=dict(log_extra, event="job.claimed", takeover=job.get("takeover", False))) + started = time.perf_counter() + outcome = "error" # исключение мимо обработчиков (БД недоступна при finish_error) + telemetry.worker_busy.add(1) + try: + try: + try: + with telemetry.child_span("job.execute"): + variants = await self.execute(job, lost) + with telemetry.child_span("job.commit"): + outcome = await self.commit(job, variants) + except (Transient, Permanent) as exc: + telemetry.mark_error(span, error_type=exc.code) + with telemetry.child_span("job.finish_error", attributes={"error.type": exc.code}): + outcome = await self.finish_error(job, exc) + log.warning("job attempt failed", extra=dict(log_extra, event="job.attempt_failed", + error_code=exc.code, outcome=outcome)) + except LeaseLost: + raise + except Exception as exc: # noqa: BLE001 — неожиданное: считаем временным + telemetry.mark_error(span, exc) + outcome = await self.finish_error(job, Transient("processing_failed", type(exc).__name__)) + log.exception("unexpected job error", extra=dict(log_extra, event="job.unexpected_error", + outcome=outcome)) + except LeaseLost: + outcome = "lease_lost" + self.stats["lease_lost"] += 1 + telemetry.mark_error(span, error_type="lease_lost") + log.warning("lease lost; result not committed", extra=dict(log_extra, event="job.lease_lost")) + with contextlib.suppress(Exception): + async with self.pool.connection() as conn: + await add_event(conn, job, "lease_lost", token=job["lease_token"], worker=self.s.worker_id) + return "lease_lost" # без ack: судьбу сообщения решит текущий владелец/БД + finally: + hb.cancel() + with contextlib.suppress(asyncio.CancelledError): + await hb + finally: + telemetry.worker_busy.add(-1) + elapsed = time.perf_counter() - started + telemetry.job_duration.record(elapsed, {"job.type": telemetry.JOB_TYPE, + "outcome": outcome}) + self.stats[{"ready": "ready", "superseded": "ready", "retry": "retried", "failed": "failed"}[outcome]] += 1 + if outcome == "ready" and job.get("time_to_ready") is not None: + telemetry.time_to_ready.record(job["time_to_ready"], {"job.type": telemetry.JOB_TYPE}) + log.info("job attempt finished", extra=dict(log_extra, event="job.finished", outcome=outcome, + duration_ms=round(elapsed * 1000, 1))) + if outcome != "retry": + self.relay_kick.set() + if outcome in ("ready", "superseded"): + await self.cleanup_staging(job) + if job["claims"] == 1 and hook(self.s, job["filename"], "crash-after-commit", job["pipeline_version"]) is not None: + crash("after result COMMIT, before consumer ack") + else: + self.relay_kick.set() # новое сообщение retry — в outbox, опубликовать сразу + await msg.ack_sync() # ack только после устойчивого эффекта (COMMIT) + return outcome + + # ---- циклы ------------------------------------------------------------------------------ + async def consume_loop(self) -> None: + sub = None + while not self.stop.is_set(): + Path(ALIVE_FILE).touch() + try: + if sub is None: + await self.broker.ensure_topology() + sub = await self.broker.pull_subscription() + log.info("worker subscribed", extra={"worker_id": self.s.worker_id, + "concurrency": self.s.worker_concurrency}) + await self.slots.acquire() + free = 1 + while free < self.s.worker_concurrency and not self.slots.locked(): + await self.slots.acquire() + free += 1 + try: + msgs = await sub.fetch(free, timeout=2) # не больше свободных слотов: prefetch ограничен + except (asyncio.TimeoutError, TimeoutError): + msgs = [] + except BaseException: + for _ in range(free): + self.slots.release() + raise + for _ in range(free - len(msgs)): + self.slots.release() + for m in msgs: + task = asyncio.create_task(self._run(m)) + self.inflight.add(task) + task.add_done_callback(self.inflight.discard) + except (BrokerUnavailable, Exception) as exc: # noqa: BLE001 + if isinstance(exc, asyncio.CancelledError): + raise + log.warning("consume loop error; retrying", extra={"error": type(exc).__name__}) + sub = None + with contextlib.suppress(asyncio.TimeoutError): + await asyncio.wait_for(self.stop.wait(), timeout=2) + + async def _run(self, msg) -> None: + try: + await self.handle(msg) + except Exception as exc: # noqa: BLE001 — ack/nak не дошёл: брокер вернёт сообщение по ack_wait + log.warning("message handling error", extra={"error": type(exc).__name__}) + finally: + self.slots.release() + + async def relay_loop(self) -> None: + while not self.stop.is_set(): + try: + if await relay_pass(self.pool, self.broker, self.s): + continue + except Exception as exc: # noqa: BLE001 + log.warning("relay pass failed", extra={"error": type(exc).__name__}) + self.relay_kick.clear() + with contextlib.suppress(asyncio.TimeoutError): + await asyncio.wait_for(self.relay_kick.wait(), timeout=self.s.relay_interval_seconds) + + async def maintenance_loop(self) -> None: + while not self.stop.is_set(): + try: + out = await maintenance_pass(self.pool, self.s3, self.s) + if any(out.values()): + log.info("maintenance", extra=out) + self.relay_kick.set() + except Exception as exc: # noqa: BLE001 + log.warning("maintenance pass failed", extra={"error": type(exc).__name__}) + with contextlib.suppress(asyncio.TimeoutError): + await asyncio.wait_for(self.stop.wait(), timeout=self.s.maintenance_interval_seconds) + + async def run(self) -> None: + loop = asyncio.get_running_loop() + for sig in (signal.SIGTERM, signal.SIGINT): + loop.add_signal_handler(sig, self.stop.set) + await self.pool.open(wait=False) + if telemetry.ENABLED: + telemetry.register_pool(self.pool, "worker") + telemetry.register_gauges([("messenger.worker.capacity", "{slot}", "Слоты worker (WORKER_CONCURRENCY)")]) + telemetry.set_gauge("messenger.worker.capacity", [(self.s.worker_concurrency, {})]) + while not self.stop.is_set(): # схема должна быть применена migrate + try: + ok, missing = await db.schema_status(self.pool) + if ok: + break + log.warning("schema is behind this worker; waiting for migrate", extra={"missing": missing}) + except Exception as exc: # noqa: BLE001 + log.warning("schema check failed; retrying", extra={"error": type(exc).__name__}) + await asyncio.sleep(1) + tasks = [asyncio.create_task(self.consume_loop()), asyncio.create_task(self.relay_loop()), + asyncio.create_task(self.maintenance_loop())] + log.info("worker started", extra={"worker_id": self.s.worker_id, "pipelines": list(self.s.worker_pipelines), + "concurrency": self.s.worker_concurrency, "lease_seconds": self.s.job_lease_seconds}) + await self.stop.wait() + # Graceful: новые сообщения не берём, текущие дорабатываем (не дольше grace); недоделанные + # без ack вернутся другому worker по ack_wait — потерь нет. + log.info("worker stopping; draining in-flight jobs", extra={"inflight": len(self.inflight)}) + tasks[0].cancel() + if self.inflight: + await asyncio.wait(self.inflight, timeout=float(os.environ.get("WORKER_DRAIN_SECONDS", "20"))) + for t in tasks[1:]: + t.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + await self.broker.close() + await self.s3.aclose() + await self.pool.close() + log.info("worker stopped", extra=self.stats) + + +def main() -> int: + from .config import load + settings = load() + if not settings.broker_url or not settings.s3_endpoint: + log.error("worker requires BROKER_URL_FILE and S3 settings") + return 2 + telemetry.setup("worker", settings.worker_id) + try: + asyncio.run(Worker(settings).run()) + finally: + telemetry.shutdown() + return 0 diff --git a/student-tests/common.py b/student-tests/common.py new file mode 100644 index 00000000..a937409c --- /dev/null +++ b/student-tests/common.py @@ -0,0 +1,185 @@ +"""Общая обвязка собственных проверок студента (stdlib, Python 3.9+). + +Переиспользует HTTP-клиент публичных тестов (tests/client.py), не изменяя его. Команды управления +стендом и доступа к SQL задаются переменными окружения; по умолчанию — Compose из этого репозитория. +""" +import base64 +import hashlib +import json +import os +import shlex +import subprocess +import sys +import time +import traceback +import uuid +import zlib +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tests")) + +from client import Client, Failure, check # noqa: E402 + +DC = os.environ.get("COMPOSE", "docker compose --env-file .env") +PSQL = os.environ.get("PSQL", DC + " exec -T postgres psql -U messenger -d messenger") +COMMANDS = { + "stop_db": os.environ.get("STOP_DB", DC + " stop postgres"), + "start_db": os.environ.get("START_DB", DC + " start postgres"), + "stop_cache": os.environ.get("STOP_CACHE", DC + " stop redis"), + "start_cache": os.environ.get("START_CACHE", DC + " start redis"), + # lab5: worker и брокер (volumes не трогаются) + "stop_worker": os.environ.get("STOP_WORKER", DC + " stop worker"), + "start_worker": os.environ.get("START_WORKER", DC + " start worker"), + "restart_broker": os.environ.get("RESTART_BROKER", DC + " restart nats"), + "restart_api": os.environ.get("RESTART_API", DC + " restart api"), +} +BASE_URL = os.environ.get("BASE_URL", "http://127.0.0.1:8080") +TTL_BASE_URL = os.environ.get("TTL_BASE_URL", "http://127.0.0.1:8081") +TTL_SECONDS = float(os.environ.get("TTL_SECONDS", "2")) + + +def sh(name_or_cmd, timeout=90): + cmd = COMMANDS.get(name_or_cmd, name_or_cmd) + subprocess.run(shlex.split(cmd), cwd=ROOT, check=True, timeout=timeout, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + + +def sql(query): + """Одна SQL-команда через psql (-At); возвращает строки результата. Только синтетические данные.""" + out = subprocess.run(shlex.split(PSQL) + ["-X", "-At", "-v", "ON_ERROR_STOP=1", "-c", query], + cwd=ROOT, check=True, capture_output=True, text=True, timeout=60) + return [line for line in out.stdout.splitlines() if line] + + +S3_ADMIN = os.environ.get("S3_ADMIN", DC + " run --rm --no-deps -T --entrypoint python s3-init -") +API_EXEC = os.environ.get("API_EXEC", DC + " exec -T api") + + +def s3_admin(op, key, data=None): + """Операция с bucket admin-ключом В ОБХОД API (внедрение отказов на стороне S3).""" + args = [op, key] + ([base64.b64encode(data).decode()] if data is not None else []) + script = (ROOT / "student-tests" / "s3_admin.py").read_bytes() + out = subprocess.run(shlex.split(S3_ADMIN) + args, cwd=ROOT, input=script, capture_output=True, + check=True, timeout=120) + return out.stdout.decode().strip() + + +# Операторские команды выполняются в контейнере API (тот же образ; worker может быть остановлен). +JOBS_EXEC = os.environ.get("JOBS_EXEC", DC + " exec -T api") + + +def jobs_cli(*args, expect=(0,)): + """python -m messenger jobs … внутри контейнера API; возвращает JSON-ответ (stdout).""" + out = subprocess.run(shlex.split(JOBS_EXEC) + ["python", "-m", "messenger", "jobs"] + [str(a) for a in args], + cwd=ROOT, capture_output=True, text=True, timeout=300) + if out.returncode not in expect: + raise Failure("jobs %s exit %d: %s" % (args[0], out.returncode, (out.stderr or out.stdout).strip()[-300:])) + return json.loads(out.stdout) + + +def events(attachment_id): + """Журнал событий работ вложения: список (event, attempt, lease_token, worker, detail).""" + return jobs_cli("status", attachment_id)["events"] + + +def wait_status(c, actor, att_id, statuses, timeout=90, interval=0.3): + """Ждать, пока GET метаданных вернёт один из statuses; возвращает Attachment.""" + statuses = (statuses,) if isinstance(statuses, str) else tuple(statuses) + deadline = time.monotonic() + timeout + last = None + while time.monotonic() < deadline: + last = c.call("GET", "/api/v1/attachments/" + att_id, actor=actor, schema="Attachment")["json"] + if last["status"] in statuses: + return last + time.sleep(interval) + raise Failure("attachment %s: status %s, expected %s within %ss" % (att_id, last and last["status"], statuses, timeout)) + + +def make_png(width=16, height=16, seed=None): + """Валидный RGB PNG (stdlib), уникальный по seed — для разных SHA-256.""" + seed = seed if seed is not None else uuid.uuid4().bytes + rnd = hashlib.sha256(seed).digest() + rows = b"".join(b"\x00" + bytes((rnd[(x + y) % 32] ^ x ^ y) & 0xFF for x in range(width * 3)) for y in range(height)) + + def chunk(t, d): + return len(d).to_bytes(4, "big") + t + d + zlib.crc32(t + d).to_bytes(4, "big") + ihdr = width.to_bytes(4, "big") + height.to_bytes(4, "big") + bytes([8, 2, 0, 0, 0]) + return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(rows)) + chunk(b"IEND", b"") + + +def upload(c, actor, chat, data=None, content_type="image/png", filename="pic.png", expected=202, headers=None): + from urllib.parse import quote + data = make_png() if data is None else data + h = {"Content-Type": content_type} + h.update(headers or {}) + r = c.call("POST", "/api/v1/chats/" + chat["id"] + "/attachments?filename=" + quote(filename), expected, + actor=actor, raw=data, headers=h, schema="Attachment" if expected == 202 else None) + return (r["json"], data) if expected == 202 else r + + +def basic(username, password): + return "Basic " + base64.b64encode((username + ":" + password).encode("utf-8")).decode() + + +def new_user(c, label="s", password=None): + username = ("st_" + label + "_" + uuid.uuid4().hex[:10])[:32] + password = password or ("Pw-" + uuid.uuid4().hex) + user = c.call("POST", "/api/v1/users", 201, schema="User", + body={"username": username, "display_name": "Тест " + label, "password": password})["json"] + return {"id": user["id"], "user": user, "username": username, "password": password} + + +def login(c, actor, expected=201): + r = c.call("POST", "/api/v1/auth/sessions", expected, headers={"Authorization": basic(actor["username"], actor["password"])}, + schema="Session" if expected == 201 else None) + if expected == 201: + actor["token"] = r["json"]["token"] + actor["expires_at"] = r["json"]["expires_at"] + return r + + +def wait_until(probe, timeout=60, interval=0.5): + deadline = time.monotonic() + timeout + last = None + while time.monotonic() < deadline: + try: + if probe(): + return time.monotonic() + except Failure as exc: + last = exc + time.sleep(interval) + raise Failure("condition not reached in %ss (%s)" % (timeout, last)) + + +class Suite: + def __init__(self, name): + self.name, self.results = name, [] + + def case(self, title): + def decorator(fn): + self.results.append((title, fn)) + return fn + return decorator + + def run(self): + passed = failed = 0 + print("## " + self.name) + for title, fn in self.results: + start = time.monotonic() + try: + note = fn() + passed += 1 + print("PASS %-62s %6.2fs%s" % (title, time.monotonic() - start, (" " + note) if note else "")) + except Exception as exc: # noqa: BLE001 + failed += 1 + print("FAIL %-62s %s" % (title, exc)) + if os.environ.get("DEBUG"): + traceback.print_exc() + print("summary: %d passed, %d failed" % (passed, failed)) + raise SystemExit(1 if failed else 0) + + +__all__ = ["Client", "Failure", "check", "sh", "sql", "basic", "new_user", "login", "wait_until", "Suite", + "s3_admin", "jobs_cli", "events", "wait_status", "make_png", "upload", + "BASE_URL", "TTL_BASE_URL", "TTL_SECONDS", "json"] diff --git a/student-tests/defense_demo.py b/student-tests/defense_demo.py new file mode 100644 index 00000000..9f78b01a --- /dev/null +++ b/student-tests/defense_demo.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python3 +"""Сценарий защиты lab5 (README, шаги 1–3) с протоколом действий: время, действие, HTTP-коды, статус, +ID вложения/работы и состояние контейнеров (StartedAt/PID). Токены и пароли не печатаются. + + 1. make test проходит отдельно (smoke). + 2. worker остановлен → upload 202 → GET queued → content 409 → другие сообщения работают. + 3. перезапуск API и брокера с сохранением volumes → запуск worker → та же запись ready, thumbnail доступен. + + python3 student-tests/defense_demo.py # нужен docker compose в PATH и работающий стенд +""" +import datetime as dt +import hashlib +import shlex +import subprocess +import sys +import time +import uuid +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests")) +from image_probe import jpeg_size # noqa: E402 + +from common import BASE_URL, DC, ROOT, Client, Failure, check, jobs_cli, login, make_png, new_user, sh, upload # noqa: E402 + +c = Client(BASE_URL, timeout=30) + + +def log(step, msg): + print("%s %-6s %s" % (dt.datetime.now(dt.timezone.utc).strftime("%H:%M:%S.%f")[:-3], step, msg), flush=True) + + +def containers(services=("api", "worker", "nats")): + out = [] + for svc in services: + ids = subprocess.run(shlex.split(DC) + ["ps", "-a", "-q", svc], cwd=ROOT, capture_output=True, text=True).stdout.split() + for i in ids: + out.append(subprocess.run(["docker", "inspect", "-f", "{{.Name}} {{.State.Status}} started={{.State.StartedAt}}" + " pid={{.State.Pid}}", i], capture_output=True, text=True).stdout.strip().lstrip("/")) + return out + + +def wait(probe, timeout, interval=0.5): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + try: + v = probe() + except Failure: # пока реплики перезапускаются, LB отвечает сам (503 без X-Instance-Id) + v = None + if v: + return v + time.sleep(interval) + raise SystemExit("timeout") + + +alice = new_user(c, "demo"); login(c, alice) +bob = new_user(c, "demob"); login(c, bob) +chat = c.call("POST", "/api/v1/chats", 201, actor=alice, schema="Chat", + body={"title": "defense", "member_ids": [alice["id"], bob["id"]]})["json"] +log("0", "chat %s, users alice/bob (tokens not shown)" % chat["id"]) +for line in containers(): + log("0", " " + line) + +log("2", "stop worker: " + DC + " stop worker") +sh("stop_worker", timeout=120) +for line in containers(("worker",)): + log("2", " " + line) +data = make_png(320, 200) +att, _ = upload(c, alice, chat, data, filename="defense.png") +log("2", "POST /chats/%s/attachments → 202, attachment_id=%s status=%s" % (chat["id"], att["id"], att["status"])) +job = jobs_cli("status", att["id"])["jobs"][0] +log("2", "job_id=%s pipeline_version=%s attempt=%s status=%s" % (job["job_id"], job["pipeline_version"], job["attempt"], + job["status"])) +r = c.call("GET", "/api/v1/attachments/%s/content" % att["id"], 409, actor=bob) +log("2", "GET /attachments/%s/content → %d (%s)" % (att["id"], r["status"], r["json"]["error"]["code"])) +m = c.call("POST", "/api/v1/chats/%s/messages" % chat["id"], 201, actor=alice, schema="Message", + body={"text": "фото во вложении", "attachment_ids": [att["id"]]}, headers={"Idempotency-Key": uuid.uuid4().hex}) +log("2", "POST message with queued attachment → 201, message_id=%s" % m["json"]["id"]) +m = c.call("POST", "/api/v1/chats/%s/messages" % chat["id"], 201, actor=bob, schema="Message", + body={"text": "обычное сообщение"}, headers={"Idempotency-Key": uuid.uuid4().hex}) +log("2", "POST plain message (bob) → 201, message_id=%s; history works while worker is down" % m["json"]["id"]) +ev = wait(lambda: [e for e in jobs_cli("status", att["id"])["events"] if e["event"] == "published"], 30) +log("2", "job published to JetStream: stream_seq=%s (outbox → relay → publish ack)" % ev[0]["detail"]["stream_seq"]) + +log("3", "restart broker (volume natsdata kept) and API replicas: restart nats; restart api") +sh("restart_broker", timeout=120) +sh("restart_api", timeout=180) +wait(lambda: c.call("GET", "/health/ready", [200, 502, 503])["status"] == 200, 90) +for line in containers(("api", "nats")): + log("3", " " + line) +meta = c.call("GET", "/api/v1/attachments/" + att["id"], actor=bob, schema="Attachment")["json"] +log("3", "after restart: attachment %s status=%s (job survived in PostgreSQL + JetStream)" % (att["id"], meta["status"])) +log("3", "start worker: " + DC + " start worker") +sh("start_worker", timeout=120) +t = time.monotonic() +meta = wait(lambda: (lambda x: x if x["status"] in ("ready", "failed") else None)( + c.call("GET", "/api/v1/attachments/" + att["id"], actor=bob, schema="Attachment")["json"]), 60) +check(meta["status"] == "ready", "not ready") +log("3", "attachment %s status=ready %.1fs after worker start; variants=%s" % ( + att["id"], time.monotonic() - t, ["%s %dx%d" % (v["name"], v["width"], v["height"]) for v in meta["variants"]])) +orig = c.call("GET", "/api/v1/attachments/%s/content" % att["id"], actor=bob)["bytes"] +thumb = c.call("GET", "/api/v1/attachments/%s/content?variant=thumbnail" % att["id"], actor=bob)["bytes"] +check(orig == data, "original differs") +log("3", "original sha256=%s… (= uploaded), thumbnail JPEG %s" % (hashlib.sha256(orig).hexdigest()[:16], jpeg_size(thumb))) +for e in jobs_cli("status", att["id"])["events"]: + log("log", "%s %-24s attempt=%s token=%s %s" % (str(e["created_at"])[11:23], e["event"], e["attempt"], + e["lease_token"], e["detail"] or "")) +print("PASS: defense scenario (worker down → 202 → 409 → restart API+broker → worker → ready)") diff --git a/student-tests/fixtures/alpha.png b/student-tests/fixtures/alpha.png new file mode 100644 index 00000000..7f3693a9 Binary files /dev/null and b/student-tests/fixtures/alpha.png differ diff --git a/student-tests/fixtures/exif6.jpg b/student-tests/fixtures/exif6.jpg new file mode 100644 index 00000000..fe1502ab Binary files /dev/null and b/student-tests/fixtures/exif6.jpg differ diff --git a/student-tests/fixtures/photo.jpg b/student-tests/fixtures/photo.jpg new file mode 100644 index 00000000..1465142a Binary files /dev/null and b/student-tests/fixtures/photo.jpg differ diff --git a/student-tests/fixtures/sof5.jpg b/student-tests/fixtures/sof5.jpg new file mode 100644 index 00000000..fc0bbce4 Binary files /dev/null and b/student-tests/fixtures/sof5.jpg differ diff --git a/student-tests/obs.py b/student-tests/obs.py new file mode 100644 index 00000000..25c4d524 --- /dev/null +++ b/student-tests/obs.py @@ -0,0 +1,177 @@ +"""Доступ к сохранённым наблюдениям через Grafana API (stdlib): Prometheus, Loki, Tempo — через +datasource proxy, т. е. ровно тем путём, которым смотрит человек в Grafana (заодно проверяется provisioning). + +Пароль admin читается из secrets/grafana_admin_password (или GRAFANA_PASSWORD_FILE) и нигде не печатается. +""" +import base64 +import json +import os +import time +import urllib.error +import urllib.parse +import urllib.request +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +GRAFANA_URL = os.environ.get("GRAFANA_URL", "http://127.0.0.1:3000").rstrip("/") +PASSWORD_FILE = os.environ.get("GRAFANA_PASSWORD_FILE", str(ROOT / "secrets" / "grafana_admin_password")) + + +class ObsError(Exception): + pass + + +class Grafana: + def __init__(self, url=GRAFANA_URL, user="admin", password_file=PASSWORD_FILE, timeout=20): + self.url = url + pw = Path(password_file).read_text(encoding="utf-8").strip() + self.auth = "Basic " + base64.b64encode(("%s:%s" % (user, pw)).encode()).decode() + self.opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) + self.timeout = timeout + + def request(self, method, path, params=None, body=None, raw=False): + url = self.url + path + ("?" + urllib.parse.urlencode(params, doseq=True) if params else "") + data = json.dumps(body).encode() if body is not None else None + req = urllib.request.Request(url, data=data, method=method, headers={ + "Authorization": self.auth, "Accept": "application/json", + **({"Content-Type": "application/json"} if data else {})}) + try: + with self.opener.open(req, timeout=self.timeout) as r: + payload = r.read() + except urllib.error.HTTPError as e: + payload = e.read() + if e.code == 404 and raw: + return None + raise ObsError("%s %s -> HTTP %d: %s" % (method, path.split("?")[0], e.code, payload[:300].decode(errors="replace"))) from None + except (urllib.error.URLError, OSError) as e: + raise ObsError("%s %s: %s" % (method, path, type(e).__name__)) from None + return json.loads(payload) if payload else None + + def get(self, path, params=None, **kw): + return self.request("GET", path, params=params, **kw) + + # ------------------------------------------------------------------ Prometheus + def prom(self, expr, at=None): + params = {"query": expr} + if at is not None: + params["time"] = "%.3f" % at + d = self.get("/api/datasources/proxy/uid/prometheus/api/v1/query", params) + if d.get("status") != "success": + raise ObsError("prometheus: %s" % d) + return d["data"]["result"] + + def prom_value(self, expr, default=None, at=None): + res = self.prom(expr, at) + if not res: + return default + return float(res[0]["value"][1]) + + def prom_range(self, expr, start, end, step=5): + d = self.get("/api/datasources/proxy/uid/prometheus/api/v1/query_range", + {"query": expr, "start": "%.3f" % start, "end": "%.3f" % end, "step": step}) + return d["data"]["result"] + + def series(self, match, since=600): + now = time.time() + d = self.get("/api/datasources/proxy/uid/prometheus/api/v1/series", + {"match[]": match, "start": "%.0f" % (now - since), "end": "%.0f" % now}) + return d["data"] + + def alerts(self): + return self.get("/api/datasources/proxy/uid/prometheus/api/v1/alerts")["data"]["alerts"] + + def rules(self): + return self.get("/api/datasources/proxy/uid/prometheus/api/v1/rules")["data"]["groups"] + + # ------------------------------------------------------------------ Loki + def loki(self, query, since=900, limit=200, start=None, end=None): + """Список записей: dict(stream labels + structured metadata) + 'line' + 'ts' (секунды).""" + end = end or time.time() + start = start or end - since + d = self.get("/api/datasources/proxy/uid/loki/loki/api/v1/query_range", + {"query": query, "limit": limit, "start": "%d" % (start * 1e9), "end": "%d" % (end * 1e9), + "direction": "backward"}) + out = [] + for stream in d["data"]["result"]: + for ts, line, *rest in stream["values"]: + rec = dict(stream["stream"]) + if rest and isinstance(rest[0], dict): + rec.update(rest[0].get("structuredMetadata", {})) + rec["line"], rec["ts"] = line, int(ts) / 1e9 + out.append(rec) + return sorted(out, key=lambda r: r["ts"]) + + def loki_metric(self, query, at=None): + d = self.get("/api/datasources/proxy/uid/loki/loki/api/v1/query", + {"query": query, **({"time": "%d" % (at * 1e9)} if at else {})}) + return d["data"]["result"] + + # ------------------------------------------------------------------ Tempo + def trace(self, trace_id): + """Spans trace (плоский список) или None, если Tempo его не нашёл.""" + d = self.get("/api/datasources/proxy/uid/tempo/api/traces/" + trace_id, raw=True) + if d is None: + return None + spans = [] + for b in d.get("batches", d.get("resourceSpans", [])): + res = {a["key"]: _val(a["value"]) for a in b["resource"].get("attributes", [])} + for ss in b.get("scopeSpans", b.get("instrumentationLibrarySpans", [])): + for s in ss.get("spans", []): + spans.append({ + "trace_id": _hex(s["traceId"]), "span_id": _hex(s["spanId"]), + "parent": _hex(s.get("parentSpanId", "")), "name": s["name"], + "kind": s.get("kind", "").replace("SPAN_KIND_", ""), "service": res.get("service.name"), + "instance": res.get("service.instance.id"), + "attrs": {a["key"]: _val(a["value"]) for a in s.get("attributes", [])}, + "links": [_hex(l["spanId"]) for l in s.get("links", [])], + "status": s.get("status", {}).get("code", "").replace("STATUS_CODE_", ""), + "start": int(s["startTimeUnixNano"]) / 1e9, "end": int(s["endTimeUnixNano"]) / 1e9, + "raw": s}) + return spans + + def search(self, traceql, since=1800, limit=50): + now = time.time() + d = self.get("/api/datasources/proxy/uid/tempo/api/search", + {"q": traceql, "start": "%d" % (now - since), "end": "%d" % (now + 60), "limit": limit, + "spss": 50}) + return d.get("traces", []) + + def trace_raw_text(self, trace_id): + d = self.get("/api/datasources/proxy/uid/tempo/api/traces/" + trace_id, raw=True) + return json.dumps(d, ensure_ascii=False) if d else "" + + # ------------------------------------------------------------------ Grafana + def ds_query(self, target, ds, since=900): + now = int(time.time() * 1000) + q = dict(target, refId=target.get("refId", "A"), datasource=ds, intervalMs=10000, maxDataPoints=200) + return self.request("POST", "/api/ds/query", body={"queries": [q], "from": str(now - since * 1000), "to": str(now)}) + + +def _val(v): + for k in ("stringValue", "intValue", "doubleValue", "boolValue"): + if k in v: + return int(v[k]) if k == "intValue" else v[k] + return v + + +def _hex(b64_or_hex): + """Tempo отдаёт ID в base64 (protobuf JSON) — приводим к hex, как в логах.""" + if not b64_or_hex: + return "" + if all(c in "0123456789abcdef" for c in b64_or_hex) and len(b64_or_hex) in (16, 32): + return b64_or_hex + return base64.b64decode(b64_or_hex).hex() + + +def wait_for(probe, timeout=60, interval=1.0, what="condition"): + deadline = time.monotonic() + timeout + last_exc = None + while time.monotonic() < deadline: + try: + v = probe() + if v: + return v + except ObsError as e: + last_exc = e + time.sleep(interval) + raise ObsError("%s not observed in %ss%s" % (what, timeout, (" (%s)" % last_exc) if last_exc else "")) diff --git a/student-tests/s3_admin.py b/student-tests/s3_admin.py new file mode 100644 index 00000000..0d450dcd --- /dev/null +++ b/student-tests/s3_admin.py @@ -0,0 +1,84 @@ +"""Внедрение отказов на стороне S3 «в обход API» (только для тестов). + +Выполняется ВНУТРИ контейнера s3-init (у него есть admin-ключи и сеть objects); тестам передаётся +через stdin: docker compose run --rm --no-deps -T --entrypoint python s3-init - [b64] + put — записать объект; delete — удалить; sha — SHA-256 или "-" + ls — ключи по префиксу; anon-get — HTTP-статус анонимного GET. + seed — n случайных объектов (параллельно), печать «key sha256 size»; + purge — удалить все объекты с префиксом (уборка после эксперимента). +""" +import asyncio +import base64 +import hashlib +import os +import sys + +from messenger.config import _secret +from messenger.s3 import S3Client, S3Error + + +async def seed(s3, bucket, prefix, n, size): + import uuid + sem = asyncio.Semaphore(32) + + async def one(): + body = os.urandom(size) + key = prefix + uuid.uuid4().hex + async with sem: + await s3.put_object(bucket, key, body) + print(key, hashlib.sha256(body).hexdigest(), size) + for start in range(0, n, 500): # пачками: 20k корутин сразу не влезают в 128 МиБ контейнера + await asyncio.gather(*(one() for _ in range(min(500, n - start)))) + + +async def purge(s3, bucket, prefix): + keys = [o.key async for o in s3.list_objects(bucket, prefix=prefix)] + sem = asyncio.Semaphore(32) + + async def one(k): + async with sem: + await s3.delete_object(bucket, k) + for start in range(0, len(keys), 500): + await asyncio.gather(*(one(k) for k in keys[start:start + 500])) + print(len(keys)) + + +async def main(op, key, data=None, extra=None): + bucket = os.environ.get("S3_BUCKET", "messenger-attachments") + endpoint = os.environ.get("S3_ENDPOINT", "http://s3:9000") + if op == "anon-get": + import httpx + async with httpx.AsyncClient() as c: + print((await c.get(f"{endpoint}/{bucket}/{key}")).status_code) + return + s3 = S3Client(endpoint, os.environ.get("S3_REGION", "us-east-1"), + _secret("S3_ADMIN_ACCESS_KEY_ID", True), _secret("S3_ADMIN_SECRET_ACCESS_KEY", True)) + try: + if op == "put": + await s3.put_object(bucket, key, base64.b64decode(data), "application/octet-stream") + elif op == "delete": + await s3.delete_object(bucket, key) + elif op == "sha": + try: + resp = await s3.get_object_stream(bucket, key) + except S3Error as exc: + if exc.status == 404: + print("-") + return + raise + print(hashlib.sha256(await resp.aread()).hexdigest()) + await resp.aclose() + elif op == "seed": + await seed(s3, bucket, key, int(data), int(extra)) + elif op == "purge": + await purge(s3, bucket, key) + elif op == "ls": + async for o in s3.list_objects(bucket, prefix=key): + print(o.key, o.size) + else: + raise SystemExit("unknown op " + op) + finally: + await s3.aclose() + + +asyncio.run(main(*sys.argv[1:])) diff --git a/student-tests/test_api.py b/student-tests/test_api.py new file mode 100644 index 00000000..0b2caf68 --- /dev/null +++ b/student-tests/test_api.py @@ -0,0 +1,238 @@ +#!/usr/bin/env python3 +"""Негативные и контрактные проверки уровня 3/4: аутентификация, KDF, валидация, ACL, пагинация, +атомарность/rollback создания чата, гонка регистрации, параметризация SQL.""" +import hashlib +import threading +import uuid +from urllib.parse import quote + +from common import BASE_URL, Client, Suite, basic, check, login, new_user, sql + +c = Client(BASE_URL) +s = Suite("API, auth, validation, ACL, transactions (" + BASE_URL + ")") +alice = new_user(c, "alice"); login(c, alice) +bob = new_user(c, "bob"); login(c, bob) +eve = new_user(c, "eve"); login(c, eve) +chat = c.call("POST", "/api/v1/chats", 201, actor=alice, schema="Chat", + body={"title": "student-tests", "member_ids": [alice["id"], bob["id"]]})["json"] +CHAT = "/api/v1/chats/" + chat["id"] + + +@s.case("password stored only as scrypt KDF hash; User has no secret fields") +def _(): + row = sql("SELECT password_hash FROM users WHERE id = '%s'" % alice["id"])[0] + check(row.startswith("$scrypt$ln=15,r=8,p=3$"), "unexpected hash format") + check(alice["password"] not in row, "plaintext password in DB") + check(set(alice["user"]) == {"id", "username", "display_name", "created_at"}, "User leaks fields") + other = new_user(c, "same", password=alice["password"]) + h2 = sql("SELECT password_hash FROM users WHERE id = '%s'" % other["id"])[0] + check(h2 != row, "same password produced same hash: salt missing") + + +@s.case("wrong password and unknown user: identical 401 + Basic challenge") +def _(): + r1 = c.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": basic(alice["username"], "wrong-password-123")}) + r2 = c.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": basic("no_such_user_x", "wrong-password-123")}) + check(r1["json"]["error"]["message"] == r2["json"]["error"]["message"], "messages differ") + check(r1["headers"]["WWW-Authenticate"] == 'Basic realm="messenger", charset="UTF-8"', "challenge mismatch") + + +@s.case("malformed Basic / Bearer on /auth/sessions / body on login") +def _(): + for value in ("Basic", "Basic !!!", "Basic " + "bm9jb2xvbg==", "Bearer " + "x" * 43): + c.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": value}) + c.call("POST", "/api/v1/auth/sessions", 401) + c.call("POST", "/api/v1/auth/sessions", 400, body={"username": alice["username"]}, + headers={"Authorization": basic(alice["username"], alice["password"])}) + + +@s.case("password with ':' and non-ASCII UTF-8 works (RFC 7617)") +def _(): + u = new_user(c, "colon", password="пароль:с:двоеточием-😀") + login(c, u) + me = c.call("GET", "/api/v1/users/me", actor=u, schema="User")["json"] + check(me["id"] == u["id"], "wrong user") + + +@s.case("opaque 256-bit token, unique per login, DB stores only SHA-256") +def _(): + a, b = dict(alice), dict(alice) + login(c, a); login(c, b) + check(a["token"] != b["token"] and len(a["token"]) == 43, "token not unique/opaque") + check(a["token"] not in (alice["id"], alice["username"]), "token derived from identity") + digest = hashlib.sha256(a["token"].encode()).hexdigest() + check(sql("SELECT count(*) FROM sessions WHERE token_hash = decode('%s','hex')" % digest) == ["1"], "hash not found") + check(sql("SELECT count(*) FROM information_schema.columns WHERE table_name = 'sessions'" + " AND data_type IN ('text', 'character varying')") == ["0"], "sessions has a text column for raw token") + + +@s.case("only Bearer accepted; Basic and X-User-Id never authenticate") +def _(): + c.call("GET", "/api/v1/users/me", 401, headers={"Authorization": basic(alice["username"], alice["password"])}) + c.call("GET", "/api/v1/chats", 401, headers={"X-User-Id": alice["id"]}) + c.call("GET", "/api/v1/users/me", 401, headers={"Authorization": "Bearer " + "A" * 43}) + c.call("GET", "/api/v1/users/me", 401, headers={"Authorization": "Bearer short"}) + me = c.call("GET", "/api/v1/users/me", actor=bob, headers={"X-User-Id": alice["id"]}, schema="User")["json"] + check(me["id"] == bob["id"], "X-User-Id overrode session") + + +@s.case("logout revokes only the current session; repeat -> 401") +def _(): + u = new_user(c, "logout"); first = dict(u); second = dict(u) + login(c, first); login(c, second) + c.call("GET", "/api/v1/users/me", actor=first, schema="User") # прогреть кэш + c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=first) + for path in ("/api/v1/users/me", "/api/v1/chats"): + c.call("GET", path, 401, actor=first) + c.call("DELETE", "/api/v1/auth/sessions/current", 401, actor=first) + c.call("GET", "/api/v1/users/me", actor=second, schema="User") + check(sql("SELECT count(*) FROM sessions WHERE user_id='%s' AND revoked_at IS NOT NULL" % u["id"]) == ["1"], + "revocation not persisted") + + +@s.case("strict JSON validation -> 400") +def _(): + base = {"username": "valid_" + uuid.uuid4().hex[:8], "display_name": "X", "password": "p" * 12} + bad = [dict(base, extra=1), dict(base, username="UPPER"), dict(base, username="ab"), + dict(base, display_name=" "), dict(base, display_name="x" * 101), dict(base, password="p" * 11), + dict(base, password="p" * 129), dict(base, display_name=5), {"username": base["username"]}] + for body in bad: + c.call("POST", "/api/v1/users", 400, body=body) + c.call("POST", "/api/v1/users", 400, raw=b'{"username": ', headers={"Content-Type": "application/json"}) + c.call("POST", "/api/v1/users", 400, raw=b'[1,2]', headers={"Content-Type": "application/json"}) + c.call("POST", "/api/v1/users", 400, raw=b'{"username":"a","username":"b"}', headers={"Content-Type": "application/json"}) + c.call("POST", "/api/v1/users", 400, raw=b'username=x', headers={"Content-Type": "application/x-www-form-urlencoded"}) + c.call("POST", "/api/v1/users", 413, raw=b'{"x":"' + b"a" * 70000 + b'"}', headers={"Content-Type": "application/json"}) + + +@s.case("message text: 4000 code points OK, 4001 / whitespace / sender_id -> 400") +def _(): + msg = c.message(alice, chat, "😀" * 4000)["json"] + check(len(msg["text"]) == 4000, "text truncated") + for body in ({"text": "a" * 4001}, {"text": " \n\t "}, {"text": "x", "sender_id": bob["id"]}, {"text": None}, {}): + c.call("POST", CHAT + "/messages", 400, actor=alice, body=body) + + +@s.case("SQL is parameterized: injection payloads stored verbatim") +def _(): + payload = "'); DROP TABLE messages; -- \" \\ %s $1" + msg = c.message(alice, chat, payload)["json"] + check(msg["text"] == payload, "payload altered") + c.call("GET", CHAT + "/messages?limit=1", actor=alice, schema="MessagePage") + c.call("GET", "/api/v1/chats/" + quote("' OR 1=1 --", safe=""), 400, actor=alice) + + +@s.case("ACL: outsider gets 404 everywhere (even for invalid body)") +def _(): + c.call("GET", CHAT, 404, actor=eve) + c.call("GET", CHAT + "/messages", 404, actor=eve) + c.call("POST", CHAT + "/messages", 404, actor=eve, body={"text": "x"}) + c.call("POST", CHAT + "/messages", 404, actor=eve, body={"text": ""}) + c.call("GET", "/api/v1/chats/" + str(uuid.uuid4()), 404, actor=alice) + c.call("GET", "/api/v1/chats/not-a-uuid", 400, actor=alice) + got = c.call("GET", CHAT, actor=bob, schema="Chat")["json"] + check(got["member_ids"] == [alice["id"], bob["id"]], "member order/content changed") + + +@s.case("create chat validation: duplicates, caller missing, unknown member") +def _(): + c.call("POST", "/api/v1/chats", 400, actor=alice, body={"title": "d", "member_ids": [alice["id"], alice["id"]]}) + c.call("POST", "/api/v1/chats", 400, actor=alice, body={"title": "d", "member_ids": [bob["id"]]}) + c.call("POST", "/api/v1/chats", 400, actor=alice, body={"title": "d", "member_ids": []}) + c.call("POST", "/api/v1/chats", 400, actor=alice, body={"title": " ", "member_ids": [alice["id"]]}) + + +@s.case("compound create-chat rolls back on FK failure (no orphan chat)") +def _(): + title = "rollback-" + uuid.uuid4().hex + before = sql("SELECT count(*) FROM chats")[0] + c.call("POST", "/api/v1/chats", 400, actor=alice, + body={"title": title, "member_ids": [alice["id"], bob["id"], str(uuid.uuid4())]}) + check(sql("SELECT count(*) FROM chats WHERE title = '%s'" % title) == ["0"], "orphan chat committed") + check(sql("SELECT count(*) FROM chat_members m LEFT JOIN chats c ON c.id = m.chat_id WHERE c.id IS NULL") == ["0"], + "orphan membership") + return "chats before=%s, failed insert left 0 rows" % before + + +@s.case("registration race: 20 parallel same username -> exactly one 201") +def _(): + username = "race_" + uuid.uuid4().hex[:12] + statuses, lock = [], threading.Lock() + barrier = threading.Barrier(20) + + def worker(): + local = Client(BASE_URL, timeout=30) + barrier.wait() + r = local.call("POST", "/api/v1/users", [201, 409], + body={"username": username, "display_name": "R", "password": "Race-password-123"}) + with lock: + statuses.append(r["status"]) + threads = [threading.Thread(target=worker) for _ in range(20)] + [t.start() for t in threads]; [t.join() for t in threads] + check(sorted(statuses) == [201] + [409] * 19, "statuses: %s" % sorted(statuses)) + check(sql("SELECT count(*) FROM users WHERE username = '%s'" % username) == ["1"], "duplicate rows") + return "201x1, 409x19, rows=1" + + +@s.case("keyset pagination: 120 msgs, varying limit, no gaps/duplicates") +def _(): + room = c.call("POST", "/api/v1/chats", 201, actor=alice, schema="Chat", + body={"title": "pages", "member_ids": [alice["id"], bob["id"]]})["json"] + path = "/api/v1/chats/" + room["id"] + "/messages" + sent = [c.message(alice if i % 2 else bob, room, "m%03d" % i)["json"] for i in range(120)] + got, cursor, limits, n = [], None, [7, 1, 50, 100, 3], 0 + while True: + q = "?limit=%d" % limits[n % len(limits)] + ("&cursor=" + quote(cursor, safe="") if cursor else "") + page = c.call("GET", path + q, actor=bob, schema="MessagePage")["json"] + got.extend(page["items"]); cursor = page["next_cursor"]; n += 1 + if cursor is None: + break + check([m["id"] for m in got] == [m["id"] for m in sent], "order/completeness mismatch") + first = c.call("GET", path + "?limit=2", actor=bob, schema="MessagePage")["json"] + c.call("GET", CHAT + "/messages?cursor=" + quote(first["next_cursor"], safe=""), 400, actor=alice) + for q in ("?limit=0", "?limit=101", "?limit=abc", "?limit=-1", "?limit=1&limit=2", "?cursor=garbage", "?cursor="): + c.call("GET", path + q, 400, actor=bob) + default = c.call("GET", path, actor=bob, schema="MessagePage")["json"] + check(len(default["items"]) == 50 and default["next_cursor"], "default limit must be 50") + return "%d pages" % n + + +@s.case("chat list: only own chats, ordered, cursor bound to user") +def _(): + u = new_user(c, "lister"); login(c, u) + made = [c.call("POST", "/api/v1/chats", 201, actor=u, schema="Chat", + body={"title": "c%d" % i, "member_ids": [u["id"]]})["json"]["id"] for i in range(3)] + got, cursor = [], None + while True: + page = c.call("GET", "/api/v1/chats?limit=1" + ("&cursor=" + quote(cursor, safe="") if cursor else ""), + actor=u, schema="ChatPage")["json"] + got += [x["id"] for x in page["items"]]; cursor = page["next_cursor"] + if cursor is None: + break + foreign = cursor + check(got == made, "chat list mismatch") + c.call("GET", "/api/v1/chats?cursor=" + quote(foreign, safe=""), 400, actor=alice) + + +@s.case("read-after-write: confirmed message visible to next read") +def _(): + m = c.message(bob, chat, "raw-" + uuid.uuid4().hex)["json"] + items, cursor = [], None + while True: + page = c.call("GET", CHAT + "/messages?limit=100" + ("&cursor=" + quote(cursor, safe="") if cursor else ""), + actor=alice, schema="MessagePage")["json"] + items += page["items"]; cursor = page["next_cursor"] + if not cursor: + break + check(items[-1] == m, "last message is not the just-written one") + + +@s.case("unknown route 404 / wrong method 405 in error format") +def _(): + c.call("GET", "/api/v1/nope", 404) + r = c.call("PUT", "/api/v1/users", 405, body={}) + check(r["json"]["error"]["code"] == "invalid_request", "405 code") + + +if __name__ == "__main__": + s.run() diff --git a/student-tests/test_attachments.py b/student-tests/test_attachments.py new file mode 100644 index 00000000..a3b771af --- /dev/null +++ b/student-tests/test_attachments.py @@ -0,0 +1,251 @@ +#!/usr/bin/env python3 +"""Вложения (lab4, адаптировано к lab5: upload → 202, готовность — по статусу): корректные файлы, лимиты, повреждения, подмена MIME, filename, ACL, чужие ID. + +Каждая пользовательская ошибка обязана дать 4xx из контракта, а не 500 (Client проверяет код и формат +Error). Только синтетические данные; стенд и volumes не трогаются. +""" +import hashlib +import os +import socket +import time +import uuid +import zlib +from pathlib import Path +from urllib.parse import quote, urlsplit + +from common import BASE_URL, Client, Suite, check, login, make_png, new_user + +c = Client(BASE_URL, timeout=30) +s = Suite("attachments (" + BASE_URL + ")") +JPEG = (Path(__file__).parent / "fixtures" / "photo.jpg").read_bytes() +MAX = int(os.environ.get("MAX_UPLOAD_BYTES", str(10 * 1024 * 1024))) +alice = new_user(c, "aa"); login(c, alice) +bob = new_user(c, "ab"); login(c, bob) +eve = new_user(c, "ae"); login(c, eve) +chat = c.call("POST", "/api/v1/chats", 201, actor=alice, schema="Chat", + body={"title": "files", "member_ids": [alice["id"], bob["id"]]})["json"] +other = c.call("POST", "/api/v1/chats", 201, actor=alice, schema="Chat", + body={"title": "other", "member_ids": [alice["id"]]})["json"] +UP = "/api/v1/chats/" + chat["id"] + "/attachments" + + +def chunk(t, d): + return len(d).to_bytes(4, "big") + t + d + zlib.crc32(t + d).to_bytes(4, "big") + + +def png_with(width, height, idat_raw, color_type=2, level=9): + ihdr = width.to_bytes(4, "big") + height.to_bytes(4, "big") + bytes([8, color_type, 0, 0, 0]) + return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(idat_raw, level)) + + chunk(b"IEND", b"")) + + +def big_png(target): + """Несжимаемый RGB PNG размером чуть меньше target байт.""" + side = int(((target - 4096) / 3) ** 0.5) + rows = b"".join(b"\x00" + os.urandom(side * 3) for _ in range(side)) + return png_with(side, side, rows, level=1) + + +def post(data, ctype="image/png", filename="f.png", expected=202, actor=None, chat_id=None): + path = "/api/v1/chats/" + (chat_id or chat["id"]) + "/attachments?filename=" + quote(filename, safe="") + return c.call("POST", path, expected, actor=actor or alice, raw=data, headers={"Content-Type": ctype}, + schema="Attachment" if expected == 202 else None) + + +def ready(att): + """lab5: content доступен только после ready (до этого — 409).""" + return c.wait_ready(alice, att) + + +def raw_http(head: bytes, body: bytes = b"", wait=5.0): + """Сырые байты через сокет: запрос, который urllib не умеет отправить (обрыв, ложный Content-Length).""" + u = urlsplit(BASE_URL) + sock = socket.create_connection((u.hostname, u.port or 80), timeout=wait) + try: + sock.sendall(head + body) + t = time.monotonic() + data = b"" + while b"\r\n" not in data: + part = sock.recv(4096) + if not part: + break + data += part + return data.split(b"\r\n", 1)[0].decode(errors="replace"), time.monotonic() - t + finally: + sock.close() + + +@s.case("valid PNG and JPEG: 202 queued → ready, byte-exact download by other member") +def _(): + png = make_png(40, 30) + for data, ctype, name in ((png, "image/png", "фото отпуска.png"), (JPEG, "image/jpeg", "photo.jpg")): + att = post(data, ctype, name)["json"] + check(att["status"] in ("queued", "processing", "ready") and att["size_bytes"] == len(data), "bad metadata") + att = ready(att) + check(att["sha256"] == hashlib.sha256(data).hexdigest() and att["filename"] == name, "sha/filename mismatch") + r = c.call("GET", "/api/v1/attachments/" + att["id"] + "/content", actor=bob) + check(r["bytes"] == data, "download differs") + h = r["headers"] + check(h.get_content_type() == ctype and h.get("X-Content-Type-Options") == "nosniff", "unsafe headers") + check(int(h["Content-Length"]) == len(data), "Content-Length") + check("attachment" in h.get("Content-Disposition", "") or "inline" in h.get("Content-Disposition", ""), + "Content-Disposition missing") + msg = c.message(alice, chat, "", attachments=[att["id"]])["json"] # пустой текст + вложение + check(msg["attachment_ids"] == [att["id"]], "message lost attachment") + + +@s.case("exactly-near limit (~10 MiB) accepted, Content-Length > limit -> 413") +def _(): + data = big_png(MAX) + check(len(data) <= MAX, "fixture too big") + att = post(data, filename="big.png")["json"] + check(att["size_bytes"] == len(data), "size") + over = data + b"\x00" * (MAX + 1 - len(data)) + post(over, filename="over.png", expected=413) + return "%.2f MiB accepted" % (len(data) / 2**20) + + +@s.case("oversize rejected BEFORE body is read (early 413, socket)") +def _(): + u = urlsplit(BASE_URL) + head = ("POST %s?filename=x.png HTTP/1.1\r\nHost: %s\r\nAuthorization: Bearer %s\r\nContent-Type: image/png\r\n" + "Content-Length: %d\r\nConnection: close\r\n\r\n" % (UP, u.netloc, alice["token"], 50 * 2**20)).encode() + status, took = raw_http(head, b"\x89PNG\r\n\x1a\n") + check(" 413 " in status + " ", "expected 413, got " + status) + check(took < 3, "413 took %.2fs (body awaited?)" % took) + return "%s in %.3fs, 50 MiB never sent" % (status, took) + + +@s.case("pixel limit: 8000x6000 header -> 413 without decoding") +def _(): + # 48 млн пикселей > 40 млн: отклоняется по IHDR/SOF, IDAT даже не нужен корректный + ihdr = (8000).to_bytes(4, "big") + (6000).to_bytes(4, "big") + bytes([8, 2, 0, 0, 0]) + bomb = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(b"\x00" * 1000)) + chunk(b"IEND", b"") + t = time.monotonic() + post(bomb, expected=413) + jpeg = bytearray(JPEG) + i = jpeg.find(b"\xff\xc0") + jpeg[i + 5:i + 9] = (7000).to_bytes(2, "big") + (7000).to_bytes(2, "big") # SOF: 49 Мп + post(bytes(jpeg), "image/jpeg", "big.jpg", expected=413) + return "%.3fs" % (time.monotonic() - t) + + +@s.case("decompression bomb: IDAT inflates beyond declared size -> 415") +def _(): + bomb = png_with(100, 100, b"\x00" * (64 * 2**20)) # 64 МиБ нулей сжимаются в ~64 КиБ + check(len(bomb) < 200_000, "bomb not small") + t = time.monotonic() + post(bomb, expected=415) + return "%d-byte file claiming 64 MiB raw, rejected in %.3fs" % (len(bomb), time.monotonic() - t) + + +@s.case("corrupted images -> 415 (truncated, bad CRC, no EOI, garbage, empty)") +def _(): + png = make_png(20, 20) + bad_crc = bytearray(png); bad_crc[30] ^= 0x01 + cases = [(png[:-12], "image/png"), (bytes(bad_crc), "image/png"), (JPEG[:-2], "image/jpeg"), + (JPEG[:len(JPEG) // 2], "image/jpeg"), (os.urandom(4096), "image/png"), + (b"\x89PNG\r\n\x1a\n" + os.urandom(500), "image/png"), (b"\xff\xd8\xff" + os.urandom(500), "image/jpeg"), + (png + b"trailing-garbage", "image/png"), (b"", "image/png")] + for data, ctype in cases: + post(data, ctype, expected=415) + return "%d variants" % len(cases) + + +@s.case("MIME spoofing by Content-Type/filename -> 415") +def _(): + gif = b"GIF89a\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\xff\xff\xff!\xf9\x04\x01\x00\x00\x00\x00,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;" + cases = [(make_png(), "image/jpeg", "a.jpg"), (JPEG, "image/png", "a.png"), + (b"", "image/png", "a.png"), + (gif, "image/png", "a.png"), (gif, "image/gif", "a.gif"), (make_png(), "application/octet-stream", "a.png"), + (make_png(), "text/html", "a.html"), (b"", "image/svg+xml", "a.svg")] + for data, ctype, name in cases: + post(data, ctype, name, expected=415) + + +@s.case("dangerous/invalid filenames -> 400; filename never becomes a path") +def _(): + png = make_png() + for name in ("", "../../etc/passwd", "a/b.png", "a\\b.png", "x\x00.png", "line\nbreak.png", "\t.png", ".", "..", + "x" * 256, "‮evil.png"): + post(png, filename=name, expected=400) + c.call("POST", UP, 400, actor=alice, raw=png, headers={"Content-Type": "image/png"}) # filename отсутствует + ok = post(png, filename="y" * 251 + ".png")["json"] + check(len(ok["filename"]) == 255, "255-char name must be accepted") + + +@s.case("missing/invalid Content-Length -> 400 (chunked upload is not accepted)") +def _(): + u = urlsplit(BASE_URL) + head = ("POST %s?filename=x.png HTTP/1.1\r\nHost: %s\r\nAuthorization: Bearer %s\r\nContent-Type: image/png\r\n" + "Transfer-Encoding: chunked\r\nConnection: close\r\n\r\n" % (UP, u.netloc, alice["token"])).encode() + png = make_png() + status, _ = raw_http(head, b"%x\r\n" % len(png) + png + b"\r\n0\r\n\r\n") + check(" 400 " in status + " " or " 411 " in status + " ", "chunked upload: " + status) + return status + + +@s.case("ACL: outsider gets 404 for upload/metadata/content; anonymous 401") +def _(): + att = post(make_png())["json"] + t = time.monotonic() + post(big_png(MAX), actor=eve, expected=404) # посторонний — 404 до чтения 10 МиБ + took = time.monotonic() - t + for path in ("", "/content", "/content?variant=original"): + c.call("GET", "/api/v1/attachments/" + att["id"] + path, 404, actor=eve) + c.call("GET", "/api/v1/attachments/" + att["id"] + path, 401) + c.call("GET", "/api/v1/attachments/" + str(uuid.uuid4()), 404, actor=alice) + c.call("GET", "/api/v1/attachments/not-a-uuid", [400, 404], actor=alice) + c.call("POST", UP + "?filename=a.png", 401, raw=make_png(), headers={"Content-Type": "image/png"}) + c.call("POST", "/api/v1/chats/" + str(uuid.uuid4()) + "/attachments?filename=a.png", 404, actor=alice, + raw=make_png(), headers={"Content-Type": "image/png"}) + return "outsider 10 MiB upload rejected in %.2fs" % took + + +@s.case("variants (lab5): original/thumbnail/crop/optimized OK after ready, unknown -> 400") +def _(): + att = ready(post(make_png())["json"]) + for v in ("original", "thumbnail", "crop", "optimized"): + c.call("GET", "/api/v1/attachments/" + att["id"] + "/content?variant=" + v, actor=bob) + c.call("GET", "/api/v1/attachments/" + att["id"] + "/content?variant=../../x", 400, actor=bob) + + +@s.case("message: foreign/unknown attachment_id -> 404, file of other chat -> 404, limits -> 400") +def _(): + mine = post(make_png())["json"] + foreign = post(make_png(), chat_id=other["id"])["json"] # тот же владелец, ДРУГОЙ чат + path = "/api/v1/chats/" + chat["id"] + "/messages" + + def send(body, expected, actor=alice): + return c.call("POST", path, expected, actor=actor, body=body, headers={"Idempotency-Key": uuid.uuid4().hex}) + send({"text": "x", "attachment_ids": [foreign["id"]]}, 404) + send({"text": "x", "attachment_ids": [mine["id"], foreign["id"]]}, 404) + send({"text": "x", "attachment_ids": [str(uuid.uuid4())]}, 404) + send({"text": "x", "attachment_ids": ["nope"]}, 400) + send({"text": "x", "attachment_ids": [mine["id"], mine["id"]]}, 400) + send({"text": "x", "attachment_ids": [str(uuid.uuid4()) for _ in range(11)]}, 400) + send({"text": "", "attachment_ids": []}, 400) + send({"text": ""}, 400) + send({"text": "x" * 4001, "attachment_ids": [mine["id"]]}, 400) + # постороннему чат не виден вовсе + c.call("POST", path, 404, actor=eve, body={"text": "x", "attachment_ids": [mine["id"]]}, + headers={"Idempotency-Key": uuid.uuid4().hex}) + hist = c.call("GET", path + "?limit=50", actor=bob, schema="MessagePage")["json"] + check(all(foreign["id"] not in m.get("attachment_ids", []) for m in hist["items"]), "foreign file leaked") + + +@s.case("idempotency includes attachment_ids (replay same, conflict on change)") +def _(): + a, b = post(make_png())["json"], post(make_png())["json"] + path = "/api/v1/chats/" + chat["id"] + "/messages" + key = uuid.uuid4().hex + first = c.call("POST", path, 201, actor=alice, body={"text": "k", "attachment_ids": [a["id"], b["id"]]}, + headers={"Idempotency-Key": key}, schema="Message")["json"] + again = c.call("POST", path, [200, 201], actor=alice, body={"text": "k", "attachment_ids": [a["id"], b["id"]]}, + headers={"Idempotency-Key": key}, schema="Message")["json"] + check(again["id"] == first["id"] and again["attachment_ids"] == [a["id"], b["id"]], "replay differs") + c.call("POST", path, 409, actor=alice, body={"text": "k", "attachment_ids": [b["id"], a["id"]]}, + headers={"Idempotency-Key": key}) + + +s.run() diff --git a/student-tests/test_cache_race.py b/student-tests/test_cache_race.py new file mode 100644 index 00000000..31710364 --- /dev/null +++ b/student-tests/test_cache_race.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python3 +"""In-process проверки политики кэша сессий против настоящего Redis/Valkey (нужен CACHE_URL[_FILE]). + +Сценарий гонки: запрос A прочитал сессию из PostgreSQL ДО logout, а записать её в кэш пытается ПОСЛЕ +logout. Без защиты отозванный токен жил бы в кэше до SESSION_CACHE_TTL_SECONDS. Защита — «надгробие» +и атомарный Lua SET-if-not-revoked. Запуск в Compose: make test-cache-race. +""" +import asyncio +import os +import secrets +import sys +import time +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) +os.environ.setdefault("DATABASE_URL", "postgresql://unused") # БД этому тесту не нужна + +from messenger.config import load # noqa: E402 +from messenger.sessions import KEY, TOMBSTONE, Principal, SessionCache # noqa: E402 + + +async def main(): + settings = load() + if not settings.cache_enabled: + raise SystemExit("CACHE_URL or CACHE_URL_FILE is required") + cache = SessionCache(settings) + cache.degraded = False + user = {"id": "00000000-0000-4000-8000-000000000000", "username": "cache_test", "display_name": "t", + "created_at": "2026-01-01T00:00:00.000000Z"} + failures = 0 + + def report(ok, title, note=""): + nonlocal failures + failures += 0 if ok else 1 + print(("PASS " if ok else "FAIL ") + title + ((" " + note) if note else "")) + + th = secrets.token_bytes(32) + p = Principal(user=user, expires_at=time.time() + 3600, token_hash=th) + await cache.put(p) + report((await cache.get(th)) is not None, "read-through put makes entry readable") + ttl = await cache.client.pttl(KEY + th.hex()) + report(0 < ttl <= settings.session_cache_ttl_seconds * 1000, "entry TTL capped by SESSION_CACHE_TTL_SECONDS", + "pttl=%dms" % ttl) + + await cache.invalidate(th) # logout + report((await cache.get(th)) is None, "invalidate removes entry") + await cache.put(p) # «опоздавший» read-through после logout + report((await cache.client.exists(KEY + th.hex())) == 0, "late put after logout is refused by tombstone") + tomb = await cache.client.pttl(TOMBSTONE + th.hex()) + report(tomb > settings.session_cache_ttl_seconds * 1000, "tombstone outlives any cache entry", "pttl=%dms" % tomb) + + th2 = secrets.token_bytes(32) + await cache.put(Principal(user=user, expires_at=time.time() + 1.2, token_hash=th2)) + ttl2 = await cache.client.pttl(KEY + th2.hex()) + report(0 < ttl2 <= 1200, "entry never outlives session expiry", "pttl=%dms" % ttl2) + await asyncio.sleep(1.3) + report((await cache.get(th2)) is None, "expired session not served from cache") + + th3 = secrets.token_bytes(32) + await cache.put(Principal(user=user, expires_at=time.time() + 3600, token_hash=th3)) + cache._fail("test", ConnectionError("simulated")) + report((await cache.get(th3)) is None, "degraded mode: cache is not read until outbox drained") + + await cache.client.delete(KEY + th.hex(), TOMBSTONE + th.hex(), KEY + th3.hex()) + await cache.close() + print("summary: %s" % ("all passed" if not failures else "%d failed" % failures)) + raise SystemExit(1 if failures else 0) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/student-tests/test_expiry.py b/student-tests/test_expiry.py new file mode 100644 index 00000000..07aa6509 --- /dev/null +++ b/student-tests/test_expiry.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python3 +"""Истечение сессии при коротком SESSION_TTL_SECONDS (экземпляр api-ttl, профиль compose `ttl`). + +Проверяет и путь через кэш Redis (запись кэша прогрета сразу после входа), и путь через PostgreSQL: +TTL записи в кэше = min(SESSION_CACHE_TTL_SECONDS, остаток сессии), поэтому кэш не продлевает сессию. +""" +import datetime as dt +import time + +from common import TTL_BASE_URL, TTL_SECONDS, Client, Suite, check, login, new_user, sql + +c = Client(TTL_BASE_URL) +s = Suite("session expiry, SESSION_TTL_SECONDS=%g (%s)" % (TTL_SECONDS, TTL_BASE_URL)) + + +@s.case("expires_at = now + SESSION_TTL_SECONDS") +def _(): + u = new_user(c, "ttl"); login(c, u) + left = dt.datetime.fromisoformat(u["expires_at"][:-1] + "+00:00") - dt.datetime.now(dt.timezone.utc) + check(0 < left.total_seconds() <= TTL_SECONDS + 0.5, "unexpected TTL: %s" % left) + return "remaining %.2fs" % left.total_seconds() + + +@s.case("token valid before expiry, 401 Bearer after (cache warmed)") +def _(): + u = new_user(c, "ttl2"); login(c, u) + c.call("GET", "/api/v1/users/me", actor=u, schema="User") # заполняет кэш + c.call("GET", "/api/v1/chats", actor=u, schema="ChatPage") + time.sleep(TTL_SECONDS + 1.0) + r = c.call("GET", "/api/v1/users/me", 401, actor=u) + check(r["headers"]["WWW-Authenticate"].startswith("Bearer"), "challenge") + c.call("DELETE", "/api/v1/auth/sessions/current", 401, actor=u) + rows = sql("SELECT (expires_at < clock_timestamp())::text, (revoked_at IS NULL)::text FROM sessions s" + " JOIN users u ON u.id = s.user_id WHERE u.username = '%s'" % u["username"]) + check(rows == ["true|true"], "expiry must come from expires_at, not deletion/revocation: %s" % rows) + + +@s.case("re-login after expiry issues a new valid session") +def _(): + u = new_user(c, "ttl3"); login(c, u) + old = u["token"] + time.sleep(TTL_SECONDS + 1.0) + c.call("GET", "/api/v1/users/me", 401, actor=u) + login(c, u) + check(u["token"] != old, "token reused") + c.call("GET", "/api/v1/users/me", actor=u, schema="User") + + +if __name__ == "__main__": + s.run() diff --git a/student-tests/test_failures.py b/student-tests/test_failures.py new file mode 100644 index 00000000..156081a6 --- /dev/null +++ b/student-tests/test_failures.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python3 +"""Отказы зависимостей: Redis (кэш) и PostgreSQL (источник истины). + +ВНИМАНИЕ: тест останавливает и снова запускает контейнеры redis и postgres (по умолчанию через +docker compose; команды переопределяются STOP_DB/START_DB/STOP_CACHE/START_CACHE). Volumes не трогает. +""" +import time +import uuid + +from common import BASE_URL, Client, Failure, Suite, basic, check, login, new_user, sh, sql, wait_until + +c = Client(BASE_URL, timeout=10) +s = Suite("dependency failures (" + BASE_URL + ")") +alice = new_user(c, "fa"); login(c, alice) +bob = new_user(c, "fb"); login(c, bob) +chat = c.call("POST", "/api/v1/chats", 201, actor=alice, schema="Chat", + body={"title": "failures", "member_ids": [alice["id"], bob["id"]]})["json"] +PATH = "/api/v1/chats/" + chat["id"] + "/messages" + + +def timed(fn): + t = time.monotonic(); r = fn(); return r, time.monotonic() - t + + +@s.case("Redis down: API bypasses cache via PostgreSQL, no anonymous trust") +def _(): + c.call("GET", "/api/v1/users/me", actor=alice, schema="User") # запись в кэше есть + victim = new_user(c, "fv"); login(c, victim) + c.call("GET", "/api/v1/users/me", actor=victim, schema="User") + sh("stop_cache") + try: + _, took = timed(lambda: c.call("GET", "/api/v1/users/me", actor=alice, schema="User")) + check(took < 2.0, "fallback too slow: %.2fs" % took) + c.call("GET", "/health/ready", schema="Health") # кэш не критичен + c.message(alice, chat, "while redis is down") + fresh = new_user(c, "fn"); login(c, fresh) # вход без Redis + c.call("GET", "/api/v1/users/me", actor=fresh, schema="User") + c.call("GET", "/api/v1/users/me", 401) # аноним — 401 + c.call("GET", "/api/v1/users/me", 401, headers={"Authorization": "Bearer " + "B" * 43}) + c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=victim) # logout при мёртвом Redis + c.call("GET", "/api/v1/users/me", 401, actor=victim) + pending = sql("SELECT count(*) FROM session_cache_invalidations")[0] + finally: + sh("start_cache") + # После возврата Redis старая запись кэша victim не должна «воскресить» отозванный токен. + wait_until(lambda: sql("SELECT count(*) FROM session_cache_invalidations") == ["0"], timeout=30) + for _ in range(10): + c.call("GET", "/api/v1/users/me", 401, actor=victim) + time.sleep(0.3) + c.call("GET", "/api/v1/users/me", actor=alice, schema="User") + return "fallback latency %.3fs; outbox rows during outage=%s, drained after recovery" % (took, pending) + + +@s.case("PostgreSQL down: bounded 503 in error format; anonymous still 401") +def _(): + before = len(c.call("GET", PATH + "?limit=100", actor=bob, schema="MessagePage")["json"]["items"]) + sh("stop_db") + observed = {} + try: + c.call("GET", "/health/live", schema="Health") + r, took = timed(lambda: c.call("GET", "/health/ready", 503)) + observed["ready"] = round(took, 2) + for name, call in { + "post_message": lambda: c.call("POST", PATH, 503, actor=alice, body={"text": "db down"}, + headers={"Idempotency-Key": uuid.uuid4().hex}), + "history": lambda: c.call("GET", PATH, 503, actor=bob), + "login": lambda: c.call("POST", "/api/v1/auth/sessions", 503, + headers={"Authorization": basic(alice["username"], alice["password"])}), + "register": lambda: c.call("POST", "/api/v1/users", 503, + body={"username": "x" + uuid.uuid4().hex[:10], "display_name": "x", "password": "p" * 12}), + }.items(): + r, took = timed(call) + check(r["json"]["error"]["code"] == "unavailable", name + ": wrong code") + check(took < 5.0, name + ": not bounded (%.2fs)" % took) + check("psycopg" not in r["json"]["error"]["message"].lower(), "leaks internals") + observed[name] = round(took, 2) + c.call("GET", "/api/v1/users/me", 401) # без токена — 401 + r = c.call("GET", "/api/v1/chats", [401, 503], headers={"Authorization": "Bearer " + "C" * 43}) + check(r["status"] != 200, "unknown token accepted") + finally: + sh("start_db") + t0 = time.monotonic() + wait_until(lambda: c.call("GET", "/health/ready", [200, 503])["status"] == 200, timeout=90) + recovered = time.monotonic() - t0 + after = c.call("GET", PATH + "?limit=100", actor=bob, schema="MessagePage")["json"]["items"] + check(len(after) == before, "data changed across DB outage") + c.message(alice, chat, "after db recovery") + return "latency(s)=%s; ready again in %.1fs" % (observed, recovered) + + +if __name__ == "__main__": + try: + s.run() + except Failure as exc: + print("FAIL", exc) + raise SystemExit(1) diff --git a/student-tests/test_idempotency.py b/student-tests/test_idempotency.py new file mode 100644 index 00000000..6adaa751 --- /dev/null +++ b/student-tests/test_idempotency.py @@ -0,0 +1,162 @@ +#!/usr/bin/env python3 +"""Общая идемпотентность POST /chats/{id}/messages через LB и несколько реплик. + +Ключ — заголовок Idempotency-Key, область: пользователь + метод + путь чата + ключ, срок ≥ 24 ч. +Проверки: повтор и конкурентный повтор через разные реплики → ровно одно сообщение; другой body → 409; +области ключа; формат ключа; неуспешный запрос не «занимает» ключ; повтор снова проверяет сессию и доступ. +""" +import json +import threading +import uuid +from collections import Counter + +from common import BASE_URL, Client, Suite, check, login, new_user, sql + +c = Client(BASE_URL) +s = Suite("idempotency across replicas (" + BASE_URL + ")") +alice = new_user(c, "ia"); login(c, alice) +bob = new_user(c, "ib"); login(c, bob) +eve = new_user(c, "ie"); login(c, eve) + + +def chat_of(*actors): + return c.call("POST", "/api/v1/chats", 201, actor=actors[0], schema="Chat", + body={"title": "idem", "member_ids": [a["id"] for a in actors]})["json"] + + +chat = chat_of(alice, bob) +PATH = "/api/v1/chats/" + chat["id"] + "/messages" + + +def post(actor, key, body=None, raw=None, expected=201, client=None, path=PATH): + h = {"Idempotency-Key": key} if key is not None else {} + if raw is not None: + h["Content-Type"] = "application/json" + return (client or c).call("POST", path, expected, actor=actor, body=body, raw=raw, headers=h, + schema="Message" if expected == 201 else None) + + +def count_text(text): + return int(sql("SELECT count(*) FROM messages WHERE text = '%s'" % text.replace("'", "''"))[0]) + + +@s.case("sequential replays: same 201 + same Message from different replicas") +def _(): + key, text = uuid.uuid4().hex, "seq-" + uuid.uuid4().hex + first = post(alice, key, {"text": text}) + instances = {first["headers"]["X-Instance-Id"]} + for _ in range(10): + r = post(alice, key, {"text": text}) + check(r["json"] == first["json"], "replay differs") + check(r["headers"].get("Idempotent-Replayed") == "true", "replay not marked") + instances.add(r["headers"]["X-Instance-Id"]) + check(len(instances) >= 2, "replays were not served by >=2 replicas: %s" % instances) + check(count_text(text) == 1, "duplicate message") + return "replicas=%d, rows=1" % len(instances) + + +@s.case("30 concurrent POSTs, same key + body, via LB -> exactly one message") +def _(): + key, text = uuid.uuid4().hex, "conc-" + uuid.uuid4().hex + results, lock, barrier = [], threading.Lock(), threading.Barrier(30) + + def worker(): + local = Client(BASE_URL, timeout=15) # отдельное соединение → LB распределяет по репликам + barrier.wait() + r = post(alice, key, {"text": text}, client=local) + with lock: + results.append((r["status"], json.dumps(r["json"], sort_keys=True), r["headers"]["X-Instance-Id"])) + threads = [threading.Thread(target=worker) for _ in range(30)] + [t.start() for t in threads]; [t.join() for t in threads] + check(len(results) == 30 and all(st == 201 for st, _, _ in results), "not all 201") + check(len({b for _, b, _ in results}) == 1, "different Message bodies returned") + per_instance = Counter(i for _, _, i in results) + check(len(per_instance) >= 2, "concurrency did not span replicas: %s" % dict(per_instance)) + check(count_text(text) == 1, "duplicates: %d" % count_text(text)) + return "per-replica responses %s, rows=1" % dict(per_instance) + + +@s.case("concurrent same key, two different bodies -> one message, others 201-same or 409") +def _(): + key, a, b = uuid.uuid4().hex, "race-a-" + uuid.uuid4().hex, "race-b-" + uuid.uuid4().hex + out, lock, barrier = [], threading.Lock(), threading.Barrier(20) + + def worker(i): + local = Client(BASE_URL, timeout=15) + barrier.wait() + r = post(alice, key, {"text": a if i % 2 else b}, client=local, expected=[201, 409]) + with lock: + out.append((i % 2, r["status"], r["json"])) + threads = [threading.Thread(target=worker, args=(i,)) for i in range(20)] + [t.start() for t in threads]; [t.join() for t in threads] + rows = count_text(a) + count_text(b) + check(rows == 1, "expected exactly one message, got %d" % rows) + winner = a if count_text(a) else b + for parity, status, body in out: + mine = a if parity else b + check(status == (201 if mine == winner else 409), "status %d for %s" % (status, "winner" if mine == winner else "loser")) + return "201x%d, 409x%d" % (sum(1 for o in out if o[1] == 201), sum(1 for o in out if o[1] == 409)) + + +@s.case("after commit: different body -> 409; reordered/whitespace JSON -> replay") +def _(): + key, text = uuid.uuid4().hex, "fmt-" + uuid.uuid4().hex + first = post(alice, key, {"text": text}) + r = post(alice, key, {"text": text + "!"}, expected=409) + check(r["json"]["error"]["code"] == "conflict", "409 code") + raw = ('{ \n "text" : ' + json.dumps(text) + ' \n}').encode() + check(post(alice, key, raw=raw)["json"] == first["json"], "semantically equal JSON not replayed") + + +@s.case("scope: user + chat + key (same key elsewhere is independent)") +def _(): + key = "shared-key:" + uuid.uuid4().hex[:8] + m1 = post(alice, key, {"text": "scope-1"})["json"] + m2 = post(bob, key, {"text": "scope-1"})["json"] # другой пользователь + other = chat_of(alice, bob) + m3 = post(alice, key, {"text": "scope-1"}, path="/api/v1/chats/" + other["id"] + "/messages")["json"] + check(len({m1["id"], m2["id"], m3["id"]}) == 3, "keys leaked across scope") + check(m2["sender_id"] == bob["id"], "sender") + + +@s.case("key format: missing/empty/129 chars/invalid -> 400; 128 chars ok") +def _(): + for key in (None, "", "a" * 129, "bad key", "k%y", "a/b", "k\"q"): + post(alice, key, {"text": "x"}, expected=400) + post(alice, "A" * 120 + "._:-z019", {"text": "len-128"}) + + +@s.case("failed attempt does not claim the key (400/404 not recorded)") +def _(): + key = uuid.uuid4().hex + post(alice, key, {"text": " "}, expected=400) + m = post(alice, key, {"text": "after-400"})["json"] + check(m["text"] == "after-400", "key was claimed by failed request") + key2 = uuid.uuid4().hex + post(eve, key2, {"text": "intruder"}, expected=404) # посторонний + post(alice, key2, {"text": "after-404"}) + + +@s.case("replay re-checks session and access") +def _(): + u = dict(alice); login(c, u) + key, text = uuid.uuid4().hex, "relogin-" + uuid.uuid4().hex + post(u, key, {"text": text}) + c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=u) + post(u, key, {"text": text}, expected=401) + post(eve, key, {"text": text}, expected=404) # чужой ключ/чат не раскрывается + check(post(alice, key, {"text": text})["json"]["text"] == text, "new session must replay") + + +@s.case("key older than IDEMPOTENCY_TTL_SECONDS is reusable (24 h window)") +def _(): + key, text = uuid.uuid4().hex, "ttl-" + uuid.uuid4().hex + first = post(alice, key, {"text": text})["json"] + sql("UPDATE idempotency_keys SET created_at = created_at - interval '25 hours' WHERE key = '%s'" % key) + second = post(alice, key, {"text": text})["json"] + check(second["id"] != first["id"], "expired key must create a new message") + check(count_text(text) == 2, "rows") + + +if __name__ == "__main__": + s.run() diff --git a/student-tests/test_imgproc.py b/student-tests/test_imgproc.py new file mode 100644 index 00000000..3ad9e220 --- /dev/null +++ b/student-tests/test_imgproc.py @@ -0,0 +1,160 @@ +#!/usr/bin/env python3 +"""Обработка изображений worker (уровень 4): правила вариантов и лимиты — проверка декодированием. + +Запускается ВНУТРИ образа приложения (нужен Pillow): + docker compose --env-file .env run --rm --no-deps -T -v "$PWD/student-tests:/app/student-tests:ro" \ + --entrypoint python worker student-tests/test_imgproc.py +Проверяет: размеры (вписывание, округление вниз, без увеличения), EXIF orientation, alpha на белом, +отсутствие EXIF/ICC в вариантах, детерминированность (основа идемпотентности), отличие pipeline v2, +лимиты пикселей/памяти/времени и классификацию ошибок (постоянная vs временная). +""" +import asyncio +import io +import json +import os +import subprocess +import sys +import time +import types +from pathlib import Path + +from PIL import Image, ImageCms, ImageDraw + +sys.path.insert(0, "/app/src") +from messenger.worker import Permanent, Transient, Worker # noqa: E402 + +FIX = Path(__file__).parent / "fixtures" +results = [] + + +def case(name): + def deco(fn): + t = time.monotonic() + try: + note = fn() + results.append(True) + print("PASS %-70s %.2fs %s" % (name, time.monotonic() - t, note or "")) + except Exception as exc: # noqa: BLE001 + results.append(False) + print("FAIL %-70s %s: %s" % (name, type(exc).__name__, exc)) + return fn + return deco + + +def run(data, version=1, mem=768, maxpx=40_000_000): + p = subprocess.run([sys.executable, "-m", "messenger.imgproc", str(maxpx), str(mem), "30", str(version)], + input=data, capture_output=True, env=dict(os.environ, PYTHONPATH="/app/src")) + head, _, rest = p.stdout.partition(b"\n") + info = json.loads(head) + if not info["ok"]: + return info + out, off = {}, 0 + for v in info["variants"]: + body = rest[off:off + v["size_bytes"]] + off += v["size_bytes"] + im = Image.open(io.BytesIO(body)) + im.load() + out[v["name"]] = (im, body, v) + return out + + +def enc(im, fmt, **kw): + b = io.BytesIO() + im.save(b, fmt, **kw) + return b.getvalue() + + +@case("fixture 320×200 → thumbnail 256×160, crop 128×128, optimized WebP 320×200") +def _(): + o = run((FIX / "photo.jpg").read_bytes()) # 96×64 — меньше коробки: без увеличения + assert o["thumbnail"][0].size == (96, 64) and o["optimized"][0].size == (96, 64) + sample = Image.new("RGB", (320, 200), (10, 120, 200)) + o = run(enc(sample, "PNG")) + assert o["thumbnail"][0].size == (256, 160) and o["crop"][0].size == (128, 128) + assert o["optimized"][0].format == "WEBP" and o["optimized"][0].size == (320, 200) + assert o["thumbnail"][0].format == "JPEG" and o["crop"][0].format == "JPEG" + + +@case("rounding down and minimum 1 px: 3000×10 → 256×1, 1280×4") +def _(): + o = run(enc(Image.new("RGB", (3000, 10)), "PNG")) + assert o["thumbnail"][0].size == (256, 1) and o["optimized"][0].size == (1280, 4), \ + (o["thumbnail"][0].size, o["optimized"][0].size) + + +@case("EXIF orientation 6 applied (400×200 stored → 128×256); orientation tag not copied") +def _(): + o = run((FIX / "exif6.jpg").read_bytes()) + t = o["thumbnail"][0] + assert t.size == (128, 256), t.size + # Левая жёлтая полоса исходника после поворота на 90° по часовой оказывается сверху. + top, bottom = t.getpixel((64, 10)), t.getpixel((64, 245)) + assert top[0] > 200 and top[2] < 100 and bottom[2] > 120, (top, bottom) + assert not t.getexif(), "EXIF must be stripped" + + +@case("alpha composited on white for JPEG variants; WebP keeps alpha") +def _(): + o = run((FIX / "alpha.png").read_bytes()) + px = o["thumbnail"][0].getpixel((5, 5)) # прозрачная половина + assert all(v >= 250 for v in px), px + assert o["thumbnail"][0].getpixel((250, 80))[0] > 180 # непрозрачная красная половина + assert o["optimized"][0].mode == "RGBA" and o["optimized"][0].getpixel((5, 5))[3] == 0 + + +@case("metadata removed: EXIF/XMP/ICC of the source are not in any variant") +def _(): + im = Image.new("RGB", (500, 300), (200, 100, 50)) + ex = Image.Exif() + ex[0x010F] = "SecretCameraMaker" + icc = ImageCms.ImageCmsProfile(ImageCms.createProfile("sRGB")).tobytes() + o = run(enc(im, "JPEG", exif=ex.tobytes(), icc_profile=icc)) + for name, (img, body, _) in o.items(): + assert b"SecretCameraMaker" not in body and not img.info.get("icc_profile") and not img.getexif(), name + + +@case("deterministic output (same bytes on re-run) — basis of idempotent effect; v2 differs") +def _(): + data = enc(Image.new("RGB", (900, 600), (30, 200, 90)), "PNG") + a, b, v2 = run(data), run(data), run(data, version=2) + assert all(a[k][2]["sha256"] == b[k][2]["sha256"] for k in a) + assert a["thumbnail"][2]["sha256"] != v2["thumbnail"][2]["sha256"] + assert all(a[k][0].size == v2[k][0].size for k in a) + + +@case("limits: pixels by header (413-class), memory (RLIMIT_AS), undecodable → permanent") +def _(): + big = enc(Image.new("L", (5000, 5000)), "PNG") + r = run(big, maxpx=10_000_000) + assert not isinstance(r, dict) or r.get("kind") == "too_large", r + r = run(enc(Image.new("RGB", (6000, 6000)), "PNG"), mem=200) + assert r.get("kind") == "resource_limit", r + r = run((FIX / "sof5.jpg").read_bytes()) + assert r.get("kind") == "invalid_image", r + return "too_large / resource_limit / invalid_image" + + +@case("worker wall-clock timeout kills the subprocess → transient (retry), not a hang") +def _(): + fake = types.SimpleNamespace(s=types.SimpleNamespace(max_image_pixels=40_000_000, worker_process_memory_mb=768, + job_timeout_seconds=0.05)) + data = enc(Image.new("RGB", (4000, 3000)), "PNG") + t = time.monotonic() + try: + asyncio.run(Worker.run_pipeline(fake, data, 1)) + raise AssertionError("no timeout") + except Transient as exc: + assert exc.code == "processing_timeout" + took = time.monotonic() - t + assert took < 2, took + fake.s.job_timeout_seconds = 30 + try: + asyncio.run(Worker.run_pipeline(fake, (FIX / "sof5.jpg").read_bytes(), 1)) + raise AssertionError("no error") + except Permanent as exc: + assert exc.code == "invalid_image" + return "killed after %.2fs; undecodable → Permanent(invalid_image)" % took + + +print("summary: %d passed, %d failed" % (sum(results), len(results) - sum(results))) +sys.exit(0 if all(results) else 1) diff --git a/student-tests/test_jobs_failures.py b/student-tests/test_jobs_failures.py new file mode 100644 index 00000000..e3ac61b1 --- /dev/null +++ b/student-tests/test_jobs_failures.py @@ -0,0 +1,345 @@ +#!/usr/bin/env python3 +"""Отказы pipeline (уровни 3–4): окна отказа из contracts/attachment-states.md и восстановление. + +ВНИМАНИЕ: останавливает/запускает worker, брокер (nats) и реплики API, поднимает профиль fault +(api-fault, :8082), внедряет падения worker хуками по имени файла (нужен FAULT_HOOKS=lab у worker). +Volumes не удаляются. Сценарии: + 1 защита: worker остановлен → 202 → 409 → сообщение создано → рестарт API и брокера → worker → ready + 2 broker недоступен: upload всё равно 202 (задание в outbox PostgreSQL), после старта брокера — ready + 3 разрыв COMMIT → publish (api-fault падает сразу после COMMIT): relay другой реплики публикует + 4 разрыв publish ack → отметка outbox: повторная публикация, брокер отбрасывает дубль по Nats-Msg-Id + 5 worker падает после claim до побочного эффекта / после записи S3 до COMMIT / после COMMIT до ack + 6 зависший worker (event loop заблокирован) против долгой, но живой обработки (heartbeat) + 7 временные ошибки: backoff с jitter; исчерпание попыток → failed retry_exhausted → replay → ready + 8 processing с истёкшим lease и потерянным сообщением → reaper возвращает работу в очередь + 9 ограниченная конкуренция: одновременно в обработке не больше replicas × WORKER_CONCURRENCY + 10 staging удаляется после ready; у failed — после retention, после чего replay честно отказывает +""" +import os +import shlex +import subprocess +import time +import uuid + +from common import (BASE_URL, DC, ROOT, Client, Failure, Suite, check, events, jobs_cli, login, make_png, new_user, + s3_admin, sh, sql, upload, wait_status, wait_until) + +FAULT_URL = os.environ.get("FAULT_BASE_URL", "http://127.0.0.1:8082") +WORKERS = int(os.environ.get("WORKER_REPLICAS", "2")) +CONCURRENCY = int(os.environ.get("WORKER_CONCURRENCY", "2")) +LEASE = float(os.environ.get("JOB_LEASE_SECONDS", "20")) +c = Client(BASE_URL, timeout=30) +s = Suite("pipeline failures (" + BASE_URL + ")") +alice = new_user(c, "fa"); login(c, alice) +bob = new_user(c, "fb"); login(c, bob) +chat = c.call("POST", "/api/v1/chats", 201, actor=alice, schema="Chat", + body={"title": "failures", "member_ids": [alice["id"], bob["id"]]})["json"] + + +def dc(*args, env=None, timeout=180): + subprocess.run(shlex.split(DC) + list(args), cwd=ROOT, check=True, timeout=timeout, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=dict(os.environ, **(env or {}))) + + +def wait_healthy(service, timeout=120): + def ok(): + ids = subprocess.run(shlex.split(DC) + ["ps", "-q", service], cwd=ROOT, capture_output=True, text=True).stdout.split() + return ids and all(subprocess.run(["docker", "inspect", "-f", "{{.State.Health.Status}}", i], capture_output=True, + text=True).stdout.strip() == "healthy" for i in ids) + wait_until(ok, timeout=timeout, interval=1) + + +def ev(att_id): + return [(e["event"], e["lease_token"], e["worker"], e["detail"]) for e in events(att_id)] + + +def names(att_id): + return [e[0] for e in ev(att_id)] + + +def message(text, att_ids=()): + return c.call("POST", "/api/v1/chats/%s/messages" % chat["id"], 201, actor=alice, schema="Message", + body={"text": text, "attachment_ids": list(att_ids)}, headers={"Idempotency-Key": uuid.uuid4().hex}) + + +def broker_messages(): + out = subprocess.run(shlex.split(DC) + ["exec", "-T", "api", "python", "-m", "messenger", "stats"], cwd=ROOT, + capture_output=True, text=True, timeout=30) + import json + return (json.loads(out.stdout).get("broker") or {}).get("stream_messages") + + +@s.case("defense: worker stopped → 202 → 409 → message ok → restart API+broker (volumes kept) → worker → ready") +def _(): + sh("stop_worker", timeout=120) + try: + att, data = upload(c, alice, chat, make_png(120, 90), filename="defense.png") + meta = c.call("GET", "/api/v1/attachments/" + att["id"], actor=bob, schema="Attachment")["json"] + check(meta["status"] == "queued", "expected queued, got " + meta["status"]) + c.call("GET", "/api/v1/attachments/%s/content" % att["id"], 409, actor=bob) + message("со вложением", [att["id"]]) + message("обычное сообщение работает без worker") + wait_until(lambda: "published" in names(att["id"]), timeout=30) + in_stream = broker_messages() + sh("restart_broker", timeout=120) + wait_healthy("nats") + sh("restart_api", timeout=180) + wait_healthy("api") + after = broker_messages() + check(after is not None and after >= 1, "job message lost on broker restart (stream has %s)" % after) + check(wait_status(c, bob, att["id"], ("queued",), timeout=10)["status"] == "queued", "not queued") + finally: + sh("start_worker", timeout=120) + t = time.monotonic() + ready = wait_status(c, bob, att["id"], ("ready", "failed"), timeout=60) + check(ready["status"] == "ready", "not ready") + check(c.call("GET", "/api/v1/attachments/%s/content" % att["id"], actor=bob)["bytes"] == data, "original") + c.call("GET", "/api/v1/attachments/%s/content?variant=thumbnail" % att["id"], actor=bob) + return "attachment %s: stream held %s→%s msgs across restart; ready %.1fs after worker start" % ( + att["id"][:8], in_stream, after, time.monotonic() - t) + + +@s.case("broker down: upload still 202 (job durable in outbox), ready after broker returns") +def _(): + dc("stop", "nats") + try: + att, _ = upload(c, alice, chat, make_png(60, 60), filename="nobroker.png") + time.sleep(2) + check("published" not in names(att["id"]), "published without broker?!") + check(c.call("GET", "/api/v1/attachments/" + att["id"], actor=alice, schema="Attachment")["json"]["status"] + == "queued", "not queued") + finally: + dc("start", "nats") + wait_healthy("nats") + ready = wait_status(c, alice, att["id"], ("ready", "failed"), timeout=60) + check(ready["status"] == "ready", "not ready") + return "202 with broker stopped; events %s" % names(att["id"])[:3] + + +def fault_upload(mode, filename): + """Загрузка через api-fault с заданной точкой отказа; процесс api-fault после неё умирает.""" + dc("--profile", "fault", "up", "-d", "--no-deps", "--force-recreate", "api-fault", env={"API_FAULT_INJECT": mode}) + fc = Client(FAULT_URL, timeout=15) + wait_until(lambda: fc.call("GET", "/health/ready", [200, 502, 503])["status"] == 200, timeout=90) + fault_instance = fc.call("GET", "/health/live")["headers"].get("X-Instance-Id") + marker = sql("SELECT clock_timestamp()")[0] + try: + upload(fc, alice, chat, make_png(70, 70), filename=filename) + except Failure: + pass # 202 могло не дойти: процесс умер — это и проверяем + rows = sql("SELECT id FROM attachments WHERE chat_id = '%s' AND filename = '%s' AND created_at >= '%s'" + % (chat["id"], filename, marker)) + check(len(rows) == 1, "accepted attachment not found (%s)" % rows) + return rows[0], fault_instance + + +@s.case("crash between COMMIT and publish: relay of another process publishes, job reaches ready") +def _(): + try: + aid, fault_instance = fault_upload("crash_after_commit_before_publish", "gap-commit-publish.png") + ready = wait_status(c, alice, aid, ("ready", "failed"), timeout=60) + check(ready["status"] == "ready", "not ready") + e = ev(aid) + seq = [x[0] for x in e] + pub = [x for x in e if x[0] == "published"] + # Порядок published/claimed в журнале — порядок COMMIT: worker может получить сообщение и + # зафиксировать claim раньше, чем relay зафиксирует отметку outbox (это и есть at-least-once). + check(seq[0] == "enqueued" and len(pub) == 1 and seq.count("committed") == 1, "events %s" % seq) + relay = pub[0][3].get("relay", "") + check(fault_instance and fault_instance not in relay, "published by the crashed process?! %s" % relay) + finally: + dc("--profile", "fault", "stop", "api-fault") + return "api-fault (%s) died after COMMIT; published by relay %s; events %s" % (fault_instance, relay, seq) + + +@s.case("crash between publish ack and outbox mark: duplicate publish dropped by Nats-Msg-Id") +def _(): + seen = None + try: + for _ in range(3): # relay другой реплики может успеть первым — тогда повтор + aid, _ = fault_upload("crash_after_publish_before_mark", "gap-publish-mark.png") + wait_status(c, alice, aid, ("ready", "failed"), timeout=60) + pub = [x for x in ev(aid) if x[0] == "published"] + check(len(pub) == 1, "published events %s" % pub) + if pub[0][3].get("duplicate"): + seen = pub[0][3] + break + finally: + dc("--profile", "fault", "stop", "api-fault") + check(seen is not None, "crash window not hit in 3 tries (another relay always won)") + e = names(aid) + check(e.count("claimed") == 1 and e.count("committed") == 1, "processed more than once: %s" % e) + return "second publish: duplicate=true, stream_seq=%s; processed once" % seen["stream_seq"] + + +def crash_case(hook, expect_takeover): + att, _ = upload(c, alice, chat, make_png(90, 70), filename="fault-%s.png" % hook) + t = time.monotonic() + ready = wait_status(c, alice, att["id"], ("ready", "failed"), timeout=LEASE * 3 + 30) + check(ready["status"] == "ready", "not ready") + e = ev(att["id"]) + seq = [x[0] for x in e] + committed = [x for x in e if x[0] == "committed"] + check(len(committed) == 1, "committed %d times" % len(committed)) + if expect_takeover: + check("lease_takeover" in seq, "no takeover: %s" % seq) + tok = [x[1] for x in e if x[0] in ("claimed", "lease_takeover")] + check(committed[0][1] == tok[-1] and tok[0] != tok[-1], "commit token %s, claims %s" % (committed[0][1], tok)) + check(sql("SELECT count(*) FROM attachment_variants WHERE attachment_id = '%s'" % att["id"]) == ["3"], "variants") + wait_healthy("worker") + return att["id"], seq, time.monotonic() - t + + +@s.case("worker crash after claim, before any side effect → lease takeover → ready") +def _(): + aid, seq, took = crash_case("crash-before-s3", True) + return "%s in %.1fs" % (seq, took) + + +@s.case("worker crash after S3 writes, before COMMIT → takeover rewrites the same keys, one result") +def _(): + aid, seq, took = crash_case("crash-after-s3", True) + keys = sql("SELECT object_key FROM attachment_variants WHERE attachment_id = '%s' ORDER BY name" % aid) + check(len(keys) == 3 and all("/v1/" in k for k in keys), "keys %s" % keys) + return "%s in %.1fs; keys deterministic: %s" % (seq, took, [k.split("/")[-1] for k in keys]) + + +@s.case("worker crash after COMMIT, before ack → redelivery is a no-op (duplicate_ignored)") +def _(): + aid, seq, took = crash_case("crash-after-commit", False) + wait_until(lambda: "duplicate_ignored" in names(aid), timeout=LEASE * 3 + 20, interval=1) + seq = names(aid) + check(seq.count("committed") == 1 and seq.count("claimed") == 1, "unexpected: %s" % seq) + return "%s" % seq + + +@s.case("hung worker (event loop blocked 45 s) loses lease; takeover commits; zombie commit is fenced") +def _(): + att, _ = upload(c, alice, chat, make_png(90, 90), filename="fault-hang-45.png") + ready = wait_status(c, alice, att["id"], ("ready", "failed"), timeout=120) + check(ready["status"] == "ready", "not ready") + wait_until(lambda: "lease_lost" in names(att["id"]), timeout=60, interval=1) + e = ev(att["id"]) + claims = [x for x in e if x[0] in ("claimed", "lease_takeover")] + commit = [x for x in e if x[0] == "committed"] + lost = [x for x in e if x[0] == "lease_lost"] + check(len(commit) == 1 and commit[0][1] == claims[-1][1] and lost[0][1] == claims[0][1], + "tokens: claims %s commit %s lost %s" % ([x[1] for x in claims], commit[0][1], lost[0][1])) + check(claims[0][2] != claims[-1][2], "takeover by the same worker?") + wait_healthy("worker", timeout=90) + return "claimed t%s → takeover t%s → committed t%s; zombie (t%s) → lease_lost" % ( + claims[0][1], claims[-1][1], commit[0][1], lost[0][1]) + + +@s.case("long but alive job (35 s > lease 20 s): heartbeat keeps the lease, no takeover, no duplicate") +def _(): + att, _ = upload(c, alice, chat, make_png(60, 40), filename="fault-slow-35.png") + t = time.monotonic() + ready = wait_status(c, alice, att["id"], ("ready", "failed"), timeout=120) + check(ready["status"] == "ready", "not ready") + seq = names(att["id"]) + check(seq.count("claimed") == 1 and "lease_takeover" not in seq and seq.count("committed") == 1, "%s" % seq) + return "ready after %.1fs, %s" % (time.monotonic() - t, seq) + + +@s.case("transient errors: retry with backoff + jitter (2 failures), then ready") +def _(): + att, _ = upload(c, alice, chat, make_png(50, 50), filename="fault-transient-2.png") + ready = wait_status(c, alice, att["id"], ("ready", "failed"), timeout=60) + check(ready["status"] == "ready", "not ready") + e = events(att["id"]) + retries = [x for x in e if x["event"] == "retry_scheduled"] + check(len(retries) == 2, "retries %d" % len(retries)) + d1, d2 = retries[0]["detail"]["delay_seconds"], retries[1]["detail"]["delay_seconds"] + check(1.0 <= d1 <= 2.0 and 2.0 <= d2 <= 4.0, "backoff windows: %s, %s" % (d1, d2)) + claims = [x for x in e if x["event"] == "claimed"] + gaps = [] + for r, nxt in zip(retries, claims[1:]): + import datetime as dt + g = (dt.datetime.fromisoformat(nxt["created_at"]) - dt.datetime.fromisoformat(r["created_at"])).total_seconds() + gaps.append(round(g, 2)) + check(g >= r["detail"]["delay_seconds"] - 0.05, "retried earlier than scheduled") + return "delays %.2fs, %.2fs (windows [1,2], [2,4]); actual gaps %s; attempts %s" % ( + d1, d2, gaps, [x["attempt"] for x in claims]) + + +@s.case("retries exhausted → failed retry_exhausted (in registry) → operator replay → ready") +def _(): + att, _ = upload(c, alice, chat, make_png(40, 40), filename="fault-transient-5.png") + failed = wait_status(c, alice, att["id"], ("ready", "failed"), timeout=90) + check(failed["status"] == "failed" and failed["error_code"] == "retry_exhausted", "got %s" % failed["status"]) + seq = names(att["id"]) + check(seq.count("claimed") == 5 and seq.count("retry_scheduled") == 4, "attempts: %s" % seq) + reg = jobs_cli("failed", "--limit", "500")["failed"] + check(any(r["attachment_id"] == att["id"] and r["replayable"] for r in reg), "not in registry") + r = jobs_cli("replay", "--attachment", att["id"], "--reason", "fixed dependency", "--operator", "student") + check(r["result"] == "replayed" and r["attempt"] == 6, "%s" % r) + ready = wait_status(c, alice, att["id"], ("ready", "failed"), timeout=60) + check(ready["status"] == "ready" and ready["error_code"] is None, "replay did not finish") + return "5 attempts → retry_exhausted; replay (attempt 6) → ready" + + +@s.case("processing with expired lease and LOST message → reaper requeues → ready") +def _(): + sh("stop_worker", timeout=120) + try: + att, _ = upload(c, alice, chat, make_png(55, 55), filename="reaper.png") + wait_until(lambda: "published" in names(att["id"]), timeout=30) + purged = jobs_cli("purge-stream")["purged"] + # имитация: worker захватил работу и умер, а его сообщение брокер уже не вернёт (потеряно) + sql("UPDATE attachment_jobs SET status = 'processing', claims = 1, lease_token = nextval('job_lease_token_seq')," + " lease_owner = 'dead-worker', lease_until = clock_timestamp() - interval '2 minutes'" + " WHERE attachment_id = '%s'" % att["id"]) + sql("UPDATE attachments SET status = 'processing' WHERE id = '%s'" % att["id"]) + finally: + sh("start_worker", timeout=120) + ready = wait_status(c, alice, att["id"], ("ready", "failed"), timeout=60) + check(ready["status"] == "ready", "not ready") + seq = names(att["id"]) + check("requeued_expired_lease" in seq, "reaper did not act: %s" % seq) + return "purged %s stream msgs; %s" % (purged, seq[-4:]) + + +@s.case("bounded concurrency: never more than replicas × WORKER_CONCURRENCY jobs in processing") +def _(): + ids = [upload(c, alice, chat, make_png(30 + i, 30), filename="fault-slow-4-n%d.png" % i)[0]["id"] for i in range(8)] + import datetime as dt + for a in ids: + wait_status(c, alice, a, ("ready", "failed"), timeout=120) + spans = [] + for a in ids: + e = events(a) + start = [x["created_at"] for x in e if x["event"] == "claimed"][0] + end = [x["created_at"] for x in e if x["event"] == "committed"][0] + spans.append((dt.datetime.fromisoformat(start), dt.datetime.fromisoformat(end))) + points = sorted([(s0, 1) for s0, _ in spans] + [(e0, -1) for _, e0 in spans]) + cur = peak = 0 + for _, d in points: + cur += d + peak = max(peak, cur) + limit = WORKERS * CONCURRENCY + check(peak <= limit, "peak %d > %d" % (peak, limit)) + total = (max(e0 for _, e0 in spans) - min(s0 for s0, _ in spans)).total_seconds() + return "8 jobs × ~4 s: peak concurrency %d (limit %d), wall %.1fs" % (peak, limit, total) + + +@s.case("staging removed after ready; failed staging kept until retention, then replay refuses honestly") +def _(): + att, _ = upload(c, alice, chat, make_png(33, 33), filename="staging.png") + wait_status(c, alice, att["id"], "ready") + hexid = att["id"].replace("-", "") + wait_until(lambda: s3_admin("ls", "staging/" + hexid) == "", timeout=30) + check(s3_admin("ls", "originals/" + hexid) != "", "original not published") + bad, _ = upload(c, alice, chat, open(os.path.join(os.path.dirname(__file__), "fixtures", "sof5.jpg"), "rb").read(), + "image/jpeg", "sof5-retention.jpg") + wait_status(c, alice, bad["id"], "failed") + bhex = bad["id"].replace("-", "") + check(s3_admin("ls", "staging/" + bhex) != "", "failed staging must be kept for replay") + sql("UPDATE attachments SET updated_at = clock_timestamp() - interval '2 days' WHERE id = '%s'" % bad["id"]) + wait_until(lambda: s3_admin("ls", "staging/" + bhex) == "", timeout=30) + r = jobs_cli("replay", "--attachment", bad["id"], "--reason", "too late") + check(r["result"] == "refused", "replay after retention: %s" % r) + return "ready: staging gone, originals/ present; failed: staging kept, removed after retention; replay %s" % r["result"] + + +s.run() diff --git a/student-tests/test_observability.py b/student-tests/test_observability.py new file mode 100644 index 00000000..de098789 --- /dev/null +++ b/student-tests/test_observability.py @@ -0,0 +1,280 @@ +#!/usr/bin/env python3 +"""Собственные проверки lab6 (уровни 3–4): telemetry своего приложения находится в сохранённых +наблюдениях — Prometheus/Loki/Tempo через Grafana (datasource proxy), без доступа к stdout контейнеров. + + python3 student-tests/test_observability.py (стенд запущен, Grafana на 127.0.0.1:3000) +""" +import re +import time +import uuid + +from common import BASE_URL, Client, Suite, check, new_user, login, upload, wait_status +from obs import Grafana, ObsError, wait_for + +suite = Suite("lab6: наблюдаемость — provisioning, сигналы, корреляция, безопасность telemetry") +c = Client(BASE_URL) +g = Grafana() +ctx = {} +UUID_RE = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") +FORBIDDEN_LABELS = {"user_id", "chat_id", "message_id", "attachment_id", "request_id", "url", "url_full", "url_path", + "http_target", "filename", "text", "job_id", "trace_id", "span_id"} + + +def setup_actors(): + if "alice" not in ctx: + ctx["password"] = "Obs-Secret-" + uuid.uuid4().hex # ищем его потом в telemetry + alice = new_user(c, "obs", password=ctx["password"]) + login(c, alice) + chat = c.call("POST", "/api/v1/chats", 201, actor=alice, schema="Chat", + body={"title": "obs", "member_ids": [alice["id"]]})["json"] + ctx.update(alice=alice, chat=chat) + return ctx["alice"], ctx["chat"] + + +def log_by_request(rid, service="messenger-api"): + recs = g.loki('{service_name="%s"} | request_id="%s"' % (service, rid), since=600) + return [r for r in recs if r.get("event") == "http.request"] + + +def descendants_of(spans, root_id): + kids = {} + for s in spans: + kids.setdefault(s["parent"], []).append(s) + out, stack = [], [root_id] + while stack: + for s in kids.get(stack.pop(), []): + out.append(s) + stack.append(s["span_id"]) + return out + + +def ancestors(spans, span): + by_id = {s["span_id"]: s for s in spans} + out, cur = [], by_id.get(span["parent"]) + while cur is not None: + out.append(cur) + cur = by_id.get(cur["parent"]) + return out + + +@suite.case("provisioning: Prometheus/Loki/Tempo из Git, health OK") +def provisioning_datasources(): + ds = {d["uid"]: d for d in g.get("/api/datasources")} + check({"prometheus", "loki", "tempo"} <= set(ds), "datasources: %s" % sorted(ds)) + check(all(ds[u]["readOnly"] for u in ("prometheus", "loki", "tempo")), "datasources must be provisioned (read-only)") + out = [] + for uid in ("prometheus", "loki", "tempo"): + h = g.get("/api/datasources/uid/%s/health" % uid) + check(h.get("status") == "OK", "%s health: %s" % (uid, h)) + out.append(uid) + return "health OK: " + ", ".join(out) + + +@suite.case("provisioning: dashboard импортирован, все запросы панелей выполняются") +def provisioning_dashboard(): + d = g.get("/api/dashboards/uid/messenger-overview") + check(d["meta"].get("provisioned"), "dashboard is not provisioned from file") + panels = [p for p in d["dashboard"]["panels"] if p.get("type") != "row"] + queries = with_data = 0 + errors = [] + for p in panels: + for t in p.get("targets", []): + queries += 1 + res = g.ds_query({k: v for k, v in t.items() if k != "datasource"}, t.get("datasource") or p["datasource"], since=1800) + r = res["results"][t.get("refId", "A")] + if r.get("error") or r.get("status", 200) >= 400: + errors.append("%s: %s" % (p["title"], (r.get("error") or "")[:120])) + elif any(f.get("data", {}).get("values") and any(len(v) for v in f["data"]["values"]) for f in r.get("frames", [])): + with_data += 1 + check(not errors, "panel query errors: %s" % errors[:5]) + return "%d панелей, %d запросов без ошибок, с данными %d" % (len(panels), queries, with_data) + + +@suite.case("HTTP: X-Request-Id → структурный лог → trace (server + DB spans)") +def request_log_trace(): + alice, chat = setup_actors() + ctx["marker"] = "obs-marker-" + uuid.uuid4().hex # текст сообщения: не должен попасть в telemetry + r = c.message(alice, chat, "Тайное содержимое " + ctx["marker"]) + rid = r["headers"]["X-Request-Id"] + recs = wait_for(lambda: log_by_request(rid), 60, what="log with request_id") + rec = recs[-1] + for f in ("trace_id", "span_id", "severity_text", "service_name", "event", "route", "status"): + check(rec.get(f), "log record lacks %s: %s" % (f, sorted(rec))) + check(rec["route"] == "/api/v1/chats/{chat_id}/messages" and rec["status"] == "201", "log route/status: %s" % rec) + spans = wait_for(lambda: g.trace(rec["trace_id"]), 60, what="trace " + rec["trace_id"]) + server = [s for s in spans if s["kind"] == "SERVER"] + check(len(server) == 1, "expected one server span, got %s" % [s["name"] for s in spans]) + sv = server[0] + check(sv["name"] == "POST /api/v1/chats/{chat_id}/messages", "server span name: %s" % sv["name"]) + check(sv["attrs"].get("messenger.request_id") == rid and sv["attrs"].get("http.response.status_code") == 201, + "server span attrs: %s" % sv["attrs"]) + check(sv["span_id"] == rec["span_id"], "log span_id %s != server span %s" % (rec["span_id"], sv["span_id"])) + db = [s for s in descendants_of(spans, sv["span_id"]) if s["attrs"].get("db.system.name") == "postgresql"] + check(any(s["name"] == "INSERT messages" for s in db), "no INSERT messages span: %s" % [s["name"] for s in db]) + ctx["msg_trace"] = rec["trace_id"] + return "request_id → trace %s…, %d spans (%d DB)" % (rec["trace_id"][:12], len(spans), len(db)) + + +@suite.case("безопасность: пароль, токен, тело сообщения не попадают в логи/трассы") +def no_secrets(): + alice, chat = setup_actors() + if "marker" not in ctx: + request_log_trace() + r = login(c, alice) # Basic с паролем → токен в ответе + rid = r["headers"]["X-Request-Id"] + rec = wait_for(lambda: log_by_request(rid), 60, what="login log")[-1] + login_trace = wait_for(lambda: g.trace_raw_text(rec["trace_id"]), 60, what="login trace") + msg_trace = g.trace_raw_text(ctx["msg_trace"]) + secrets = {"password": ctx["password"], "token": alice["token"], "message text": ctx["marker"], "Bearer": "Bearer "} + leaks = [] + for name, value in secrets.items(): + for where, text in (("login trace", login_trace), ("message trace", msg_trace)): + if value in text: + leaks.append("%s in %s" % (name, where)) + if name != "Bearer" and g.loki('{service_name=~"messenger-api|messenger-worker"} |= "%s"' % value, since=900): + leaks.append(name + " in Loki") + check(not leaks, "telemetry leaks: %s" % leaks) + check("password.verify" in login_trace, "login trace has no password.verify span (KDF time not visible)") + return "проверено в Loki и 2 trace: пароль, токен, текст сообщения, Authorization" + + +@suite.case("upload → create → send → process → S3/DB: один trace; лог worker с тем же trace_id") +def upload_chain(): + alice, chat = setup_actors() + att, _ = upload(c, alice, chat) + wait_status(c, alice, att["id"], "ready", timeout=60) + + def find(): + traces = g.search('{ span.messenger.attachment.id = "%s" }' % att["id"], since=600) + if not traces: + return None + spans = g.trace(traces[0]["traceID"]) + procs = [s for s in spans or [] if s["kind"] == "CONSUMER" and s["attrs"].get("messenger.job.outcome")] + return spans if procs else None + spans = wait_for(find, 90, what="worker span in upload trace") + by = lambda n: [s for s in spans if s["name"] == n] # noqa: E731 + server = by("POST /api/v1/chats/{chat_id}/attachments") + create, send = by("create attachments.process.v1"), by("send attachments.process.v1") + process = by("process attachments.process.v1") + check(len(server) == 1 and server[0]["kind"] == "SERVER" and server[0]["service"] == "messenger-api", "server span") + check(len(create) == 1 and create[0]["kind"] == "PRODUCER" and create[0]["parent"] == server[0]["span_id"], + "create span must be PRODUCER child of upload server span") + check(len(send) >= 1 and all(s["kind"] == "PRODUCER" and s["parent"] == create[0]["span_id"] for s in send), + "send span must be PRODUCER child of create") + check(len(process) == 1 and process[0]["kind"] == "CONSUMER" and process[0]["service"] == "messenger-worker" + and process[0]["parent"] == send[0]["span_id"], "process must be CONSUMER child of send (worker)") + p = process[0] + check(p["attrs"].get("messenger.job.outcome") == "ready" and p["attrs"].get("messaging.system") == "nats", "process attrs") + inner = descendants_of(spans, p["span_id"]) + names = [s["name"] for s in inner] + check(names.count("S3.PutObject") >= 4, "original + 3 variants PUT expected: %s" % names) + check("imgproc.run" in names and "job.commit" in names and "UPDATE attachments" in names, "pipeline spans: %s" % names) + tid = p["trace_id"] + rec = wait_for(lambda: g.loki('{service_name="messenger-worker"} | event="job.finished" | attachment_id="%s"' % att["id"], + since=600), 60, what="worker log")[-1] + check(rec.get("trace_id") == tid and rec.get("span_id") == p["span_id"], "worker log not linked to process span") + ctx["upload_trace"] = tid + return "%d spans: SERVER→create→send→process(%s)→S3×%d; queue %.2f с" % ( + len(spans), p["service"], names.count("S3.PutObject"), p["start"] - send[0]["end"]) + + +@suite.case("retry: 2 временные ошибки + успех — три попытки в одном trace") +def retry_chain(): + alice, chat = setup_actors() + att, _ = upload(c, alice, chat, filename="obs-fault-transient-2.png") + wait_status(c, alice, att["id"], "ready", timeout=90) + + def find(): + traces = g.search('{ span.messenger.attachment.id = "%s" }' % att["id"], since=600) + spans = g.trace(traces[0]["traceID"]) if traces else None + procs = [s for s in spans or [] if s["name"] == "process attachments.process.v1"] + return spans if len(procs) >= 3 and any(s["attrs"].get("messenger.job.outcome") == "ready" for s in procs) else None + spans = wait_for(find, 90, what="3 process spans") + procs = sorted([s for s in spans if s["name"] == "process attachments.process.v1"], key=lambda s: s["start"]) + outcomes = [s["attrs"].get("messenger.job.outcome") for s in procs] + check(outcomes == ["retry", "retry", "ready"], "outcomes: %s" % outcomes) + check([s["attrs"].get("messenger.job.attempt") for s in procs] == [1, 2, 3], "attempts") + check(all(s["status"] == "ERROR" and s["attrs"].get("error.type") == "processing_failed" for s in procs[:2]), + "failed attempts must be marked as errors") + check(procs[0] in ancestors(spans, procs[1]) and procs[1] in ancestors(spans, procs[2]), + "next attempt must descend from previous attempt (retry → outbox → send → process)") + return "попытки 1→2→3: %s; паузы backoff %.1f с и %.1f с" % ( + outcomes, procs[1]["start"] - procs[0]["end"], procs[2]["start"] - procs[1]["end"]) + + +@suite.case("метрики контракта: имена, низкая кардинальность, шаблоны маршрутов") +def metric_contract(): + required = ["http_server_request_duration_seconds_count", "http_server_active_requests", + "db_client_operation_duration_seconds_count", "db_client_connection_count", + "db_client_connection_pending_requests", "db_client_connection_max", + "messenger_jobs_processed_total", "messenger_job_duration_seconds_count", + "messenger_attachment_time_to_ready_seconds_count", "messenger_job_queue_wait_seconds_count", + "messenger_queue_depth", "messenger_queue_lag_seconds", "messenger_queue_oldest_age_seconds", + "messenger_broker_pending", "messenger_worker_busy", "messenger_worker_capacity", + "container_cpu_time_seconds_total", "container_memory_usage_bytes", "process_memory_usage_bytes", + "otel_sdk_processor_span_processed_total"] + missing = [m for m in required if not g.series(m, since=900)] + check(not missing, "metrics missing: %s" % missing) + series = g.series('{__name__=~"messenger_.*|http_server_.*|db_client_.*|container_.*"}', since=900) + labels = set().union(*(s.keys() for s in series)) + bad = labels & FORBIDDEN_LABELS + check(not bad, "forbidden metric labels: %s" % bad) + routes = {s.get("http_route") for s in series if s.get("http_route")} + check(routes and not any(UUID_RE.search(r) for r in routes), "routes must be templates: %s" % routes) + check(all(s.get("service_name") in ("messenger-api", "messenger-worker") and s.get("deployment_environment_name") == "lab" + and s.get("service_instance_id") for s in series), "resource labels missing on some series") + n_http = len([s for s in series if s["__name__"] == "http_server_request_duration_seconds_count"]) + check(n_http < 300, "too many http series: %d" % n_http) + return "%d метрик; серий %d (HTTP count — %d); маршрутов %d; запрещённых labels нет" % ( + len(required), len(series), n_http, len(routes)) + + +@suite.case("метрики отражают обработку: jobs, retry, time-to-ready, p95 из histogram") +def metric_values(): + def ok(): + ready = g.prom_value('sum(messenger_jobs_processed_total{outcome="ready"})', 0) + retry = g.prom_value('sum(messenger_jobs_processed_total{outcome="retry"})', 0) + ttr = g.prom_value("sum(messenger_attachment_time_to_ready_seconds_count)", 0) + return (ready, retry, ttr) if ready >= 2 and retry >= 2 and ttr >= 2 else None + ready, retry, ttr = wait_for(ok, 40, what="job metrics") + p95 = g.prom_value('histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket' + '{service_name="messenger-api",http_route!~"/health/.*"}[10m])))') + check(p95 is not None and p95 > 0, "p95 from histogram: %s" % p95) + t95 = g.prom_value("histogram_quantile(0.95, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket[30m])))") + return "ready=%d retry=%d time_to_ready count=%d; p95 HTTP %.0f мс, p95 ready %.2f с" % (ready, retry, ttr, p95 * 1000, t95 or 0) + + +@suite.case("алерты: правила загружены и вычисляются без ошибок") +def alert_rules(): + groups = g.rules() + rules = [r for grp in groups for r in grp["rules"]] + names = {r["name"] for r in rules if r["type"] == "alerting"} + need = {"ApiHighErrorRate", "JobQueueLagGrowing", "WorkerHeartbeatMissing", "DbSlowQueries", "ApiLatencyHigh", + "TelemetryExportFailing"} + check(need <= names, "alerts missing: %s" % (need - names)) + bad = [r["name"] for r in rules if r.get("health") != "ok" or r.get("lastError")] + check(not bad, "rules with evaluation errors: %s" % bad) + for r in rules: + if r["type"] == "alerting": + ann = r.get("annotations", {}) + check(ann.get("summary") and ann.get("runbook_url"), "alert %s lacks summary/runbook" % r["name"]) + firing = [a["labels"]["alertname"] for a in g.alerts() if a["state"] == "firing"] + return "%d правил (%d алертов), firing сейчас: %s" % (len(rules), len(names), firing or "нет") + + +@suite.case("SDK: spans/logs не отбрасываются при работающем Collector") +def sdk_no_drops(): + total = g.prom_value("sum(otel_sdk_processor_span_processed_total)", 0) + dropped = g.prom_value('sum(otel_sdk_processor_span_processed_total{error_type!=""})', 0) + ldropped = g.prom_value('sum(otel_sdk_processor_log_processed_total{error_type!=""})', 0) + check(total > 0, "no SDK span counters") + check(dropped == 0 and ldropped == 0, "dropped spans=%s logs=%s" % (dropped, ldropped)) + return "обработано spans %d, отброшено 0" % total + + +if __name__ == "__main__": + try: + g.get("/api/health") + except ObsError as e: + raise SystemExit("Grafana недоступна: %s" % e) + suite.run() diff --git a/student-tests/test_pipeline.py b/student-tests/test_pipeline.py new file mode 100644 index 00000000..fdae5dc4 --- /dev/null +++ b/student-tests/test_pipeline.py @@ -0,0 +1,187 @@ +#!/usr/bin/env python3 +"""Асинхронный pipeline вложений (уровни 3–4): 202/queued → ready, варианты по контракту, failed, +409 для неготовых, запрет прикреплять failed, идемпотентность повторной доставки, безопасный replay. + +Размеры вариантов проверяются по РЕАЛЬНЫМ байтам (JPEG SOF и заголовок WebP), а не только по JSON. +Стенд должен работать с worker; volumes не трогаются. Для операторских шагов используется +`python -m messenger jobs …` в контейнере worker (нужен docker compose в PATH). +""" +import hashlib +import sys +import time +import zlib +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests")) +from image_probe import jpeg_size # noqa: E402 + +from common import (BASE_URL, Client, Suite, check, events, jobs_cli, login, make_png, new_user, upload, # noqa: E402 + wait_status) + +FIX = Path(__file__).parent / "fixtures" +c = Client(BASE_URL, timeout=30) +s = Suite("attachment pipeline (" + BASE_URL + ")") +alice = new_user(c, "pa"); login(c, alice) +bob = new_user(c, "pb"); login(c, bob) +eve = new_user(c, "pe"); login(c, eve) +chat = c.call("POST", "/api/v1/chats", 201, actor=alice, schema="Chat", + body={"title": "pipeline", "member_ids": [alice["id"], bob["id"]]})["json"] + + +def webp_size(data): + check(data[:4] == b"RIFF" and data[8:12] == b"WEBP", "optimized is not WebP") + kind = data[12:16] + if kind == b"VP8 ": + return int.from_bytes(data[26:28], "little") & 0x3FFF, int.from_bytes(data[28:30], "little") & 0x3FFF + if kind == b"VP8L": + b = int.from_bytes(data[21:25], "little") + return (b & 0x3FFF) + 1, ((b >> 14) & 0x3FFF) + 1 + if kind == b"VP8X": + return int.from_bytes(data[24:27], "little") + 1, int.from_bytes(data[27:30], "little") + 1 + raise AssertionError("unknown WebP chunk %r" % kind) + + +def flat_png(w, h, rgb=(40, 160, 90)): + """Однотонный RGB PNG любого размера (stdlib): хорошо сжимается, годится для проверки размеров.""" + row = b"\x00" + bytes(rgb) * w + raw = zlib.compress(row * h, 6) + + def chunk(t, d): + return len(d).to_bytes(4, "big") + t + d + zlib.crc32(t + d).to_bytes(4, "big") + return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", w.to_bytes(4, "big") + h.to_bytes(4, "big") + bytes([8, 2, 0, 0, 0])) + + chunk(b"IDAT", raw) + chunk(b"IEND", b"")) + + +def fit(w, h, box): + m = max(w, h) + return (w, h) if m <= box else (max(1, w * box // m), max(1, h * box // m)) + + +def check_variants(att, logical_w, logical_h): + """Все три варианта: заявленные метаданные = реальные байты; размеры — по правилам контракта.""" + got = {v["name"]: v for v in att["variants"]} + check(set(got) == {"thumbnail", "crop", "optimized"}, "variants %s" % sorted(got)) + expect = {"thumbnail": ("image/jpeg", fit(logical_w, logical_h, 256)), "crop": ("image/jpeg", (128, 128)), + "optimized": ("image/webp", fit(logical_w, logical_h, 1280))} + for name, (ctype, dims) in expect.items(): + v = got[name] + r = c.call("GET", "/api/v1/attachments/%s/content?variant=%s" % (att["id"], name), actor=bob) + body = r["bytes"] + check(r["headers"].get_content_type() == ctype == v["content_type"], name + " content type") + check(len(body) == v["size_bytes"] and hashlib.sha256(body).hexdigest() == v["sha256"], name + " checksum") + real = jpeg_size(body) if ctype == "image/jpeg" else webp_size(body) + check(real == dims == (v["width"], v["height"]), "%s: real %s, meta %s, expected %s" + % (name, real, (v["width"], v["height"]), dims)) + return got + + +@s.case("upload → 202 queued snapshot, then ready; original byte-exact; three variants by contract") +def _(): + data = (Path(__file__).resolve().parents[1] / "tests" / "fixtures" / "sample.png").read_bytes() + att, _ = upload(c, alice, chat, data, filename="sample.png") + check(att["status"] in ("queued", "processing", "ready") and att["error_code"] is None, "202 snapshot") + t = time.monotonic() + ready = wait_status(c, bob, att["id"], ("ready", "failed")) + check(ready["status"] == "ready", "not ready: %s" % ready) + took = time.monotonic() - t + orig = c.call("GET", "/api/v1/attachments/%s/content" % att["id"], actor=bob)["bytes"] + check(orig == data and ready["sha256"] == hashlib.sha256(data).hexdigest(), "original changed") + check_variants(ready, 320, 200) + return "ready %.2fs after 202; thumbnail 256×160, crop 128×128, optimized 320×200 WebP" % took + + +@s.case("big image: optimized fits 1280 without upscale, thumbnail rounds down") +def _(): + att, _ = upload(c, alice, chat, flat_png(3001, 1999), filename="big.png") + ready = wait_status(c, alice, att["id"], ("ready", "failed")) + check(ready["status"] == "ready", "not ready") + got = check_variants(ready, 3001, 1999) + return "thumbnail %sx%s, optimized %sx%s" % (got["thumbnail"]["width"], got["thumbnail"]["height"], + got["optimized"]["width"], got["optimized"]["height"]) + + +@s.case("EXIF orientation applied (stored 400×200, orientation 6 → 200×400); tiny image not upscaled") +def _(): + att, _ = upload(c, alice, chat, (FIX / "exif6.jpg").read_bytes(), "image/jpeg", "exif6.jpg") + ready = wait_status(c, alice, att["id"], ("ready", "failed")) + check_variants(ready, 200, 400) + tiny, _ = upload(c, alice, chat, make_png(40, 30), filename="tiny.png") + ready = wait_status(c, alice, tiny["id"], ("ready", "failed")) + got = check_variants(ready, 40, 30) + check((got["thumbnail"]["width"], got["thumbnail"]["height"]) == (40, 30), "tiny thumbnail upscaled") + att, _ = upload(c, alice, chat, (FIX / "alpha.png").read_bytes(), filename="alpha.png") + check_variants(wait_status(c, alice, att["id"], ("ready", "failed")), 300, 200) + + +@s.case("variant parameter: unknown → 400; default original; outsider → 404") +def _(): + att, data = upload(c, alice, chat, make_png(64, 64)) + wait_status(c, alice, att["id"], "ready") + c.call("GET", "/api/v1/attachments/%s/content?variant=../../x" % att["id"], 400, actor=bob) + c.call("GET", "/api/v1/attachments/%s/content?variant=preview" % att["id"], 400, actor=bob) + check(c.call("GET", "/api/v1/attachments/%s/content?variant=original" % att["id"], actor=bob)["bytes"] == data, "orig") + for v in ("", "?variant=thumbnail"): + c.call("GET", "/api/v1/attachments/%s/content%s" % (att["id"], v), 404, actor=eve) + c.call("GET", "/api/v1/attachments/%s" % att["id"], 404, actor=eve) + + +@s.case("undecodable image → failed with safe error_code, no retries; content 409; cannot attach (409)") +def _(): + att, _ = upload(c, alice, chat, (FIX / "sof5.jpg").read_bytes(), "image/jpeg", "sof5.jpg") + failed = wait_status(c, alice, att["id"], ("ready", "failed")) + check(failed["status"] == "failed" and failed["error_code"] == "invalid_image", "got %s/%s" + % (failed["status"], failed["error_code"])) + check(failed["variants"] == [], "failed must have no variants") + for v in ("", "?variant=thumbnail"): + c.call("GET", "/api/v1/attachments/%s/content%s" % (att["id"], v), 409, actor=bob) + c.call("POST", "/api/v1/chats/%s/messages" % chat["id"], 409, actor=alice, + body={"text": "x", "attachment_ids": [att["id"]]}, headers={"Idempotency-Key": "failed-" + att["id"]}) + ev = [e["event"] for e in events(att["id"])] + check(ev.count("claimed") == 1 and "retry_scheduled" not in ev and ev[-1] == "failed", "permanent: %s" % ev) + reg = jobs_cli("failed", "--limit", "500")["failed"] + check(any(r["attachment_id"] == att["id"] and r["error_code"] == "invalid_image" for r in reg), "not in registry") + return "events %s; listed in failed registry" % ev + + +@s.case("queued/processing attachment can be attached to a message right away") +def _(): + att, _ = upload(c, alice, chat, make_png(50, 50)) + m = c.call("POST", "/api/v1/chats/%s/messages" % chat["id"], 201, actor=bob, schema="Message", + body={"text": "", "attachment_ids": [att["id"]]}, headers={"Idempotency-Key": "q-" + att["id"]})["json"] + check(m["attachment_ids"] == [att["id"]], "message lost attachment") + wait_status(c, alice, att["id"], "ready") + + +@s.case("duplicate deliveries of a finished job are no-ops (5 raw duplicates)") +def _(): + att, _ = upload(c, alice, chat, make_png(80, 60)) + before = wait_status(c, alice, att["id"], "ready") + job = jobs_cli("status", att["id"])["jobs"][0] + jobs_cli("publish-raw", "--job", job["job_id"], "--count", "5") + time.sleep(3) + ev = [e["event"] for e in events(att["id"])] + after = c.call("GET", "/api/v1/attachments/" + att["id"], actor=alice, schema="Attachment")["json"] + check(ev.count("committed") == 1 and ev.count("duplicate_ignored") == 5, "events %s" % ev) + check(after["variants"] == before["variants"] and after["updated_at"] == before["updated_at"], "result changed") + return "committed ×1, duplicate_ignored ×5, metadata unchanged" + + +@s.case("replay is safe: ready → noop; failed (permanent) → re-executed once, failed again") +def _(): + att, _ = upload(c, alice, chat, make_png(30, 30)) + wait_status(c, alice, att["id"], "ready") + r = jobs_cli("replay", "--attachment", att["id"], "--reason", "test ready") + check(r["result"] == "noop" and r["status"] == "ready", "replay of ready must be noop: %s" % r) + bad, _ = upload(c, alice, chat, (FIX / "sof5.jpg").read_bytes(), "image/jpeg", "sof5-replay.jpg") + wait_status(c, alice, bad["id"], "failed") + r = jobs_cli("replay", "--attachment", bad["id"], "--reason", "operator retry", "--operator", "student") + check(r["result"] == "replayed" and r["attempt"] == 2, "replay: %s" % r) + wait_status(c, alice, bad["id"], "failed") + ev = [e for e in events(bad["id"])] + rp = [e for e in ev if e["event"] == "replayed"] + check(len(rp) == 1 and rp[0]["detail"]["operator"] == "student", "audit record missing") + check([e["event"] for e in ev].count("failed") == 2, "expected second failure") + return "ready: %s; failed: replayed (audit by %s) → failed again (permanent error)" % (r and "noop", "student") + + +s.run() diff --git a/student-tests/test_pipeline_idempotency.py b/student-tests/test_pipeline_idempotency.py new file mode 100644 index 00000000..da2e10e2 --- /dev/null +++ b/student-tests/test_pipeline_idempotency.py @@ -0,0 +1,188 @@ +#!/usr/bin/env python3 +"""Трек 2: доказанная идемпотентность versioned pipeline — автоматическая инъекция отказов. + +Каждый сценарий внедряет отказ, ждёт завершения и проверяет инварианты (python -m messenger jobs +invariants: I1 нет потерь, I2 один набор вариантов на ключ эффекта, I3 один COMMIT на работу, +I4 монотонный указатель версии, I5 ready не откатывается, I6 fencing, I7 нет осиротевших объектов). + D дубли: 8 копий сообщения одной работы одновременно (worker'ы стартуют на полной очереди) + R reorder: устаревшие попытки (attempt 1, 2) приходят после attempt 3; попытка «из будущего» + C crash до побочного эффекта / после записи S3 до COMMIT / после COMMIT до ack / зависание (fencing) + V1 устаревшая работа после новой версии: v2 опубликована, затем исполняется v1 → superseded без эффектов + V2 гонка версий: v1 медленно пишет результат, v2 фиксируется раньше → v1 не двигает указатель назад + V3 повторная доставка v1 после перехода на v2 и повтор reprocess — no-op +ВНИМАНИЕ: останавливает/пересоздаёт worker (в т. ч. с WORKER_PIPELINES=2), volumes не трогает. +""" +import os +import shlex +import subprocess +import time +import uuid + +from common import (BASE_URL, DC, ROOT, Client, Suite, check, events, jobs_cli, login, make_png, new_user, s3_admin, + sh, sql, upload, wait_status, wait_until) + +LEASE = float(os.environ.get("JOB_LEASE_SECONDS", "20")) +c = Client(BASE_URL, timeout=30) +s = Suite("track 2: pipeline idempotency (" + BASE_URL + ")") +alice = new_user(c, "ia"); login(c, alice) +chat = c.call("POST", "/api/v1/chats", 201, actor=alice, schema="Chat", + body={"title": "idempotency", "member_ids": [alice["id"]]})["json"] +START = sql("SELECT to_char(clock_timestamp() AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"')")[0] + + +def workers(pipelines=None): + """Пересоздать worker'ы с заданным WORKER_PIPELINES (None — по умолчанию 1,2) и дождаться healthy.""" + env = dict(os.environ) + if pipelines: + env["WORKER_PIPELINES"] = pipelines + else: + env.pop("WORKER_PIPELINES", None) + subprocess.run(shlex.split(DC) + ["up", "-d", "--no-deps", "--force-recreate", "--wait", "worker"], cwd=ROOT, + check=True, timeout=180, env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + + +def names(aid): + return [e["event"] for e in events(aid)] + + +def jobs_of(aid): + return {j["pipeline_version"]: j for j in jobs_cli("status", aid)["jobs"]} + + +def invariants(scope_since=START): + r = jobs_cli("invariants", "--settled", "--verify-bytes", "--since", scope_since, expect=(0, 1)) + check(r["ok"], "invariants violated: %s" % r["violations"]) + return r["stats"] + + +def served(aid): + return {v["name"]: v["sha256"] for v in + c.call("GET", "/api/v1/attachments/" + aid, actor=alice, schema="Attachment")["json"]["variants"]} + + +def v_rows(aid): + return sql("SELECT pipeline_version || ':' || name || ':' || sha256 FROM attachment_variants" + " WHERE attachment_id = '%s' ORDER BY 1" % aid) + + +@s.case("D: 8 duplicate copies of one job delivered concurrently → one claim, one commit") +def _(): + sh("stop_worker", timeout=120) + try: + att, _ = upload(c, alice, chat, make_png(70, 50), filename="dup.png") + wait_until(lambda: "published" in names(att["id"]), timeout=30) + job = jobs_of(att["id"])[1] + jobs_cli("publish-raw", "--job", job["job_id"], "--count", "8") + finally: + sh("start_worker", timeout=120) + wait_status(c, alice, att["id"], ("ready", "failed"), timeout=60) + wait_until(lambda: names(att["id"]).count("duplicate_ignored") == 8, timeout=LEASE * 3, interval=1) + seq = names(att["id"]) + check(seq.count("claimed") == 1 and seq.count("committed") == 1 and "lease_takeover" not in seq, "%s" % seq) + check(len(v_rows(att["id"])) == 3, "variant rows") + return "9 deliveries: claimed 1, committed 1, duplicate_ignored 8" + + +@s.case("R: reorder — stale attempts (1, 2) and a future one arrive DURING attempt 3 → ignored") +def _(): + # попытки 1–2 падают «временно», попытка 3 медленная (15 с) — в это окно приходят старые сообщения + att, _ = upload(c, alice, chat, make_png(44, 44), filename="fault-transient-2-fault-slow-15.png") + wait_until(lambda: names(att["id"]).count("claimed") == 3, timeout=60, interval=0.5) + job = jobs_of(att["id"])[1] + check(job["attempt"] == 3 and job["status"] == "processing", "job %s/%s" % (job["status"], job["attempt"])) + for a in (2, 1, 9): + jobs_cli("publish-raw", "--job", job["job_id"], "--attempt", a) + wait_until(lambda: names(att["id"]).count("stale_ignored") == 3, timeout=30, interval=1) + check(jobs_of(att["id"])[1]["status"] == "processing", "stale message interrupted the live attempt") + wait_status(c, alice, att["id"], "ready", timeout=60) + seq = names(att["id"]) + check(seq.count("committed") == 1 and seq.count("claimed") == 3 and "lease_takeover" not in seq, "%s" % seq) + future = [e for e in events(att["id"]) if e["event"] == "stale_ignored" and (e["detail"] or {}).get("future")] + check(len(future) == 1 and len(v_rows(att["id"])) == 3, "future attempt / variants") + return "during attempt 3: attempts 2, 1 → stale_ignored; 9 → stale_ignored(future) + term; one commit" + + +@s.case("C: crash before/after side effect, after COMMIT, hung worker — all reach one result") +def _(): + kinds = ["crash-before-s3", "crash-after-s3", "crash-after-commit", "hang-40"] + ids = {k: upload(c, alice, chat, make_png(60, 61), filename="fault-%s-m.png" % k)[0]["id"] for k in kinds} + for k, aid in ids.items(): + check(wait_status(c, alice, aid, ("ready", "failed"), timeout=LEASE * 6)["status"] == "ready", k) + wait_until(lambda: "lease_lost" in names(ids["hang-40"]), timeout=60, interval=1) + out = {} + for k, aid in ids.items(): + seq = names(aid) + check(seq.count("committed") == 1, "%s: %s" % (k, seq)) + out[k] = "takeover" if "lease_takeover" in seq else ("dup_ignored" if "duplicate_ignored" in seq else "-") + return "%s" % out + + +@s.case("V1: stale v1 job after v2 is published → superseded, no v1 side effects") +def _(): + sh("stop_worker", timeout=120) + att, data = upload(c, alice, chat, make_png(150, 100), filename="v1-after-v2.png") + r = jobs_cli("reprocess", "--attachment", att["id"], "--pipeline-version", 2) + check(r["result"] == "enqueued", "%s" % r) + wait_until(lambda: names(att["id"]).count("published") == 2, timeout=30) + workers("2") # только v2-worker'ы: v1 откладывается (nak), v2 исполняется + try: + wait_until(lambda: jobs_of(att["id"])[2]["status"] == "ready", timeout=60) + finally: + workers() # снова 1,2 — теперь доходит устаревшая v1 + wait_until(lambda: jobs_of(att["id"])[1]["status"] == "superseded", timeout=LEASE * 2, interval=1) + rows = v_rows(att["id"]) + check(all(r.startswith("2:") for r in rows) and len(rows) == 3, "v1 wrote variants: %s" % rows) + check(s3_admin("ls", "variants/%s/v1/" % att["id"].replace("-", "")) == "", "v1 objects exist") + meta = c.call("GET", "/api/v1/attachments/" + att["id"], actor=alice, schema="Attachment")["json"] + check(meta["status"] == "ready", "status") + check(sql("SELECT published_version FROM attachments WHERE id = '%s'" % att["id"]) == ["2"], "pointer") + return "v2 ready first; v1 → superseded at claim; variants only v2, pointer 2" + + +@s.case("V2: version race — slow v1 commits after v2 → pointer stays on v2 (no overwrite by older)") +def _(): + att, _ = upload(c, alice, chat, make_png(140, 90), filename="race-fault-slow-12-v1.png") + wait_until(lambda: "claimed" in names(att["id"]), timeout=30, interval=0.5) + jobs_cli("reprocess", "--attachment", att["id"], "--pipeline-version", 2) + wait_until(lambda: jobs_of(att["id"]).get(2, {}).get("status") == "ready", timeout=60) + check(sql("SELECT published_version FROM attachments WHERE id = '%s'" % att["id"]) == ["2"], "v2 not published") + v2_served = served(att["id"]) + wait_until(lambda: jobs_of(att["id"])[1]["status"] in ("superseded", "ready"), timeout=60, interval=1) + j1 = jobs_of(att["id"])[1] + check(j1["status"] == "superseded", "v1 status %s" % j1["status"]) + check(sql("SELECT published_version FROM attachments WHERE id = '%s'" % att["id"]) == ["2"], "pointer moved back") + check(served(att["id"]) == v2_served, "served variants changed") + ev = [e for e in events(att["id"]) if e["event"] == "published_version_changed"] + check([e["detail"]["to"] for e in ev] == [2], "pointer history %s" % [e["detail"] for e in ev]) + return "v1 finished after v2 → superseded at commit; pointer history %s" % [(e["detail"]["from"], e["detail"]["to"]) for e in ev] + + +@s.case("V3: redelivered v1 after v2 rollout and repeated reprocess are no-ops") +def _(): + att, _ = upload(c, alice, chat, make_png(64, 48), filename="rollout.png") + wait_status(c, alice, att["id"], "ready") + v1_served = served(att["id"]) + jobs_cli("reprocess", "--attachment", att["id"], "--pipeline-version", 2) + wait_until(lambda: sql("SELECT published_version FROM attachments WHERE id = '%s'" % att["id"]) == ["2"], timeout=60) + v2_served = served(att["id"]) + check(v2_served != v1_served and set(v2_served) == set(v1_served), "v2 variants not served") + j = jobs_of(att["id"]) + jobs_cli("publish-raw", "--job", j[1]["job_id"], "--count", "3") + r1 = jobs_cli("reprocess", "--attachment", att["id"], "--pipeline-version", 2) + r2 = jobs_cli("reprocess", "--attachment", att["id"], "--pipeline-version", 1) + check(r1["result"] == r2["result"] == "noop", "%s %s" % (r1, r2)) + wait_until(lambda: names(att["id"]).count("duplicate_ignored") >= 3, timeout=30, interval=1) + check(served(att["id"]) == v2_served, "v1 duplicate changed result") + check(sql("SELECT published_version FROM attachments WHERE id = '%s'" % att["id"]) == ["2"], "pointer") + return "v1 ready → v2 ready (pointer 1→2); 3 v1 duplicates ignored; reprocess v1/v2 again → noop" + + +@s.case("invariants I1–I7 hold for everything this suite produced (settled, bytes verified)") +def _(): + wait_until(lambda: jobs_cli("invariants", "--settled", "--since", START, expect=(0, 1))["ok"], timeout=60, interval=2) + st = invariants() + return "attachments %s, jobs %s %s, variants %s, events %s" % ( + st["attachments"], st["jobs"], st["job_status"], st["variants"], st["events"]) + + +s.run() diff --git a/student-tests/test_storage_failures.py b/student-tests/test_storage_failures.py new file mode 100644 index 00000000..bdaf5061 --- /dev/null +++ b/student-tests/test_storage_failures.py @@ -0,0 +1,147 @@ +#!/usr/bin/env python3 +"""Отказы объектного хранилища и согласованность S3 ↔ PostgreSQL (уровень 4). + +ВНИМАНИЕ: тест останавливает/запускает контейнер s3 и поднимает профиль fault (api-fault, :8082). +Volumes не удаляются. Команды переопределяются STOP_S3/START_S3/FAULT_UP/FAULT_DOWN. +""" +import os +import socket +import subprocess +import shlex +import time +from urllib.parse import urlsplit + +from common import (BASE_URL, DC, ROOT, Client, Failure, Suite, check, login, make_png, new_user, s3_admin, sh, sql, + upload, wait_until) + +FAULT_URL = os.environ.get("FAULT_BASE_URL", "http://127.0.0.1:8082") +CMD = {"stop_s3": os.environ.get("STOP_S3", DC + " stop s3"), + "start_s3": os.environ.get("START_S3", DC + " start s3"), + "fault_up": os.environ.get("FAULT_UP", DC + " --profile fault up -d --no-deps --force-recreate api-fault"), + "fault_down": os.environ.get("FAULT_DOWN", DC + " --profile fault stop api-fault")} +c = Client(BASE_URL, timeout=15) +s = Suite("object storage failures (" + BASE_URL + ")") +alice = new_user(c, "sa"); login(c, alice) +bob = new_user(c, "sb"); login(c, bob) +chat = c.call("POST", "/api/v1/chats", 201, actor=alice, schema="Chat", + body={"title": "storage", "member_ids": [alice["id"], bob["id"]]})["json"] +UP = "/api/v1/chats/" + chat["id"] + "/attachments" + + +def n_objects(): + """lab5: загрузка пишет в staging/ (оригинал публикует worker в originals/ после обработки).""" + return len(s3_admin("ls", "staging/").splitlines()) + + +def n_intents(): + return int(sql("SELECT count(*) FROM upload_intents")[0]) + + +@s.case("bucket is private outside API: anonymous GET/LIST/PUT denied, API key limited") +def _(): + att, _ = upload(c, alice, chat) + c.wait_ready(alice, att) # оригинал опубликован в originals/ + key = sql("SELECT object_key FROM attachments WHERE id = '%s'" % att["id"])[0] + status = s3_admin("anon-get", key) + check(status in ("401", "403"), "anonymous GET of existing object returned " + status) + out = subprocess.run(shlex.split(DC + " exec -T api python -m messenger s3-check"), cwd=ROOT, + capture_output=True, text=True, timeout=60) + lines = [ln for ln in out.stdout.splitlines() if ln.startswith(("PASS", "FAIL"))] + check(out.returncode == 0 and lines and all(ln.startswith("PASS") for ln in lines), "s3-check failed: " + out.stdout[-400:]) + return "anon GET %s; s3-check %d/%d PASS" % (status, len(lines), len(lines)) + + +@s.case("S3 down: upload/download 503 fast, text messages and readiness keep working") +def _(): + att, data = upload(c, alice, chat) + c.wait_ready(alice, att) + sh(CMD["stop_s3"]) + try: + t = time.monotonic() + c.call("POST", UP + "?filename=a.png", 503, actor=alice, raw=make_png(), headers={"Content-Type": "image/png"}) + took_up = time.monotonic() - t + t = time.monotonic() + c.call("GET", "/api/v1/attachments/" + att["id"] + "/content", 503, actor=bob) + took_down = time.monotonic() - t + c.call("GET", "/api/v1/attachments/" + att["id"], actor=bob, schema="Attachment") # метаданные — из БД + c.message(alice, chat, "S3 лежит, текст работает") + c.message(alice, chat, "", attachments=[att["id"]]) # ссылка на готовое вложение + c.call("GET", "/health/ready", schema="Health") + check(took_up < 5 and took_down < 5, "503 too slow: %.2f / %.2f s" % (took_up, took_down)) + finally: + sh(CMD["start_s3"]) + # После старта SeaweedFS чтение возвращается раньше записи (прогрев топологии ~15 с): ждём оба. + slow = Client(BASE_URL, timeout=60) + t0 = time.monotonic() + wait_until(lambda: slow.call("GET", "/api/v1/attachments/" + att["id"] + "/content", [200, 503], actor=bob)["status"] == 200, + timeout=90) + read_back = time.monotonic() - t0 + wait_until(lambda: slow.call("POST", UP + "?filename=b.png", [202, 503], actor=alice, raw=make_png(), + headers={"Content-Type": "image/png"})["status"] == 202, timeout=90) + write_back = time.monotonic() - t0 + check(c.call("GET", "/api/v1/attachments/" + att["id"] + "/content", actor=bob)["bytes"] == data, "data changed") + return "503 in %.2fs/%.2fs; after start: reads %.1fs, writes %.1fs" % (took_up, took_down, read_back, write_back) + + +@s.case("interrupted upload: no object and no intent left behind") +def _(): + objects, intents = n_objects(), n_intents() + png = make_png(300, 300) + u = urlsplit(BASE_URL) + head = ("POST %s?filename=cut.png HTTP/1.1\r\nHost: %s\r\nAuthorization: Bearer %s\r\nContent-Type: image/png\r\n" + "Content-Length: %d\r\n\r\n" % (UP, u.netloc, alice["token"], len(png))).encode() + for cut in (len(png) // 3, len(png) - 1): + sock = socket.create_connection((u.hostname, u.port or 80), timeout=5) + sock.sendall(head + png[:cut]) + time.sleep(0.3) + sock.close() # клиент пропал посреди тела + wait_until(lambda: n_intents() <= intents, timeout=30) + check(n_objects() == objects, "objects changed: %d -> %d" % (objects, n_objects())) + return "objects %d, intents %d — unchanged" % (objects, intents) + + +@s.case("uploads rejected at the very end (truncated PNG) leave no staging object (race regression)") +def _(): + # Ошибка обнаруживается только в finish(), после последнего байта. Раньше S3 мог зафиксировать + # объект уже после компенсирующего DELETE (нашёл инвариант I7); теперь последний кусок + # придерживается до проверки, и PUT обрывается раньше Content-Length. + before = n_objects() + png = make_png(20, 20) + for i in range(30): + c.call("POST", UP + "?filename=trunc%d.png" % i, 415, actor=alice, raw=png[:-12], headers={"Content-Type": "image/png"}) + time.sleep(3) + after = n_objects() + check(after == before, "staging objects %d -> %d" % (before, after)) + return "30 × 415 at finish(); staging objects %d → %d" % (before, after) + + +@s.case("crash between staging PUT and DB COMMIT: intent recorded, janitor removes object after grace") +def _(): + os.environ["API_FAULT_INJECT"] = "crash_after_s3_put" # точка отказа api-fault для этого сценария + sh(CMD["fault_up"], timeout=120) + try: + fc = Client(FAULT_URL, timeout=10) + wait_until(lambda: fc.call("GET", "/health/ready", [200, 503])["status"] == 200, timeout=90) + objects = n_objects() + try: + upload(fc, alice, chat, make_png(50, 50)) + raise Failure("upload to crashing replica unexpectedly succeeded") + except Failure as exc: + if "unexpectedly" in str(exc): + raise + rows = sql("SELECT object_key FROM upload_intents WHERE created_at > clock_timestamp() - interval '1 minute'") + check(rows, "no intent recorded before S3 PUT") + key = rows[-1] + check(s3_admin("sha", key) != "-", "object must exist after PUT (crash happened after it)") + check(sql("SELECT count(*) FROM attachments WHERE staging_key = '%s'" % key) == ["0"], "metadata committed?!") + t = time.monotonic() + wait_until(lambda: s3_admin("sha", key) == "-" and + sql("SELECT count(*) FROM upload_intents WHERE object_key = '%s'" % key) == ["0"], timeout=90, interval=2) + check(n_objects() == objects, "untracked objects remain") + return "orphan %s… removed %.1fs after crash (grace 10 s)" % (key[:20], time.monotonic() - t) + finally: + sh(CMD["fault_down"], timeout=120) + os.environ.pop("API_FAULT_INJECT", None) + + +s.run() diff --git a/student-tests/test_telemetry_persistence.py b/student-tests/test_telemetry_persistence.py new file mode 100644 index 00000000..b7527eb8 --- /dev/null +++ b/student-tests/test_telemetry_persistence.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python3 +"""lab6: история наблюдений переживает перезапуск хранилищ telemetry (volumes promdata/lokidata/tempodata/ +grafanadata) и сбор продолжается после него. + +Сценарий: контролируемый запрос (известный X-Request-Id) → его лог, trace и значение метрики в прошлом → +scripts/restart.sh (перезапуск ВСЕХ сервисов, включая Collector, Prometheus, Loki, Tempo, Grafana) → +тот же лог, тот же trace и то же историческое значение метрики находятся снова; dashboard по-прежнему +provisioned; новый запрос после рестарта тоже доходит до всех трёх хранилищ. +""" +import os +import subprocess +import sys +import time + +from common import BASE_URL, ROOT, Client, Suite, check, login, new_user +from obs import Grafana, ObsError, wait_for + +suite = Suite("lab6: сохранность истории telemetry после перезапуска") +c = Client(BASE_URL) +g = Grafana() +st = {} +HOOK = os.environ.get("RESTART_HOOK", "scripts/restart.ps1" if os.name == "nt" else "scripts/restart.sh") + + +def controlled_request(): + a = new_user(c, "persist") + login(c, a) + chat = c.call("POST", "/api/v1/chats", 201, actor=a, schema="Chat", body={"title": "p", "member_ids": [a["id"]]})["json"] + r = c.call("POST", "/api/v1/chats/%s/messages" % chat["id"], 201, actor=a, body={"text": "persist"}, + headers={"Idempotency-Key": "persist-%d" % time.time_ns()}) + rid = r["headers"]["X-Request-Id"] + rec = wait_for(lambda: [x for x in g.loki('{service_name="messenger-api"} | request_id="%s"' % rid, since=600) + if x.get("event") == "http.request"], 60, what="log")[-1] + wait_for(lambda: g.trace(rec["trace_id"]), 60, what="trace") + return rid, rec["trace_id"] + + +@suite.case("до рестарта: лог, trace и метрика контрольного запроса сохранены") +def before(): + rid, tid = controlled_request() + time.sleep(15) # метрика экспортирована и записана + st["t"] = time.time() + st["metric"] = g.prom_value('sum(http_server_request_duration_seconds_count{service_name="messenger-api",' + 'http_route="/api/v1/chats/{chat_id}/messages"})', at=st["t"]) + check(st["metric"], "no metric value") + st.update(rid=rid, tid=tid) + return "request_id → trace %s…, счётчик POST messages = %d" % (tid[:12], st["metric"]) + + +@suite.case("перезапуск всех сервисов и хранилищ (volumes сохраняются)") +def restart(): + cmd = (["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", HOOK] if HOOK.endswith(".ps1") else [HOOK]) + t0 = time.time() + subprocess.run(cmd, cwd=ROOT, check=True, timeout=300, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + + def ready(): + ok = c.call("GET", "/health/ready", [200, 503, 502])["status"] == 200 + ok = ok and all(g.get("/api/datasources/uid/%s/health" % u).get("status") == "OK" for u in ("prometheus", "loki", "tempo")) + return ok + wait_for(ready, 180, interval=2, what="stack ready after restart") + return "hook %s + готовность за %.0f с" % (HOOK, time.time() - t0) + + +@suite.case("после рестарта: тот же лог, тот же trace, то же значение метрики в прошлом") +def after(): + recs = wait_for(lambda: g.loki('{service_name="messenger-api"} | request_id="%s"' % st["rid"], since=1800), 60, what="old log") + check(any(r.get("trace_id") == st["tid"] for r in recs), "old log lost or unlinked") + spans = wait_for(lambda: g.trace(st["tid"]), 90, what="old trace") + check(any(s["kind"] == "SERVER" and s["attrs"].get("messenger.request_id") == st["rid"] for s in spans), "old trace content") + v = g.prom_value('sum(http_server_request_duration_seconds_count{service_name="messenger-api",' + 'http_route="/api/v1/chats/{chat_id}/messages"})', at=st["t"]) + check(v == st["metric"], "historical metric changed: %s != %s" % (v, st["metric"])) + d = g.get("/api/dashboards/uid/messenger-overview") + check(d["meta"].get("provisioned"), "dashboard lost") + return "лог, trace (%d spans), метрика (%d) и dashboard на месте" % (len(spans), v) + + +@suite.case("после рестарта: новые данные доходят во все три хранилища") +def new_data(): + rid, tid = controlled_request() + v = wait_for(lambda: g.prom_value('sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api"}[1m]))'), + 60, what="fresh metrics") + return "новый trace %s…, текущий RPS API %.2f" % (tid[:12], v) + + +if __name__ == "__main__": + try: + g.get("/api/health") + except ObsError as e: + sys.exit("Grafana недоступна: %s" % e) + suite.run()