Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 73 additions & 16 deletions src/Middleware/OutputCaching/src/Memory/MemoryOutputCacheStore.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Diagnostics;
using System.Linq;
using Microsoft.Extensions.Caching.Memory;

namespace Microsoft.AspNetCore.OutputCaching.Memory;
Expand All @@ -18,6 +20,9 @@ internal MemoryOutputCacheStore(IMemoryCache cache)
_cache = cache;
}

// For testing
internal Dictionary<string, HashSet<string>> TaggedEntries => _taggedEntries;

public ValueTask EvictByTagAsync(string tag, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(tag);
Expand All @@ -26,12 +31,29 @@ public ValueTask EvictByTagAsync(string tag, CancellationToken cancellationToken
{
if (_taggedEntries.TryGetValue(tag, out var keys))
{
foreach (var key in keys)
if (keys != null && keys.Count > 0)
{
_cache.Remove(key);
}
// Since eviction callbacks run inline, iterating over keys could throw
// To prevent allocating a copy of the keys we check if the eviction callback ran,
// and if it did we restart the loop.

_taggedEntries.Remove(tag);
var i = keys.Count;
while (i > 0)
{
var oldCount = keys.Count;
foreach (var key in keys)
{
_cache.Remove(key);
i--;
if (oldCount != keys.Count)
{
// eviction callback ran inline, we need to restart the loop to avoid
// "collection modified while iterating" errors
break;
}
}
}
}
}
}

Expand Down Expand Up @@ -71,26 +93,61 @@ public ValueTask SetAsync(string key, byte[] value, string[]? tags, TimeSpan val
keys.Add(key);
}

SetEntry();
SetEntry(key, value, tags, validFor);
}
}
else
{
SetEntry();
SetEntry(key, value, tags, validFor);
}

void SetEntry()
return ValueTask.CompletedTask;
}

void SetEntry(string key, byte[] value, string[]? tags, TimeSpan validFor)
{
var options = new MemoryCacheEntryOptions
{
_cache.Set(
key,
value,
new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = validFor,
Size = value.Length
});
AbsoluteExpirationRelativeToNow = validFor,
Size = value.Length
};

if (tags != null && tags.Length > 0)
{
// Remove cache keys from tag lists when the entry is evicted
options.RegisterPostEvictionCallback(RemoveFromTags, tags);
}

return ValueTask.CompletedTask;
_cache.Set(key, value, options);
}

void RemoveFromTags(object key, object? value, EvictionReason reason, object? state)
{
var tags = state as string[];

Debug.Assert(tags != null);
Debug.Assert(tags.Length > 0);

if (key is not string stringKey)
{
return;
}

lock (_tagsLock)
{
foreach (var tag in tags!)
{
if (_taggedEntries.TryGetValue(tag, out var tagged) && tagged != null)
{
tagged.Remove(stringKey);

// Remove the collection if there is no more keys in it
if (tagged.Count == 0)
{
_taggedEntries.Remove(tag);
}
}
}
}
}
}
57 changes: 57 additions & 0 deletions src/Middleware/OutputCaching/test/MemoryOutputCacheStoreTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,19 @@ public async Task EvictByTag_SingleTag_SingleEntry()
await store.EvictByTagAsync("tag1", default);
var result = await store.GetAsync(key, default);

HashSet<string> tag1s;

// Wait for the hashset to be removed as it happens on a separate thread

using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));

while (store.TaggedEntries.TryGetValue("tag1", out tag1s) && !cts.IsCancellationRequested)
{
await Task.Yield();
}

Assert.Null(result);
Assert.Null(tag1s);
}

[Fact]
Expand Down Expand Up @@ -140,6 +152,51 @@ public async Task EvictByTag_MultipleTags_MultipleEntries()
Assert.Null(result2);
}

[Fact]
public async Task ExpiredEntries_AreRemovedFromTags()
{
var testClock = new TestMemoryOptionsClock { UtcNow = DateTimeOffset.UtcNow };
var cache = new MemoryCache(new MemoryCacheOptions { SizeLimit = 1000, Clock = testClock, ExpirationScanFrequency = TimeSpan.FromMilliseconds(1) });
var store = new MemoryOutputCacheStore(cache);
var value = "abc"u8.ToArray();

await store.SetAsync("a", value, new[] { "tag1" }, TimeSpan.FromMilliseconds(5), default);
await store.SetAsync("b", value, new[] { "tag1", "tag2" }, TimeSpan.FromMilliseconds(5), default);
await store.SetAsync("c", value, new[] { "tag2" }, TimeSpan.FromMilliseconds(20), default);

testClock.Advance(TimeSpan.FromMilliseconds(10));

// Background expiration checks are triggered by misc cache activity.
_ = cache.Get("a");

var resulta = await store.GetAsync("a", default);
var resultb = await store.GetAsync("b", default);
var resultc = await store.GetAsync("c", default);

Assert.Null(resulta);
Assert.Null(resultb);
Assert.NotNull(resultc);

HashSet<string> tag1s, tag2s;

// Wait for the hashset to be removed as it happens on a separate thread

using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));

while (store.TaggedEntries.TryGetValue("tag1", out tag1s) && !cts.IsCancellationRequested)
{
await Task.Yield();
}

while (store.TaggedEntries.TryGetValue("tag2", out tag2s) && tag2s.Count != 1 && !cts.IsCancellationRequested)
{
await Task.Yield();
}

Assert.Null(tag1s);
Assert.Single(tag2s);
}

private class TestMemoryOptionsClock : Extensions.Internal.ISystemClock
{
public DateTimeOffset UtcNow { get; set; }
Expand Down