Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

instrumentation/kafka: fix handling consumer iteration if transaction not sampled #2075

Merged
merged 1 commit into from
Jul 9, 2024
Merged
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
3 changes: 2 additions & 1 deletion elasticapm/instrumentation/packages/kafka.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,8 @@ def call(self, module, method, wrapped, instance, args, kwargs):
try:
result = wrapped(*args, **kwargs)
except StopIteration:
span.cancel()
if span:
span.cancel()
raise
if span and not isinstance(span, DroppedSpan):
topic = result[0]
Expand Down
24 changes: 21 additions & 3 deletions tests/instrumentation/kafka_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,10 @@

pytestmark = [pytest.mark.kafka]

if "KAFKA_HOST" not in os.environ:
KAFKA_HOST = os.environ.get("KAFKA_HOST")
if not KAFKA_HOST:
pytestmark.append(pytest.mark.skip("Skipping kafka tests, no KAFKA_HOST environment variable set"))

KAFKA_HOST = os.environ["KAFKA_HOST"]


@pytest.fixture(scope="function")
def topics():
Expand Down Expand Up @@ -233,3 +232,22 @@ def test_kafka_poll_unsampled_transaction(instrument, elasticapm_client, consume
elasticapm_client.end_transaction("foo")
spans = elasticapm_client.events[SPAN]
assert len(spans) == 0


def test_kafka_consumer_unsampled_transaction_handles_stop_iteration(
instrument, elasticapm_client, producer, consumer, topics
):
def delayed_send():
time.sleep(0.2)
producer.send("test", key=b"foo", value=b"bar")

thread = threading.Thread(target=delayed_send)
thread.start()
transaction = elasticapm_client.begin_transaction("foo")
transaction.is_sampled = False
for item in consumer:
pass
thread.join()
elasticapm_client.end_transaction("foo")
spans = elasticapm_client.events[SPAN]
assert len(spans) == 0
Loading