Exemple #1
0
        /// <summary>
        /// Builds a <see cref="Policy" /> that will wait for a delegate to complete for a specified period of time. A <see cref="TimeoutRejectedException" /> will be thrown if the delegate does not complete within the configured timeout.
        /// </summary>
        /// <param name="timeout">The timeout.</param>
        /// <param name="timeoutStrategy">The timeout strategy.</param>
        /// <returns>The policy instance.</returns>
        /// <exception cref="System.ArgumentOutOfRangeException">timeout;Value must be a positive TimeSpan (or Timeout.InfiniteTimeSpan to indicate no timeout)</exception>
        public static TimeoutPolicy Timeout(TimeSpan timeout, TimeoutStrategy timeoutStrategy)
        {
            TimeoutValidator.ValidateTimeoutIsInRange(timeout);
            Action <Context, TimeSpan, Task> doNothing = (_, __, ___) => { };

            return(Timeout(ctx => timeout, timeoutStrategy, doNothing));
        }
Exemple #2
0
        /// <summary>
        /// Builds a <see cref="Policy" /> that will wait for a delegate to complete for a specified period of time. A <see cref="TimeoutRejectedException" /> will be thrown if the delegate does not complete within the configured timeout.
        /// </summary>
        /// <param name="seconds">The number of seconds after which to timeout.</param>
        /// <param name="timeoutStrategy">The timeout strategy.</param>
        /// <returns>The policy instance.</returns>
        /// <exception cref="System.ArgumentOutOfRangeException">seconds;Value must be greater than zero.</exception>
        public static TimeoutPolicy Timeout(int seconds, TimeoutStrategy timeoutStrategy)
        {
            if (seconds <= 0) throw new ArgumentOutOfRangeException(nameof(seconds));
            Action<Context, TimeSpan, Task> doNothing = (_, __, ___) => { };

            return Timeout(() => TimeSpan.FromSeconds(seconds), timeoutStrategy, doNothing);
        }
Exemple #3
0
 public StoreCopyClient(CatchUpClient catchUpClient, Monitors monitors, LogProvider logProvider, TimeoutStrategy backOffStrategy)
 {
     this._catchUpClient = catchUpClient;
     this._monitors      = monitors;
     _log = logProvider.getLog(this.GetType());
     this._backOffStrategy = backOffStrategy;
 }
Exemple #4
0
        /// <summary>
        /// Builds a <see cref="Policy{TResult}" /> that will wait for a delegate to complete for a specified period of time. A <see cref="TimeoutRejectedException" /> will be thrown if the delegate does not complete within the configured timeout.
        /// </summary>
        /// <typeparam name="TResult">The return type of delegates which may be executed through the policy.</typeparam>
        /// <param name="timeout">The timeout.</param>
        /// <param name="timeoutStrategy">The timeout strategy.</param>
        /// <returns>The policy instance.</returns>
        /// <exception cref="System.ArgumentOutOfRangeException">timeout;Value must be a positive TimeSpan (or Timeout.InfiniteTimeSpan to indicate no timeout)</exception>
        public static TimeoutPolicy <TResult> Timeout <TResult>(TimeSpan timeout, TimeoutStrategy timeoutStrategy)
        {
            TimeoutValidator.ValidateTimeSpanTimeout(timeout);
            Action <Context, TimeSpan, Task, Exception> doNothing = (_, __, ___, ____) => { };

            return(Timeout <TResult>(ctx => timeout, timeoutStrategy, doNothing));
        }
        /// <summary>
        /// Builds a <see cref="Policy" /> that will wait asynchronously for a delegate to complete for a specified period of time. A <see cref="TimeoutRejectedException" /> will be thrown if the delegate does not complete within the configured timeout.
        /// </summary>
        /// <param name="seconds">The number of seconds after which to timeout.</param>
        /// <param name="timeoutStrategy">The timeout strategy.</param>
        /// <returns>The policy instance.</returns>
        /// <exception cref="System.ArgumentOutOfRangeException">seconds;Value must be greater than zero.</exception>
        public static TimeoutPolicy TimeoutAsync(int seconds, TimeoutStrategy timeoutStrategy)
        {
            if (seconds <= 0) throw new ArgumentOutOfRangeException(nameof(seconds));
            Func<Context, TimeSpan, Task, Task> doNothingAsync = (_, __, ___) => TaskHelper.EmptyTask;

            return TimeoutAsync(() => TimeSpan.FromSeconds(seconds), timeoutStrategy, doNothingAsync);
        }
Exemple #6
0
        /// <summary>
        /// Builds a <see cref="Policy{TResult}" /> that will wait for a delegate to complete for a specified period of time. A <see cref="TimeoutRejectedException" /> will be thrown if the delegate does not complete within the configured timeout.
        /// </summary>
        /// <typeparam name="TResult">The return type of delegates which may be executed through the policy.</typeparam>
        /// <param name="seconds">The number of seconds after which to timeout.</param>
        /// <param name="timeoutStrategy">The timeout strategy.</param>
        /// <returns>The policy instance.</returns>
        /// <exception cref="System.ArgumentOutOfRangeException">seconds;Value must be greater than zero.</exception>
        public static TimeoutPolicy <TResult> Timeout <TResult>(int seconds, TimeoutStrategy timeoutStrategy)
        {
            TimeoutValidator.ValidateSecondsTimeout(seconds);
            Action <Context, TimeSpan, Task, Exception> doNothing = (_, __, ___, ____) => { };

            return(Timeout <TResult>(ctx => TimeSpan.FromSeconds(seconds), timeoutStrategy, doNothing));
        }
Exemple #7
0
 public StringCircuitBreakingHandler(int exceptionsAllowedBeforeBreaking,
                                     TimeSpan durationOfBreak,
                                     TimeSpan timeoutValue,
                                     TimeoutStrategy timeoutStrategy = TimeoutStrategy.Pessimistic)
     : base(exceptionsAllowedBeforeBreaking, durationOfBreak, timeoutValue, timeoutStrategy)
 {
 }
        /// <summary>
        /// Builds a <see cref="Policy" /> that will wait asynchronously for a delegate to complete for a specified period of time. A <see cref="TimeoutRejectedException" /> will be thrown if the delegate does not complete within the configured timeout.
        /// </summary>
        /// <param name="timeout">The timeout.</param>
        /// <param name="timeoutStrategy">The timeout strategy.</param>
        /// <returns>The policy instance.</returns>
        /// <exception cref="System.ArgumentOutOfRangeException">timeout;Value must be a positive TimeSpan (or Timeout.InfiniteTimeSpan to indicate no timeout)</exception>
        public static TimeoutPolicy TimeoutAsync(TimeSpan timeout, TimeoutStrategy timeoutStrategy)
        {
            TimeoutValidator.ValidateTimeSpanTimeout(timeout);
            Func <Context, TimeSpan, Task, Exception, Task> doNothingAsync = (_, __, ___, ____) => TaskHelper.EmptyTask;

            return(TimeoutAsync(ctx => timeout, timeoutStrategy, doNothingAsync));
        }
        /// <summary>
        /// Builds a <see cref="Policy" /> that will wait asynchronously for a delegate to complete for a specified period of time. A <see cref="TimeoutRejectedException" /> will be thrown if the delegate does not complete within the configured timeout.
        /// </summary>
        /// <param name="seconds">The number of seconds after which to timeout.</param>
        /// <param name="timeoutStrategy">The timeout strategy.</param>
        /// <returns>The policy instance.</returns>
        /// <exception cref="System.ArgumentOutOfRangeException">seconds;Value must be greater than zero.</exception>
        public static TimeoutPolicy TimeoutAsync(int seconds, TimeoutStrategy timeoutStrategy)
        {
            TimeoutValidator.ValidateSecondsTimeout(seconds);
            Func <Context, TimeSpan, Task, Exception, Task> doNothingAsync = (_, __, ___, ____) => TaskHelper.EmptyTask;

            return(TimeoutAsync(ctx => TimeSpan.FromSeconds(seconds), timeoutStrategy, doNothingAsync));
        }
Exemple #10
0
        internal static TResult Implementation <TResult>(
            Func <Context, CancellationToken, TResult> action,
            Context context,
            CancellationToken cancellationToken,
            Func <Context, TimeSpan> timeoutProvider,
            TimeoutStrategy timeoutStrategy,
            Action <Context, TimeSpan, Task> onTimeout)
        {
            cancellationToken.ThrowIfCancellationRequested();
            TimeSpan timeout = timeoutProvider(context);

            using (CancellationTokenSource timeoutCancellationTokenSource = new CancellationTokenSource())
            {
                using (CancellationTokenSource combinedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutCancellationTokenSource.Token))
                {
                    CancellationToken combinedToken = combinedTokenSource.Token;

                    Task <TResult> actionTask = null;
                    try
                    {
                        if (timeoutStrategy == TimeoutStrategy.Optimistic)
                        {
                            timeoutCancellationTokenSource.CancelAfter(timeout);
                            return(action(context, combinedToken));
                        }

                        // else: timeoutStrategy == TimeoutStrategy.Pessimistic

                        timeoutCancellationTokenSource.CancelAfter(timeout);

                        actionTask =

                        #if NET40
                            TaskEx
                        #else
                            Task
                        #endif

                            .Run(() =>
                                 action(context, combinedToken)                // cancellation token here allows the user delegate to react to cancellation: possibly clear up; then throw an OperationCanceledException.
                                 , combinedToken);                             // cancellation token here only allows Task.Run() to not begin the passed delegate at all, if cancellation occurs prior to invoking the delegate.

                        actionTask.Wait(timeoutCancellationTokenSource.Token); // cancellation token here cancels the Wait() and causes it to throw, but does not cancel actionTask.  We use only timeoutCancellationTokenSource.Token here, not combinedToken.  If we allowed the user's cancellation token to cancel the Wait(), in this pessimistic scenario where the user delegate may not observe that cancellation, that would create a no-longer-observed task.  That task could in turn later fault before completing, risking an UnobservedTaskException.

                        return(actionTask.Result);
                    }
                    catch (Exception ex)
                    {
                        if (timeoutCancellationTokenSource.IsCancellationRequested)
                        {
                            onTimeout(context, timeout, actionTask);
                            throw new TimeoutRejectedException("The delegate executed through TimeoutPolicy did not complete within the timeout.", ex);
                        }

                        throw;
                    }
                }
            }
        }
        internal static TResult Implementation <TResult>(
            Func <Context, CancellationToken, TResult> action,
            Context context,
            CancellationToken cancellationToken,
            Func <Context, TimeSpan> timeoutProvider,
            TimeoutStrategy timeoutStrategy,
            Action <Context, TimeSpan, Task, Exception> onTimeout)
        {
            cancellationToken.ThrowIfCancellationRequested();
            TimeSpan timeout = timeoutProvider(context);

            using (CancellationTokenSource timeoutCancellationTokenSource = new CancellationTokenSource())
            {
                using (CancellationTokenSource combinedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutCancellationTokenSource.Token))
                {
                    CancellationToken combinedToken = combinedTokenSource.Token;

                    Task <TResult> actionTask = null;
                    try
                    {
                        if (timeoutStrategy == TimeoutStrategy.Optimistic)
                        {
                            SystemClock.CancelTokenAfter(timeoutCancellationTokenSource, timeout);
                            return(action(context, combinedToken));
                        }

                        // else: timeoutStrategy == TimeoutStrategy.Pessimistic

                        SystemClock.CancelTokenAfter(timeoutCancellationTokenSource, timeout);

                        actionTask = Task.Run(() =>
                                              action(context, combinedToken) // cancellation token here allows the user delegate to react to cancellation: possibly clear up; then throw an OperationCanceledException.
                                              , combinedToken);              // cancellation token here only allows Task.Run() to not begin the passed delegate at all, if cancellation occurs prior to invoking the delegate.
                        try
                        {
                            actionTask.Wait(timeoutCancellationTokenSource.Token);        // cancellation token here cancels the Wait() and causes it to throw, but does not cancel actionTask.  We use only timeoutCancellationTokenSource.Token here, not combinedToken.  If we allowed the user's cancellation token to cancel the Wait(), in this pessimistic scenario where the user delegate may not observe that cancellation, that would create a no-longer-observed task.  That task could in turn later fault before completing, risking an UnobservedTaskException.
                        }
                        catch (AggregateException ex) when(ex.InnerExceptions.Count == 1) // Issue #270.  Unwrap extra AggregateException caused by the way pessimistic timeout policy for synchronous executions is necessarily constructed.
                        {
                            ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
                        }

                        return(actionTask.Result);
                    }
                    catch (Exception ex)
                    {
                        // Note that we cannot rely on testing (operationCanceledException.CancellationToken == combinedToken || operationCanceledException.CancellationToken == timeoutCancellationTokenSource.Token)
                        // as either of those tokens could have been onward combined with another token by executed code, and so may not be the token expressed on operationCanceledException.CancellationToken.
                        if (ex is OperationCanceledException && timeoutCancellationTokenSource.IsCancellationRequested)
                        {
                            onTimeout(context, timeout, actionTask, ex);
                            throw new TimeoutRejectedException("The delegate executed through TimeoutPolicy did not complete within the timeout.", ex);
                        }

                        throw;
                    }
                }
            }
        }
Exemple #12
0
        /// <summary>
        /// Builds a <see cref="Policy{TResult}"/> that will wait asynchronously for a delegate to complete for a specified period of time. A <see cref="TimeoutRejectedException"/> will be thrown if the delegate does not complete within the configured timeout.
        /// </summary>
        /// <param name="seconds">The number of seconds after which to timeout.</param>
        /// <param name="timeoutStrategy">The timeout strategy.</param>
        /// <exception cref="System.ArgumentOutOfRangeException">seconds;Value must be greater than zero.</exception>
        /// <returns>The policy instance.</returns>
        public static TimeoutPolicy <TResult> TimeoutAsync <TResult>(int seconds, TimeoutStrategy timeoutStrategy)
        {
            TimeoutValidator.ValidateSecondsTimeout(seconds);

            Func <Context, TimeSpan, Task, Task> doNothingAsync = (_, __, ___) => TaskHelper.FromResult(default(TResult));

            return(TimeoutAsync <TResult>(ctx => TimeSpan.FromSeconds(seconds), timeoutStrategy, doNothingAsync));
        }
        public void TestWhenMessagetWithAttribute()
        {
            var timeoutStrategy = new TimeoutStrategy(new ConnectionConfiguration {
                Timeout = 10
            });

            Assert.AreEqual(90, timeoutStrategy.GetTimeoutSeconds(typeof(MessageWithTimeoutAttribute)));
        }
        public void TestWhenPersistentMessagesIsFalse()
        {
            var timeoutStrategy = new TimeoutStrategy(new ConnectionConfiguration {
                Timeout = 10
            });

            Assert.AreEqual(10, timeoutStrategy.GetTimeoutSeconds(typeof(MessageWithoutTimeoutAttribute)));
        }
 /// <summary>
 /// Builds a <see cref="Policy{TResult}" /> that will wait for a delegate to complete for a specified period of time. A <see cref="TimeoutRejectedException" /> will be thrown if the delegate does not complete within the configured timeout.
 /// </summary>
 /// <typeparam name="TResult">The return type of delegates which may be executed through the policy.</typeparam>
 /// <param name="timeout">The timeout.</param>
 /// <param name="timeoutStrategy">The timeout strategy.</param>
 /// <param name="onTimeout">An action to call on timeout, passing the execution context, the timeout applied, and a <see cref="Task{TResult}" /> capturing the abandoned, timed-out action.
 /// <remarks>The Task parameter will be null if the executed action responded co-operatively to cancellation before the policy timed it out.</remarks></param>
 /// <returns>The policy instance.</returns>
 /// <exception cref="System.ArgumentOutOfRangeException">timeout;Value must be greater than zero.</exception>
 /// <exception cref="System.ArgumentNullException">onTimeout</exception>
 public static TimeoutPolicy <TResult> Timeout <TResult>(TimeSpan timeout, TimeoutStrategy timeoutStrategy, Action <Context, TimeSpan, Task> onTimeout)
 {
     if (timeout <= TimeSpan.Zero)
     {
         throw new ArgumentOutOfRangeException(nameof(timeout));
     }
     return(Timeout <TResult>(() => timeout, timeoutStrategy, onTimeout));
 }
Exemple #16
0
        /// <summary>
        /// Builds a <see cref="Policy" /> that will wait for a delegate to complete for a specified period of time. A <see cref="TimeoutRejectedException" /> will be thrown if the delegate does not complete within the configured timeout.
        /// </summary>
        /// <param name="timeoutProvider">A function to provide the timeout for this execution.</param>
        /// <param name="timeoutStrategy">The timeout strategy.</param>
        /// <param name="onTimeout">An action to call on timeout, passing the execution context, the timeout applied, the <see cref="Task" /> capturing the abandoned, timed-out action, and the captured <see cref="Exception"/>.
        /// <remarks>The Task parameter will be null if the executed action responded cooperatively to cancellation before the policy timed it out.</remarks></param>
        /// <returns>The policy instance.</returns>
        /// <exception cref="ArgumentNullException">timeoutProvider</exception>
        /// <exception cref="ArgumentNullException">onTimeout</exception>
        public static TimeoutPolicy Timeout(Func <TimeSpan> timeoutProvider, TimeoutStrategy timeoutStrategy, Action <Context, TimeSpan, Task, Exception> onTimeout)
        {
            if (timeoutProvider == null)
            {
                throw new ArgumentNullException(nameof(timeoutProvider));
            }

            return(Timeout(_ => timeoutProvider(), timeoutStrategy, onTimeout));
        }
        /// <summary>
        /// Builds a <see cref="Policy" /> that will wait asynchronously for a delegate to complete for a specified period of time. A <see cref="TimeoutRejectedException" /> will be thrown if the delegate does not complete within the configured timeout.
        /// </summary>
        /// <param name="timeoutProvider">A function to provide the timeout for this execution.</param>
        /// <param name="timeoutStrategy">The timeout strategy.</param>
        /// <param name="onTimeoutAsync">An action to call on timeout, passing the execution context, the timeout applied, the <see cref="Task" /> capturing the abandoned, timed-out action, and the captured <see cref="Exception"/>.
        /// <remarks>The Task parameter will be null if the executed action responded co-operatively to cancellation before the policy timed it out.</remarks></param>
        /// <returns>The policy instance.</returns>
        /// <exception cref="System.ArgumentNullException">timeoutProvider</exception>
        /// <exception cref="System.ArgumentNullException">onTimeoutAsync</exception>
        public static TimeoutPolicy TimeoutAsync(Func <TimeSpan> timeoutProvider, TimeoutStrategy timeoutStrategy, Func <Context, TimeSpan, Task, Exception, Task> onTimeoutAsync)
        {
            if (timeoutProvider == null)
            {
                throw new ArgumentNullException(nameof(timeoutProvider));
            }

            return(TimeoutAsync(ctx => timeoutProvider(), timeoutStrategy, onTimeoutAsync));
        }
Exemple #18
0
        /// <summary>
        /// Builds a <see cref="Policy" /> that will wait asynchronously for a delegate to complete for a specified period of time. A <see cref="TimeoutRejectedException" /> will be thrown if the delegate does not complete within the configured timeout.
        /// </summary>
        /// <param name="timeout">The timeout.</param>
        /// <param name="timeoutStrategy">The timeout strategy.</param>
        /// <param name="onTimeoutAsync">An action to call on timeout, passing the execution context, the timeout applied, and a <see cref="Task" /> capturing the abandoned, timed-out action.
        /// <remarks>The Task parameter will be null if the executed action responded co-operatively to cancellation before the policy timed it out.</remarks></param>
        /// <returns>The policy instance.</returns>
        /// <exception cref="System.ArgumentOutOfRangeException">timeout;Value must be greater than zero.</exception>
        /// <exception cref="System.ArgumentNullException">onTimeoutAsync</exception>
        public static TimeoutPolicy TimeoutAsync(TimeSpan timeout, TimeoutStrategy timeoutStrategy, Func <Context, TimeSpan, Task, Task> onTimeoutAsync)
        {
            if (timeout <= TimeSpan.Zero)
            {
                throw new ArgumentOutOfRangeException(nameof(timeout));
            }

            return(TimeoutAsync(() => timeout, timeoutStrategy, onTimeoutAsync));
        }
Exemple #19
0
 internal TimeoutPolicy(
     Func <Context, TimeSpan> timeoutProvider,
     TimeoutStrategy timeoutStrategy,
     Action <Context, TimeSpan, Task, Exception> onTimeout)
 {
     _timeoutProvider = timeoutProvider ?? throw new ArgumentNullException(nameof(timeoutProvider));
     _timeoutStrategy = timeoutStrategy;
     _onTimeout       = onTimeout ?? throw new ArgumentNullException(nameof(onTimeout));
 }
        internal static async Task <TResult> ImplementationAsync <TResult>(
            Func <Context, CancellationToken, Task <TResult> > action,
            Context context,
            Func <Context, TimeSpan> timeoutProvider,
            TimeoutStrategy timeoutStrategy,
            Func <Context, TimeSpan, Task, Exception, Task> onTimeoutAsync,
            CancellationToken cancellationToken,
            bool continueOnCapturedContext)
        {
            cancellationToken.ThrowIfCancellationRequested();
            TimeSpan timeout = timeoutProvider(context);

            using (CancellationTokenSource timeoutCancellationTokenSource = new CancellationTokenSource())
            {
                using (CancellationTokenSource combinedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutCancellationTokenSource.Token))
                {
                    Task <TResult>    actionTask    = null;
                    CancellationToken combinedToken = combinedTokenSource.Token;

                    try
                    {
                        if (timeoutStrategy == TimeoutStrategy.Optimistic)
                        {
                            SystemClock.CancelTokenAfter(timeoutCancellationTokenSource, timeout);
                            return(await action(context, combinedToken).ConfigureAwait(continueOnCapturedContext));
                        }

                        // else: timeoutStrategy == TimeoutStrategy.Pessimistic

                        Task <TResult> timeoutTask = timeoutCancellationTokenSource.Token.AsTask <TResult>();

                        SystemClock.CancelTokenAfter(timeoutCancellationTokenSource, timeout);

                        actionTask = action(context, combinedToken);

                        return(await(await
#if NET40
                                     TaskEx
#else
                                     Task
#endif
                                     .WhenAny(actionTask, timeoutTask).ConfigureAwait(continueOnCapturedContext)).ConfigureAwait(continueOnCapturedContext));
                    }
                    catch (Exception ex)
                    {
                        if (timeoutCancellationTokenSource.IsCancellationRequested)
                        {
                            await onTimeoutAsync(context, timeout, actionTask, ex).ConfigureAwait(continueOnCapturedContext);

                            throw new TimeoutRejectedException("The delegate executed asynchronously through TimeoutPolicy did not complete within the timeout.", ex);
                        }

                        throw;
                    }
                }
            }
        }
        /// <summary>
        /// Builds a <see cref="Policy" /> that will wait asynchronously for a delegate to complete for a specified period of time. A <see cref="TimeoutRejectedException" /> will be thrown if the delegate does not complete within the configured timeout.
        /// </summary>
        /// <param name="seconds">The number of seconds after which to timeout.</param>
        /// <param name="timeoutStrategy">The timeout strategy.</param>
        /// <param name="onTimeoutAsync">An action to call on timeout, passing the execution context, the timeout applied, the <see cref="Task" /> capturing the abandoned, timed-out action, and the captured <see cref="Exception"/>.
        /// <remarks>The Task parameter will be null if the executed action responded co-operatively to cancellation before the policy timed it out.</remarks></param>
        /// <returns>The policy instance.</returns>
        /// <exception cref="System.ArgumentOutOfRangeException">seconds;Value must be greater than zero.</exception>
        /// <exception cref="System.ArgumentNullException">seconds;Value must be greater than zero.</exception>
        public static TimeoutPolicy TimeoutAsync(int seconds, TimeoutStrategy timeoutStrategy, Func <Context, TimeSpan, Task, Exception, Task> onTimeoutAsync)
        {
            if (seconds <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(seconds));
            }

            return(TimeoutAsync(ctx => TimeSpan.FromSeconds(seconds), timeoutStrategy, onTimeoutAsync));
        }
Exemple #22
0
        /// <summary>
        /// Builds a <see cref="Policy{TResult}" /> that will wait for a delegate to complete for a specified period of time. A <see cref="TimeoutRejectedException" /> will be thrown if the delegate does not complete within the configured timeout.
        /// </summary>
        /// <typeparam name="TResult">The return type of delegates which may be executed through the policy.</typeparam>
        /// <param name="seconds">The number of seconds after which to timeout.</param>
        /// <param name="timeoutStrategy">The timeout strategy.</param>
        /// <param name="onTimeout">An action to call on timeout, passing the execution context, the timeout applied, the <see cref="Task{TResult}" /> capturing the abandoned, timed-out action, and the captured <see cref="Exception"/>.
        /// <remarks>The Task parameter will be null if the executed action responded co-operatively to cancellation before the policy timed it out.</remarks></param>
        /// <returns>The policy instance.</returns>
        /// <exception cref="System.ArgumentOutOfRangeException">seconds;Value must be greater than zero.</exception>
        /// <exception cref="System.ArgumentNullException">onTimeout</exception>
        public static TimeoutPolicy <TResult> Timeout <TResult>(int seconds, TimeoutStrategy timeoutStrategy, Action <Context, TimeSpan, Task, Exception> onTimeout)
        {
            if (seconds <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(seconds));
            }

            return(Timeout <TResult>(ctx => TimeSpan.FromSeconds(seconds), timeoutStrategy, onTimeout));
        }
        static async Task RunAsync()
        {
            CancellationToken cancellationToken = new CancellationToken();

            double          timeoutvalue    = 200;
            TimeoutStrategy timeoutStrategy = TimeoutStrategy.Pessimistic;

            var client = new HttpClient();

            var timeoutPolicy = Policy
                                .TimeoutAsync(TimeSpan.FromMilliseconds(timeoutvalue), timeoutStrategy);

            var circuitBreakerPolicy = Policy
                                       .Handle <Exception>()
                                       .Or <TimeoutRejectedException>()
                                       .Or <TimeoutException>()
                                       .CircuitBreakerAsync(
                exceptionsAllowedBeforeBreaking: 4,
                durationOfBreak: TimeSpan.FromSeconds(8),
                onBreak: (ex, breakDelay) =>
            {
                Console.WriteLine(".Breaker logging: Breaking the circuit for " + breakDelay.TotalMilliseconds + "ms!");
                Console.WriteLine("...due to: " + ex.Message);
            },
                onReset: () => Console.WriteLine(".Breaker logging: Call ok! Closed the circuit again."),
                onHalfOpen: () => Console.WriteLine(".Breaker logging: Half-open; next call is a trial.")
                );
            int i = 0;

            // Do the following until a key is pressed
            while (!Console.KeyAvailable && !cancellationToken.IsCancellationRequested)
            {
                i++;
                try
                {
                    // Retry the following call according to the policy - 3 times.
                    string msg = await Policy.WrapAsync(circuitBreakerPolicy, timeoutPolicy).ExecuteAsync <String>(() =>
                    {
                        return(client.GetStringAsync("http://10.1.2.2:5000/greeting"));
                    });

                    Console.WriteLine("Request " + i + ": " + msg);
                }
                catch (BrokenCircuitException b) {
                    Console.WriteLine("Request " + i + " failed with: " + b.GetType().Name);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Request " + i + " eventually failed with: " + e.Message);
                }

                // Wait half second
                await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
            }
            ;
        }
Exemple #24
0
        /// <summary>
        /// Builds a <see cref="Policy{TResult}" /> that will wait for a delegate to complete for a specified period of time. A <see cref="TimeoutRejectedException" /> will be thrown if the delegate does not complete within the configured timeout.
        /// </summary>
        /// <typeparam name="TResult">The return type of delegates which may be executed through the policy.</typeparam>
        /// <param name="seconds">The number of seconds after which to timeout.</param>
        /// <param name="timeoutStrategy">The timeout strategy.</param>
        /// <returns>The policy instance.</returns>
        /// <exception cref="System.ArgumentOutOfRangeException">seconds;Value must be greater than zero.</exception>
        public static TimeoutPolicy <TResult> Timeout <TResult>(int seconds, TimeoutStrategy timeoutStrategy)
        {
            if (seconds <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(seconds));
            }
            Action <Context, TimeSpan, Task> doNothing = (_, __, ___) => { };

            return(Timeout <TResult>(ctx => TimeSpan.FromSeconds(seconds), timeoutStrategy, doNothing));
        }
 internal AsyncTimeoutPolicy(
     Func <Context, TimeSpan> timeoutProvider,
     TimeoutStrategy timeoutStrategy,
     Func <Context, TimeSpan, Task, Exception, Task> onTimeoutAsync
     )
 {
     _timeoutProvider = timeoutProvider ?? throw new ArgumentNullException(nameof(timeoutProvider));
     _timeoutStrategy = timeoutStrategy;
     _onTimeoutAsync  = onTimeoutAsync ?? throw new ArgumentNullException(nameof(onTimeoutAsync));
 }
Exemple #26
0
 public CircuitBreakingHandler(int exceptionsAllowedBeforeBreaking,
                               TimeSpan durationOfBreak,
                               TimeSpan timeoutValue,
                               TimeoutStrategy timeoutStrategy = TimeoutStrategy.Pessimistic)
     : base(string.Format("Handler:{0}", nameof(T)))
 {
     _exceptionsAllowedBeforeBreaking = exceptionsAllowedBeforeBreaking;
     _durationOfBreak      = durationOfBreak;
     _timeoutBreakerPolicy = Policy.Timeout(timeoutValue, timeoutStrategy);
 }
Exemple #27
0
        /// <summary>
        /// Builds a <see cref="Policy" /> that will wait asynchronously for a delegate to complete for a specified period of time. A <see cref="TimeoutRejectedException" /> will be thrown if the delegate does not complete within the configured timeout.
        /// </summary>
        /// <param name="timeout">The timeout.</param>
        /// <param name="timeoutStrategy">The timeout strategy.</param>
        /// <returns>The policy instance.</returns>
        /// <exception cref="System.ArgumentOutOfRangeException"></exception>
        public static TimeoutPolicy TimeoutAsync(TimeSpan timeout, TimeoutStrategy timeoutStrategy)
        {
            if (timeout <= TimeSpan.Zero)
            {
                throw new ArgumentOutOfRangeException(nameof(timeout));
            }
            Func <Context, TimeSpan, Task, Task> doNothingAsync = (_, __, ___) => TaskHelper.EmptyTask;

            return(TimeoutAsync(() => timeout, timeoutStrategy, doNothingAsync));
        }
        /// <summary>
        /// Builds a <see cref="Policy{TResult}" /> that will wait for a delegate to complete for a specified period of time. A <see cref="TimeoutRejectedException" /> will be thrown if the delegate does not complete within the configured timeout.
        /// </summary>
        /// <typeparam name="TResult">The return type of delegates which may be executed through the policy.</typeparam>
        /// <param name="timeout">The timeout.</param>
        /// <param name="timeoutStrategy">The timeout strategy.</param>
        /// <returns>The policy instance.</returns>
        /// <exception cref="System.ArgumentOutOfRangeException">timeout</exception>
        public static TimeoutPolicy <TResult> Timeout <TResult>(TimeSpan timeout, TimeoutStrategy timeoutStrategy)
        {
            if (timeout <= TimeSpan.Zero)
            {
                throw new ArgumentOutOfRangeException(nameof(timeout));
            }
            Action <Context, TimeSpan, Task> doNothing = (_, __, ___) => { };

            return(Timeout <TResult>(() => timeout, timeoutStrategy, doNothing));
        }
Exemple #29
0
        /// <summary>
        /// Builds a <see cref="Policy" /> that will wait asynchronously for a delegate to complete for a specified period of time. A <see cref="TimeoutRejectedException" /> will be thrown if the delegate does not complete within the configured timeout.
        /// </summary>
        /// <param name="seconds">The number of seconds after which to timeout.</param>
        /// <param name="timeoutStrategy">The timeout strategy.</param>
        /// <returns>The policy instance.</returns>
        /// <exception cref="System.ArgumentOutOfRangeException">seconds;Value must be greater than zero.</exception>
        public static TimeoutPolicy TimeoutAsync(int seconds, TimeoutStrategy timeoutStrategy)
        {
            if (seconds <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(seconds));
            }
            Func <Context, TimeSpan, Task, Task> doNothingAsync = (_, __, ___) => TaskHelper.EmptyTask;

            return(TimeoutAsync(ctx => TimeSpan.FromSeconds(seconds), timeoutStrategy, doNothingAsync));
        }
        /// <summary>
        /// Builds a <see cref="Policy" /> that will wait asynchronously for a delegate to complete for a specified period of time. A <see cref="TimeoutRejectedException" /> will be thrown if the delegate does not complete within the configured timeout.
        /// </summary>
        /// <param name="timeoutProvider">A function to provide the timeout for this execution.</param>
        /// <param name="timeoutStrategy">The timeout strategy.</param>
        /// <returns>The policy instance.</returns>
        /// <exception cref="System.ArgumentNullException">timeoutProvider</exception>
        public static TimeoutPolicy TimeoutAsync(Func <TimeSpan> timeoutProvider, TimeoutStrategy timeoutStrategy)
        {
            if (timeoutProvider == null)
            {
                throw new ArgumentNullException(nameof(timeoutProvider));
            }

            Func <Context, TimeSpan, Task, Exception, Task> doNothingAsync = (_, __, ___, ____) => TaskHelper.EmptyTask;

            return(TimeoutAsync(ctx => timeoutProvider(), timeoutStrategy, doNothingAsync));
        }
Exemple #31
0
 public HandshakeClientInitializer(ApplicationProtocolRepository applicationProtocolRepository, ModifierProtocolRepository modifierProtocolRepository, ProtocolInstallerRepository <Org.Neo4j.causalclustering.protocol.ProtocolInstaller_Orientation_Client> protocolInstallerRepository, NettyPipelineBuilderFactory pipelineBuilderFactory, Duration handshakeTimeout, LogProvider debugLogProvider, LogProvider userLogProvider)
 {
     this._debugLog = debugLogProvider.getLog(this.GetType());
     this._userLog  = userLogProvider.getLog(this.GetType());
     this._applicationProtocolRepository = applicationProtocolRepository;
     this._modifierProtocolRepository    = modifierProtocolRepository;
     this._timeout                = handshakeTimeout;
     this._protocolInstaller      = protocolInstallerRepository;
     this._pipelineBuilderFactory = pipelineBuilderFactory;
     this._handshakeDelay         = new ExponentialBackoffStrategy(1, 2000, MILLISECONDS);
 }
Exemple #32
0
 public QoSOptions(
     int exceptionsAllowedBeforeBreaking,
     int durationofBreak,
     int timeoutValue,
     TimeoutStrategy timeoutStrategy = TimeoutStrategy.Pessimistic)
 {
     ExceptionsAllowedBeforeBreaking = exceptionsAllowedBeforeBreaking;
     DurationOfBreak = TimeSpan.FromMilliseconds(durationofBreak);
     TimeoutValue    = TimeSpan.FromMilliseconds(timeoutValue);
     TimeoutStrategy = timeoutStrategy;
 }
Exemple #33
0
        /// <summary>
        /// Builds a <see cref="Policy" /> that will wait for a delegate to complete for a specified period of time. A <see cref="TimeoutRejectedException" /> will be thrown if the delegate does not complete within the configured timeout.
        /// </summary>
        /// <param name="timeout">The timeout.</param>
        /// <param name="timeoutStrategy">The timeout strategy.</param>
        /// <param name="onTimeout">An action to call on timeout, passing the execution context, the timeout applied, and a <see cref="Task" /> capturing the abandoned, timed-out action.
        /// <remarks>The Task parameter will be null if the executed action responded co-operatively to cancellation before the policy timed it out.</remarks></param>
        /// <returns>The policy instance.</returns>
        /// <exception cref="System.ArgumentOutOfRangeException">timeout;Value must be greater than zero.</exception>
        /// <exception cref="System.ArgumentNullException">onTimeout</exception>
        public static TimeoutPolicy Timeout(TimeSpan timeout, TimeoutStrategy timeoutStrategy, Action<Context, TimeSpan, Task> onTimeout)
        {
            if (timeout <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(timeout));

            return Timeout(() => timeout, timeoutStrategy, onTimeout);
        }
Exemple #34
0
        /// <summary>
        /// Builds a <see cref="Policy" /> that will wait asynchronously for a delegate to complete for a specified period of time. A <see cref="TimeoutRejectedException" /> will be thrown if the delegate does not complete within the configured timeout.
        /// </summary>
        /// <param name="timeoutProvider">A function to provide the timeout for this execution.</param>
        /// <param name="timeoutStrategy">The timeout strategy.</param>
        /// <returns>The policy instance.</returns>
        /// <exception cref="System.ArgumentNullException">timeoutProvider</exception>
        public static TimeoutPolicy TimeoutAsync(Func<TimeSpan> timeoutProvider, TimeoutStrategy timeoutStrategy)
        {
            Func<Context, TimeSpan, Task, Task> doNothingAsync = (_, __, ___) => TaskHelper.EmptyTask;

            return TimeoutAsync(timeoutProvider, timeoutStrategy, doNothingAsync);
        }
Exemple #35
0
        /// <summary>
        /// Builds a <see cref="Policy" /> that will wait asynchronously for a delegate to complete for a specified period of time. A <see cref="TimeoutRejectedException" /> will be thrown if the delegate does not complete within the configured timeout.
        /// </summary>
        /// <param name="timeoutProvider">A function to provide the timeout for this execution.</param>
        /// <param name="timeoutStrategy">The timeout strategy.</param>
        /// <param name="onTimeoutAsync">An action to call on timeout, passing the execution context, the timeout applied, and a <see cref="Task" /> capturing the abandoned, timed-out action.
        /// <remarks>The Task parameter will be null if the executed action responded co-operatively to cancellation before the policy timed it out.</remarks></param>
        /// <returns>The policy instance.</returns>
        /// <exception cref="System.ArgumentNullException">timeoutProvider</exception>
        /// <exception cref="System.ArgumentNullException">onTimeoutAsync</exception>
        public static TimeoutPolicy TimeoutAsync(Func<TimeSpan> timeoutProvider, TimeoutStrategy timeoutStrategy, Func<Context, TimeSpan, Task, Task> onTimeoutAsync)
        {
            if (timeoutProvider == null) throw new ArgumentNullException(nameof(timeoutProvider));
            if (onTimeoutAsync == null) throw new ArgumentNullException(nameof(onTimeoutAsync));

            return new TimeoutPolicy(
                (action, context, cancellationToken, continueOnCapturedContext) => TimeoutEngine.ImplementationAsync(
                    async ct => { await action(ct).ConfigureAwait(continueOnCapturedContext); return EmptyStruct.Instance; },
                    context,
                    timeoutProvider,
                    timeoutStrategy,
                    onTimeoutAsync,
                    cancellationToken, 
                    continueOnCapturedContext)
                );
        }
Exemple #36
0
        /// <summary>
        /// Builds a <see cref="Policy" /> that will wait for a delegate to complete for a specified period of time. A <see cref="TimeoutRejectedException" /> will be thrown if the delegate does not complete within the configured timeout.
        /// </summary>
        /// <param name="timeout">The timeout.</param>
        /// <param name="timeoutStrategy">The timeout strategy.</param>
        /// <returns>The policy instance.</returns>
        /// <exception cref="System.ArgumentOutOfRangeException"></exception>
        public static TimeoutPolicy Timeout(TimeSpan timeout, TimeoutStrategy timeoutStrategy)
        {
            if (timeout <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(timeout));
            Action<Context, TimeSpan, Task> doNothing = (_, __, ___) => { };

            return Timeout(() => timeout, timeoutStrategy, doNothing);
        }
Exemple #37
0
        /// <summary>
        /// Builds a <see cref="Policy" /> that will wait for a delegate to complete for a specified period of time. A <see cref="TimeoutRejectedException" /> will be thrown if the delegate does not complete within the configured timeout.
        /// </summary>
        /// <param name="seconds">The number of seconds after which to timeout.</param>
        /// <param name="timeoutStrategy">The timeout strategy.</param>
        /// <param name="onTimeout">An action to call on timeout, passing the execution context, the timeout applied, and a <see cref="Task" /> capturing the abandoned, timed-out action.
        /// <remarks>The Task parameter will be null if the executed action responded co-operatively to cancellation before the policy timed it out.</remarks></param>
        /// <returns>The policy instance.</returns>
        /// <exception cref="System.ArgumentOutOfRangeException">seconds;Value must be greater than zero.</exception>
        /// <exception cref="System.ArgumentNullException">onTimeout</exception>
        public static TimeoutPolicy Timeout(int seconds, TimeoutStrategy timeoutStrategy, Action<Context, TimeSpan, Task> onTimeout)
        {
            if (seconds <= 0) throw new ArgumentOutOfRangeException(nameof(seconds));

            return Timeout(() => TimeSpan.FromSeconds(seconds), timeoutStrategy, onTimeout);
        }
Exemple #38
0
        /// <summary>
        /// Builds a <see cref="Policy" /> that will wait asynchronously for a delegate to complete for a specified period of time. A <see cref="TimeoutRejectedException" /> will be thrown if the delegate does not complete within the configured timeout.
        /// </summary>
        /// <param name="timeout">The timeout.</param>
        /// <param name="timeoutStrategy">The timeout strategy.</param>
        /// <returns>The policy instance.</returns>
        /// <exception cref="System.ArgumentOutOfRangeException"></exception>
        public static TimeoutPolicy TimeoutAsync(TimeSpan timeout, TimeoutStrategy timeoutStrategy)
        {
            if (timeout <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(timeout));
            Func<Context, TimeSpan, Task, Task> doNothingAsync = (_, __, ___) => TaskHelper.EmptyTask;

            return TimeoutAsync(() => timeout, timeoutStrategy, doNothingAsync);
        }
 public void TestWhenMessagetWithAttribute()
 {
     var timeoutStrategy = new TimeoutStrategy(new ConnectionConfiguration {Timeout = 10});
     Assert.AreEqual(90, timeoutStrategy.GetTimeoutSeconds(typeof(MessageWithTimeoutAttribute)));
 }
 public void TestWhenPersistentMessagesIsFalse()
 {
     var timeoutStrategy = new TimeoutStrategy(new ConnectionConfiguration { Timeout = 10 });
     Assert.AreEqual(10, timeoutStrategy.GetTimeoutSeconds(typeof(MessageWithoutTimeoutAttribute)));
 }
Exemple #41
0
        /// <summary>
        /// Builds a <see cref="Policy" /> that will wait for a delegate to complete for a specified period of time. A <see cref="TimeoutRejectedException" /> will be thrown if the delegate does not complete within the configured timeout.
        /// </summary>
        /// <param name="timeoutProvider">A function to provide the timeout for this execution.</param>
        /// <param name="timeoutStrategy">The timeout strategy.</param>
        /// <param name="onTimeout">An action to call on timeout, passing the execution context, the timeout applied, and a <see cref="Task" /> capturing the abandoned, timed-out action.
        /// <remarks>The Task parameter will be null if the executed action responded co-operatively to cancellation before the policy timed it out.</remarks></param>
        /// <returns>The policy instance.</returns>
        /// <exception cref="System.ArgumentNullException">timeoutProvider</exception>
        /// <exception cref="System.ArgumentNullException">onTimeout</exception>
        public static TimeoutPolicy Timeout(Func<TimeSpan> timeoutProvider, TimeoutStrategy timeoutStrategy, Action<Context, TimeSpan, Task> onTimeout)
        {
            if (timeoutProvider == null) throw new ArgumentNullException(nameof(timeoutProvider));
            if (onTimeout == null) throw new ArgumentNullException(nameof(onTimeout));

            return new TimeoutPolicy(
                (action, context, cancellationToken) => TimeoutEngine.Implementation(
                    ct => { action(ct); return EmptyStruct.Instance; },
                    context,
                    cancellationToken,
                    timeoutProvider,
                    timeoutStrategy,
                    onTimeout)
                );
        }
Exemple #42
0
 /// <summary>
 /// Builds a <see cref="Policy" /> that will wait for a delegate to complete for a specified period of time. A <see cref="TimeoutRejectedException" /> will be thrown if the delegate does not complete within the configured timeout.
 /// </summary>
 /// <param name="timeoutProvider">A function to provide the timeout for this execution.</param>
 /// <param name="timeoutStrategy">The timeout strategy.</param>
 /// <returns>The policy instance.</returns>
 /// <exception cref="System.ArgumentNullException">timeoutProvider</exception>
 public static TimeoutPolicy Timeout(Func<TimeSpan> timeoutProvider, TimeoutStrategy timeoutStrategy)
 {
     Action<Context, TimeSpan, Task> doNothing = (_, __, ___) => { };
     return Timeout(timeoutProvider, timeoutStrategy, doNothing);
 }