-
Notifications
You must be signed in to change notification settings - Fork 159
/
CachingService.cs
344 lines (286 loc) · 13.3 KB
/
CachingService.cs
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using LazyCache.Providers;
using Microsoft.Extensions.Caching.Memory;
namespace LazyCache
{
// ReSharper disable once ClassWithVirtualMembersNeverInherited.Global
public class CachingService : IAppCache
{
private readonly Lazy<ICacheProvider> cacheProvider;
private readonly int[] keyLocks;
public CachingService() : this(DefaultCacheProvider)
{
}
public CachingService(Lazy<ICacheProvider> cacheProvider)
{
this.cacheProvider = cacheProvider ?? throw new ArgumentNullException(nameof(cacheProvider));
var lockCount = Math.Max(Environment.ProcessorCount * 8, 32);
keyLocks = new int[lockCount];
}
public CachingService(Func<ICacheProvider> cacheProviderFactory)
{
if (cacheProviderFactory == null) throw new ArgumentNullException(nameof(cacheProviderFactory));
cacheProvider = new Lazy<ICacheProvider>(cacheProviderFactory);
var lockCount = Math.Max(Environment.ProcessorCount * 8, 32);
keyLocks = new int[lockCount];
}
public CachingService(ICacheProvider cache) : this(() => cache)
{
if (cache == null) throw new ArgumentNullException(nameof(cache));
}
public static Lazy<ICacheProvider> DefaultCacheProvider { get; set; }
= new Lazy<ICacheProvider>(() =>
new MemoryCacheProvider(
new MemoryCache(
new MemoryCacheOptions())
));
/// <summary>
/// Seconds to cache objects for by default
/// </summary>
[Obsolete("DefaultCacheDuration has been replaced with DefaultCacheDurationSeconds")]
public virtual int DefaultCacheDuration
{
get => DefaultCachePolicy.DefaultCacheDurationSeconds;
set => DefaultCachePolicy.DefaultCacheDurationSeconds = value;
}
/// <summary>
/// Policy defining how long items should be cached for unless specified
/// </summary>
public virtual CacheDefaults DefaultCachePolicy { get; set; } = new CacheDefaults();
public virtual void Add<T>(string key, T item, MemoryCacheEntryOptions policy)
{
if (item == null)
throw new ArgumentNullException(nameof(item));
ValidateKey(key);
CacheProvider.Set(key, item, policy);
}
public virtual T Get<T>(string key)
{
ValidateKey(key);
var item = CacheProvider.Get(key);
return GetValueFromLazy<T>(item, out _);
}
public virtual Task<T> GetAsync<T>(string key)
{
ValidateKey(key);
var item = CacheProvider.Get(key);
return GetValueFromAsyncLazy<T>(item, out _);
}
public virtual bool TryGetValue<T>(string key, out T value)
{
ValidateKey(key);
return CacheProvider.TryGetValue(key, out value);
}
public virtual T GetOrAdd<T>(string key, Func<ICacheEntry, T> addItemFactory)
{
return GetOrAdd(key, addItemFactory, null);
}
public virtual T GetOrAdd<T>(string key, Func<ICacheEntry, T> addItemFactory, MemoryCacheEntryOptions policy)
{
ValidateKey(key);
object cacheItem;
object CacheFactory(ICacheEntry entry) =>
new Lazy<T>(() =>
{
var result = addItemFactory(entry);
SetAbsoluteExpirationFromRelative(entry);
EnsureEvictionCallbackDoesNotReturnTheAsyncOrLazy<T>(entry.PostEvictionCallbacks);
return result;
});
// acquire lock per key
uint hash = (uint)key.GetHashCode() % (uint)keyLocks.Length;
while (Interlocked.CompareExchange(ref keyLocks[hash], 1, 0) == 1) { Thread.Yield(); }
try
{
cacheItem = CacheProvider.GetOrCreate<object>(key, policy, CacheFactory);
}
finally
{
keyLocks[hash] = 0;
}
try
{
var result = GetValueFromLazy<T>(cacheItem, out var valueHasChangedType);
// if we get a cache hit but for something with the wrong type we need to evict it, start again and cache the new item instead
if (valueHasChangedType)
{
CacheProvider.Remove(key);
// acquire lock again
hash = (uint)key.GetHashCode() % (uint)keyLocks.Length;
while (Interlocked.CompareExchange(ref keyLocks[hash], 1, 0) == 1) { Thread.Yield(); }
try
{
cacheItem = CacheProvider.GetOrCreate<object>(key, CacheFactory);
}
finally
{
keyLocks[hash] = 0;
}
result = GetValueFromLazy<T>(cacheItem, out _ /* we just evicted so type change cannot happen this time */);
}
return result;
}
catch //addItemFactory errored so do not cache the exception
{
CacheProvider.Remove(key);
throw;
}
}
private static void SetAbsoluteExpirationFromRelative(ICacheEntry entry)
{
if (!entry.AbsoluteExpirationRelativeToNow.HasValue) return;
var absoluteExpiration = DateTimeOffset.UtcNow + entry.AbsoluteExpirationRelativeToNow.Value;
if (!entry.AbsoluteExpiration.HasValue || absoluteExpiration < entry.AbsoluteExpiration)
entry.AbsoluteExpiration = absoluteExpiration;
}
public virtual void Remove(string key)
{
ValidateKey(key);
CacheProvider.Remove(key);
}
public virtual ICacheProvider CacheProvider => cacheProvider.Value;
public virtual Task<T> GetOrAddAsync<T>(string key, Func<ICacheEntry, Task<T>> addItemFactory)
{
return GetOrAddAsync(key, addItemFactory, null);
}
public virtual async Task<T> GetOrAddAsync<T>(string key, Func<ICacheEntry, Task<T>> addItemFactory,
MemoryCacheEntryOptions policy)
{
ValidateKey(key);
object cacheItem;
// Ensure only one thread can place an item into the cache provider at a time.
// We are not evaluating the addItemFactory inside here - that happens outside the lock,
// below, and guarded using the async lazy. Here we just ensure only one thread can place
// the AsyncLazy into the cache at one time
// acquire lock
uint hash = (uint)key.GetHashCode() % (uint)keyLocks.Length;
while (Interlocked.CompareExchange(ref keyLocks[hash], 1, 0) == 1) { Thread.Yield(); }
object CacheFactory(ICacheEntry entry) =>
new AsyncLazy<T>(async () =>
{
var result = await addItemFactory(entry).ConfigureAwait(false);
SetAbsoluteExpirationFromRelative(entry);
EnsureEvictionCallbackDoesNotReturnTheAsyncOrLazy<T>(entry.PostEvictionCallbacks);
return result;
});
try
{
cacheItem = CacheProvider.GetOrCreate<object>(key, policy, CacheFactory);
}
finally
{
keyLocks[hash] = 0;
}
try
{
var result = GetValueFromAsyncLazy<T>(cacheItem, out var valueHasChangedType);
// if we get a cache hit but for something with the wrong type we need to evict it, start again and cache the new item instead
if (valueHasChangedType)
{
CacheProvider.Remove(key);
// acquire lock
hash = (uint)key.GetHashCode() % (uint)keyLocks.Length;
while (Interlocked.CompareExchange(ref keyLocks[hash], 1, 0) == 1) { Thread.Yield(); }
try
{
cacheItem = CacheProvider.GetOrCreate<object>(key, CacheFactory);
}
finally
{
keyLocks[hash] = 0;
}
result = GetValueFromAsyncLazy<T>(cacheItem, out _ /* we just evicted so type change cannot happen this time */);
}
if (result.IsCanceled || result.IsFaulted)
CacheProvider.Remove(key);
return await result.ConfigureAwait(false);
}
catch //addItemFactory errored so do not cache the exception
{
CacheProvider.Remove(key);
throw;
}
}
protected virtual T GetValueFromLazy<T>(object item, out bool valueHasChangedType)
{
valueHasChangedType = false;
switch (item)
{
case Lazy<T> lazy:
return lazy.Value;
case T variable:
return variable;
case AsyncLazy<T> asyncLazy:
// this is async to sync - and should not really happen as long as GetOrAddAsync is used for an async
// value. Only happens when you cache something async and then try and grab it again later using
// the non async methods.
return asyncLazy.Value.ConfigureAwait(false).GetAwaiter().GetResult();
case Task<T> task:
return task.Result;
}
// if they have cached something else with the same key we need to tell caller to reset the cached item
// although this is probably not the fastest this should not get called on the main use case
// where you just hit the first switch case above.
var itemsType = item?.GetType();
if (itemsType != null && itemsType.IsGenericType && itemsType.GetGenericTypeDefinition() == typeof(Lazy<>))
{
valueHasChangedType = true;
}
return default(T);
}
protected virtual Task<T> GetValueFromAsyncLazy<T>(object item, out bool valueHasChangedType)
{
valueHasChangedType = false;
switch (item)
{
case AsyncLazy<T> asyncLazy:
return asyncLazy.Value;
case Task<T> task:
return task;
// this is sync to async and only happens if you cache something sync and then get it later async
case Lazy<T> lazy:
return Task.FromResult(lazy.Value);
case T variable:
return Task.FromResult(variable);
}
// if they have cached something else with the same key we need to tell caller to reset the cached item
// although this is probably not the fastest this should not get called on the main use case
// where you just hit the first switch case above.
var itemsType = item?.GetType();
if (itemsType != null && itemsType.IsGenericType && itemsType.GetGenericTypeDefinition() == typeof(AsyncLazy<>))
{
valueHasChangedType = true;
}
return Task.FromResult(default(T));
}
protected virtual void EnsureEvictionCallbackDoesNotReturnTheAsyncOrLazy<T>(
IList<PostEvictionCallbackRegistration> callbackRegistrations)
{
if (callbackRegistrations != null)
foreach (var item in callbackRegistrations)
{
var originalCallback = item.EvictionCallback;
item.EvictionCallback = (key, value, reason, state) =>
{
// before the original callback we need to unwrap the Lazy that holds the cache item
if (value is AsyncLazy<T> asyncCacheItem)
value = asyncCacheItem.IsValueCreated ? asyncCacheItem.Value : Task.FromResult(default(T));
else if (value is Lazy<T> cacheItem)
value = cacheItem.IsValueCreated ? cacheItem.Value : default(T);
// pass the unwrapped cached value to the original callback
originalCallback(key, value, reason, state);
};
}
}
protected virtual void ValidateKey(string key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
if (string.IsNullOrWhiteSpace(key))
throw new ArgumentOutOfRangeException(nameof(key), "Cache keys cannot be empty or whitespace");
}
}
}