object ICache.TrySet(object key, Func <object, object> contentGetter, ICachePolicy policy) { if (key == null) { throw new ArgumentNullException("key"); } if (contentGetter == null) { throw new ArgumentNullException("contentGetter"); } if (!(key is TKey)) { throw new ArgumentException("The parameter key must be of type " + typeof(TKey).FullName); } return(TrySet((TKey)key, k => { var content = contentGetter(key); if (content == null) { throw new ArgumentException("The value getter delegate may not return null"); } if (!(content is TValue)) { throw new ArgumentException("The value must be of type " + typeof(TValue).FullName); } return (TValue)content; })); }
public static CacheItemPolicy CreatePolicy(ICacheKey key, ICachePolicy cachePolicy) { var policy = new CacheItemPolicy(); switch (cachePolicy.Mode) { case CacheExpirationMode.Sliding: policy.SlidingExpiration = cachePolicy.SlidingExpiration; break; case CacheExpirationMode.Absolute: policy.AbsoluteExpiration = cachePolicy.AbsoluteExpiration; break; case CacheExpirationMode.Duration: policy.AbsoluteExpiration = DateTimeOffset.Now.Add(cachePolicy.Duration); break; default: policy.AbsoluteExpiration = ObjectCache.InfiniteAbsoluteExpiration; break; } var changeMonitor = CreateChangeMonitor(key); if (changeMonitor != null) { policy.ChangeMonitors.Add(changeMonitor); } return(policy); }
protected override void Prepare(ICachePolicy <TKey, TValue> policy) { foreach (var subCache in subCaches) { subCache.Policy = policy; } }
private void AssertPurged <TKey, TValue>(ICachePolicy <TKey, TValue> policy, TKey expectedKey) { TKey purgedKey = default(TKey); Assert.IsTrue(policy.Purge(out purgedKey)); Assert.AreEqual(expectedKey, purgedKey); }
public TValue TrySet(TKey key, Func <TKey, TValue> valueGetter, ICachePolicy policy) { _rwLock.EnterReadLock(); try { if (_contents.TryGetValue(key, out var cached)) { return(cached.Value); } } finally { _rwLock.ExitReadLock(); } _rwLock.EnterWriteLock(); try { if (_contents.TryGetValue(key, out var cached)) { return(cached.Value); } cached = new CacheContent <TKey, TValue>(key, valueGetter(key), policy); UpdateExpiryControl(cached.ExpiresAt, key); return(cached.Value); } finally { _rwLock.ExitWriteLock(); } }
public CachingQueryHandlerDecorator( IQueryHandler <TQuery, TResult> decorated, ICachePolicy <TQuery> cachePolicy) { this.decorated = decorated; this.Policy = cachePolicy; }
protected BaseController(IServiceProvider serviceProvider) { contentCache = serviceProvider.GetRequiredService <IContentCache>(); cachePolicy = serviceProvider.GetRequiredService <ICachePolicy>(); rolesCache = serviceProvider.GetRequiredService <IRolesCache>(); userManager = serviceProvider.GetRequiredService <SunUserManager>(); keyGenerator = serviceProvider.GetRequiredService <CacheKeyGenerator>(); }
public CacheContent(TKey key, TContent value, ICachePolicy policy) { Key = key; Value = value; _policy = policy; CreatedAt = DateTime.Now; LastAccessedAt = DateTime.Now; }
/// <summary> /// Inserts a cache entry into the cache overwriting any existing cache entry. /// </summary> /// <param name="cacheKey">A unique identifier for the cache entry.</param> /// <param name="value">The object to insert.</param> /// <param name="cachePolicy">A <see cref="CachePolicy"/> that contains eviction details for the cache entry.</param> /// <returns></returns> public override bool Set(ICacheKey cacheKey, object value, ICachePolicy cachePolicy) { string key = GetKey(cacheKey); var item = new CacheItem(key, value); var policy = CreatePolicy(cacheKey, cachePolicy); MemoryCache.Default.Set(item, policy); return(true); }
internal virtual CacheAddParameters <T> BuildParameters <T>(string name, ICachePolicy policy, Func <FreshnessRequest, T> filler) where T : class { return(new CacheAddParameters <T>( name , policy , (freshness) => filler(freshness) , (parameters, value) => InternalPut(parameters, value))); }
public MemoryCache(ICachePolicy policy, IEqualityComparer <TKey> keyComparer) { _policy = policy; _timer = new Timer(CacheValidationCallback, null, Disabled, Disabled); _queue = new DateTimeQueue <TKey>(); _contents = new Dictionary <TKey, CacheContent <TKey, TValue> >(keyComparer); _nextTimerExecution = DateTime.MaxValue; _rwLock = new ReaderWriterLockSlim(); }
/// <summary> /// Inserts a cache entry into the cache without overwriting any existing cache entry. /// </summary> /// <param name="cacheKey">A unique identifier for the cache entry.</param> /// <param name="value">The object to insert.</param> /// <param name="cachePolicy">An object that contains eviction details for the cache entry.</param> /// <returns> /// <c>true</c> if insertion succeeded, or <c>false</c> if there is an already an entry in the cache that has the same key as key. /// </returns> public override bool Add(ICacheKey cacheKey, object value, ICachePolicy cachePolicy) { string key = GetKey(cacheKey); var item = new CacheItem(key, value); var policy = CreatePolicy(cacheKey, cachePolicy); var existing = MemoryCache.Default.AddOrGetExisting(item, policy); return(existing.Value == null); }
public GraphQlExecutionMiddleware( IGraphqlInAppCacheService cacheInAppService, ICachePolicy cachePolicy, CacheConfiguration cacheConfiguration) { _cacheConfiguration = cacheConfiguration; _cachePolicy = cachePolicy; _cacheConfiguration = cacheConfiguration; _cacheInAppService = cacheInAppService; }
/// <summary> /// Initializes a new instance of the <see cref="DeviceDataProvider"/> class. /// </summary> /// <param name="configService">The configuration service.</param> /// <param name="errorService">The error service.</param> /// <param name="logService">The log service.</param> /// <param name="cacheService">The cache service.</param> public DeviceDataProvider(IConfiguration configService, IErrorPolicy errorService, ILogPolicy logService, ICachePolicy cacheService) : base(configService, errorService, logService) { this.CacheService = cacheService; this.cacheScope = this.GetType().ToString(); // Create new scope where to save the entities from this provider this.CacheService.CreateScope(this.cacheScope); }
public MassTransitCache(ICachePolicy <TValue, TCacheValue> policy, CacheOptions options = default) { _policy = policy; options ??= new CacheOptions(); _tracker = new ValueTracker <TValue, TCacheValue>(policy, options.Capacity); _values = new ConcurrentDictionary <TKey, TCacheValue>(options.ConcurrencyLevel, options.Capacity); _metrics = new CacheMetrics(); }
/// <summary> /// Creates a real memory cache. /// </summary> /// <param name="cachePolicy">When no policy is provided an empty only will be used.</param> /// <returns>MemoryCacheService</returns> public MemoryCacheService CreateMemoryCacheService(ICachePolicy cachePolicy = null) { if (cachePolicy == null) { cachePolicy = new StubCachePolicy(); } var cacheKeyGenerator = new CacheKeyGenerator(); return(new MemoryCacheService(cachePolicy, cacheKeyGenerator)); }
public dynamic Get(string key, ICachePolicy cachePolicy) { CheckConnection(); if (!Exists(key)) { return(null); } var serializedCachedValue = _cacheDb.StringGet(key); return(cachePolicy.Converter.Deserialize(serializedCachedValue, cachePolicy.ContentType)); }
public void Set(string forUser, IEnumerable <Category> categories, ICachePolicy policy) { if (policy == null) { cache.Set(prefix + forUser, categories, ObjectCache.InfiniteAbsoluteExpiration); } else { cache.Set(prefix + forUser, categories, policy.GetMonitorCachePolicy()); } }
public CacheAddParameters( string name , ICachePolicy policy , Func <FreshnessRequest, T> filler , Action <CacheAddParameters <T>, T> putter) : base( name , policy , (freshness) => filler(freshness) , (parms, value) => putter(parms as CacheAddParameters <T>, (T)value)) { }
public ValueTracker(ICachePolicy <TValue, TCacheValue> policy, int capacity) { if (capacity < 8) { throw new ArgumentOutOfRangeException(nameof(capacity), "Capacity must be >= 8"); } _policy = policy; _new = new Bucket <TValue, TCacheValue>(this, capacity / 4); _used = new Bucket <TValue, TCacheValue>(this, capacity / 2); _unused = new Bucket <TValue, TCacheValue>(this, capacity / 4); }
public CacheResponse(IResponse response) { response.ThrowIfNull("response"); _statusCode = response.StatusCode; _contentType = response.ContentType; _charset = response.Charset ?? DefaultCharset; _contentEncoding = response.ContentEncoding ?? _defaultContentEncoding; _headers = response.Headers.Select(arg => arg.Clone()).ToArray(); _headerEncoding = response.HeaderEncoding ?? _defaultHeaderEncoding; _cookies = response.Cookies.Select(arg => arg.Clone()).ToArray(); _cachePolicy = response.CachePolicy.Clone(); _content = response.GetContent(); }
public void Set(string key, dynamic value, ICachePolicy cachePolicy) { CheckConnection(); var cachedValue = cachePolicy.Converter.Serialize(value, cachePolicy.ContentType); if (cachePolicy.LifeTimeCaching) { _cacheDb.StringSet(key, cachedValue); } else { _cacheDb.StringSet(key, cachedValue, cachePolicy.TimeToLive); } }
public ICachePolicy Adjust(ICachePolicy policy) { if (ConfiguredPolicy.AbsoluteSeconds != policy.AbsoluteSeconds || ConfiguredPolicy.SlidingSeconds != policy.SlidingSeconds || ConfiguredPolicy.RefillCount != policy.RefillCount) { policy = policy.Clone(); policy.AbsoluteSeconds = ConfiguredPolicy.AbsoluteSeconds; policy.SlidingSeconds = ConfiguredPolicy.SlidingSeconds; policy.RefillCount = ConfiguredPolicy.RefillCount; } return(policy); }
public MicroObjectCache(ObjectCache cache, ICachePolicy cachePolicy) { if (cache == null) { throw new ArgumentNullException("cache"); } if (cachePolicy == null) { throw new ArgumentNullException("cachePolicy"); } this.cache = cache; this.cachePolicy = cachePolicy; }
/// <summary> /// Loads the cache type and policy configurations. /// </summary> private static void LoadCaches(CachePolicyConfigPolicy config, ICachePolicy policy) { if (config.Caches == null) { return; } foreach (var cache in config.Caches) { if (!string.IsNullOrEmpty(cache)) { CachePolicyManager.Set(cache, policy); } } }
public CacheResponse(IResponse response) { response.ThrowIfNull("response"); _statusCode = response.StatusCode; _contentType = response.ContentType; _charset = response.Charset ?? DefaultCharset; _contentEncoding = response.ContentEncoding ?? _defaultContentEncoding; _headers = response.Headers.Select(arg => arg.Clone()).ToArray(); _headerEncoding = response.HeaderEncoding ?? _defaultHeaderEncoding; _cookies = response.Cookies.Select(arg => arg.Clone()).ToArray(); _cachePolicy = response.CachePolicy.Clone(); _skipIisCustomErrors = response.SkipIisCustomErrors; _content = new AsyncLazy<byte[]>(() => response.GetContentAsync()); }
public CacheResponse(IResponse response) { response.ThrowIfNull("response"); _statusCode = response.StatusCode; _contentType = response.ContentType; _charset = response.Charset ?? DefaultCharset; _contentEncoding = response.ContentEncoding ?? _defaultContentEncoding; _headers = response.Headers.Select(arg => arg.Clone()).ToArray(); _headerEncoding = response.HeaderEncoding ?? _defaultHeaderEncoding; _cookies = response.Cookies.Select(arg => arg.Clone()).ToArray(); _cachePolicy = response.CachePolicy.Clone(); _skipIisCustomErrors = response.SkipIisCustomErrors; _content = new AsyncLazy <byte[]>(() => response.GetContentAsync()); }
public BaseCacheAddParameters( string name , ICachePolicy policy , Func <FreshnessRequest, object> filler , Action <BaseCacheAddParameters, object> putter) { _absoluteSeconds = policy.AbsoluteSeconds; Name = name; Filler = filler; Putter = putter; SlidingTimeout = policy.SlidingSeconds == ICachePolicyOptions.Unused ? Cache.NoSlidingExpiration : TimeSpan.FromSeconds(policy.SlidingSeconds); NumberOfRefillsRemaining = policy.RefillCount; }
protected override void Prepare(ICachePolicy <TKey, TValue> policy) { var type = policy != null? policy.GetCacheEvictionType() ?? typeof(NoCacheEviction <TKey, TValue>) : typeof(NoCacheEviction <TKey, TValue>); // Necessary test, as the policy (which the eviction is derived from) // may never have been set yet if (State != null) { State.Clear(); } State = (ICacheEviction <TKey, TValue>)Activator.CreateInstance(type, this, Capacity); }
/// <summary> /// Creates a disk-based caching store. /// </summary> /// <param name="directoryPath">A path to a directory.</param> /// <param name="cachePolicy">A cache policy to apply to values in the cache.</param> /// <param name="storageCapacity">The maximum amount of space to store in the cache.</param> /// <param name="pollingInterval">The maximum time that will elapse before a cache policy will be applied. Defaults to 1 minute.</param> /// <param name="keyComparer">The <see cref="IEqualityComparer{TKey}"/> implementation to use when comparing cache keys, or <c>null</c> to use the default <see cref="EqualityComparer{TKey}"/> implementation for the set type.</param> /// <exception cref="ArgumentNullException"><paramref name="directoryPath"/> is <c>null</c>, empty or whitespace. Also thrown when <paramref name="cachePolicy"/> is <c>null</c>.</exception> /// <exception cref="DirectoryNotFoundException">The directory at <paramref name="directoryPath"/> does not exist.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="storageCapacity"/> is less than <c>1</c>. Can also be thrown when <paramref name="pollingInterval"/> represents a negative timespan or a zero-length timespan.</exception> public DiskCache(string directoryPath, ICachePolicy <TKey> cachePolicy, ulong storageCapacity, TimeSpan?pollingInterval = null, IEqualityComparer <TKey> keyComparer = null) { if (string.IsNullOrWhiteSpace(directoryPath)) { throw new ArgumentNullException(nameof(directoryPath)); } if (!Directory.Exists(directoryPath)) { throw new DirectoryNotFoundException($"The cache directory does not exist. The directory at '{ directoryPath }' must be present."); } if (storageCapacity == 0) { throw new ArgumentOutOfRangeException("The storage capacity must be at least 1 byte. Given: " + storageCapacity.ToString(CultureInfo.InvariantCulture), nameof(storageCapacity)); } pollingInterval = pollingInterval ?? TimeSpan.FromMinutes(1); var interval = pollingInterval.Value; if (interval <= TimeSpan.Zero) { throw new ArgumentOutOfRangeException("The polling time interval must be a non-negative and non-zero timespan. Given: " + interval.ToString(), nameof(pollingInterval)); } CachePath = new DirectoryInfo(directoryPath); Policy = cachePolicy ?? throw new ArgumentNullException(nameof(cachePolicy)); MaximumStorageCapacity = storageCapacity; PollingInterval = interval; KeyComparer = keyComparer ?? EqualityComparer <TKey> .Default; // Database storage if (!Directory.Exists("dbs")) { Directory.CreateDirectory("dbs"); } _entryLookup = new PersistentDictionary <TKey, CacheEntry <TKey> >("dbs/chunkCache", "entryLookup"); _fileLookup = new PersistentDictionary <TKey, FileEntry <TKey> >("dbs/chunkCache", "fileLookup"); Task.Run(async() => { while (true) { await Task.Delay(PollingInterval).ConfigureAwait(false); ApplyCachePolicy(); } }, _cts.Token); }
public CacheEntry(ServerResponseCacheAttribute cachingInfo, byte[] responseBody, int statusCode, IHeaderDictionary headers, bool isRequestDataSet, object requestData, KeyValuePair <string, object>[] routeData, ICachePolicy policy, object policyMetadata) { CachingInfo = cachingInfo ?? throw new ArgumentNullException(nameof(cachingInfo)); ResponseBody = responseBody ?? throw new ArgumentNullException(nameof(responseBody)); StatusCode = statusCode; Headers = headers ?? throw new ArgumentNullException(nameof(headers)); ServerCacheExpirationTime = DateTime.UtcNow.AddSeconds(CachingInfo.CacheDuration); IsRequestDataSet = isRequestDataSet; RequestData = requestData; Policy = policy ?? throw new ArgumentNullException(nameof(policy)); RouteData = routeData ?? throw new ArgumentNullException(nameof(routeData)); PolicyMetadata = policyMetadata; ApproximateSizeInMemory = ResponseBody.Length + 100; }
/// <summary> /// Gets the cached <see cref="IEnumerable{TList}"/>. /// </summary> /// <returns>The underlying <see cref="IEnumerable{TList}"/>.</returns> protected IEnumerable <TItem> GetCache() { lock (Lock) { // Refresh cache if expired or no data exists. ICachePolicy policy = GetPolicy(); if (_cache != null && !policy.HasExpired()) { return(_cache); } // Set the cache using the getCache and resets expiry. SetCacheInternal(LoadCache !(Data)); policy.Reset(); return(_cache !); } }
public void SetUp() { _handler = new NonCacheableResponseHandler(); _httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); _httpCachePolicyBase = MockRepository.GenerateMock<HttpCachePolicyBase>(); _httpResponse = MockRepository.GenerateMock<HttpResponseBase>(); _httpResponse.Stub(arg => arg.BinaryWrite(Arg<byte[]>.Is.Anything)).WhenCalled(arg => _responseWritten = true); _httpResponse.Stub(arg => arg.Cache).Return(_httpCachePolicyBase); _cachePolicy = MockRepository.GenerateMock<ICachePolicy>(); _cachePolicy.Stub(arg => arg.Clone()).Return(_cachePolicy); _response = MockRepository.GenerateMock<IResponse>(); _response.Stub(arg => arg.CachePolicy).Return(_cachePolicy); _response.Stub(arg => arg.Cookies).Return(Enumerable.Empty<Cookie>()); _response.Stub(arg => arg.GetContent()).Return(new byte[0]); _response.Stub(arg => arg.Headers).Return(Enumerable.Empty<Header>()); _response.Stub(arg => arg.StatusCode).Return(new StatusAndSubStatusCode(HttpStatusCode.OK)); _cache = MockRepository.GenerateMock<ICache>(); _result = _handler.HandleResponse(_httpRequest, _httpResponse, _response, _cache, "key"); }
public void SetUp() { _systemClock = MockRepository.GenerateMock<ISystemClock>(); _handler = new CacheableResponseHandler(_systemClock); _httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); _httpRequest.Stub(arg => arg.Headers).Return(new NameValueCollection()); _httpResponse = MockRepository.GenerateMock<HttpResponseBase>(); _httpResponse.Stub(arg => arg.Headers).Return(new NameValueCollection()); _cachePolicy = MockRepository.GenerateMock<ICachePolicy>(); _cachePolicy.Stub(arg => arg.Clone()).Return(_cachePolicy); _cachePolicy.Stub(arg => arg.ClientCacheExpirationUtcTimestamp).Return(DateTime.UtcNow); _response = MockRepository.GenerateMock<IResponse>(); _response.Stub(arg => arg.CachePolicy).Return(_cachePolicy); _response.Stub(arg => arg.Cookies).Return(Enumerable.Empty<Cookie>()); _response.Stub(arg => arg.Headers).Return(Enumerable.Empty<Header>()); _response.Stub(arg => arg.StatusCode).Return(new StatusAndSubStatusCode(HttpStatusCode.OK)); _response.Stub(arg => arg.GetContent()).Return(new byte[0]); _cache = MockRepository.GenerateMock<ICache>(); }
/// <summary> /// Initializes a new instance of the <see cref="LinqCompileCacheDecorator" /> class. /// </summary> /// <param name="handler">The handler.</param> /// <param name="cache">The cache.</param> /// <param name="cachePolicy">The cache policy.</param> /// <param name="metrics">The metrics.</param> /// <param name="connectionInformation">The connection information.</param> public LinqCompileCacheDecorator( ILinqCompiler handler, ObjectCache cache, ICachePolicy<ILinqCompiler> cachePolicy, IMetrics metrics, IConnectionInformation connectionInformation) { _handler = handler; _cache = cache; _itemPolicy = new CacheItemPolicy {SlidingExpiration = cachePolicy.SlidingExpiration}; var name = handler.GetType().Name; _counterActionCacheHit = metrics.Counter($"{connectionInformation.QueueName}.{name}.LinqActionCacheHitCounter", Units.Items); _counterActionCacheMiss = metrics.Counter($"{connectionInformation.QueueName}.{name}.LinqActionCacheMissCounter", Units.Items); _counterActionCacheUnique = metrics.Counter($"{connectionInformation.QueueName}.{name}.LinqActionUniqueFlaggedCounter", Units.Items); _counterFunctionCacheHit = metrics.Counter($"{connectionInformation.QueueName}.{name}.LinqFunctionCacheHiCountert", Units.Items); _counterFunctionCacheMiss = metrics.Counter($"{connectionInformation.QueueName}.{name}.LinqFunctionCacheMissCounter", Units.Items); _counterFunctionCacheUnique = metrics.Counter($"{connectionInformation.QueueName}.{name}.LinqFunctionUniqueFlaggedCounter", Units.Items); }
public void SetUp() { _cachePolicy = new CachePolicy(); }
public ICachePolicy Adjust(ICachePolicy policy) { return policy; }
public DocumentCacheService(ICachePolicy cachePolicy, DocumentListCacheService cacheService) : base(cachePolicy) { _cacheService = cacheService; }
public SpaceCacheService(ICachePolicy cachePolicy, SpaceListCacheService cacheService) : base(cachePolicy) { _cacheService = cacheService; }
public void SetUp() { _handler = new DescriptiveTextStatusCodeHandler(200); _httpRequest = MockRepository.GenerateMock<HttpRequestBase>(); _httpRequest.Stub(arg => arg.Headers).Return(new NameValueCollection()); _httpCachePolicyBase = MockRepository.GenerateMock<HttpCachePolicyBase>(); _httpResponse = MockRepository.GenerateMock<HttpResponseBase>(); _httpResponse.Stub(arg => arg.Cache).Return(_httpCachePolicyBase); _httpResponse.Stub(arg => arg.TrySkipIisCustomErrors).PropertyBehavior(); _cachePolicy = MockRepository.GenerateMock<ICachePolicy>(); _cachePolicy.Stub(arg => arg.Clone()).Return(_cachePolicy); _response = MockRepository.GenerateMock<IResponse>(); _response.Stub(arg => arg.CachePolicy).Return(_cachePolicy); _response.Stub(arg => arg.Cookies).Return(Enumerable.Empty<Cookie>()); _response.Stub(arg => arg.GetContent()).Return(new byte[0]); _response.Stub(arg => arg.Headers).Return(Enumerable.Empty<Header>()); }
public SpaceListCacheService(ICachePolicy cachePolicy) : base(cachePolicy) { }
public ICachePolicy Adjust(ICachePolicy policy) { if (ConfiguredPolicy.AbsoluteSeconds != policy.AbsoluteSeconds || ConfiguredPolicy.SlidingSeconds != policy.SlidingSeconds || ConfiguredPolicy.RefillCount != policy.RefillCount) { policy = policy.Clone(); policy.AbsoluteSeconds = ConfiguredPolicy.AbsoluteSeconds; policy.SlidingSeconds = ConfiguredPolicy.SlidingSeconds; policy.RefillCount = ConfiguredPolicy.RefillCount; } return policy; }
public DocumentListCacheService(ICachePolicy cachePolicy) : base(cachePolicy) { }
public ICachePolicy ComputePolicy(string policyKey, ICachePolicy defaultPolicy) { // do nothing, it's easy return UnchangedPolicyAdjust.Instance.Adjust(defaultPolicy); }