From dec4ede429107078d21d63a1071098456b0148f9 Mon Sep 17 00:00:00 2001 From: dmice9 Date: Thu, 3 Dec 2026 20:20:07 +0300 Subject: [PATCH] Implement Lab 6 observability --- .env.example | 3 + .gitattributes | 2 + .github/workflows/application.yml | 19 ++ Dockerfile | 15 + REPORT.md | 77 +++-- compose.yaml | 267 ++++++++++++++++++ evidence/load.json | 17 ++ evidence/observability.json | 124 ++++++++ evidence/queue-recovery.json | 34 +++ infra/haproxy.cfg | 44 +++ infra/otel/README.md | 8 +- infra/otel/collector.yaml | 51 ++++ infra/otel/grafana/dashboards/messenger.json | 182 ++++++++++++ .../grafana/provisioning/dashboards/lab.yaml | 8 + .../grafana/provisioning/datasources/lab.yaml | 27 ++ infra/otel/loki.yaml | 48 ++++ infra/otel/prometheus.yaml | 9 + infra/otel/tempo.yaml | 24 ++ migrations/001_initial.sql | 40 +++ migrations/002_idempotency.sql | 15 + migrations/003_attachments.sql | 29 ++ migrations/004_attachment_jobs.sql | 21 ++ requirements.lock | 43 +++ scripts/setup.py | 54 ++++ src/__init__.py | 1 + src/__main__.py | 21 ++ src/app.py | 213 ++++++++++++++ src/attachments.py | 131 +++++++++ src/bootstrap.py | 53 ++++ src/config.py | 23 ++ src/errors.py | 15 + src/jobs.py | 234 +++++++++++++++ src/migrate.py | 50 ++++ src/models.py | 61 ++++ src/objects.py | 57 ++++ src/pagination.py | 44 +++ src/security.py | 63 +++++ src/storage.py | 244 ++++++++++++++++ src/telemetry.py | 140 +++++++++ student-tests/observability.py | 174 ++++++++++++ student-tests/queue_recovery.py | 172 +++++++++++ 41 files changed, 2828 insertions(+), 29 deletions(-) create mode 100644 .gitattributes create mode 100644 .github/workflows/application.yml create mode 100644 Dockerfile create mode 100644 compose.yaml create mode 100644 evidence/load.json create mode 100644 evidence/observability.json create mode 100644 evidence/queue-recovery.json create mode 100644 infra/haproxy.cfg create mode 100644 infra/otel/collector.yaml create mode 100644 infra/otel/grafana/dashboards/messenger.json create mode 100644 infra/otel/grafana/provisioning/dashboards/lab.yaml create mode 100644 infra/otel/grafana/provisioning/datasources/lab.yaml create mode 100644 infra/otel/loki.yaml create mode 100644 infra/otel/prometheus.yaml create mode 100644 infra/otel/tempo.yaml create mode 100644 migrations/001_initial.sql create mode 100644 migrations/002_idempotency.sql create mode 100644 migrations/003_attachments.sql create mode 100644 migrations/004_attachment_jobs.sql create mode 100644 requirements.lock create mode 100644 scripts/setup.py create mode 100644 src/__init__.py create mode 100644 src/__main__.py create mode 100644 src/app.py create mode 100644 src/attachments.py create mode 100644 src/bootstrap.py create mode 100644 src/config.py create mode 100644 src/errors.py create mode 100644 src/jobs.py create mode 100644 src/migrate.py create mode 100644 src/models.py create mode 100644 src/objects.py create mode 100644 src/pagination.py create mode 100644 src/security.py create mode 100644 src/storage.py create mode 100644 src/telemetry.py create mode 100644 student-tests/observability.py create mode 100644 student-tests/queue_recovery.py diff --git a/.env.example b/.env.example index 2b326558..0b4ebc80 100644 --- a/.env.example +++ b/.env.example @@ -3,6 +3,9 @@ APP_HOST=0.0.0.0 APP_PORT=8080 APP_ENV=lab +# Host loopback ports for the load balancer and Grafana. +HTTP_PORT=8080 +GRAFANA_PORT=13006 SESSION_TTL_SECONDS=3600 # Choose credentials locally. File paths contain no secret values. DATABASE_URL_FILE=/run/secrets/database_url diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..4b887bf0 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +* text=auto eol=lf +*.cmd text eol=crlf diff --git a/.github/workflows/application.yml b/.github/workflows/application.yml new file mode 100644 index 00000000..b42042e5 --- /dev/null +++ b/.github/workflows/application.yml @@ -0,0 +1,19 @@ +name: Application +on: [push, pull_request] +permissions: + contents: read +jobs: + smoke: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - run: python -X utf8 scripts/setup.py + - run: docker compose up -d --build --wait --wait-timeout 180 + - run: curl --fail --retry 20 --retry-all-errors --retry-delay 1 http://127.0.0.1:8080/health/ready + - run: curl --fail --retry 20 --retry-all-errors --retry-delay 1 http://127.0.0.1:13006/api/dashboards/uid/lab-messenger > /dev/null + - run: make test PYTHON='python -X utf8' BASE_URL=http://127.0.0.1:8080 + - if: always() + run: docker compose down diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..2c1cae8d --- /dev/null +++ b/Dockerfile @@ -0,0 +1,15 @@ +FROM python:3.13.14-slim-bookworm@sha256:67a1e1f215ccda113cfc024e8639049257e88f273898f595b61476d128d387e8 + +ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 PYTHONUTF8=1 \ + APP_HOST=0.0.0.0 APP_PORT=8080 APP_ENV=lab +WORKDIR /app +COPY requirements.lock . +RUN python -m pip install --no-cache-dir -r requirements.lock \ + && useradd --uid 10001 --create-home messenger +COPY src ./src +COPY migrations ./migrations +USER messenger +EXPOSE 8080 +HEALTHCHECK --interval=5s --timeout=4s --start-period=10s --retries=6 \ + CMD python -c "import os,urllib.request; urllib.request.urlopen('http://127.0.0.1:'+os.environ['APP_PORT']+'/health/ready',timeout=3).close()" +CMD ["python", "-m", "src"] diff --git a/REPORT.md b/REPORT.md index b97ae42d..744c1fa0 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,66 @@ -# Отчёт — лабораторная 6 +# ЛР 6 — наблюдаемость мессенджера -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +Кузнецов Даниил Русланович, БПИ2304. Целевая оценка — **3**. Ветка Gitea — `solution/bpi2304-kuznetsov`. -## Запуск из чистого clone +## Запуск -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +Нужны Git, Python 3.9+ для локальных проверок и Docker с Compose v2. На Windows запустите Docker Desktop. Из чистого clone выполните: -## Архитектура и решения +```sh +python -X utf8 scripts/setup.py +docker compose config --quiet +docker compose up -d --build --wait --wait-timeout 180 +curl -f http://127.0.0.1:8080/health/ready +``` -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab5, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +Скрипт создаёт локальные `.env` и `secrets/`, PostgreSQL применяет миграции через сервис `migrate`, а `bootstrap` подготавливает приватный S3. Открыть панель «Мессенджер — лабораторная 6» можно по адресу `http://127.0.0.1:13006/d/lab-messenger`. Для просмотра включён локальный анонимный Viewer. Для администрирования используется пользователь `admin` с паролем из локального `secrets/grafana_password`. -## Доказательства критериев +API доступен через HAProxy на `127.0.0.1:8080`. Порты можно изменить через `HTTP_PORT` и `GRAFANA_PORT`. В этом прогоне API работал на 18086, чтобы не занимать порт ЛР 5. Повторить проверки можно на любом из этих портов, указав его во всех `--base-url`. Внутренние порты OTLP, хранилищ и реплик API доступны в сети Compose. -| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | -| --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | +```sh +python -X utf8 scripts/check_contract.py +python -X utf8 tests/smoke.py --base-url http://127.0.0.1:8080 +python -X utf8 tests/load.py --duration 8 --concurrency 2 --base-url http://127.0.0.1:8080 --output evidence/load.json +python -X utf8 student-tests/observability.py --base-url http://127.0.0.1:8080 --output evidence/observability.json +python -X utf8 student-tests/queue_recovery.py --base-url http://127.0.0.1:8080 --output evidence/queue-recovery.json +``` -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +Первые две команды соответствуют `make check test PYTHON='python -X utf8'`. Сценарии сбоев запускаются отдельно на свободном локальном учебном стенде. Они создают синтетические записи, временно останавливают сервисы и запускают их обратно. `docker compose down` останавливает стенд с сохранением volumes. Команда `docker compose down --volumes` предназначена для намеренного удаления всех учебных данных проекта. -## Эксперименты и отказы +## Хранилища и сигналы -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +Из ЛР 5 перенесены две реплики API, PostgreSQL, HAProxy, приватный S3, RabbitMQ, dispatcher и worker. Бизнес-API сохранился. API и worker отправляют OTLP/HTTP на `otel-collector:4318`. Collector передаёт логи и трассы дальше, а Prometheus опрашивает его метрики каждые пять секунд. Для запросов к источникам и дашборда используется Grafana. -| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | -| --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +| Компонент | Версия | Назначение | +| --- | --- | --- | +| OpenTelemetry Python SDK | 1.45.2, semantic conventions 0.66b2 | HTTP server spans, worker consumer spans, счётчики, гистограммы и JSON-события | +| Collector Contrib | 0.133.0 | Приём OTLP и маршрутизация трёх сигналов | +| Prometheus | 3.5.0 | Метрики, volume `promdata` | +| Loki | 3.5.3 | Структурные логи, volume `lokidata` | +| Tempo | 2.8.2 | Трассы, volume `tempodata` | +| Grafana | 12.1.1 | Запросы к трём хранилищам, provisioned dashboard, volume `grafanadata` | -## Ограничения и следующие шаги +Данные метрик, логов и трасс настроены на хранение в течение трёх дней. Конфигурации и [импортируемый dashboard](infra/otel/grafana/dashboards/messenger.json) находятся в `infra/otel/`. Для записи в Loki используется его нативный OTLP endpoint. SDK экспортирует в фоне с ограниченными очередями и таймаутами. В Collector настроены размеры очередей, памяти и ограниченные по времени повторы экспорта. -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +| Сигнал | Метрика и измерения | +| --- | --- | +| HTTP RPS и ответы 5xx | `messenger_http_requests_total` с `http_method`, `http_route`, `http_status_class`. Dashboard показывает RPS по шаблону маршрута и отдельно частоту 5xx. Health-маршруты видны как отдельные ряды. | +| Длительность HTTP | `messenger_http_duration_seconds` с теми же измерениями. Dashboard делит скорость роста суммы на скорость роста количества и показывает среднее в секундах до передачи ответа из middleware. | +| Итоги доставки worker | `messenger_job_deliveries_total` с `job_type`, `job_outcome`. `ready` — работа завершена, `failed` — окончательная ошибка. `retry`, `duplicate` и `error` учитываются отдельно. | +| Длительность обработки | `messenger_job_duration_seconds` с измерениями jobs. Время считается от получения валидной доставки до результата обработки, включая работу с PostgreSQL и S3. | + +У всех сигналов есть `service.name`, `service.version`, `service.instance.id` и `deployment.environment.name`. В Loki индексируются имя сервиса и окружение. В прикладные логи выводятся безопасные поля события, включая `trace_id` и `span_id`. Для запроса можно найти лог по `request_id`. Для задания — по `attachment_id` или `job_id`. Эти ID отсутствуют в labels метрик. В логи и трассы не записываются тела запросов, содержимое изображения, пароли, заголовок Authorization, токены и сырые URL. + +## Проверки и разбор сбоев + +Файл [observability.json](evidence/observability.json) содержит измеренные значения из Prometheus и пары лог/трасса из Loki и Tempo. В Grafana откройте Explore → Loki и выполните `{service_name="messenger-api"} | json | request_id=""`. Для worker используйте `{service_name="messenger-worker"} | json | attachment_id=""`. В записи нажмите ссылку Trace или откройте её `trace_id` в Tempo. У обоих событий ID спана в логе совпадает с ID реального спана. + +1. При краткой остановке PostgreSQL API вернул 503 на `GET /health/ready`. В Loki видно событие запроса с 503. В спане Tempo есть событие `postgresql.unavailable`, которое указывает на недоступность БД. Проверка обращается к API из его контейнера, чтобы увидеть его собственный ответ до обработки HAProxy. После запуска БД публичный health снова ответил 200. +2. У отдельного синтетического вложения удалена копия из staging при выключенном worker. После запуска worker получил задачу и исчерпал пять попыток. Лог и consumer span показывают `staging_unavailable`, поэтому причину можно отличить от сбоя при записи результата. API отдаёт безопасный код `retry_exhausted`. +3. Во время остановки Tempo запись сообщения через API вернула 201. Затем Tempo запущен обратно. При более долгой недоступности telemetry backend ограниченные очереди могут терять данные. + +Проверка структуры контракта и публичный smoke прошли. Короткий локальный closed-loop тест двумя клиентами дал 1500 успешных записей за 8 секунд без ошибок. Подробности в [load.json](evidence/load.json). Повторная проверка сценария ЛР 5 сохранена в [queue-recovery.json](evidence/queue-recovery.json). + +Трассы API и worker можно исследовать независимо. Наблюдения относятся к одному локальному Docker-хосту и синтетическим данным. + +При переносе кода, настройке телеметрии и проверке использован Codex. [ЛР 5](https://gitea.privcloud.tech/mtusi2026/mtusi2026lab5/pulls/153) · [OpenTelemetry Python exporters](https://opentelemetry.io/docs/languages/python/exporters/) · [OTLP в Loki](https://grafana.com/docs/loki/latest/send-data/otel/) · [Collector и Tempo](https://grafana.com/docs/tempo/latest/set-up-for-tracing/instrument-send/set-up-collector/otel-collector/). diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 00000000..2b0caa8e --- /dev/null +++ b/compose.yaml @@ -0,0 +1,267 @@ +name: kuznetsov-lab6 + +x-app: &app + image: mtusi-messenger:kuznetsov-lab6 + build: . + environment: &environment + APP_HOST: 0.0.0.0 + APP_PORT: 8080 + APP_ENV: lab + DATABASE_URL_FILE: /run/secrets/database_url + CURSOR_SECRET_FILE: /run/secrets/cursor_key + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400} + S3_ENDPOINT: http://s3:9000 + S3_REGION: us-east-1 + S3_BUCKET: ${S3_BUCKET:-messenger-attachments} + S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_access_key_id + S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key + OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318} + secrets: + - database_url + - cursor_key + - s3_access_key_id + - s3_secret_access_key + stop_grace_period: 3s + +services: + db: + image: postgres:17.11-bookworm@sha256:665dc7b37ac52a17e298511414c21d23ffa4e6a6ef6225b3e5d59c7afb35e994 + environment: + POSTGRES_USER: messenger + POSTGRES_DB: messenger + POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password + secrets: + - postgres_password + volumes: + - pgdata:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"] + interval: 2s + timeout: 3s + retries: 30 + stop_grace_period: 10s + + s3-storage: + image: chrislusf/seaweedfs:4.54@sha256:4b42c212543a0acd4c0e675215ecdcaf62a186ef98def76c7e12701871222d15 + command: ["server", "-filer", "-dir=/data", "-ip=s3-storage", "-ip.bind=0.0.0.0", + "-master.volumeSizeLimitMB=128", "-volume.max=64", "-master.electionTimeout=1s", + "-master.heartbeatInterval=100ms"] + volumes: + - s3data:/data + networks: + - storage + healthcheck: + test: ["CMD-SHELL", "wget -q -O - http://127.0.0.1:9333/cluster/status | grep -q '\"IsLeader\":true'"] + interval: 2s + timeout: 2s + retries: 45 + stop_grace_period: 10s + + s3: + image: chrislusf/seaweedfs:4.54@sha256:4b42c212543a0acd4c0e675215ecdcaf62a186ef98def76c7e12701871222d15 + command: ["s3", "-filer=s3-storage:8888", "-port=9000", "-ip.bind=0.0.0.0", + "-config=/run/secrets/s3_config", "-iam=false", "-port.iceberg=0", "-port.lance=0"] + secrets: + - s3_config + networks: + - default + - storage + depends_on: + s3-storage: + condition: service_healthy + stop_grace_period: 3s + + migrate: + <<: *app + command: ["python", "-m", "src.migrate"] + secrets: + - database_url + healthcheck: + disable: true + depends_on: + db: + condition: service_healthy + + bootstrap: + <<: *app + command: ["python", "-m", "src.bootstrap"] + environment: + <<: *environment + S3_ADMIN_ACCESS_KEY_ID_FILE: /run/secrets/s3_admin_access_key_id + S3_ADMIN_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_admin_secret_access_key + secrets: + - s3_access_key_id + - s3_secret_access_key + - s3_admin_access_key_id + - s3_admin_secret_access_key + healthcheck: + disable: true + depends_on: + s3: + condition: service_started + + api1: &api + <<: *app + mem_limit: 768m + depends_on: + db: + condition: service_healthy + migrate: + condition: service_completed_successfully + bootstrap: + condition: service_completed_successfully + + api2: + <<: *api + + broker: + image: rabbitmq:4.1.4-alpine@sha256:b736d649308e1b3e1a116c3f36986b605ee3d03e88f10166be2900083d2e63f2 + hostname: broker + secrets: + - source: rabbitmq_config + target: /etc/rabbitmq/conf.d/20-messenger.conf + volumes: + - rabbitdata:/var/lib/rabbitmq + healthcheck: + test: ["CMD", "rabbitmq-diagnostics", "-q", "check_running"] + interval: 3s + timeout: 5s + retries: 25 + + dispatcher: + <<: *app + command: ["python", "-m", "src.jobs", "dispatch"] + environment: &job-environment + <<: *environment + BROKER_URL_FILE: /run/secrets/broker_url + JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5} + secrets: + - database_url + - broker_url + healthcheck: + disable: true + restart: on-failure + depends_on: + broker: + condition: service_healthy + migrate: + condition: service_completed_successfully + + worker: + <<: *app + command: ["python", "-m", "src.jobs", "worker"] + environment: *job-environment + secrets: + - database_url + - broker_url + - s3_access_key_id + - s3_secret_access_key + healthcheck: + disable: true + mem_limit: 768m + restart: on-failure + depends_on: + broker: + condition: service_healthy + migrate: + condition: service_completed_successfully + bootstrap: + condition: service_completed_successfully + + lb: + image: haproxy:3.2.26@sha256:1242e4006ac3f1ed15871efadca3d8d089e76f720017a1c51747133ee40cc953 + ports: + - "127.0.0.1:${HTTP_PORT:-8080}:8080" + volumes: + - ./infra/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + depends_on: + api1: + condition: service_started + api2: + condition: service_started + stop_grace_period: 3s + + otel-collector: + image: otel/opentelemetry-collector-contrib:0.133.0@sha256:98274b756324abdb2473fa0c898247a246091e861e61d1548f9be483198eecea + command: ["--config=/etc/otelcol-contrib/collector.yaml"] + volumes: + - ./infra/otel/collector.yaml:/etc/otelcol-contrib/collector.yaml:ro + mem_limit: 256m + + prometheus: + image: prom/prometheus:v3.5.0@sha256:63805ebb8d2b3920190daf1cb14a60871b16fd38bed42b857a3182bc621f4996 + command: ["--config.file=/etc/prometheus/prometheus.yml", "--storage.tsdb.path=/prometheus", + "--storage.tsdb.retention.time=3d"] + volumes: + - ./infra/otel/prometheus.yaml:/etc/prometheus/prometheus.yml:ro + - promdata:/prometheus + + loki: + image: grafana/loki:3.5.3@sha256:3165cecce301ce5b9b6e3530284b080934a05cd5cafac3d3d82edcb887b45ecd + command: ["-config.file=/etc/loki/lab.yaml"] + volumes: + - ./infra/otel/loki.yaml:/etc/loki/lab.yaml:ro + - lokidata:/loki + + tempo: + image: grafana/tempo:2.8.2@sha256:0ef775495967cd5d7a6b2e146b6ea695d624803c8db8349fb8ce4164f719f9b7 + command: ["-config.file=/etc/tempo.yaml"] + volumes: + - ./infra/otel/tempo.yaml:/etc/tempo.yaml:ro + - tempodata:/var/tempo + + grafana: + image: grafana/grafana:12.1.1@sha256:a1701c2180249361737a99a01bc770db39381640e4d631825d38ff4535efa47d + environment: + GF_AUTH_ANONYMOUS_ENABLED: "true" + GF_AUTH_ANONYMOUS_ORG_ROLE: Viewer + GF_SECURITY_ADMIN_PASSWORD__FILE: /run/secrets/grafana_password + GF_ANALYTICS_REPORTING_ENABLED: "false" + GF_ANALYTICS_CHECK_FOR_UPDATES: "false" + GF_ANALYTICS_CHECK_FOR_PLUGIN_UPDATES: "false" + ports: + - "127.0.0.1:${GRAFANA_PORT:-13006}:3000" + secrets: + - grafana_password + volumes: + - grafanadata:/var/lib/grafana + - ./infra/otel/grafana/provisioning:/etc/grafana/provisioning:ro + - ./infra/otel/grafana/dashboards:/etc/grafana/dashboards:ro + +volumes: + pgdata: + s3data: + rabbitdata: + promdata: + lokidata: + tempodata: + grafanadata: + +networks: + storage: + internal: true + +secrets: + postgres_password: + file: ./secrets/postgres_password + database_url: + file: ./secrets/database_url + cursor_key: + file: ./secrets/cursor_key + s3_config: + file: ./secrets/s3_config.json + s3_access_key_id: + file: ./secrets/s3_access_key_id + s3_secret_access_key: + file: ./secrets/s3_secret_access_key + s3_admin_access_key_id: + file: ./secrets/s3_admin_access_key_id + s3_admin_secret_access_key: + file: ./secrets/s3_admin_secret_access_key + broker_url: + file: ./secrets/broker_url + rabbitmq_config: + file: ./secrets/rabbitmq.conf + grafana_password: + file: ./secrets/grafana_password diff --git a/evidence/load.json b/evidence/load.json new file mode 100644 index 00000000..abad7ad3 --- /dev/null +++ b/evidence/load.json @@ -0,0 +1,17 @@ +{ + "lab": 6, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 8.0, + "elapsed_seconds": 8.016, + "concurrency": 2, + "successful_requests": 1500, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 187.126, + "successful_latency_ms": { + "p50": 15.0, + "p95": 31.0, + "p99": 32.0 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/observability.json b/evidence/observability.json new file mode 100644 index 00000000..a60067ac --- /dev/null +++ b/evidence/observability.json @@ -0,0 +1,124 @@ +{ + "dashboard": "lab-messenger", + "metrics": { + "sum(messenger_http_requests_total)": 2445.0, + "sum(messenger_http_requests_total{http_status_class=\"5xx\"})": 5.0, + "sum(messenger_http_duration_seconds_count)": 2445.0, + "sum(messenger_job_deliveries_total{job_outcome=\"ready\"})": 3.0, + "sum(messenger_job_deliveries_total{job_outcome=\"failed\"})": 1.0, + "sum(messenger_job_duration_seconds_count)": 8.0 + }, + "api_correlation": { + "log": { + "event": "http.request", + "service": "messenger-api", + "request_id": "5fab7c41-45c0-4858-9083-916a356be9a7", + "method": "POST", + "route": "/api/v1/chats/{chat_id}/messages", + "status": 201, + "duration_ms": 7.05, + "trace_id": "b87ae9bb16beea84ef60bc1dc1f447cc", + "span_id": "a531d01e14510c6e" + }, + "trace": { + "name": "POST /api/v1/chats/{chat_id}/messages", + "kind": "SPAN_KIND_SERVER", + "attributes": { + "http.request.method": "POST", + "http.route": "/api/v1/chats/{chat_id}/messages", + "http.response.status_code": "201", + "request.id": "5fab7c41-45c0-4858-9083-916a356be9a7" + }, + "events": [] + } + }, + "worker_correlation": { + "log": { + "event": "job.process", + "service": "messenger-worker", + "job_type": "attachment.process.v1", + "job_id": "c88bc1dd-4db2-4847-b130-f84b699078b0", + "attachment_id": "9006033d-d6a1-498d-a3f3-ff840a3ab169", + "attempt": 1, + "outcome": "ready", + "reason": "completed", + "duration_ms": 19.389, + "trace_id": "14cfaf613183dcc9449ea94dcf359a6f", + "span_id": "c06c5be6126e576b" + }, + "trace": { + "name": "attachment.process.v1 process", + "kind": "SPAN_KIND_CONSUMER", + "attributes": { + "messaging.system": "rabbitmq", + "messaging.destination.name": "attachment.process.v1", + "messaging.operation.type": "process", + "messaging.message.id": "c88bc1dd-4db2-4847-b130-f84b699078b0", + "attachment.id": "9006033d-d6a1-498d-a3f3-ff840a3ab169", + "job.attempt": "1", + "job.outcome": "ready", + "job.reason": "completed" + }, + "events": [] + } + }, + "postgresql_incident": { + "log": { + "event": "http.request", + "service": "messenger-api", + "request_id": "0084b9e7-97d9-47ae-8394-36e8b70c74f1", + "method": "GET", + "route": "/health/ready", + "status": 503, + "duration_ms": 3001.269, + "trace_id": "f73f9e68c796d4868325485e2e94177d", + "span_id": "f98e20c6167c2e72" + }, + "trace": { + "name": "GET /health/ready", + "kind": "SPAN_KIND_SERVER", + "attributes": { + "http.request.method": "GET", + "http.route": "/health/ready", + "http.response.status_code": "503", + "request.id": "0084b9e7-97d9-47ae-8394-36e8b70c74f1" + }, + "events": [ + "postgresql.unavailable" + ] + } + }, + "staging_incident": { + "log": { + "event": "job.process", + "service": "messenger-worker", + "job_type": "attachment.process.v1", + "job_id": "4a59e1e7-913b-4197-82d9-7362b8d5fd0f", + "attachment_id": "ddb7648f-6101-4499-8f8f-716ef7ab354f", + "attempt": 5, + "outcome": "failed", + "reason": "staging_unavailable", + "duration_ms": 6.487, + "trace_id": "334430e49f915695042a69f79db598f4", + "span_id": "65282ea2a6dd5453" + }, + "trace": { + "name": "attachment.process.v1 process", + "kind": "SPAN_KIND_CONSUMER", + "attributes": { + "messaging.system": "rabbitmq", + "messaging.destination.name": "attachment.process.v1", + "messaging.operation.type": "process", + "messaging.message.id": "4a59e1e7-913b-4197-82d9-7362b8d5fd0f", + "attachment.id": "ddb7648f-6101-4499-8f8f-716ef7ab354f", + "job.attempt": "5", + "job.outcome": "failed", + "job.reason": "staging_unavailable" + }, + "events": [] + } + }, + "staging_attempts": 5, + "message_status_with_tempo_stopped": 201, + "message_marker_absent": true +} diff --git a/evidence/queue-recovery.json b/evidence/queue-recovery.json new file mode 100644 index 00000000..87674e1c --- /dev/null +++ b/evidence/queue-recovery.json @@ -0,0 +1,34 @@ +{ + "attachment_id": "5e40e04f-7c59-474f-98bc-55ccbf8bfae4", + "message_id": "7594f573-c2ba-4a65-b894-738dd3c41605", + "upload_status": 202, + "content_while_queued": 409, + "queued_jobs_after_broker_restart_with_dispatcher_stopped": 1, + "api_instance_ids_before": [ + "7465b626dc9e42b08f18e746fbe52754", + "8c6d9168efea4625858e7c1e318171b9" + ], + "api_instance_ids_after": [ + "7b57ff1e300249e8bfe5341ab36ac951", + "d8f978d38b124d27862290a2528bd39d" + ], + "message_preserved_after_restart": true, + "final_status": "ready", + "original_bytes_match": true, + "thumbnail": { + "name": "thumbnail", + "width": 256, + "height": 160, + "sha256": "b8e59b0cad429b1c49c27c4a1c79e52bfc23e2fab7c7238d18d5addd4df4b546", + "size_bytes": 5813, + "content_type": "image/jpeg" + }, + "duplicate_acknowledged": true, + "duplicate_preserved_metadata_and_bytes": true, + "retry_limit": { + "attachment_id": "ef2bfe35-cf02-47fb-9ea8-abab14a5f623", + "attempts": 5, + "status": "failed", + "error_code": "retry_exhausted" + } +} diff --git a/infra/haproxy.cfg b/infra/haproxy.cfg new file mode 100644 index 00000000..7f3de21f --- /dev/null +++ b/infra/haproxy.cfg @@ -0,0 +1,44 @@ +global + log stdout format raw local0 + maxconn 256 + +defaults + mode http + log global + timeout connect 1s + timeout client 60s + timeout server 60s + timeout check 3s + retries 0 + http-error status 503 content-type application/json lf-string '{"error":{"code":"unavailable","message":"API temporarily unavailable","request_id":"%[unique-id]"}}' hdr X-Request-Id %[unique-id] + +resolvers docker + nameserver local 127.0.0.11:53 + resolve_retries 2 + timeout resolve 1s + timeout retry 1s + hold valid 1s + hold nx 1s + hold obsolete 1s + +frontend public + bind :8080 + unique-id-format %[uuid()] + use_backend api_live if { path /health/live } + default_backend api_ready + +backend api_ready + balance roundrobin + option httpchk GET /health/ready + http-check expect status 200 + default-server inter 1s fall 2 rise 1 resolvers docker init-addr libc,none + server first api1:8080 check + server second api2:8080 check + +backend api_live + balance roundrobin + option httpchk GET /health/live + http-check expect status 200 + default-server inter 1s fall 2 rise 1 resolvers docker init-addr libc,none + server first api1:8080 check + server second api2:8080 check diff --git a/infra/otel/README.md b/infra/otel/README.md index c46fe89a..48e9978f 100644 --- a/infra/otel/README.md +++ b/infra/otel/README.md @@ -1,7 +1,5 @@ -# Конфигурация наблюдаемости — реализовать +# Конфигурация наблюдаемости -Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend. +`collector.yaml` принимает OTLP/HTTP от API и worker, экспортирует логи в Loki, трассы в Tempo и отдаёт метрики Prometheus. В `prometheus.yaml`, `loki.yaml` и `tempo.yaml` заданы параметры хранения. -Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. На 4 — alert rules и runbooks. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`. - -Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён. +В `grafana/` находятся настройки источников и дашборд. Grafana доступна по loopback, остальные сервисы телеметрии доступны внутри Compose. Команды запуска и запросы для проверки есть в [REPORT.md](../../REPORT.md). diff --git a/infra/otel/collector.yaml b/infra/otel/collector.yaml new file mode 100644 index 00000000..31c40050 --- /dev/null +++ b/infra/otel/collector.yaml @@ -0,0 +1,51 @@ +receivers: + otlp: + protocols: + http: + endpoint: 0.0.0.0:4318 + +processors: + memory_limiter: + check_interval: 1s + limit_mib: 192 + spike_limit_mib: 48 + batch: + timeout: 1s + send_batch_size: 256 + send_batch_max_size: 512 + +exporters: + prometheus: + endpoint: 0.0.0.0:9464 + metric_expiration: 5m + resource_to_telemetry_conversion: + enabled: true + otlphttp/loki: + endpoint: http://loki:3100/otlp + timeout: 3s + sending_queue: + queue_size: 128 + retry_on_failure: + max_elapsed_time: 30s + otlphttp/tempo: + endpoint: http://tempo:4318 + timeout: 3s + sending_queue: + queue_size: 128 + retry_on_failure: + max_elapsed_time: 30s + +service: + pipelines: + metrics: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [prometheus] + logs: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [otlphttp/loki] + traces: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [otlphttp/tempo] diff --git a/infra/otel/grafana/dashboards/messenger.json b/infra/otel/grafana/dashboards/messenger.json new file mode 100644 index 00000000..7650ce84 --- /dev/null +++ b/infra/otel/grafana/dashboards/messenger.json @@ -0,0 +1,182 @@ +{ + "uid": "lab-messenger", + "title": "Мессенджер — лабораторная 6", + "schemaVersion": 39, + "version": 1, + "refresh": "10s", + "time": { + "from": "now-15m", + "to": "now" + }, + "tags": [ + "mtusi" + ], + "panels": [ + { + "id": 1, + "type": "timeseries", + "title": "API — запросы в секунду", + "gridPos": { + "x": 0, + "y": 0, + "w": 12, + "h": 8 + }, + "datasource": { + "type": "prometheus", + "uid": "lab-prometheus" + }, + "fieldConfig": { + "defaults": { + "unit": "reqps" + }, + "overrides": [] + }, + "targets": [ + { + "refId": "A", + "expr": "sum by (http_route) (rate(messenger_http_requests_total[1m]))", + "legendFormat": "{{http_route}}" + } + ] + }, + { + "id": 2, + "type": "timeseries", + "title": "API — ответы 5xx в секунду", + "gridPos": { + "x": 12, + "y": 0, + "w": 12, + "h": 8 + }, + "datasource": { + "type": "prometheus", + "uid": "lab-prometheus" + }, + "fieldConfig": { + "defaults": { + "unit": "reqps" + }, + "overrides": [] + }, + "targets": [ + { + "refId": "A", + "expr": "sum by (http_route) (rate(messenger_http_requests_total{http_status_class=\"5xx\"}[1m]))", + "legendFormat": "{{http_route}}" + } + ] + }, + { + "id": 3, + "type": "timeseries", + "title": "API — средняя длительность", + "gridPos": { + "x": 0, + "y": 8, + "w": 12, + "h": 8 + }, + "datasource": { + "type": "prometheus", + "uid": "lab-prometheus" + }, + "fieldConfig": { + "defaults": { + "unit": "s" + }, + "overrides": [] + }, + "targets": [ + { + "refId": "A", + "expr": "sum by (http_route) (rate(messenger_http_duration_seconds_sum[1m])) / sum by (http_route) (rate(messenger_http_duration_seconds_count[1m]))", + "legendFormat": "{{http_route}}" + } + ] + }, + { + "id": 4, + "type": "timeseries", + "title": "Worker — задания по исходу", + "gridPos": { + "x": 12, + "y": 8, + "w": 12, + "h": 8 + }, + "datasource": { + "type": "prometheus", + "uid": "lab-prometheus" + }, + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + }, + "targets": [ + { + "refId": "A", + "expr": "sum by (job_outcome) (messenger_job_deliveries_total)", + "legendFormat": "{{job_outcome}}" + } + ] + }, + { + "id": 5, + "type": "timeseries", + "title": "Worker — средняя длительность", + "gridPos": { + "x": 0, + "y": 16, + "w": 12, + "h": 8 + }, + "datasource": { + "type": "prometheus", + "uid": "lab-prometheus" + }, + "fieldConfig": { + "defaults": { + "unit": "s" + }, + "overrides": [] + }, + "targets": [ + { + "refId": "A", + "expr": "sum by (job_outcome) (rate(messenger_job_duration_seconds_sum[1m])) / sum by (job_outcome) (rate(messenger_job_duration_seconds_count[1m]))", + "legendFormat": "{{job_outcome}}" + } + ] + }, + { + "id": 6, + "type": "logs", + "title": "Логи API и worker", + "gridPos": { + "x": 12, + "y": 16, + "w": 12, + "h": 8 + }, + "datasource": { + "type": "loki", + "uid": "lab-loki" + }, + "targets": [ + { + "refId": "A", + "expr": "{service_name=~\"messenger-api|messenger-worker\"}" + } + ], + "options": { + "showTime": true, + "showLogDetails": true, + "sortOrder": "Descending" + } + } + ] +} diff --git a/infra/otel/grafana/provisioning/dashboards/lab.yaml b/infra/otel/grafana/provisioning/dashboards/lab.yaml new file mode 100644 index 00000000..28cdeac7 --- /dev/null +++ b/infra/otel/grafana/provisioning/dashboards/lab.yaml @@ -0,0 +1,8 @@ +apiVersion: 1 + +providers: + - name: Messenger + folder: MTUSI + type: file + options: + path: /etc/grafana/dashboards diff --git a/infra/otel/grafana/provisioning/datasources/lab.yaml b/infra/otel/grafana/provisioning/datasources/lab.yaml new file mode 100644 index 00000000..6089a7bd --- /dev/null +++ b/infra/otel/grafana/provisioning/datasources/lab.yaml @@ -0,0 +1,27 @@ +apiVersion: 1 + +datasources: + - name: Prometheus + uid: lab-prometheus + type: prometheus + access: proxy + url: http://prometheus:9090 + isDefault: true + jsonData: + timeInterval: 5s + - name: Loki + uid: lab-loki + type: loki + access: proxy + url: http://loki:3100 + jsonData: + derivedFields: + - name: Trace + matcherRegex: '"trace_id":"([0-9a-f]{32})"' + datasourceUid: lab-tempo + url: '$${__value.raw}' + - name: Tempo + uid: lab-tempo + type: tempo + access: proxy + url: http://tempo:3200 diff --git a/infra/otel/loki.yaml b/infra/otel/loki.yaml new file mode 100644 index 00000000..f5db56c3 --- /dev/null +++ b/infra/otel/loki.yaml @@ -0,0 +1,48 @@ +auth_enabled: false + +server: + http_listen_port: 3100 + +common: + instance_addr: 127.0.0.1 + path_prefix: /loki + storage: + filesystem: + chunks_directory: /loki/chunks + rules_directory: /loki/rules + ring: + kvstore: + store: inmemory + replication_factor: 1 + +ingester: + wal: + dir: /loki/wal + +schema_config: + configs: + - from: 2024-01-01 + store: tsdb + object_store: filesystem + schema: v13 + index: + prefix: lab_index_ + period: 24h + +compactor: + working_directory: /loki/compactor + retention_enabled: true + delete_request_store: filesystem + +limits_config: + allow_structured_metadata: true + retention_period: 72h + otlp_config: + resource_attributes: + ignore_defaults: true + attributes_config: + - action: index_label + attributes: [service.name, deployment.environment.name] + +analytics: + reporting_enabled: false diff --git a/infra/otel/prometheus.yaml b/infra/otel/prometheus.yaml new file mode 100644 index 00000000..13707d1a --- /dev/null +++ b/infra/otel/prometheus.yaml @@ -0,0 +1,9 @@ +global: + scrape_interval: 5s + evaluation_interval: 5s + +scrape_configs: + - job_name: otel-collector + honor_labels: true + static_configs: + - targets: ["otel-collector:9464"] diff --git a/infra/otel/tempo.yaml b/infra/otel/tempo.yaml new file mode 100644 index 00000000..ecb423e5 --- /dev/null +++ b/infra/otel/tempo.yaml @@ -0,0 +1,24 @@ +server: + http_listen_port: 3200 + +distributor: + receivers: + otlp: + protocols: + http: + endpoint: 0.0.0.0:4318 + +storage: + trace: + backend: local + local: + path: /var/tempo/blocks + wal: + path: /var/tempo/wal + +compactor: + compaction: + block_retention: 72h + +usage_report: + reporting_enabled: false diff --git a/migrations/001_initial.sql b/migrations/001_initial.sql new file mode 100644 index 00000000..c738da85 --- /dev/null +++ b/migrations/001_initial.sql @@ -0,0 +1,40 @@ +CREATE TABLE users ( + id uuid PRIMARY KEY, + username varchar(32) NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'), + display_name varchar(100) NOT NULL CHECK (length(btrim(display_name)) > 0), + password_hash text NOT NULL, + created_at timestamptz NOT NULL DEFAULT clock_timestamp() +); + +CREATE TABLE chats ( + id uuid PRIMARY KEY, + title varchar(100) NOT NULL CHECK (length(btrim(title)) > 0), + created_at timestamptz NOT NULL DEFAULT clock_timestamp() +); + +CREATE TABLE chat_members ( + chat_id uuid NOT NULL REFERENCES chats(id), + user_id uuid NOT NULL REFERENCES users(id), + PRIMARY KEY (chat_id, user_id) +); +CREATE INDEX chat_members_user_idx ON chat_members(user_id, chat_id); +CREATE INDEX chats_history_idx ON chats(created_at, id); + +CREATE TABLE messages ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL REFERENCES chats(id), + sender_id uuid NOT NULL REFERENCES users(id), + text varchar(4000) NOT NULL CHECK (length(btrim(text)) > 0), + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members(chat_id, user_id) +); +CREATE INDEX messages_history_idx ON messages(chat_id, created_at, id); + +CREATE TABLE sessions ( + token_hash char(64) PRIMARY KEY, + user_id uuid NOT NULL REFERENCES users(id), + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + expires_at timestamptz NOT NULL, + CHECK (expires_at > created_at) +); +CREATE INDEX sessions_expiry_idx ON sessions(expires_at); diff --git a/migrations/002_idempotency.sql b/migrations/002_idempotency.sql new file mode 100644 index 00000000..46a6ffe5 --- /dev/null +++ b/migrations/002_idempotency.sql @@ -0,0 +1,15 @@ +CREATE TABLE idempotency_keys ( + user_id uuid NOT NULL REFERENCES users(id), + method varchar(8) NOT NULL CHECK (method = 'POST'), + path varchar(128) NOT NULL, + request_key varchar(128) NOT NULL CHECK (request_key ~ '^[A-Za-z0-9._:-]{1,128}$'), + request_hash char(64) NOT NULL, + message_id uuid NOT NULL REFERENCES messages(id), + response_status smallint NOT NULL CHECK (response_status = 201), + response_body jsonb NOT NULL, + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + expires_at timestamptz NOT NULL, + PRIMARY KEY (user_id, method, path, request_key), + CHECK (expires_at > created_at) +); +CREATE INDEX idempotency_expiry_idx ON idempotency_keys(expires_at); diff --git a/migrations/003_attachments.sql b/migrations/003_attachments.sql new file mode 100644 index 00000000..a6af80a0 --- /dev/null +++ b/migrations/003_attachments.sql @@ -0,0 +1,29 @@ +CREATE TABLE attachments ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL REFERENCES chats(id), + owner_id uuid NOT NULL REFERENCES users(id), + filename varchar(255) NOT NULL, + content_type text NOT NULL CHECK (content_type IN ('image/png', 'image/jpeg')), + size_bytes integer NOT NULL CHECK (size_bytes BETWEEN 1 AND 10485760), + sha256 char(64) NOT NULL CHECK (sha256 ~ '^[a-f0-9]{64}$'), + object_key text NOT NULL UNIQUE, + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + updated_at timestamptz NOT NULL DEFAULT clock_timestamp(), + UNIQUE (id, chat_id), + FOREIGN KEY (chat_id, owner_id) REFERENCES chat_members(chat_id, user_id) +); +CREATE INDEX attachments_chat_idx ON attachments(chat_id, created_at, id); + +ALTER TABLE messages DROP CONSTRAINT messages_text_check; +ALTER TABLE messages ADD CONSTRAINT messages_id_chat_unique UNIQUE (id, chat_id); + +CREATE TABLE message_attachments ( + message_id uuid NOT NULL, + attachment_id uuid NOT NULL, + chat_id uuid NOT NULL, + position smallint NOT NULL CHECK (position BETWEEN 0 AND 9), + PRIMARY KEY (message_id, attachment_id), + UNIQUE (message_id, position), + FOREIGN KEY (message_id, chat_id) REFERENCES messages(id, chat_id), + FOREIGN KEY (attachment_id, chat_id) REFERENCES attachments(id, chat_id) +); diff --git a/migrations/004_attachment_jobs.sql b/migrations/004_attachment_jobs.sql new file mode 100644 index 00000000..8e6d9cc8 --- /dev/null +++ b/migrations/004_attachment_jobs.sql @@ -0,0 +1,21 @@ +ALTER TABLE attachments + ADD COLUMN status text NOT NULL DEFAULT 'queued' + CHECK (status IN ('queued', 'processing', 'ready', 'failed')), + ADD COLUMN variants jsonb NOT NULL DEFAULT '[]', + ADD COLUMN error_code text, + ADD CHECK ((status = 'failed') = (error_code IS NOT NULL)); + +CREATE TABLE attachment_jobs ( + id uuid PRIMARY KEY, + attachment_id uuid NOT NULL UNIQUE REFERENCES attachments(id), + source_key text NOT NULL, + attempts integer NOT NULL DEFAULT 0 CHECK (attempts >= 0), + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + publish_at timestamptz DEFAULT clock_timestamp() +); +CREATE INDEX attachment_jobs_pending_idx ON attachment_jobs(publish_at, id) + WHERE publish_at IS NOT NULL; + +-- Existing Lab 4 originals can be used as input without copying or deleting them. +INSERT INTO attachment_jobs(id, attachment_id, source_key) +SELECT gen_random_uuid(), id, object_key FROM attachments; diff --git a/requirements.lock b/requirements.lock new file mode 100644 index 00000000..3b941d63 --- /dev/null +++ b/requirements.lock @@ -0,0 +1,43 @@ +annotated-doc==0.0.5 +annotated-types==0.8.0 +anyio==4.16.0 +argon2-cffi==25.1.0 +argon2-cffi-bindings==26.1.0 +boto3==1.44.3 +botocore==1.44.3 +certifi==2026.11.20 +cffi==2.1.1 +charset-normalizer==3.5.3 +click==8.5.1 +fastapi==0.162.2 +googleapis-common-protos==1.76.0 +h11==0.16.0 +idna==3.20 +jmespath==1.1.0 +opentelemetry-api==1.45.2 +opentelemetry-exporter-http-transport==0.66b2 +opentelemetry-exporter-otlp-common==0.66b2 +opentelemetry-exporter-otlp-proto-common==1.45.2 +opentelemetry-exporter-otlp-proto-http==1.45.2 +opentelemetry-proto==1.45.2 +opentelemetry-sdk==1.45.2 +opentelemetry-semantic-conventions==0.66b2 +pika==1.3.2 +pillow==13.0.0 +protobuf==7.36.2 +psycopg==3.3.8 +psycopg-binary==3.3.8 +psycopg-pool==3.3.3 +pycparser==3.12 +pydantic==2.14.3 +pydantic_core==2.50.4 +python-dateutil==2.9.0.post0 +requests==2.34.2 +s3transfer==0.19.3 +six==1.17.0 +starlette==1.10.0 +typing-inspection==0.4.5 +typing_extensions==4.16.0 +tzdata==2026.6 +urllib3==2.8.0 +uvicorn==0.54.0 diff --git a/scripts/setup.py b/scripts/setup.py new file mode 100644 index 00000000..672d0d7b --- /dev/null +++ b/scripts/setup.py @@ -0,0 +1,54 @@ +import json +import os +import secrets +import shutil +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] + + +def main(): + env_file = ROOT / ".env" + if not env_file.exists(): + shutil.copyfile(ROOT / ".env.example", env_file) + env = {} + for line in env_file.read_text(encoding="utf-8-sig").splitlines(): + key, separator, value = line.partition("=") + if separator and not key.strip().startswith("#"): + env[key.strip()] = value.strip() + bucket = os.environ.get("S3_BUCKET", env.get("S3_BUCKET", "messenger-attachments")) + folder = ROOT / "secrets" + folder.mkdir(mode=0o700, exist_ok=True) + + def initialize(name, value): + path = folder / name + try: + with path.open("x", encoding="ascii") as output: + output.write(value + "\n") + except FileExistsError: + pass + return path.read_text(encoding="ascii").strip() + + password = initialize("postgres_password", secrets.token_hex(32)) + initialize("database_url", f"postgresql://messenger:{password}@db:5432/messenger") + initialize("cursor_key", secrets.token_hex(32)) + identities = [] + for name, prefix, actions in ( + ("bootstrap", "s3_admin_", ["Admin", "Read", "Write", "List"]), + ("messenger", "s3_", [f"{action}:{bucket}" for action in ("Read", "Write", "List")]), + ): + access_key = initialize(prefix + "access_key_id", secrets.token_hex(32)) + secret_key = initialize(prefix + "secret_access_key", secrets.token_hex(32)) + identities.append({"name": name, "credentials": [{"accessKey": access_key, "secretKey": secret_key}], + "actions": actions}) + initialize("s3_config.json", json.dumps({"identities": identities})) + broker_password = initialize("broker_password", secrets.token_hex(32)) + initialize("rabbitmq.conf", f"default_user = messenger\ndefault_pass = {broker_password}") + initialize("broker_url", f"amqp://messenger:{broker_password}@broker:5672/%2F") + initialize("grafana_password", secrets.token_hex(32)) + print("Local environment and secrets are ready.") + + +if __name__ == "__main__": + main() diff --git a/src/__init__.py b/src/__init__.py new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/src/__init__.py @@ -0,0 +1 @@ + diff --git a/src/__main__.py b/src/__main__.py new file mode 100644 index 00000000..c5f2db93 --- /dev/null +++ b/src/__main__.py @@ -0,0 +1,21 @@ +import logging +import os + +import uvicorn + + +if __name__ == "__main__": + logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") + logging.getLogger("messenger").info("environment=%s", os.environ.get("APP_ENV", "lab")) + port = int(os.environ.get("APP_PORT", "8080")) + if not 1 <= port <= 65535: + raise SystemExit("APP_PORT должен быть от 1 до 65535") + uvicorn.run( + "src.app:create_app", + factory=True, + host=os.environ.get("APP_HOST", "0.0.0.0"), + port=port, + workers=1, + access_log=False, + timeout_graceful_shutdown=2, + ) diff --git a/src/app.py b/src/app.py new file mode 100644 index 00000000..3a1f65e6 --- /dev/null +++ b/src/app.py @@ -0,0 +1,213 @@ +from contextlib import asynccontextmanager +import logging +import re +from uuid import UUID, uuid4 +from urllib.parse import quote +from typing import Literal + +from fastapi import FastAPI, Request, Response +from fastapi.exceptions import RequestValidationError +from fastapi.responses import JSONResponse, StreamingResponse +from starlette.background import BackgroundTask +from starlette.concurrency import run_in_threadpool +from starlette.exceptions import HTTPException + +from .attachments import Attachments, thumbnail_key +from .objects import Objects +from .errors import ApiError, invalid, not_found +from .models import CreateChat, CreateMessage, CreateUser +from .security import basic_credentials, bearer_token +from .storage import PostgresStore +from .telemetry import Telemetry, observe_http + + +logger = logging.getLogger("messenger") +SESSION_PATH = "/api/v1/auth/sessions" + + +def uuid_value(value): + try: + return UUID(value) + except ValueError: + raise invalid("Неверный UUID") from None + + +def page_args(request): + raw = request.query_params.get("limit", "50") + normalized = raw.lstrip("0") or "0" + if re.fullmatch(r"[0-9]+", raw) is None or len(normalized) > 3 or not 1 <= int(normalized) <= 100: + raise invalid("Limit должен быть от 1 до 100") + return int(normalized), request.query_params.get("cursor") + + +def create_app(): + store = PostgresStore() + objects = Objects() + attachments = Attachments(store, objects) + instance_id = uuid4().hex + telemetry = Telemetry("messenger-api", instance_id) + + @asynccontextmanager + async def lifespan(app): + await run_in_threadpool(store.open) + try: + yield + finally: + await run_in_threadpool(store.close) + objects.close() + await run_in_threadpool(telemetry.shutdown) + + app = FastAPI(redirect_slashes=False, docs_url=None, redoc_url=None, openapi_url=None, lifespan=lifespan) + app.state.store = store + + def error_response(request, error): + request_id = request.state.request_id + headers = dict(error.headers) + if error.status == 401: + headers["WWW-Authenticate"] = ( + 'Basic realm="messenger", charset="UTF-8"' if request.url.path == SESSION_PATH + else 'Bearer realm="messenger"' + ) + return JSONResponse( + status_code=error.status, headers=headers, + content={"error": {"code": error.code, "message": error.message, "request_id": request_id}}, + ) + + @app.middleware("http") + async def request_context(request, call_next): + request.state.request_id = str(uuid4()) + try: + path = request.url.path + registration = path == "/api/v1/users" and request.method == "POST" + login = path == SESSION_PATH and request.method == "POST" + if login: + request.state.credentials = basic_credentials(request.headers.get("Authorization")) + async for chunk in request.stream(): + if chunk: + raise invalid("Вход не принимает тело запроса") + elif path.startswith("/api/v1/") and not registration: + token = bearer_token(request.headers.get("Authorization")) + request.state.user_id = await run_in_threadpool(store.authenticate, token) + request.state.token = token + upload = re.fullmatch(r"/api/v1/chats/[^/]+/attachments", path) is not None + if request.method == "POST" and path.startswith("/api/v1/") and not login and not upload: + media_type = request.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if media_type != "application/json": + raise ApiError(415, "unsupported_media_type", "Нужен application/json") + try: + (await request.body()).decode("utf-8") + except UnicodeDecodeError: + raise invalid("JSON должен быть в UTF-8") from None + response = await call_next(request) + except ApiError as error: + response = error_response(request, error) + except Exception as error: + logger.error("request failed: %s", type(error).__name__) + response = error_response(request, ApiError(500, "internal_error", "Внутренняя ошибка")) + response.headers["X-Instance-Id"] = instance_id + response.headers["X-Request-Id"] = request.state.request_id + return response + + @app.middleware("http") + async def telemetry_context(request, call_next): + return await observe_http(telemetry, request, call_next) + + @app.exception_handler(ApiError) + async def api_error(request, error): + return error_response(request, error) + + @app.exception_handler(RequestValidationError) + async def validation_error(request, error): + return error_response(request, invalid("Неверные поля запроса")) + + @app.exception_handler(HTTPException) + async def http_error(request, error): + code = "not_found" if error.status_code == 404 else "invalid_request" + return error_response(request, ApiError(error.status_code, code, "Неверный запрос")) + + @app.get("/health/live") + def live(): + return {"status": "ok"} + + @app.get("/health/ready") + def ready(): + result = store.ready() + objects.ready() + return result + + @app.post("/api/v1/users", status_code=201) + def create_user(body: CreateUser): + return store.create_user(body) + + @app.post(SESSION_PATH, status_code=201) + def login(request: Request): + return store.create_session(*request.state.credentials) + + @app.delete(SESSION_PATH + "/current", status_code=204) + def logout(request: Request): + store.logout(request.state.token) + return Response(status_code=204) + + @app.get("/api/v1/users/me") + def me(request: Request): + return store.user(request.state.user_id) + + @app.post("/api/v1/chats", status_code=201) + def create_chat(body: CreateChat, request: Request): + return store.create_chat(request.state.user_id, body) + + @app.get("/api/v1/chats") + def list_chats(request: Request): + return store.list_chats(request.state.user_id, *page_args(request)) + + @app.get("/api/v1/chats/{chat_id}") + def chat(chat_id: str, request: Request): + return store.chat(request.state.user_id, uuid_value(chat_id)) + + @app.post("/api/v1/chats/{chat_id}/messages", status_code=201) + def create_message(chat_id: str, body: CreateMessage, request: Request): + key = request.headers.get("Idempotency-Key", "") + if re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", key) is None: + raise invalid("Неверный Idempotency-Key") + return store.create_message(request.state.user_id, uuid_value(chat_id), body, key) + + @app.get("/api/v1/chats/{chat_id}/messages") + def messages(chat_id: str, request: Request): + return store.list_messages(request.state.user_id, uuid_value(chat_id), *page_args(request)) + + @app.post("/api/v1/chats/{chat_id}/attachments", status_code=202) + async def upload(chat_id: str, filename: str, request: Request): + return await attachments.receive(request, uuid_value(chat_id), filename) + + @app.get("/api/v1/attachments/{attachment_id}") + def attachment(attachment_id: str, request: Request): + return attachments.get(request.state.user_id, uuid_value(attachment_id)) + + @app.get("/api/v1/attachments/{attachment_id}/content") + def download(attachment_id: str, request: Request, + variant: Literal["original", "thumbnail", "crop", "optimized"] = "original"): + row = attachments.get(request.state.user_id, uuid_value(attachment_id), internal=True) + if row["status"] != "ready": + raise ApiError(409, "conflict", "Вложение ещё недоступно") + key, metadata, filename = row["object_key"], row, row["filename"] + if variant != "original": + metadata = next((item for item in row["variants"] if item["name"] == variant), None) + if metadata is None: + raise not_found() + key, filename = thumbnail_key(key), "thumbnail.jpg" + body = objects.content(key) + + def chunks(): + try: + while data := body.read(65536): + yield data + finally: + body.close() + + return StreamingResponse( + chunks(), media_type=metadata["content_type"], background=BackgroundTask(body.close), + headers={"Content-Length": str(metadata["size_bytes"]), "X-Content-Type-Options": "nosniff", + "Content-Disposition": "attachment; filename*=UTF-8''" + quote(filename, safe="")}, + ) + + return app diff --git a/src/attachments.py b/src/attachments.py new file mode 100644 index 00000000..5cfb94d3 --- /dev/null +++ b/src/attachments.py @@ -0,0 +1,131 @@ +import asyncio +import hashlib +import tempfile +import unicodedata +import warnings +from uuid import uuid4 + +import anyio +from PIL import Image, UnidentifiedImageError +from starlette.concurrency import run_in_threadpool +from starlette.requests import ClientDisconnect + +from .errors import ApiError, invalid, not_found +from .storage import serialize + + +MAX_BYTES = 10485760 +MAX_PIXELS = 40000000 +Image.MAX_IMAGE_PIXELS = MAX_PIXELS +FIELDS = ("id,chat_id,owner_id,filename,content_type,size_bytes,sha256,created_at,updated_at," + "status,variants,error_code") + + +def thumbnail_key(original_key): + return original_key + ".v1.thumbnail.jpg" + + +def filename_value(value): + if not 1 <= len(value) <= 255 or not value.strip(): + raise invalid("Неверное имя файла") + if any(c in "/\\" or unicodedata.category(c) == "Cc" for c in value): + raise invalid("Неверное имя файла") + try: + value.encode("utf-8") + except UnicodeError: + raise invalid("Неверное имя файла") from None + return value + + +def validate_image(source, media_type): + try: + with warnings.catch_warnings(): + warnings.simplefilter("error", Image.DecompressionBombWarning) + source.seek(0) + with Image.open(source, formats=["PNG", "JPEG"]) as image: + if image.width * image.height > MAX_PIXELS: + raise ApiError(413, "payload_too_large", "Слишком много пикселей") + actual = {"PNG": "image/png", "JPEG": "image/jpeg"}[image.format] + if actual != media_type: + raise ApiError(415, "unsupported_media_type", "Формат не совпадает с Content-Type") + image.verify() + source.seek(0) + with Image.open(source, formats=["PNG", "JPEG"]) as image: + image.load() + except (Image.DecompressionBombWarning, Image.DecompressionBombError): + raise ApiError(413, "payload_too_large", "Слишком много пикселей") from None + except (UnidentifiedImageError, OSError, ValueError, SyntaxError): + raise ApiError(415, "unsupported_media_type", "Повреждённое изображение") from None + + +class Attachments: + def __init__(self, store, objects): + self.store = store + self.objects = objects + self.slots = asyncio.Semaphore(2) + + async def receive(self, request, chat_id, filename): + user_id = request.state.user_id + await run_in_threadpool(self.store.chat, user_id, chat_id) + filename = filename_value(filename) + media_type = request.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if media_type not in ("image/png", "image/jpeg"): + raise ApiError(415, "unsupported_media_type", "Нужен PNG или JPEG") + declared = request.headers.get("Content-Length") + if declared is not None: + if not declared.isascii() or not declared.isdecimal() or len(declared) > 18: + raise invalid("Неверный Content-Length") + if int(declared) > MAX_BYTES: + raise ApiError(413, "payload_too_large", "Файл больше 10 MiB") + try: + await asyncio.wait_for(self.slots.acquire(), timeout=15) + except TimeoutError: + raise ApiError(429, "rate_limited", "Загрузки заняты", {"Retry-After": "1"}) from None + try: + with tempfile.TemporaryFile(mode="w+b") as source: + size, checksum = 0, hashlib.sha256() + try: + with anyio.fail_after(15): + async for chunk in request.stream(): + size += len(chunk) + if size > MAX_BYTES: + raise ApiError(413, "payload_too_large", "Файл больше 10 MiB") + checksum.update(chunk) + await run_in_threadpool(source.write, chunk) + except (TimeoutError, ClientDisconnect): + raise invalid("Загрузка прервана или слишком медленная") from None + await run_in_threadpool(validate_image, source, media_type) + return await run_in_threadpool( + self.stage, user_id, chat_id, filename, media_type, size, checksum.hexdigest(), source, + ) + finally: + self.slots.release() + + def stage(self, user_id, chat_id, filename, media_type, size, checksum, source): + attachment_id = uuid4() + key = "originals/" + attachment_id.hex + staging_key = "staging/" + attachment_id.hex + self.objects.put(staging_key, source, size, media_type) + with self.store.connection() as connection: + self.store.require_chat(connection, user_id, chat_id) + row = connection.execute( + "INSERT INTO attachments(id,chat_id,owner_id,filename,content_type,size_bytes,sha256,object_key) " + "VALUES (%s,%s,%s,%s,%s,%s,%s,%s) RETURNING " + FIELDS, + (attachment_id, chat_id, user_id, filename, media_type, size, checksum, key), + ).fetchone() + connection.execute( + "INSERT INTO attachment_jobs(id, attachment_id, source_key) VALUES (%s, %s, %s)", + (uuid4(), attachment_id, staging_key), + ) + return serialize(row) + + def get(self, user_id, attachment_id, internal=False): + with self.store.connection() as connection: + row = connection.execute( + "SELECT " + FIELDS + (",object_key" if internal else "") + " FROM attachments a " + "WHERE a.id=%s AND EXISTS (SELECT 1 FROM chat_members m " + "WHERE m.chat_id=a.chat_id AND m.user_id=%s)", (attachment_id, user_id), + ).fetchone() + if not row: + raise not_found() + return row if internal else serialize(row) diff --git a/src/bootstrap.py b/src/bootstrap.py new file mode 100644 index 00000000..861da2e8 --- /dev/null +++ b/src/bootstrap.py @@ -0,0 +1,53 @@ +import logging +import time +from io import BytesIO + +from botocore.exceptions import BotoCoreError, ClientError + +from .objects import Objects +from .errors import ApiError + + +def main(): + admin, app = Objects(admin=True), Objects() + try: + deadline = time.monotonic() + 90 + while True: + try: + admin.client.list_buckets() + break + except (ClientError, BotoCoreError): + if time.monotonic() >= deadline: + raise RuntimeError("S3 startup timeout") from None + time.sleep(1) + try: + admin.client.head_bucket(Bucket=admin.bucket) + except ClientError as error: + if error.response["ResponseMetadata"]["HTTPStatusCode"] != 404: + raise RuntimeError("Bucket is not accessible") from None + admin.client.create_bucket(Bucket=admin.bucket) + acl = admin.client.get_bucket_acl(Bucket=admin.bucket) + if any("URI" in grant["Grantee"] for grant in acl["Grants"]): + raise RuntimeError("Bucket must be private") + while True: + try: + probe = b"messenger-ready" + app.put("system/readiness", BytesIO(probe), len(probe), "application/octet-stream") + app.ready() + break + except ApiError: + if time.monotonic() >= deadline: + raise RuntimeError("S3 object path is not ready") from None + time.sleep(0.5) + print("PASS: private bucket ready; application credentials work", flush=True) + finally: + admin.close() + app.close() + + +if __name__ == "__main__": + try: + main() + except Exception as error: + logging.error("S3 bootstrap failed: %s", type(error).__name__) + raise SystemExit(1) diff --git a/src/config.py b/src/config.py new file mode 100644 index 00000000..fb2639da --- /dev/null +++ b/src/config.py @@ -0,0 +1,23 @@ +import os +from pathlib import Path + + +def secret(name): + value = Path(os.environ[name]).read_text(encoding="utf-8").strip() + if not value: + raise ValueError(f"Empty secret file: {name}") + return value + + +def session_ttl(): + value = int(os.environ.get("SESSION_TTL_SECONDS", "3600")) + if not 1 <= value <= 86400: + raise ValueError("SESSION_TTL_SECONDS must be between 1 and 86400") + return value + + +def idempotency_ttl(): + value = int(os.environ.get("IDEMPOTENCY_TTL_SECONDS", "86400")) + if value < 86400: + raise ValueError("IDEMPOTENCY_TTL_SECONDS must be at least 86400") + return value diff --git a/src/errors.py b/src/errors.py new file mode 100644 index 00000000..b1213300 --- /dev/null +++ b/src/errors.py @@ -0,0 +1,15 @@ +class ApiError(Exception): + def __init__(self, status, code, message, headers=None): + super().__init__(message) + self.status = status + self.code = code + self.message = message + self.headers = headers or {} + + +def invalid(message="Неверный запрос"): + return ApiError(400, "invalid_request", message) + + +def not_found(): + return ApiError(404, "not_found", "Объект не найден") diff --git a/src/jobs.py b/src/jobs.py new file mode 100644 index 00000000..ab4f1cd2 --- /dev/null +++ b/src/jobs.py @@ -0,0 +1,234 @@ +import hashlib +import json +import logging +import os +import sys +import time +from io import BytesIO +from uuid import UUID, uuid4 + +import pika +import psycopg +from botocore.exceptions import BotoCoreError +from PIL import Image, ImageOps +from psycopg.rows import dict_row +from psycopg.types.json import Jsonb + +from .attachments import MAX_BYTES, thumbnail_key +from .config import secret +from .errors import ApiError +from .objects import Objects +from .storage import serialize +from .telemetry import Telemetry, observe_delivery + + +QUEUE = "attachment.process.v1" +MAX_ATTEMPTS = int(os.environ.get("JOB_MAX_ATTEMPTS", "5")) +logger = logging.getLogger("attachment_jobs") + + +class StagingUnavailable(Exception): + pass + + +def database(): + return psycopg.connect( + secret("DATABASE_URL_FILE"), row_factory=dict_row, autocommit=True, connect_timeout=3, + options="-c timezone=UTC -c statement_timeout=5000", + ) + + +def broker(): + params = pika.URLParameters(secret("BROKER_URL_FILE")) + params.heartbeat = 60 + params.blocked_connection_timeout = 10 + params.socket_timeout = 5 + return pika.BlockingConnection(params) + + +def publish(channel, row, attempt): + message = { + "schema_version": 1, + "type": QUEUE, + "job_id": str(row["id"]), + "attachment_id": str(row["attachment_id"]), + "pipeline_version": 1, + "attempt": attempt, + "created_at": serialize(row["created_at"]), + } + channel.basic_publish( + exchange="", routing_key=QUEUE, body=json.dumps(message), mandatory=True, + properties=pika.BasicProperties(delivery_mode=2, content_type="application/json", + message_id=message["job_id"]), + ) + + +def dispatch(db, connection, channel): + channel.confirm_delivery() + while True: + with db.transaction(): + row = db.execute( + """SELECT id,attachment_id,attempts,created_at FROM attachment_jobs + WHERE publish_at <= clock_timestamp() + ORDER BY publish_at,id LIMIT 1 FOR UPDATE SKIP LOCKED""" + ).fetchone() + if row: + publish(channel, row, row["attempts"] + 1) + db.execute("UPDATE attachment_jobs SET publish_at=NULL WHERE id=%s", (row["id"],)) + if not row: + connection.sleep(0.25) + + +def render_thumbnail(original): + with Image.open(BytesIO(original), formats=["PNG", "JPEG"]) as image: + oriented = ImageOps.exif_transpose(image) + width, height = oriented.size + edge = max(width, height) + size = (max(1, width * 256 // edge), max(1, height * 256 // edge)) if edge > 256 else oriented.size + rgba = oriented.convert("RGBA") + resized = rgba.resize(size, Image.Resampling.LANCZOS) + background = Image.new("RGB", size, "white") + background.paste(resized, mask=resized.getchannel("A")) + output = BytesIO() + background.save(output, "JPEG", quality=85) + return output.getvalue(), size + + +def save_objects(objects, row): + try: + body = objects.content(row["source_key"]) + try: + original = body.read(MAX_BYTES + 1) + finally: + body.close() + except (ApiError, BotoCoreError) as error: + raise StagingUnavailable from error + if len(original) != row["size_bytes"] or hashlib.sha256(original).hexdigest() != row["sha256"]: + raise ValueError("Original checksum mismatch") + thumbnail, (width, height) = render_thumbnail(original) + if row["source_key"] != row["object_key"]: + objects.put(row["object_key"], BytesIO(original), len(original), row["content_type"]) + objects.put(thumbnail_key(row["object_key"]), BytesIO(thumbnail), len(thumbnail), "image/jpeg") + return {"name": "thumbnail", "content_type": "image/jpeg", "size_bytes": len(thumbnail), + "width": width, "height": height, "sha256": hashlib.sha256(thumbnail).hexdigest()} + + +def fail_or_retry(db, row, permanent=False): + if permanent or row["attempts"] >= MAX_ATTEMPTS: + code = "invalid_image" if permanent else "retry_exhausted" + db.execute( + """UPDATE attachments SET status='failed',error_code=%s,updated_at=clock_timestamp() + WHERE id=%s""", + (code, row["attachment_id"]), + ) + return "failed" + else: + db.execute("UPDATE attachments SET status='queued',updated_at=clock_timestamp() WHERE id=%s", + (row["attachment_id"],)) + db.execute( + "UPDATE attachment_jobs SET publish_at=clock_timestamp() + interval '1 second' WHERE id=%s", + (row["id"],), + ) + return "retry" + + +def process(db, objects, job_id, attachment_id, attempt): + # A session lock spans both commits. PostgreSQL releases it when a worker dies. + db.execute("SELECT pg_advisory_lock(hashtextextended(%s, 5))", (str(job_id),)) + try: + with db.transaction(): + row = db.execute( + """SELECT j.id,j.attachment_id,j.source_key,j.attempts,a.object_key,a.status, + a.content_type,a.size_bytes,a.sha256 + FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id + WHERE j.id=%s AND a.id=%s FOR UPDATE OF j""", + (job_id, attachment_id), + ).fetchone() + if not row or row["status"] in ("ready", "failed"): + return "duplicate", "job_already_terminal_or_missing" + if row["status"] == "processing" and attempt == row["attempts"]: + return fail_or_retry(db, row), "previous_attempt_interrupted" + if row["status"] != "queued" or attempt != row["attempts"] + 1: + return "duplicate", "obsolete_attempt" + row["attempts"] = attempt + db.execute("UPDATE attachment_jobs SET attempts=%s,publish_at=NULL WHERE id=%s", (attempt, job_id)) + db.execute("UPDATE attachments SET status='processing',updated_at=clock_timestamp() WHERE id=%s", + (attachment_id,)) + try: + variant = save_objects(objects, row) + except StagingUnavailable: + with db.transaction(): + return fail_or_retry(db, row), "staging_unavailable" + except (ApiError, BotoCoreError): + with db.transaction(): + return fail_or_retry(db, row), "result_storage_unavailable" + except (ValueError, OSError, SyntaxError, Image.DecompressionBombError): + with db.transaction(): + return fail_or_retry(db, row, permanent=True), "invalid_image" + db.execute( + """UPDATE attachments SET status='ready',variants=%s,updated_at=clock_timestamp() + WHERE id=%s""", + (Jsonb([variant]), attachment_id), + ) + if row["source_key"] != row["object_key"]: + try: + objects.delete(row["source_key"]) + except ApiError: + logger.warning("Staging cleanup deferred for job %s", job_id) + return "ready", "completed" + finally: + db.execute("SELECT pg_advisory_unlock(hashtextextended(%s, 5))", (str(job_id),)) + + +def consume(db, channel, telemetry): + objects = Objects() + try: + channel.basic_qos(prefetch_count=1) + for delivery, _, body in channel.consume(QUEUE, auto_ack=False): + try: + message = json.loads(body) + if message["schema_version"] != 1 or message["type"] != QUEUE or message["pipeline_version"] != 1: + raise ValueError("Unsupported job version") + job_id = UUID(message["job_id"]) + attachment_id = UUID(message["attachment_id"]) + attempt = message["attempt"] + if type(attempt) is not int or attempt < 1: + raise ValueError("Invalid attempt") + except (ValueError, KeyError, TypeError, AttributeError): + logger.warning("Rejected invalid attachment job") + channel.basic_reject(delivery.delivery_tag, requeue=False) + continue + observe_delivery(telemetry, QUEUE, job_id, attachment_id, attempt, + lambda: process(db, objects, job_id, attachment_id, attempt)) + channel.basic_ack(delivery.delivery_tag) + finally: + objects.close() + + +def main(role): + if not 1 <= MAX_ATTEMPTS <= 50: + raise ValueError("JOB_MAX_ATTEMPTS must be between 1 and 50") + telemetry = Telemetry("messenger-worker", uuid4().hex) if role == "worker" else None + try: + while True: + try: + with database() as db, broker() as connection: + channel = connection.channel() + channel.queue_declare(queue=QUEUE, durable=True) + if role == "dispatch": + dispatch(db, connection, channel) + else: + consume(db, channel, telemetry) + except (pika.exceptions.AMQPError, psycopg.Error, OSError) as error: + logger.warning("%s connection error: %s", role, type(error).__name__) + time.sleep(1) + finally: + if telemetry is not None: + telemetry.shutdown() + + +if __name__ == "__main__": + if len(sys.argv) != 2 or sys.argv[1] not in ("dispatch", "worker"): + raise SystemExit("Usage: python -m src.jobs {dispatch|worker}") + logging.basicConfig(level=logging.INFO) + main(sys.argv[1]) diff --git a/src/migrate.py b/src/migrate.py new file mode 100644 index 00000000..5e13605f --- /dev/null +++ b/src/migrate.py @@ -0,0 +1,50 @@ +import hashlib +import logging +from pathlib import Path + +import psycopg + +from .config import secret + + +def migrate(): + files = sorted((Path(__file__).resolve().parents[1] / "migrations").glob("*.sql")) + if not files: + raise RuntimeError("No migrations found") + with psycopg.connect(secret("DATABASE_URL_FILE"), connect_timeout=5) as connection: + with connection.transaction(): + connection.execute("SELECT pg_advisory_xact_lock(230402)") + connection.execute(""" + CREATE TABLE IF NOT EXISTS schema_migrations ( + version text PRIMARY KEY, + checksum char(64) NOT NULL, + applied_at timestamptz NOT NULL DEFAULT clock_timestamp() + ) + """) + for file in files: + content = file.read_text(encoding="utf-8") + checksum = hashlib.sha256(content.encode("utf-8")).hexdigest() + with connection.transaction(): + connection.execute("SELECT pg_advisory_xact_lock(230402)") + old = connection.execute( + "SELECT checksum FROM schema_migrations WHERE version = %s", (file.name,) + ).fetchone() + if old: + if old[0] != checksum: + raise RuntimeError("Applied migration was changed") + print("Already applied: " + file.name, flush=True) + continue + connection.execute(content) + connection.execute( + "INSERT INTO schema_migrations(version, checksum) VALUES (%s, %s)", + (file.name, checksum), + ) + print("Applied: " + file.name, flush=True) + + +if __name__ == "__main__": + try: + migrate() + except Exception as error: + logging.error("Migration failed: %s", type(error).__name__) + raise SystemExit(1) diff --git a/src/models.py b/src/models.py new file mode 100644 index 00000000..38469018 --- /dev/null +++ b/src/models.py @@ -0,0 +1,61 @@ +import re +from typing import Annotated +from uuid import UUID + +from pydantic import AfterValidator, BaseModel, ConfigDict, Field, StringConstraints, field_validator, model_validator + + +def nonblank(value: str) -> str: + if not value.strip() or "\x00" in value: + raise ValueError("Пустая строка или NUL") + value.encode("utf-8") + return value + + +Name = Annotated[str, StringConstraints(min_length=1, max_length=100), AfterValidator(nonblank)] +Text = Annotated[str, StringConstraints(min_length=1, max_length=4000), AfterValidator(nonblank)] +Password = Annotated[str, StringConstraints(min_length=12, max_length=128), AfterValidator(nonblank)] +UserId = Annotated[UUID, Field(strict=False)] + + +class RequestBody(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + + +class CreateUser(RequestBody): + username: str + display_name: Name + password: Password = Field(repr=False) + + @field_validator("username") + @classmethod + def check_username(cls, value): + if re.fullmatch(r"[a-z0-9_]{3,32}", value) is None: + raise ValueError("Неверный username") + return value + + +class CreateChat(RequestBody): + title: Name + member_ids: list[UserId] = Field(min_length=1, max_length=100) + + @field_validator("member_ids") + @classmethod + def unique_members(cls, value): + if len(set(value)) != len(value): + raise ValueError("Повтор участника") + return value + + +class CreateMessage(RequestBody): + text: str = Field(max_length=4000) + attachment_ids: list[UserId] = Field(default_factory=list, max_length=10) + + @model_validator(mode="after") + def check_message(self): + if "\x00" in self.text or (not self.text.strip() and not self.attachment_ids): + raise ValueError("Нужен текст или вложение") + self.text.encode("utf-8") + if len(set(self.attachment_ids)) != len(self.attachment_ids): + raise ValueError("Повтор вложения") + return self diff --git a/src/objects.py b/src/objects.py new file mode 100644 index 00000000..8ef615e0 --- /dev/null +++ b/src/objects.py @@ -0,0 +1,57 @@ +import os + +import boto3 +from botocore.config import Config +from botocore.exceptions import BotoCoreError, ClientError + +from .config import secret +from .errors import ApiError + + +class Objects: + def __init__(self, admin=False): + prefix = "S3_ADMIN_" if admin else "S3_" + self.bucket = os.environ.get("S3_BUCKET", "messenger-attachments") + self.client = boto3.client( + "s3", endpoint_url=os.environ.get("S3_ENDPOINT", "http://s3:9000"), + region_name=os.environ.get("S3_REGION", "us-east-1"), + aws_access_key_id=secret(prefix + "ACCESS_KEY_ID_FILE"), + aws_secret_access_key=secret(prefix + "SECRET_ACCESS_KEY_FILE"), + config=Config( + signature_version="s3v4", connect_timeout=2, read_timeout=5, + max_pool_connections=8, retries={"total_max_attempts": 1}, proxies={}, + s3={"addressing_style": "path"}, + request_checksum_calculation="when_required", + response_checksum_validation="when_required", + ), + ) + + def call(self, operation, **values): + try: + return getattr(self.client, operation)(Bucket=self.bucket, **values) + except (BotoCoreError, ClientError): + raise ApiError(503, "unavailable", "Файловое хранилище недоступно") from None + + def ready(self): + self.call("head_bucket") + body = self.content("system/readiness") + try: + if body.read(32) != b"messenger-ready": + raise ApiError(503, "unavailable", "Файловое хранилище не готово") + except BotoCoreError: + raise ApiError(503, "unavailable", "Файловое хранилище недоступно") from None + finally: + body.close() + + def put(self, key, source, size, content_type): + source.seek(0) + self.call("put_object", Key=key, Body=source, ContentLength=size, ContentType=content_type) + + def content(self, key): + return self.call("get_object", Key=key)["Body"] + + def delete(self, key): + self.call("delete_object", Key=key) + + def close(self): + self.client.close() diff --git a/src/pagination.py b/src/pagination.py new file mode 100644 index 00000000..5d7ca2a9 --- /dev/null +++ b/src/pagination.py @@ -0,0 +1,44 @@ +import base64 +import hashlib +import hmac +import json +from datetime import datetime, timezone +from uuid import UUID + +from .errors import invalid + + +class Pagination: + def __init__(self, secret): + self.secret = secret + + def encode(self, scope, item): + data = json.dumps([1, scope, item["created_at"], item["id"]], separators=(",", ":")) + payload = base64.urlsafe_b64encode(data.encode()).rstrip(b"=").decode() + signature = hmac.new(self.secret, payload.encode(), hashlib.sha256).hexdigest() + return payload + "." + signature + + def decode(self, scope, cursor): + try: + if not isinstance(cursor, str) or not cursor or len(cursor) > 2048: + raise ValueError() + payload, signature = cursor.split(".") + expected = hmac.new(self.secret, payload.encode("ascii"), hashlib.sha256).hexdigest() + if not hmac.compare_digest(signature, expected): + raise ValueError() + data = json.loads(base64.b64decode(payload + "=" * (-len(payload) % 4), altchars=b"-_", validate=True)) + if not isinstance(data, list) or len(data) != 4 or data[:2] != [1, scope]: + raise ValueError() + if not isinstance(data[2], str) or not data[2].endswith("Z"): + raise ValueError() + created_at = datetime.fromisoformat(data[2].replace("Z", "+00:00")) + if created_at.utcoffset() != timezone.utc.utcoffset(created_at): + raise ValueError() + return created_at, UUID(data[3]) + except (ValueError, TypeError, UnicodeError, KeyError, OverflowError): + raise invalid("Неверный cursor") from None + + def page(self, rows, scope, limit): + items = rows[:limit] + cursor = self.encode(scope, items[-1]) if len(rows) > limit else None + return {"items": items, "next_cursor": cursor} diff --git a/src/security.py b/src/security.py new file mode 100644 index 00000000..294dc21a --- /dev/null +++ b/src/security.py @@ -0,0 +1,63 @@ +import base64 +import binascii +import hashlib +import re +import secrets +from threading import BoundedSemaphore + +from argon2 import PasswordHasher +from argon2.exceptions import VerificationError +from argon2.low_level import Type + +from .errors import ApiError + +HASHER = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1, type=Type.ID) +HASH_SLOTS = BoundedSemaphore(4) +DUMMY_HASH = HASHER.hash(secrets.token_urlsafe(32)) + + +def unauthorized(): + return ApiError(401, "unauthorized", "Неверные данные авторизации") + + +def hash_password(password): + with HASH_SLOTS: + return HASHER.hash(password) + + +def verify_password(password_hash, password): + try: + with HASH_SLOTS: + return HASHER.verify(password_hash or DUMMY_HASH, password) + except (VerificationError, ValueError): + return False + + +def basic_credentials(header): + try: + scheme, encoded = header.split(" ", 1) + if scheme.lower() != "basic" or len(encoded) > 2048: + raise ValueError() + decoded = base64.b64decode(encoded, validate=True).decode("utf-8") + username, separator, password = decoded.partition(":") + if not separator or re.fullmatch(r"[a-z0-9_]{3,32}", username) is None: + raise ValueError() + if not 12 <= len(password) <= 128 or not password.strip() or "\x00" in password: + raise ValueError() + return username, password + except (ValueError, UnicodeError, AttributeError, binascii.Error): + raise unauthorized() from None + + +def bearer_token(header): + try: + scheme, token = header.split(" ", 1) + if scheme.lower() != "bearer" or not re.fullmatch(r"[A-Za-z0-9_-]{43}", token): + raise ValueError() + return token + except (ValueError, TypeError, AttributeError): + raise unauthorized() from None + + +def token_hash(token): + return hashlib.sha256(token.encode("ascii")).hexdigest() diff --git a/src/storage.py b/src/storage.py new file mode 100644 index 00000000..207d3f50 --- /dev/null +++ b/src/storage.py @@ -0,0 +1,244 @@ +from contextlib import contextmanager +from datetime import datetime +import logging +import hashlib +import json +import secrets +from uuid import UUID, uuid4 + +import psycopg +from opentelemetry.trace import get_current_span +from psycopg.rows import dict_row +from psycopg.types.json import Jsonb +from psycopg_pool import ConnectionPool, PoolTimeout, TooManyRequests + +from .config import idempotency_ttl, secret, session_ttl +from .errors import ApiError, invalid, not_found +from .pagination import Pagination +from .security import hash_password, token_hash, unauthorized, verify_password + + +USER_FIELDS = "id, username, display_name, created_at" +CHAT_FIELDS = """ + c.id, c.title, c.created_at, + ARRAY(SELECT cm.user_id FROM chat_members cm WHERE cm.chat_id=c.id ORDER BY cm.user_id) AS member_ids +""" + + +def serialize(value): + if isinstance(value, UUID): + return str(value) + if isinstance(value, datetime): + return value.isoformat(timespec="microseconds").replace("+00:00", "Z") + if isinstance(value, dict): + return {key: serialize(item) for key, item in value.items()} + if isinstance(value, list): + return [serialize(item) for item in value] + return value + + +class PostgresStore: + def __init__(self): + logging.getLogger("psycopg.pool").setLevel(logging.CRITICAL) + self.pool = ConnectionPool( + secret("DATABASE_URL_FILE"), min_size=1, max_size=10, timeout=3, max_waiting=40, + open=False, check=ConnectionPool.check_connection, + kwargs={"row_factory": dict_row, "connect_timeout": 3, + "options": "-c timezone=UTC -c statement_timeout=5000 -c lock_timeout=2000"}, + ) + self.pagination = Pagination(secret("CURSOR_SECRET_FILE").encode("ascii")) + self.ttl = session_ttl() + self.idempotency_ttl = idempotency_ttl() + + def open(self): + self.pool.open() + + def close(self): + self.pool.close() + + @contextmanager + def connection(self): + try: + with self.pool.connection() as connection: + yield connection + except (psycopg.OperationalError, psycopg.InterfaceError, PoolTimeout, TooManyRequests, + psycopg.errors.QueryCanceled, psycopg.errors.LockNotAvailable): + get_current_span().add_event("postgresql.unavailable") + raise ApiError(503, "unavailable", "Хранилище временно недоступно") from None + + def ready(self): + try: + with self.connection() as connection: + row = connection.execute( + "SELECT version FROM schema_migrations WHERE version=%s", ("004_attachment_jobs.sql",) + ).fetchone() + if not row: + raise ApiError(503, "unavailable", "Схема ещё не готова") + except psycopg.errors.UndefinedTable: + raise ApiError(503, "unavailable", "Схема ещё не готова") from None + return {"status": "ok"} + + def create_user(self, body): + password_hash = hash_password(body.password) + try: + with self.connection() as connection: + row = connection.execute( + "INSERT INTO users(id,username,display_name,password_hash) VALUES (%s,%s,%s,%s) RETURNING " + + USER_FIELDS, + (uuid4(), body.username, body.display_name, password_hash), + ).fetchone() + return serialize(row) + except psycopg.errors.UniqueViolation: + raise ApiError(409, "conflict", "Username уже занят") from None + + def create_session(self, username, password): + with self.connection() as connection: + row = connection.execute( + "SELECT " + USER_FIELDS + ", password_hash FROM users WHERE username=%s", (username,) + ).fetchone() + if not verify_password(row["password_hash"] if row else None, password) or row is None: + raise unauthorized() + token = secrets.token_urlsafe(32) + with self.connection() as connection: + session = connection.execute(""" + INSERT INTO sessions(token_hash,user_id,created_at,expires_at) + VALUES (%s,%s,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP + %s * INTERVAL '1 second') + RETURNING expires_at + """, (token_hash(token), row["id"], self.ttl)).fetchone() + user = {key: value for key, value in row.items() if key != "password_hash"} + return {"token": token, "token_type": "Bearer", "expires_at": serialize(session["expires_at"]), + "user": serialize(user)} + + def authenticate(self, token): + with self.connection() as connection: + row = connection.execute(""" + SELECT user_id FROM sessions + WHERE token_hash=%s AND expires_at > CURRENT_TIMESTAMP + """, (token_hash(token),)).fetchone() + if row is None: + raise unauthorized() + return row["user_id"] + + def logout(self, token): + with self.connection() as connection: + result = connection.execute("DELETE FROM sessions WHERE token_hash=%s", (token_hash(token),)) + if result.rowcount != 1: + raise unauthorized() + + def user(self, user_id): + with self.connection() as connection: + row = connection.execute("SELECT " + USER_FIELDS + " FROM users WHERE id=%s", (user_id,)).fetchone() + if not row: + raise unauthorized() + return serialize(row) + + def create_chat(self, user_id, body): + members = body.member_ids + if user_id not in members: + raise invalid("Неверный список участников") + with self.connection() as connection: + found = connection.execute("SELECT id FROM users WHERE id=ANY(%s)", (members,)).fetchall() + if len(found) != len(members): + raise invalid("Неверный список участников") + chat_id = uuid4() + # чат и участники коммитятся вместе + connection.execute("INSERT INTO chats(id,title) VALUES (%s,%s)", (chat_id, body.title)) + with connection.cursor() as cursor: + cursor.executemany( + "INSERT INTO chat_members(chat_id,user_id) VALUES (%s,%s)", + [(chat_id, member) for member in members], + ) + return serialize(self.require_chat(connection, user_id, chat_id)) + + def require_chat(self, connection, user_id, chat_id): + row = connection.execute( + "SELECT " + CHAT_FIELDS + """ FROM chats c WHERE c.id=%s + AND EXISTS (SELECT 1 FROM chat_members m WHERE m.chat_id=c.id AND m.user_id=%s) + """, (chat_id, user_id) + ).fetchone() + if row is None: + raise not_found() + return row + + def chat(self, user_id, chat_id): + with self.connection() as connection: + return serialize(self.require_chat(connection, user_id, chat_id)) + + def list_chats(self, user_id, limit, cursor): + scope = "chats:" + str(user_id) + after = self.pagination.decode(scope, cursor) if cursor is not None else None + condition = " AND (c.created_at,c.id) > (%s,%s)" if after else "" + with self.connection() as connection: + rows = connection.execute( + "SELECT " + CHAT_FIELDS + """ FROM chats c + WHERE EXISTS (SELECT 1 FROM chat_members m WHERE m.chat_id=c.id AND m.user_id=%s)""" + + condition + " ORDER BY c.created_at,c.id LIMIT %s", + [user_id, *(after or ()), limit + 1], + ).fetchall() + return self.pagination.page(serialize(rows), scope, limit) + + def create_message(self, user_id, chat_id, body, key): + path = f"/api/v1/chats/{chat_id}/messages" + scope = (user_id, "POST", path, key) + canonical = json.dumps(body.model_dump(mode="json"), sort_keys=True, ensure_ascii=False, separators=(",", ":")) + request_hash = hashlib.sha256(canonical.encode("utf-8")).hexdigest() + lock_data = json.dumps([str(user_id), "POST", path, key], separators=(",", ":")).encode() + lock_id = int.from_bytes(hashlib.sha256(lock_data).digest()[:8], "big", signed=True) + with self.connection() as connection: + self.require_chat(connection, user_id, chat_id) + # один ключ блокируется сразу для обеих реплик + connection.execute("SELECT pg_advisory_xact_lock(%s)", (lock_id,)) + saved = connection.execute(""" + SELECT request_hash,response_body,expires_at > clock_timestamp() AS active + FROM idempotency_keys WHERE user_id=%s AND method=%s AND path=%s AND request_key=%s + """, scope).fetchone() + if saved and saved["active"]: + if saved["request_hash"] != request_hash: + raise ApiError(409, "conflict", "С этим ключом уже отправлен другой запрос") + return saved["response_body"] + if saved: + connection.execute(""" + DELETE FROM idempotency_keys WHERE user_id=%s AND method=%s AND path=%s AND request_key=%s + """, scope) + if body.attachment_ids: + found = connection.execute( + "SELECT id,status FROM attachments WHERE chat_id=%s AND id=ANY(%s) FOR SHARE", + (chat_id, body.attachment_ids), + ).fetchall() + if len(found) != len(body.attachment_ids): + raise not_found() + if any(row["status"] == "failed" for row in found): + raise ApiError(409, "conflict", "Обработка вложения завершилась ошибкой") + row = connection.execute(""" + INSERT INTO messages(id,chat_id,sender_id,text) VALUES (%s,%s,%s,%s) + RETURNING id,chat_id,sender_id,text,created_at + """, (uuid4(), chat_id, user_id, body.text)).fetchone() + for position, attachment_id in enumerate(body.attachment_ids): + connection.execute( + "INSERT INTO message_attachments(message_id,attachment_id,chat_id,position) VALUES (%s,%s,%s,%s)", + (row["id"], attachment_id, chat_id, position), + ) + row["attachment_ids"] = body.attachment_ids + message = serialize(row) + connection.execute(""" + INSERT INTO idempotency_keys + (user_id,method,path,request_key,request_hash,message_id,response_status,response_body,expires_at) + VALUES (%s,%s,%s,%s,%s,%s,201,%s,clock_timestamp() + %s * INTERVAL '1 second') + """, (*scope, request_hash, row["id"], Jsonb(message), self.idempotency_ttl)) + return message + + def list_messages(self, user_id, chat_id, limit, cursor): + scope = "messages:" + str(chat_id) + after = self.pagination.decode(scope, cursor) if cursor is not None else None + condition = " AND (created_at,id) > (%s,%s)" if after else "" + with self.connection() as connection: + self.require_chat(connection, user_id, chat_id) + rows = connection.execute( + """SELECT m.id,m.chat_id,m.sender_id,m.text,m.created_at, + ARRAY(SELECT ma.attachment_id FROM message_attachments ma + WHERE ma.message_id=m.id ORDER BY ma.position) AS attachment_ids + FROM messages m WHERE chat_id=%s""" + + condition + " ORDER BY created_at,id LIMIT %s", + [chat_id, *(after or ()), limit + 1], + ).fetchall() + return self.pagination.page(serialize(rows), scope, limit) diff --git a/src/telemetry.py b/src/telemetry.py new file mode 100644 index 00000000..33690f90 --- /dev/null +++ b/src/telemetry.py @@ -0,0 +1,140 @@ +import json +import logging +import os +from time import perf_counter + +from opentelemetry import trace +from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter +from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter +from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter +from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler +from opentelemetry.sdk._logs.export import BatchLogRecordProcessor +from opentelemetry.sdk.metrics import MeterProvider +from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader +from opentelemetry.sdk.resources import Resource +from opentelemetry.sdk.trace import TracerProvider +from opentelemetry.sdk.trace.export import BatchSpanProcessor +from opentelemetry.trace import SpanKind, Status, StatusCode +from starlette.routing import Match + + +HTTP_BUCKETS = (0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10) +JOB_BUCKETS = (0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30) +HTTP_METHODS = frozenset({"GET", "POST", "DELETE", "HEAD", "OPTIONS", "PUT", "PATCH"}) + + +class Telemetry: + def __init__(self, service, instance): + self.service = service + resource = Resource.create({ + "service.name": service, + "service.version": "1.6.0", + "service.instance.id": instance, + "deployment.environment.name": "lab", + }) + endpoint = os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT", "http://otel-collector:4318").rstrip("/") + self.traces = TracerProvider(resource=resource, shutdown_on_exit=False) + self.traces.add_span_processor(BatchSpanProcessor( + OTLPSpanExporter(endpoint=f"{endpoint}/v1/traces", timeout=2), + max_queue_size=512, max_export_batch_size=128, schedule_delay_millis=1000, + )) + self.logs = LoggerProvider(resource=resource, shutdown_on_exit=False) + self.logs.add_log_record_processor(BatchLogRecordProcessor( + OTLPLogExporter(endpoint=f"{endpoint}/v1/logs", timeout=2), + max_queue_size=512, max_export_batch_size=128, schedule_delay_millis=1000, + )) + reader = PeriodicExportingMetricReader( + OTLPMetricExporter(endpoint=f"{endpoint}/v1/metrics", timeout=2), + export_interval_millis=2000, export_timeout_millis=2000, + ) + self.metrics = MeterProvider(resource=resource, metric_readers=[reader], shutdown_on_exit=False) + self.tracer = self.traces.get_tracer("messenger") + self.logger = logging.Logger("messenger.events") + self.logger.addHandler(LoggingHandler(logger_provider=self.logs)) + meter = self.metrics.get_meter("messenger") + self.requests = meter.create_counter("messenger_http_requests") + self.http_duration = meter.create_histogram( + "messenger_http_duration", unit="s", explicit_bucket_boundaries_advisory=HTTP_BUCKETS, + ) + self.deliveries = meter.create_counter("messenger_job_deliveries") + self.job_duration = meter.create_histogram( + "messenger_job_duration", unit="s", explicit_bucket_boundaries_advisory=JOB_BUCKETS, + ) + + def event(self, event, severity=logging.INFO, **fields): + context = trace.get_current_span().get_span_context() + entry = {"event": event, "service": self.service, **fields} + if context.is_valid: + entry["trace_id"] = f"{context.trace_id:032x}" + entry["span_id"] = f"{context.span_id:016x}" + self.logger.log(severity, json.dumps(entry, separators=(",", ":"))) + + def shutdown(self): + self.metrics.shutdown(timeout_millis=3000) + self.traces.shutdown() + self.logs.shutdown() + + +def route_template(request): + route = request.scope.get("route") + if route is not None: + return route.path + for candidate in request.app.router.routes: + if candidate.matches(request.scope)[0] is Match.FULL: + return candidate.path + return "unmatched" + + +async def observe_http(telemetry, request, call_next): + start = perf_counter() + response = None + method = request.method if request.method in HTTP_METHODS else "OTHER" + with telemetry.tracer.start_as_current_span( + f"HTTP {method}", kind=SpanKind.SERVER, record_exception=False, set_status_on_exception=False, + ) as span: + try: + response = await call_next(request) + return response + finally: + duration = perf_counter() - start + route = route_template(request) + status = response.status_code if response is not None else 500 + request_id = getattr(request.state, "request_id", "") + attrs = {"http_method": method, "http_route": route, "http_status_class": f"{status // 100}xx"} + telemetry.requests.add(1, attrs) + telemetry.http_duration.record(duration, attrs) + span.update_name(f"{method} {route}") + span.set_attributes({"http.request.method": method, "http.route": route, + "http.response.status_code": status, "request.id": request_id}) + if status >= 500: + span.set_status(Status(StatusCode.ERROR)) + telemetry.event("http.request", logging.ERROR if status >= 500 else logging.INFO, + request_id=request_id, method=method, route=route, status=status, + duration_ms=round(duration * 1000, 3)) + + +def observe_delivery(telemetry, queue, job_id, attachment_id, attempt, run): + start = perf_counter() + outcome = "error" + reason = "delivery_interrupted" + with telemetry.tracer.start_as_current_span( + f"{queue} process", kind=SpanKind.CONSUMER, record_exception=False, set_status_on_exception=False, + attributes={"messaging.system": "rabbitmq", "messaging.destination.name": queue, + "messaging.operation.type": "process", "messaging.message.id": str(job_id), + "attachment.id": str(attachment_id), "job.attempt": attempt}, + ) as span: + try: + outcome, reason = run() + finally: + duration = perf_counter() - start + attrs = {"job_type": queue, "job_outcome": outcome} + telemetry.deliveries.add(1, attrs) + telemetry.job_duration.record(duration, attrs) + span.set_attributes({"job.outcome": outcome, "job.reason": reason}) + failed = outcome in ("failed", "error", "retry") + if failed: + span.set_status(Status(StatusCode.ERROR)) + telemetry.event("job.process", logging.ERROR if failed else logging.INFO, + job_type=queue, job_id=str(job_id), attachment_id=str(attachment_id), + attempt=attempt, outcome=outcome, reason=reason, + duration_ms=round(duration * 1000, 3)) diff --git a/student-tests/observability.py b/student-tests/observability.py new file mode 100644 index 00000000..925be506 --- /dev/null +++ b/student-tests/observability.py @@ -0,0 +1,174 @@ +"""Verify the provisioned Grafana data sources on the dedicated local Lab 6 stack.""" + +import argparse +from base64 import b64encode +import json +import os +from pathlib import Path +import time +from urllib.parse import urlencode +from urllib.request import ProxyHandler, build_opener +from uuid import uuid4 + +from queue_recovery import Client, check, check_retry_limit, compose, wait_for + + +HTTP = build_opener(ProxyHandler({})) + + +class Grafana: + def __init__(self, base): + self.base = base.rstrip("/") + + def get(self, path, **params): + query = "?" + urlencode(params) if params else "" + try: + with HTTP.open(self.base + path + query, timeout=5) as response: + return json.load(response) + except (OSError, ValueError): + return None + + def source(self, name, path, **params): + return self.get(f"/api/datasources/proxy/uid/lab-{name}{path}", **params) + + def logs(self, service, **fields): + query = f'{{service_name="{service}"}} | json' + for key, value in fields.items(): + query += f" | {key} = {json.dumps(value)}" + result = self.source("loki", "/loki/api/v1/query_range", query=query, + start=str(time.time_ns() - 15 * 60 * 10**9), limit=50) + entries = [] + for stream in (result or {}).get("data", {}).get("result", []): + for record in stream["values"]: + entries.append(json.loads(record[1])) + return entries + + def metric(self, expression): + result = self.source("prometheus", "/api/v1/query", query=expression) + samples = (result or {}).get("data", {}).get("result", []) + return float(samples[0]["value"][1]) if samples else None + + +def spans(value): + if isinstance(value, dict): + if "spanId" in value and "name" in value: + yield value + else: + for child in value.values(): + yield from spans(child) + if isinstance(value, list): + for child in value: + yield from spans(child) + + +def correlated(grafana, service, span_name, **fields): + entries = wait_for(lambda: grafana.logs(service, **fields), f"Missing log for {service}: {fields}") + entry = entries[0] + trace_id, span_id = entry["trace_id"], entry["span_id"] + check(len(trace_id) == 32 and len(span_id) == 16, "Malformed trace identifiers") + trace = wait_for(lambda: grafana.source("tempo", "/api/traces/" + trace_id), + f"Trace missing in Tempo: {trace_id}") + span = next((span for span in spans(trace) if span["name"] == span_name), None) + check(span is not None, f"Span missing in Tempo: {span_name}") + for field, identifier in (("spanId", span_id), ("traceId", trace_id)): + encoded = b64encode(bytes.fromhex(identifier)).decode("ascii") + check(span[field] in (identifier, encoded), f"Log and trace {field} differ") + expected_kind = 2 if service == "messenger-api" else 5 + expected_name = "SPAN_KIND_SERVER" if expected_kind == 2 else "SPAN_KIND_CONSUMER" + check(span["kind"] in (expected_kind, expected_name), "Unexpected span kind") + attributes = {item["key"]: next(iter(item["value"].values())) for item in span.get("attributes", [])} + return {"log": entry, "trace": {"name": span_name, "kind": span["kind"], "attributes": attributes, + "events": [event["name"] for event in span.get("events", [])]}} + + +def postgres_incident(): + code = """ +import json +from urllib.error import HTTPError +from urllib.request import urlopen +try: + urlopen('http://127.0.0.1:8080/health/ready', timeout=12) +except HTTPError as error: + print(json.dumps({'status': error.code, 'request_id': error.headers.get('X-Request-Id')})) +""" + try: + compose("stop", "db") + observed = json.loads(compose("exec", "-T", "api1", "python", "-c", code)) + check(observed["status"] == 503 and observed["request_id"], "Database outage did not yield API 503") + return observed + finally: + compose("start", "db") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--base-url", default="http://127.0.0.1:8080") + parser.add_argument("--grafana-url", default="http://127.0.0.1:13006") + parser.add_argument("--output", type=Path) + args = parser.parse_args() + grafana = Grafana(args.grafana_url) + dashboard = wait_for(lambda: grafana.get("/api/dashboards/uid/lab-messenger"), + "Grafana dashboard was not provisioned") + client = Client(args.base_url) + alice, bob, _, chat = client.bootstrap() + marker = "lab6_content_" + uuid4().hex + message = client.message(alice, chat, marker) + request_id = message["headers"]["X-Request-Id"] + request = correlated(grafana, "messenger-api", "POST /api/v1/chats/{chat_id}/messages", + request_id=request_id) + attachment, _ = client.attachment(alice, chat) + client.wait_ready(bob, attachment) + delivery = correlated(grafana, "messenger-worker", "attachment.process.v1 process", + attachment_id=attachment["id"], outcome="ready") + + database = postgres_incident() + wait_for(lambda: client.call("GET", "/health/ready", schema="Health"), "API did not recover") + outage = correlated(grafana, "messenger-api", "GET /health/ready", request_id=database["request_id"]) + check("postgresql.unavailable" in outage["trace"]["events"], "Trace does not diagnose the PostgreSQL outage") + + try: + staging = check_retry_limit(client, alice, bob, chat) + failed = correlated(grafana, "messenger-worker", "attachment.process.v1 process", + attachment_id=staging["attachment_id"], outcome="failed") + check(failed["trace"]["attributes"]["job.reason"] == "staging_unavailable", + "Worker trace does not diagnose the staging failure") + finally: + compose("start", "worker") + + try: + compose("stop", "tempo") + during_tempo_stop = client.message(alice, chat, "Проверка работы при остановленном Tempo") + check(during_tempo_stop["status"] == 201, "Tempo outage stopped business requests") + finally: + compose("start", "tempo") + + metrics = {} + expressions = ( + "sum(messenger_http_requests_total)", + 'sum(messenger_http_requests_total{http_status_class="5xx"})', + "sum(messenger_http_duration_seconds_count)", + 'sum(messenger_job_deliveries_total{job_outcome="ready"})', + 'sum(messenger_job_deliveries_total{job_outcome="failed"})', + "sum(messenger_job_duration_seconds_count)", + ) + for expression in expressions: + metrics[expression] = wait_for(lambda: grafana.metric(expression), f"Missing metric: {expression}") + check(marker not in json.dumps(grafana.logs("messenger-api", request_id=request_id)), + "Message content leaked into the API log") + check(marker not in json.dumps(request["trace"]), "Message content leaked into the API trace") + report = { + "dashboard": dashboard["dashboard"]["uid"], "metrics": metrics, + "api_correlation": request, "worker_correlation": delivery, + "postgresql_incident": outage, "staging_incident": failed, "staging_attempts": staging["attempts"], + "message_status_with_tempo_stopped": during_tempo_stop["status"], "message_marker_absent": True, + } + rendered = json.dumps(report, ensure_ascii=False, indent=2) + if args.output: + args.output.write_text(rendered + "\n", encoding="utf-8") + print("PASS: metrics, structured logs and correlated traces for API and worker, plus two incidents.") + + +if __name__ == "__main__": + for variable in ("NO_PROXY", "no_proxy"): + os.environ[variable] = ",".join(filter(None, (os.environ.get(variable), "127.0.0.1", "localhost"))) + main() diff --git a/student-tests/queue_recovery.py b/student-tests/queue_recovery.py new file mode 100644 index 00000000..8bb3bd78 --- /dev/null +++ b/student-tests/queue_recovery.py @@ -0,0 +1,172 @@ +"""Exercise the dedicated local Compose project using synthetic attachments.""" + +import argparse +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import time + + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tests")) +from client import Client, Failure, check +from image_probe import jpeg_size + + +def compose(*args): + return subprocess.check_output(["docker", "compose", *args], cwd=ROOT, text=True, encoding="utf-8") + + +def wait_for(action, description): + deadline = time.monotonic() + 70 + while time.monotonic() < deadline: + try: + result = action() + if result: + return result + except (Failure, subprocess.CalledProcessError): + pass + time.sleep(0.5) + raise Failure(description) + + +def queue_depth(): + output = subprocess.check_output( + ["docker", "compose", "exec", "-T", "broker", "rabbitmqctl", "-q", "list_queues", + "name", "messages_ready", "messages_unacknowledged"], + cwd=ROOT, text=True, encoding="utf-8", stderr=subprocess.PIPE, + ) + for line in output.splitlines(): + fields = line.split() + if fields and fields[0] == "attachment.process.v1": + return tuple(map(int, fields[1:])) + return None + + +def api_instances(client): + instances = {client.call("GET", "/health/ready", schema="Health")["headers"]["X-Instance-Id"] + for _ in range(4)} + return instances if len(instances) == 2 else None + + +def duplicate(attachment_id): + code = """ +import sys +from src.jobs import QUEUE, broker, database, publish +with database() as db, broker() as connection: + job = db.execute('SELECT * FROM attachment_jobs WHERE attachment_id=%s', (sys.argv[1],)).fetchone() + channel = connection.channel() + channel.queue_declare(queue=QUEUE, durable=True) + channel.confirm_delivery() + publish(channel, job, job['attempts']) +""" + compose("exec", "-T", "dispatcher", "python", "-c", code, attachment_id) + + +def check_retry_limit(client, alice, bob, chat): + compose("stop", "worker") + attachment, _ = client.attachment(alice, chat) + path = "/api/v1/attachments/" + attachment["id"] + # Remove only the staging object created for this synthetic case. + code = """ +import sys +from uuid import UUID +from src.objects import Objects +objects = Objects() +try: + objects.delete('staging/' + UUID(sys.argv[1]).hex) +finally: + objects.close() +""" + compose("exec", "-T", "api1", "python", "-c", code, attachment["id"]) + compose("start", "worker") + + def failed(): + result = client.call("GET", path, actor=bob, schema="Attachment")["json"] + return result if result["status"] == "failed" else None + + terminal = wait_for(failed, "Missing staging object did not reach failed") + check(terminal["error_code"] == "retry_exhausted", "Unexpected final error") + client.call("GET", path + "/content", 409, actor=bob) + code = """ +import sys +from src.jobs import MAX_ATTEMPTS, database +with database() as db: + job = db.execute('SELECT attempts,publish_at FROM attachment_jobs WHERE attachment_id=%s', + (sys.argv[1],)).fetchone() + assert job['attempts'] == MAX_ATTEMPTS and job['publish_at'] is None + print(job['attempts']) +""" + attempts = int(compose("exec", "-T", "worker", "python", "-c", code, attachment["id"]).strip()) + return {"attachment_id": attachment["id"], "attempts": attempts, + "status": terminal["status"], "error_code": terminal["error_code"]} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--base-url", default="http://127.0.0.1:8080") + parser.add_argument("--output", type=Path) + args = parser.parse_args() + client = Client(args.base_url) + alice, bob, _, chat = client.bootstrap() + compose("stop", "worker") + try: + check(queue_depth() == (0, 0), "Expected an idle lab queue before the test") + attachment, original = client.attachment(alice, chat) + path = "/api/v1/attachments/" + attachment["id"] + message = client.message(alice, chat, "", attachments=[attachment["id"]])["json"] + client.call("GET", path + "/content", 409, actor=bob) + wait_for(lambda: queue_depth() == (1, 0), "RabbitMQ did not receive the job") + compose("stop", "dispatcher") + old_instances = wait_for(lambda: api_instances(client), "Expected two ready API replicas") + compose("restart", "api1", "api2", "broker") + new_instances = wait_for(lambda: api_instances(client), "Both API replicas did not come back") + check(old_instances.isdisjoint(new_instances), "An API process did not restart") + wait_for(lambda: queue_depth() == (1, 0), "Job did not survive RabbitMQ restart") + client.call("GET", path + "/content", 409, actor=bob) + history = client.call("GET", "/api/v1/chats/" + chat["id"] + "/messages", actor=bob, + schema="MessagePage")["json"] + check(message in history["items"], "Message missing after API restart") + compose("start", "worker") + ready = client.wait_ready(bob, attachment) + downloaded = client.call("GET", path + "/content", actor=bob)["bytes"] + check(downloaded == original, "Original bytes changed") + thumbnail_path = path + "/content?variant=thumbnail" + image = client.call("GET", thumbnail_path, actor=bob)["bytes"] + check(jpeg_size(image) == (256, 160), "Unexpected thumbnail dimensions") + check(len(ready["variants"]) == 1, "Expected exactly one variant") + check(ready["variants"][0]["sha256"] == hashlib.sha256(image).hexdigest(), "Thumbnail checksum mismatch") + wait_for(lambda: queue_depth() == (0, 0), "Worker did not acknowledge the job") + compose("stop", "worker") + compose("start", "dispatcher") + duplicate(attachment["id"]) + wait_for(lambda: queue_depth() == (1, 0), "Duplicate was not published") + compose("start", "worker") + wait_for(lambda: queue_depth() == (0, 0), "Duplicate was not acknowledged") + check(client.call("GET", path, actor=bob, schema="Attachment")["json"] == ready, + "Duplicate changed ready metadata") + check(client.call("GET", thumbnail_path, actor=bob)["bytes"] == image, "Duplicate changed JPEG") + result = { + "attachment_id": attachment["id"], "message_id": message["id"], "upload_status": 202, + "content_while_queued": 409, "queued_jobs_after_broker_restart_with_dispatcher_stopped": 1, + "api_instance_ids_before": sorted(old_instances), "api_instance_ids_after": sorted(new_instances), + "message_preserved_after_restart": True, "final_status": ready["status"], + "original_bytes_match": True, "thumbnail": ready["variants"][0], "duplicate_acknowledged": True, + "duplicate_preserved_metadata_and_bytes": True, + "retry_limit": check_retry_limit(client, alice, bob, chat), + } + rendered = json.dumps(result, indent=2) + if args.output: + args.output.write_text(rendered + "\n", encoding="utf-8") + print(rendered) + finally: + compose("start", "dispatcher", "worker") + + +if __name__ == "__main__": + for variable in ("NO_PROXY", "no_proxy"): + os.environ[variable] = ",".join(filter(None, (os.environ.get(variable), "127.0.0.1", "localhost"))) + main()