Skip to content

Commit

Permalink
Ensure AsyncAgedCache is correctly updated (#693)
Browse files Browse the repository at this point in the history
  • Loading branch information
frederikprijck authored Jan 10, 2024
1 parent 36c8767 commit 24a6502
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/Auth0.AuthenticationApi/Tokens/AsyncAgedCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ public Task<TValue> GetOrAddAsync(TKey key, TimeSpan maxAge)
var cacheExpiresAt = entry.CachedAt.Add(maxAge);
if (now < cacheExpiresAt)
return entry.Task;

// When a cache entry was found, but expired, we want to remove it.
cache.TryRemove(key, out _);
}

var task = valueFactory(key);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,28 @@ public async Task DoesNotCallFactoryWhenAlreadyCached()
await cache.GetOrAddAsync("abc", TimeSpan.FromSeconds(30));
Assert.Equal(1, factoryCallCount);
}

[Fact]
public async Task CorrectlyUpdatesTheCache()
{
var factoryCallCount = 0;
Task<int> factory(string s) => Task.FromResult(factoryCallCount++);
var cache = new AsyncAgedCache<string, int>(factory);

await cache.GetOrAddAsync("abc", TimeSpan.FromSeconds(1));
Assert.Equal(1, factoryCallCount);
await cache.GetOrAddAsync("abc", TimeSpan.FromSeconds(1));
Assert.Equal(1, factoryCallCount);

// Wait 2 sec
await Task.Delay(2000);
factoryCallCount = 0;

await cache.GetOrAddAsync("abc", TimeSpan.FromSeconds(1));
Assert.Equal(1, factoryCallCount);
await cache.GetOrAddAsync("abc", TimeSpan.FromSeconds(1));
Assert.Equal(1, factoryCallCount);
}

[Fact]
public async Task DoesNotCallFactoryWithWrongKey()
Expand Down

0 comments on commit 24a6502

Please sign in to comment.