Skip to content

Commit 0a77f30

Browse files
committed
Save cache in static context
1 parent b1fa4da commit 0a77f30

File tree

1 file changed

+3
-3
lines changed

1 file changed

+3
-3
lines changed

src/api/Elastic.Documentation.Api.Infrastructure/Gcp/GcpIdTokenProvider.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,14 +15,14 @@ namespace Elastic.Documentation.Api.Infrastructure.Gcp;
1515
public class GcpIdTokenProvider(HttpClient httpClient)
1616
{
1717
// Cache tokens by target audience to avoid regenerating them on every request
18-
private readonly ConcurrentDictionary<string, CachedToken> _tokenCache = new();
18+
private static readonly ConcurrentDictionary<string, CachedToken> TokenCache = new();
1919

2020
private record CachedToken(string Token, DateTimeOffset ExpiresAt);
2121

2222
public async Task<string> GenerateIdTokenAsync(string serviceAccount, string targetAudience, Cancel cancellationToken = default)
2323
{
2424
// Check if we have a valid cached token
25-
if (_tokenCache.TryGetValue(targetAudience, out var cachedToken) &&
25+
if (TokenCache.TryGetValue(targetAudience, out var cachedToken) &&
2626
cachedToken.ExpiresAt > DateTimeOffset.UtcNow.AddMinutes(1)) // Refresh 1 minute before expiry
2727
return cachedToken.Token;
2828

@@ -73,7 +73,7 @@ public async Task<string> GenerateIdTokenAsync(string serviceAccount, string tar
7373
var idToken = await ExchangeJwtForIdToken(jwt, targetAudience, cancellationToken);
7474

7575
var expiresAt = expirationTime.Subtract(TimeSpan.FromMinutes(1));
76-
_ = _tokenCache.AddOrUpdate(targetAudience,
76+
_ = TokenCache.AddOrUpdate(targetAudience,
7777
new CachedToken(idToken, expiresAt),
7878
(_, _) => new CachedToken(idToken, expiresAt));
7979

0 commit comments

Comments
 (0)