public TenantOriginProvider( ITenantAllowedOriginsRepository tenantAllowedOriginsRepository, ICacheStore cache) { _cache = cache; _tenantAllowedOriginsRepository = tenantAllowedOriginsRepository; }
public AllowedOriginsProvider( ICacheStore cache, ITenantsRepository tenantsRepository) { _cache = cache; _tenantsRepository = tenantsRepository; }
public DataManipulator(MessageStorage ms) { logger = ms._logger; fileStorage = ms._filestorage; cacheStorage = ms._cache; saveOrReadStorage = ms._saveOrReadStorage; }
internal static void UpdateCachedResponse(CacheKey cacheKey, HttpResponseMessage cachedResponse, HttpResponseMessage serverResponse, ICacheStore store) { TraceWriter.WriteLine("CachingHandler.UpdateCachedResponse - response: " + serverResponse.Headers, TraceLevel.Verbose); // update only if server had a cachecontrol. // TODO: merge CacheControl headers instead of replace if ((serverResponse.Headers.CacheControl != null) && !serverResponse.Headers.CacheControl.NoCache) // added to cover issue #139 { TraceWriter.WriteLine( "CachingHandler.UpdateCachedResponse - CacheControl: " + serverResponse.Headers.CacheControl, TraceLevel.Verbose); cachedResponse.Headers.CacheControl = serverResponse.Headers.CacheControl; } else { TraceWriter.WriteLine( "CachingHandler.UpdateCachedResponse - CacheControl missing from server. Applying sliding expiration. Date => " + DateTimeOffset.UtcNow, TraceLevel.Verbose); } cachedResponse.Headers.Date = DateTimeOffset.UtcNow; // very important store.AddOrUpdate(cacheKey, cachedResponse); }
/// <summary> /// ########### ###### ####### ### ###### # ######## # ###### ####. /// </summary> /// <param name="userConnection">User connection.</param> /// <returns></returns> public QueuesUpdateUtilities(UserConnection userConnection) { _userConnection = userConnection; _insertQueueItemTopValue = GetInsertQueueItemTopValue(); _maximumQueueItemsInQueue = GetMaximumQueueItemsInQueue(); _cache = Store.Cache[CacheLevel.Application].WithLocalCachingOnly(_expireGroupKey); }
public Dictionary <string, string> GetMetrics() { if (CacheManager.CacheStores == null) { return(null); } Dictionary <string, string> metrics = new Dictionary <string, string>(); ICacheStore cacheStore = CacheManager.CacheStores[CacheStoreName]; if (cacheStore == null) { return(metrics); } foreach (string key in cacheStore.Keys()) { string[] cacheKeyParts = key.Split('_'); string cacheDetail = cacheKeyParts.Length > 0 ? cacheKeyParts[cacheKeyParts.Length - 1] : ""; string cacheKey = key.Replace("_" + cacheDetail, "") + ""; if (metrics.ContainsKey(cacheKey)) { metrics[cacheKey] += ",\n" + cacheDetail; } else { metrics.Add(cacheKey, cacheDetail); } } return(metrics); //.OrderBy(metric => metric.Key); }
public static IServiceProvider Initialize( IServiceCollection services, string connectionString, ICacheStore cacheStore, IEmailSender emailSender, EmailsSettings emailsSettings, ILogger logger, IExecutionContextAccessor executionContextAccessor, bool runQuartz = true) { if (runQuartz) { StartQuartz(connectionString, emailsSettings, logger, executionContextAccessor); } services.AddSingleton(cacheStore); var serviceProvider = CreateAutofacServiceProvider( services, connectionString, emailSender, emailsSettings, logger, executionContextAccessor); return(serviceProvider); }
public Cache(ICacheStore store, ICacheRegistry registry, ISite site = null) { _store = store; _registry = registry; Site = site; }
private static void RunInstance1(ICacheStore cache) { var instanceId = 1; Console.WriteLine($"{instanceId}: ------- instance started -------"); Console.WriteLine($"{instanceId}: get requst"); Thread.Sleep(100); var lease = cache.TryGetLease(TimeSpan.FromSeconds(20)); var counter = cache.Get <int>(CounterKeyName); counter++; cache.Set(CounterKeyName, counter); cache.ReleaseLease(lease); Console.WriteLine($"{instanceId}: processed"); Thread.Sleep(300); Console.WriteLine($"{instanceId}: get requst"); Thread.Sleep(150); lease = cache.TryGetLease(TimeSpan.FromSeconds(20)); counter = cache.Get <int>(CounterKeyName); counter++; cache.Set(CounterKeyName, counter); cache.ReleaseLease(lease); Console.WriteLine($"{instanceId}: processed"); Console.WriteLine($"{instanceId}: access count: {cache.Get<int>(CounterKeyName)}"); Console.WriteLine($"{instanceId}: ------- instance shutdown -------"); }
public void SetUp() { _configuration = new Mock <Configuration.IConfiguration>(); _restClient = new Mock <ILoggingRestClient>(); _cacheManagerMock = new Mock <ICacheManager <string, string> >(); _cacheStoreMock = new RedisCacheStore(_cacheManagerMock.Object, true); }
public SectionRepository(UserConnection uc) { UserConnection = uc; EntitySchemaManager = uc.EntitySchemaManager; ApplicationCache = uc.ApplicationCache; ResourceStorage = uc.ResourceStorage; }
/// <summary> /// Creates HttpClient with the store and HttpClientHandler /// </summary> /// <param name="store"></param> /// <param name="handler"></param> /// <returns></returns> public static HttpClient CreateClient(this ICacheStore store, HttpMessageHandler handler = null) { return(new HttpClient(new CachingHandler(store) { InnerHandler = handler ?? new HttpClientHandler() })); }
public WorkplaceRepository(UserConnection uc) { _userConnection = uc; _entitySchemaManager = uc.EntitySchemaManager; _applicationCache = uc.ApplicationCache; _resourceStorage = uc.ResourceStorage; }
public void Setup() { _cacheStore = Substitute.For <ICacheStore>(); _cacheStore.StoreId.Returns(10); _adaptor = new CacheStoreAdaptor(_cacheStore); Assert.AreEqual(10, _adaptor.StoreId); }
public void Setup() { _cacheStore = Substitute.For<ICacheStore>(); _cacheStore.StoreId.Returns(10); _adaptor = new CacheStoreAdaptor(_cacheStore); Assert.AreEqual(10, _adaptor.StoreId); }
public HomeViewModel() { _cacheStore = DependencyService.Resolve <ICacheStore>(); Cards = new ObservableRangeCollection <HomeCard>(); LoadData().SafeFireAndForget(); }
public CacheServer(ICacheStore store, string url) { Store = store; _server = new SelfHostServer(url); _server.DependencyResolver.Register(typeof(CacheConnection), () => new CacheConnection(this)); _server.MapConnection<CacheConnection>("/cache"); }
protected BaseBackgroundCacheService( ICacheStore cacheStore, IAmtrackLogger logger) : base(logger) { cancellationTokenSource = new CancellationTokenSource(); }
private IServiceProvider CreateServiceProvider(ICacheStore <CacheUser> userCache, IVersionedTable <CacheUser> userTable) { // Create the services collection. var services = new ServiceCollection(); ServerLibInitializer.RegisterTypes(services, this.global.MakeTestConfiguration()); // Mock the caches. var cachesMock = new Mock <ICaches>(); cachesMock.SetupGet(c => c.Users).Returns(userCache); cachesMock.Setup(c => c.StoreForType <CacheUser>()).Returns(userCache); services.AddSingleton(cachesMock.Object); // Mock the database. var tablesMock = new Mock <ITables>(); tablesMock.Setup(t => t.TableForType <CacheUser>()).Returns(userTable); tablesMock.Setup(t => t.TableForVersionedType <CacheUser>()).Returns(userTable); services.AddSingleton(tablesMock.Object); // Create the service provider and return. return(services.BuildServiceProvider()); }
public CosmonautCache( ICacheStore <CacheItem> cacheStore, ILogger <CosmonautCache <T> > logger) { _cacheStore = cacheStore; _logger = logger; }
public CountriesController(AppDbContext context, ICacheStore cacheStore, ICacheManager cacheManager, IConfiguration configuration) { _context = context; _cacheStore = cacheStore; _cacheManager = cacheManager; _configuration = configuration; }
public GoQrService(IQrClient client, IQrProvider provider, ICacheStore cacheStore, ILogger <GoQrService> logger) { _client = client; _provider = provider; _cacheStore = cacheStore; _logger = logger; }
public ScoringAssessmentsServiceV3(ICacheStore cache, IDomainServiceProvider domainServiceProvider, IOdsApiClientProvider odsApiClientProvider, IOdsApiSettingsProvider odsApiSettingsProvider) { _cache = cache; _domainServiceProvider = domainServiceProvider; _odsApiClientProvider = odsApiClientProvider; _odsApiSettingsProvider = odsApiSettingsProvider; }
/// <summary> /// Creates <see cref="RedisDistributedCacheStore"/> from <see cref="CacheStoreDefinition"/> configuration /// </summary> /// <param name="cacheStoreInfo">Redis <see cref="CacheStoreDefinition"/> configuration</param> /// <returns><see cref="CustomDistributedCacheStore"/> object</returns> public ICacheStore CreateCacheStore(CacheStoreDefinition cacheStoreInfo) { ICacheStore cacheStore = null; if (!string.IsNullOrWhiteSpace(cacheStoreInfo.StoreConfig)) { //CustomStoreInfo sqlServerStoreInfo = // JsonConvert.DeserializeObject<CustomStoreInfo>(cacheStoreInfo.CacheOptions); //cacheStore = new CustomDistributedCacheStore<T>(Type.GetType(cacheStoreInfo.TypeInfo)) //{ // CacheOptions = options => // { // options.ConnectionString = sqlServerStoreInfo.ConnectionString; // options.DefaultSlidingExpiration = sqlServerStoreInfo.DefaultSlidingExpiration; // options.ExpiredItemsDeletionInterval = sqlServerStoreInfo.ExpiredItemsDeletionInterval; // options.SchemaName = sqlServerStoreInfo.SchemaName; // options.TableName = sqlServerStoreInfo.TableName; // } //}; } else { //cacheStore = new CustomDistributedCacheStore<Type>() { CacheOptions = options => { } }; } return(cacheStore); }
public PageEntityRepository(UserConnection uc) { UserConnection = uc; EntitySchemaManager = uc.EntitySchemaManager; ApplicationCache = uc.ApplicationCache; CurrentUser = uc.CurrentUser; Workspace = uc.Workspace; }
public PersonsController(IPersonSource personSource, ICacheStore cacheStore, IDistributedCache cache) { PersonSource = personSource; CacheStore = cacheStore; Cache = cache; }
public ArtistsViewModel() { _cacheStore = DependencyService.Resolve <ICacheStore>(); Artists = new ObservableRangeCollection <Artist>(); ArtistTappedCommand = new AsyncCommand <Artist>(ArtistTappedAsync); LoadData().SafeFireAndForget(); }
public OdsApiSettingsProvider(AppSettings appSettings, ICacheStore cacheProvider, IConfiguration configuration, IEnvironmentProvider environmentProvider, IKeyVaultFacade keyVaultProvider) { _appSettings = appSettings; _cacheProvider = cacheProvider; _configuration = configuration; _environmentProvider = environmentProvider; _keyVaultProvider = keyVaultProvider; }
public AsyncInventoryCacheService( ICacheStore cacheStore, IAmtrackLogger logger, bool synchronous, string serviceName) : base(cacheStore, logger, synchronous, serviceName) { }
public void InitialData() { this.Cache = CacheHelper.GetCacheStore(); // warmup cache for further reading this.ListForReading = Seed.BuildReasons(totalKeys: 5000, totalReasons: 2, totalRemovedEntities: 4); this.WarmUpCacheForReading(); }
public AdminService(IUnitOfWork unitOfWork, ICacheStore cacheStore, IPasswordService hasher, IIdentityProvider identityProvider) { _unitOfWork = unitOfWork; _cacheStore = cacheStore; _hasher = hasher; _identityProvider = identityProvider; }
public ArtistDetailsViewModel(string id) { ArtistId = id; _cacheStore = DependencyService.Resolve <ICacheStore>(); LoadData().SafeFireAndForget(); }
public void Setup() { _mockRepository = new MockRepository(); _cacheStore = _mockRepository.StrictMock<ICacheStore>(); _messageHandler = new DummyMessageHandler(); _cachingHandler = new CachingHandler(_cacheStore) { InnerHandler = _messageHandler }; _client = new HttpClient(_cachingHandler); }
/// <summary> /// /// </summary> /// <param name="nancyBootstrapper"></param> /// <param name="routeResolver"></param> /// <param name="pipeline"></param> /// <param name="cacheKeyGenerator"></param> /// <param name="cacheStore"></param> public static void Enable(INancyBootstrapper nancyBootstrapper, IRouteResolver routeResolver, IPipelines pipeline, ICacheKeyGenerator cacheKeyGenerator, ICacheStore cacheStore) { if (_enabled) return; _enabled = true; _cacheKeyGenerator = cacheKeyGenerator; _cacheStore = cacheStore; _nancyBootstrapper = nancyBootstrapper; _routeResolver = routeResolver; pipeline.BeforeRequest.AddItemToStartOfPipeline(CheckCache); pipeline.AfterRequest.AddItemToEndOfPipeline(SetCache); }
/// <summary> /// /// </summary> /// <param name="nancyBootstrapper"></param> /// <param name="routeResolver"></param> /// <param name="pipeline"></param> /// <param name="varyParams"></param> /// <param name="cacheStore"></param> public static void Enable(INancyBootstrapper nancyBootstrapper, IRouteResolver routeResolver, IPipelines pipeline, IEnumerable<string> varyParams, ICacheStore cacheStore) { if (_enabled) return; _enabled = true; _varyParams = varyParams.Select(key => key.ToLower().Trim()).ToArray(); _cacheStore = cacheStore; _nancyBootstrapper = nancyBootstrapper; _routeResolver = routeResolver; pipeline.BeforeRequest.AddItemToStartOfPipeline(CheckCache); pipeline.AfterRequest.AddItemToEndOfPipeline(SetCache); }
/// <summary> /// Initializes a new instance of the <see cref="CacheStore" /> class. /// </summary> /// <param name="store">Store.</param> /// <param name="convertBinary">Whether to convert binary objects.</param> /// <param name="registry">The handle registry.</param> private CacheStore(ICacheStore store, bool convertBinary, HandleRegistry registry) { Debug.Assert(store != null); _store = store; _convertBinary = convertBinary; _sesProxy = new CacheStoreSessionProxy(); ResourceProcessor.InjectStoreSession(store, _sesProxy); _handle = registry.AllocateCritical(this); }
/// <summary> /// Instantiates the HttpCacheHandler /// </summary> /// <param name="cacheStore">An instance of an implementation of ICacheStore</param> /// <param name="cacheHandlerSettings">An instance of an implementation of IHttpCacheHandlerSettings</param> public HttpCacheHandler(ICacheStore cacheStore, IHttpCacheHandlerSettings cacheHandlerSettings) { if (cacheStore == null) { throw new ArgumentNullException("cacheStore", "Provided ICacheStore implementation cannot be null."); } if (cacheHandlerSettings == null) { throw new ArgumentNullException("cacheHandlerSettings", "Provided IHttpCacheHandlerSettings implementation cannot be null."); } _cacheStore = cacheStore; _forceRevalidationOfStaleResourceRepresentations = cacheHandlerSettings.ForceRevalidationOfStaleResourceRepresentations; _enableConditionalPatch = cacheHandlerSettings.EnableConditionalPatch; _enableConditionalPut = cacheHandlerSettings.EnableConditionalPut; _enableClearRelatedResourceRepresentationsAfterPatch = cacheHandlerSettings.EnableClearRelatedResourceRepresentationsAfterPatch; _enableClearRelatedResourceRepresentationsAfterPut = cacheHandlerSettings.EnableClearRelatedResourceRepresentationsAfterPut; }
internal static void UpdateCachedResponse(CacheKey cacheKey, HttpResponseMessage cachedResponse, HttpResponseMessage serverResponse, ICacheStore store) { TraceWriter.WriteLine("CachingHandler.UpdateCachedResponse - response: " + serverResponse.Headers.ToString(), TraceLevel.Verbose); // update only if server had a cachecontrol. // TODO: merge CacheControl headers instead of replace if (serverResponse.Headers.CacheControl != null && (!serverResponse.Headers.CacheControl.NoCache)) // added to cover issue #139 { TraceWriter.WriteLine("CachingHandler.UpdateCachedResponse - CacheControl: " + serverResponse.Headers.CacheControl.ToString(), TraceLevel.Verbose); cachedResponse.Headers.CacheControl = serverResponse.Headers.CacheControl; } else { TraceWriter.WriteLine("CachingHandler.UpdateCachedResponse - CacheControl missing from server. Applying sliding expiration. Date => " + DateTimeOffset.UtcNow, TraceLevel.Verbose); } cachedResponse.Headers.Date = DateTimeOffset.UtcNow; // very important store.AddOrUpdate(cacheKey, cachedResponse); }
/// <summary> /// Enables Nancy.LightningCache using the supplied parameters and CacheStore type /// </summary> /// <param name="bootstrapper"></param> /// <param name="routeResolver"> </param> /// <param name="pipelines"></param> /// <param name="varyParams"></param> /// <param name="cacheStore"> </param> public static void EnableLightningCache(this INancyBootstrapper bootstrapper, IRouteResolver routeResolver, IPipelines pipelines, IEnumerable<string> varyParams, ICacheStore cacheStore) { LightningCache.Enable(bootstrapper, routeResolver, pipelines, varyParams, cacheStore); }
public CachingHandler(ICacheStore cacheStore) : this(cacheStore, new InMemoryVaryHeaderStore()) { _disposeVaryStore = true; }
public CachingHandler(ICacheStore cacheStore, IVaryHeaderStore varyHeaderStore) { _cacheStore = cacheStore; UseConditionalPut = true; MustRevalidateByDefault = true; VaryHeaderStore = varyHeaderStore; DefaultVaryHeaders = new string[] { "Accept" }; ResponseValidator = (response) => { // 13.4 //Unless specifically constrained by a cache-control (section 14.9) directive, a caching system MAY always store // a successful response (see section 13.8) as a cache entry, MAY return it without validation if it // is fresh, and MAY return it after successful validation. If there is neither a cache validator nor an // explicit expiration time associated with a response, we do not expect it to be cached, but certain caches MAY violate this expectation // (for example, when little or no network connectivity is available). // 14.9.1 // If the no-cache directive does not specify a field-name, then a cache MUST NOT use the response to satisfy a subsequent request without // successful revalidation with the origin server. This allows an origin server to prevent caching // even by caches that have been configured to return stale responses to client requests. //If the no-cache directive does specify one or more field-names, then a cache MAY use the response // to satisfy a subsequent request, subject to any other restrictions on caching. However, the specified // field-name(s) MUST NOT be sent in the response to a subsequent request without successful revalidation // with the origin server. This allows an origin server to prevent the re-use of certain header fields in a response, while still allowing caching of the rest of the response. if (!response.StatusCode.IsIn(_cacheableStatuses)) return ResponseValidationResult.NotCacheable; if (!response.IsSuccessStatusCode || response.Headers.CacheControl == null || response.Headers.CacheControl.NoStore) // || response.Headers.CacheControl.NoCache was removed. See issue return ResponseValidationResult.NotCacheable; if (response.Headers.Date == null) TraceWriter.WriteLine("Response date is NULL", TraceLevel.Warning); response.Headers.Date = response.Headers.Date ?? DateTimeOffset.UtcNow; // this also helps in cache creation var dateTimeOffset = response.Headers.Date; TraceWriter.WriteLine( String.Format("CachedResponse date was => {0} - compared to UTC.Now => {1}", dateTimeOffset, DateTimeOffset.UtcNow), TraceLevel.Verbose); if (response.Content == null) return ResponseValidationResult.NotCacheable; if (response.Headers.CacheControl.MaxAge == null && response.Headers.CacheControl.SharedMaxAge == null && response.Content.Headers.Expires == null) return ResponseValidationResult.NotCacheable; if (response.Headers.CacheControl.NoCache) return ResponseValidationResult.MustRevalidate; // here we use if (response.Content.Headers.Expires != null && response.Content.Headers.Expires < DateTimeOffset.UtcNow) return response.Headers.CacheControl.ShouldRevalidate(MustRevalidateByDefault) ? ResponseValidationResult.MustRevalidate : ResponseValidationResult.Stale; if (response.Headers.CacheControl.MaxAge != null && DateTimeOffset.UtcNow > response.Headers.Date.Value.Add(response.Headers.CacheControl.MaxAge.Value)) return response.Headers.CacheControl.ShouldRevalidate(MustRevalidateByDefault) ? ResponseValidationResult.MustRevalidate : ResponseValidationResult.Stale; if (response.Headers.CacheControl.SharedMaxAge != null && DateTimeOffset.UtcNow > response.Headers.Date.Value.Add(response.Headers.CacheControl.SharedMaxAge.Value)) return response.Headers.CacheControl.ShouldRevalidate(MustRevalidateByDefault) ? ResponseValidationResult.MustRevalidate : ResponseValidationResult.Stale; return ResponseValidationResult.OK; }; _ignoreRequestRules = (request) => { if (!request.Method.IsIn(HttpMethod.Get, HttpMethod.Put)) return true; // client can tell CachingHandler not to do caching for a particular request if (request.Headers.CacheControl != null) { if (request.Headers.CacheControl.NoStore) return true; } return false; }; ResponseStoragePreparationRules = (response) => { // 14.9.3 // If a response includes both an Expires header and a max-age directive, // the max-age directive overrides the Expires header, even if the Expires header is more restrictive. if (response.Content.Headers.Expires != null && (response.Headers.CacheControl.MaxAge != null || response.Headers.CacheControl.SharedMaxAge != null)) { response.Content.Headers.Expires = null; } }; }
public CacheStoreAdaptor(ICacheStore syncCacheStore) { _syncCacheStore = syncCacheStore; }
public void IgnoreExceptionPolicy_Ignores_CacheStore_Exceptions() { // setup var request = new HttpRequestMessage(HttpMethod.Put, DummyUrl); var responseFromServer = GetOkMessage(); _messageHandler.Response = responseFromServer; _cacheStore = new FaultyCacheStore(); _cachingHandler = new CachingHandler(_cacheStore) { InnerHandler = _messageHandler }; _cachingHandler.ExceptionHandler = CachingHandler.IgnoreExceptionPolicy; _client = new HttpClient(_cachingHandler); // run var task = _client.SendAsync(request); var responseReturned = task.Result; // verify Assert.AreEqual(responseFromServer, responseReturned); }
/// <summary> /// Enables Nancy.LightningCache using the supplied parameters and CacheStore type /// </summary> /// <param name="bootstrapper"></param> /// <param name="routeResolver"> </param> /// <param name="pipelines"></param> /// <param name="cacheKeyGenerator"></param> /// <param name="cacheStore"> </param> public static void EnableLightningCache(this INancyBootstrapper bootstrapper, IRouteResolver routeResolver, IPipelines pipelines, ICacheKeyGenerator cacheKeyGenerator, ICacheStore cacheStore) { LightningCache.Enable(bootstrapper, routeResolver, pipelines, cacheKeyGenerator, cacheStore); }
/// <summary> /// Instantiates the HttpCacheHandler /// </summary> /// <param name="cacheStore">An instance of an implementation of ICacheStore</param> public HttpCacheHandler(ICacheStore cacheStore) : this(cacheStore, new HttpCacheHandlerSettings()) { }
public CacheServer(ICacheStore store, string url) { Store = store; Store.OnEntryRemoved = OnEntryRemoved; _url = url; }
public HttpCacheMiddleware(RequestDelegate next, ICacheStore store, ILogger logger) { _next = next; _store = store; _logger = logger; }
internal static void UpdateCachedResponse(CacheKey cacheKey, HttpResponseMessage cachedResponse, HttpResponseMessage serverResponse, ICacheStore store) { // update only if server had a cachecontrol. // TODO: merge CacheControl headers instead of replace if (serverResponse.Headers.CacheControl != null) { cachedResponse.Headers.CacheControl = serverResponse.Headers.CacheControl; cachedResponse.Headers.Date = DateTimeOffset.UtcNow; // very important store.AddOrUpdate(cacheKey, cachedResponse); } }
public CachingHandler(ICacheStore cacheStore) { _cacheStore = cacheStore; UseConditionalPut = true; VaryHeaderStore = new InMemoryVaryHeaderStore(); DefaultVaryHeaders = new string[]{"Accept"}; ResponseValidator = (response) => { // 13.4 //Unless specifically constrained by a cache-control (section 14.9) directive, a caching system MAY always store // a successful response (see section 13.8) as a cache entry, MAY return it without validation if it // is fresh, and MAY return it after successful validation. If there is neither a cache validator nor an // explicit expiration time associated with a response, we do not expect it to be cached, but certain caches MAY violate this expectation // (for example, when little or no network connectivity is available). if (!response.StatusCode.IsIn(_cacheableStatuses)) return ResponseValidationResult.NotCacheable; if (!response.IsSuccessStatusCode || response.Headers.CacheControl == null || response.Headers.CacheControl.NoStore || response.Headers.CacheControl.NoCache) return ResponseValidationResult.NotCacheable; response.Headers.Date = response.Headers.Date ?? DateTimeOffset.UtcNow; // this also helps in cache creation var dateTimeOffset = response.Headers.Date; if(response.Content == null) return ResponseValidationResult.NotCacheable; if (response.Headers.CacheControl.MaxAge == null && response.Headers.CacheControl.SharedMaxAge == null && response.Content.Headers.Expires == null) return ResponseValidationResult.NotCacheable; if (response.Content.Headers.Expires != null && response.Content.Headers.Expires < DateTimeOffset.UtcNow) return response.Headers.CacheControl.MustRevalidate ? ResponseValidationResult.MustRevalidate : ResponseValidationResult.Stale; if (response.Headers.CacheControl.MaxAge != null && DateTimeOffset.UtcNow > response.Headers.Date.Value.Add(response.Headers.CacheControl.MaxAge.Value)) return response.Headers.CacheControl.MustRevalidate ? ResponseValidationResult.MustRevalidate : ResponseValidationResult.Stale; if (response.Headers.CacheControl.SharedMaxAge != null && DateTimeOffset.UtcNow > response.Headers.Date.Value.Add(response.Headers.CacheControl.SharedMaxAge.Value)) return response.Headers.CacheControl.MustRevalidate ? ResponseValidationResult.MustRevalidate : ResponseValidationResult.Stale; return ResponseValidationResult.OK; }; _ignoreRequestRules = (request) => { if (!request.Method.IsIn(HttpMethod.Get, HttpMethod.Put)) return true; // client can tell CachingHandler not to do caching for a particular request if(request.Headers.CacheControl!=null) { if (request.Headers.CacheControl.NoCache || request.Headers.CacheControl.NoStore) return true; } return false; }; ResponseStoragePreparationRules = (response) => { // 14.9.3 // If a response includes both an Expires header and a max-age directive, // the max-age directive overrides the Expires header, even if the Expires header is more restrictive. if(response.Content.Headers.Expires!=null && (response.Headers.CacheControl.MaxAge != null || response.Headers.CacheControl.SharedMaxAge!=null)) { response.Content.Headers.Expires = null; } }; }
internal CacheStoreDecorator(ICacheStore inner) { this.inner = inner; }
public HttpCacheActionFilter(ICacheStore store, ILogger<HttpCacheActionFilter> logger) { _store = store; _logger = logger; }
internal CountingCacheStore(ICacheStore inner) : base(inner) { this.ResetCounters(); }
/// <summary> /// Register the <see cref="ICacheStore" /> /// </summary> /// <param name="store"></param> /// <returns></returns> public void RegisterStore(ICacheStore store) { if (store == null) { throw new ArgumentNullException(nameof(store)); } if (store.StoreId > 0 && _asyncCacheStore.ContainsKey(store.StoreId)) { throw new InvalidOperationException($"There is a registered IAsyncCacheStore with id {store.StoreId}: {_asyncCacheStore[store.StoreId].GetType().Name}"); } _cacheStore[store.StoreId] = store; _cacheStoreTypes[store.GetType()] = store; }
public CachingHandler(ICacheStore cacheStore) { _cacheStore = cacheStore; VaryHeaderStore = new InMemoryVaryHeaderStore(); DefaultVaryHeaders = new string[]{"Accept"}; }
public void DefaultExceptionPolicy_Throws_CacheStore_Exceptions() { // setup var request = new HttpRequestMessage(HttpMethod.Put, DummyUrl); var responseFromServer = GetOkMessage(); _messageHandler.Response = responseFromServer; _cacheStore = new FaultyCacheStore(); _cachingHandler = new CachingHandler(_cacheStore) { InnerHandler = _messageHandler }; _client = new HttpClient(_cachingHandler); // run var task = _client.SendAsync(request); var responseReturned = task.Result; }
public MemoryCacheProvider_Tests() { LocalIocManager.Register<ICacheProvider, MemoryCacheProvider>(); _cacheProvider = LocalIocManager.Resolve<ICacheProvider>(); _cacheStore = _cacheProvider.GetOrCreateCacheStore<string, MyCacheItem>("MyCacheItems"); }
/// <summary> /// Inject cache store session. /// </summary> /// <param name="store">Store.</param> /// <param name="ses">Store session.</param> public static void InjectStoreSession(ICacheStore store, ICacheStoreSession ses) { Debug.Assert(store != null); Descriptor(store.GetType()).InjectStoreSession(store, ses); }
/// <summary> /// Enables Nancy.LightningCache using the supplied parameters and CacheStore type /// </summary> /// <param name="bootstrapper"></param> /// <param name="routeResolver"> </param> /// <param name="pipelines"></param> /// <param name="varyParams"></param> /// <param name="cacheStore"> </param> public static void EnableLightningCache(this INancyBootstrapper bootstrapper, IRouteResolver routeResolver, IPipelines pipelines, string[] varyParams, ICacheStore cacheStore) { LightningCache.Enable(bootstrapper, routeResolver, pipelines, new DefaultCacheKeyGenerator(varyParams), cacheStore); }