Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions faststream/confluent/opentelemetry/provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ def get_consume_attrs_from_message(
SpanAttributes.MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES: len(msg.body),
SpanAttributes.MESSAGING_KAFKA_DESTINATION_PARTITION: msg.raw_message.partition(),
SpanAttributes.MESSAGING_KAFKA_MESSAGE_OFFSET: msg.raw_message.offset(),
SpanAttributes.MESSAGING_DESTINATION_NAME: msg.raw_message.topic(),
MESSAGING_DESTINATION_PUBLISH_NAME: msg.raw_message.topic(),
}

Expand All @@ -86,7 +87,7 @@ def get_consume_attrs_from_message(
msg: "StreamMessage[tuple[Message, ...]]",
) -> dict[str, Any]:
raw_message = msg.raw_message[0]
return {
attrs: dict[str, Any] = {
SpanAttributes.MESSAGING_SYSTEM: self.messaging_system,
SpanAttributes.MESSAGING_MESSAGE_ID: msg.message_id,
SpanAttributes.MESSAGING_MESSAGE_CONVERSATION_ID: msg.correlation_id,
Expand All @@ -95,9 +96,16 @@ def get_consume_attrs_from_message(
bytearray().join(cast("Sequence[bytes]", msg.body)),
),
SpanAttributes.MESSAGING_KAFKA_DESTINATION_PARTITION: raw_message.partition(),
MESSAGING_DESTINATION_PUBLISH_NAME: raw_message.topic(),
}

topic = raw_message.topic()
if all(record.topic() == topic for record in msg.raw_message):
attrs[SpanAttributes.MESSAGING_DESTINATION_NAME] = topic

# Keep the legacy topic when the SDK drops older attributes at its limit.
attrs[MESSAGING_DESTINATION_PUBLISH_NAME] = topic
return attrs

@override
def get_consume_destination_name(
self,
Expand Down
12 changes: 10 additions & 2 deletions faststream/kafka/opentelemetry/provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ def get_consume_attrs_from_message(
SpanAttributes.MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES: len(msg.body),
SpanAttributes.MESSAGING_KAFKA_DESTINATION_PARTITION: msg.raw_message.partition,
SpanAttributes.MESSAGING_KAFKA_MESSAGE_OFFSET: msg.raw_message.offset,
SpanAttributes.MESSAGING_DESTINATION_NAME: msg.raw_message.topic,
MESSAGING_DESTINATION_PUBLISH_NAME: msg.raw_message.topic,
}

Expand Down Expand Up @@ -93,7 +94,7 @@ def get_consume_attrs_from_message(
) -> dict[str, Any]:
raw_message = msg.raw_message[0]

return {
attrs: dict[str, Any] = {
SpanAttributes.MESSAGING_SYSTEM: self.messaging_system,
SpanAttributes.MESSAGING_MESSAGE_ID: msg.message_id,
SpanAttributes.MESSAGING_MESSAGE_CONVERSATION_ID: msg.correlation_id,
Expand All @@ -102,9 +103,16 @@ def get_consume_attrs_from_message(
),
SpanAttributes.MESSAGING_BATCH_MESSAGE_COUNT: len(msg.raw_message),
SpanAttributes.MESSAGING_KAFKA_DESTINATION_PARTITION: raw_message.partition,
MESSAGING_DESTINATION_PUBLISH_NAME: raw_message.topic,
}

topic = raw_message.topic
if all(record.topic == topic for record in msg.raw_message):
attrs[SpanAttributes.MESSAGING_DESTINATION_NAME] = topic

# Keep the legacy topic when the SDK drops older attributes at its limit.
attrs[MESSAGING_DESTINATION_PUBLISH_NAME] = topic
return attrs

@override
def get_consume_destination_name(
self,
Expand Down
7 changes: 6 additions & 1 deletion tests/opentelemetry/confluent/test_confluent.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ def assert_span(
assert attrs[SpanAttr.MESSAGING_DESTINATION_NAME] == queue

if span.kind == SpanKind.CONSUMER and action in {Action.CREATE, Action.PROCESS}:
assert attrs[SpanAttr.MESSAGING_DESTINATION_NAME] == queue
assert attrs[MESSAGING_DESTINATION_PUBLISH_NAME] == queue
assert attrs[SpanAttr.MESSAGING_MESSAGE_ID] == IsStr(regex=r"0-.+")
assert attrs[SpanAttr.MESSAGING_KAFKA_DESTINATION_PARTITION] == 0
Expand Down Expand Up @@ -116,6 +117,8 @@ async def handler(m: Any, baggage: CurrentBaggage) -> None:
spans = self.get_spans(trace_exporter)
_, publish, create_process, process = spans

assert (process.attributes or {})[SpanAttr.MESSAGING_DESTINATION_NAME] == queue

assert (publish.attributes or {})[
SpanAttr.MESSAGING_BATCH_MESSAGE_COUNT
] == expected_msg_count
Expand Down Expand Up @@ -254,7 +257,9 @@ async def handler(m: Any, baggage: CurrentBaggage) -> None:
metrics = self.get_metrics(metric_reader)
proc_dur, proc_msg, pub_dur, pub_msg = metrics
spans = self.get_spans(trace_exporter)
create_process = spans[-2]
create_process, process = spans[-2:]

assert (process.attributes or {})[SpanAttr.MESSAGING_DESTINATION_NAME] == queue

assert len(spans) == expected_span_count
assert len(create_process.links) == expected_link_count
Expand Down
7 changes: 6 additions & 1 deletion tests/opentelemetry/kafka/test_kafka.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ def assert_span(
assert attrs[SpanAttr.MESSAGING_DESTINATION_NAME] == queue

if span.kind == SpanKind.CONSUMER and action in {Action.CREATE, Action.PROCESS}:
assert attrs[SpanAttr.MESSAGING_DESTINATION_NAME] == queue
assert attrs[MESSAGING_DESTINATION_PUBLISH_NAME] == queue
assert attrs[SpanAttr.MESSAGING_MESSAGE_ID] == IsStr(regex=r"0-.+")
assert attrs[SpanAttr.MESSAGING_KAFKA_DESTINATION_PARTITION] == 0
Expand Down Expand Up @@ -116,6 +117,8 @@ async def handler(m: Any, baggage: CurrentBaggage) -> None:
spans = self.get_spans(trace_exporter)
_, publish, create_process, process = spans

assert (process.attributes or {})[SpanAttr.MESSAGING_DESTINATION_NAME] == queue

assert (publish.attributes or {})[
SpanAttr.MESSAGING_BATCH_MESSAGE_COUNT
] == expected_msg_count
Expand Down Expand Up @@ -254,7 +257,9 @@ async def handler(m: Any, baggage: CurrentBaggage) -> None:
metrics = self.get_metrics(metric_reader)
proc_dur, proc_msg, pub_dur, pub_msg = metrics
spans = self.get_spans(trace_exporter)
create_process = spans[-2]
create_process, process = spans[-2:]

assert (process.attributes or {})[SpanAttr.MESSAGING_DESTINATION_NAME] == queue

assert len(spans) == expected_span_count
assert len(create_process.links) == expected_link_count
Expand Down
116 changes: 116 additions & 0 deletions tests/opentelemetry/test_kafka_consume_destination.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import pytest
from aiokafka import ConsumerRecord
from dirty_equals import IsPartialDict
from opentelemetry.sdk.trace import SpanLimits, TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
from opentelemetry.semconv.trace import SpanAttributes
from opentelemetry.trace import SpanKind

from faststream._internal.context.repository import ContextRepo
from faststream.confluent.opentelemetry import (
KafkaTelemetryMiddleware as ConfluentTelemetryMiddleware,
)
from faststream.confluent.testing import MockConfluentMessage
from faststream.kafka.opentelemetry import KafkaTelemetryMiddleware
from faststream.message import StreamMessage
from faststream.opentelemetry.consts import MESSAGING_DESTINATION_PUBLISH_NAME


async def process_message(message: StreamMessage[object]) -> None:
pass


@pytest.mark.asyncio()
@pytest.mark.parametrize(
"backend",
(
pytest.param("aiokafka", marks=pytest.mark.kafka(), id="aiokafka"),
pytest.param("confluent", marks=pytest.mark.confluent(), id="confluent"),
),
)
@pytest.mark.parametrize(
("topics", "max_attributes", "expected_topic"),
(
pytest.param(("orders", "orders"), 2, None, id="two-attribute-slots"),
pytest.param(("orders", "orders"), None, "orders", id="same-topic"),
pytest.param(("orders", "payments", "orders"), None, None, id="mixed-topics"),
pytest.param(("orders",), None, "orders", id="singleton"),
),
)
async def test_batch_consume_destination(
backend: str,
topics: tuple[str, ...],
max_attributes: int | None,
expected_topic: str | None,
) -> None:
exporter = InMemorySpanExporter()
tracer_provider = TracerProvider(
span_limits=SpanLimits(max_span_attributes=max_attributes),
)
tracer_provider.add_span_processor(SimpleSpanProcessor(exporter))

records: tuple[ConsumerRecord, ...] | tuple[MockConfluentMessage, ...]
middleware: KafkaTelemetryMiddleware | ConfluentTelemetryMiddleware
if backend == "aiokafka":
middleware = KafkaTelemetryMiddleware(tracer_provider=tracer_provider)
records = tuple(
ConsumerRecord(
topic=topic,
partition=partition,
offset=0,
timestamp=0,
timestamp_type=0,
key=None,
value=b"x",
checksum=None,
serialized_key_size=-1,
serialized_value_size=1,
headers=(),
)
for partition, topic in enumerate(topics)
)
else:
middleware = ConfluentTelemetryMiddleware(tracer_provider=tracer_provider)
records = tuple(
MockConfluentMessage(
raw_msg=b"x",
topic=topic,
key=b"",
headers=(),
offset=0,
partition=partition,
timestamp_type=0,
timestamp_ms=0,
)
for partition, topic in enumerate(topics)
)

message: StreamMessage[object] = StreamMessage(
raw_message=records,
body=[b"x"] * len(records),
batch_headers=[{} for _ in records],
)
scope = middleware(records, context=ContextRepo())
try:
async with scope:
await scope.consume_scope(process_message, message)

(span,) = (
span
for span in exporter.get_finished_spans()
if (span.attributes or {}).get(SpanAttributes.MESSAGING_OPERATION)
== "process"
)
assert span.kind is SpanKind.CONSUMER
attrs = span.attributes or {}
if expected_topic is None:
assert attrs[MESSAGING_DESTINATION_PUBLISH_NAME] == "orders"
assert SpanAttributes.MESSAGING_DESTINATION_NAME not in attrs
else:
assert dict(attrs) == IsPartialDict({
MESSAGING_DESTINATION_PUBLISH_NAME: "orders",
SpanAttributes.MESSAGING_DESTINATION_NAME: expected_topic,
})
finally:
tracer_provider.shutdown()
Loading