public static Task OpenAsyncWithRetry(
                                       this SqlConnection connection,
                                       CancellationToken cancellationToken,
                                       IRetryPolicy retryPolicy)
 {
     return retryPolicy.ExecuteAsyncWithRetry(() => connection.OpenAsync(cancellationToken));
 }
Пример #2
0
 public static Task<SqlDataReader> ExecuteReaderAsyncWithRetry(
                                                               SqlCommand command,
                                                               CancellationToken cancellationToken,
                                                               IRetryPolicy retryPolicy)
 {
     return retryPolicy.ExecuteAsyncWithRetry(() => command.ExecuteReaderAsync(cancellationToken));
 }
Пример #3
0
        static AzureTableDefaultPolicies()
        {
            MaxTableCreationRetries = 60;
            PauseBetweenTableCreationRetries = TimeSpan.FromSeconds(1);

            MaxTableOperationRetries = 5;
            PauseBetweenTableOperationRetries = TimeSpan.FromMilliseconds(100);

            MaxBusyRetries = 120;
            PauseBetweenBusyRetries = TimeSpan.FromMilliseconds(500);
#if DEBUG
            if (Debugger.IsAttached)
            {
                PauseBetweenTableCreationRetries = PauseBetweenTableCreationRetries.Multiply(100);
                PauseBetweenTableOperationRetries = PauseBetweenTableOperationRetries.Multiply(100);
                PauseBetweenBusyRetries = PauseBetweenBusyRetries.Multiply(10);
            }
#endif
            TableCreationRetryPolicy = new LinearRetry(PauseBetweenTableCreationRetries, MaxTableCreationRetries); // 60 x 1s
            TableCreationTimeout = PauseBetweenTableCreationRetries.Multiply(MaxTableCreationRetries).Multiply(3);    // 3 min

            TableOperationRetryPolicy = new LinearRetry(PauseBetweenTableOperationRetries, MaxTableOperationRetries); // 5 x 100ms
            TableOperationTimeout = PauseBetweenTableOperationRetries.Multiply(MaxTableOperationRetries).Multiply(6);    // 3 sec

            BusyRetriesTimeout = PauseBetweenBusyRetries.Multiply(MaxBusyRetries);  // 1 minute
        }
Пример #4
0
        /// <summary>
        /// Initialize a <see cref="HaConnection"/> with a list of <see cref="ManagedConnectionFactory"/>
        /// These connection factories are responsibile for creating <see cref="IConnection"/> to nodes in the clusters
        /// </summary>
        /// <param name="retryPolicy"></param>
        /// <param name="watcher"></param>
        /// <param name="connectionFactories"></param>
        public HaConnection(IRetryPolicy retryPolicy, IRabbitWatcher watcher, IList<ManagedConnectionFactory> connectionFactories) : base(retryPolicy, watcher)
        {        
            _connectionFactories = new RoundRobinList<ConnectionFactory>(connectionFactories);
            ConnectionEstablished handler = (endpoint, virtualHost) =>
            {
                if (_connectionFactories.All.Any(f => f.Endpoint + f.VirtualHost == endpoint + virtualHost))
                {
                    if (!IsConnected)
                    {
                        while (_connectionFactories.Current.Endpoint + _connectionFactories.Current.VirtualHost != endpoint + virtualHost)
                        {
                            //IF there are 2 different Tunnels using 2 HaConnection with 2 lists of cluster nodes in different orders:
                            //Example:

                            // ConnectionString1: host=q1;username=guest;password=guest|host=q2;username=guest;password=guest|host=q3;username=guest;password=guest
                            // ConnectionString2: host=q2;username=guest;password=guest|host=q3;username=guest;password=guest|host=q1;username=guest;password=guest

                            // When the first tunnel established the connection successfully to q1, it fires event and these lines of code is triggered.
                            // The 2nd HaConnection needs to set it's _connectionFactories.Current to q1 established by other tunnel. Before changing, _connectionFactories.Current is q3 by the order in the ConnectionString2 
                            _connectionFactories.GetNext();
                        }
                    }

                    FireConnectedEvent();
                }
            };
            ManagedConnectionFactory.ConnectionEstablished += handler;
            _unsubscribeEvents = () => { ManagedConnectionFactory.ConnectionEstablished -= handler; };
        }
        public HttpRestClientConfiguration(HttpMessageHandler defaultHttpClientHandler = null,
            IEnumerable<DelegatingHandler> messageProcessingHandlers = null,
            IRetryPolicy retryPolicy = null, 
            TimeSpan? httpRequestTimeout = null)
        {
            this._httpRequestTimeout = httpRequestTimeout ?? TimeSpan.FromMinutes(1);
            this.HttpMessageHandler = defaultHttpClientHandler ?? new HttpClientHandler();
            if (messageProcessingHandlers == null)
            {
                this._additionalDelegatingHandlers = new ReadOnlyCollection<DelegatingHandler>(new List<DelegatingHandler>());
            }
            else
            {
                this._additionalDelegatingHandlers = new ReadOnlyCollection<DelegatingHandler>(messageProcessingHandlers.ToList());
            }

            this.RetryPolicy = retryPolicy ?? new NoRetryPolicy();

            //Here we chain the delegating handlers such that each delegating handler has the next one as its inner handler
            for (int i = this.DelegatingHandlers.Count - 1; i >= 0; i--)
            {
                if (i - 1 >= 0)
                {
                    this.DelegatingHandlers[i - 1].InnerHandler = this.DelegatingHandlers[i];
                }
            }

            //the first delegating handler has the default defaultHttpClientHandler as its inner handler
            if (this.DelegatingHandlers.Any())
            {
                this.DelegatingHandlers.Last().InnerHandler = this.HttpMessageHandler;
            }

        }
 public Task UploadBlob(
     Uri url,
     string localFile,
     FileEncryption fileEncryption,
     CancellationToken cancellationToken,
     CloudBlobClient client,
     IRetryPolicy retryPolicy,
     string contentType = null,
     string subDirectory = "",
     Func<string> getSharedAccessSignature = null,
     int parallelTransferThreadCount = 10,
     int numberOfConcurrentTransfers = default(int))
 {
     SetConnectionLimits(url, numberOfConcurrentTransfers);
     return Task.Factory.StartNew(
         () => UploadFileToBlob(
             cancellationToken,
             url,
             localFile,
             contentType,
             subDirectory,
             fileEncryption,
             client,
             retryPolicy,
             getSharedAccessSignature,
             parallelTransferThreadCount),
             cancellationToken);
 }
        public static void Execute(Action method, IRetryPolicy retryPolicy, IBackOffScheme backOffScheme, int numRetries = Constants.LoadBalancingHelperNumRetriesDefault)
        {
            int retryCount = 0;
            bool requestSuccess = false;
            while ((!requestSuccess) && (retryCount < numRetries))
            {
                try
                {
                    method();
                    requestSuccess = true;
                }
                catch (Exception ex)
                {
                    Trace.TraceError("\tAttempt {0} failed with exception {1} - {2}", retryCount, ex.GetType(), ex.Message);

                    retryCount++;
                    if ((retryCount < numRetries) && (retryPolicy.ShouldRetryAttempt(ex)))
                    {
                        var sleepInterval = backOffScheme.GetRetryInterval(retryCount);
                        if (sleepInterval != default (TimeSpan))
                        {
                            Trace.TraceInformation("\tWill retry after {0} milliseconds......", sleepInterval.TotalMilliseconds);
                            Thread.Sleep(sleepInterval);
                        }
                    }
                    else
                    {
                        throw;
                    }
                }
            }
        }
Пример #8
0
 static AzureQueueDefaultPolicies()
 {
     MaxQueueOperationRetries = 5;
     PauseBetweenQueueOperationRetries = TimeSpan.FromMilliseconds(100);
     QueueOperationRetryPolicy = new LinearRetry(PauseBetweenQueueOperationRetries, MaxQueueOperationRetries); // 5 x 100ms
     QueueOperationTimeout = PauseBetweenQueueOperationRetries.Multiply(MaxQueueOperationRetries).Multiply(6);    // 3 sec
 }
Пример #9
0
 public static Task<int> ExecuteNonQueryAsyncWithRetry(
                                                       SqlCommand command,
                                                       CancellationToken cancellationToken,
                                                       IRetryPolicy retryPolicy)
 {
     return retryPolicy.ExecuteAsyncWithRetry(() => command.ExecuteNonQueryAsync(cancellationToken));
 }
 public Task UploadBlob(
     Uri url,
     string localFile,
     FileEncryption fileEncryption,
     CancellationToken cancellationToken,
     CloudBlobClient client,
     IRetryPolicy retryPolicy,
     string contentType = null,
     string subDirectory = "",
     Func<string> getSharedAccessSignature = null)
 {
     SetConnectionLimits(url);
     return Task.Factory.StartNew(
         () => UploadFileToBlob(
             cancellationToken,
             url,
             localFile,
             contentType,
             subDirectory,
             fileEncryption,
             client,
             retryPolicy,
             getSharedAccessSignature),
         cancellationToken);
 }
        public Task DownloadBlob(
            Uri uri,
            string localFile,
            FileEncryption fileEncryption,
            ulong initializationVector,
            CloudBlobClient client,
            CancellationToken cancellationToken,
            IRetryPolicy retryPolicy,
            Func<string> getSharedAccessSignature = null,
            long start = 0,
            long length = -1,
            int parallelTransferThreadCount = 10,
            int numberOfConcurrentTransfers = 2)
        {
            if (client != null && getSharedAccessSignature != null)
            {
                throw new InvalidOperationException("The arguments client and getSharedAccessSignature cannot both be non-null");
            }

            SetConnectionLimits(uri, Environment.ProcessorCount * numberOfConcurrentTransfers * parallelTransferThreadCount);

            Task task =
                Task.Factory.StartNew(
                    () =>
                        DownloadFileFromBlob(uri, localFile, fileEncryption, initializationVector, client,
                            cancellationToken, retryPolicy, getSharedAccessSignature, start: start, length: length,
                            parallelTransferThreadCount: parallelTransferThreadCount));
            return task;
        }
Пример #12
0
 public static Task<SqlDataReader> ExecuteReaderAsyncWithRetry(
                                                               SqlCommand command,
                                                               CommandBehavior behavior,
                                                               IRetryPolicy retryPolicy)
 {
     return retryPolicy.ExecuteAsyncWithRetry(() => command.ExecuteReaderAsync(behavior));
 }
Пример #13
0
        public EventStreamProducer(IEventStreamWriter streamWriter, IRetryPolicy retryPolicy)
        {
            Require.NotNull(streamWriter, "streamWriter");
            Require.NotNull(retryPolicy, "retryPolicy");

            m_streamWriter = streamWriter;
            m_retryPolicy = retryPolicy;
        }
Пример #14
0
 /// <summary>
 ///  Creates a new <code>Policies</code> object using the provided policies.
 /// </summary>
 /// <param name="loadBalancingPolicy"> the load balancing policy to use. </param>
 /// <param name="reconnectionPolicy"> the reconnection policy to use. </param>
 /// <param name="retryPolicy"> the retry policy to use.</param>
 public Policies(ILoadBalancingPolicy loadBalancingPolicy,
                 IReconnectionPolicy reconnectionPolicy,
                 IRetryPolicy retryPolicy)
 {
     this._loadBalancingPolicy = loadBalancingPolicy;
     this._reconnectionPolicy = reconnectionPolicy;
     this._retryPolicy = retryPolicy;
 }
Пример #15
0
        public BatchService(BatchSharedKeyCredential credentials)
        {
            this.Client = BatchClient.Open(credentials);
            this.Credentials = credentials;
            this.retryPolicy = new LinearRetry(TimeSpan.FromSeconds(10), 5);

            this.Client.CustomBehaviors.Add(new RetryPolicyProvider(this.retryPolicy));
        }
        public HttpRestClientRetryPolicy(IRetryPolicy retryPolicy)
        {
            if (retryPolicy == null)
            {
                throw new ArgumentNullException("retryPolicy");
            }

            this.retryPolicy = retryPolicy;
        }
 /// <summary>
 /// Initializes a new instance of the AbstractionContext class.
 /// </summary>
 /// <param name="tokenSource">A Cancellation token source.</param>
 /// <param name="logger">A logger instance.</param>
 /// <param name="httpOperationTimeout">The HTTP operation timeout.</param>
 /// <param name="retryPolicy">The retry policy.</param>
 public AbstractionContext(CancellationTokenSource tokenSource, ILogger logger, TimeSpan httpOperationTimeout, IRetryPolicy retryPolicy)
 {
     this.RetryPolicy = retryPolicy;
     tokenSource.ArgumentNotNull("tokenSource");
     logger.ArgumentNotNull("logger");
     this.CancellationTokenSource = tokenSource;
     this.Logger = logger;
     this.HttpOperationTimeout = httpOperationTimeout;
 }
 public BatchService(string baseUrl, BatchCredentials credentials)
 {
     this.Client = BatchClient.Connect(baseUrl, credentials);
     this.BaseUri = new Uri(baseUrl);
     this.Credentials = credentials;
     this.retryPolicy = new LinearRetry(TimeSpan.FromSeconds(10), 5);
     
     this.Client.CustomBehaviors.Add(new SetRetryPolicy(this.retryPolicy));
     this.Client.CustomBehaviors.Add(new RequestInterceptor((req) => { req.MaximumExecutionTime = TimeSpan.FromMinutes(2); }));
 }
        public ServiceBusReceiveTransport(IServiceBusHost host, ReceiveSettings settings, params TopicSubscriptionSettings[] subscriptionSettings)
        {
            _host = host;
            _settings = settings;
            _subscriptionSettings = subscriptionSettings;
            _receiveObservers = new ReceiveObservable();
            _endpointObservers = new ReceiveEndpointObservable();

            _connectionRetryPolicy = Retry.Exponential(1000, TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(1));
        }
Пример #20
0
        public RabbitMqHost(RabbitMqHostSettings hostSettings)
        {
            _hostSettings = hostSettings;

            var exceptionFilter = Retry.Selected<RabbitMqConnectionException>();

            _connectionRetryPolicy = exceptionFilter.Exponential(1000, TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(1));

            _supervisor = new TaskSupervisor($"{TypeMetadataCache<RabbitMqHost>.ShortName} - {_hostSettings.ToDebugString()}");

            _connectionCache = new RabbitMqConnectionCache(hostSettings, _supervisor);
        }
        public ElasticRequestProcessor(IElasticConnection connection, IElasticMapping mapping, ILog log, IRetryPolicy retryPolicy)
        {
            Argument.EnsureNotNull("connection", connection);
            Argument.EnsureNotNull("mapping", mapping);
            Argument.EnsureNotNull("log", log);
            Argument.EnsureNotNull("retryPolicy", retryPolicy);

            this.connection = connection;
            this.mapping = mapping;
            this.log = log;
            this.retryPolicy = retryPolicy;
        }
Пример #22
0
 internal DurableConnection(IRetryPolicy retryPolicy, IRabbitWatcher watcher)
 {
     if (retryPolicy == null)
     {
         throw new ArgumentNullException(nameof(retryPolicy));
     }
     if (watcher == null)
     {
         throw new ArgumentNullException(nameof(watcher));
     }
     _retryPolicy = retryPolicy;
     _watcher = watcher;
 }
Пример #23
0
 /**
  *
  * @param connectString list of servers to connect to
  * @param sessionTimeoutMs session timeout
  * @param connectionTimeoutMs connection timeout
  * @param watcher default watcher or null
  * @param retryPolicy the retry policy to use
  */
 public CuratorZookeeperClient(String connectString, 
                                 int sessionTimeoutMs, 
                                 int connectionTimeoutMs, 
                                 Watcher watcher, 
                                 IRetryPolicy retryPolicy)
     : this(new DefaultZookeeperFactory(),
             new FixedEnsembleProvider(connectString),
             sessionTimeoutMs,
             connectionTimeoutMs,
             watcher,
             retryPolicy,
             false)
 {
 }
Пример #24
0
 /**
  * @param ensembleProvider the ensemble provider
  * @param sessionTimeoutMs session timeout
  * @param connectionTimeoutMs connection timeout
  * @param watcher default watcher or null
  * @param retryPolicy the retry policy to use
  */
 public CuratorZookeeperClient(IEnsembleProvider ensembleProvider, 
                                 int sessionTimeoutMs, 
                                 int connectionTimeoutMs, 
                                 Watcher watcher, 
                                 IRetryPolicy retryPolicy)
     : this(new DefaultZookeeperFactory(),
             ensembleProvider,
             sessionTimeoutMs,
             connectionTimeoutMs,
             watcher,
             retryPolicy,
             false)
 {
 }
Пример #25
0
		/**
     * @param zookeeperFactory factory for creating {@link ZooKeeper} instances
     * @param ensembleProvider the ensemble provider
     * @param sessionTimeoutMs session timeout
     * @param connectionTimeoutMs connection timeout
     * @param watcher default watcher or null
     * @param retryPolicy the retry policy to use
     * @param canBeReadOnly if true, allow ZooKeeper client to enter
     *                      read only mode in case of a network partition. See
     *                      {@link ZooKeeper#ZooKeeper(String, int, Watcher, long, byte[], bool)}
     *                      for details
     */
		public CuratorZookeeperClient(IZookeeperFactory zookeeperFactory, IEnsembleProvider ensembleProvider, int sessionTimeoutMs, int connectionTimeoutMs, IWatcher watcher, IRetryPolicy retryPolicy, bool canBeReadOnly)
		{
			if ( sessionTimeoutMs < connectionTimeoutMs )
			{
				log.Warn(String.Format("session timeout [{0}] is less than connection timeout [{1}]", sessionTimeoutMs, connectionTimeoutMs));
			}


//			retryPolicy = Preconditions.checkNotNull(retryPolicy, "retryPolicy cannot be null");
//			ensembleProvider = Preconditions.checkNotNull(ensembleProvider, "ensembleProvider cannot be null");

			this.connectionTimeoutMs = connectionTimeoutMs;
			state = new ConnectionState(zookeeperFactory, ensembleProvider, TimeSpan.FromMilliseconds(sessionTimeoutMs), TimeSpan.FromMilliseconds(connectionTimeoutMs), watcher, tracer, canBeReadOnly);
			SetRetryPolicy(retryPolicy);
		}
        public RabbitMqReceiveTransport(IRabbitMqHost host, ReceiveSettings settings, Mediator<ISetPrefetchCount> mediator,
            params ExchangeBindingSettings[] bindings)
        {
            _host = host;
            _settings = settings;
            _bindings = bindings;
            _mediator = mediator;

            _receiveObservable = new ReceiveObservable();
            _receiveEndpointObservable = new ReceiveEndpointObservable();

            var exceptionFilter = Retry.Selected<RabbitMqConnectionException>();

            _connectionRetryPolicy = exceptionFilter.Exponential(1000, TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(1));
        }
        private static async Task TestSqlRetryPolicy(IRetryPolicy retryPolicy, int interval)
        {
            var retryCount = 0;
            retryPolicy.Retry += (sender, args) =>
            {
                retryCount++;

                // Assert
                Assert.Equal(typeof(TimeoutException), args.Exception.GetType());
                Assert.Equal(retryCount, args.RetryCount);
                Assert.Equal(retryCount * interval, args.Delay.TotalMilliseconds);
            };

            var taskFunction = TaskFunctionTestFactory.GetTaskFunctionTResultWithRetry();

            // Act
            await retryPolicy.ExecuteAsyncWithRetry(taskFunction);
        }
Пример #28
0
        public DurableConnection(IRetryPolicy retryPolicy, IRabbitWatcher watcher, ConnectionFactory connectionFactory)
        {
            if (retryPolicy == null)
            {
                throw new ArgumentNullException("retryPolicy");
            }
            if (watcher == null)
            {
                throw new ArgumentNullException("watcher");
            }
            if (connectionFactory == null)
            {
                throw new ArgumentNullException("connectionFactory");
            }

            _retryPolicy = retryPolicy;
            _watcher = watcher;
            ConnectionFactory = connectionFactory;
        }
Пример #29
0
        /// <summary>
        /// Initialize a <see cref="DurableConnection"/> object
        /// </summary>
        /// <param name="retryPolicy"></param>
        /// <param name="watcher"></param>
        /// <param name="connectionFactory"></param>
        public DurableConnection(IRetryPolicy retryPolicy, IRabbitWatcher watcher, ConnectionFactory connectionFactory)
            : this(retryPolicy, watcher)
        {
            if (connectionFactory == null)
            {
                throw new ArgumentNullException(nameof(connectionFactory));
            }

            
            _connectionFactory = ManagedConnectionFactory.CreateFromConnectionFactory(connectionFactory);
            ConnectionEstablished handler = (endpoint, virtualHost) =>
            {
                if (_connectionFactory.Endpoint + _connectionFactory.VirtualHost == endpoint + virtualHost)
                {
                    //NOTE: Fire connected event whenever a new connection to 1 of the servers in the cluster is made
                    FireConnectedEvent();
                }
            };
            ManagedConnectionFactory.ConnectionEstablished += handler;
            _unsubscribeEvents = () => { ManagedConnectionFactory.ConnectionEstablished -= handler; };
        }
        public Task DownloadBlob(
            Uri uri, 
            string localFile, 
            FileEncryption fileEncryption, 
            ulong initializationVector, 
            CloudBlobClient client, 
            CancellationToken cancellationToken, 
            IRetryPolicy retryPolicy, 
            Func<string> getSharedAccessSignature = null,
            long start = 0,
            long length = -1)
        {
            if (client != null && getSharedAccessSignature != null)
            {
                throw new InvalidOperationException("The arguments client and getSharedAccessSignature cannot both be non-null");
            }

            SetConnectionLimits(uri);

            Task task = Task.Factory.StartNew(() => DownloadFileFromBlob(uri, localFile, fileEncryption, initializationVector, client, cancellationToken, retryPolicy, getSharedAccessSignature, start:start, length:length));
            return task;
        }
 public static RetryPolicyDecorator For(IRetryPolicy retryPolicy, Action <int> doBefore)
 => new RetryPolicyDecorator(retryPolicy, doBefore);
Пример #32
0
 public ManagedConnection(IConnectionFactory factory, IRetryPolicy retryPolicy) : this(factory, CommandRunnerMode.AutoCommit, retryPolicy)
 {
 }
 public RequestRetryModule(IRetryPolicy retryPolicy, IRetryStrategy retryStrategy)
 {
     this.retryPolicy   = retryPolicy;
     this.retryStrategy = retryStrategy;
 }
Пример #34
0
        private static IManagedConnection buildManagedConnection(SessionOptions options, ITenant tenant,
                                                                 CommandRunnerMode commandRunnerMode, IRetryPolicy retryPolicy)
        {
            // TODO -- this is all spaghetti code. Make this some kind of more intelligent state machine
            // w/ the logic encapsulated into SessionOptions

            // Hate crap like this, but if we don't control the transation, use External to direct
            // IManagedConnection not to call commit or rollback
            if (!options.OwnsTransactionLifecycle && commandRunnerMode != CommandRunnerMode.ReadOnly)
            {
                commandRunnerMode = CommandRunnerMode.External;
            }

            if (options.Connection != null || options.Transaction != null)
            {
                options.OwnsConnection = false;
            }

            if (options.Transaction != null)
            {
                options.Connection = options.Transaction.Connection;
            }

            if (options.Connection == null && options.DotNetTransaction != null)
            {
                var connection = tenant.CreateConnection();
                connection.Open();

                options.OwnsConnection = true;
                options.Connection     = connection;
            }

            if (options.DotNetTransaction != null)
            {
                options.Connection.EnlistTransaction(options.DotNetTransaction);
                options.OwnsTransactionLifecycle = false;
            }

            if (options.Connection == null)
            {
                return(tenant.OpenConnection(commandRunnerMode, options.IsolationLevel, options.Timeout));
            }
            return(new ManagedConnection(options, commandRunnerMode, retryPolicy));
        }
Пример #35
0
 public void AddRetryPolicy(string policyKey, IRetryPolicy retryPolicy)
 {
     Contract.Requires(policyKey != null);
     Contract.Requires(retryPolicy != null);
 }
Пример #36
0
 public RetryFilter(IRetryPolicy retryPolicy, RetryObservable observers)
 {
     _retryPolicy = retryPolicy;
     _observers   = observers;
 }
Пример #37
0
 /// <summary>
 /// Start a new retriable task for an action.
 /// </summary>
 /// <param name="action">The action for which to start a retriable tasks.</param>
 /// <param name="cancellationToken">The token with which cancellation is signalled.</param>
 /// <param name="taskCreationOptions">The task creation options.</param>
 /// <param name="scheduler">The task scheduler.</param>
 /// <param name="strategy">The retry strategy.</param>
 /// <param name="policy">The retry policy.</param>
 /// <returns>A task which completes when the action is complete.</returns>
 public Task StartNew(Action action, CancellationToken cancellationToken, TaskCreationOptions taskCreationOptions, TaskScheduler scheduler, IRetryStrategy strategy, IRetryPolicy policy)
 {
     return(Task.Factory.StartNew(action, cancellationToken, taskCreationOptions, scheduler).ContinueWith(t => HandleTask(t, () => new Task(action, cancellationToken, taskCreationOptions), strategy, policy)));
 }
Пример #38
0
 /// <summary>
 /// Start a new retriable task for an action.
 /// </summary>
 /// <param name="action">The action for which to start a retriable tasks.</param>
 /// <param name="state">The state to pass to the task on creation.</param>
 /// <param name="cancellationToken">The token with which cancellation is signalled.</param>
 /// <param name="strategy">The retry strategy.</param>
 /// <param name="policy">The retry policy.</param>
 /// <returns>A task which completes when the action is complete.</returns>
 public Task StartNew(Action <object> action, object state, CancellationToken cancellationToken, IRetryStrategy strategy, IRetryPolicy policy)
 {
     return(Task.Factory.StartNew(action, state, cancellationToken).ContinueWith(t => HandleTask(t, () => new Task(action, state, cancellationToken), strategy, policy)));
 }
Пример #39
0
 /// <summary>
 /// Start a new retriable task for an action.
 /// </summary>
 /// <param name="action">The action for which to start a retriable tasks.</param>
 /// <param name="state">The state to pass to the task on creation.</param>
 /// <param name="taskCreationOptions">The task creation options.</param>
 /// <param name="strategy">The retry strategy.</param>
 /// <param name="policy">The retry policy.</param>
 /// <returns>A task which completes when the action is complete.</returns>
 public Task StartNew(Action <object> action, object state, TaskCreationOptions taskCreationOptions, IRetryStrategy strategy, IRetryPolicy policy)
 {
     return(Task.Factory.StartNew(action, state, taskCreationOptions).ContinueWith(t => HandleTask(t, () => new Task(action, state, taskCreationOptions), strategy, policy)));
 }
Пример #40
0
 /// <summary>
 /// Start a new retriable task for an action.
 /// </summary>
 /// <param name="action">The action for which to start a retriable tasks.</param>
 /// <param name="strategy">The retry strategy.</param>
 /// <param name="policy">The retry policy.</param>
 /// <returns>A task which completes when the action is complete.</returns>
 public Task StartNew(Action action, IRetryStrategy strategy, IRetryPolicy policy)
 {
     return(Task.Factory.StartNew(action).ContinueWith(t => HandleTask(t, () => new Task(action), strategy, policy)));
 }
Пример #41
0
 /// <summary>
 /// Start a new retriable task for an action.
 /// </summary>
 /// <param name="action">The action for which to start a retriable tasks.</param>
 /// <param name="policy">The retry policy.</param>
 /// <returns>A task which completes when the action is complete.</returns>
 public Task StartNew(Action action, IRetryPolicy policy)
 {
     return(this.StartNew(action, new Count(), policy));
 }
Пример #42
0
 /// <summary>
 /// Start a new retriable task for an action.
 /// </summary>
 /// <param name="action">The action for which to start a retriable tasks.</param>
 /// <param name="state">The state to pass to the task on creation.</param>
 /// <param name="taskCreationOptions">The task creation options.</param>
 /// <param name="policy">The retry policy.</param>
 /// <returns>A task which completes when the action is complete.</returns>
 public Task StartNew(Action <object> action, object state, TaskCreationOptions taskCreationOptions, IRetryPolicy policy)
 {
     return(this.StartNew(action, state, taskCreationOptions, new Count(), policy));
 }
Пример #43
0
 /// <summary>
 /// Start a new retriable task for an action.
 /// </summary>
 /// <param name="action">The action for which to start a retriable tasks.</param>
 /// <param name="taskCreationOptions">The task creation options.</param>
 /// <param name="policy">The retry policy.</param>
 /// <returns>A task which completes when the action is complete.</returns>
 public Task StartNew(Action action, TaskCreationOptions taskCreationOptions, IRetryPolicy policy)
 {
     return(this.StartNew(action, taskCreationOptions, new Count(), policy));
 }
Пример #44
0
        /// <summary>
        /// Handles retrying a given task.
        /// </summary>
        /// <param name="task">The task that is currently executing.</param>
        /// <param name="createTask">A function that can create a new task to retry the operation.</param>
        /// <param name="strategy">The retry strategy.</param>
        /// <param name="policy">The retry policy.</param>
        /// <returns>A new task which is retrying the existing task, or the original task if retry is not required.</returns>
        /// <remarks>
        /// <para>
        /// If the task completed successfully, then retry is not required and the original task is returned.
        /// </para>
        /// <para>
        /// It the task failed, then this method uses the strategy to determine whether it will retry based on the exception on the original task.
        /// If it will retry, it raises the <see cref="IRetryStrategy.Retrying"/> event, then delays for the calculated time using the Sleep service.
        /// It then creates a new task using the <c>createTask</c> function provided, and runs the task synchronously.
        /// </para>
        /// </remarks>
        internal static Task HandleRetry(Task task, Func <Task> createTask, IRetryStrategy strategy, IRetryPolicy policy)
        {
            while (task.Exception != null)
            {
                TimeSpan delay = strategy.PrepareToRetry(task.Exception);

                if (!WillRetry(task, strategy, policy))
                {
                    break;
                }

                strategy.OnRetrying(new RetryEventArgs(task.Exception, delay));

                if (delay != TimeSpan.Zero)
                {
                    SleepService?.Sleep(delay);
                }

                task = createTask();
                task.RunSynchronously();
            }

            return(task);
        }
Пример #45
0
 /// <summary>
 ///  Configure the retry policy to use for the new cluster. <p> If no retry policy
 ///  is set through this method, <link>Policies.DefaultRetryPolicy</link> will
 ///  be used instead.</p>
 /// </summary>
 /// <param name="policy"> the retry policy to use </param>
 ///
 /// <returns>this Builder</returns>
 public Builder WithRetryPolicy(IRetryPolicy policy)
 {
     _retryPolicy = policy;
     return(this);
 }
Пример #46
0
 private static bool WillRetry(Task task, IRetryStrategy strategy, IRetryPolicy policy)
 {
     return(strategy.CanRetry && !task.IsCanceled && task.Exception.Flatten().InnerExceptions.All(policy.CanRetry));
 }
Пример #47
0
        private static void HandleTask(Task task, Func <Task> createTask, IRetryStrategy strategy, IRetryPolicy policy)
        {
            task = HandleRetry(task, createTask, strategy, policy);

            HandleException(task, strategy);
        }
Пример #48
0
        private static HubConnection CreateHubConnection(TestConnection connection, IHubProtocol protocol = null, ILoggerFactory loggerFactory = null, IRetryPolicy reconnectPolicy = null)
        {
            var builder = new HubConnectionBuilder();

            var delegateConnectionFactory = new DelegateConnectionFactory(
                connection.StartAsync,
                c => ((TestConnection)c).DisposeAsync());

            builder.Services.AddSingleton <IConnectionFactory>(delegateConnectionFactory);

            if (loggerFactory != null)
            {
                builder.WithLoggerFactory(loggerFactory);
            }

            if (protocol != null)
            {
                builder.Services.AddSingleton(protocol);
            }

            if (reconnectPolicy != null)
            {
                builder.WithAutomaticReconnect(reconnectPolicy);
            }

            return(builder.Build());
        }
Пример #49
0
 protected BaseRetryPolicyContext(IRetryPolicy policy, TContext context)
 {
     _policy = policy;
     Context = context;
 }
Пример #50
0
 /// <summary>
 /// Creates a new <c>Policies</c> object using the provided policies.
 /// </summary>
 /// <param name="loadBalancingPolicy"> the load balancing policy to use. </param>
 /// <param name="reconnectionPolicy"> the reconnection policy to use. </param>
 /// <param name="retryPolicy"> the retry policy to use.</param>
 public Policies(ILoadBalancingPolicy loadBalancingPolicy, IReconnectionPolicy reconnectionPolicy, IRetryPolicy retryPolicy)
     : this(loadBalancingPolicy, reconnectionPolicy, retryPolicy, DefaultSpeculativeExecutionPolicy, DefaultTimestampGenerator)
 {
     //Part of the public API can not be removed
 }
 public RedeliveryRetryPipeSpecification(IRetryPolicy retryPolicy)
 {
     _retryPolicy = retryPolicy;
 }
Пример #52
0
 public DontRetryOnNotModifiedPolicy(IRetryPolicy policy)
 {
     _innerPolicy = policy;
 }
 public void SetRetryPolicy(IRetryPolicy retryPolicy)
 {
     Client.DefaultRequestOptions.RetryPolicy = retryPolicy;
 }
Пример #54
0
        /// <summary>
        /// Create a new ElasticQueryProvider for a given connection, mapping, log, retry policy and field prefix.
        /// </summary>
        /// <param name="connection">Connection to use to connect to Elasticsearch.</param>
        /// <param name="mapping">A mapping to specify how queries and results are translated.</param>
        /// <param name="log">A log to receive any information or debugging messages.</param>
        /// <param name="retryPolicy">A policy to describe how to handle network issues.</param>
        public ElasticQueryProvider(IElasticConnection connection, IElasticMapping mapping, ILog log, IRetryPolicy retryPolicy)
        {
            Argument.EnsureNotNull(nameof(connection), connection);
            Argument.EnsureNotNull(nameof(mapping), mapping);
            Argument.EnsureNotNull(nameof(log), log);
            Argument.EnsureNotNull(nameof(retryPolicy), retryPolicy);

            Connection  = connection;
            Mapping     = mapping;
            Log         = log;
            RetryPolicy = retryPolicy;

            requestProcessor = new ElasticRequestProcessor(connection, mapping, log, retryPolicy);
        }
 private RetryPolicyDecorator(IRetryPolicy defaultRetryPolicy, Action <int> doBefore)
 {
     this.defaultRetryPolicy = defaultRetryPolicy;
     this.doBefore           = doBefore;
 }
Пример #56
0
 public void SetRetryPolicy(IRetryPolicy retryPolicy)
 {
     this.cloudBlobClient.DefaultRequestOptions.RetryPolicy = retryPolicy;
 }
Пример #57
0
 public RestClient(Uri baseAddress, IRetryPolicy retryPolicy)
     : this(baseAddress, retryPolicy, new AutomaticDecompressionHandler())
 {
 }
Пример #58
0
        /// <summary>
        /// Run a cancellable function until cancellation.
        /// </summary>
        /// <param name="runFunction">The function to run until cancellation.</param>
        /// <param name="retryPolicy">The retry policy used to control whether the task will be restarted on failure.</param>
        /// <returns>An instance of a runner which can be used to control the long-running function.</returns>
        public static ReliableTaskRunner Run(Func <CancellationToken, Task> runFunction, IRetryPolicy retryPolicy)
        {
            var runner = new ReliableTaskRunner();

            runner.RunInternal(runFunction, retryPolicy);
            return(runner);
        }
Пример #59
0
 /// <summary>
 /// Start a new retriable task for an action.
 /// </summary>
 /// <param name="action">The action for which to start a retriable tasks.</param>
 /// <param name="cancellationToken">The token with which cancellation is signalled.</param>
 /// <param name="taskCreationOptions">The task creation options.</param>
 /// <param name="scheduler">The task scheduler.</param>
 /// <param name="policy">The retry policy.</param>
 /// <returns>A task which completes when the action is complete.</returns>
 public Task StartNew(Action action, CancellationToken cancellationToken, TaskCreationOptions taskCreationOptions, TaskScheduler scheduler, IRetryPolicy policy)
 {
     return(this.StartNew(action, cancellationToken, taskCreationOptions, scheduler, new Count(), policy));
 }
Пример #60
0
 /// <summary>
 /// Start a new retriable task for an action.
 /// </summary>
 /// <param name="action">The action for which to start a retriable tasks.</param>
 /// <param name="cancellationToken">The token with which cancellation is signalled.</param>
 /// <param name="policy">The retry policy.</param>
 /// <returns>A task which completes when the action is complete.</returns>
 public Task StartNew(Action action, CancellationToken cancellationToken, IRetryPolicy policy)
 {
     return(this.StartNew(action, cancellationToken, new Count(), policy));
 }