internal static IRetryPolicy GetRetryPolicy(string policyName, TimeSpan deltaBackoff, int maxAttempts) { IRetryPolicy policy; switch (policyName) { case "Exponential": policy = new ExponentialRetry(deltaBackoff, maxAttempts); break; case "Linear": policy = new LinearRetry(deltaBackoff, maxAttempts); break; case "NoRetry": policy = new NoRetry(); break; default: policy = new NoRetry(); break; } return(policy); }
public async Task RetrySetRetryPolicyVerifyInternalsSuccess() { // arrange var innerHandlerMock = Substitute.For <IDelegatingHandler>(); var contextMock = Substitute.For <PipelineContext>(); contextMock.ConnectionStatusChangesHandler = new ConnectionStatusChangesHandler(delegate(ConnectionStatus status, ConnectionStatusChangeReason reason) { }); var sut = new RetryDelegatingHandler(contextMock, innerHandlerMock); var retryPolicy = new TestRetryPolicy(); sut.SetRetryPolicy(retryPolicy); int innerHandlerCallCounter = 0; innerHandlerMock.OpenAsync(Arg.Any <CancellationToken>()).Returns(t => { innerHandlerCallCounter++; throw new IotHubCommunicationException(); }); // act and assert await sut.OpenAsync(CancellationToken.None).ExpectedAsync <IotHubCommunicationException>().ConfigureAwait(false); innerHandlerCallCounter.Should().Be(2); retryPolicy.Counter.Should().Be(2); var noretry = new NoRetry(); sut.SetRetryPolicy(noretry); await sut.OpenAsync(CancellationToken.None).ExpectedAsync <IotHubCommunicationException>().ConfigureAwait(false); innerHandlerCallCounter.Should().Be(3); retryPolicy.Counter.Should().Be(2); }
public void Create_Dead_Letter_Message_Receiver_With_Expected_NonDefault_Properties() { var config = new MyEndpointHandlingConfig { ConnectionString = "Endpoint=sb://your-sb.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=", EntityPath = "unittests.singlemessagetype/Subscriptions/MessageReceiverFactoryShould", MaxConcurrentCalls = 2, MaxAutoRenewDurationSeconds = 60, AutoComplete = true, }; var expectedServiceBusEndpoint = "sb://your-sb.windows.net/"; var expectedDeadLetterPath = EntityNameHelper.FormatDeadLetterPath(config.EntityPath); var expectedReceiveMode = ReceiveMode.ReceiveAndDelete; var expectedRetryPolicy = new NoRetry(); var expectedPrefetchCount = 1; var messageReceiver = _messageReceiverFactory.CreateDeadLetterMessageReceiver(config, expectedReceiveMode, expectedRetryPolicy, expectedPrefetchCount); (messageReceiver as MessageReceiver).ServiceBusConnection.Endpoint.Should().Be(expectedServiceBusEndpoint); (messageReceiver as MessageReceiver).Path.Should().Be(expectedDeadLetterPath); (messageReceiver as MessageReceiver).ReceiveMode.Should().Be(expectedReceiveMode); (messageReceiver as MessageReceiver).RetryPolicy.Should().Be(expectedRetryPolicy); (messageReceiver as MessageReceiver).PrefetchCount.Should().Be(expectedPrefetchCount); }
public async Task BatchRequestNoRetriesWithNonBatchException() { int serviceRequestFuncCallCount = 0; var request = new BatchRequest < JobScheduleListOptions, AzureOperationResponse <IPage <ProxyModels.CloudJobSchedule> > >(null, CancellationToken.None); request.ServiceRequestFunc = (token) => { ++serviceRequestFuncCallCount; throw new TimeoutException(); }; IRetryPolicy policy = new NoRetry(); request.RetryPolicy = policy; TimeoutException e = await Assert.ThrowsAsync <TimeoutException>(async() => { await request.ExecuteRequestAsync(); }); Assert.Equal(1, serviceRequestFuncCallCount); Assert.Equal(1, request.OperationContext.RequestResults.Count); foreach (RequestResult requestResult in request.OperationContext.RequestResults) { Assert.IsType <TimeoutException>(requestResult.Exception); Assert.Null(requestResult.RequestInformation.BatchError); Assert.Null(requestResult.RequestInformation.HttpStatusCode); Assert.Null(requestResult.RequestInformation.HttpStatusMessage); Assert.Null(requestResult.RequestInformation.ServiceRequestId); Assert.NotEqual(Guid.Empty, requestResult.RequestInformation.ClientRequestId); } }
public async Task RetrySetRetryPolicyVerifyInternalsSuccess() { var innerHandlerMock = Substitute.For <IDelegatingHandler>(); var contextMock = Substitute.For <IPipelineContext>(); var sut = new RetryDelegatingHandler(contextMock, innerHandlerMock); var retryPolicy = new TestRetryPolicy(); sut.SetRetryPolicy(retryPolicy); int innerHandlerCallCounter = 0; innerHandlerMock.OpenAsync(Arg.Any <CancellationToken>()).Returns(t => { innerHandlerCallCounter++; throw new IotHubCommunicationException(); }); await sut.OpenAsync(CancellationToken.None).ExpectedAsync <IotHubCommunicationException>().ConfigureAwait(false); Assert.AreEqual(2, innerHandlerCallCounter); Assert.AreEqual(2, retryPolicy.Counter); var noretry = new NoRetry(); sut.SetRetryPolicy(noretry); await sut.OpenAsync(CancellationToken.None).ExpectedAsync <IotHubCommunicationException>().ConfigureAwait(false); Assert.AreEqual(3, innerHandlerCallCounter); Assert.AreEqual(2, retryPolicy.Counter); }
public async Task CanRegisterQueueWithRetryPolicy() { var composer = new ServiceBusComposer(); var retryPolicy = new NoRetry(); var factory = new Mock <IQueueClientFactory>(); factory .Setup(o => o.Create(It.Is <QueueOptions>(opts => opts.RetryPolicy == retryPolicy))) .Returns((QueueOptions o) => new QueueClientMock("testQueue").QueueClient) .Verifiable(); composer.WithAdditionalServices( services => { services.OverrideQueueClientFactory(factory.Object); services.ConfigureServiceBus( options => { options.RegisterQueue("testQueue") .WithConnectionString("testConnectionString") .WithRetryPolicy(retryPolicy); }); }); var provider = await composer.ComposeAndSimulateStartup(); var registry = provider.GetService <IServiceBusRegistry>(); factory.VerifyAll(); Assert.Equal("testQueue", registry.GetQueueSender("testQueue")?.Name); }
static async Task Main(string[] args) { // Async Ingestion From a Single Azure Blob using KustoQueuedIngestClient with (optional) RetryPolicy: //Create Kusto connection string with App Authentication var kustoConnectionStringBuilderDM = new KustoConnectionStringBuilder(@"https://ingest-{clusterNameAndRegion}.kusto.windows.net").WithAadApplicationKeyAuthentication( applicationClientId: "{Application Client ID}", applicationKey: "{Application Key (secret)}", authority: "{AAD TenantID or name}"); // Create an ingest client // Note, that creating a separate instance per ingestion operation is an anti-pattern. // IngestClient classes are thread-safe and intended for reuse IKustoIngestClient client = KustoIngestFactory.CreateQueuedIngestClient(kustoConnectionStringBuilderDM); // Ingest from blobs according to the required properties var kustoIngestionProperties = new KustoIngestionProperties(databaseName: "myDB", tableName: "myTable"); var sourceOptions = new StorageSourceOptions() { DeleteSourceOnSuccess = true }; //// Create your custom implementation of IRetryPolicy, which will affect how the ingest client handles retrying on transient failures IRetryPolicy retryPolicy = new NoRetry(); //// This line sets the retry policy on the ingest client that will be enforced on every ingest call from here on ((IKustoQueuedIngestClient)client).QueueRetryPolicy = retryPolicy; await client.IngestFromStorageAsync(uri : @"BLOB-URI-WITH-SAS-KEY", ingestionProperties : kustoIngestionProperties, sourceOptions); client.Dispose(); }
public async Task CanRegisterSubscriptionWithRetryPolicy() { var composer = new ServiceBusComposer(); var retryPolicy = new NoRetry(); var factory = new Mock <ISubscriptionClientFactory>(); factory .Setup(o => o.Create(It.Is <SubscriptionOptions>(opts => opts.RetryPolicy == retryPolicy))) .Returns((SubscriptionOptions o) => new SubscriptionClientMock("testSubscription").Client) .Verifiable(); composer.WithAdditionalServices( services => { services.OverrideSubscriptionClientFactory(factory.Object); services.ConfigureServiceBus( options => { options.RegisterSubscription("testTopic", "testSubscription") .WithConnectionString("testConnectionString") .WithRetryPolicy(retryPolicy); }); }); var provider = await composer.ComposeAndSimulateStartup(); var registry = provider.GetService <IServiceBusRegistry>(); factory.VerifyAll(); }
public void Retry_SetRetryPolicyVerifyInternals_Success() { var innerHandlerMock = Substitute.For <IDelegatingHandler>(); var contextMock = Substitute.For <IPipelineContext>(); var sut = new RetryDelegatingHandler(contextMock); sut.ContinuationFactory = c => innerHandlerMock; var exponentialBackoff = new ExponentialBackoff(10, TimeSpan.FromSeconds(1), TimeSpan.FromMinutes(1), TimeSpan.FromMilliseconds(10)); sut.SetRetryPolicy(exponentialBackoff); Assert.AreEqual(typeof(RetryDelegatingHandler.IotHubTransientErrorIgnoreStrategy), sut.internalRetryPolicy.ErrorDetectionStrategy.GetType()); Assert.AreEqual(typeof(RetryDelegatingHandler.IotHubRuntimeOperationRetryStrategy), sut.internalRetryPolicy.RetryStrategy.GetType()); var iotHubRuntimeOperationRetryStrategy = (RetryDelegatingHandler.IotHubRuntimeOperationRetryStrategy)sut.internalRetryPolicy.RetryStrategy; Assert.AreEqual(typeof(TransientFaultHandling.RetryStrategyWrapper), iotHubRuntimeOperationRetryStrategy.retryStrategy.GetType()); Assert.AreSame(exponentialBackoff, ((TransientFaultHandling.RetryStrategyWrapper)iotHubRuntimeOperationRetryStrategy.retryStrategy).retryPolicy); var noretry = new NoRetry(); sut.SetRetryPolicy(noretry); Assert.AreEqual(typeof(RetryDelegatingHandler.IotHubTransientErrorIgnoreStrategy), sut.internalRetryPolicy.ErrorDetectionStrategy.GetType()); Assert.AreEqual(typeof(RetryDelegatingHandler.IotHubRuntimeOperationRetryStrategy), sut.internalRetryPolicy.RetryStrategy.GetType()); iotHubRuntimeOperationRetryStrategy = (RetryDelegatingHandler.IotHubRuntimeOperationRetryStrategy)sut.internalRetryPolicy.RetryStrategy; Assert.AreEqual(typeof(TransientFaultHandling.RetryStrategyWrapper), iotHubRuntimeOperationRetryStrategy.retryStrategy.GetType()); Assert.AreSame(noretry, ((TransientFaultHandling.RetryStrategyWrapper)iotHubRuntimeOperationRetryStrategy.retryStrategy).retryPolicy); }
public void QueryWithOptions() { NoRetry noRetry = new NoRetry(); var retry = Substitute.For <IRetryPolicy>(); retry.CreateInstance().Returns(noRetry); TableRequestOptions options = new TableRequestOptions(); options.RetryPolicy = retry; var table = 'a' + Guid.NewGuid().ToString().ToLowerInvariant().Replace('-', 'a'); ITableStorage storageWithOptions = new TableStorage(table, TestHelpers.DevConnectionString, options); var random = new Random(); var count = random.Next(2, 25); var entities = new List <IDictionary <string, object> >(); var partition = Guid.NewGuid().ToString(); for (var i = 0; i < count; i++) { var dic = new Dictionary <string, object>(); dic.Add(TableStorage.PartitionKey, partition); dic.Add(TableStorage.RowKey, Guid.NewGuid().ToString()); dic.Add("Id", Guid.NewGuid()); entities.Add(dic); } storageWithOptions.Insert(entities); retry.Received().CreateInstance(); }
public void NoRetryPolicy_RecommendsNo() { // arrange var noRetryPolicy = new NoRetry(); // act and assert Assert.IsFalse(noRetryPolicy.ShouldRetry(0, null, out TimeSpan retryInterval)); Assert.AreEqual(TimeSpan.Zero, retryInterval); }
public void NoRetryPolicy_VerifyBehavior_Success() { var noRetryPolicy = new NoRetry(); TimeSpan retryInterval; Assert.IsFalse(noRetryPolicy.ShouldRetry(Arg.Any <int>(), Arg.Any <Exception>(), out retryInterval)); Assert.AreEqual(TimeSpan.Zero, retryInterval); }
public LoRaDeviceClient(string devEUI, DeviceClient deviceClient) { this.devEUI = devEUI; this.deviceClient = deviceClient; this.noRetryPolicy = new NoRetry(); this.exponentialBackoff = new ExponentialBackoff(int.MaxValue, TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(10), TimeSpan.FromMilliseconds(100)); this.SetRetry(false); }
public LoRaDeviceClient(string devEUI, string connectionString, ITransportSettings[] transportSettings) { this.devEUI = devEUI; this.noRetryPolicy = new NoRetry(); this.exponentialBackoff = new ExponentialBackoff(int.MaxValue, TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(10), TimeSpan.FromMilliseconds(100)); this.connectionString = connectionString; this.transportSettings = transportSettings; this.deviceClient = DeviceClient.CreateFromConnectionString(this.connectionString, this.transportSettings); this.SetRetry(false); }
public AzureQueue(CloudStorageAccount account, string queueName, TimeSpan visibilityTimeout) { this.account = account; this.visibilityTimeout = visibilityTimeout; var client = this.account.CreateCloudQueueClient(); // retry policy is handled by TFHAB IRetryPolicy noRetryPolicy = new NoRetry(); this.queue = client.GetQueueReference(queueName); }
public ExecutionState(RESTCommand <T> cmd, IRetryPolicy policy, OperationContext operationContext) { Cmd = cmd; object retryPolicy2; if (policy == null) { IRetryPolicy retryPolicy = new NoRetry(); retryPolicy2 = retryPolicy; } else { retryPolicy2 = policy.CreateInstance(); } RetryPolicy = (IRetryPolicy)retryPolicy2; OperationContext = (operationContext ?? new OperationContext()); InitializeLocation(); if (OperationContext.StartTime == DateTimeOffset.MinValue) { OperationContext.StartTime = DateTimeOffset.Now; } }