| | | 1 | | using System.Threading.Channels; |
| | | 2 | | using Elsa.Mediator.Contracts; |
| | | 3 | | using Elsa.Mediator.Middleware.Notification; |
| | | 4 | | using Elsa.Mediator.Options; |
| | | 5 | | using Microsoft.Extensions.DependencyInjection; |
| | | 6 | | using Microsoft.Extensions.Hosting; |
| | | 7 | | using Microsoft.Extensions.Logging; |
| | | 8 | | using Microsoft.Extensions.Options; |
| | | 9 | | |
| | | 10 | | namespace Elsa.Mediator.HostedServices; |
| | | 11 | | |
| | | 12 | | /// <summary> |
| | | 13 | | /// Continuously reads from a channel to which notifications can be sent, publishing each received notification. |
| | | 14 | | /// </summary> |
| | | 15 | | public class BackgroundEventPublisherHostedService : BackgroundService |
| | | 16 | | { |
| | | 17 | | private readonly int _workerCount; |
| | | 18 | | private readonly INotificationsChannel _notificationsChannel; |
| | | 19 | | private readonly IServiceScopeFactory _scopeFactory; |
| | | 20 | | private readonly List<Channel<NotificationContext>> _outputs; |
| | | 21 | | private readonly ILogger _logger; |
| | | 22 | | |
| | | 23 | | /// <inheritdoc /> |
| | 1 | 24 | | public BackgroundEventPublisherHostedService(IOptions<MediatorOptions> options, INotificationsChannel notificationsC |
| | | 25 | | { |
| | 1 | 26 | | _workerCount = options.Value.NotificationWorkerCount; |
| | 1 | 27 | | _notificationsChannel = notificationsChannel; |
| | 1 | 28 | | _scopeFactory = scopeFactory; |
| | 1 | 29 | | _logger = logger; |
| | 1 | 30 | | _outputs = new(_workerCount); |
| | 1 | 31 | | } |
| | | 32 | | |
| | | 33 | | /// <inheritdoc /> |
| | | 34 | | protected override async Task ExecuteAsync(CancellationToken cancellationToken) |
| | | 35 | | { |
| | | 36 | | // Index to round-robin distribute notifications across worker channels |
| | 1 | 37 | | var index = 0; |
| | | 38 | | |
| | 1 | 39 | | using var scope = _scopeFactory.CreateScope(); |
| | 1 | 40 | | var notificationSender = scope.ServiceProvider.GetRequiredService<INotificationSender>(); |
| | | 41 | | |
| | | 42 | | // Create multiple output channels and start worker tasks for parallel processing |
| | 10 | 43 | | for (var i = 0; i < _workerCount; i++) |
| | | 44 | | { |
| | 4 | 45 | | var output = Channel.CreateUnbounded<NotificationContext>(); |
| | 4 | 46 | | _outputs.Add(output); |
| | | 47 | | // Start a background task to process notifications from this output channel |
| | 4 | 48 | | _ = ReadOutputAsync(output, notificationSender, cancellationToken); |
| | | 49 | | } |
| | | 50 | | |
| | 1 | 51 | | var channelReader = _notificationsChannel.Reader; |
| | | 52 | | |
| | | 53 | | // Continuously read notifications from the input channel and distribute them to worker channels |
| | | 54 | | // using round-robin distribution for load balancing |
| | 2 | 55 | | await foreach (var notification in channelReader.ReadAllAsync(cancellationToken)) |
| | | 56 | | { |
| | 0 | 57 | | var output = _outputs[index]; |
| | 0 | 58 | | await output.Writer.WriteAsync(notification, cancellationToken); |
| | | 59 | | // Move to the next worker in a circular fashion |
| | 0 | 60 | | index = (index + 1) % _workerCount; |
| | | 61 | | } |
| | | 62 | | |
| | | 63 | | // When the input channel is completed, complete all output channels |
| | 0 | 64 | | foreach (var output in _outputs) |
| | | 65 | | { |
| | 0 | 66 | | output.Writer.Complete(); |
| | | 67 | | } |
| | 0 | 68 | | } |
| | | 69 | | |
| | | 70 | | /// <summary> |
| | | 71 | | /// Processes notifications from an output channel asynchronously. |
| | | 72 | | /// </summary> |
| | | 73 | | /// <param name="output">The channel to read notifications from</param> |
| | | 74 | | /// <param name="notificationSender">The service used to send notifications</param> |
| | | 75 | | /// <param name="cancellationToken">Cancellation token from the hosted service</param> |
| | | 76 | | private async Task ReadOutputAsync(Channel<NotificationContext> output, INotificationSender notificationSender, Canc |
| | | 77 | | { |
| | 8 | 78 | | await foreach (var notificationContext in output.Reader.ReadAllAsync(cancellationToken)) |
| | | 79 | | { |
| | | 80 | | try |
| | | 81 | | { |
| | 0 | 82 | | var notification = notificationContext.Notification; |
| | | 83 | | // Link the cancellation tokens so that cancellation can happen from either source |
| | 0 | 84 | | using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, notific |
| | 0 | 85 | | await notificationSender.SendAsync(notification, NotificationStrategy.Sequential, linkedTokenSource.Toke |
| | 0 | 86 | | } |
| | 0 | 87 | | catch (OperationCanceledException e) |
| | | 88 | | { |
| | 0 | 89 | | _logger.LogDebug(e, "An operation was cancelled while processing the queue"); |
| | 0 | 90 | | } |
| | 0 | 91 | | catch (Exception e) |
| | | 92 | | { |
| | 0 | 93 | | _logger.LogError(e, "An unhandled exception occurred while processing the queue"); |
| | 0 | 94 | | } |
| | | 95 | | } |
| | 0 | 96 | | } |
| | | 97 | | } |