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 @@ -528,6 +528,15 @@ void recordRetry(
retries.add(1L, attributes, otelContext);
}

void recordRequestActive(Context otelContext, String operationName, long delta) {
if (requestActive == null) {
return;
}
Attributes attributes =
baseAttributes.toBuilder().put(KEY_GCP_STORAGE_OPERATION, operationName).build();
requestActive.add(delta, 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 @@ -70,12 +70,33 @@ public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
return new SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {
private final AtomicBoolean ttfbRecorded = new AtomicBoolean(false);
private final AtomicLong ttfbStartNanos = new AtomicLong();
private final AtomicBoolean activeReleased = new AtomicBoolean(false);

@Override
public void start(Listener<RespT> responseListener, Metadata headers) {
long startTimeNanos = clock.nanoTime();
ttfbStartNanos.set(startTimeNanos);
metrics.recordRequestActive(otelContext, operationName, 1L);
Comment thread
nidhiii-27 marked this conversation as resolved.
Resolved

try {
startWithMetrics(responseListener, headers, startTimeNanos);
} catch (RuntimeException | Error e) {
// Per the ClientCall contract, onClose is not delivered when start throws, so balance
// the +1 here. A misbehaving downstream call may still have closed the listener inline
// before throwing, so releaseActive() ensures the -1 is recorded only once.
releaseActive();
throw e;
}
}

private void releaseActive() {
if (activeReleased.compareAndSet(false, true)) {
metrics.recordRequestActive(otelContext, operationName, -1L);
}
}

private void startWithMetrics(
Listener<RespT> responseListener, Metadata headers, long startTimeNanos) {
super.start(
new SimpleForwardingClientCallListener<RespT>(responseListener) {
@Override
Expand Down Expand Up @@ -112,6 +133,7 @@ public void onClose(Status status, Metadata trailers) {
metrics.recordRpcCallDuration(
otelContext, durationSeconds, rpcMethod, statusCode, networkPath, errorType);
} finally {
releaseActive();
super.onClose(status, trailers);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;

Expand Down Expand Up @@ -137,6 +138,8 @@ public void initialize(HttpRequest request) throws IOException {

AtomicLong startTimeNanos = new AtomicLong();
AtomicBoolean recorded = new AtomicBoolean(true);
AtomicReference<Context> activeOtelContext = new AtomicReference<>(Context.root());
AtomicReference<String> activeOperationName = new AtomicReference<>("");
// 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);
Expand All @@ -151,21 +154,40 @@ public void initialize(HttpRequest request) throws IOException {
existingExec.intercept(req);
}
startTimeNanos.set(clock.nanoTime());
recorded.set(false);
boolean started = recorded.compareAndSet(true, false);
if (started && metrics.getRequestActive() != null) {
StorageMetricsContext ctx = StorageMetricsContext.current();
Context otelContext = ctx != null ? ctx.getOtelContext() : Context.current();
String operationName = resolveOperationName(req, extractUrlTemplate(req.getUrl()));
activeOtelContext.set(otelContext);
activeOperationName.set(operationName);
metrics.recordRequestActive(otelContext, operationName, 1L);
}
});

if (existingUnsuccessfulHandler != null) {
request.setUnsuccessfulResponseHandler(
(req, response, supportsRetry) -> {
long endNanos = clock.nanoTime();
boolean handled =
existingUnsuccessfulHandler.handleResponse(req, response, supportsRetry);
boolean ownResponse = response.getRequest() == req;
if (handled && supportsRetry && ownResponse && response.getStatusCode() >= 400) {
pendingRetryStatusCode.set(response.getStatusCode());
boolean handled = false;
boolean completedNormally = false;
try {
handled = existingUnsuccessfulHandler.handleResponse(req, response, supportsRetry);
completedNormally = true;
} finally {
if ((handled || !completedNormally)
&& response.getRequest() == req
&& recorded.compareAndSet(false, true)) {
metrics.recordRequestActive(
activeOtelContext.get(), activeOperationName.get(), -1L);
recordResponse(req, startTimeNanos.get(), endNanos, response.getStatusCode());
}
}
if (handled && ownResponse && recorded.compareAndSet(false, true)) {
recordResponse(req, startTimeNanos.get(), endNanos, response.getStatusCode());
if (handled
&& supportsRetry
&& response.getRequest() == req
&& response.getStatusCode() >= 400) {
pendingRetryStatusCode.set(response.getStatusCode());
}
return handled;
});
Expand All @@ -174,11 +196,15 @@ public void initialize(HttpRequest request) throws IOException {
request.setResponseInterceptor(
response -> {
long endNanos = clock.nanoTime();
if (existingResp != null) {
existingResp.interceptResponse(response);
}
if (recorded.compareAndSet(false, true)) {
recordResponse(request, startTimeNanos.get(), endNanos, response.getStatusCode());
try {
if (existingResp != null) {
existingResp.interceptResponse(response);
}
} finally {
if (response.getRequest() == request && recorded.compareAndSet(false, true)) {
metrics.recordRequestActive(activeOtelContext.get(), activeOperationName.get(), -1L);
recordResponse(request, startTimeNanos.get(), endNanos, response.getStatusCode());
}
}
});

Expand All @@ -188,6 +214,7 @@ public void initialize(HttpRequest request) throws IOException {
request.setIOExceptionHandler(
(req, supportsRetry) -> {
if (recorded.compareAndSet(false, true)) {
metrics.recordRequestActive(activeOtelContext.get(), activeOperationName.get(), -1L);
double durationSeconds = (clock.nanoTime() - startTimeNanos.get()) / 1_000_000_000.0;
recordDuration(
req,
Expand Down Expand Up @@ -287,6 +314,9 @@ static String extractUrlTemplate(GenericUrl url) {
if (path == null || path.isEmpty()) {
return "/";
}
while (path.length() > 1 && path.startsWith("//")) {
path = path.substring(1);
}
String host = url.getHost();
if (host != null
&& host.endsWith(".storage.googleapis.com")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ public class HttpStorageRpc implements StorageRpc {

private final StorageOptions options;
private final Storage storage;
private final Storage batchPartStorage;
private final Tracer tracer = Tracing.getTracer();
private final HttpRequestInitializer batchRequestInitializer;

Expand Down Expand Up @@ -159,6 +160,7 @@ public HttpStorageRpc(StorageOptions options, JsonFactory jsonFactory) {
CensusHttpModule censusHttpModule = new CensusHttpModule(tracer, IS_RECORD_EVENTS);
initializer = censusHttpModule.getHttpRequestInitializer(initializer);
initializer = new InvocationIdInitializer(initializer, applicationName, tm);
HttpRequestInitializer batchPartInitializer = initializer;
initializer = options.decorateWithMetrics(initializer);
batchRequestInitializer =
options.decorateWithMetrics(censusHttpModule.getHttpRequestInitializer(null));
Expand Down Expand Up @@ -186,6 +188,14 @@ public HttpStorageRpc(StorageOptions options, JsonFactory jsonFactory) {
storageBuilder.setRootUrl(host);
}
storage = storageBuilder.build();
// Batch parts skip decorateWithMetrics: they are serialized into the outer multipart request
// and never execute as their own HTTP exchange, so a metrics interceptor on them would
// increment gcp.storage.client.request.active without a matching response. The outer batch
// request (batchRequestInitializer) is instrumented instead.
batchPartStorage =

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 short comment on why batchPartStorage intentionally skips decorateWithMetrics?

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 88ec8a8: added a comment. Batch parts are serialized into the outer multipart request and never run as their own HTTP exchange, so instrumenting them would increment request.active with no matching response; the outer batch request is instrumented instead.

Co-authored by AI Agent

initializer == batchPartInitializer
? storage
: storageBuilder.setHttpRequestInitializer(batchPartInitializer).build();
}

public Storage getStorage() {
Expand Down Expand Up @@ -288,7 +298,7 @@ public void addDelete(
batches.add(storage.batch(batchRequestInitializer));
currentBatchSize = 0;
}
Delete call = deleteCall(storageObject, options);
Delete call = deleteCall(this.storage, storageObject, options);
addIdempotencyTokenToCall(call);
call.queue(batches.getLast(), toJsonCallback(callback));
currentBatchSize++;
Expand All @@ -307,7 +317,7 @@ public void addPatch(
batches.add(storage.batch(batchRequestInitializer));
currentBatchSize = 0;
}
Patch call = patchCall(storageObject, options);
Patch call = patchCall(this.storage, storageObject, options);
addIdempotencyTokenToCall(call);
call.queue(batches.getLast(), toJsonCallback(callback));
currentBatchSize++;
Expand All @@ -326,7 +336,7 @@ public void addGet(
batches.add(storage.batch(batchRequestInitializer));
currentBatchSize = 0;
}
Get call = getCall(storageObject, options);
Get call = getCall(this.storage, storageObject, options);
addIdempotencyTokenToCall(call);
call.queue(batches.getLast(), toJsonCallback(callback));
currentBatchSize++;
Expand Down Expand Up @@ -607,9 +617,9 @@ public Bucket get(Bucket bucket, Map<Option, ?> options) {
}
}

private Storage.Objects.Get getCall(StorageObject object, Map<Option, ?> options)
private Storage.Objects.Get getCall(Storage client, StorageObject object, Map<Option, ?> options)
throws IOException {
Storage.Objects.Get get = storage.objects().get(object.getBucket(), object.getName());
Storage.Objects.Get get = client.objects().get(object.getBucket(), object.getName());
setEncryptionHeaders(get.getRequestHeaders(), ENCRYPTION_KEY_PREFIX, options);
setExtraHeaders(get, options);
return get.setGeneration(object.getGeneration())
Expand All @@ -628,7 +638,7 @@ public StorageObject get(StorageObject object, Map<Option, ?> options) {
Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_GET_OBJECT);
Scope scope = tracer.withSpan(span);
try {
return getCall(object, options).execute();
return getCall(storage, object, options).execute();
} catch (IOException ex) {
span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage()));
StorageException serviceException = translate(ex);
Expand Down Expand Up @@ -726,10 +736,10 @@ public Bucket patch(Bucket bucket, Map<Option, ?> options) {
}
}

private Storage.Objects.Patch patchCall(StorageObject storageObject, Map<Option, ?> options)
throws IOException {
private Storage.Objects.Patch patchCall(
Storage client, StorageObject storageObject, Map<Option, ?> options) throws IOException {
Storage.Objects.Patch patch =
storage
client
.objects()
.patch(storageObject.getBucket(), storageObject.getName(), storageObject)
.setProjection(DEFAULT_PROJECTION)
Expand All @@ -749,7 +759,7 @@ public StorageObject patch(StorageObject storageObject, Map<Option, ?> options)
Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_PATCH_OBJECT);
Scope scope = tracer.withSpan(span);
try {
return patchCall(storageObject, options).execute();
return patchCall(storage, storageObject, options).execute();
} catch (IOException ex) {
span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage()));
throw translate(ex);
Expand Down Expand Up @@ -787,10 +797,10 @@ public boolean delete(Bucket bucket, Map<Option, ?> options) {
}
}

private Storage.Objects.Delete deleteCall(StorageObject blob, Map<Option, ?> options)
throws IOException {
private Storage.Objects.Delete deleteCall(
Storage client, StorageObject blob, Map<Option, ?> options) throws IOException {
Storage.Objects.Delete delete =
storage
client
.objects()
.delete(blob.getBucket(), blob.getName())
.setGeneration(blob.getGeneration())
Expand All @@ -808,7 +818,7 @@ public boolean delete(StorageObject blob, Map<Option, ?> options) {
Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_DELETE_OBJECT);
Scope scope = tracer.withSpan(span);
try {
deleteCall(blob, options).execute();
deleteCall(storage, blob, options).execute();
return true;
} catch (IOException ex) {
span.setStatus(Status.UNKNOWN.withDescription(ex.getMessage()));
Expand Down Expand Up @@ -906,7 +916,7 @@ public RpcBatch createBatch() {
Span span = startSpan(HttpStorageRpcSpans.SPAN_NAME_CREATE_BATCH);
Scope scope = tracer.withSpan(span);
try {
return new DefaultRpcBatch(storage);
return new DefaultRpcBatch(batchPartStorage);
} finally {
scope.close();
span.end(HttpStorageRpcSpans.END_SPAN_OPTIONS);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,7 @@ public void inMemoryMetricReader_verifiesViewsAndBoundaries() {
StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_REQUEST_ACTIVE.replace(".", "/");
assertThat(metricsMap).containsKey(requestActiveName);
assertThat(metricsMap.get(requestActiveName).getUnit()).isEqualTo("{request}");
assertThat(metricsMap.get(requestActiveName).getLongSumData().isMonotonic()).isFalse();

String serverUnreachedName =
StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_SERVER_UNREACHED.replace(".", "/");
Expand Down
Loading
Loading