Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -152,16 +153,21 @@ 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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nit: Can we add a test case that hits this retryable branch too?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in 736b10f: added midStreamIoException_directlyRetryable_recordsRetryAndErrorMetrics, where the algorithm accepts the raw exception so the first branch is taken.

Co-authored by AI Agent

sbc = null;
} else if (t instanceof IOException) {
IOException ioE = (IOException) t;
if (resultRetryAlgorithm.shouldRetry(StorageException.translate(ioE), null)) {
recordMidStreamRetry(ioE);
sbc = null;
Comment thread
nidhiii-27 marked this conversation as resolved.
Resolved
} 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);
Expand Down Expand Up @@ -203,6 +209,21 @@ public void close() throws IOException {
}
}

private void recordMidStreamRetry(Throwable error) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Should we also call metricsContext.recordError(...) in the non-retryable else branches so terminal mid-stream errors are counted?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in 736b10f: both terminal branches (throw ioE and throw new IOException(coalesce(t))) now record gcp.storage.client.errors before rethrowing (no retry). The open path runs outside this try, so it can't double count with Retrying. Added midStreamIoException_notRetryable_recordsErrorWithoutRetry.

Co-authored by AI Agent

StorageMetricsContext metricsContext = retrier.getMetricsContext();
if (metricsContext != null) {
metricsContext.recordError(error);
metricsContext.recordRetry(error);
}
}

private void recordMidStreamError(Throwable error) {
StorageMetricsContext metricsContext = retrier.getMetricsContext();
if (metricsContext != null) {
metricsContext.recordError(error);
}
}

private void setXGoogGeneration(long xGoogGeneration) {
this.xGoogGeneration = xGoogGeneration;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -163,9 +163,11 @@ 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));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nit: Can we add a test case that hits this IOException branch too?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in 736b10f: added midStreamIoException_retried_recordsRetryAndErrorMetrics (gRPC), which queues an IOException mid-stream that the algorithm retries.

Co-authored by AI Agent

cancelAndDrainCurrentObserver();
continue;
} else {
recordMidStreamError(StorageException.coalesce(ioe));
ioe.addSuppressed(new AsyncStorageTaskException());
throw ioe;
}
Expand All @@ -174,9 +176,11 @@ 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 {
recordMidStreamError(coalesce);
close();
throw new IOException(coalesce);
}
Expand Down Expand Up @@ -298,6 +302,21 @@ private void drainQueue() throws IOException {
}
}

private void recordMidStreamRetry(Throwable error) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Same here: should we call metricsContext.recordError(...) in the non-retryable else branches for terminal mid-stream errors?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in 736b10f: same change on the gRPC path for both terminal branches, using the same coalesce(...) input as the retry branch. Added midStreamError_notRetryable_recordsErrorWithoutRetry.

Co-authored by AI Agent

StorageMetricsContext metricsContext = retrier.getMetricsContext();
if (metricsContext != null) {
metricsContext.recordError(error);
metricsContext.recordRetry(error);
}
}

private void recordMidStreamError(Throwable error) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Should we also call recordMidStreamError in validateCumulativeChecksum so EOF checksum mismatches are counted on gRPC reads too?

StorageMetricsContext metricsContext = retrier.getMetricsContext();
if (metricsContext != null) {
metricsContext.recordError(error);
}
}

private void cancelAndDrainCurrentObserver() {
if (readObjectObserver != null) {
readObjectObserver.cancel();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -212,6 +222,11 @@ public <Response, Model> 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 {
Expand Down Expand Up @@ -329,6 +344,11 @@ public <Response, Model> Model run(
httpRpcContext.clearInvocationId();
}
}

@Override
public @Nullable StorageMetricsContext getMetricsContext() {
return delegate.getMetricsContext();
}
}

@NonNull
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand All @@ -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);
}
Expand All @@ -149,7 +160,11 @@ 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)) {
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;
Expand Down Expand Up @@ -181,11 +196,35 @@ public void initialize(HttpRequest request) throws IOException {
extractUrlTemplate(req.getUrl()),
StorageErrorTypeMapper.STATUS_CONNECTION_ERROR);
}
return existingIoHandler != null
&& existingIoHandler.handleIOException(req, supportsRetry);
boolean handled =
existingIoHandler != null && existingIoHandler.handleIOException(req, supportsRetry);
if (handled && supportsRetry) {
pendingRetryStatusCode.set(NO_RESPONSE);
}
return handled;
});
}

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());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -291,32 +291,55 @@ 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);
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()
.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());
}
}
}

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;
Expand All @@ -328,6 +351,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;
}
Expand Down
Loading
Loading