From bb06e800e7ef644b45e106976f27717ebeee07fa Mon Sep 17 00:00:00 2001 From: Nidhi Nandwani Date: Thu, 19 Nov 2026 16:13:02 +0000 Subject: [PATCH 1/2] feat(storage): promote server.unreached to Standard tier with gRPC and HTTP heuristics Promote gcp.storage.client.server.unreached to the Standard metrics tier with unit "{request}" and record exact 8-key attributes across gRPC (DirectPath/CloudPath heuristics) and HTTP (X-GUploader-UploadID / X-Goog-Gfe-Service-Time markers and IOException handler). [Generated-by: AI] --- .../cloud/storage/StorageClientMetrics.java | 45 ++-- .../StorageGrpcMetricsInterceptor.java | 67 ++++- .../StorageHttpMetricsInterceptor.java | 43 +++- .../storage/StorageClientMetricsTest.java | 62 ++++- .../StorageGrpcMetricsInterceptorTest.java | 229 +++++++++++++++++- .../StorageHttpMetricsInterceptorTest.java | 137 ++++++++++- 6 files changed, 542 insertions(+), 41 deletions(-) diff --git a/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageClientMetrics.java b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageClientMetrics.java index 19d2e04fed3d..285028a61479 100644 --- a/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageClientMetrics.java +++ b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageClientMetrics.java @@ -86,14 +86,14 @@ final class StorageClientMetrics implements AutoCloseable { "gcp.storage.client.request.body.size"; static final String METRIC_GCP_STORAGE_CLIENT_RESPONSE_BODY_SIZE = "gcp.storage.client.response.body.size"; + static final String METRIC_GCP_STORAGE_CLIENT_SERVER_UNREACHED = + "gcp.storage.client.server.unreached"; // Debug metric names static final String METRIC_GCP_STORAGE_CLIENT_REQUEST_ACTIVE = "gcp.storage.client.request.active"; static final String METRIC_GCP_STORAGE_CLIENT_SERVER_DURATION = "gcp.storage.client.server.duration"; - static final String METRIC_GCP_STORAGE_CLIENT_SERVER_UNREACHED = - "gcp.storage.client.server.unreached"; static final String METRIC_GCP_STORAGE_CLIENT_STALL_DURATION = "gcp.storage.client.stall.duration"; static final String METRIC_GCP_STORAGE_CLIENT_NETWORK_IO = "gcp.storage.client.network.io"; @@ -191,10 +191,10 @@ static StorageClientMetrics create( @Nullable private final DoubleHistogram ttfb; @Nullable private final LongHistogram requestBodySize; @Nullable private final LongHistogram responseBodySize; + @Nullable private final LongCounter serverUnreached; @Nullable private final LongUpDownCounter requestActive; @Nullable private final DoubleHistogram serverDuration; - @Nullable private final LongCounter serverUnreached; @Nullable private final DoubleHistogram stallDuration; @Nullable private final LongCounter networkIo; @Nullable private final DoubleHistogram credentialRefreshDuration; @@ -299,6 +299,12 @@ private StorageClientMetrics( .setExplicitBucketBoundariesAdvice( OpenTelemetryBootstrappingUtils.sizeHistogramLongBoundaries()) .build(); + this.serverUnreached = + meter + .counterBuilder(METRIC_GCP_STORAGE_CLIENT_SERVER_UNREACHED) + .setDescription("Count of requests that failed before reaching the GCS server.") + .setUnit("{request}") + .build(); } else { this.rpcClientCallDuration = null; this.httpClientRequestDuration = null; @@ -310,6 +316,7 @@ private StorageClientMetrics( this.ttfb = null; this.requestBodySize = null; this.responseBodySize = null; + this.serverUnreached = null; } if (enableOtelDebugMetrics) { @@ -329,15 +336,6 @@ private StorageClientMetrics( .setExplicitBucketBoundariesAdvice( OpenTelemetryBootstrappingUtils.latencyHistogramBoundaries()) .build(); - this.serverUnreached = - meter - .counterBuilder(METRIC_GCP_STORAGE_CLIENT_SERVER_UNREACHED) - .setDescription( - "Number of attempts that received no response from a GCS server (gRPC:" - + " grpc-server-stats-bin trailer absent; HTTP: X-GUploader-UploadID header" - + " absent).") - .setUnit("{attempt}") - .build(); this.stallDuration = meter .histogramBuilder(METRIC_GCP_STORAGE_CLIENT_STALL_DURATION) @@ -369,7 +367,6 @@ private StorageClientMetrics( } else { this.requestActive = null; this.serverDuration = null; - this.serverUnreached = null; this.stallDuration = null; this.networkIo = null; this.credentialRefreshDuration = null; @@ -431,6 +428,10 @@ Attributes attachClientAttributes(@Nullable Attributes other) { return responseBodySize; } + @Nullable LongCounter getServerUnreached() { + return serverUnreached; + } + @Nullable LongUpDownCounter getRequestActive() { return requestActive; } @@ -439,10 +440,6 @@ Attributes attachClientAttributes(@Nullable Attributes other) { return serverDuration; } - @Nullable LongCounter getServerUnreached() { - return serverUnreached; - } - @Nullable DoubleHistogram getStallDuration() { return stallDuration; } @@ -552,6 +549,20 @@ void recordServerDuration( serverDuration.record(durationSeconds, attributes, otelContext); } + void recordServerUnreached( + Context otelContext, String operationName, String networkPath, String errorType) { + if (serverUnreached == null) { + return; + } + Attributes attributes = + baseAttributes.toBuilder() + .put(KEY_GCP_STORAGE_OPERATION, operationName) + .put(KEY_NETWORK_PATH, networkPath) + .put(KEY_ERROR_TYPE, errorType) + .build(); + serverUnreached.add(1L, attributes, otelContext); + } + @Nullable static StorageMetricsContext createContext( @Nullable StorageClientMetrics metrics, String operationName) { diff --git a/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageGrpcMetricsInterceptor.java b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageGrpcMetricsInterceptor.java index 3152a215837c..5d532321ad81 100644 --- a/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageGrpcMetricsInterceptor.java +++ b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageGrpcMetricsInterceptor.java @@ -52,6 +52,8 @@ final class StorageGrpcMetricsInterceptor implements ClientInterceptor { static final Metadata.Key GRPC_SERVER_STATS_BIN_KEY = Metadata.Key.of("grpc-server-stats-bin", Metadata.BINARY_BYTE_MARSHALLER); + static final Metadata.Key UPLOADER_UPLOAD_ID_KEY = + Metadata.Key.of("x-guploader-uploadid", Metadata.ASCII_STRING_MARSHALLER); private final StorageClientMetrics metrics; private final ApiClock clock; @@ -84,8 +86,15 @@ public void start(Listener responseListener, Metadata headers) { super.start( new SimpleForwardingClientCallListener(responseListener) { + private boolean receivedServerHeaders; + private boolean headerHasUploadId; + @Override public void onHeaders(Metadata headers) { + receivedServerHeaders = true; + if (hasNonEmptyMetadata(headers, UPLOADER_UPLOAD_ID_KEY)) { + headerHasUploadId = true; + } if (metricsCtx != null) { metricsCtx.setNetworkPath(detectNetworkPath(getAttributes())); } @@ -117,12 +126,21 @@ public void onClose(Status status, Metadata trailers) { metrics.recordRpcCallDuration( otelContext, durationSeconds, rpcMethod, statusCode, networkPath, errorType); - if (metrics.getServerDuration() != null) { - double serverDurationSeconds = decodeServerDurationSeconds(trailers); - if (serverDurationSeconds >= 0.0) { - metrics.recordServerDuration( - otelContext, serverDurationSeconds, operationName, networkPath); - } + double serverDurationSeconds = decodeServerDurationSeconds(trailers); + if (serverDurationSeconds >= 0.0) { + metrics.recordServerDuration( + otelContext, serverDurationSeconds, operationName, networkPath); + } + if (isServerUnreached( + networkPath, + status, + errorType, + serverDurationSeconds >= 0.0, + receivedServerHeaders, + headerHasUploadId, + trailers)) { + metrics.recordServerUnreached( + otelContext, operationName, networkPath, errorType); } } finally { metrics.recordRequestActive(otelContext, operationName, -1L); @@ -211,4 +229,41 @@ static boolean isDirectPathIp(InetAddress addr) { } return false; } + + private static boolean isServerUnreached( + String networkPath, + Status status, + String errorType, + boolean hasServerDuration, + boolean receivedServerHeaders, + boolean headerHasUploadId, + Metadata trailers) { + if (StorageClientMetrics.NETWORK_PATH_DIRECTPATH.equals(networkPath)) { + boolean reached = + hasServerDuration || receivedServerHeaders || !trailers.keys().isEmpty() || status.isOk(); + return !reached && isPreServerErrorType(errorType); + } + boolean hasUploadId = + headerHasUploadId || hasNonEmptyMetadata(trailers, UPLOADER_UPLOAD_ID_KEY); + boolean reached = hasServerDuration || hasUploadId; + return !reached && !isAmbiguousClientAbort(errorType); + } + + private static boolean isAmbiguousClientAbort(String errorType) { + return StorageErrorTypeMapper.STATUS_CANCELLED.equals(errorType) + || StorageErrorTypeMapper.STATUS_TIMEOUT.equals(errorType) + || StorageErrorTypeMapper.STATUS_DEADLINE_EXCEEDED.equals(errorType); + } + + private static boolean isPreServerErrorType(String errorType) { + return StorageErrorTypeMapper.STATUS_AUTHENTICATION_ERROR.equals(errorType) + || StorageErrorTypeMapper.STATUS_TLS_FAILURE.equals(errorType) + || StorageErrorTypeMapper.STATUS_DNS_FAILURE.equals(errorType) + || StorageErrorTypeMapper.STATUS_CONNECTION_ERROR.equals(errorType); + } + + private static boolean hasNonEmptyMetadata(Metadata metadata, Metadata.Key key) { + String value = metadata.get(key); + return value != null && !value.isEmpty(); + } } diff --git a/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageHttpMetricsInterceptor.java b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageHttpMetricsInterceptor.java index 2e7b54c49f2a..e5bc9f96c87a 100644 --- a/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageHttpMetricsInterceptor.java +++ b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageHttpMetricsInterceptor.java @@ -23,6 +23,7 @@ import com.google.api.client.http.HttpIOExceptionHandler; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestInitializer; +import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpResponseInterceptor; import com.google.api.client.http.HttpUnsuccessfulResponseHandler; import com.google.api.core.ApiClock; @@ -54,6 +55,9 @@ @NullMarked final class StorageHttpMetricsInterceptor implements HttpRequestInitializer { + static final String HEADER_UPLOADER_UPLOAD_ID = "X-GUploader-UploadID"; + static final String HEADER_GFE_SERVICE_TIME = "X-Goog-Gfe-Service-Time"; + private static final ImmutableSet OBJECT_SUB_RESOURCES = ImmutableSet.of("acl", "compose", "restore"); @@ -170,9 +174,9 @@ public void initialize(HttpRequest request) throws IOException { activeOtelContext.get(), activeOperationName.get(), -1L); recordResponse( req, + response, startTimeNanos.get(), endNanos, - response.getStatusCode(), /* isRetry= */ handled && supportsRetry); } } @@ -191,11 +195,7 @@ public void initialize(HttpRequest request) throws IOException { if (response.getRequest() == request && recorded.compareAndSet(false, true)) { metrics.recordRequestActive(activeOtelContext.get(), activeOperationName.get(), -1L); recordResponse( - request, - startTimeNanos.get(), - endNanos, - response.getStatusCode(), - /* isRetry= */ false); + request, response, startTimeNanos.get(), endNanos, /* isRetry= */ false); } } }); @@ -207,25 +207,33 @@ public void initialize(HttpRequest request) throws IOException { (req, supportsRetry) -> { long endNanos = clock.nanoTime(); boolean recordedThisAttempt = recorded.compareAndSet(false, true); - String urlTemplate = recordedThisAttempt ? extractUrlTemplate(req.getUrl()) : ""; + Context otelContext = Context.root(); + String operationName = ""; if (recordedThisAttempt) { metrics.recordRequestActive(activeOtelContext.get(), activeOperationName.get(), -1L); double durationSeconds = (endNanos - startTimeNanos.get()) / 1_000_000_000.0; + String urlTemplate = extractUrlTemplate(req.getUrl()); recordDuration( req, durationSeconds, 0L, urlTemplate, StorageErrorTypeMapper.STATUS_CONNECTION_ERROR); + StorageMetricsContext ctx = StorageMetricsContext.current(); + otelContext = ctx != null ? ctx.getOtelContext() : Context.current(); + operationName = resolveOperationName(ctx, req, urlTemplate); + metrics.recordServerUnreached( + otelContext, + operationName, + StorageClientMetrics.NETWORK_PATH_CLOUDPATH, + StorageErrorTypeMapper.STATUS_CONNECTION_ERROR); } boolean handled = existingIoHandler != null && existingIoHandler.handleIOException(req, supportsRetry); if (supportsRetry && handled && recordedThisAttempt) { - StorageMetricsContext ctx = StorageMetricsContext.current(); - Context otelContext = ctx != null ? ctx.getOtelContext() : Context.current(); metrics.recordRetry( otelContext, - resolveOperationName(ctx, req, urlTemplate), + operationName, StorageClientMetrics.NETWORK_PATH_CLOUDPATH, StorageErrorTypeMapper.STATUS_CONNECTION_ERROR); } @@ -234,7 +242,8 @@ public void initialize(HttpRequest request) throws IOException { } private void recordResponse( - HttpRequest request, long startNanos, long endNanos, int statusCode, boolean isRetry) { + HttpRequest request, HttpResponse response, long startNanos, long endNanos, boolean isRetry) { + int statusCode = response.getStatusCode(); double durationSeconds = (endNanos - startNanos) / 1_000_000_000.0; String urlTemplate = extractUrlTemplate(request.getUrl()); String errorType = @@ -250,6 +259,13 @@ private void recordResponse( String operationName = resolveOperationName(ctx, request, urlTemplate); metrics.recordTtfb( otelContext, operationName, durationSeconds, StorageClientMetrics.NETWORK_PATH_CLOUDPATH); + boolean reached = + hasNonEmptyHeader(response, HEADER_UPLOADER_UPLOAD_ID) + || hasNonEmptyHeader(response, HEADER_GFE_SERVICE_TIME); + if (!reached) { + metrics.recordServerUnreached( + otelContext, operationName, StorageClientMetrics.NETWORK_PATH_CLOUDPATH, errorType); + } if (isRetry) { metrics.recordRetry( otelContext, operationName, StorageClientMetrics.NETWORK_PATH_CLOUDPATH, errorType); @@ -411,4 +427,9 @@ private static String extractObjectUrlTemplate(String[] segments) { } return "/storage/v1/b/{bucket}/o/{object}"; } + + private static boolean hasNonEmptyHeader(HttpResponse response, String headerName) { + String value = response.getHeaders().getFirstHeaderStringValue(headerName); + return value != null && !value.isEmpty(); + } } diff --git a/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageClientMetricsTest.java b/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageClientMetricsTest.java index 2e3ad9a252ca..bac9b60883a8 100644 --- a/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageClientMetricsTest.java +++ b/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageClientMetricsTest.java @@ -58,13 +58,13 @@ public final class StorageClientMetricsTest { StorageClientMetrics::getErrors, StorageClientMetrics::getTtfb, StorageClientMetrics::getRequestBodySize, - StorageClientMetrics::getResponseBodySize); + StorageClientMetrics::getResponseBodySize, + StorageClientMetrics::getServerUnreached); private static final List> DEBUG_INSTRUMENTS = ImmutableList.of( StorageClientMetrics::getRequestActive, StorageClientMetrics::getServerDuration, - StorageClientMetrics::getServerUnreached, StorageClientMetrics::getStallDuration, StorageClientMetrics::getNetworkIo, StorageClientMetrics::getCredentialRefreshDuration); @@ -229,7 +229,7 @@ public void inMemoryMetricReader_verifiesViewsAndBoundaries() { String serverUnreachedName = StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_SERVER_UNREACHED.replace(".", "/"); assertThat(metricsMap).containsKey(serverUnreachedName); - assertThat(metricsMap.get(serverUnreachedName).getUnit()).isEqualTo("{attempt}"); + assertThat(metricsMap.get(serverUnreachedName).getUnit()).isEqualTo("{request}"); assertThat(metricsMap) .containsKey(StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_NETWORK_IO.replace(".", "/")); @@ -581,6 +581,62 @@ public void recordServerDuration_recordsExactSevenAttributes() { .build()); } + @Test + public void recordServerUnreached_recordsExactEightAttributes() { + SdkMeterProvider provider = SdkMeterProvider.builder().registerMetricReader(reader).build(); + StorageClientMetrics disabledMetrics = StorageClientMetrics.create(provider, false, false); + disabledMetrics.recordServerUnreached( + Context.current(), + "GetObject", + StorageClientMetrics.NETWORK_PATH_CLOUDPATH, + StorageErrorTypeMapper.STATUS_CONNECTION_ERROR); + assertThat(findMetric(StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_SERVER_UNREACHED)) + .isNull(); + + StorageClientMetrics standardMetrics = + StorageOptions.http() + .setProjectId("test-project") + .setCredentials(NoCredentials.getInstance()) + .setEnableOtelMetrics(true) + .setMeterProvider(provider) + .build() + .getStorageClientMetrics(); + + standardMetrics.recordServerUnreached( + Context.current(), + "GetObject", + StorageClientMetrics.NETWORK_PATH_CLOUDPATH, + StorageErrorTypeMapper.STATUS_CONNECTION_ERROR); + + MetricData metricData = + findMetric(StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_SERVER_UNREACHED); + assertThat(metricData).isNotNull(); + assertThat(metricData.getUnit()).isEqualTo("{request}"); + assertThat(metricData.getLongSumData().getPoints()).hasSize(1); + LongPointData point = metricData.getLongSumData().getPoints().iterator().next(); + assertThat(point.getValue()).isEqualTo(1L); + assertThat(point.getAttributes()) + .isEqualTo( + Attributes.builder() + .put( + StorageClientMetrics.KEY_GCP_CLIENT_SERVICE, + StorageClientMetrics.SERVICE_STORAGE) + .put(StorageClientMetrics.KEY_GCP_CLIENT_VERSION, StorageOptions.version()) + .put( + StorageClientMetrics.KEY_GCP_CLIENT_ARTIFACT, + StorageClientMetrics.ARTIFACT_STORAGE) + .put(StorageClientMetrics.KEY_RPC_SYSTEM_NAME, "http") + .put(StorageClientMetrics.KEY_SERVER_ADDRESS, "storage.googleapis.com") + .put(StorageClientMetrics.KEY_GCP_STORAGE_OPERATION, "GetObject") + .put( + StorageClientMetrics.KEY_NETWORK_PATH, + StorageClientMetrics.NETWORK_PATH_CLOUDPATH) + .put( + StorageClientMetrics.KEY_ERROR_TYPE, + StorageErrorTypeMapper.STATUS_CONNECTION_ERROR) + .build()); + } + static final class TestMetricReader implements MetricReader { private final MetricReader delegate = InMemoryMetricReader.create(); final AtomicBoolean shutdownCalled = new AtomicBoolean(false); diff --git a/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageGrpcMetricsInterceptorTest.java b/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageGrpcMetricsInterceptorTest.java index 0675f0a89df7..f69bb9540ee1 100644 --- a/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageGrpcMetricsInterceptorTest.java +++ b/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageGrpcMetricsInterceptorTest.java @@ -53,10 +53,12 @@ import io.opentelemetry.sdk.metrics.data.MetricData; import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; import java.io.ByteArrayInputStream; +import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.net.InetAddress; import java.net.InetSocketAddress; +import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.ArrayList; @@ -64,7 +66,10 @@ import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicLong; +import javax.net.ssl.SSLException; +import javax.security.sasl.AuthenticationException; import org.jspecify.annotations.Nullable; import org.junit.Before; import org.junit.Test; @@ -482,6 +487,166 @@ public void interceptCall_serverDuration_recordsWhenDebugEnabledAndValidTrailerP .build()); } + @Test + public void interceptCall_serverUnreached_directPathAndCloudPathRules() throws Exception { + Attributes directPathAttrs = + Attributes.newBuilder() + .set( + Grpc.TRANSPORT_ATTR_REMOTE_ADDR, + new InetSocketAddress(InetAddress.getByName("34.126.1.2"), 443)) + .build(); + Attributes cloudPathAttrs = + Attributes.newBuilder() + .set( + Grpc.TRANSPORT_ATTR_REMOTE_ADDR, + new InetSocketAddress(InetAddress.getByName("142.250.1.1"), 443)) + .build(); + Metadata headerWithUploadId = new Metadata(); + headerWithUploadId.put(StorageGrpcMetricsInterceptor.UPLOADER_UPLOAD_ID_KEY, "upload-1"); + Metadata headerWithEmptyUploadId = new Metadata(); + headerWithEmptyUploadId.put(StorageGrpcMetricsInterceptor.UPLOADER_UPLOAD_ID_KEY, ""); + Metadata trailerWithStats = new Metadata(); + trailerWithStats.put( + StorageGrpcMetricsInterceptor.GRPC_SERVER_STATS_BIN_KEY, + encodeServerStats(0, 0, 50_000_000L)); + Metadata trailerNonEmpty = new Metadata(); + trailerNonEmpty.put(Metadata.Key.of("x-custom-trailer", Metadata.ASCII_STRING_MARSHALLER), "v"); + + // DirectPath & unknown: only pre-server errors with no headers/trailers/stats/OK are unreached. + assertServerUnreached( + "dp connection error", + directPathAttrs, + null, + new Metadata(), + Status.UNAVAILABLE.withCause(new IOException("connect failed")), + StorageClientMetrics.NETWORK_PATH_DIRECTPATH, + StorageErrorTypeMapper.STATUS_CONNECTION_ERROR); + assertServerUnreached( + "dp dns failure", + directPathAttrs, + null, + new Metadata(), + Status.UNAVAILABLE.withCause(new UnknownHostException("dns")), + StorageClientMetrics.NETWORK_PATH_DIRECTPATH, + StorageErrorTypeMapper.STATUS_DNS_FAILURE); + assertServerUnreached( + "dp tls failure", + directPathAttrs, + null, + new Metadata(), + Status.UNAVAILABLE.withCause(new SSLException("tls")), + StorageClientMetrics.NETWORK_PATH_DIRECTPATH, + StorageErrorTypeMapper.STATUS_TLS_FAILURE); + assertServerUnreached( + "dp authentication error", + directPathAttrs, + null, + new Metadata(), + Status.UNAUTHENTICATED.withCause(new AuthenticationException("token failed")), + StorageClientMetrics.NETWORK_PATH_DIRECTPATH, + StorageErrorTypeMapper.STATUS_AUTHENTICATION_ERROR); + assertServerUnreached( + "unknown path pre-connect error", + Attributes.EMPTY, + null, + new Metadata(), + Status.UNAVAILABLE.withCause(new IOException("connection refused")), + StorageClientMetrics.NETWORK_PATH_UNKNOWN, + StorageErrorTypeMapper.STATUS_CONNECTION_ERROR); + assertServerUnreached( + "dp bare UNAVAILABLE not pre-server", + directPathAttrs, + null, + new Metadata(), + Status.UNAVAILABLE, + null, + null); + assertServerUnreached( + "dp connection error after headers received", + directPathAttrs, + new Metadata(), + new Metadata(), + Status.UNAVAILABLE.withCause(new IOException("reset")), + null, + null); + assertServerUnreached( + "dp connection error with non-empty trailers", + directPathAttrs, + null, + trailerNonEmpty, + Status.UNAVAILABLE.withCause(new IOException("reset")), + null, + null); + assertServerUnreached( + "dp OK without headers", directPathAttrs, null, new Metadata(), Status.OK, null, null); + + // CloudPath: unreached when no stats-bin and no x-guploader-uploadid, excluding client aborts. + assertServerUnreached( + "cp UNAVAILABLE without markers", + cloudPathAttrs, + null, + new Metadata(), + Status.UNAVAILABLE, + StorageClientMetrics.NETWORK_PATH_CLOUDPATH, + StorageErrorTypeMapper.STATUS_UNAVAILABLE); + assertServerUnreached( + "cp empty upload id header treated as absent", + cloudPathAttrs, + headerWithEmptyUploadId, + new Metadata(), + Status.UNAVAILABLE, + StorageClientMetrics.NETWORK_PATH_CLOUDPATH, + StorageErrorTypeMapper.STATUS_UNAVAILABLE); + assertServerUnreached( + "cp reached via header upload id", + cloudPathAttrs, + headerWithUploadId, + new Metadata(), + Status.UNAVAILABLE, + null, + null); + assertServerUnreached( + "cp reached via trailer upload id", + cloudPathAttrs, + null, + headerWithUploadId, + Status.UNAVAILABLE, + null, + null); + assertServerUnreached( + "cp reached via server stats bin", + cloudPathAttrs, + null, + trailerWithStats, + Status.UNAVAILABLE, + null, + null); + assertServerUnreached( + "cp CANCELLED ambiguous abort", + cloudPathAttrs, + null, + new Metadata(), + Status.CANCELLED, + null, + null); + assertServerUnreached( + "cp DEADLINE_EXCEEDED ambiguous abort", + cloudPathAttrs, + null, + new Metadata(), + Status.DEADLINE_EXCEEDED, + null, + null); + assertServerUnreached( + "cp TIMEOUT ambiguous abort", + cloudPathAttrs, + null, + new Metadata(), + Status.UNAVAILABLE.withCause(new TimeoutException("timed out")), + null, + null); + } + @Test public void interceptCall_withStorageMetricsContext_propagatesContextAndFeedsNetworkPath() throws Exception { @@ -735,6 +900,64 @@ public void grpcStorageOptions_interceptorProviderWiring() throws Exception { assertThat(extractInterceptorProvider(disabledDefaultChannelProvider)).isNull(); } + private void assertServerUnreached( + String label, + Attributes attrs, + @Nullable Metadata headers, + Metadata trailers, + Status status, + @Nullable String expectedNetworkPath, + @Nullable String expectedErrorType) { + InMemoryMetricReader caseReader = InMemoryMetricReader.create(); + SdkMeterProvider caseProvider = + SdkMeterProvider.builder().registerMetricReader(caseReader).build(); + StorageClientMetrics caseMetrics = + StorageOptions.grpc() + .setProjectId("test-project") + .setCredentials(NoCredentials.getInstance()) + .setEnableOtelMetrics(true) + .setMeterProvider(caseProvider) + .build() + .getStorageClientMetrics(); + TestClientCall testCall = new TestClientCall<>(attrs); + new StorageGrpcMetricsInterceptor(caseMetrics, clock) + .interceptCall(READ_OBJECT_METHOD, CallOptions.DEFAULT, new TestChannel(testCall)) + .start(new TestListener<>(), new Metadata()); + if (headers != null) { + testCall.receiveHeaders(headers); + } + testCall.close(status, trailers); + + MetricData unreached = + findMetric(caseReader, StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_SERVER_UNREACHED); + if (expectedErrorType == null) { + assertWithMessage(label).that(unreached).isNull(); + return; + } + assertWithMessage(label).that(unreached).isNotNull(); + assertWithMessage(label).that(unreached.getUnit()).isEqualTo("{request}"); + assertWithMessage(label).that(unreached.getLongSumData().getPoints()).hasSize(1); + LongPointData point = unreached.getLongSumData().getPoints().iterator().next(); + assertWithMessage(label).that(point.getValue()).isEqualTo(1L); + assertWithMessage(label) + .that(point.getAttributes()) + .isEqualTo( + io.opentelemetry.api.common.Attributes.builder() + .put( + StorageClientMetrics.KEY_GCP_CLIENT_SERVICE, + StorageClientMetrics.SERVICE_STORAGE) + .put(StorageClientMetrics.KEY_GCP_CLIENT_VERSION, StorageOptions.version()) + .put( + StorageClientMetrics.KEY_GCP_CLIENT_ARTIFACT, + StorageClientMetrics.ARTIFACT_STORAGE) + .put(StorageClientMetrics.KEY_RPC_SYSTEM_NAME, "grpc") + .put(StorageClientMetrics.KEY_SERVER_ADDRESS, "storage.googleapis.com") + .put(StorageClientMetrics.KEY_GCP_STORAGE_OPERATION, "ReadObject") + .put(StorageClientMetrics.KEY_NETWORK_PATH, expectedNetworkPath) + .put(StorageClientMetrics.KEY_ERROR_TYPE, expectedErrorType) + .build()); + } + private StorageGrpcMetricsInterceptor createDebugInterceptor() { StorageClientMetrics debugMetrics = StorageOptions.grpc() @@ -765,7 +988,11 @@ private LongPointData requestActivePoint() { } private @Nullable MetricData findMetric(String name) { - return reader.collectAllMetrics().stream() + return findMetric(reader, name); + } + + private static @Nullable MetricData findMetric(InMemoryMetricReader metricReader, String name) { + return metricReader.collectAllMetrics().stream() .filter(m -> m.getName().equals(name)) .findFirst() .orElse(null); diff --git a/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageHttpMetricsInterceptorTest.java b/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageHttpMetricsInterceptorTest.java index 982984929319..48b8e208228a 100644 --- a/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageHttpMetricsInterceptorTest.java +++ b/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageHttpMetricsInterceptorTest.java @@ -50,6 +50,7 @@ import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; import io.opentelemetry.sdk.metrics.data.HistogramPointData; import io.opentelemetry.sdk.metrics.data.LongPointData; +import io.opentelemetry.sdk.metrics.data.MetricData; import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; import java.io.IOException; import java.nio.ByteBuffer; @@ -58,6 +59,7 @@ import java.util.Objects; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; +import org.jspecify.annotations.Nullable; import org.junit.Before; import org.junit.Test; @@ -700,7 +702,8 @@ public LowLevelHttpResponse execute() throws IOException { assertThat(retries.get(0).getValue()).isEqualTo(1L); assertThat(retries.get(0).getAttributes()) .isEqualTo( - expectedRetryAttributes("GetBucket", StorageErrorTypeMapper.STATUS_CONNECTION_ERROR)); + expectedOperationErrorAttributes( + "GetBucket", StorageErrorTypeMapper.STATUS_CONNECTION_ERROR)); } @Test @@ -781,7 +784,7 @@ public LowLevelHttpResponse execute() { assertThat(retries).hasSize(1); assertThat(retries.get(0).getValue()).isEqualTo(1L); assertThat(retries.get(0).getAttributes()) - .isEqualTo(expectedRetryAttributes("ReadObject", "UNAUTHENTICATED")); + .isEqualTo(expectedOperationErrorAttributes("ReadObject", "UNAUTHENTICATED")); } @Test @@ -963,6 +966,52 @@ public LowLevelHttpResponse execute() { assertSingleRequestActive(0L, "Batch"); } + @Test + public void initialize_serverUnreached_cases() throws IOException { + assertServerUnreached( + "reached via upload id (debug on, no server.duration)", + true, + 200, + StorageHttpMetricsInterceptor.HEADER_UPLOADER_UPLOAD_ID, + "u-123", + null); + assertServerUnreached( + "reached via gfe service time (debug on, no server.duration)", + true, + 503, + StorageHttpMetricsInterceptor.HEADER_GFE_SERVICE_TIME, + "12.5", + null); + assertServerUnreached( + "502 without markers (standard tier)", + false, + 502, + null, + null, + StorageErrorTypeMapper.STATUS_UNAVAILABLE); + assertServerUnreached( + "504 proxy timeout without markers", + false, + 504, + null, + null, + StorageErrorTypeMapper.STATUS_DEADLINE_EXCEEDED); + assertServerUnreached( + "502 with empty upload id header", + false, + 502, + StorageHttpMetricsInterceptor.HEADER_UPLOADER_UPLOAD_ID, + "", + StorageErrorTypeMapper.STATUS_UNAVAILABLE); + assertServerUnreached( + "transport IOException", + false, + 0, + null, + null, + StorageErrorTypeMapper.STATUS_CONNECTION_ERROR); + } + @Test public void initialize_batchPart401_doesNotRecordPartDuration() throws IOException { AtomicBoolean refreshHandlerCalled = new AtomicBoolean(false); @@ -1184,6 +1233,87 @@ private List requestActivePoints() { return longSumPoints(StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_REQUEST_ACTIVE); } + private static @Nullable MetricData findMetric(InMemoryMetricReader metricReader, String name) { + return metricReader.collectAllMetrics().stream() + .filter(m -> m.getName().equals(name)) + .findFirst() + .orElse(null); + } + + private void assertServerUnreached( + String label, + boolean debugEnabled, + int statusCode, + @Nullable String headerName, + @Nullable String headerValue, + @Nullable String expectedError) + throws IOException { + InMemoryMetricReader caseReader = InMemoryMetricReader.create(); + SdkMeterProvider caseProvider = + SdkMeterProvider.builder().registerMetricReader(caseReader).build(); + StorageClientMetrics caseMetrics = + StorageOptions.http() + .setProjectId("test-project") + .setCredentials(NoCredentials.getInstance()) + .setClock(clock) + .setEnableOtelMetrics(true) + .setEnableOtelDebugMetrics(debugEnabled) + .setMeterProvider(caseProvider) + .build() + .getStorageClientMetrics(); + StorageHttpMetricsInterceptor interceptor = + new StorageHttpMetricsInterceptor(null, caseMetrics, clock); + HttpTransport transport = + new MockHttpTransport() { + @Override + public LowLevelHttpRequest buildRequest(String method, String url) { + return new MockLowLevelHttpRequest() { + @Override + public LowLevelHttpResponse execute() throws IOException { + if (statusCode == 0) { + throw new IOException("connection refused"); + } + MockLowLevelHttpResponse resp = + new MockLowLevelHttpResponse().setStatusCode(statusCode); + if (headerName != null) { + resp.addHeader(headerName, headerValue); + } + return resp; + } + }; + } + }; + HttpRequest req = + transport + .createRequestFactory(interceptor) + .buildGetRequest(new GenericUrl("https://storage.googleapis.com/storage/v1/b/my-b")); + if (statusCode == 0) { + assertThrows(IOException.class, req::execute); + } else { + req.setThrowExceptionOnExecuteError(false); + req.execute(); + } + + assertWithMessage(label) + .that( + findMetric(caseReader, StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_SERVER_DURATION)) + .isNull(); + MetricData unreached = + findMetric(caseReader, StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_SERVER_UNREACHED); + if (expectedError == null) { + assertWithMessage(label).that(unreached).isNull(); + return; + } + assertWithMessage(label).that(unreached).isNotNull(); + assertWithMessage(label).that(unreached.getUnit()).isEqualTo("{request}"); + assertWithMessage(label).that(unreached.getLongSumData().getPoints()).hasSize(1); + LongPointData point = unreached.getLongSumData().getPoints().iterator().next(); + assertWithMessage(label).that(point.getValue()).isEqualTo(1L); + assertWithMessage(label) + .that(point.getAttributes()) + .isEqualTo(expectedOperationErrorAttributes("GetBucket", expectedError)); + } + private List longSumPoints(String metricName) { return reader.collectAllMetrics().stream() .filter(m -> m.getName().equals(metricName)) @@ -1212,7 +1342,8 @@ private void assertSingleRequestActive(long expectedValue, String expectedOperat .build()); } - private static Attributes expectedRetryAttributes(String operationName, String errorType) { + private static Attributes expectedOperationErrorAttributes( + String operationName, String errorType) { return Attributes.builder() .put(StorageClientMetrics.KEY_GCP_CLIENT_SERVICE, StorageClientMetrics.SERVICE_STORAGE) .put(StorageClientMetrics.KEY_GCP_CLIENT_VERSION, StorageOptions.version()) From 24a3854dcf9d1f36fcb998b0c8992065cdff10dc Mon Sep 17 00:00:00 2001 From: Nidhi Nandwani Date: Thu, 26 Nov 2026 05:24:33 +0000 Subject: [PATCH 2/2] fix(storage): shorten the server.unreached counter description [Generated-by: AI] --- .../com/google/cloud/storage/StorageClientMetrics.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageClientMetrics.java b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageClientMetrics.java index 285028a61479..bd20259e8097 100644 --- a/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageClientMetrics.java +++ b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageClientMetrics.java @@ -256,9 +256,7 @@ private StorageClientMetrics( this.retries = meter .counterBuilder(METRIC_GCP_STORAGE_CLIENT_RETRIES) - .setDescription( - "Number of GCS client attempts that retried an earlier failed attempt of the same" - + " request.") + .setDescription("Number of GCS client retry attempts") .setUnit("{attempt}") .build(); this.errors = @@ -302,7 +300,8 @@ private StorageClientMetrics( this.serverUnreached = meter .counterBuilder(METRIC_GCP_STORAGE_CLIENT_SERVER_UNREACHED) - .setDescription("Count of requests that failed before reaching the GCS server.") + .setDescription( + "Number of GCS client requests that failed before reaching the server") .setUnit("{request}") .build(); } else {