Repository navigation
Expand file tree
/
Copy pathReferenceDataHybridCache.cs
More file actions
113 lines (97 loc) · 5.75 KB
/
Copy pathReferenceDataHybridCache.cs
File metadata and controls
113 lines (97 loc) · 5.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
namespace CoreEx.RefData;
/// <summary>
/// Provides <see cref="IReferenceDataCache"/> implementation using an <see cref="IHybridCache"/>.
/// </summary>
/// <param name="cache">The underlying <see cref="IHybridCache"/>.</param>
public partial class ReferenceDataHybridCache(IHybridCache cache) : IReferenceDataCache
{
// IReferenceDataCache is scoped, so the gate must be shared across instances to cover concurrent requests.
private static readonly ConcurrentDictionary<string, SemaphoreSlim> _semaphores = new();
private readonly ConcurrentDictionary<Type, HybridCacheEntryOptions> _entryOptions = new();
/// <summary>
/// Gets the underlying <see cref="IHybridCache"/>.
/// </summary>
public IHybridCache Cache { get; set; } = cache.ThrowIfNull();
/// <summary>
/// Gets or creates the <see cref="HybridCacheEntryOptions"/> for the specified <paramref name="type"/>.
/// </summary>
private HybridCacheEntryOptions GetOrCreateEntryOptions(Type type) => _entryOptions.GetOrAdd(type, _ =>
{
var options = HybridCacheEntryOptions.CreateForName(type.Name);
OnCreateCacheEntry(type, options);
return options;
});
/// <summary>
/// Provides an opportunity to further configure the <see cref="HybridCacheEntryOptions"/>.
/// </summary>
/// <param name="type">The <see cref="IReferenceData"/> <see cref="Type"/>.</param>
/// <param name="entry">The <see cref="HybridCacheEntryOptions"/>.</param>
protected virtual void OnCreateCacheEntry(Type type, HybridCacheEntryOptions entry) { }
/// <inheritdoc/>
public async Task<IReferenceDataCollection> GetOrCreateAsync(Type type, Func<Type, CancellationToken, Task<IReferenceDataCollection>> factory, CancellationToken cancellationToken = default)
{
var key = $"RefData:{(Internal.GetNamespaceFormattedName(type))}";
var options = GetOrCreateEntryOptions(type);
// Use invoker to ensure properly typed (needed for the likes of deserialization, where/if used).
var invoker = GetInvokerForType(type);
// Try and get as most likely already in the cache; where exists then exit fast.
var (Exists, Value) = await invoker(Cache, key, options, cancellationToken).ConfigureAwait(false);
if (Exists)
return (IReferenceDataCollection)Value!;
var semaphore = GetSemaphore(key);
// Use the semaphore to manage a single thread to perform the "expensive" get operation.
await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
// Does a get or create as it may have been added as we went to lock; use the typed invoker (as opposed to relying on C# generic type inference) to ensure the concrete type,
// rather than the IReferenceDataCollection interface, is used as the underlying cache generic type argument (see GetOrCreateInvokerForType remarks).
var getOrCreateInvoker = GetOrCreateInvokerForType(type);
return await getOrCreateInvoker(Cache, key, factory, type, options, cancellationToken).ConfigureAwait(false);
}
finally
{
semaphore.Release();
}
}
/// <inheritdoc/>
/// <remarks>The removal is performed under the same process-wide per-key semaphore as cache loads, including loads in other request scopes. Any in-flight load completes (and is then evicted) rather than repopulating the cache with stale data after the removal.</remarks>
public async Task RemoveAsync(Type type, CancellationToken cancellationToken = default)
{
var key = $"RefData:{(Internal.GetNamespaceFormattedName(type))}";
var semaphore = GetSemaphore(key);
await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
await Cache.RemoveByKeyAsync(key, GetOrCreateEntryOptions(type), cancellationToken).ConfigureAwait(false);
}
finally
{
semaphore.Release();
}
}
/// <summary>
/// Gets or adds the <see cref="SemaphoreSlim"/> used to manage single concurrency for the specified cache <paramref name="key"/>.
/// </summary>
private static SemaphoreSlim GetSemaphore(string key) => _semaphores.GetOrAdd(key, _ => new SemaphoreSlim(1, 1));
/// <summary>
/// Registers the <see cref="HybridCacheEntryOptions"/> for the specified <typeparamref name="TRefColl"/>.
/// </summary>
/// <typeparam name="TRefColl">The <see cref="IReferenceData"/> <see cref="Type"/>.</typeparam>
/// <param name="options">The <see cref="HybridCacheEntryOptions"/>.</param>
/// <returns>The <see cref="ReferenceDataHybridCache"/> to support fluent-style method-chaining.</returns>
public ReferenceDataHybridCache RegisterCacheEntryOptions<TRefColl>(HybridCacheEntryOptions options) where TRefColl : IReferenceDataCollection => RegisterCacheEntryOptions(typeof(TRefColl), options);
/// <summary>
/// Registers the <see cref="HybridCacheEntryOptions"/> for the specified <paramref name="type"/> (should be a <see cref="IReferenceDataCollection"/> <see cref="Type"/>).
/// </summary>
/// <param name="type">The <see cref="Type"/>.</param>
/// <param name="options">The <see cref="HybridCacheEntryOptions"/>.</param>
/// <returns>The <see cref="ReferenceDataHybridCache"/> to support fluent-style method-chaining.</returns>
public ReferenceDataHybridCache RegisterCacheEntryOptions(Type type, HybridCacheEntryOptions options)
{
if (type.ThrowIfNull().GetInterface(nameof(IReferenceDataCollection)) == null)
throw new ArgumentException($"The specified '{type.Name}' is not a valid {nameof(IReferenceDataCollection)} type.", nameof(type));
options.ThrowIfNull();
_entryOptions[type] = options;
return this;
}
}