diff --git a/src/Umbraco.Core/Cache/AppCaches.cs b/src/Umbraco.Core/Cache/AppCaches.cs index 7dd95624ef..6372bccbab 100644 --- a/src/Umbraco.Core/Cache/AppCaches.cs +++ b/src/Umbraco.Core/Cache/AppCaches.cs @@ -4,47 +4,41 @@ using System.Web; namespace Umbraco.Core.Cache { /// - /// Represents the application-wide caches. + /// Represents the application caches. /// public class AppCaches { /// - /// Initializes a new instance for use in the web + /// Initializes a new instance of the for use in a web application. /// public AppCaches() - : this( - new HttpRuntimeCacheProvider(HttpRuntime.Cache), - new StaticCacheProvider(), - new HttpRequestCacheProvider(), - new IsolatedRuntimeCache(t => new ObjectCacheRuntimeCacheProvider())) - { - } + : this(HttpRuntime.Cache) + { } /// - /// Initializes a new instance for use in the web + /// Initializes a new instance of the for use in a web application. /// public AppCaches(System.Web.Caching.Cache cache) : this( - new HttpRuntimeCacheProvider(cache), - new StaticCacheProvider(), - new HttpRequestCacheProvider(), - new IsolatedRuntimeCache(t => new ObjectCacheRuntimeCacheProvider())) - { - } + new WebCachingAppCache(cache), + new DictionaryCacheProvider(), + new HttpRequestAppCache(), + new IsolatedCaches(t => new ObjectCacheAppCache())) + { } /// - /// Initializes a new instance based on the provided providers + /// Initializes a new instance of the with cache providers. /// public AppCaches( - IRuntimeCacheProvider httpCacheProvider, - ICacheProvider staticCacheProvider, - ICacheProvider requestCacheProvider, - IsolatedRuntimeCache isolatedCacheManager) + IAppPolicedCache runtimeCache, + IAppCache staticCacheProvider, + IAppCache requestCache, + IsolatedCaches isolatedCaches) { - RuntimeCache = httpCacheProvider ?? throw new ArgumentNullException(nameof(httpCacheProvider)); + RuntimeCache = runtimeCache ?? throw new ArgumentNullException(nameof(runtimeCache)); StaticCache = staticCacheProvider ?? throw new ArgumentNullException(nameof(staticCacheProvider)); - RequestCache = requestCacheProvider ?? throw new ArgumentNullException(nameof(requestCacheProvider)); - IsolatedRuntimeCache = isolatedCacheManager ?? throw new ArgumentNullException(nameof(isolatedCacheManager)); + RequestCache = requestCache ?? throw new ArgumentNullException(nameof(requestCache)); + IsolatedCaches = isolatedCaches ?? throw new ArgumentNullException(nameof(isolatedCaches)); } /// @@ -54,7 +48,7 @@ namespace Umbraco.Core.Cache /// When used by repositories, all cache policies apply, but the underlying caches do not cache anything. /// Used by tests. /// - public static AppCaches Disabled { get; } = new AppCaches(NullCacheProvider.Instance, NullCacheProvider.Instance, NullCacheProvider.Instance, new IsolatedRuntimeCache(_ => NullCacheProvider.Instance)); + public static AppCaches Disabled { get; } = new AppCaches(NoAppCache.Instance, NoAppCache.Instance, NoAppCache.Instance, new IsolatedCaches(_ => NoAppCache.Instance)); /// /// Gets the special no-cache instance. @@ -63,27 +57,42 @@ namespace Umbraco.Core.Cache /// When used by repositories, all cache policies are bypassed. /// Used by repositories that do no cache. /// - public static AppCaches NoCache { get; } = new AppCaches(NullCacheProvider.Instance, NullCacheProvider.Instance, NullCacheProvider.Instance, new IsolatedRuntimeCache(_ => NullCacheProvider.Instance)); + public static AppCaches NoCache { get; } = new AppCaches(NoAppCache.Instance, NoAppCache.Instance, NoAppCache.Instance, new IsolatedCaches(_ => NoAppCache.Instance)); /// - /// Returns the current Request cache + /// Gets the per-request cache. /// - public ICacheProvider RequestCache { get; internal set; } + /// + /// The per-request caches works on top of the current HttpContext items. + /// fixme - what about non-web applications? + /// + public IAppCache RequestCache { get; } /// /// Returns the current Runtime cache /// - public ICacheProvider StaticCache { get; internal set; } + /// + /// fixme - what is this? why not use RuntimeCache? + /// + public IAppCache StaticCache { get; } /// - /// Returns the current Runtime cache + /// Gets the runtime cache. /// - public IRuntimeCacheProvider RuntimeCache { get; internal set; } + /// + /// The runtime cache is the main application cache. + /// + public IAppPolicedCache RuntimeCache { get; } /// - /// Returns the current Isolated Runtime cache manager + /// Gets the isolated caches. /// - public IsolatedRuntimeCache IsolatedRuntimeCache { get; internal set; } + /// + /// Isolated caches are used by e.g. repositories, to ensure that each cached entity + /// type has its own cache, so that lookups are fast and the repository does not need to + /// search through all keys on a global scale. + /// + public IsolatedCaches IsolatedCaches { get; } } diff --git a/src/Umbraco.Core/Cache/AppPolicedCacheDictionary.cs b/src/Umbraco.Core/Cache/AppPolicedCacheDictionary.cs new file mode 100644 index 0000000000..51cc3c4c53 --- /dev/null +++ b/src/Umbraco.Core/Cache/AppPolicedCacheDictionary.cs @@ -0,0 +1,74 @@ +using System; +using System.Collections.Concurrent; + +namespace Umbraco.Core.Cache +{ + /// + /// Provides a base class for implementing a dictionary of . + /// + /// The type of the dictionary key. + public abstract class AppPolicedCacheDictionary + { + private readonly ConcurrentDictionary _caches = new ConcurrentDictionary(); + + /// + /// Initializes a new instance of the class. + /// + /// + protected AppPolicedCacheDictionary(Func cacheFactory) + { + CacheFactory = cacheFactory; + } + + /// + /// Gets the internal cache factory, for tests only! + /// + internal readonly Func CacheFactory; + + /// + /// Gets or creates a cache. + /// + public IAppPolicedCache GetOrCreate(TKey key) + => _caches.GetOrAdd(key, k => CacheFactory(k)); + + /// + /// Tries to get a cache. + /// + public Attempt Get(TKey key) + => _caches.TryGetValue(key, out var cache) ? Attempt.Succeed(cache) : Attempt.Fail(); + + /// + /// Removes a cache. + /// + public void Remove(TKey key) + { + _caches.TryRemove(key, out _); + } + + /// + /// Removes all caches. + /// + public void RemoveAll() + { + _caches.Clear(); + } + + /// + /// Clears a cache. + /// + public void ClearCache(TKey key) + { + if (_caches.TryGetValue(key, out var cache)) + cache.Clear(); + } + + /// + /// Clears all caches. + /// + public void ClearAllCaches() + { + foreach (var cache in _caches.Values) + cache.Clear(); + } + } +} \ No newline at end of file diff --git a/src/Umbraco.Core/Cache/CacheProviderExtensions.cs b/src/Umbraco.Core/Cache/CacheProviderExtensions.cs index e42cb4d9ad..0e41b981fb 100644 --- a/src/Umbraco.Core/Cache/CacheProviderExtensions.cs +++ b/src/Umbraco.Core/Cache/CacheProviderExtensions.cs @@ -10,7 +10,7 @@ namespace Umbraco.Core.Cache /// public static class CacheProviderExtensions { - public static T GetCacheItem(this IRuntimeCacheProvider provider, + public static T GetCacheItem(this IAppPolicedCache provider, string cacheKey, Func getCacheItem, TimeSpan? timeout, @@ -19,11 +19,11 @@ namespace Umbraco.Core.Cache CacheItemRemovedCallback removedCallback = null, string[] dependentFiles = null) { - var result = provider.GetCacheItem(cacheKey, () => getCacheItem(), timeout, isSliding, priority, removedCallback, dependentFiles); + var result = provider.Get(cacheKey, () => getCacheItem(), timeout, isSliding, priority, removedCallback, dependentFiles); return result == null ? default(T) : result.TryConvertTo().Result; } - public static void InsertCacheItem(this IRuntimeCacheProvider provider, + public static void InsertCacheItem(this IAppPolicedCache provider, string cacheKey, Func getCacheItem, TimeSpan? timeout = null, @@ -32,24 +32,24 @@ namespace Umbraco.Core.Cache CacheItemRemovedCallback removedCallback = null, string[] dependentFiles = null) { - provider.InsertCacheItem(cacheKey, () => getCacheItem(), timeout, isSliding, priority, removedCallback, dependentFiles); + provider.Insert(cacheKey, () => getCacheItem(), timeout, isSliding, priority, removedCallback, dependentFiles); } - public static IEnumerable GetCacheItemsByKeySearch(this ICacheProvider provider, string keyStartsWith) + public static IEnumerable GetCacheItemsByKeySearch(this IAppCache provider, string keyStartsWith) { - var result = provider.GetCacheItemsByKeySearch(keyStartsWith); + var result = provider.SearchByKey(keyStartsWith); return result.Select(x => x.TryConvertTo().Result); } - public static IEnumerable GetCacheItemsByKeyExpression(this ICacheProvider provider, string regexString) + public static IEnumerable GetCacheItemsByKeyExpression(this IAppCache provider, string regexString) { - var result = provider.GetCacheItemsByKeyExpression(regexString); + var result = provider.SearchByRegex(regexString); return result.Select(x => x.TryConvertTo().Result); } - public static T GetCacheItem(this ICacheProvider provider, string cacheKey) + public static T GetCacheItem(this IAppCache provider, string cacheKey) { - var result = provider.GetCacheItem(cacheKey); + var result = provider.Get(cacheKey); if (result == null) { return default(T); @@ -57,9 +57,9 @@ namespace Umbraco.Core.Cache return result.TryConvertTo().Result; } - public static T GetCacheItem(this ICacheProvider provider, string cacheKey, Func getCacheItem) + public static T GetCacheItem(this IAppCache provider, string cacheKey, Func getCacheItem) { - var result = provider.GetCacheItem(cacheKey, () => getCacheItem()); + var result = provider.Get(cacheKey, () => getCacheItem()); if (result == null) { return default(T); diff --git a/src/Umbraco.Core/Cache/CacheRefresherBase.cs b/src/Umbraco.Core/Cache/CacheRefresherBase.cs index 5e6ec593af..bfa16ff3fa 100644 --- a/src/Umbraco.Core/Cache/CacheRefresherBase.cs +++ b/src/Umbraco.Core/Cache/CacheRefresherBase.cs @@ -102,7 +102,7 @@ namespace Umbraco.Core.Cache protected void ClearAllIsolatedCacheByEntityType() where TEntity : class, IEntity { - AppCaches.IsolatedRuntimeCache.ClearCache(); + AppCaches.IsolatedCaches.ClearCache(); } /// diff --git a/src/Umbraco.Core/Cache/DeepCloneAppCache.cs b/src/Umbraco.Core/Cache/DeepCloneAppCache.cs new file mode 100644 index 0000000000..cdc66f1db7 --- /dev/null +++ b/src/Umbraco.Core/Cache/DeepCloneAppCache.cs @@ -0,0 +1,157 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web.Caching; +using Umbraco.Core.Models; +using Umbraco.Core.Models.Entities; + +namespace Umbraco.Core.Cache +{ + /// + /// Implements by wrapping an inner other + /// instance, and ensuring that all inserts and returns are deep cloned copies of the cache item, + /// when the item is deep-cloneable. + /// + internal class DeepCloneAppCache : IAppPolicedCache + { + /// + /// Initializes a new instance of the class. + /// + public DeepCloneAppCache(IAppPolicedCache innerCache) + { + var type = typeof (DeepCloneAppCache); + + if (innerCache.GetType() == type) + throw new InvalidOperationException($"A {type} cannot wrap another instance of itself."); + + InnerCache = innerCache; + } + + /// + /// Gets the inner cache. + /// + public IAppPolicedCache InnerCache { get; } + + /// + public object Get(string key) + { + var item = InnerCache.Get(key); + return CheckCloneableAndTracksChanges(item); + } + + /// + public object Get(string key, Func factory) + { + var cached = InnerCache.Get(key, () => + { + var result = FastDictionaryAppCacheBase.GetSafeLazy(factory); + var value = result.Value; // force evaluation now - this may throw if cacheItem throws, and then nothing goes into cache + // do not store null values (backward compat), clone / reset to go into the cache + return value == null ? null : CheckCloneableAndTracksChanges(value); + }); + return CheckCloneableAndTracksChanges(cached); + } + + /// + public IEnumerable SearchByKey(string keyStartsWith) + { + return InnerCache.SearchByKey(keyStartsWith) + .Select(CheckCloneableAndTracksChanges); + } + + /// + public IEnumerable SearchByRegex(string regex) + { + return InnerCache.SearchByRegex(regex) + .Select(CheckCloneableAndTracksChanges); + } + + /// + public object Get(string key, Func factory, TimeSpan? timeout, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, string[] dependentFiles = null) + { + var cached = InnerCache.Get(key, () => + { + var result = FastDictionaryAppCacheBase.GetSafeLazy(factory); + var value = result.Value; // force evaluation now - this may throw if cacheItem throws, and then nothing goes into cache + // do not store null values (backward compat), clone / reset to go into the cache + return value == null ? null : CheckCloneableAndTracksChanges(value); + + // clone / reset to go into the cache + }, timeout, isSliding, priority, removedCallback, dependentFiles); + + // clone / reset to go into the cache + return CheckCloneableAndTracksChanges(cached); + } + + /// + public void Insert(string key, Func factory, TimeSpan? timeout = null, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, string[] dependentFiles = null) + { + InnerCache.Insert(key, () => + { + var result = FastDictionaryAppCacheBase.GetSafeLazy(factory); + var value = result.Value; // force evaluation now - this may throw if cacheItem throws, and then nothing goes into cache + // do not store null values (backward compat), clone / reset to go into the cache + return value == null ? null : CheckCloneableAndTracksChanges(value); + }, timeout, isSliding, priority, removedCallback, dependentFiles); + } + + /// + public void Clear() + { + InnerCache.Clear(); + } + + /// + public void Clear(string key) + { + InnerCache.Clear(key); + } + + /// + public void ClearOfType(string typeName) + { + InnerCache.ClearOfType(typeName); + } + + /// + public void ClearOfType() + { + InnerCache.ClearOfType(); + } + + /// + public void ClearOfType(Func predicate) + { + InnerCache.ClearOfType(predicate); + } + + /// + public void ClearByKey(string keyStartsWith) + { + InnerCache.ClearByKey(keyStartsWith); + } + + /// + public void ClearByRegex(string regex) + { + InnerCache.ClearByRegex(regex); + } + + private static object CheckCloneableAndTracksChanges(object input) + { + if (input is IDeepCloneable cloneable) + { + input = cloneable.DeepClone(); + } + + // reset dirty initial properties + if (input is IRememberBeingDirty tracksChanges) + { + tracksChanges.ResetDirtyProperties(false); + input = tracksChanges; + } + + return input; + } + } +} diff --git a/src/Umbraco.Core/Cache/DeepCloneRuntimeCacheProvider.cs b/src/Umbraco.Core/Cache/DeepCloneRuntimeCacheProvider.cs deleted file mode 100644 index 255d7b526d..0000000000 --- a/src/Umbraco.Core/Cache/DeepCloneRuntimeCacheProvider.cs +++ /dev/null @@ -1,155 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web.Caching; -using Umbraco.Core.Models; -using Umbraco.Core.Models.Entities; - -namespace Umbraco.Core.Cache -{ - /// - /// Interface describing this cache provider as a wrapper for another - /// - internal interface IRuntimeCacheProviderWrapper - { - IRuntimeCacheProvider InnerProvider { get; } - } - - /// - /// A wrapper for any IRuntimeCacheProvider that ensures that all inserts and returns - /// are a deep cloned copy of the item when the item is IDeepCloneable and that tracks changes are - /// reset if the object is TracksChangesEntityBase - /// - internal class DeepCloneRuntimeCacheProvider : IRuntimeCacheProvider, IRuntimeCacheProviderWrapper - { - public IRuntimeCacheProvider InnerProvider { get; } - - public DeepCloneRuntimeCacheProvider(IRuntimeCacheProvider innerProvider) - { - var type = typeof (DeepCloneRuntimeCacheProvider); - - if (innerProvider.GetType() == type) - throw new InvalidOperationException($"A {type} cannot wrap another instance of {type}."); - - InnerProvider = innerProvider; - } - - #region Clear - doesn't require any changes - - public void ClearAllCache() - { - InnerProvider.ClearAllCache(); - } - - public void ClearCacheItem(string key) - { - InnerProvider.ClearCacheItem(key); - } - - public void ClearCacheObjectTypes(string typeName) - { - InnerProvider.ClearCacheObjectTypes(typeName); - } - - public void ClearCacheObjectTypes() - { - InnerProvider.ClearCacheObjectTypes(); - } - - public void ClearCacheObjectTypes(Func predicate) - { - InnerProvider.ClearCacheObjectTypes(predicate); - } - - public void ClearCacheByKeySearch(string keyStartsWith) - { - InnerProvider.ClearCacheByKeySearch(keyStartsWith); - } - - public void ClearCacheByKeyExpression(string regexString) - { - InnerProvider.ClearCacheByKeyExpression(regexString); - } - - #endregion - - public IEnumerable GetCacheItemsByKeySearch(string keyStartsWith) - { - return InnerProvider.GetCacheItemsByKeySearch(keyStartsWith) - .Select(CheckCloneableAndTracksChanges); - } - - public IEnumerable GetCacheItemsByKeyExpression(string regexString) - { - return InnerProvider.GetCacheItemsByKeyExpression(regexString) - .Select(CheckCloneableAndTracksChanges); - } - - public object GetCacheItem(string cacheKey) - { - var item = InnerProvider.GetCacheItem(cacheKey); - return CheckCloneableAndTracksChanges(item); - } - - public object GetCacheItem(string cacheKey, Func getCacheItem) - { - var cached = InnerProvider.GetCacheItem(cacheKey, () => - { - var result = DictionaryCacheProviderBase.GetSafeLazy(getCacheItem); - var value = result.Value; // force evaluation now - this may throw if cacheItem throws, and then nothing goes into cache - if (value == null) return null; // do not store null values (backward compat) - - return CheckCloneableAndTracksChanges(value); - }); - return CheckCloneableAndTracksChanges(cached); - } - - public object GetCacheItem(string cacheKey, Func getCacheItem, TimeSpan? timeout, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, string[] dependentFiles = null) - { - var cached = InnerProvider.GetCacheItem(cacheKey, () => - { - var result = DictionaryCacheProviderBase.GetSafeLazy(getCacheItem); - var value = result.Value; // force evaluation now - this may throw if cacheItem throws, and then nothing goes into cache - if (value == null) return null; // do not store null values (backward compat) - - // clone / reset to go into the cache - return CheckCloneableAndTracksChanges(value); - }, timeout, isSliding, priority, removedCallback, dependentFiles); - - // clone / reset to go into the cache - return CheckCloneableAndTracksChanges(cached); - } - - public void InsertCacheItem(string cacheKey, Func getCacheItem, TimeSpan? timeout = null, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, string[] dependentFiles = null) - { - InnerProvider.InsertCacheItem(cacheKey, () => - { - var result = DictionaryCacheProviderBase.GetSafeLazy(getCacheItem); - var value = result.Value; // force evaluation now - this may throw if cacheItem throws, and then nothing goes into cache - if (value == null) return null; // do not store null values (backward compat) - - // clone / reset to go into the cache - return CheckCloneableAndTracksChanges(value); - }, timeout, isSliding, priority, removedCallback, dependentFiles); - } - - private static object CheckCloneableAndTracksChanges(object input) - { - var cloneable = input as IDeepCloneable; - if (cloneable != null) - { - input = cloneable.DeepClone(); - } - - // reset dirty initial properties (U4-1946) - var tracksChanges = input as IRememberBeingDirty; - if (tracksChanges != null) - { - tracksChanges.ResetDirtyProperties(false); - input = tracksChanges; - } - - return input; - } - } -} diff --git a/src/Umbraco.Core/Cache/DefaultRepositoryCachePolicy.cs b/src/Umbraco.Core/Cache/DefaultRepositoryCachePolicy.cs index 8387f547d3..6f160cd552 100644 --- a/src/Umbraco.Core/Cache/DefaultRepositoryCachePolicy.cs +++ b/src/Umbraco.Core/Cache/DefaultRepositoryCachePolicy.cs @@ -23,7 +23,7 @@ namespace Umbraco.Core.Cache private static readonly TEntity[] EmptyEntities = new TEntity[0]; // const private readonly RepositoryCachePolicyOptions _options; - public DefaultRepositoryCachePolicy(IRuntimeCacheProvider cache, IScopeAccessor scopeAccessor, RepositoryCachePolicyOptions options) + public DefaultRepositoryCachePolicy(IAppPolicedCache cache, IScopeAccessor scopeAccessor, RepositoryCachePolicyOptions options) : base(cache, scopeAccessor) { _options = options ?? throw new ArgumentNullException(nameof(options)); @@ -42,7 +42,7 @@ namespace Umbraco.Core.Cache protected virtual void InsertEntity(string cacheKey, TEntity entity) { - Cache.InsertCacheItem(cacheKey, () => entity, TimeSpan.FromMinutes(5), true); + Cache.Insert(cacheKey, () => entity, TimeSpan.FromMinutes(5), true); } protected virtual void InsertEntities(TId[] ids, TEntity[] entities) @@ -52,7 +52,7 @@ namespace Umbraco.Core.Cache // getting all of them, and finding nothing. // if we can cache a zero count, cache an empty array, // for as long as the cache is not cleared (no expiration) - Cache.InsertCacheItem(GetEntityTypeCacheKey(), () => EmptyEntities); + Cache.Insert(GetEntityTypeCacheKey(), () => EmptyEntities); } else { @@ -60,7 +60,7 @@ namespace Umbraco.Core.Cache foreach (var entity in entities) { var capture = entity; - Cache.InsertCacheItem(GetEntityCacheKey(entity.Id), () => capture, TimeSpan.FromMinutes(5), true); + Cache.Insert(GetEntityCacheKey(entity.Id), () => capture, TimeSpan.FromMinutes(5), true); } } } @@ -77,21 +77,21 @@ namespace Umbraco.Core.Cache // just to be safe, we cannot cache an item without an identity if (entity.HasIdentity) { - Cache.InsertCacheItem(GetEntityCacheKey(entity.Id), () => entity, TimeSpan.FromMinutes(5), true); + Cache.Insert(GetEntityCacheKey(entity.Id), () => entity, TimeSpan.FromMinutes(5), true); } // if there's a GetAllCacheAllowZeroCount cache, ensure it is cleared - Cache.ClearCacheItem(GetEntityTypeCacheKey()); + Cache.Clear(GetEntityTypeCacheKey()); } catch { // if an exception is thrown we need to remove the entry from cache, // this is ONLY a work around because of the way // that we cache entities: http://issues.umbraco.org/issue/U4-4259 - Cache.ClearCacheItem(GetEntityCacheKey(entity.Id)); + Cache.Clear(GetEntityCacheKey(entity.Id)); // if there's a GetAllCacheAllowZeroCount cache, ensure it is cleared - Cache.ClearCacheItem(GetEntityTypeCacheKey()); + Cache.Clear(GetEntityTypeCacheKey()); throw; } @@ -109,21 +109,21 @@ namespace Umbraco.Core.Cache // just to be safe, we cannot cache an item without an identity if (entity.HasIdentity) { - Cache.InsertCacheItem(GetEntityCacheKey(entity.Id), () => entity, TimeSpan.FromMinutes(5), true); + Cache.Insert(GetEntityCacheKey(entity.Id), () => entity, TimeSpan.FromMinutes(5), true); } // if there's a GetAllCacheAllowZeroCount cache, ensure it is cleared - Cache.ClearCacheItem(GetEntityTypeCacheKey()); + Cache.Clear(GetEntityTypeCacheKey()); } catch { // if an exception is thrown we need to remove the entry from cache, // this is ONLY a work around because of the way // that we cache entities: http://issues.umbraco.org/issue/U4-4259 - Cache.ClearCacheItem(GetEntityCacheKey(entity.Id)); + Cache.Clear(GetEntityCacheKey(entity.Id)); // if there's a GetAllCacheAllowZeroCount cache, ensure it is cleared - Cache.ClearCacheItem(GetEntityTypeCacheKey()); + Cache.Clear(GetEntityTypeCacheKey()); throw; } @@ -142,9 +142,9 @@ namespace Umbraco.Core.Cache { // whatever happens, clear the cache var cacheKey = GetEntityCacheKey(entity.Id); - Cache.ClearCacheItem(cacheKey); + Cache.Clear(cacheKey); // if there's a GetAllCacheAllowZeroCount cache, ensure it is cleared - Cache.ClearCacheItem(GetEntityTypeCacheKey()); + Cache.Clear(GetEntityTypeCacheKey()); } } @@ -238,7 +238,7 @@ namespace Umbraco.Core.Cache /// public override void ClearAll() { - Cache.ClearCacheByKeySearch(GetEntityTypeCacheKey()); + Cache.ClearByKey(GetEntityTypeCacheKey()); } } } diff --git a/src/Umbraco.Core/Cache/DictionaryCacheProvider.cs b/src/Umbraco.Core/Cache/DictionaryCacheProvider.cs index 98dceb80b0..2ff5f6ea83 100644 --- a/src/Umbraco.Core/Cache/DictionaryCacheProvider.cs +++ b/src/Umbraco.Core/Cache/DictionaryCacheProvider.cs @@ -1,147 +1,97 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; -using System.Linq; using System.Text.RegularExpressions; -using Umbraco.Core.Composing; namespace Umbraco.Core.Cache { - internal class DictionaryCacheProvider : ICacheProvider + /// + /// Implements on top of a concurrent dictionary. + /// + public class DictionaryCacheProvider : IAppCache { - private readonly ConcurrentDictionary> _items - = new ConcurrentDictionary>(); + /// + /// Gets the internal items dictionary, for tests only! + /// + internal readonly ConcurrentDictionary Items = new ConcurrentDictionary(); - // for tests - internal ConcurrentDictionary> Items => _items; - - public void ClearAllCache() + /// + public virtual object Get(string key) { - _items.Clear(); + // fixme throws if non-existing, shouldn't it return null? + return Items[key]; } - public void ClearCacheItem(string key) + /// + public virtual object Get(string key, Func factory) { - _items.TryRemove(key, out _); + return Items.GetOrAdd(key, _ => factory()); } - public void ClearCacheObjectTypes(string typeName) + /// + public virtual IEnumerable SearchByKey(string keyStartsWith) { - var type = TypeFinder.GetTypeByName(typeName); - if (type == null) return; - var isInterface = type.IsInterface; - - foreach (var kvp in _items - .Where(x => - { - // entry.Value is Lazy 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 = DictionaryCacheProviderBase.GetSafeLazyValue(x.Value, true); - - // 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)); - })) - _items.TryRemove(kvp.Key, out _); + var items = new List(); + foreach (var (key, value) in Items) + if (key.InvariantStartsWith(keyStartsWith)) + items.Add(value); + return items; } - public void ClearCacheObjectTypes() + /// + public IEnumerable SearchByRegex(string regex) + { + var compiled = new Regex(regex, RegexOptions.Compiled); + var items = new List(); + foreach (var (key, value) in Items) + if (compiled.IsMatch(key)) + items.Add(value); + return items; + } + + /// + public virtual void Clear() + { + Items.Clear(); + } + + /// + public virtual void Clear(string key) + { + Items.TryRemove(key, out _); + } + + /// + public virtual void ClearOfType(string typeName) + { + Items.RemoveAll(kvp => kvp.Value != null && kvp.Value.GetType().ToString().InvariantEquals(typeName)); + } + + /// + public virtual void ClearOfType() { var typeOfT = typeof(T); - var isInterface = typeOfT.IsInterface; - - foreach (var kvp in _items - .Where(x => - { - // entry.Value is Lazy and not null, its value may be null - // remove null values as well, does not hurt - // compare on exact type, don't use "is" - // get non-created as NonCreatedValue & exceptions as null - var value = DictionaryCacheProviderBase.GetSafeLazyValue(x.Value, true); - - // 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)); - })) - _items.TryRemove(kvp.Key, out _); + Items.RemoveAll(kvp => kvp.Value != null && kvp.Value.GetType() == typeOfT); } - public void ClearCacheObjectTypes(Func predicate) + /// + public virtual void ClearOfType(Func predicate) { var typeOfT = typeof(T); - var isInterface = typeOfT.IsInterface; - - foreach (var kvp in _items - .Where(x => - { - // entry.Value is Lazy and not null, its value may be null - // remove null values as well, does not hurt - // compare on exact type, don't use "is" - // get non-created as NonCreatedValue & exceptions as null - var value = DictionaryCacheProviderBase.GetSafeLazyValue(x.Value, true); - 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)) - // run predicate on the 'public key' part only, ie without prefix - && predicate(x.Key, (T)value); - })) - _items.TryRemove(kvp.Key, out _); + Items.RemoveAll(kvp => kvp.Value != null && kvp.Value.GetType() == typeOfT && predicate(kvp.Key, (T)kvp.Value)); } - public void ClearCacheByKeySearch(string keyStartsWith) + /// + public virtual void ClearByKey(string keyStartsWith) { - foreach (var ikvp in _items - .Where(kvp => kvp.Key.InvariantStartsWith(keyStartsWith))) - _items.TryRemove(ikvp.Key, out _); + Items.RemoveAll(kvp => kvp.Key.InvariantStartsWith(keyStartsWith)); } - public void ClearCacheByKeyExpression(string regexString) + /// + public virtual void ClearByRegex(string regex) { - foreach (var ikvp in _items - .Where(kvp => Regex.IsMatch(kvp.Key, regexString))) - _items.TryRemove(ikvp.Key, out _); - } - - public IEnumerable GetCacheItemsByKeySearch(string keyStartsWith) - { - return _items - .Where(kvp => kvp.Key.InvariantStartsWith(keyStartsWith)) - .Select(kvp => DictionaryCacheProviderBase.GetSafeLazyValue(kvp.Value)) - .Where(x => x != null); - } - - public IEnumerable GetCacheItemsByKeyExpression(string regexString) - { - return _items - .Where(kvp => Regex.IsMatch(kvp.Key, regexString)) - .Select(kvp => DictionaryCacheProviderBase.GetSafeLazyValue(kvp.Value)) - .Where(x => x != null); - } - - public object GetCacheItem(string cacheKey) - { - _items.TryGetValue(cacheKey, out var result); // else null - return result == null ? null : DictionaryCacheProviderBase.GetSafeLazyValue(result); // return exceptions as null - } - - public object GetCacheItem(string cacheKey, Func getCacheItem) - { - var result = _items.GetOrAdd(cacheKey, k => DictionaryCacheProviderBase.GetSafeLazy(getCacheItem)); - - var value = result.Value; // will not throw (safe lazy) - if (!(value is DictionaryCacheProviderBase.ExceptionHolder eh)) - return value; - - // and... it's in the cache anyway - so contrary to other cache providers, - // which would trick with GetSafeLazyValue, we need to remove by ourselves, - // in order NOT to cache exceptions - - _items.TryRemove(cacheKey, out result); - eh.Exception.Throw(); // throw once! - return null; // never reached + var compiled = new Regex(regex, RegexOptions.Compiled); + Items.RemoveAll(kvp => compiled.IsMatch(kvp.Key)); } } } diff --git a/src/Umbraco.Core/Cache/DictionaryCacheProviderBase.cs b/src/Umbraco.Core/Cache/FastDictionaryAppCacheBase.cs similarity index 81% rename from src/Umbraco.Core/Cache/DictionaryCacheProviderBase.cs rename to src/Umbraco.Core/Cache/FastDictionaryAppCacheBase.cs index f556d47a8e..371ab90a57 100644 --- a/src/Umbraco.Core/Cache/DictionaryCacheProviderBase.cs +++ b/src/Umbraco.Core/Cache/FastDictionaryAppCacheBase.cs @@ -8,7 +8,10 @@ using Umbraco.Core.Composing; namespace Umbraco.Core.Cache { - internal abstract class DictionaryCacheProviderBase : ICacheProvider + /// + /// Provides a base class to fast, dictionary-based implementations. + /// + internal abstract class FastDictionaryAppCacheBase : IAppCache { // prefix cache keys so we know which one are ours protected const string CacheItemPrefix = "umbrtmche"; @@ -16,82 +19,75 @@ namespace Umbraco.Core.Cache // an object that represent a value that has not been created yet protected internal static readonly object ValueNotCreated = new object(); - // manupulate the underlying cache entries - // these *must* be called from within the appropriate locks - // and use the full prefixed cache keys - protected abstract IEnumerable GetDictionaryEntries(); - protected abstract void RemoveEntry(string key); - protected abstract object GetEntry(string key); + #region IAppCache - // read-write lock the underlying cache - //protected abstract IDisposable ReadLock { get; } - //protected abstract IDisposable WriteLock { get; } - - protected abstract void EnterReadLock(); - protected abstract void ExitReadLock(); - protected abstract void EnterWriteLock(); - protected abstract void ExitWriteLock(); - - protected string GetCacheKey(string key) + /// + public virtual object Get(string key) { - return string.Format("{0}-{1}", CacheItemPrefix, key); - } - - protected internal static Lazy GetSafeLazy(Func getCacheItem) - { - // try to generate the value and if it fails, - // wrap in an ExceptionHolder - would be much simpler - // to just use lazy.IsValueFaulted alas that field is - // internal - return new Lazy(() => - { - try - { - return getCacheItem(); - } - catch (Exception e) - { - return new ExceptionHolder(ExceptionDispatchInfo.Capture(e)); - } - }); - } - - protected internal static object GetSafeLazyValue(Lazy lazy, bool onlyIfValueIsCreated = false) - { - // if onlyIfValueIsCreated, do not trigger value creation - // must return something, though, to differenciate from null values - if (onlyIfValueIsCreated && lazy.IsValueCreated == false) return ValueNotCreated; - - // if execution has thrown then lazy.IsValueCreated is false - // and lazy.IsValueFaulted is true (but internal) so we use our - // own exception holder (see Lazy source code) to return null - if (lazy.Value is ExceptionHolder) return null; - - // we have a value and execution has not thrown so returning - // here does not throw - unless we're re-entering, take care of it + key = GetCacheKey(key); + Lazy result; try { - return lazy.Value; + EnterReadLock(); + result = GetEntry(key) as Lazy; // null if key not found } - catch (InvalidOperationException e) + finally { - throw new InvalidOperationException("The method that computes a value for the cache has tried to read that value from the cache.", e); + ExitReadLock(); } + return result == null ? null : GetSafeLazyValue(result); // return exceptions as null } - internal class ExceptionHolder + /// + public abstract object Get(string key, Func factory); + + /// + public virtual IEnumerable SearchByKey(string keyStartsWith) { - public ExceptionHolder(ExceptionDispatchInfo e) + var plen = CacheItemPrefix.Length + 1; + IEnumerable entries; + try { - Exception = e; + EnterReadLock(); + entries = GetDictionaryEntries() + .Where(x => ((string)x.Key).Substring(plen).InvariantStartsWith(keyStartsWith)) + .ToArray(); // evaluate while locked + } + finally + { + ExitReadLock(); } - public ExceptionDispatchInfo Exception { get; } + return entries + .Select(x => GetSafeLazyValue((Lazy)x.Value)) // return exceptions as null + .Where(x => x != null); // backward compat, don't store null values in the cache } - #region Clear + /// + public virtual IEnumerable SearchByRegex(string regex) + { + const string prefix = CacheItemPrefix + "-"; + var compiled = new Regex(regex, RegexOptions.Compiled); + var plen = prefix.Length; + IEnumerable entries; + try + { + EnterReadLock(); + entries = GetDictionaryEntries() + .Where(x => compiled.IsMatch(((string)x.Key).Substring(plen))) + .ToArray(); // evaluate while locked + } + finally + { + ExitReadLock(); + } + return entries + .Select(x => GetSafeLazyValue((Lazy)x.Value)) // return exceptions as null + .Where(x => x != null); // backward compat, don't store null values in the cache + } - public virtual void ClearAllCache() + /// + public virtual void Clear() { try { @@ -106,7 +102,8 @@ namespace Umbraco.Core.Cache } } - public virtual void ClearCacheItem(string key) + /// + public virtual void Clear(string key) { var cacheKey = GetCacheKey(key); try @@ -120,7 +117,8 @@ namespace Umbraco.Core.Cache } } - public virtual void ClearCacheObjectTypes(string typeName) + /// + public virtual void ClearOfType(string typeName) { var type = TypeFinder.GetTypeByName(typeName); if (type == null) return; @@ -149,7 +147,8 @@ namespace Umbraco.Core.Cache } } - public virtual void ClearCacheObjectTypes() + /// + public virtual void ClearOfType() { var typeOfT = typeof(T); var isInterface = typeOfT.IsInterface; @@ -178,7 +177,8 @@ namespace Umbraco.Core.Cache } } - public virtual void ClearCacheObjectTypes(Func predicate) + /// + public virtual void ClearOfType(Func predicate) { var typeOfT = typeof(T); var isInterface = typeOfT.IsInterface; @@ -210,7 +210,8 @@ namespace Umbraco.Core.Cache } } - public virtual void ClearCacheByKeySearch(string keyStartsWith) + /// + public virtual void ClearByKey(string keyStartsWith) { var plen = CacheItemPrefix.Length + 1; try @@ -227,14 +228,16 @@ namespace Umbraco.Core.Cache } } - public virtual void ClearCacheByKeyExpression(string regexString) + /// + public virtual void ClearByRegex(string regex) { + var compiled = new Regex(regex, RegexOptions.Compiled); var plen = CacheItemPrefix.Length + 1; try { EnterWriteLock(); foreach (var entry in GetDictionaryEntries() - .Where(x => Regex.IsMatch(((string)x.Key).Substring(plen), regexString)) + .Where(x => compiled.IsMatch(((string)x.Key).Substring(plen))) .ToArray()) RemoveEntry((string) entry.Key); } @@ -246,67 +249,80 @@ namespace Umbraco.Core.Cache #endregion - #region Get + #region Dictionary - public virtual IEnumerable GetCacheItemsByKeySearch(string keyStartsWith) + // manipulate the underlying cache entries + // these *must* be called from within the appropriate locks + // and use the full prefixed cache keys + protected abstract IEnumerable GetDictionaryEntries(); + protected abstract void RemoveEntry(string key); + protected abstract object GetEntry(string key); + + // read-write lock the underlying cache + //protected abstract IDisposable ReadLock { get; } + //protected abstract IDisposable WriteLock { get; } + + protected abstract void EnterReadLock(); + protected abstract void ExitReadLock(); + protected abstract void EnterWriteLock(); + protected abstract void ExitWriteLock(); + + protected string GetCacheKey(string key) { - var plen = CacheItemPrefix.Length + 1; - IEnumerable entries; - try - { - EnterReadLock(); - entries = GetDictionaryEntries() - .Where(x => ((string)x.Key).Substring(plen).InvariantStartsWith(keyStartsWith)) - .ToArray(); // evaluate while locked - } - finally - { - ExitReadLock(); - } - - return entries - .Select(x => GetSafeLazyValue((Lazy)x.Value)) // return exceptions as null - .Where(x => x != null); // backward compat, don't store null values in the cache + return $"{CacheItemPrefix}-{key}"; } - public virtual IEnumerable GetCacheItemsByKeyExpression(string regexString) + protected internal static Lazy GetSafeLazy(Func getCacheItem) { - const string prefix = CacheItemPrefix + "-"; - var plen = prefix.Length; - IEnumerable entries; - try + // try to generate the value and if it fails, + // wrap in an ExceptionHolder - would be much simpler + // to just use lazy.IsValueFaulted alas that field is + // internal + return new Lazy(() => { - EnterReadLock(); - entries = GetDictionaryEntries() - .Where(x => Regex.IsMatch(((string)x.Key).Substring(plen), regexString)) - .ToArray(); // evaluate while locked - } - finally - { - ExitReadLock(); - } - return entries - .Select(x => GetSafeLazyValue((Lazy)x.Value)) // return exceptions as null - .Where(x => x != null); // backward compat, don't store null values in the cache + try + { + return getCacheItem(); + } + catch (Exception e) + { + return new ExceptionHolder(ExceptionDispatchInfo.Capture(e)); + } + }); } - public virtual object GetCacheItem(string cacheKey) + protected internal static object GetSafeLazyValue(Lazy lazy, bool onlyIfValueIsCreated = false) { - cacheKey = GetCacheKey(cacheKey); - Lazy result; + // if onlyIfValueIsCreated, do not trigger value creation + // must return something, though, to differentiate from null values + if (onlyIfValueIsCreated && lazy.IsValueCreated == false) return ValueNotCreated; + + // if execution has thrown then lazy.IsValueCreated is false + // and lazy.IsValueFaulted is true (but internal) so we use our + // own exception holder (see Lazy source code) to return null + if (lazy.Value is ExceptionHolder) return null; + + // we have a value and execution has not thrown so returning + // here does not throw - unless we're re-entering, take care of it try { - EnterReadLock(); - result = GetEntry(cacheKey) as Lazy; // null if key not found + return lazy.Value; } - finally + catch (InvalidOperationException e) { - ExitReadLock(); + throw new InvalidOperationException("The method that computes a value for the cache has tried to read that value from the cache.", e); } - return result == null ? null : GetSafeLazyValue(result); // return exceptions as null } - public abstract object GetCacheItem(string cacheKey, Func getCacheItem); + internal class ExceptionHolder + { + public ExceptionHolder(ExceptionDispatchInfo e) + { + Exception = e; + } + + public ExceptionDispatchInfo Exception { get; } + } #endregion } diff --git a/src/Umbraco.Core/Cache/FastDictionaryCacheProvider.cs b/src/Umbraco.Core/Cache/FastDictionaryCacheProvider.cs new file mode 100644 index 0000000000..a3863dac52 --- /dev/null +++ b/src/Umbraco.Core/Cache/FastDictionaryCacheProvider.cs @@ -0,0 +1,162 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Text.RegularExpressions; +using Umbraco.Core.Composing; + +namespace Umbraco.Core.Cache +{ + /// + /// Implements a fast on top of a concurrent dictionary. + /// + internal class FastDictionaryCacheProvider : IAppCache + { + /// + /// Gets the internal items dictionary, for tests only! + /// + internal readonly ConcurrentDictionary> Items = new ConcurrentDictionary>(); + + /// + public object Get(string cacheKey) + { + Items.TryGetValue(cacheKey, out var result); // else null + return result == null ? null : FastDictionaryAppCacheBase.GetSafeLazyValue(result); // return exceptions as null + } + + /// + public object Get(string cacheKey, Func getCacheItem) + { + var result = Items.GetOrAdd(cacheKey, k => FastDictionaryAppCacheBase.GetSafeLazy(getCacheItem)); + + var value = result.Value; // will not throw (safe lazy) + if (!(value is FastDictionaryAppCacheBase.ExceptionHolder eh)) + return value; + + // and... it's in the cache anyway - so contrary to other cache providers, + // which would trick with GetSafeLazyValue, we need to remove by ourselves, + // in order NOT to cache exceptions + + Items.TryRemove(cacheKey, out result); + eh.Exception.Throw(); // throw once! + return null; // never reached + } + + /// + public IEnumerable SearchByKey(string keyStartsWith) + { + return Items + .Where(kvp => kvp.Key.InvariantStartsWith(keyStartsWith)) + .Select(kvp => FastDictionaryAppCacheBase.GetSafeLazyValue(kvp.Value)) + .Where(x => x != null); + } + + /// + public IEnumerable SearchByRegex(string regex) + { + var compiled = new Regex(regex, RegexOptions.Compiled); + return Items + .Where(kvp => compiled.IsMatch(kvp.Key)) + .Select(kvp => FastDictionaryAppCacheBase.GetSafeLazyValue(kvp.Value)) + .Where(x => x != null); + } + + /// + public void Clear() + { + Items.Clear(); + } + + /// + public void Clear(string key) + { + Items.TryRemove(key, out _); + } + + /// + public void ClearOfType(string typeName) + { + var type = TypeFinder.GetTypeByName(typeName); + if (type == null) return; + var isInterface = type.IsInterface; + + foreach (var kvp in Items + .Where(x => + { + // entry.Value is Lazy 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 = FastDictionaryAppCacheBase.GetSafeLazyValue(x.Value, true); + + // 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)); + })) + Items.TryRemove(kvp.Key, out _); + } + + /// + public void ClearOfType() + { + var typeOfT = typeof(T); + var isInterface = typeOfT.IsInterface; + + foreach (var kvp in Items + .Where(x => + { + // entry.Value is Lazy and not null, its value may be null + // remove null values as well, does not hurt + // compare on exact type, don't use "is" + // get non-created as NonCreatedValue & exceptions as null + var value = FastDictionaryAppCacheBase.GetSafeLazyValue(x.Value, true); + + // 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)); + })) + Items.TryRemove(kvp.Key, out _); + } + + /// + public void ClearOfType(Func predicate) + { + var typeOfT = typeof(T); + var isInterface = typeOfT.IsInterface; + + foreach (var kvp in Items + .Where(x => + { + // entry.Value is Lazy and not null, its value may be null + // remove null values as well, does not hurt + // compare on exact type, don't use "is" + // get non-created as NonCreatedValue & exceptions as null + var value = FastDictionaryAppCacheBase.GetSafeLazyValue(x.Value, true); + 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)) + // run predicate on the 'public key' part only, ie without prefix + && predicate(x.Key, (T)value); + })) + Items.TryRemove(kvp.Key, out _); + } + + /// + public void ClearByKey(string keyStartsWith) + { + foreach (var ikvp in Items + .Where(kvp => kvp.Key.InvariantStartsWith(keyStartsWith))) + Items.TryRemove(ikvp.Key, out _); + } + + /// + public void ClearByRegex(string regex) + { + var compiled = new Regex(regex, RegexOptions.Compiled); + foreach (var ikvp in Items + .Where(kvp => compiled.IsMatch(kvp.Key))) + Items.TryRemove(ikvp.Key, out _); + } + } +} diff --git a/src/Umbraco.Core/Cache/FullDataSetRepositoryCachePolicy.cs b/src/Umbraco.Core/Cache/FullDataSetRepositoryCachePolicy.cs index 319d84d41f..3bc4c9d059 100644 --- a/src/Umbraco.Core/Cache/FullDataSetRepositoryCachePolicy.cs +++ b/src/Umbraco.Core/Cache/FullDataSetRepositoryCachePolicy.cs @@ -24,7 +24,7 @@ namespace Umbraco.Core.Cache private readonly Func _entityGetId; private readonly bool _expires; - public FullDataSetRepositoryCachePolicy(IRuntimeCacheProvider cache, IScopeAccessor scopeAccessor, Func entityGetId, bool expires) + public FullDataSetRepositoryCachePolicy(IAppPolicedCache cache, IScopeAccessor scopeAccessor, Func entityGetId, bool expires) : base(cache, scopeAccessor) { _entityGetId = entityGetId; @@ -55,11 +55,11 @@ namespace Umbraco.Core.Cache if (_expires) { - Cache.InsertCacheItem(key, () => new DeepCloneableList(entities), TimeSpan.FromMinutes(5), true); + Cache.Insert(key, () => new DeepCloneableList(entities), TimeSpan.FromMinutes(5), true); } else { - Cache.InsertCacheItem(key, () => new DeepCloneableList(entities)); + Cache.Insert(key, () => new DeepCloneableList(entities)); } } @@ -171,7 +171,7 @@ namespace Umbraco.Core.Cache /// public override void ClearAll() { - Cache.ClearCacheItem(GetEntityTypeCacheKey()); + Cache.Clear(GetEntityTypeCacheKey()); } } } diff --git a/src/Umbraco.Core/Cache/HttpRequestCacheProvider.cs b/src/Umbraco.Core/Cache/HttpRequestAppCache.cs similarity index 53% rename from src/Umbraco.Core/Cache/HttpRequestCacheProvider.cs rename to src/Umbraco.Core/Cache/HttpRequestAppCache.cs index 52c230ff71..dcb2621d75 100644 --- a/src/Umbraco.Core/Cache/HttpRequestCacheProvider.cs +++ b/src/Umbraco.Core/Cache/HttpRequestAppCache.cs @@ -7,54 +7,83 @@ using System.Web; namespace Umbraco.Core.Cache { /// - /// A cache provider that caches items in the HttpContext.Items + /// Implements a fast on top of HttpContext.Items. /// /// - /// If the Items collection is null, then this provider has no effect + /// If no current HttpContext items can be found (no current HttpContext, + /// or no Items...) then this cache acts as a pass-through and does not cache + /// anything. /// - internal class HttpRequestCacheProvider : DictionaryCacheProviderBase + internal class HttpRequestAppCache : FastDictionaryAppCacheBase { - // context provider - // the idea is that there is only one, application-wide HttpRequestCacheProvider instance, - // that is initialized with a method that returns the "current" context. - // NOTE - // but then it is initialized with () => new HttpContextWrapper(HttpContent.Current) - // which is higly inefficient because it creates a new wrapper each time we refer to _context() - // so replace it with _context1 and _context2 below + a way to get context.Items. - //private readonly Func _context; - - // NOTE - // and then in almost 100% cases _context2 will be () => HttpContext.Current - // so why not bring that logic in here and fallback on to HttpContext.Current when - // _context1 is null? - //private readonly HttpContextBase _context1; - //private readonly Func _context2; private readonly HttpContextBase _context; - private IDictionary ContextItems - { - //get { return _context1 != null ? _context1.Items : _context2().Items; } - get { return _context != null ? _context.Items : HttpContext.Current.Items; } - } - - private bool HasContextItems - { - get { return (_context != null && _context.Items != null) || HttpContext.Current != null; } - } - - // for unit tests - public HttpRequestCacheProvider(HttpContextBase context) + /// + /// Initializes a new instance of the class with a context, for unit tests! + /// + public HttpRequestAppCache(HttpContextBase context) { _context = context; } - // main constructor - // will use HttpContext.Current - public HttpRequestCacheProvider(/*Func context*/) + /// + /// Initializes a new instance of the class. + /// + /// + /// Will use HttpContext.Current. + /// fixme - should use IHttpContextAccessor + /// + public HttpRequestAppCache() + { } + + private IDictionary ContextItems => _context?.Items ?? HttpContext.Current?.Items; + + private bool HasContextItems => _context?.Items != null || HttpContext.Current != null; + + /// + public override object Get(string key, Func factory) { - //_context2 = context; + //no place to cache so just return the callback result + if (HasContextItems == false) return factory(); + + key = GetCacheKey(key); + + Lazy result; + + try + { + EnterWriteLock(); + result = ContextItems[key] as Lazy; // null if key not found + + // cannot create value within the lock, so if result.IsValueCreated is false, just + // do nothing here - means that if creation throws, a race condition could cause + // more than one thread to reach the return statement below and throw - accepted. + + if (result == null || GetSafeLazyValue(result, true) == null) // get non-created as NonCreatedValue & exceptions as null + { + result = GetSafeLazy(factory); + ContextItems[key] = result; + } + } + finally + { + ExitWriteLock(); + } + + // using GetSafeLazy and GetSafeLazyValue ensures that we don't cache + // exceptions (but try again and again) and silently eat them - however at + // some point we have to report them - so need to re-throw here + + // this does not throw anymore + //return result.Value; + + var value = result.Value; // will not throw (safe lazy) + if (value is ExceptionHolder eh) eh.Exception.Throw(); // throw once! + return value; } + #region Entries + protected override IEnumerable GetDictionaryEntries() { const string prefix = CacheItemPrefix + "-"; @@ -62,7 +91,7 @@ namespace Umbraco.Core.Cache if (HasContextItems == false) return Enumerable.Empty(); return ContextItems.Cast() - .Where(x => x.Key is string && ((string)x.Key).StartsWith(prefix)); + .Where(x => x.Key is string s && s.StartsWith(prefix)); } protected override void RemoveEntry(string key) @@ -77,6 +106,8 @@ namespace Umbraco.Core.Cache return HasContextItems ? ContextItems[key] : null; } + #endregion + #region Lock private bool _entered; @@ -103,59 +134,5 @@ namespace Umbraco.Core.Cache } #endregion - - #region Get - - public override object GetCacheItem(string cacheKey, Func getCacheItem) - { - //no place to cache so just return the callback result - if (HasContextItems == false) return getCacheItem(); - - cacheKey = GetCacheKey(cacheKey); - - Lazy result; - - try - { - EnterWriteLock(); - result = ContextItems[cacheKey] as Lazy; // null if key not found - - // cannot create value within the lock, so if result.IsValueCreated is false, just - // do nothing here - means that if creation throws, a race condition could cause - // more than one thread to reach the return statement below and throw - accepted. - - if (result == null || GetSafeLazyValue(result, true) == null) // get non-created as NonCreatedValue & exceptions as null - { - result = GetSafeLazy(getCacheItem); - ContextItems[cacheKey] = result; - } - } - finally - { - ExitWriteLock(); - } - - // using GetSafeLazy and GetSafeLazyValue ensures that we don't cache - // exceptions (but try again and again) and silently eat them - however at - // some point we have to report them - so need to re-throw here - - // this does not throw anymore - //return result.Value; - - var value = result.Value; // will not throw (safe lazy) - if (value is ExceptionHolder eh) eh.Exception.Throw(); // throw once! - return value; - } - - #endregion - - #region Insert - #endregion - - private class NoopLocker : DisposableObjectSlim - { - protected override void DisposeResources() - { } - } } } diff --git a/src/Umbraco.Core/Cache/IAppCache.cs b/src/Umbraco.Core/Cache/IAppCache.cs new file mode 100644 index 0000000000..674781f6d6 --- /dev/null +++ b/src/Umbraco.Core/Cache/IAppCache.cs @@ -0,0 +1,94 @@ +using System; +using System.Collections.Generic; + +namespace Umbraco.Core.Cache +{ + /// + /// Defines an application cache. + /// + public interface IAppCache + { + /// + /// Gets an item identified by its key. + /// + /// The key of the item. + /// The item, or null if the item was not found. + object Get(string key); + + /// + /// Gets or creates an item identified by its key. + /// + /// The key of the item. + /// A factory function that can create the item. + /// The item. + object Get(string key, Func factory); + + /// + /// Gets items with a key starting with the specified value. + /// + /// The StartsWith value to use in the search. + /// Items matching the search. + IEnumerable SearchByKey(string keyStartsWith); + + /// + /// Gets items with a key matching a regular expression. + /// + /// The regular expression. + /// Items matching the search. + IEnumerable SearchByRegex(string regex); + + /// + /// Removes all items from the cache. + /// + void Clear(); + + /// + /// Removes an item identified by its key from the cache. + /// + /// The key of the item. + void Clear(string key); + + /// + /// Removes items of a specified type from the cache. + /// + /// The name of the type to remove. + /// + /// If the type is an interface, then all items of a type implementing that interface are + /// removed. Otherwise, only items of that exact type are removed (items of type inheriting from + /// the specified type are not removed). + /// Performs a case-sensitive search. + /// + void ClearOfType(string typeName); + + /// + /// Removes items of a specified type from the cache. + /// + /// The type of the items to remove. + /// If the type is an interface, then all items of a type implementing that interface are + /// removed. Otherwise, only items of that exact type are removed (items of type inheriting from + /// the specified type are not removed). + void ClearOfType(); + + /// + /// Removes items of a specified type from the cache. + /// + /// The type of the items to remove. + /// The predicate to satisfy. + /// If the type is an interface, then all items of a type implementing that interface are + /// removed. Otherwise, only items of that exact type are removed (items of type inheriting from + /// the specified type are not removed). + void ClearOfType(Func predicate); + + /// + /// Clears items with a key starting with the specified value. + /// + /// The StartsWith value to use in the search. + void ClearByKey(string keyStartsWith); + + /// + /// Clears items with a key matching a regular expression. + /// + /// The regular expression. + void ClearByRegex(string regex); + } +} diff --git a/src/Umbraco.Core/Cache/IAppPolicedCache.cs b/src/Umbraco.Core/Cache/IAppPolicedCache.cs new file mode 100644 index 0000000000..0aee7584df --- /dev/null +++ b/src/Umbraco.Core/Cache/IAppPolicedCache.cs @@ -0,0 +1,54 @@ +using System; +using System.Web.Caching; + +// fixme should this be/support non-web? + +namespace Umbraco.Core.Cache +{ + /// + /// Defines an application cache that support cache policies. + /// + /// A cache policy can be used to cache with timeouts, + /// or depending on files, and with a remove callback, etc. + public interface IAppPolicedCache : IAppCache + { + /// + /// Gets an item identified by its key. + /// + /// The key of the item. + /// A factory function that can create the item. + /// An optional cache timeout. + /// An optional value indicating whether the cache timeout is sliding (default is false). + /// An optional cache priority (default is Normal). + /// An optional callback to handle removals. + /// Files the cache entry depends on. + /// The item. + object Get( + string key, + Func factory, + TimeSpan? timeout, + bool isSliding = false, + CacheItemPriority priority = CacheItemPriority.Normal, + CacheItemRemovedCallback removedCallback = null, + string[] dependentFiles = null); + + /// + /// Inserts an item. + /// + /// The key of the item. + /// A factory function that can create the item. + /// An optional cache timeout. + /// An optional value indicating whether the cache timeout is sliding (default is false). + /// An optional cache priority (default is Normal). + /// An optional callback to handle removals. + /// Files the cache entry depends on. + void Insert( + string key, + Func factory, + TimeSpan? timeout = null, + bool isSliding = false, + CacheItemPriority priority = CacheItemPriority.Normal, + CacheItemRemovedCallback removedCallback = null, + string[] dependentFiles = null); + } +} diff --git a/src/Umbraco.Core/Cache/ICacheProvider.cs b/src/Umbraco.Core/Cache/ICacheProvider.cs deleted file mode 100644 index 177f7570c2..0000000000 --- a/src/Umbraco.Core/Cache/ICacheProvider.cs +++ /dev/null @@ -1,68 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace Umbraco.Core.Cache -{ - /// - /// An interface for implementing a basic cache provider - /// - public interface ICacheProvider - { - /// - /// Removes all items from the cache. - /// - void ClearAllCache(); - - /// - /// Removes an item from the cache, identified by its key. - /// - /// The key of the item. - void ClearCacheItem(string key); - - /// - /// Removes items from the cache, of a specified type. - /// - /// The name of the type to remove. - /// - /// If the type is an interface, then all items of a type implementing that interface are - /// removed. Otherwise, only items of that exact type are removed (items of type inheriting from - /// the specified type are not removed). - /// Performs a case-sensitive search. - /// - void ClearCacheObjectTypes(string typeName); - - /// - /// Removes items from the cache, of a specified type. - /// - /// The type of the items to remove. - /// If the type is an interface, then all items of a type implementing that interface are - /// removed. Otherwise, only items of that exact type are removed (items of type inheriting from - /// the specified type are not removed). - void ClearCacheObjectTypes(); - - /// - /// Removes items from the cache, of a specified type, satisfying a predicate. - /// - /// The type of the items to remove. - /// The predicate to satisfy. - /// If the type is an interface, then all items of a type implementing that interface are - /// removed. Otherwise, only items of that exact type are removed (items of type inheriting from - /// the specified type are not removed). - void ClearCacheObjectTypes(Func predicate); - - void ClearCacheByKeySearch(string keyStartsWith); - void ClearCacheByKeyExpression(string regexString); - - IEnumerable GetCacheItemsByKeySearch(string keyStartsWith); - IEnumerable GetCacheItemsByKeyExpression(string regexString); - - /// - /// Returns an item with a given key - /// - /// - /// - object GetCacheItem(string cacheKey); - - object GetCacheItem(string cacheKey, Func getCacheItem); - } -} diff --git a/src/Umbraco.Core/Cache/IRuntimeCacheProvider.cs b/src/Umbraco.Core/Cache/IRuntimeCacheProvider.cs deleted file mode 100644 index 9f3d687e1d..0000000000 --- a/src/Umbraco.Core/Cache/IRuntimeCacheProvider.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System; -using System.Runtime.Caching; -using System.Text; -using System.Web.Caching; -using CacheItemPriority = System.Web.Caching.CacheItemPriority; - -namespace Umbraco.Core.Cache -{ - /// - /// An abstract class for implementing a runtime cache provider - /// - /// - /// - public interface IRuntimeCacheProvider : ICacheProvider - { - object GetCacheItem( - string cacheKey, - Func getCacheItem, - TimeSpan? timeout, - bool isSliding = false, - CacheItemPriority priority = CacheItemPriority.Normal, - CacheItemRemovedCallback removedCallback = null, - string[] dependentFiles = null); - - void InsertCacheItem( - string cacheKey, - Func getCacheItem, - TimeSpan? timeout = null, - bool isSliding = false, - CacheItemPriority priority = CacheItemPriority.Normal, - CacheItemRemovedCallback removedCallback = null, - string[] dependentFiles = null); - - } -} diff --git a/src/Umbraco.Core/Cache/IsolatedCaches.cs b/src/Umbraco.Core/Cache/IsolatedCaches.cs new file mode 100644 index 0000000000..bc624be20d --- /dev/null +++ b/src/Umbraco.Core/Cache/IsolatedCaches.cs @@ -0,0 +1,41 @@ +using System; + +namespace Umbraco.Core.Cache +{ + /// + /// Represents a dictionary of for types. + /// + /// + /// Isolated caches are used by e.g. repositories, to ensure that each cached entity + /// type has its own cache, so that lookups are fast and the repository does not need to + /// search through all keys on a global scale. + /// + public class IsolatedCaches : AppPolicedCacheDictionary + { + /// + /// Initializes a new instance of the class. + /// + /// + public IsolatedCaches(Func cacheFactory) + : base(cacheFactory) + { } + + /// + /// Gets a cache. + /// + public IAppPolicedCache GetOrCreate() + => GetOrCreate(typeof(T)); + + /// + /// Tries to get a cache. + /// + public Attempt Get() + => Get(typeof(T)); + + /// + /// Clears a cache. + /// + public void ClearCache() + => ClearCache(typeof(T)); + } +} diff --git a/src/Umbraco.Core/Cache/IsolatedRuntimeCache.cs b/src/Umbraco.Core/Cache/IsolatedRuntimeCache.cs deleted file mode 100644 index ee73a17532..0000000000 --- a/src/Umbraco.Core/Cache/IsolatedRuntimeCache.cs +++ /dev/null @@ -1,91 +0,0 @@ -using System; -using System.Collections.Concurrent; - -namespace Umbraco.Core.Cache -{ - /// - /// Used to get/create/manipulate isolated runtime cache - /// - /// - /// This is useful for repository level caches to ensure that cache lookups by key are fast so - /// that the repository doesn't need to search through all keys on a global scale. - /// - public class IsolatedRuntimeCache - { - internal Func CacheFactory { get; set; } - - /// - /// Constructor that allows specifying a factory for the type of runtime isolated cache to create - /// - /// - public IsolatedRuntimeCache(Func cacheFactory) - { - CacheFactory = cacheFactory; - } - - private readonly ConcurrentDictionary _isolatedCache = new ConcurrentDictionary(); - - /// - /// Returns an isolated runtime cache for a given type - /// - /// - /// - public IRuntimeCacheProvider GetOrCreateCache() - { - return _isolatedCache.GetOrAdd(typeof(T), type => CacheFactory(type)); - } - - /// - /// Returns an isolated runtime cache for a given type - /// - /// - public IRuntimeCacheProvider GetOrCreateCache(Type type) - { - return _isolatedCache.GetOrAdd(type, t => CacheFactory(t)); - } - - /// - /// Tries to get a cache by the type specified - /// - /// - /// - public Attempt GetCache() - { - IRuntimeCacheProvider cache; - if (_isolatedCache.TryGetValue(typeof(T), out cache)) - { - return Attempt.Succeed(cache); - } - return Attempt.Fail(); - } - - /// - /// Clears all values inside this isolated runtime cache - /// - /// - /// - public void ClearCache() - { - IRuntimeCacheProvider cache; - if (_isolatedCache.TryGetValue(typeof(T), out cache)) - { - cache.ClearAllCache(); - } - } - - /// - /// Clears all of the isolated caches - /// - public void ClearAllCaches() - { - foreach (var key in _isolatedCache.Keys) - { - IRuntimeCacheProvider cache; - if (_isolatedCache.TryRemove(key, out cache)) - { - cache.ClearAllCache(); - } - } - } - } -} diff --git a/src/Umbraco.Core/Cache/NoAppCache.cs b/src/Umbraco.Core/Cache/NoAppCache.cs new file mode 100644 index 0000000000..8a7e15cb29 --- /dev/null +++ b/src/Umbraco.Core/Cache/NoAppCache.cs @@ -0,0 +1,82 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web.Caching; + +namespace Umbraco.Core.Cache +{ + /// + /// Implements and do not cache. + /// + public class NoAppCache : IAppPolicedCache + { + private NoAppCache() { } + + /// + /// Gets the singleton instance. + /// + public static NoAppCache Instance { get; } = new NoAppCache(); + + /// + public virtual object Get(string cacheKey) + { + return null; + } + + /// + public virtual object Get(string cacheKey, Func factory) + { + return factory(); + } + + /// + public virtual IEnumerable SearchByKey(string keyStartsWith) + { + return Enumerable.Empty(); + } + + /// + public IEnumerable SearchByRegex(string regex) + { + return Enumerable.Empty(); + } + + /// + public object Get(string key, Func factory, TimeSpan? timeout, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, string[] dependentFiles = null) + { + return factory(); + } + + /// + public void Insert(string key, Func factory, TimeSpan? timeout = null, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, string[] dependentFiles = null) + { } + + /// + public virtual void Clear() + { } + + /// + public virtual void Clear(string key) + { } + + /// + public virtual void ClearOfType(string typeName) + { } + + /// + public virtual void ClearOfType() + { } + + /// + public virtual void ClearOfType(Func predicate) + { } + + /// + public virtual void ClearByKey(string keyStartsWith) + { } + + /// + public virtual void ClearByRegex(string regex) + { } + } +} diff --git a/src/Umbraco.Core/Cache/NoCacheRepositoryCachePolicy.cs b/src/Umbraco.Core/Cache/NoCacheRepositoryCachePolicy.cs index a3e7335d7f..acc67be679 100644 --- a/src/Umbraco.Core/Cache/NoCacheRepositoryCachePolicy.cs +++ b/src/Umbraco.Core/Cache/NoCacheRepositoryCachePolicy.cs @@ -13,7 +13,7 @@ namespace Umbraco.Core.Cache public static NoCacheRepositoryCachePolicy Instance { get; } = new NoCacheRepositoryCachePolicy(); - public IRepositoryCachePolicy Scoped(IRuntimeCacheProvider runtimeCache, IScope scope) + public IRepositoryCachePolicy Scoped(IAppPolicedCache runtimeCache, IScope scope) { throw new NotImplementedException(); } diff --git a/src/Umbraco.Core/Cache/NullCacheProvider.cs b/src/Umbraco.Core/Cache/NullCacheProvider.cs deleted file mode 100644 index 78286f75e2..0000000000 --- a/src/Umbraco.Core/Cache/NullCacheProvider.cs +++ /dev/null @@ -1,66 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web.Caching; - -namespace Umbraco.Core.Cache -{ - /// - /// Represents a cache provider that does not cache anything. - /// - public class NullCacheProvider : IRuntimeCacheProvider - { - private NullCacheProvider() { } - - public static NullCacheProvider Instance { get; } = new NullCacheProvider(); - - public virtual void ClearAllCache() - { } - - public virtual void ClearCacheItem(string key) - { } - - public virtual void ClearCacheObjectTypes(string typeName) - { } - - public virtual void ClearCacheObjectTypes() - { } - - public virtual void ClearCacheObjectTypes(Func predicate) - { } - - public virtual void ClearCacheByKeySearch(string keyStartsWith) - { } - - public virtual void ClearCacheByKeyExpression(string regexString) - { } - - public virtual IEnumerable GetCacheItemsByKeySearch(string keyStartsWith) - { - return Enumerable.Empty(); - } - - public IEnumerable GetCacheItemsByKeyExpression(string regexString) - { - return Enumerable.Empty(); - } - - public virtual object GetCacheItem(string cacheKey) - { - return default(object); - } - - public virtual object GetCacheItem(string cacheKey, Func getCacheItem) - { - return getCacheItem(); - } - - public object GetCacheItem(string cacheKey, Func getCacheItem, TimeSpan? timeout, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, string[] dependentFiles = null) - { - return getCacheItem(); - } - - public void InsertCacheItem(string cacheKey, Func getCacheItem, TimeSpan? timeout = null, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, string[] dependentFiles = null) - { } - } -} diff --git a/src/Umbraco.Core/Cache/ObjectCacheRuntimeCacheProvider.cs b/src/Umbraco.Core/Cache/ObjectCacheAppCache.cs similarity index 73% rename from src/Umbraco.Core/Cache/ObjectCacheRuntimeCacheProvider.cs rename to src/Umbraco.Core/Cache/ObjectCacheAppCache.cs index 8a844bbc9b..9c5917a53c 100644 --- a/src/Umbraco.Core/Cache/ObjectCacheRuntimeCacheProvider.cs +++ b/src/Umbraco.Core/Cache/ObjectCacheAppCache.cs @@ -11,31 +11,142 @@ using CacheItemPriority = System.Web.Caching.CacheItemPriority; namespace Umbraco.Core.Cache { /// - /// Represents a cache provider that caches item in a . - /// A cache provider that wraps the logic of a System.Runtime.Caching.ObjectCache + /// Implements on top of a . /// - /// The 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. - public class ObjectCacheRuntimeCacheProvider : IRuntimeCacheProvider + public class ObjectCacheAppCache : IAppPolicedCache { private readonly ReaderWriterLockSlim _locker = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion); - internal ObjectCache MemoryCache; /// - /// Used for debugging + /// Initializes a new instance of the . /// - internal Guid InstanceId { get; private set; } - - public ObjectCacheRuntimeCacheProvider() + public ObjectCacheAppCache() { + // 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. MemoryCache = new MemoryCache("in-memory"); - InstanceId = Guid.NewGuid(); } - #region Clear + /// + /// Gets the internal memory cache, for tests only! + /// + internal readonly ObjectCache MemoryCache; - public virtual void ClearAllCache() + /// + public object Get(string key) + { + Lazy result; + try + { + _locker.EnterReadLock(); + result = MemoryCache.Get(key) as Lazy; // null if key not found + } + finally + { + if (_locker.IsReadLockHeld) + _locker.ExitReadLock(); + } + return result == null ? null : FastDictionaryAppCacheBase.GetSafeLazyValue(result); // return exceptions as null + } + + /// + public object Get(string key, Func factory) + { + return Get(key, factory, null); + } + + /// + public IEnumerable SearchByKey(string keyStartsWith) + { + KeyValuePair[] 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 => FastDictionaryAppCacheBase.GetSafeLazyValue((Lazy)x.Value)) // return exceptions as null + .Where(x => x != null) // backward compat, don't store null values in the cache + .ToList(); + } + + /// + public IEnumerable SearchByRegex(string regex) + { + var compiled = new Regex(regex, RegexOptions.Compiled); + + KeyValuePair[] 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 => FastDictionaryAppCacheBase.GetSafeLazyValue((Lazy)x.Value)) // return exceptions as null + .Where(x => x != null) // backward compat, don't store null values in the cache + .ToList(); + } + + /// + public object Get(string key, Func factory, TimeSpan? timeout, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, string[] dependentFiles = null) + { + // see notes in HttpRuntimeCacheProvider + + Lazy result; + + using (var lck = new UpgradeableReadLock(_locker)) + { + result = MemoryCache.Get(key) as Lazy; + if (result == null || FastDictionaryAppCacheBase.GetSafeLazyValue(result, true) == null) // get non-created as NonCreatedValue & exceptions as null + { + result = FastDictionaryAppCacheBase.GetSafeLazy(factory); + var policy = GetPolicy(timeout, isSliding, removedCallback, dependentFiles); + + 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 FastDictionaryAppCacheBase.ExceptionHolder eh) eh.Exception.Throw(); // throw once! + return value; + } + + /// + public void Insert(string key, Func factory, TimeSpan? timeout = null, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, string[] dependentFiles = null) + { + // NOTE - here also we must insert a Lazy but we can evaluate it right now + // and make sure we don't store a null value. + + var result = FastDictionaryAppCacheBase.GetSafeLazy(factory); + var value = result.Value; // force evaluation now + if (value == null) return; // do not store null values (backward compat) + + var policy = GetPolicy(timeout, isSliding, removedCallback, dependentFiles); + //NOTE: This does an add or update + MemoryCache.Set(key, result, policy); + } + + /// + public virtual void Clear() { try { @@ -50,7 +161,8 @@ namespace Umbraco.Core.Cache } } - public virtual void ClearCacheItem(string key) + /// + public virtual void Clear(string key) { try { @@ -65,7 +177,8 @@ namespace Umbraco.Core.Cache } } - public virtual void ClearCacheObjectTypes(string typeName) + /// + public virtual void ClearOfType(string typeName) { var type = TypeFinder.GetTypeByName(typeName); if (type == null) return; @@ -79,7 +192,7 @@ namespace Umbraco.Core.Cache // x.Value is Lazy 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 = DictionaryCacheProviderBase.GetSafeLazyValue((Lazy)x.Value, true); + var value = FastDictionaryAppCacheBase.GetSafeLazyValue((Lazy)x.Value, true); // if T is an interface remove anything that implements that interface // otherwise remove exact types (not inherited types) @@ -96,12 +209,13 @@ namespace Umbraco.Core.Cache } } - public virtual void ClearCacheObjectTypes() + /// + public virtual void ClearOfType() { try { _locker.EnterWriteLock(); - var typeOfT = typeof (T); + var typeOfT = typeof(T); var isInterface = typeOfT.IsInterface; foreach (var key in MemoryCache .Where(x => @@ -109,7 +223,7 @@ namespace Umbraco.Core.Cache // x.Value is Lazy 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 = DictionaryCacheProviderBase.GetSafeLazyValue((Lazy)x.Value, true); + var value = FastDictionaryAppCacheBase.GetSafeLazyValue((Lazy)x.Value, true); // if T is an interface remove anything that implements that interface // otherwise remove exact types (not inherited types) @@ -127,7 +241,8 @@ namespace Umbraco.Core.Cache } } - public virtual void ClearCacheObjectTypes(Func predicate) + /// + public virtual void ClearOfType(Func predicate) { try { @@ -140,7 +255,7 @@ namespace Umbraco.Core.Cache // x.Value is Lazy 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 = DictionaryCacheProviderBase.GetSafeLazyValue((Lazy)x.Value, true); + var value = FastDictionaryAppCacheBase.GetSafeLazyValue((Lazy)x.Value, true); if (value == null) return true; // if T is an interface remove anything that implements that interface @@ -159,7 +274,8 @@ namespace Umbraco.Core.Cache } } - public virtual void ClearCacheByKeySearch(string keyStartsWith) + /// + public virtual void ClearByKey(string keyStartsWith) { try { @@ -177,13 +293,16 @@ namespace Umbraco.Core.Cache } } - public virtual void ClearCacheByKeyExpression(string regexString) + /// + public virtual void ClearByRegex(string regex) { + var compiled = new Regex(regex, RegexOptions.Compiled); + try { _locker.EnterWriteLock(); foreach (var key in MemoryCache - .Where(x => Regex.IsMatch(x.Key, regexString)) + .Where(x => compiled.IsMatch(x.Key)) .Select(x => x.Key) .ToArray()) // ToArray required to remove MemoryCache.Remove(key); @@ -195,120 +314,6 @@ namespace Umbraco.Core.Cache } } - #endregion - - #region Get - - public IEnumerable GetCacheItemsByKeySearch(string keyStartsWith) - { - KeyValuePair[] 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 => DictionaryCacheProviderBase.GetSafeLazyValue((Lazy)x.Value)) // return exceptions as null - .Where(x => x != null) // backward compat, don't store null values in the cache - .ToList(); - } - - public IEnumerable GetCacheItemsByKeyExpression(string regexString) - { - KeyValuePair[] entries; - try - { - _locker.EnterReadLock(); - entries = MemoryCache - .Where(x => Regex.IsMatch(x.Key, regexString)) - .ToArray(); // evaluate while locked - } - finally - { - if (_locker.IsReadLockHeld) - _locker.ExitReadLock(); - } - return entries - .Select(x => DictionaryCacheProviderBase.GetSafeLazyValue((Lazy)x.Value)) // return exceptions as null - .Where(x => x != null) // backward compat, don't store null values in the cache - .ToList(); - } - - public object GetCacheItem(string cacheKey) - { - Lazy result; - try - { - _locker.EnterReadLock(); - result = MemoryCache.Get(cacheKey) as Lazy; // null if key not found - } - finally - { - if (_locker.IsReadLockHeld) - _locker.ExitReadLock(); - } - return result == null ? null : DictionaryCacheProviderBase.GetSafeLazyValue(result); // return exceptions as null - } - - public object GetCacheItem(string cacheKey, Func getCacheItem) - { - return GetCacheItem(cacheKey, getCacheItem, null); - } - - public object GetCacheItem(string cacheKey, Func getCacheItem, TimeSpan? timeout, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, string[] dependentFiles = null) - { - // see notes in HttpRuntimeCacheProvider - - Lazy result; - - using (var lck = new UpgradeableReadLock(_locker)) - { - result = MemoryCache.Get(cacheKey) as Lazy; - if (result == null || DictionaryCacheProviderBase.GetSafeLazyValue(result, true) == null) // get non-created as NonCreatedValue & exceptions as null - { - result = DictionaryCacheProviderBase.GetSafeLazy(getCacheItem); - var policy = GetPolicy(timeout, isSliding, removedCallback, dependentFiles); - - lck.UpgradeToWriteLock(); - //NOTE: This does an add or update - MemoryCache.Set(cacheKey, result, policy); - } - } - - //return result.Value; - - var value = result.Value; // will not throw (safe lazy) - if (value is DictionaryCacheProviderBase.ExceptionHolder eh) eh.Exception.Throw(); // throw once! - return value; - } - - #endregion - - #region Insert - - public void InsertCacheItem(string cacheKey, Func getCacheItem, TimeSpan? timeout = null, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, string[] dependentFiles = null) - { - // NOTE - here also we must insert a Lazy but we can evaluate it right now - // and make sure we don't store a null value. - - var result = DictionaryCacheProviderBase.GetSafeLazy(getCacheItem); - var value = result.Value; // force evaluation now - if (value == null) return; // do not store null values (backward compat) - - var policy = GetPolicy(timeout, isSliding, removedCallback, dependentFiles); - //NOTE: This does an add or update - MemoryCache.Set(cacheKey, result, policy); - } - - #endregion - private static CacheItemPolicy GetPolicy(TimeSpan? timeout = null, bool isSliding = false, CacheItemRemovedCallback removedCallback = null, string[] dependentFiles = null) { var absolute = isSliding ? ObjectCache.InfiniteAbsoluteExpiration : (timeout == null ? ObjectCache.InfiniteAbsoluteExpiration : DateTime.Now.Add(timeout.Value)); diff --git a/src/Umbraco.Core/Cache/RepositoryCachePolicyBase.cs b/src/Umbraco.Core/Cache/RepositoryCachePolicyBase.cs index 2d21d410a7..f8bba4b033 100644 --- a/src/Umbraco.Core/Cache/RepositoryCachePolicyBase.cs +++ b/src/Umbraco.Core/Cache/RepositoryCachePolicyBase.cs @@ -13,16 +13,16 @@ namespace Umbraco.Core.Cache internal abstract class RepositoryCachePolicyBase : IRepositoryCachePolicy where TEntity : class, IEntity { - private readonly IRuntimeCacheProvider _globalCache; + private readonly IAppPolicedCache _globalCache; private readonly IScopeAccessor _scopeAccessor; - protected RepositoryCachePolicyBase(IRuntimeCacheProvider globalCache, IScopeAccessor scopeAccessor) + protected RepositoryCachePolicyBase(IAppPolicedCache globalCache, IScopeAccessor scopeAccessor) { _globalCache = globalCache ?? throw new ArgumentNullException(nameof(globalCache)); _scopeAccessor = scopeAccessor ?? throw new ArgumentNullException(nameof(scopeAccessor)); } - protected IRuntimeCacheProvider Cache + protected IAppPolicedCache Cache { get { @@ -32,9 +32,9 @@ namespace Umbraco.Core.Cache case RepositoryCacheMode.Default: return _globalCache; case RepositoryCacheMode.Scoped: - return ambientScope.IsolatedRuntimeCache.GetOrCreateCache(); + return ambientScope.IsolatedCaches.GetOrCreate(); case RepositoryCacheMode.None: - return NullCacheProvider.Instance; + return NoAppCache.Instance; default: throw new NotSupportedException($"Repository cache mode {ambientScope.RepositoryCacheMode} is not supported."); } diff --git a/src/Umbraco.Core/Cache/SingleItemsOnlyRepositoryCachePolicy.cs b/src/Umbraco.Core/Cache/SingleItemsOnlyRepositoryCachePolicy.cs index d89524d4f9..714798a47c 100644 --- a/src/Umbraco.Core/Cache/SingleItemsOnlyRepositoryCachePolicy.cs +++ b/src/Umbraco.Core/Cache/SingleItemsOnlyRepositoryCachePolicy.cs @@ -16,7 +16,7 @@ namespace Umbraco.Core.Cache internal class SingleItemsOnlyRepositoryCachePolicy : DefaultRepositoryCachePolicy where TEntity : class, IEntity { - public SingleItemsOnlyRepositoryCachePolicy(IRuntimeCacheProvider cache, IScopeAccessor scopeAccessor, RepositoryCachePolicyOptions options) + public SingleItemsOnlyRepositoryCachePolicy(IAppPolicedCache cache, IScopeAccessor scopeAccessor, RepositoryCachePolicyOptions options) : base(cache, scopeAccessor, options) { } diff --git a/src/Umbraco.Core/Cache/StaticCacheProvider.cs b/src/Umbraco.Core/Cache/StaticCacheProvider.cs deleted file mode 100644 index 1604add4d7..0000000000 --- a/src/Umbraco.Core/Cache/StaticCacheProvider.cs +++ /dev/null @@ -1,79 +0,0 @@ -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Linq; -using System.Text.RegularExpressions; - -namespace Umbraco.Core.Cache -{ - /// - /// Represents a cache provider that statically caches item in a concurrent dictionary. - /// - public class StaticCacheProvider : ICacheProvider - { - internal readonly ConcurrentDictionary StaticCache = new ConcurrentDictionary(); - - public virtual void ClearAllCache() - { - StaticCache.Clear(); - } - - public virtual void ClearCacheItem(string key) - { - object val; - StaticCache.TryRemove(key, out val); - } - - public virtual void ClearCacheObjectTypes(string typeName) - { - StaticCache.RemoveAll(kvp => kvp.Value != null && kvp.Value.GetType().ToString().InvariantEquals(typeName)); - } - - public virtual void ClearCacheObjectTypes() - { - var typeOfT = typeof(T); - StaticCache.RemoveAll(kvp => kvp.Value != null && kvp.Value.GetType() == typeOfT); - } - - public virtual void ClearCacheObjectTypes(Func predicate) - { - var typeOfT = typeof(T); - StaticCache.RemoveAll(kvp => kvp.Value != null && kvp.Value.GetType() == typeOfT && predicate(kvp.Key, (T)kvp.Value)); - } - - public virtual void ClearCacheByKeySearch(string keyStartsWith) - { - StaticCache.RemoveAll(kvp => kvp.Key.InvariantStartsWith(keyStartsWith)); - } - - public virtual void ClearCacheByKeyExpression(string regexString) - { - StaticCache.RemoveAll(kvp => Regex.IsMatch(kvp.Key, regexString)); - } - - public virtual IEnumerable GetCacheItemsByKeySearch(string keyStartsWith) - { - return (from KeyValuePair c in StaticCache - where c.Key.InvariantStartsWith(keyStartsWith) - select c.Value).ToList(); - } - - public IEnumerable GetCacheItemsByKeyExpression(string regexString) - { - return (from KeyValuePair c in StaticCache - where Regex.IsMatch(c.Key, regexString) - select c.Value).ToList(); - } - - public virtual object GetCacheItem(string cacheKey) - { - var result = StaticCache[cacheKey]; - return result; - } - - public virtual object GetCacheItem(string cacheKey, Func getCacheItem) - { - return StaticCache.GetOrAdd(cacheKey, key => getCacheItem()); - } - } -} diff --git a/src/Umbraco.Core/Cache/HttpRuntimeCacheProvider.cs b/src/Umbraco.Core/Cache/WebCachingAppCache.cs similarity index 68% rename from src/Umbraco.Core/Cache/HttpRuntimeCacheProvider.cs rename to src/Umbraco.Core/Cache/WebCachingAppCache.cs index 835c5d1ee6..b762fcda07 100644 --- a/src/Umbraco.Core/Cache/HttpRuntimeCacheProvider.cs +++ b/src/Umbraco.Core/Cache/WebCachingAppCache.cs @@ -4,14 +4,15 @@ using System.Collections.Generic; using System.Linq; using System.Threading; using System.Web.Caching; -using CacheItemPriority = System.Web.Caching.CacheItemPriority; namespace Umbraco.Core.Cache { /// + /// Implements on top of a . /// A CacheProvider that wraps the logic of the HttpRuntime.Cache /// - internal class HttpRuntimeCacheProvider : DictionaryCacheProviderBase, IRuntimeCacheProvider + /// The underlying cache is expected to be HttpRuntime.Cache. + internal class WebCachingAppCache : FastDictionaryAppCacheBase, IAppPolicedCache { // locker object that supports upgradeable read locking // does not need to support recursion if we implement the cache correctly and ensure @@ -21,16 +22,43 @@ namespace Umbraco.Core.Cache private readonly System.Web.Caching.Cache _cache; /// - /// Used for debugging + /// Initializes a new instance of the class. /// - internal Guid InstanceId { get; private set; } - - public HttpRuntimeCacheProvider(System.Web.Caching.Cache cache) + public WebCachingAppCache(System.Web.Caching.Cache cache) { _cache = cache; - InstanceId = Guid.NewGuid(); } + /// + public override object Get(string key, Func factory) + { + return Get(key, factory, null, dependentFiles: null); + } + + /// + public object Get(string key, Func factory, TimeSpan? timeout, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, string[] dependentFiles = null) + { + CacheDependency dependency = null; + if (dependentFiles != null && dependentFiles.Any()) + { + dependency = new CacheDependency(dependentFiles); + } + return Get(key, factory, timeout, isSliding, priority, removedCallback, dependency); + } + + /// + public void Insert(string key, Func factory, TimeSpan? timeout = null, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, string[] dependentFiles = null) + { + CacheDependency dependency = null; + if (dependentFiles != null && dependentFiles.Any()) + { + dependency = new CacheDependency(dependentFiles); + } + Insert(key, factory, timeout, isSliding, priority, removedCallback, dependency); + } + + #region Dictionary + protected override IEnumerable GetDictionaryEntries() { const string prefix = CacheItemPrefix + "-"; @@ -48,6 +76,8 @@ namespace Umbraco.Core.Cache return _cache.Get(key); } + #endregion + #region Lock protected override void EnterReadLock() @@ -74,33 +104,9 @@ namespace Umbraco.Core.Cache #endregion - #region Get - - /// - /// Gets (and adds if necessary) an item from the cache with all of the default parameters - /// - /// - /// - /// - public override object GetCacheItem(string cacheKey, Func getCacheItem) + private object Get(string key, Func factory, TimeSpan? timeout, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, CacheDependency dependency = null) { - return GetCacheItem(cacheKey, getCacheItem, null, dependentFiles: null); - } - - /// - /// This overload is here for legacy purposes - /// - /// - /// - /// - /// - /// - /// - /// - /// - internal object GetCacheItem(string cacheKey, Func getCacheItem, TimeSpan? timeout, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, CacheDependency dependency = null) - { - cacheKey = GetCacheKey(cacheKey); + key = GetCacheKey(key); // NOTE - because we don't know what getCacheItem does, how long it will take and whether it will hang, // getCacheItem should run OUTSIDE of the global application lock else we run into lock contention and @@ -133,7 +139,7 @@ namespace Umbraco.Core.Cache try { _locker.EnterReadLock(); - result = _cache.Get(cacheKey) as Lazy; // null if key not found + result = _cache.Get(key) as Lazy; // null if key not found } finally { @@ -145,7 +151,7 @@ namespace Umbraco.Core.Cache using (var lck = new UpgradeableReadLock(_locker)) { - result = _cache.Get(cacheKey) as Lazy; // null if key not found + result = _cache.Get(key) as Lazy; // null if key not found // cannot create value within the lock, so if result.IsValueCreated is false, just // do nothing here - means that if creation throws, a race condition could cause @@ -153,13 +159,13 @@ namespace Umbraco.Core.Cache if (result == null || GetSafeLazyValue(result, true) == null) // get non-created as NonCreatedValue & exceptions as null { - result = GetSafeLazy(getCacheItem); + result = GetSafeLazy(factory); var absolute = isSliding ? System.Web.Caching.Cache.NoAbsoluteExpiration : (timeout == null ? System.Web.Caching.Cache.NoAbsoluteExpiration : DateTime.Now.Add(timeout.Value)); var sliding = isSliding == false ? System.Web.Caching.Cache.NoSlidingExpiration : (timeout ?? System.Web.Caching.Cache.NoSlidingExpiration); lck.UpgradeToWriteLock(); //NOTE: 'Insert' on System.Web.Caching.Cache actually does an add or update! - _cache.Insert(cacheKey, result, dependency, absolute, sliding, priority, removedCallback); + _cache.Insert(key, result, dependency, absolute, sliding, priority, removedCallback); } } @@ -175,31 +181,7 @@ namespace Umbraco.Core.Cache return value; } - public object GetCacheItem(string cacheKey, Func getCacheItem, TimeSpan? timeout, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, string[] dependentFiles = null) - { - CacheDependency dependency = null; - if (dependentFiles != null && dependentFiles.Any()) - { - dependency = new CacheDependency(dependentFiles); - } - return GetCacheItem(cacheKey, getCacheItem, timeout, isSliding, priority, removedCallback, dependency); - } - - #endregion - - #region Insert - - /// - /// This overload is here for legacy purposes - /// - /// - /// - /// - /// - /// - /// - /// - internal void InsertCacheItem(string cacheKey, Func getCacheItem, TimeSpan? timeout = null, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, CacheDependency dependency = null) + private void Insert(string cacheKey, Func getCacheItem, TimeSpan? timeout = null, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, CacheDependency dependency = null) { // NOTE - here also we must insert a Lazy but we can evaluate it right now // and make sure we don't store a null value. @@ -225,17 +207,5 @@ namespace Umbraco.Core.Cache _locker.ExitWriteLock(); } } - - public void InsertCacheItem(string cacheKey, Func getCacheItem, TimeSpan? timeout = null, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, string[] dependentFiles = null) - { - CacheDependency dependency = null; - if (dependentFiles != null && dependentFiles.Any()) - { - dependency = new CacheDependency(dependentFiles); - } - InsertCacheItem(cacheKey, getCacheItem, timeout, isSliding, priority, removedCallback, dependency); - } - - #endregion } } diff --git a/src/Umbraco.Core/Composing/TypeLoader.cs b/src/Umbraco.Core/Composing/TypeLoader.cs index acb12ab575..fe277676d7 100644 --- a/src/Umbraco.Core/Composing/TypeLoader.cs +++ b/src/Umbraco.Core/Composing/TypeLoader.cs @@ -29,7 +29,7 @@ namespace Umbraco.Core.Composing { private const string CacheKey = "umbraco-types.list"; - private readonly IRuntimeCacheProvider _runtimeCache; + private readonly IAppPolicedCache _runtimeCache; private readonly IProfilingLogger _logger; private readonly Dictionary _types = new Dictionary(); @@ -51,7 +51,7 @@ namespace Umbraco.Core.Composing /// The application runtime cache. /// Files storage mode. /// A profiling logger. - public TypeLoader(IRuntimeCacheProvider runtimeCache, LocalTempStorage localTempStorage, IProfilingLogger logger) + public TypeLoader(IAppPolicedCache runtimeCache, LocalTempStorage localTempStorage, IProfilingLogger logger) : this(runtimeCache, localTempStorage, logger, true) { } @@ -62,7 +62,7 @@ namespace Umbraco.Core.Composing /// Files storage mode. /// A profiling logger. /// Whether to detect changes using hashes. - internal TypeLoader(IRuntimeCacheProvider runtimeCache, LocalTempStorage localTempStorage, IProfilingLogger logger, bool detectChanges) + internal TypeLoader(IAppPolicedCache runtimeCache, LocalTempStorage localTempStorage, IProfilingLogger logger, bool detectChanges) { _runtimeCache = runtimeCache ?? throw new ArgumentNullException(nameof(runtimeCache)); _localTempStorage = localTempStorage == LocalTempStorage.Unknown ? LocalTempStorage.Default : localTempStorage; @@ -478,7 +478,7 @@ namespace Umbraco.Core.Composing var typesHashFilePath = GetTypesHashFilePath(); DeleteFile(typesHashFilePath, FileDeleteTimeout); - _runtimeCache.ClearCacheItem(CacheKey); + _runtimeCache.Clear(CacheKey); } private Stream GetFileStream(string path, FileMode fileMode, FileAccess fileAccess, FileShare fileShare, int timeoutMilliseconds) diff --git a/src/Umbraco.Core/ConfigsExtensions.cs b/src/Umbraco.Core/ConfigsExtensions.cs index 1414dbc852..9b2abda53c 100644 --- a/src/Umbraco.Core/ConfigsExtensions.cs +++ b/src/Umbraco.Core/ConfigsExtensions.cs @@ -46,7 +46,7 @@ namespace Umbraco.Core configs.Add(() => new CoreDebug()); // GridConfig depends on runtime caches, manifest parsers... and cannot be available during composition - configs.Add(factory => new GridConfig(factory.GetInstance(), factory.GetInstance(), configDir, factory.GetInstance().Debug)); + configs.Add(factory => new GridConfig(factory.GetInstance(), factory.GetInstance(), configDir, factory.GetInstance().Debug)); } } } \ No newline at end of file diff --git a/src/Umbraco.Core/Configuration/Grid/GridConfig.cs b/src/Umbraco.Core/Configuration/Grid/GridConfig.cs index 6c16a5e7ef..979eccb839 100644 --- a/src/Umbraco.Core/Configuration/Grid/GridConfig.cs +++ b/src/Umbraco.Core/Configuration/Grid/GridConfig.cs @@ -6,7 +6,7 @@ namespace Umbraco.Core.Configuration.Grid { class GridConfig : IGridConfig { - public GridConfig(ILogger logger, IRuntimeCacheProvider runtimeCache, DirectoryInfo configFolder, bool isDebug) + public GridConfig(ILogger logger, IAppPolicedCache runtimeCache, DirectoryInfo configFolder, bool isDebug) { EditorsConfig = new GridEditorsConfig(logger, runtimeCache, configFolder, isDebug); } diff --git a/src/Umbraco.Core/Configuration/Grid/GridEditorsConfig.cs b/src/Umbraco.Core/Configuration/Grid/GridEditorsConfig.cs index 94249aa135..121b74194c 100644 --- a/src/Umbraco.Core/Configuration/Grid/GridEditorsConfig.cs +++ b/src/Umbraco.Core/Configuration/Grid/GridEditorsConfig.cs @@ -13,11 +13,11 @@ namespace Umbraco.Core.Configuration.Grid internal class GridEditorsConfig : IGridEditorsConfig { private readonly ILogger _logger; - private readonly IRuntimeCacheProvider _runtimeCache; + private readonly IAppPolicedCache _runtimeCache; private readonly DirectoryInfo _configFolder; private readonly bool _isDebug; - public GridEditorsConfig(ILogger logger, IRuntimeCacheProvider runtimeCache, DirectoryInfo configFolder, bool isDebug) + public GridEditorsConfig(ILogger logger, IAppPolicedCache runtimeCache, DirectoryInfo configFolder, bool isDebug) { _logger = logger; _runtimeCache = runtimeCache; diff --git a/src/Umbraco.Core/Manifest/ManifestParser.cs b/src/Umbraco.Core/Manifest/ManifestParser.cs index 59753df66a..fd344674af 100644 --- a/src/Umbraco.Core/Manifest/ManifestParser.cs +++ b/src/Umbraco.Core/Manifest/ManifestParser.cs @@ -20,7 +20,7 @@ namespace Umbraco.Core.Manifest { private static readonly string Utf8Preamble = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble()); - private readonly IRuntimeCacheProvider _cache; + private readonly IAppPolicedCache _cache; private readonly ILogger _logger; private readonly ManifestValueValidatorCollection _validators; @@ -29,14 +29,14 @@ namespace Umbraco.Core.Manifest /// /// Initializes a new instance of the class. /// - public ManifestParser(IRuntimeCacheProvider cache, ManifestValueValidatorCollection validators, ILogger logger) + public ManifestParser(IAppPolicedCache cache, ManifestValueValidatorCollection validators, ILogger logger) : this(cache, validators, "~/App_Plugins", logger) { } /// /// Initializes a new instance of the class. /// - private ManifestParser(IRuntimeCacheProvider cache, ManifestValueValidatorCollection validators, string path, ILogger logger) + private ManifestParser(IAppPolicedCache cache, ManifestValueValidatorCollection validators, string path, ILogger logger) { _cache = cache ?? throw new ArgumentNullException(nameof(cache)); _validators = validators ?? throw new ArgumentNullException(nameof(validators)); diff --git a/src/Umbraco.Core/Models/UserExtensions.cs b/src/Umbraco.Core/Models/UserExtensions.cs index ba4d8cf590..7db3e3adbe 100644 --- a/src/Umbraco.Core/Models/UserExtensions.cs +++ b/src/Umbraco.Core/Models/UserExtensions.cs @@ -54,7 +54,7 @@ namespace Umbraco.Core.Models /// /// A list of 5 different sized avatar URLs /// - internal static string[] GetUserAvatarUrls(this IUser user, ICacheProvider staticCache) + internal static string[] GetUserAvatarUrls(this IUser user, IAppCache staticCache) { // If FIPS is required, never check the Gravatar service as it only supports MD5 hashing. // Unfortunately, if the FIPS setting is enabled on Windows, using MD5 will throw an exception diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/ConsentRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/ConsentRepository.cs index bd55654809..8df9bf686d 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/ConsentRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/ConsentRepository.cs @@ -86,7 +86,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement Database.Update(dto); entity.ResetDirtyProperties(); - IsolatedCache.ClearCacheItem(RepositoryCacheKeys.GetKey(entity.Id)); + IsolatedCache.Clear(RepositoryCacheKeys.GetKey(entity.Id)); } /// diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/DictionaryRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/DictionaryRepository.cs index 3517fb3545..9b191d830c 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/DictionaryRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/DictionaryRepository.cs @@ -174,8 +174,8 @@ namespace Umbraco.Core.Persistence.Repositories.Implement entity.ResetDirtyProperties(); //Clear the cache entries that exist by uniqueid/item key - IsolatedCache.ClearCacheItem(RepositoryCacheKeys.GetKey(entity.ItemKey)); - IsolatedCache.ClearCacheItem(RepositoryCacheKeys.GetKey(entity.Key)); + IsolatedCache.Clear(RepositoryCacheKeys.GetKey(entity.ItemKey)); + IsolatedCache.Clear(RepositoryCacheKeys.GetKey(entity.Key)); } protected override void PersistDeletedItem(IDictionaryItem entity) @@ -186,8 +186,8 @@ namespace Umbraco.Core.Persistence.Repositories.Implement Database.Delete("WHERE id = @Id", new { Id = entity.Key }); //Clear the cache entries that exist by uniqueid/item key - IsolatedCache.ClearCacheItem(RepositoryCacheKeys.GetKey(entity.ItemKey)); - IsolatedCache.ClearCacheItem(RepositoryCacheKeys.GetKey(entity.Key)); + IsolatedCache.Clear(RepositoryCacheKeys.GetKey(entity.ItemKey)); + IsolatedCache.Clear(RepositoryCacheKeys.GetKey(entity.Key)); entity.DeleteDate = DateTime.Now; } @@ -203,8 +203,8 @@ namespace Umbraco.Core.Persistence.Repositories.Implement Database.Delete("WHERE id = @Id", new { Id = dto.UniqueId }); //Clear the cache entries that exist by uniqueid/item key - IsolatedCache.ClearCacheItem(RepositoryCacheKeys.GetKey(dto.Key)); - IsolatedCache.ClearCacheItem(RepositoryCacheKeys.GetKey(dto.UniqueId)); + IsolatedCache.Clear(RepositoryCacheKeys.GetKey(dto.Key)); + IsolatedCache.Clear(RepositoryCacheKeys.GetKey(dto.UniqueId)); } } diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/RepositoryBaseOfTIdTEntity.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/RepositoryBaseOfTIdTEntity.cs index 2626f60123..f106949c77 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/RepositoryBaseOfTIdTEntity.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/RepositoryBaseOfTIdTEntity.cs @@ -30,7 +30,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement protected AppCaches GlobalCache { get; } - protected IRuntimeCacheProvider GlobalIsolatedCache => GlobalCache.IsolatedRuntimeCache.GetOrCreateCache(); + protected IAppPolicedCache GlobalIsolatedCache => GlobalCache.IsolatedCaches.GetOrCreate(); protected IScopeAccessor ScopeAccessor { get; } @@ -60,18 +60,18 @@ namespace Umbraco.Core.Persistence.Repositories.Implement /// Gets the isolated cache. /// /// Depends on the ambient scope cache mode. - protected IRuntimeCacheProvider IsolatedCache + protected IAppPolicedCache IsolatedCache { get { switch (AmbientScope.RepositoryCacheMode) { case RepositoryCacheMode.Default: - return GlobalCache.IsolatedRuntimeCache.GetOrCreateCache(); + return GlobalCache.IsolatedCaches.GetOrCreate(); case RepositoryCacheMode.Scoped: - return AmbientScope.IsolatedRuntimeCache.GetOrCreateCache(); + return AmbientScope.IsolatedCaches.GetOrCreate(); case RepositoryCacheMode.None: - return NullCacheProvider.Instance; + return NoAppCache.Instance; default: throw new Exception("oops: cache mode."); } @@ -157,7 +157,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement /// /// Adds or Updates an entity of type TEntity /// - /// This method is backed by an cache + /// This method is backed by an cache /// public void Save(TEntity entity) { diff --git a/src/Umbraco.Core/Runtime/CoreRuntime.cs b/src/Umbraco.Core/Runtime/CoreRuntime.cs index f29109b9d2..e37b5e254e 100644 --- a/src/Umbraco.Core/Runtime/CoreRuntime.cs +++ b/src/Umbraco.Core/Runtime/CoreRuntime.cs @@ -332,10 +332,10 @@ namespace Umbraco.Core.Runtime // is overriden by the web runtime return new AppCaches( - new DeepCloneRuntimeCacheProvider(new ObjectCacheRuntimeCacheProvider()), - new StaticCacheProvider(), - NullCacheProvider.Instance, - new IsolatedRuntimeCache(type => new DeepCloneRuntimeCacheProvider(new ObjectCacheRuntimeCacheProvider()))); + new DeepCloneAppCache(new ObjectCacheAppCache()), + new DictionaryCacheProvider(), + NoAppCache.Instance, + new IsolatedCaches(type => new DeepCloneAppCache(new ObjectCacheAppCache()))); } // by default, returns null, meaning that Umbraco should auto-detect the application root path. diff --git a/src/Umbraco.Core/Scoping/IScope.cs b/src/Umbraco.Core/Scoping/IScope.cs index eefc964965..de4eef0a08 100644 --- a/src/Umbraco.Core/Scoping/IScope.cs +++ b/src/Umbraco.Core/Scoping/IScope.cs @@ -38,7 +38,7 @@ namespace Umbraco.Core.Scoping /// /// Gets the scope isolated cache. /// - IsolatedRuntimeCache IsolatedRuntimeCache { get; } + IsolatedCaches IsolatedCaches { get; } /// /// Completes the scope. diff --git a/src/Umbraco.Core/Scoping/Scope.cs b/src/Umbraco.Core/Scoping/Scope.cs index b8d4d7b430..aa08016d3c 100644 --- a/src/Umbraco.Core/Scoping/Scope.cs +++ b/src/Umbraco.Core/Scoping/Scope.cs @@ -34,7 +34,7 @@ namespace Umbraco.Core.Scoping private bool _disposed; private bool? _completed; - private IsolatedRuntimeCache _isolatedRuntimeCache; + private IsolatedCaches _isolatedCaches; private IUmbracoDatabase _database; private EventMessages _messages; private ICompletable _fscope; @@ -177,14 +177,14 @@ namespace Umbraco.Core.Scoping } /// - public IsolatedRuntimeCache IsolatedRuntimeCache + public IsolatedCaches IsolatedCaches { get { - if (ParentScope != null) return ParentScope.IsolatedRuntimeCache; + if (ParentScope != null) return ParentScope.IsolatedCaches; - return _isolatedRuntimeCache ?? (_isolatedRuntimeCache - = new IsolatedRuntimeCache(type => new DeepCloneRuntimeCacheProvider(new ObjectCacheRuntimeCacheProvider()))); + return _isolatedCaches ?? (_isolatedCaches + = new IsolatedCaches(type => new DeepCloneAppCache(new ObjectCacheAppCache()))); } } diff --git a/src/Umbraco.Core/Services/Implement/LocalizedTextServiceFileSources.cs b/src/Umbraco.Core/Services/Implement/LocalizedTextServiceFileSources.cs index 3b3f90a412..5577508adb 100644 --- a/src/Umbraco.Core/Services/Implement/LocalizedTextServiceFileSources.cs +++ b/src/Umbraco.Core/Services/Implement/LocalizedTextServiceFileSources.cs @@ -17,7 +17,7 @@ namespace Umbraco.Core.Services.Implement public class LocalizedTextServiceFileSources { private readonly ILogger _logger; - private readonly IRuntimeCacheProvider _cache; + private readonly IAppPolicedCache _cache; private readonly IEnumerable _supplementFileSources; private readonly DirectoryInfo _fileSourceFolder; @@ -37,7 +37,7 @@ namespace Umbraco.Core.Services.Implement /// public LocalizedTextServiceFileSources( ILogger logger, - IRuntimeCacheProvider cache, + IAppPolicedCache cache, DirectoryInfo fileSourceFolder, IEnumerable supplementFileSources) { @@ -140,7 +140,7 @@ namespace Umbraco.Core.Services.Implement /// /// /// - public LocalizedTextServiceFileSources(ILogger logger, IRuntimeCacheProvider cache, DirectoryInfo fileSourceFolder) + public LocalizedTextServiceFileSources(ILogger logger, IAppPolicedCache cache, DirectoryInfo fileSourceFolder) : this(logger, cache, fileSourceFolder, Enumerable.Empty()) { diff --git a/src/Umbraco.Core/Umbraco.Core.csproj b/src/Umbraco.Core/Umbraco.Core.csproj index 79162c06ad..41f2bc4951 100755 --- a/src/Umbraco.Core/Umbraco.Core.csproj +++ b/src/Umbraco.Core/Umbraco.Core.csproj @@ -109,6 +109,7 @@ + @@ -118,29 +119,29 @@ - + - - + + - - - + + + - - + + - - + + - + diff --git a/src/Umbraco.Tests/Cache/CacheProviderTests.cs b/src/Umbraco.Tests/Cache/CacheProviderTests.cs index d060df3c56..f2288cbaf2 100644 --- a/src/Umbraco.Tests/Cache/CacheProviderTests.cs +++ b/src/Umbraco.Tests/Cache/CacheProviderTests.cs @@ -9,7 +9,7 @@ namespace Umbraco.Tests.Cache { public abstract class CacheProviderTests { - internal abstract ICacheProvider Provider { get; } + internal abstract IAppCache Provider { get; } protected abstract int GetTotalItemCount { get; } [SetUp] @@ -21,7 +21,7 @@ namespace Umbraco.Tests.Cache [TearDown] public virtual void TearDown() { - Provider.ClearAllCache(); + Provider.Clear(); } [Test] @@ -32,11 +32,11 @@ namespace Umbraco.Tests.Cache Assert.Ignore("Do not run for StaticCacheProvider."); Exception exception = null; - var result = Provider.GetCacheItem("blah", () => + var result = Provider.Get("blah", () => { try { - var result2 = Provider.GetCacheItem("blah"); + var result2 = Provider.Get("blah"); } catch (Exception e) { @@ -56,7 +56,7 @@ namespace Umbraco.Tests.Cache object result; try { - result = Provider.GetCacheItem("Blah", () => + result = Provider.Get("Blah", () => { counter++; throw new Exception("Do not cache this"); @@ -66,7 +66,7 @@ namespace Umbraco.Tests.Cache try { - result = Provider.GetCacheItem("Blah", () => + result = Provider.Get("Blah", () => { counter++; throw new Exception("Do not cache this"); @@ -85,13 +85,13 @@ namespace Umbraco.Tests.Cache object result; - result = Provider.GetCacheItem("Blah", () => + result = Provider.Get("Blah", () => { counter++; return ""; }); - result = Provider.GetCacheItem("Blah", () => + result = Provider.Get("Blah", () => { counter++; return ""; @@ -108,14 +108,14 @@ namespace Umbraco.Tests.Cache var cacheContent2 = new MacroCacheContent(new LiteralControl(), "Test2"); var cacheContent3 = new MacroCacheContent(new LiteralControl(), "Test3"); var cacheContent4 = new LiteralControl(); - Provider.GetCacheItem("Test1", () => cacheContent1); - Provider.GetCacheItem("Tester2", () => cacheContent2); - Provider.GetCacheItem("Tes3", () => cacheContent3); - Provider.GetCacheItem("different4", () => cacheContent4); + Provider.Get("Test1", () => cacheContent1); + Provider.Get("Tester2", () => cacheContent2); + Provider.Get("Tes3", () => cacheContent3); + Provider.Get("different4", () => cacheContent4); Assert.AreEqual(4, GetTotalItemCount); - var result = Provider.GetCacheItemsByKeySearch("Tes"); + var result = Provider.SearchByKey("Tes"); Assert.AreEqual(3, result.Count()); } @@ -127,14 +127,14 @@ namespace Umbraco.Tests.Cache var cacheContent2 = new MacroCacheContent(new LiteralControl(), "Test2"); var cacheContent3 = new MacroCacheContent(new LiteralControl(), "Test3"); var cacheContent4 = new LiteralControl(); - Provider.GetCacheItem("TTes1t", () => cacheContent1); - Provider.GetCacheItem("Tester2", () => cacheContent2); - Provider.GetCacheItem("Tes3", () => cacheContent3); - Provider.GetCacheItem("different4", () => cacheContent4); + Provider.Get("TTes1t", () => cacheContent1); + Provider.Get("Tester2", () => cacheContent2); + Provider.Get("Tes3", () => cacheContent3); + Provider.Get("different4", () => cacheContent4); Assert.AreEqual(4, GetTotalItemCount); - Provider.ClearCacheByKeyExpression("^\\w+es\\d.*"); + Provider.ClearByRegex("^\\w+es\\d.*"); Assert.AreEqual(2, GetTotalItemCount); } @@ -146,14 +146,14 @@ namespace Umbraco.Tests.Cache var cacheContent2 = new MacroCacheContent(new LiteralControl(), "Test2"); var cacheContent3 = new MacroCacheContent(new LiteralControl(), "Test3"); var cacheContent4 = new LiteralControl(); - Provider.GetCacheItem("Test1", () => cacheContent1); - Provider.GetCacheItem("Tester2", () => cacheContent2); - Provider.GetCacheItem("Tes3", () => cacheContent3); - Provider.GetCacheItem("different4", () => cacheContent4); + Provider.Get("Test1", () => cacheContent1); + Provider.Get("Tester2", () => cacheContent2); + Provider.Get("Tes3", () => cacheContent3); + Provider.Get("different4", () => cacheContent4); Assert.AreEqual(4, GetTotalItemCount); - Provider.ClearCacheByKeySearch("Test"); + Provider.ClearByKey("Test"); Assert.AreEqual(2, GetTotalItemCount); } @@ -165,15 +165,15 @@ namespace Umbraco.Tests.Cache var cacheContent2 = new MacroCacheContent(new LiteralControl(), "Test2"); var cacheContent3 = new MacroCacheContent(new LiteralControl(), "Test3"); var cacheContent4 = new LiteralControl(); - Provider.GetCacheItem("Test1", () => cacheContent1); - Provider.GetCacheItem("Test2", () => cacheContent2); - Provider.GetCacheItem("Test3", () => cacheContent3); - Provider.GetCacheItem("Test4", () => cacheContent4); + Provider.Get("Test1", () => cacheContent1); + Provider.Get("Test2", () => cacheContent2); + Provider.Get("Test3", () => cacheContent3); + Provider.Get("Test4", () => cacheContent4); Assert.AreEqual(4, GetTotalItemCount); - Provider.ClearCacheItem("Test1"); - Provider.ClearCacheItem("Test2"); + Provider.Clear("Test1"); + Provider.Clear("Test2"); Assert.AreEqual(2, GetTotalItemCount); } @@ -185,14 +185,14 @@ namespace Umbraco.Tests.Cache var cacheContent2 = new MacroCacheContent(new LiteralControl(), "Test2"); var cacheContent3 = new MacroCacheContent(new LiteralControl(), "Test3"); var cacheContent4 = new LiteralControl(); - Provider.GetCacheItem("Test1", () => cacheContent1); - Provider.GetCacheItem("Test2", () => cacheContent2); - Provider.GetCacheItem("Test3", () => cacheContent3); - Provider.GetCacheItem("Test4", () => cacheContent4); + Provider.Get("Test1", () => cacheContent1); + Provider.Get("Test2", () => cacheContent2); + Provider.Get("Test3", () => cacheContent3); + Provider.Get("Test4", () => cacheContent4); Assert.AreEqual(4, GetTotalItemCount); - Provider.ClearAllCache(); + Provider.Clear(); Assert.AreEqual(0, GetTotalItemCount); } @@ -201,7 +201,7 @@ namespace Umbraco.Tests.Cache public void Can_Add_When_Not_Available() { var cacheContent1 = new MacroCacheContent(new LiteralControl(), "Test1"); - Provider.GetCacheItem("Test1", () => cacheContent1); + Provider.Get("Test1", () => cacheContent1); Assert.AreEqual(1, GetTotalItemCount); } @@ -209,8 +209,8 @@ namespace Umbraco.Tests.Cache public void Can_Get_When_Available() { var cacheContent1 = new MacroCacheContent(new LiteralControl(), "Test1"); - var result = Provider.GetCacheItem("Test1", () => cacheContent1); - var result2 = Provider.GetCacheItem("Test1", () => cacheContent1); + var result = Provider.Get("Test1", () => cacheContent1); + var result2 = Provider.Get("Test1", () => cacheContent1); Assert.AreEqual(1, GetTotalItemCount); Assert.AreEqual(result, result2); } @@ -222,15 +222,15 @@ namespace Umbraco.Tests.Cache var cacheContent2 = new MacroCacheContent(new LiteralControl(), "Test2"); var cacheContent3 = new MacroCacheContent(new LiteralControl(), "Test3"); var cacheContent4 = new LiteralControl(); - Provider.GetCacheItem("Test1", () => cacheContent1); - Provider.GetCacheItem("Test2", () => cacheContent2); - Provider.GetCacheItem("Test3", () => cacheContent3); - Provider.GetCacheItem("Test4", () => cacheContent4); + Provider.Get("Test1", () => cacheContent1); + Provider.Get("Test2", () => cacheContent2); + Provider.Get("Test3", () => cacheContent3); + Provider.Get("Test4", () => cacheContent4); Assert.AreEqual(4, GetTotalItemCount); //Provider.ClearCacheObjectTypes("umbraco.MacroCacheContent"); - Provider.ClearCacheObjectTypes(typeof(MacroCacheContent).ToString()); + Provider.ClearOfType(typeof(MacroCacheContent).ToString()); Assert.AreEqual(1, GetTotalItemCount); } @@ -242,14 +242,14 @@ namespace Umbraco.Tests.Cache var cacheContent2 = new MacroCacheContent(new LiteralControl(), "Test2"); var cacheContent3 = new MacroCacheContent(new LiteralControl(), "Test3"); var cacheContent4 = new LiteralControl(); - Provider.GetCacheItem("Test1", () => cacheContent1); - Provider.GetCacheItem("Test2", () => cacheContent2); - Provider.GetCacheItem("Test3", () => cacheContent3); - Provider.GetCacheItem("Test4", () => cacheContent4); + Provider.Get("Test1", () => cacheContent1); + Provider.Get("Test2", () => cacheContent2); + Provider.Get("Test3", () => cacheContent3); + Provider.Get("Test4", () => cacheContent4); Assert.AreEqual(4, GetTotalItemCount); - Provider.ClearCacheObjectTypes(); + Provider.ClearOfType(); Assert.AreEqual(1, GetTotalItemCount); } diff --git a/src/Umbraco.Tests/Cache/DeepCloneRuntimeCacheProviderTests.cs b/src/Umbraco.Tests/Cache/DeepCloneRuntimeCacheProviderTests.cs index 169100153e..5158989a8b 100644 --- a/src/Umbraco.Tests/Cache/DeepCloneRuntimeCacheProviderTests.cs +++ b/src/Umbraco.Tests/Cache/DeepCloneRuntimeCacheProviderTests.cs @@ -16,7 +16,7 @@ namespace Umbraco.Tests.Cache [TestFixture] public class DeepCloneRuntimeCacheProviderTests : RuntimeCacheProviderTests { - private DeepCloneRuntimeCacheProvider _provider; + private DeepCloneAppCache _provider; protected override int GetTotalItemCount { @@ -26,15 +26,15 @@ namespace Umbraco.Tests.Cache public override void Setup() { base.Setup(); - _provider = new DeepCloneRuntimeCacheProvider(new HttpRuntimeCacheProvider(HttpRuntime.Cache)); + _provider = new DeepCloneAppCache(new WebCachingAppCache(HttpRuntime.Cache)); } - internal override ICacheProvider Provider + internal override IAppCache Provider { get { return _provider; } } - internal override IRuntimeCacheProvider RuntimeProvider + internal override IAppPolicedCache RuntimeProvider { get { return _provider; } } @@ -75,15 +75,15 @@ namespace Umbraco.Tests.Cache public void DoesNotCacheExceptions() { string value; - Assert.Throws(() => { value = (string)_provider.GetCacheItem("key", () => GetValue(1)); }); - Assert.Throws(() => { value = (string)_provider.GetCacheItem("key", () => GetValue(2)); }); + Assert.Throws(() => { value = (string)_provider.Get("key", () => GetValue(1)); }); + Assert.Throws(() => { value = (string)_provider.Get("key", () => GetValue(2)); }); // does not throw - value = (string)_provider.GetCacheItem("key", () => GetValue(3)); + value = (string)_provider.Get("key", () => GetValue(3)); Assert.AreEqual("succ3", value); // cache - value = (string)_provider.GetCacheItem("key", () => GetValue(4)); + value = (string)_provider.Get("key", () => GetValue(4)); Assert.AreEqual("succ3", value); } diff --git a/src/Umbraco.Tests/Cache/DefaultCachePolicyTests.cs b/src/Umbraco.Tests/Cache/DefaultCachePolicyTests.cs index 37488600c7..0f649328fe 100644 --- a/src/Umbraco.Tests/Cache/DefaultCachePolicyTests.cs +++ b/src/Umbraco.Tests/Cache/DefaultCachePolicyTests.cs @@ -28,8 +28,8 @@ namespace Umbraco.Tests.Cache public void Caches_Single() { var isCached = false; - var cache = new Mock(); - cache.Setup(x => x.InsertCacheItem(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), + var cache = new Mock(); + cache.Setup(x => x.Insert(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Callback(() => { @@ -45,8 +45,8 @@ namespace Umbraco.Tests.Cache [Test] public void Get_Single_From_Cache() { - var cache = new Mock(); - cache.Setup(x => x.GetCacheItem(It.IsAny())).Returns(new AuditItem(1, AuditType.Copy, 123, "test", "blah")); + var cache = new Mock(); + cache.Setup(x => x.Get(It.IsAny())).Returns(new AuditItem(1, AuditType.Copy, 123, "test", "blah")); var defaultPolicy = new DefaultRepositoryCachePolicy(cache.Object, DefaultAccessor, new RepositoryCachePolicyOptions()); @@ -58,14 +58,14 @@ namespace Umbraco.Tests.Cache public void Caches_Per_Id_For_Get_All() { var cached = new List(); - var cache = new Mock(); - cache.Setup(x => x.InsertCacheItem(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), + var cache = new Mock(); + cache.Setup(x => x.Insert(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Callback((string cacheKey, Func o, TimeSpan? t, bool b, CacheItemPriority cip, CacheItemRemovedCallback circ, string[] s) => { cached.Add(cacheKey); }); - cache.Setup(x => x.GetCacheItemsByKeySearch(It.IsAny())).Returns(new AuditItem[] {}); + cache.Setup(x => x.SearchByKey(It.IsAny())).Returns(new AuditItem[] {}); var defaultPolicy = new DefaultRepositoryCachePolicy(cache.Object, DefaultAccessor, new RepositoryCachePolicyOptions()); @@ -81,8 +81,8 @@ namespace Umbraco.Tests.Cache [Test] public void Get_All_Without_Ids_From_Cache() { - var cache = new Mock(); - cache.Setup(x => x.GetCacheItemsByKeySearch(It.IsAny())).Returns(new[] + var cache = new Mock(); + cache.Setup(x => x.SearchByKey(It.IsAny())).Returns(new[] { new AuditItem(1, AuditType.Copy, 123, "test", "blah"), new AuditItem(2, AuditType.Copy, 123, "test", "blah2") @@ -98,8 +98,8 @@ namespace Umbraco.Tests.Cache public void If_CreateOrUpdate_Throws_Cache_Is_Removed() { var cacheCleared = false; - var cache = new Mock(); - cache.Setup(x => x.ClearCacheItem(It.IsAny())) + var cache = new Mock(); + cache.Setup(x => x.Clear(It.IsAny())) .Callback(() => { cacheCleared = true; @@ -124,8 +124,8 @@ namespace Umbraco.Tests.Cache public void If_Removes_Throws_Cache_Is_Removed() { var cacheCleared = false; - var cache = new Mock(); - cache.Setup(x => x.ClearCacheItem(It.IsAny())) + var cache = new Mock(); + cache.Setup(x => x.Clear(It.IsAny())) .Callback(() => { cacheCleared = true; diff --git a/src/Umbraco.Tests/Cache/FullDataSetCachePolicyTests.cs b/src/Umbraco.Tests/Cache/FullDataSetCachePolicyTests.cs index 404587bcfa..7c5a1524d2 100644 --- a/src/Umbraco.Tests/Cache/FullDataSetCachePolicyTests.cs +++ b/src/Umbraco.Tests/Cache/FullDataSetCachePolicyTests.cs @@ -37,8 +37,8 @@ namespace Umbraco.Tests.Cache }; var isCached = false; - var cache = new Mock(); - cache.Setup(x => x.InsertCacheItem(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), + var cache = new Mock(); + cache.Setup(x => x.Insert(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Callback(() => { @@ -60,8 +60,8 @@ namespace Umbraco.Tests.Cache new AuditItem(2, AuditType.Copy, 123, "test", "blah2") }; - var cache = new Mock(); - cache.Setup(x => x.GetCacheItem(It.IsAny())).Returns(new AuditItem(1, AuditType.Copy, 123, "test", "blah")); + var cache = new Mock(); + cache.Setup(x => x.Get(It.IsAny())).Returns(new AuditItem(1, AuditType.Copy, 123, "test", "blah")); var defaultPolicy = new FullDataSetRepositoryCachePolicy(cache.Object, DefaultAccessor, item => item.Id, false); @@ -78,8 +78,8 @@ namespace Umbraco.Tests.Cache IList list = null; - var cache = new Mock(); - cache.Setup(x => x.InsertCacheItem(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), + var cache = new Mock(); + cache.Setup(x => x.Insert(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Callback((string cacheKey, Func o, TimeSpan? t, bool b, CacheItemPriority cip, CacheItemRemovedCallback circ, string[] s) => { @@ -87,7 +87,7 @@ namespace Umbraco.Tests.Cache list = o() as IList; }); - cache.Setup(x => x.GetCacheItem(It.IsAny())).Returns(() => + cache.Setup(x => x.Get(It.IsAny())).Returns(() => { //return null if this is the first pass return cached.Any() ? new DeepCloneableList(ListCloneBehavior.CloneOnce) : null; @@ -121,8 +121,8 @@ namespace Umbraco.Tests.Cache var cached = new List(); IList list = null; - var cache = new Mock(); - cache.Setup(x => x.InsertCacheItem(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), + var cache = new Mock(); + cache.Setup(x => x.Insert(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Callback((string cacheKey, Func o, TimeSpan? t, bool b, CacheItemPriority cip, CacheItemRemovedCallback circ, string[] s) => { @@ -130,7 +130,7 @@ namespace Umbraco.Tests.Cache list = o() as IList; }); - cache.Setup(x => x.GetCacheItem(It.IsAny())).Returns(new AuditItem[] { }); + cache.Setup(x => x.Get(It.IsAny())).Returns(new AuditItem[] { }); var defaultPolicy = new FullDataSetRepositoryCachePolicy(cache.Object, DefaultAccessor, item => item.Id, false); @@ -145,9 +145,9 @@ namespace Umbraco.Tests.Cache { var getAll = new[] { (AuditItem)null }; - var cache = new Mock(); + var cache = new Mock(); - cache.Setup(x => x.GetCacheItem(It.IsAny())).Returns(() => new DeepCloneableList(ListCloneBehavior.CloneOnce) + cache.Setup(x => x.Get(It.IsAny())).Returns(() => new DeepCloneableList(ListCloneBehavior.CloneOnce) { new AuditItem(1, AuditType.Copy, 123, "test", "blah"), new AuditItem(2, AuditType.Copy, 123, "test", "blah2") @@ -169,8 +169,8 @@ namespace Umbraco.Tests.Cache }; var cacheCleared = false; - var cache = new Mock(); - cache.Setup(x => x.ClearCacheItem(It.IsAny())) + var cache = new Mock(); + cache.Setup(x => x.Clear(It.IsAny())) .Callback(() => { cacheCleared = true; @@ -201,8 +201,8 @@ namespace Umbraco.Tests.Cache }; var cacheCleared = false; - var cache = new Mock(); - cache.Setup(x => x.ClearCacheItem(It.IsAny())) + var cache = new Mock(); + cache.Setup(x => x.Clear(It.IsAny())) .Callback(() => { cacheCleared = true; diff --git a/src/Umbraco.Tests/Cache/HttpRequestCacheProviderTests.cs b/src/Umbraco.Tests/Cache/HttpRequestCacheProviderTests.cs index cbb8d4e49d..f442319d7f 100644 --- a/src/Umbraco.Tests/Cache/HttpRequestCacheProviderTests.cs +++ b/src/Umbraco.Tests/Cache/HttpRequestCacheProviderTests.cs @@ -7,17 +7,17 @@ namespace Umbraco.Tests.Cache [TestFixture] public class HttpRequestCacheProviderTests : CacheProviderTests { - private HttpRequestCacheProvider _provider; + private HttpRequestAppCache _provider; private FakeHttpContextFactory _ctx; public override void Setup() { base.Setup(); _ctx = new FakeHttpContextFactory("http://localhost/test"); - _provider = new HttpRequestCacheProvider(_ctx.HttpContext); + _provider = new HttpRequestAppCache(_ctx.HttpContext); } - internal override ICacheProvider Provider + internal override IAppCache Provider { get { return _provider; } } @@ -31,22 +31,22 @@ namespace Umbraco.Tests.Cache [TestFixture] public class StaticCacheProviderTests : CacheProviderTests { - private StaticCacheProvider _provider; + private DictionaryCacheProvider _provider; public override void Setup() { base.Setup(); - _provider = new StaticCacheProvider(); + _provider = new DictionaryCacheProvider(); } - internal override ICacheProvider Provider + internal override IAppCache Provider { get { return _provider; } } protected override int GetTotalItemCount { - get { return _provider.StaticCache.Count; } + get { return _provider.Items.Count; } } } } diff --git a/src/Umbraco.Tests/Cache/HttpRuntimeCacheProviderTests.cs b/src/Umbraco.Tests/Cache/HttpRuntimeCacheProviderTests.cs index 679b8c5125..56f3303e9c 100644 --- a/src/Umbraco.Tests/Cache/HttpRuntimeCacheProviderTests.cs +++ b/src/Umbraco.Tests/Cache/HttpRuntimeCacheProviderTests.cs @@ -9,7 +9,7 @@ namespace Umbraco.Tests.Cache [TestFixture] public class HttpRuntimeCacheProviderTests : RuntimeCacheProviderTests { - private HttpRuntimeCacheProvider _provider; + private WebCachingAppCache _provider; protected override int GetTotalItemCount { @@ -19,15 +19,15 @@ namespace Umbraco.Tests.Cache public override void Setup() { base.Setup(); - _provider = new HttpRuntimeCacheProvider(HttpRuntime.Cache); + _provider = new WebCachingAppCache(HttpRuntime.Cache); } - internal override ICacheProvider Provider + internal override IAppCache Provider { get { return _provider; } } - internal override IRuntimeCacheProvider RuntimeProvider + internal override IAppPolicedCache RuntimeProvider { get { return _provider; } } @@ -36,15 +36,15 @@ namespace Umbraco.Tests.Cache public void DoesNotCacheExceptions() { string value; - Assert.Throws(() => { value = (string)_provider.GetCacheItem("key", () => GetValue(1)); }); - Assert.Throws(() => { value = (string)_provider.GetCacheItem("key", () => GetValue(2)); }); + Assert.Throws(() => { value = (string)_provider.Get("key", () => GetValue(1)); }); + Assert.Throws(() => { value = (string)_provider.Get("key", () => GetValue(2)); }); // does not throw - value = (string)_provider.GetCacheItem("key", () => GetValue(3)); + value = (string)_provider.Get("key", () => GetValue(3)); Assert.AreEqual("succ3", value); // cache - value = (string)_provider.GetCacheItem("key", () => GetValue(4)); + value = (string)_provider.Get("key", () => GetValue(4)); Assert.AreEqual("succ3", value); } diff --git a/src/Umbraco.Tests/Cache/ObjectCacheProviderTests.cs b/src/Umbraco.Tests/Cache/ObjectCacheProviderTests.cs index e373fdda4d..6ed7f590e0 100644 --- a/src/Umbraco.Tests/Cache/ObjectCacheProviderTests.cs +++ b/src/Umbraco.Tests/Cache/ObjectCacheProviderTests.cs @@ -10,7 +10,7 @@ namespace Umbraco.Tests.Cache [TestFixture] public class ObjectCacheProviderTests : RuntimeCacheProviderTests { - private ObjectCacheRuntimeCacheProvider _provider; + private ObjectCacheAppCache _provider; protected override int GetTotalItemCount { @@ -20,15 +20,15 @@ namespace Umbraco.Tests.Cache public override void Setup() { base.Setup(); - _provider = new ObjectCacheRuntimeCacheProvider(); + _provider = new ObjectCacheAppCache(); } - internal override ICacheProvider Provider + internal override IAppCache Provider { get { return _provider; } } - internal override IRuntimeCacheProvider RuntimeProvider + internal override IAppPolicedCache RuntimeProvider { get { return _provider; } } diff --git a/src/Umbraco.Tests/Cache/PublishedCache/PublishedContentCacheTests.cs b/src/Umbraco.Tests/Cache/PublishedCache/PublishedContentCacheTests.cs index 12ea87087d..79d0dfb9da 100644 --- a/src/Umbraco.Tests/Cache/PublishedCache/PublishedContentCacheTests.cs +++ b/src/Umbraco.Tests/Cache/PublishedCache/PublishedContentCacheTests.cs @@ -63,7 +63,7 @@ namespace Umbraco.Tests.Cache.PublishedCache _xml = new XmlDocument(); _xml.LoadXml(GetXml()); var xmlStore = new XmlStore(() => _xml, null, null, null); - var cacheProvider = new StaticCacheProvider(); + var cacheProvider = new DictionaryCacheProvider(); var domainCache = new DomainCache(ServiceContext.DomainService, DefaultCultureAccessor); var publishedShapshot = new Umbraco.Web.PublishedCache.XmlPublishedCache.PublishedSnapshot( new PublishedContentCache(xmlStore, domainCache, cacheProvider, globalSettings, new SiteDomainHelper(), ContentTypesCache, null, null), diff --git a/src/Umbraco.Tests/Cache/PublishedCache/PublishedMediaCacheTests.cs b/src/Umbraco.Tests/Cache/PublishedCache/PublishedMediaCacheTests.cs index 6add88009d..ee16a1dede 100644 --- a/src/Umbraco.Tests/Cache/PublishedCache/PublishedMediaCacheTests.cs +++ b/src/Umbraco.Tests/Cache/PublishedCache/PublishedMediaCacheTests.cs @@ -75,7 +75,7 @@ namespace Umbraco.Tests.Cache.PublishedCache var mChild2 = MakeNewMedia("Child2", mType, user, mRoot2.Id); var ctx = GetUmbracoContext("/test"); - var cache = new PublishedMediaCache(new XmlStore((XmlDocument) null, null, null, null), ServiceContext.MediaService, ServiceContext.UserService, new StaticCacheProvider(), ContentTypesCache, Factory.GetInstance()); + var cache = new PublishedMediaCache(new XmlStore((XmlDocument) null, null, null, null), ServiceContext.MediaService, ServiceContext.UserService, new DictionaryCacheProvider(), ContentTypesCache, Factory.GetInstance()); var roots = cache.GetAtRoot(); Assert.AreEqual(2, roots.Count()); Assert.IsTrue(roots.Select(x => x.Id).ContainsAll(new[] {mRoot1.Id, mRoot2.Id})); @@ -93,7 +93,7 @@ namespace Umbraco.Tests.Cache.PublishedCache //var publishedMedia = PublishedMediaTests.GetNode(mRoot.Id, GetUmbracoContext("/test", 1234)); var umbracoContext = GetUmbracoContext("/test"); - var cache = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), Current.Services.MediaService, Current.Services.UserService, new StaticCacheProvider(), ContentTypesCache, Factory.GetInstance()); + var cache = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), Current.Services.MediaService, Current.Services.UserService, new DictionaryCacheProvider(), ContentTypesCache, Factory.GetInstance()); var publishedMedia = cache.GetById(mRoot.Id); Assert.IsNotNull(publishedMedia); @@ -204,7 +204,7 @@ namespace Umbraco.Tests.Cache.PublishedCache var result = new SearchResult("1234", 1, () => fields.ToDictionary(x => x.Key, x => new List { x.Value })); - var store = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), ServiceContext.MediaService, ServiceContext.UserService, new StaticCacheProvider(), ContentTypesCache, Factory.GetInstance()); + var store = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), ServiceContext.MediaService, ServiceContext.UserService, new DictionaryCacheProvider(), ContentTypesCache, Factory.GetInstance()); var doc = store.CreateFromCacheValues(store.ConvertFromSearchResult(result)); DoAssert(doc, 1234, key, templateIdVal: null, 0, "/media/test.jpg", "Image", 23, "Shannon", "Shannon", 0, 0, "-1,1234", DateTime.Parse("2012-07-17T10:34:09"), DateTime.Parse("2012-07-16T10:34:09"), 2); @@ -220,7 +220,7 @@ namespace Umbraco.Tests.Cache.PublishedCache var xmlDoc = GetMediaXml(); ((XmlElement)xmlDoc.DocumentElement.FirstChild).SetAttribute("key", key.ToString()); var navigator = xmlDoc.SelectSingleNode("/root/Image").CreateNavigator(); - var cache = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), ServiceContext.MediaService, ServiceContext.UserService, new StaticCacheProvider(), ContentTypesCache, Factory.GetInstance()); + var cache = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), ServiceContext.MediaService, ServiceContext.UserService, new DictionaryCacheProvider(), ContentTypesCache, Factory.GetInstance()); var doc = cache.CreateFromCacheValues(cache.ConvertFromXPathNavigator(navigator, true)); DoAssert(doc, 2000, key, templateIdVal: null, 2, "image1", "Image", 23, "Shannon", "Shannon", 33, 33, "-1,2000", DateTime.Parse("2012-06-12T14:13:17"), DateTime.Parse("2012-07-20T18:50:43"), 1); diff --git a/src/Umbraco.Tests/Cache/RuntimeCacheProviderTests.cs b/src/Umbraco.Tests/Cache/RuntimeCacheProviderTests.cs index e45dfd4250..08eb5e9a60 100644 --- a/src/Umbraco.Tests/Cache/RuntimeCacheProviderTests.cs +++ b/src/Umbraco.Tests/Cache/RuntimeCacheProviderTests.cs @@ -8,7 +8,7 @@ namespace Umbraco.Tests.Cache public abstract class RuntimeCacheProviderTests : CacheProviderTests { - internal abstract IRuntimeCacheProvider RuntimeProvider { get; } + internal abstract IAppPolicedCache RuntimeProvider { get; } [Test] @@ -16,7 +16,7 @@ namespace Umbraco.Tests.Cache public void Can_Add_And_Expire_Struct_Strongly_Typed_With_Null() { var now = DateTime.Now; - RuntimeProvider.InsertCacheItem("DateTimeTest", () => now, new TimeSpan(0, 0, 0, 0, 200)); + RuntimeProvider.Insert("DateTimeTest", () => now, new TimeSpan(0, 0, 0, 0, 200)); Assert.AreEqual(now, Provider.GetCacheItem("DateTimeTest")); Assert.AreEqual(now, Provider.GetCacheItem("DateTimeTest")); diff --git a/src/Umbraco.Tests/Cache/SingleItemsOnlyCachePolicyTests.cs b/src/Umbraco.Tests/Cache/SingleItemsOnlyCachePolicyTests.cs index 1c2227f79b..2b37d85801 100644 --- a/src/Umbraco.Tests/Cache/SingleItemsOnlyCachePolicyTests.cs +++ b/src/Umbraco.Tests/Cache/SingleItemsOnlyCachePolicyTests.cs @@ -28,14 +28,14 @@ namespace Umbraco.Tests.Cache public void Get_All_Doesnt_Cache() { var cached = new List(); - var cache = new Mock(); - cache.Setup(x => x.InsertCacheItem(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), + var cache = new Mock(); + cache.Setup(x => x.Insert(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Callback((string cacheKey, Func o, TimeSpan? t, bool b, CacheItemPriority cip, CacheItemRemovedCallback circ, string[] s) => { cached.Add(cacheKey); }); - cache.Setup(x => x.GetCacheItemsByKeySearch(It.IsAny())).Returns(new AuditItem[] { }); + cache.Setup(x => x.SearchByKey(It.IsAny())).Returns(new AuditItem[] { }); var defaultPolicy = new SingleItemsOnlyRepositoryCachePolicy(cache.Object, DefaultAccessor, new RepositoryCachePolicyOptions()); @@ -52,8 +52,8 @@ namespace Umbraco.Tests.Cache public void Caches_Single() { var isCached = false; - var cache = new Mock(); - cache.Setup(x => x.InsertCacheItem(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), + var cache = new Mock(); + cache.Setup(x => x.Insert(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Callback(() => { diff --git a/src/Umbraco.Tests/Composing/ComposingTestBase.cs b/src/Umbraco.Tests/Composing/ComposingTestBase.cs index 48850afd97..407d953509 100644 --- a/src/Umbraco.Tests/Composing/ComposingTestBase.cs +++ b/src/Umbraco.Tests/Composing/ComposingTestBase.cs @@ -21,7 +21,7 @@ namespace Umbraco.Tests.Composing { ProfilingLogger = new ProfilingLogger(Mock.Of(), Mock.Of()); - TypeLoader = new TypeLoader(NullCacheProvider.Instance, LocalTempStorage.Default, ProfilingLogger, detectChanges: false) + TypeLoader = new TypeLoader(NoAppCache.Instance, LocalTempStorage.Default, ProfilingLogger, detectChanges: false) { AssembliesToScan = AssembliesToScan }; diff --git a/src/Umbraco.Tests/Composing/TypeLoaderTests.cs b/src/Umbraco.Tests/Composing/TypeLoaderTests.cs index 1649f3675d..add3424599 100644 --- a/src/Umbraco.Tests/Composing/TypeLoaderTests.cs +++ b/src/Umbraco.Tests/Composing/TypeLoaderTests.cs @@ -28,7 +28,7 @@ namespace Umbraco.Tests.Composing public void Initialize() { // this ensures it's reset - _typeLoader = new TypeLoader(NullCacheProvider.Instance, LocalTempStorage.Default, new ProfilingLogger(Mock.Of(), Mock.Of())); + _typeLoader = new TypeLoader(NoAppCache.Instance, LocalTempStorage.Default, new ProfilingLogger(Mock.Of(), Mock.Of())); foreach (var file in Directory.GetFiles(IOHelper.MapPath(SystemDirectories.TempData.EnsureEndsWith('/') + "TypesCache"))) File.Delete(file); diff --git a/src/Umbraco.Tests/CoreThings/UdiTests.cs b/src/Umbraco.Tests/CoreThings/UdiTests.cs index 2b4ace8810..35080e8c24 100644 --- a/src/Umbraco.Tests/CoreThings/UdiTests.cs +++ b/src/Umbraco.Tests/CoreThings/UdiTests.cs @@ -26,7 +26,7 @@ namespace Umbraco.Tests.CoreThings var container = new Mock(); var globalSettings = SettingsForTests.GenerateMockGlobalSettings(); container.Setup(x => x.GetInstance(typeof(TypeLoader))).Returns( - new TypeLoader(NullCacheProvider.Instance, LocalTempStorage.Default, new ProfilingLogger(Mock.Of(), Mock.Of()))); + new TypeLoader(NoAppCache.Instance, LocalTempStorage.Default, new ProfilingLogger(Mock.Of(), Mock.Of()))); Current.Factory = container.Object; Udi.ResetUdiTypes(); diff --git a/src/Umbraco.Tests/FrontEnd/UmbracoHelperTests.cs b/src/Umbraco.Tests/FrontEnd/UmbracoHelperTests.cs index 7508395c64..088ef6b54b 100644 --- a/src/Umbraco.Tests/FrontEnd/UmbracoHelperTests.cs +++ b/src/Umbraco.Tests/FrontEnd/UmbracoHelperTests.cs @@ -413,7 +413,7 @@ namespace Umbraco.Tests.FrontEnd container .Setup(x => x.GetInstance(typeof(TypeLoader))) .Returns(new TypeLoader( - NullCacheProvider.Instance, + NoAppCache.Instance, LocalTempStorage.Default, new ProfilingLogger(Mock.Of(), Mock.Of()) ) diff --git a/src/Umbraco.Tests/Macros/MacroTests.cs b/src/Umbraco.Tests/Macros/MacroTests.cs index 23e198b778..225bd17618 100644 --- a/src/Umbraco.Tests/Macros/MacroTests.cs +++ b/src/Umbraco.Tests/Macros/MacroTests.cs @@ -22,10 +22,10 @@ namespace Umbraco.Tests.Macros { //we DO want cache enabled for these tests var cacheHelper = new AppCaches( - new ObjectCacheRuntimeCacheProvider(), - new StaticCacheProvider(), - NullCacheProvider.Instance, - new IsolatedRuntimeCache(type => new ObjectCacheRuntimeCacheProvider())); + new ObjectCacheAppCache(), + new DictionaryCacheProvider(), + NoAppCache.Instance, + new IsolatedCaches(type => new ObjectCacheAppCache())); //Current.ApplicationContext = new ApplicationContext(cacheHelper, new ProfilingLogger(Mock.Of(), Mock.Of())); Current.Reset(); diff --git a/src/Umbraco.Tests/Manifest/ManifestParserTests.cs b/src/Umbraco.Tests/Manifest/ManifestParserTests.cs index ce3d1d705c..74f9fd7157 100644 --- a/src/Umbraco.Tests/Manifest/ManifestParserTests.cs +++ b/src/Umbraco.Tests/Manifest/ManifestParserTests.cs @@ -44,7 +44,7 @@ namespace Umbraco.Tests.Manifest new RequiredValidator(Mock.Of()), new RegexValidator(Mock.Of(), null) }; - _parser = new ManifestParser(NullCacheProvider.Instance, new ManifestValueValidatorCollection(validators), Mock.Of()); + _parser = new ManifestParser(NoAppCache.Instance, new ManifestValueValidatorCollection(validators), Mock.Of()); } [Test] diff --git a/src/Umbraco.Tests/Models/ContentTests.cs b/src/Umbraco.Tests/Models/ContentTests.cs index ea5614fb85..14f766fba1 100644 --- a/src/Umbraco.Tests/Models/ContentTests.cs +++ b/src/Umbraco.Tests/Models/ContentTests.cs @@ -232,8 +232,8 @@ namespace Umbraco.Tests.Models content.UpdateDate = DateTime.Now; content.WriterId = 23; - var runtimeCache = new ObjectCacheRuntimeCacheProvider(); - runtimeCache.InsertCacheItem(content.Id.ToString(CultureInfo.InvariantCulture), () => content); + var runtimeCache = new ObjectCacheAppCache(); + runtimeCache.Insert(content.Id.ToString(CultureInfo.InvariantCulture), () => content); var proflog = GetTestProfilingLogger(); @@ -241,7 +241,7 @@ namespace Umbraco.Tests.Models { for (int j = 0; j < 1000; j++) { - var clone = runtimeCache.GetCacheItem(content.Id.ToString(CultureInfo.InvariantCulture)); + var clone = runtimeCache.Get(content.Id.ToString(CultureInfo.InvariantCulture)); } } diff --git a/src/Umbraco.Tests/Persistence/Repositories/DocumentRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/DocumentRepositoryTest.cs index 772147f5ad..1641631f43 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/DocumentRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/DocumentRepositoryTest.cs @@ -76,10 +76,10 @@ namespace Umbraco.Tests.Persistence.Repositories public void CacheActiveForIntsAndGuids() { var realCache = new AppCaches( - new ObjectCacheRuntimeCacheProvider(), - new StaticCacheProvider(), - new StaticCacheProvider(), - new IsolatedRuntimeCache(t => new ObjectCacheRuntimeCacheProvider())); + new ObjectCacheAppCache(), + new DictionaryCacheProvider(), + new DictionaryCacheProvider(), + new IsolatedCaches(t => new ObjectCacheAppCache())); var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) diff --git a/src/Umbraco.Tests/Persistence/Repositories/MediaRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/MediaRepositoryTest.cs index 5e1900b29e..33c8524bb4 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/MediaRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/MediaRepositoryTest.cs @@ -47,10 +47,10 @@ namespace Umbraco.Tests.Persistence.Repositories MediaTypeRepository mediaTypeRepository; var realCache = new AppCaches( - new ObjectCacheRuntimeCacheProvider(), - new StaticCacheProvider(), - new StaticCacheProvider(), - new IsolatedRuntimeCache(t => new ObjectCacheRuntimeCacheProvider())); + new ObjectCacheAppCache(), + new DictionaryCacheProvider(), + new DictionaryCacheProvider(), + new IsolatedCaches(t => new ObjectCacheAppCache())); var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) diff --git a/src/Umbraco.Tests/Published/PropertyCacheLevelTests.cs b/src/Umbraco.Tests/Published/PropertyCacheLevelTests.cs index 33a595626e..04444855fb 100644 --- a/src/Umbraco.Tests/Published/PropertyCacheLevelTests.cs +++ b/src/Umbraco.Tests/Published/PropertyCacheLevelTests.cs @@ -118,8 +118,8 @@ namespace Umbraco.Tests.Published publishedContentTypeFactory.CreatePropertyType("prop1", 1), }); - var elementsCache = new DictionaryCacheProvider(); - var snapshotCache = new DictionaryCacheProvider(); + var elementsCache = new FastDictionaryCacheProvider(); + var snapshotCache = new FastDictionaryCacheProvider(); var publishedSnapshot = new Mock(); publishedSnapshot.Setup(x => x.SnapshotCache).Returns(snapshotCache); diff --git a/src/Umbraco.Tests/PublishedContent/PublishedContentSnapshotTestBase.cs b/src/Umbraco.Tests/PublishedContent/PublishedContentSnapshotTestBase.cs index 6b280832da..5b1dcde728 100644 --- a/src/Umbraco.Tests/PublishedContent/PublishedContentSnapshotTestBase.cs +++ b/src/Umbraco.Tests/PublishedContent/PublishedContentSnapshotTestBase.cs @@ -40,7 +40,7 @@ namespace Umbraco.Tests.PublishedContent Composition.RegisterUnique(f => new PublishedModelFactory(f.GetInstance().GetTypes())); } - protected override TypeLoader CreateTypeLoader(IRuntimeCacheProvider runtimeCache, IGlobalSettings globalSettings, IProfilingLogger logger) + protected override TypeLoader CreateTypeLoader(IAppPolicedCache runtimeCache, IGlobalSettings globalSettings, IProfilingLogger logger) { var pluginManager = base.CreateTypeLoader(runtimeCache, globalSettings, logger); diff --git a/src/Umbraco.Tests/PublishedContent/PublishedContentTests.cs b/src/Umbraco.Tests/PublishedContent/PublishedContentTests.cs index 603464e18b..e798be82c4 100644 --- a/src/Umbraco.Tests/PublishedContent/PublishedContentTests.cs +++ b/src/Umbraco.Tests/PublishedContent/PublishedContentTests.cs @@ -74,7 +74,7 @@ namespace Umbraco.Tests.PublishedContent ContentTypesCache.GetPublishedContentTypeByAlias = alias => alias.InvariantEquals("home") ? homeType : anythingType; } - protected override TypeLoader CreateTypeLoader(IRuntimeCacheProvider runtimeCache, IGlobalSettings globalSettings, IProfilingLogger logger) + protected override TypeLoader CreateTypeLoader(IAppPolicedCache runtimeCache, IGlobalSettings globalSettings, IProfilingLogger logger) { var pluginManager = base.CreateTypeLoader(runtimeCache, globalSettings, logger); diff --git a/src/Umbraco.Tests/PublishedContent/PublishedMediaTests.cs b/src/Umbraco.Tests/PublishedContent/PublishedMediaTests.cs index 4f55b4fd71..4257e3dabb 100644 --- a/src/Umbraco.Tests/PublishedContent/PublishedMediaTests.cs +++ b/src/Umbraco.Tests/PublishedContent/PublishedMediaTests.cs @@ -68,7 +68,7 @@ namespace Umbraco.Tests.PublishedContent internal IPublishedContent GetNode(int id, UmbracoContext umbracoContext) { var cache = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), - ServiceContext.MediaService, ServiceContext.UserService, new StaticCacheProvider(), ContentTypesCache, + ServiceContext.MediaService, ServiceContext.UserService, new DictionaryCacheProvider(), ContentTypesCache, Factory.GetInstance()); var doc = cache.GetById(id); Assert.IsNotNull(doc); @@ -126,7 +126,7 @@ namespace Umbraco.Tests.PublishedContent var searcher = indexer.GetSearcher(); var ctx = GetUmbracoContext("/test"); - var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, new StaticCacheProvider(), ContentTypesCache, Factory.GetInstance()); + var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, new DictionaryCacheProvider(), ContentTypesCache, Factory.GetInstance()); //we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace var publishedMedia = cache.GetById(1111); @@ -156,7 +156,7 @@ namespace Umbraco.Tests.PublishedContent var searcher = indexer.GetSearcher(); var ctx = GetUmbracoContext("/test"); - var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, new StaticCacheProvider(), ContentTypesCache, Factory.GetInstance()); + var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, new DictionaryCacheProvider(), ContentTypesCache, Factory.GetInstance()); //ensure it is found var publishedMedia = cache.GetById(3113); @@ -203,7 +203,7 @@ namespace Umbraco.Tests.PublishedContent var searcher = indexer.GetSearcher(); var ctx = GetUmbracoContext("/test"); - var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, new StaticCacheProvider(), ContentTypesCache, Factory.GetInstance()); + var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, new DictionaryCacheProvider(), ContentTypesCache, Factory.GetInstance()); //we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace var publishedMedia = cache.GetById(1111); @@ -231,7 +231,7 @@ namespace Umbraco.Tests.PublishedContent var searcher = indexer.GetSearcher(); var ctx = GetUmbracoContext("/test"); - var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, new StaticCacheProvider(), ContentTypesCache, Factory.GetInstance()); + var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, new DictionaryCacheProvider(), ContentTypesCache, Factory.GetInstance()); //we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace var publishedMedia = cache.GetById(1111); @@ -259,7 +259,7 @@ namespace Umbraco.Tests.PublishedContent var searcher = indexer.GetSearcher(); var ctx = GetUmbracoContext("/test"); - var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, new StaticCacheProvider(), ContentTypesCache, Factory.GetInstance()); + var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, new DictionaryCacheProvider(), ContentTypesCache, Factory.GetInstance()); //we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace var publishedMedia = cache.GetById(1111); @@ -288,7 +288,7 @@ namespace Umbraco.Tests.PublishedContent var ctx = GetUmbracoContext("/test"); var searcher = indexer.GetSearcher(); - var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, new StaticCacheProvider(), ContentTypesCache, Factory.GetInstance()); + var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, new DictionaryCacheProvider(), ContentTypesCache, Factory.GetInstance()); //we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace var publishedMedia = cache.GetById(3113); @@ -314,7 +314,7 @@ namespace Umbraco.Tests.PublishedContent var ctx = GetUmbracoContext("/test"); var searcher = indexer.GetSearcher(); - var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, new StaticCacheProvider(), ContentTypesCache, Factory.GetInstance()); + var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, new DictionaryCacheProvider(), ContentTypesCache, Factory.GetInstance()); //we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace var publishedMedia = cache.GetById(3113); @@ -482,7 +482,7 @@ namespace Umbraco.Tests.PublishedContent "); var node = xml.DescendantsAndSelf("Image").Single(x => (int)x.Attribute("id") == nodeId); - var publishedMedia = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), ServiceContext.MediaService, ServiceContext.UserService, new StaticCacheProvider(), ContentTypesCache, Factory.GetInstance()); + var publishedMedia = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), ServiceContext.MediaService, ServiceContext.UserService, new DictionaryCacheProvider(), ContentTypesCache, Factory.GetInstance()); var nav = node.CreateNavigator(); @@ -502,7 +502,7 @@ namespace Umbraco.Tests.PublishedContent var errorXml = new XElement("error", string.Format("No media is maching '{0}'", 1234)); var nav = errorXml.CreateNavigator(); - var publishedMedia = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), ServiceContext.MediaService, ServiceContext.UserService, new StaticCacheProvider(), ContentTypesCache, Factory.GetInstance()); + var publishedMedia = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), ServiceContext.MediaService, ServiceContext.UserService, new DictionaryCacheProvider(), ContentTypesCache, Factory.GetInstance()); var converted = publishedMedia.ConvertFromXPathNodeIterator(nav.Select("/"), 1234); Assert.IsNull(converted); diff --git a/src/Umbraco.Tests/PublishedContent/SolidPublishedSnapshot.cs b/src/Umbraco.Tests/PublishedContent/SolidPublishedSnapshot.cs index deaecf821e..f7077ecb3a 100644 --- a/src/Umbraco.Tests/PublishedContent/SolidPublishedSnapshot.cs +++ b/src/Umbraco.Tests/PublishedContent/SolidPublishedSnapshot.cs @@ -36,9 +36,9 @@ namespace Umbraco.Tests.PublishedContent public void Resync() { } - public ICacheProvider SnapshotCache => null; + public IAppCache SnapshotCache => null; - public ICacheProvider ElementsCache => null; + public IAppCache ElementsCache => null; } class SolidPublishedContentCache : PublishedCacheBase, IPublishedContentCache, IPublishedMediaCache diff --git a/src/Umbraco.Tests/Scoping/ScopedRepositoryTests.cs b/src/Umbraco.Tests/Scoping/ScopedRepositoryTests.cs index 5d4fa4f182..6e01de1670 100644 --- a/src/Umbraco.Tests/Scoping/ScopedRepositoryTests.cs +++ b/src/Umbraco.Tests/Scoping/ScopedRepositoryTests.cs @@ -41,10 +41,10 @@ namespace Umbraco.Tests.Scoping { // this is what's created core web runtime return new AppCaches( - new DeepCloneRuntimeCacheProvider(new ObjectCacheRuntimeCacheProvider()), - new StaticCacheProvider(), - NullCacheProvider.Instance, - new IsolatedRuntimeCache(type => new DeepCloneRuntimeCacheProvider(new ObjectCacheRuntimeCacheProvider()))); + new DeepCloneAppCache(new ObjectCacheAppCache()), + new DictionaryCacheProvider(), + NoAppCache.Instance, + new IsolatedCaches(type => new DeepCloneAppCache(new ObjectCacheAppCache()))); } [TearDown] @@ -60,13 +60,13 @@ namespace Umbraco.Tests.Scoping { var scopeProvider = ScopeProvider; var service = Current.Services.UserService; - var globalCache = Current.ApplicationCache.IsolatedRuntimeCache.GetOrCreateCache(typeof(IUser)); + var globalCache = Current.ApplicationCache.IsolatedCaches.GetOrCreate(typeof(IUser)); var user = (IUser)new User("name", "email", "username", "rawPassword"); service.Save(user); // global cache contains the entity - var globalCached = (IUser) globalCache.GetCacheItem(GetCacheIdKey(user.Id), () => null); + var globalCached = (IUser) globalCache.Get(GetCacheIdKey(user.Id), () => null); Assert.IsNotNull(globalCached); Assert.AreEqual(user.Id, globalCached.Id); Assert.AreEqual("name", globalCached.Name); @@ -85,20 +85,20 @@ namespace Umbraco.Tests.Scoping Assert.AreSame(scope, scopeProvider.AmbientScope); // scope has its own isolated cache - var scopedCache = scope.IsolatedRuntimeCache.GetOrCreateCache(typeof (IUser)); + var scopedCache = scope.IsolatedCaches.GetOrCreate(typeof (IUser)); Assert.AreNotSame(globalCache, scopedCache); user.Name = "changed"; service.Save(user); // scoped cache contains the "new" entity - var scopeCached = (IUser) scopedCache.GetCacheItem(GetCacheIdKey(user.Id), () => null); + var scopeCached = (IUser) scopedCache.Get(GetCacheIdKey(user.Id), () => null); Assert.IsNotNull(scopeCached); Assert.AreEqual(user.Id, scopeCached.Id); Assert.AreEqual("changed", scopeCached.Name); // global cache is unchanged - globalCached = (IUser) globalCache.GetCacheItem(GetCacheIdKey(user.Id), () => null); + globalCached = (IUser) globalCache.Get(GetCacheIdKey(user.Id), () => null); Assert.IsNotNull(globalCached); Assert.AreEqual(user.Id, globalCached.Id); Assert.AreEqual("name", globalCached.Name); @@ -108,7 +108,7 @@ namespace Umbraco.Tests.Scoping } Assert.IsNull(scopeProvider.AmbientScope); - globalCached = (IUser) globalCache.GetCacheItem(GetCacheIdKey(user.Id), () => null); + globalCached = (IUser) globalCache.Get(GetCacheIdKey(user.Id), () => null); if (complete) { // global cache has been cleared @@ -125,7 +125,7 @@ namespace Umbraco.Tests.Scoping Assert.AreEqual(complete ? "changed" : "name", user.Name); // global cache contains the entity again - globalCached = (IUser) globalCache.GetCacheItem(GetCacheIdKey(user.Id), () => null); + globalCached = (IUser) globalCache.Get(GetCacheIdKey(user.Id), () => null); Assert.IsNotNull(globalCached); Assert.AreEqual(user.Id, globalCached.Id); Assert.AreEqual(complete ? "changed" : "name", globalCached.Name); @@ -137,18 +137,18 @@ namespace Umbraco.Tests.Scoping { var scopeProvider = ScopeProvider; var service = Current.Services.LocalizationService; - var globalCache = Current.ApplicationCache.IsolatedRuntimeCache.GetOrCreateCache(typeof (ILanguage)); + var globalCache = Current.ApplicationCache.IsolatedCaches.GetOrCreate(typeof (ILanguage)); var lang = (ILanguage) new Language("fr-FR"); service.Save(lang); // global cache has been flushed, reload - var globalFullCached = (IEnumerable) globalCache.GetCacheItem(GetCacheTypeKey(), () => null); + var globalFullCached = (IEnumerable) globalCache.Get(GetCacheTypeKey(), () => null); Assert.IsNull(globalFullCached); var reload = service.GetLanguageById(lang.Id); // global cache contains the entity - globalFullCached = (IEnumerable) globalCache.GetCacheItem(GetCacheTypeKey(), () => null); + globalFullCached = (IEnumerable) globalCache.Get(GetCacheTypeKey(), () => null); Assert.IsNotNull(globalFullCached); var globalCached = globalFullCached.First(x => x.Id == lang.Id); Assert.IsNotNull(globalCached); @@ -166,19 +166,19 @@ namespace Umbraco.Tests.Scoping Assert.AreSame(scope, scopeProvider.AmbientScope); // scope has its own isolated cache - var scopedCache = scope.IsolatedRuntimeCache.GetOrCreateCache(typeof (ILanguage)); + var scopedCache = scope.IsolatedCaches.GetOrCreate(typeof (ILanguage)); Assert.AreNotSame(globalCache, scopedCache); lang.IsoCode = "de-DE"; service.Save(lang); // scoped cache has been flushed, reload - var scopeFullCached = (IEnumerable) scopedCache.GetCacheItem(GetCacheTypeKey(), () => null); + var scopeFullCached = (IEnumerable) scopedCache.Get(GetCacheTypeKey(), () => null); Assert.IsNull(scopeFullCached); reload = service.GetLanguageById(lang.Id); // scoped cache contains the "new" entity - scopeFullCached = (IEnumerable) scopedCache.GetCacheItem(GetCacheTypeKey(), () => null); + scopeFullCached = (IEnumerable) scopedCache.Get(GetCacheTypeKey(), () => null); Assert.IsNotNull(scopeFullCached); var scopeCached = scopeFullCached.First(x => x.Id == lang.Id); Assert.IsNotNull(scopeCached); @@ -186,7 +186,7 @@ namespace Umbraco.Tests.Scoping Assert.AreEqual("de-DE", scopeCached.IsoCode); // global cache is unchanged - globalFullCached = (IEnumerable) globalCache.GetCacheItem(GetCacheTypeKey(), () => null); + globalFullCached = (IEnumerable) globalCache.Get(GetCacheTypeKey(), () => null); Assert.IsNotNull(globalFullCached); globalCached = globalFullCached.First(x => x.Id == lang.Id); Assert.IsNotNull(globalCached); @@ -198,7 +198,7 @@ namespace Umbraco.Tests.Scoping } Assert.IsNull(scopeProvider.AmbientScope); - globalFullCached = (IEnumerable) globalCache.GetCacheItem(GetCacheTypeKey(), () => null); + globalFullCached = (IEnumerable) globalCache.Get(GetCacheTypeKey(), () => null); if (complete) { // global cache has been cleared @@ -215,7 +215,7 @@ namespace Umbraco.Tests.Scoping Assert.AreEqual(complete ? "de-DE" : "fr-FR", lang.IsoCode); // global cache contains the entity again - globalFullCached = (IEnumerable) globalCache.GetCacheItem(GetCacheTypeKey(), () => null); + globalFullCached = (IEnumerable) globalCache.Get(GetCacheTypeKey(), () => null); Assert.IsNotNull(globalFullCached); globalCached = globalFullCached.First(x => x.Id == lang.Id); Assert.IsNotNull(globalCached); @@ -229,7 +229,7 @@ namespace Umbraco.Tests.Scoping { var scopeProvider = ScopeProvider; var service = Current.Services.LocalizationService; - var globalCache = Current.ApplicationCache.IsolatedRuntimeCache.GetOrCreateCache(typeof (IDictionaryItem)); + var globalCache = Current.ApplicationCache.IsolatedCaches.GetOrCreate(typeof (IDictionaryItem)); var lang = (ILanguage)new Language("fr-FR"); service.Save(lang); @@ -242,7 +242,7 @@ namespace Umbraco.Tests.Scoping service.Save(item); // global cache contains the entity - var globalCached = (IDictionaryItem) globalCache.GetCacheItem(GetCacheIdKey(item.Id), () => null); + var globalCached = (IDictionaryItem) globalCache.Get(GetCacheIdKey(item.Id), () => null); Assert.IsNotNull(globalCached); Assert.AreEqual(item.Id, globalCached.Id); Assert.AreEqual("item-key", globalCached.ItemKey); @@ -258,20 +258,20 @@ namespace Umbraco.Tests.Scoping Assert.AreSame(scope, scopeProvider.AmbientScope); // scope has its own isolated cache - var scopedCache = scope.IsolatedRuntimeCache.GetOrCreateCache(typeof (IDictionaryItem)); + var scopedCache = scope.IsolatedCaches.GetOrCreate(typeof (IDictionaryItem)); Assert.AreNotSame(globalCache, scopedCache); item.ItemKey = "item-changed"; service.Save(item); // scoped cache contains the "new" entity - var scopeCached = (IDictionaryItem) scopedCache.GetCacheItem(GetCacheIdKey(item.Id), () => null); + var scopeCached = (IDictionaryItem) scopedCache.Get(GetCacheIdKey(item.Id), () => null); Assert.IsNotNull(scopeCached); Assert.AreEqual(item.Id, scopeCached.Id); Assert.AreEqual("item-changed", scopeCached.ItemKey); // global cache is unchanged - globalCached = (IDictionaryItem) globalCache.GetCacheItem(GetCacheIdKey(item.Id), () => null); + globalCached = (IDictionaryItem) globalCache.Get(GetCacheIdKey(item.Id), () => null); Assert.IsNotNull(globalCached); Assert.AreEqual(item.Id, globalCached.Id); Assert.AreEqual("item-key", globalCached.ItemKey); @@ -281,7 +281,7 @@ namespace Umbraco.Tests.Scoping } Assert.IsNull(scopeProvider.AmbientScope); - globalCached = (IDictionaryItem) globalCache.GetCacheItem(GetCacheIdKey(item.Id), () => null); + globalCached = (IDictionaryItem) globalCache.Get(GetCacheIdKey(item.Id), () => null); if (complete) { // global cache has been cleared @@ -298,7 +298,7 @@ namespace Umbraco.Tests.Scoping Assert.AreEqual(complete ? "item-changed" : "item-key", item.ItemKey); // global cache contains the entity again - globalCached = (IDictionaryItem) globalCache.GetCacheItem(GetCacheIdKey(item.Id), () => null); + globalCached = (IDictionaryItem) globalCache.Get(GetCacheIdKey(item.Id), () => null); Assert.IsNotNull(globalCached); Assert.AreEqual(item.Id, globalCached.Id); Assert.AreEqual(complete ? "item-changed" : "item-key", globalCached.ItemKey); diff --git a/src/Umbraco.Tests/TestHelpers/BaseUsingSqlCeSyntax.cs b/src/Umbraco.Tests/TestHelpers/BaseUsingSqlCeSyntax.cs index 7fd2f0f18b..35fcc853d4 100644 --- a/src/Umbraco.Tests/TestHelpers/BaseUsingSqlCeSyntax.cs +++ b/src/Umbraco.Tests/TestHelpers/BaseUsingSqlCeSyntax.cs @@ -38,7 +38,7 @@ namespace Umbraco.Tests.TestHelpers var container = RegisterFactory.Create(); var logger = new ProfilingLogger(Mock.Of(), Mock.Of()); - var typeLoader = new TypeLoader(NullCacheProvider.Instance, + var typeLoader = new TypeLoader(NoAppCache.Instance, LocalTempStorage.Default, logger, false); diff --git a/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs b/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs index 0729aa0b6e..2deb30bbdd 100644 --- a/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs +++ b/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs @@ -246,7 +246,7 @@ namespace Umbraco.Tests.TestHelpers protected virtual IPublishedSnapshotService CreatePublishedSnapshotService() { - var cache = NullCacheProvider.Instance; + var cache = NoAppCache.Instance; ContentTypesCache = new PublishedContentTypeCache( Factory.GetInstance(), diff --git a/src/Umbraco.Tests/Testing/UmbracoTestBase.cs b/src/Umbraco.Tests/Testing/UmbracoTestBase.cs index c980f9c1ee..2d6e01b6bb 100644 --- a/src/Umbraco.Tests/Testing/UmbracoTestBase.cs +++ b/src/Umbraco.Tests/Testing/UmbracoTestBase.cs @@ -245,7 +245,7 @@ namespace Umbraco.Tests.Testing .ComposeWebMappingProfiles(); } - protected virtual TypeLoader GetTypeLoader(IRuntimeCacheProvider runtimeCache, IGlobalSettings globalSettings, IProfilingLogger logger, UmbracoTestOptions.TypeLoader option) + protected virtual TypeLoader GetTypeLoader(IAppPolicedCache runtimeCache, IGlobalSettings globalSettings, IProfilingLogger logger, UmbracoTestOptions.TypeLoader option) { switch (option) { @@ -260,13 +260,13 @@ namespace Umbraco.Tests.Testing } } - protected virtual TypeLoader CreateTypeLoader(IRuntimeCacheProvider runtimeCache, IGlobalSettings globalSettings, IProfilingLogger logger) + protected virtual TypeLoader CreateTypeLoader(IAppPolicedCache runtimeCache, IGlobalSettings globalSettings, IProfilingLogger logger) { return CreateCommonTypeLoader(runtimeCache, globalSettings, logger); } // common to all tests = cannot be overriden - private static TypeLoader CreateCommonTypeLoader(IRuntimeCacheProvider runtimeCache, IGlobalSettings globalSettings, IProfilingLogger logger) + private static TypeLoader CreateCommonTypeLoader(IAppPolicedCache runtimeCache, IGlobalSettings globalSettings, IProfilingLogger logger) { return new TypeLoader(runtimeCache, globalSettings.LocalTempStorageLocation, logger, false) { diff --git a/src/Umbraco.Tests/Web/Mvc/UmbracoViewPageTests.cs b/src/Umbraco.Tests/Web/Mvc/UmbracoViewPageTests.cs index 192b0975d1..133cbb2ee7 100644 --- a/src/Umbraco.Tests/Web/Mvc/UmbracoViewPageTests.cs +++ b/src/Umbraco.Tests/Web/Mvc/UmbracoViewPageTests.cs @@ -415,7 +415,7 @@ namespace Umbraco.Tests.Web.Mvc // CacheHelper.CreateDisabledCacheHelper(), // new ProfilingLogger(logger, Mock.Of())) { /*IsReady = true*/ }; - var cache = NullCacheProvider.Instance; + var cache = NoAppCache.Instance; //var provider = new ScopeUnitOfWorkProvider(databaseFactory, new RepositoryFactory(Mock.Of())); var scopeProvider = TestObjects.GetScopeProvider(Mock.Of()); var factory = Mock.Of(); diff --git a/src/Umbraco.Tests/Web/TemplateUtilitiesTests.cs b/src/Umbraco.Tests/Web/TemplateUtilitiesTests.cs index 047d0b0b8f..e95ae7b785 100644 --- a/src/Umbraco.Tests/Web/TemplateUtilitiesTests.cs +++ b/src/Umbraco.Tests/Web/TemplateUtilitiesTests.cs @@ -39,7 +39,7 @@ namespace Umbraco.Tests.Web // fixme - bad in a unit test - but Udi has a static ctor that wants it?! var factory = new Mock(); factory.Setup(x => x.GetInstance(typeof(TypeLoader))).Returns( - new TypeLoader(NullCacheProvider.Instance, LocalTempStorage.Default, new ProfilingLogger(Mock.Of(), Mock.Of()))); + new TypeLoader(NoAppCache.Instance, LocalTempStorage.Default, new ProfilingLogger(Mock.Of(), Mock.Of()))); factory.Setup(x => x.GetInstance(typeof (ServiceContext))).Returns(serviceContext); var settings = SettingsForTests.GetDefaultUmbracoSettings(); diff --git a/src/Umbraco.Web/Cache/ApplicationCacheRefresher.cs b/src/Umbraco.Web/Cache/ApplicationCacheRefresher.cs index cf93b44215..751b2194b7 100644 --- a/src/Umbraco.Web/Cache/ApplicationCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/ApplicationCacheRefresher.cs @@ -25,7 +25,7 @@ namespace Umbraco.Web.Cache public override void RefreshAll() { - AppCaches.RuntimeCache.ClearCacheItem(CacheKeys.ApplicationsCacheKey); + AppCaches.RuntimeCache.Clear(CacheKeys.ApplicationsCacheKey); base.RefreshAll(); } @@ -37,7 +37,7 @@ namespace Umbraco.Web.Cache public override void Remove(int id) { - AppCaches.RuntimeCache.ClearCacheItem(CacheKeys.ApplicationsCacheKey); + AppCaches.RuntimeCache.Clear(CacheKeys.ApplicationsCacheKey); base.Remove(id); } diff --git a/src/Umbraco.Web/Cache/ApplicationTreeCacheRefresher.cs b/src/Umbraco.Web/Cache/ApplicationTreeCacheRefresher.cs index 72fceec631..4d2dcd8efb 100644 --- a/src/Umbraco.Web/Cache/ApplicationTreeCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/ApplicationTreeCacheRefresher.cs @@ -25,7 +25,7 @@ namespace Umbraco.Web.Cache public override void RefreshAll() { - AppCaches.RuntimeCache.ClearCacheItem(CacheKeys.ApplicationTreeCacheKey); + AppCaches.RuntimeCache.Clear(CacheKeys.ApplicationTreeCacheKey); base.RefreshAll(); } @@ -37,7 +37,7 @@ namespace Umbraco.Web.Cache public override void Remove(int id) { - AppCaches.RuntimeCache.ClearCacheItem(CacheKeys.ApplicationTreeCacheKey); + AppCaches.RuntimeCache.Clear(CacheKeys.ApplicationTreeCacheKey); base.Remove(id); } diff --git a/src/Umbraco.Web/Cache/ContentCacheRefresher.cs b/src/Umbraco.Web/Cache/ContentCacheRefresher.cs index 3ae2f8e3dd..36397540b6 100644 --- a/src/Umbraco.Web/Cache/ContentCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/ContentCacheRefresher.cs @@ -44,14 +44,14 @@ namespace Umbraco.Web.Cache public override void Refresh(JsonPayload[] payloads) { - AppCaches.RuntimeCache.ClearCacheObjectTypes(); + AppCaches.RuntimeCache.ClearOfType(); var idsRemoved = new HashSet(); - var isolatedCache = AppCaches.IsolatedRuntimeCache.GetOrCreateCache(); + var isolatedCache = AppCaches.IsolatedCaches.GetOrCreate(); foreach (var payload in payloads) { - isolatedCache.ClearCacheItem(RepositoryCacheKeys.GetKey(payload.Id)); + isolatedCache.Clear(RepositoryCacheKeys.GetKey(payload.Id)); _idkMap.ClearCache(payload.Id); @@ -59,7 +59,7 @@ namespace Umbraco.Web.Cache if (payload.ChangeTypes.HasTypesAny(TreeChangeTypes.RefreshBranch | TreeChangeTypes.Remove)) { var pathid = "," + payload.Id + ","; - isolatedCache.ClearCacheObjectTypes((k, v) => v.Path.Contains(pathid)); + isolatedCache.ClearOfType((k, v) => v.Path.Contains(pathid)); } //if the item is being completely removed, we need to refresh the domains cache if any domain was assigned to the content @@ -162,8 +162,8 @@ namespace Umbraco.Web.Cache appCaches.ClearPartialViewCache(); MacroCacheRefresher.ClearMacroContentCache(appCaches); // just the content - appCaches.IsolatedRuntimeCache.ClearCache(); - appCaches.IsolatedRuntimeCache.ClearCache(); + appCaches.IsolatedCaches.ClearCache(); + appCaches.IsolatedCaches.ClearCache(); } #endregion diff --git a/src/Umbraco.Web/Cache/DataTypeCacheRefresher.cs b/src/Umbraco.Web/Cache/DataTypeCacheRefresher.cs index e1a8f05e39..f3d1337403 100644 --- a/src/Umbraco.Web/Cache/DataTypeCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/DataTypeCacheRefresher.cs @@ -49,7 +49,7 @@ namespace Umbraco.Web.Cache ClearAllIsolatedCacheByEntityType(); ClearAllIsolatedCacheByEntityType(); - var dataTypeCache = AppCaches.IsolatedRuntimeCache.GetCache(); + var dataTypeCache = AppCaches.IsolatedCaches.Get(); foreach (var payload in payloads) { diff --git a/src/Umbraco.Web/Cache/MacroCacheRefresher.cs b/src/Umbraco.Web/Cache/MacroCacheRefresher.cs index cdeb2ffdd0..6b739b4f49 100644 --- a/src/Umbraco.Web/Cache/MacroCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/MacroCacheRefresher.cs @@ -33,11 +33,11 @@ namespace Umbraco.Web.Cache public override void RefreshAll() { foreach (var prefix in GetAllMacroCacheKeys()) - AppCaches.RuntimeCache.ClearCacheByKeySearch(prefix); + AppCaches.RuntimeCache.ClearByKey(prefix); ClearAllIsolatedCacheByEntityType(); - AppCaches.RuntimeCache.ClearCacheObjectTypes(); + AppCaches.RuntimeCache.ClearOfType(); base.RefreshAll(); } @@ -49,12 +49,12 @@ namespace Umbraco.Web.Cache foreach (var payload in payloads) { foreach (var alias in GetCacheKeysForAlias(payload.Alias)) - AppCaches.RuntimeCache.ClearCacheByKeySearch(alias); + AppCaches.RuntimeCache.ClearByKey(alias); - var macroRepoCache = AppCaches.IsolatedRuntimeCache.GetCache(); + var macroRepoCache = AppCaches.IsolatedCaches.Get(); if (macroRepoCache) { - macroRepoCache.Result.ClearCacheItem(RepositoryCacheKeys.GetKey(payload.Id)); + macroRepoCache.Result.Clear(RepositoryCacheKeys.GetKey(payload.Id)); } }; @@ -112,7 +112,7 @@ namespace Umbraco.Web.Cache public static void ClearMacroContentCache(AppCaches appCaches) { - appCaches.RuntimeCache.ClearCacheObjectTypes(); + appCaches.RuntimeCache.ClearOfType(); } #endregion diff --git a/src/Umbraco.Web/Cache/MediaCacheRefresher.cs b/src/Umbraco.Web/Cache/MediaCacheRefresher.cs index a6ccd7e005..cdaf43dac3 100644 --- a/src/Umbraco.Web/Cache/MediaCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/MediaCacheRefresher.cs @@ -49,7 +49,7 @@ namespace Umbraco.Web.Cache { Current.ApplicationCache.ClearPartialViewCache(); - var mediaCache = AppCaches.IsolatedRuntimeCache.GetCache(); + var mediaCache = AppCaches.IsolatedCaches.Get(); foreach (var payload in payloads) { @@ -61,13 +61,13 @@ namespace Umbraco.Web.Cache // repository cache // it *was* done for each pathId but really that does not make sense // only need to do it for the current media - mediaCache.Result.ClearCacheItem(RepositoryCacheKeys.GetKey(payload.Id)); + mediaCache.Result.Clear(RepositoryCacheKeys.GetKey(payload.Id)); // remove those that are in the branch if (payload.ChangeTypes.HasTypesAny(TreeChangeTypes.RefreshBranch | TreeChangeTypes.Remove)) { var pathid = "," + payload.Id + ","; - mediaCache.Result.ClearCacheObjectTypes((_, v) => v.Path.Contains(pathid)); + mediaCache.Result.ClearOfType((_, v) => v.Path.Contains(pathid)); } } } @@ -121,7 +121,7 @@ namespace Umbraco.Web.Cache public static void RefreshMediaTypes(AppCaches appCaches) { - appCaches.IsolatedRuntimeCache.ClearCache(); + appCaches.IsolatedCaches.ClearCache(); } #endregion diff --git a/src/Umbraco.Web/Cache/MemberCacheRefresher.cs b/src/Umbraco.Web/Cache/MemberCacheRefresher.cs index 29c102e7a2..1565b1c849 100644 --- a/src/Umbraco.Web/Cache/MemberCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/MemberCacheRefresher.cs @@ -60,9 +60,9 @@ namespace Umbraco.Web.Cache _idkMap.ClearCache(id); AppCaches.ClearPartialViewCache(); - var memberCache = AppCaches.IsolatedRuntimeCache.GetCache(); + var memberCache = AppCaches.IsolatedCaches.Get(); if (memberCache) - memberCache.Result.ClearCacheItem(RepositoryCacheKeys.GetKey(id)); + memberCache.Result.Clear(RepositoryCacheKeys.GetKey(id)); } #endregion @@ -71,7 +71,7 @@ namespace Umbraco.Web.Cache public static void RefreshMemberTypes(AppCaches appCaches) { - appCaches.IsolatedRuntimeCache.ClearCache(); + appCaches.IsolatedCaches.ClearCache(); } #endregion diff --git a/src/Umbraco.Web/Cache/MemberGroupCacheRefresher.cs b/src/Umbraco.Web/Cache/MemberGroupCacheRefresher.cs index 9368b0f9f4..3e195cec5e 100644 --- a/src/Umbraco.Web/Cache/MemberGroupCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/MemberGroupCacheRefresher.cs @@ -49,7 +49,7 @@ namespace Umbraco.Web.Cache // Since we cache by group name, it could be problematic when renaming to // previously existing names - see http://issues.umbraco.org/issue/U4-10846. // To work around this, just clear all the cache items - AppCaches.IsolatedRuntimeCache.ClearCache(); + AppCaches.IsolatedCaches.ClearCache(); } #endregion diff --git a/src/Umbraco.Web/Cache/RelationTypeCacheRefresher.cs b/src/Umbraco.Web/Cache/RelationTypeCacheRefresher.cs index 8b1c8581cd..c9c8b47bbf 100644 --- a/src/Umbraco.Web/Cache/RelationTypeCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/RelationTypeCacheRefresher.cs @@ -34,8 +34,8 @@ namespace Umbraco.Web.Cache public override void Refresh(int id) { - var cache = AppCaches.IsolatedRuntimeCache.GetCache(); - if (cache) cache.Result.ClearCacheItem(RepositoryCacheKeys.GetKey(id)); + var cache = AppCaches.IsolatedCaches.Get(); + if (cache) cache.Result.Clear(RepositoryCacheKeys.GetKey(id)); base.Refresh(id); } @@ -47,8 +47,8 @@ namespace Umbraco.Web.Cache public override void Remove(int id) { - var cache = AppCaches.IsolatedRuntimeCache.GetCache(); - if (cache) cache.Result.ClearCacheItem(RepositoryCacheKeys.GetKey(id)); + var cache = AppCaches.IsolatedCaches.Get(); + if (cache) cache.Result.Clear(RepositoryCacheKeys.GetKey(id)); base.Remove(id); } diff --git a/src/Umbraco.Web/Cache/TemplateCacheRefresher.cs b/src/Umbraco.Web/Cache/TemplateCacheRefresher.cs index 7ff7c6fdb6..eda3b6eef4 100644 --- a/src/Umbraco.Web/Cache/TemplateCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/TemplateCacheRefresher.cs @@ -52,7 +52,7 @@ namespace Umbraco.Web.Cache private void RemoveFromCache(int id) { _idkMap.ClearCache(id); - AppCaches.RuntimeCache.ClearCacheItem($"{CacheKeys.TemplateFrontEndCacheKey}{id}"); + AppCaches.RuntimeCache.Clear($"{CacheKeys.TemplateFrontEndCacheKey}{id}"); //need to clear the runtime cache for templates ClearAllIsolatedCacheByEntityType(); diff --git a/src/Umbraco.Web/Cache/UserCacheRefresher.cs b/src/Umbraco.Web/Cache/UserCacheRefresher.cs index a502a7554f..922a9df385 100644 --- a/src/Umbraco.Web/Cache/UserCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/UserCacheRefresher.cs @@ -40,9 +40,9 @@ namespace Umbraco.Web.Cache public override void Remove(int id) { - var userCache = AppCaches.IsolatedRuntimeCache.GetCache(); + var userCache = AppCaches.IsolatedCaches.Get(); if (userCache) - userCache.Result.ClearCacheItem(RepositoryCacheKeys.GetKey(id)); + userCache.Result.Clear(RepositoryCacheKeys.GetKey(id)); base.Remove(id); } diff --git a/src/Umbraco.Web/Cache/UserGroupCacheRefresher.cs b/src/Umbraco.Web/Cache/UserGroupCacheRefresher.cs index 4dea595c85..cfdf8f3669 100644 --- a/src/Umbraco.Web/Cache/UserGroupCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/UserGroupCacheRefresher.cs @@ -35,10 +35,10 @@ namespace Umbraco.Web.Cache public override void RefreshAll() { ClearAllIsolatedCacheByEntityType(); - var userGroupCache = AppCaches.IsolatedRuntimeCache.GetCache(); + var userGroupCache = AppCaches.IsolatedCaches.Get(); if (userGroupCache) { - userGroupCache.Result.ClearCacheByKeySearch(UserGroupRepository.GetByAliasCacheKeyPrefix); + userGroupCache.Result.ClearByKey(UserGroupRepository.GetByAliasCacheKeyPrefix); } //We'll need to clear all user cache too @@ -55,11 +55,11 @@ namespace Umbraco.Web.Cache public override void Remove(int id) { - var userGroupCache = AppCaches.IsolatedRuntimeCache.GetCache(); + var userGroupCache = AppCaches.IsolatedCaches.Get(); if (userGroupCache) { - userGroupCache.Result.ClearCacheItem(RepositoryCacheKeys.GetKey(id)); - userGroupCache.Result.ClearCacheByKeySearch(UserGroupRepository.GetByAliasCacheKeyPrefix); + userGroupCache.Result.Clear(RepositoryCacheKeys.GetKey(id)); + userGroupCache.Result.ClearByKey(UserGroupRepository.GetByAliasCacheKeyPrefix); } //we don't know what user's belong to this group without doing a look up so we'll need to just clear them all diff --git a/src/Umbraco.Web/CacheHelperExtensions.cs b/src/Umbraco.Web/CacheHelperExtensions.cs index 3c5ea1930d..ae8df63415 100644 --- a/src/Umbraco.Web/CacheHelperExtensions.cs +++ b/src/Umbraco.Web/CacheHelperExtensions.cs @@ -56,7 +56,7 @@ namespace Umbraco.Web /// public static void ClearPartialViewCache(this AppCaches appCaches) { - appCaches.RuntimeCache.ClearCacheByKeySearch(PartialViewCacheKey); + appCaches.RuntimeCache.ClearByKey(PartialViewCacheKey); } } } diff --git a/src/Umbraco.Web/Dictionary/UmbracoCultureDictionary.cs b/src/Umbraco.Web/Dictionary/UmbracoCultureDictionary.cs index f30f8e9745..5234bf9fa7 100644 --- a/src/Umbraco.Web/Dictionary/UmbracoCultureDictionary.cs +++ b/src/Umbraco.Web/Dictionary/UmbracoCultureDictionary.cs @@ -21,7 +21,7 @@ namespace Umbraco.Web.Dictionary public class DefaultCultureDictionary : Core.Dictionary.ICultureDictionary { private readonly ILocalizationService _localizationService; - private readonly ICacheProvider _requestCacheProvider; + private readonly IAppCache _requestCacheProvider; private readonly CultureInfo _specificCulture; public DefaultCultureDictionary() @@ -30,7 +30,7 @@ namespace Umbraco.Web.Dictionary } - public DefaultCultureDictionary(ILocalizationService localizationService, ICacheProvider requestCacheProvider) + public DefaultCultureDictionary(ILocalizationService localizationService, IAppCache requestCacheProvider) { _localizationService = localizationService ?? throw new ArgumentNullException(nameof(localizationService)); _requestCacheProvider = requestCacheProvider ?? throw new ArgumentNullException(nameof(requestCacheProvider)); @@ -42,7 +42,7 @@ namespace Umbraco.Web.Dictionary _specificCulture = specificCulture ?? throw new ArgumentNullException(nameof(specificCulture)); } - public DefaultCultureDictionary(CultureInfo specificCulture, ILocalizationService localizationService, ICacheProvider requestCacheProvider) + public DefaultCultureDictionary(CultureInfo specificCulture, ILocalizationService localizationService, IAppCache requestCacheProvider) { _localizationService = localizationService ?? throw new ArgumentNullException(nameof(localizationService)); _requestCacheProvider = requestCacheProvider ?? throw new ArgumentNullException(nameof(requestCacheProvider)); diff --git a/src/Umbraco.Web/Editors/ExamineManagementController.cs b/src/Umbraco.Web/Editors/ExamineManagementController.cs index b583babee3..db9de424a9 100644 --- a/src/Umbraco.Web/Editors/ExamineManagementController.cs +++ b/src/Umbraco.Web/Editors/ExamineManagementController.cs @@ -29,12 +29,12 @@ namespace Umbraco.Web.Editors { private readonly IExamineManager _examineManager; private readonly ILogger _logger; - private readonly IRuntimeCacheProvider _runtimeCacheProvider; + private readonly IAppPolicedCache _runtimeCacheProvider; private readonly IndexRebuilder _indexRebuilder; public ExamineManagementController(IExamineManager examineManager, ILogger logger, - IRuntimeCacheProvider runtimeCacheProvider, + IAppPolicedCache runtimeCacheProvider, IndexRebuilder indexRebuilder) { _examineManager = examineManager; @@ -114,7 +114,7 @@ namespace Umbraco.Web.Editors throw new HttpResponseException(validate); var cacheKey = "temp_indexing_op_" + indexName; - var found = ApplicationCache.RuntimeCache.GetCacheItem(cacheKey); + var found = ApplicationCache.RuntimeCache.Get(cacheKey); //if its still there then it's not done return found != null @@ -153,7 +153,7 @@ namespace Umbraco.Web.Editors var cacheKey = "temp_indexing_op_" + index.Name; //put temp val in cache which is used as a rudimentary way to know when the indexing is done - ApplicationCache.RuntimeCache.InsertCacheItem(cacheKey, () => "tempValue", TimeSpan.FromMinutes(5)); + ApplicationCache.RuntimeCache.Insert(cacheKey, () => "tempValue", TimeSpan.FromMinutes(5)); _indexRebuilder.RebuildIndex(indexName); @@ -269,7 +269,7 @@ namespace Umbraco.Web.Editors >($"Rebuilding index '{indexer.Name}' done, {indexer.CommitCount} items committed (can differ from the number of items in the index)"); var cacheKey = "temp_indexing_op_" + indexer.Name; - _runtimeCacheProvider.ClearCacheItem(cacheKey); + _runtimeCacheProvider.Clear(cacheKey); } } } diff --git a/src/Umbraco.Web/Editors/UsersController.cs b/src/Umbraco.Web/Editors/UsersController.cs index e46e83c6e4..15cfda9ffd 100644 --- a/src/Umbraco.Web/Editors/UsersController.cs +++ b/src/Umbraco.Web/Editors/UsersController.cs @@ -63,7 +63,7 @@ namespace Umbraco.Web.Editors return await PostSetAvatarInternal(Request, Services.UserService, ApplicationCache.StaticCache, id); } - internal static async Task PostSetAvatarInternal(HttpRequestMessage request, IUserService userService, ICacheProvider staticCache, int id) + internal static async Task PostSetAvatarInternal(HttpRequestMessage request, IUserService userService, IAppCache staticCache, int id) { if (request.Content.IsMimeMultipartContent() == false) { diff --git a/src/Umbraco.Web/Macros/MacroRenderer.cs b/src/Umbraco.Web/Macros/MacroRenderer.cs index e0a0fd65c8..0bcdb3225b 100755 --- a/src/Umbraco.Web/Macros/MacroRenderer.cs +++ b/src/Umbraco.Web/Macros/MacroRenderer.cs @@ -152,7 +152,7 @@ namespace Umbraco.Web.Macros macroContent.Date = DateTime.Now; var cache = Current.ApplicationCache.RuntimeCache; - cache.InsertCacheItem( + cache.Insert( CacheKeys.MacroContentCacheKey + model.CacheIdentifier, () => macroContent, new TimeSpan(0, 0, model.CacheDuration), diff --git a/src/Umbraco.Web/Models/Mapping/UserMapperProfile.cs b/src/Umbraco.Web/Models/Mapping/UserMapperProfile.cs index 8261dda0d4..4b27af3120 100644 --- a/src/Umbraco.Web/Models/Mapping/UserMapperProfile.cs +++ b/src/Umbraco.Web/Models/Mapping/UserMapperProfile.cs @@ -22,7 +22,7 @@ namespace Umbraco.Web.Models.Mapping => entity is ContentEntitySlim contentEntity ? contentEntity.ContentTypeIcon : null; public UserMapperProfile(ILocalizedTextService textService, IUserService userService, IEntityService entityService, ISectionService sectionService, - IRuntimeCacheProvider runtimeCache, ActionCollection actions, IGlobalSettings globalSettings) + IAppPolicedCache runtimeCache, ActionCollection actions, IGlobalSettings globalSettings) { var userGroupDefaultPermissionsResolver = new UserGroupDefaultPermissionsResolver(textService, actions); diff --git a/src/Umbraco.Web/PublishedCache/IPublishedSnapshot.cs b/src/Umbraco.Web/PublishedCache/IPublishedSnapshot.cs index 0636eb808c..0865e61f08 100644 --- a/src/Umbraco.Web/PublishedCache/IPublishedSnapshot.cs +++ b/src/Umbraco.Web/PublishedCache/IPublishedSnapshot.cs @@ -36,7 +36,7 @@ namespace Umbraco.Web.PublishedCache /// /// The snapshot-level cache belongs to this snapshot only. /// - ICacheProvider SnapshotCache { get; } + IAppCache SnapshotCache { get; } /// /// Gets the elements-level cache. @@ -45,7 +45,7 @@ namespace Umbraco.Web.PublishedCache /// The elements-level cache is shared by all snapshots relying on the same elements, /// ie all snapshots built on top of unchanging content / media / etc. /// - ICacheProvider ElementsCache { get; } + IAppCache ElementsCache { get; } /// /// Forces the preview mode. diff --git a/src/Umbraco.Web/PublishedCache/NuCache/ContentCache.cs b/src/Umbraco.Web/PublishedCache/NuCache/ContentCache.cs index 817c363fa5..566ab240c1 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/ContentCache.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/ContentCache.cs @@ -21,8 +21,8 @@ namespace Umbraco.Web.PublishedCache.NuCache internal class ContentCache : PublishedCacheBase, IPublishedContentCache, INavigableData, IDisposable { private readonly ContentStore.Snapshot _snapshot; - private readonly ICacheProvider _snapshotCache; - private readonly ICacheProvider _elementsCache; + private readonly IAppCache _snapshotCache; + private readonly IAppCache _elementsCache; private readonly DomainHelper _domainHelper; private readonly IGlobalSettings _globalSettings; private readonly ILocalizationService _localizationService; @@ -34,7 +34,7 @@ namespace Umbraco.Web.PublishedCache.NuCache // it's too late for UmbracoContext which has captured previewDefault and stuff into these ctor vars // but, no, UmbracoContext returns snapshot.Content which comes from elements SO a resync should create a new cache - public ContentCache(bool previewDefault, ContentStore.Snapshot snapshot, ICacheProvider snapshotCache, ICacheProvider elementsCache, DomainHelper domainHelper, IGlobalSettings globalSettings, ILocalizationService localizationService) + public ContentCache(bool previewDefault, ContentStore.Snapshot snapshot, IAppCache snapshotCache, IAppCache elementsCache, DomainHelper domainHelper, IGlobalSettings globalSettings, ILocalizationService localizationService) : base(previewDefault) { _snapshot = snapshot; @@ -259,7 +259,7 @@ namespace Umbraco.Web.PublishedCache.NuCache return GetAtRootNoCache(preview); // note: ToArray is important here, we want to cache the result, not the function! - return (IEnumerable)cache.GetCacheItem( + return (IEnumerable)cache.Get( CacheKeys.ContentCacheRoots(preview), () => GetAtRootNoCache(preview).ToArray()); } diff --git a/src/Umbraco.Web/PublishedCache/NuCache/MediaCache.cs b/src/Umbraco.Web/PublishedCache/NuCache/MediaCache.cs index f107b52a40..28c7c38c36 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/MediaCache.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/MediaCache.cs @@ -13,12 +13,12 @@ namespace Umbraco.Web.PublishedCache.NuCache internal class MediaCache : PublishedCacheBase, IPublishedMediaCache, INavigableData, IDisposable { private readonly ContentStore.Snapshot _snapshot; - private readonly ICacheProvider _snapshotCache; - private readonly ICacheProvider _elementsCache; + private readonly IAppCache _snapshotCache; + private readonly IAppCache _elementsCache; #region Constructors - public MediaCache(bool previewDefault, ContentStore.Snapshot snapshot, ICacheProvider snapshotCache, ICacheProvider elementsCache) + public MediaCache(bool previewDefault, ContentStore.Snapshot snapshot, IAppCache snapshotCache, IAppCache elementsCache) : base(previewDefault) { _snapshot = snapshot; @@ -63,7 +63,7 @@ namespace Umbraco.Web.PublishedCache.NuCache return GetAtRootNoCache(); // note: ToArray is important here, we want to cache the result, not the function! - return (IEnumerable)cache.GetCacheItem( + return (IEnumerable)cache.Get( CacheKeys.MediaCacheRoots(false), // ignore preview, only 1 key! () => GetAtRootNoCache().ToArray()); } diff --git a/src/Umbraco.Web/PublishedCache/NuCache/MemberCache.cs b/src/Umbraco.Web/PublishedCache/NuCache/MemberCache.cs index f2392c9c3d..ecf099f90b 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/MemberCache.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/MemberCache.cs @@ -19,12 +19,12 @@ namespace Umbraco.Web.PublishedCache.NuCache private readonly IPublishedSnapshotAccessor _publishedSnapshotAccessor; public readonly IVariationContextAccessor VariationContextAccessor; private readonly IEntityXmlSerializer _entitySerializer; - private readonly ICacheProvider _snapshotCache; + private readonly IAppCache _snapshotCache; private readonly IMemberService _memberService; private readonly PublishedContentTypeCache _contentTypeCache; private readonly bool _previewDefault; - public MemberCache(bool previewDefault, ICacheProvider snapshotCache, IMemberService memberService, PublishedContentTypeCache contentTypeCache, IPublishedSnapshotAccessor publishedSnapshotAccessor, IVariationContextAccessor variationContextAccessor, IEntityXmlSerializer entitySerializer) + public MemberCache(bool previewDefault, IAppCache snapshotCache, IMemberService memberService, PublishedContentTypeCache contentTypeCache, IPublishedSnapshotAccessor publishedSnapshotAccessor, IVariationContextAccessor variationContextAccessor, IEntityXmlSerializer entitySerializer) { _snapshotCache = snapshotCache; _publishedSnapshotAccessor = publishedSnapshotAccessor; diff --git a/src/Umbraco.Web/PublishedCache/NuCache/Property.cs b/src/Umbraco.Web/PublishedCache/NuCache/Property.cs index 132c4b6d59..2c8bc94d90 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/Property.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/Property.cs @@ -125,7 +125,7 @@ namespace Umbraco.Web.PublishedCache.NuCache { CacheValues cacheValues; PublishedSnapshot publishedSnapshot; - ICacheProvider cache; + IAppCache cache; switch (cacheLevel) { case PropertyCacheLevel.None: @@ -161,11 +161,11 @@ namespace Umbraco.Web.PublishedCache.NuCache return cacheValues; } - private CacheValues GetCacheValues(ICacheProvider cache) + private CacheValues GetCacheValues(IAppCache cache) { if (cache == null) // no cache, don't cache return new CacheValues(); - return (CacheValues) cache.GetCacheItem(ValuesCacheKey, () => new CacheValues()); + return (CacheValues) cache.Get(ValuesCacheKey, () => new CacheValues()); } // this is always invoked from within a lock, so does not require its own lock diff --git a/src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs b/src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs index 25e5244d32..65b7a1560a 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs @@ -48,7 +48,7 @@ namespace Umbraco.Web.PublishedCache.NuCache var cache = GetCurrentSnapshotCache(); return cache == null ? GetProfileNameByIdNoCache(id) - : (string)cache.GetCacheItem(CacheKeys.ProfileName(id), () => GetProfileNameByIdNoCache(id)); + : (string)cache.Get(CacheKeys.ProfileName(id), () => GetProfileNameByIdNoCache(id)); } private static string GetProfileNameByIdNoCache(int id) @@ -328,7 +328,7 @@ namespace Umbraco.Web.PublishedCache.NuCache return GetChildren(); // note: ToArray is important here, we want to cache the result, not the function! - return (IEnumerable)cache.GetCacheItem(ChildrenCacheKey, () => GetChildren().ToArray()); + return (IEnumerable)cache.Get(ChildrenCacheKey, () => GetChildren().ToArray()); } } @@ -383,7 +383,7 @@ namespace Umbraco.Web.PublishedCache.NuCache #region Caching // beware what you use that one for - you don't want to cache its result - private ICacheProvider GetAppropriateCache() + private IAppCache GetAppropriateCache() { var publishedSnapshot = (PublishedSnapshot)_publishedSnapshotAccessor.PublishedSnapshot; var cache = publishedSnapshot == null @@ -394,7 +394,7 @@ namespace Umbraco.Web.PublishedCache.NuCache return cache; } - private ICacheProvider GetCurrentSnapshotCache() + private IAppCache GetCurrentSnapshotCache() { var publishedSnapshot = (PublishedSnapshot)_publishedSnapshotAccessor.PublishedSnapshot; return publishedSnapshot?.SnapshotCache; @@ -436,7 +436,7 @@ namespace Umbraco.Web.PublishedCache.NuCache var cache = GetAppropriateCache(); if (cache == null) return new PublishedContent(this).CreateModel(); - return (IPublishedContent)cache.GetCacheItem(AsPreviewingCacheKey, () => new PublishedContent(this).CreateModel()); + return (IPublishedContent)cache.Get(AsPreviewingCacheKey, () => new PublishedContent(this).CreateModel()); } // used by Navigable.Source,... diff --git a/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshot.cs b/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshot.cs index 9b8982c69c..2ceced75eb 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshot.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshot.cs @@ -25,8 +25,8 @@ namespace Umbraco.Web.PublishedCache.NuCache public MediaCache MediaCache; public MemberCache MemberCache; public DomainCache DomainCache; - public ICacheProvider SnapshotCache; - public ICacheProvider ElementsCache; + public IAppCache SnapshotCache; + public IAppCache ElementsCache; public void Dispose() { @@ -48,9 +48,9 @@ namespace Umbraco.Web.PublishedCache.NuCache #region Caches - public ICacheProvider SnapshotCache => Elements.SnapshotCache; + public IAppCache SnapshotCache => Elements.SnapshotCache; - public ICacheProvider ElementsCache => Elements.ElementsCache; + public IAppCache ElementsCache => Elements.ElementsCache; #endregion diff --git a/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs b/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs index 36f3472c31..bcb1c6ede3 100755 --- a/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs @@ -932,7 +932,7 @@ namespace Umbraco.Web.PublishedCache.NuCache #region Create, Get Published Snapshot private long _contentGen, _mediaGen, _domainGen; - private ICacheProvider _elementsCache; + private IAppCache _elementsCache; public override IPublishedSnapshot CreatePublishedSnapshot(string previewToken) { @@ -960,7 +960,7 @@ namespace Umbraco.Web.PublishedCache.NuCache ContentStore.Snapshot contentSnap, mediaSnap; SnapDictionary.Snapshot domainSnap; - ICacheProvider elementsCache; + IAppCache elementsCache; lock (_storesLock) { var scopeContext = _scopeProvider.Context; @@ -998,11 +998,11 @@ namespace Umbraco.Web.PublishedCache.NuCache _contentGen = contentSnap.Gen; _mediaGen = mediaSnap.Gen; _domainGen = domainSnap.Gen; - elementsCache = _elementsCache = new DictionaryCacheProvider(); + elementsCache = _elementsCache = new FastDictionaryCacheProvider(); } } - var snapshotCache = new StaticCacheProvider(); + var snapshotCache = new DictionaryCacheProvider(); var memberTypeCache = new PublishedContentTypeCache(null, null, _serviceContext.MemberTypeService, _publishedContentTypeFactory, _logger); diff --git a/src/Umbraco.Web/PublishedCache/PublishedElementPropertyBase.cs b/src/Umbraco.Web/PublishedCache/PublishedElementPropertyBase.cs index cff1e40b69..6d69b96e0c 100644 --- a/src/Umbraco.Web/PublishedCache/PublishedElementPropertyBase.cs +++ b/src/Umbraco.Web/PublishedCache/PublishedElementPropertyBase.cs @@ -106,7 +106,7 @@ namespace Umbraco.Web.PublishedCache } } - private ICacheProvider GetSnapshotCache() + private IAppCache GetSnapshotCache() { // cache within the snapshot cache, unless previewing, then use the snapshot or // elements cache (if we don't want to pollute the elements cache with short-lived @@ -135,12 +135,12 @@ namespace Umbraco.Web.PublishedCache case PropertyCacheLevel.Elements: // cache within the elements cache, depending... var snapshotCache = GetSnapshotCache(); - cacheValues = (CacheValues) snapshotCache?.GetCacheItem(ValuesCacheKey, () => new CacheValues()) ?? new CacheValues(); + cacheValues = (CacheValues) snapshotCache?.Get(ValuesCacheKey, () => new CacheValues()) ?? new CacheValues(); break; case PropertyCacheLevel.Snapshot: // cache within the snapshot cache var facadeCache = _publishedSnapshotAccessor?.PublishedSnapshot?.SnapshotCache; - cacheValues = (CacheValues) facadeCache?.GetCacheItem(ValuesCacheKey, () => new CacheValues()) ?? new CacheValues(); + cacheValues = (CacheValues) facadeCache?.Get(ValuesCacheKey, () => new CacheValues()) ?? new CacheValues(); break; default: throw new InvalidOperationException("Invalid cache level."); diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/DictionaryPublishedContent.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/DictionaryPublishedContent.cs index 6f6a39144a..ea38af314f 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/DictionaryPublishedContent.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/DictionaryPublishedContent.cs @@ -35,7 +35,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache Func getParent, Func> getChildren, Func getProperty, - ICacheProvider cacheProvider, + IAppCache cacheProvider, PublishedContentTypeCache contentTypeCache, XPathNavigator nav, bool fromExamine) @@ -133,7 +133,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache //private readonly Func> _getChildren; private readonly Lazy> _getChildren; private readonly Func _getProperty; - private readonly ICacheProvider _cacheProvider; + private readonly IAppCache _cacheProvider; /// /// Returns 'Media' as the item type diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedContentCache.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedContentCache.cs index e022e36fc0..67813ce9f6 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedContentCache.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedContentCache.cs @@ -15,7 +15,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache { internal class PublishedContentCache : PublishedCacheBase, IPublishedContentCache { - private readonly ICacheProvider _cacheProvider; + private readonly IAppCache _cacheProvider; private readonly IGlobalSettings _globalSettings; private readonly RoutesCache _routesCache; private readonly IDomainCache _domainCache; @@ -30,7 +30,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache public PublishedContentCache( XmlStore xmlStore, // an XmlStore containing the master xml IDomainCache domainCache, // an IDomainCache implementation - ICacheProvider cacheProvider, // an ICacheProvider that should be at request-level + IAppCache cacheProvider, // an ICacheProvider that should be at request-level IGlobalSettings globalSettings, ISiteDomainHelper siteDomainHelper, PublishedContentTypeCache contentTypeCache, // a PublishedContentType cache @@ -517,7 +517,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache // clear recursive properties cached by XmlPublishedContent.GetProperty // assume that nothing else is going to cache IPublishedProperty items (else would need to do ByKeySearch) // NOTE also clears all the media cache properties, which is OK (see media cache) - _cacheProvider.ClearCacheObjectTypes(); + _cacheProvider.ClearOfType(); //_cacheProvider.ClearCacheByKeySearch("XmlPublishedCache.PublishedContentCache:RecursiveProperty-"); } diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedMediaCache.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedMediaCache.cs index 09b76b5c2e..3ead5a5166 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedMediaCache.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedMediaCache.cs @@ -43,9 +43,9 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache private readonly IEntityXmlSerializer _entitySerializer; // must be specified by the ctor - private readonly ICacheProvider _cacheProvider; + private readonly IAppCache _cacheProvider; - public PublishedMediaCache(XmlStore xmlStore, IMediaService mediaService, IUserService userService, ICacheProvider cacheProvider, PublishedContentTypeCache contentTypeCache, IEntityXmlSerializer entitySerializer) + public PublishedMediaCache(XmlStore xmlStore, IMediaService mediaService, IUserService userService, IAppCache cacheProvider, PublishedContentTypeCache contentTypeCache, IEntityXmlSerializer entitySerializer) : base(false) { _mediaService = mediaService ?? throw new ArgumentNullException(nameof(mediaService)); @@ -66,7 +66,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache /// /// /// - internal PublishedMediaCache(IMediaService mediaService, IUserService userService, ISearcher searchProvider, ICacheProvider cacheProvider, PublishedContentTypeCache contentTypeCache, IEntityXmlSerializer entitySerializer) + internal PublishedMediaCache(IMediaService mediaService, IUserService userService, ISearcher searchProvider, IAppCache cacheProvider, PublishedContentTypeCache contentTypeCache, IEntityXmlSerializer entitySerializer) : base(false) { _mediaService = mediaService ?? throw new ArgumentNullException(nameof(mediaService)); @@ -678,7 +678,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache var cache = Current.ApplicationCache.RuntimeCache; var key = PublishedMediaCacheKey + id; - return (CacheValues)cache.GetCacheItem(key, () => func(id), _publishedMediaCacheTimespan); + return (CacheValues)cache.Get(key, () => func(id), _publishedMediaCacheTimespan); } internal static void ClearCache(int id) @@ -696,11 +696,11 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache // cache.ClearCacheItem(PublishedMediaCacheKey + GetValuesValue(exist.Values, "parentID")); // clear the item - cache.ClearCacheItem(key); + cache.Clear(key); // clear all children - in case we moved and their path has changed var fid = "/" + sid + "/"; - cache.ClearCacheObjectTypes((k, v) => + cache.ClearOfType((k, v) => GetValuesValue(v.Values, "path", "__Path").Contains(fid)); } diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedMemberCache.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedMemberCache.cs index 2328a1cefd..a622a4934c 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedMemberCache.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedMemberCache.cs @@ -13,11 +13,11 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache class PublishedMemberCache : IPublishedMemberCache { private readonly IMemberService _memberService; - private readonly ICacheProvider _requestCache; + private readonly IAppCache _requestCache; private readonly XmlStore _xmlStore; private readonly PublishedContentTypeCache _contentTypeCache; - public PublishedMemberCache(XmlStore xmlStore, ICacheProvider requestCacheProvider, IMemberService memberService, PublishedContentTypeCache contentTypeCache) + public PublishedMemberCache(XmlStore xmlStore, IAppCache requestCacheProvider, IMemberService memberService, PublishedContentTypeCache contentTypeCache) { _requestCache = requestCacheProvider; _memberService = memberService; diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedSnapshot.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedSnapshot.cs index 61ea7d2534..b9243309a2 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedSnapshot.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedSnapshot.cs @@ -38,10 +38,10 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache public IDomainCache Domains { get; } /// - public ICacheProvider SnapshotCache => null; + public IAppCache SnapshotCache => null; /// - public ICacheProvider ElementsCache => null; + public IAppCache ElementsCache => null; /// public IDisposable ForcedPreview(bool preview, Action callback = null) diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedSnapshotService.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedSnapshotService.cs index e286e9d95c..c4ce05c9a9 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedSnapshotService.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedSnapshotService.cs @@ -30,7 +30,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache private readonly IMemberService _memberService; private readonly IMediaService _mediaService; private readonly IUserService _userService; - private readonly ICacheProvider _requestCache; + private readonly IAppCache _requestCache; private readonly IGlobalSettings _globalSettings; private readonly IDefaultCultureAccessor _defaultCultureAccessor; private readonly ISiteDomainHelper _siteDomainHelper; @@ -42,7 +42,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache public PublishedSnapshotService(ServiceContext serviceContext, IPublishedContentTypeFactory publishedContentTypeFactory, IScopeProvider scopeProvider, - ICacheProvider requestCache, + IAppCache requestCache, IPublishedSnapshotAccessor publishedSnapshotAccessor, IVariationContextAccessor variationContextAccessor, IDocumentRepository documentRepository, IMediaRepository mediaRepository, IMemberRepository memberRepository, IDefaultCultureAccessor defaultCultureAccessor, @@ -63,7 +63,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache internal PublishedSnapshotService(ServiceContext serviceContext, IPublishedContentTypeFactory publishedContentTypeFactory, IScopeProvider scopeProvider, - ICacheProvider requestCache, + IAppCache requestCache, IPublishedSnapshotAccessor publishedSnapshotAccessor, IVariationContextAccessor variationContextAccessor, IDocumentRepository documentRepository, IMediaRepository mediaRepository, IMemberRepository memberRepository, IDefaultCultureAccessor defaultCultureAccessor, diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlPublishedContent.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlPublishedContent.cs index efd4535bd4..a1fda17df1 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlPublishedContent.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlPublishedContent.cs @@ -20,7 +20,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache [XmlType(Namespace = "http://umbraco.org/webservices/")] internal class XmlPublishedContent : PublishedContentBase { - private XmlPublishedContent(XmlNode xmlNode, bool isPreviewing, ICacheProvider cacheProvider, PublishedContentTypeCache contentTypeCache) + private XmlPublishedContent(XmlNode xmlNode, bool isPreviewing, IAppCache cacheProvider, PublishedContentTypeCache contentTypeCache) { _xmlNode = xmlNode; _isPreviewing = isPreviewing; @@ -31,7 +31,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache private readonly XmlNode _xmlNode; private readonly bool _isPreviewing; - private readonly ICacheProvider _cacheProvider; // at snapshot/request level (see PublishedContentCache) + private readonly IAppCache _cacheProvider; // at snapshot/request level (see PublishedContentCache) private readonly PublishedContentTypeCache _contentTypeCache; private readonly object _initializeLock = new object(); @@ -426,7 +426,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache /// Maintains a per-request cache of IPublishedContent items in order to make /// sure that we create only one instance of each for the duration of a request. The /// returned IPublishedContent is a model, if models are enabled. - public static IPublishedContent Get(XmlNode node, bool isPreviewing, ICacheProvider cacheProvider, PublishedContentTypeCache contentTypeCache) + public static IPublishedContent Get(XmlNode node, bool isPreviewing, IAppCache cacheProvider, PublishedContentTypeCache contentTypeCache) { // only 1 per request @@ -434,12 +434,12 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache var id = attrs?.GetNamedItem("id").Value; if (id.IsNullOrWhiteSpace()) throw new InvalidOperationException("Node has no ID attribute."); var key = CacheKeyPrefix + id; // dont bother with preview, wont change during request in Xml cache - return (IPublishedContent) cacheProvider.GetCacheItem(key, () => (new XmlPublishedContent(node, isPreviewing, cacheProvider, contentTypeCache)).CreateModel()); + return (IPublishedContent) cacheProvider.Get(key, () => (new XmlPublishedContent(node, isPreviewing, cacheProvider, contentTypeCache)).CreateModel()); } public static void ClearRequest() { - Current.ApplicationCache.RequestCache.ClearCacheByKeySearch(CacheKeyPrefix); + Current.ApplicationCache.RequestCache.ClearByKey(CacheKeyPrefix); } private const string CacheKeyPrefix = "CONTENTCACHE_XMLPUBLISHEDCONTENT_"; diff --git a/src/Umbraco.Web/Runtime/WebRuntime.cs b/src/Umbraco.Web/Runtime/WebRuntime.cs index c69a3bec8b..e9d27a2a1c 100644 --- a/src/Umbraco.Web/Runtime/WebRuntime.cs +++ b/src/Umbraco.Web/Runtime/WebRuntime.cs @@ -62,14 +62,14 @@ namespace Umbraco.Web.Runtime protected override AppCaches GetAppCaches() => new AppCaches( // we need to have the dep clone runtime cache provider to ensure // all entities are cached properly (cloned in and cloned out) - new DeepCloneRuntimeCacheProvider(new HttpRuntimeCacheProvider(HttpRuntime.Cache)), - new StaticCacheProvider(), + new DeepCloneAppCache(new WebCachingAppCache(HttpRuntime.Cache)), + new DictionaryCacheProvider(), // we need request based cache when running in web-based context - new HttpRequestCacheProvider(), - new IsolatedRuntimeCache(type => + new HttpRequestAppCache(), + new IsolatedCaches(type => // we need to have the dep clone runtime cache provider to ensure // all entities are cached properly (cloned in and cloned out) - new DeepCloneRuntimeCacheProvider(new ObjectCacheRuntimeCacheProvider()))); + new DeepCloneAppCache(new ObjectCacheAppCache()))); #endregion } diff --git a/src/Umbraco.Web/Services/ApplicationTreeService.cs b/src/Umbraco.Web/Services/ApplicationTreeService.cs index 2ddec054c7..30d50e136c 100644 --- a/src/Umbraco.Web/Services/ApplicationTreeService.cs +++ b/src/Umbraco.Web/Services/ApplicationTreeService.cs @@ -357,7 +357,7 @@ namespace Umbraco.Web.Services //remove the cache now that it has changed SD: I'm leaving this here even though it // is taken care of by events as well, I think unit tests may rely on it being cleared here. - _cache.RuntimeCache.ClearCacheItem(CacheKeys.ApplicationTreeCacheKey); + _cache.RuntimeCache.Clear(CacheKeys.ApplicationTreeCacheKey); } } } diff --git a/src/Umbraco.Web/Services/SectionService.cs b/src/Umbraco.Web/Services/SectionService.cs index 2d06141292..09972a6dca 100644 --- a/src/Umbraco.Web/Services/SectionService.cs +++ b/src/Umbraco.Web/Services/SectionService.cs @@ -132,7 +132,7 @@ namespace Umbraco.Web.Services //remove the cache so it gets re-read ... SD: I'm leaving this here even though it // is taken care of by events as well, I think unit tests may rely on it being cleared here. - _cache.RuntimeCache.ClearCacheItem(CacheKeys.ApplicationsCacheKey); + _cache.RuntimeCache.Clear(CacheKeys.ApplicationsCacheKey); } } }