Esempio n. 1
0
    public async Task Wait()
    {
        try
        {
            IsRunning = true;

            await RunAsync(Enumerate(), async task =>
            {
                _running++;
                try
                {
                    _cancellation.Token.ThrowIfCancellationRequested();
                    _onStart?.Invoke(task);
                    var result = await _resiliencePolicy.ExecuteAndCaptureAsync(task);
                    if (result.Outcome == OutcomeType.Failure)
                    {
                        if (!IsCancelationException(result.FinalException))
                        {
                            _onError?.Invoke(task, result.FinalException);
                        }
                    }
                    else
                    {
                        _onSuccess?.Invoke(task);
                    }
                }
                catch (Exception e)
                {
                    if (!IsCancelationException(e))
                    {
                        _onError?.Invoke(task, e);
                    }
                }
                finally
                {
                    _running--;
                }
            }, _maxDegreeOfParallelism);
        }
        catch (Exception e) when(!IsCancelationException(e))
        {
            _logger?.LogError(e, e.Message);
            throw;
        }
        finally
        {
            IsRunning = false;
        }
    }
Esempio n. 2
0
        public async Task Outermost_policy_not_handling_exception_even_if_inner_policies_do_should_report_as_unhandled_exception()
        {
            var innerHandlingDBZE = Policy
                                    .Handle <DivideByZeroException>()
                                    .CircuitBreakerAsync(1, TimeSpan.Zero);
            var outerHandlingANE = Policy
                                   .Handle <ArgumentNullException>()
                                   .CircuitBreakerAsync(1, TimeSpan.Zero);
            AsyncPolicyWrap wrap = outerHandlingANE.WrapAsync(innerHandlingDBZE);

            PolicyResult executeAndCaptureResultOnPolicyWrap =
                await wrap.ExecuteAndCaptureAsync(() => { throw new DivideByZeroException(); });

            executeAndCaptureResultOnPolicyWrap.Outcome.Should().Be(OutcomeType.Failure);
            executeAndCaptureResultOnPolicyWrap.FinalException.Should().BeOfType <DivideByZeroException>();
            executeAndCaptureResultOnPolicyWrap.ExceptionType.Should().Be(ExceptionType.Unhandled);
        }
Esempio n. 3
0
        //=========================== QSFP

        /// <summary>
        ///  Reads an SFF8636 register.
        ///
        /// Retries and Timeout set by policy.
        /// </summary>
        /// <param name="reg"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        ///
        public async Task <dynamic> GetRegAsync(Sff8636 reg, CancellationToken cancellationToken = default)
        {
            var policyWrapResults = await _policyWrap.ExecuteAndCaptureAsync(async (context, ct) =>
            {
                ct.ThrowIfCancellationRequested();

                SetPage(reg.Register.Page);
                var readData = await I2C.I2C_RandomReadAsync(Sff8636.I2CAddress, reg.Register.Address, reg.Register.Size).ConfigureAwait(false);
                var res      = ConvertData(reg, readData);
                return(res);
            }, new Dictionary <string, object>() { { $"{GetCaller()}", $"{reg.Name}({reg.Page}.{reg.Address})" } }, cancellationToken : cancellationToken);

            if (policyWrapResults.Outcome == OutcomeType.Failure)
            {
                throw policyWrapResults.FinalException;
            }

            return(policyWrapResults.Result);
        }
        public async Task DeleteExpiredShoppingCarts()
        {
            var olderThanUtc = DateTime.UtcNow.AddDays(-30);

            var expiredCarts = new List <ShoppingCart>();

            await _unitOfWork.RunInTrunsaction(async (con, tran) =>
            {
                var sqlSelectQuery = @"
                    SELECT TOP 100 *
                    FROM ShoppingCart
                    WHERE LatestUpdatedOn <= @olderThanUtc";

                expiredCarts.AddRange(await con.QueryAsync <ShoppingCart>(sqlSelectQuery, new { olderThanUtc }, tran));

                var expiredCartIds = expiredCarts.Select(x => x.Id).ToArray();

                var sqlDeleteQuery = @"
                    DELETE
                    FROM ShoppingCart
                    WHERE Id IN @Ids";

                return(await con.ExecuteAsync(sqlDeleteQuery, new { Ids = expiredCartIds }, tran));
            });

            // ignore errors, or use repeatable jobs (persist storage)
            foreach (var cart in expiredCarts)
            {
                var content = new StringContent(JsonSerializer.Serialize(cart), Encoding.Default, "application/json");

                var client = _httpClientFactory.CreateClient();

                await _webhookApiPolicy.ExecuteAndCaptureAsync(async ct =>
                                                               await client.PostAsync(_onDeleteWebhookUrl, content, ct),
                                                               CancellationToken.None);
            }
        }
Esempio n. 5
0
        public async Task Outermost_generic_policy_not_handling_result_even_if_inner_policies_do_should_not_report_as_handled()
        {
            var innerHandlingFaultAgain = Policy
                                          .HandleResult(ResultPrimitive.FaultAgain)
                                          .CircuitBreakerAsync(1, TimeSpan.Zero);
            var outerHandlingFault = Policy
                                     .HandleResult(ResultPrimitive.Fault)
                                     .CircuitBreakerAsync(1, TimeSpan.Zero);
            AsyncPolicyWrap <ResultPrimitive> wrap = outerHandlingFault.WrapAsync(innerHandlingFaultAgain);

            PolicyResult <ResultPrimitive> executeAndCaptureResultOnPolicyWrap = await wrap.ExecuteAndCaptureAsync(() => Task.FromResult(ResultPrimitive.FaultAgain));

            executeAndCaptureResultOnPolicyWrap.Outcome.Should().Be(OutcomeType.Successful);
            executeAndCaptureResultOnPolicyWrap.FinalHandledResult.Should().Be(default(ResultPrimitive));
            executeAndCaptureResultOnPolicyWrap.FaultType.Should().BeNull();
            executeAndCaptureResultOnPolicyWrap.FinalException.Should().BeNull();
            executeAndCaptureResultOnPolicyWrap.ExceptionType.Should().BeNull();
        }
Esempio n. 6
0
        public async Task Outermost_generic_policy_handling_result_should_report_as_PolicyWrap_handled_result()
        {
            var innerHandlingFaultAgain = Policy
                                          .HandleResult(ResultPrimitive.FaultAgain)
                                          .CircuitBreakerAsync(1, TimeSpan.Zero);
            var outerHandlingFault = Policy
                                     .HandleResult(ResultPrimitive.Fault)
                                     .CircuitBreakerAsync(1, TimeSpan.Zero);
            AsyncPolicyWrap <ResultPrimitive> wrap = outerHandlingFault.WrapAsync(innerHandlingFaultAgain);

            PolicyResult <ResultPrimitive> executeAndCaptureResultOnPolicyWrap = await wrap.ExecuteAndCaptureAsync(() => Task.FromResult(ResultPrimitive.Fault));

            executeAndCaptureResultOnPolicyWrap.Outcome.Should().Be(OutcomeType.Failure);
            executeAndCaptureResultOnPolicyWrap.FaultType.Should().Be(FaultType.ResultHandledByThisPolicy);
            executeAndCaptureResultOnPolicyWrap.FinalHandledResult.Should().Be(ResultPrimitive.Fault);
            executeAndCaptureResultOnPolicyWrap.FinalException.Should().BeNull();
            executeAndCaptureResultOnPolicyWrap.ExceptionType.Should().BeNull();
        }
Esempio n. 7
0
        public async Task Outermost_generic_policy_handling_exception_should_report_as_PolicyWrap_handled_exception()
        {
            var innerHandlingDBZE = Policy <ResultPrimitive>
                                    .Handle <DivideByZeroException>()
                                    .CircuitBreakerAsync(1, TimeSpan.Zero);

            var outerHandlingANE = Policy <ResultPrimitive>
                                   .Handle <ArgumentNullException>()
                                   .CircuitBreakerAsync(1, TimeSpan.Zero);

            AsyncPolicyWrap <ResultPrimitive> wrap = outerHandlingANE.WrapAsync(innerHandlingDBZE);

            PolicyResult <ResultPrimitive> executeAndCaptureResultOnPolicyWrap = await wrap.ExecuteAndCaptureAsync(() => { throw new ArgumentNullException(); });

            executeAndCaptureResultOnPolicyWrap.Outcome.Should().Be(OutcomeType.Failure);
            executeAndCaptureResultOnPolicyWrap.FinalException.Should().BeOfType <ArgumentNullException>();
            executeAndCaptureResultOnPolicyWrap.ExceptionType.Should().Be(ExceptionType.HandledByThisPolicy);
            executeAndCaptureResultOnPolicyWrap.FaultType.Should().Be(FaultType.ExceptionHandledByThisPolicy);
        }