Repository navigation
Expand file tree
/
Copy pathExtensionMethods.GetSet.cs
More file actions
329 lines (299 loc) · 13.4 KB
/
Copy pathExtensionMethods.GetSet.cs
File metadata and controls
329 lines (299 loc) · 13.4 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
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
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Caching.Memory;
namespace Opserver
{
public static partial class ExtensionMethods
{
private static readonly object _syncLock = new object();
private static readonly ConcurrentDictionary<string, object> _getSetNullLocks = new ConcurrentDictionary<string, object>();
private static readonly ConcurrentDictionary<string, SemaphoreSlim> _getSetSemaphores = new ConcurrentDictionary<string, SemaphoreSlim>();
internal class GetSetWrapper<T>
{
public DateTime StaleAfter { get; set; }
public T Data { get; set; }
}
/// <summary>
/// A context passed to GetSet methods, in case there is some context we want here later.
/// </summary>
public class MicroContext : IDisposable
{
void IDisposable.Dispose() { }
}
/// <summary>
/// Sets a value in cache *only if it's not already there*.
/// Note: this requires all competition to flow through the same method (as it uses a lock specific to this path).
/// </summary>
/// <typeparam name="T">The type to insert into cache.</typeparam>
/// <param name="cache">The cache to put the value in.</param>
/// <param name="key">The key in cache to use.</param>
/// <param name="val">The value to insert.</param>
/// <returns>True if the value was inserted (not already present), false if it already existed.</returns>
public static bool SetNXSync<T>(this IMemoryCache cache, string key, T val)
{
lock (_syncLock)
{
if (cache.Get<T>(key).Equals(default(T)))
{
cache.Set(key, val);
return true;
}
return false;
}
}
// return true if this caller won the race to load whatever would go at key
private static bool GotCompeteLock(IMemoryCache cache, string key)
{
while (true)
{
var competeKey = key + "-cload";
if (cache.SetNXSync(competeKey, DateTime.UtcNow))
{
// Got it!
return true;
}
var x = cache.Get<DateTime>(competeKey);
// Did somebody abandoned the lock?
if (DateTime.UtcNow - x > TimeSpan.FromMinutes(5))
{
// Yep, clear it and try again
cache.Remove(competeKey);
continue;
}
// Lost the lock competition
return false;
}
}
// called by a winner of CompeteToLoad, to make it so the next person to call CompeteToLoad will get true
private static void ReleaseCompeteLock(IMemoryCache cache, string key) => cache.Remove(key + "-cload");
private static SemaphoreSlim GetNullSemaphore(ref SemaphoreSlim semaphore, string key)
{
if (semaphore == null)
{
semaphore = _getSetSemaphores.AddOrUpdate(key, _ => new SemaphoreSlim(1), (_, old) => old);
}
return semaphore;
}
private static int _totalGetSetSync, _totalGetSetAsyncSuccess, _totalGetSetAsyncError;
/// <summary>
/// Indicates how many sync (first), async-success (second) and async-error (third) GetSet operations have been completed
/// </summary>
public static Tuple<int, int, int> GetGetSetStatistics() =>
Tuple.Create(Interlocked.CompareExchange(ref _totalGetSetSync, 0, 0),
Interlocked.CompareExchange(ref _totalGetSetAsyncSuccess, 0, 0),
Interlocked.CompareExchange(ref _totalGetSetAsyncError, 0, 0));
/// <summary>
/// Gets the current data via <paramref name="lookup"/>.
/// When data is missing or stale (older than <paramref name="duration"/>), a background refresh is
/// initiated on stale fetches still within <paramref name="staleDuration"/> after <paramref name="duration"/>.
/// </summary>
/// <typeparam name="T">The type of value to get.</typeparam>
/// <param name="cache">The cache to use.</param>
/// <param name="key">The cache key to use.</param>
/// <param name="lookup">Refreshes the data if necessary, passing the old data if we have it.</param>
/// <param name="duration">The time to cache the data, before it's considered stale.</param>
/// <param name="staleDuration">The time available to serve stale data, while a background fetch is performed.</param>
public static T GetSet<T>(this IMemoryCache cache, string key, Func<T, MicroContext, T> lookup, TimeSpan duration, TimeSpan staleDuration)
where T : class
{
var possiblyStale = cache.Get<GetSetWrapper<T>>(key);
var localLockName = key;
var nullLoadLock = _getSetNullLocks.AddOrUpdate(localLockName, _ => new object(), (_, old) => old);
if (possiblyStale == null)
{
// We can't prevent multiple web server's from running this (well, we can but its probably overkill) but we can
// at least stop the query from running multiple times on *this* web server
lock (nullLoadLock)
{
possiblyStale = cache.Get<GetSetWrapper<T>>(key);
if (possiblyStale == null)
{
T data;
using (var ctx = new MicroContext())
{
data = lookup(null, ctx);
}
possiblyStale = new GetSetWrapper<T>
{
Data = data,
StaleAfter = DateTime.UtcNow + duration
};
cache.Set(key, possiblyStale, duration + staleDuration);
Interlocked.Increment(ref _totalGetSetSync);
}
}
}
if (possiblyStale.StaleAfter > DateTime.UtcNow) return possiblyStale.Data;
bool gotCompeteLock = false;
if (Monitor.TryEnter(nullLoadLock, 0))
{ // it isn't actively being refreshed; we'll check for a mutex on the cache
try
{
gotCompeteLock = GotCompeteLock(cache, key);
}
finally
{
Monitor.Exit(nullLoadLock);
}
}
if (gotCompeteLock)
{
var old = possiblyStale.Data;
var task = new Task(delegate
{
lock (nullLoadLock) // holding this lock allows us to locally short-circuit all the other threads that come asking
{
try
{
var updated = new GetSetWrapper<T>();
using (var ctx = new MicroContext())
{
updated.Data = lookup(old, ctx);
updated.StaleAfter = DateTime.UtcNow + duration;
}
cache.Remove(key);
cache.Set(key, updated, duration + staleDuration);
}
finally
{
ReleaseCompeteLock(cache, key);
}
}
});
task.ContinueWith(t =>
{
if (t.IsFaulted)
{
Interlocked.Increment(ref _totalGetSetAsyncError);
t.Exception.Log();
}
else
{
Interlocked.Increment(ref _totalGetSetAsyncSuccess);
}
});
task.Start();
}
return possiblyStale.Data;
}
/// <summary>
/// Asynchronously gets the current data via <paramref name="lookup"/>.
/// When data is missing or stale (older than <paramref name="duration"/>), a background refresh is
/// initiated on stale fetches still within <paramref name="staleDuration"/> after <paramref name="duration"/>.
/// </summary>
/// <typeparam name="T">The type of value to get.</typeparam>
/// <param name="cache">The cache to use.</param>
/// <param name="key">The cache key to use.</param>
/// <param name="lookup">Refreshes the data if necessary, passing the old data if we have it.</param>
/// <param name="duration">The time to cache the data, before it's considered stale.</param>
/// <param name="staleDuration">The time available to serve stale data, while a background fetch is performed.</param>
public static Task<T> GetSetAsync<T>(
this IMemoryCache cache,
string key,
Func<T, MicroContext, Task<T>> lookup,
TimeSpan duration,
TimeSpan staleDuration)
{
var possiblyStale = cache.Get<GetSetWrapper<T>>(key);
if (possiblyStale?.StaleAfter > DateTime.UtcNow)
{
return Task.FromResult(possiblyStale.Data);
}
return GetSetAsyncFallback(cache, key, lookup, duration, staleDuration);
}
private static async Task<T> GetSetAsyncFallback<T>(
IMemoryCache cache,
string key,
Func<T, MicroContext, Task<T>> lookup,
TimeSpan duration,
TimeSpan staleDuration)
{
GetSetWrapper<T> possiblyStale;
SemaphoreSlim nullLoadSemaphore = null;
// We can't prevent multiple web server's from running this (well, we can but its probably overkill) but we can
// at least stop the query from running multiple times on *this* web server
await GetNullSemaphore(ref nullLoadSemaphore, key).WaitAsync();
try
{
possiblyStale = cache.Get<GetSetWrapper<T>>(key);
if (possiblyStale == null)
{
T data;
using (var ctx = new MicroContext())
{
data = await lookup(default, ctx);
}
possiblyStale = new GetSetWrapper<T>
{
Data = data,
StaleAfter = DateTime.UtcNow + duration
};
cache.Set(key, possiblyStale, duration + staleDuration);
Interlocked.Increment(ref _totalGetSetSync);
}
}
finally
{
nullLoadSemaphore.Release();
}
if (possiblyStale?.StaleAfter > DateTime.UtcNow)
{
return possiblyStale.Data;
}
var gotCompeteLock = false;
if (await GetNullSemaphore(ref nullLoadSemaphore, key).WaitAsync(0))
{
try
{
gotCompeteLock = GotCompeteLock(cache, key);
}
finally
{
nullLoadSemaphore.Release();
}
}
if (gotCompeteLock)
{
var old = possiblyStale.Data;
// The using is okay because we just need suppression when creating the task
using (ExecutionContext.SuppressFlow())
{
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
Task.Run(async () =>
{
await nullLoadSemaphore.WaitAsync();
try
{
GetSetWrapper<T> updated;
using (var ctx = new MicroContext())
{
updated = new GetSetWrapper<T>
{
Data = await lookup(old, ctx),
StaleAfter = DateTime.UtcNow + duration
};
}
cache.Remove(key);
cache.Set(key, updated, duration + staleDuration);
Interlocked.Increment(ref _totalGetSetAsyncSuccess);
}
catch (Exception ex)
{
Interlocked.Increment(ref _totalGetSetAsyncError);
ex.Log();
}
finally
{
ReleaseCompeteLock(cache, key);
nullLoadSemaphore.Release();
}
});
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
}
}
return possiblyStale.Data;
}
}
}