Skip to content
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);
Comment thread
nidhiii-27 marked this conversation as resolved.
Resolved
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) {
Comment thread
nidhiii-27 marked this conversation as resolved.
Resolved
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));
Comment thread
nidhiii-27 marked this conversation as resolved.
Resolved
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) {
Comment thread
nidhiii-27 marked this conversation as resolved.
Resolved
StorageMetricsContext metricsContext = retrier.getMetricsContext();
if (metricsContext != null) {
metricsContext.recordError(error);
metricsContext.recordRetry(error);
}
}

private void recordMidStreamError(Throwable error) {
Comment thread
nidhiii-27 marked this conversation as resolved.
Resolved
StorageMetricsContext metricsContext = retrier.getMetricsContext();
if (metricsContext != null) {
metricsContext.recordError(error);
}
}

private void cancelAndDrainCurrentObserver() {
if (readObjectObserver != null) {
readObjectObserver.cancel();
Expand Down Expand Up @@ -355,7 +374,9 @@ private void validateCumulativeChecksum() throws IOException {
try {
cumulativeHasher.validateCumulativeChecksum(metadata);
} catch (UncheckedCumulativeChecksumMismatchException exception) {
throw new IOException(StorageException.coalesce(exception));
BaseServiceException coalesce = StorageException.coalesce(exception);
recordMidStreamError(coalesce);
throw new IOException(coalesce);
}
}
}
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 @@ -34,6 +34,7 @@
import java.io.OutputStream;
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 @@ -111,6 +112,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 @@ -137,9 +141,16 @@ public void initialize(HttpRequest request) throws IOException {
AtomicLong startTimeNanos = new AtomicLong();
AtomicLong bodyWriteEndNanos = 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 @@ -160,7 +171,11 @@ && isMediaUploadRequest(req)) {
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(),
Expand Down Expand Up @@ -203,11 +218,35 @@ && isMediaUploadRequest(req)) {
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()), ctx),
StorageClientMetrics.NETWORK_PATH_CLOUDPATH,
errorType);
}

private void recordResponse(
HttpRequest request, long startNanos, long writeEndNanos, long endNanos, int statusCode) {
double durationSeconds = Math.max(0L, endNanos - startNanos) / 1_000_000_000.0;
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