Example #1
0
        public IEnumerable<IResult> Export()
        {
            var saveFileResult = new SaveFileResult()
                    .FilterFiles(x => x.AddFilter("csv", isDefault: true).WithDescription("CSV Datei"))
                    .In(Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments));

            yield return saveFileResult;

            var exportResult = new DelegateResult(() => CsvImporter.Export(BarcodeManager.Barcodes, saveFileResult.FileName));

            yield return exportResult
                .Rescue().With(coroutine: ExportRescue);
        }
        public async Task <bool> CanRetryAsync(DelegateResult <TResult> delegateResult, CancellationToken cancellationToken, bool continueOnCapturedContext)
        {
            if (_errorCount < int.MaxValue)
            {
                _errorCount += 1;
            }

            var currentTimeSpan = _sleepDurationProvider(_errorCount, _context);

            await _onRetryAsync(delegateResult, currentTimeSpan, _context).ConfigureAwait(continueOnCapturedContext);

            await SystemClock.SleepAsync(currentTimeSpan, cancellationToken).ConfigureAwait(continueOnCapturedContext);

            return(true);
        }
Example #3
0
 public static void LogApiFailure(this Serilog.ILogger logger, DelegateResult <HttpResponseMessage> result, TimeSpan timeSpan, int retryCount, Context context)
 {
     if (result.Exception != null)
     {
         logger.Warning(result.Exception, "An exception occurred on retry {RetryAttempt} for {PolicyKey} - Retrying in {SleepDuration}ms",
                        retryCount, context.PolicyKey, timeSpan.TotalMilliseconds);
     }
     else
     {
         logger.Warning("A non success code {StatusCode} with reason {Reason} and content {Content} was received on retry {RetryAttempt} for {PolicyKey} - Retrying in {SleepDuration}ms",
                        (int)result.Result.StatusCode, result.Result.ReasonPhrase,
                        result.Result.Content?.ReadAsStringAsync().GetAwaiter().GetResult(),
                        retryCount, context.PolicyKey, timeSpan.TotalMilliseconds);
     }
 }
        public void BusyIndicatorIsSetToBusyBeforeTheInnerResultGetsExecuted()
        {
            bool isInnerExecuted = false;

            BusyIndicatorMock.Setup(x => x.Busy(It.IsAny<string>()))
                .Callback(() => Assert.IsFalse(isInnerExecuted, "BusyIndicator set busy to busy after inner result was executed"));

            var inner = new DelegateResult(() => isInnerExecuted = true);
            var sut = new BusyResultDecorator(inner, "foo")
                .In(BusyIndicator);

            sut.Execute(null);

            BusyIndicatorMock.VerifyAll();
        }
        public bool CanRetry(DelegateResult <TResult> delegateResult, CancellationToken cancellationToken)
        {
            if (_errorCount < int.MaxValue)
            {
                _errorCount += 1;
            }

            TimeSpan waitTimeSpan = _sleepDurationProvider(_errorCount, delegateResult, _context);

            _onRetry(delegateResult, waitTimeSpan, _context);

            SystemClock.Sleep(waitTimeSpan, cancellationToken);

            return(true);
        }
Example #6
0
        private Task <HttpResponseMessage> FallbackAction(
            DelegateResult <HttpResponseMessage> responseToFailedRequest,
            Context context,
            CancellationToken cancellationToken)
        {
            var uri         = responseToFailedRequest.Result.RequestMessage.RequestUri.ToString();
            var metalType   = uri.Contains("GOLD") ? Metal.Gold : Metal.Silver;
            var metalPrices = _metalsPricesProvider.Get(metalType).Result;

            HttpResponseMessage httpResponseMessage = new HttpResponseMessage(responseToFailedRequest.Result.StatusCode)
            {
                Content = new StringContent(metalPrices, Encoding.UTF8, "application/json")
            };

            return(Task.FromResult(httpResponseMessage));
        }
Example #7
0
    private static async Task LogFailure(ILogger logger, DelegateResult <HttpResponseMessage> result, TimeSpan timeSpan, int retryCount, Context context)
    {
        if (result.Exception != null)
        {
            logger.Warning(result.Exception, "An exception occurred on retry {RetryAttempt} for {PolicyKey} - Retrying in {SleepDuration}ms",
                           retryCount, context.PolicyKey, timeSpan.TotalMilliseconds);
        }
        else
        {
            var content = await result.Result.Content.ReadAsStringAsync();

            logger.Warning("A non success code {StatusCode} with reason {Reason} and content {Content} was received on retry {RetryAttempt} for {PolicyKey} - Retrying in {SleepDuration}ms",
                           (int)result.Result.StatusCode, result.Result.ReasonPhrase,
                           content, retryCount, context.PolicyKey, timeSpan.TotalMilliseconds);
        }
    }
Example #8
0
        public bool CanRetry(DelegateResult <TResult> delegateResult, CancellationToken cancellationToken)
        {
            _errorCount += 1;

            bool shouldRetry = _errorCount <= _retryCount;

            if (shouldRetry)
            {
                TimeSpan waitTimeSpan = _sleepDurationProvider(_errorCount, delegateResult, _context);

                _onRetry(delegateResult, waitTimeSpan, _errorCount, _context);

                SystemClock.Sleep(waitTimeSpan, cancellationToken);
            }

            return(shouldRetry);
        }
        public bool CanRetry(DelegateResult <TResult> delegateResult)
        {
            if (!_sleepDurationsEnumerator.MoveNext())
            {
                return(false);
            }

            _errorCount += 1;

            var currentTimeSpan = _sleepDurationsEnumerator.Current;

            _onRetry(delegateResult, currentTimeSpan, _errorCount, _context);

            SystemClock.Sleep(currentTimeSpan);

            return(true);
        }
Example #10
0
        public async Task <bool> CanRetryAsync(DelegateResult <TResult> delegateResult, CancellationToken cancellationToken, bool continueOnCapturedContext)
        {
            _errorCount += 1;

            bool shouldRetry = _errorCount <= _retryCount;

            if (shouldRetry)
            {
                TimeSpan waitTimeSpan = _sleepDurationProvider(_errorCount, _context);

                await _onRetryAsync(delegateResult, waitTimeSpan, _errorCount, _context).ConfigureAwait(continueOnCapturedContext);

                await SystemClock.SleepAsync(waitTimeSpan, cancellationToken).ConfigureAwait(continueOnCapturedContext);
            }

            return(shouldRetry);
        }
Example #11
0
        public async Task <bool> CanRetryAsync(DelegateResult <TResult> delegateResult, CancellationToken cancellationToken, bool continueOnCapturedContext)
        {
            if (!_sleepDurationsEnumerator.MoveNext())
            {
                return(false);
            }

            _errorCount += 1;

            var currentTimeSpan = _sleepDurationsEnumerator.Current;

            await _onRetryAsync(delegateResult, currentTimeSpan, _errorCount, _context).ConfigureAwait(continueOnCapturedContext);

            await SystemClock.SleepAsync(currentTimeSpan, cancellationToken).ConfigureAwait(continueOnCapturedContext);

            return(true);
        }
Example #12
0
        /// <summary>
        /// Tells Apizr to log retries plus some more actions
        /// </summary>
        /// <param name="result"></param>
        /// <param name="timeSpan"></param>
        /// <param name="retryCount"></param>
        /// <param name="context"></param>
        /// <param name="onRetry"></param>
        public static void OnLoggedRetry(DelegateResult <HttpResponseMessage> result, TimeSpan timeSpan, int retryCount, Context context, Action <DelegateResult <HttpResponseMessage>, TimeSpan, int, Context> onRetry)
        {
            if (context.TryGetLogHandler(out var logger))
            {
                if (result.Exception != null)
                {
                    logger.Write($"An exception occurred on retry {retryCount} for {context.PolicyKey}",
                                 result.Exception.ToString());
                }
                else
                {
                    logger.Write(
                        $"A non success code {(int) result.Result.StatusCode} was received on retry {retryCount} for {context.PolicyKey}");
                }
            }

            onRetry?.Invoke(result, timeSpan, retryCount, context);
        }
Example #13
0
        public void Should_not_call_fallbackAction_with_the_fault_if_fault_unhandled()
        {
            DelegateResult <ResultPrimitive> fallbackOutcome = null;

            Func <DelegateResult <ResultPrimitive>, Context, CancellationToken, ResultPrimitive> fallbackAction =
                (outcome, ctx, ct) => { fallbackOutcome = outcome; return(ResultPrimitive.Substitute); };

            Action <DelegateResult <ResultPrimitive>, Context> onFallback = (ex, ctx) => { };

            FallbackPolicy <ResultPrimitive> fallbackPolicy = Policy <ResultPrimitive>
                                                              .HandleResult(ResultPrimitive.Fault)
                                                              .Fallback(fallbackAction, onFallback);

            fallbackPolicy.Execute(() => { return(ResultPrimitive.FaultAgain); })
            .Should().Be(ResultPrimitive.FaultAgain);

            fallbackOutcome.Should().BeNull();
        }
        private void OnRetry(DelegateResult <HttpResponseMessage> wrappedResponse, TimeSpan timeSpan, int retryAttempt, Context context)
        {
            if (wrappedResponse.Exception != null)
            {
                logger.LogError(wrappedResponse.Exception, "Error with Heroes Profile Service");
            }

            if (wrappedResponse.Result != null)
            {
                logger.LogDebug($"retry attempt {retryAttempt}: {wrappedResponse.Result.StatusCode}: {wrappedResponse.Result.ReasonPhrase}");
            }

            if (wrappedResponse?.Result?.Headers?.RetryAfter != null)
            {
                TimeSpan retryAfter = wrappedResponse.Result.Headers.RetryAfter.Delta.Value;
                logger.LogWarning($"Setting retry-after to {retryAfter}");
                context["retry-after"] = retryAfter;
            }
        }
        public override void OnActionFailure(DelegateResult <TResult> outcome, Context context)
        {
            using (TimedLock.Lock(_lock))
            {
                _lastOutcome = outcome;

                if (_circuitState == CircuitState.HalfOpen)
                {
                    Break_NeedsLock(context);
                    return;
                }

                _count += 1;
                if (_count >= _exceptionsAllowedBeforeBreaking)
                {
                    Break_NeedsLock(context);
                }
            }
        }
 public static Task OnBreakDefault(DelegateResult <HttpResponseMessage> response, CircuitState state, TimeSpan duration, Context context, ILogger <AgonesCircuitDelegate> logger)
 {
     if (response.Result == null)
     {
         logger?.LogDebug($"OnBreak: Circuit cut, requests will not flow. State {state}; CorrelationId {context.CorrelationId}; Exception {response.Exception?.Message}");
     }
     else
     {
         if (response.Exception == null)
         {
             logger?.LogDebug($"OnBreak: Circuit cut, requests will not flow. State {state}; CorrelationId {context.CorrelationId}; StatusCode {response.Result?.StatusCode}; Reason {response.Result?.ReasonPhrase};");
         }
         else
         {
             logger?.LogDebug($"OnBreak: Circuit cut, requests will not flow. State {state}; CorrelationId {context.CorrelationId}; StatusCode {response.Result?.StatusCode}; Reason {response.Result?.ReasonPhrase}; Exception {response.Exception.Message}");
         }
     }
     return(Task.Delay(duration));
 }
        private async Task OnRetryAsync(DelegateResult <HttpResponseMessage> result, int attempt)
        {
            const int AccessTokenExpired  = 1;
            const int RefreshTokenExpired = 2;

            switch (attempt)
            {
            case AccessTokenExpired:
                await _getRefreshedToken().ConfigureAwait(false);

                break;

            case RefreshTokenExpired:
                throw new ExpiredRefreshTokenException(result.Exception);

            default:
                throw new InvalidOperationException($"Can't handle attempt number: {attempt.ToString()}", result.Exception);
            }
        }
        public async Task Should_not_call_fallbackAction_with_the_fault_if_fault_unhandled()
        {
            DelegateResult <ResultPrimitive> fallbackOutcome = null;

            Func <DelegateResult <ResultPrimitive>, Context, CancellationToken, Task <ResultPrimitive> > fallbackAction =
                (outcome, ctx, ct) => { fallbackOutcome = outcome; return(Task.FromResult(ResultPrimitive.Substitute)); };

            Func <DelegateResult <ResultPrimitive>, Context, Task> onFallback = (ex, ctx) => { return(TaskHelper.EmptyTask); };

            FallbackPolicy <ResultPrimitive> fallbackPolicy = Policy <ResultPrimitive>
                                                              .HandleResult(ResultPrimitive.Fault)
                                                              .FallbackAsync(fallbackAction, onFallback);

            var result = await fallbackPolicy.ExecuteAsync(() => { return(Task.FromResult(ResultPrimitive.FaultAgain)); });

            result.Should().Be(ResultPrimitive.FaultAgain);

            fallbackOutcome.Should().BeNull();
        }
        public void BusyIndicatorIsSetToIdleAfterTheInnerResultCompleted()
        {
            bool isInnerCompleted = false;

            BusyIndicatorMock.Setup(x => x.Idle())
                .Callback(() => Assert.IsTrue(isInnerCompleted, "BusyIndicator set busy to idle before inner result completed"));

            var inner = new DelegateResult(() => { });
            inner.Completed += (sender, args) => { isInnerCompleted = true; };
            var sut = new BusyResultDecorator(inner, "foo")
                .In(BusyIndicator);
            var waitHandle = new ManualResetEvent(false);
            sut.Completed += (sender, args) => waitHandle.Set();

            sut.Execute(null);
            waitHandle.WaitOne(3000);

            BusyIndicatorMock.VerifyAll();
        }
Example #20
0
        internal static async Task <TResult> ImplementationAsync <TResult>(
            Func <Context, CancellationToken, Task <TResult> > action,
            Context context,
            IEnumerable <ExceptionPredicate> shouldHandleExceptionPredicates,
            IEnumerable <ResultPredicate <TResult> > shouldHandleResultPredicates,
            Func <DelegateResult <TResult>, Context, Task> onFallbackAsync,
            Func <DelegateResult <TResult>, Context, CancellationToken, Task <TResult> > fallbackAction,
            CancellationToken cancellationToken,
            bool continueOnCapturedContext)
        {
            DelegateResult <TResult> delegateOutcome;

            try
            {
                cancellationToken.ThrowIfCancellationRequested();

                TResult result = await action(context, cancellationToken).ConfigureAwait(continueOnCapturedContext);

                if (!shouldHandleResultPredicates.Any(predicate => predicate(result)))
                {
                    return(result);
                }

                delegateOutcome = new DelegateResult <TResult>(result);
            }
            catch (Exception ex)
            {
                Exception handledException = shouldHandleExceptionPredicates
                                             .Select(predicate => predicate(ex))
                                             .FirstOrDefault(e => e != null);
                if (handledException == null)
                {
                    throw;
                }

                delegateOutcome = new DelegateResult <TResult>(handledException);
            }

            await onFallbackAsync(delegateOutcome, context).ConfigureAwait(continueOnCapturedContext);

            return(await fallbackAction(delegateOutcome, context, cancellationToken).ConfigureAwait(continueOnCapturedContext));
        }
        public void InnerResultIsExecutedOnWorkerThread()
        {
            int threadId = Thread.CurrentThread.ManagedThreadId;
            var waitHandle = new ManualResetEvent(false);
            int? innerThreadId = null;

            var inner = new DelegateResult(() =>
            {
                innerThreadId = Thread.CurrentThread.ManagedThreadId;
                waitHandle.Set();
            });

            var sut = new WorkerThreadResultDecorator(inner);

            sut.Execute(null);
            waitHandle.WaitOne(3000);

            Assert.IsNotNull(innerThreadId);
            Assert.AreNotEqual(threadId, innerThreadId.Value);
        }
Example #22
0
        public void InnerResultIsExecutedOnWorkerThread()
        {
            int threadId      = Thread.CurrentThread.ManagedThreadId;
            var waitHandle    = new ManualResetEvent(false);
            int?innerThreadId = null;

            var inner = new DelegateResult(() =>
            {
                innerThreadId = Thread.CurrentThread.ManagedThreadId;
                waitHandle.Set();
            });

            var sut = new WorkerThreadResultDecorator(inner);

            sut.Execute(null);
            waitHandle.WaitOne(3000);

            Assert.IsNotNull(innerThreadId);
            Assert.AreNotEqual(threadId, innerThreadId.Value);
        }
Example #23
0
        public void Should_call_fallbackAction_with_the_fault()
        {
            DelegateResult <ResultPrimitive> fallbackOutcome = null;

            Func <DelegateResult <ResultPrimitive>, Context, CancellationToken, ResultPrimitive> fallbackAction =
                (outcome, _, _) => { fallbackOutcome = outcome; return(ResultPrimitive.Substitute); };

            Action <DelegateResult <ResultPrimitive>, Context> onFallback = (_, _) => { };

            FallbackPolicy <ResultPrimitive> fallbackPolicy = Policy <ResultPrimitive>
                                                              .HandleResult(ResultPrimitive.Fault)
                                                              .Fallback(fallbackAction, onFallback);

            fallbackPolicy.Execute(() => ResultPrimitive.Fault)
            .Should().Be(ResultPrimitive.Substitute);

            fallbackOutcome.Should().NotBeNull();
            fallbackOutcome.Exception.Should().BeNull();
            fallbackOutcome.Result.Should().Be(ResultPrimitive.Fault);
        }
Example #24
0
        internal static TResult Implementation <TResult>(
            Func <Context, CancellationToken, TResult> action,
            Context context,
            CancellationToken cancellationToken,
            IEnumerable <ExceptionPredicate> shouldHandleExceptionPredicates,
            IEnumerable <ResultPredicate <TResult> > shouldHandleResultPredicates,
            Action <DelegateResult <TResult>, Context> onFallback,
            Func <DelegateResult <TResult>, Context, CancellationToken, TResult> fallbackAction)
        {
            DelegateResult <TResult> delegateOutcome;

            try
            {
                cancellationToken.ThrowIfCancellationRequested();

                TResult result = action(context, cancellationToken);

                if (!shouldHandleResultPredicates.Any(predicate => predicate(result)))
                {
                    return(result);
                }

                delegateOutcome = new DelegateResult <TResult>(result);
            }
            catch (Exception ex)
            {
                Exception handledException = shouldHandleExceptionPredicates
                                             .Select(predicate => predicate(ex))
                                             .FirstOrDefault(e => e != null);
                if (handledException == null)
                {
                    throw;
                }

                delegateOutcome = new DelegateResult <TResult>(handledException);
            }

            onFallback(delegateOutcome, context);

            return(fallbackAction(delegateOutcome, context, cancellationToken));
        }
Example #25
0
        internal static TResult Implementation <TResult>(
            Func <CancellationToken, TResult> action,
            CancellationToken cancellationToken,
            IEnumerable <ExceptionPredicate> shouldRetryExceptionPredicates,
            IEnumerable <ResultPredicate <TResult> > shouldRetryResultPredicates,
            Func <IRetryPolicyState <TResult> > policyStateFactory)
        {
            IRetryPolicyState <TResult> policyState = policyStateFactory();

            while (true)
            {
                cancellationToken.ThrowIfCancellationRequested();

                try
                {
                    DelegateResult <TResult> delegateOutcome = new DelegateResult <TResult>(action(cancellationToken));

                    if (!shouldRetryResultPredicates.Any(predicate => predicate(delegateOutcome.Result)))
                    {
                        return(delegateOutcome.Result);
                    }

                    if (!policyState.CanRetry(delegateOutcome, cancellationToken))
                    {
                        return(delegateOutcome.Result);
                    }
                }
                catch (Exception ex)
                {
                    if (!shouldRetryExceptionPredicates.Any(predicate => predicate(ex)))
                    {
                        throw;
                    }

                    if (!policyState.CanRetry(new DelegateResult <TResult>(ex), cancellationToken))
                    {
                        throw;
                    }
                }
            }
        }
Example #26
0
        public void BusyIndicatorIsSetToIdleAfterTheInnerResultCompleted()
        {
            bool isInnerCompleted = false;

            BusyIndicatorMock.Setup(x => x.Idle())
            .Callback(() => Assert.IsTrue(isInnerCompleted, "BusyIndicator set busy to idle before inner result completed"));

            var inner = new DelegateResult(() => { });

            inner.Completed += (sender, args) => { isInnerCompleted = true; };
            var sut = new BusyResultDecorator(inner, "foo")
                      .In(BusyIndicator);
            var waitHandle = new ManualResetEvent(false);

            sut.Completed += (sender, args) => waitHandle.Set();

            sut.Execute(null);
            waitHandle.WaitOne(3000);

            BusyIndicatorMock.VerifyAll();
        }
Example #27
0
        private static void WaitAndRetryAction(DelegateResult <HttpResponseMessage> response, TimeSpan retryTime)
        {
            var ex = response.Exception;

            if (ex != null)
            {
                Console.WriteLine($"重試,發生錯誤:{ex.Message},延遲 {retryTime} 後重試");
                return;
            }

            var result = response.Result;

            if (result != null)
            {
                var errorMsg = result.Content
                               .ReadAsStringAsync()
                               .GetAwaiter()
                               .GetResult();
                Console.WriteLine($"重試,發生錯誤:{errorMsg},延遲 {retryTime} 後重試");
            }
        }
        private static TimeSpan?GetServerWaitDuration(DelegateResult <HttpResponseMessage> response)
        {
            var retryAfter = response?.Result?.Headers?.RetryAfter;

            if (retryAfter == null)
            {
                return(null);
            }

            if (retryAfter.Delta.HasValue)             // Delta priority check, because its simple TimeSpan value
            {
                return(retryAfter.Delta.Value);
            }

            if (retryAfter.Date.HasValue)
            {
                return(retryAfter.Date.Value - DateTime.UtcNow);
            }

            return(null);            // when nothing was found
        }
Example #29
0
        public async Task Should_call_fallbackAction_with_the_fault()
        {
            DelegateResult <ResultPrimitive> fallbackOutcome = null;

            Func <DelegateResult <ResultPrimitive>, Context, CancellationToken, Task <ResultPrimitive> > fallbackAction =
                (outcome, _, _) => { fallbackOutcome = outcome; return(Task.FromResult(ResultPrimitive.Substitute)); };

            Func <DelegateResult <ResultPrimitive>, Context, Task> onFallback = (_, _) => TaskHelper.EmptyTask;

            var fallbackPolicy = Policy <ResultPrimitive>
                                 .HandleResult(ResultPrimitive.Fault)
                                 .FallbackAsync(fallbackAction, onFallback);

            var result = await fallbackPolicy.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Fault));

            result.Should().Be(ResultPrimitive.Substitute);

            fallbackOutcome.Should().NotBeNull();
            fallbackOutcome.Exception.Should().BeNull();
            fallbackOutcome.Result.Should().Be(ResultPrimitive.Fault);
        }
Example #30
0
        // Get info about the retry event
        // Returns a Named Tuple https://docs.microsoft.com/en-us/dotnet/csharp/tuples
        private (string message, string reason) GetRetryInfo(DelegateResult <HttpResponseMessage> result, TimeSpan timeSpan, int retryAttempt)
        {
            string reason                = null;
            string resourcePath          = null;
            string requestUrl            = null;
            string originalRequestUrl    = null;
            string originalRequestMethod = null;

            if (result.Exception != null)
            {
                reason                = $"Exception: {result.Exception.Message}";
                resourcePath          = result.Exception.GetResourcePath();
                requestUrl            = result.Exception.GetRequestUrl();
                originalRequestUrl    = result.Exception.GetOriginalRequestUrl();
                originalRequestMethod = result.Exception.GetOriginalRequestMethod();
            }
            else if (result.Result != null)     //result.Result is a HttpResponseMessage
            {
                reason                = $"StatusCode: {(int)result.Result.StatusCode} ({result.Result.StatusCode.ToString()})";
                resourcePath          = result.Result.RequestMessage.GetResourcePath();
                requestUrl            = result.Result?.RequestMessage?.RequestUri?.AbsoluteUri?.ToString();
                originalRequestUrl    = result.Result.RequestMessage.GetOriginalRequestUrl();
                originalRequestMethod = result.Result.RequestMessage.GetOriginalRequestMethod();
            }
            // Detect if we were redirected
            bool isRedirected = false;

            if (!String.IsNullOrEmpty(requestUrl) && requestUrl != originalRequestUrl)
            {
                isRedirected = true;
            }
            string redirected = isRedirected ? " Redirected" : "";
            string message    = $"{DateTime.Now.ToString()} : Failed{redirected} {originalRequestMethod} Request to Resource: {resourcePath} {redirected}Url: {requestUrl} failed with {reason}. \nWaiting {timeSpan} ({timeSpan.TotalSeconds} seconds) before retrying...";

            if (retryAttempt > 1)
            {
                message = $"{message}. Retry attempts: {retryAttempt - 1}";
            }
            return(message, reason);
        }
        internal static async Task <TResult> ImplementationAsync <TResult>(
            Func <CancellationToken, Task <TResult> > action,
            Context context,
            IEnumerable <ExceptionPredicate> shouldHandleExceptionPredicates,
            IEnumerable <ResultPredicate <TResult> > shouldHandleResultPredicates,
            ICircuitController <TResult> breakerController,
            CancellationToken cancellationToken,
            bool continueOnCapturedContext)
        {
            cancellationToken.ThrowIfCancellationRequested();

            breakerController.OnActionPreExecute();

            try
            {
                DelegateResult <TResult> delegateOutcome = new DelegateResult <TResult>(await action(cancellationToken).ConfigureAwait(continueOnCapturedContext));

                if (shouldHandleResultPredicates.Any(predicate => predicate(delegateOutcome.Result)))
                {
                    breakerController.OnActionFailure(delegateOutcome, context);
                }
                else
                {
                    breakerController.OnActionSuccess(context);
                }

                return(delegateOutcome.Result);
            }
            catch (Exception ex)
            {
                if (!shouldHandleExceptionPredicates.Any(predicate => predicate(ex)))
                {
                    throw;
                }

                breakerController.OnActionFailure(new DelegateResult <TResult>(ex), context);

                throw;
            }
        }
Example #32
0
        public void Should_call_fallbackAction_with_the_fault_when_execute_and_capture()
        {
            DelegateResult <ResultPrimitive> fallbackOutcome = null;

            Func <DelegateResult <ResultPrimitive>, Context, CancellationToken, ResultPrimitive> fallbackAction =
                (outcome, ctx, ct) => { fallbackOutcome = outcome; return(ResultPrimitive.Substitute); };

            Action <DelegateResult <ResultPrimitive>, Context> onFallback = (ex, ctx) => { };

            FallbackPolicy <ResultPrimitive> fallbackPolicy = Policy <ResultPrimitive>
                                                              .HandleResult(ResultPrimitive.Fault)
                                                              .Fallback(fallbackAction, onFallback);

            var result = fallbackPolicy.ExecuteAndCapture(() => { return(ResultPrimitive.Fault); });

            result.Should().NotBeNull();
            result.Result.Should().Be(ResultPrimitive.Substitute);

            fallbackOutcome.Should().NotBeNull();
            fallbackOutcome.Exception.Should().BeNull();
            fallbackOutcome.Result.Should().Be(ResultPrimitive.Fault);
        }
        private async Task GetAuthToken(DelegateResult <HttpResponseMessage> result, int retryCount)
        {
            if (_accessToken.Value != null && (int)DateTime.UtcNow.Subtract(_accessToken.Updated).TotalSeconds < _accessToken.ExpiresIn / 2)
            {
                return;
            }

            await _getTokenLocker.LockAsync(async() =>
            {
                if (_accessToken.Value != null && (int)DateTime.UtcNow.Subtract(_accessToken.Updated).TotalSeconds < _accessToken.ExpiresIn / 2)
                {
                    return;
                }

                await this.ActualizeToken(new ClientCredentialsTokenRequest
                {
                    ClientId     = _clientConfiguration.ClientId,
                    ClientSecret = _clientConfiguration.ClientSecret,
                    GrantType    = OidcConstants.GrantTypes.ClientCredentials
                });
            });
        }
Example #34
0
        public override void OnActionFailure(DelegateResult <TResult> outcome, Context context)
        {
            using (TimedLock.Lock(_lock))
            {
                _lastOutcome = outcome;

                if (_circuitState == CircuitState.HalfOpen)
                {
                    Break_NeedsLock(context);
                    return;
                }

                _metrics.IncrementFailure_NeedsLock();
                var healthCount = _metrics.GetHealthCount_NeedsLock();

                int throughput = healthCount.Total;
                if (throughput >= _minimumThroughput && ((double)healthCount.Failures) / throughput >= _failureThreshold)
                {
                    Break_NeedsLock(context);
                }
            }
        }
        public void DecoratorDoesntCompleteOnWorkerThreadWhenContextIsGiven()
        {
            var waitHandle = new ManualResetEvent(false);
            var sendInvoked = false;
            var contextMock = new Mock<SynchronizationContext>();
            contextMock.Setup(x => x.Send(It.IsAny<SendOrPostCallback>(), It.IsAny<object>()))
                .Callback<SendOrPostCallback, object>((cb, args) =>
                {
                    Assert.IsInstanceOf<ResultCompletionEventArgs>(args);
                    sendInvoked = true;
                    waitHandle.Set();
                });
            SynchronizationContext.SetSynchronizationContext(contextMock.Object);

            var inner = new DelegateResult(() => { });
            var sut = new WorkerThreadResultDecorator(inner);

            sut.Execute(null);
            waitHandle.WaitOne(3000);

            Assert.IsTrue(sendInvoked);
        }
Example #36
0
 protected static void CreateSut(Action action)
 {
     Sut = new DelegateResult(action);
     Sut.Completed += (sender, args) => CompletionArgs = args;
 }
Example #37
0
        public IEnumerable<IResult> Import()
        {
            var openFileResult = new OpenFileResult()
                    .FilterFiles(x => x.AddFilter("csv", isDefault: true).WithDescription("CSV Datei"))
                    .In(Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments));

            yield return openFileResult
                .Rescue().With(coroutine: ImportRescue);

            var clearBeforeQuestion = new Question("Frage", "Aktuelle Liste vor dem Import verwerfen?", Answer.Yes, Answer.No);
            yield return clearBeforeQuestion.AsResult();

            var importResult = new DelegateResult(() =>
                                                 {
                                                     if (clearBeforeQuestion.GivenResponse == Answer.Yes)
                                                     {
                                                         BarcodeManager.Clear();
                                                     }
                                                     foreach (var barcode in CsvImporter.Import(openFileResult.FileName))
                                                     {
                                                         BarcodeManager.Import(barcode);
                                                     }
                                                 });

            yield return importResult
                .Rescue().With(coroutine: ImportRescue);
        }