Skip to content

feat(storage): add MetricsRecordingCredentials decorator for credential_refresh.duration - #15233

Open
nidhiii-27 wants to merge 8 commits into
feat/storage-http-stall-duration-metricfrom
feat/storage-credential-refresh-wrapper
Open

nidhiii-27 wants to merge 8 commits into
feat/storage-http-stall-duration-metricfrom
feat/storage-credential-refresh-wrapper

Conversation

@nidhiii-27

Copy link
Copy Markdown
Contributor

Summary

Stacked on #15232.

Adds Debug-tier gcp.storage.client.auth.credential_refresh.duration (DoubleHistogram, unit s) and the package-private MetricsRecordingCredentials decorator to measure access token acquisition/refresh latency while omitting cached token hits.

Changes

  • StorageClientMetrics: add recordCredentialRefreshDuration(Context, double durationSeconds, String errorType) emitting exact 4-key attributes (gcp.client.service, gcp.client.version, gcp.client.artifact, error.type, omitting server.address and rpc.system.name).
  • MetricsRecordingCredentials: package-private decorator extending GoogleCredentials (preserving gRPC PRIVACY_AND_INTEGRITY and QuotaProjectIdProvider semantics):
    • Skips incompatible or non-refreshable credential types (NoCredentials, non-GoogleCredentials, GdchCredentials, unscoped ServiceAccountCredentials, and AppEngineCredentials).
    • Tracks token refreshes across synchronous getRequestMetadata, asynchronous getRequestMetadata(URI, Executor, RequestMetadataCallback), refresh(), and refreshIfExpired() using a backward-clobber-safe CAS loop so cached token hits and concurrent coalesced refreshes are not double-counted.
    • Handles Java serialization safely (degrading to pass-through delegation when transient metrics state is absent after deserialization).
  • Unit tests in StorageClientMetricsTest and MetricsRecordingCredentialsTest.

[Generated-by: AI]

…al_refresh.duration

Add Debug-tier StorageClientMetrics.recordCredentialRefreshDuration
(exact 4-key clientAttributes + error.type, unit "s") and package-private
MetricsRecordingCredentials extending GoogleCredentials to preserve
PRIVACY_AND_INTEGRITY and QuotaProjectIdProvider, skip incompatible
credential types (NoCredentials, non-GoogleCredentials, GdchCredentials,
unscoped ServiceAccountCredentials, AppEngineCredentials), deduplicate
concurrent coalesced refreshes with a backward-clobber-safe CAS loop,
and handle Java serialization safely.

[Generated-by: AI]

@gemini-code-assist gemini-code-assist Bot left a comment

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.

Code Review

This pull request introduces MetricsRecordingCredentials, a decorator for GoogleCredentials that records credential refresh durations, along with corresponding metric recording methods and unit tests. The review feedback highlights a correctness issue where getAccessToken() and refreshAccessToken() are not overridden, which could cause downstream components to receive stale or null tokens. Additionally, an optimization is suggested for maybeRecordTokenChange to reduce lock contention by avoiding redundant calls to delegate.getAccessToken() inside a loop.

…age-credential-refresh-wrapper [Generated-by: AI]
Construct real GdchCredentials and ServiceAccountCredentials instances via their builders in MetricsRecordingCredentialsTest instead of Mockito mocks. In google-auth-library 1.58.0, both classes carry JSpecify @NullMarked (whose @target includes ElementType.MODULE), which causes ByteBuddy's annotation inspection to throw ArrayStoreException on JDK 8.

[Generated-by: AI]
…age-credential-refresh-wrapper

[Generated-by: AI]
…t test

MetricsRecordingCredentialsTest already asserts the exact four attribute keys (no
server.address or rpc.system.name) and the unit end to end.

[Generated-by: AI]
…age-credential-refresh-wrapper

[Generated-by: AI]
…age-credential-refresh-wrapper

[Generated-by: AI]
…age-credential-refresh-wrapper

[Generated-by: AI]
@nidhiii-27
nidhiii-27 marked this pull request as ready for review November 26, 2026 06:05
@nidhiii-27
nidhiii-27 requested review from a team as code owners November 26, 2026 06:05
@nidhiii-27
nidhiii-27 requested review from Dhriti07 and cpriti-os and removed request for a team November 26, 2026 06:05

@cpriti-os cpriti-os left a comment

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.

Initial review

* failures are recorded per waiter.
*/
@NullMarked
final class MetricsRecordingCredentials extends GoogleCredentials {

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.

Should we override equals and hashCode to delegate to delegate, since inheriting GoogleCredentials.equals compares unset superclass fields and treats any two wrapped credentials as equal?

}

@VisibleForTesting
static String mapAuthErrorType(@Nullable Throwable t) {

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 move mapAuthErrorType into StorageErrorTypeMapper to reuse MAX_CAUSE_DEPTH and keep error-type mapping in one place?

public GoogleCredentials createScoped(
Collection<String> scopes, Collection<String> defaultScopes) {
return rewrap(delegate.createScoped(scopes, defaultScopes));
}

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.

Should we also override createWithQuotaProject, createDelegated, createWithCustomRetryStrategy, and getCredentialInfo so createWithQuotaProject doesn't drop delegate via GoogleCredentials.toBuilder()?

}

@Override
public Map<String, List<String>> getRequestMetadata(@Nullable URI uri) throws IOException {

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 generalize runRecorded to return a value so getRequestMetadata(URI) doesn't duplicate the same timing and recording block?

Map<String, List<String>> metadata = delegate.getRequestMetadata(uri);
maybeRecordTokenChange(m, c, otelContext, startNanos, before);
return metadata;
} catch (IOException e) {

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.

Should we also catch RuntimeException here, in runRecorded, and around the async delegate.getRequestMetadata call since OAuth2Credentials rethrows RuntimeException causes like CancellationException directly?

.isSameInstanceAs(nonGoogle);
assertThat(MetricsRecordingCredentials.wrap(gdch, debugMetrics, fakeClock))
.isSameInstanceAs(gdch);
assertThat(MetricsRecordingCredentials.wrap(unscopedSa, debugMetrics, fakeClock))

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.

Can we also add a case for a scoped ServiceAccountCredentials to verify it gets wrapped?

assertThat(wrapped.hasRequestMetadata()).isTrue();
assertThat(wrapped.hasRequestMetadataOnly()).isTrue();
assertThat(wrapped.createScopedRequired()).isFalse();
assertThat(wrapped.createScoped(Collections.singletonList("scope"))).isSameInstanceAs(wrapped);

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.

Can we also test both createScoped overloads with a delegate that returns a new instance so the rewrap() path where scoped != delegate is covered?

assertThat(wrapped.getRequestMetadata(STORAGE_URI)).containsKey("Authorization");
clockNanos.addAndGet(50_000_000L);
assertThat(wrapped.getRequestMetadata(STORAGE_URI)).containsKey("Authorization");
wrapped.refreshIfExpired();

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.

Can we also test refreshIfExpired() on an uninitialized or expired credential to cover its refresh recording path?

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ai-generated Pull Request generated by AI

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants