/// <summary>
        /// All policies implement ISyncPolicy or IAsyncPolicy
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public string UseRegistry(int input)
        {
            var policy   = _registry.Get <ISyncPolicy>("DefaultRetry");
            var response = policy.Execute(
                () => dbContext.First(r => r.Key == input));

            return(response.Value);
        }
        public void Should_be_able_to_overwrite_existing_Policy_if_key_exists_when_inserting_using_Indexer()
        {
            Policy policy = Policy.NoOp();
            string key    = Guid.NewGuid().ToString();

            _registry.Add(key, policy);

            Policy policy_new = Policy.NoOp();

            _registry[key] = policy_new;

            _registry.Count.Should().Be(1);

            _registry.Get <Policy>(key).Should().BeSameAs(policy_new);
        }
        public void ProcessRquestData(byte[] data, TaskCompletionSource <Message> responseRawDataAvailableTcs, TaskCompletionSource <object> responseSentTcs)
        {
            var           applicationMessage = _messageFactory.CreateApplicationMessage(data);
            IInboundReply reply = null;

            var messageAvailable = applicationMessage.Message != null;

            reply = _replyFactory.CreateIInboundReply(responseRawDataAvailableTcs, responseSentTcs);

            var circuitBreaker = _policyRegistry.Get <CircuitBreakerPolicy <Message> >(applicationMessage.Backend);

            var policy = Policy.HandleResult <Message>(r => r.IsFault).
                         Fallback(applicationMessage.Message, (x) =>
            {
                reply.Reply(applicationMessage.ErrorMessage, TimeSpan.FromSeconds(1));
            }).Wrap(circuitBreaker);

            policy.Execute(() =>
            {
                if (messageAvailable)
                {
                    _inboundQueue.Enqueue(new Tuple <bool, Message, IInboundReply>(messageAvailable, applicationMessage.Message, reply));
                }

                return(applicationMessage.Message);
            });
        }
Esempio n. 4
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);
 }
        protected QueueBase(string connectionString, IPolicyRegistry <string> policyRegistry, string policyRegistryKey, CancellationToken cancellationToken)
        {
            CancellationToken = cancellationToken;
            StorageAccount    = CloudStorageAccount.Parse(connectionString);
            QueueClient       = StorageAccount.CreateCloudQueueClient();

            _cachingPolicy = policyRegistry.Get <ISyncPolicy <CloudQueue> >(policyRegistryKey);
        }
Esempio n. 6
0
        public UserController(HttpClient client, IResilientHttpClient resilientClient, IPolicyRegistry <string> registry)
        {
            _client = client;
            // _circuitBreakerPolicy = circuitBreakerPolicy;
            _resilientClient = resilientClient;

            _cachePolicy = registry.Get <CachePolicy <HttpResponseMessage> >("cache");
        }
        public void ProcessResponseData(byte[] data)
        {
            var applicationMessage = _messageFactory.CreateApplicationMessage(data);

            var circuitBreaker = _policyRegistry.Get <CircuitBreakerPolicy <Message> >(applicationMessage.Backend);

            circuitBreaker.Execute(() => applicationMessage.Message);

            _tcs.TrySetResult(applicationMessage.Message);
        }
        public IDictionary <string, CircuitState> GetCircuitStates()
        {
            var dict = new Dictionary <string, CircuitState>(Registry.Count);

            foreach (var policy in Registry)
            {
                dict.Add(policy.Key, Registry.Get <ICircuitBreakerPolicy>(policy.Key).CircuitState);
            }

            return(dict);
        }
Esempio n. 9
0
        public async Task <IActionResult> Get(Guid id)
        {
            //policy inside the MessageHandler
            //var response = await azureDevOpsApi.GetProject(id);

            //policy injected from registry
            var retryPolicy = policyRegistry.Get <IAsyncPolicy <ApiResponse <Project> > >(PolicyNames.RefitRetryPolicy);
            var response    = await retryPolicy.ExecuteAsync(() => azureDevOpsApi.GetProject(id));

            return(!response.IsSuccessStatusCode ?
                   StatusCode((int)response.StatusCode, response.Error.Content) :
                   Ok(response.Content));
        }
Esempio n. 10
0
        public async Task <IActionResult> Get(int id)
        {
            string requestEndpoint = $"inventory/{id}";

            IAsyncPolicy <HttpResponseMessage> httpRetryPolicy =
                _policyRegistry.Get <IAsyncPolicy <HttpResponseMessage> >("SimpleHttpRetryPolicy");

            IAsyncPolicy httpClientTimeoutExceptionPolicy =
                _policyRegistry.Get <IAsyncPolicy>("SimpleHttpTimeoutPolicy");

            HttpResponseMessage response =
                await httpRetryPolicy.ExecuteAsync(
                    () => httpClientTimeoutExceptionPolicy.ExecuteAsync(
                        async token => await _httpClient.GetAsync(requestEndpoint, token), CancellationToken.None));

            if (response.IsSuccessStatusCode)
            {
                int itemsInStock = JsonConvert.DeserializeObject <int>(await response.Content.ReadAsStringAsync());
                return(Ok(itemsInStock));
            }

            return(StatusCode((int)response.StatusCode, response.Content.ReadAsStringAsync()));
        }
Esempio n. 11
0
 public MeetupService(IOptions <MeetupEndPoint> meetupOptions,
                      IPolicyRegistry <string> policyRegistry,
                      IHttpClientFactory httpClientFactory)
 {
     _meetupOptions      = meetupOptions;
     _client             = httpClientFactory.CreateClient();
     _client.BaseAddress = new Uri(meetupOptions.Value.Url);
     _cachePolicy        = policyRegistry.Get <IAsyncPolicy <HttpResponseMessage> >("myCachePolicy");
     if (Token == null)
     {
         Token              = new AuthToken();
         Token.Token        = _meetupOptions.Value.Token;
         Token.RefreshToken = _meetupOptions.Value.RefreshToken;
     }
 }
Esempio n. 12
0
        public async Task <LoginResponse> Login()
        {
            var     timeoutPolicy          = _registry.Get <IAsyncPolicy>("thirtySecondTimeoutPolicy");
            var     asyncGetPolicy         = _registry.Get <IAsyncPolicy <HttpResponseMessage> >("thriceTriplingRetryPolicy");
            var     readStreamPolicy       = _registry.Get <IAsyncPolicy <LoginResponse> >("loginResponseRetryPolicy");
            var     cachePolicy            = _registry.Get <IAsyncPolicy <LoginResponse> >("oneMinuteLoginCachePolicy");
            Context policyExecutionContext = new Context($"AuthLogin");

            return(await cachePolicy.ExecuteAsync(async context =>
                                                  await readStreamPolicy.ExecuteAsync(async() =>
            {
                HttpResponseMessage responseMessage = await asyncGetPolicy.ExecuteAsync(async() =>
                                                                                        await timeoutPolicy.ExecuteAsync(async token =>
                                                                                                                         await _httpClient.PostAsync(_url, _loginBody, token), CancellationToken.None));
                if (!responseMessage.IsSuccessStatusCode)
                {
                    throw new HttpResponseException(responseMessage);
                }
                string content = await responseMessage.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject <LoginResponse>(content);
            }),
                                                  policyExecutionContext
                                                  ));
        }
        public static IHttpClientBuilder AddLCUTimeoutPolicy(this IHttpClientBuilder httpClientBuilder,
                                                             IPolicyRegistry <string> registry)
        {
            return(httpClientBuilder
                   .AddPolicyHandler(request =>
            {
                var timeoutPolicy = "regular";

                if (request.Method != HttpMethod.Get)
                {
                    timeoutPolicy = "long";
                }

                return registry.Get <IAsyncPolicy <HttpResponseMessage> >(timeoutPolicy);
            }));
        }
Esempio n. 14
0
        /// <summary>
        /// Inject a registry created elsewhere, and execute a policy from it.
        /// </summary>
        /// <param name="registry"></param>
        /// <returns></returns>
        public void RetryUsingRegistry(IPolicyRegistry <string> registry)
        {
            var results = new Results();
            var policy  = registry.Get <RetryPolicy>("DefaultRetry");

            for (int i = 1; i <= 20; i++)
            {
                int response = -1;
                policy.Execute(() =>
                {
                    response = _service.MostlyBad(i);
                    Program.ResultsLog.Success++;
                });
                //Console.WriteLine($"Request {i} | Response {response}");
            }
        }
Esempio n. 15
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] MyClaim myClaim,
            [Inject] IClaimsClient claimsClient,
            [Inject] IPolicyRegistry <string> policyRegistry,
            ILogger log)
        {
            string referenceNum = default(string);

            var authPolicy = policyRegistry.Get <IAsyncPolicy <string> >("auth_policy");

            await authPolicy.ExecuteAsync(
                async() =>
                referenceNum = await claimsClient.PostAsync(myClaim)
                );

            return(new OkObjectResult(referenceNum));
        }
Esempio n. 16
0
        public async Task <string> Get(int id)
        {
            var policy = _policyRegistry.Get <AsyncCachePolicy <HttpResponseMessage> >("cache");

            var executionContext = new Context($"id-{id}");
            var response         =
                await policy.ExecuteAsync(async (x) => await _httpClient.GetAsync($"weatherforecast?id={id}"), executionContext);

            var responseString = await response.Content.ReadAsStringAsync();

            if (response.IsSuccessStatusCode)
            {
                return(responseString);
            }

            throw new Exception(responseString);
        }
Esempio n. 17
0
        public void ExecuteGetCall(string name, string endpoint, string policyName)
        {
            var policy = _policyRegistry.Get <IAsyncPolicy <HttpResponseMessage> >(policyName);

            policy.ExecuteAsync(async context =>
            {
                HttpResponseMessage result = null;
                try
                {
                    using (var httpClient = _httpClientFactory.CreateClient(name))
                    {
                        result = await httpClient.GetAsync(endpoint);

                        if (result == null)
                        {
                            _logger.LogWarning("Result was null");
                        }
                        else if (result.Content == null)
                        {
                            _logger.LogWarning("Result.Content was null");
                        }
                        else
                        {
                            var content = await result.Content.ReadAsStringAsync();
                            _logger.LogInformation($"Result is <{content}>");
                        }
                    }
                }
                catch (HttpRequestException hre)
                {
                    _logger.LogError($"HttpRequestException occurred <{hre.Message}>");
                }
                catch (Polly.CircuitBreaker.BrokenCircuitException bce)
                {
                    _logger.LogError($"BrokenCircuitException occurred <{bce.Message}>");
                }

                return(result);
            }, new Context("myCachedValue"));

            //await Task.CompletedTask;
        }
Esempio n. 18
0
        public async Task <T> Invoke <T>(BetfairMethod method, BetfairRequestParameters requestParameters)
        {
            if (method == BetfairMethod.UnknownMethod)
            {
                throw new ArgumentOutOfRangeException("Method must be defined", "method");
            }
            string methodName = BetfairMethodExtensions.GetMethodName(method);

            IDictionary <string, object> args = new Dictionary <string, object>()
            {
                { "filter", requestParameters?.Filter ?? new MarketFilter() }
            };

            if (requestParameters != null && requestParameters.MarketProjections != null &&
                requestParameters.MarketProjections.Count > 0)
            {
                args["marketProjection"] = requestParameters.MarketProjections;
            }
            if (requestParameters != null && requestParameters.MaxResults != null &&
                requestParameters.MaxResults > 0 && requestParameters.MaxResults <= 1000)
            {
                args["maxResults"] = requestParameters.MaxResults;
            }

            LoginResponse loginResponse = await _authenticationClient.Login();

            if (loginResponse == null)
            {
                throw new AuthenticationException("LoginResponse is null");
            }
            else if (loginResponse.SessionToken == null)
            {
                throw new AuthenticationException("LoginResponse does not contain SessionToken");
            }
            else
            {
                _customHeaders[_sessionTokenHeader] = loginResponse.SessionToken;
            }

            var json = JsonConvert.SerializeObject(new JsonRequest {
                Method = _methodPrefix + methodName, Id = 1, Params = args
            },
                                                   new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            });

            var content = new StringContent(json, Encoding.UTF8, _requestContentType);

            foreach (var header in _customHeaders)
            {
                content.Headers.Add(header.Key, header.Value);
            }

            var timeoutPolicy  = _registry.Get <IAsyncPolicy>("thirtySecondTimeoutPolicy");
            var asyncGetPolicy = _registry.Get <IAsyncPolicy <HttpResponseMessage> >("thriceTriplingRetryPolicy");
            IAsyncPolicy <JsonResponse <T> > readStreamPolicy = Policy.HandleResult <JsonResponse <T> >(jr => jr.HasError)
                                                                .Or <TimeoutRejectedException>()
                                                                .WaitAndRetryAsync(_retryDelays);

            JsonResponse <T> response = await readStreamPolicy.ExecuteAsync(async() =>
            {
                HttpResponseMessage responseMessage = await asyncGetPolicy.ExecuteAsync(async() =>
                                                                                        await timeoutPolicy.ExecuteAsync(async token =>
                                                                                                                         await _httpClient.PostAsync("", content, token), CancellationToken.None));

                if (!responseMessage.IsSuccessStatusCode)
                {
                    throw new HttpResponseException(responseMessage);
                }
                string responseContent = await responseMessage.Content.ReadAsStringAsync();
                return(JsonConvert.DeserializeObject <JsonResponse <T> >(responseContent));
            });

            if (response.HasError)
            {
                throw ReconstituteException(response.Error);
            }
            else
            {
                return(response.Result);
            }
        }
Esempio n. 19
0
 public HomeController(IPolicyRegistry <string> myRegistry, HttpClient httpClient)
 {
     _httpClient  = httpClient;
     _cachePolicy = myRegistry.Get <CachePolicy <HttpResponseMessage> >("myPollyCache");
 }
Esempio n. 20
0
 private void CheckCircuit(Action send)
 {
     _policyRegistry.Get <Policy>(CIRCUITBREAKER).Execute(send);
 }
Esempio n. 21
0
 public CatalogController(IPolicyRegistry <string> myRegistry, HttpClient httpClient)
 {
     _httpClient  = httpClient;
     _cachePolicy = myRegistry.Get <CachePolicy <HttpResponseMessage> >("myLocalCachePolicy");
 }