Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 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
60 changes: 51 additions & 9 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,16 @@ 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);
}
// Clone the tags as the collection might be updated by the post eviction callback
var keysArray = keys.ToArray();

_taggedEntries.Remove(tag);
foreach (var key in keysArray)
{
_cache.Remove(key);
}
}
}
}

Expand Down Expand Up @@ -81,14 +90,47 @@ public ValueTask SetAsync(string key, byte[] value, string[]? tags, TimeSpan val

void SetEntry()
{
_cache.Set(
key,
value,
new MemoryCacheEntryOptions
var options = new MemoryCacheEntryOptions
{
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);
}

_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);

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

// Remove the collection if there is no more keys in it
if (tagged.Count == 0)
{
_taggedEntries.Remove(tag);
}
}
}
}
}
}

return ValueTask.CompletedTask;
Expand Down
45 changes: 45 additions & 0 deletions src/Middleware/OutputCaching/test/MemoryOutputCacheStoreTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,15 @@ 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
var timeout = Task.Delay(1000);
while (store.TaggedEntries.TryGetValue("tag1", out tag1s) && !timeout.IsCompleted) { }

Assert.Null(result);
Assert.Null(tag1s);
Assert.False(timeout.IsCompleted);
}

[Fact]
Expand Down Expand Up @@ -140,6 +148,43 @@ 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
var timeout = Task.Delay(2000);
while (store.TaggedEntries.TryGetValue("tag1", out tag1s) && !timeout.IsCompleted) { }
while (store.TaggedEntries.TryGetValue("tag2", out tag2s) && tag2s.Count != 1 && !timeout.IsCompleted) { }

Assert.False(timeout.IsCompleted);
Assert.Null(tag1s);
Assert.Single(tag2s);
}

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