Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
e50ed9d
feat: add rpc.client.call.duration metric for gRPC calls
nidhiii-27 Oct 22, 2026
154841b
fix(storage): address PR #14743 review feedback in StorageGrpcMetrics…
nidhiii-27 Nov 3, 2026
7527ba2
fix(storage): merge base branch and use OpenTelemetryBootstrappingUti…
nidhiii-27 Nov 3, 2026
01d37cf
docs(storage): refine StorageGrpcMetricsInterceptor Javadoc description
nidhiii-27 Nov 5, 2026
792fc8a
refactor(storage): use DirectPath IP string prefixes in isDirectPathIp
nidhiii-27 Nov 5, 2026
98f8bcc
refactor(storage): move recordRpcCallDuration to StorageMetricsContext
nidhiii-27 Nov 5, 2026
bda1d6e
Merge commit 'fd0a88f67b57e2bd69185d16a250f8bf57208dd5' into feat/sto…
nidhiii-27 Nov 7, 2026
e5cc1b8
fix(storage): resolve PR #14743 review comments in StorageGrpcMetrics…
nidhiii-27 Nov 7, 2026
6a75474
test(storage): align RetryingMetricsTest with DEADLINE_EXCEEDED error…
nidhiii-27 Nov 7, 2026
90af99d
chore(storage): merge feat/storage-grpc-veneer-operation-metrics into…
nidhiii-27 Nov 12, 2026
f321b31
Merge branch 'feat/storage-grpc-veneer-operation-metrics' into feat/s…
nidhiii-27 Nov 12, 2026
4420530
fix(storage): address PR review feedback on gRPC metrics interceptor
nidhiii-27 Nov 12, 2026
63952f4
Merge branch 'feat/storage-grpc-veneer-operation-metrics' into feat/s…
nidhiii-27 Nov 12, 2026
4bf512c
Merge remote-tracking branch 'origin/feat/storage-grpc-veneer-operati…
nidhiii-27 Nov 16, 2026
f515297
fix(storage): address follow-up review comments on PR #14743
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
Expand Up @@ -334,7 +334,27 @@ private Tuple<StorageSettings, Opts<UserProject>> resolveSettingsAndOpts() throw
Collections.singletonList(InstantiatingGrpcChannelProvider.HardBoundTokenTypes.ALTS));
}

if (!NoopGrpcInterceptorProvider.INSTANCE.equals(grpcInterceptorProvider)) {
StorageClientMetrics clientMetrics = getStorageClientMetrics();
if (clientMetrics != null) {
StorageGrpcMetricsInterceptor metricsInterceptor =
new StorageGrpcMetricsInterceptor(clientMetrics, getClock());
GrpcInterceptorProvider combinedProvider =
grpcInterceptorProvider == null
|| NoopGrpcInterceptorProvider.INSTANCE.equals(grpcInterceptorProvider)
? () -> ImmutableList.of(metricsInterceptor)
: () -> {
List<ClientInterceptor> existing = grpcInterceptorProvider.getInterceptors();
if (existing == null || existing.isEmpty()) {
return ImmutableList.of(metricsInterceptor);
}
return ImmutableList.<ClientInterceptor>builder()
.addAll(existing)
.add(metricsInterceptor)
.build();
};
channelProviderBuilder.setInterceptorProvider(combinedProvider);
} else if (grpcInterceptorProvider != null
&& !NoopGrpcInterceptorProvider.INSTANCE.equals(grpcInterceptorProvider)) {
channelProviderBuilder.setInterceptorProvider(grpcInterceptorProvider);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import io.opentelemetry.api.metrics.LongUpDownCounter;
import io.opentelemetry.api.metrics.Meter;
import io.opentelemetry.api.metrics.MeterProvider;
import io.opentelemetry.context.Context;
import io.opentelemetry.sdk.metrics.SdkMeterProvider;
import java.util.logging.Logger;
import org.checkerframework.checker.nullness.qual.Nullable;
Expand Down Expand Up @@ -171,10 +172,12 @@ static StorageClientMetrics create(
.put(KEY_GCP_CLIENT_VERSION, StorageOptions.version())
.put(KEY_GCP_CLIENT_ARTIFACT, ARTIFACT_STORAGE)
.build();
Attributes baseAttributes =
clientAttributes.toBuilder().put(KEY_SERVER_ADDRESS, "storage.googleapis.com").build();
return new StorageClientMetrics(
meter,
clientAttributes,
clientAttributes,
baseAttributes,
ownedMeterProvider,
enableOtelMetrics,
enableOtelDebugMetrics);
Expand Down Expand Up @@ -448,6 +451,27 @@ StorageMetricsContext createMultiStepContext(String operationName) {
return StorageMetricsContext.createForMultiStep(this, operationName, baseAttributes);
}

void recordRpcCallDuration(
Context otelContext,
double durationSeconds,
String rpcMethod,
String statusCode,
String networkPath,
String errorType) {
if (rpcClientCallDuration == null) {
return;
}
Attributes attributes =
baseAttributes.toBuilder()
.put(KEY_RPC_SYSTEM_NAME, "grpc")
.put(KEY_RPC_METHOD, rpcMethod)
.put(KEY_RPC_RESPONSE_STATUS_CODE, statusCode)
.put(KEY_NETWORK_PATH, networkPath)
.put(KEY_ERROR_TYPE, errorType)
.build();
rpcClientCallDuration.record(durationSeconds, attributes, otelContext);
}

@Nullable
static StorageMetricsContext createContext(
@Nullable StorageClientMetrics metrics, String operationName) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
/*
* 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 static java.util.Objects.requireNonNull;

import com.google.api.core.ApiClock;
import io.grpc.Attributes;
import io.grpc.CallOptions;
import io.grpc.Channel;
import io.grpc.ClientCall;
import io.grpc.ClientInterceptor;
import io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
import io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
import io.grpc.Grpc;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor;
import io.grpc.Status;
import io.opentelemetry.context.Context;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.concurrent.atomic.AtomicBoolean;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;

/**
* {@link ClientInterceptor} that instruments outgoing gRPC calls to record OpenTelemetry client
* metrics.
*/
@NullMarked
final class StorageGrpcMetricsInterceptor implements ClientInterceptor {

private final StorageClientMetrics metrics;
private final ApiClock clock;

StorageGrpcMetricsInterceptor(StorageClientMetrics metrics, ApiClock clock) {
this.metrics = requireNonNull(metrics, "metrics cannot be null");
this.clock = requireNonNull(clock, "clock cannot be null");
}

@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
if (metrics.getRpcClientCallDuration() == null) {
return next.newCall(method, callOptions);
}

String rpcMethod = method.getFullMethodName();
StorageMetricsContext metricsCtx = StorageMetricsContext.from(callOptions);
Comment thread
nidhiii-27 marked this conversation as resolved.
Resolved
Context otelContext = metricsCtx != null ? metricsCtx.getOtelContext() : Context.current();

return new SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {
@Override
public void start(Listener<RespT> responseListener, Metadata headers) {
long startTimeNanos = clock.nanoTime();
AtomicBoolean callRecorded = new AtomicBoolean(false);

super.start(
new SimpleForwardingClientCallListener<RespT>(responseListener) {
@Override
public void onHeaders(Metadata headers) {
if (metricsCtx != null) {
metricsCtx.setNetworkPath(detectNetworkPath(getAttributes()));
}
super.onHeaders(headers);
}

@Override
public void onClose(Status status, Metadata trailers) {
try {
if (callRecorded.compareAndSet(false, true)) {
double durationSeconds =
Math.max(0.0, (clock.nanoTime() - startTimeNanos) / 1_000_000_000.0);
String networkPath = detectNetworkPath(getAttributes());
Comment thread
nidhiii-27 marked this conversation as resolved.
Resolved

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.

For ReadObject the retrier returns as soon as the first response arrives (GapicUnbufferedReadableByteChannel completes open in onResponseImpl), so the attempt is recorded before this onClose write and the first read attempt still falls back to cloudpath. Can we also set the path from onHeaders (peer attrs are available by then) so streaming attempts pick up the real one?

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 (metricsCtx != null) {
metricsCtx.setNetworkPath(networkPath);
}
String statusCode = status.getCode().name();
String errorType = StorageErrorTypeMapper.mapGrpcStatus(status);

metrics.recordRpcCallDuration(
otelContext,
durationSeconds,
rpcMethod,
statusCode,
networkPath,
errorType);
}
} finally {
super.onClose(status, trailers);
}
}
},
headers);
}
};
}

static String detectNetworkPath(@Nullable Attributes callAttributes) {
SocketAddress remoteAddr =
callAttributes != null ? callAttributes.get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR) : null;
if (remoteAddr instanceof InetSocketAddress) {
InetAddress inetAddr = ((InetSocketAddress) remoteAddr).getAddress();
if (inetAddr != null) {
return isDirectPathIp(inetAddr)
? StorageClientMetrics.NETWORK_PATH_DIRECTPATH
: StorageClientMetrics.NETWORK_PATH_CLOUDPATH;
}
}
return StorageClientMetrics.NETWORK_PATH_UNKNOWN;
}

static boolean isDirectPathIp(InetAddress addr) {
Comment thread
nidhiii-27 marked this conversation as resolved.
Resolved
byte[] b = addr.getAddress();
if (b.length == 4) {
// 34.126.0.0/18
return b[0] == 34 && b[1] == 126 && (b[2] & 0xC0) == 0;
}
if (b.length == 16) {
// 2001:4860:8040::/42
return b[0] == 0x20
&& b[1] == 0x01
&& b[2] == 0x48
&& b[3] == 0x60
&& b[4] == (byte) 0x80
&& (b[5] & 0xC0) == 0x40;
}
return false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ final class StorageMetricsContext {
private final AtomicInteger attemptCount = new AtomicInteger(0);
private final AtomicLong requestBytes = new AtomicLong(0L);
private final AtomicLong responseBytes = new AtomicLong(0L);
@Nullable private volatile String networkPath;

private StorageMetricsContext(
@Nullable StorageClientMetrics metrics,
Expand Down Expand Up @@ -268,6 +269,10 @@ void recordAttemptFailure(@Nullable StorageClientMetrics metrics, Throwable e) {
}
}

void setNetworkPath(String networkPath) {
this.networkPath = networkPath;
}

/**
* 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 Expand Up @@ -324,6 +329,10 @@ private Attributes buildAttemptBaseAttributes(StorageClientMetrics metrics) {
}

private String resolveNetworkPath() {
String detected = this.networkPath;
if (detected != null && !detected.isEmpty()) {
return detected;
}
String path = baseAttributes.get(StorageClientMetrics.KEY_NETWORK_PATH);
if (path != null && !path.isEmpty()) {
return path;
Expand Down
Loading
Loading