171 lines
6.4 KiB
Python
171 lines
6.4 KiB
Python
"""Лаба 6, уровень 4: перенос контекста через задание, насыщение, журнал SDK.
|
|
|
|
Без стенда: SDK с in-memory экспортёрами из `test_telemetry.py`. Цепочка
|
|
загрузка → строка задания → producer span → заголовки → consumer span
|
|
собирается из тех же функций, что зовут API, relay и worker.
|
|
"""
|
|
|
|
import logging
|
|
from collections.abc import Iterator
|
|
from types import SimpleNamespace
|
|
|
|
import pytest
|
|
from opentelemetry.trace import SpanKind
|
|
from test_telemetry import ENDPOINT, Pipeline
|
|
|
|
from src import telemetry
|
|
from src.broker import trace_headers
|
|
from src.config import Telemetry as TelemetrySettings
|
|
from src.log import ThrottleFilter
|
|
|
|
pytestmark = pytest.mark.unit
|
|
|
|
TRACEPARENT = "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01"
|
|
|
|
|
|
@pytest.fixture
|
|
def pipeline() -> Iterator[Pipeline]:
|
|
built = Pipeline(TelemetrySettings.from_env(ENDPOINT))
|
|
yield built
|
|
built.session.shutdown(1.0)
|
|
|
|
|
|
def _upload_carrier() -> dict[str, str]:
|
|
"""Что сохранила бы загрузка: контекст её server span."""
|
|
with telemetry.root_span(
|
|
"POST /api/v1/chats/{chat_id}/attachments",
|
|
kind=SpanKind.SERVER,
|
|
attributes={},
|
|
):
|
|
return telemetry.carrier()
|
|
|
|
|
|
def test_chain_upload_relay_worker_is_one_trace(pipeline: Pipeline) -> None:
|
|
stored = _upload_carrier()
|
|
assert set(stored) == {"traceparent"}
|
|
# две публикации одной строки: первая попытка и повтор после backoff
|
|
for attempt in (1, 2):
|
|
with telemetry.producer_span(
|
|
"publish q", stored, {"messenger.job.attempt": attempt}
|
|
) as headers:
|
|
pass
|
|
with (
|
|
telemetry.root_span(
|
|
"process q",
|
|
kind=SpanKind.CONSUMER,
|
|
attributes={"messenger.job.attempt": attempt},
|
|
parent=telemetry.extract(headers),
|
|
),
|
|
telemetry.child_span("S3 put_object", {}),
|
|
):
|
|
pass
|
|
finished = pipeline.spans.get_finished_spans()
|
|
spans = {(s.name, s.attributes.get("messenger.job.attempt")): s for s in finished}
|
|
assert len({s.context.trace_id for s in finished}) == 1
|
|
server = next(s for s in finished if s.kind == SpanKind.SERVER)
|
|
for attempt in (1, 2):
|
|
producer = spans[("publish q", attempt)]
|
|
consumer = spans[("process q", attempt)]
|
|
assert producer.kind == SpanKind.PRODUCER
|
|
assert producer.parent.span_id == server.context.span_id
|
|
assert consumer.parent.span_id == producer.context.span_id
|
|
put = [s for s in finished if s.name == "S3 put_object"]
|
|
assert {s.parent.span_id for s in put} == {
|
|
spans[("process q", 1)].context.span_id,
|
|
spans[("process q", 2)].context.span_id,
|
|
}
|
|
|
|
|
|
def test_relay_without_stored_context_starts_no_trace(pipeline: Pipeline) -> None:
|
|
with telemetry.producer_span("publish q", {}, {}) as headers:
|
|
assert headers == {}
|
|
assert pipeline.spans.get_finished_spans() == ()
|
|
|
|
|
|
def test_disabled_relay_passes_stored_context_through() -> None:
|
|
assert not telemetry.enabled()
|
|
stored = {"traceparent": TRACEPARENT, "tracestate": "vendor=1"}
|
|
with telemetry.producer_span("publish q", stored, {}) as headers:
|
|
assert headers == stored
|
|
assert telemetry.carrier() == {}
|
|
|
|
|
|
def test_unsampled_upload_stays_unsampled_downstream() -> None:
|
|
built = Pipeline(
|
|
TelemetrySettings.from_env({**ENDPOINT, "OTEL_TRACES_SAMPLER_ARG": "0"})
|
|
)
|
|
try:
|
|
stored = _upload_carrier()
|
|
with telemetry.producer_span("publish q", stored, {}) as headers:
|
|
pass
|
|
# бит sampled (0x01) в trace-flags снят у обоих
|
|
assert int(stored["traceparent"][-2:], 16) & 1 == 0
|
|
assert int(headers["traceparent"][-2:], 16) & 1 == 0
|
|
assert built.spans.get_finished_spans() == ()
|
|
finally:
|
|
built.session.shutdown(1.0)
|
|
|
|
|
|
def test_trace_headers_accept_bytes_and_ignore_rest() -> None:
|
|
message = SimpleNamespace(
|
|
headers={"traceparent": TRACEPARENT.encode(), "x-other": "1", "tracestate": ""}
|
|
)
|
|
assert trace_headers(message) == {"traceparent": TRACEPARENT}
|
|
assert trace_headers(SimpleNamespace(headers=None)) == {}
|
|
|
|
|
|
def test_saturation_gauges(pipeline: Pipeline) -> None:
|
|
telemetry.watch_pool(lambda: (3, 7, 2, 15))
|
|
telemetry.worker_capacity(2)
|
|
telemetry.queue_snapshot("db.attachment-jobs", {"outbox": 4, "processing": 1}, 42.5)
|
|
with telemetry.busy():
|
|
used = {
|
|
p.attributes["db.client.connection.state"]: p.value
|
|
for p in pipeline.points("db.client.connection.count")
|
|
}
|
|
busy = pipeline.points("messenger.worker.busy")
|
|
assert used == {"used": 3, "idle": 7}
|
|
assert [
|
|
p.value for p in pipeline.points("db.client.connection.pending_requests")
|
|
] == [2]
|
|
assert [p.value for p in busy] == [1]
|
|
assert [p.value for p in pipeline.points("messenger.worker.capacity")] == [2]
|
|
depth = {
|
|
p.attributes["messenger.job.state"]: p.value
|
|
for p in pipeline.points("messenger.job.queue.depth")
|
|
}
|
|
assert depth == {"outbox": 4, "processing": 1}
|
|
(age,) = pipeline.points("messenger.job.queue.oldest_age")
|
|
assert age.value == 42.5
|
|
assert pipeline.points("process.memory.usage")[0].value > 0
|
|
modes = {p.attributes["cpu.mode"] for p in pipeline.points("process.cpu.time")}
|
|
assert modes == {"user", "system"}
|
|
telemetry.gauges.capacity = 0
|
|
telemetry.gauges.depth = {}
|
|
telemetry.gauges.oldest_age = None
|
|
|
|
|
|
def test_time_to_ready_histogram(pipeline: Pipeline) -> None:
|
|
telemetry.record_ready(3.2)
|
|
telemetry.record_ready(-0.1) # часы разошлись — не отрицательное
|
|
(point,) = pipeline.points(telemetry.TIME_TO_READY)
|
|
assert point.count == 2
|
|
assert point.min == 0.0
|
|
assert dict(point.attributes) == {}
|
|
|
|
|
|
def test_throttle_filter_lets_one_record_per_window() -> None:
|
|
throttle = ThrottleFilter(window=60)
|
|
|
|
def record(text: str) -> logging.LogRecord:
|
|
return logging.LogRecord(
|
|
"opentelemetry.x", logging.WARNING, "", 0, text, (), None
|
|
)
|
|
|
|
assert throttle.filter(record("first"))
|
|
assert not any(throttle.filter(record("again")) for _ in range(5))
|
|
throttle._last["opentelemetry.x"] -= 61
|
|
late = record("later")
|
|
assert throttle.filter(late)
|
|
assert "suppressed=5" in late.getMessage()
|