From 4940a70b5382183b0dcf6b16a229b5865863c12b Mon Sep 17 00:00:00 2001 From: Nidhi Nandwani Date: Thu, 19 Nov 2026 15:14:26 +0000 Subject: [PATCH 1/2] feat(storage): record gcp.storage.client.retries for mid-stream and HTTP retries [Generated-by: AI] --- .../ApiaryUnbufferedReadableByteChannel.java | 10 ++ .../GapicUnbufferedReadableByteChannel.java | 10 ++ .../com/google/cloud/storage/Retrying.java | 20 +++ .../StorageHttpMetricsInterceptor.java | 56 ++++++-- .../cloud/storage/StorageMetricsContext.java | 36 +++-- ...iaryUnbufferedReadableByteChannelTest.java | 127 ++++++++++++++++++ ...apicUnbufferedReadableByteChannelTest.java | 117 ++++++++++++++++ .../cloud/storage/RetryingMetricsTest.java | 8 +- .../StorageHttpMetricsInterceptorTest.java | 84 ++++++++++++ 9 files changed, 446 insertions(+), 22 deletions(-) diff --git a/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/ApiaryUnbufferedReadableByteChannel.java b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/ApiaryUnbufferedReadableByteChannel.java index a0bbadf67076..b18fb4b8251c 100644 --- a/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/ApiaryUnbufferedReadableByteChannel.java +++ b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/ApiaryUnbufferedReadableByteChannel.java @@ -152,10 +152,12 @@ public long read(ByteBuffer[] dsts, int offset, int length) throws IOException { if (resultRetryAlgorithm.shouldRetry(t, null)) { // if our retry algorithm COULD allow a retry, continue the loop and allow trying to // open the stream again. + recordMidStreamRetry(t); sbc = null; } else if (t instanceof IOException) { IOException ioE = (IOException) t; if (resultRetryAlgorithm.shouldRetry(StorageException.translate(ioE), null)) { + recordMidStreamRetry(ioE); sbc = null; } else { throw ioE; @@ -203,6 +205,14 @@ public void close() throws IOException { } } + private void recordMidStreamRetry(Throwable error) { + StorageMetricsContext metricsContext = retrier.getMetricsContext(); + if (metricsContext != null) { + metricsContext.recordError(error); + metricsContext.recordRetry(error); + } + } + private void setXGoogGeneration(long xGoogGeneration) { this.xGoogGeneration = xGoogGeneration; } diff --git a/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/GapicUnbufferedReadableByteChannel.java b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/GapicUnbufferedReadableByteChannel.java index 7989fcaecb4b..f516f2d8a0ad 100644 --- a/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/GapicUnbufferedReadableByteChannel.java +++ b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/GapicUnbufferedReadableByteChannel.java @@ -163,6 +163,7 @@ public long read(ByteBuffer[] dsts, int offset, int length) throws IOException { if (take instanceof IOException) { IOException ioe = (IOException) take; if (alg.shouldRetry(ioe, null)) { + recordMidStreamRetry(StorageException.coalesce(ioe)); cancelAndDrainCurrentObserver(); continue; } else { @@ -174,6 +175,7 @@ public long read(ByteBuffer[] dsts, int offset, int length) throws IOException { Throwable throwable = (Throwable) take; BaseServiceException coalesce = StorageException.coalesce(throwable); if (alg.shouldRetry(coalesce, null)) { + recordMidStreamRetry(coalesce); cancelAndDrainCurrentObserver(); continue; } else { @@ -298,6 +300,14 @@ private void drainQueue() throws IOException { } } + private void recordMidStreamRetry(Throwable error) { + StorageMetricsContext metricsContext = retrier.getMetricsContext(); + if (metricsContext != null) { + metricsContext.recordError(error); + metricsContext.recordRetry(error); + } + } + private void cancelAndDrainCurrentObserver() { if (readObjectObserver != null) { readObjectObserver.cancel(); 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 ebc9a822f1c6..da247befbcfe 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 @@ -84,6 +84,11 @@ default Retrier withMetricsContext(@Nullable StorageMetricsContext metricsContex return metricsContext == null ? this : new ContextBoundRetrier(this, metricsContext); } + @Nullable + default StorageMetricsContext getMetricsContext() { + return null; + } + static Retrier attemptOnce() { return AttemptOnceRetrier.INSTANCE; } @@ -169,6 +174,11 @@ public RetrierWithAlg withAlg( public Retrier withMetricsContext(@Nullable StorageMetricsContext explicitCtx) { return explicitCtx != null ? new ContextBoundRetrier(delegate, explicitCtx) : this; } + + @Override + public StorageMetricsContext getMetricsContext() { + return metricsContext; + } } static final class DefaultRetrierWithAlg implements RetrierWithAlg { @@ -212,6 +222,11 @@ public Model run( @Nullable StorageMetricsContext metricsContext) { return retrier.run(alg, c, d, metricsContext != null ? metricsContext : boundMetricsContext); } + + @Override + public @Nullable StorageMetricsContext getMetricsContext() { + return boundMetricsContext != null ? boundMetricsContext : retrier.getMetricsContext(); + } } static final class DefaultRetrier implements Retrier { @@ -331,6 +346,11 @@ public Model run( httpRpcContext.clearInvocationId(); } } + + @Override + public @Nullable StorageMetricsContext getMetricsContext() { + return delegate.getMetricsContext(); + } } @NonNull 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 49d8891c4fd8..f6446ec1b607 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 @@ -150,7 +150,12 @@ public void initialize(HttpRequest request) throws IOException { boolean handled = existingUnsuccessfulHandler.handleResponse(req, response, supportsRetry); if (handled && response.getRequest() == req && recorded.compareAndSet(false, true)) { - recordResponse(req, startTimeNanos.get(), endNanos, response.getStatusCode()); + recordResponse( + req, + startTimeNanos.get(), + endNanos, + response.getStatusCode(), + /* isRetry= */ supportsRetry); } return handled; }); @@ -163,7 +168,12 @@ public void initialize(HttpRequest request) throws IOException { existingResp.interceptResponse(response); } if (recorded.compareAndSet(false, true)) { - recordResponse(request, startTimeNanos.get(), endNanos, response.getStatusCode()); + recordResponse( + request, + startTimeNanos.get(), + endNanos, + response.getStatusCode(), + /* isRetry= */ false); } }); @@ -172,21 +182,35 @@ public void initialize(HttpRequest request) throws IOException { // (specific subtypes like TIMEOUT, DNS_FAILURE, and TLS_FAILURE are mapped in Retrying). request.setIOExceptionHandler( (req, supportsRetry) -> { - if (recorded.compareAndSet(false, true)) { - double durationSeconds = (clock.nanoTime() - startTimeNanos.get()) / 1_000_000_000.0; + long endNanos = clock.nanoTime(); + boolean recordedThisAttempt = recorded.compareAndSet(false, true); + String urlTemplate = recordedThisAttempt ? extractUrlTemplate(req.getUrl()) : ""; + if (recordedThisAttempt) { + double durationSeconds = (endNanos - startTimeNanos.get()) / 1_000_000_000.0; recordDuration( req, durationSeconds, 0L, - extractUrlTemplate(req.getUrl()), + urlTemplate, + 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), + StorageClientMetrics.NETWORK_PATH_CLOUDPATH, StorageErrorTypeMapper.STATUS_CONNECTION_ERROR); } - return existingIoHandler != null - && existingIoHandler.handleIOException(req, supportsRetry); + return handled; }); } - private void recordResponse(HttpRequest request, long startNanos, long endNanos, int statusCode) { + private void recordResponse( + HttpRequest request, long startNanos, long endNanos, int statusCode, boolean isRetry) { double durationSeconds = (endNanos - startNanos) / 1_000_000_000.0; String urlTemplate = extractUrlTemplate(request.getUrl()); String errorType = @@ -199,11 +223,13 @@ private void recordResponse(HttpRequest request, long startNanos, long endNanos, // may append query parameters (e.g. alt=media, uploadType) after buildRequest(). StorageMetricsContext ctx = StorageMetricsContext.current(); Context otelContext = ctx != null ? ctx.getOtelContext() : Context.current(); + String operationName = resolveOperationName(ctx, request, urlTemplate); metrics.recordTtfb( - otelContext, - resolveOperationName(request, urlTemplate), - durationSeconds, - StorageClientMetrics.NETWORK_PATH_CLOUDPATH); + otelContext, operationName, durationSeconds, StorageClientMetrics.NETWORK_PATH_CLOUDPATH); + if (isRetry) { + metrics.recordRetry( + otelContext, operationName, StorageClientMetrics.NETWORK_PATH_CLOUDPATH, errorType); + } } private void recordDuration( @@ -217,7 +243,11 @@ private void recordDuration( } static String resolveOperationName(HttpRequest request, String urlTemplate) { - StorageMetricsContext ctx = StorageMetricsContext.current(); + return resolveOperationName(StorageMetricsContext.current(), request, urlTemplate); + } + + private static String resolveOperationName( + @Nullable StorageMetricsContext ctx, HttpRequest request, String urlTemplate) { return ctx != null ? ctx.getOperationName() : defaultOperationName(request, urlTemplate); } 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 50902753d1e6..97b8615a68d1 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 @@ -298,14 +298,7 @@ void recordAttemptFailure(@Nullable StorageClientMetrics metrics, Throwable e) { String errorType = StorageErrorTypeMapper.mapThrowable(e); String networkPath = resolveNetworkPath(); Attributes attemptBase = buildAttemptBaseAttributes(metrics); - if (metrics.getErrors() != null) { - Attributes errorAttributes = - attemptBase.toBuilder() - .put(StorageClientMetrics.KEY_ERROR_TYPE, errorType) - .put(StorageClientMetrics.KEY_NETWORK_PATH, networkPath) - .build(); - metrics.getErrors().add(1, errorAttributes); - } + recordErrorCounter(metrics, attemptBase, errorType, networkPath); if (metrics.getAttempts() != null) { AttributesBuilder builder = attemptBase.toBuilder() @@ -317,6 +310,21 @@ void recordAttemptFailure(@Nullable StorageClientMetrics metrics, Throwable e) { } } + void recordError(Throwable e) { + if (metrics == null || metrics.getErrors() == null) { + return; + } + recordErrorCounter( + metrics, + buildAttemptBaseAttributes(metrics), + StorageErrorTypeMapper.mapThrowable(e), + resolveNetworkPath()); + } + + void recordRetry(Throwable priorError) { + recordRetry(this.metrics, priorError); + } + void recordRetry(@Nullable StorageClientMetrics metrics, Throwable priorError) { if (metrics == null) { return; @@ -328,6 +336,18 @@ void recordRetry(@Nullable StorageClientMetrics metrics, Throwable priorError) { StorageErrorTypeMapper.mapThrowable(priorError)); } + private void recordErrorCounter( + StorageClientMetrics metrics, Attributes attemptBase, String errorType, String networkPath) { + if (metrics.getErrors() != null) { + Attributes errorAttributes = + attemptBase.toBuilder() + .put(StorageClientMetrics.KEY_ERROR_TYPE, errorType) + .put(StorageClientMetrics.KEY_NETWORK_PATH, networkPath) + .build(); + metrics.getErrors().add(1, errorAttributes, otelContext); + } + } + void setNetworkPath(String networkPath) { this.networkPath = networkPath; } diff --git a/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/ApiaryUnbufferedReadableByteChannelTest.java b/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/ApiaryUnbufferedReadableByteChannelTest.java index 2b4304f6234e..40c80ba0b3a2 100644 --- a/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/ApiaryUnbufferedReadableByteChannelTest.java +++ b/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/ApiaryUnbufferedReadableByteChannelTest.java @@ -31,12 +31,18 @@ import com.google.api.gax.retrying.BasicResultRetryAlgorithm; import com.google.api.services.storage.Storage; import com.google.api.services.storage.model.StorageObject; +import com.google.cloud.NoCredentials; import com.google.cloud.storage.ApiaryUnbufferedReadableByteChannel.ApiaryReadRequest; import com.google.cloud.storage.Retrying.Retrier; import com.google.cloud.storage.Retrying.RetrierWithAlg; import com.google.cloud.storage.UnbufferedReadableByteChannelSession.UnbufferedReadableByteChannel; import com.google.cloud.storage.spi.v1.AuditingHttpTransport; import com.google.common.collect.ImmutableMap; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.data.LongPointData; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -47,6 +53,7 @@ import java.nio.channels.WritableByteChannel; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; import java.util.List; import java.util.Locale; import java.util.Map; @@ -415,4 +422,124 @@ public void close() throws SecurityException {} logger.removeHandler(handler); } } + + @Test + public void midStreamIoException_retried_recordsRetryAndErrorMetrics() throws IOException { + InMemoryMetricReader reader = InMemoryMetricReader.create(); + SdkMeterProvider provider = SdkMeterProvider.builder().registerMetricReader(reader).build(); + HttpStorageOptions options = + StorageOptions.http() + .setProjectId("test-project") + .setCredentials(NoCredentials.getInstance()) + .setEnableOtelMetrics(true) + .setMeterProvider(provider) + .build(); + StorageMetricsContext ctx = + options.getStorageClientMetrics().createMultiStepContext("ReadObject"); + + AtomicInteger calls = new AtomicInteger(0); + HttpTransport transport = + new HttpTransport() { + @Override + protected LowLevelHttpRequest buildRequest(String method, String url) { + return new MockLowLevelHttpRequest() { + @Override + public LowLevelHttpResponse execute() { + InputStream body = + calls.incrementAndGet() == 1 + ? new InputStream() { + @Override + public int read() throws IOException { + throw new IOException("connection reset mid-stream"); + } + } + : new ByteArrayInputStream(CONTENT_BYTES); + return new MockLowLevelHttpResponse() + .setStatusCode(200) + .setContent(body) + .addHeader("x-goog-generation", "12345"); + } + }; + } + }; + Storage storageClient = + new Storage.Builder(transport, GsonFactory.getDefaultInstance(), null) + .setApplicationName("test") + .build(); + ApiaryReadRequest req = + new ApiaryReadRequest( + new StorageObject().setBucket("bucket").setName("blob"), + ImmutableMap.of(), + ByteRangeSpec.nullRange()); + + try (ApiaryUnbufferedReadableByteChannel channel = + new ApiaryUnbufferedReadableByteChannel( + req, + storageClient, + SettableApiFuture.create(), + options.createRetrier().withMetricsContext(ctx), + new BasicResultRetryAlgorithm() { + @Override + public boolean shouldRetry(Throwable previousThrowable, Object previousResponse) { + return previousThrowable instanceof StorageException; + } + }, + Hasher.noop())) { + ByteBuffer buf = ByteBuffer.allocate(CONTENT_BYTES.length); + assertThat(channel.read(new ByteBuffer[] {buf}, 0, 1)).isEqualTo(CONTENT_BYTES.length); + } + + Collection collected = reader.collectAllMetrics(); + assertThat(calls.get()).isEqualTo(2); + LongPointData retryPoint = + findSinglePoint(collected, StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_RETRIES); + assertThat(retryPoint.getValue()).isEqualTo(1L); + assertThat(retryPoint.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, "ReadObject") + .put( + StorageClientMetrics.KEY_NETWORK_PATH, + StorageClientMetrics.NETWORK_PATH_CLOUDPATH) + .put( + StorageClientMetrics.KEY_ERROR_TYPE, + StorageErrorTypeMapper.STATUS_CONNECTION_ERROR) + .build()); + + LongPointData errorPoint = + findSinglePoint(collected, StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_ERRORS); + assertThat(errorPoint.getValue()).isEqualTo(1L); + assertThat(errorPoint.getAttributes().get(StorageClientMetrics.KEY_ERROR_TYPE)) + .isEqualTo(StorageErrorTypeMapper.STATUS_CONNECTION_ERROR); + assertThat(errorPoint.getAttributes().get(StorageClientMetrics.KEY_GCP_STORAGE_OPERATION)) + .isEqualTo("ReadObject"); + + long attemptsTotal = + collected.stream() + .filter( + m -> m.getName().equals(StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_ATTEMPTS)) + .flatMap(m -> m.getLongSumData().getPoints().stream()) + .mapToLong(LongPointData::getValue) + .sum(); + assertThat(attemptsTotal).isEqualTo(2L); + } + + private static LongPointData findSinglePoint(Collection collected, String name) { + MetricData metric = + collected.stream() + .filter(m -> m.getName().equals(name)) + .findFirst() + .orElseThrow(() -> new AssertionError("Missing metric " + name)); + assertThat(metric.getLongSumData().getPoints()).hasSize(1); + return metric.getLongSumData().getPoints().iterator().next(); + } } diff --git a/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/GapicUnbufferedReadableByteChannelTest.java b/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/GapicUnbufferedReadableByteChannelTest.java index 2305d1634835..8990cdc0ce9d 100644 --- a/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/GapicUnbufferedReadableByteChannelTest.java +++ b/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/GapicUnbufferedReadableByteChannelTest.java @@ -24,6 +24,7 @@ import com.google.api.gax.rpc.ApiCallContext; import com.google.api.gax.rpc.ResponseObserver; import com.google.api.gax.rpc.ServerStreamingCallable; +import com.google.cloud.NoCredentials; import com.google.cloud.storage.GrpcUtils.ZeroCopyServerStreamingCallable; import com.google.cloud.storage.Retrying.Retrier; import com.google.cloud.storage.it.ChecksummedTestContent; @@ -31,9 +32,17 @@ import com.google.storage.v2.ObjectChecksums; import com.google.storage.v2.ReadObjectRequest; import com.google.storage.v2.ReadObjectResponse; +import io.grpc.Status; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +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; +import java.util.Collection; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; import org.junit.Test; public final class GapicUnbufferedReadableByteChannelTest { @@ -537,4 +546,112 @@ public void call( assertThat(c.read(buffer)).isEqualTo(-1); } } + + @Test + public void midStreamError_retried_recordsRetryAndErrorMetrics() throws IOException { + InMemoryMetricReader reader = InMemoryMetricReader.create(); + SdkMeterProvider provider = SdkMeterProvider.builder().registerMetricReader(reader).build(); + GrpcStorageOptions options = + StorageOptions.grpc() + .setProjectId("test-project") + .setCredentials(NoCredentials.getInstance()) + .setEnableOtelMetrics(true) + .setMeterProvider(provider) + .build(); + StorageMetricsContext ctx = + options.getStorageClientMetrics().createMultiStepContext("ReadObject"); + ctx.setNetworkPath(StorageClientMetrics.NETWORK_PATH_DIRECTPATH); + + byte[] firstPart = DataGenerator.base64Characters().genBytes(5); + byte[] secondPart = DataGenerator.base64Characters().genBytes(5); + ChecksummedTestContent firstContent = ChecksummedTestContent.of(firstPart); + ChecksummedTestContent secondContent = ChecksummedTestContent.of(secondPart); + AtomicInteger calls = new AtomicInteger(0); + + try (GapicUnbufferedReadableByteChannel c = + new GapicUnbufferedReadableByteChannel( + SettableApiFuture.create(), + new ZeroCopyServerStreamingCallable<>( + new ServerStreamingCallable() { + @Override + public void call( + ReadObjectRequest request, + ResponseObserver respond, + ApiCallContext context) { + respond.onStart(TestUtils.nullStreamController()); + if (calls.incrementAndGet() == 1) { + respond.onResponse( + ReadObjectResponse.newBuilder() + .setChecksummedData(firstContent.asChecksummedData()) + .build()); + respond.onError(Status.UNAVAILABLE.asRuntimeException()); + } else { + respond.onResponse( + ReadObjectResponse.newBuilder() + .setChecksummedData(secondContent.asChecksummedData()) + .build()); + respond.onComplete(); + } + } + }, + ResponseContentLifecycleManager.noop()), + ReadObjectRequest.getDefaultInstance(), + Hasher.noop(), + options.createRetrier().withMetricsContext(ctx), + Retrying.alwaysRetry())) { + ByteBuffer buffer = ByteBuffer.allocate(10); + assertThat(c.read(buffer)).isEqualTo(10); + } + + Collection collected = reader.collectAllMetrics(); + assertThat(calls.get()).isEqualTo(2); + LongPointData retryPoint = + findSinglePoint(collected, StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_RETRIES); + assertThat(retryPoint.getValue()).isEqualTo(1L); + assertThat(retryPoint.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, "grpc") + .put(StorageClientMetrics.KEY_SERVER_ADDRESS, "storage.googleapis.com") + .put(StorageClientMetrics.KEY_GCP_STORAGE_OPERATION, "ReadObject") + .put( + StorageClientMetrics.KEY_NETWORK_PATH, + StorageClientMetrics.NETWORK_PATH_DIRECTPATH) + .put(StorageClientMetrics.KEY_ERROR_TYPE, StorageErrorTypeMapper.STATUS_UNAVAILABLE) + .build()); + + LongPointData errorPoint = + findSinglePoint(collected, StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_ERRORS); + assertThat(errorPoint.getValue()).isEqualTo(1L); + assertThat(errorPoint.getAttributes().get(StorageClientMetrics.KEY_ERROR_TYPE)) + .isEqualTo(StorageErrorTypeMapper.STATUS_UNAVAILABLE); + assertThat(errorPoint.getAttributes().get(StorageClientMetrics.KEY_GCP_STORAGE_OPERATION)) + .isEqualTo("ReadObject"); + + long attemptsTotal = + collected.stream() + .filter( + m -> m.getName().equals(StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_ATTEMPTS)) + .flatMap(m -> m.getLongSumData().getPoints().stream()) + .mapToLong(LongPointData::getValue) + .sum(); + assertThat(attemptsTotal).isEqualTo(2L); + } + + private static LongPointData findSinglePoint(Collection collected, String name) { + MetricData metric = + collected.stream() + .filter(m -> m.getName().equals(name)) + .findFirst() + .orElseThrow(() -> new AssertionError("Missing metric " + name)); + assertThat(metric.getLongSumData().getPoints()).hasSize(1); + return metric.getLongSumData().getPoints().iterator().next(); + } } 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 fe1583faf069..06c963fd2646 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 @@ -42,6 +42,7 @@ import com.google.cloud.NoCredentials; import com.google.cloud.storage.Conversions.Decoder; import com.google.cloud.storage.Retrying.DefaultRetrier; +import com.google.cloud.storage.Retrying.HttpRetrier; import com.google.cloud.storage.Retrying.Retrier; import com.google.cloud.storage.Retrying.RetrierWithAlg; import com.google.cloud.storage.Retrying.RetryingDependencies; @@ -538,7 +539,8 @@ public void withMetricsContext_withAlg_runTwoArgs_recordsAttemptsAndErrors() { } @Test - public void retriedCall_viaStorageOptions_recordsExactRetryAttributes() { + public void + retriedCall_viaStorageOptions_recordsExactRetryAttributesAndDelegatesMetricsContext() { GrpcStorageOptions options = StorageOptions.grpc() .setProjectId("test-project") @@ -550,6 +552,10 @@ public void retriedCall_viaStorageOptions_recordsExactRetryAttributes() { StorageMetricsContext ctx = options.getStorageClientMetrics().createContext("GetObject"); ctx.setNetworkPath(StorageClientMetrics.NETWORK_PATH_DIRECTPATH); Retrier bound = options.createRetrier().withMetricsContext(ctx); + assertThat(bound.getMetricsContext()).isSameInstanceAs(ctx); + assertThat(bound.withAlg(Retrying.alwaysRetry()).getMetricsContext()).isSameInstanceAs(ctx); + assertThat(new HttpRetrier(bound).getMetricsContext()).isSameInstanceAs(ctx); + assertThat(Retrier.attemptOnce().getMetricsContext()).isNull(); AtomicInteger attempts = new AtomicInteger(0); String result = 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 0e11c6a49a0e..bb9ca17f99b7 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 @@ -18,6 +18,7 @@ import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertWithMessage; +import static org.junit.Assert.assertThrows; import com.google.api.client.googleapis.batch.BatchCallback; import com.google.api.client.googleapis.batch.BatchRequest; @@ -48,6 +49,7 @@ import io.opentelemetry.sdk.metrics.SdkMeterProvider; 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.testing.exporter.InMemoryMetricReader; import java.io.IOException; import java.nio.ByteBuffer; @@ -578,6 +580,7 @@ public void initialize_altMediaAddedAfterBuildGetRequest_recordsTtfb() throws IO .isEqualTo("ReadObject"); assertThat(ttfbPoint.getAttributes().get(StorageClientMetrics.KEY_SERVER_ADDRESS)) .isEqualTo("storage.googleapis.com"); + assertThat(retriesPoints()).isEmpty(); } @Test @@ -629,6 +632,7 @@ public void initialize_unsuccessfulResponseHandlerReturnsFalseOn404_recordsOnce( .isEqualTo("ReadObject"); assertThat(ttfbPoint.getAttributes().get(StorageClientMetrics.KEY_SERVER_ADDRESS)) .isEqualTo("storage.googleapis.com"); + assertThat(retriesPoints()).isEmpty(); } @Test @@ -689,6 +693,13 @@ public LowLevelHttpResponse execute() throws IOException { assertThat(ttfbPoint.getSum()).isWithin(1e-6).of(0.20); assertThat(ttfbPoint.getAttributes().get(StorageClientMetrics.KEY_GCP_STORAGE_OPERATION)) .isEqualTo("GetBucket"); + + List retries = retriesPoints(); + assertThat(retries).hasSize(1); + assertThat(retries.get(0).getValue()).isEqualTo(1L); + assertThat(retries.get(0).getAttributes()) + .isEqualTo( + expectedRetryAttributes("GetBucket", StorageErrorTypeMapper.STATUS_CONNECTION_ERROR)); } @Test @@ -764,6 +775,57 @@ public LowLevelHttpResponse execute() { .isEqualTo("ReadObject"); assertThat(ttfbPoint.getAttributes().get(StorageClientMetrics.KEY_SERVER_ADDRESS)) .isEqualTo("storage.googleapis.com"); + + List retries = retriesPoints(); + assertThat(retries).hasSize(1); + assertThat(retries.get(0).getValue()).isEqualTo(1L); + assertThat(retries.get(0).getAttributes()) + .isEqualTo(expectedRetryAttributes("ReadObject", "UNAUTHENTICATED")); + } + + @Test + public void initialize_supportsRetryFalse_doesNotRecordRetry() throws IOException { + HttpRequestInitializer delegate = + request -> { + request.setUnsuccessfulResponseHandler((req, response, supportsRetry) -> true); + request.setIOExceptionHandler((req, supportsRetry) -> true); + }; + StorageHttpMetricsInterceptor interceptor = + new StorageHttpMetricsInterceptor(delegate, metrics, clock); + + // 401 where handler returns true (like HttpCredentialsAdapter) but retries are exhausted. + HttpTransport unauthorizedTransport = createAdvancingTransport(401, 50_000_000L); + HttpRequest req401 = + unauthorizedTransport + .createRequestFactory(interceptor) + .buildGetRequest(new GenericUrl("https://storage.googleapis.com/storage/v1/b/my-b")); + req401.setNumberOfRetries(0); + req401.setThrowExceptionOnExecuteError(false); + req401.execute(); + + // IOException where handler returns true but retries are exhausted. + HttpTransport ioTransport = + new MockHttpTransport() { + @Override + public LowLevelHttpRequest buildRequest(String method, String url) { + return new MockLowLevelHttpRequest() { + @Override + public LowLevelHttpResponse execute() throws IOException { + clock.advanceNanos(50_000_000L); + throw new IOException("connection reset"); + } + }; + } + }; + HttpRequest reqIo = + ioTransport + .createRequestFactory(interceptor) + .buildGetRequest(new GenericUrl("https://storage.googleapis.com/storage/v1/b/my-b")); + reqIo.setNumberOfRetries(0); + assertThrows(IOException.class, reqIo::execute); + + assertThat(durationPoints()).hasSize(2); + assertThat(retriesPoints()).isEmpty(); } @Test @@ -864,6 +926,7 @@ public void onFailure(Void e, HttpHeaders responseHeaders) { HistogramPointData batchTtfb = findTtfbPointByOperation(ttfb, "Batch"); assertThat(batchTtfb.getCount()).isEqualTo(2L); assertThat(batchTtfb.getSum()).isWithin(1e-6).of(0.20); + assertThat(retriesPoints()).isEmpty(); } @Test @@ -978,6 +1041,27 @@ private List ttfbPoints() { return histogramPoints(StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_TTFB); } + private List retriesPoints() { + return reader.collectAllMetrics().stream() + .filter(m -> m.getName().equals(StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_RETRIES)) + .findFirst() + .map(m -> ImmutableList.copyOf(m.getLongSumData().getPoints())) + .orElse(ImmutableList.of()); + } + + private static Attributes expectedRetryAttributes(String operationName, String errorType) { + return 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, operationName) + .put(StorageClientMetrics.KEY_NETWORK_PATH, StorageClientMetrics.NETWORK_PATH_CLOUDPATH) + .put(StorageClientMetrics.KEY_ERROR_TYPE, errorType) + .build(); + } + private List histogramPoints(String metricName) { return reader.collectAllMetrics().stream() .filter(m -> m.getName().equals(metricName)) From 736b10fb24a6c8f9ccce45932de0477604200260 Mon Sep 17 00:00:00 2001 From: Nidhi Nandwani Date: Thu, 26 Nov 2026 05:17:08 +0000 Subject: [PATCH 2/2] fix(storage): record HTTP retries when the next attempt starts and count terminal mid-stream errors - StorageHttpMetricsInterceptor keeps the status of a failed attempt that google-http-client will retry (>= 400, or no response for an IOException) and records gcp.storage.client.retries once the next attempt starts. This drops the isRetry plumbing and no longer records a retry for a handled 3xx. - The internally retried failed attempt also records gcp.storage.client.attempts and gcp.storage.client.errors via StorageMetricsContext.recordAttemptFailure, since Retrying only observes the final outcome of HttpRequest.execute(). - Apiary/Gapic unbuffered read channels record gcp.storage.client.errors for terminal (non-retryable) mid-stream failures. [Generated-by: AI] --- .../ApiaryUnbufferedReadableByteChannel.java | 13 ++- .../GapicUnbufferedReadableByteChannel.java | 9 ++ .../StorageHttpMetricsInterceptor.java | 89 ++++++++++--------- .../cloud/storage/StorageMetricsContext.java | 19 +++- ...iaryUnbufferedReadableByteChannelTest.java | 56 +++++++++--- ...apicUnbufferedReadableByteChannelTest.java | 52 +++++++++-- .../StorageHttpMetricsInterceptorTest.java | 74 ++++++++++++++- 7 files changed, 249 insertions(+), 63 deletions(-) diff --git a/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/ApiaryUnbufferedReadableByteChannel.java b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/ApiaryUnbufferedReadableByteChannel.java index b18fb4b8251c..0be3515ced9c 100644 --- a/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/ApiaryUnbufferedReadableByteChannel.java +++ b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/ApiaryUnbufferedReadableByteChannel.java @@ -29,6 +29,7 @@ import com.google.api.services.storage.Storage.Objects; import com.google.api.services.storage.Storage.Objects.Get; import com.google.api.services.storage.model.StorageObject; +import com.google.cloud.BaseServiceException; import com.google.cloud.storage.Conversions.Decoder; import com.google.cloud.storage.Retrying.Retrier; import com.google.cloud.storage.UnbufferedReadableByteChannelSession.UnbufferedReadableByteChannel; @@ -160,10 +161,13 @@ public long read(ByteBuffer[] dsts, int offset, int length) throws IOException { recordMidStreamRetry(ioE); sbc = null; } else { + recordMidStreamError(ioE); throw ioE; } } else { - throw new IOException(StorageException.coalesce(t)); + BaseServiceException coalesced = StorageException.coalesce(t); + recordMidStreamError(coalesced); + throw new IOException(coalesced); } } finally { long totalRemainingAfter = Buffers.totalRemaining(dsts, offset, length); @@ -213,6 +217,13 @@ private void recordMidStreamRetry(Throwable error) { } } + private void recordMidStreamError(Throwable error) { + StorageMetricsContext metricsContext = retrier.getMetricsContext(); + if (metricsContext != null) { + metricsContext.recordError(error); + } + } + private void setXGoogGeneration(long xGoogGeneration) { this.xGoogGeneration = xGoogGeneration; } diff --git a/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/GapicUnbufferedReadableByteChannel.java b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/GapicUnbufferedReadableByteChannel.java index f516f2d8a0ad..4548b108f1ca 100644 --- a/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/GapicUnbufferedReadableByteChannel.java +++ b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/GapicUnbufferedReadableByteChannel.java @@ -167,6 +167,7 @@ public long read(ByteBuffer[] dsts, int offset, int length) throws IOException { cancelAndDrainCurrentObserver(); continue; } else { + recordMidStreamError(StorageException.coalesce(ioe)); ioe.addSuppressed(new AsyncStorageTaskException()); throw ioe; } @@ -179,6 +180,7 @@ public long read(ByteBuffer[] dsts, int offset, int length) throws IOException { cancelAndDrainCurrentObserver(); continue; } else { + recordMidStreamError(coalesce); close(); throw new IOException(coalesce); } @@ -308,6 +310,13 @@ private void recordMidStreamRetry(Throwable error) { } } + private void recordMidStreamError(Throwable error) { + StorageMetricsContext metricsContext = retrier.getMetricsContext(); + if (metricsContext != null) { + metricsContext.recordError(error); + } + } + private void cancelAndDrainCurrentObserver() { if (readObjectObserver != null) { readObjectObserver.cancel(); 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 f6446ec1b607..3ac461ed565c 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 @@ -32,6 +32,7 @@ import java.io.IOException; import java.util.Locale; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; @@ -108,6 +109,9 @@ final class StorageHttpMetricsInterceptor implements HttpRequestInitializer { .put("GET /storage/v1/projects/{project}/serviceAccount", "GetServiceAccount") .build(); + private static final int NO_PENDING_RETRY = -1; + private static final int NO_RESPONSE = 0; + @Nullable private final HttpRequestInitializer delegate; private final StorageClientMetrics metrics; private final ApiClock clock; @@ -133,9 +137,16 @@ public void initialize(HttpRequest request) throws IOException { AtomicLong startTimeNanos = new AtomicLong(); AtomicBoolean recorded = new AtomicBoolean(true); + // HTTP status of a failed attempt that google-http-client is about to retry (NO_RESPONSE for + // an IOException), recorded once the next attempt starts. + AtomicInteger pendingRetryStatusCode = new AtomicInteger(NO_PENDING_RETRY); request.setInterceptor( req -> { + int priorStatusCode = pendingRetryStatusCode.getAndSet(NO_PENDING_RETRY); + if (priorStatusCode != NO_PENDING_RETRY) { + recordInternalRetry(req, priorStatusCode); + } if (existingExec != null) { existingExec.intercept(req); } @@ -149,13 +160,12 @@ public void initialize(HttpRequest request) throws IOException { long endNanos = clock.nanoTime(); boolean handled = existingUnsuccessfulHandler.handleResponse(req, response, supportsRetry); - if (handled && response.getRequest() == req && recorded.compareAndSet(false, true)) { - recordResponse( - req, - startTimeNanos.get(), - endNanos, - response.getStatusCode(), - /* isRetry= */ supportsRetry); + boolean ownResponse = response.getRequest() == req; + if (handled && supportsRetry && ownResponse && response.getStatusCode() >= 400) { + pendingRetryStatusCode.set(response.getStatusCode()); + } + if (handled && ownResponse && recorded.compareAndSet(false, true)) { + recordResponse(req, startTimeNanos.get(), endNanos, response.getStatusCode()); } return handled; }); @@ -168,12 +178,7 @@ public void initialize(HttpRequest request) throws IOException { existingResp.interceptResponse(response); } if (recorded.compareAndSet(false, true)) { - recordResponse( - request, - startTimeNanos.get(), - endNanos, - response.getStatusCode(), - /* isRetry= */ false); + recordResponse(request, startTimeNanos.get(), endNanos, response.getStatusCode()); } }); @@ -182,35 +187,45 @@ public void initialize(HttpRequest request) throws IOException { // (specific subtypes like TIMEOUT, DNS_FAILURE, and TLS_FAILURE are mapped in Retrying). request.setIOExceptionHandler( (req, supportsRetry) -> { - long endNanos = clock.nanoTime(); - boolean recordedThisAttempt = recorded.compareAndSet(false, true); - String urlTemplate = recordedThisAttempt ? extractUrlTemplate(req.getUrl()) : ""; - if (recordedThisAttempt) { - double durationSeconds = (endNanos - startTimeNanos.get()) / 1_000_000_000.0; + if (recorded.compareAndSet(false, true)) { + double durationSeconds = (clock.nanoTime() - startTimeNanos.get()) / 1_000_000_000.0; recordDuration( req, durationSeconds, 0L, - urlTemplate, + extractUrlTemplate(req.getUrl()), 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), - StorageClientMetrics.NETWORK_PATH_CLOUDPATH, - StorageErrorTypeMapper.STATUS_CONNECTION_ERROR); + if (handled && supportsRetry) { + pendingRetryStatusCode.set(NO_RESPONSE); } return handled; }); } - private void recordResponse( - HttpRequest request, long startNanos, long endNanos, int statusCode, boolean isRetry) { + private void recordInternalRetry(HttpRequest request, int priorStatusCode) { + String errorType = + priorStatusCode == NO_RESPONSE + ? StorageErrorTypeMapper.STATUS_CONNECTION_ERROR + : StorageErrorTypeMapper.mapHttpResponseCode(priorStatusCode); + StorageMetricsContext ctx = StorageMetricsContext.current(); + Context otelContext = Context.current(); + if (ctx != null) { + // Retrying only sees the final outcome of HttpRequest.execute(), so the failed attempt that + // google-http-client retried internally is recorded here. + ctx.recordAttemptFailure(errorType, priorStatusCode); + otelContext = ctx.getOtelContext(); + } + metrics.recordRetry( + otelContext, + resolveOperationName(request, extractUrlTemplate(request.getUrl())), + StorageClientMetrics.NETWORK_PATH_CLOUDPATH, + errorType); + } + + private void recordResponse(HttpRequest request, long startNanos, long endNanos, int statusCode) { double durationSeconds = (endNanos - startNanos) / 1_000_000_000.0; String urlTemplate = extractUrlTemplate(request.getUrl()); String errorType = @@ -223,13 +238,11 @@ private void recordResponse( // may append query parameters (e.g. alt=media, uploadType) after buildRequest(). StorageMetricsContext ctx = StorageMetricsContext.current(); Context otelContext = ctx != null ? ctx.getOtelContext() : Context.current(); - String operationName = resolveOperationName(ctx, request, urlTemplate); metrics.recordTtfb( - otelContext, operationName, durationSeconds, StorageClientMetrics.NETWORK_PATH_CLOUDPATH); - if (isRetry) { - metrics.recordRetry( - otelContext, operationName, StorageClientMetrics.NETWORK_PATH_CLOUDPATH, errorType); - } + otelContext, + resolveOperationName(request, urlTemplate), + durationSeconds, + StorageClientMetrics.NETWORK_PATH_CLOUDPATH); } private void recordDuration( @@ -243,11 +256,7 @@ private void recordDuration( } static String resolveOperationName(HttpRequest request, String urlTemplate) { - return resolveOperationName(StorageMetricsContext.current(), request, urlTemplate); - } - - private static String resolveOperationName( - @Nullable StorageMetricsContext ctx, HttpRequest request, String urlTemplate) { + StorageMetricsContext ctx = StorageMetricsContext.current(); return ctx != null ? ctx.getOperationName() : defaultOperationName(request, urlTemplate); } 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 97b8615a68d1..96e7d4081bfe 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 @@ -291,11 +291,26 @@ void recordAttemptFailure(Throwable e) { } void recordAttemptFailure(@Nullable StorageClientMetrics metrics, Throwable e) { + recordAttemptFailure(metrics, StorageErrorTypeMapper.mapThrowable(e), e, HTTP_STATUS_UNSET); + } + + /** + * Records a failed attempt that google-http-client retried internally (for example a 401 + * credential refresh or an {@code IOException}), which {@link Retrying} never observes. + */ + void recordAttemptFailure(String errorType, long httpStatusCode) { + recordAttemptFailure(this.metrics, errorType, null, httpStatusCode); + } + + private void recordAttemptFailure( + @Nullable StorageClientMetrics metrics, + String errorType, + @Nullable Throwable e, + long defaultHttpStatus) { if (metrics == null) { return; } try (Scope ignore = otelContext.makeCurrent()) { - String errorType = StorageErrorTypeMapper.mapThrowable(e); String networkPath = resolveNetworkPath(); Attributes attemptBase = buildAttemptBaseAttributes(metrics); recordErrorCounter(metrics, attemptBase, errorType, networkPath); @@ -304,7 +319,7 @@ void recordAttemptFailure(@Nullable StorageClientMetrics metrics, Throwable e) { attemptBase.toBuilder() .put(StorageClientMetrics.KEY_ERROR_TYPE, errorType) .put(StorageClientMetrics.KEY_NETWORK_PATH, networkPath); - putAttemptStatusCodes(builder, e, StorageErrorTypeMapper.STATUS_UNKNOWN, HTTP_STATUS_UNSET); + putAttemptStatusCodes(builder, e, StorageErrorTypeMapper.STATUS_UNKNOWN, defaultHttpStatus); metrics.getAttempts().add(1, builder.build()); } } diff --git a/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/ApiaryUnbufferedReadableByteChannelTest.java b/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/ApiaryUnbufferedReadableByteChannelTest.java index 40c80ba0b3a2..e2de2a6eb5cf 100644 --- a/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/ApiaryUnbufferedReadableByteChannelTest.java +++ b/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/ApiaryUnbufferedReadableByteChannelTest.java @@ -58,6 +58,7 @@ import java.util.Locale; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Predicate; import java.util.logging.Handler; import java.util.logging.LogRecord; import java.util.logging.Logger; @@ -425,6 +426,31 @@ public void close() throws SecurityException {} @Test public void midStreamIoException_retried_recordsRetryAndErrorMetrics() throws IOException { + // Not retryable as-is; retried once translated to a StorageException. + assertMidStreamRetryRecorded( + readWithMidStreamIoException(retryIf(t -> t instanceof StorageException), true)); + } + + @Test + public void midStreamIoException_directlyRetryable_recordsRetryAndErrorMetrics() + throws IOException { + assertMidStreamRetryRecorded(readWithMidStreamIoException(retryIf(t -> true), true)); + } + + @Test + public void midStreamIoException_notRetryable_recordsErrorWithoutRetry() throws IOException { + Collection collected = readWithMidStreamIoException(retryIf(t -> false), false); + LongPointData errorPoint = + findSinglePoint(collected, StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_ERRORS); + assertThat(errorPoint.getValue()).isEqualTo(1L); + assertThat(errorPoint.getAttributes().get(StorageClientMetrics.KEY_ERROR_TYPE)) + .isEqualTo(StorageErrorTypeMapper.STATUS_CONNECTION_ERROR); + assertThat(collected.stream().map(MetricData::getName)) + .doesNotContain(StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_RETRIES); + } + + private static Collection readWithMidStreamIoException( + BasicResultRetryAlgorithm alg, boolean expectSuccess) throws IOException { InMemoryMetricReader reader = InMemoryMetricReader.create(); SdkMeterProvider provider = SdkMeterProvider.builder().registerMetricReader(reader).build(); HttpStorageOptions options = @@ -478,19 +504,20 @@ public int read() throws IOException { storageClient, SettableApiFuture.create(), options.createRetrier().withMetricsContext(ctx), - new BasicResultRetryAlgorithm() { - @Override - public boolean shouldRetry(Throwable previousThrowable, Object previousResponse) { - return previousThrowable instanceof StorageException; - } - }, + alg, Hasher.noop())) { - ByteBuffer buf = ByteBuffer.allocate(CONTENT_BYTES.length); - assertThat(channel.read(new ByteBuffer[] {buf}, 0, 1)).isEqualTo(CONTENT_BYTES.length); + ByteBuffer[] bufs = {ByteBuffer.allocate(CONTENT_BYTES.length)}; + if (expectSuccess) { + assertThat(channel.read(bufs, 0, 1)).isEqualTo(CONTENT_BYTES.length); + } else { + assertThrows(IOException.class, () -> channel.read(bufs, 0, 1)); + } } + assertThat(calls.get()).isEqualTo(expectSuccess ? 2 : 1); + return reader.collectAllMetrics(); + } - Collection collected = reader.collectAllMetrics(); - assertThat(calls.get()).isEqualTo(2); + private static void assertMidStreamRetryRecorded(Collection collected) { LongPointData retryPoint = findSinglePoint(collected, StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_RETRIES); assertThat(retryPoint.getValue()).isEqualTo(1L); @@ -533,6 +560,15 @@ public boolean shouldRetry(Throwable previousThrowable, Object previousResponse) assertThat(attemptsTotal).isEqualTo(2L); } + private static BasicResultRetryAlgorithm retryIf(Predicate shouldRetry) { + return new BasicResultRetryAlgorithm() { + @Override + public boolean shouldRetry(Throwable previousThrowable, Object previousResponse) { + return shouldRetry.test(previousThrowable); + } + }; + } + private static LongPointData findSinglePoint(Collection collected, String name) { MetricData metric = collected.stream() diff --git a/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/GapicUnbufferedReadableByteChannelTest.java b/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/GapicUnbufferedReadableByteChannelTest.java index 8990cdc0ce9d..01b1643c8f61 100644 --- a/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/GapicUnbufferedReadableByteChannelTest.java +++ b/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/GapicUnbufferedReadableByteChannelTest.java @@ -21,6 +21,7 @@ import static org.junit.Assert.assertThrows; import com.google.api.core.SettableApiFuture; +import com.google.api.gax.retrying.ResultRetryAlgorithm; import com.google.api.gax.rpc.ApiCallContext; import com.google.api.gax.rpc.ResponseObserver; import com.google.api.gax.rpc.ServerStreamingCallable; @@ -549,6 +550,36 @@ public void call( @Test public void midStreamError_retried_recordsRetryAndErrorMetrics() throws IOException { + assertMidStreamRetryRecorded( + readWithMidStreamError( + Status.UNAVAILABLE.asRuntimeException(), Retrying.alwaysRetry(), true), + StorageErrorTypeMapper.STATUS_UNAVAILABLE); + } + + @Test + public void midStreamIoException_retried_recordsRetryAndErrorMetrics() throws IOException { + IOException ioe = new IOException("connection reset"); + assertMidStreamRetryRecorded( + readWithMidStreamError(ioe, Retrying.alwaysRetry(), true), + StorageErrorTypeMapper.mapThrowable(StorageException.coalesce(ioe))); + } + + @Test + public void midStreamError_notRetryable_recordsErrorWithoutRetry() throws IOException { + Collection collected = + readWithMidStreamError( + Status.PERMISSION_DENIED.asRuntimeException(), Retrying.neverRetry(), false); + LongPointData errorPoint = + findSinglePoint(collected, StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_ERRORS); + assertThat(errorPoint.getValue()).isEqualTo(1L); + assertThat(errorPoint.getAttributes().get(StorageClientMetrics.KEY_ERROR_TYPE)) + .isEqualTo("PERMISSION_DENIED"); + assertThat(collected.stream().map(MetricData::getName)) + .doesNotContain(StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_RETRIES); + } + + private static Collection readWithMidStreamError( + Throwable firstError, ResultRetryAlgorithm alg, boolean expectSuccess) throws IOException { InMemoryMetricReader reader = InMemoryMetricReader.create(); SdkMeterProvider provider = SdkMeterProvider.builder().registerMetricReader(reader).build(); GrpcStorageOptions options = @@ -584,7 +615,7 @@ public void call( ReadObjectResponse.newBuilder() .setChecksummedData(firstContent.asChecksummedData()) .build()); - respond.onError(Status.UNAVAILABLE.asRuntimeException()); + respond.onError(firstError); } else { respond.onResponse( ReadObjectResponse.newBuilder() @@ -598,13 +629,20 @@ public void call( ReadObjectRequest.getDefaultInstance(), Hasher.noop(), options.createRetrier().withMetricsContext(ctx), - Retrying.alwaysRetry())) { + alg)) { ByteBuffer buffer = ByteBuffer.allocate(10); - assertThat(c.read(buffer)).isEqualTo(10); + if (expectSuccess) { + assertThat(c.read(buffer)).isEqualTo(10); + } else { + assertThrows(IOException.class, () -> c.read(buffer)); + } } + assertThat(calls.get()).isEqualTo(expectSuccess ? 2 : 1); + return reader.collectAllMetrics(); + } - Collection collected = reader.collectAllMetrics(); - assertThat(calls.get()).isEqualTo(2); + private static void assertMidStreamRetryRecorded( + Collection collected, String errorType) { LongPointData retryPoint = findSinglePoint(collected, StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_RETRIES); assertThat(retryPoint.getValue()).isEqualTo(1L); @@ -624,14 +662,14 @@ public void call( .put( StorageClientMetrics.KEY_NETWORK_PATH, StorageClientMetrics.NETWORK_PATH_DIRECTPATH) - .put(StorageClientMetrics.KEY_ERROR_TYPE, StorageErrorTypeMapper.STATUS_UNAVAILABLE) + .put(StorageClientMetrics.KEY_ERROR_TYPE, errorType) .build()); LongPointData errorPoint = findSinglePoint(collected, StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_ERRORS); assertThat(errorPoint.getValue()).isEqualTo(1L); assertThat(errorPoint.getAttributes().get(StorageClientMetrics.KEY_ERROR_TYPE)) - .isEqualTo(StorageErrorTypeMapper.STATUS_UNAVAILABLE); + .isEqualTo(errorType); assertThat(errorPoint.getAttributes().get(StorageClientMetrics.KEY_GCP_STORAGE_OPERATION)) .isEqualTo("ReadObject"); 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 bb9ca17f99b7..1e772b0d898b 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 @@ -667,7 +667,9 @@ public LowLevelHttpResponse execute() throws IOException { transport .createRequestFactory(interceptor) .buildGetRequest(new GenericUrl("https://storage.googleapis.com/storage/v1/b/my-b")); - req.execute(); + try (Scope ignore = metrics.createContext("GetBucket").makeCurrent()) { + req.execute(); + } List points = durationPoints(); assertThat(points).hasSize(2); @@ -700,6 +702,7 @@ public LowLevelHttpResponse execute() throws IOException { assertThat(retries.get(0).getAttributes()) .isEqualTo( expectedRetryAttributes("GetBucket", StorageErrorTypeMapper.STATUS_CONNECTION_ERROR)); + assertInternallyRetriedAttempt(StorageErrorTypeMapper.STATUS_CONNECTION_ERROR, 0L); } @Test @@ -747,7 +750,9 @@ public LowLevelHttpResponse execute() { .buildGetRequest( new GenericUrl( "https://storage.googleapis.com/download/storage/v1/b/my-b/o/my-obj?alt=media")); - req.execute(); + try (Scope ignore = metrics.createContext("ReadObject").makeCurrent()) { + req.execute(); + } List points = durationPoints(); assertThat(points).hasSize(2); @@ -781,6 +786,40 @@ public LowLevelHttpResponse execute() { assertThat(retries.get(0).getValue()).isEqualTo(1L); assertThat(retries.get(0).getAttributes()) .isEqualTo(expectedRetryAttributes("ReadObject", "UNAUTHENTICATED")); + assertInternallyRetriedAttempt("UNAUTHENTICATED", 401L); + } + + @Test + public void initialize_handled3xxThenRetry_doesNotRecordRetry() throws IOException { + AtomicBoolean firstAttempt = new AtomicBoolean(true); + HttpRequestInitializer delegate = + request -> request.setUnsuccessfulResponseHandler((req, response, supportsRetry) -> true); + StorageHttpMetricsInterceptor interceptor = + new StorageHttpMetricsInterceptor(delegate, metrics, clock); + HttpTransport transport = + new MockHttpTransport() { + @Override + public LowLevelHttpRequest buildRequest(String method, String url) { + return new MockLowLevelHttpRequest() { + @Override + public LowLevelHttpResponse execute() { + return new MockLowLevelHttpResponse() + .setStatusCode(firstAttempt.compareAndSet(true, false) ? 308 : 200); + } + }; + } + }; + HttpRequest req = + transport + .createRequestFactory(interceptor) + .buildGetRequest(new GenericUrl("https://storage.googleapis.com/storage/v1/b/my-b")); + try (Scope ignore = metrics.createContext("GetBucket").makeCurrent()) { + req.execute(); + } + + assertThat(durationPoints()).hasSize(2); + assertThat(retriesPoints()).isEmpty(); + assertThat(longSumPoints(StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_ATTEMPTS)).isEmpty(); } @Test @@ -824,6 +863,13 @@ public LowLevelHttpResponse execute() throws IOException { reqIo.setNumberOfRetries(0); assertThrows(IOException.class, reqIo::execute); + // IOException with retries left but no IOExceptionHandler, so google-http-client rethrows it. + HttpRequest reqUnhandled = + ioTransport + .createRequestFactory(new StorageHttpMetricsInterceptor(null, metrics, clock)) + .buildGetRequest(new GenericUrl("https://storage.googleapis.com/storage/v1/b/my-b")); + assertThrows(IOException.class, reqUnhandled::execute); + assertThat(durationPoints()).hasSize(2); assertThat(retriesPoints()).isEmpty(); } @@ -1042,13 +1088,35 @@ private List ttfbPoints() { } private List retriesPoints() { + return longSumPoints(StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_RETRIES); + } + + private List longSumPoints(String metricName) { return reader.collectAllMetrics().stream() - .filter(m -> m.getName().equals(StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_RETRIES)) + .filter(m -> m.getName().equals(metricName)) .findFirst() .map(m -> ImmutableList.copyOf(m.getLongSumData().getPoints())) .orElse(ImmutableList.of()); } + private void assertInternallyRetriedAttempt(String errorType, long httpStatusCode) { + List attempts = + longSumPoints(StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_ATTEMPTS); + assertThat(attempts).hasSize(1); + assertThat(attempts.get(0).getValue()).isEqualTo(1L); + assertThat(attempts.get(0).getAttributes().get(StorageClientMetrics.KEY_ERROR_TYPE)) + .isEqualTo(errorType); + assertThat( + attempts.get(0).getAttributes().get(StorageClientMetrics.KEY_HTTP_RESPONSE_STATUS_CODE)) + .isEqualTo(httpStatusCode); + List errors = + longSumPoints(StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_ERRORS); + assertThat(errors).hasSize(1); + assertThat(errors.get(0).getValue()).isEqualTo(1L); + assertThat(errors.get(0).getAttributes().get(StorageClientMetrics.KEY_ERROR_TYPE)) + .isEqualTo(errorType); + } + private static Attributes expectedRetryAttributes(String operationName, String errorType) { return Attributes.builder() .put(StorageClientMetrics.KEY_GCP_CLIENT_SERVICE, StorageClientMetrics.SERVICE_STORAGE)