Repository navigation
feat(storage): add MetricsRecordingCredentials decorator for credential_refresh.duration #15233
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
nidhiii-27
wants to merge
11
commits into
feat/storage-http-stall-duration-metric
Choose a base branch
from
feat/storage-credential-refresh-wrapper
base: feat/storage-http-stall-duration-metric
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+1,055
−0
Open
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
a82161f
feat(storage): add MetricsRecordingCredentials decorator for credenti…
nidhiii-27 575e297
Merge branch 'feat/storage-http-stall-duration-metric' into feat/stor…
nidhiii-27 26a80d4
test(storage): avoid Mockito mocks of @NullMarked credentials on Java 8
nidhiii-27 2bbe41f
Merge branch 'feat/storage-http-stall-duration-metric' into feat/stor…
nidhiii-27 accd725
test(storage): drop duplicated credential_refresh exact-attribute uni…
nidhiii-27 a598769
Merge branch 'feat/storage-http-stall-duration-metric' into feat/stor…
nidhiii-27 49c7593
Merge branch 'feat/storage-http-stall-duration-metric' into feat/stor…
nidhiii-27 37ffbc5
Merge branch 'feat/storage-http-stall-duration-metric' into feat/stor…
nidhiii-27 3fe16da
Merge branch 'feat/storage-http-stall-duration-metric' into feat/stor…
nidhiii-27 707f1c1
Address credential_refresh.duration review feedback
nidhiii-27 367666d
test(storage): merge Java 8 GrpcStorageImplTest StreamController fix
nidhiii-27 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
329 changes: 329 additions & 0 deletions
329
...gle-cloud-storage/src/main/java/com/google/cloud/storage/MetricsRecordingCredentials.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,329 @@ | ||
| /* | ||
| * 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 com.google.auth.CredentialTypeForMetrics; | ||
| import com.google.auth.Credentials; | ||
| import com.google.auth.RequestMetadataCallback; | ||
| import com.google.auth.oauth2.AccessToken; | ||
| import com.google.auth.oauth2.GdchCredentials; | ||
| import com.google.auth.oauth2.GoogleCredentials; | ||
| import com.google.auth.oauth2.ServiceAccountCredentials; | ||
| import io.opentelemetry.context.Context; | ||
| import java.io.IOException; | ||
| import java.io.ObjectInputStream; | ||
| import java.net.URI; | ||
| import java.util.Collection; | ||
| import java.util.List; | ||
| import java.util.Map; | ||
| import java.util.Objects; | ||
| import java.util.concurrent.CancellationException; | ||
| import java.util.concurrent.Executor; | ||
| import java.util.concurrent.atomic.AtomicReference; | ||
| import org.jspecify.annotations.NullMarked; | ||
| import org.jspecify.annotations.Nullable; | ||
|
|
||
| /** | ||
| * Package-private {@link GoogleCredentials} decorator that records {@code | ||
| * gcp.storage.client.auth.credential_refresh.duration} for blocking token acquisitions and | ||
| * refreshes while preserving {@code instanceof GoogleCredentials} (for gRPC {@code | ||
| * PRIVACY_AND_INTEGRITY}) and {@code QuotaProjectIdProvider}. Cached and non-blocking {@code STALE} | ||
| * async lookups are skipped; concurrent coalesced successful refreshes are deduplicated while | ||
| * failures are recorded per waiter. | ||
| */ | ||
| @NullMarked | ||
| final class MetricsRecordingCredentials extends GoogleCredentials { | ||
|
|
||
| private static final long serialVersionUID = 1L; | ||
| private static final String APP_ENGINE_CREDENTIALS_CLASS = | ||
| "com.google.auth.appengine.AppEngineCredentials"; | ||
| private static final String LEGACY_APP_ENGINE_CREDENTIALS_CLASS = | ||
| "com.google.auth.oauth2.AppEngineCredentials"; | ||
|
|
||
| private final GoogleCredentials delegate; | ||
| private final transient @Nullable StorageClientMetrics metrics; | ||
| private final transient @Nullable ApiClock clock; | ||
| private transient AtomicReference<@Nullable AccessToken> lastObservedToken; | ||
|
|
||
| private MetricsRecordingCredentials( | ||
| GoogleCredentials delegate, StorageClientMetrics metrics, ApiClock clock) { | ||
| this.delegate = requireNonNull(delegate, "delegate cannot be null"); | ||
| this.metrics = requireNonNull(metrics, "metrics cannot be null"); | ||
| this.clock = requireNonNull(clock, "clock cannot be null"); | ||
| this.lastObservedToken = new AtomicReference<>(delegate.getAccessToken()); | ||
| } | ||
|
|
||
| static @Nullable Credentials wrap( | ||
| @Nullable Credentials credentials, @Nullable StorageClientMetrics metrics, ApiClock clock) { | ||
| if (!(credentials instanceof GoogleCredentials) | ||
| || credentials instanceof GdchCredentials | ||
| || (credentials instanceof ServiceAccountCredentials | ||
| && ((ServiceAccountCredentials) credentials).createScopedRequired()) | ||
| || credentials instanceof MetricsRecordingCredentials | ||
| || metrics == null | ||
| || metrics.getCredentialRefreshDuration() == null) { | ||
| return credentials; | ||
| } | ||
| String className = credentials.getClass().getName(); | ||
| if (APP_ENGINE_CREDENTIALS_CLASS.equals(className) | ||
| || LEGACY_APP_ENGINE_CREDENTIALS_CLASS.equals(className)) { | ||
| return credentials; | ||
| } | ||
| return new MetricsRecordingCredentials((GoogleCredentials) credentials, metrics, clock); | ||
| } | ||
|
|
||
| @Override | ||
| public boolean equals(@Nullable Object obj) { | ||
| if (this == obj) { | ||
| return true; | ||
| } | ||
| if (!(obj instanceof MetricsRecordingCredentials)) { | ||
| return false; | ||
| } | ||
| MetricsRecordingCredentials other = (MetricsRecordingCredentials) obj; | ||
| return Objects.equals(delegate, other.delegate); | ||
| } | ||
|
|
||
| @Override | ||
| public int hashCode() { | ||
| return Objects.hashCode(delegate); | ||
| } | ||
|
|
||
| @Override | ||
| public String getAuthenticationType() { | ||
| return delegate.getAuthenticationType(); | ||
| } | ||
|
nidhiii-27 marked this conversation as resolved.
Resolved
|
||
|
|
||
| @Override | ||
| public String getUniverseDomain() throws IOException { | ||
| return delegate.getUniverseDomain(); | ||
| } | ||
|
|
||
| @Override | ||
| public CredentialTypeForMetrics getMetricsCredentialType() { | ||
| return delegate.getMetricsCredentialType(); | ||
| } | ||
|
|
||
| @Override | ||
| public boolean hasRequestMetadata() { | ||
| return delegate.hasRequestMetadata(); | ||
| } | ||
|
|
||
| @Override | ||
| public boolean hasRequestMetadataOnly() { | ||
| return delegate.hasRequestMetadataOnly(); | ||
| } | ||
|
|
||
| @Override | ||
| public @Nullable String getQuotaProjectId() { | ||
| return delegate.getQuotaProjectId(); | ||
| } | ||
|
|
||
| @Override | ||
| public @Nullable String getProjectId() { | ||
| return delegate.getProjectId(); | ||
| } | ||
|
|
||
| @Override | ||
| public boolean createScopedRequired() { | ||
| return delegate.createScopedRequired(); | ||
| } | ||
|
|
||
| @Override | ||
| public GoogleCredentials createScoped(Collection<String> scopes) { | ||
| return rewrap(delegate.createScoped(scopes)); | ||
| } | ||
|
|
||
| @Override | ||
| public GoogleCredentials createScoped( | ||
| Collection<String> scopes, Collection<String> defaultScopes) { | ||
| return rewrap(delegate.createScoped(scopes, defaultScopes)); | ||
| } | ||
|
nidhiii-27 marked this conversation as resolved.
Resolved
|
||
|
|
||
| @Override | ||
| public GoogleCredentials createWithQuotaProject(String quotaProject) { | ||
| return rewrap(delegate.createWithQuotaProject(quotaProject)); | ||
| } | ||
|
|
||
| @Override | ||
| public GoogleCredentials createDelegated(String user) { | ||
| return rewrap(delegate.createDelegated(user)); | ||
| } | ||
|
|
||
| @Override | ||
| public GoogleCredentials createWithCustomRetryStrategy(boolean defaultRetriesEnabled) { | ||
| return rewrap(delegate.createWithCustomRetryStrategy(defaultRetriesEnabled)); | ||
| } | ||
|
|
||
| @Override | ||
| public Map<String, String> getCredentialInfo() { | ||
| return delegate.getCredentialInfo(); | ||
| } | ||
|
|
||
| @Override | ||
| public Map<String, List<String>> getRequestMetadata(@Nullable URI uri) throws IOException { | ||
|
nidhiii-27 marked this conversation as resolved.
Resolved
|
||
| return runRecorded(() -> delegate.getRequestMetadata(uri)); | ||
| } | ||
|
|
||
| @Override | ||
| public void getRequestMetadata( | ||
| @Nullable URI uri, Executor executor, RequestMetadataCallback callback) { | ||
| StorageClientMetrics m = this.metrics; | ||
| ApiClock c = this.clock; | ||
| if (m == null || c == null) { | ||
| delegate.getRequestMetadata(uri, executor, callback); | ||
| return; | ||
| } | ||
| Context otelContext = Context.current(); | ||
| AccessToken before = delegate.getAccessToken(); | ||
| long startNanos = c.nanoTime(); | ||
| try { | ||
| delegate.getRequestMetadata( | ||
| uri, | ||
| executor, | ||
| new RequestMetadataCallback() { | ||
| @Override | ||
| public void onSuccess(Map<String, List<String>> metadata) { | ||
| maybeRecordTokenChange(m, c, otelContext, startNanos, before); | ||
| callback.onSuccess(metadata); | ||
| } | ||
|
|
||
| @Override | ||
| public void onFailure(Throwable exception) { | ||
| if (shouldRecordFailure(exception)) { | ||
| record( | ||
| m, | ||
| c, | ||
| otelContext, | ||
| startNanos, | ||
| StorageErrorTypeMapper.mapAuthErrorType(exception)); | ||
| } | ||
| callback.onFailure(exception); | ||
| } | ||
| }); | ||
| } catch (RuntimeException e) { | ||
| if (shouldRecordFailure(e)) { | ||
| record(m, c, otelContext, startNanos, StorageErrorTypeMapper.mapAuthErrorType(e)); | ||
| } | ||
| throw e; | ||
| } | ||
| } | ||
|
|
||
| @Override | ||
| public void refresh() throws IOException { | ||
| runRecorded(delegate::refresh); | ||
| } | ||
|
|
||
| @Override | ||
| public void refreshIfExpired() throws IOException { | ||
| runRecorded(delegate::refreshIfExpired); | ||
| } | ||
|
|
||
| private void runRecorded(IoAction action) throws IOException { | ||
| runRecorded( | ||
| () -> { | ||
| action.run(); | ||
| return null; | ||
| }); | ||
| } | ||
|
|
||
| private <T extends @Nullable Object> T runRecorded(IoSupplier<T> supplier) throws IOException { | ||
| StorageClientMetrics m = this.metrics; | ||
| ApiClock c = this.clock; | ||
| if (m == null || c == null) { | ||
| return supplier.get(); | ||
| } | ||
| Context otelContext = Context.current(); | ||
| AccessToken before = delegate.getAccessToken(); | ||
| long startNanos = c.nanoTime(); | ||
| try { | ||
| T result = supplier.get(); | ||
| maybeRecordTokenChange(m, c, otelContext, startNanos, before); | ||
| return result; | ||
| } catch (IOException | RuntimeException e) { | ||
| if (shouldRecordFailure(e)) { | ||
| record(m, c, otelContext, startNanos, StorageErrorTypeMapper.mapAuthErrorType(e)); | ||
| } | ||
| throw e; | ||
| } | ||
| } | ||
|
|
||
| // Static non-refreshable credentials (e.g., GoogleCredentials.create(null)) throw | ||
| // IllegalStateException on probes and must not emit spurious AUTHENTICATION_ERROR metrics. | ||
| // CancellationException extends IllegalStateException and must still be recorded. | ||
| private static boolean shouldRecordFailure(Throwable t) { | ||
| return !(t instanceof IllegalStateException) || t instanceof CancellationException; | ||
| } | ||
|
|
||
| @FunctionalInterface | ||
| private interface IoSupplier<T extends @Nullable Object> { | ||
| T get() throws IOException; | ||
| } | ||
|
|
||
| @FunctionalInterface | ||
| private interface IoAction { | ||
| void run() throws IOException; | ||
| } | ||
|
|
||
| private GoogleCredentials rewrap(GoogleCredentials scoped) { | ||
| if (scoped == delegate) { | ||
| return this; | ||
| } | ||
| StorageClientMetrics m = this.metrics; | ||
| ApiClock c = this.clock; | ||
| if (m == null || c == null) { | ||
| return scoped; | ||
| } | ||
| return (GoogleCredentials) requireNonNull(wrap(scoped, m, c)); | ||
| } | ||
|
|
||
| private void maybeRecordTokenChange( | ||
| StorageClientMetrics m, | ||
| ApiClock c, | ||
| Context otelContext, | ||
| long startNanos, | ||
| @Nullable AccessToken before) { | ||
| AccessToken after = delegate.getAccessToken(); | ||
| if (after == null || Objects.equals(before, after)) { | ||
| return; | ||
| } | ||
| while (true) { | ||
| AccessToken prev = lastObservedToken.get(); | ||
| if (Objects.equals(prev, after) || !Objects.equals(delegate.getAccessToken(), after)) { | ||
| return; | ||
| } | ||
| if (lastObservedToken.compareAndSet(prev, after)) { | ||
| record(m, c, otelContext, startNanos, StorageErrorTypeMapper.STATUS_OK); | ||
| return; | ||
| } | ||
| } | ||
| } | ||
|
nidhiii-27 marked this conversation as resolved.
Resolved
|
||
|
|
||
| private static void record( | ||
| StorageClientMetrics m, ApiClock c, Context otelContext, long startNanos, String errorType) { | ||
| double durationSeconds = (c.nanoTime() - startNanos) / 1_000_000_000.0; | ||
| m.recordCredentialRefreshDuration(otelContext, durationSeconds, errorType); | ||
| } | ||
|
|
||
| private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { | ||
| in.defaultReadObject(); | ||
| this.lastObservedToken = new AtomicReference<>(delegate.getAccessToken()); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.