Пример #1
1
        public static async Task Insert(CloudTable table)
        {
            CustomerEntity customer1 = new CustomerEntity("Harp", "Walters")
            {
                Email = "*****@*****.**",
                PhoneNumber = "425-555-0101"
            };
            CustomerEntity customer2 = new CustomerEntity("Harp", "Ben")
            {
                Email = "*****@*****.**",
                PhoneNumber = "425-555-0102"
            };
            TableBatchOperation batchOperation = new TableBatchOperation();
            // Create the TableOperation object that inserts the customer entity.
            TableOperation insertOperation = TableOperation.Insert(customer1);
            batchOperation.Insert(customer1);
            batchOperation.Insert(customer2);
            // Execute the insert operation.

            Incremental retryStrategy = new Incremental(5, TimeSpan.FromSeconds(1),
   TimeSpan.FromSeconds(2));
            ExponentialBackoff retryStrategy2=new ExponentialBackoff(5,TimeSpan.FromSeconds(1),TimeSpan.FromSeconds(5),TimeSpan.FromSeconds(2));
            TimeSpan back = TimeSpan.FromSeconds(31);
 
            // Define your retry policy using the retry strategy and the Azure storage
            // transient fault detection strategy.
            RetryPolicy<StorageTransientErrorDetectionStrategy> retryPolicy =
              new RetryPolicy<StorageTransientErrorDetectionStrategy>(retryStrategy);

            RetryPolicy<StorageTransientErrorDetectionStrategy> r =
                new RetryPolicy<StorageTransientErrorDetectionStrategy>(retryStrategy2);
            // Receive notifications about retries.
            retryPolicy.Retrying += (sender, args) =>
            {
                Console.WriteLine("Information");
                // Log details of the retry.
                var msg = String.Format("Retry - Count:{0}, Delay:{1}, Exception:{2}",
                    args.CurrentRetryCount, args.Delay, args.LastException);
                Console.WriteLine(msg, "Information");
            };

            try
            {
                // Do some work that may result in a transient fault.
              await retryPolicy.ExecuteAsync(
                  () => table.ExecuteBatchAsync(batchOperation));
            }
            catch (Exception e)
            {
                var z = e;
            }
            Console.ReadLine();












          /*  // Create a new customer entity.
            CustomerEntity customer1 = new CustomerEntity("Harp", "Walters")
            {
                Email = "*****@*****.**",
                PhoneNumber = "425-555-0101"
            };
            CustomerEntity customer2 = new CustomerEntity("Harp", "Ben")
            {
                Email = "*****@*****.**",
                PhoneNumber = "425-555-0102"
            };
            TableBatchOperation batchOperation = new TableBatchOperation();
            // Create the TableOperation object that inserts the customer entity.
            TableOperation insertOperation = TableOperation.Insert(customer1);
            batchOperation.Insert(customer1);
            batchOperation.Insert(customer2);
            // Execute the insert operation.
            try
            {
                IList<TableResult> z = await table.ExecuteBatchAsync(batchOperation);
                foreach (var i in z)
                {
                    CustomerEntity y = (CustomerEntity)i.Result;
                    Console.WriteLine(y.PartitionKey);
                }
                var x = z;
            }
            catch (StorageException e)
            {

                var z = e.RequestInformation.HttpStatusCode;
                var zz = 3;
            }*/
            
        }
        async Task <T> IQueryStore.GetAsync <T>(string key)
        {
            var filterBuilder = Builders <T> .Filter;

            var filter = filterBuilder.Eq(d => d.Id, key);

            var collection = GetCollection <T>();
            var result     = await RetryPolicy.ExecuteAsync(_ =>
                                                            collection.Find(filter).FirstOrDefaultAsync(),
                                                            new Context(nameof(IQueryStore.GetAsync)));

            return(result);
        }
Пример #3
0
        public async Task <int> ExecuteAsync(ISqlCommand command)
        {
            return(await RetryPolicy.ExecuteAsync(async() =>
            {
                await OpenConnectionAsync();

                var dbCommand = CreateTextCommand(command) as DbCommand;

                return await dbCommand
                .ExecuteNonQueryAsync()
                .ConfigureAwait(false);
            }));
        }
Пример #4
0
        /// <summary>
        /// Executes the with retries.
        /// </summary>
        /// <typeparam name="T">Generic parameter for return type.</typeparam>
        /// <param name="func">The function.</param>
        /// <param name="conversation">The conversation.</param>
        /// <returns>Task operation result.</returns>
        private static async Task <T> ExecuteWithRetries <T>(Func <Task <T> > func, IConversations conversation)
        {
            RetryPolicy retryPolicy;

            if (retryStrategyMap.TryGetValue(conversation, out retryPolicy))
            {
                return(await retryPolicy.ExecuteAsync(func));
            }
            else
            {
                return(await defaultRetryPolicy.ExecuteAsync(func));
            }
        }
        Task IQueryStore.DeleteAsync <T>(string typeName, string key)
        {
            var collection = GetCollection <T>();

            var filterBuilder = Builders <T> .Filter;

            var filter = filterBuilder.Eq(d => d.ViewType, typeName)
                         & filterBuilder.Eq(d => d.Id, key);

            return(RetryPolicy.ExecuteAsync(_ =>
                                            collection.DeleteOneAsync(filter),
                                            new Context(nameof(IQueryStore.DeleteAsync))));
        }
Пример #6
0
        Task IQueryStore.UpsertAsync <T>(T item)
        {
            var collection = GetCollection <T>();

            var filterBuilder = Builders <T> .Filter;

            var filter = filterBuilder.Eq(d => d.ViewType, item.ViewType)
                         & filterBuilder.Eq(d => d.Id, item.Id);

            return(RetryPolicy.ExecuteAsync(context => collection.ReplaceOneAsync(filter, item, new UpdateOptions {
                IsUpsert = true
            }), new Context(nameof(IQueryStore.UpsertAsync))));
        }
Пример #7
0
        public async Task <long> DeleteManyAsync <T, T1>(string typeName, Expression <Func <T, T1> > property, T1 value) where T : QueryProjectionBase
        {
            var filterBuilder = Builders <T> .Filter;

            var filter = filterBuilder.Eq(d => d.ViewType, typeName)
                         & filterBuilder.Lt(property, value);

            var collection = GetCollection <T>();

            var result = await RetryPolicy.ExecuteAsync(context => collection.DeleteManyAsync(filter), new Context(nameof(IQueryStore.DeleteManyAsync)));

            return(result.DeletedCount);
        }
 public async Task SendToChat(string chatId, string text)
 {
     try
     {
         await RetryPolicy.ExecuteAsync(async() =>
                                        await _telegramBotClient.SendTextMessageAsync(chatId, text, ParseMode.Html));
     }
     catch (Exception ex)
     {
         _logger.LogError(ex, "Failed to send message to telegram to chat. {@ChatId}. {@ExMessage}", chatId,
                          ex.Message);
     }
 }
        public async Task <IEnumerable <long> > GetAllVacancyReferencesAsync()
        {
            var filter = Builders <Vacancy> .Filter.Empty;

            var collection = GetCollection <Vacancy>();

            var result = await RetryPolicy.ExecuteAsync(_ =>
                                                        collection.Distinct(v => v.VacancyReference, filter)
                                                        .ToListAsync(),
                                                        new Context(nameof(GetAllVacancyReferencesAsync)));

            return(result.Where(r => r.HasValue).Select(r => r.Value));
        }
        private async Task <Vacancy> FindVacancy <TField>(Expression <Func <Vacancy, TField> > expression, TField value)
        {
            var filter = Builders <Vacancy> .Filter.Eq(expression, value);

            var options = new FindOptions <Vacancy> {
                Limit = 1
            };

            var collection = GetCollection <Vacancy>();
            var result     = await RetryPolicy.ExecuteAsync(context => collection.FindAsync(filter, options), new Context(nameof(FindVacancy)));

            return(result.SingleOrDefault());
        }
        public async Task <List <T> > GetStaleDocumentsAsync <T>(string typeName, DateTime documentsNotAccessedSinceDate) where T : QueryProjectionBase
        {
            var filterBuilder = Builders <T> .Filter;

            var filter = filterBuilder.Eq(d => d.ViewType, typeName)
                         & filterBuilder.Lt(d => d.LastUpdated, documentsNotAccessedSinceDate);

            var collection = GetCollection <T>();

            return(await RetryPolicy.ExecuteAsync(_ =>
                                                  collection.Find(filter).ToListAsync(),
                                                  new Context(nameof(IQueryStore.UpsertAsync))));
        }
        public async Task <BrokeredMessage> BlockingReceiveAsync()
        {
            while (true)
            {
                var message =
                    await RetryPolicy.ExecuteAsync(async() => await Client.ReceiveAsync(TimeSpan.FromMinutes(60)));

                if (message != null)
                {
                    return(message);
                }
            }
        }
        public async Task <EmployerProfile> GetAsync(string employerAccountId, long legalEntityId)
        {
            var builder = Builders <EmployerProfile> .Filter;
            var filter  = builder.Eq(x => x.Id, EmployerProfile.GetId(employerAccountId, legalEntityId));

            var collection = GetCollection <EmployerProfile>();

            var result = await RetryPolicy.ExecuteAsync(_ =>
                                                        collection.Find(filter).SingleOrDefaultAsync(),
                                                        new Context(nameof(GetAsync)));

            return(result);
        }
        public async Task <BlockedOrganisation> GetByOrganisationIdAsync(string organisationId)
        {
            var builder    = Builders <BlockedOrganisation> .Filter;
            var filter     = builder.Eq(bo => bo.OrganisationId, organisationId);
            var collection = GetCollection <BlockedOrganisation>();

            var result = await RetryPolicy.ExecuteAsync(_ =>
                                                        collection.Find(filter)
                                                        .SortByDescending(bo => bo.UpdatedDate).FirstOrDefaultAsync(),
                                                        new Context(nameof(GetByOrganisationIdAsync)));

            return(result);
        }
Пример #15
0
        private async Task <List <VacancyReview> > GetVacancyReviewsAsync(FilterDefinition <VacancyReview> filter)
        {
            var collection = GetCollection <VacancyReview>();

            var result = await RetryPolicy
                         .ExecuteAsync(
                context => collection
                .Find(filter)
                .ToListAsync(),
                new Context(nameof(GetLatestReviewByReferenceAsync)));

            return(result);
        }
Пример #16
0
        public async Task <IEnumerable <dynamic> > FindAsync(ISqlCommand command)
        {
            return(await RetryPolicy.ExecuteAsync(async() =>
            {
                await OpenConnectionAsync();

                var dbCommand = CreateTextCommand(command) as DbCommand;
                var reader = await dbCommand.ExecuteReaderAsync()
                             .ConfigureAwait(false);

                return await reader.Map()
                .ConfigureAwait(false);
            }));
        }
Пример #17
0
        public async Task <string> GetJSON(string url, string auth = null)
        {
            using (var client = new HttpClient())
            {
                client.Timeout = TimeSpan.FromSeconds(15);
                client.DefaultRequestHeaders.Connection.Add("close");
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Add("User-Agent", "SnekNet Backend v0.1");

                if (auth != null)
                {
                    client.DefaultRequestHeaders.Add("Authorization", auth);
                }

                return(await retryPolicy.ExecuteAsync(async() =>
                {
                    using (var response = await client.GetAsync(url))
                    {
                        return await GetResponseBody(response);
                    }
                }));
            }
        }
Пример #18
0
        public async Task <IEnumerable <Vacancy> > GetProviderOwnedVacanciesForLegalEntityAsync(long ukprn, long legalEntityId)
        {
            var filter = GetProviderOwnedVacanciesForLegalEntityFilter(ukprn, legalEntityId);

            var collection = GetCollection <Vacancy>();

            var result = await RetryPolicy.ExecuteAsync(_ =>
                                                        collection.Aggregate()
                                                        .Match(filter)
                                                        .ToListAsync(),
                                                        new Context(nameof(GetProviderOwnedVacanciesForLegalEntityAsync)));

            return(result);
        }
Пример #19
0
        public virtual Task <IEnumerable <Student> > GetStudents()
        {
            return(_serverRetryPolicy.ExecuteAsync(async() =>
            {
                var serverUrl = _serverUrls[_currentConfigIndex];
                var requestPath = $"{serverUrl}api/students";

                _logger.LogInformation($"Making request to {requestPath}");
                var response = await _apiClient.GetAsync(requestPath).ConfigureAwait(false);
                var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                return JsonConvert.DeserializeObject <IEnumerable <Student> >(content);
            }));
        }
Пример #20
0
        public async Task <List <T> > GetForVacancyAsync <T>(long vacancyReference)
        {
            var filter = Builders <T> .Filter.Eq(VacancyReference, vacancyReference);

            var collection = GetCollection <T>();

            var result = await RetryPolicy.ExecuteAsync(_ =>
                                                        collection.Find(filter)
                                                        .Project <T>(GetProjection <T>())
                                                        .ToListAsync(),
                                                        new Context(nameof(GetForVacancyAsync)));

            return(result);
        }
Пример #21
0
        public async Task <ApplicationReview> GetAsync(long vacancyReference, Guid candidateId)
        {
            var builder = Builders <ApplicationReview> .Filter;
            var filter  = builder.Eq(r => r.VacancyReference, vacancyReference) &
                          builder.Eq(r => r.CandidateId, candidateId);

            var collection = GetCollection <ApplicationReview>();

            var result = await RetryPolicy.ExecuteAsync(_ =>
                                                        collection.Find(filter).SingleOrDefaultAsync(),
                                                        new Context(nameof(GetAsync)));

            return(result);
        }
Пример #22
0
 public void SendAsync(Func <BrokeredMessage> messageFactory, Action successCallback, Action <Exception> exceptionCallback)
 {
     retryPolicy.ExecuteAsync(() => this.topicClient.SendAsync(messageFactory())).ContinueWith(r =>
     {
         if (r.Exception != null)
         {
             exceptionCallback(r.Exception);
         }
         else
         {
             successCallback();
         }
     });
 }
        public async Task <List <BlockedOrganisationSummary> > GetAllBlockedEmployersAsync()
        {
            var collection = GetCollection <BlockedOrganisation>();
            var result     = await RetryPolicy.ExecuteAsync(async _ =>
            {
                var pipeline   = BlockedOrganisationsAggQueryBuilder.GetBlockedEmployersAggregateQueryPipeline();
                var mongoQuery = pipeline.ToJson();
                var aggResults = await collection.AggregateAsync <BlockedOrganisationSummary>(pipeline);
                return(await aggResults.ToListAsync());
            },
                                                            new Context(nameof(GetAllBlockedProvidersAsync)));

            return(result.ToList());
        }
Пример #24
0
        public async Task <int> GetApprovedCountAsync(string submittedByUserId)
        {
            var filterBuilder = Builders <VacancyReview> .Filter;
            var filter        = filterBuilder.Eq(r => r.SubmittedByUser.UserId, submittedByUserId) &
                                filterBuilder.Eq(r => r.Status, ReviewStatus.Closed) &
                                filterBuilder.Eq(r => r.ManualOutcome, ManualQaOutcome.Approved);

            var collection = GetCollection <VacancyReview>();
            var count      = await RetryPolicy.ExecuteAsync(context => collection
                                                            .CountDocumentsAsync(filter),
                                                            new Context(nameof(GetApprovedCountAsync)));

            return((int)count);
        }
Пример #25
0
        public static void Throws_WhenExceptionIsNotRetryable()
        {
            var fake = Substitute.For<IFake>();
            var ex = new Exception();
            fake.DoSomething().ThrowsTask(ex);
            fake.IsRetryable(Arg.Any<int>(), ex).Returns(false);
            var logger = Substitute.For<ILog>();
            var delay = Substitute.For<Delay>();
            var retryHandler = new RetryPolicy(logger, 100, 10, delay);

            var actualEx = Record.Exception(() => retryHandler.ExecuteAsync(fake.DoSomething, fake.IsRetryable).GetAwaiter().GetResult());

            Assert.Equal(ex, actualEx);
        }
Пример #26
0
        public static async Task <int> SaveChangesAsync(
            this DbContext context, Func <IEnumerable <DbEntityEntry>, Task> resolveConflictsAsync, RetryStrategy retryStrategy)
        {
            context.NotNull(nameof(context));
            resolveConflictsAsync.NotNull(nameof(resolveConflictsAsync));
            retryStrategy.NotNull(nameof(retryStrategy));

            RetryPolicy retryPolicy = new RetryPolicy(
                new TransientDetection <DbUpdateConcurrencyException>(), retryStrategy);

            retryPolicy.Retrying += (sender, e) =>
                                    resolveConflictsAsync(((DbUpdateConcurrencyException)e.LastException).Entries).Wait();
            return(await retryPolicy.ExecuteAsync(async() => await context.SaveChangesAsync()));
        }
Пример #27
0
        internal void CopyFile(
            [Required, Description("Machine to copy from")] string host,
            [Required, Description("Expected content hash")] string hashString,
            [Required, Description("Path to destination file")] string destinationPath,
            [Description("Whether or not GZip is enabled"), DefaultValue(false)] bool useCompressionForCopies,
            [Description("File name where the GRPC port can be found when using cache service. 'CASaaS GRPC port' if not specified")] string grpcPortFileName,
            [Description("The GRPC port"), DefaultValue(0)] int grpcPort)
        {
            Initialize();

            var context     = new Context(_logger);
            var retryPolicy = new RetryPolicy(
                new TransientErrorDetectionStrategy(),
                new FixedInterval("RetryInterval", (int)_retryCount, TimeSpan.FromSeconds(_retryIntervalSeconds), false));

            if (grpcPort == 0)
            {
                grpcPort = Helpers.GetGrpcPortFromFile(_logger, grpcPortFileName);
            }

            if (!ContentHash.TryParse(hashString, out var hash))
            {
                throw new CacheException($"Invalid content hash string provided: {hashString}");
            }

            try
            {
                using (var clientCache = new GrpcCopyClientCache(context))
                    using (var rpcClientWrapper = clientCache.CreateAsync(host, grpcPort, useCompressionForCopies).GetAwaiter().GetResult())
                    {
                        var rpcClient = rpcClientWrapper.Value;
                        var finalPath = new AbsolutePath(destinationPath);

                        // This action is synchronous to make sure the calling application doesn't exit before the method returns.
                        var copyFileResult = retryPolicy.ExecuteAsync(() => rpcClient.CopyFileAsync(context, hash, finalPath, options: null, CancellationToken.None)).Result;
                        if (!copyFileResult.Succeeded)
                        {
                            throw new CacheException(copyFileResult.ErrorMessage);
                        }
                        else
                        {
                            _logger.Debug($"Copy of {hashString} to {finalPath} was successful");
                        }
                    }
            }
            catch (Exception ex)
            {
                throw new CacheException(ex.ToString());
            }
        }
        public async Task <long> DeleteAllAsync <T>(string typeName) where T : QueryProjectionBase
        {
            var filterBuilder = Builders <T> .Filter;

            var filter = filterBuilder.Eq(d => d.ViewType, typeName);

            var collection = GetCollection <T>();

            var result = await RetryPolicy.ExecuteAsync(_ =>
                                                        collection.DeleteManyAsync(filter),
                                                        new Context(nameof(IQueryStore.DeleteManyLessThanAsync)));

            return(result.DeletedCount);
        }
Пример #29
0
        async Task <Option <Twin> > GetTwinFromIoTHub(bool retrying = false)
        {
            IModuleClient moduleClient = null;

            try
            {
                async Task <Twin> GetTwinFunc()
                {
                    Events.GettingModuleClient(retrying);
                    moduleClient = await this.moduleConnection.GetOrCreateModuleClient();

                    Events.GotModuleClient();
                    return(await moduleClient.GetTwinAsync());
                }

                // if GetTwinAsync fails its possible that it might be due to transient network errors or because
                // we are getting throttled by IoT Hub; if we didn't attempt a retry then this object would be
                // stuck in an "error" state till either the connection status on the underlying device connection
                // changes or we receive a patch deployment; doing an exponential back-off retry here allows us to
                // recover from this situation
                var retryPolicy = new RetryPolicy(AllButFatalErrorDetectionStrategy, this.retryStrategy);
                retryPolicy.Retrying += (_, args) => Events.RetryingGetTwin(args);
                Twin twin = await retryPolicy.ExecuteAsync(GetTwinFunc);

                Events.GotTwin(twin);
                this.deploymentMetrics.ReportIotHubSync(true);
                return(Option.Some(twin));
            }
            catch (Exception e)
            {
                Events.ErrorGettingTwin(e);
                this.deploymentMetrics.ReportIotHubSync(false);

                if (!retrying && moduleClient != null)
                {
                    try
                    {
                        await moduleClient.CloseAsync();
                    }
                    catch (Exception e2)
                    {
                        Events.ErrorClosingModuleClientForRetry(e2);
                    }

                    return(await this.GetTwinFromIoTHub(true));
                }

                return(Option.None <Twin>());
            }
        }
Пример #30
0
        public async Task <IEnumerable <FlurlCookie> > LoginUserAsync(string userName, string password)
        {
            var request = FlurlClient.Request("login");
            var cookies = new CookieJar();
            var body    = new
            {
                username = userName,
                password
            };
            await RetryPolicy.ExecuteAsync(() => request.WithCookies(out cookies).PostUrlEncodedAsync(body));

            Cookies = cookies.Remove(cookie => !cookie.Name.StartsWith("bgg", StringComparison.OrdinalIgnoreCase));
            return(Cookies);
        }
        public async Task <int> GetVacancyCountForUserAsync(string userId)
        {
            var builder = Builders <Vacancy> .Filter;
            var filter  = builder.Eq(CreatedByUserId, userId) |
                          builder.Eq(SubmittedByUserId, userId);

            var collection = GetCollection <Vacancy>();

            var result = await RetryPolicy.ExecuteAsync(_ =>
                                                        collection.CountDocumentsAsync(filter),
                                                        new Context(nameof(GetVacancyCountForUserAsync)));

            return((int)result);
        }
        public async Task <IEnumerable <T> > GetVacanciesByStatusAsync <T>(VacancyStatus status)
        {
            var filter = Builders <T> .Filter.Eq(VacancyStatusFieldName, status.ToString());

            var collection = GetCollection <T>();

            var result = await RetryPolicy.ExecuteAsync(_ =>
                                                        collection.Find(filter)
                                                        .Project <T>(GetProjection <T>())
                                                        .ToListAsync(),
                                                        new Context(nameof(GetVacanciesByStatusAsync)));

            return(result);
        }
Пример #33
0
        public static async Task DoesNotRetry()
        {
            var fake = Substitute.For<IFake>();
            fake.DoSomething().ReturnsTask(0);
            fake.IsRetryable(1337, null).Returns(true);
            fake.IsRetryable(0, null).Returns(false);
            var logger = Substitute.For<ILog>();
            var delay = Substitute.For<Delay>();
            var retryHandler = new RetryPolicy(logger, 100, 10, delay);

            var result = await retryHandler.ExecuteAsync(fake.DoSomething, fake.IsRetryable);

            Assert.Equal(0, result);
            fake.Received(1, x => x.DoSomething());
        }
        protected override async Task StartAsync()
        {
            InfoLogging(string.Format("{0} - Processing", SubscriptionName));

            _subClient = await _clientFactory.CreateSubscriptionClientAsync(TopicName, SubscriptionName).ConfigureAwait(false);
            
            _retryStrategy = CreateRetryPolicy(MessageRepostMaxCount);
            var stopWatch = new Stopwatch();

            while (!Token.IsCancellationRequested)
            {
                var message = await _subClient.ReceiveAsync(new TimeSpan(0, 0, 10)).ConfigureAwait(false);
                if (message == null) continue;

                var messageBody = message.GetBody<string>();
                if (String.IsNullOrEmpty(messageBody)) continue;

                var messageId = message.MessageId;
                message.Complete();

                DebugLogging(string.Format("{0} - Received new message", SubscriptionName), messageId);
                var failed = false;
                stopWatch.Restart();

                try
                {
                    await _retryStrategy.ExecuteAsync(() =>
                        Do(messageBody), Token).ConfigureAwait(false);

                    stopWatch.Stop();
                    var timeSpan = stopWatch.Elapsed;
                    DebugLogging(string.Format("{0} - Processed message",
                        SubscriptionName), messageId,
                        timeSpan.TotalSeconds);
                }
                catch (Exception exception)
                {
                    ErrorLogging("Message processing failed after retry, posting as failed message.", messageId,
                        exception);
                    failed = true;
                }

                if (failed)
                    await HandleFailedMessageAsync(messageBody).ConfigureAwait(false);
            }
        }
Пример #35
0
        public static async Task Retries_WhenShouldRetry()
        {
            var fake = Substitute.For<IFake>();
            fake.DoSomething().ReturnsTask(1337, 1337, 1337, 0);
            fake.IsRetryable(1337, null).Returns(true);
            fake.IsRetryable(0, null).Returns(false);
            var logger = Substitute.For<ILog>();
            var delay = Substitute.For<Delay>();
            var retryHandler = new RetryPolicy(logger, 100, 10, delay);

            await retryHandler.ExecuteAsync(fake.DoSomething, fake.IsRetryable);

            fake.Received(4, x => x.DoSomething());
            delay.Received(1, x => x.Received(100));
            delay.Received(1, x => x.Received(200));
            delay.Received(1, x => x.Received(400));

            // Test logging for each retry
            AssertInfoLog(logger, 0, 100, 1);
            AssertInfoLog(logger, 1, 200, 2);
            AssertInfoLog(logger, 2, 400, 3);
        }
Пример #36
0
        public static async Task MergesLogInfo()
        {
            var fake = Substitute.For<IFake>();
            fake.DoSomething().ReturnsTask(1337, 0);
            fake.IsRetryable(1337, null).Returns(true);
            fake.IsRetryable(0, null).Returns(false);
            var logger = Substitute.For<ILog>();
            var delay = Substitute.For<Delay>();
            var retryHandler = new RetryPolicy(logger, 100, 10, delay);

            await retryHandler.ExecuteAsync(fake.DoSomething, fake.IsRetryable,
                (result, loggerInfo) =>
                {
                    loggerInfo["couchbaseDocumentKey"] = "mykey";
                    loggerInfo["result"] = result;
                });

            var fields = AssertInfoLog(logger, 0, 100, 1);
            Assert.Equal("mykey", fields["couchbaseDocumentKey"]);
            Assert.Equal(1337, fields["result"]);
        }
Пример #37
0
        public static async void Throws_WhenCancellationTokenIsAlreadyCancelled()
        {
            var logger = Substitute.For<ILog>();
            var retryHandler = new RetryPolicy(logger);

            var ex = await Assert.ThrowsAsync<TaskCanceledException>(() => retryHandler.ExecuteAsync(async c => { await Task.Delay(5000, c); return true; }, (b, e) => true,  cancellationToken: new CancellationToken(true)));
            Assert.True(ex.Task.IsCanceled);
        }
Пример #38
0
        public static async void Throws_WhenCancellationTokenIsSubsequentlyCancelled()
        {
            var logger = Substitute.For<ILog>();
            var retryHandler = new RetryPolicy(logger);

            var cts = new CancellationTokenSource(500);
            var result = retryHandler.ExecuteAsync(async c => { await Task.Delay(4000, c); return true; }, (b, e) => true, cancellationToken: cts.Token);

            await Assert.ThrowsAsync<TaskCanceledException>(async () => await result);
            Assert.True(result.IsCanceled);
        }
        internal static void SafeMessagingActionAsync(Task messageAction, BrokeredMessage message, Action<bool> callback, string actionErrorDescription, string messageId, string subscription, long processingElapsedMilliseconds, long schedulingElapsedMilliseconds, Stopwatch roundtripStopwatch)
        {
            var retryPolicy = new RetryPolicy<ServiceBusTransientErrorDetectionStrategy>(retryStrategy);
            retryPolicy.Retrying +=
                (s, e) =>
                {
                    Trace.TraceWarning("An error occurred in attempt number {1} to release message {3} in subscription {2}: {0}",
                    e.LastException.GetType().Name + " - " + e.LastException.Message,
                    e.CurrentRetryCount,
                    subscription,
                    message.MessageId);
                };

            long messagingActionStart = roundtripStopwatch.ElapsedMilliseconds;

            retryPolicy.ExecuteAsync(() => messageAction.ContinueWith(r =>
            {
                if (r.Exception != null)
                {
                    Exception e = r.Exception;
                    roundtripStopwatch.Stop();
                    if (e is MessageLockLostException || e is MessagingException || e is TimeoutException)
                    {
                        Trace.TraceWarning(actionErrorDescription, messageId, subscription, e.GetType().Name + " - " + e.Message, processingElapsedMilliseconds, schedulingElapsedMilliseconds, messagingActionStart, roundtripStopwatch.ElapsedMilliseconds);
                    }
                    else
                    {
                        Trace.TraceError("Unexpected error releasing message in subscription {1}:\r\n{0}", e, subscription);
                    }

                    callback(false);
                }
                else
                {
                    messagingActionStart = roundtripStopwatch.ElapsedMilliseconds;
                    roundtripStopwatch.Stop();
                    callback(true);
                }
            }));
        }
Пример #40
0
        public static void Throws_IfRetriesAreExhausted()
        {
            var fake = Substitute.For<IFake>();
            fake.DoSomething().ReturnsTask(1337, 1337);
            fake.IsRetryable(1337, null).Returns(true);
            fake.IsRetryable(0, null).Returns(false);
            var logger = Substitute.For<ILog>();
            var delay = Substitute.For<Delay>();
            var retryHandler = new RetryPolicy(logger, 100, 2, delay);

            var ex = Assert.Throws<RetryFailedException>(() => retryHandler.ExecuteAsync(fake.DoSomething, fake.IsRetryable).GetAwaiter().GetResult());
            Assert.Equal("The operation did not succeed after the maximum number of retries (2).", ex.Message);
        }