Skip to content
Open
Original file line number Diff line number Diff line change
Expand Up @@ -537,6 +537,19 @@ void recordRequestActive(Context otelContext, String operationName, long delta)
requestActive.add(delta, attributes, otelContext);
}

void recordServerDuration(
Context otelContext, double durationSeconds, String operationName, String networkPath) {
if (serverDuration == null) {
return;
}
Attributes attributes =
baseAttributes.toBuilder()
.put(KEY_GCP_STORAGE_OPERATION, operationName)
.put(KEY_NETWORK_PATH, networkPath)
.build();
serverDuration.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
Expand Up @@ -36,6 +36,8 @@
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import org.jspecify.annotations.NullMarked;
Expand All @@ -48,6 +50,9 @@
@NullMarked
final class StorageGrpcMetricsInterceptor implements ClientInterceptor {

static final Metadata.Key<byte[]> GRPC_SERVER_STATS_BIN_KEY =
Metadata.Key.of("grpc-server-stats-bin", Metadata.BINARY_BYTE_MARSHALLER);

private final StorageClientMetrics metrics;
private final ApiClock clock;

Expand Down Expand Up @@ -135,6 +140,13 @@ public void onClose(Status status, Metadata trailers) {

metrics.recordRpcCallDuration(
otelContext, durationSeconds, rpcMethod, statusCode, networkPath, errorType);
if (metrics.getServerDuration() != null) {
double serverDurationSeconds = decodeServerDurationSeconds(trailers);
if (serverDurationSeconds >= 0.0) {
metrics.recordServerDuration(
otelContext, serverDurationSeconds, operationName, networkPath);
}
}
} finally {
releaseActive();
super.onClose(status, trailers);
Expand Down Expand Up @@ -166,6 +178,17 @@ public void halfClose() {
};
}

static double decodeServerDurationSeconds(Metadata trailers) {
byte[] bytes = trailers.get(GRPC_SERVER_STATS_BIN_KEY);
// Census ServerStats binary encoding: version (0x00), field ID (0x00), 8-byte LE uint64 nanos.
// Any additional trailing fields are ignored.
if (bytes == null || bytes.length < 10 || bytes[0] != 0 || bytes[1] != 0) {
return -1.0;
}
long nanos = ByteBuffer.wrap(bytes, 2, 8).order(ByteOrder.LITTLE_ENDIAN).getLong();
return nanos >= 0 ? nanos / 1_000_000_000.0 : -1.0;
}
Comment thread
nidhiii-27 marked this conversation as resolved.
Resolved

static String defaultOperationName(@Nullable String bareMethod) {
if (bareMethod == null || bareMethod.isEmpty()) {
return "UNKNOWN";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,15 @@
package com.google.cloud.storage;

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.core.ApiClock;
import com.google.api.gax.grpc.GrpcInterceptorProvider;
import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider;
import com.google.cloud.NoCredentials;
import com.google.common.collect.ImmutableList;
import com.google.common.primitives.Bytes;
import com.google.protobuf.ByteString;
import com.google.storage.v2.BidiWriteObjectRequest;
import com.google.storage.v2.BidiWriteObjectResponse;
Expand Down Expand Up @@ -66,6 +68,8 @@
import java.lang.reflect.Field;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
Expand Down Expand Up @@ -420,17 +424,7 @@ public void interceptCall_callFails_recordsErrorType() {

@Test
public void interceptCall_requestActive_tracksInFlightAndBalancesOnClose() {
StorageClientMetrics debugMetrics =
StorageOptions.grpc()
.setProjectId("test-project")
.setCredentials(NoCredentials.getInstance())
.setEnableOtelMetrics(true)
.setEnableOtelDebugMetrics(true)
.setMeterProvider(meterProvider)
.build()
.getStorageClientMetrics();
StorageGrpcMetricsInterceptor debugInterceptor =
new StorageGrpcMetricsInterceptor(debugMetrics, clock);
StorageGrpcMetricsInterceptor debugInterceptor = createDebugInterceptor();

TestClientCall<Void, Void> okCall = new TestClientCall<>(Attributes.EMPTY);
ClientCall<Void, Void> wrappedOk =
Expand Down Expand Up @@ -468,19 +462,125 @@ public void interceptCall_requestActive_tracksInFlightAndBalancesOnClose() {
assertThat(requestActivePoint().getValue()).isEqualTo(0L);
}

@Test
public void decodeServerDurationSeconds_cases() {
java.lang.Object[][] cases = {
{"valid 125ms", encodeServerStats(0, 0, 125_000_000L), 0.125},
{
"raw LE wire bytes 250ms",
new byte[] {0, 0, (byte) 0x80, (byte) 0xB2, (byte) 0xE6, 0x0E, 0, 0, 0, 0},
0.25
},
{"valid 0ns", encodeServerStats(0, 0, 0L), 0.0},
{"absent trailer", null, -1.0},
{"too short (9 bytes)", new byte[9], -1.0},
{
"trailing fields ignored (13 bytes)",
Bytes.concat(encodeServerStats(0, 0, 125_000_000L), new byte[] {1, 0, 7}),
0.125
},
{"wrong version", encodeServerStats(1, 0, 125_000_000L), -1.0},
{"wrong field id", encodeServerStats(0, 1, 125_000_000L), -1.0},
{"negative nanos overflow", encodeServerStats(0, 0, Long.MIN_VALUE), -1.0},
};
for (java.lang.Object[] testCase : cases) {
String label = (String) testCase[0];
byte[] payload = (byte[]) testCase[1];
double expected = (double) testCase[2];
Metadata trailers = new Metadata();
if (payload != null) {
trailers.put(StorageGrpcMetricsInterceptor.GRPC_SERVER_STATS_BIN_KEY, payload);
}
assertWithMessage(label)
.that(StorageGrpcMetricsInterceptor.decodeServerDurationSeconds(trailers))
.isWithin(1e-9)
.of(expected);
}
}

@Test
public void interceptCall_serverDuration_recordsWhenDebugEnabledAndValidTrailerPresent()
throws Exception {
Attributes directPathAttrs =
Attributes.newBuilder()
.set(
Grpc.TRANSPORT_ATTR_REMOTE_ADDR,
new InetSocketAddress(InetAddress.getByName("34.126.1.2"), 443))
.build();
Metadata validTrailers = new Metadata();
validTrailers.put(
StorageGrpcMetricsInterceptor.GRPC_SERVER_STATS_BIN_KEY,
encodeServerStats(0, 0, 250_000_000L));

// Debug disabled: must not record server.duration even when trailer is present.
TestClientCall<Void, Void> standardCall = new TestClientCall<>(directPathAttrs);
interceptor
.interceptCall(READ_OBJECT_METHOD, CallOptions.DEFAULT, new TestChannel(standardCall))
.start(new TestListener<>(), new Metadata());
standardCall.close(Status.OK, validTrailers);
assertThat(findMetric(StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_SERVER_DURATION)).isNull();

// Debug enabled: records exact 7-key server.duration on valid 10-byte trailer; skips absent.
StorageGrpcMetricsInterceptor debugInterceptor = createDebugInterceptor();

TestClientCall<Void, Void> noTrailerCall = new TestClientCall<>(directPathAttrs);
debugInterceptor
.interceptCall(READ_OBJECT_METHOD, CallOptions.DEFAULT, new TestChannel(noTrailerCall))
.start(new TestListener<>(), new Metadata());
noTrailerCall.close(Status.OK, new Metadata());
assertThat(findMetric(StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_SERVER_DURATION)).isNull();

TestClientCall<Void, Void> withTrailerCall = new TestClientCall<>(directPathAttrs);
debugInterceptor
.interceptCall(READ_OBJECT_METHOD, CallOptions.DEFAULT, new TestChannel(withTrailerCall))
.start(new TestListener<>(), new Metadata());
withTrailerCall.close(Status.OK, validTrailers);
Comment thread
nidhiii-27 marked this conversation as resolved.
Resolved

// Recorded regardless of the call status, and for a 0ns server duration.
TestClientCall<Void, Void> failedCall = new TestClientCall<>(directPathAttrs);
debugInterceptor
.interceptCall(READ_OBJECT_METHOD, CallOptions.DEFAULT, new TestChannel(failedCall))
.start(new TestListener<>(), new Metadata());
failedCall.close(Status.UNAVAILABLE, validTrailers);
Metadata zeroTrailers = new Metadata();
zeroTrailers.put(
StorageGrpcMetricsInterceptor.GRPC_SERVER_STATS_BIN_KEY, encodeServerStats(0, 0, 0L));
TestClientCall<Void, Void> zeroCall = new TestClientCall<>(directPathAttrs);
debugInterceptor
.interceptCall(READ_OBJECT_METHOD, CallOptions.DEFAULT, new TestChannel(zeroCall))
.start(new TestListener<>(), new Metadata());
zeroCall.close(Status.OK, zeroTrailers);

MetricData serverDuration =
findMetric(StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_SERVER_DURATION);
assertThat(serverDuration).isNotNull();
assertThat(serverDuration.getUnit()).isEqualTo("s");
assertThat(serverDuration.getHistogramData().getPoints()).hasSize(1);
HistogramPointData point = serverDuration.getHistogramData().getPoints().iterator().next();
assertThat(point.getCount()).isEqualTo(3L);
assertThat(point.getSum()).isWithin(1e-6).of(0.5);
assertThat(point.getAttributes())
.isEqualTo(
io.opentelemetry.api.common.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)
.build());
}

@Test
public void interceptCall_requestActive_balancesWhenStartThrows() {
StorageClientMetrics debugMetrics =
StorageOptions.grpc()
.setProjectId("test-project")
.setCredentials(NoCredentials.getInstance())
.setEnableOtelMetrics(true)
.setEnableOtelDebugMetrics(true)
.setMeterProvider(meterProvider)
.build()
.getStorageClientMetrics();
StorageGrpcMetricsInterceptor debugInterceptor =
new StorageGrpcMetricsInterceptor(debugMetrics, clock);
StorageGrpcMetricsInterceptor debugInterceptor = createDebugInterceptor();
IllegalStateException failure = new IllegalStateException("start failed");
Channel throwingChannel = Mockito.mock(Channel.class);
@SuppressWarnings("unchecked")
Expand All @@ -501,17 +601,7 @@ public void interceptCall_requestActive_balancesWhenStartThrows() {

@Test
public void interceptCall_requestActive_releasesOnceWhenClosedInlineBeforeStartThrows() {
StorageClientMetrics debugMetrics =
StorageOptions.grpc()
.setProjectId("test-project")
.setCredentials(NoCredentials.getInstance())
.setEnableOtelMetrics(true)
.setEnableOtelDebugMetrics(true)
.setMeterProvider(meterProvider)
.build()
.getStorageClientMetrics();
StorageGrpcMetricsInterceptor debugInterceptor =
new StorageGrpcMetricsInterceptor(debugMetrics, clock);
StorageGrpcMetricsInterceptor debugInterceptor = createDebugInterceptor();
IllegalStateException failure = new IllegalStateException("start failed after close");
Channel throwingChannel = Mockito.mock(Channel.class);
@SuppressWarnings("unchecked")
Expand Down Expand Up @@ -807,6 +897,28 @@ public void grpcStorageOptions_disabledWithDefaultProvider_leavesInterceptorProv
assertThat(extractInterceptorProvider(disabledDefaultChannelProvider)).isNull();
}

private StorageGrpcMetricsInterceptor createDebugInterceptor() {
StorageClientMetrics debugMetrics =
StorageOptions.grpc()
.setProjectId("test-project")
.setCredentials(NoCredentials.getInstance())
.setEnableOtelMetrics(true)
.setEnableOtelDebugMetrics(true)
.setMeterProvider(meterProvider)
.build()
.getStorageClientMetrics();
return new StorageGrpcMetricsInterceptor(debugMetrics, clock);
}

private static byte[] encodeServerStats(int version, int fieldId, long nanos) {
return ByteBuffer.allocate(10)
.order(ByteOrder.LITTLE_ENDIAN)
.put((byte) version)
.put((byte) fieldId)
.putLong(nanos)
.array();
}

private LongPointData requestActivePoint() {
MetricData metric = findMetric(StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_REQUEST_ACTIVE);
assertThat(metric).isNotNull();
Expand Down
Loading