-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
CacheEntry.cs
372 lines (320 loc) · 13 KB
/
CacheEntry.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
// 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.Generic;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Primitives;
namespace Microsoft.Extensions.Caching.Memory
{
internal class CacheEntry : ICacheEntry
{
private static readonly Action<object> ExpirationCallback = ExpirationTokensExpired;
private readonly object _lock = new object();
private readonly MemoryCache _cache;
private IList<IDisposable> _expirationTokenRegistrations;
private IList<PostEvictionCallbackRegistration> _postEvictionCallbacks;
private IList<IChangeToken> _expirationTokens;
private TimeSpan? _absoluteExpirationRelativeToNow;
private TimeSpan? _slidingExpiration;
private long? _size;
private CacheEntry _previous; // this field is not null only before the entry is added to the cache
private object _value;
private int _state; // actually a [Flag] enum called "State"
internal CacheEntry(object key, MemoryCache memoryCache)
{
Key = key ?? throw new ArgumentNullException(nameof(key));
_cache = memoryCache ?? throw new ArgumentNullException(nameof(memoryCache));
_previous = CacheEntryHelper.EnterScope(this);
}
/// <summary>
/// Gets or sets an absolute expiration date for the cache entry.
/// </summary>
public DateTimeOffset? AbsoluteExpiration { get; set; }
/// <summary>
/// Gets or sets an absolute expiration time, relative to now.
/// </summary>
public TimeSpan? AbsoluteExpirationRelativeToNow
{
get => _absoluteExpirationRelativeToNow;
set
{
// this method does not set AbsoluteExpiration as it would require calling Clock.UtcNow twice:
// once here and once in MemoryCache.SetEntry
if (value <= TimeSpan.Zero)
{
throw new ArgumentOutOfRangeException(
nameof(AbsoluteExpirationRelativeToNow),
value,
"The relative expiration value must be positive.");
}
_absoluteExpirationRelativeToNow = value;
}
}
/// <summary>
/// Gets or sets how long a cache entry can be inactive (e.g. not accessed) before it will be removed.
/// This will not extend the entry lifetime beyond the absolute expiration (if set).
/// </summary>
public TimeSpan? SlidingExpiration
{
get => _slidingExpiration;
set
{
if (value <= TimeSpan.Zero)
{
throw new ArgumentOutOfRangeException(
nameof(SlidingExpiration),
value,
"The sliding expiration value must be positive.");
}
_slidingExpiration = value;
}
}
/// <summary>
/// Gets the <see cref="IChangeToken"/> instances which cause the cache entry to expire.
/// </summary>
public IList<IChangeToken> ExpirationTokens => _expirationTokens ??= new List<IChangeToken>();
/// <summary>
/// Gets or sets the callbacks will be fired after the cache entry is evicted from the cache.
/// </summary>
public IList<PostEvictionCallbackRegistration> PostEvictionCallbacks => _postEvictionCallbacks ??= new List<PostEvictionCallbackRegistration>();
/// <summary>
/// Gets or sets the priority for keeping the cache entry in the cache during a
/// memory pressure triggered cleanup. The default is <see cref="CacheItemPriority.Normal"/>.
/// </summary>
public CacheItemPriority Priority { get; set; } = CacheItemPriority.Normal;
/// <summary>
/// Gets or sets the size of the cache entry value.
/// </summary>
public long? Size
{
get => _size;
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value), value, $"{nameof(value)} must be non-negative.");
}
_size = value;
}
}
public object Key { get; private set; }
public object Value
{
get => _value;
set
{
_value = value;
IsValueSet = true;
}
}
internal DateTimeOffset LastAccessed { get; set; }
internal EvictionReason EvictionReason { get; private set; }
private bool IsDisposed { get => ((State)_state).HasFlag(State.IsDisposed); set => Set(State.IsDisposed, value); }
private bool IsExpired { get => ((State)_state).HasFlag(State.IsExpired); set => Set(State.IsExpired, value); }
private bool IsValueSet { get => ((State)_state).HasFlag(State.IsValueSet); set => Set(State.IsValueSet, value); }
public void Dispose()
{
if (!IsDisposed)
{
IsDisposed = true;
// Don't commit or propagate options if the CacheEntry Value was never set.
// We assume an exception occurred causing the caller to not set the Value successfully,
// so don't use this entry.
if (IsValueSet)
{
_cache.SetEntry(this);
if (_previous != null && CanPropagateOptions())
{
PropagateOptions(_previous);
}
}
CacheEntryHelper.ExitScope(this, _previous);
_previous = null; // we don't want to root unnecessary objects
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal bool CheckExpired(in DateTimeOffset now) => IsExpired || CheckForExpiredTime(now) || CheckForExpiredTokens();
internal void SetExpired(EvictionReason reason)
{
if (EvictionReason == EvictionReason.None)
{
EvictionReason = reason;
}
IsExpired = true;
DetachTokens();
}
private bool CheckForExpiredTime(in DateTimeOffset now)
{
if (!AbsoluteExpiration.HasValue && !_slidingExpiration.HasValue)
{
return false;
}
return FullCheck(now);
bool FullCheck(in DateTimeOffset offset)
{
if (AbsoluteExpiration.HasValue && AbsoluteExpiration.Value <= offset)
{
SetExpired(EvictionReason.Expired);
return true;
}
if (_slidingExpiration.HasValue
&& (offset - LastAccessed) >= _slidingExpiration)
{
SetExpired(EvictionReason.Expired);
return true;
}
return false;
}
}
private bool CheckForExpiredTokens()
{
if (_expirationTokens == null)
{
return false;
}
return CheckTokens();
bool CheckTokens()
{
for (int i = 0; i < _expirationTokens.Count; i++)
{
IChangeToken expiredToken = _expirationTokens[i];
if (expiredToken.HasChanged)
{
SetExpired(EvictionReason.TokenExpired);
return true;
}
}
return false;
}
}
internal void AttachTokens()
{
if (_expirationTokens != null)
{
lock (_lock)
{
for (int i = 0; i < _expirationTokens.Count; i++)
{
IChangeToken expirationToken = _expirationTokens[i];
if (expirationToken.ActiveChangeCallbacks)
{
if (_expirationTokenRegistrations == null)
{
_expirationTokenRegistrations = new List<IDisposable>(1);
}
IDisposable registration = expirationToken.RegisterChangeCallback(ExpirationCallback, this);
_expirationTokenRegistrations.Add(registration);
}
}
}
}
}
private static void ExpirationTokensExpired(object obj)
{
// start a new thread to avoid issues with callbacks called from RegisterChangeCallback
Task.Factory.StartNew(state =>
{
var entry = (CacheEntry)state;
entry.SetExpired(EvictionReason.TokenExpired);
entry._cache.EntryExpired(entry);
}, obj, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
private void DetachTokens()
{
// _expirationTokenRegistrations is not checked for null, because AttachTokens might initialize it under lock
lock (_lock)
{
IList<IDisposable> registrations = _expirationTokenRegistrations;
if (registrations != null)
{
_expirationTokenRegistrations = null;
for (int i = 0; i < registrations.Count; i++)
{
IDisposable registration = registrations[i];
registration.Dispose();
}
}
}
}
internal void InvokeEvictionCallbacks()
{
if (_postEvictionCallbacks != null)
{
Task.Factory.StartNew(state => InvokeCallbacks((CacheEntry)state), this,
CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
}
private static void InvokeCallbacks(CacheEntry entry)
{
IList<PostEvictionCallbackRegistration> callbackRegistrations = Interlocked.Exchange(ref entry._postEvictionCallbacks, null);
if (callbackRegistrations == null)
{
return;
}
for (int i = 0; i < callbackRegistrations.Count; i++)
{
PostEvictionCallbackRegistration registration = callbackRegistrations[i];
try
{
registration.EvictionCallback?.Invoke(entry.Key, entry.Value, entry.EvictionReason, registration.State);
}
catch (Exception e)
{
// This will be invoked on a background thread, don't let it throw.
entry._cache._logger.LogError(e, "EvictionCallback invoked failed");
}
}
}
// this simple check very often allows us to avoid expensive call to PropagateOptions(CacheEntryHelper.Current)
internal bool CanPropagateOptions() => _expirationTokens != null || AbsoluteExpiration.HasValue;
internal void PropagateOptions(CacheEntry parent)
{
if (parent == null)
{
return;
}
// Copy expiration tokens and AbsoluteExpiration to the cache entries hierarchy.
// We do this regardless of it gets cached because the tokens are associated with the value we'll return.
if (_expirationTokens != null)
{
lock (_lock)
{
lock (parent._lock)
{
foreach (IChangeToken expirationToken in _expirationTokens)
{
parent.AddExpirationToken(expirationToken);
}
}
}
}
if (AbsoluteExpiration.HasValue)
{
if (!parent.AbsoluteExpiration.HasValue || AbsoluteExpiration < parent.AbsoluteExpiration)
{
parent.AbsoluteExpiration = AbsoluteExpiration;
}
}
}
private void Set(State option, bool value)
{
int before, after;
do
{
before = _state;
after = value ? (_state | (int)option) : (_state & ~(int)option);
} while (Interlocked.CompareExchange(ref _state, after, before) != before);
}
[Flags]
private enum State
{
Default = 0,
IsValueSet = 1 << 0,
IsExpired = 1 << 1,
IsDisposed = 1 << 2,
}
}
}