Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using Azure.Messaging.ServiceBus.Primitives;
using Microsoft.Azure.WebJobs.Description;
using Microsoft.Azure.WebJobs.Extensions.ServiceBus.Config;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Azure.WebJobs.Host.Bindings;
using Microsoft.Azure.WebJobs.Host.Config;
using Microsoft.Azure.WebJobs.Host.Scale;
Expand All @@ -33,6 +34,7 @@ internal class ServiceBusExtensionConfigProvider : IExtensionConfigProvider
private readonly IConverterManager _converterManager;
private readonly ServiceBusClientFactory _clientFactory;
private readonly ConcurrencyManager _concurrencyManager;
private readonly IDrainModeManager _drainModeManager;

/// <summary>
/// Creates a new <see cref="ServiceBusExtensionConfigProvider"/> instance.
Expand All @@ -45,7 +47,8 @@ public ServiceBusExtensionConfigProvider(
ILoggerFactory loggerFactory,
IConverterManager converterManager,
ServiceBusClientFactory clientFactory,
ConcurrencyManager concurrencyManager)
ConcurrencyManager concurrencyManager,
IDrainModeManager drainModeManager)
{
_options = options.Value;
_messagingProvider = messagingProvider;
Expand All @@ -54,6 +57,7 @@ public ServiceBusExtensionConfigProvider(
_converterManager = converterManager;
_clientFactory = clientFactory;
_concurrencyManager = concurrencyManager;
_drainModeManager = drainModeManager;
}

/// <summary>
Expand Down Expand Up @@ -101,7 +105,16 @@ public void Initialize(ExtensionConfigContext context)
.AddOpenConverter<ServiceBusReceivedMessage, OpenType.Poco>(typeof(MessageToPocoConverter<>), _options.JsonSerializerSettings);

// register our trigger binding provider
ServiceBusTriggerAttributeBindingProvider triggerBindingProvider = new ServiceBusTriggerAttributeBindingProvider(_nameResolver, _options, _messagingProvider, _loggerFactory, _converterManager, _clientFactory, _concurrencyManager);
ServiceBusTriggerAttributeBindingProvider triggerBindingProvider = new ServiceBusTriggerAttributeBindingProvider(
_nameResolver,
_options,
_messagingProvider,
_loggerFactory,
_converterManager,
_clientFactory,
_concurrencyManager,
_drainModeManager);

context.AddBindingRule<ServiceBusTriggerAttribute>()
.BindToTrigger(triggerBindingProvider);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
using Azure.Messaging.ServiceBus.Diagnostics;
using Microsoft.Azure.WebJobs.Extensions.ServiceBus.Config;
using Microsoft.Azure.WebJobs.Extensions.ServiceBus.Listeners;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Azure.WebJobs.Host.Executors;
using Microsoft.Azure.WebJobs.Host.Listeners;
using Microsoft.Azure.WebJobs.Host.Scale;
Expand All @@ -29,7 +30,8 @@ internal sealed class ServiceBusListener : IListener, IScaleMonitorProvider, ITa
private readonly string _entityPath;
private readonly bool _isSessionsEnabled;
private readonly bool _autoCompleteMessages;
private readonly CancellationTokenSource _cancellationTokenSource;
private readonly CancellationTokenSource _stoppingCancellationTokenSource;
private readonly CancellationTokenSource _functionExecutionCancellationTokenSource;
private readonly ServiceBusOptions _serviceBusOptions;
private readonly bool _singleDispatch;
private readonly ILogger<ServiceBusListener> _logger;
Expand Down Expand Up @@ -65,6 +67,7 @@ internal sealed class ServiceBusListener : IListener, IScaleMonitorProvider, ITa
private Task _batchLoop;
private Lazy<string> _details;
private Lazy<MessagingClientDiagnostics> _clientDiagnostics;
private readonly IDrainModeManager _drainModeManager;

public ServiceBusListener(
string functionId,
Expand All @@ -79,15 +82,18 @@ public ServiceBusListener(
ILoggerFactory loggerFactory,
bool singleDispatch,
ServiceBusClientFactory clientFactory,
ConcurrencyManager concurrencyManager)
ConcurrencyManager concurrencyManager,
IDrainModeManager drainModeManager)
{
_entityPath = entityPath;
_isSessionsEnabled = isSessionsEnabled;
_autoCompleteMessages = autoCompleteMessages;
_triggerExecutor = triggerExecutor;
_cancellationTokenSource = new CancellationTokenSource();
_stoppingCancellationTokenSource = new CancellationTokenSource();
_functionExecutionCancellationTokenSource = new CancellationTokenSource();
_logger = loggerFactory.CreateLogger<ServiceBusListener>();
_functionId = functionId;
_drainModeManager = drainModeManager;

_client = new Lazy<ServiceBusClient>(
() => clientFactory.CreateClientFromSetting(connection));
Expand Down Expand Up @@ -195,7 +201,7 @@ public async Task StartAsync(CancellationToken cancellationToken)
}
else
{
_batchLoop = RunBatchReceiveLoopAsync(_cancellationTokenSource);
_batchLoop = RunBatchReceiveLoopAsync(_stoppingCancellationTokenSource);
}
}
catch
Expand All @@ -211,6 +217,11 @@ public async Task StartAsync(CancellationToken cancellationToken)

public async Task StopAsync(CancellationToken cancellationToken)
{
if (!_drainModeManager.IsDrainModeEnabled)
{
_functionExecutionCancellationTokenSource.Cancel();
}

ThrowIfDisposed();

_logger.LogDebug($"Attempting to stop ServiceBus listener ({_details.Value})");
Expand All @@ -226,7 +237,7 @@ public async Task StopAsync(CancellationToken cancellationToken)
}

// This will also cancel the background monitoring task through the linked cancellation token source.
_cancellationTokenSource.Cancel();
_stoppingCancellationTokenSource.Cancel();

// CloseAsync method stop new messages from being processed while allowing in-flight messages to be processed.
if (_singleDispatch)
Expand Down Expand Up @@ -273,7 +284,7 @@ public async Task StopAsync(CancellationToken cancellationToken)
public void Cancel()
{
ThrowIfDisposed();
_cancellationTokenSource.Cancel();
_stoppingCancellationTokenSource.Cancel();
}

[SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed", MessageId = "_cancellationTokenSource")]
Expand All @@ -290,7 +301,8 @@ public void Dispose()
// Mark it canceled but don't dispose of the source while the callers are running.
// Otherwise, callers would receive ObjectDisposedException when calling token.Register.
// For now, rely on finalization to clean up _cancellationTokenSource's wait handle (if allocated).
_cancellationTokenSource.Cancel();
_stoppingCancellationTokenSource.Cancel();
_functionExecutionCancellationTokenSource.Cancel();

if (_batchReceiver.IsValueCreated)
{
Expand Down Expand Up @@ -321,10 +333,14 @@ public void Dispose()
}

_stopAsyncSemaphore.Dispose();
_cancellationTokenSource.Dispose();
_stoppingCancellationTokenSource.Dispose();
_batchReceiveRegistration.Dispose();
_concurrencyUpdateManager?.Dispose();

// No need to dispose the _disposingCancellationTokenSource since we don't create it as a linked token and
// it won't use a timer, so the Dispose method is essentially a no-op. The downside to disposing it is that
// any customers who are trying to use it to cancel their own operations would get an ObjectDisposedException.

Disposed = true;

_logger.LogDebug($"ServiceBus listener disposed({_details.Value})");
Expand All @@ -336,7 +352,7 @@ internal async Task ProcessMessageAsync(ProcessMessageEventArgs args)

_concurrencyUpdateManager?.MessageProcessed();

using (CancellationTokenSource linkedCts = CancellationTokenSource.CreateLinkedTokenSource(args.CancellationToken, _cancellationTokenSource.Token))
using (CancellationTokenSource linkedCts = CancellationTokenSource.CreateLinkedTokenSource(args.CancellationToken, _stoppingCancellationTokenSource.Token))
{
var actions = new ServiceBusMessageActions(args);
if (!await _messageProcessor.Value.BeginProcessingMessageAsync(actions, args.Message, linkedCts.Token).ConfigureAwait(false))
Expand All @@ -349,7 +365,7 @@ internal async Task ProcessMessageAsync(ProcessMessageEventArgs args)

TriggeredFunctionData data = input.GetTriggerFunctionData();

FunctionResult result = await _triggerExecutor.TryExecuteAsync(data, linkedCts.Token).ConfigureAwait(false);
FunctionResult result = await _triggerExecutor.TryExecuteAsync(data, _functionExecutionCancellationTokenSource.Token).ConfigureAwait(false);
try
{
await _messageProcessor.Value.CompleteProcessingMessageAsync(actions, args.Message, result, linkedCts.Token)
Expand All @@ -369,7 +385,7 @@ internal async Task ProcessSessionMessageAsync(ProcessSessionMessageEventArgs ar
_concurrencyUpdateManager?.MessageProcessed();

using (CancellationTokenSource linkedCts =
CancellationTokenSource.CreateLinkedTokenSource(args.CancellationToken, _cancellationTokenSource.Token))
CancellationTokenSource.CreateLinkedTokenSource(args.CancellationToken, _stoppingCancellationTokenSource.Token))
{
var actions = new ServiceBusSessionMessageActions(args);
if (!await _sessionMessageProcessor.Value.BeginProcessingMessageAsync(actions, args.Message, linkedCts.Token)
Expand All @@ -382,7 +398,7 @@ internal async Task ProcessSessionMessageAsync(ProcessSessionMessageEventArgs ar
ServiceBusTriggerInput input = ServiceBusTriggerInput.CreateSingle(args.Message, actions, receiveActions, _client.Value);

TriggeredFunctionData data = input.GetTriggerFunctionData();
FunctionResult result = await _triggerExecutor.TryExecuteAsync(data, linkedCts.Token).ConfigureAwait(false);
FunctionResult result = await _triggerExecutor.TryExecuteAsync(data, _functionExecutionCancellationTokenSource.Token).ConfigureAwait(false);

if (actions.ShouldReleaseSession)
{
Expand Down Expand Up @@ -643,7 +659,7 @@ private async Task TriggerAndCompleteMessagesInternal(ServiceBusReceivedMessage[
scope.SetMessageData(messagesArray);

scope.Start();
FunctionResult result = await _triggerExecutor.TryExecuteAsync(input.GetTriggerFunctionData(), cancellationToken).ConfigureAwait(false);
FunctionResult result = await _triggerExecutor.TryExecuteAsync(input.GetTriggerFunctionData(), _functionExecutionCancellationTokenSource.Token).ConfigureAwait(false);
if (result.Exception != null)
{
scope.Failed(result.Exception);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ internal class ServiceBusTriggerAttributeBindingProvider : ITriggerBindingProvid
private readonly ServiceBusClientFactory _clientFactory;
private readonly ILogger<ServiceBusTriggerAttributeBindingProvider> _logger;
private readonly ConcurrencyManager _concurrencyManager;
private readonly IDrainModeManager _drainModeManager;

public ServiceBusTriggerAttributeBindingProvider(
INameResolver nameResolver,
Expand All @@ -36,7 +37,8 @@ public ServiceBusTriggerAttributeBindingProvider(
ILoggerFactory loggerFactory,
IConverterManager converterManager,
ServiceBusClientFactory clientFactory,
ConcurrencyManager concurrencyManager)
ConcurrencyManager concurrencyManager,
IDrainModeManager drainModeManager)
{
_nameResolver = nameResolver ?? throw new ArgumentNullException(nameof(nameResolver));
_options = options ?? throw new ArgumentNullException(nameof(options));
Expand All @@ -46,6 +48,7 @@ public ServiceBusTriggerAttributeBindingProvider(
_clientFactory = clientFactory;
_logger = _loggerFactory.CreateLogger<ServiceBusTriggerAttributeBindingProvider>();
_concurrencyManager = concurrencyManager;
_drainModeManager = drainModeManager;
}

public Task<ITriggerBinding> TryCreateAsync(TriggerBindingProviderContext context)
Expand Down Expand Up @@ -84,7 +87,21 @@ public Task<ITriggerBinding> TryCreateAsync(TriggerBindingProviderContext contex
(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);
IListener listener = new ServiceBusListener(
factoryContext.Descriptor.Id,
serviceBusEntityType,
entityPath,
attribute.IsSessionsEnabled,
autoCompleteMessagesOptionEvaluatedValue,
factoryContext.Executor,
_options,
attribute.Connection,
_messagingProvider,
_loggerFactory,
singleDispatch,
_clientFactory,
_concurrencyManager,
_drainModeManager);

return Task.FromResult(listener);
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public ServiceBusTriggerAttributeBindingProviderTests()
Mock<IConverterManager> convertManager = new Mock<IConverterManager>(MockBehavior.Default);
var provider = new MessagingProvider(new OptionsWrapper<ServiceBusOptions>(options));
var factory = new ServiceBusClientFactory(configuration, new Mock<AzureComponentFactory>().Object, provider, new AzureEventSourceLogForwarder(new NullLoggerFactory()), new OptionsWrapper<ServiceBusOptions>(options));
_provider = new ServiceBusTriggerAttributeBindingProvider(mockResolver.Object, options, provider, NullLoggerFactory.Instance, convertManager.Object, factory, concurrencyManager);
_provider = new ServiceBusTriggerAttributeBindingProvider(mockResolver.Object, options, provider, NullLoggerFactory.Instance, convertManager.Object, factory, concurrencyManager, default);
}

[Test]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using System.Threading.Tasks;
using Azure.Messaging.ServiceBus;
using Microsoft.Azure.WebJobs.Extensions.ServiceBus.Config;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Azure.WebJobs.Host.Executors;
using Microsoft.Azure.WebJobs.Host.Scale;
using Microsoft.Azure.WebJobs.Host.TestCommon;
Expand Down Expand Up @@ -39,6 +40,7 @@ public class ServiceBusListenerTests
private readonly Mock<IConcurrencyThrottleManager> _mockConcurrencyThrottleManager;
private readonly ServiceBusClient _client;
private readonly ConcurrencyManager _concurrencyManager;
private readonly Mock<IDrainModeManager> _mockDrainModeManager;

public ServiceBusListenerTests()
{
Expand All @@ -58,6 +60,9 @@ public ServiceBusListenerTests()
_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()));

_mockDrainModeManager = new Mock<IDrainModeManager>();
_mockDrainModeManager.Setup(p => p.IsDrainModeEnabled).Returns(true);

_mockMessagingProvider
.Setup(p => p.CreateMessageProcessor(It.IsAny<ServiceBusClient>(), _entityPath, It.IsAny<ServiceBusProcessorOptions>()))
.Returns(_mockMessageProcessor.Object);
Expand Down Expand Up @@ -87,7 +92,8 @@ public ServiceBusListenerTests()
_loggerFactory,
false,
_mockClientFactory.Object,
_concurrencyManager);
_concurrencyManager,
_mockDrainModeManager.Object);
}

[SetUp]
Expand Down Expand Up @@ -246,7 +252,8 @@ public async Task SessionIdleTimeoutRespected()
_loggerFactory,
false,
_mockClientFactory.Object,
_concurrencyManager);
_concurrencyManager,
_mockDrainModeManager.Object);

await listener.StartAsync(CancellationToken.None);
await listener.StopAsync(CancellationToken.None);
Expand Down Expand Up @@ -290,7 +297,8 @@ public async Task SessionIdleTimeoutIgnoredWhenNotUsingSessions()
_loggerFactory,
false,
_mockClientFactory.Object,
_concurrencyManager);
_concurrencyManager,
_mockDrainModeManager.Object);

await listener.StartAsync(CancellationToken.None);
await listener.StopAsync(CancellationToken.None);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,8 @@ public void Setup()
_loggerFactory,
false,
_mockClientFactory.Object,
concurrencyManager);
concurrencyManager,
default);

_scaleMonitor = (ServiceBusScaleMonitor)_listener.GetMonitor();
}
Expand Down Expand Up @@ -539,7 +540,8 @@ private ServiceBusListener CreateListener(bool useDeadletterQueue = false)
_loggerFactory,
false,
_mockClientFactory.Object,
concurrencyManager);
concurrencyManager,
default);
}

[Test]
Expand Down
Loading