Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces OpenTelemetry Scope management to the SpanTracer class to track active spans during execution attempts. Review feedback indicates that storing the Scope as a class field is unsafe for asynchronous environments where methods may be called on different threads, potentially leading to incorrect context restoration. Additionally, it is recommended to use a try-finally block and null checks when closing the scope to ensure exception safety and proper resource cleanup.
| spanBuilder.setAllAttributes(ObservabilityUtils.toOtelAttributes(currentAttemptAttributes)); | ||
|
|
||
| this.attemptSpan = spanBuilder.startSpan(); | ||
| this.scope = attemptSpan.makeCurrent(); |
There was a problem hiding this comment.
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.
| scope.close(); | ||
| attemptSpan.end(); | ||
| attemptSpan = null; |
There was a problem hiding this comment.
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
- 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.
This PR adds a new feature that manages the lifecycle of OpenTelemetry Scope in SpanTracer.
The span is set to current context at the start of a request, and is cleared from current context at the end of a request.