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
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@
import io.opentelemetry.api.trace.SpanBuilder;
import io.opentelemetry.api.trace.SpanKind;
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.context.Scope;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CancellationException;
Expand All @@ -53,6 +55,7 @@ public class SpanTracer implements ApiTracer {
private final String attemptSpanName;
private final ApiTracerContext apiTracerContext;
private Span attemptSpan;
private io.opentelemetry.context.Scope scope;

@Override
public void injectTraceContext(java.util.Map<String, String> carrier) {
Expand Down Expand Up @@ -144,6 +147,7 @@ public void attemptStarted(Object request, int attemptNumber) {
spanBuilder.setAllAttributes(ObservabilityUtils.toOtelAttributes(currentAttemptAttributes));

this.attemptSpan = spanBuilder.startSpan();
this.scope = attemptSpan.makeCurrent();
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Managing an OpenTelemetry Scope as a class field is risky in asynchronous environments. Scope is thread-local and must be closed on the same thread it was opened. In gax-java, ApiTracer methods like attemptStarted and endAttempt are frequently called on different threads (e.g., the request thread and the gRPC callback thread). Closing the scope on a different thread will lead to incorrect context restoration and potential state corruption in OpenTelemetry.

}

@Override
Expand Down Expand Up @@ -249,6 +253,7 @@ private void endAttempt() {
return;
}

scope.close();
attemptSpan.end();
attemptSpan = null;
Comment on lines +256 to 258
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

To ensure exception safety and adhere to the LIFO rule for resource management, scope.close() should be wrapped in a try-finally block. This guarantees that attemptSpan.end() is called even if an unexpected exception occurs during scope closure. Additionally, a null check for scope is recommended to prevent potential NPEs if makeCurrent() failed or wasn't called, and the field should be cleared after closing.

    try {
      if (scope != null) {
        scope.close();
      }
    } finally {
      scope = null;
      attemptSpan.end();
      attemptSpan = null;
    }
References
  1. When managing a collection of closeable resources (e.g., scopes), ensure they are closed in the reverse order of their creation (LIFO). The implementation must be exception-safe to prevent resource leaks, meaning all opened resources should be closed even if exceptions occur during their creation or closing.

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,7 @@
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.*;

import com.google.api.gax.rpc.ApiException;
import com.google.api.gax.rpc.ErrorDetails;
Expand All @@ -48,6 +46,7 @@
import io.opentelemetry.api.trace.SpanBuilder;
import io.opentelemetry.api.trace.SpanKind;
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.context.Scope;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import org.junit.jupiter.api.BeforeEach;
Expand All @@ -62,6 +61,7 @@ class SpanTracerTest {
@Mock private Tracer tracer;
@Mock private SpanBuilder spanBuilder;
@Mock private Span span;
@Mock private Scope scope;
private SpanTracer spanTracer;
private static final String ATTEMPT_SPAN_NAME = "Service/Method/attempt";

Expand All @@ -71,6 +71,7 @@ void setUp() {
when(spanBuilder.setSpanKind(any(SpanKind.class))).thenReturn(spanBuilder);
when(spanBuilder.setAllAttributes(any(Attributes.class))).thenReturn(spanBuilder);
when(spanBuilder.startSpan()).thenReturn(span);
lenient().when(span.makeCurrent()).thenReturn(scope);
spanTracer = new SpanTracer(tracer, ApiTracerContext.empty(), ATTEMPT_SPAN_NAME);
}

Expand Down Expand Up @@ -625,4 +626,31 @@ void testInjectTraceContext_addsHeaders() {
assertThat(carrier.get("traceparent")).contains("00000000000000000000000000000001");
assertThat(carrier.get("traceparent")).contains("0000000000000002");
}

@Test
void testAttemptStarted_makesSpanCurrent() {
spanTracer.attemptStarted(new Object(), 1);
verify(span).makeCurrent();
}

@Test
void testAttemptEnded_closesScope_succeeded() {
spanTracer.attemptStarted(new Object(), 1);
spanTracer.attemptSucceeded();
verify(scope).close();
}

@Test
void testAttemptEnded_closesScope_failed() {
spanTracer.attemptStarted(new Object(), 1);
spanTracer.attemptFailedRetriesExhausted(new RuntimeException());
verify(scope).close();
}

@Test
void testAttemptEnded_closesScope_cancelled() {
spanTracer.attemptStarted(new Object(), 1);
spanTracer.attemptCancelled();
verify(scope).close();
}
}
Loading