Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
2590f0e
feat: add http.client.request.duration metric for HTTP requests
nidhiii-27 Oct 22, 2026
510824a
fix(storage): address PR #14744 review comments and align HTTP durati…
nidhiii-27 Nov 3, 2026
88cef70
fix(storage): merge base branch and align StorageHttpMetricsInterceptor
nidhiii-27 Nov 5, 2026
57e750a
Merge branch 'feat/storage-rpc-call-duration' into feat/storage-http-…
nidhiii-27 Nov 5, 2026
9a1c760
Merge branch 'feat/storage-rpc-call-duration' into feat/storage-http-…
nidhiii-27 Nov 5, 2026
759422a
Merge branch 'feat/storage-rpc-call-duration' into feat/storage-http-…
nidhiii-27 Nov 5, 2026
df4a503
refactor(storage): simplify extractUrlTemplate and move recordHttpReq…
nidhiii-27 Nov 5, 2026
d015a76
Merge branch 'feat/storage-rpc-call-duration' into feat/storage-http-…
nidhiii-27 Nov 7, 2026
610bd86
fix(storage): resolve PR #14744 review comments in StorageHttpMetrics…
nidhiii-27 Nov 7, 2026
baa4283
test(storage): align RetryingMetricsTest with DEADLINE_EXCEEDED error…
nidhiii-27 Nov 7, 2026
d6b4def
fix(storage): merge feat/storage-rpc-call-duration and use long statu…
nidhiii-27 Nov 12, 2026
a92031d
Merge branch 'feat/storage-rpc-call-duration' into feat/storage-http-…
nidhiii-27 Nov 12, 2026
f71f98a
fix(storage): address PR review feedback on HTTP request duration int…
nidhiii-27 Nov 12, 2026
f8d3db1
Merge branch 'feat/storage-rpc-call-duration' into feat/storage-http-…
nidhiii-27 Nov 12, 2026
dfae3dd
Merge remote-tracking branch 'origin/feat/storage-rpc-call-duration' …
nidhiii-27 Nov 16, 2026
d36f02b
fix(storage): address follow-up review comments on PR #14744
nidhiii-27 Nov 16, 2026
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
@@ -0,0 +1,277 @@
/*
* Copyright 2026 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.cloud.storage;

import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpExecuteInterceptor;
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.HttpResponseInterceptor;
import com.google.api.client.http.HttpUnsuccessfulResponseHandler;
import com.google.api.core.ApiClock;
import com.google.common.collect.ImmutableSet;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;

/**
* {@link HttpRequestInitializer} that instruments outgoing HTTP requests to record OpenTelemetry
* client metrics.
*
* <p>Note: {@code google-http-client} invokes {@link HttpResponseInterceptor#interceptResponse}
* inside {@link HttpRequest#execute()} when the HTTP response headers arrive, so download durations
* recorded here end at response headers and exclude streaming body transfer (a follow-up is tracked
* for recording when the response body is closed). End-to-end download duration including body
* transfer is captured by {@code gcp.client.request.duration}.
*/
@NullMarked
final class StorageHttpMetricsInterceptor implements HttpRequestInitializer {

private static final ImmutableSet<String> OBJECT_SUB_RESOURCES =
ImmutableSet.of("acl", "compose", "restore", "watchAll");

@Nullable private final HttpRequestInitializer delegate;
@Nullable private final StorageClientMetrics metrics;
private final ApiClock clock;
@Nullable private final String defaultServerAddress;

StorageHttpMetricsInterceptor(
@Nullable HttpRequestInitializer delegate,
@Nullable StorageClientMetrics metrics,
ApiClock clock,
@Nullable String host) {
this.delegate = delegate;
this.metrics = metrics;
this.clock = clock;
this.defaultServerAddress = OpenTelemetryBootstrappingUtils.extractServerAddress(host);
}

@Override
public void initialize(HttpRequest request) throws IOException {
if (delegate != null) {
delegate.initialize(request);
}
if (metrics == null || metrics.getHttpClientRequestDuration() == null) {
return;
}

HttpExecuteInterceptor existingExec = request.getInterceptor();
HttpResponseInterceptor existingResp = request.getResponseInterceptor();
HttpUnsuccessfulResponseHandler existingUnsuccessfulHandler =
request.getUnsuccessfulResponseHandler();
HttpIOExceptionHandler existingIoHandler = request.getIOExceptionHandler();

AtomicLong startTimeNanos = new AtomicLong();
AtomicBoolean recorded = new AtomicBoolean(true);

request.setInterceptor(
req -> {
if (existingExec != null) {
existingExec.intercept(req);
}
startTimeNanos.set(clock.nanoTime());
recorded.set(false);
});

if (existingUnsuccessfulHandler != null) {
request.setUnsuccessfulResponseHandler(
(req, response, supportsRetry) -> {
long endNanos = clock.nanoTime();
boolean handled =
existingUnsuccessfulHandler.handleResponse(req, response, supportsRetry);
if (handled && recorded.compareAndSet(false, true)) {

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.

Can we take the end time before delegating to the existing handler here? Otherwise the 401 point includes the token refresh round trip.

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

Co-authored by AI Agent

int statusCode = response.getStatusCode();
String errorType =
statusCode >= 400
? StorageErrorTypeMapper.mapHttpResponseCode(statusCode)
: StorageErrorTypeMapper.STATUS_OK;
recordDuration(req, startTimeNanos.get(), endNanos, (long) statusCode, errorType);
}
return handled;
});
}

request.setResponseInterceptor(
response -> {
if (existingResp != null) {
existingResp.interceptResponse(response);
}
if (recorded.compareAndSet(false, true)) {
Comment thread
nidhiii-27 marked this conversation as resolved.
Resolved
int statusCode = response.getStatusCode();
String errorType =
statusCode >= 400
? StorageErrorTypeMapper.mapHttpResponseCode(statusCode)
: StorageErrorTypeMapper.STATUS_OK;
recordDuration(request, startTimeNanos.get(), (long) statusCode, errorType);
}
});

// 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).
request.setIOExceptionHandler(
Comment thread
nidhiii-27 marked this conversation as resolved.
Resolved
(req, supportsRetry) -> {
if (recorded.compareAndSet(false, true)) {
recordDuration(
req,
startTimeNanos.get(),
StorageMetricsContext.HTTP_STATUS_UNSET,
StorageErrorTypeMapper.STATUS_CONNECTION_ERROR);
}
return existingIoHandler != null
&& existingIoHandler.handleIOException(req, supportsRetry);
});
}

private void recordDuration(
HttpRequest request, long startNanos, long statusCode, String errorType) {
recordDuration(request, startNanos, clock.nanoTime(), statusCode, errorType);
}

private void recordDuration(
HttpRequest request, long startNanos, long endNanos, long statusCode, String errorType) {
if (metrics == null) {
return;
}
double durationSeconds = Math.max(0.0, (endNanos - startNanos) / 1_000_000_000.0);
String method = request.getRequestMethod() != null ? request.getRequestMethod() : "UNKNOWN";
String urlTemplate = extractUrlTemplate(request.getUrl());
String serverAddress = resolveServerAddress(request.getUrl(), defaultServerAddress);

StorageMetricsContext.recordHttpRequestDuration(
metrics, durationSeconds, method, statusCode, urlTemplate, serverAddress, errorType);
}

@Nullable
static String resolveServerAddress(
@Nullable GenericUrl url, @Nullable String defaultServerAddress) {
String host = url != null ? url.getHost() : null;
if (host == null || host.isEmpty()) {
return defaultServerAddress;
}
if (host.endsWith(".storage.googleapis.com") && !host.equals("storage.googleapis.com")) {
return "storage.googleapis.com";
}
if (defaultServerAddress != null
&& !defaultServerAddress.isEmpty()
&& host.endsWith("." + defaultServerAddress)) {
return defaultServerAddress;
}
return host;
}

static String extractUrlTemplate(@Nullable GenericUrl url) {
if (url == null) {
return "/";
}
String path = url.getRawPath();
if (path == null || path.isEmpty()) {
return "/";
}
String host = url.getHost();
if (host != null
&& host.endsWith(".storage.googleapis.com")
&& !host.equals("storage.googleapis.com")) {
return "/".equals(path) ? "/" : "/{object}";
}
if (path.length() > 1 && path.endsWith("/")) {
path = path.substring(0, path.length() - 1);
}
if (path.startsWith("/upload/storage/v1/b/")) {
return "/upload/storage/v1/b/{bucket}/o";
}
if (path.startsWith("/download/storage/v1/b/")) {
return "/download/storage/v1/b/{bucket}/o/{object}";
}
if (path.startsWith("/batch/storage/v1")) {
return "/batch/storage/v1";
}
if (path.startsWith("/storage/v1/")) {
return extractV1UrlTemplate(path.substring("/storage/v1/".length()));
}
String trimmed = path.startsWith("/") ? path.substring(1) : path;
if (trimmed.isEmpty()) {
return "/";
}
String[] parts = trimmed.split("/", 2);
return parts.length == 1 ? "/{bucket}" : "/{bucket}/{object}";
}

private static String extractV1UrlTemplate(String rest) {
if ("b".equals(rest)) {
return "/storage/v1/b";
}
String[] segments = rest.split("/");
if (segments.length >= 2 && "b".equals(segments[0])) {
Comment thread
nidhiii-27 marked this conversation as resolved.
Resolved
if (segments.length == 2) {
return "/storage/v1/b/{bucket}";
}
if ("o".equals(segments[2])) {
return extractObjectUrlTemplate(segments);
}
if ("iam".equals(segments[2]) && segments.length > 3) {
return "/storage/v1/b/{bucket}/iam/" + segments[3];
}
if (segments.length >= 4) {
if ("acl".equals(segments[2]) || "defaultObjectAcl".equals(segments[2])) {
return "/storage/v1/b/{bucket}/" + segments[2] + "/{entity}";
}
if ("notificationConfigs".equals(segments[2]) || "notifications".equals(segments[2])) {
return "/storage/v1/b/{bucket}/" + segments[2] + "/{notification}";
}
}
return "/storage/v1/b/{bucket}/" + segments[2];

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.

My earlier comment was imprecise, sorry: only raw ids should not leak; Python keeps {entity} on acl paths and {notification} on notificationConfigs. Fine to restore those so get-one and list don't share a template, otherwise happy to leave as is.

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

Co-authored by AI Agent

}
if (segments.length >= 2 && "projects".equals(segments[0])) {
segments[1] = "{project}";
if (segments.length >= 4 && "hmacKeys".equals(segments[2])) {
segments[3] = "{access_id}";
}
return "/storage/v1/" + String.join("/", segments);
}
return "/storage/v1";
}

private static String extractObjectUrlTemplate(String[] segments) {
if (segments.length == 3) {
return "/storage/v1/b/{bucket}/o";
}
if (segments.length == 4) {
return "/storage/v1/b/{bucket}/o/{object}";
}
String action = segments[4];
if (("copyTo".equals(action) || "rewriteTo".equals(action))
&& segments.length >= 8
&& "b".equals(segments[5])
&& "o".equals(segments[7])) {
return "/storage/v1/b/{bucket}/o/{object}/" + action + "/b/{bucket}/o/{object}";
}
if ("moveTo".equals(action) && segments.length >= 7 && "o".equals(segments[5])) {
return "/storage/v1/b/{bucket}/o/{object}/moveTo/o/{object}";
}
if ("acl".equals(action) && segments.length >= 6) {
return "/storage/v1/b/{bucket}/o/{object}/acl/{entity}";
}
if (OBJECT_SUB_RESOURCES.contains(action)) {
return "/storage/v1/b/{bucket}/o/{object}/" + action;
}
return "/storage/v1/b/{bucket}/o/{object}";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ final class StorageMetricsContext {
CallOptions.Key.create("storage-metrics-context");

private static final long HTTP_STATUS_OK = 200L;
private static final long HTTP_STATUS_UNSET = 0L;
static final long HTTP_STATUS_UNSET = 0L;

@Nullable private final StorageClientMetrics metrics;
private final String operationName;
Expand Down Expand Up @@ -273,6 +273,32 @@ void setNetworkPath(String networkPath) {
this.networkPath = networkPath;
}

static void recordHttpRequestDuration(
@Nullable StorageClientMetrics metrics,
double durationSeconds,
String httpMethod,
long statusCode,
String urlTemplate,
@Nullable String serverAddress,
String errorType) {
if (metrics == null || metrics.getHttpClientRequestDuration() == null) {
return;
}
Attributes attributes =
metrics
.clientAttributesBuilder()
.put(StorageClientMetrics.KEY_RPC_SYSTEM_NAME, "http")
.put(StorageClientMetrics.KEY_HTTP_REQUEST_METHOD, httpMethod)
.put(StorageClientMetrics.KEY_HTTP_RESPONSE_STATUS_CODE, statusCode)
.put(StorageClientMetrics.KEY_NETWORK_PATH, StorageClientMetrics.NETWORK_PATH_CLOUDPATH)
.put(StorageClientMetrics.KEY_URL_TEMPLATE, urlTemplate)
.put(
StorageClientMetrics.KEY_SERVER_ADDRESS, serverAddress != null ? serverAddress : "")
.put(StorageClientMetrics.KEY_ERROR_TYPE, errorType)
.build();
metrics.getHttpClientRequestDuration().record(durationSeconds, attributes, Context.current());
}

/**
* Populates both {@code rpc.response.status_code} and {@code http.response.status_code} on
* attempt metrics so every {@code gcp.storage.client.attempts} data point emits a consistent set
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

import static com.google.common.base.Preconditions.checkArgument;

import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.core.BetaApi;
import com.google.api.core.InternalApi;
import com.google.cloud.NoCredentials;
Expand Down Expand Up @@ -402,6 +403,16 @@ synchronized void closeStorageClientMetrics() {
}
}

@InternalApi
@Nullable
public HttpRequestInitializer decorateWithMetrics(@Nullable HttpRequestInitializer initializer) {
StorageClientMetrics metrics = getStorageClientMetrics();
if (metrics == null) {
return initializer;
}
return new StorageHttpMetricsInterceptor(initializer, metrics, getClock(), getHost());
}

/**
* The metric export interval configured for periodic metric reading.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,9 @@ public HttpStorageRpc(StorageOptions options, JsonFactory jsonFactory) {
CensusHttpModule censusHttpModule = new CensusHttpModule(tracer, IS_RECORD_EVENTS);
initializer = censusHttpModule.getHttpRequestInitializer(initializer);
initializer = new InvocationIdInitializer(initializer, applicationName, tm);
batchRequestInitializer = censusHttpModule.getHttpRequestInitializer(null);
initializer = options.decorateWithMetrics(initializer);
batchRequestInitializer =
options.decorateWithMetrics(censusHttpModule.getHttpRequestInitializer(null));
String host = options.getHost();
Storage.Builder storageBuilder =
new Storage.Builder(transport, jsonFactory, initializer)
Expand Down Expand Up @@ -283,7 +285,7 @@ public void addDelete(
StorageObject storageObject, RpcBatch.Callback<Void> callback, Map<Option, ?> options) {
try {
if (currentBatchSize == MAX_BATCH_SIZE) {
batches.add(storage.batch());
batches.add(storage.batch(batchRequestInitializer));
currentBatchSize = 0;
}
Delete call = deleteCall(storageObject, options);
Expand All @@ -302,7 +304,7 @@ public void addPatch(
Map<Option, ?> options) {
try {
if (currentBatchSize == MAX_BATCH_SIZE) {
batches.add(storage.batch());
batches.add(storage.batch(batchRequestInitializer));
currentBatchSize = 0;
}
Patch call = patchCall(storageObject, options);
Expand All @@ -321,7 +323,7 @@ public void addGet(
Map<Option, ?> options) {
try {
if (currentBatchSize == MAX_BATCH_SIZE) {
batches.add(storage.batch());
batches.add(storage.batch(batchRequestInitializer));
currentBatchSize = 0;
}
Get call = getCall(storageObject, options);
Expand Down
Loading
Loading