-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
MemoryCache.cs
640 lines (545 loc) · 23.4 KB
/
MemoryCache.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
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
namespace Microsoft.Extensions.Caching.Memory
{
/// <summary>
/// An implementation of <see cref="IMemoryCache"/> using a dictionary to
/// store its entries.
/// </summary>
public class MemoryCache : IMemoryCache
{
internal readonly ILogger _logger;
private readonly MemoryCacheOptions _options;
private readonly List<WeakReference<Stats>>? _allStats;
private readonly Stats? _accumulatedStats;
private readonly ThreadLocal<Stats>? _stats;
private CoherentState _coherentState;
private bool _disposed;
private DateTime _lastExpirationScan;
/// <summary>
/// Creates a new <see cref="MemoryCache"/> instance.
/// </summary>
/// <param name="optionsAccessor">The options of the cache.</param>
public MemoryCache(IOptions<MemoryCacheOptions> optionsAccessor)
: this(optionsAccessor, NullLoggerFactory.Instance) { }
/// <summary>
/// Creates a new <see cref="MemoryCache"/> instance.
/// </summary>
/// <param name="optionsAccessor">The options of the cache.</param>
/// <param name="loggerFactory">The factory used to create loggers.</param>
public MemoryCache(IOptions<MemoryCacheOptions> optionsAccessor, ILoggerFactory loggerFactory)
{
ThrowHelper.ThrowIfNull(optionsAccessor);
ThrowHelper.ThrowIfNull(loggerFactory);
_options = optionsAccessor.Value;
_logger = loggerFactory.CreateLogger<MemoryCache>();
_coherentState = new CoherentState();
if (_options.TrackStatistics)
{
_allStats = new List<WeakReference<Stats>>();
_accumulatedStats = new Stats();
_stats = new ThreadLocal<Stats>(() => new Stats(this));
}
_lastExpirationScan = UtcNow;
TrackLinkedCacheEntries = _options.TrackLinkedCacheEntries; // we store the setting now so it's consistent for entire MemoryCache lifetime
}
private DateTime UtcNow => _options.Clock?.UtcNow.UtcDateTime ?? DateTime.UtcNow;
/// <summary>
/// Cleans up the background collection events.
/// </summary>
~MemoryCache() => Dispose(false);
/// <summary>
/// Gets the count of the current entries for diagnostic purposes.
/// </summary>
public int Count => _coherentState.Count;
// internal for testing
internal long Size => _coherentState.Size;
internal bool TrackLinkedCacheEntries { get; }
/// <inheritdoc />
public ICacheEntry CreateEntry(object key)
{
CheckDisposed();
ValidateCacheKey(key);
return new CacheEntry(key, this);
}
internal void SetEntry(CacheEntry entry)
{
if (_disposed)
{
// No-op instead of throwing since this is called during CacheEntry.Dispose
return;
}
if (_options.HasSizeLimit && entry.Size < 0)
{
throw new InvalidOperationException(SR.Format(SR.CacheEntryHasEmptySize, nameof(entry.Size), nameof(_options.SizeLimit)));
}
DateTime utcNow = UtcNow;
// Applying the option's absolute expiration only if it's not already smaller.
// This can be the case if a dependent cache entry has a smaller value, and
// it was set by cascading it to its parent.
if (entry.AbsoluteExpirationRelativeToNow.Ticks > 0)
{
long absoluteExpiration = (utcNow + entry.AbsoluteExpirationRelativeToNow).Ticks;
if ((ulong)absoluteExpiration < (ulong)entry.AbsoluteExpirationTicks)
{
entry.AbsoluteExpirationTicks = absoluteExpiration;
}
}
// Initialize the last access timestamp at the time the entry is added
entry.LastAccessed = utcNow;
CoherentState coherentState = _coherentState; // Clear() can update the reference in the meantime
if (coherentState._entries.TryGetValue(entry.Key, out CacheEntry? priorEntry))
{
priorEntry.SetExpired(EvictionReason.Replaced);
}
if (entry.CheckExpired(utcNow))
{
entry.InvokeEvictionCallbacks();
if (priorEntry != null)
{
coherentState.RemoveEntry(priorEntry, _options);
}
}
else if (!UpdateCacheSizeExceedsCapacity(entry, coherentState))
{
bool entryAdded;
if (priorEntry == null)
{
// Try to add the new entry if no previous entries exist.
entryAdded = coherentState._entries.TryAdd(entry.Key, entry);
}
else
{
// Try to update with the new entry if a previous entries exist.
entryAdded = coherentState._entries.TryUpdate(entry.Key, entry, priorEntry);
if (entryAdded)
{
if (_options.HasSizeLimit)
{
// The prior entry was removed, decrease the by the prior entry's size
Interlocked.Add(ref coherentState._cacheSize, -priorEntry.Size);
}
}
else
{
// The update will fail if the previous entry was removed after retrival.
// Adding the new entry will succeed only if no entry has been added since.
// This guarantees removing an old entry does not prevent adding a new entry.
entryAdded = coherentState._entries.TryAdd(entry.Key, entry);
}
}
if (entryAdded)
{
entry.AttachTokens();
}
else
{
if (_options.HasSizeLimit)
{
// Entry could not be added, reset cache size
Interlocked.Add(ref coherentState._cacheSize, -entry.Size);
}
entry.SetExpired(EvictionReason.Replaced);
entry.InvokeEvictionCallbacks();
}
priorEntry?.InvokeEvictionCallbacks();
}
else
{
entry.SetExpired(EvictionReason.Capacity);
TriggerOvercapacityCompaction();
entry.InvokeEvictionCallbacks();
if (priorEntry != null)
{
coherentState.RemoveEntry(priorEntry, _options);
}
}
StartScanForExpiredItemsIfNeeded(utcNow);
}
/// <inheritdoc />
public bool TryGetValue(object key, out object? result)
{
ThrowHelper.ThrowIfNull(key);
CheckDisposed();
DateTime utcNow = UtcNow;
CoherentState coherentState = _coherentState; // Clear() can update the reference in the meantime
if (coherentState._entries.TryGetValue(key, out CacheEntry? tmp))
{
CacheEntry entry = tmp;
// Check if expired due to expiration tokens, timers, etc. and if so, remove it.
// Allow a stale Replaced value to be returned due to concurrent calls to SetExpired during SetEntry.
if (!entry.CheckExpired(utcNow) || entry.EvictionReason == EvictionReason.Replaced)
{
entry.LastAccessed = utcNow;
result = entry.Value;
if (TrackLinkedCacheEntries)
{
// When this entry is retrieved in the scope of creating another entry,
// that entry needs a copy of these expiration tokens.
entry.PropagateOptionsToCurrent();
}
StartScanForExpiredItemsIfNeeded(utcNow);
// Hit
if (_allStats is not null)
{
if (IntPtr.Size == 4)
Interlocked.Increment(ref GetStats().Hits);
else
GetStats().Hits++;
}
return true;
}
else
{
// TODO: For efficiency queue this up for batch removal
coherentState.RemoveEntry(entry, _options);
}
}
StartScanForExpiredItemsIfNeeded(utcNow);
result = null;
// Miss
if (_allStats is not null)
{
if (IntPtr.Size == 4)
Interlocked.Increment(ref GetStats().Misses);
else
GetStats().Misses++;
}
return false;
}
/// <inheritdoc />
public void Remove(object key)
{
ThrowHelper.ThrowIfNull(key);
CheckDisposed();
CoherentState coherentState = _coherentState; // Clear() can update the reference in the meantime
if (coherentState._entries.TryRemove(key, out CacheEntry? entry))
{
if (_options.HasSizeLimit)
{
Interlocked.Add(ref coherentState._cacheSize, -entry.Size);
}
entry.SetExpired(EvictionReason.Removed);
entry.InvokeEvictionCallbacks();
}
StartScanForExpiredItemsIfNeeded(UtcNow);
}
/// <summary>
/// Removes all keys and values from the cache.
/// </summary>
public void Clear()
{
CheckDisposed();
CoherentState oldState = Interlocked.Exchange(ref _coherentState, new CoherentState());
foreach (KeyValuePair<object, CacheEntry> entry in oldState._entries)
{
entry.Value.SetExpired(EvictionReason.Removed);
entry.Value.InvokeEvictionCallbacks();
}
}
/// <summary>
/// Gets a snapshot of the current statistics for the memory cache.
/// </summary>
/// <returns>Returns <see langword="null"/> if statistics are not being tracked because <see cref="MemoryCacheOptions.TrackStatistics" /> is <see langword="false"/>.</returns>
public MemoryCacheStatistics? GetCurrentStatistics()
{
if (_allStats is not null)
{
(long hit, long miss) sumTotal = Sum();
return new MemoryCacheStatistics()
{
TotalMisses = sumTotal.miss,
TotalHits = sumTotal.hit,
CurrentEntryCount = Count,
CurrentEstimatedSize = _options.SizeLimit.HasValue ? Size : null
};
}
return null;
}
internal void EntryExpired(CacheEntry entry)
{
// TODO: For efficiency consider processing these expirations in batches.
_coherentState.RemoveEntry(entry, _options);
StartScanForExpiredItemsIfNeeded(UtcNow);
}
// Called by multiple actions to see how long it's been since we last checked for expired items.
// If sufficient time has elapsed then a scan is initiated on a background task.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void StartScanForExpiredItemsIfNeeded(DateTime utcNow)
{
if (_options.ExpirationScanFrequency < utcNow - _lastExpirationScan)
{
ScheduleTask(utcNow);
}
void ScheduleTask(DateTime utcNow)
{
_lastExpirationScan = utcNow;
Task.Factory.StartNew(state => ((MemoryCache)state!).ScanForExpiredItems(), this,
CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
}
private (long, long) Sum()
{
lock (_allStats!)
{
long hits = _accumulatedStats!.Hits;
long misses = _accumulatedStats.Misses;
foreach (WeakReference<Stats> wr in _allStats)
{
if (wr.TryGetTarget(out Stats? stats))
{
hits += Interlocked.Read(ref stats.Hits);
misses += Interlocked.Read(ref stats.Misses);
}
}
return (hits, misses);
}
}
private Stats GetStats() => _stats!.Value!;
internal sealed class Stats
{
private readonly MemoryCache? _memoryCache;
public long Hits;
public long Misses;
public Stats() { }
public Stats(MemoryCache memoryCache)
{
_memoryCache = memoryCache;
_memoryCache.AddToStats(this);
}
~Stats() => _memoryCache?.RemoveFromStats(this);
}
private void RemoveFromStats(Stats current)
{
lock (_allStats!)
{
for (int i = 0; i < _allStats.Count; i++)
{
if (_allStats[i].TryGetTarget(out Stats? stats) && stats == current)
{
_allStats.RemoveAt(i);
break;
}
}
_accumulatedStats!.Hits += Interlocked.Read(ref current.Hits);
_accumulatedStats.Misses += Interlocked.Read(ref current.Misses);
_allStats.TrimExcess();
}
}
private void AddToStats(Stats current)
{
lock (_allStats!)
{
_allStats.Add(new WeakReference<Stats>(current));
}
}
private void ScanForExpiredItems()
{
DateTime utcNow = _lastExpirationScan = UtcNow;
CoherentState coherentState = _coherentState; // Clear() can update the reference in the meantime
foreach (KeyValuePair<object, CacheEntry> item in coherentState._entries)
{
CacheEntry entry = item.Value;
if (entry.CheckExpired(utcNow))
{
coherentState.RemoveEntry(entry, _options);
}
}
}
private bool UpdateCacheSizeExceedsCapacity(CacheEntry entry, CoherentState coherentState)
{
long sizeLimit = _options.SizeLimitValue;
if (sizeLimit < 0)
{
return false;
}
long sizeRead = coherentState.Size;
for (int i = 0; i < 100; i++)
{
long newSize = sizeRead + entry.Size;
if ((ulong)newSize > (ulong)sizeLimit)
{
// Overflow occurred, return true without updating the cache size
return true;
}
long original = Interlocked.CompareExchange(ref coherentState._cacheSize, newSize, sizeRead);
if (sizeRead == original)
{
return false;
}
sizeRead = original;
}
return true;
}
private void TriggerOvercapacityCompaction()
{
if (_logger.IsEnabled(LogLevel.Debug))
_logger.LogDebug("Overcapacity compaction triggered");
// Spawn background thread for compaction
ThreadPool.QueueUserWorkItem(s => ((MemoryCache)s!).OvercapacityCompaction(), this);
}
private void OvercapacityCompaction()
{
CoherentState coherentState = _coherentState; // Clear() can update the reference in the meantime
long currentSize = coherentState.Size;
if (_logger.IsEnabled(LogLevel.Debug))
_logger.LogDebug($"Overcapacity compaction executing. Current size {currentSize}");
long sizeLimit = _options.SizeLimitValue;
if (sizeLimit >= 0)
{
long lowWatermark = sizeLimit - (long)(sizeLimit * _options.CompactionPercentage);
if (currentSize > lowWatermark)
{
Compact(currentSize - (long)lowWatermark, entry => entry.Size, coherentState);
}
}
if (_logger.IsEnabled(LogLevel.Debug))
_logger.LogDebug($"Overcapacity compaction executed. New size {coherentState.Size}");
}
/// Remove at least the given percentage (0.10 for 10%) of the total entries (or estimated memory?), according to the following policy:
/// 1. Remove all expired items.
/// 2. Bucket by CacheItemPriority.
/// 3. Least recently used objects.
/// ?. Items with the soonest absolute expiration.
/// ?. Items with the soonest sliding expiration.
/// ?. Larger objects - estimated by object graph size, inaccurate.
public void Compact(double percentage)
{
CoherentState coherentState = _coherentState; // Clear() can update the reference in the meantime
int removalCountTarget = (int)(coherentState.Count * percentage);
Compact(removalCountTarget, _ => 1, coherentState);
}
private void Compact(long removalSizeTarget, Func<CacheEntry, long> computeEntrySize, CoherentState coherentState)
{
var entriesToRemove = new List<CacheEntry>();
// cache LastAccessed outside of the CacheEntry so it is stable during compaction
var lowPriEntries = new List<(CacheEntry entry, DateTimeOffset lastAccessed)>();
var normalPriEntries = new List<(CacheEntry entry, DateTimeOffset lastAccessed)>();
var highPriEntries = new List<(CacheEntry entry, DateTimeOffset lastAccessed)>();
long removedSize = 0;
// Sort items by expired & priority status
DateTime utcNow = UtcNow;
foreach (KeyValuePair<object, CacheEntry> item in coherentState._entries)
{
CacheEntry entry = item.Value;
if (entry.CheckExpired(utcNow))
{
entriesToRemove.Add(entry);
removedSize += computeEntrySize(entry);
}
else
{
switch (entry.Priority)
{
case CacheItemPriority.Low:
lowPriEntries.Add((entry, entry.LastAccessed));
break;
case CacheItemPriority.Normal:
normalPriEntries.Add((entry, entry.LastAccessed));
break;
case CacheItemPriority.High:
highPriEntries.Add((entry, entry.LastAccessed));
break;
case CacheItemPriority.NeverRemove:
break;
default:
throw new NotSupportedException("Not implemented: " + entry.Priority);
}
}
}
ExpirePriorityBucket(ref removedSize, removalSizeTarget, computeEntrySize, entriesToRemove, lowPriEntries);
ExpirePriorityBucket(ref removedSize, removalSizeTarget, computeEntrySize, entriesToRemove, normalPriEntries);
ExpirePriorityBucket(ref removedSize, removalSizeTarget, computeEntrySize, entriesToRemove, highPriEntries);
foreach (CacheEntry entry in entriesToRemove)
{
coherentState.RemoveEntry(entry, _options);
}
// Policy:
// 1. Least recently used objects.
// ?. Items with the soonest absolute expiration.
// ?. Items with the soonest sliding expiration.
// ?. Larger objects - estimated by object graph size, inaccurate.
static void ExpirePriorityBucket(ref long removedSize, long removalSizeTarget, Func<CacheEntry, long> computeEntrySize, List<CacheEntry> entriesToRemove, List<(CacheEntry Entry, DateTimeOffset LastAccessed)> priorityEntries)
{
// Do we meet our quota by just removing expired entries?
if (removalSizeTarget <= removedSize)
{
// No-op, we've met quota
return;
}
// Expire enough entries to reach our goal
// TODO: Refine policy
// LRU
priorityEntries.Sort(static (e1, e2) => e1.LastAccessed.CompareTo(e2.LastAccessed));
foreach ((CacheEntry entry, _) in priorityEntries)
{
entry.SetExpired(EvictionReason.Capacity);
entriesToRemove.Add(entry);
removedSize += computeEntrySize(entry);
if (removalSizeTarget <= removedSize)
{
break;
}
}
}
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
_stats?.Dispose();
GC.SuppressFinalize(this);
}
_disposed = true;
}
}
private void CheckDisposed()
{
if (_disposed)
{
Throw();
}
[DoesNotReturn]
static void Throw() => throw new ObjectDisposedException(typeof(MemoryCache).FullName);
}
private static void ValidateCacheKey(object key)
{
ThrowHelper.ThrowIfNull(key);
}
private sealed class CoherentState
{
internal ConcurrentDictionary<object, CacheEntry> _entries = new ConcurrentDictionary<object, CacheEntry>();
internal long _cacheSize;
private ICollection<KeyValuePair<object, CacheEntry>> EntriesCollection => _entries;
internal int Count => _entries.Count;
internal long Size => Volatile.Read(ref _cacheSize);
internal void RemoveEntry(CacheEntry entry, MemoryCacheOptions options)
{
if (EntriesCollection.Remove(new KeyValuePair<object, CacheEntry>(entry.Key, entry)))
{
if (options.SizeLimit.HasValue)
{
Interlocked.Add(ref _cacheSize, -entry.Size);
}
entry.InvokeEvictionCallbacks();
}
}
}
}
}