feat: propagate trace context through outbox and add pipeline saturation metrics

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-11 19:54:37 +03:00
co-authored by Claude Opus 5.5
parent ff0073e8e3
commit 72cfa9aaf6
64 changed files with 4699 additions and 552 deletions
+222
View File
@@ -0,0 +1,222 @@
"""Сборка провайдеров SDK OpenTelemetry и экспортёров OTLP/HTTP.
Единственный модуль пакета, который импортирует SDK, экспортёр и `requests`
(design change `job-trace-propagation`, решение 7): его импортирует только
`core.start()`, поэтому процесс с выключенной телеметрией, уборщик и команда
replay модулей SDK, protobuf и HTTP-клиента экспортёра не загружают. Остальные
модули пакета — только `opentelemetry-api`.
Всё — из `[telemetry]` (design change `otel-telemetry`, решение 8): ресурс
конструктором без детекторов, у параметров явные значения, `atexit` SDK
выключен. Sampler — `ParentBased(ALWAYS_ON)` (решение 5): корни выбираются
всегда, удалённый родитель из задания передаёт свой флаг выборки.
"""
from collections.abc import Mapping
from dataclasses import dataclass
from typing import Any
# транспорт экспортёров OTLP/HTTP (зависимость opentelemetry-exporter-otlp-
# proto-http): своя сессия без окружения
import requests
from opentelemetry.exporter.otlp.proto.http import Compression
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, LogRecordLimits
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
from opentelemetry.sdk.metrics import (
AlwaysOffExemplarFilter,
Counter,
Histogram,
MeterProvider,
ObservableCounter,
ObservableGauge,
ObservableUpDownCounter,
UpDownCounter,
)
from opentelemetry.sdk.metrics.export import (
AggregationTemporality,
PeriodicExportingMetricReader,
)
from opentelemetry.sdk.metrics.view import (
ExplicitBucketHistogramAggregation,
View,
)
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import SpanLimits, TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.sdk.trace.sampling import ALWAYS_ON, ParentBased
from src.config.settings import Telemetry as TelemetrySettings
from src.utils.constants import (
HTTP_DURATION_BUCKETS,
JOB_DURATION_BUCKETS,
METRIC_HTTP_SERVER_DURATION,
METRIC_JOB_DURATION,
METRIC_JOB_TIME_TO_READY,
TELEMETRY_LOG_ATTRIBUTE_LENGTH,
TELEMETRY_LOGS_PATH,
TELEMETRY_MAX_ATTRIBUTES,
TELEMETRY_METRICS_PATH,
TELEMETRY_SPAN_ATTRIBUTE_LENGTH,
TELEMETRY_TRACES_PATH,
TIME_TO_READY_BUCKETS,
)
# все инструменты — cumulative: Prometheus забирает накопленное (решение 3)
_CUMULATIVE = dict.fromkeys(
(
Counter,
UpDownCounter,
Histogram,
ObservableCounter,
ObservableUpDownCounter,
ObservableGauge,
),
AggregationTemporality.CUMULATIVE,
)
# границы buckets histogram по имени инструмента
_BUCKETS = {
METRIC_HTTP_SERVER_DURATION: HTTP_DURATION_BUCKETS,
METRIC_JOB_DURATION: JOB_DURATION_BUCKETS,
METRIC_JOB_TIME_TO_READY: TIME_TO_READY_BUCKETS,
}
@dataclass(frozen=True, slots=True)
class Providers:
tracer_provider: TracerProvider
meter_provider: MeterProvider
logger_provider: LoggerProvider
def build(
*,
resource: Mapping[str, Any],
config: TelemetrySettings,
exporters: Any | None,
) -> Providers:
"""Провайдеры трасс, метрик и логов. `exporters` — получатели вместо OTLP
(`core.Exporters`, быстрые тесты) или `None`."""
if exporters is None:
exporters = otlp_exporters(config)
attributes = Resource(dict(resource))
timeout_ms = config.export_timeout_seconds * 1000
delay_ms = config.schedule_delay_seconds * 1000
tracer_provider = TracerProvider(
sampler=ParentBased(ALWAYS_ON),
resource=attributes,
shutdown_on_exit=False,
span_limits=SpanLimits(
max_attributes=TELEMETRY_MAX_ATTRIBUTES,
max_events=TELEMETRY_MAX_ATTRIBUTES,
max_links=TELEMETRY_MAX_ATTRIBUTES,
max_span_attributes=TELEMETRY_MAX_ATTRIBUTES,
max_event_attributes=TELEMETRY_MAX_ATTRIBUTES,
max_link_attributes=TELEMETRY_MAX_ATTRIBUTES,
max_attribute_length=TELEMETRY_SPAN_ATTRIBUTE_LENGTH,
max_span_attribute_length=TELEMETRY_SPAN_ATTRIBUTE_LENGTH,
),
)
tracer_provider.add_span_processor(
BatchSpanProcessor(
exporters.spans,
max_queue_size=config.max_queue_size,
schedule_delay_millis=delay_ms,
max_export_batch_size=config.max_export_batch_size,
export_timeout_millis=timeout_ms,
),
)
meter_provider = MeterProvider(
metric_readers=[exporters.metrics],
resource=attributes,
exemplar_filter=AlwaysOffExemplarFilter(),
shutdown_on_exit=False,
views=[
View(
instrument_name=name,
aggregation=ExplicitBucketHistogramAggregation(
boundaries=boundaries,
),
)
for name, boundaries in _BUCKETS.items()
],
)
logger_provider = LoggerProvider(
resource=attributes,
shutdown_on_exit=False,
log_record_limits=LogRecordLimits(
max_attributes=TELEMETRY_MAX_ATTRIBUTES,
max_attribute_length=TELEMETRY_LOG_ATTRIBUTE_LENGTH,
),
)
logger_provider.add_log_record_processor(
BatchLogRecordProcessor(
exporters.logs,
schedule_delay_millis=delay_ms,
max_export_batch_size=config.max_export_batch_size,
export_timeout_millis=timeout_ms,
max_queue_size=config.max_queue_size,
),
)
return Providers(
tracer_provider=tracer_provider,
meter_provider=meter_provider,
logger_provider=logger_provider,
)
def export_session() -> requests.Session:
"""Сессия отправки без окружения: `HTTP(S)_PROXY`, `NO_PROXY`, `.netrc`
и `REQUESTS_CA_BUNDLE` на неё не действуют — данные идут только по адресу
`[telemetry]` (verify S5 change `otel-telemetry`, как с `OTEL_*`)."""
session = requests.Session()
session.trust_env = False
return session
def otlp_exporters(config: TelemetrySettings) -> Any:
"""OTLP/HTTP protobuf только из `[telemetry]`: адрес, срок, без
заголовков и сжатия, своя сессия без прокси окружения."""
# тип получателей живёт в core: он нужен быстрым тестам без этого модуля
from src.infra.telemetry.core import Exporters
timeout = config.export_timeout_seconds
endpoint = config.otlp_endpoint
return Exporters(
spans=OTLPSpanExporter(
endpoint=endpoint + TELEMETRY_TRACES_PATH,
headers={},
timeout=timeout,
compression=Compression.NoCompression,
session=export_session(),
),
metrics=PeriodicExportingMetricReader(
OTLPMetricExporter(
endpoint=endpoint + TELEMETRY_METRICS_PATH,
headers={},
timeout=timeout,
compression=Compression.NoCompression,
preferred_temporality=_CUMULATIVE,
session=export_session(),
),
export_interval_millis=config.metric_export_interval_seconds
* 1000,
export_timeout_millis=timeout * 1000,
),
logs=OTLPLogExporter(
endpoint=endpoint + TELEMETRY_LOGS_PATH,
headers={},
timeout=timeout,
compression=Compression.NoCompression,
session=export_session(),
),
)