From bb06e800e7ef644b45e106976f27717ebeee07fa Mon Sep 17 00:00:00 2001 From: Nidhi Nandwani Date: Thu, 19 Nov 2026 16:13:02 +0000 Subject: [PATCH 1/4] 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/4] 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 { From cdca421de1ee955faa4b7396313aeeec6d88ffbf Mon Sep 17 00:00:00 2001 From: Nidhi Nandwani Date: Fri, 4 Dec 2026 11:15:06 +0000 Subject: [PATCH 3/4] test(storage): use TestUtils.nullStreamController in GrpcStorageImplTest for Java 8 compatibility Replace Mockito.mock(StreamController.class) with TestUtils.nullStreamController() in stubMidStreamReadFailure to avoid ByteBuddy JDK 8 failures when copying JSpecify @NullMarked annotations from StreamController. [Generated-by: AI] --- .../java/com/google/cloud/storage/GrpcStorageImplTest.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/GrpcStorageImplTest.java b/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/GrpcStorageImplTest.java index 1243c9f71fc1..d5cd81f20804 100644 --- a/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/GrpcStorageImplTest.java +++ b/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/GrpcStorageImplTest.java @@ -40,7 +40,6 @@ import com.google.api.gax.rpc.NotFoundException; import com.google.api.gax.rpc.ResponseObserver; import com.google.api.gax.rpc.ServerStreamingCallable; -import com.google.api.gax.rpc.StreamController; import com.google.api.gax.rpc.UnaryCallable; import com.google.cloud.NoCredentials; import com.google.cloud.WriteChannel; @@ -770,8 +769,7 @@ public void call( ReadObjectRequest request, ResponseObserver responseObserver, ApiCallContext context) { - StreamController controller = Mockito.mock(StreamController.class); - responseObserver.onStart(controller); + responseObserver.onStart(TestUtils.nullStreamController()); responseObserver.onResponse( ReadObjectResponse.newBuilder() .setChecksummedData( From 1d45947a2ac5add2044ec8d7b91b0d01d99ad8d9 Mon Sep 17 00:00:00 2001 From: Nidhi Nandwani Date: Fri, 4 Dec 2026 11:46:36 +0000 Subject: [PATCH 4/4] fix(storage): record HTTP pre-server server.unreached with actual IOException --- .../com/google/cloud/storage/Retrying.java | 1 + .../cloud/storage/StorageErrorTypeMapper.java | 7 + .../StorageGrpcMetricsInterceptor.java | 9 +- .../StorageHttpMetricsInterceptor.java | 32 ++-- .../cloud/storage/StorageMetricsContext.java | 16 ++ .../cloud/storage/RetryingMetricsTest.java | 116 ++++++++++++ .../StorageGrpcMetricsInterceptorTest.java | 14 +- .../StorageHttpMetricsInterceptorTest.java | 177 ++++++++++++++++-- 8 files changed, 330 insertions(+), 42 deletions(-) diff --git a/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/Retrying.java b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/Retrying.java index 20e579695d97..f5b953bef3a3 100644 --- a/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/Retrying.java +++ b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/Retrying.java @@ -270,6 +270,7 @@ public Model run( attemptAgain.set(false); if (metricsContext != null) { metricsContext.incrementAttempts(); + metricsContext.resetHttpResponseReceived(); } try { Response result = c.call(); diff --git a/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageErrorTypeMapper.java b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageErrorTypeMapper.java index 3a980dad833c..f018e0fb490b 100644 --- a/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageErrorTypeMapper.java +++ b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageErrorTypeMapper.java @@ -66,6 +66,13 @@ final class StorageErrorTypeMapper { static final String STATUS_AUTHENTICATION_ERROR = "AUTHENTICATION_ERROR"; static final String STATUS_CHECKSUM_MISMATCH = "CHECKSUM_MISMATCH"; + static boolean isPreServerErrorType(String errorType) { + return STATUS_AUTHENTICATION_ERROR.equals(errorType) + || STATUS_TLS_FAILURE.equals(errorType) + || STATUS_DNS_FAILURE.equals(errorType) + || STATUS_CONNECTION_ERROR.equals(errorType); + } + static String mapGrpcStatus(@Nullable Status status) { return mapGrpcStatus(status, 0); } 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 c63073f65ed6..74a786a6abe7 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 @@ -277,7 +277,7 @@ private static boolean isServerUnreached( if (StorageClientMetrics.NETWORK_PATH_DIRECTPATH.equals(networkPath)) { boolean reached = hasServerDuration || receivedServerHeaders || !trailers.keys().isEmpty() || status.isOk(); - return !reached && isPreServerErrorType(errorType); + return !reached && StorageErrorTypeMapper.isPreServerErrorType(errorType); } boolean hasUploadId = headerHasUploadId || hasNonEmptyMetadata(trailers, UPLOADER_UPLOAD_ID_KEY); @@ -291,13 +291,6 @@ private static boolean isAmbiguousClientAbort(String 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 6a0f927bf680..0dcdcf7ef60b 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 @@ -158,6 +158,10 @@ public void initialize(HttpRequest request) throws IOException { if (priorStatusCode != NO_PENDING_RETRY) { recordInternalRetry(req, priorStatusCode); } + StorageMetricsContext ctx = StorageMetricsContext.current(); + if (ctx != null) { + ctx.resetHttpResponseReceived(); + } if (existingExec != null) { existingExec.intercept(req); } @@ -171,7 +175,6 @@ && isMediaUploadRequest(req)) { startTimeNanos.set(clock.nanoTime()); boolean started = recorded.compareAndSet(true, false); if (started && metrics.getRequestActive() != null) { - StorageMetricsContext ctx = StorageMetricsContext.current(); Context otelContext = ctx != null ? ctx.getOtelContext() : Context.current(); String operationName = resolveOperationName(req, extractUrlTemplate(req.getUrl()), ctx); activeOtelContext.set(otelContext); @@ -197,11 +200,7 @@ && isMediaUploadRequest(req)) { metrics.recordRequestActive( activeOtelContext.get(), activeOperationName.get(), -1L); recordResponse( - req, - response, - startTimeNanos.get(), - bodyWriteEndNanos.get(), - endNanos); + req, response, startTimeNanos.get(), bodyWriteEndNanos.get(), endNanos); } } if (handled && supportsRetry && ownResponse && response.getStatusCode() >= 400) { @@ -222,18 +221,16 @@ && isMediaUploadRequest(req)) { if (response.getRequest() == request && recorded.compareAndSet(false, true)) { metrics.recordRequestActive(activeOtelContext.get(), activeOperationName.get(), -1L); recordResponse( - request, - response, - startTimeNanos.get(), - bodyWriteEndNanos.get(), - endNanos); + request, response, startTimeNanos.get(), bodyWriteEndNanos.get(), endNanos); } } }); // HttpIOExceptionHandler does not receive the thrown IOException instance from - // google-http-client, so transport-level IOExceptions default to STATUS_CONNECTION_ERROR here - // (specific subtypes like TIMEOUT, DNS_FAILURE, and TLS_FAILURE are mapped in Retrying). + // google-http-client and also fires on SocketTimeoutException read timeouts, so + // server.unreached is NOT recorded here; HTTP pre-server IOExceptions (DNS_FAILURE, + // TLS_FAILURE, CONNECTION_ERROR, AUTHENTICATION_ERROR) are recorded with the actual + // exception in StorageMetricsContext#recordAttemptFailure. request.setIOExceptionHandler( (req, supportsRetry) -> { if (recorded.compareAndSet(false, true)) { @@ -247,12 +244,6 @@ && isMediaUploadRequest(req)) { 0L, urlTemplate, StorageErrorTypeMapper.STATUS_CONNECTION_ERROR); - StorageMetricsContext ctx = StorageMetricsContext.current(); - metrics.recordServerUnreached( - ctx != null ? ctx.getOtelContext() : Context.current(), - resolveOperationName(req, urlTemplate), - StorageClientMetrics.NETWORK_PATH_CLOUDPATH, - StorageErrorTypeMapper.STATUS_CONNECTION_ERROR); } boolean handled = existingIoHandler != null && existingIoHandler.handleIOException(req, supportsRetry); @@ -305,6 +296,9 @@ private void recordResponse( // initialize(HttpRequest), because callers such as MediaHttpDownloader or MediaHttpUploader // may append query parameters (e.g. alt=media, uploadType) after buildRequest(). StorageMetricsContext ctx = StorageMetricsContext.current(); + if (ctx != null) { + ctx.markHttpResponseReceived(); + } Context otelContext = ctx != null ? ctx.getOtelContext() : Context.current(); String operationName = resolveOperationName(request, urlTemplate, ctx); metrics.recordTtfb( diff --git a/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageMetricsContext.java b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageMetricsContext.java index 96e7d4081bfe..ea7148e88fdb 100644 --- a/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageMetricsContext.java +++ b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageMetricsContext.java @@ -55,6 +55,7 @@ final class StorageMetricsContext { private final Attributes baseAttributes; private final boolean recordOperationOnRetrierExit; private final AtomicBoolean operationRecorded = new AtomicBoolean(false); + private final AtomicBoolean httpResponseReceived = new AtomicBoolean(false); private final AtomicInteger attemptCount = new AtomicInteger(0); private final AtomicLong requestBytes = new AtomicLong(0L); private final AtomicLong responseBytes = new AtomicLong(0L); @@ -322,6 +323,13 @@ private void recordAttemptFailure( putAttemptStatusCodes(builder, e, StorageErrorTypeMapper.STATUS_UNKNOWN, defaultHttpStatus); metrics.getAttempts().add(1, builder.build()); } + if (e != null + && "http".equals(baseAttributes.get(StorageClientMetrics.KEY_RPC_SYSTEM_NAME)) + && !httpResponseReceived.get() + && StorageErrorTypeMapper.extractHttpStatusCode(e) == null + && StorageErrorTypeMapper.isPreServerErrorType(errorType)) { + metrics.recordServerUnreached(otelContext, operationName, networkPath, errorType); + } } } @@ -462,6 +470,14 @@ GrpcCallContext attach(@Nullable GrpcCallContext context) { return callContext.withCallOptions(attach(callContext.getCallOptions())); } + void resetHttpResponseReceived() { + httpResponseReceived.set(false); + } + + void markHttpResponseReceived() { + httpResponseReceived.set(true); + } + int incrementAttempts() { return attemptCount.incrementAndGet(); } diff --git a/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/RetryingMetricsTest.java b/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/RetryingMetricsTest.java index 06c963fd2646..82aa72cba112 100644 --- a/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/RetryingMetricsTest.java +++ b/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/RetryingMetricsTest.java @@ -26,11 +26,14 @@ import static com.google.cloud.storage.StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_ERRORS; import static com.google.cloud.storage.StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_OPERATIONS; import static com.google.cloud.storage.StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_RETRIES; +import static com.google.cloud.storage.StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_SERVER_UNREACHED; +import static com.google.cloud.storage.StorageErrorTypeMapper.STATUS_CONNECTION_ERROR; import static com.google.cloud.storage.StorageErrorTypeMapper.STATUS_DEADLINE_EXCEEDED; import static com.google.cloud.storage.StorageErrorTypeMapper.STATUS_DNS_FAILURE; import static com.google.cloud.storage.StorageErrorTypeMapper.STATUS_NOT_FOUND; import static com.google.cloud.storage.StorageErrorTypeMapper.STATUS_OK; import static com.google.cloud.storage.StorageErrorTypeMapper.STATUS_TIMEOUT; +import static com.google.cloud.storage.StorageErrorTypeMapper.STATUS_TLS_FAILURE; import static com.google.cloud.storage.StorageErrorTypeMapper.STATUS_UNAVAILABLE; import static com.google.cloud.storage.StorageErrorTypeMapper.STATUS_UNKNOWN; import static com.google.common.truth.Truth.assertThat; @@ -58,12 +61,15 @@ 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.net.ConnectException; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.time.Duration; import java.util.Collection; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.UnaryOperator; +import javax.net.ssl.SSLException; import org.checkerframework.checker.nullness.qual.Nullable; import org.junit.Before; import org.junit.Test; @@ -596,6 +602,116 @@ public void withMetricsContext_withAlg_runTwoArgs_recordsAttemptsAndErrors() { .build()); } + @Test + public void httpRetrier_preServerIoExceptions_recordsServerUnreachedWithSpecificErrorTypes() { + HttpStorageOptions httpOptions = + StorageOptions.http() + .setProjectId("test-project") + .setCredentials(NoCredentials.getInstance()) + .setRetrySettings(RETRY_SETTINGS) + .setEnableOtelMetrics(true) + .setMeterProvider(provider) + .build(); + Retrier httpRetrier = httpOptions.createRetrier(); + StorageMetricsContext ctx = httpOptions.getStorageClientMetrics().createContext("GetObject"); + + AtomicInteger attempts = new AtomicInteger(0); + String result = + httpRetrier.run( + Retrying.alwaysRetry(), + () -> { + int attempt = attempts.incrementAndGet(); + if (attempt == 1) { + throw StorageException.translate( + new UnknownHostException("storage.googleapis.com")); + } else if (attempt == 2) { + throw StorageException.translate(new SSLException("handshake failed")); + } + return "recovered"; + }, + Decoder.identity(), + ctx); + assertThat(result).isEqualTo("recovered"); + + StorageMetricsContext connCtx = + httpOptions.getStorageClientMetrics().createContext("GetObject"); + assertThrows( + StorageException.class, + () -> + httpRetrier.run( + Retrying.neverRetry(), + () -> { + throw StorageException.translate(new ConnectException("connection refused")); + }, + Decoder.identity(), + connCtx)); + + assertThat(getCounterValue(collect(), METRIC_GCP_STORAGE_CLIENT_SERVER_UNREACHED)) + .isEqualTo(3L); + assertAttr(METRIC_GCP_STORAGE_CLIENT_SERVER_UNREACHED, KEY_ERROR_TYPE, STATUS_DNS_FAILURE, 1L); + assertAttr(METRIC_GCP_STORAGE_CLIENT_SERVER_UNREACHED, KEY_ERROR_TYPE, STATUS_TLS_FAILURE, 1L); + assertAttr( + METRIC_GCP_STORAGE_CLIENT_SERVER_UNREACHED, KEY_ERROR_TYPE, STATUS_CONNECTION_ERROR, 1L); + } + + @Test + public void httpRetrier_socketTimeoutException_doesNotRecordServerUnreached() { + HttpStorageOptions httpOptions = + StorageOptions.http() + .setProjectId("test-project") + .setCredentials(NoCredentials.getInstance()) + .setRetrySettings(RETRY_SETTINGS) + .setEnableOtelMetrics(true) + .setMeterProvider(provider) + .build(); + StorageMetricsContext ctx = httpOptions.getStorageClientMetrics().createContext("GetObject"); + + assertThrows( + StorageException.class, + () -> + httpOptions + .createRetrier() + .run( + Retrying.neverRetry(), + () -> { + throw StorageException.translate( + new SocketTimeoutException("Read timed out")); + }, + Decoder.identity(), + ctx)); + + assertThat(findMetric(collect(), METRIC_GCP_STORAGE_CLIENT_SERVER_UNREACHED)).isNull(); + } + + @Test + public void httpRetrier_ioExceptionAfterHttpResponseReceived_doesNotRecordServerUnreached() { + HttpStorageOptions httpOptions = + StorageOptions.http() + .setProjectId("test-project") + .setCredentials(NoCredentials.getInstance()) + .setRetrySettings(RETRY_SETTINGS) + .setEnableOtelMetrics(true) + .setMeterProvider(provider) + .build(); + StorageMetricsContext ctx = httpOptions.getStorageClientMetrics().createContext("GetObject"); + + assertThrows( + StorageException.class, + () -> + httpOptions + .createRetrier() + .run( + Retrying.neverRetry(), + () -> { + ctx.markHttpResponseReceived(); + throw StorageException.translate(new IOException("Premature EOF")); + }, + Decoder.identity(), + ctx)); + + assertThat(findMetric(collect(), METRIC_GCP_STORAGE_CLIENT_SERVER_UNREACHED)).isNull(); + } + private void assertCreateRetrierWiresMetricsWhenEnabled(StorageOptions options) { assertThat(options.getStorageClientMetrics()).isNotNull(); Retrier retrier = options.createRetrier(); 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 a12606c5ea4e..bc106eeac9df 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 @@ -608,7 +608,7 @@ public void interceptCall_serverUnreached_directPathAndCloudPathRules() throws E 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. + // DirectPath: only pre-server errors with no headers/trailers/stats/OK are unreached. assertServerUnreached( "dp connection error", directPathAttrs, @@ -676,7 +676,17 @@ public void interceptCall_serverUnreached_directPathAndCloudPathRules() throws E 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. + // CloudPath & unknown: unreached when no stats-bin and no x-guploader-uploadid, excluding + // client + // aborts (pre-connect failures have Attributes.EMPTY -> unknown). + assertServerUnreached( + "unknown path bare UNAVAILABLE without markers", + Attributes.EMPTY, + null, + new Metadata(), + Status.UNAVAILABLE, + StorageClientMetrics.NETWORK_PATH_UNKNOWN, + StorageErrorTypeMapper.STATUS_UNAVAILABLE); assertServerUnreached( "cp UNAVAILABLE without markers", cloudPathAttrs, 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 b8f55f838b49..7cea4ce7b828 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 @@ -55,7 +55,11 @@ import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.InputStream; import java.io.OutputStream; +import java.net.ConnectException; +import java.net.SocketTimeoutException; +import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.List; @@ -63,6 +67,7 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; +import javax.net.ssl.SSLException; import org.jspecify.annotations.Nullable; import org.junit.Before; import org.junit.Test; @@ -710,7 +715,8 @@ public LowLevelHttpResponse execute() throws IOException { assertThat(retries.get(0).getValue()).isEqualTo(1L); assertThat(retries.get(0).getAttributes()) .isEqualTo( - expectedRetryAttributes("ReadObject", StorageErrorTypeMapper.STATUS_CONNECTION_ERROR)); + expectedOperationErrorAttributes( + "ReadObject", StorageErrorTypeMapper.STATUS_CONNECTION_ERROR)); assertInternallyRetriedAttempt(StorageErrorTypeMapper.STATUS_CONNECTION_ERROR, 0L); } @@ -1076,15 +1082,164 @@ public void initialize_serverUnreached_cases() throws IOException { StorageHttpMetricsInterceptor.HEADER_UPLOADER_UPLOAD_ID, "", StorageErrorTypeMapper.STATUS_UNAVAILABLE); - assertServerUnreached( - "transport IOException", - false, - 0, - null, - null, + } + + @Test + public void initialize_ioExceptionWithoutRetrier_doesNotRecordServerUnreached() { + StorageHttpMetricsInterceptor interceptor = + new StorageHttpMetricsInterceptor(null, metrics, clock); + for (IOException ioe : + ImmutableList.of( + new IOException("connection refused"), new SocketTimeoutException("read timed out"))) { + HttpTransport transport = + new MockHttpTransport() { + @Override + public LowLevelHttpRequest buildRequest(String method, String url) { + return new MockLowLevelHttpRequest() { + @Override + public LowLevelHttpResponse execute() throws IOException { + throw ioe; + } + }; + } + }; + HttpRequest req; + try { + req = + transport + .createRequestFactory(interceptor) + .buildGetRequest( + new GenericUrl("https://storage.googleapis.com/storage/v1/b/my-b")); + } catch (IOException e) { + throw new AssertionError(e); + } + assertThrows(IOException.class, req::execute); + } + assertThat(findMetric(reader, StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_SERVER_UNREACHED)) + .isNull(); + } + + @Test + public void endToEnd_httpPreServerIoExceptions_recordsSpecificServerUnreachedErrorTypes() + throws Exception { + assertEndToEndPreServerUnreached( + "dns failure", + new UnknownHostException("storage.googleapis.com"), + StorageErrorTypeMapper.STATUS_DNS_FAILURE); + assertEndToEndPreServerUnreached( + "tls failure", + new SSLException("handshake failed"), + StorageErrorTypeMapper.STATUS_TLS_FAILURE); + assertEndToEndPreServerUnreached( + "connection error", + new ConnectException("connection refused"), StorageErrorTypeMapper.STATUS_CONNECTION_ERROR); } + @Test + public void endToEnd_httpSocketTimeoutException_doesNotRecordServerUnreached() throws Exception { + assertEndToEndPreServerUnreached( + "socket read timeout", new SocketTimeoutException("Read timed out"), null); + } + + @Test + public void + endToEnd_httpResponseWithMarkerFollowedByBodyIoException_doesNotRecordServerUnreached() + throws Exception { + InMemoryMetricReader caseReader = InMemoryMetricReader.create(); + SdkMeterProvider caseProvider = + SdkMeterProvider.builder().registerMetricReader(caseReader).build(); + HttpTransport transport = + new MockHttpTransport() { + @Override + public LowLevelHttpRequest buildRequest(String method, String url) { + return new MockLowLevelHttpRequest() { + @Override + public LowLevelHttpResponse execute() { + MockLowLevelHttpResponse resp = new MockLowLevelHttpResponse(); + resp.setStatusCode(200); + resp.addHeader(StorageHttpMetricsInterceptor.HEADER_GFE_SERVICE_TIME, "5.0"); + resp.setContent( + new InputStream() { + @Override + public int read() throws IOException { + throw new IOException("Premature EOF"); + } + }); + return resp; + } + }; + } + }; + + try (Storage storage = + StorageOptions.http() + .setProjectId("test-project") + .setCredentials(NoCredentials.getInstance()) + .setClock(clock) + .setEnableOtelMetrics(true) + .setMeterProvider(caseProvider) + .setTransportOptions( + HttpTransportOptions.newBuilder().setHttpTransportFactory(() -> transport).build()) + .setRetrySettings(ServiceOptions.getNoRetrySettings()) + .build() + .getService()) { + assertThrows(StorageException.class, () -> storage.readAllBytes(BlobId.of("my-b", "my-obj"))); + } + + assertThat( + findMetric(caseReader, StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_SERVER_UNREACHED)) + .isNull(); + } + + private void assertEndToEndPreServerUnreached( + String label, IOException failure, @Nullable String expectedErrorType) throws Exception { + InMemoryMetricReader caseReader = InMemoryMetricReader.create(); + SdkMeterProvider caseProvider = + SdkMeterProvider.builder().registerMetricReader(caseReader).build(); + HttpTransport transport = + new MockHttpTransport() { + @Override + public LowLevelHttpRequest buildRequest(String method, String url) { + return new MockLowLevelHttpRequest() { + @Override + public LowLevelHttpResponse execute() throws IOException { + throw failure; + } + }; + } + }; + + try (Storage storage = + StorageOptions.http() + .setProjectId("test-project") + .setCredentials(NoCredentials.getInstance()) + .setClock(clock) + .setEnableOtelMetrics(true) + .setMeterProvider(caseProvider) + .setTransportOptions( + HttpTransportOptions.newBuilder().setHttpTransportFactory(() -> transport).build()) + .setRetrySettings(ServiceOptions.getNoRetrySettings()) + .build() + .getService()) { + assertThrows(StorageException.class, () -> storage.get(BlobId.of("my-b", "my-obj"))); + } + + 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.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("GetObject", expectedErrorType)); + } + @Test public void initialize_batchPart401_doesNotRecordPartDuration() throws IOException { AtomicBoolean refreshHandlerCalled = new AtomicBoolean(false); @@ -1608,12 +1763,8 @@ public LowLevelHttpResponse execute() throws IOException { 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(); - } + req.setThrowExceptionOnExecuteError(false); + req.execute(); assertWithMessage(label) .that(