public void Setup()
        {
            _mockExecutor = new Mock <ITriggeredFunctionExecutor>(MockBehavior.Strict);
            var client = new ServiceBusClient(_testConnection);
            ServiceBusProcessorOptions processorOptions = new ServiceBusProcessorOptions();
            ServiceBusProcessor        messageProcessor = client.CreateProcessor(_entityPath);

            _mockMessageProcessor = new Mock <MessageProcessor>(MockBehavior.Strict, messageProcessor);

            _serviceBusOptions     = new ServiceBusOptions();
            _mockMessagingProvider = new Mock <MessagingProvider>(MockBehavior.Strict, new OptionsWrapper <ServiceBusOptions>(_serviceBusOptions));

            _mockMessagingProvider
            .Setup(p => p.CreateMessageProcessor(_entityPath, _testConnection))
            .Returns(_mockMessageProcessor.Object);

            _mockServiceBusAccount = new Mock <ServiceBusAccount>(MockBehavior.Strict);
            _mockServiceBusAccount.Setup(a => a.ConnectionString).Returns(_testConnection);

            _loggerFactory  = new LoggerFactory();
            _loggerProvider = new TestLoggerProvider();
            _loggerFactory.AddProvider(_loggerProvider);

            _listener = new ServiceBusListener(_functionId, EntityType.Queue, _entityPath, false, _mockExecutor.Object, _serviceBusOptions, _mockServiceBusAccount.Object,
                                               _mockMessagingProvider.Object, _loggerFactory, false);
            _scaleMonitor = (ServiceBusScaleMonitor)_listener.GetMonitor();
        }
Ejemplo n.º 2
0
        public ServiceBusListenerTests()
        {
            _mockExecutor = new Mock <ITriggeredFunctionExecutor>(MockBehavior.Strict);

            string testConnection = "Endpoint=sb://test.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=abc123=";

            _messagingFactory = MessagingFactory.CreateFromConnectionString(testConnection);
            OnMessageOptions messageOptions = new OnMessageOptions();

            _mockMessageProcessor = new Mock <MessageProcessor>(MockBehavior.Strict, messageOptions);

            ServiceBusConfiguration config = new ServiceBusConfiguration
            {
                MessageOptions = messageOptions
            };

            _mockMessagingProvider   = new Mock <MessagingProvider>(MockBehavior.Strict, config);
            config.MessagingProvider = _mockMessagingProvider.Object;

            _mockMessagingProvider.Setup(p => p.CreateMessageProcessor(_entityPath))
            .Returns(_mockMessageProcessor.Object);

            ServiceBusTriggerExecutor triggerExecutor = new ServiceBusTriggerExecutor(_mockExecutor.Object);

            _listener = new ServiceBusListener(_messagingFactory, _entityPath, triggerExecutor, config);
        }
        public void Should_abandon_message_if_errors()
        {
            // Given
            var    subscriberOne = A.Fake <IDynamicSubscriber>();
            string foo           = null;
            long   baz           = 0;

            A.CallTo(() => subscriberOne.CanProcess(A <IServiceBusMessage> ._))
            .Returns(true);
            A.CallTo(() => subscriberOne.Process(A <IServiceBusMessage> ._, A <object> ._))
            .Invokes(foc =>
            {
                throw new InvalidOperationException();
            });
            var listener = new ServiceBusListener(
                new[] { subscriberOne },
                new SimpleJsonSerialiser(),
                this.bus);
            var message = this.GetMessage("foo", "{ \"Foo\" : \"Bar\", \"Baz\" : 23 }");

            listener.Connect(this.connectionString, this.queueName);

            // When
            this.bus.CallBack.Invoke(message).Wait();

            // Then
            message.Completed.ShouldBeFalse();
            message.Abandoned.ShouldBeTrue();
        }
        public void Should_complete_message_if_no_error()
        {
            // Given
            var    subscriberOne = A.Fake <IDynamicSubscriber>();
            string foo           = null;
            long   baz           = 0;

            A.CallTo(() => subscriberOne.CanProcess(A <IServiceBusMessage> ._))
            .Returns(true);
            A.CallTo(() => subscriberOne.Process(A <IServiceBusMessage> ._, A <object> ._))
            .Invokes(foc =>
            {
                dynamic model = foc.Arguments[1];

                foo = model.Foo;
                baz = model.Baz;
            }).Returns(Task.FromResult(0));
            var listener = new ServiceBusListener(
                new[] { subscriberOne },
                new SimpleJsonSerialiser(),
                this.bus);
            var message = this.GetMessage("foo", "{ \"Foo\" : \"Bar\", \"Baz\" : 23 }");

            listener.Connect(this.connectionString, this.queueName);

            // When
            this.bus.CallBack.Invoke(message).Wait();

            // Then
            message.Completed.ShouldBeTrue();
            message.Abandoned.ShouldBeFalse();
        }
Ejemplo n.º 5
0
        public ServiceBusListenerTests()
        {
            _mockExecutor = new Mock <ITriggeredFunctionExecutor>(MockBehavior.Strict);

            MessageHandlerOptions messageOptions  = new MessageHandlerOptions(ExceptionReceivedHandler);
            MessageReceiver       messageReceiver = new MessageReceiver(_testConnection, _entityPath);

            _mockMessageProcessor = new Mock <MessageProcessor>(MockBehavior.Strict, messageReceiver, messageOptions);

            ServiceBusOptions config = new ServiceBusOptions
            {
                MessageHandlerOptions = messageOptions
            };

            _mockMessagingProvider = new Mock <MessagingProvider>(MockBehavior.Strict, new OptionsWrapper <ServiceBusOptions>(config));

            _mockMessagingProvider
            .Setup(p => p.CreateMessageProcessor(_entityPath, _testConnection))
            .Returns(_mockMessageProcessor.Object);

            ServiceBusTriggerExecutor triggerExecutor       = new ServiceBusTriggerExecutor(_mockExecutor.Object);
            Mock <ServiceBusAccount>  mockServiceBusAccount = new Mock <ServiceBusAccount>(MockBehavior.Strict);

            mockServiceBusAccount.Setup(a => a.ConnectionString).Returns(_testConnection);

            _loggerFactory  = new LoggerFactory();
            _loggerProvider = new TestLoggerProvider();
            _loggerFactory.AddProvider(_loggerProvider);

            _listener = new ServiceBusListener(_functionId, EntityType.Queue, _entityPath, false, triggerExecutor, config, mockServiceBusAccount.Object,
                                               _mockMessagingProvider.Object, _loggerFactory);
        }
Ejemplo n.º 6
0
        public ServiceBusListenerTests()
        {
            _mockExecutor = new Mock <ITriggeredFunctionExecutor>(MockBehavior.Strict);

            MessageHandlerOptions messageOptions  = new MessageHandlerOptions(ExceptionReceivedHandler);
            MessageReceiver       messageReceiver = new MessageReceiver(_testConnection, _entityPath);

            _mockMessageProcessor = new Mock <MessageProcessor>(MockBehavior.Strict, messageReceiver, messageOptions);

            ServiceBusConfiguration config = new ServiceBusConfiguration
            {
                MessageOptions = messageOptions
            };

            _mockMessagingProvider   = new Mock <MessagingProvider>(MockBehavior.Strict, config);
            config.MessagingProvider = _mockMessagingProvider.Object;

            _mockMessagingProvider.Setup(p => p.CreateMessageProcessor(_entityPath, _testConnection))
            .Returns(_mockMessageProcessor.Object);

            ServiceBusTriggerExecutor triggerExecutor = new ServiceBusTriggerExecutor(_mockExecutor.Object);
            var mockServiceBusAccount = new Mock <ServiceBusAccount>(MockBehavior.Strict);

            mockServiceBusAccount.Setup(a => a.ConnectionString).Returns(_testConnection);

            _listener = new ServiceBusListener(_entityPath, triggerExecutor, config, mockServiceBusAccount.Object);
        }
        public void Should_only_call_subscriber_who_can_process()
        {
            // Given
            var subscriberOne = A.Fake <IDynamicSubscriber>();

            A.CallTo(() => subscriberOne.CanProcess(A <IServiceBusMessage> ._)).Returns(true);
            var subscriberTwo = A.Fake <IDynamicSubscriber>();

            A.CallTo(() => subscriberTwo.CanProcess(A <IServiceBusMessage> ._)).Returns(false);
            var listener = new ServiceBusListener(
                new[] { subscriberOne, subscriberTwo },
                this.serialiser,
                this.bus);
            var message = this.GetMessage("foo");

            listener.Connect(this.connectionString, this.queueName);

            // When
            this.bus.CallBack.Invoke(message).Wait();

            // Then
            A.CallTo(() => subscriberOne.Process(A <IServiceBusMessage> ._, A <object> ._))
            .MustHaveHappened(Repeated.Exactly.Once);
            A.CallTo(() => subscriberTwo.Process(A <IServiceBusMessage> ._, A <object> ._))
            .MustNotHaveHappened();
        }
        static SitemapEventRegistrator()
        {
            SitemapGeneratorScheduler = ServiceLocator.GetService <ISitemapGeneratorScheduler>();

            var settings = ServiceLocator.GetService <IServiceBusSettings>();

            ServiceBusListener = new ServiceBusListener(settings, "Events");
        }
        public async Task GetMetrics_HandlesExceptions()
        {
            // MessagingEntityNotFoundException
            _mockMessagingProvider
            .Setup(p => p.CreateBatchMessageReceiver(_entityPath, _testConnection))
            .Throws(new ServiceBusException("", reason: ServiceBusFailureReason.MessagingEntityNotFound));
            ServiceBusListener listener = new ServiceBusListener(_functionId, EntityType.Queue, _entityPath, false, _mockExecutor.Object, _serviceBusOptions,
                                                                 _mockServiceBusAccount.Object, _mockMessagingProvider.Object, _loggerFactory, false);

            var metrics = await((ServiceBusScaleMonitor)listener.GetMonitor()).GetMetricsAsync();

            Assert.AreEqual(0, metrics.PartitionCount);
            Assert.AreEqual(0, metrics.MessageCount);
            Assert.AreEqual(TimeSpan.FromSeconds(0), metrics.QueueTime);
            Assert.AreNotEqual(default(DateTime), metrics.Timestamp);

            var warning = _loggerProvider.GetAllLogMessages().Single(p => p.Level == LogLevel.Warning);

            Assert.AreEqual($"ServiceBus queue '{_entityPath}' was not found.", warning.FormattedMessage);
            _loggerProvider.ClearAllLogMessages();

            // UnauthorizedAccessException
            _mockMessagingProvider
            .Setup(p => p.CreateBatchMessageReceiver(_entityPath, _testConnection))
            .Throws(new UnauthorizedAccessException(""));
            listener = new ServiceBusListener(_functionId, EntityType.Queue, _entityPath, false, _mockExecutor.Object, _serviceBusOptions,
                                              _mockServiceBusAccount.Object, _mockMessagingProvider.Object, _loggerFactory, false);

            metrics = await((ServiceBusScaleMonitor)listener.GetMonitor()).GetMetricsAsync();

            Assert.AreEqual(0, metrics.PartitionCount);
            Assert.AreEqual(0, metrics.MessageCount);
            Assert.AreEqual(TimeSpan.FromSeconds(0), metrics.QueueTime);
            Assert.AreNotEqual(default(DateTime), metrics.Timestamp);

            warning = _loggerProvider.GetAllLogMessages().Single(p => p.Level == LogLevel.Warning);
            Assert.AreEqual($"Connection string does not have Manage claim for queue '{_entityPath}'. Failed to get queue description to derive queue length metrics. " +
                            $"Falling back to using first message enqueued time.",
                            warning.FormattedMessage);
            _loggerProvider.ClearAllLogMessages();

            // Generic Exception
            _mockMessagingProvider
            .Setup(p => p.CreateBatchMessageReceiver(_entityPath, _testConnection))
            .Throws(new Exception("Uh oh"));
            listener = new ServiceBusListener(_functionId, EntityType.Queue, _entityPath, false, _mockExecutor.Object, _serviceBusOptions,
                                              _mockServiceBusAccount.Object, _mockMessagingProvider.Object, _loggerFactory, false);

            metrics = await((ServiceBusScaleMonitor)listener.GetMonitor()).GetMetricsAsync();

            Assert.AreEqual(0, metrics.PartitionCount);
            Assert.AreEqual(0, metrics.MessageCount);
            Assert.AreEqual(TimeSpan.FromSeconds(0), metrics.QueueTime);
            Assert.AreNotEqual(default(DateTime), metrics.Timestamp);

            warning = _loggerProvider.GetAllLogMessages().Single(p => p.Level == LogLevel.Warning);
            Assert.AreEqual($"Error querying for Service Bus queue scale status: Uh oh", warning.FormattedMessage);
        }
Ejemplo n.º 10
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("Hello SpeedTestLogger!");

            var config = new LoggerConfiguration();

            var serviceBusListener = new ServiceBusListener(config);
            await serviceBusListener.Listen(async (msg) => await DoWork(config));
        }
Ejemplo n.º 11
0
        public static IApplicationBuilder UseServiceBusListener(this IApplicationBuilder app)
        {
            _listener = (ServiceBusListener)app.ApplicationServices.GetService(typeof(ServiceBusListener));

            IApplicationLifetime lifetime = (IApplicationLifetime)app.ApplicationServices.GetService(typeof(IApplicationLifetime));

            lifetime.ApplicationStarted.Register(OnStarted);
            lifetime.ApplicationStopping.Register(OnStopping);

            return(app);
        }
Ejemplo n.º 12
0
            public async Task Stop_Will_Return_True()
            {
                //Arrange
                var listener = new ServiceBusListener(_mockSerialiser.Object, _mockHandlerResolver.Object,
                                                      _mockHandlerInvoker.Object);

                //Act
                var result = await listener.Stop();

                //Assert
                Assert.That(result, Is.True);
            }
        public void Setup()
        {
            _mockExecutor = new Mock <ITriggeredFunctionExecutor>(MockBehavior.Strict);
            _client       = new ServiceBusClient(_testConnection);
            ServiceBusProcessorOptions processorOptions = new ServiceBusProcessorOptions();
            ServiceBusProcessor        messageProcessor = _client.CreateProcessor(_entityPath);
            ServiceBusReceiver         receiver         = _client.CreateReceiver(_entityPath);

            _mockMessageProcessor = new Mock <MessageProcessor>(MockBehavior.Strict, messageProcessor);
            var configuration = ConfigurationUtilities.CreateConfiguration(new KeyValuePair <string, string>(_connection, _testConnection));

            _serviceBusOptions = new ServiceBusOptions();
            _mockProvider      = new Mock <MessagingProvider>(new OptionsWrapper <ServiceBusOptions>(_serviceBusOptions));
            _mockClientFactory = new Mock <ServiceBusClientFactory>(
                configuration,
                Mock.Of <AzureComponentFactory>(),
                _mockProvider.Object,
                new AzureEventSourceLogForwarder(new NullLoggerFactory()),
                new OptionsWrapper <ServiceBusOptions>(_serviceBusOptions));

            _mockProvider
            .Setup(p => p.CreateMessageProcessor(_client, _entityPath, It.IsAny <ServiceBusProcessorOptions>()))
            .Returns(_mockMessageProcessor.Object);

            _mockProvider
            .Setup(p => p.CreateClient(_testConnection, It.IsAny <ServiceBusClientOptions>()))
            .Returns(_client);

            _loggerFactory  = new LoggerFactory();
            _loggerProvider = new TestLoggerProvider();
            _loggerFactory.AddProvider(_loggerProvider);

            var concurrencyOptions             = new OptionsWrapper <ConcurrencyOptions>(new ConcurrencyOptions());
            var mockConcurrencyThrottleManager = new Mock <IConcurrencyThrottleManager>(MockBehavior.Strict);
            var concurrencyManager             = new ConcurrencyManager(concurrencyOptions, _loggerFactory, mockConcurrencyThrottleManager.Object);

            _listener = new ServiceBusListener(
                _functionId,
                ServiceBusEntityType.Queue,
                _entityPath,
                false,
                _serviceBusOptions.AutoCompleteMessages,
                _mockExecutor.Object,
                _serviceBusOptions,
                _connection,
                _mockProvider.Object,
                _loggerFactory,
                false,
                _mockClientFactory.Object,
                concurrencyManager);

            _scaleMonitor = (ServiceBusScaleMonitor)_listener.GetMonitor();
        }
        public async Task <IListener> CreateListenerAsync(ListenerFactoryContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            IListenerFactory factory = new ServiceBusListenerFactory(_account, _entityPath, _isSessionsEnabled, context.Executor, _options, _messagingProvider);

            _listener = (ServiceBusListener)await factory.CreateAsync(context.CancellationToken);

            return(_listener);
        }
Ejemplo n.º 15
0
        public ServiceBusListenerTests()
        {
            _mockExecutor = new Mock <ITriggeredFunctionExecutor>(MockBehavior.Strict);

            _client = new ServiceBusClient(_testConnection);
            ServiceBusProcessor processor = _client.CreateProcessor(_entityPath);
            ServiceBusReceiver  receiver  = _client.CreateReceiver(_entityPath);
            var configuration             = ConfigurationUtilities.CreateConfiguration(new KeyValuePair <string, string>("connection", _testConnection));

            ServiceBusOptions config = new ServiceBusOptions
            {
                ProcessErrorAsync = ExceptionReceivedHandler
            };

            _mockMessageProcessor = new Mock <MessageProcessor>(MockBehavior.Strict, processor);

            _mockMessagingProvider = new Mock <MessagingProvider>(new OptionsWrapper <ServiceBusOptions>(config));
            _mockClientFactory     = new Mock <ServiceBusClientFactory>(configuration, Mock.Of <AzureComponentFactory>(), _mockMessagingProvider.Object, new AzureEventSourceLogForwarder(new NullLoggerFactory()), new OptionsWrapper <ServiceBusOptions>(new ServiceBusOptions()));
            _mockMessagingProvider
            .Setup(p => p.CreateMessageProcessor(It.IsAny <ServiceBusClient>(), _entityPath, It.IsAny <ServiceBusProcessorOptions>()))
            .Returns(_mockMessageProcessor.Object);

            _mockMessagingProvider
            .Setup(p => p.CreateBatchMessageReceiver(It.IsAny <ServiceBusClient>(), _entityPath, default))
            .Returns(receiver);

            _loggerFactory  = new LoggerFactory();
            _loggerProvider = new TestLoggerProvider();
            _loggerFactory.AddProvider(_loggerProvider);

            var concurrencyOptions = new OptionsWrapper <ConcurrencyOptions>(new ConcurrencyOptions());

            _mockConcurrencyThrottleManager = new Mock <IConcurrencyThrottleManager>(MockBehavior.Strict);
            var concurrencyManager = new ConcurrencyManager(concurrencyOptions, _loggerFactory, _mockConcurrencyThrottleManager.Object);

            _listener = new ServiceBusListener(
                _functionId,
                ServiceBusEntityType.Queue,
                _entityPath,
                false,
                config.AutoCompleteMessages,
                _mockExecutor.Object,
                config,
                "connection",
                _mockMessagingProvider.Object,
                _loggerFactory,
                false,
                _mockClientFactory.Object,
                concurrencyManager);
            _listener.Started = true;
        }
        public Task <ITriggerBinding> TryCreateAsync(TriggerBindingProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            ParameterInfo parameter = context.Parameter;
            var           attribute = TypeUtility.GetResolvedAttribute <ServiceBusTriggerAttribute>(parameter);

            if (attribute == null)
            {
                return(Task.FromResult <ITriggerBinding>(null));
            }

            string     queueName        = null;
            string     topicName        = null;
            string     subscriptionName = null;
            string     entityPath       = null;
            EntityType entityType;

            if (attribute.QueueName != null)
            {
                queueName  = Resolve(attribute.QueueName);
                entityPath = queueName;
                entityType = EntityType.Queue;
            }
            else
            {
                topicName        = Resolve(attribute.TopicName);
                subscriptionName = Resolve(attribute.SubscriptionName);
                entityPath       = EntityNameHelper.FormatSubscriptionPath(topicName, subscriptionName);
                entityType       = EntityType.Topic;
            }

            attribute.Connection = Resolve(attribute.Connection);
            ServiceBusAccount account = new ServiceBusAccount(_options, _configuration, attribute);

            Func <ListenerFactoryContext, bool, Task <IListener> > createListener =
                (factoryContext, singleDispatch) =>
            {
                IListener listener = new ServiceBusListener(factoryContext.Descriptor.Id, entityType, entityPath, attribute.IsSessionsEnabled, factoryContext.Executor, _options, account, _messagingProvider, _loggerFactory, singleDispatch);
                return(Task.FromResult(listener));
            };

#pragma warning disable 618
            ITriggerBinding binding = BindingFactory.GetTriggerBinding(new ServiceBusTriggerBindingStrategy(), parameter, _converterManager, createListener);
#pragma warning restore 618

            return(Task.FromResult <ITriggerBinding>(binding));
        }
Ejemplo n.º 17
0
            public async Task Failing_To_Attach_To_Transport_Manager_Will_Return_False()
            {
                //Arrange
                var transport        = new Mock <ITransport>();
                var transportManager = new ServiceBusTransportManager(transport.Object, Mock.Of <ICircuitBreaker>(), Mock.Of <IEventLogger>());
                var listener         = new ServiceBusListener(_mockSerialiser.Object, _mockHandlerResolver.Object,
                                                              _mockHandlerInvoker.Object);

                //Act
                var result = await listener.AttachTo(transportManager);

                //Assert
                Assert.That(result, Is.False);
            }
        public void Should_use_passed_in_queue_parameters_if_specified()
        {
            // Given
            var description = new QueueDescription(this.queueName);
            var listener = new ServiceBusListener(
                Enumerable.Empty<ISubscriber>(),
                this.serialiser,
                this.bus);

            // When
            listener.Connect(this.connectionString, this.queueName, description);

            // Then
            this.bus.VerifyQueueDescription.ShouldBeSameAs(description);
        }
        public void Should_connect()
        {
            // Given
            var listener = new ServiceBusListener(
                Enumerable.Empty <ISubscriber>(),
                this.serialiser,
                this.bus);

            // When
            listener.Connect(this.connectionString, this.queueName);

            // Then
            this.bus.ConnectionString.ShouldEqual(this.connectionString);
            this.bus.QueueName.ShouldEqual(this.queueName);
        }
        public void Should_use_passed_in_queue_parameters_if_specified()
        {
            // Given
            var description = new QueueDescription(this.queueName);
            var listener    = new ServiceBusListener(
                Enumerable.Empty <ISubscriber>(),
                this.serialiser,
                this.bus);

            // When
            listener.Connect(this.connectionString, this.queueName, description);

            // Then
            this.bus.VerifyQueueDescription.ShouldBeSameAs(description);
        }
        public void Should_connect()
        {
            // Given
            var listener = new ServiceBusListener(
                Enumerable.Empty<ISubscriber>(),
                this.serialiser,
                this.bus);

            // When
            listener.Connect(this.connectionString, this.queueName);

            // Then
            this.bus.ConnectionString.ShouldEqual(this.connectionString);
            this.bus.QueueName.ShouldEqual(this.queueName);
        }
        public Task <ITriggerBinding> TryCreateAsync(TriggerBindingProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            ParameterInfo parameter = context.Parameter;
            var           attribute = TypeUtility.GetResolvedAttribute <ServiceBusTriggerAttribute>(parameter);

            if (attribute == null)
            {
                return(Task.FromResult <ITriggerBinding>(null));
            }

            attribute.Connection = _nameResolver.ResolveWholeString(attribute.Connection);
            string entityPath;
            ServiceBusEntityType serviceBusEntityType;

            if (attribute.QueueName != null)
            {
                var queueName = _nameResolver.ResolveWholeString(attribute.QueueName);
                entityPath           = queueName;
                serviceBusEntityType = ServiceBusEntityType.Queue;
            }
            else
            {
                var topicName        = _nameResolver.ResolveWholeString(attribute.TopicName);
                var subscriptionName = _nameResolver.ResolveWholeString(attribute.SubscriptionName);
                entityPath           = EntityNameFormatter.FormatSubscriptionPath(topicName, subscriptionName);
                serviceBusEntityType = ServiceBusEntityType.Topic;
            }

            Func <ListenerFactoryContext, bool, Task <IListener> > createListener =
                (factoryContext, singleDispatch) =>
            {
                var       autoCompleteMessagesOptionEvaluatedValue = GetAutoCompleteMessagesOptionToUse(attribute, factoryContext.Descriptor.ShortName);
                IListener listener = new ServiceBusListener(factoryContext.Descriptor.Id, serviceBusEntityType, entityPath, attribute.IsSessionsEnabled, autoCompleteMessagesOptionEvaluatedValue, factoryContext.Executor, _options, attribute.Connection, _messagingProvider, _loggerFactory, singleDispatch, _clientFactory, _concurrencyManager);

                return(Task.FromResult(listener));
            };

#pragma warning disable 618
            ITriggerBinding binding = BindingFactory.GetTriggerBinding(new ServiceBusTriggerBindingStrategy(), parameter, _converterManager, createListener);
#pragma warning restore 618

            return(Task.FromResult <ITriggerBinding>(binding));
        }
        public void Should_verify_queue_on_connect()
        {
            // Given
            var listener = new ServiceBusListener(
                Enumerable.Empty<ISubscriber>(),
                this.serialiser,
                this.bus);

            // When
            listener.Connect(this.connectionString, this.queueName);

            // Then
            this.bus.VerifyQueueConnectionString.ShouldEqual(this.connectionString);
            this.bus.VerifyQueueDescription.ShouldNotBeNull();
            this.bus.VerifyQueueDescription.Path.ShouldEqual(this.queueName);
        }
Ejemplo n.º 24
0
        public async Task GetMetrics_DoesNotPeekBatchesWhenFirstAttemptReturnsNull()
        {
            _mockMessageReceiver.Setup(x => x.PeekMessageAsync(It.IsAny <long>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(() => null);

            _mockMessageReceiver.Verify(x => x.PeekMessagesAsync(It.IsAny <int>(), It.IsAny <long>(), It.IsAny <CancellationToken>()), Times.Never);

            ServiceBusListener listener = CreateListener();

            var metrics = await((ServiceBusScaleMonitor)listener.GetMonitor()).GetMetricsAsync();

            Assert.AreEqual(0, metrics.PartitionCount);
            Assert.AreEqual(0, metrics.MessageCount);
            Assert.AreEqual(TimeSpan.FromSeconds(0), metrics.QueueTime);
            Assert.AreNotEqual(default(DateTime), metrics.Timestamp);
        }
        public void Should_verify_queue_on_connect()
        {
            // Given
            var listener = new ServiceBusListener(
                Enumerable.Empty <ISubscriber>(),
                this.serialiser,
                this.bus);

            // When
            listener.Connect(this.connectionString, this.queueName);

            // Then
            this.bus.VerifyQueueConnectionString.ShouldEqual(this.connectionString);
            this.bus.VerifyQueueDescription.ShouldNotBeNull();
            this.bus.VerifyQueueDescription.Path.ShouldEqual(this.queueName);
        }
Ejemplo n.º 26
0
        public async Task GetMetrics_CalculatesMetrics()
        {
            var message = ServiceBusModelFactory.ServiceBusReceivedMessage(enqueuedTime: DateTimeOffset.UtcNow.Subtract(TimeSpan.FromSeconds(30)));

            _mockMessageReceiver.Setup(x => x.PeekMessageAsync(It.IsAny <long>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(message);

            ServiceBusListener listener = CreateListener();

            var metrics = await((ServiceBusScaleMonitor)listener.GetMonitor()).GetMetricsAsync();

            Assert.AreEqual(0, metrics.PartitionCount);
            Assert.AreEqual(1, metrics.MessageCount);
            Assert.That(metrics.QueueTime, Is.GreaterThanOrEqualTo(TimeSpan.FromSeconds(30)));
            Assert.AreNotEqual(default(DateTime), metrics.Timestamp);
        }
Ejemplo n.º 27
0
            public void If_Empty_Byte_Array_Is_Received_Then_A_Null_Reference_Exception_Should_Be_Thrown()
            {
                //Arrange
                var mockBytes = new byte[] { };
                var listener  = new ServiceBusListener(_mockSerialiser.Object, _mockHandlerResolver.Object,
                                                       _mockHandlerInvoker.Object);

                //Act
                async Task Delegate()
                {
                    await listener.ReceiveMessage(mockBytes, CancellationToken.None);
                }

                //Assert
                Assert.That(Delegate, Throws.TypeOf <NullReferenceException>());
            }
Ejemplo n.º 28
0
            public async Task Listener_Can_Be_Attached_To_An_Active_Transport_Manager()
            {
                //Arrange
                var transport = new Mock <ITransport>();

                transport.Setup(x => x.Configuration).Returns(new TransportConfiguration());
                var transportManager = new ServiceBusTransportManager(transport.Object, Mock.Of <ICircuitBreaker>(), Mock.Of <IEventLogger>());
                var listener         = new ServiceBusListener(_mockSerialiser.Object, _mockHandlerResolver.Object,
                                                              _mockHandlerInvoker.Object);

                //Act
                var result = await listener.AttachTo(transportManager);

                //Assert
                Assert.That(result, Is.True);
                Assert.That(transport.Object.Configuration.Listeners, Has.Exactly(1).EqualTo(listener));
            }
Ejemplo n.º 29
0
            public void Receive_Message_Transactional_Will_Throw_A_Not_Implemented_Exception()
            {
                //Arrange
                var mockBytes       = new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 };
                var mockTransaction = new Mock <ITransaction>();
                var listener        = new ServiceBusListener(_mockSerialiser.Object, _mockHandlerResolver.Object,
                                                             _mockHandlerInvoker.Object);

                //Act
                async Task Delegate()
                {
                    await listener.ReceiveMessageTransactional(mockBytes, mockTransaction.Object, CancellationToken.None);
                }

                //Assert
                Assert.That(Delegate, Throws.TypeOf <NotImplementedException>());
            }
        static void Main(string[] args)
        {
            Console.Write("Enter connectionstring: ");
            var connectionString = Console.ReadLine();

            Console.Write("Enter queue name: ");
            var queueName = Console.ReadLine();

            var listener = new ServiceBusListener(new[] { new BusSubscriber() });

            listener.Connect(connectionString, queueName);

            while (true)
            {
                Thread.Sleep(1000);
            }
        }
Ejemplo n.º 31
0
        public async Task GetMetrics_DoesNotPeekBatchesWhenFirstAttemptReturnsActive()
        {
            var activeMessage = ServiceBusModelFactory.ServiceBusReceivedMessage(enqueuedTime: DateTimeOffset.UtcNow.Subtract(TimeSpan.FromSeconds(30)), sequenceNumber: 2);

            _mockMessageReceiver.Setup(x => x.PeekMessageAsync(It.IsAny <long>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(activeMessage);

            _mockMessageReceiver.Verify(x => x.PeekMessagesAsync(It.IsAny <int>(), It.IsAny <long>(), It.IsAny <CancellationToken>()), Times.Never);

            ServiceBusListener listener = CreateListener();

            var metrics = await((ServiceBusScaleMonitor)listener.GetMonitor()).GetMetricsAsync();

            Assert.AreEqual(0, metrics.PartitionCount);
            Assert.AreEqual(1, metrics.MessageCount);
            Assert.That(metrics.QueueTime, Is.GreaterThanOrEqualTo(TimeSpan.FromSeconds(30)));
            Assert.AreNotEqual(default(DateTime), metrics.Timestamp);
        }
Ejemplo n.º 32
0
        public async Task GetMetrics_IgnoresEmptyBatch()
        {
            var deferredMessage = ServiceBusModelFactory.ServiceBusReceivedMessage(serviceBusMessageState: ServiceBusMessageState.Deferred);

            _mockMessageReceiver.Setup(x => x.PeekMessageAsync(It.IsAny <long>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(deferredMessage);

            _mockMessageReceiver.Setup(x => x.PeekMessagesAsync(It.IsAny <int>(), It.IsAny <long>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(new List <ServiceBusReceivedMessage>());

            ServiceBusListener listener = CreateListener();

            var metrics = await((ServiceBusScaleMonitor)listener.GetMonitor()).GetMetricsAsync();

            Assert.AreEqual(0, metrics.PartitionCount);
            Assert.AreEqual(0, metrics.MessageCount);
            Assert.AreEqual(TimeSpan.FromSeconds(0), metrics.QueueTime);
            Assert.AreNotEqual(default(DateTime), metrics.Timestamp);
        }
Ejemplo n.º 33
0
        public ServiceBusListenerTests()
        {
            _mockExecutor = new Mock <ITriggeredFunctionExecutor>(MockBehavior.Strict);

            var client = new ServiceBusClient(_testConnection);
            ServiceBusProcessor processor = client.CreateProcessor(_entityPath);
            ServiceBusReceiver  receiver  = client.CreateReceiver(_entityPath);
            var configuration             = ConfigurationUtilities.CreateConfiguration(new KeyValuePair <string, string>("connection", _testConnection));

            ServiceBusOptions config = new ServiceBusOptions
            {
                ExceptionHandler = ExceptionReceivedHandler
            };

            _mockMessageProcessor = new Mock <MessageProcessor>(MockBehavior.Strict, processor, receiver);

            _mockMessagingProvider = new Mock <MessagingProvider>(new OptionsWrapper <ServiceBusOptions>(config));
            _mockClientFactory     = new Mock <ServiceBusClientFactory>(configuration, Mock.Of <AzureComponentFactory>(), _mockMessagingProvider.Object);
            _mockMessagingProvider
            .Setup(p => p.CreateMessageProcessor(It.IsAny <ServiceBusClient>(), _entityPath))
            .Returns(_mockMessageProcessor.Object);

            _mockMessagingProvider
            .Setup(p => p.CreateBatchMessageReceiver(It.IsAny <ServiceBusClient>(), _entityPath))
            .Returns(receiver);

            _loggerFactory  = new LoggerFactory();
            _loggerProvider = new TestLoggerProvider();
            _loggerFactory.AddProvider(_loggerProvider);

            _listener = new ServiceBusListener(
                _functionId,
                EntityType.Queue,
                _entityPath,
                false,
                _mockExecutor.Object,
                config,
                "connection",
                _mockMessagingProvider.Object,
                _loggerFactory,
                false,
                _mockClientFactory.Object);
        }
        public void Should_complete_message_if_no_error()
        {
            // Given
            var subscriberOne = A.Fake<IDynamicSubscriber>();
            string foo = null;
            long baz = 0;
            A.CallTo(() => subscriberOne.CanProcess(A<IServiceBusMessage>._))
             .Returns(true);
            A.CallTo(() => subscriberOne.Process(A<IServiceBusMessage>._, A<object>._))
                .Invokes(foc =>
                {
                    dynamic model = foc.Arguments[1];

                    foo = model.Foo;
                    baz = model.Baz;
                }).Returns(Task.FromResult(0));
            var listener = new ServiceBusListener(
                new[] { subscriberOne },
                new SimpleJsonSerialiser(),
                this.bus);
            var message = this.GetMessage("foo", "{ \"Foo\" : \"Bar\", \"Baz\" : 23 }");
            listener.Connect(this.connectionString, this.queueName);

            // When
            this.bus.CallBack.Invoke(message).Wait();

            // Then
            message.Completed.ShouldBeTrue();
            message.Abandoned.ShouldBeFalse();
        }
        public void Should_abandon_message_if_errors()
        {
            // Given
            var subscriberOne = A.Fake<IDynamicSubscriber>();
            string foo = null;
            long baz = 0;
            A.CallTo(() => subscriberOne.CanProcess(A<IServiceBusMessage>._))
             .Returns(true);
            A.CallTo(() => subscriberOne.Process(A<IServiceBusMessage>._, A<object>._))
                .Invokes(foc =>
                {
                    throw new InvalidOperationException();
                });
            var listener = new ServiceBusListener(
                new[] { subscriberOne },
                new SimpleJsonSerialiser(),
                this.bus);
            var message = this.GetMessage("foo", "{ \"Foo\" : \"Bar\", \"Baz\" : 23 }");
            listener.Connect(this.connectionString, this.queueName);

            // When
            this.bus.CallBack.Invoke(message).Wait();

            // Then
            message.Completed.ShouldBeFalse();
            message.Abandoned.ShouldBeTrue();
        }
        public void Should_call_can_process_on_each_subscriber()
        {
            // Given
            var subscriberOne = A.Fake<ISubscriber>();
            var subscriberTwo = A.Fake<ISubscriber>();
            var listener = new ServiceBusListener(
                new[] { subscriberOne, subscriberTwo },
                this.serialiser,
                this.bus);
            var message = this.GetMessage("foo");
            listener.Connect(this.connectionString, this.queueName);

            // When
            this.bus.CallBack.Invoke(message).Wait();

            // Then
            A.CallTo(() => subscriberOne.CanProcess(A<IServiceBusMessage>._))
             .MustHaveHappened(Repeated.Exactly.Once);
            A.CallTo(() => subscriberTwo.CanProcess(A<IServiceBusMessage>._))
             .MustHaveHappened(Repeated.Exactly.Once);
        }