Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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 @@ -271,14 +271,15 @@ public static ClientContext create(StubSettings settings) throws IOException {
if (watchdogProvider != null && watchdogProvider.shouldAutoClose()) {
backgroundResources.add(watchdog);
}
ApiTracerContext apiTracerContext =
ApiTracerContext.newBuilder()
.setServerAddress(endpointContext.resolvedServerAddress())
.setServerPort(endpointContext.resolvedServerPort())
.setLibraryMetadata(settings.getLibraryMetadata())
.build();

ApiTracerFactory apiTracerFactory = settings.getTracerFactory();
if (apiTracerFactory instanceof SpanTracerFactory) {
if (apiTracerFactory.needsContext()) {
ApiTracerContext apiTracerContext =
ApiTracerContext.newBuilder()
.setServerAddress(endpointContext.resolvedServerAddress())
.setServerPort(endpointContext.resolvedServerPort())
.setLibraryMetadata(settings.getLibraryMetadata())
.build();
apiTracerFactory = apiTracerFactory.withContext(apiTracerContext);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,13 @@ default ApiTracer newTracer(ApiTracer parent, ApiTracerContext tracerContext) {
}

/**
* @return the {@link ApiTracerContext} for this factory
* Indicates whether this factory requires an {@link ApiTracerContext} to be injected via {@link
* #withContext(ApiTracerContext)} before creating tracers.
*
* @return {@code true} if an {@link ApiTracerContext} should be injected, {@code false} otherwise.
*/
default ApiTracerContext getApiTracerContext() {
return ApiTracerContext.empty();
default boolean needsContext() {
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.

I see this is only used in ClientContext. Is this to avoid an unnecessary flow on legacy tracer factories? If so, I think we should also use this function in GrcpCallableFactory and its HttpJson counterpart.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

It is mostly used to avoid calling withContext() if needsContext is false, to prevent potential test cases in customers' repos. I don't think we need it in GrpcCallableFactory.

return false;
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
/*
* Copyright 2026 Google LLC
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google LLC nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.google.api.gax.tracing;

import com.google.api.core.InternalApi;
import com.google.common.collect.ImmutableList;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
* A composite implementation of {@link ApiTracer} that delegates all tracing events to a list of
* underlying tracers.
*
* <p>For internal use only.
*/
@InternalApi
class CompositeTracer extends BaseApiTracer {
private final List<ApiTracer> children;

public CompositeTracer(List<ApiTracer> children) {
this.children = ImmutableList.copyOf(children);
}

@Override
public Scope inScope() {
final List<Scope> childScopes = new ArrayList<>(children.size());

for (ApiTracer child : children) {
childScopes.add(child.inScope());
}

return () -> {
for (Scope childScope : childScopes) {
childScope.close();
}
};
}
Comment on lines +53 to +88
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.

medium

The inScope() implementation has a few issues:

  1. LIFO Order: Scopes should be closed in reverse order (Last-In, First-Out) to correctly handle nested contexts, similar to how try-with-resources handles multiple resources.
  2. Exception Safety: If child.inScope() throws an exception, previously opened scopes are leaked. Similarly, if one childScope.close() throws, subsequent scopes are not closed.

Consider using a more robust implementation that ensures all scopes are closed even if some fail.

  @Override
  public Scope inScope() {
    final List<Scope> childScopes = new ArrayList<>(children.size());
    try {
      for (ApiTracer child : children) {
        childScopes.add(child.inScope());
      }
    } catch (RuntimeException e) {
      for (Scope scope : childScopes) {
        try {
          scope.close();
        } catch (RuntimeException suppressed) {
          e.addSuppressed(suppressed);
        }
      }
      throw e;
    }

    return () -> {
      Throwable error = null;
      for (int i = childScopes.size() - 1; i >= 0; i--) {
        try {
          childScopes.get(i).close();
        } catch (Throwable t) {
          if (error == null) {
            error = t;
          } else {
            error.addSuppressed(t);
          }
        }
      }
      if (error != null) {
        if (error instanceof RuntimeException) throw (RuntimeException) error;
        if (error instanceof Error) throw (Error) error;
        throw new RuntimeException(error);
      }
    };
  }

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.

I agree with #1 here, logging needs to close before tracing.

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.

Exception safety also looks valid to me. User code may be swallowing exceptions while leaving open tracers in scope.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I agree with both, updated. That being said, this is mostly for backward compatibility, it is not used by any of the tracers at this moment. It was originally designed to mimic OpenCensus Scope, but OpenTelemetry significant reduced the complexity of it and we don't have to manage the lifecycle of it mostly of time.


@Override
public void operationSucceeded() {
for (ApiTracer child : children) {
child.operationSucceeded();
}
}

@Override
public void operationCancelled() {
for (ApiTracer child : children) {
child.operationCancelled();
}
}

@Override
public void operationFailed(Throwable error) {
for (ApiTracer child : children) {
child.operationFailed(error);
}
}

@Override
public void connectionSelected(String id) {
for (ApiTracer child : children) {
child.connectionSelected(id);
}
}

@Override
@Deprecated
public void attemptStarted(int attemptNumber) {
for (ApiTracer child : children) {
child.attemptStarted(attemptNumber);
}
}

@Override
public void attemptStarted(Object request, int attemptNumber) {
for (ApiTracer child : children) {
child.attemptStarted(request, attemptNumber);
}
}

@Override
public void attemptSucceeded() {
for (ApiTracer child : children) {
child.attemptSucceeded();
}
}

@Override
public void attemptCancelled() {
for (ApiTracer child : children) {
child.attemptCancelled();
}
}

@Override
public void attemptFailed(Throwable error, org.threeten.bp.Duration delay) {
for (ApiTracer child : children) {
child.attemptFailed(error, delay);
}
}

@Override
public void attemptFailedDuration(Throwable error, java.time.Duration delay) {
for (ApiTracer child : children) {
child.attemptFailedDuration(error, delay);
}
}

@Override
public void attemptFailedRetriesExhausted(Throwable error) {
for (ApiTracer child : children) {
child.attemptFailedRetriesExhausted(error);
}
}

@Override
public void attemptPermanentFailure(Throwable error) {
for (ApiTracer child : children) {
child.attemptPermanentFailure(error);
}
}

@Override
public void lroStartFailed(Throwable error) {
for (ApiTracer child : children) {
child.lroStartFailed(error);
}
}

@Override
public void lroStartSucceeded() {
for (ApiTracer child : children) {
child.lroStartSucceeded();
}
}

@Override
public void responseReceived() {
for (ApiTracer child : children) {
child.responseReceived();
}
}

@Override
public void responseHeadersReceived(Map<String, Object> headers) {
for (ApiTracer child : children) {
child.responseHeadersReceived(headers);
}
}

@Override
public void requestSent() {
for (ApiTracer child : children) {
child.requestSent();
}
}

@Override
public void batchRequestSent(long elementCount, long requestSize) {
for (ApiTracer child : children) {
child.batchRequestSent(elementCount, requestSize);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
/*
* Copyright 2026 Google LLC
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google LLC nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.google.api.gax.tracing;

import com.google.common.collect.ImmutableList;
import java.util.ArrayList;
import java.util.List;

/**
* A composite implementation of {@link ApiTracerFactory} that bundles multiple tracing factories
* and produces a {@link CompositeTracer} out of them.
*
*/
public class CompositeTracerFactory extends BaseApiTracerFactory {
private final List<ApiTracerFactory> apiTracerFactories;

public CompositeTracerFactory(List<ApiTracerFactory> apiTracerFactories) {
this.apiTracerFactories = ImmutableList.copyOf(apiTracerFactories);
}

@Override
public ApiTracer newTracer(ApiTracer parent, SpanName spanName, OperationType operationType) {
List<ApiTracer> children = new ArrayList<>(apiTracerFactories.size());

for (ApiTracerFactory factory : apiTracerFactories) {
children.add(factory.newTracer(parent, spanName, operationType));
}
return new CompositeTracer(children);
}

@Override
public ApiTracer newTracer(ApiTracer parent, ApiTracerContext tracerContext) {
List<ApiTracer> children = new ArrayList<>(apiTracerFactories.size());

for (ApiTracerFactory factory : apiTracerFactories) {
children.add(factory.newTracer(parent, tracerContext));
}
return new CompositeTracer(children);
}

@Override
public boolean needsContext() {
for (ApiTracerFactory factory : apiTracerFactories) {
if (factory.needsContext()) {
return true;
}
}
return false;
}

@Override
public ApiTracerFactory withContext(ApiTracerContext context) {
List<ApiTracerFactory> contextualizedChildren = new ArrayList<>(apiTracerFactories.size());

for (ApiTracerFactory factory : apiTracerFactories) {
contextualizedChildren.add(factory.withContext(context));
}
return new CompositeTracerFactory(contextualizedChildren);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,11 @@ public ApiTracer newTracer(ApiTracer parent, ApiTracerContext methodLevelTracerC
return new GoldenSignalsMetricsTracer(metricsRecorder, mergedTracerContext);
}

@Override
public boolean needsContext() {
return clientLevelTracerContext == null || clientLevelTracerContext.equals(ApiTracerContext.empty());
}

@Override
public ApiTracerFactory withContext(ApiTracerContext context) {
if (context == null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@

import com.google.api.core.BetaApi;
import com.google.api.core.InternalApi;
import com.google.common.annotations.VisibleForTesting;

/** A {@link ApiTracerFactory} that creates instances of {@link LoggingTracer}. */
@BetaApi
Expand All @@ -57,11 +58,16 @@ public ApiTracer newTracer(ApiTracer parent, ApiTracerContext context) {
return new LoggingTracer(apiTracerContext.merge(context));
}

@Override
public ApiTracerContext getApiTracerContext() {
@VisibleForTesting
ApiTracerContext getApiTracerContext() {
return apiTracerContext;
}

@Override
public boolean needsContext() {
return apiTracerContext == null || apiTracerContext.equals(ApiTracerContext.empty());
}

@Override
public ApiTracerFactory withContext(ApiTracerContext context) {
return new LoggingTracerFactory(apiTracerContext.merge(context));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,8 @@ public ApiTracer newTracer(ApiTracer parent, ApiTracerContext apiTracerContext)
}

@Override
public ApiTracerContext getApiTracerContext() {
return apiTracerContext;
public boolean needsContext() {
return apiTracerContext == null || apiTracerContext.equals(ApiTracerContext.empty());
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1298,6 +1298,7 @@ void testCreate_withTracerFactoryReturningNullWithContext() throws IOException {
FixedCredentialsProvider.create(Mockito.mock(Credentials.class)));

ApiTracerFactory apiTracerFactory = Mockito.mock(SpanTracerFactory.class);
Mockito.doReturn(true).when(apiTracerFactory).needsContext();
Mockito.doReturn(apiTracerFactory).when(apiTracerFactory).withContext(Mockito.any());

FakeStubSettings settings = Mockito.spy(builder.build());
Expand Down
Loading
Loading