public async Task ConnectionTransportCannotRetrieveMetadataWhenCustomValidationRejectsTheCertificate()
        {
            await using (EventHubScope scope = await EventHubScope.CreateAsync(1))
            {
                var connectionString = EventHubsTestEnvironment.Instance.BuildConnectionStringForEventHub(scope.EventHubName);
                var retryOptions     = new EventHubsRetryOptions {
                    TryTimeout = TimeSpan.FromMinutes(2)
                };

                var clientOptions = new EventHubConnectionOptions
                {
                    CertificateValidationCallback = (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) => false
                };

                await using (var connection = new TestConnectionWithRetryPolicy(connectionString))
                    await using (var certificateRejectingConnection = new TestConnectionWithRetryPolicy(connectionString, clientOptions))
                    {
                        connection.RetryPolicy = new BasicRetryPolicy(retryOptions);
                        certificateRejectingConnection.RetryPolicy = new BasicRetryPolicy(retryOptions);

                        var partition = (await connection.GetPartitionIdsAsync()).First();

                        Assert.That(async() => await certificateRejectingConnection.GetPartitionIdsAsync(), Throws.InstanceOf <AuthenticationException>());
                        Assert.That(async() => await certificateRejectingConnection.GetPropertiesAsync(), Throws.InstanceOf <AuthenticationException>());
                        Assert.That(async() => await certificateRejectingConnection.GetPartitionPropertiesAsync(partition), Throws.InstanceOf <AuthenticationException>());
                    }
            }
        }
        public void GetPropertiesAsyncConsidersOperationCanceledExceptionAsRetriable(EventHubsRetryOptions retryOptions)
        {
            var eventHubName       = "myName";
            var tokenValue         = "123ABC";
            var retryPolicy        = new BasicRetryPolicy(retryOptions);
            var retriableException = new OperationCanceledException();
            var mockConverter      = new Mock <AmqpMessageConverter>();
            var mockCredential     = new Mock <EventHubTokenCredential>(Mock.Of <TokenCredential>(), "{namespace}.servicebus.windows.net");
            var mockScope          = new Mock <AmqpConnectionScope>();

            using var cancellationSource = new CancellationTokenSource();

            mockCredential
            .Setup(credential => credential.GetTokenAsync(It.IsAny <TokenRequestContext>(), It.Is <CancellationToken>(value => value == cancellationSource.Token)))
            .Returns(new ValueTask <AccessToken>(new AccessToken(tokenValue, DateTimeOffset.MaxValue)));

            mockConverter
            .Setup(converter => converter.CreateEventHubPropertiesRequest(It.Is <string>(value => value == eventHubName), It.Is <string>(value => value == tokenValue)))
            .Returns(default(AmqpMessage));

            mockScope
            .Setup(scope => scope.OpenManagementLinkAsync(It.IsAny <TimeSpan>(), It.IsAny <CancellationToken>()))
            .Throws(retriableException);

            var client = new InjectableMockClient("my.eventhub.com", eventHubName, mockCredential.Object, new EventHubConnectionOptions(), mockScope.Object, mockConverter.Object);

            Assert.That(async() => await client.GetPropertiesAsync(retryPolicy, cancellationSource.Token), Throws.InstanceOf(retriableException.GetType()));

            mockScope.Verify(scope => scope.OpenManagementLinkAsync(It.IsAny <TimeSpan>(), It.IsAny <CancellationToken>()), Times.Exactly(1 + retryOptions.MaximumRetries));
        }
Exemplo n.º 3
0
        /// <summary>
        ///   Compares retry options between two instances to determine if the
        ///   instances represent the same set of options.
        /// </summary>
        ///
        /// <param name="instance">The instance that this method was invoked on.</param>
        /// <param name="other">The other set of retry options to consider.</param>
        ///
        /// <returns><c>true</c>, if the two sets of options are structurally equivalent; otherwise, <c>false</c>.</returns>
        ///
        public static bool IsEquivalentTo(this EventHubsRetryOptions instance,
                                          EventHubsRetryOptions other)
        {
            // If the events are the same instance, they're equal.  This should only happen
            // if both are null or they are the exact same instance.

            if (Object.ReferenceEquals(instance, other))
            {
                return(true);
            }

            // If one or the other is null, then they cannot be equal, since we know that
            // they are not both null.

            if ((instance == null) || (other == null))
            {
                return(false);
            }

            // If the contents of each attribute are equal, the instance are
            // equal.

            return
                (
                instance.Mode == other.Mode &&
                instance.MaximumRetries == other.MaximumRetries &&
                instance.Delay == other.Delay &&
                instance.MaximumDelay == other.MaximumDelay &&
                instance.TryTimeout == other.TryTimeout &&
                instance.CustomRetryPolicy == other.CustomRetryPolicy
                );
        }
Exemplo n.º 4
0
        public void CreateConsumerInvokesTheTransportClient()
        {
            var transportClient = new ObservableTransportClientMock();
            var client = new InjectableTransportClientMock(transportClient, "Endpoint=sb://not-real.servicebus.windows.net/;SharedAccessKeyName=DummyKey;SharedAccessKey=[not_real];EntityPath=fake");
            var expectedPosition = EventPosition.FromOffset(65);
            var expectedPartition = "2123";
            var expectedConsumerGroup = EventHubConsumerClient.DefaultConsumerGroupName;
            var expectedRetryPolicy = new EventHubsRetryOptions {
                MaximumRetries = 67
            }.ToRetryPolicy();
            var expectedTrackLastEnqueued = false;
            var expectedPrefetch          = 99U;
            var expectedOwnerLevel        = 123L;

            client.CreateTransportConsumer(expectedConsumerGroup, expectedPartition, expectedPosition, expectedRetryPolicy, expectedTrackLastEnqueued, expectedOwnerLevel, expectedPrefetch);
            (var actualConsumerGroup, var actualPartition, EventPosition actualPosition, var actualRetry, var actualTrackLastEnqueued, var actualOwnerLevel, var actualPrefetch) = transportClient.CreateConsumerCalledWith;

            Assert.That(actualPartition, Is.EqualTo(expectedPartition), "The partition should have been passed.");
            Assert.That(actualConsumerGroup, Is.EqualTo(expectedConsumerGroup), "The consumer groups should match.");
            Assert.That(actualPosition.Offset, Is.EqualTo(expectedPosition.Offset), "The event position to receive should match.");
            Assert.That(actualRetry, Is.SameAs(expectedRetryPolicy), "The retryPolicy should match.");
            Assert.That(actualOwnerLevel, Is.EqualTo(expectedOwnerLevel), "The owner levels should match.");
            Assert.That(actualPrefetch, Is.EqualTo(expectedPrefetch), "The prefetch counts should match.");
            Assert.That(actualTrackLastEnqueued, Is.EqualTo(expectedTrackLastEnqueued), "The flag for tracking the last enqueued event should match.");
        }
Exemplo n.º 5
0
        public void MaximumDelayIsValidated(int seconds)
        {
            var options      = new EventHubsRetryOptions();
            var invalidValue = TimeSpan.FromSeconds(seconds);

            Assert.That(() => options.MaximumDelay = invalidValue, Throws.InstanceOf <ArgumentException>());
        }
        public void SendBatchRespectsTheRetryPolicy(EventHubsRetryOptions retryOptions)
        {
            var partitionKey = "testMe";
            var options      = new CreateBatchOptions {
                PartitionKey = partitionKey
            };
            var retriableException = new EventHubsException(true, "Test");
            var retryPolicy        = new BasicRetryPolicy(retryOptions);
            var batch = new EventDataBatch(Mock.Of <TransportEventBatch>(), options.ToSendOptions());

            var producer = new Mock <AmqpProducer>("aHub", null, Mock.Of <AmqpConnectionScope>(), new AmqpMessageConverter(), retryPolicy)
            {
                CallBase = true
            };

            producer
            .Protected()
            .Setup <Task <SendingAmqpLink> >("CreateLinkAndEnsureProducerStateAsync",
                                             ItExpr.IsAny <string>(),
                                             ItExpr.IsAny <TimeSpan>(),
                                             ItExpr.IsAny <CancellationToken>())
            .Throws(retriableException);

            using CancellationTokenSource cancellationSource = new CancellationTokenSource();
            Assert.That(async() => await producer.Object.SendAsync(batch, cancellationSource.Token), Throws.InstanceOf(retriableException.GetType()));

            producer
            .Protected()
            .Verify("CreateLinkAndEnsureProducerStateAsync", Times.Exactly(1 + retryOptions.MaximumRetries),
                    ItExpr.Is <string>(value => value == null),
                    ItExpr.IsAny <TimeSpan>(),
                    ItExpr.IsAny <CancellationToken>());
        }
Exemplo n.º 7
0
        public void GetPartitionPropertiesAsyncAppliesTheRetryPolicyForAmqpErrors(EventHubsRetryOptions retryOptions)
        {
            var eventHubName       = "myName";
            var partitionId        = "Barney";
            var tokenValue         = "123ABC";
            var retryPolicy        = new BasicRetryPolicy(retryOptions);
            var retriableException = AmqpError.CreateExceptionForError(new Error {
                Condition = AmqpError.ServerBusyError
            }, "dummy");
            var mockConverter  = new Mock <AmqpMessageConverter>();
            var mockCredential = new Mock <EventHubTokenCredential>(Mock.Of <TokenCredential>());
            var mockScope      = new Mock <AmqpConnectionScope>();

            using var cancellationSource = new CancellationTokenSource();

            mockCredential
            .Setup(credential => credential.GetTokenAsync(It.IsAny <TokenRequestContext>(), It.Is <CancellationToken>(value => value == cancellationSource.Token)))
            .Returns(new ValueTask <AccessToken>(new AccessToken(tokenValue, DateTimeOffset.MaxValue)));

            mockConverter
            .Setup(converter => converter.CreatePartitionPropertiesRequest(It.Is <string>(value => value == eventHubName), It.Is <string>(value => value == partitionId), It.Is <string>(value => value == tokenValue)))
            .Returns(default(AmqpMessage));

            mockScope
            .Setup(scope => scope.OpenManagementLinkAsync(It.IsAny <TimeSpan>(), It.IsAny <CancellationToken>()))
            .Throws(retriableException);

            var client = new InjectableMockClient("my.eventhub.com", eventHubName, mockCredential.Object, new EventHubConnectionOptions(), mockScope.Object, mockConverter.Object);

            Assert.That(async() => await client.GetPartitionPropertiesAsync(partitionId, retryPolicy, cancellationSource.Token), Throws.InstanceOf(retriableException.GetType()));

            mockScope.Verify(scope => scope.OpenManagementLinkAsync(It.IsAny <TimeSpan>(), It.IsAny <CancellationToken>()), Times.Exactly(1 + retryOptions.MaximumRetries));
        }
Exemplo n.º 8
0
        public async Task ConnectionTransportCannotRetrieveMetadataWhenProxyIsInvalid()
        {
            await using (EventHubScope scope = await EventHubScope.CreateAsync(1))
            {
                var connectionString = TestEnvironment.BuildConnectionStringForEventHub(scope.EventHubName);
                var retryOptions     = new EventHubsRetryOptions {
                    TryTimeout = TimeSpan.FromMinutes(2)
                };

                var clientOptions = new EventHubConnectionOptions
                {
                    Proxy         = new WebProxy("http://1.2.3.4:9999"),
                    TransportType = EventHubsTransportType.AmqpWebSockets
                };

                await using (var connection = new TestConnectionWithTransport(connectionString))
                    await using (var invalidProxyConnection = new TestConnectionWithTransport(connectionString, clientOptions))
                    {
                        connection.RetryPolicy             = new BasicRetryPolicy(retryOptions);
                        invalidProxyConnection.RetryPolicy = new BasicRetryPolicy(retryOptions);

                        var partition = (await connection.GetPartitionIdsAsync()).First();

                        Assert.That(async() => await invalidProxyConnection.GetPartitionIdsAsync(), Throws.InstanceOf <WebSocketException>().Or.InstanceOf <TimeoutException>());
                        Assert.That(async() => await invalidProxyConnection.GetPropertiesAsync(), Throws.InstanceOf <WebSocketException>().Or.InstanceOf <TimeoutException>());
                        Assert.That(async() => await invalidProxyConnection.GetPartitionPropertiesAsync(partition), Throws.InstanceOf <WebSocketException>().Or.InstanceOf <TimeoutException>());
                    }
            }
        }
        public void SendEnumerableRespectsTheRetryPolicy(EventHubsRetryOptions retryOptions)
        {
            var partitionId        = "testMe";
            var retriableException = new EventHubsException(true, "Test");
            var retryPolicy        = new BasicRetryPolicy(retryOptions);

            var producer = new Mock <AmqpProducer>("aHub", partitionId, Mock.Of <AmqpConnectionScope>(), new AmqpMessageConverter(), retryPolicy)
            {
                CallBase = true
            };

            producer
            .Protected()
            .Setup <Task <SendingAmqpLink> >("CreateLinkAndEnsureProducerStateAsync",
                                             ItExpr.IsAny <string>(),
                                             ItExpr.IsAny <TimeSpan>(),
                                             ItExpr.IsAny <CancellationToken>())
            .Throws(retriableException);

            using CancellationTokenSource cancellationSource = new CancellationTokenSource();
            Assert.That(async() => await producer.Object.SendAsync(new[] { new EventData(new byte[] { 0x65 }) }, new SendEventOptions(), cancellationSource.Token), Throws.InstanceOf(retriableException.GetType()));

            producer
            .Protected()
            .Verify("CreateLinkAndEnsureProducerStateAsync", Times.Exactly(1 + retryOptions.MaximumRetries),
                    ItExpr.Is <string>(value => value == partitionId),
                    ItExpr.IsAny <TimeSpan>(),
                    ItExpr.IsAny <CancellationToken>());
        }
Exemplo n.º 10
0
        public void ReceiveAsyncAppliesTheRetryPolicyForAmqpErrors(EventHubsRetryOptions retryOptions)
        {
            var eventHub           = "eventHubName";
            var consumerGroup      = "$DEFAULT";
            var partition          = "3";
            var identifier         = "cusTOM-1D";
            var eventPosition      = EventPosition.FromOffset(123);
            var trackLastEnqueued  = false;
            var invalidateOnSteal  = true;
            var ownerLevel         = 123L;
            var tokenValue         = "123ABC";
            var retryPolicy        = new BasicRetryPolicy(retryOptions);
            var retriableException = AmqpError.CreateExceptionForError(new Error {
                Condition = AmqpError.ServerBusyError
            }, "dummy");
            var mockConverter  = new Mock <AmqpMessageConverter>();
            var mockCredential = new Mock <TokenCredential>();
            var mockScope      = new Mock <AmqpConnectionScope>();

            using var cancellationSource = new CancellationTokenSource();

            mockCredential
            .Setup(credential => credential.GetTokenAsync(It.IsAny <TokenRequestContext>(), It.Is <CancellationToken>(value => value == cancellationSource.Token)))
            .Returns(new ValueTask <AccessToken>(new AccessToken(tokenValue, DateTimeOffset.MaxValue)));

            mockScope
            .Setup(scope => scope.OpenConsumerLinkAsync(
                       It.IsAny <string>(),
                       It.IsAny <string>(),
                       It.IsAny <EventPosition>(),
                       It.IsAny <TimeSpan>(),
                       It.IsAny <TimeSpan>(),
                       It.IsAny <uint>(),
                       It.IsAny <long?>(),
                       It.IsAny <long?>(),
                       It.IsAny <bool>(),
                       It.IsAny <string>(),
                       It.IsAny <CancellationToken>()))
            .Throws(retriableException);

            var consumer = new AmqpConsumer(eventHub, consumerGroup, partition, identifier, eventPosition, trackLastEnqueued, invalidateOnSteal, ownerLevel, null, null, mockScope.Object, Mock.Of <AmqpMessageConverter>(), retryPolicy);

            Assert.That(async() => await consumer.ReceiveAsync(100, null, cancellationSource.Token), Throws.InstanceOf(retriableException.GetType()));

            mockScope
            .Verify(scope => scope.OpenConsumerLinkAsync(
                        It.Is <string>(value => value == consumerGroup),
                        It.Is <string>(value => value == partition),
                        It.Is <EventPosition>(value => value == eventPosition),
                        It.IsAny <TimeSpan>(),
                        It.IsAny <TimeSpan>(),
                        It.IsAny <uint>(),
                        It.IsAny <long?>(),
                        It.Is <long?>(value => value == ownerLevel),
                        It.Is <bool>(value => value == trackLastEnqueued),
                        It.Is <string>(value => value == identifier),
                        It.IsAny <CancellationToken>()),
                    Times.Exactly(1 + retryOptions.MaximumRetries));
        }
Exemplo n.º 11
0
        public void RetryOptionsAreOptimizedForBufferedPublishing()
        {
            var standardRetryOptions = new EventHubsRetryOptions();
            var options = new EventHubBufferedProducerClientOptions();

            Assert.That(options.RetryOptions, Is.Not.Null, "The retry options should not be null.");
            Assert.That(options.RetryOptions.MaximumRetries, Is.GreaterThan(standardRetryOptions.MaximumRetries), "The buffered retry options should allow for more retries than the standard.");
            Assert.That(options.RetryOptions.TryTimeout, Is.GreaterThan(standardRetryOptions.TryTimeout), "The buffered retry options should allow for a longer try timeout than the standard.");
        }
        public void CalulateTryTimeoutRespectsOptions(int attemptCount)
        {
            var timeout = TimeSpan.FromSeconds(5);
            var options = new EventHubsRetryOptions {
                TryTimeout = timeout
            };
            var policy = new BasicRetryPolicy(options);

            Assert.That(policy.CalculateTryTimeout(attemptCount), Is.EqualTo(options.TryTimeout));
        }
Exemplo n.º 13
0
 /// <summary>
 ///   Creates a new copy of the current <see cref="EventHubsRetryOptions" />, cloning its attributes into a new instance.
 /// </summary>
 ///
 /// <param name="instance">The instance that this method was invoked on.</param>
 ///
 /// <returns>A new copy of <see cref="EventHubsRetryOptions" />.</returns>
 ///
 public static EventHubsRetryOptions Clone(this EventHubsRetryOptions instance) =>
 new EventHubsRetryOptions
 {
     Mode = instance.Mode,
     CustomRetryPolicy = instance.CustomRetryPolicy,
     MaximumRetries    = instance.MaximumRetries,
     Delay             = instance.Delay,
     MaximumDelay      = instance.MaximumDelay,
     TryTimeout        = instance.TryTimeout
 };
        public void IsEquivalentToDetectsCustomPolicy()
        {
            var first = new EventHubsRetryOptions {
                CustomRetryPolicy = Mock.Of <EventHubsRetryPolicy>()
            };
            var second = new EventHubsRetryOptions {
                CustomRetryPolicy = new BasicRetryPolicy(new EventHubsRetryOptions())
            };

            Assert.That(first.IsEquivalentTo(second), Is.False);
        }
        public void IsEquivalentToDetectsTryTimeout()
        {
            var first = new EventHubsRetryOptions {
                TryTimeout = TimeSpan.FromSeconds(9)
            };
            var second = new EventHubsRetryOptions {
                TryTimeout = TimeSpan.FromSeconds(8)
            };

            Assert.That(first.IsEquivalentTo(second), Is.False);
        }
        public void IsEquivalentToDetectsMaximumRetries()
        {
            var first = new EventHubsRetryOptions {
                MaximumRetries = 7
            };
            var second = new EventHubsRetryOptions {
                MaximumRetries = 99
            };

            Assert.That(first.IsEquivalentTo(second), Is.False);
        }
        public void IsEquivalentToDetectsDelay()
        {
            var first = new EventHubsRetryOptions {
                Delay = TimeSpan.FromSeconds(7)
            };
            var second = new EventHubsRetryOptions {
                Delay = TimeSpan.FromMinutes(1)
            };

            Assert.That(first.IsEquivalentTo(second), Is.False);
        }
        public void IsEquivalentToDetectsModes()
        {
            var first = new EventHubsRetryOptions {
                Mode = EventHubsRetryMode.Exponential
            };
            var second = new EventHubsRetryOptions {
                Mode = EventHubsRetryMode.Fixed
            };

            Assert.That(first.IsEquivalentTo(second), Is.False);
        }
        public void IsEquivalentToDetectsEqualOptionSets()
        {
            var customPolicy = Mock.Of <EventHubsRetryPolicy>();
            var first        = new EventHubsRetryOptions {
                CustomRetryPolicy = customPolicy
            };
            var second = new EventHubsRetryOptions {
                CustomRetryPolicy = customPolicy
            };

            Assert.That(first.IsEquivalentTo(second), Is.True);
        }
        /// <summary>
        ///   Initializes a new instance of the <see cref="EventHubProducerClient" /> class.
        /// </summary>
        ///
        /// <param name="connection">The connection to use as the basis for delegation of client-type operations.</param>
        /// <param name="transportProducer">The transport producer instance to use as the basis for service communication.</param>
        /// <param name="partitionProducerPool">A <see cref="TransportProducerPool" /> used to manage a set of partition specific <see cref="TransportProducer" />.</param>
        ///
        /// <remarks>
        ///   This constructor is intended to be used internally for functional
        ///   testing only.
        /// </remarks>
        ///
        internal EventHubProducerClient(EventHubConnection connection,
                                        TransportProducer transportProducer,
                                        TransportProducerPool partitionProducerPool = default)
        {
            Argument.AssertNotNull(connection, nameof(connection));
            Argument.AssertNotNull(transportProducer, nameof(transportProducer));

            OwnsConnection        = false;
            Connection            = connection;
            RetryPolicy           = new EventHubsRetryOptions().ToRetryPolicy();
            PartitionProducerPool = partitionProducerPool ?? new TransportProducerPool(Connection, RetryPolicy, eventHubProducer: transportProducer);
        }
Exemplo n.º 21
0
        public void TryTimeoutConfiguration()
        {
            #region Snippet:EventHubs_Sample02_RetryOptionsTryTimeout

            var options = new EventHubsRetryOptions
            {
                TryTimeout = TimeSpan.FromMinutes(1)
            };

            #endregion

            Assert.That(options, Is.Not.Null);
        }
Exemplo n.º 22
0
        public void CustomRetry()
        {
            #region Snippet:EventHubs_Sample02_CustomRetryUse

            var options = new EventHubsRetryOptions
            {
                CustomRetryPolicy = new ExampleRetryPolicy()
            };

            #endregion

            Assert.That(options, Is.Not.Null);
        }
        public void IsEquivalentToDetectsNullArgument()
        {
            var first = new EventHubsRetryOptions
            {
                Mode           = EventHubsRetryMode.Fixed,
                MaximumRetries = 99,
                MaximumDelay   = TimeSpan.FromMinutes(3),
                Delay          = TimeSpan.FromSeconds(4),
                TryTimeout     = TimeSpan.Zero
            };

            Assert.That(first.IsEquivalentTo((EventHubsRetryOptions)null), Is.False);
        }
        public void IsEquivalentToDetectsSameInstance()
        {
            var first = new EventHubsRetryOptions
            {
                Mode           = EventHubsRetryMode.Fixed,
                MaximumRetries = 99,
                MaximumDelay   = TimeSpan.FromMinutes(3),
                Delay          = TimeSpan.FromSeconds(4),
                TryTimeout     = TimeSpan.Zero
            };

            Assert.That(first.IsEquivalentTo(first), Is.True);
        }
Exemplo n.º 25
0
        public void RespectsConnectionOptionsForConsumer(string expectedPathName, string connectionString)
        {
            var             testEndpoint = new Uri("http://mycustomendpoint.com");
            EventHubOptions options      = new EventHubOptions
            {
                ConnectionOptions = new EventHubConnectionOptions
                {
                    CustomEndpointAddress = testEndpoint
                },
                RetryOptions = new EventHubsRetryOptions
                {
                    MaximumRetries = 10
                }
            };

            options.AddReceiver(expectedPathName, connectionString);

            var configuration = CreateConfiguration();
            var factory       = new EventHubClientFactory(configuration, Mock.Of <AzureComponentFactory>(), Options.Create(options), new DefaultNameResolver(configuration));

            var consumer       = factory.GetEventHubConsumerClient(expectedPathName, null, "consumer");
            var consumerClient = (EventHubConsumerClient)typeof(EventHubConsumerClientImpl)
                                 .GetField("_client", BindingFlags.NonPublic | BindingFlags.Instance)
                                 .GetValue(consumer);
            EventHubConnection connection = (EventHubConnection)typeof(EventHubConsumerClient)
                                            .GetProperty("Connection", BindingFlags.NonPublic | BindingFlags.Instance)
                                            .GetValue(consumerClient);
            EventHubConnectionOptions connectionOptions = (EventHubConnectionOptions)typeof(EventHubConnection)
                                                          .GetProperty("Options", BindingFlags.NonPublic | BindingFlags.Instance)
                                                          .GetValue(connection);

            Assert.AreEqual(testEndpoint, connectionOptions.CustomEndpointAddress);

            EventHubsRetryPolicy retryPolicy = (EventHubsRetryPolicy)typeof(EventHubConsumerClient)
                                               .GetProperty("RetryPolicy", BindingFlags.NonPublic | BindingFlags.Instance)
                                               .GetValue(consumerClient);

            // Reflection was still necessary here because BasicRetryOptions (which is the concrete derived type)
            // is internal.
            EventHubsRetryOptions retryOptions = (EventHubsRetryOptions)retryPolicy.GetType()
                                                 .GetProperty("Options", BindingFlags.Public | BindingFlags.Instance)
                                                 .GetValue(retryPolicy);

            Assert.AreEqual(10, retryOptions.MaximumRetries);
            Assert.AreEqual(expectedPathName, consumer.EventHubName);
        }
Exemplo n.º 26
0
        public void ToRetryPolicyWithCustomPolicyUsesTheCustomPolicy()
        {
            var options = new EventHubsRetryOptions
            {
                Mode              = EventHubsRetryMode.Fixed,
                MaximumRetries    = 65,
                Delay             = TimeSpan.FromSeconds(1),
                MaximumDelay      = TimeSpan.FromSeconds(2),
                TryTimeout        = TimeSpan.FromSeconds(3),
                CustomRetryPolicy = Mock.Of <EventHubsRetryPolicy>()
            };

            var policy = options.ToRetryPolicy();

            Assert.That(policy, Is.Not.Null, "The policy should not be null.");
            Assert.That(policy, Is.SameAs(options.CustomRetryPolicy), "The custom retry policy should have been used.");
            Assert.That(policy, Is.Not.InstanceOf <BasicRetryPolicy>(), "The default policy type should not have been generated.");
        }
Exemplo n.º 27
0
        public void ToRetryPolicyWithoutCustomPolicyCreatesThePolicy()
        {
            var options = new EventHubsRetryOptions
            {
                Mode              = EventHubsRetryMode.Fixed,
                MaximumRetries    = 65,
                Delay             = TimeSpan.FromSeconds(1),
                MaximumDelay      = TimeSpan.FromSeconds(2),
                TryTimeout        = TimeSpan.FromSeconds(3),
                CustomRetryPolicy = null
            };

            var policy = options.ToRetryPolicy();

            Assert.That(policy, Is.Not.Null, "The policy should not be null.");
            Assert.That(policy, Is.InstanceOf <BasicRetryPolicy>(), "The options should produce a basic retry policy.");
            Assert.That(((BasicRetryPolicy)policy).Options, Is.SameAs(options), "The options should have been used for the retry policy.");
            Assert.That(policy, Is.Not.SameAs(options.CustomRetryPolicy), "The custom retry policy should not have been used, since it was not populated.");
        }
Exemplo n.º 28
0
        private void Initialize()
        {
            EventHubConnectionOptions connectionOptions = new EventHubConnectionOptions()
            {
                TransportType = EventHubsTransportType.AmqpTcp
            };

            EventHubsRetryOptions retryOptions = new EventHubsRetryOptions()
            {
                MaximumRetries = 1,
                Mode           = EventHubsRetryMode.Exponential
            };

            EventHubProducerClientOptions clientOptions = new EventHubProducerClientOptions()
            {
                ConnectionOptions = connectionOptions,
                RetryOptions      = retryOptions
            };

            this.EventHubProducerClient = new EventHubProducerClient(this.EventHubConnectionString, this.EventHubName, clientOptions);

            this.TelemetryClient?.TrackTrace("EventHubSenderService.Initialize:Complete", SeverityLevel.Information);
        }
Exemplo n.º 29
0
        public void CloneProducesACopy()
        {
            var options = new EventHubsRetryOptions
            {
                Mode              = EventHubsRetryMode.Fixed,
                MaximumRetries    = 65,
                Delay             = TimeSpan.FromSeconds(1),
                MaximumDelay      = TimeSpan.FromSeconds(2),
                TryTimeout        = TimeSpan.FromSeconds(3),
                CustomRetryPolicy = Mock.Of <EventHubsRetryPolicy>()
            };

            EventHubsRetryOptions clone = options.Clone();

            Assert.That(clone, Is.Not.Null, "The clone should not be null.");

            Assert.That(clone.Mode, Is.EqualTo(options.Mode), "The mode of the clone should match.");
            Assert.That(clone.MaximumRetries, Is.EqualTo(options.MaximumRetries), "The maximum retry limit of the clone should match.");
            Assert.That(clone.Delay, Is.EqualTo(options.Delay), "The delay of the clone should match.");
            Assert.That(clone.MaximumDelay, Is.EqualTo(options.MaximumDelay), "The maximum delay of the clone should match.");
            Assert.That(clone.TryTimeout, Is.EqualTo(options.TryTimeout), "The per-try of the clone should match.");
            Assert.That(clone.CustomRetryPolicy, Is.SameAs(options.CustomRetryPolicy), "The custom retry policy should match.");
        }
Exemplo n.º 30
0
 /// <summary>
 ///   Initializes a new instance of the <see cref="BasicRetryPolicy" /> class.
 /// </summary>
 ///
 /// <param name="retryOptions">The options which control the retry approach.</param>
 ///
 public BasicRetryPolicy(EventHubsRetryOptions retryOptions)
 {
     Argument.AssertNotNull(retryOptions, nameof(retryOptions));
     Options = retryOptions;
 }