diff --git a/.env.example b/.env.example index 5851129e..16c7408a 100644 --- a/.env.example +++ b/.env.example @@ -89,3 +89,16 @@ OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318 OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=lab LB_EXPIRY_PORT=8083 +APP_REVISION=1.6.0 +OTEL_METRIC_EXPORT_INTERVAL=2000 +OTEL_METRIC_EXPORT_TIMEOUT=1000 +OTEL_EXPORTER_OTLP_TIMEOUT=1 +OTEL_BSP_MAX_QUEUE_SIZE=256 +OTEL_BSP_MAX_EXPORT_BATCH_SIZE=64 +OTEL_BSP_SCHEDULE_DELAY=1000 +OTEL_BSP_EXPORT_TIMEOUT=1000 +OTEL_BLRP_MAX_QUEUE_SIZE=256 +OTEL_BLRP_MAX_EXPORT_BATCH_SIZE=64 +OTEL_BLRP_SCHEDULE_DELAY=1000 +OTEL_BLRP_EXPORT_TIMEOUT=1000 +GRAFANA_PORT=3006 diff --git a/Dockerfile b/Dockerfile index 3c8d7873..74211423 100644 --- a/Dockerfile +++ b/Dockerfile @@ -5,8 +5,11 @@ ENV PYTHONDONTWRITEBYTECODE=1 \ POETRY_VIRTUALENVS_CREATE=false WORKDIR /app +RUN --mount=type=cache,target=/root/.cache/pip \ + pip install --timeout 30 --retries 8 "poetry==2.2.1" COPY poetry.lock pyproject.toml ./ -RUN pip install --no-cache-dir --timeout 60 --retries 10 "poetry==2.2.1" \ +RUN --mount=type=cache,target=/root/.cache/pypoetry \ + poetry config requests.max-retries 6 \ && poetry install --only main --no-root --no-interaction COPY migrations ./migrations COPY src ./src diff --git a/Makefile b/Makefile index cd719d4b..af1edcc4 100644 --- a/Makefile +++ b/Makefile @@ -138,3 +138,13 @@ jobs-failed: replay: @test -n "$(JOB_ID)" -a -n "$(OPERATOR)" -a -n "$(REASON)" || (echo "Set JOB_ID, OPERATOR and REASON"; exit 2) docker compose exec -T dispatcher python src/jobs.py replay --job-id "$(JOB_ID)" --operator "$(OPERATOR)" --reason "$(REASON)" + +GRAFANA_URL ?= http://localhost:3006 + +.PHONY: test-observability test-observability-incidents + +test-observability: + $(PYTHON) scripts/check_observability.py --base-url "$(BASE_URL)" --grafana-url "$(GRAFANA_URL)" + +test-observability-incidents: + $(PYTHON) scripts/check_observability.py --base-url "$(BASE_URL)" --grafana-url "$(GRAFANA_URL)" --incidents diff --git a/README.md b/README.md index f1fe7f3d..824039bb 100644 --- a/README.md +++ b/README.md @@ -1,19 +1,20 @@ # Лабораторная 6. Наблюдаемость: OpenTelemetry и Grafana -## Запуск базового стенда +## Запуск ```sh make init make up make test +make test-observability ``` -API: `http://localhost:8082`, Swagger: `http://localhost:8082/docs`, PostgreSQL: `localhost:55435`. Проект `messenger-lab6` использует отдельные образ и volumes. Для собственных проверок: `make install && make student-test`. Реализация наблюдаемости выполняется следующим этапом. +API и Swagger доступны на порту 8082. [Дашборд Grafana](http://localhost:3006/d/messenger-lab6/) открывается на порту 3006. Для проверки алертов и восстановления запустите `make test-observability-incidents`. Запуск и результаты описаны в [REPORT.md](REPORT.md). + +## Задание Научиться находить причину деградации через метрики, логи и трассы всей системы, включая фоновую обработку. -Это **skeleton**, а не готовый сервер. Здесь есть задание, контракт и публичные проверки. Реализацию приложения, Dockerfile и требуемую инфраструктуру пишет студент. Язык и framework свободные; UI не обязателен. - [Карта курса](COURSE.md) · [Процесс fork/PR](CONTRIBUTING.md) · [OpenAPI](contracts/openapi.json) · [Семантика API](contracts/README.md) · [Проверки](tests/README.md) · [Отчёт](REPORT.md) · [Примеры JSON](contracts/examples.json) · [Памятка преподавателю](MAINTAINERS.md) ## Откуда начинаем @@ -61,7 +62,7 @@ API: `http://localhost:8082`, Swagger: `http://localhost:8082/docs`, PostgreSQL: make check # После реализации запустите свой сервер/стенд по REPORT.md. -# По умолчанию тест использует http://localhost:8080. +# Makefile использует http://localhost:8082. make test ``` diff --git a/REPORT.md b/REPORT.md index b97ae42d..a59aa934 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,58 @@ -# Отчёт — лабораторная 6 +# Лабораторная 6. Наблюдаемость Messenger -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +Саватеев Артём. Целевая оценка **4**. -## Запуск из чистого clone +## Запуск -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +```sh +make init +make up +make test +make test-observability +make test-observability-incidents +``` -## Архитектура и решения +Нужны Docker Compose ≥ 2.20.2 и Python ≥ 3.10 для проверки телеметрии. Приложение собрано на Python 3.12.12. Swagger доступен на [8082/docs](http://localhost:8082/docs), дашборд Grafana — на [3006](http://localhost:3006/d/messenger-lab6/). Тома Prometheus, Loki, Tempo и Grafana сохраняются между запусками. -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab5, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +## Сигналы и корреляция -## Доказательства критериев +Две API-реплики, dispatcher и worker отправляют OTLP/HTTP в Collector. Prometheus забирает метрики с Collector. Loki принимает структурированные логи a Grafana читает эти источника. -| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | -| --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | +API сохраняет W3C trace context в той же транзакции, что job и outbox. Dispatcher создаёт producer span для каждой отправки и передаёт её контекст в `traceparent`/`tracestate` задания RabbitMQ. Worker продолжает его consumer span, внутри которого видны S3 и PostgreSQL. При retry обе попытки остаются в трассе исходного upload. `X-Trace-Id` ведёт в Tempo, `X-Request-Id` связывает ответ с HTTP-логом. В Loki для корреляции доступны `service_name`, `event`, `severity`, `trace_id` и `span_id`. -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +## Дашборд и алерты -## Эксперименты и отказы +| Сигнал | Запрос или метрика | Единица | +| --- | --- | --- | +| RPS | `sum by (method, route) (rate(messenger_http_requests_total[1m]))` | запрос/с | +| p50/p95/p99 HTTP | `histogram_quantile(0.95, sum by (le) (rate(messenger_http_duration_seconds_bucket[2m])))`; аналогично 0.5/0.99 | с | +| Обработка и время до ready | `messenger_jobs_total{outcome=…}`, `messenger_job_duration_seconds_bucket`, `messenger_attachment_ready_duration_seconds_bucket` | задания, с | +| Ожидающие jobs и outbox | `messenger_queue_depth`, `messenger_queue_oldest_age_seconds`, `messenger_outbox_pending` | задания, с, события | +| PostgreSQL и worker | `messenger_db_pool{state=…}`, `sum(messenger_worker_busy) / sum(messenger_worker_capacity)` | соединения, доля | +| Ресурсы | `rate(messenger_process_cpu_seconds_total[1m])`, `messenger_process_memory_bytes`; аналогично метрики cgroup | ядра, байты | -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +Глубина и возраст относятся к ожидающим jobs в PostgreSQL, включая задания до отправки в RabbitMQ. Возраст считается от принятия исходной job. Перцентили агрегируют histogram buckets реплик. Таймер ready заканчивается после фиксации результата. -| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | -| --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +**SLI** — доля бизнес-ответов без 5xx в скользящем окне 15 минут. Health и Swagger исключены, 4xx входят в знаменатель. **SLO** — ≥ 99%. При отсутствии запросов SLI не определён. `MessengerHighErrorRate` срабатывает при доле 5xx > 5% за 30 с при минимум пяти запросах и выдержке 6 с. `MessengerQueueLag` срабатывает при возрасте > 10 с и непустой очереди в течение 6 с. Правила оценивает Prometheus. Диагностика описана в [runbook](infra/otel/runbook.md). -## Ограничения и следующие шаги +## Буферизация и отказы -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +SDK держит до 256 записей логов и 256 спанов на процесс и отправляет их пакетами до 64. Таймаут OTLP — 1 с. Collector ограничен 256 MiB, memory limiter настроен на 160 MiB с резервом 32 MiB. Размер batch — до 128 записей. Для Loki и Tempo используются отдельные очереди по 16 пакетов с повторами до 8 с. Измеряемые потери при отказе отражаются в счётчиках ошибок отправки Collector. API и worker выполняют бизнес-операции независимо от экспорта. + +## Проверки + +Локальный прогон 23.11.2026. Все 27 запросов дашборда выполнились через Grafana. В Prometheus найдены 16 проверяемых метрик. Одна загрузка дала 22 связанных спана и логи API и worker. [Проверка дашборда](evidence/lab6-dashboard.txt). + +| Сценарий | Наблюдение и результат | +| --- | --- | +| Остановлен worker | В очереди появилось одно задание, возраст достиг 19,9 с. Алерт `MessengerQueueLag` сработал и снялся после обработки. В трассе `2cb55e0cec7f29110c363a2a581ca265` видны publish и consume для исходной попытки и retry. SHA-256 скачанного оригинала совпал. | +| Остановлен PostgreSQL | 44 ответа 503, доля 5xx в окне достигла 73%. В трассе `83aa5b76b36831200387fe72ba38c175` видна ошибка `postgres.pool.acquire`, в Loki найден связанный лог `postgres.unavailable`. После запуска БД запись прошла, алерт снялся. | +| Остановлены Loki и Tempo | API принял 450 сообщений за 18 с. Сумма счётчиков ошибок отправки и переполнения очередей выросла на 2017 записей логов и спанов. Пик RSS Collector составил 213,9 MiB при лимите 256 MiB. После запуска хранилищ доступны прежние логи и трассы, новые записи снова поступают. | + +[Протокол сценариев](evidence/lab6-incidents.txt). Прошли [публичный smoke](evidence/lab6-public.txt), [OpenAPI и JSON Schema](evidence/lab6-contracts.txt) и [миграции на пустой БД](evidence/lab6-migrations.txt). В [основном наборе](evidence/lab6-student-tests.txt) прошло 195 тестов, ещё 23 требуют отдельного запуска. + +После перезапуска PostgreSQL, Valkey, S3, RabbitMQ и сервисов приложения сохранились сессия, сообщение и байты вложения. Команда `make test-persistence ACTION_SCRIPT=scripts/restart.sh`. Через Grafana доступны исторические метрики, логи и трассы после перезапуска стенда. [Протокол перезапуска](evidence/lab6-persistence.txt). + +Нагрузка 24.11.2026. Docker на Mac16,12, 10 vCPU и 7,65 GiB RAM. Лимиты каждой API-реплики 1 CPU и 512 MiB, worker 2 CPU и 1792 MiB, Collector 256 MiB. После 5 с прогрева 4 клиента отправляли синтетические сообщения в один чат в течение 30 с (`python3 tests/load.py --base-url http://localhost:8082 --duration 30 --concurrency 4`). Получено 3797 успешных запросов и 4 ошибки (0,11%), 114,7 успешных запросов/с. p50/p95/p99 успешных ответов — 14,5/63,6/92,9 мс. [Результат нагрузки](evidence/lab6-load.json), [замер CPU и RAM во время теста](evidence/lab6-load-resources.txt). + +Стенд работает на одном хосте. История сигналов хранится 7 дней. Счётчики потерь Collector охватывают записи, дошедшие до его экспортёров. diff --git a/compose.yaml b/compose.yaml index f047eab9..a1178242 100644 --- a/compose.yaml +++ b/compose.yaml @@ -43,6 +43,7 @@ x-api: &api - edge - backend - storage + - ingest healthcheck: test: ["CMD", "python", "src/healthcheck.py"] interval: 5s @@ -84,7 +85,7 @@ services: build: context: . args: - APP_REVISION: ${APP_REVISION:-dev} + APP_REVISION: ${APP_REVISION} deploy: <<: *api-resources replicas: ${API_REPLICAS:-2} @@ -289,6 +290,9 @@ services: <<: *app command: ["python", "src/dispatcher.py"] restart: unless-stopped + environment: + <<: *app-network + OTEL_SERVICE_NAME: messenger-dispatcher depends_on: migrate: condition: service_completed_successfully @@ -298,6 +302,7 @@ services: - broker_url networks: - backend + - ingest healthcheck: test: ["CMD", "python", "src/healthcheck.py", "dispatcher"] interval: 5s @@ -315,6 +320,9 @@ services: <<: *app command: ["python", "src/worker.py"] restart: unless-stopped + environment: + <<: *app-network + OTEL_SERVICE_NAME: messenger-worker depends_on: migrate: condition: service_completed_successfully @@ -329,6 +337,7 @@ services: networks: - backend - storage + - ingest healthcheck: test: ["CMD", "python", "src/healthcheck.py", "worker"] interval: 5s @@ -353,7 +362,73 @@ services: <<: *api-resources replicas: 1 + otel-collector: + image: otel/opentelemetry-collector-contrib:0.145.0 + command: ["--config=/etc/otelcol-contrib/collector.yaml"] + volumes: + - ./infra/otel/collector.yaml:/etc/otelcol-contrib/collector.yaml:ro + networks: [ingest, monitoring] + mem_limit: 256m + restart: unless-stopped + + prometheus: + image: prom/prometheus:v3.11.3 + command: + - --config.file=/etc/prometheus/prometheus.yaml + - --storage.tsdb.path=/prometheus + - --storage.tsdb.retention.time=7d + volumes: + - ./infra/prometheus:/etc/prometheus:ro + - prometheus_data:/prometheus + networks: [monitoring] + mem_limit: 384m + restart: unless-stopped + + loki: + image: grafana/loki:3.6.8 + command: ["-config.file=/etc/loki/loki.yaml"] + volumes: + - ./infra/loki/loki.yaml:/etc/loki/loki.yaml:ro + - loki_data:/loki + networks: [monitoring] + mem_limit: 512m + restart: unless-stopped + + tempo: + image: grafana/tempo:2.9.0 + command: ["-config.file=/etc/tempo/tempo.yaml"] + volumes: + - ./infra/tempo/tempo.yaml:/etc/tempo/tempo.yaml:ro + - tempo_data:/var/tempo + networks: [monitoring] + mem_limit: 384m + restart: unless-stopped + + grafana: + image: grafana/grafana:13.2.4 + environment: + GF_AUTH_ANONYMOUS_ENABLED: "true" + GF_AUTH_ANONYMOUS_ORG_ROLE: Viewer + GF_SECURITY_ADMIN_PASSWORD__FILE: /run/secrets/grafana_admin_password + GF_USERS_ALLOW_SIGN_UP: "false" + GF_ANALYTICS_REPORTING_ENABLED: "false" + GF_ANALYTICS_CHECK_FOR_UPDATES: "false" + secrets: [grafana_admin_password] + ports: + - "127.0.0.1:${GRAFANA_PORT}:3000" + volumes: + - ./infra/grafana/provisioning:/etc/grafana/provisioning:ro + - ./infra/grafana/dashboards:/etc/grafana/dashboards:ro + - grafana_data:/var/lib/grafana + networks: [edge, monitoring] + mem_limit: 384m + restart: unless-stopped + networks: + ingest: + internal: true + monitoring: + internal: true edge: {} backend: internal: true @@ -367,9 +442,15 @@ volumes: postgres_data: s3_data: rabbitmq_data: + prometheus_data: + loki_data: + tempo_data: + grafana_data: # Создаются scripts/init-secrets.sh; в git не попадают secrets: + grafana_admin_password: + file: ./secrets/grafana_admin_password broker_url: file: ./secrets/broker_url s3_access_key_id: diff --git a/evidence/lab6-contracts.txt b/evidence/lab6-contracts.txt new file mode 100644 index 00000000..ed9cd475 --- /dev/null +++ b/evidence/lab6-contracts.txt @@ -0,0 +1,4 @@ +.venv/bin/python scripts/check_contract.py +PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. +.venv/bin/python scripts/validate_openapi.py +PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested. diff --git a/evidence/lab6-dashboard.txt b/evidence/lab6-dashboard.txt new file mode 100644 index 00000000..6ea9026f --- /dev/null +++ b/evidence/lab6-dashboard.txt @@ -0,0 +1 @@ +PASS: Grafana loaded 17 panels, Prometheus executed 27 dashboard queries diff --git a/evidence/lab6-incidents.txt b/evidence/lab6-incidents.txt new file mode 100644 index 00000000..3dc738c3 --- /dev/null +++ b/evidence/lab6-incidents.txt @@ -0,0 +1,35 @@ +python3 scripts/check_observability.py --base-url "http://localhost:8082" --grafana-url "http://localhost:3006" --incidents +SIGNALS trace=4a2dec658965c2c25e0e33c7f357c738 request_id=99d9ad1341dd202e5b6f22975ae3e9b8 spans=22 metrics=16 panels=17 + Container messenger-lab6-worker-1 Stopping + Container messenger-lab6-worker-1 Stopped + Container messenger-lab6-postgres-1 Waiting + Container messenger-lab6-s3-1 Waiting + Container messenger-lab6-s3-1 Healthy + Container messenger-lab6-postgres-1 Healthy + Container messenger-lab6-s3-bootstrap-1 Starting + Container messenger-lab6-migrate-1 Starting + Container messenger-lab6-s3-bootstrap-1 Started + Container messenger-lab6-migrate-1 Started + Container messenger-lab6-broker-1 Waiting + Container messenger-lab6-migrate-1 Waiting + Container messenger-lab6-s3-bootstrap-1 Waiting + Container messenger-lab6-broker-1 Healthy + Container messenger-lab6-s3-bootstrap-1 Exited + Container messenger-lab6-migrate-1 Exited + Container messenger-lab6-worker-1 Starting + Container messenger-lab6-worker-1 Started +QUEUE firing → resolved; depth=1 oldest=19.9s trace=2cb55e0cec7f29110c363a2a581ca265 retry linked + Container messenger-lab6-postgres-1 Stopping + Container messenger-lab6-postgres-1 Stopped + Container messenger-lab6-postgres-1 Starting + Container messenger-lab6-postgres-1 Started +DB firing → resolved; 503=44 ratio=73.0% trace=83aa5b76b36831200387fe72ba38c175 failed_span=postgres.pool.acquire + Container messenger-lab6-tempo-1 Stopping + Container messenger-lab6-loki-1 Stopping + Container messenger-lab6-tempo-1 Stopped + Container messenger-lab6-loki-1 Stopped + Container messenger-lab6-loki-1 Starting + Container messenger-lab6-tempo-1 Starting + Container messenger-lab6-tempo-1 Started + Container messenger-lab6-loki-1 Started +STORAGE successful writes=450 dropped logs/spans=2017 peak collector RSS=213.9 MiB; history preserved and new signals ingested diff --git a/evidence/lab6-load-resources.txt b/evidence/lab6-load-resources.txt new file mode 100644 index 00000000..4d08af63 --- /dev/null +++ b/evidence/lab6-load-resources.txt @@ -0,0 +1,4 @@ +messenger-lab6-api-1 49.66% 81.23MiB / 512MiB +messenger-lab6-api-2 99.58% 81.36MiB / 512MiB +messenger-lab6-worker-1 0.34% 77.75MiB / 1.75GiB +messenger-lab6-otel-collector-1 3.29% 65.54MiB / 256MiB diff --git a/evidence/lab6-load.json b/evidence/lab6-load.json new file mode 100644 index 00000000..df30047a --- /dev/null +++ b/evidence/lab6-load.json @@ -0,0 +1,17 @@ +{ + "lab": 6, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 33.104, + "concurrency": 4, + "successful_requests": 3797, + "failed_requests": 4, + "error_ratio": 0.001052, + "successful_rps": 114.697, + "successful_latency_ms": { + "p50": 14.476, + "p95": 63.627, + "p99": 92.915 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/lab6-migrations.txt b/evidence/lab6-migrations.txt new file mode 100644 index 00000000..3657ad12 --- /dev/null +++ b/evidence/lab6-migrations.txt @@ -0,0 +1,19 @@ +./scripts/check_migrations.sh +2026-11-23 16:54:45.450 | INFO | infrastructure.dependencies.database:create_pool:71 - Установка соединения с базой данных psql +2026-11-23 16:54:45.523 | INFO | infrastructure.dependencies.database:create_pool:101 - Соединение с базой данных psql установлено. DB_NAME: test, pool: 2..10 +пустой volume: таблиц в public = 0 +API до migrate: В БД не применены миграции [1, 2, 3, 4, 5, 6]: сначала запустите migrate +2026-11-23 16:54:45.540 | INFO | infrastructure.dependencies.database:apply_migrations:154 - Применена миграция 0001_init.sql +2026-11-23 16:54:45.541 | INFO | infrastructure.dependencies.database:apply_migrations:154 - Применена миграция 0002_message_idempotency.sql +2026-11-23 16:54:45.546 | INFO | infrastructure.dependencies.database:apply_migrations:154 - Применена миграция 0003_attachments.sql +2026-11-23 16:54:45.553 | INFO | infrastructure.dependencies.database:apply_migrations:154 - Применена миграция 0004_attachment_jobs.sql +2026-11-23 16:54:45.554 | INFO | infrastructure.dependencies.database:apply_migrations:154 - Применена миграция 0005_job_error_code.sql +2026-11-23 16:54:45.554 | INFO | infrastructure.dependencies.database:apply_migrations:154 - Применена миграция 0006_job_trace_context.sql +2026-11-23 16:54:45.555 | INFO | infrastructure.dependencies.database:apply_migrations:159 - Схема БД в актуальной версии +запуск 1: schema_migrations = [(1, '0001_init'), (2, '0002_message_idempotency'), (3, '0003_attachments'), (4, '0004_attachment_jobs'), (5, '0005_job_error_code'), (6, '0006_job_trace_context')], таблиц = 13 +2026-11-23 16:54:45.556 | INFO | infrastructure.dependencies.database:apply_migrations:159 - Схема БД в актуальной версии +запуск 2: schema_migrations = [(1, '0001_init'), (2, '0002_message_idempotency'), (3, '0003_attachments'), (4, '0004_attachment_jobs'), (5, '0005_job_error_code'), (6, '0006_job_trace_context')], таблиц = 13 +2026-11-23 16:54:45.556 | INFO | infrastructure.dependencies.database:apply_migrations:159 - Схема БД в актуальной версии +запуск 3: schema_migrations = [(1, '0001_init'), (2, '0002_message_idempotency'), (3, '0003_attachments'), (4, '0004_attachment_jobs'), (5, '0005_job_error_code'), (6, '0006_job_trace_context')], таблиц = 13 +2026-11-23 16:54:45.557 | INFO | infrastructure.dependencies.database:check_migrations:181 - Схема БД совместима: версия 6 +API после migrate: схема совместима diff --git a/evidence/lab6-persistence.txt b/evidence/lab6-persistence.txt new file mode 100644 index 00000000..62a571e1 --- /dev/null +++ b/evidence/lab6-persistence.txt @@ -0,0 +1,4 @@ +python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://localhost:8082" +Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. +PASS: historical metrics, logs and spans are still accessible via Grafana after restarting the stack. diff --git a/evidence/lab6-public.txt b/evidence/lab6-public.txt new file mode 100644 index 00000000..5eab6946 --- /dev/null +++ b/evidence/lab6-public.txt @@ -0,0 +1,2 @@ +python3 tests/smoke.py --base-url "http://localhost:8082" +PASS: lab6 public API scenario; infrastructure and grading evidence remain separate. diff --git a/evidence/lab6-student-tests.txt b/evidence/lab6-student-tests.txt new file mode 100644 index 00000000..efa36244 --- /dev/null +++ b/evidence/lab6-student-tests.txt @@ -0,0 +1 @@ +================== 195 passed, 23 skipped in 61.04s (0:01:01) ================== diff --git a/infra/grafana/dashboards/messenger.json b/infra/grafana/dashboards/messenger.json new file mode 100644 index 00000000..b30523d6 --- /dev/null +++ b/infra/grafana/dashboards/messenger.json @@ -0,0 +1,675 @@ +{ + "uid": "messenger-lab6", + "title": "Messenger · наблюдаемость", + "tags": [ + "lab6", + "messenger" + ], + "schemaVersion": 41, + "timezone": "browser", + "version": 1, + "refresh": "5s", + "time": { + "from": "now-15m", + "to": "now" + }, + "panels": [ + { + "id": 1, + "type": "timeseries", + "title": "HTTP — запросы в секунду", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 0, + "y": 0, + "w": 12, + "h": 8 + }, + "fieldConfig": { + "defaults": { + "unit": "reqps" + }, + "overrides": [] + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (method, route) (rate(messenger_http_requests_total[1m]))", + "legendFormat": "{{method}} {{route}}" + } + ] + }, + { + "id": 2, + "type": "timeseries", + "title": "HTTP — длительность", + "description": "Перцентили из суммарных histogram buckets всех API-реплик за 2 минуты.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 12, + "y": 0, + "w": 12, + "h": 8 + }, + "fieldConfig": { + "defaults": { + "unit": "s" + }, + "overrides": [] + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_http_duration_seconds_bucket[2m])))", + "legendFormat": "p50" + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_http_duration_seconds_bucket[2m])))", + "legendFormat": "p95" + }, + { + "refId": "C", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_http_duration_seconds_bucket[2m])))", + "legendFormat": "p99" + } + ] + }, + { + "id": 3, + "type": "timeseries", + "title": "HTTP — доля 5xx", + "description": "Только /api/v1. Health и Swagger исключены. 4xx входят в знаменатель.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 0, + "y": 8, + "w": 12, + "h": 8 + }, + "fieldConfig": { + "defaults": { + "unit": "percentunit" + }, + "overrides": [] + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "messenger:http_error_ratio:30s", + "legendFormat": "5xx / все запросы" + } + ] + }, + { + "id": 4, + "type": "timeseries", + "title": "SLO доступности API за 15 минут", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 12, + "y": 8, + "w": 12, + "h": 8 + }, + "fieldConfig": { + "defaults": { + "unit": "percentunit" + }, + "overrides": [] + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "messenger:http_availability:15m", + "legendFormat": "SLI" + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "vector(0.99)", + "legendFormat": "SLO 99%" + } + ] + }, + { + "id": 5, + "type": "timeseries", + "title": "Worker — исходы обработки", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 0, + "y": 16, + "w": 12, + "h": 8 + }, + "fieldConfig": { + "defaults": { + "unit": "ops" + }, + "overrides": [] + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (outcome) (rate(messenger_jobs_total[1m]))", + "legendFormat": "{{outcome}}" + } + ] + }, + { + "id": 6, + "type": "timeseries", + "title": "Worker — время обработки", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 12, + "y": 16, + "w": 12, + "h": 8 + }, + "fieldConfig": { + "defaults": { + "unit": "s" + }, + "overrides": [] + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_job_duration_seconds_bucket[2m])))", + "legendFormat": "p50" + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_duration_seconds_bucket[2m])))", + "legendFormat": "p95" + }, + { + "refId": "C", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_job_duration_seconds_bucket[2m])))", + "legendFormat": "p99" + } + ] + }, + { + "id": 7, + "type": "timeseries", + "title": "Очередь — ожидающие задания", + "description": "Устойчивый backlog в PostgreSQL включает задачи до publish и после publish, пока worker их не захватил.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 0, + "y": 24, + "w": 12, + "h": 8 + }, + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "max(messenger_queue_depth)", + "legendFormat": "queued" + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "max(messenger_outbox_pending)", + "legendFormat": "не отправлено в RabbitMQ" + } + ] + }, + { + "id": 8, + "type": "timeseries", + "title": "Очередь — возраст старейшей job", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 12, + "y": 24, + "w": 12, + "h": 8 + }, + "fieldConfig": { + "defaults": { + "unit": "s" + }, + "overrides": [] + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "max by (queue) (messenger_queue_oldest_age_seconds)", + "legendFormat": "{{queue}}" + } + ] + }, + { + "id": 9, + "type": "timeseries", + "title": "Время от 202 до ready", + "description": "От создания job в транзакции принятия до COMMIT готового вложения.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 0, + "y": 32, + "w": 12, + "h": 8 + }, + "fieldConfig": { + "defaults": { + "unit": "s" + }, + "overrides": [] + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_attachment_ready_duration_seconds_bucket[2m])))", + "legendFormat": "p50" + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_attachment_ready_duration_seconds_bucket[2m])))", + "legendFormat": "p95" + }, + { + "refId": "C", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_attachment_ready_duration_seconds_bucket[2m])))", + "legendFormat": "p99" + } + ] + }, + { + "id": 10, + "type": "timeseries", + "title": "Worker — занятые слоты", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 12, + "y": 32, + "w": 12, + "h": 8 + }, + "fieldConfig": { + "defaults": { + "unit": "percentunit" + }, + "overrides": [] + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(messenger_worker_busy) / sum(messenger_worker_capacity)", + "legendFormat": "busy / capacity" + } + ] + }, + { + "id": 11, + "type": "timeseries", + "title": "PostgreSQL — пул соединений", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 0, + "y": 40, + "w": 12, + "h": 8 + }, + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (service_name, state) (messenger_db_pool{state=~\"used|waiting|capacity\"})", + "legendFormat": "{{service_name}} {{state}}" + } + ] + }, + { + "id": 12, + "type": "timeseries", + "title": "CPU — ядра", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 12, + "y": 40, + "w": 12, + "h": 8 + }, + "fieldConfig": { + "defaults": { + "unit": "cores" + }, + "overrides": [] + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (service_name) (rate(messenger_process_cpu_seconds_total[1m]))", + "legendFormat": "процесс {{service_name}}" + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (service_name) (rate(messenger_container_cpu_seconds_total[1m]))", + "legendFormat": "контейнер {{service_name}}" + } + ] + }, + { + "id": 13, + "type": "timeseries", + "title": "RAM — процесс и контейнер", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 0, + "y": 48, + "w": 12, + "h": 8 + }, + "fieldConfig": { + "defaults": { + "unit": "bytes" + }, + "overrides": [] + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (service_name) (messenger_process_memory_bytes)", + "legendFormat": "RSS {{service_name}}" + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (service_name) (messenger_container_memory_bytes)", + "legendFormat": "cgroup {{service_name}}" + } + ] + }, + { + "id": 14, + "type": "timeseries", + "title": "Алерты", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 12, + "y": 48, + "w": 12, + "h": 8 + }, + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "ALERTS", + "legendFormat": "{{alertname}} {{alertstate}}" + } + ] + }, + { + "id": 15, + "type": "timeseries", + "title": "Collector — потери записей", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 0, + "y": 56, + "w": 12, + "h": 8 + }, + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(increase(otelcol_exporter_send_failed_log_records_total[1m])) + sum(increase(otelcol_exporter_enqueue_failed_log_records_total[1m]))", + "legendFormat": "логи {{exporter}}" + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(increase(otelcol_exporter_send_failed_spans_total[1m])) + sum(increase(otelcol_exporter_enqueue_failed_spans_total[1m]))", + "legendFormat": "спаны {{exporter}}" + } + ] + }, + { + "id": 16, + "type": "timeseries", + "title": "Collector — память", + "description": "RSS процесса Collector. Лимит контейнера 256 MiB.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 12, + "y": 56, + "w": 12, + "h": 8 + }, + "fieldConfig": { + "defaults": { + "unit": "bytes" + }, + "overrides": [] + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "otelcol_process_memory_rss_bytes", + "legendFormat": "RSS" + } + ] + }, + { + "id": 17, + "type": "logs", + "title": "API, dispatcher и worker", + "datasource": { + "type": "loki", + "uid": "loki" + }, + "gridPos": { + "x": 0, + "y": 64, + "w": 24, + "h": 12 + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "loki", + "uid": "loki" + }, + "expr": "{service_name=~\"messenger-api|messenger-worker|messenger-dispatcher\"} | event=~\"http.response|job.processed|job.processing_error|postgres.unavailable\"" + } + ], + "options": { + "showTime": true, + "showLabels": true, + "enableLogDetails": true + } + } + ] +} diff --git a/infra/grafana/provisioning/dashboards/telemetry.yaml b/infra/grafana/provisioning/dashboards/telemetry.yaml new file mode 100644 index 00000000..72f10f2c --- /dev/null +++ b/infra/grafana/provisioning/dashboards/telemetry.yaml @@ -0,0 +1,7 @@ +apiVersion: 1 +providers: + - name: Messenger + folder: Lab6 + type: file + options: + path: /etc/grafana/dashboards diff --git a/infra/grafana/provisioning/datasources/telemetry.yaml b/infra/grafana/provisioning/datasources/telemetry.yaml new file mode 100644 index 00000000..64987c9c --- /dev/null +++ b/infra/grafana/provisioning/datasources/telemetry.yaml @@ -0,0 +1,39 @@ +apiVersion: 1 +datasources: + - name: Prometheus + uid: prometheus + type: prometheus + access: proxy + url: http://prometheus:9090 + isDefault: true + editable: false + jsonData: + timeInterval: 2s + - name: Loki + uid: loki + type: loki + access: proxy + url: http://loki:3100 + editable: false + jsonData: + derivedFields: + - name: TraceID + matcherType: label + matcherRegex: trace_id + datasourceUid: tempo + url: '$${__value.raw}' + - name: Tempo + uid: tempo + type: tempo + access: proxy + url: http://tempo:3200 + editable: false + jsonData: + tracesToLogsV2: + datasourceUid: loki + spanStartTimeShift: '-2m' + spanEndTimeShift: '2m' + filterByTraceID: true + tags: + - key: service.name + value: service_name diff --git a/infra/loki/loki.yaml b/infra/loki/loki.yaml new file mode 100644 index 00000000..64f95047 --- /dev/null +++ b/infra/loki/loki.yaml @@ -0,0 +1,39 @@ +auth_enabled: false +server: + http_listen_port: 3100 +analytics: + reporting_enabled: false +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 + discover_log_levels: true + retention_period: 168h + otlp_config: + resource_attributes: + ignore_defaults: true + attributes_config: + - action: index_label + attributes: [service.name, deployment.environment.name] +compactor: + working_directory: /loki/compactor + retention_enabled: true + delete_request_store: filesystem diff --git a/infra/otel/README.md b/infra/otel/README.md index c46fe89a..6d3d44c9 100644 --- a/infra/otel/README.md +++ b/infra/otel/README.md @@ -1,7 +1,7 @@ -# Конфигурация наблюдаемости — реализовать +# Наблюдаемость Messenger -Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend. +API, dispatcher и worker отправляют метрики, логи и трассы по OTLP/HTTP в `otel-collector`. Collector отдаёт метрики на scrape Prometheus и отправляет логи в Loki, трассы в Tempo. Grafana получает все три источника и дашборд из `infra/grafana`. -Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. На 4 — alert rules и runbooks. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`. +Collector использует memory limiter и batch. Экспортёры Loki/Tempo имеют отдельные очереди и ограниченный повтор. Порты OTLP, Prometheus, Loki и Tempo доступны в сетях Compose. Grafana доступна только через loopback хоста на порту 3006. -Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён. +Конфиги лежат в `infra/otel`, `infra/prometheus`, `infra/loki`, `infra/tempo`. Сценарии диагностики описаны в [runbook.md](runbook.md). diff --git a/infra/otel/collector.yaml b/infra/otel/collector.yaml new file mode 100644 index 00000000..44249eda --- /dev/null +++ b/infra/otel/collector.yaml @@ -0,0 +1,72 @@ +extensions: + health_check: + endpoint: 0.0.0.0:13133 + +receivers: + otlp: + protocols: + http: + endpoint: 0.0.0.0:4318 + max_request_body_size: 4194304 + +processors: + memory_limiter: + check_interval: 1s + limit_mib: 160 + spike_limit_mib: 32 + batch: + timeout: 1s + send_batch_size: 128 + send_batch_max_size: 128 + +exporters: + prometheus: + endpoint: 0.0.0.0:9464 + metric_expiration: 30s + resource_to_telemetry_conversion: + enabled: true + otlp_http/loki: + endpoint: http://loki:3100/otlp + timeout: 2s + sending_queue: + num_consumers: 1 + queue_size: 16 + retry_on_failure: + initial_interval: 1s + max_interval: 3s + max_elapsed_time: 8s + otlp_http/tempo: + endpoint: http://tempo:4318 + timeout: 2s + sending_queue: + num_consumers: 1 + queue_size: 16 + retry_on_failure: + initial_interval: 1s + max_interval: 3s + max_elapsed_time: 8s + +service: + extensions: [health_check] + telemetry: + metrics: + level: detailed + readers: + - pull: + exporter: + prometheus: + host: 0.0.0.0 + port: 8888 + pipelines: + metrics: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [prometheus] + logs: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [otlp_http/loki] + traces: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [otlp_http/tempo] diff --git a/infra/otel/runbook.md b/infra/otel/runbook.md new file mode 100644 index 00000000..a8051da8 --- /dev/null +++ b/infra/otel/runbook.md @@ -0,0 +1,19 @@ +# Диагностика стенда Lab6 + +Откройте дашборд **Messenger · наблюдаемость** в Grafana на порту 3006. В Explore доступны Prometheus, Loki и Tempo. Для перехода от HTTP-ответа к трассе возьмите `X-Trace-Id` и найдите Trace ID в Tempo. Связанный лог в Loki находится запросом `{service_name="messenger-api"} | trace_id=""`. Для worker замените имя сервиса на `messenger-worker`. + +## Queue lag + +1. Проверьте `max(messenger_queue_oldest_age_seconds)`, `max(messenger_queue_depth)` и `max(messenger_outbox_pending)`. +2. Если возраст растёт, outbox пуст, а актуальный ряд `messenger_worker_capacity` исчез, проверяйте запущен ли worker. Если worker работает, сравните `messenger_worker_busy` с его capacity и разберите ошибки `job.processed` в Loki. +3. После запуска worker убедитесь, что глубина очереди вернулась к нулю, `MessengerQueueLag` снялся и вложение стало ready. В Tempo проследите publish, consume, запись S3 и фиксацию результата PostgreSQL. + +## Error rate + +1. Проверьте `messenger:http_error_ratio:30s` и разложите запросы по статусам и маршрутам. Алерт `MessengerHighErrorRate` реагирует на 5xx. +2. Откройте лог `{service_name="messenger-api"} | event="http.response" | status_code>=500` и перейдите в Tempo по Trace ID. Ошибка в спане `postgres.pool.acquire` или репозитории и событие `postgres.unavailable` в той же трассе указывают на PostgreSQL. +3. После восстановления проверьте успешную запись сообщения и дождитесь выхода 5xx из окна алерта. + +## Экспорт телеметрии + +Проверьте `otelcol_exporter_send_failed_log_records_total`, `otelcol_exporter_send_failed_spans_total`, `otelcol_exporter_queue_size` и `otelcol_process_memory_rss_bytes`. При недоступности Loki или Tempo возможна потеря пакетов после исчерпания очереди и времени повтора. После восстановления отправьте новый запрос и проверьте наличие лога и трассы. Сценарии воспроизводятся командой `make test-observability-incidents` на локальном стенде lab6. diff --git a/infra/prometheus/prometheus.yaml b/infra/prometheus/prometheus.yaml new file mode 100644 index 00000000..c581df66 --- /dev/null +++ b/infra/prometheus/prometheus.yaml @@ -0,0 +1,15 @@ +global: + scrape_interval: 2s + scrape_timeout: 1s + evaluation_interval: 2s + +rule_files: + - /etc/prometheus/rules.yaml + +scrape_configs: + - job_name: messenger + static_configs: + - targets: [otel-collector:9464] + - job_name: collector + static_configs: + - targets: [otel-collector:8888] diff --git a/infra/prometheus/rules.yaml b/infra/prometheus/rules.yaml new file mode 100644 index 00000000..8d238e3b --- /dev/null +++ b/infra/prometheus/rules.yaml @@ -0,0 +1,31 @@ +groups: + - name: messenger + rules: + - record: messenger:http_error_ratio:30s + expr: | + (sum(rate(messenger_http_requests_total{status_class="5xx"}[30s])) or vector(0)) + / sum(rate(messenger_http_requests_total[30s])) + - record: messenger:http_availability:15m + expr: | + 1 - (sum(increase(messenger_http_requests_total{status_class="5xx"}[15m])) or vector(0)) + / sum(increase(messenger_http_requests_total[15m])) + - alert: MessengerHighErrorRate + expr: messenger:http_error_ratio:30s > 0.05 and sum(increase(messenger_http_requests_total[30s])) >= 5 + for: 6s + labels: + severity: warning + annotations: + summary: API возвращает более 5% ответов 5xx + description: За 30 секунд наблюдалось минимум 5 бизнес-запросов. + runbook: infra/otel/runbook.md#error-rate + - alert: MessengerQueueLag + expr: | + max(messenger_queue_oldest_age_seconds) > 10 + and max(messenger_queue_depth) > 0 + for: 6s + labels: + severity: warning + annotations: + summary: Старейшее ожидающее вложение в очереди более 10 секунд + description: Проверьте worker capacity, backlog и ожидающие события outbox. + runbook: infra/otel/runbook.md#queue-lag diff --git a/infra/tempo/tempo.yaml b/infra/tempo/tempo.yaml new file mode 100644 index 00000000..9176e767 --- /dev/null +++ b/infra/tempo/tempo.yaml @@ -0,0 +1,35 @@ +server: + http_listen_port: 3200 +usage_report: + reporting_enabled: false +distributor: + receivers: + otlp: + protocols: + http: + endpoint: 0.0.0.0:4318 +ingester: + max_block_duration: 5m +compactor: + compaction: + block_retention: 168h +metrics_generator: + storage: + path: /var/tempo/generator/wal + traces_storage: + path: /var/tempo/generator/traces + processor: + local_blocks: + filter_server_spans: false + flush_to_storage: true +overrides: + defaults: + metrics_generator: + processors: [local-blocks] +storage: + trace: + backend: local + wal: + path: /var/tempo/wal + local: + path: /var/tempo/blocks diff --git a/migrations/0006_job_trace_context.sql b/migrations/0006_job_trace_context.sql new file mode 100644 index 00000000..7b9742c9 --- /dev/null +++ b/migrations/0006_job_trace_context.sql @@ -0,0 +1,3 @@ +-- Контекст хранится вместе с намерением обработки и переживает рестарт outbox. +ALTER TABLE attachment_jobs ADD COLUMN traceparent text; +ALTER TABLE attachment_jobs ADD COLUMN tracestate text; diff --git a/poetry.lock b/poetry.lock index 5de74b61..9d16dc96 100644 --- a/poetry.lock +++ b/poetry.lock @@ -501,7 +501,7 @@ version = "2026.7.22" description = "Python package for providing Mozilla's CA Bundle." optional = false python-versions = ">=3.7" -groups = ["dev"] +groups = ["main", "dev"] files = [ {file = "certifi-2026.7.22-py3-none-any.whl", hash = "sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775"}, {file = "certifi-2026.7.22.tar.gz", hash = "sha256:741e2c3b351ddf169a738da9f2c048608ff7f2c5cc02f1ebc6b118bb090d5d55"}, @@ -620,6 +620,188 @@ files = [ [package.dependencies] pycparser = {version = "*", markers = "implementation_name != \"PyPy\""} +[[package]] +name = "charset-normalizer" +version = "3.5.2" +description = "The Real First Universal Charset Detector. Open, modern and actively maintained alternative to Chardet." +optional = false +python-versions = ">=3.7" +groups = ["main"] +files = [ + {file = "charset_normalizer-3.5.2-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:195c26fb65950f8fce54e26349852b7bdd7c5f120aeefbcc440b8a20faaed4a3"}, + {file = "charset_normalizer-3.5.2-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9373ad13ef0d2c0fb761e04e55bfdee5a08b52cef2c882c8fbe9935b1517152e"}, + {file = "charset_normalizer-3.5.2-cp310-cp310-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:ddf19c062bea7a0cc80f519243d2c01dd091be0cf952a0750d4ad576709559f5"}, + {file = "charset_normalizer-3.5.2-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:3d14b50de6bf4d0edf857a9386836846f982b8f524e188e2e68b96d702bcf4aa"}, + {file = "charset_normalizer-3.5.2-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:28a15fdad492a99b6eccfaaed66ef3f74050680545ea61ec8b2f4c538f1f1320"}, + {file = "charset_normalizer-3.5.2-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8a893cc101149f80a653f82062ebc95b34525a2614382e1da5458fe7c6997249"}, + {file = "charset_normalizer-3.5.2-cp310-cp310-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:619799369eeef6366ed3e8755a5670f4f2f0fb6b30a0fd7264dc0fdc2357058e"}, + {file = "charset_normalizer-3.5.2-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:447441e76ec720b15e64418d32e092297340387053047c7c694f579efb0ee1d9"}, + {file = "charset_normalizer-3.5.2-cp310-cp310-musllinux_1_2_armv7l.whl", hash = "sha256:62588a277bfb59def052abd940703fa35107152bf479781a878617d60faf8fb5"}, + {file = "charset_normalizer-3.5.2-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:44bd4fbb29dfbeba60e7d2bd000c59e4b21ddb3cc53912b14048d37092706d7c"}, + {file = "charset_normalizer-3.5.2-cp310-cp310-musllinux_1_2_riscv64.whl", hash = "sha256:30fcd120b732aa79317f08dee04d7de0847822e4cf7ee0e9f445bb958832252c"}, + {file = "charset_normalizer-3.5.2-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:50e3adfb96fc189eb27b1cf62d3b598b89b4bb0420d93a3d3e42e137409011be"}, + {file = "charset_normalizer-3.5.2-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:b736353c0a625bbd5fcec108576e2385db3496f4f771f785ff32e108d3c3bc45"}, + {file = "charset_normalizer-3.5.2-cp310-cp310-win32.whl", hash = "sha256:f5833ad231be5eb6553de524a70f48d71b2c8563101750531e0b80184e175cd4"}, + {file = "charset_normalizer-3.5.2-cp310-cp310-win_amd64.whl", hash = "sha256:1461ac396c4fdb983a675f20aa555624f0ee18ac83d832b9244ffff3d8055275"}, + {file = "charset_normalizer-3.5.2-cp310-cp310-win_arm64.whl", hash = "sha256:c6708715abcf3c73b99508253e961a9967f02fe536532834149574eda6de0d1c"}, + {file = "charset_normalizer-3.5.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:3d21b8b13c7592db2ac5e544a6d83187b995257472b0c9e8351b6d507ae37ed6"}, + {file = "charset_normalizer-3.5.2-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d760fe2a4d7c3b226cb9026d6a842868d52a7901bd98420e1baf14e80da85cf5"}, + {file = "charset_normalizer-3.5.2-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c9790464842f85f437dbbb54417eda1e0e6bfc52dd8d22d6fd1c994b73b2dc74"}, + {file = "charset_normalizer-3.5.2-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:4685902cf26edf013ed7a3da0f426ebba7a00ebb9541386d835afbf002c11cab"}, + {file = "charset_normalizer-3.5.2-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:4495c5002a7b28557e7e222e77e0b661183e432b7d6d2e788101e3f240e05b8c"}, + {file = "charset_normalizer-3.5.2-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:211d5a3eb6af8f513b8d4ca19a8c1b7accab1b5f0d3175f9826b03c1a920dc1f"}, + {file = "charset_normalizer-3.5.2-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:ef4fcbf3327382cd4c9f540babd61248208af7b93eec4de397b4d5f58a09e288"}, + {file = "charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:bd16aabe4a02a297c23417aa17ac6299dbd8c49f673bcd645b4929b11f5a4400"}, + {file = "charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:fb9e68df06293761f9fe66ade60a9bc6d0f5e42b8acf2939a9158af86ab0e5bd"}, + {file = "charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:59f63901b0031c3136cf64704dcb21de0bbae62ce2c9529bc39d27665463de37"}, + {file = "charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:304d5463e65a35d7bb0850550e0780395395f6fcf452f04db7d5ca7cecc425ac"}, + {file = "charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:9cf9b1a857e25c4baceeb3624e92a56df3668f398c4acba74e174d81fb4d1d3a"}, + {file = "charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:114e4d0c92d618409ed82a99e22b5c5e768fe995f2973f78265f4524f49d4640"}, + {file = "charset_normalizer-3.5.2-cp311-cp311-win32.whl", hash = "sha256:2625388c6c754520c37abaf3b41eb34d1cc4a373f457898f08606c8e362b891d"}, + {file = "charset_normalizer-3.5.2-cp311-cp311-win_amd64.whl", hash = "sha256:87e50a3e7cb90af586b6c5faf23e302a970415ac73bd7bd90a515a04b427ef96"}, + {file = "charset_normalizer-3.5.2-cp311-cp311-win_arm64.whl", hash = "sha256:254eb48b9fa5ee9898a3c445825a1f340fe53712a098904b39b0bddba8ea3cb1"}, + {file = "charset_normalizer-3.5.2-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:ed2a239c0ea213acc1908150a3037257083c7c083128f1a4cec2ec4b97dca491"}, + {file = "charset_normalizer-3.5.2-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b91363207bd9dc966a691e959bb47f64b30f7ac4b072be9968b366982f7db77c"}, + {file = "charset_normalizer-3.5.2-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:38a873987f3be698494da8b2e3085e29da02da7b633dce73e79c699a113d7bf0"}, + {file = "charset_normalizer-3.5.2-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:355ad8011081dec5412240c087a9a0c9d4d5039f3ed11a3f13e18c2b29b56c51"}, + {file = "charset_normalizer-3.5.2-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:ee21e28f0430bd6dc9086c6e525d5e818a44a5ad19720c8a0ef766792f3eb5e5"}, + {file = "charset_normalizer-3.5.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3d31298449090ab8d47b7b1b2a555ff73cac7ed438a08b7ac160980c7ebed649"}, + {file = "charset_normalizer-3.5.2-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:5cde776b7cc66e4f6c99612cea4aa7269aa65863f7a15841b2c264f103822f4e"}, + {file = "charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:ae4f5fea5b8b8ccff88238cc8569303e5ee95efae67fa62922a311397a71f346"}, + {file = "charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:f7d486c83842422badd511868fd8a9a20e9407ace71564b6af47ce7e60a336c1"}, + {file = "charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:11a4d68a6ecda3292cb1e50239e111543ba5d709bb62a6b4ea1afcfa729d8875"}, + {file = "charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:d6734d2ef8a50fbf8445c139477da401f50d62a0606bf00e20ec6d87773fefb1"}, + {file = "charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:a815775b6c38d4e0ff7bcffbeba67feded90202bb6a226b8dd35f1c855217413"}, + {file = "charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:23851fb4e1b85ed3f6c2a27b777cdfe2e19fb5b38429a8faf38c7542b7665869"}, + {file = "charset_normalizer-3.5.2-cp312-cp312-win32.whl", hash = "sha256:db19d07e2e0129e974a0e65d0064fc222a446cd5122c2fd4184d2af9fc734a9e"}, + {file = "charset_normalizer-3.5.2-cp312-cp312-win_amd64.whl", hash = "sha256:780fbe7cab297b81dad9fb8dc5eb003c0468ffb0d9e5f65068c53a34661a96bc"}, + {file = "charset_normalizer-3.5.2-cp312-cp312-win_arm64.whl", hash = "sha256:e2af3aad578aa6bd1384bcf4750fc285e5a9de53f40b7d41e5a0bf748edeb2b3"}, + {file = "charset_normalizer-3.5.2-cp313-cp313-android_24_arm64_v8a.whl", hash = "sha256:ed905975ab14056a2e5eb1c376cb2e1ebc5396baf84163939c518556fccde9f5"}, + {file = "charset_normalizer-3.5.2-cp313-cp313-android_24_x86_64.whl", hash = "sha256:a66c3bc5ab1f0ff2164fc9965ddd611ff0802173f4b9d24554c563f6ab7e1d6e"}, + {file = "charset_normalizer-3.5.2-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:d2374b62878abb00cd8309b32af6c0b715cd02dec0ca74ef12e5069bdc64144a"}, + {file = "charset_normalizer-3.5.2-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:d376bbd28b3a8999db1a103b3b388aee6f1ddeb3e51bc2172993efdcd86e064d"}, + {file = "charset_normalizer-3.5.2-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:6045373d5a89a5ec71afde535db987ca28e76dfa276c2d4c818265b375d4b055"}, + {file = "charset_normalizer-3.5.2-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:849df64e889b2e17230d58410a03dba311a65b163508fd33679b2b737d4b7858"}, + {file = "charset_normalizer-3.5.2-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:15c44f7edfd477b06f517a5cc317fc1707edb9de2c865f43d4b6513907473234"}, + {file = "charset_normalizer-3.5.2-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a89012d6d5476ee112d20d998570ed58df2260a852afb1758809cd6900411d21"}, + {file = "charset_normalizer-3.5.2-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:0c951d5e6dd9c2ff60609476752bee49da4206adde960ebc247766937f72e718"}, + {file = "charset_normalizer-3.5.2-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7218e8f32b0956cfcd048fd42d9d5779809745ca1d86113ca56f66e7ae1549c4"}, + {file = "charset_normalizer-3.5.2-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:a19a731138fc27d5682277d3b9df22855cea1239bce7fcec5f78f42ef2d1f3c3"}, + {file = "charset_normalizer-3.5.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:62603db9a7caa0802eaa28c1c46fecd7b3a263a774069c24c3c28c302448721c"}, + {file = "charset_normalizer-3.5.2-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:b6856554c4f44d79fc2307d5768854310a8f0096e501c75637542c82292b0429"}, + {file = "charset_normalizer-3.5.2-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:1bc0baf5ef96b6ede57d47f4b8fe4d9d84019c3bfcbeb20a41edc6a6ee341f1f"}, + {file = "charset_normalizer-3.5.2-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:56bc200a365efb37383b7852e4cc5898d3b2da5987289b543956cf8cad71018a"}, + {file = "charset_normalizer-3.5.2-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:2c9ad19a6cfcd5ea5c0d41161d22f9df1dcc277e9bef2751391334546a314c00"}, + {file = "charset_normalizer-3.5.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e243bd13217235fc7290c621941c3f5cc8b66e4872495be821d7436ba2fb838d"}, + {file = "charset_normalizer-3.5.2-cp313-cp313-pyemscripten_2025_0_wasm32.whl", hash = "sha256:a090bb2c68df85450502e3e20d665e3a5af9c65a84d6508ed477badd49166fd3"}, + {file = "charset_normalizer-3.5.2-cp313-cp313-win32.whl", hash = "sha256:2b7b3bbfb4fe8ef40600792d762fbaa9057559f9d3fad209525b7a22b99e91fd"}, + {file = "charset_normalizer-3.5.2-cp313-cp313-win_amd64.whl", hash = "sha256:78456a747de8dc58360ffa581f30a002baf5aa28cb262536545e91f113ed7639"}, + {file = "charset_normalizer-3.5.2-cp313-cp313-win_arm64.whl", hash = "sha256:11912e4bb14baae7c5d8791aa55ba0a3a03ec6729073307b0f57270abaa713d3"}, + {file = "charset_normalizer-3.5.2-cp314-cp314-android_24_arm64_v8a.whl", hash = "sha256:1afb975bd5d68d5ce9f6b6d44fdf2f7e34b895a35e95708a7a91b20a3b51d187"}, + {file = "charset_normalizer-3.5.2-cp314-cp314-android_24_x86_64.whl", hash = "sha256:bbbfc8e28816f19d7c0f1816664980c0a9875d01b27cdf8eedddb639d9e108ad"}, + {file = "charset_normalizer-3.5.2-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:7967d08cf06dee78443b874f98c98036f624f3a4e73e11f9f64f5be4d25393cf"}, + {file = "charset_normalizer-3.5.2-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:4c2b5031f63e331e3839b40aed2dd6f191e9c07edbde303e7876846ea1946995"}, + {file = "charset_normalizer-3.5.2-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:fcff63213e8e6e47770541a4607175404f47cbb3ebea7b6058cc82d524a0e424"}, + {file = "charset_normalizer-3.5.2-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8d86d6fc60743dc916eb79e2eb1ec4818e21e427731543af40a3021851174a13"}, + {file = "charset_normalizer-3.5.2-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:7a881931aa470808df94a8c380eed2bbbc76cd9dc622310f99665658c821eb6d"}, + {file = "charset_normalizer-3.5.2-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:8024d00c3faf3fc0c16e07a69f4405e8eac7cc0ab15f65fe6cf43827c4cf72b4"}, + {file = "charset_normalizer-3.5.2-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:4d48f2d08b9de5864e2c8744d4461b862fb149a18274abc8b698c45975573438"}, + {file = "charset_normalizer-3.5.2-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:34276fd796040bf0993ab33a369aa572e6979c7aab225a88893667ad8eac8f7a"}, + {file = "charset_normalizer-3.5.2-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0521c5665880b33d603717defa76c094048900010897909952397feb3039da56"}, + {file = "charset_normalizer-3.5.2-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:eff0ac9dbe711a4aee69bf04a83896aa9b85f19641264053a9f6d48573abb7dd"}, + {file = "charset_normalizer-3.5.2-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:1503bccbeb36d5527790c3930327704c39af22de3112f1b1666a9f3ce15ee204"}, + {file = "charset_normalizer-3.5.2-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:52aa6992700996af31f375de0c6bacd402b0097fe40b53c426b9f51a90ebabc7"}, + {file = "charset_normalizer-3.5.2-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:e09a3942ecbdee5cce73ea9d42da82b81b72ac1bf031ce069b93b5adf4eac8cd"}, + {file = "charset_normalizer-3.5.2-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:c7c9ab723cde841fefb34efbad91e87f00a674b1fe1cd0784fde742bf2c154dc"}, + {file = "charset_normalizer-3.5.2-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:ddc7dacc8ece3a182e7f15cb862d1fd616b46d076cb1ae9dd232b2c38b655874"}, + {file = "charset_normalizer-3.5.2-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:ee43c17b173d46a3212baa6ead3ae258eeabdae48c263a01ccf0218c366dd655"}, + {file = "charset_normalizer-3.5.2-cp314-cp314-win32.whl", hash = "sha256:4f87960d57feabfb618e4e0af6e7371645fa26a277860739d6e5d6e0012c92f0"}, + {file = "charset_normalizer-3.5.2-cp314-cp314-win_amd64.whl", hash = "sha256:e4e81e09c1578b8df602e3db08b0b3ea0a6947ad612f52bf8dc5ea8d47691f0c"}, + {file = "charset_normalizer-3.5.2-cp314-cp314-win_arm64.whl", hash = "sha256:80d02b6f04e92601a081dd97b23d3128033098bff5d35d392ddcc0476ea11253"}, + {file = "charset_normalizer-3.5.2-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:dca9ab98072a5a54ebacebdc45f53e645336b320c667410b061be1ca588ae709"}, + {file = "charset_normalizer-3.5.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f0aa869112ef88429ae17820d99c3dd9504c9e9c671d3c246f3d7442cb051084"}, + {file = "charset_normalizer-3.5.2-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c0afc6800ba57ccc350374c5bd6150419915d95ce93cdbab2d783d75eaf30ecb"}, + {file = "charset_normalizer-3.5.2-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:7dcd882da75ef9adf94903b1e3b9419e8aa8fb4c7396822b834b9ef7fb96954f"}, + {file = "charset_normalizer-3.5.2-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2e06a3a98f916dd41d27f3105e02e7a40181c98c94b9158733d03a6f80506c09"}, + {file = "charset_normalizer-3.5.2-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6bd128f206a7752ae1f2ab6c61bf8a24ba28913a10df8b14c2637b973ff97a80"}, + {file = "charset_normalizer-3.5.2-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c8f3d67aeaf55f017982b73683f0e7342ba2f6635a78f69ce89ebb26aa411e5c"}, + {file = "charset_normalizer-3.5.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:fe9753dfee015c570d73df76f899f18444d41388bffcde097deba51c4fadbb9f"}, + {file = "charset_normalizer-3.5.2-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:92888bb3187c5ba50500b00b3b310c9f2c651709d28036077680cb5255450a03"}, + {file = "charset_normalizer-3.5.2-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:d008d90a7f2471519aef0c90dfbe73b3e6e4d5e66ac48e19154c17e89e98b604"}, + {file = "charset_normalizer-3.5.2-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:31f3930700408d211f13378ccbe1c40845d8da54bd0681fac3a9b5aae81c7aa8"}, + {file = "charset_normalizer-3.5.2-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:2a925889534b3748302dae5dead07cc13480de1dac3aea80a941b729b471ef93"}, + {file = "charset_normalizer-3.5.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:f5ec61164adcec446f8969a3358ec3f9b26bbda3b9213e5586d219afa8df2915"}, + {file = "charset_normalizer-3.5.2-cp314-cp314t-win32.whl", hash = "sha256:598a11a2c7ebaa5334bf698bf29568c9c390abac6a154d8170fedecd1cea38c5"}, + {file = "charset_normalizer-3.5.2-cp314-cp314t-win_amd64.whl", hash = "sha256:7fdde2c9fd9e3eca40631e024664cf2584272cc8f96308cbe5fdfc930f51d8bc"}, + {file = "charset_normalizer-3.5.2-cp314-cp314t-win_arm64.whl", hash = "sha256:d1befeed746d247c81127bb14de9dc3d30edb6e5976d34f83f86ed262b1d9105"}, + {file = "charset_normalizer-3.5.2-cp315-cp315-macosx_10_15_universal2.whl", hash = "sha256:87475fabc8d9996fd9c27debb395e642e8c838d78a00b6e932227a0e06b81e26"}, + {file = "charset_normalizer-3.5.2-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9409a8bf35cf78353942504b24a57de3d75b708997a1e4bd8db71ac8633ce364"}, + {file = "charset_normalizer-3.5.2-cp315-cp315-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:498dc3188ca05a68231ac3fdbfc7f57eb67e1343c30e0fea17f8218c1599b253"}, + {file = "charset_normalizer-3.5.2-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:e242bb1c5e76e97dfa9e7f209a71e93a01d7f19ffdd5cfbb2e2d55b4f08f8ab0"}, + {file = "charset_normalizer-3.5.2-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:def79fa35ef0cef8d2accec024f4fdc7ead3012ff02f5215c783f39f03ef8cfc"}, + {file = "charset_normalizer-3.5.2-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3df041de8887954562c9b261cba85ca0e9ded74048daf125f45edcfaa4832229"}, + {file = "charset_normalizer-3.5.2-cp315-cp315-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:04851f73ae72b8413dddadb16a49dfee95263553741fd42d546f7d66907e6be5"}, + {file = "charset_normalizer-3.5.2-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:183b88127acdb4fabe59d951ab424faf1af7b63cdbb5f776186c1ea2ffcaed98"}, + {file = "charset_normalizer-3.5.2-cp315-cp315-musllinux_1_2_armv7l.whl", hash = "sha256:16fa0eccf81304b79c5cd87f9271c3b85dd9dd99245e4422ae9c0dd45e0f99d3"}, + {file = "charset_normalizer-3.5.2-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:7441d755b7ab94f8d4eb3e43ec05482d760842fd263d003a99102d742cd835e2"}, + {file = "charset_normalizer-3.5.2-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:ca403d7e4798f525fdfc78e258820419cbbd0f0ecbab9de7840e3c017cf6b8cf"}, + {file = "charset_normalizer-3.5.2-cp315-cp315-musllinux_1_2_s390x.whl", hash = "sha256:df29a0a7107f7011e77f4eebdddec4c7331e24d787a0b21a46d63bdf7445da95"}, + {file = "charset_normalizer-3.5.2-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:f3c96f633825733f735c5a9cf21d21a257d8e1edf0b1cee0a064b9c424ca0f7d"}, + {file = "charset_normalizer-3.5.2-cp315-cp315-win32.whl", hash = "sha256:281cb91036248400f4cc957495cccd44c275c2e0c5854f7e45ac5cf7dc193847"}, + {file = "charset_normalizer-3.5.2-cp315-cp315-win_amd64.whl", hash = "sha256:89b53f3cda69831909888e0494f4fa0bcd3537e3e138dabeb620bd6ad946bae8"}, + {file = "charset_normalizer-3.5.2-cp315-cp315-win_arm64.whl", hash = "sha256:6be488a102b8cf28d0391d8c4ba7748938ae28b78ad901f8585520fca33ead1a"}, + {file = "charset_normalizer-3.5.2-cp315-cp315t-macosx_10_15_universal2.whl", hash = "sha256:915563965d418f986e7e145accc592eae9e1a1be3566ff98a05d7a9ec42a76e1"}, + {file = "charset_normalizer-3.5.2-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:65cd72beeeca9d3aaea1201e5923859f308f952f9c71de93f06063c79f0f7a3b"}, + {file = "charset_normalizer-3.5.2-cp315-cp315t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:b7fd005a73d9e657273b7a10dc71a9e03c8fb9ee6999798d6918ce095b81ac7f"}, + {file = "charset_normalizer-3.5.2-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:e54da4baf05720032d527874d40b65fa4d7e5c6c6a43d0c3adbeffcaf275a2b3"}, + {file = "charset_normalizer-3.5.2-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:124fbf1a8ff966d87ae05bb8bd45a71f966055ed8bba320d0c7cf450bc5f4d0e"}, + {file = "charset_normalizer-3.5.2-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:28b4f0d66fb834ff90f28209ac7bce77868c45d8c93e26f906709d9b7c2e1af9"}, + {file = "charset_normalizer-3.5.2-cp315-cp315t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:58ca3755ee7ff7f59b57789ec9833c9de9ea275405cdd240eda1f193112e398a"}, + {file = "charset_normalizer-3.5.2-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:443eae2bf318abeaf6f15d785138f71fd6de770e99a92158b8b814265e079115"}, + {file = "charset_normalizer-3.5.2-cp315-cp315t-musllinux_1_2_armv7l.whl", hash = "sha256:58f361dcbab699cf8f42db3f47c8e7fd1036f138c23a5d08de9fde5f425a730c"}, + {file = "charset_normalizer-3.5.2-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:1b4cbc7c3491ccb4aa17fcd8165649d01cf39f76de1696da8631b5f71b85401d"}, + {file = "charset_normalizer-3.5.2-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:ba0b1d2620edf869789c3879223f52bf2afc5d31b3cb47cc57b3a12c05e2aa9d"}, + {file = "charset_normalizer-3.5.2-cp315-cp315t-musllinux_1_2_s390x.whl", hash = "sha256:5e2b6b57e9733d39f0c9fd3185efa6b8e29652c4cd8fe94180272cf6ed9a78c4"}, + {file = "charset_normalizer-3.5.2-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:51cf45226a9b588d0d2b4880c62d686934b63ab0bd79ca23ab0e9762eb27441b"}, + {file = "charset_normalizer-3.5.2-cp315-cp315t-win32.whl", hash = "sha256:5fb29fb8cd1a46c27a1bf9613ad5ec2599310d46b4025d9556404a6b6a292800"}, + {file = "charset_normalizer-3.5.2-cp315-cp315t-win_amd64.whl", hash = "sha256:a192e2c40070d92c3ccf777e3a5c4ff515573cd2bb7ed0c537fdadbbec5bbf21"}, + {file = "charset_normalizer-3.5.2-cp315-cp315t-win_arm64.whl", hash = "sha256:749e97e1b32313717a565abbe321bc2190bc8b35f1a67e4cdbc7c56c8d8ffe58"}, + {file = "charset_normalizer-3.5.2-cp37-abi3-macosx_10_9_universal2.whl", hash = "sha256:4275811936e2f06feff5e598fb42a1b7ae852da8e39605211892b56b81a34efd"}, + {file = "charset_normalizer-3.5.2-cp37-abi3-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:1c50fe28bbc2ced33386f298650d91218076c05420e6cbd790b913adc41659e7"}, + {file = "charset_normalizer-3.5.2-cp37-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d19fbd981a488e22cd04883659ca6b08f50b5974f9fd7c95655ef6a043e5893f"}, + {file = "charset_normalizer-3.5.2-cp37-abi3-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:0fed1d06615f022ee3b13caf5e8b180cfea32bb2c5aded8a9d44277afc040f93"}, + {file = "charset_normalizer-3.5.2-cp37-abi3-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:838dcc90063569a0448120554591a1d6c4a4ffe11babf048908793154ab86ade"}, + {file = "charset_normalizer-3.5.2-cp37-abi3-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2ce45c6627b22c47e390bc91a41c3d13032192e699fa0bea96e9671b373d69b0"}, + {file = "charset_normalizer-3.5.2-cp37-abi3-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0774bf9bf620249fee3e0b8b9fd3065de213be30f3aa94ce2494b3b638949e26"}, + {file = "charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:1db38f4c5496827c1a501846d64d14c3b80c7e6714e406cd7dc36a9899fa1011"}, + {file = "charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:304d8e4d493af723536393eee0c689eb7813f4a474c8b479dee63f1fdd98f621"}, + {file = "charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_ppc64le.whl", hash = "sha256:9b7f416ff0978e2f2249330527f0ad6fa02f4932e6199692d3b52da2048c19e4"}, + {file = "charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_riscv64.whl", hash = "sha256:01077390b03f7988f11d700a2194e69b119741a86b1a638b1db88891e3eced8e"}, + {file = "charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_s390x.whl", hash = "sha256:7e841fb9010836c992c9f12fcbd43a831de93a5f726fc1ccd8ca1d0268c5014c"}, + {file = "charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:9cae88599c7219005d879f98e5ed53341e9a122af585e1091200358a3003d2a0"}, + {file = "charset_normalizer-3.5.2-cp37-abi3-win32.whl", hash = "sha256:01b0c0d2262a9e28e8484a278c7e1b5d650e3ac8cf2683d2967e25899f208bdf"}, + {file = "charset_normalizer-3.5.2-cp37-abi3-win_amd64.whl", hash = "sha256:9f56f72050826f63dcee7a7f55b0a77168cb3bfc553fd405e7f8f9ece75a4036"}, + {file = "charset_normalizer-3.5.2-cp37-abi3-win_arm64.whl", hash = "sha256:40ab6bffa02ae10a0581e6c198be7d2d8ca5c2a0c64e4ed3465d766df457573e"}, + {file = "charset_normalizer-3.5.2-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:75a3ceed0724d625d64b86ca20aba182e4df462e04c2414fc941c0f523f06aac"}, + {file = "charset_normalizer-3.5.2-cp39-cp39-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0891b9d3903c5571c03771ca669a4b0ec5618ca722a5c957d3d29cd4e5062848"}, + {file = "charset_normalizer-3.5.2-cp39-cp39-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:fc14a032f813bf5fe624d991960ea83e9715adc27e4c1830a2361eb1d02ac341"}, + {file = "charset_normalizer-3.5.2-cp39-cp39-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:8b2bfab86aa71ae13aa41a6a26aab338e0db2b8bc75434b05aea89e011ff35a4"}, + {file = "charset_normalizer-3.5.2-cp39-cp39-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:9bde855991b7e362c146535e3136a50bfaffc0487d38b33ca7e5edefc6e23849"}, + {file = "charset_normalizer-3.5.2-cp39-cp39-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:55ea99acb17b9325618de155a0cd6a2e8f5d10be008113e1d433bbb58db543b2"}, + {file = "charset_normalizer-3.5.2-cp39-cp39-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:68eb192d85ab8e5f6ec69c2bc6ac0179fbf04a5ac1569d12fbef74883fe102d0"}, + {file = "charset_normalizer-3.5.2-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:d913de495d90407cd859d263bee2e5d1a4ed3eb6573c04e70d9ec619a7cbed7f"}, + {file = "charset_normalizer-3.5.2-cp39-cp39-musllinux_1_2_armv7l.whl", hash = "sha256:3ddacd27458c45bdacd6bd6db644bfb730efbf9e830310186e3045c9c5be8fb2"}, + {file = "charset_normalizer-3.5.2-cp39-cp39-musllinux_1_2_ppc64le.whl", hash = "sha256:588461c2e8384d309bd63e5826019b6977bc66d629b99ac8737bb795d7b2cb5a"}, + {file = "charset_normalizer-3.5.2-cp39-cp39-musllinux_1_2_riscv64.whl", hash = "sha256:e80e6c2f55656b4824d72065abb4ddd6a525c74bd78a0aab5d9fc2cf4fb5af50"}, + {file = "charset_normalizer-3.5.2-cp39-cp39-musllinux_1_2_s390x.whl", hash = "sha256:d4a7319f304a774bed22115bc891618e45f85065ab44ea6acd07d274e750519a"}, + {file = "charset_normalizer-3.5.2-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:fd1fbe0f116b6e55da77aca2c6ddcddcfac2186cbf78bdebf40fc156efca389d"}, + {file = "charset_normalizer-3.5.2-cp39-cp39-win32.whl", hash = "sha256:93223adc95033dd47133a46ccfc316a0139176fd79085762e27202ec56018f03"}, + {file = "charset_normalizer-3.5.2-cp39-cp39-win_amd64.whl", hash = "sha256:15bb4005af6320d259dc7593ca84a38d7fe06a421dbcf7b910ae23979101e787"}, + {file = "charset_normalizer-3.5.2-cp39-cp39-win_arm64.whl", hash = "sha256:2cc961b171b3f3440f410489ab3573e86aea8736134ebbb40ea1338b7f0831bc"}, + {file = "charset_normalizer-3.5.2-py3-none-any.whl", hash = "sha256:b6b751274acb69d77b3323d6b7dbaa3c7fdfc1eb829b7eb61d262f32e1af9685"}, + {file = "charset_normalizer-3.5.2.tar.gz", hash = "sha256:39de2a259fc954455c57274dc94c79d5842774e1247a016aff30bc0efed0f4ef"}, +] + [[package]] name = "click" version = "8.5.0" @@ -825,6 +1007,24 @@ files = [ {file = "frozenlist-1.8.0.tar.gz", hash = "sha256:3ede829ed8d842f6cd48fc7081d7a41001a56f1f38603f9d49bf3020d59a31ad"}, ] +[[package]] +name = "googleapis-common-protos" +version = "1.76.0" +description = "Common protobufs used in Google APIs" +optional = false +python-versions = ">=3.10" +groups = ["main"] +files = [ + {file = "googleapis_common_protos-1.76.0-py3-none-any.whl", hash = "sha256:59e13344a9f3651aa201a03e2bee815a3bf43a4baf1f9ff8a9b62a840ce25fac"}, + {file = "googleapis_common_protos-1.76.0.tar.gz", hash = "sha256:71db0e44a1d4c2dd024ebad44ca67129cc1e2892e4861df466764749d5ef8642"}, +] + +[package.dependencies] +protobuf = ">=6.33.5,<8.0.0" + +[package.extras] +grpc = ["grpcio (>=1.59.0,<2.0.0)"] + [[package]] name = "h11" version = "0.16.0" @@ -1125,19 +1325,150 @@ files = [ [[package]] name = "opentelemetry-api" -version = "1.45.0" +version = "1.45.2" description = "OpenTelemetry Python API" optional = false python-versions = ">=3.10" groups = ["main"] files = [ - {file = "opentelemetry_api-1.45.0-py3-none-any.whl", hash = "sha256:80e068aba7cd56c8b58512d6a36f8d25cb1dfaa0c0a4cc1c938ccf9f362d9cb3"}, - {file = "opentelemetry_api-1.45.0.tar.gz", hash = "sha256:711ede81773c8025c2c03dac0450bc89f3d30aea6eabcc815c570d4e35a963f7"}, + {file = "opentelemetry_api-1.45.2-py3-none-any.whl", hash = "sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34"}, + {file = "opentelemetry_api-1.45.2.tar.gz", hash = "sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4"}, ] [package.dependencies] typing-extensions = ">=4.5.0" +[[package]] +name = "opentelemetry-exporter-http-transport" +version = "0.66b2" +description = "OpenTelemetry Exporters HTTP transport" +optional = false +python-versions = ">=3.10" +groups = ["main"] +files = [ + {file = "opentelemetry_exporter_http_transport-0.66b2-py3-none-any.whl", hash = "sha256:fd5f5b490c099acda1cd7b909d5e8981436bf18cc8c6098d302d114c271720e9"}, + {file = "opentelemetry_exporter_http_transport-0.66b2.tar.gz", hash = "sha256:66d6ed810a515432c8891da9a834464332fd70badeca45bdeeae81b4280c903b"}, +] + +[package.dependencies] +opentelemetry-api = ">=1.15,<2.0" +requests = {version = ">=2.25,<3.0", optional = true, markers = "extra == \"requests\""} + +[package.extras] +requests = ["requests (>=2.25,<3.0)"] +urllib3 = ["urllib3 (>=1.26)"] + +[[package]] +name = "opentelemetry-exporter-otlp-common" +version = "0.66b2" +description = "OpenTelemetry OTLP HTTP export utilities" +optional = false +python-versions = ">=3.10" +groups = ["main"] +files = [ + {file = "opentelemetry_exporter_otlp_common-0.66b2-py3-none-any.whl", hash = "sha256:ace86efb75489f925f1ef809856ae5f0c7db534e4afdc624530222228b1236a5"}, + {file = "opentelemetry_exporter_otlp_common-0.66b2.tar.gz", hash = "sha256:06f5a9b88638e310efa1f1d206cdf6b75393e112aba4e174a963416192bd1028"}, +] + +[package.dependencies] +opentelemetry-sdk = ">=1.45.2,<1.46.0" + +[package.extras] +http = ["opentelemetry-exporter-http-transport (==0.66b2)"] + +[[package]] +name = "opentelemetry-exporter-otlp-proto-common" +version = "1.45.2" +description = "OpenTelemetry Protobuf encoding" +optional = false +python-versions = ">=3.10" +groups = ["main"] +files = [ + {file = "opentelemetry_exporter_otlp_proto_common-1.45.2-py3-none-any.whl", hash = "sha256:af483b24217028892f017096731b794b196b785025d2e6808874720fd0b05a80"}, + {file = "opentelemetry_exporter_otlp_proto_common-1.45.2.tar.gz", hash = "sha256:f1f2806f3f28ce7938033823e50934fcd91595a39de38e69a28a51e19f40fc6d"}, +] + +[package.dependencies] +opentelemetry-proto = "1.45.2" + +[[package]] +name = "opentelemetry-exporter-otlp-proto-http" +version = "1.45.2" +description = "OpenTelemetry Collector Protobuf over HTTP Exporter" +optional = false +python-versions = ">=3.10" +groups = ["main"] +files = [ + {file = "opentelemetry_exporter_otlp_proto_http-1.45.2-py3-none-any.whl", hash = "sha256:6e4d025138829d0ee57946930c2ccad6491ad4d92a958e9c7eea69278fe60cfc"}, + {file = "opentelemetry_exporter_otlp_proto_http-1.45.2.tar.gz", hash = "sha256:5984a3fb46bc4628e4e2b85d4a6e72637e03962aae6cf372791137768a4ad939"}, +] + +[package.dependencies] +googleapis-common-protos = ">=1.52,<2.0" +opentelemetry-api = ">=1.15,<2.0" +opentelemetry-exporter-http-transport = {version = "0.66b2", extras = ["requests"]} +opentelemetry-exporter-otlp-common = "0.66b2" +opentelemetry-exporter-otlp-proto-common = "1.45.2" +opentelemetry-proto = "1.45.2" +opentelemetry-sdk = ">=1.45.2,<1.46.0" +requests = ">=2.7,<3.0" +typing-extensions = ">=4.5.0" + +[package.extras] +gcp-auth = ["opentelemetry-exporter-credential-provider-gcp (>=0.59b0)"] +requests = ["opentelemetry-exporter-http-transport[requests] (==0.66b2)", "requests (>=2.7,<3.0)"] + +[[package]] +name = "opentelemetry-proto" +version = "1.45.2" +description = "OpenTelemetry Python Proto" +optional = false +python-versions = ">=3.10" +groups = ["main"] +files = [ + {file = "opentelemetry_proto-1.45.2-py3-none-any.whl", hash = "sha256:03a7ca1b43f89fd5b965d5975902bb2515c0c86e2428b456836e9a6149c6235a"}, + {file = "opentelemetry_proto-1.45.2.tar.gz", hash = "sha256:bd8d23cf770605b0af9b7be2071d26a464fea289d35429abfd2a66226114ad64"}, +] + +[package.dependencies] +protobuf = ">=5.0,<8.0" + +[[package]] +name = "opentelemetry-sdk" +version = "1.45.2" +description = "OpenTelemetry Python SDK" +optional = false +python-versions = ">=3.10" +groups = ["main"] +files = [ + {file = "opentelemetry_sdk-1.45.2-py3-none-any.whl", hash = "sha256:ff974ea70ee4f1d51e2ec152db37c2b626c7bf82bb3f7d86114fd8704e7199c6"}, + {file = "opentelemetry_sdk-1.45.2.tar.gz", hash = "sha256:7eec4de13dd21ff3a1670dcb0e02079e692736f94d733dfdce5af461d884248d"}, +] + +[package.dependencies] +opentelemetry-api = "1.45.2" +opentelemetry-semantic-conventions = "0.66b2" +typing-extensions = ">=4.5.0" + +[package.extras] +file-configuration = ["opentelemetry-configuration (==0.66b2)"] + +[[package]] +name = "opentelemetry-semantic-conventions" +version = "0.66b2" +description = "OpenTelemetry Semantic Conventions" +optional = false +python-versions = ">=3.10" +groups = ["main"] +files = [ + {file = "opentelemetry_semantic_conventions-0.66b2-py3-none-any.whl", hash = "sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8"}, + {file = "opentelemetry_semantic_conventions-0.66b2.tar.gz", hash = "sha256:7da5f1a5dc4383eb66711d4d3d3e71824d9403ac1559fea021cc103c1a4c4976"}, +] + +[package.dependencies] +opentelemetry-api = "1.45.2" +typing-extensions = ">=4.5.0" + [[package]] name = "packaging" version = "26.3" @@ -1435,6 +1766,24 @@ files = [ {file = "propcache-0.5.4.tar.gz", hash = "sha256:ff6b113f50bc066a698db5d944d2c6dc7507168dd3341e255a8892fd0715a558"}, ] +[[package]] +name = "protobuf" +version = "7.36.2" +description = "" +optional = false +python-versions = ">=3.10" +groups = ["main"] +files = [ + {file = "protobuf-7.36.2-cp310-abi3-macosx_10_9_universal2.whl", hash = "sha256:cbc70b17ee27e28894c7fee8bb04be1abead49e936bc70eb60052531eee2079e"}, + {file = "protobuf-7.36.2-cp310-abi3-manylinux2014_aarch64.whl", hash = "sha256:e11e1f0180583a2af89db6a2ecd9e8dc40aa6d2988ca175bfd0e6d12ea72d74e"}, + {file = "protobuf-7.36.2-cp310-abi3-manylinux2014_s390x.whl", hash = "sha256:f4fee11ec330d238b34a05c9b675f693c20415d1c5bd7d5320cc2f8a798eb9cf"}, + {file = "protobuf-7.36.2-cp310-abi3-manylinux2014_x86_64.whl", hash = "sha256:89f23aa53c24553a2416fd4fd1ec06f74fa42b14b546d8883128813f775bbfd2"}, + {file = "protobuf-7.36.2-cp310-abi3-win32.whl", hash = "sha256:912c1221170e16c08d1f086762f563dd61ff83c18b5fa6652952dfaded66f728"}, + {file = "protobuf-7.36.2-cp310-abi3-win_amd64.whl", hash = "sha256:a300819d441e078a5608c0d3c709796bb548136058fda017ae51d425b44fd353"}, + {file = "protobuf-7.36.2-py3-none-any.whl", hash = "sha256:bdb3a345d48db958e6ce1f18e508beb0cc981d64f24088427549c866cd039f1e"}, + {file = "protobuf-7.36.2.tar.gz", hash = "sha256:497d0463ff3316681da6c0b9e8d06cb465d61abce00b613ab42226175644d1bb"}, +] + [[package]] name = "pycparser" version = "3.0" @@ -1672,6 +2021,28 @@ hiredis = ["hiredis (>=3.2.0)"] jwt = ["pyjwt (>=2.9.0)"] ocsp = ["cryptography (>=36.0.1)", "pyopenssl (>=20.0.1)", "requests (>=2.31.0)"] +[[package]] +name = "requests" +version = "2.34.2" +description = "Python HTTP for Humans." +optional = false +python-versions = ">=3.10" +groups = ["main"] +files = [ + {file = "requests-2.34.2-py3-none-any.whl", hash = "sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0"}, + {file = "requests-2.34.2.tar.gz", hash = "sha256:f288924cae4e29463698d6d60bc6a4da69c89185ad1e0bcc4104f584e960b9ed"}, +] + +[package.dependencies] +certifi = ">=2023.5.7" +charset_normalizer = ">=2,<4" +idna = ">=2.5,<4" +urllib3 = ">=1.26,<3" + +[package.extras] +socks = ["PySocks (>=1.5.6,!=1.5.7)"] +use-chardet-on-py3 = ["chardet (>=3.0.2,<8)"] + [[package]] name = "six" version = "1.17.0" @@ -2053,4 +2424,4 @@ propcache = ">=0.2.1" [metadata] lock-version = "2.1" python-versions = ">=3.12,<3.13" -content-hash = "69933c0954709c4398ecd965170999e4a57c4fb1738dac53d799e2741e0db2e8" +content-hash = "5cb889e64fedb82dc81f35765856f870024880ebe1f1ad80db7ec27e5ce71be7" diff --git a/pyproject.toml b/pyproject.toml index 5808d0e7..c064d7f7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,7 +1,7 @@ [tool.poetry] name = "max2" -version = "1.5.0" -description = "Мессенджер с RabbitMQ и асинхронной обработкой изображений, лабораторная 5" +version = "1.6.0" +description = "Мессенджер с OpenTelemetry и Prometheus, Loki и Tempo, лабораторная 6" authors = ["Саватеев Артём"] package-mode = false @@ -18,6 +18,8 @@ argon2-cffi = "25.1.0" aiobotocore = "3.9.1" pillow = "12.3.0" aio-pika = "9.5.8" +opentelemetry-sdk = "1.45.2" +opentelemetry-exporter-otlp-proto-http = "1.45.2" [tool.poetry.group.dev.dependencies] pytest = "9.1.1" diff --git a/scripts/check_observability.py b/scripts/check_observability.py new file mode 100644 index 00000000..6055d7aa --- /dev/null +++ b/scripts/check_observability.py @@ -0,0 +1,428 @@ +#!/usr/bin/env python3 +"""Проверка сигналов и отказов на локальном учебном Compose-стенде.""" + +import argparse +import hashlib +import json +import re +import subprocess +import sys +import time +import uuid +from concurrent.futures import ThreadPoolExecutor +from contextlib import contextmanager +from pathlib import Path +from urllib.error import HTTPError, URLError +from urllib.parse import urlencode +from urllib.request import urlopen + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tests")) +from client import Client, Failure, check, run + +BACKLOG_ALERT = "MessengerQueueLag" +ERROR_ALERT = "MessengerHighErrorRate" +UPLOAD_ROUTE = "/api/v1/chats/{chat_id}/attachments" + + +def compose(*args, stdin=None): + subprocess.run( + ["docker", "compose", "-p", "messenger-lab6", *args], + cwd=ROOT, + input=stdin, + text=True, + check=True, + timeout=90, + stdout=sys.stderr, + ) + + +def sql(statement): + compose( + "exec", + "-T", + "postgres", + "sh", + "-c", + 'psql -X -q -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$POSTGRES_DB"', + stdin=statement, + ) + + +@contextmanager +def stopped(*services): + compose("stop", *services) + try: + yield + finally: + compose("start", *services) + + +def eventually(label, predicate, timeout=60): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + try: + result = predicate() + if result: + return result + except (URLError, TimeoutError, Failure): + pass + time.sleep(1) + raise Failure(label) + + +class Observations: + def __init__(self, grafana): + self.grafana = grafana.rstrip("/") + + def get(self, path, **params): + url = self.grafana + path + ("?" + urlencode(params) if params else "") + with urlopen(url, timeout=5) as response: + return json.load(response) + + def ready(self, datasource): + url = self.grafana + f"/api/datasources/proxy/uid/{datasource}/ready" + with urlopen(url, timeout=5) as response: + return response.status == 200 + + def query(self, expression): + data = self.get( + "/api/datasources/proxy/uid/prometheus/api/v1/query", query=expression + ) + return data["data"]["result"] + + def value(self, expression): + rows = self.query(expression) + return float(rows[0]["value"][1]) if rows else 0.0 + + def firing(self, name): + alerts = self.get("/api/datasources/proxy/uid/prometheus/api/v1/alerts")[ + "data" + ]["alerts"] + return any( + alert["labels"]["alertname"] == name and alert["state"] == "firing" + for alert in alerts + ) + + def trace(self, trace_id): + try: + data = self.get("/api/datasources/proxy/uid/tempo/api/traces/" + trace_id) + except HTTPError as error: + if error.code == 404: + return [] + raise + return [ + (span, attributes(batch["resource"]).get("service.name")) + for batch in data.get("batches", data.get("resourceSpans", [])) + for scope in batch["scopeSpans"] + for span in scope["spans"] + ] + + def logs(self, service, trace_id): + data = self.get( + "/api/datasources/proxy/uid/loki/loki/api/v1/query_range", + query=f'{{service_name="{service}"}} | trace_id="{trace_id}"', + limit=50, + ) + return data["data"]["result"] + + +def attributes(entity): + return { + item["key"]: next(iter(item["value"].values())) + for item in entity.get("attributes", []) + } + + +def upload(client, actor, chat): + body = (ROOT / "tests/fixtures/sample.png").read_bytes() + name = "private-filename-" + uuid.uuid4().hex + ".png" + response = client.call( + "POST", + f"/api/v1/chats/{chat['id']}/attachments?filename={name}", + 202, + actor=actor, + raw=body, + headers={"Content-Type": "image/png"}, + schema="Attachment", + ) + check(response["json"]["status"] == "queued", "upload did not return queued") + trace_id = response["headers"].get("X-Trace-Id", "") + check(bool(re.fullmatch(r"[0-9a-f]{32}", trace_id)), "missing trace ID") + return response["json"], trace_id, response["headers"]["X-Request-Id"], name + + +def chain(obs, trace_id, attempts): + def lookup(): + spans = obs.trace(trace_id) + producer = { + int(attributes(span)["job.attempt"]): span + for span, service in spans + if service == "messenger-dispatcher" and span["name"] == "rabbitmq.publish" + } + consumer = { + int(attributes(span)["job.attempt"]): span + for span, service in spans + if service == "messenger-worker" and span["name"] == "rabbitmq.consume" + } + names = {span["name"] for span, _ in spans} + if not ( + {f"POST {UPLOAD_ROUTE}", "s3.put", "postgres.complete"} <= names + and attempts <= producer.keys() + and attempts <= consumer.keys() + ): + return None + for attempt in attempts: + check( + consumer[attempt]["parentSpanId"] == producer[attempt]["spanId"], + "consumer parent mismatch", + ) + return spans + + return eventually("trace lacks upload, RabbitMQ, S3 or committed result", lookup) + + +def verify_signals(client, obs, alice, chat): + attachment, trace_id, request_id, filename = upload(client, alice, chat) + ready = client.wait_ready(alice, attachment) + check(len(ready["variants"]) == 3, "missing image variants") + spans = chain(obs, trace_id, {1}) + api_logs = eventually( + "API log missing", lambda: obs.logs("messenger-api", trace_id) + ) + worker_logs = eventually( + "worker log missing", lambda: obs.logs("messenger-worker", trace_id) + ) + exported = json.dumps([spans, api_logs, worker_logs]) + check(request_id in exported, "request ID absent") + check( + alice["token"] not in exported + and alice["registration"]["password"] not in exported + and filename not in exported, + "private data exported", + ) + metrics = [ + "messenger_http_requests_total", + "messenger_http_duration_seconds_bucket", + "messenger_jobs_total", + "messenger_job_duration_seconds_bucket", + "messenger_attachment_ready_duration_seconds_bucket", + "messenger_queue_depth", + "messenger_queue_oldest_age_seconds", + "messenger_outbox_pending", + "messenger_db_pool", + "messenger_worker_busy", + "messenger_worker_capacity", + "messenger_process_cpu_seconds_total", + "messenger_process_memory_bytes", + "messenger_container_cpu_seconds_total", + "messenger_container_memory_bytes", + "messenger:http_availability:15m", + ] + eventually( + "missing Prometheus series", + lambda: all(obs.query(metric) for metric in metrics), + ) + disallowed = { + "request_id", + "user_id", + "chat_id", + "message_id", + "attachment_id", + "filename", + "url", + } + check( + not any( + disallowed & row["metric"].keys() + for metric in metrics + for row in obs.query(metric) + ), + "unexpected metric labels", + ) + dashboard = obs.get("/api/dashboards/uid/messenger-lab6")["dashboard"] + check( + dashboard["uid"] == "messenger-lab6" and len(dashboard["panels"]) >= 16, + "dashboard not provisioned", + ) + print( + f"SIGNALS trace={trace_id} request_id={request_id} spans={len(spans)} " + f"metrics={len(metrics)} panels={len(dashboard['panels'])}", + flush=True, + ) + return trace_id + + +def verify_queue(client, obs, alice, chat): + with stopped("worker"): + attachment, trace_id, _, _ = upload(client, alice, chat) + client.message(alice, chat, "Контроль очереди", attachments=[attachment["id"]]) + client.call( + "GET", f"/api/v1/attachments/{attachment['id']}/content", 409, actor=alice + ) + eventually("queue alert did not fire", lambda: obs.firing(BACKLOG_ALERT)) + depth = obs.value("max(messenger_queue_depth)") + age = obs.value("max(messenger_queue_oldest_age_seconds)") + check(depth >= 1 and age > 10, "queue metrics did not show backlog") + trigger = "lab6_retry_" + uuid.uuid4().hex + sql(f"""CREATE FUNCTION {trigger}() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN IF NEW.id = '{attachment["id"]}' AND NEW.status = 'ready' + THEN RAISE EXCEPTION 'lab6 retry verification'; END IF; RETURN NEW; END; $$; + CREATE TRIGGER {trigger} BEFORE UPDATE ON attachments FOR EACH ROW + EXECUTE FUNCTION {trigger}();""") + try: + eventually( + "retry was not exported", + lambda: any( + attributes(span).get("job.outcome") == "retry" + for span, _ in obs.trace(trace_id) + ), + ) + finally: + sql( + f"DROP TRIGGER IF EXISTS {trigger} ON attachments; DROP FUNCTION IF EXISTS {trigger}();" + ) + ready = client.wait_ready(alice, attachment) + chain(obs, trace_id, {1, 2}) + downloaded = client.call( + "GET", f"/api/v1/attachments/{ready['id']}/content", actor=alice + )["bytes"] + check(hashlib.sha256(downloaded).hexdigest() == ready["sha256"], "original changed") + eventually( + "queue did not drain or alert still firing", + lambda: obs.value("max(messenger_queue_depth)") == 0 + and not obs.firing(BACKLOG_ALERT), + ) + print( + f"QUEUE firing → resolved; depth={depth:g} oldest={age:.1f}s trace={trace_id} retry linked", + flush=True, + ) + + +def verify_database(client, obs, alice, chat): + with stopped("postgres"): + first_failed = None + started = time.monotonic() + failures = 0 + while time.monotonic() - started < 35: + response = client.call( + "POST", + f"/api/v1/chats/{chat['id']}/messages", + 503, + actor=alice, + body={"text": "Контроль отказа"}, + headers={"Idempotency-Key": uuid.uuid4().hex}, + ) + first_failed = first_failed or response["headers"]["X-Trace-Id"] + failures += 1 + if obs.firing(ERROR_ALERT): + break + time.sleep(0.25) + check(obs.firing(ERROR_ALERT), "5xx alert did not fire") + error_ratio = obs.value("messenger:http_error_ratio:30s") + spans = eventually( + "PostgreSQL failure span missing", + lambda: [ + span + for span, _ in obs.trace(first_failed) + if span["name"].startswith("postgres.") + and attributes(span).get("error.type") + ], + ) + logs = eventually( + "PostgreSQL error log missing", + lambda: obs.logs("messenger-api", first_failed), + ) + check( + "postgres.unavailable" in json.dumps(logs), + "trace and DB error log not linked", + ) + eventually( + "PostgreSQL did not recover", + lambda: client.call("GET", "/health/ready", schema="Health"), + ) + client.message(alice, chat, "PostgreSQL восстановлен") + eventually("5xx alert still firing", lambda: not obs.firing(ERROR_ALERT)) + print( + f"DB firing → resolved; 503={failures} ratio={error_ratio:.1%} " + f"trace={first_failed} failed_span={spans[0]['name']}", + flush=True, + ) + + +def verify_storage(client, obs, alice, chat, previous_trace): + metrics = 'sum({__name__=~"otelcol_exporter_(send|enqueue)_failed_(log_records|spans)_total"})' + before = eventually( + "Prometheus counters unavailable", lambda: (obs.value(metrics),) + )[0] + with stopped("loki", "tempo"): + deadline = time.monotonic() + 18 + successes = 0 + with ThreadPoolExecutor(max_workers=3) as pool: + while time.monotonic() < deadline: + successes += sum( + pool.map( + lambda _: client.message(alice, chat, "Контроль экспорта")[ + "status" + ] + == 201, + range(6), + ) + ) + time.sleep(0.2) + # Counters increase after a batch exhausts its retry budget. + lost = eventually( + "collector drop counters did not increase", + lambda: max(0, obs.value(metrics) - before), + ) + rss = eventually( + "Collector RSS missing", + lambda: obs.value( + "max(max_over_time(otelcol_process_memory_rss_bytes[1m]))" + ), + ) + check( + 0 < rss < 256 * 1024 * 1024, "collector RSS not observed below cgroup limit" + ) + check( + successes >= 30, + "not enough successful business requests during telemetry outage", + ) + eventually("Loki/Tempo not ready", lambda: obs.ready("loki") and obs.ready("tempo")) + eventually( + "collector queues did not drain", + lambda: bool(obs.query("otelcol_exporter_queue_size")) + and obs.value("sum(otelcol_exporter_queue_size)") == 0, + ) + check(obs.logs("messenger-api", previous_trace), "Loki history lost on restart") + check(obs.trace(previous_trace), "Tempo history lost on restart") + _, trace_id, _, _ = upload(client, alice, chat) + eventually( + "Loki did not resume ingest", lambda: obs.logs("messenger-api", trace_id) + ) + eventually("Tempo did not resume ingest", lambda: obs.trace(trace_id)) + print( + f"STORAGE successful writes={successes} dropped logs/spans={lost:g} " + f"peak collector RSS={rss / 1024**2:.1f} MiB; history preserved and new signals ingested", + flush=True, + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--base-url", required=True) + parser.add_argument("--grafana-url", required=True) + parser.add_argument("--incidents", action="store_true") + args = parser.parse_args() + client = Client(args.base_url) + obs = Observations(args.grafana_url) + alice, _, _, chat = client.bootstrap() + trace_id = verify_signals(client, obs, alice, chat) + if args.incidents: + verify_queue(client, obs, alice, chat) + verify_database(client, obs, alice, chat) + verify_storage(client, obs, alice, chat, trace_id) + + +if __name__ == "__main__": + run(main) diff --git a/scripts/init-secrets.sh b/scripts/init-secrets.sh index 5b83185d..6f1a4724 100755 --- a/scripts/init-secrets.sh +++ b/scripts/init-secrets.sh @@ -86,3 +86,5 @@ PYTHON echo "created secrets/broker_url" fi chmod 644 secrets/broker_url + +secret grafana_admin_password 32 diff --git a/src/application/api/middlewares/request_context.py b/src/application/api/middlewares/request_context.py index 389a95be..11ceac00 100644 --- a/src/application/api/middlewares/request_context.py +++ b/src/application/api/middlewares/request_context.py @@ -5,6 +5,7 @@ import uuid from fastapi import Request, Response from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint +from application.api.middlewares.telemetry import normalize_method, route_template from application.api.utils import INSTANCE_ID_HEADER, REQUEST_ID_HEADER, error_response from config import INSTANCE_ID, LOGGER from domain.errors import AppError @@ -34,7 +35,9 @@ class RequestContextMiddleware(BaseHTTPMiddleware): try: response = await call_next(request) except Exception: - LOGGER.exception(f"Необработанная ошибка | request_id={request_id}") + LOGGER.bind(event="http.unhandled", request_id=request_id).error( + "Необработанная ошибка" + ) error = AppError() response = error_response( request_id, error.status_code, error.code, error.message @@ -64,8 +67,10 @@ class RequestContextMiddleware(BaseHTTPMiddleware): level = "DEBUG" else: level = "INFO" - LOGGER.log( - level, - f"{request.method} {request.url.path} -> {response.status_code} " - f"| {duration_ms:.1f} ms | request_id={request_id}", - ) + LOGGER.bind( + event="http.response", + request_id=request_id, + method=normalize_method(request.method), + route=route_template(request.scope), + status_code=response.status_code, + ).log(level, f"HTTP {response.status_code} за {duration_ms:.1f} мс") diff --git a/src/application/api/middlewares/telemetry.py b/src/application/api/middlewares/telemetry.py new file mode 100644 index 00000000..4905ab2a --- /dev/null +++ b/src/application/api/middlewares/telemetry.py @@ -0,0 +1,81 @@ +import time + +from opentelemetry import trace +from opentelemetry.trace import SpanKind, Status, StatusCode + +from infrastructure.observability import telemetry + +BUSINESS_PREFIX = "/api/v1" + +KNOWN_METHODS = frozenset({"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"}) + + +def route_template(scope): + route = scope.get("route") + path = getattr(route, "path", None) + if path is None: + return "unmatched" + if scope["path"].startswith(BUSINESS_PREFIX + "/") and not path.startswith( + BUSINESS_PREFIX + "/" + ): + return BUSINESS_PREFIX + path + return path + + +def normalize_method(method): + return method if method in KNOWN_METHODS else "OTHER" + + +class TelemetryMiddleware: + """Только бизнес-HTTP: route template, полный ASGI response, без URL/headers/body.""" + + def __init__(self, app): + self.app = app + + async def __call__(self, scope, receive, send): + if scope["type"] != "http" or not scope["path"].startswith( + BUSINESS_PREFIX + "/" + ): + await self.app(scope, receive, send) + return + headers = { + key.decode("latin1"): value.decode("latin1") + for key, value in scope["headers"] + if key in {b"traceparent", b"tracestate"} + } + method = normalize_method(scope["method"]) + started, status = time.perf_counter(), 500 + with telemetry.span( + "HTTP", + {"http.request.method": method}, + kind=SpanKind.SERVER, + context=telemetry.extract(headers), + root=True, + ) as span: + + async def send_wrapper(message): + nonlocal status + if message["type"] == "http.response.start": + status = message["status"] + span_context = trace.get_current_span().get_span_context() + if span_context.is_valid: + message.setdefault("headers", []).append( + (b"x-trace-id", f"{span_context.trace_id:032x}".encode()) + ) + await send(message) + + try: + await self.app(scope, receive, send_wrapper) + finally: + route = route_template(scope) + span.update_name(f"{method} {route}") + span.set_attribute("http.route", route) + span.set_attribute("http.response.status_code", status) + request_id = scope.get("state", {}).get("request_id") + if request_id: + span.set_attribute("request_id", request_id) + if status >= 500: + span.set_status(Status(StatusCode.ERROR)) + telemetry.record_http( + time.perf_counter() - started, method, route, status + ) diff --git a/src/config/settings.py b/src/config/settings.py index 78861c0c..0c803bc3 100644 --- a/src/config/settings.py +++ b/src/config/settings.py @@ -86,3 +86,5 @@ JOB_RETRY_MAX_SECONDS = env.float("JOB_RETRY_MAX_SECONDS") IMAGE_PROCESS_MEMORY_MB = env.int("IMAGE_PROCESS_MEMORY_MB") STAGING_RETENTION_SECONDS = env.int("STAGING_RETENTION_SECONDS") OUTBOX_POLL_SECONDS = env.float("OUTBOX_POLL_SECONDS") + +OTEL_SERVICE_NAME = env.str("OTEL_SERVICE_NAME") diff --git a/src/dispatcher.py b/src/dispatcher.py index 33a19918..26e75597 100644 --- a/src/dispatcher.py +++ b/src/dispatcher.py @@ -5,9 +5,12 @@ from pathlib import Path from config import DB_STARTUP_TIMEOUT_SEC, LOGGER from config.settings import BROKER_URL_FILE, OUTBOX_POLL_SECONDS, WORKER_PREFETCH +from domain.errors import UnavailableError from infrastructure import database_pool_manager from infrastructure.broker import RabbitBrokerManager from infrastructure.dependencies.jobs import create_job_repository +from infrastructure.observability import telemetry +from infrastructure.repositories.observability import PostgresObservabilityRepository from infrastructure.utils.faults import crash_once @@ -16,11 +19,23 @@ async def main() -> None: loop = asyncio.get_running_loop() for signum in (signal.SIGTERM, signal.SIGINT): loop.add_signal_handler(signum, stop.set) + telemetry.start(database_pool_manager) await database_pool_manager.create_pool(DB_STARTUP_TIMEOUT_SEC) await database_pool_manager.check_migrations() jobs = create_job_repository() broker = RabbitBrokerManager(BROKER_URL_FILE, WORKER_PREFETCH) failures = 0 + observability = PostgresObservabilityRepository(database_pool_manager) + + async def sample_backlog(): + while not stop.is_set(): + try: + telemetry.queue_stats = await observability.queue_snapshot() + except UnavailableError: + telemetry.queue_stats = None + await asyncio.sleep(2) + + sampler = asyncio.create_task(sample_backlog()) try: while not stop.is_set(): delay = OUTBOX_POLL_SECONDS @@ -44,8 +59,11 @@ async def main() -> None: except TimeoutError: pass finally: + sampler.cancel() + await asyncio.gather(sampler, return_exceptions=True) await broker.close() await database_pool_manager.close() + await asyncio.to_thread(telemetry.shutdown) if __name__ == "__main__": diff --git a/src/gateway.py b/src/gateway.py index f0cf1cb6..14c3a33c 100644 --- a/src/gateway.py +++ b/src/gateway.py @@ -9,6 +9,7 @@ from fastapi import FastAPI from application import api_endpoints, health_endpoints from application.api.handlers import register_exception_handlers from application.api.middlewares import RequestContextMiddleware +from application.api.middlewares.telemetry import TelemetryMiddleware from config import ( APP_ENV, APP_HOST, @@ -33,6 +34,7 @@ from infrastructure import ( database_pool_manager, storage_manager, ) +from infrastructure.observability import telemetry @asynccontextmanager @@ -44,6 +46,7 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]: S3 на старт не влияет: реплика стартует и обслуживает сообщения, а readiness остаётся 503, пока bucket недоступен. """ + telemetry.start(database_pool_manager) await database_pool_manager.create_pool(DB_STARTUP_TIMEOUT_SEC) await database_pool_manager.check_migrations() cache_manager.create_client() @@ -72,17 +75,19 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]: await database_pool_manager.close() password_hasher.close() image_inspector.close() + await asyncio.to_thread(telemetry.shutdown) LOGGER.info(f"Application stopped, instance={INSTANCE_ID}, connections closed") app = FastAPI( title="mtuci-labs-messanger", description="мессенджер-конкурент-максу", - version="1.5.0", + version="1.6.0", lifespan=lifespan, ) app.add_middleware(RequestContextMiddleware) +app.add_middleware(TelemetryMiddleware) register_exception_handlers(app) app.include_router(health_endpoints) diff --git a/src/infrastructure/broker/rabbit.py b/src/infrastructure/broker/rabbit.py index ee43a7ef..c45c6162 100644 --- a/src/infrastructure/broker/rabbit.py +++ b/src/infrastructure/broker/rabbit.py @@ -3,8 +3,10 @@ import asyncio import aio_pika from aio_pika.abc import AbstractRobustConnection from aiormq import spec +from opentelemetry.trace import SpanKind from domain.jobs import JobMessageSchema +from infrastructure.observability import telemetry from infrastructure.security.secrets import read_secret from interfaces.job_repository import JobPublisher @@ -61,26 +63,40 @@ class RabbitBrokerManager(JobPublisher): self.queue = queue async def publish(self, message: JobMessageSchema) -> None: - async with asyncio.timeout(PUBLISH_TIMEOUT_SECONDS): - await self.connect() - confirmation = await self._exchange.publish( - aio_pika.Message( - body=message.model_dump_json(exclude_none=True).encode(), - content_type="application/json", - delivery_mode=aio_pika.DeliveryMode.PERSISTENT, - message_id=str(message.job_id), - type=message.type, - headers={ - "pipeline_version": message.pipeline_version, - "attempt": message.attempt, - }, - ), - routing_key=ROUTING_KEY, - mandatory=True, - timeout=PUBLISH_TIMEOUT_SECONDS, - ) - if not isinstance(confirmation, spec.Basic.Ack): - raise ConnectionError("RabbitMQ не подтвердил публикацию") + with telemetry.span( + "rabbitmq.publish", + { + "messaging.system": "rabbitmq", + "messaging.destination.name": QUEUE, + "messaging.operation.type": "send", + "job.attempt": message.attempt, + }, + kind=SpanKind.PRODUCER, + context=telemetry.extract(message.model_dump()), + root=True, + ): + async with asyncio.timeout(PUBLISH_TIMEOUT_SECONDS): + await self.connect() + confirmation = await self._exchange.publish( + aio_pika.Message( + body=message.model_copy(update=telemetry.inject()) + .model_dump_json(exclude_none=True) + .encode(), + content_type="application/json", + delivery_mode=aio_pika.DeliveryMode.PERSISTENT, + message_id=str(message.job_id), + type=message.type, + headers={ + "pipeline_version": message.pipeline_version, + "attempt": message.attempt, + }, + ), + routing_key=ROUTING_KEY, + mandatory=True, + timeout=PUBLISH_TIMEOUT_SECONDS, + ) + if not isinstance(confirmation, spec.Basic.Ack): + raise ConnectionError("RabbitMQ не подтвердил публикацию") async def close(self) -> None: connection = self._connection diff --git a/src/infrastructure/dependencies/database.py b/src/infrastructure/dependencies/database.py index 3b22ea03..ccff3977 100644 --- a/src/infrastructure/dependencies/database.py +++ b/src/infrastructure/dependencies/database.py @@ -19,6 +19,7 @@ from config import ( DB_USER, LOGGER, ) +from infrastructure.observability import telemetry from infrastructure.utils import DATABASE_UNAVAILABLE_ERRORS MIGRATIONS_DIR = Path(__file__).resolve().parents[3] / "migrations" @@ -61,6 +62,7 @@ class DatabasePoolManager: self.connect_timeout = connect_timeout self.command_timeout = command_timeout self.pool: asyncpg.Pool | None = None + self.waiting = 0 async def create_pool(self, startup_timeout: float) -> asyncpg.Pool: """ @@ -196,8 +198,18 @@ class DatabasePoolManager: """ assert self.pool is not None try: - async with self.pool.acquire(timeout=self.connect_timeout) as connection: + self.waiting += 1 + try: + with telemetry.span( + "postgres.pool.acquire", {"db.system.name": "postgresql"} + ): + connection = await self.pool.acquire(timeout=self.connect_timeout) + finally: + self.waiting -= 1 + try: yield connection + finally: + await self.pool.release(connection) except BROKEN_CONNECTION_ERRORS: await self.pool.expire_connections() raise diff --git a/src/infrastructure/observability/__init__.py b/src/infrastructure/observability/__init__.py new file mode 100644 index 00000000..d8663df9 --- /dev/null +++ b/src/infrastructure/observability/__init__.py @@ -0,0 +1,3 @@ +from .manager import telemetry + +__all__ = ["telemetry"] diff --git a/src/infrastructure/observability/manager.py b/src/infrastructure/observability/manager.py new file mode 100644 index 00000000..f01450ef --- /dev/null +++ b/src/infrastructure/observability/manager.py @@ -0,0 +1,318 @@ +"""OpenTelemetry SDK: три OTLP-сигнала, ограниченные очереди и безопасные атрибуты.""" + +import os +import time +from contextlib import contextmanager, nullcontext +from pathlib import Path + +from opentelemetry import metrics, trace +from opentelemetry._logs import LogRecord, SeverityNumber +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.metrics import Observation +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.metrics.view import ExplicitBucketHistogramAggregation, View +from opentelemetry.sdk.resources import Resource +from opentelemetry.sdk.trace import TracerProvider +from opentelemetry.sdk.trace.export import BatchSpanProcessor +from opentelemetry.trace import SpanKind, Status, StatusCode +from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator + +from config import LOGGER +from config.settings import ( + APP_ENV, + APP_REVISION, + INSTANCE_ID, + LOG_LEVEL, + OTEL_SERVICE_NAME, + WORKER_CONCURRENCY, +) + +PROPAGATOR = TraceContextTextMapPropagator() +DURATION_BUCKETS = ( + 0.005, + 0.01, + 0.025, + 0.05, + 0.1, + 0.25, + 0.5, + 1, + 2.5, + 5, + 10, + 30, + 60, + 120, +) + + +class TelemetryManager: + def __init__(self) -> None: + self.meters = None + self.traces = None + self.logs = None + self.database = None + self.worker_busy = 0 + self.queue_stats = None + self._sink_id = None + + def start(self, database) -> None: + self.database = database + resource = Resource.create( + { + "service.name": OTEL_SERVICE_NAME, + "service.version": APP_REVISION, + "service.instance.id": INSTANCE_ID, + "deployment.environment.name": APP_ENV, + } + ) + reader = PeriodicExportingMetricReader(OTLPMetricExporter()) + self.meters = MeterProvider( + resource=resource, + metric_readers=[reader], + views=[ + View( + instrument_name="messenger_*_duration", + aggregation=ExplicitBucketHistogramAggregation(DURATION_BUCKETS), + aggregation_cardinality_limit=256, + ), + ], + ) + metrics.set_meter_provider(self.meters) + meter = self.meters.get_meter("messenger", "1.6.0") + self.http_requests = meter.create_counter("messenger_http_requests", unit="") + self.http_duration = meter.create_histogram("messenger_http_duration", unit="s") + self.jobs = meter.create_counter("messenger_jobs", unit="") + self.job_duration = meter.create_histogram("messenger_job_duration", unit="s") + self.ready_duration = meter.create_histogram( + "messenger_attachment_ready_duration", unit="s" + ) + meter.create_observable_gauge( + "messenger_db_pool", callbacks=[self._pool_values], unit="" + ) + if OTEL_SERVICE_NAME == "messenger-worker": + meter.create_observable_gauge( + "messenger_worker_busy", + callbacks=[lambda _: [Observation(self.worker_busy)]], + unit="", + ) + meter.create_observable_gauge( + "messenger_worker_capacity", + callbacks=[lambda _: [Observation(WORKER_CONCURRENCY)]], + unit="", + ) + meter.create_observable_counter( + "messenger_process_cpu", + callbacks=[lambda _: [Observation(time.process_time())]], + unit="s", + ) + meter.create_observable_gauge( + "messenger_process_memory", callbacks=[self._process_memory], unit="By" + ) + meter.create_observable_gauge( + "messenger_container_memory", + callbacks=[lambda _: self._file_gauge("/sys/fs/cgroup/memory.current")], + unit="By", + ) + meter.create_observable_counter( + "messenger_container_cpu", callbacks=[self._container_cpu], unit="s" + ) + meter.create_observable_gauge( + "messenger_queue_depth", + callbacks=[lambda _: self._queue_values("queued")], + unit="", + ) + meter.create_observable_gauge( + "messenger_queue_oldest_age", + callbacks=[lambda _: self._queue_values("oldest_age")], + unit="s", + ) + meter.create_observable_gauge( + "messenger_outbox_pending", + callbacks=[lambda _: self._queue_values("outbox_pending")], + unit="", + ) + self.traces = TracerProvider(resource=resource) + self.traces.add_span_processor( + BatchSpanProcessor( + OTLPSpanExporter(meter_provider=self.meters), + meter_provider=self.meters, + ) + ) + trace.set_tracer_provider(self.traces) + self.logs = LoggerProvider(resource=resource) + self.logs.add_log_record_processor( + BatchLogRecordProcessor( + OTLPLogExporter(meter_provider=self.meters), + meter_provider=self.meters, + ) + ) + self._logger = self.logs.get_logger("messenger", "1.6.0") + self._sink_id = LOGGER.add(self._export_log, level=LOG_LEVEL, catch=True) + + def _export_log(self, message) -> None: + record = message.record + level = record["level"].name + severity = getattr( + SeverityNumber, + {"WARNING": "WARN", "SUCCESS": "INFO", "CRITICAL": "FATAL"}.get( + level, level + ), + SeverityNumber.INFO, + ) + extra = record["extra"] + if "event" not in extra: + return + attributes = { + key: value + for key, value in extra.items() + if key + in { + "event", + "request_id", + "job_id", + "attempt", + "outcome", + "method", + "route", + "status_code", + "operation", + } + and isinstance(value, (str, int, float, bool)) + } + attributes["severity"] = level + self._logger.emit( + LogRecord( + timestamp=int(record["time"].timestamp() * 1_000_000_000), + severity_number=severity, + severity_text=level, + body=record["message"], + attributes=attributes, + ) + ) + + def _pool_values(self, _): + pool = self.database.pool if self.database is not None else None + if pool is None: + return [] + return [ + Observation(value, {"state": state}) + for state, value in { + "used": pool.get_size() - pool.get_idle_size(), + "idle": pool.get_idle_size(), + "capacity": self.database.max_size, + "waiting": self.database.waiting, + }.items() + ] + + @staticmethod + def _file_gauge(filename): + try: + return [Observation(int(Path(filename).read_text().strip()))] + except (OSError, ValueError): + return [] + + @staticmethod + def _process_memory(_): + try: + rss = int(Path("/proc/self/statm").read_text().split()[1]) * os.sysconf( + "SC_PAGE_SIZE" + ) + return [Observation(rss)] + except (OSError, ValueError, IndexError): + return [] + + @staticmethod + def _container_cpu(_): + try: + fields = dict( + line.split() + for line in Path("/sys/fs/cgroup/cpu.stat").read_text().splitlines() + ) + return [Observation(int(fields["usage_usec"]) / 1_000_000)] + except (OSError, ValueError, KeyError): + return [] + + def _queue_values(self, key): + if self.queue_stats is None: + return [] + return [Observation(self.queue_stats[key], {"queue": "attachments.process.v1"})] + + def record_http(self, duration, method, route, status): + if self.meters is not None: + attributes = { + "method": method, + "route": route, + "status_class": f"{status // 100}xx", + } + self.http_requests.add(1, attributes) + self.http_duration.record(duration, attributes) + + def record_job(self, duration, outcome, ready_seconds=None): + if self.meters is not None: + attributes = {"job_type": "attachment.process.v1", "outcome": outcome} + self.jobs.add(1, attributes) + self.job_duration.record(duration, attributes) + if ready_seconds is not None: + self.ready_duration.record( + ready_seconds, {"job_type": "attachment.process.v1"} + ) + + @contextmanager + def span( + self, name, attributes=None, *, kind=SpanKind.INTERNAL, context=None, root=False + ): + parent = trace.get_current_span() + manager = ( + trace.get_tracer("messenger").start_as_current_span( + name, + context=context, + kind=kind, + attributes=attributes, + record_exception=False, + set_status_on_exception=False, + ) + if root or parent.get_span_context().is_valid + else nullcontext(parent) + ) + with manager as span: + try: + yield span + except BaseException as error: + span.set_attribute("error.type", type(error).__name__) + span.set_status(Status(StatusCode.ERROR)) + raise + + @staticmethod + def inject(): + carrier = {} + PROPAGATOR.inject(carrier) + return carrier + + @staticmethod + def extract(carrier): + return PROPAGATOR.extract( + { + key: value + for key, value in carrier.items() + if key in {"traceparent", "tracestate"} and value + } + ) + + def shutdown(self): + if self._sink_id is not None: + LOGGER.remove(self._sink_id) + if self.logs is not None: + self.logs.shutdown() + if self.traces is not None: + self.traces.shutdown() + if self.meters is not None: + self.meters.shutdown(timeout_millis=3000) + + +telemetry = TelemetryManager() diff --git a/src/infrastructure/repositories/attachment_repository/postgres.py b/src/infrastructure/repositories/attachment_repository/postgres.py index 112b275f..554299a7 100644 --- a/src/infrastructure/repositories/attachment_repository/postgres.py +++ b/src/infrastructure/repositories/attachment_repository/postgres.py @@ -11,6 +11,7 @@ from domain import ( UnfinishedUploadSchema, ) from domain.errors import NotFoundError +from infrastructure.observability import telemetry from infrastructure.utils import Pool, repository_logs from interfaces import AttachmentRepository @@ -87,9 +88,13 @@ class PostgresAttachmentRepository(AttachmentRepository): ) if row is None: return None + carrier = telemetry.inject() job_id = await conn.fetchval( - "INSERT INTO attachment_jobs (attachment_id) VALUES ($1) RETURNING id;", + """INSERT INTO attachment_jobs (attachment_id, traceparent, tracestate) + VALUES ($1, $2, $3) RETURNING id;""", attachment_id, + carrier.get("traceparent"), + carrier.get("tracestate"), ) await conn.execute( "INSERT INTO attachment_outbox (job_id, attempt) VALUES ($1, 1);", diff --git a/src/infrastructure/repositories/job_repository/postgres.py b/src/infrastructure/repositories/job_repository/postgres.py index e88053ea..fdb486b5 100644 --- a/src/infrastructure/repositories/job_repository/postgres.py +++ b/src/infrastructure/repositories/job_repository/postgres.py @@ -112,7 +112,7 @@ class PostgresJobRepository(JobRepository): ) return True - async def _reschedule(self, conn, row, code: str, permanent: bool) -> None: + async def _reschedule(self, conn, row, code: str, permanent: bool) -> str: failures = row["failures"] + 1 terminal = permanent or failures >= self._max_attempts # Equal jitter: нижняя половина задержки гарантирована, верхняя случайна. @@ -142,9 +142,10 @@ class PostgresJobRepository(JobRepository): SELECT id, attempt, available_at FROM attachment_jobs WHERE id = $1;""", row["id"], ) + return "failed" if terminal else "retry" @repository_logs - async def fail(self, job: ClaimedJobSchema, code: str, permanent: bool) -> None: + async def fail(self, job: ClaimedJobSchema, code: str, permanent: bool) -> str: async with self._pool.acquire() as conn, conn.transaction(): row = await conn.fetchrow( """SELECT * FROM attachment_jobs WHERE id = $1 AND lease_token = $2 @@ -153,7 +154,8 @@ class PostgresJobRepository(JobRepository): job.lease_token, ) if row is not None: - await self._reschedule(conn, row, code, permanent) + return await self._reschedule(conn, row, code, permanent) + return "lease_lost" @repository_logs async def recover_expired(self) -> int: @@ -180,7 +182,8 @@ class PostgresJobRepository(JobRepository): UPDATE attachment_outbox o SET claim_token = $1, claim_until = clock_timestamp() + interval '15 seconds' FROM next, attachment_jobs j WHERE o.id = next.id AND j.id = o.job_id - RETURNING o.id, o.attempt, j.id AS job_id, j.attachment_id, j.pipeline_version, j.created_at; + RETURNING o.id, o.attempt, j.id AS job_id, j.attachment_id, j.pipeline_version, + j.created_at, j.traceparent, j.tracestate; """, token, ) @@ -198,6 +201,8 @@ class PostgresJobRepository(JobRepository): "pipeline_version", "attempt", "created_at", + "traceparent", + "tracestate", ) } ), diff --git a/src/infrastructure/repositories/observability/__init__.py b/src/infrastructure/repositories/observability/__init__.py new file mode 100644 index 00000000..5af69d1d --- /dev/null +++ b/src/infrastructure/repositories/observability/__init__.py @@ -0,0 +1,3 @@ +from .postgres import PostgresObservabilityRepository + +__all__ = ["PostgresObservabilityRepository"] diff --git a/src/infrastructure/repositories/observability/postgres.py b/src/infrastructure/repositories/observability/postgres.py new file mode 100644 index 00000000..2ee8d1dd --- /dev/null +++ b/src/infrastructure/repositories/observability/postgres.py @@ -0,0 +1,18 @@ +from infrastructure.utils import Pool, repository_logs + + +class PostgresObservabilityRepository: + def __init__(self, pool: Pool) -> None: + self._pool = pool + + @repository_logs + async def queue_snapshot(self) -> dict: + async with self._pool.acquire() as conn: + row = await conn.fetchrow(""" + SELECT count(*) FILTER (WHERE a.status = 'queued') AS queued, + COALESCE(max(extract(epoch FROM clock_timestamp() - j.created_at)) + FILTER (WHERE a.status = 'queued'), 0) AS oldest_age, + (SELECT count(*) FROM attachment_outbox WHERE published_at IS NULL) AS outbox_pending + FROM attachment_jobs j JOIN attachments a ON a.id = j.attachment_id; + """) + return {key: float(value) for key, value in dict(row).items()} diff --git a/src/infrastructure/utils/repository_utils.py b/src/infrastructure/utils/repository_utils.py index e450afe1..88574348 100644 --- a/src/infrastructure/utils/repository_utils.py +++ b/src/infrastructure/utils/repository_utils.py @@ -6,6 +6,7 @@ import asyncpg from config import LOGGER from domain.errors import UnavailableError +from infrastructure.observability import telemetry DATABASE_UNAVAILABLE_ERRORS: tuple[type[Exception], ...] = ( OSError, @@ -29,9 +30,14 @@ def repository_logs(func: Callable) -> Callable: f"|| Function: {func.__name__} || " ) try: - result = await func(*args, **kwargs) + with telemetry.span( + "postgres." + func.__name__, {"db.system.name": "postgresql"} + ): + result = await func(*args, **kwargs) except DATABASE_UNAVAILABLE_ERRORS as error: - LOGGER.warning(log_text + f"failed || Error: {type(error).__name__}") + LOGGER.bind(event="postgres.unavailable", operation=func.__name__).warning( + f"PostgreSQL: {type(error).__name__}" + ) raise UnavailableError() from None LOGGER.debug(log_text + "completed") return result diff --git a/src/infrastructure/utils/storage_utils.py b/src/infrastructure/utils/storage_utils.py index 79bf8239..cb3e3ebd 100644 --- a/src/infrastructure/utils/storage_utils.py +++ b/src/infrastructure/utils/storage_utils.py @@ -7,6 +7,7 @@ from botocore.exceptions import BotoCoreError, ClientError from config import LOGGER from domain.errors import UnavailableError +from infrastructure.observability import telemetry # Сеть, таймауты и ответы S3 с ошибкой (5xx, AccessDenied, BadDigest): # для клиента — 503, подробности только в журнале @@ -38,9 +39,14 @@ def storage_logs(func: Callable) -> Callable: f"|| Function: {func.__name__} || " ) try: - result = await func(*args, **kwargs) + with telemetry.span( + "s3." + func.__name__, {"rpc.system": "aws-api", "rpc.service": "S3"} + ): + result = await func(*args, **kwargs) except STORAGE_UNAVAILABLE_ERRORS as error: - LOGGER.warning(log_text + f"failed || Error: {storage_error_code(error)}") + LOGGER.bind(event="s3.unavailable", operation=func.__name__).warning( + f"S3: {storage_error_code(error)}" + ) raise UnavailableError("Хранилище файлов временно недоступно") from None LOGGER.debug(log_text + "completed") return result diff --git a/src/interfaces/job_repository.py b/src/interfaces/job_repository.py index bade9555..a7d04809 100644 --- a/src/interfaces/job_repository.py +++ b/src/interfaces/job_repository.py @@ -23,7 +23,7 @@ class JobRepository(ABC): pass @abstractmethod - async def fail(self, job: ClaimedJobSchema, code: str, permanent: bool) -> None: + async def fail(self, job: ClaimedJobSchema, code: str, permanent: bool) -> str: pass @abstractmethod diff --git a/src/worker.py b/src/worker.py index f090cfdf..b9a65951 100644 --- a/src/worker.py +++ b/src/worker.py @@ -1,7 +1,10 @@ import asyncio import signal +import time +from datetime import UTC, datetime from pathlib import Path +from opentelemetry.trace import SpanKind, Status, StatusCode from pydantic import ValidationError from config import DB_STARTUP_TIMEOUT_SEC, LOGGER, MAX_IMAGE_PIXELS, MAX_UPLOAD_BYTES @@ -16,6 +19,7 @@ from domain.jobs import JobMessageSchema, ProcessingError from infrastructure import database_pool_manager, storage_manager from infrastructure.broker import RabbitBrokerManager from infrastructure.dependencies.jobs import create_job_repository +from infrastructure.observability import telemetry from infrastructure.repositories import S3ObjectStorage from infrastructure.services.image_pipeline import ImagePipeline @@ -25,6 +29,7 @@ async def main() -> None: loop = asyncio.get_running_loop() for signum in (signal.SIGTERM, signal.SIGINT): loop.add_signal_handler(signum, stop.set) + telemetry.start(database_pool_manager) await database_pool_manager.create_pool(DB_STARTUP_TIMEOUT_SEC) await database_pool_manager.check_migrations() await storage_manager.create_client() @@ -41,6 +46,19 @@ async def main() -> None: slots = asyncio.Semaphore(WORKER_CONCURRENCY) tasks = set() + async def process(job) -> str: + try: + async with asyncio.timeout(JOB_TIMEOUT_SECONDS): + completed = await pipeline.process(job) + return "ready" if completed else "lease_lost" + except ProcessingError as error: + return await jobs.fail(job, error.code, permanent=True) + except Exception as error: + LOGGER.bind( + event="job.processing_error", job_id=str(job.message.job_id) + ).warning(f"Ошибка обработки: {type(error).__name__}") + return await jobs.fail(job, "processing_failed", permanent=False) + async def consume(message) -> None: task = asyncio.current_task() tasks.add(task) @@ -52,21 +70,49 @@ async def main() -> None: LOGGER.warning("Невалидное сообщение отправлено в quarantine") return async with slots: - job = await jobs.claim(data) - if job is not None: - try: - async with asyncio.timeout(JOB_TIMEOUT_SECONDS): - await pipeline.process(job) - except ProcessingError as error: - await jobs.fail(job, error.code, permanent=True) - except Exception as error: - LOGGER.warning( - f"Job {data.job_id}: {type(error).__name__}, retry" - ) - await jobs.fail(job, "processing_failed", permanent=False) - await message.ack() + with telemetry.span( + "rabbitmq.consume", + { + "messaging.system": "rabbitmq", + "messaging.destination.name": "attachments.process.v1", + "messaging.operation.type": "process", + "job.attempt": data.attempt, + }, + context=telemetry.extract(data.model_dump()), + kind=SpanKind.CONSUMER, + root=True, + ) as span: + job = await jobs.claim(data) + if job is not None: + telemetry.worker_busy += 1 + started = time.perf_counter() + try: + outcome = await process(job) + ready_seconds = None + if outcome == "ready": + ready_seconds = ( + datetime.now(UTC) - data.created_at + ).total_seconds() + else: + span.set_status(Status(StatusCode.ERROR)) + span.set_attribute("job.outcome", outcome) + telemetry.record_job( + time.perf_counter() - started, outcome, ready_seconds + ) + LOGGER.bind( + event="job.processed", + job_id=str(data.job_id), + attempt=data.attempt, + outcome=outcome, + ).log( + "INFO" if outcome == "ready" else "WARNING", + f"Обработка вложения: {outcome}", + ) + finally: + telemetry.worker_busy -= 1 + await message.ack() except asyncio.CancelledError: - raise + raise except Exception as error: LOGGER.warning( f"Consumer: {type(error).__name__}; сообщение не подтверждено" @@ -98,6 +144,7 @@ async def main() -> None: await broker.close() await storage_manager.close() await database_pool_manager.close() + await asyncio.to_thread(telemetry.shutdown) if __name__ == "__main__":