public async Task GetMetrics_HandlesExceptions()
        {
            // MessagingEntityNotFoundException
            _mockProvider
            .Setup(p => p.CreateBatchMessageReceiver(_client, _entityPath))
            .Throws(new ServiceBusException("", reason: ServiceBusFailureReason.MessagingEntityNotFound));

            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);

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

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

            // UnauthorizedAccessException
            _mockProvider
            .Setup(p => p.CreateBatchMessageReceiver(_client, _entityPath))
            .Throws(new UnauthorizedAccessException(""));
            listener = CreateListener();

            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
            _mockProvider
            .Setup(p => p.CreateBatchMessageReceiver(_client, _entityPath))
            .Throws(new Exception("Uh oh"));
            listener = CreateListener();

            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);
        }
Example #2
0
        public void GetMonitor_ReturnsExpectedValue()
        {
            IScaleMonitor scaleMonitor = _listener.GetMonitor();

            Assert.AreEqual(typeof(ServiceBusScaleMonitor), scaleMonitor.GetType());
            Assert.AreEqual(scaleMonitor.Descriptor.Id, $"{_functionId}-ServiceBusTrigger-{_entityPath}".ToLower());

            var scaleMonitor2 = _listener.GetMonitor();

            Assert.AreSame(scaleMonitor, scaleMonitor2);
        }
Example #3
0
        public ServiceBusScaleMonitorTests()
        {
            _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 = new ServiceBusOptions
            {
                MessageHandlerOptions = messageOptions
            };
            _mockMessagingProvider = new Mock <MessagingProvider>(MockBehavior.Strict, new OptionsWrapper <ServiceBusOptions>(_serviceBusOptions));

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

            _triggerExecutor       = new ServiceBusTriggerExecutor(_mockExecutor.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, _triggerExecutor, _serviceBusOptions, _mockServiceBusAccount.Object,
                                               _mockMessagingProvider.Object, _loggerFactory);
            _scaleMonitor = (ServiceBusScaleMonitor)_listener.GetMonitor();
        }
        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();
        }
        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();
        }
Example #6
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);
        }
Example #7
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);
        }
Example #8
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);
        }
Example #9
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);
        }
Example #10
0
        public async Task GetMetrics_GiveUpAfterFirstAndBatchPeekDoesntReturnActive()
        {
            var firstDeferredMessage = ServiceBusModelFactory.ServiceBusReceivedMessage(serviceBusMessageState: ServiceBusMessageState.Deferred);

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

            _mockMessageReceiver.Setup(x => x.PeekMessagesAsync(It.IsAny <int>(), It.IsAny <long>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync((int batchSize, long _, CancellationToken __) => Enumerable.Range(1, batchSize)
                          .Select(i => ServiceBusModelFactory.ServiceBusReceivedMessage(serviceBusMessageState: ServiceBusMessageState.Scheduled))
                          .ToList());

            ServiceBusListener listener = CreateListener();

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

            Assert.AreEqual(0, metrics.PartitionCount);
            Assert.AreEqual(0, metrics.MessageCount);
            Assert.AreEqual(TimeSpan.FromSeconds(0), metrics.QueueTime);
            Assert.AreNotEqual(default(DateTime), metrics.Timestamp);
        }
Example #11
0
        public async Task GetMetrics_PeeksOneFromHeadAndTenWithBatching()
        {
            var deferredMessage = ServiceBusModelFactory.ServiceBusReceivedMessage(serviceBusMessageState: ServiceBusMessageState.Deferred);
            var activeMessage   = ServiceBusModelFactory.ServiceBusReceivedMessage(enqueuedTime: DateTimeOffset.UtcNow.Subtract(TimeSpan.FromSeconds(30)), sequenceNumber: 2);

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

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

            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);
        }
Example #12
0
        public async Task GetMetrics_IgnoresDeferredOrScheduledMessagesUntilItFindsAnActive()
        {
            var firstDeferredMessage   = ServiceBusModelFactory.ServiceBusReceivedMessage(serviceBusMessageState: ServiceBusMessageState.Deferred);
            var secondScheduledMessage = ServiceBusModelFactory.ServiceBusReceivedMessage(serviceBusMessageState: ServiceBusMessageState.Scheduled);
            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(firstDeferredMessage);

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

            ServiceBusListener listener = CreateListener();

            var serviceBusScaleMonitor = (ServiceBusScaleMonitor)listener.GetMonitor();
            var metrics = await serviceBusScaleMonitor.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);
        }