Skip to content

Commit

Permalink
Improve the GetOrSetAsync state machine (#212)
Browse files Browse the repository at this point in the history
Less awaiting paths mean a smaller code size and more "simple" state machine
  • Loading branch information
Turnerj authored Jul 23, 2022
1 parent 0425770 commit 3465738
Showing 1 changed file with 6 additions and 3 deletions.
9 changes: 6 additions & 3 deletions src/CacheTower/CacheStack.cs
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,7 @@ public async ValueTask<T> GetOrSetAsync<T>(string cacheKey, Func<T, Task<T>> val

var currentTime = DateTimeProvider.Now;
var cacheEntryPoint = await GetWithLayerIndexAsync<T>(cacheKey);
var cacheEntryStatus = CacheEntryStatus.Stale;
if (cacheEntryPoint != default)
{
if (cacheEntryPoint.CacheEntry.Expiry > currentTime)
Expand All @@ -215,7 +216,7 @@ public async ValueTask<T> GetOrSetAsync<T>(string cacheKey, Func<T, Task<T>> val
if (settings.StaleAfter.HasValue && cacheEntry.GetStaleDate(settings) < currentTime)
{
//If the cache entry is stale, refresh the value in the background
_ = RefreshValueAsync(cacheKey, valueFactory, settings, CacheEntryStatus.Stale);
_ = RefreshValueAsync(cacheKey, valueFactory, settings, cacheEntryStatus);
}
else if (cacheEntryPoint.LayerIndex > 0)
{
Expand All @@ -228,14 +229,16 @@ public async ValueTask<T> GetOrSetAsync<T>(string cacheKey, Func<T, Task<T>> val
else
{
//Refresh the value in the current thread because we only have expired data (we never return expired data)
return (await RefreshValueAsync(cacheKey, valueFactory, settings, CacheEntryStatus.Expired))!.Value!;
cacheEntryStatus = CacheEntryStatus.Expired;
}
}
else
{
//Refresh the value in the current thread because we have no existing data
return (await RefreshValueAsync(cacheKey, valueFactory, settings, CacheEntryStatus.Miss))!.Value!;
cacheEntryStatus = CacheEntryStatus.Miss;
}

return (await RefreshValueAsync(cacheKey, valueFactory, settings, cacheEntryStatus))!.Value!;
}

private async ValueTask BackPopulateCacheAsync<T>(int fromIndexExclusive, string cacheKey, CacheEntry<T> cacheEntry)
Expand Down

0 comments on commit 3465738

Please sign in to comment.