Skip to content
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
9 changes: 7 additions & 2 deletions gax-java/dependencies.properties
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ maven.com_google_api_grpc_proto_google_common_protos=com.google.api.grpc:proto-g
maven.com_google_api_grpc_grpc_google_common_protos=com.google.api.grpc:grpc-google-common-protos:2.63.2
maven.com_google_auth_google_auth_library_oauth2_http=com.google.auth:google-auth-library-oauth2-http:1.42.1
maven.com_google_auth_google_auth_library_credentials=com.google.auth:google-auth-library-credentials:1.42.1
maven.io_opentelemetry_opentelemetry_api=io.opentelemetry:opentelemetry-api:1.47.0
maven.io_opentelemetry_opentelemetry_context=io.opentelemetry:opentelemetry-context:1.47.0
maven.io_opentelemetry_opentelemetry_api=io.opentelemetry:opentelemetry-api:1.51.0
maven.io_opentelemetry_opentelemetry_context=io.opentelemetry:opentelemetry-context:1.51.0
maven.io_opencensus_opencensus_api=io.opencensus:opencensus-api:0.31.1
maven.io_opencensus_opencensus_contrib_grpc_metrics=io.opencensus:opencensus-contrib-grpc-metrics:0.31.1
maven.io_opencensus_opencensus_contrib_http_util=io.opencensus:opencensus-contrib-http-util:0.31.1
Expand Down Expand Up @@ -91,3 +91,8 @@ maven.net_bytebuddy_byte_buddy=net.bytebuddy:byte-buddy:1.17.0
maven.org_objenesis_objenesis=org.objenesis:objenesis:2.6
maven.org_junit_jupiter_junit_jupiter_api=org.junit.jupiter:junit-jupiter-api:5.11.4
maven.org_junit_jupiter_junit_jupiter_params=org.junit.jupiter:junit-jupiter-params:5.11.4
maven.io_opentelemetry_opentelemetry_sdk_testing=io.opentelemetry:opentelemetry-sdk-testing:1.51.0
maven.io_opentelemetry_opentelemetry_sdk=io.opentelemetry:opentelemetry-sdk:1.51.0
maven.io_opentelemetry_opentelemetry_sdk_common=io.opentelemetry:opentelemetry-sdk-common:1.51.0
maven.io_opentelemetry_opentelemetry_sdk_metrics=io.opentelemetry:opentelemetry-sdk-metrics:1.51.0
maven.com_google_guava_guava_testlib=com.google.guava:guava-testlib:32.1.3-jre
5 changes: 5 additions & 0 deletions gax-java/gax/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@ _TEST_COMPILE_DEPS = [
"@net_bytebuddy_byte_buddy//jar",
"@org_objenesis_objenesis//jar",
"@com_googlecode_java_diff_utils_diffutils//jar",
"@io_opentelemetry_opentelemetry_sdk_testing//jar",
"@io_opentelemetry_opentelemetry_sdk//jar",
"@io_opentelemetry_opentelemetry_sdk_metrics//jar",
"@io_opentelemetry_opentelemetry_sdk_common//jar",
"@com_google_guava_guava_testlib//jar",
]

java_library(
Expand Down
11 changes: 11 additions & 0 deletions gax-java/gax/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,17 @@
<artifactId>opentelemetry-context</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-sdk-testing</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava-testlib</artifactId>
<version>${guava.version}</version>
<scope>test</scope>
</dependency>
<!-- Logging dependency -->
<dependency>
<groupId>org.slf4j</groupId>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/*
* 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 io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.metrics.DoubleHistogram;
import io.opentelemetry.api.metrics.Meter;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
* This class takes an OpenTelemetry object, and creates instruments (meters, histograms etc.) from
* it for recording golden signal metrics. There must be only one instance of
* GoldenSignalsMetricsRecorder per client, all the methods in this class are expected to be called
* from multiple threads, hence they need to be thread safe.
*/
class GoldenSignalsMetricsRecorder {
static final String CLIENT_REQUEST_DURATION_METRIC_NAME = "gcp.client.request.duration";
static final String CLIENT_REQUEST_DURATION_METRIC_DESCRIPTION =
"Measures the total time taken for a logical client request, including any retries, backoff, and pre/post-processing";

static final List<Double> BOUNDARIES =
Arrays.asList(
0.0, 0.0001, 0.0005, 0.0010, 0.005, 0.010, 0.050, 0.100, 0.5, 1.0, 5.0, 10.0, 60.0, 300.0,
900.0, 3600.0);
final DoubleHistogram clientRequestDurationRecorder;

GoldenSignalsMetricsRecorder(OpenTelemetry openTelemetry, String libraryName) {
Meter meter = openTelemetry.meterBuilder(libraryName).build();

this.clientRequestDurationRecorder =
meter
.histogramBuilder(CLIENT_REQUEST_DURATION_METRIC_NAME)
.setDescription(CLIENT_REQUEST_DURATION_METRIC_DESCRIPTION)
.setUnit("s")
.setExplicitBucketBoundariesAdvice(BOUNDARIES)
.build();
}

void recordOperationLatency(double operationLatency, Map<String, String> attributes) {
clientRequestDurationRecorder.record(
operationLatency, ObservabilityUtils.toOtelAttributes(attributes));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
/*
* 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 static com.google.api.gax.tracing.ObservabilityAttributes.RPC_RESPONSE_STATUS_ATTRIBUTE;

import com.google.api.gax.rpc.StatusCode;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Stopwatch;
import com.google.common.base.Ticker;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
* This class computes golden signal metrics that can be observed in the lifecycle of an RPC
* operation. The responsibility of recording metrics should delegate to {@link
* GoldenSignalsMetricsRecorder}, hence this class should not have any knowledge about the
* observability framework (e.g. OpenTelemetry).
*/
class GoldenSignalsMetricsTracer implements ApiTracer {
private final Stopwatch clientRequestTimer;
private final GoldenSignalsMetricsRecorder metricsRecorder;
private final Map<String, String> attributes = new HashMap<>();

/**
* Creates the following instruments for the following metrics:
*
* <ul>
* <li>Client Request Duration: Histogram
* </ul>
*
* @param metricsRecorder OpenTelemetry
*/
GoldenSignalsMetricsTracer(GoldenSignalsMetricsRecorder metricsRecorder) {
this.clientRequestTimer = Stopwatch.createStarted();
this.metricsRecorder = metricsRecorder;
}

@VisibleForTesting
GoldenSignalsMetricsTracer(GoldenSignalsMetricsRecorder metricsRecorder, Ticker ticker) {
this.clientRequestTimer = Stopwatch.createStarted(ticker);
this.metricsRecorder = metricsRecorder;
}

/**
* The concept of "operation" and "client request" are the same. They both represent the total
* time taken for a logical client request, including any retries, backoff, and
* pre/post-processing
*/
@Override
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Add more doc that "Operation" is actually "Client Request" in the context of golden signal metrics.

public void operationSucceeded() {
attributes.put(RPC_RESPONSE_STATUS_ATTRIBUTE, StatusCode.Code.OK.toString());
metricsRecorder.recordOperationLatency(
clientRequestTimer.elapsed(TimeUnit.NANOSECONDS) / 1_000_000_000.0, attributes);
}

@Override
public void operationCancelled() {
attributes.put(RPC_RESPONSE_STATUS_ATTRIBUTE, StatusCode.Code.CANCELLED.toString());
metricsRecorder.recordOperationLatency(
clientRequestTimer.elapsed(TimeUnit.NANOSECONDS) / 1_000_000_000.0, attributes);
}

@Override
public void operationFailed(Throwable error) {
attributes.put(RPC_RESPONSE_STATUS_ATTRIBUTE, ObservabilityUtils.extractStatus(error));
metricsRecorder.recordOperationLatency(
clientRequestTimer.elapsed(TimeUnit.NANOSECONDS) / 1_000_000_000.0, attributes);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/*
* 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.BetaApi;
import com.google.api.core.InternalApi;
import io.opentelemetry.api.OpenTelemetry;

/**
* A {@link ApiTracerFactory} to build instances of {@link GoldenSignalsMetricsTracer}.
*
* <p>This class is expected to be initialized once during client initialization.
*/
@BetaApi
@InternalApi
public class GoldenSignalsMetricsTracerFactory implements ApiTracerFactory {

private ApiTracerContext apiTracerContext;

Check warning on line 45 in gax-java/gax/src/main/java/com/google/api/gax/tracing/GoldenSignalsMetricsTracerFactory.java

View check run for this annotation

SonarQubeCloud / [gapic-generator-java-root] SonarCloud Code Analysis

Remove the "apiTracerContext" field and declare it as a local variable in the relevant methods.

See more on https://sonarcloud.io/project/issues?id=googleapis_gapic-generator-java&issues=AZzUjUp-WDS9qebI_0nt&open=AZzUjUp-WDS9qebI_0nt&pullRequest=4132

Check warning on line 45 in gax-java/gax/src/main/java/com/google/api/gax/tracing/GoldenSignalsMetricsTracerFactory.java

View check run for this annotation

SonarQubeCloud / [java_showcase_integration_tests] SonarCloud Code Analysis

Remove the "apiTracerContext" field and declare it as a local variable in the relevant methods.

See more on https://sonarcloud.io/project/issues?id=googleapis_gapic-generator-java_integration_tests&issues=AZzUkN8MEH4qK0277yMy&open=AZzUkN8MEH4qK0277yMy&pullRequest=4132
private final OpenTelemetry openTelemetry;
private GoldenSignalsMetricsRecorder metricsRecorder;

public GoldenSignalsMetricsTracerFactory(OpenTelemetry openTelemetry) {
this.openTelemetry = openTelemetry;
}

@Override
public ApiTracer newTracer(ApiTracer parent, SpanName spanName, OperationType operationType) {
if (metricsRecorder == null) {
// This should never happen, in case it happens, create a no-op api tracer to not block
// regular requests.
return new BaseApiTracer();
}
return new GoldenSignalsMetricsTracer(metricsRecorder);
}
Comment on lines +54 to +61
Copy link
Contributor

Choose a reason for hiding this comment

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

high

The apiTracerContext field is not initialized in the constructor and can be null if newTracer is called before withContext. This would lead to a NullPointerException when apiTracerContext.libraryMetadata() is called inside the GoldenTelemetryMetricsTracer constructor. To make the factory more robust against misuse, please add a null-check for apiTracerContext and throw an IllegalStateException if it hasn't been set.

  public ApiTracer newTracer(ApiTracer parent, SpanName spanName, OperationType operationType) {
    if (apiTracerContext == null) {
      throw new IllegalStateException(
          "ApiTracerContext has not been set. Call withContext() before creating a new tracer.");
    }
    return new GoldenTelemetryMetricsTracer(openTelemetry, apiTracerContext);
  }
References
  1. Explicit if checks for null handling are preferred for better readability in simple cases, aligning with the preference over java.util.Optional for such scenarios.

Copy link
Contributor

Choose a reason for hiding this comment

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

I think this should not happen with the current setup but +1 for the extra safety "against misuse" a null check brings.


@Override
public ApiTracerFactory withContext(ApiTracerContext context) {
this.apiTracerContext = context;
this.metricsRecorder =
new GoldenSignalsMetricsRecorder(
openTelemetry, apiTracerContext.libraryMetadata().artifactName());
return this;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,16 +35,13 @@
import com.google.api.core.BetaApi;
import com.google.api.core.InternalApi;
import com.google.api.core.ObsoleteApi;
import com.google.api.gax.rpc.ApiException;
import com.google.api.gax.rpc.StatusCode;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Stopwatch;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CancellationException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.annotation.Nullable;

/**
* This class computes generic metrics that can be observed in the lifecycle of an RPC operation.
Expand Down Expand Up @@ -123,7 +120,7 @@ public void operationFailed(Throwable error) {
if (operationFinished.getAndSet(true)) {
throw new IllegalStateException(OPERATION_FINISHED_STATUS_MESSAGE);
}
attributes.put(STATUS_ATTRIBUTE, extractStatus(error));
attributes.put(STATUS_ATTRIBUTE, ObservabilityUtils.extractStatus(error));
metricsRecorder.recordOperationLatency(
operationTimer.elapsed(TimeUnit.MILLISECONDS), attributes);
metricsRecorder.recordOperationCount(1, attributes);
Expand Down Expand Up @@ -175,7 +172,7 @@ public void attemptCancelled() {
*/
@Override
public void attemptFailedDuration(Throwable error, java.time.Duration delay) {
attributes.put(STATUS_ATTRIBUTE, extractStatus(error));
attributes.put(STATUS_ATTRIBUTE, ObservabilityUtils.extractStatus(error));
metricsRecorder.recordAttemptLatency(attemptTimer.elapsed(TimeUnit.MILLISECONDS), attributes);
metricsRecorder.recordAttemptCount(1, attributes);
}
Expand All @@ -199,7 +196,7 @@ public void attemptFailed(Throwable error, org.threeten.bp.Duration delay) {
*/
@Override
public void attemptFailedRetriesExhausted(Throwable error) {
attributes.put(STATUS_ATTRIBUTE, extractStatus(error));
attributes.put(STATUS_ATTRIBUTE, ObservabilityUtils.extractStatus(error));
metricsRecorder.recordAttemptLatency(attemptTimer.elapsed(TimeUnit.MILLISECONDS), attributes);
metricsRecorder.recordAttemptCount(1, attributes);
}
Expand All @@ -213,29 +210,11 @@ public void attemptFailedRetriesExhausted(Throwable error) {
*/
@Override
public void attemptPermanentFailure(Throwable error) {
attributes.put(STATUS_ATTRIBUTE, extractStatus(error));
attributes.put(STATUS_ATTRIBUTE, ObservabilityUtils.extractStatus(error));
metricsRecorder.recordAttemptLatency(attemptTimer.elapsed(TimeUnit.MILLISECONDS), attributes);
metricsRecorder.recordAttemptCount(1, attributes);
}

/** Function to extract the status of the error as a string */
@VisibleForTesting
static String extractStatus(@Nullable Throwable error) {
final String statusString;

if (error == null) {
return StatusCode.Code.OK.toString();
} else if (error instanceof CancellationException) {
statusString = StatusCode.Code.CANCELLED.toString();
} else if (error instanceof ApiException) {
statusString = ((ApiException) error).getStatusCode().getCode().toString();
} else {
statusString = StatusCode.Code.UNKNOWN.toString();
}

return statusString;
}

/**
* Add attributes that will be attached to all metrics. This is expected to be called by
* handwritten client teams to add additional attributes that are not supposed be collected by
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,10 @@ public class ObservabilityAttributes {

/** The RPC system name, e.g. 'grpc' or 'http'. */
public static final String RPC_SYSTEM_NAME_ATTRIBUTE = "rpc.system.name";

/**
* The error codes of the request. The value will be the string representation of the canonical
* gRPC status code (e.g., "OK", "INTERNAL").
*/
public static final String RPC_RESPONSE_STATUS_ATTRIBUTE = "rpc.response.status_code";
}
Loading
Loading