-
Notifications
You must be signed in to change notification settings - Fork 824
Expand file tree
/
Copy pathCache.cs
More file actions
382 lines (347 loc) · 14.9 KB
/
Cache.cs
File metadata and controls
382 lines (347 loc) · 14.9 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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
using System;
using System.Collections;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using StackExchange.Profiling;
using StackExchange.Profiling.Internal;
using StackExchange.Profiling.Storage;
namespace Opserver.Data
{
public class Cache<T> : Cache where T : class
{
/// <summary>
/// Returns if this cache has data - THIS WILL NOT TRIGGER A FETCH
/// </summary>
public override bool ContainsData => _hasData == 1 && Data != null;
private int _hasData;
internal override object InnerCache => Data;
public override Type Type => typeof (T);
private readonly SemaphoreSlim _pollSemaphoreSlim = new(1);
public override string InventoryDescription
{
get
{
var tmp = Data;
return tmp == null ? null : ((tmp as IList)?.Count.Pluralize("item") ?? "1 Item");
}
}
private readonly Func<Task<T>> _updateFunc;
private Task<T> DataTask { get; set; }
public T Data { get; private set; }
// TODO: Find name that doesn't suck, has to override so...
public override Task PollGenericAsync(bool force = false) => PollAsync(force);
/// <summary>
/// Allows awaiting of this cache directly.
/// </summary>
public TaskAwaiter<T> GetAwaiter() => DataTask.GetAwaiter();
// This makes more semantic sense...
public Task<T> GetData() => PollAsync();
public Task<T> PollAsync(bool force = false)
{
// First call polls data.
if ((_hasData == 0 && Interlocked.CompareExchange(ref _hasData, 1, 0) == 0) || force)
{
DataTask = UpdateAsync(force);
}
// Force polls and replaces data when done.
else if (IsStale)
{
return UpdateAsync(false).ContinueWith(_ =>
{
DataTask = _;
return _.GetAwaiter().GetResult();
},
CancellationToken.None,
TaskContinuationOptions.ExecuteSynchronously,
TaskScheduler.Default);
}
return DataTask;
}
private async Task<T> UpdateAsync(bool force)
{
PollStatus = "UpdateAsync";
if (!force && !IsStale) return Data;
Interlocked.Increment(ref PollingService._globalActivePolls);
PollStatus = "Awaiting Semaphore";
await _pollSemaphoreSlim.WaitAsync();
bool errored = false;
try
{
if (!force && !IsStale) return Data;
if (_isPolling) return Data;
CurrentPollDuration = Stopwatch.StartNew();
_isPolling = true;
PollStatus = "UpdateCache";
await _updateFunc();
PollStatus = "UpdateCache Complete";
Interlocked.Increment(ref _pollsTotal);
if (DataTask != null)
Interlocked.Increment(ref _pollsSuccessful);
}
catch (Exception e)
{
var errorMessage = e.Message;
if (e.InnerException != null) errorMessage += "\n" + e.InnerException.Message;
SetFail(e, errorMessage);
errored = true;
}
finally
{
if (CurrentPollDuration != null)
{
CurrentPollDuration.Stop();
LastPollDuration = CurrentPollDuration.Elapsed;
}
CurrentPollDuration = null;
_isPolling = false;
PollStatus = errored ? "Failed" : "Completed";
_pollSemaphoreSlim.Release();
Interlocked.Decrement(ref PollingService._globalActivePolls);
}
return Data;
}
private string MiniProfilerDescription { get; }
// ReSharper disable once StaticMemberInGenericType
private static readonly MiniProfilerBaseOptions _profilerOptions = new()
{
Storage = new NullStorage(),
ProfilerProvider = new DefaultProfilerProvider()
};
/// <summary>
/// Creates a cache poller
/// </summary>
/// <typeparam name="T">Type of item in the cache</typeparam>
/// <param name="owner">The PollNode owner of this Cache</param>
/// <param name="description">Description of the operation, used purely for profiling</param>
/// <param name="cacheDuration">The length of time to cache data for</param>
/// <param name="getData">The operation used to actually get data, e.g. <code>using (var conn = GetConnectionAsync()) { return getFromConnection(conn); }</code></param>
/// <param name="timeoutMs">The timeout in milliseconds for this poll to complete before aborting.</param>
/// <param name="logExceptions">Whether to log any exceptions to the log</param>
/// <param name="addExceptionData">Optionally add exception data, e.g. <code>e => e.AddLoggedData("Server", Name)</code></param>
/// <param name="afterPoll">An optional action to run after polling has completed successfully</param>
/// <param name="memberName"></param>
/// <param name="sourceFilePath"></param>
/// <param name="sourceLineNumber"></param>
/// <returns>A cache update action, used when creating a <see cref="Cache"/>.</returns>
public Cache(PollNode owner,
string description,
TimeSpan cacheDuration,
Func<Task<T>> getData,
int? timeoutMs = null,
bool? logExceptions = null,
Action<Exception> addExceptionData = null,
Action<Cache<T>> afterPoll = null,
[CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0)
: base(owner, cacheDuration, memberName, sourceFilePath, sourceLineNumber)
{
MiniProfilerDescription = "Poll: " + description; // concatenate once
// TODO: Settings via owner
logExceptions ??= LogExceptions;
_updateFunc = async () =>
{
var success = true;
PollStatus = "UpdateCacheItem";
if (EnableProfiling)
{
Profiler = _profilerOptions.StartProfiler(MiniProfilerDescription);
Profiler.Id = UniqueId;
}
using (MiniProfiler.Current.Step(description))
{
try
{
PollStatus = "Fetching";
using (MiniProfiler.Current.Step("Data Fetch"))
{
var task = getData();
if (timeoutMs.HasValue)
{
if (await Task.WhenAny(task, Task.Delay(timeoutMs.Value)) == task)
{
// Re-await for throws.
Data = await task;
}
else
{
// This means the .WhenAny returned the timeout first...boom.
throw new TimeoutException($"Fetch timed out after {timeoutMs} ms.");
}
}
else
{
Data = await task;
}
}
PollStatus = "Fetch Complete";
SetSuccess();
afterPoll?.Invoke(this);
}
catch (Exception e)
{
success = false;
if (logExceptions.Value)
{
addExceptionData?.Invoke(e);
e.Log();
}
var errorMessage = StringBuilderCache.Get()
.Append("Unable to fetch from ")
.Append(owner.NodeType)
.Append(": ")
.Append(e.Message);
#if DEBUG
errorMessage.Append(" @ ").Append(e.StackTrace);
#endif
if (e.InnerException != null) errorMessage.AppendLine().Append(e.InnerException.Message);
PollStatus = "Fetch Failed";
SetFail(e, errorMessage.ToStringRecycle());
}
owner.PollComplete(this, success);
}
if (EnableProfiling)
{
Profiler.Stop();
}
PollStatus = "UpdateCacheItem Complete";
return Data;
};
}
}
/// <summary>
/// A lightweight cache class for storing and handling overlap for cache refreshment for on-demand items
/// </summary>
/// <typeparam name="T">Type stored in this cache</typeparam>
public class LightweightCache<T> : LightweightCache where T : class
{
public T Data { get; private set; }
public DateTime? LastFetch { get; private set; }
public Exception Error { get; private set; }
public bool Successful => Error == null;
public string ErrorMessage => Error?.Message + (Error?.InnerException != null ? "\n" + Error.InnerException.Message : "");
// Temp: all async when views can be in MVC Core
public static LightweightCache<T> Get(PollNode owner, string key, Func<T> getData, TimeSpan duration, TimeSpan staleDuration)
{
using (MiniProfiler.Current.Step("LightweightCache: " + key))
{
// Let GetSet handle the overlap and locking, for now. That way it's store dependent.
return owner.MemCache.GetSet<LightweightCache<T>>(key, (_, __) =>
{
var tc = new LightweightCache<T>() { Key = key };
try
{
tc.Data = getData();
}
catch (Exception e)
{
tc.Error = e;
e.Log();
}
tc.LastFetch = DateTime.UtcNow;
return tc;
}, duration, staleDuration);
}
}
}
public class LightweightCache
{
public string Key { get; protected set; }
}
public abstract class Cache : IMonitorStatus, IDisposable
{
public PollNode Owner { get; private set; }
public virtual Type Type => typeof(Cache);
public Guid UniqueId { get; }
public TimeSpan CacheDuration { get; }
public TimeSpan? CacheFailureDuration { get; set; } = TimeSpan.FromSeconds(15);
public bool AffectsNodeStatus { get; set; }
public bool ShouldPoll => IsStale && !_isPolling;
protected volatile bool _isPolling;
public bool IsPolling => _isPolling;
public bool IsStale => (NextPoll ?? DateTime.MinValue) < DateTime.UtcNow;
protected long _pollsTotal, _pollsSuccessful;
public long PollsTotal => _pollsTotal;
public long PollsSuccessful => _pollsSuccessful;
public Stopwatch CurrentPollDuration { get; protected set; }
public DateTime? NextPoll { get; protected set; }
public DateTime? LastPoll { get; internal set; }
public TimeSpan? LastPollDuration { get; internal set; }
public DateTime? LastSuccess { get; internal set; }
public bool LastPollSuccessful { get; internal set; }
/// <summary>
/// If profiling for cache polls is active, this contains a MiniProfiler of the current or last poll
/// </summary>
public MiniProfiler Profiler { get; protected set; }
private static IOptions<OpserverSettings> Settings { get; set; }
public static bool EnableProfiling => Settings?.Value.Global.ProfilePollers ?? false;
public static bool LogExceptions => Settings?.Value.Global.LogPollerExceptions ?? false;
public static void Configure(IOptions<OpserverSettings> settings) => Settings = settings;
internal void SetSuccess()
{
LastSuccess = LastPoll = DateTime.UtcNow;
NextPoll = DateTime.UtcNow.Add(CacheDuration);
LastPollSuccessful = true;
ErrorMessage = "";
}
internal void SetFail(Exception e, string errorMessage)
{
LastPoll = DateTime.UtcNow;
NextPoll = DateTime.UtcNow.Add(CacheFailureDuration ?? CacheDuration);
LastPollSuccessful = false;
Error = e;
ErrorMessage = errorMessage;
}
public string PollStatus { get; internal set; }
public MonitorStatus MonitorStatus
{
get
{
if (LastPoll == null ) return MonitorStatus.Unknown;
return LastPollSuccessful ? MonitorStatus.Good : MonitorStatus.Critical;
}
}
public string MonitorStatusReason
{
get
{
if (LastPoll == null) return "Never Polled";
return !LastPollSuccessful ? "Poll " + LastPoll?.ToRelativeTime() + " failed: " + ErrorMessage : null;
}
}
public virtual bool ContainsData => false;
internal virtual object InnerCache => null;
public Exception Error { get; internal set; }
public string ErrorMessage { get; internal set; }
public virtual string InventoryDescription => null;
public abstract Task PollGenericAsync(bool force = false);
/// <summary>
/// Info for monitoring the monitoring, debugging, etc.
/// </summary>
public string ParentMemberName { get; }
public string SourceFilePath { get; }
public int SourceLineNumber { get; }
protected Cache(
PollNode owner,
TimeSpan cacheDuration,
[CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0)
{
Owner = owner;
UniqueId = Guid.NewGuid();
CacheDuration = cacheDuration;
ParentMemberName = memberName;
SourceFilePath = sourceFilePath;
SourceLineNumber = sourceLineNumber;
}
public void Dispose()
{
Owner = null;
}
public const string TimedCacheKey = "TimedCache";
}
}