public Downloader(HttpMessageHandler handler = null)
        {
            _client = handler == null ?
                      new HttpClient(new HttpClientHandler {
                AllowAutoRedirect = true
            }, disposeHandler: false) :
                      new HttpClient(handler, disposeHandler: false);

            _client.Timeout = TimeSpan.FromSeconds(5);

            _retryPolicy = Policy.Handle <HttpRequestException>()
                           .WaitAndRetryAsync(3, i => TimeSpan.FromMilliseconds(300)); // Retry 3 times, with 300 millisecond delay.
        }
Exemple #2
0
        public void Initialize(string connectionString, int retryTime, CancellationToken cancellationToken)
        {
            this.connectionString  = connectionString;
            this.cancellationToken = cancellationToken;

            retryPolicy = Policy
                          .Handle <Exception>()
                          .WaitAndRetryForeverAsync(
                onRetry: (exception, reconnection) => OnRetry(
                    exception: exception,
                    reconnection: reconnection),
                sleepDurationProvider: (p) => TimeSpan.FromSeconds(retryTime));
        }
Exemple #3
0
        public SubscriptionRepo(DataContext context, ILogger <SubscriptionRepo> logger)
        {
            _context = context;
            _logger  = logger;

            _retryPolicy = Policy.Handle <Microsoft.Data.Sqlite.SqliteException>()
                           .WaitAndRetryAsync(MaxRetries,
                                              times => TimeSpan.FromMilliseconds(times * 1000), // Waiting longer and longer after each retry.
                                              onRetry: (exception, _) =>
            {
                logger.LogWarning(exception.Message);     // logging exception messages.
            });
        }
Exemple #4
0
 /// <summary>
 /// Override the numberOfAttempts, the initialBackoffDelayInMillis, the retry predicate and the `Action` executed
 /// on every retry
 /// </summary>
 public On(
     int numberOfAttempts,
     int initialBackoffDelayInMillis,
     Func <System.Net.Http.HttpResponseMessage, Boolean> retryCondition,
     Action <DelegateResult <System.Net.Http.HttpResponseMessage>, TimeSpan> onRetry)
 {
     this._policy = Polly.Policy.HandleResult <HttpResponseMessage>(retryCondition)
                    .WaitAndRetryAsync(
         numberOfAttempts,
         attempt => TimeSpan.FromMilliseconds((initialBackoffDelayInMillis + r.Next(0, 100)) * Math.Pow(2, attempt)),
         (res, time) => onRetry(res, time)
         );
 }
Exemple #5
0
        public StartJobs(IBookmarkFinder bookmarkFinder, IWorkflowInstanceScheduler workflowScheduler, IDistributedLockProvider distributedLockProvider, ILogger <StartJobs> logger)
        {
            _bookmarkFinder          = bookmarkFinder;
            _workflowScheduler       = workflowScheduler;
            _distributedLockProvider = distributedLockProvider;
            _logger = logger;

            _retryPolicy = Policy
                           .Handle <Exception>()
                           .WaitAndRetryForeverAsync(retryAttempt =>
                                                     TimeSpan.FromSeconds(5)
                                                     );
        }
        public OrderEventHandler(Func <ConferenceContext> contextFactory)
        {
            this.contextFactory = contextFactory;
            var delay = Backoff.ConstantBackoff(TimeSpan.FromMilliseconds(200), retryCount: 5, fastFirst: true);

            this.retryPolicy = Policy
                               .Handle <Exception>()
                               .WaitAndRetryAsync(delay, (exception, i, span) =>
            {
                Trace.TraceWarning(
                    $"An error occurred in attempt number {i} to access the database in ConferenceService: {exception.Message}");
            });
        }
Exemple #7
0
 public Startup(IConfiguration configuration, ILoggerFactory loggerFactory)
 {
     _configuration = configuration;
     _logger        = loggerFactory.CreateLogger("Default");
     _syncPolicy    = Policy.Handle <Exception>()
                      .WaitAndRetryAsync(3,
                                         retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
                                         async(ex, timespan) =>
     {
         _logger.LogWarning("Sync:Retrying");
         await Task.Delay(timespan);
     });
 }
Exemple #8
0
        public GraphWrapper(ILogger <GraphWrapper> logger)
        {
            _logger = logger;

            _retryPolicy = Policy
                           .Handle <Exception>()
                           .WaitAndRetryAsync(2, retryAttempt =>
            {
                var timeToWait = TimeSpan.FromSeconds(Math.Pow(2, retryAttempt));
                return(timeToWait);
            }
                                              );
        }
Exemple #9
0
 protected MessageListener(IServiceProvider serviceProvider,
                           IAdvancedBus easyNetQBus,
                           IOptions <TBus> messageBus,
                           ILogger <MessageListener <TBus> > log)
 {
     ServiceProvider = serviceProvider;
     _easyNetQBus    = easyNetQBus;
     _messageBus     = messageBus;
     _log            = log;
     _retryPolicy    = Policy.Handle <Exception>(e => {
         log.LogError(e, "Failed to start message listener.");
         return(true);
     }).WaitAndRetryForeverAsync(_ => TimeSpan.FromSeconds(10));
 }
 /// <summary>
 /// Set retry policy to try up to 20 times, every 15 seconds.
 /// </summary>
 /// <param name="filesApi"></param>
 public WaitForVirusScan(IFilesApi filesApi)
 {
     _filesApi = filesApi;
     _policy   =
         Policy
         .Handle <ApiException>(e => e.ErrorCode == 423 /* Virus scan in progress */)
         .WaitAndRetryAsync(
             20,
             sleepDurationProvider: (retryNumber) =>
     {
         Console.WriteLine($"retrying {retryNumber}");
         return(TimeSpan.FromSeconds(15));
     });
 }
        /// <summary>
        /// Wait and Retry Policy Config
        /// Exponential Backoff strategy
        /// </summary>
        /// <param name="retryCount">Exponential backoff count</param>
        /// <param name="retryWaitTime">Wait time for exponential backoff in milliseconds</param>
        /// <returns></returns>
        public ArtesianPolicyConfig RetryPolicyConfig(int retryCount = RetryCountDefault, int retryWaitTime = RetryWaitTimeDefault)
        {
            _retryPolicy = Policy
                           .Handle <Exception>(x =>
            {
                var result = x.InnerException is HttpRequestException;
                return(result);
            })
                           .WaitAndRetryAsync(
                DecorrelatedJitterBackoff(TimeSpan.FromMilliseconds(retryWaitTime), TimeSpan.FromSeconds(10), retryCount, fastFirst: true)
                );

            return(this);
        }
Exemple #12
0
        private async Task RetryAssertUntilTelemetryShouldBeAvailableAsync(Func <Task> assertion, TimeSpan timeout)
        {
            AsyncRetryPolicy retryPolicy =
                Policy.Handle <Exception>(exception =>
            {
                _outputWriter.WriteLine("Failed to contact Azure Application Insights. Reason: {0}", exception.Message);
                return(true);
            })
                .WaitAndRetryForeverAsync(index => TimeSpan.FromSeconds(1));

            await Policy.TimeoutAsync(timeout)
            .WrapAsync(retryPolicy)
            .ExecuteAsync(assertion);
        }
Exemple #13
0
        protected ApiClientBase(HttpClient httpClient, ITokenService tokenService, ILogger <QnaApiClient> logger)
        {
            TokenService = tokenService;

            _logger = logger;

            HttpClient = httpClient;

            _retryPolicy = HttpPolicyExtensions
                           .HandleTransientHttpError()
                           .OrResult(msg => msg.StatusCode == System.Net.HttpStatusCode.NotFound)
                           .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2,
                                                                                               retryAttempt)));
        }
        public async Task <IActionResult> GetProduct(int productId)
        {
            var httpClient = new HttpClient();

            httpClient.BaseAddress = new Uri("https://localhost:44363/");

            AsyncRetryPolicy <HttpResponseMessage> retryPolicy = _registry.Get <AsyncRetryPolicy <HttpResponseMessage> >("WaitAndRetry");

            var response = await retryPolicy.ExecuteAsync(() => httpClient.GetAsync($"api/inventories/{productId}"));

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

            return(new OkObjectResult(result));
        }
Exemple #15
0
 public BazzasBazaarService(StoreClient storeClient, ILogger <BazzasBazaarService> logger)
 {
     _storeClient = storeClient;
     _logger      = logger;
     _retryPolicy = Policy
                    .Handle <Exception>()
                    .WaitAndRetryAsync(
         5,
         retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
         (exception, timeSpan, context) => {
         var methodThatRaisedException = context["methodName"];
         _logger.LogError("Exception in " + methodThatRaisedException + " " + exception + exception.StackTrace);
     });
 }
Exemple #16
0
        public GetDateTimeService(string url) : base(url)
        {
            _wcfClientService = new GetDateTimeServiceClient(_binding, _endpoint);

            _retryPolicy = Policy
                           .Handle <Exception>()
                           .WaitAndRetryAsync(5,
                                              retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
                                              (ex, timeSpan) =>
            {
                Console.WriteLine($"Erro: {ex.Message}");
                Console.WriteLine($"Retentativa em {timeSpan.Seconds} segundos");
            });
        }
        /// <summary>
        /// Constructor for SMS Service. Takes dependency injected services to
        /// send SMS notifications.
        /// </summary>
        /// <param name="smsSender">The <see cref="ISMSSender"/> implementation to use in this SMS Service</param>
        /// <param name="logger">The <see cref="ILogger"/> to be used in logging</param>
        /// <param name="dataService">The <see cref="IDataService"/> used for data access</param>
        /// <param name="settings">DI <see cref="SMSSettings"/> for the application.</param>
        public SMSService(ISMSSender smsSender, ILogger <SMSService> logger, IDataService dataService, IOptions <SMSSettings> settings)
        {
            _smsSender   = smsSender;
            _logger      = logger;
            _dataService = dataService;
            _smsSettings = settings.Value;
            var maxDelay = TimeSpan.FromSeconds(36);
            var delay    = Backoff.DecorrelatedJitterBackoffV2(medianFirstRetryDelay: TimeSpan.FromSeconds(1), retryCount: 50)
                           .Select(s => TimeSpan.FromTicks(Math.Min(s.Ticks, maxDelay.Ticks)));

            _retryPolicy = Policy
                           .Handle <Exception>()
                           .WaitAndRetryAsync(delay);
        }
Exemple #18
0
        public MeetingServiceRetryDecorator(IMeetingService meetingService)
        {
            var logger = LogManager.GetLogger(GetType());

            policy = Policy.Handle <Exception>().WaitAndRetryAsync(
                3,
                i => TimeSpan.FromSeconds(2),
                ((exception, span, retry, context) =>
            {
                logger.Warn($"Execution failed with exception {exception.Message}. Waiting {span} before next retry. Retry attempt {retry}");
            }));

            this.meetingService = meetingService;
        }
Exemple #19
0
        protected override void LoadJobParametersFromConfiguration(string configSectionKey)
        {
            base.LoadJobParametersFromConfiguration(configSectionKey);

            TaskDelayInMilliseconds = Parameters.IterationDelayInMilliseconds ?? WebJobsGlossary.DefaultIterationDelayInMilliseconds;
            MaxDegreeOfParallelism  = Parameters.ListMaxDegreeOfParallelism ?? WebJobsGlossary.DefaultListMaxDegreeOfParallelism;
            UseSemaphoreParallelism = Parameters.UseSemaphoreParallelism ?? false;

            _defaultRetryPolicyAsync = Policy
                                       .Handle <Exception>()
                                       .WaitAndRetryAsync(
                retryCount: WebJobsGlossary.DefaultListItemProcessingRetryCount,
                sleepDurationProvider: retryAttempt => TimeSpan.FromMilliseconds(WebJobsGlossary.DefaultListItemProcessingRetryDelayInMilliseconds));
        }
Exemple #20
0
        public void Initialize(string host, int port, int retryTime, string messageType)
        {
            this.host        = host;
            this.port        = port;
            this.messageType = messageType;

            retryPolicy = Policy
                          .Handle <Exception>()
                          .WaitAndRetryForeverAsync(
                sleepDurationProvider: (p) => TimeSpan.FromSeconds(retryTime),
                onRetry: (exception, reconnection) => OnRetry(
                    exception: exception,
                    reconnection: reconnection));
        }
Exemple #21
0
        public DeltaHub(IBroadcastManager broadcastManager,
                        IPeerSettings peerSettings,
                        IDfs dfs,
                        ILogger logger)
        {
            _broadcastManager = broadcastManager;
            _peerId           = peerSettings.PeerId;
            _dfs    = dfs;
            _logger = logger;

            DfsRetryPolicy = Polly.Policy <Cid> .Handle <Exception>()
                             .WaitAndRetryAsync(4, retryAttempt =>
                                                TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
        }
        protected TableStorageService(
            string tableName,
            string storageConnectionString,
            int maxAttempts         = 10,
            int waitAndRetrySeconds = 1,
            bool autoCreateTable    = false,
            TableRequestOptions tableRequestOptions = default)
        {
            _maxAttempts         = maxAttempts;
            _waitAndRetrySeconds = waitAndRetrySeconds;
            _autoCreateTable     = autoCreateTable;
            _retryPolicy         = (autoCreateTable) ?

                                   Policy.Handle <StorageException>(e => e.HandleStorageException())
                                   .WaitAndRetryAsync(maxAttempts,
                                                      i => TimeSpan.FromSeconds(_waitAndRetrySeconds),
                                                      async(a, t) => await CreateTableIfNotExistsAsync()) :

                                   Policy.Handle <StorageException>(e => e.HandleStorageException())
                                   .WaitAndRetryAsync(maxAttempts,
                                                      i => TimeSpan.FromSeconds(_waitAndRetrySeconds));

            StorageAccount = CloudStorageAccount.Parse(storageConnectionString);

            var tableServicePoint = ServicePointManager.FindServicePoint(StorageAccount.TableEndpoint);

            //few optimizations specifics for storage requests
            tableServicePoint.UseNagleAlgorithm = false;
            tableServicePoint.Expect100Continue = false;
            tableServicePoint.ConnectionLimit   = 100;

            // Create the table client.
            TableClient = StorageAccount.CreateCloudTableClient();
            Table       = TableClient.GetTableReference(tableName);

            TableName = tableName;

            //set default options if not provided
            TableRequestOptions = tableRequestOptions ?? new TableRequestOptions()
            {
                RetryPolicy = new LinearRetry(TimeSpan.FromSeconds(_waitAndRetrySeconds), _maxAttempts),
                // For Read-access geo-redundant storage, use PrimaryThenSecondary.
                // Otherwise set this to PrimaryOnly.
                LocationMode = LocationMode.PrimaryOnly

                               // Maximum execution time based on the business use case.
                               //MaximumExecutionTime = TimeSpan.FromSeconds(10) //not user yet ,if used , may raise timeout exceptions for huge requests
            };
            TableClient.DefaultRequestOptions = TableRequestOptions;
        }
        public OnPremUploadDownloadController(ITopicClient topic, CloudBlobContainer container, IHttpMessageFactory messageFactory, IConfiguration config)
        {
            this.topic          = topic ?? throw new ArgumentNullException(nameof(topic));
            this.container      = container ?? throw new ArgumentNullException(nameof(container));
            this.messageFactory = messageFactory ?? throw new ArgumentNullException(nameof(messageFactory));
            this.config         = config ?? throw new ArgumentNullException(nameof(config));

            // asyncronously handle transient exceptions by waiting 0.5 seconds, 2 seconds, 4 seconds, etc., before retrying, and finally throwing the exception
            policy = Policy.Handle <Exception>().WaitAndRetryAsync(3, i => TimeSpan.FromSeconds(0.5 * Math.Pow(2, i)));

            // syncronously handle transient file IO exceptions (excluding security exceptions) by waiting 0.5 seconds, 2 seconds, 4 seconds, etc., before retrying, and finally throwing the exception
            policyFile = Policy.Handle <Exception>(ex => !(ex is SecurityException || ex is UnauthorizedAccessException))
                         .WaitAndRetry(3, i => TimeSpan.FromSeconds(0.5 * Math.Pow(2, i)));
        }
Exemple #24
0
        //constructor injection
        public Cats(HttpClient httpClient, IOptions <ConfigSettings> config)
        {
            _httpClient = httpClient;
            _urls       = config.Value;

            //handle re-tries for http failures (can be pushed to start up at time of registeration)
            _httpRetryPolicy =
                Policy.HandleResult <HttpResponseMessage>(msg => msg.StatusCode == System.Net.HttpStatusCode.GatewayTimeout)
                .Or <TimeoutRejectedException>()
                .WaitAndRetryAsync(2, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));

            //set timeout policy
            _timeoutPolicy = Policy.TimeoutAsync(25);
        }
        /// <summary>
        /// Constructor for Email Service. Takes dependency injected services to
        /// send email notifications.
        /// </summary>
        /// <param name="emailSender">The <see cref="IEmailSender"/> implementation to use in this Email Service</param>
        /// <param name="logger">The <see cref="ILogger"/> to be used in logging</param>
        /// <param name="dataService">The <see cref="IDataService"/> used for data access</param>
        public EmailService(IEmailSender emailSender, ILogger <EmailService> logger, IDataService dataService)
        {
            _emailSender = emailSender;
            _logger      = logger;
            _dataService = dataService;

            var maxDelay = TimeSpan.FromSeconds(36);
            var delay    = Backoff.DecorrelatedJitterBackoffV2(medianFirstRetryDelay: TimeSpan.FromSeconds(1), retryCount: 50)
                           .Select(s => TimeSpan.FromTicks(Math.Min(s.Ticks, maxDelay.Ticks)));

            _retryPolicy = Policy
                           .Handle <Exception>()
                           .WaitAndRetryAsync(delay);
        }
Exemple #26
0
        public CancelExportRequestHandler(IFhirOperationDataStore fhirOperationDataStore, IAuthorizationService <DataActions> authorizationService, int retryCount, Func <int, TimeSpan> sleepDurationProvider, ILogger <CancelExportRequestHandler> logger)
        {
            EnsureArg.IsNotNull(fhirOperationDataStore, nameof(fhirOperationDataStore));
            EnsureArg.IsNotNull(authorizationService, nameof(authorizationService));
            EnsureArg.IsGte(retryCount, 0, nameof(retryCount));
            EnsureArg.IsNotNull(sleepDurationProvider, nameof(sleepDurationProvider));
            EnsureArg.IsNotNull(logger, nameof(logger));

            _fhirOperationDataStore = fhirOperationDataStore;
            _authorizationService   = authorizationService;
            _logger = logger;

            _retryPolicy = Policy.Handle <JobConflictException>()
                           .WaitAndRetryAsync(retryCount, sleepDurationProvider);
        }
Exemple #27
0
            public SessionMessageHandler(HttpMessageHandler innerHandler, AsyncLocal <SessionTokenContainer> asyncLocalSessionTokenContainer)
                : base(innerHandler)
            {
                _asyncLocalSessionTokenContainer = asyncLocalSessionTokenContainer;
                EnsureArg.IsNotNull(asyncLocalSessionTokenContainer, nameof(asyncLocalSessionTokenContainer));
                _polly = Policy.Handle <HttpRequestException>(x =>
                {
                    if (x.InnerException is IOException || x.InnerException is SocketException)
                    {
                        return(true);
                    }

                    return(false);
                }).WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
            }
Exemple #28
0
        public DurableSendingAgent(ISender sender, AdvancedSettings settings, ITransportLogger logger,
                                   IMessageLogger messageLogger,
                                   IEnvelopePersistence persistence, Endpoint endpoint) : base(logger, messageLogger, sender, settings, endpoint)
        {
            _logger = logger;

            _persistence = persistence;

            _policy = Policy
                      .Handle <Exception>()
                      .WaitAndRetryForeverAsync(i => (i * 100).Milliseconds()
                                                , (e, timeSpan) => {
                _logger.LogException(e, message: "Failed while trying to enqueue a message batch for retries");
            });
        }
Exemple #29
0
        public RetryPolicy(IConfiguration config, ILogger <RetryPolicy> logger)
        {
            _config = config;
            _logger = logger;

            //TODO: change so the policy config is injected to allow more use cases
            _retryPolicyAsync = Policy.Handle <Exception>()
                                .WaitAndRetryAsync(
                retryCount: int.Parse(_config["retryAmount"]),
                sleepDurationProvider: attempt => TimeSpan.FromMilliseconds(int.Parse(_config["retryPause"])),
                onRetry: (response, delay, retryCount, context) => {
                _logger.LogWarning($"Connection Failure - Attempt: {retryCount}, Due to - Message: {response.Message}");
            }
                );
        }
Exemple #30
0
 /// <summary>
 /// Creates a new instance of a LtsaService, initializes with specified arguments.
 /// </summary>
 /// <param name="options"></param>
 /// <param name="client"></param>
 /// <param name="tokenHandler"></param>
 /// <param name="logger"></param>
 /// <param name="serializerOptions"></param>
 public LtsaService(IOptions <LtsaOptions> options, IHttpRequestClient client, ILogger <ILtsaService> logger, IOptions <JsonSerializerOptions> serializerOptions)
 {
     this.Options           = options.Value;
     this.Client            = client;
     _logger                = logger;
     _jsonSerializerOptions = serializerOptions.Value;
     _authPolicy            = Policy
                              .Handle <HttpClientRequestException>(ex => ex.StatusCode == HttpStatusCode.Forbidden || ex.StatusCode == HttpStatusCode.Unauthorized)
                              .RetryAsync(async(exception, retryCount) =>
     {
         _token = await RefreshAccessTokenAsync();
         this.Client.Client?.DefaultRequestHeaders?.Clear();
         this.Client.Client?.DefaultRequestHeaders?.Add("X-Authorization", $"Bearer {_token.AccessToken}");
     });
 }