Add the OpenTelemetry API and SDK, the OTLP over HTTP exporter and the FastAPI and asyncpg instrumentations to the lock, and a platform module that builds one resource per process (service.name, service.version, service.instance.id as hostname and pid, deployment.environment.name from OTEL_RESOURCE_ATTRIBUTES), batch processors for traces and logs, a periodic metric reader, PostgreSQL client spans and a bounded shutdown in a daemon thread instead of the 30 s flush of the SDK. The SDK stays off without a Collector address or with OTEL_SDK_DISABLED. The sampler lets only server, consumer and producer spans open a trace, so readiness probes, outbox polls and sweeps do not become one-span traces. Log records carry trace_id and span_id in stdout and go to OTLP through a handler that keeps only the allowlisted fields, and deferred event subscribers now run in the context the event was emitted in, so audit records stay linked to their request or job. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
4.4 KiB
4.4 KiB
1. Зависимости и платформа телеметрии
- 1.1 Зависимости
opentelemetry-sdk,opentelemetry-exporter-otlp-proto-http,opentelemetry-instrumentation-fastapi,opentelemetry-instrumentation-asyncpg,faststream[rabbit,otel]вpyproject.tomlиuv.lock - 1.2
PlatformSettings:otel_sdk_disabled,otel_exporter_otlp_endpoint,otel_service_name,telemetry_shutdown_seconds - 1.3
shared/infrastructure/telemetry.py: resource, samplerParentBased(ServerRoots), batch-экспорт трёх сигналов, View без метрик FastStream,OtlpLogHandler, инструментация asyncpg, ограниченныйshutdown,tag_request - 1.4 Журнал:
trace_id/span_idв записи и вPLATFORM_FIELDS;EventBusвыполняет отложенных подписчиков в контексте события - 1.5 Проверка группы: unit-тесты — выключенный SDK не ставит провайдеры, запись с span несёт
trace_id/span_id, OTLP-запись содержит только allowlist, подписчик получает контекст события
2. Зона attachments
- 2.1 Порт
JobObserver, адаптерOtelJobObserver(counter, histogram с buckets, атрибуты и статус span), провайдер вWorkerProvider - 2.2 Точка входа worker: длительность, исход,
job.processedв журнал - 2.3 Проверка группы: тест адаптера на
InMemoryMetricReaderиInMemorySpanExporter— labelsjob.type/outcome, атрибуты иERRORдляfailed
3. Сборка процессов
- 3.1
main.py: телеметрия вcreate_app, FastAPI-инструментация без/health/*и внутренних spans,messenger.request_idиз конвейера, остановка в lifespan - 3.2
worker.py: телеметрияmessenger-worker,RabbitTelemetryMiddlewareна брокере, остановка после FastStream;relay.py: телеметрияmessenger-relay - 3.3 Проверка группы: тест server span и HTTP-метрики на
create_appс in-memory провайдерами — шаблон маршрута, без/health,messenger.request_id;make lint,make student-test
4. Стек наблюдаемости
- 4.1
infra/otel/collector.yaml,infra/prometheus/prometheus.ymlи recording rules,infra/loki/loki.yaml,infra/tempo/tempo.yamlиз.prep/lab6 - 4.2
infra/grafana/provisioning, dashboardsmessenger-apiиmessenger-pipelineуровня «3» - 4.3
compose.yaml:healthtools,otel-collector,prometheus,loki,tempo,grafana, volumes, секрет Grafana, сетиbackend/edge, переменные OTel уapi,relay,worker;.env.example - 4.4
scripts/secrets-lab6.sh,scripts/obs-validate.sh,scripts/obs_check.py; целиsecrets,obs-validate,telemetry-check,obs-evidence - 4.5 Проверка группы:
make obs-validate,docker compose config --quiet,make upиз чистого состояния — все сервисыhealthy, порты наблюдаемости только на127.0.0.1
5. Проверка на стенде
- 5.1
make test,make test-persistence ACTION_SCRIPT=scripts/restart.sh,make test-failover ACTION_SCRIPT=scripts/stop-one.shдля обеих реплик сmake restore,make level3 - 5.2
obs_check.py grafana,dashboards --strict,request,job,leaks, cardinality, история после рестарта хранилищ,make testпри остановленном Collector - 5.3 Проверка группы:
make check,make validate,make lint,make student-test
6. Отчёт
- 6.1
evidence/: стенд, smoke, persistence, failover, level3, obs-validate, grafana, dashboards, trace-request, trace-job, leaks, cardinality, telemetry-restart, student-tests, contract-checks - 6.2
REPORT.md: шапка, запуск из чистого clone, архитектура и решения, роли, назначение хранилищ, соответствие сигналов и переменных, строки уровня «3», таблица отказов уровня «3»