454 lines
17 KiB
Python
454 lines
17 KiB
Python
"""Юнит-тесты телеметрии (лаба 6): настройки, SDK, middleware, журнал.
|
|
|
|
Без стенда и сети: SDK собирается с in-memory экспортёрами
|
|
(`sdk.Exporters`), приложение — маленький FastAPI с теми же middleware,
|
|
что у API. Запуск — `make unit-test`; в `make student-test` и
|
|
`make test-isolated` они идут вместе с остальными.
|
|
"""
|
|
|
|
import logging
|
|
import re
|
|
import threading
|
|
import time
|
|
import uuid
|
|
from collections.abc import Iterator
|
|
|
|
import pytest
|
|
from fastapi import FastAPI
|
|
from opentelemetry.sdk._logs.export import InMemoryLogRecordExporter
|
|
from opentelemetry.sdk.metrics.export import InMemoryMetricReader
|
|
from opentelemetry.sdk.trace.export import SpanExportResult
|
|
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
|
|
from opentelemetry.trace import SpanKind
|
|
from starlette.testclient import TestClient
|
|
|
|
from src import log as app_log
|
|
from src import telemetry
|
|
from src.api.request_id import RequestIdMiddleware
|
|
from src.api.tracing import HttpTelemetryMiddleware, RouteTemplates
|
|
from src.config import ConfigError, Settings
|
|
from src.config import Telemetry as TelemetrySettings
|
|
from src.constants import APP_VERSION, SERVICE_API
|
|
from src.telemetry import sdk
|
|
|
|
pytestmark = pytest.mark.unit
|
|
|
|
ENDPOINT = {"OTEL_EXPORTER_OTLP_ENDPOINT": "http://otel-collector:4318"}
|
|
UUID_RE = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-")
|
|
# метки, которых не должно быть у метрик (contracts/observability.md)
|
|
FORBIDDEN_LABEL_PARTS = ("user", "chat", "message", "attachment", "request_id", "url")
|
|
|
|
|
|
class Pipeline:
|
|
"""Собранный SDK с in-memory экспортёрами и доступ к результату."""
|
|
|
|
def __init__(self, settings: TelemetrySettings) -> None:
|
|
self.spans = InMemorySpanExporter()
|
|
self.metrics = InMemoryMetricReader()
|
|
self.logs = InMemoryLogRecordExporter()
|
|
session = sdk.start(
|
|
settings,
|
|
service_name=SERVICE_API,
|
|
instance_id="test-instance",
|
|
exporters=sdk.Exporters(self.spans, self.metrics, self.logs),
|
|
)
|
|
assert session is not None
|
|
self.session = session
|
|
|
|
def points(self, name: str) -> list:
|
|
data = self.metrics.get_metrics_data()
|
|
found = []
|
|
for resource in data.resource_metrics if data else ():
|
|
for scope in resource.scope_metrics:
|
|
for metric in scope.metrics:
|
|
if metric.name == name:
|
|
found.extend(metric.data.data_points)
|
|
return found
|
|
|
|
|
|
@pytest.fixture
|
|
def pipeline() -> Iterator[Pipeline]:
|
|
built = Pipeline(TelemetrySettings.from_env(ENDPOINT))
|
|
yield built
|
|
built.session.shutdown(1.0)
|
|
assert not telemetry.enabled()
|
|
|
|
|
|
def make_app(session) -> FastAPI:
|
|
"""Мини-API: те же middleware и шаблоны маршрутов, что в src.main."""
|
|
app = FastAPI()
|
|
|
|
@app.get("/api/v1/chats/{chat_id}/messages")
|
|
async def history(chat_id: str) -> dict:
|
|
return {"items": []}
|
|
|
|
@app.get("/api/v1/attachments/{attachment_id}/content")
|
|
async def content(attachment_id: str) -> dict:
|
|
return {}
|
|
|
|
@app.get("/api/v1/attachments/{attachment_id}")
|
|
async def meta(attachment_id: str) -> dict:
|
|
return {}
|
|
|
|
@app.get("/health/live")
|
|
async def live() -> dict:
|
|
return {"status": "ok"}
|
|
|
|
@app.get("/api/v1/boom")
|
|
async def boom() -> dict:
|
|
raise RuntimeError("secret detail must not leak")
|
|
|
|
app.add_middleware(RequestIdMiddleware, instance_id="test-instance")
|
|
if session is not None:
|
|
app.add_middleware(HttpTelemetryMiddleware, routes=RouteTemplates(app))
|
|
return app
|
|
|
|
|
|
# --- настройки ---------------------------------------------------------------------
|
|
|
|
|
|
def test_settings_default_is_off() -> None:
|
|
settings = Settings.from_env({})
|
|
assert not settings.telemetry.enabled
|
|
assert sdk.start(settings.telemetry, service_name="x", instance_id="y") is None
|
|
assert not telemetry.enabled()
|
|
|
|
|
|
def test_settings_full_telemetry_by_default_when_endpoint_set() -> None:
|
|
settings = TelemetrySettings.from_env(ENDPOINT)
|
|
assert settings.enabled
|
|
assert settings.sample_ratio == 1.0
|
|
assert settings.buckets == "default"
|
|
assert settings.metric_interval_ms == 15_000
|
|
assert settings.environment == "lab"
|
|
|
|
|
|
def test_settings_knobs() -> None:
|
|
settings = TelemetrySettings.from_env(
|
|
{
|
|
**ENDPOINT,
|
|
"OTEL_TRACES_SAMPLER_ARG": "0.1",
|
|
"OTEL_METRIC_EXPORT_INTERVAL": "30000",
|
|
"TELEMETRY_HISTOGRAM_BUCKETS": "coarse",
|
|
"OTEL_RESOURCE_ATTRIBUTES": "deployment.environment.name=bench",
|
|
}
|
|
)
|
|
assert (settings.sample_ratio, settings.metric_interval_ms) == (0.1, 30_000)
|
|
assert (settings.buckets, settings.environment) == ("coarse", "bench")
|
|
off = TelemetrySettings.from_env({**ENDPOINT, "OTEL_SDK_DISABLED": "true"})
|
|
assert not off.enabled
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("name", "value"),
|
|
[
|
|
("OTEL_EXPORTER_OTLP_PROTOCOL", "grpc"),
|
|
("OTEL_EXPORTER_OTLP_ENDPOINT", "otel-collector:4318"),
|
|
("OTEL_EXPORTER_OTLP_ENDPOINT", "http://otel-collector:4318/v1/traces"),
|
|
("OTEL_SDK_DISABLED", "yes"),
|
|
("OTEL_TRACES_SAMPLER_ARG", "1.5"),
|
|
("OTEL_METRIC_EXPORT_INTERVAL", "10"),
|
|
("TELEMETRY_HISTOGRAM_BUCKETS", "fine"),
|
|
("OTEL_RESOURCE_ATTRIBUTES", "service.name=evil"),
|
|
("OTEL_RESOURCE_ATTRIBUTES", "deployment.environment.name=Bad Name"),
|
|
],
|
|
)
|
|
def test_settings_reject_bad_values(name: str, value: str) -> None:
|
|
with pytest.raises(ConfigError, match=name.split("_")[0]):
|
|
Settings.from_env({**ENDPOINT, name: value})
|
|
|
|
|
|
# --- HTTP --------------------------------------------------------------------------
|
|
|
|
|
|
def test_http_span_and_metric_use_route_template(pipeline: Pipeline) -> None:
|
|
chat_id = str(uuid.uuid4())
|
|
with TestClient(make_app(pipeline.session)) as client:
|
|
response = client.get(
|
|
f"/api/v1/chats/{chat_id}/messages?cursor=abc",
|
|
headers={"X-Request-Id": "unit-rid-1", "Authorization": "Bearer t0ken"},
|
|
)
|
|
assert response.status_code == 200
|
|
(span,) = pipeline.spans.get_finished_spans()
|
|
assert span.kind == SpanKind.SERVER
|
|
assert span.name == "GET /api/v1/chats/{chat_id}/messages"
|
|
attrs = dict(span.attributes)
|
|
assert attrs["http.route"] == "/api/v1/chats/{chat_id}/messages"
|
|
assert attrs["http.response.status_code"] == 200
|
|
assert attrs["messenger.request_id"] == "unit-rid-1"
|
|
flat = repr(attrs)
|
|
for leaked in (chat_id, "t0ken", "cursor"):
|
|
assert leaked not in flat
|
|
resource = dict(span.resource.attributes)
|
|
assert resource == {
|
|
"service.name": SERVICE_API,
|
|
"service.version": APP_VERSION,
|
|
"service.instance.id": "test-instance",
|
|
"deployment.environment.name": "lab",
|
|
}
|
|
|
|
(point,) = pipeline.points(telemetry.HTTP_DURATION)
|
|
assert dict(point.attributes) == {
|
|
"http.request.method": "GET",
|
|
"http.route": "/api/v1/chats/{chat_id}/messages",
|
|
"http.response.status_code": 200,
|
|
"http.response.status_class": "2xx",
|
|
}
|
|
assert point.count == 1
|
|
assert point.explicit_bounds == tuple(
|
|
sdk.BUCKETS["default"][telemetry.HTTP_DURATION]
|
|
)
|
|
|
|
|
|
def test_more_specific_template_wins(pipeline: Pipeline) -> None:
|
|
with TestClient(make_app(pipeline.session)) as client:
|
|
client.get(f"/api/v1/attachments/{uuid.uuid4()}/content")
|
|
client.get(f"/api/v1/attachments/{uuid.uuid4()}")
|
|
names = sorted(span.name for span in pipeline.spans.get_finished_spans())
|
|
assert names == [
|
|
"GET /api/v1/attachments/{attachment_id}",
|
|
"GET /api/v1/attachments/{attachment_id}/content",
|
|
]
|
|
|
|
|
|
def test_unknown_path_and_method_do_not_create_labels(pipeline: Pipeline) -> None:
|
|
with TestClient(make_app(pipeline.session)) as client:
|
|
client.get(f"/scanner/{uuid.uuid4()}")
|
|
client.request("PROPFIND", "/api/v1/boom")
|
|
for point in pipeline.points(telemetry.HTTP_DURATION):
|
|
attrs = dict(point.attributes)
|
|
assert attrs["http.request.method"] in ("GET", "_OTHER")
|
|
assert not UUID_RE.search(repr(attrs))
|
|
unknown = [s for s in pipeline.spans.get_finished_spans() if s.name == "GET"]
|
|
assert len(unknown) == 1
|
|
assert "http.route" not in unknown[0].attributes
|
|
|
|
|
|
def test_health_is_not_traced(pipeline: Pipeline) -> None:
|
|
with TestClient(make_app(pipeline.session)) as client:
|
|
assert client.get("/health/live").status_code == 200
|
|
assert pipeline.spans.get_finished_spans() == ()
|
|
assert pipeline.points(telemetry.HTTP_DURATION) == []
|
|
|
|
|
|
def test_server_error_marks_span_without_message(pipeline: Pipeline) -> None:
|
|
with TestClient(make_app(pipeline.session), raise_server_exceptions=False) as c:
|
|
assert c.get("/api/v1/boom").status_code == 500
|
|
(span,) = pipeline.spans.get_finished_spans()
|
|
assert span.status.is_ok is False
|
|
assert span.attributes["error.type"] == "RuntimeError"
|
|
assert span.attributes["http.response.status_code"] == 500
|
|
assert "secret detail" not in repr(span.attributes)
|
|
assert span.events == ()
|
|
(point,) = pipeline.points(telemetry.HTTP_DURATION)
|
|
assert point.attributes["http.response.status_class"] == "5xx"
|
|
|
|
|
|
def test_metric_labels_are_low_cardinality(pipeline: Pipeline) -> None:
|
|
with TestClient(make_app(pipeline.session)) as client:
|
|
for _ in range(5):
|
|
client.get(
|
|
f"/api/v1/chats/{uuid.uuid4()}/messages",
|
|
headers={"X-Request-Id": uuid.uuid4().hex},
|
|
)
|
|
points = pipeline.points(telemetry.HTTP_DURATION)
|
|
assert len(points) == 1
|
|
assert points[0].count == 5
|
|
for key in points[0].attributes:
|
|
assert not any(part in key for part in FORBIDDEN_LABEL_PARTS), key
|
|
|
|
|
|
def test_disabled_app_has_no_telemetry_middleware() -> None:
|
|
app = make_app(None)
|
|
with TestClient(app) as client:
|
|
assert client.get("/health/live").status_code == 200
|
|
assert not any(m.cls is HttpTelemetryMiddleware for m in app.user_middleware)
|
|
|
|
|
|
# --- span хранилищ, задания, relay -------------------------------------------------
|
|
|
|
|
|
def test_child_span_only_under_a_root(pipeline: Pipeline) -> None:
|
|
with telemetry.child_span("postgresql read", {"db.system.name": "postgresql"}):
|
|
pass
|
|
assert pipeline.spans.get_finished_spans() == ()
|
|
with (
|
|
telemetry.root_span("process q", kind=SpanKind.CONSUMER, attributes={}),
|
|
telemetry.child_span("S3 GetObject", {"rpc.method": "GetObject"}),
|
|
):
|
|
pass
|
|
child, root = pipeline.spans.get_finished_spans()
|
|
assert child.parent is not None
|
|
assert child.parent.span_id == root.context.span_id
|
|
assert child.context.trace_id == root.context.trace_id
|
|
|
|
|
|
def test_child_span_records_error_type(pipeline: Pipeline) -> None:
|
|
with (
|
|
pytest.raises(TimeoutError),
|
|
telemetry.root_span("process q", kind=SpanKind.CONSUMER, attributes={}),
|
|
telemetry.child_span("S3 PutObject", {}),
|
|
):
|
|
raise TimeoutError("key attachments/123 in text")
|
|
child, root = pipeline.spans.get_finished_spans()
|
|
assert child.attributes["error.type"] == "TimeoutError"
|
|
assert root.attributes["error.type"] == "TimeoutError"
|
|
assert "attachments/123" not in repr(child.attributes) + repr(child.events)
|
|
|
|
|
|
def test_job_histogram_by_type_and_outcome(pipeline: Pipeline) -> None:
|
|
for outcome in ("ready", "ready", "failed"):
|
|
with telemetry.root_span(
|
|
"process q", kind=SpanKind.CONSUMER, attributes={}
|
|
) as span:
|
|
telemetry.record_job(
|
|
span, job_type="attachment.process.v1", outcome=outcome, seconds=0.3
|
|
)
|
|
counts = {
|
|
p.attributes["messenger.job.outcome"]: p.count
|
|
for p in pipeline.points(telemetry.JOB_DURATION)
|
|
}
|
|
assert counts == {"ready": 2, "failed": 1}
|
|
outcomes = [
|
|
s.attributes["messenger.job.outcome"]
|
|
for s in pipeline.spans.get_finished_spans()
|
|
]
|
|
assert sorted(outcomes) == ["failed", "ready", "ready"]
|
|
|
|
|
|
def test_relay_counter_skips_zero(pipeline: Pipeline) -> None:
|
|
telemetry.count_relay({"published": 3, "requeued": 0})
|
|
telemetry.count_relay({"published": 2})
|
|
(point,) = pipeline.points(telemetry.RELAY_JOBS)
|
|
assert point.value == 5
|
|
assert dict(point.attributes) == {"messenger.relay.action": "published"}
|
|
|
|
|
|
# --- журнал ------------------------------------------------------------------------
|
|
|
|
|
|
def test_log_record_carries_trace_and_request_id(pipeline: Pipeline) -> None:
|
|
logger = logging.getLogger("src.unit")
|
|
logger.setLevel(logging.INFO)
|
|
logger.addHandler(pipeline.session.log_handler)
|
|
token = app_log.request_id_var.set("unit-rid-2")
|
|
try:
|
|
with telemetry.root_span("GET /x", kind=SpanKind.SERVER, attributes={}) as span:
|
|
logger.info("chat created chat_id=%s members=%d", "c1", 2)
|
|
suffix = telemetry.trace_fields()
|
|
finally:
|
|
app_log.request_id_var.reset(token)
|
|
logger.removeHandler(pipeline.session.log_handler)
|
|
(exported,) = pipeline.logs.get_finished_logs()
|
|
record = exported.log_record
|
|
assert record.body == "chat created chat_id=c1 members=2"
|
|
assert record.trace_id == span.get_span_context().trace_id
|
|
assert record.span_id == span.get_span_context().span_id
|
|
assert dict(record.attributes) == {
|
|
"event": "chat created",
|
|
"logger": "src.unit",
|
|
"request_id": "unit-rid-2",
|
|
}
|
|
assert record.severity_text == "INFO"
|
|
trace_id = f"{span.get_span_context().trace_id:032x}"
|
|
assert suffix.startswith(f" trace_id={trace_id} span_id=")
|
|
|
|
|
|
def test_stdout_line_gets_trace_fields_only_inside_span(pipeline: Pipeline) -> None:
|
|
record = logging.LogRecord("src.x", logging.INFO, __file__, 1, "hello", (), None)
|
|
app_log.RequestIdFilter().filter(record)
|
|
assert record.trace == ""
|
|
with telemetry.root_span("GET /x", kind=SpanKind.SERVER, attributes={}):
|
|
app_log.RequestIdFilter().filter(record)
|
|
assert re.fullmatch(r" trace_id=[0-9a-f]{32} span_id=[0-9a-f]{16}", record.trace)
|
|
|
|
|
|
def test_unsampled_root_has_no_trace_fields() -> None:
|
|
built = Pipeline(
|
|
TelemetrySettings.from_env({**ENDPOINT, "OTEL_TRACES_SAMPLER_ARG": "0"})
|
|
)
|
|
try:
|
|
with telemetry.root_span("GET /x", kind=SpanKind.SERVER, attributes={}):
|
|
assert telemetry.trace_fields() == ""
|
|
assert built.spans.get_finished_spans() == ()
|
|
finally:
|
|
built.session.shutdown(1.0)
|
|
|
|
|
|
def test_exception_traceback_is_not_exported(pipeline: Pipeline) -> None:
|
|
logger = logging.getLogger("src.unit.exc")
|
|
logger.addHandler(pipeline.session.log_handler)
|
|
try:
|
|
try:
|
|
raise ValueError("password=hunter2")
|
|
except ValueError:
|
|
logger.error("job delivery failed job_id=%s", "j1", exc_info=True)
|
|
finally:
|
|
logger.removeHandler(pipeline.session.log_handler)
|
|
(exported,) = pipeline.logs.get_finished_logs()
|
|
assert exported.log_record.attributes["exception.type"] == "ValueError"
|
|
assert "hunter2" not in repr(exported.log_record.attributes)
|
|
|
|
|
|
def test_event_name_from_template() -> None:
|
|
def record(msg: str, **extra: str) -> logging.LogRecord:
|
|
item = logging.LogRecord("src.x", logging.INFO, __file__, 1, msg, (), None)
|
|
item.__dict__.update(extra)
|
|
return item
|
|
|
|
assert sdk.event_name(record("attachment processed attachment_id=%s")) == (
|
|
"attachment processed"
|
|
)
|
|
assert sdk.event_name(record("%s %s -> %d", event="http request")) == "http request"
|
|
assert sdk.event_name(record("Started server process [%d]")) == (
|
|
"Started server process"
|
|
)
|
|
assert sdk.event_name(record("%s")) == "src.x"
|
|
|
|
|
|
# --- наборы границ и закрытие ------------------------------------------------------
|
|
|
|
|
|
def test_coarse_buckets_are_applied() -> None:
|
|
built = Pipeline(
|
|
TelemetrySettings.from_env(
|
|
{**ENDPOINT, "TELEMETRY_HISTOGRAM_BUCKETS": "coarse"}
|
|
)
|
|
)
|
|
try:
|
|
telemetry.record_job(None, job_type="t", outcome="ready", seconds=1.0)
|
|
(point,) = built.points(telemetry.JOB_DURATION)
|
|
assert point.explicit_bounds == tuple(
|
|
sdk.BUCKETS["coarse"][telemetry.JOB_DURATION]
|
|
)
|
|
finally:
|
|
built.session.shutdown(1.0)
|
|
|
|
|
|
class _StuckExporter(InMemorySpanExporter):
|
|
"""Экспортёр, который «висит», как замороженный Collector."""
|
|
|
|
def __init__(self) -> None:
|
|
super().__init__()
|
|
self.release = threading.Event()
|
|
|
|
def export(self, spans) -> SpanExportResult:
|
|
self.release.wait(10)
|
|
return SpanExportResult.SUCCESS
|
|
|
|
|
|
def test_shutdown_respects_deadline() -> None:
|
|
built = Pipeline(TelemetrySettings.from_env(ENDPOINT))
|
|
stuck = _StuckExporter()
|
|
built.session.tracer_provider.add_span_processor(
|
|
sdk.BatchSpanProcessor(stuck, schedule_delay_millis=10)
|
|
)
|
|
with telemetry.root_span("GET /x", kind=SpanKind.SERVER, attributes={}):
|
|
pass
|
|
time.sleep(0.1)
|
|
started = time.monotonic()
|
|
assert built.session.shutdown(0.3) is False
|
|
assert time.monotonic() - started < 1.0
|
|
assert not telemetry.enabled()
|
|
stuck.release.set()
|