Files
Umbraco-CMS/src/Umbraco.Core/Cache/ObjectCacheAppCache.cs

334 lines
12 KiB
C#
Raw Normal View History

2018-06-29 19:52:40 +02:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Caching;
using System.Text.RegularExpressions;
using System.Threading;
using Umbraco.Extensions;
2018-06-29 19:52:40 +02:00
namespace Umbraco.Cms.Core.Cache
2018-06-29 19:52:40 +02:00
{
/// <summary>
2019-01-18 07:56:38 +01:00
/// Implements <see cref="IAppPolicyCache"/> on top of a <see cref="ObjectCache"/>.
2018-06-29 19:52:40 +02:00
/// </summary>
2019-01-18 07:56:38 +01:00
public class ObjectCacheAppCache : IAppPolicyCache
2018-06-29 19:52:40 +02:00
{
private readonly ReaderWriterLockSlim _locker = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
/// <summary>
2019-01-17 11:01:23 +01:00
/// Initializes a new instance of the <see cref="ObjectCacheAppCache"/>.
2018-06-29 19:52:40 +02:00
/// </summary>
public ObjectCacheAppCache()
2018-06-29 19:52:40 +02:00
{
2019-01-17 11:01:23 +01:00
// the MemoryCache is created with name "in-memory". That name is
// used to retrieve configuration options. It does not identify the memory cache, i.e.
// each instance of this class has its own, independent, memory cache.
2018-06-29 19:52:40 +02:00
MemoryCache = new MemoryCache("in-memory");
}
2019-01-17 11:01:23 +01:00
/// <summary>
/// Gets the internal memory cache, for tests only!
/// </summary>
public ObjectCache MemoryCache { get; private set; }
2019-01-17 11:01:23 +01:00
/// <inheritdoc />
public object Get(string key)
{
Lazy<object> result;
try
{
_locker.EnterReadLock();
result = MemoryCache.Get(key) as Lazy<object>; // null if key not found
}
finally
{
if (_locker.IsReadLockHeld)
_locker.ExitReadLock();
}
return result == null ? null : SafeLazy.GetSafeLazyValue(result); // return exceptions as null
2019-01-17 11:01:23 +01:00
}
/// <inheritdoc />
public object Get(string key, Func<object> factory)
{
return Get(key, factory, null);
}
/// <inheritdoc />
public IEnumerable<object> SearchByKey(string keyStartsWith)
{
KeyValuePair<string, object>[] entries;
try
{
_locker.EnterReadLock();
entries = MemoryCache
.Where(x => x.Key.InvariantStartsWith(keyStartsWith))
.ToArray(); // evaluate while locked
}
finally
{
if (_locker.IsReadLockHeld)
_locker.ExitReadLock();
}
return entries
.Select(x => SafeLazy.GetSafeLazyValue((Lazy<object>)x.Value)) // return exceptions as null
2019-01-17 11:01:23 +01:00
.Where(x => x != null) // backward compat, don't store null values in the cache
.ToList();
}
2018-06-29 19:52:40 +02:00
2019-01-17 11:01:23 +01:00
/// <inheritdoc />
public IEnumerable<object> SearchByRegex(string regex)
{
var compiled = new Regex(regex, RegexOptions.Compiled);
KeyValuePair<string, object>[] entries;
try
{
_locker.EnterReadLock();
entries = MemoryCache
.Where(x => compiled.IsMatch(x.Key))
.ToArray(); // evaluate while locked
}
finally
{
if (_locker.IsReadLockHeld)
_locker.ExitReadLock();
}
return entries
.Select(x => SafeLazy.GetSafeLazyValue((Lazy<object>)x.Value)) // return exceptions as null
2019-01-17 11:01:23 +01:00
.Where(x => x != null) // backward compat, don't store null values in the cache
.ToList();
}
/// <inheritdoc />
public object Get(string key, Func<object> factory, TimeSpan? timeout, bool isSliding = false, string[] dependentFiles = null)
2019-01-17 11:01:23 +01:00
{
2019-01-18 08:14:08 +01:00
// see notes in HttpRuntimeAppCache
2019-01-17 11:01:23 +01:00
Lazy<object> result;
using (var lck = new UpgradeableReadLock(_locker))
{
result = MemoryCache.Get(key) as Lazy<object>;
if (result == null || SafeLazy.GetSafeLazyValue(result, true) == null) // get non-created as NonCreatedValue & exceptions as null
2019-01-17 11:01:23 +01:00
{
result = SafeLazy.GetSafeLazy(factory);
var policy = GetPolicy(timeout, isSliding, dependentFiles);
2019-01-17 11:01:23 +01:00
lck.UpgradeToWriteLock();
//NOTE: This does an add or update
MemoryCache.Set(key, result, policy);
}
}
//return result.Value;
var value = result.Value; // will not throw (safe lazy)
if (value is SafeLazy.ExceptionHolder eh) eh.Exception.Throw(); // throw once!
2019-01-17 11:01:23 +01:00
return value;
}
/// <inheritdoc />
public void Insert(string key, Func<object> factory, TimeSpan? timeout = null, bool isSliding = false, string[] dependentFiles = null)
2019-01-17 11:01:23 +01:00
{
// NOTE - here also we must insert a Lazy<object> but we can evaluate it right now
// and make sure we don't store a null value.
var result = SafeLazy.GetSafeLazy(factory);
2019-01-17 11:01:23 +01:00
var value = result.Value; // force evaluation now
if (value == null) return; // do not store null values (backward compat)
var policy = GetPolicy(timeout, isSliding, dependentFiles);
2019-01-17 11:01:23 +01:00
//NOTE: This does an add or update
MemoryCache.Set(key, result, policy);
}
/// <inheritdoc />
public virtual void Clear()
2018-06-29 19:52:40 +02:00
{
try
{
_locker.EnterWriteLock();
MemoryCache.DisposeIfDisposable();
MemoryCache = new MemoryCache("in-memory");
}
finally
{
if (_locker.IsWriteLockHeld)
2018-06-29 19:52:40 +02:00
_locker.ExitWriteLock();
}
}
2019-01-17 11:01:23 +01:00
/// <inheritdoc />
public virtual void Clear(string key)
2018-06-29 19:52:40 +02:00
{
try
{
_locker.EnterWriteLock();
if (MemoryCache[key] == null) return;
MemoryCache.Remove(key);
}
finally
{
if (_locker.IsWriteLockHeld)
_locker.ExitWriteLock();
}
}
2019-01-17 11:01:23 +01:00
/// <inheritdoc />
public virtual void ClearOfType(Type type)
2018-06-29 19:52:40 +02:00
{
if (type == null) return;
var isInterface = type.IsInterface;
try
{
_locker.EnterWriteLock();
foreach (var key in MemoryCache
.Where(x =>
{
// x.Value is Lazy<object> and not null, its value may be null
// remove null values as well, does not hurt
// get non-created as NonCreatedValue & exceptions as null
var value = SafeLazy.GetSafeLazyValue((Lazy<object>)x.Value, true);
2018-06-29 19:52:40 +02:00
// if T is an interface remove anything that implements that interface
// otherwise remove exact types (not inherited types)
return value == null || (isInterface ? (type.IsInstanceOfType(value)) : (value.GetType() == type));
})
.Select(x => x.Key)
.ToArray()) // ToArray required to remove
MemoryCache.Remove(key);
}
finally
{
if (_locker.IsWriteLockHeld)
_locker.ExitWriteLock();
}
}
2019-01-17 11:01:23 +01:00
/// <inheritdoc />
public virtual void ClearOfType<T>()
2018-06-29 19:52:40 +02:00
{
try
{
_locker.EnterWriteLock();
2019-01-17 11:01:23 +01:00
var typeOfT = typeof(T);
2018-06-29 19:52:40 +02:00
var isInterface = typeOfT.IsInterface;
foreach (var key in MemoryCache
.Where(x =>
{
// x.Value is Lazy<object> and not null, its value may be null
// remove null values as well, does not hurt
// get non-created as NonCreatedValue & exceptions as null
var value = SafeLazy.GetSafeLazyValue((Lazy<object>)x.Value, true);
2018-06-29 19:52:40 +02:00
// if T is an interface remove anything that implements that interface
// otherwise remove exact types (not inherited types)
return value == null || (isInterface ? (value is T) : (value.GetType() == typeOfT));
})
.Select(x => x.Key)
.ToArray()) // ToArray required to remove
MemoryCache.Remove(key);
}
finally
{
if (_locker.IsWriteLockHeld)
_locker.ExitWriteLock();
}
}
2019-01-17 11:01:23 +01:00
/// <inheritdoc />
public virtual void ClearOfType<T>(Func<string, T, bool> predicate)
2018-06-29 19:52:40 +02:00
{
try
{
_locker.EnterWriteLock();
var typeOfT = typeof(T);
var isInterface = typeOfT.IsInterface;
foreach (var key in MemoryCache
.Where(x =>
{
// x.Value is Lazy<object> and not null, its value may be null
// remove null values as well, does not hurt
// get non-created as NonCreatedValue & exceptions as null
var value = SafeLazy.GetSafeLazyValue((Lazy<object>)x.Value, true);
2018-06-29 19:52:40 +02:00
if (value == null) return true;
// if T is an interface remove anything that implements that interface
// otherwise remove exact types (not inherited types)
return (isInterface ? (value is T) : (value.GetType() == typeOfT))
&& predicate(x.Key, (T)value);
})
.Select(x => x.Key)
.ToArray()) // ToArray required to remove
MemoryCache.Remove(key);
}
finally
{
if (_locker.IsWriteLockHeld)
_locker.ExitWriteLock();
}
}
2019-01-17 11:01:23 +01:00
/// <inheritdoc />
public virtual void ClearByKey(string keyStartsWith)
2018-06-29 19:52:40 +02:00
{
try
{
_locker.EnterWriteLock();
foreach (var key in MemoryCache
.Where(x => x.Key.InvariantStartsWith(keyStartsWith))
.Select(x => x.Key)
.ToArray()) // ToArray required to remove
MemoryCache.Remove(key);
}
finally
{
if (_locker.IsWriteLockHeld)
_locker.ExitWriteLock();
}
}
2019-01-17 11:01:23 +01:00
/// <inheritdoc />
public virtual void ClearByRegex(string regex)
2018-06-29 19:52:40 +02:00
{
2019-01-17 11:01:23 +01:00
var compiled = new Regex(regex, RegexOptions.Compiled);
2018-06-29 19:52:40 +02:00
try
{
_locker.EnterWriteLock();
foreach (var key in MemoryCache
2019-01-17 11:01:23 +01:00
.Where(x => compiled.IsMatch(x.Key))
2018-06-29 19:52:40 +02:00
.Select(x => x.Key)
.ToArray()) // ToArray required to remove
MemoryCache.Remove(key);
}
finally
{
if (_locker.IsWriteLockHeld)
_locker.ExitWriteLock();
}
}
private static CacheItemPolicy GetPolicy(TimeSpan? timeout = null, bool isSliding = false, string[] dependentFiles = null)
2018-06-29 19:52:40 +02:00
{
var absolute = isSliding ? ObjectCache.InfiniteAbsoluteExpiration : (timeout == null ? ObjectCache.InfiniteAbsoluteExpiration : DateTime.Now.Add(timeout.Value));
var sliding = isSliding == false ? ObjectCache.NoSlidingExpiration : (timeout ?? ObjectCache.NoSlidingExpiration);
var policy = new CacheItemPolicy
{
AbsoluteExpiration = absolute,
SlidingExpiration = sliding
};
if (dependentFiles != null && dependentFiles.Any())
{
policy.ChangeMonitors.Add(new HostFileChangeMonitor(dependentFiles.ToList()));
}
return policy;
}
}
}