Skip to content
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 @@ -71,12 +71,33 @@ public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
private final AtomicBoolean ttfbRecorded = new AtomicBoolean(false);
private final AtomicBoolean ttfbReanchored = 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 @@ -115,6 +136,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 @@ -36,6 +36,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 @@ -141,6 +142,8 @@ public void initialize(HttpRequest request) throws IOException {
AtomicLong startTimeNanos = new AtomicLong();
AtomicLong bodyWriteEndNanos = 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 @@ -162,44 +165,65 @@ && isMediaUploadRequest(req)) {
req.setContent(new BodyWriteTrackingContent(content, bodyWriteEndNanos, clock));
}
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()), ctx);
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 handled = false;
boolean completedNormally = false;
boolean ownResponse = response.getRequest() == req;
try {
handled = existingUnsuccessfulHandler.handleResponse(req, response, supportsRetry);
completedNormally = true;
} finally {
if ((handled || !completedNormally)
&& ownResponse
&& recorded.compareAndSet(false, true)) {
metrics.recordRequestActive(
activeOtelContext.get(), activeOperationName.get(), -1L);
recordResponse(
req,
startTimeNanos.get(),
bodyWriteEndNanos.get(),
endNanos,
response.getStatusCode());
}
}
if (handled && supportsRetry && ownResponse && response.getStatusCode() >= 400) {
pendingRetryStatusCode.set(response.getStatusCode());
}
if (handled && ownResponse && recorded.compareAndSet(false, true)) {
recordResponse(
req,
startTimeNanos.get(),
bodyWriteEndNanos.get(),
endNanos,
response.getStatusCode());
}
return handled;
});
}

request.setResponseInterceptor(
response -> {
long endNanos = clock.nanoTime();
if (existingResp != null) {
existingResp.interceptResponse(response);
}
if (recorded.compareAndSet(false, true)) {
recordResponse(
request,
startTimeNanos.get(),
bodyWriteEndNanos.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(),
bodyWriteEndNanos.get(),
endNanos,
response.getStatusCode());
}
}
});

Expand All @@ -209,6 +233,7 @@ && isMediaUploadRequest(req)) {
request.setIOExceptionHandler(
(req, supportsRetry) -> {
if (recorded.compareAndSet(false, true)) {
metrics.recordRequestActive(activeOtelContext.get(), activeOperationName.get(), -1L);
double durationSeconds =
Math.max(0L, clock.nanoTime() - startTimeNanos.get()) / 1_000_000_000.0;
metrics.recordHttpRequestDuration(
Expand Down Expand Up @@ -341,6 +366,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 @@ -133,6 +133,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 @@ -160,6 +161,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;
if (options instanceof HttpStorageOptions) {
HttpStorageOptions httpOptions = (HttpStorageOptions) options;
initializer = httpOptions.decorateWithMetrics(initializer);
Expand Down Expand Up @@ -192,6 +194,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 =
Comment thread
nidhiii-27 marked this conversation as resolved.
Resolved
initializer == batchPartInitializer
? storage
: storageBuilder.setHttpRequestInitializer(batchPartInitializer).build();
}

public Storage getStorage() {
Expand Down Expand Up @@ -294,7 +304,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 @@ -313,7 +323,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 @@ -332,7 +342,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 @@ -613,9 +623,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 @@ -634,7 +644,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 @@ -732,10 +742,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 @@ -755,7 +765,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 @@ -793,10 +803,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 @@ -814,7 +824,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 @@ -912,7 +922,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