// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IPolicyRegistry <string> policyRegistry, IAsyncCacheProvider memoryCache)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            Func <Context, HttpResponseMessage, Ttl> ttlFilter = (context, result) =>
                                                                 new Ttl(result.IsSuccessStatusCode ? TimeSpan.FromSeconds(30) : TimeSpan.Zero);

            AsyncCachePolicy <HttpResponseMessage> policy =
                Policy.CacheAsync(memoryCache.AsyncFor <HttpResponseMessage>(),
                                  new ResultTtl <HttpResponseMessage>(ttlFilter));

            policyRegistry.Add("cache", policy);

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
Example #2
0
 public ProjectsController(IHttpClientFactory clientFactory, IPolicyRegistry <string> policyRegistry)
 {
     this.clientFactory  = clientFactory;
     this.policyRegistry = policyRegistry;
     //this.cachePolicy = policyRegistry.Get<AsyncCachePolicy<HttpResponseMessage>>(PolicyNames.CachePolicy);
     this.cachePolicy = policyRegistry.Get <AsyncCachePolicy <HttpResponseMessage> >(PolicyNames.CacheOnlyOkPolicy);
 }
        public JsonPlaceholderClient(HttpClient httpClient, IReadOnlyPolicyRegistry <string> policyRegistry)
        {
            _httpClient = httpClient;

            // Resolve the caching policy to be used with this client
            _cachePolicy = policyRegistry.Get <AsyncCachePolicy <string> >("jsonPlaceHolderClientCachePolicy");
        }
        public AuthenticationApiClientCachingDecorator(IAuthenticationApiClient inner)
        {
            _inner = inner;
            _accessTokenResponseCachePolicy = Policy.CacheAsync(
                _memoryCacheProvider.AsyncFor <AccessTokenResponse>(),
                new ResultTtl <AccessTokenResponse>(r => new Ttl(_expiresIn(r), false)));

            _userInfoCachePolicy = Policy.CacheAsync(
                _memoryCacheProvider.AsyncFor <UserInfo>(),
                new ContextualTtl());
        }
Example #5
0
        public static void GetPolicyRegistry(IAsyncCacheProvider cacheProvider,
                                             IPolicyRegistry <string> registry)
        {
            registry.Add("thriceTriplingRetryPolicy", Policy.HandleResult <HttpResponseMessage>(r => !r.IsSuccessStatusCode)
                         .Or <TimeoutRejectedException>()
                         .WaitAndRetryAsync(thriceTriplingTimeSpans));
            registry.Add("loginResponseRetryPolicy", Policy.HandleResult <LoginResponse>(lr => lr.LoginStatus != _successfulLoginStatus)
                         .Or <TimeoutRejectedException>()
                         .WaitAndRetryAsync(thriceTriplingTimeSpans));
            registry.Add("thirtySecondTimeoutPolicy", Policy.TimeoutAsync(TimeSpan.FromSeconds(30)));

            AsyncCachePolicy <LoginResponse> cachePolicy = Policy.CacheAsync <LoginResponse>(cacheProvider, _timeToLive);

            registry.Add("oneMinuteLoginCachePolicy", cachePolicy);
        }
Example #6
0
        internal AccessTokenService(string clientId, string clientSecret, IHttpRequestSender requestSender)
        {
            _clientId      = clientId;
            _clientSecret  = clientSecret;
            _requestSender = requestSender;

            _cache       = new MemoryCache(new MemoryCacheOptions());
            _cachePolicy = Policy.CacheAsync(
                new MemoryCacheProvider(_cache).AsyncFor <AccessToken>(),
                new ResultTtl <AccessToken>(t => new Ttl(t.LifeTime - TimeSpan.FromHours(1))),
                onCacheError: (ctx, _, ex) =>
            {
                Logger.ErrorException($"Could not retrieve access token: '{ex.Message}'", ex);
            });
        }
Example #7
0
        public static AsyncPolicyWrap <HttpResponseMessage> GetRequestPolicy(IMemoryCache memoryCache = null, int cacheSeconds = 0, int additionalRetries = 0, int requestTimeoutSeconds = 100)
        {
            AsyncCachePolicy cache = null;

            if (memoryCache != null)
            {
                var memoryCacheProvider = new MemoryCacheProvider(memoryCache);
                cache = Policy.CacheAsync(memoryCacheProvider, TimeSpan.FromSeconds(cacheSeconds));
            }

            int[] httpStatusCodesWorthRetrying =
            {
                StatusCodes.Status408RequestTimeout,
                StatusCodes.Status429TooManyRequests,
                //StatusCodes.Status500InternalServerError,
                StatusCodes.Status502BadGateway,
                StatusCodes.Status503ServiceUnavailable,
                StatusCodes.Status504GatewayTimeout
            };

            var waitAndRetryPolicy = Policy
                                     .Handle <HttpRequestException>() //HttpClient Timeout or CancellationToken
                                     .Or <TimeoutRejectedException>()
                                     .OrResult <HttpResponseMessage>(r => httpStatusCodesWorthRetrying.Contains((int)r.StatusCode))
                                     .WaitAndRetryAsync(additionalRetries,
                                                        retryAttempt => TimeSpan.FromSeconds(1));

            //https://github.com/App-vNext/Polly/wiki/Timeout
            var requestTimeout = Policy.TimeoutAsync(TimeSpan.FromSeconds(requestTimeoutSeconds));

            //https://github.com/App-vNext/Polly/wiki/PolicyWrap
            AsyncPolicyWrap <HttpResponseMessage> policyWrap = null;

            if (cache != null)
            {
                policyWrap = cache.WrapAsync(waitAndRetryPolicy).WrapAsync(requestTimeout);
            }
            else
            {
                policyWrap = waitAndRetryPolicy.WrapAsync(requestTimeout);
            }

            return(policyWrap);
        }
Example #8
0
        public NewCombinedFeedSource(IEnumerable <IAmACommunityMember> tamarins)
        {
            EnsureHttpClient();

            Tamarins = tamarins;

            if (retryPolicy == null)
            {
                // cache in memory for an hour
                var memoryCache         = new MemoryCache(new MemoryCacheOptions());
                var memoryCacheProvider = new MemoryCacheProvider(memoryCache);
                cachePolicy = Policy.CacheAsync(memoryCacheProvider, TimeSpan.FromHours(1), OnCacheError);

                // retry policy with max 2 retries, delay by x*x^1.2 where x is retry attempt
                // this will ensure we don't retry too quickly
                retryPolicy = Policy.Handle <FeedReadFailedException>()
                              .WaitAndRetryAsync(2, retry => TimeSpan.FromSeconds(retry * Math.Pow(1.2, retry)));
            }
        }
Example #9
0
        public void Configure(
            IApplicationBuilder p_App,
            IWebHostEnvironment p_Env,
            IAsyncCacheProvider p_CacheProvider,
            IPolicyRegistry <string> p_Registry)
        {
            AsyncCachePolicy <HttpResponseMessage> v_Policy =
                Policy.CacheAsync <HttpResponseMessage>(
                    p_CacheProvider,
                    TimeSpan.FromSeconds(30)
                    );

            p_Registry.Add("CachingPolicy", v_Policy);

            Services = p_App.ApplicationServices;

            if (p_Env.IsDevelopment())
            {
                p_App.UseDeveloperExceptionPage();
            }
            else
            {
                p_App.UseExceptionHandler("/Home/Error");
                p_App.UseHsts();
            }
            p_App.UseHttpsRedirection();
            p_App.UseStaticFiles();

            p_App.UseRouting();

            p_App.UseAuthorization();

            p_App.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
        private AsyncPolicy <ClassToCache> SetupAsyncCachePolicy(bool isPolicyEnabled, ClassToCache valueToReturnFromClassToCache)
        {
            this.cacheProvider.Invocations.Clear();
            this.agingStrategy.Invocations.Clear();

            this.cacheProvider.Setup(provider => provider.GetAsync <ClassToCache>(It.IsAny <string>(), It.IsAny <Context>()))
            .ReturnsAsync(valueToReturnFromClassToCache);
            this.cacheProvider.Setup(provider => provider.SetAsync <ClassToCache>(It.IsAny <string>(), It.IsAny <ClassToCache>(), It.IsAny <TimeSpan>(), It.IsAny <Context>()))
            .Returns(Task.CompletedTask);
            this.agingStrategy.Setup(agingStrategy => agingStrategy.GetGraceRelativeToNow(It.IsAny <ClassToCache>(), It.IsAny <Context>()))
            .Returns(TimeSpan.FromDays(1));
            this.agingStrategy.Setup(agingStrategy => agingStrategy.GetExpirationRelativeToNow(It.IsAny <ClassToCache>(), It.IsAny <Context>()))
            .Returns(TimeSpan.FromDays(5));

            var asyncCachePolicy = AsyncCachePolicy <ClassToCache>
                                   .CreateBuilder(isPolicyEnabled, this.agingStrategy.Object, this.cacheProvider.Object, this.loggingProvider.Object)
                                   .FallbackToCacheWhenThrows <TimeoutException>()
                                   .OrFallbackToCacheWhenReturns(returnedValue => returnedValue.Property.Equals(this.errorBackendValue.Property))
                                   .Build();

            return(asyncCachePolicy);
        }
        public async Task <T> GetCachedDataAsync <T>(Func <CancellationToken, Task <T> > dataGetter, string key, CancellationToken cancellationToken, CoordinatedResetCacheTime resetCacheTime = CoordinatedResetCacheTime.OnHour)
        {
            TimeSpan timeToReset;

            switch (resetCacheTime)
            {
            case CoordinatedResetCacheTime.OnHour:
                timeToReset = GetLengthOfTimeUntilNextHour();
                break;

            case CoordinatedResetCacheTime.OnMinute:
                timeToReset = GetLengthOfTimeUntilNextMinute();
                break;
            }

            AsyncCachePolicy cachePolicy = Policy.CacheAsync(_pollyMemoryCacheProvider.MemoryCacheProvider, timeToReset);

            Context context = new Context($"{nameof(CoordinatedResetCache)}_{key}");

            // collapser policy used to prevent concurrent calls retrieving the same data twice
            T result = await _collapserPolicy.WrapAsync(cachePolicy).ExecuteAsync(_ => dataGetter.Invoke(cancellationToken), context);

            return(result);
        }