| | | 1 | | using System.Threading.Channels; |
| | | 2 | | using Elsa.Mediator.Contracts; |
| | | 3 | | using Elsa.Mediator.Middleware.Command; |
| | | 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 commands can be sent, executing each received command. |
| | | 14 | | /// </summary> |
| | | 15 | | public class BackgroundCommandSenderHostedService : BackgroundService |
| | | 16 | | { |
| | | 17 | | private readonly int _workerCount; |
| | | 18 | | private readonly ICommandsChannel _commandsChannel; |
| | | 19 | | private readonly IServiceScopeFactory _scopeFactory; |
| | | 20 | | private readonly List<Channel<CommandContext>> _outputs; |
| | | 21 | | private readonly ILogger _logger; |
| | | 22 | | |
| | | 23 | | /// <inheritdoc /> |
| | 1 | 24 | | public BackgroundCommandSenderHostedService(IOptions<MediatorOptions> options, ICommandsChannel commandsChannel, ISe |
| | | 25 | | { |
| | 1 | 26 | | _workerCount = options.Value.CommandWorkerCount; |
| | 1 | 27 | | _commandsChannel = commandsChannel; // The shared input channel for all commands |
| | 1 | 28 | | _scopeFactory = scopeFactory; |
| | 1 | 29 | | _logger = logger; |
| | 1 | 30 | | _outputs = new(_workerCount); // Prepare a list to hold worker-specific channels |
| | 1 | 31 | | } |
| | | 32 | | |
| | | 33 | | /// <inheritdoc /> |
| | | 34 | | protected override async Task ExecuteAsync(CancellationToken cancellationToken) |
| | | 35 | | { |
| | 1 | 36 | | var index = 0; // Used for round-robin distribution of work |
| | | 37 | | |
| | | 38 | | // Set up worker channels and start background tasks for each worker |
| | 10 | 39 | | for (var i = 0; i < _workerCount; i++) |
| | | 40 | | { |
| | 4 | 41 | | var output = Channel.CreateUnbounded<CommandContext>(); |
| | 4 | 42 | | _outputs.Add(output); |
| | | 43 | | // Start a background task that processes commands from this worker's channel |
| | 4 | 44 | | _ = ReadOutputAsync(output, cancellationToken); |
| | | 45 | | } |
| | | 46 | | |
| | | 47 | | // Main dispatcher loop: read from the input channel and distribute to worker channels |
| | 46 | 48 | | await foreach (var commandContext in _commandsChannel.Reader.ReadAllAsync(cancellationToken)) |
| | | 49 | | { |
| | 22 | 50 | | var output = _outputs[index]; |
| | 22 | 51 | | await output.Writer.WriteAsync(commandContext, cancellationToken); |
| | | 52 | | // Round-robin distribution - move to next worker |
| | 22 | 53 | | index = (index + 1) % _workerCount; |
| | | 54 | | } |
| | | 55 | | |
| | | 56 | | // If the input channel is completed, complete all worker channels |
| | 0 | 57 | | foreach (var output in _outputs) |
| | 0 | 58 | | output.Writer.Complete(); |
| | 0 | 59 | | } |
| | | 60 | | |
| | | 61 | | private async Task ReadOutputAsync(Channel<CommandContext> output, CancellationToken cancellationToken) |
| | | 62 | | { |
| | | 63 | | // Worker task: process commands from the worker's channel |
| | 52 | 64 | | await foreach (var commandContext in output.Reader.ReadAllAsync(cancellationToken)) |
| | | 65 | | { |
| | | 66 | | try |
| | | 67 | | { |
| | | 68 | | // Create a fresh scope for each command to ensure proper service lifetime |
| | 22 | 69 | | using var scope = _scopeFactory.CreateScope(); |
| | 22 | 70 | | var commandSender = scope.ServiceProvider.GetRequiredService<ICommandSender>(); |
| | | 71 | | |
| | | 72 | | // Link the service cancellation token with the command's token to ensure proper cancellation |
| | 22 | 73 | | using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource( |
| | 22 | 74 | | cancellationToken, |
| | 22 | 75 | | commandContext.CancellationToken); |
| | | 76 | | |
| | | 77 | | // Process the command using the command sender service with the linked token |
| | 22 | 78 | | await commandSender.SendAsync( |
| | 22 | 79 | | commandContext.Command, |
| | 22 | 80 | | CommandStrategy.Default, |
| | 22 | 81 | | commandContext.Headers, |
| | 22 | 82 | | linkedTokenSource.Token); |
| | 22 | 83 | | } |
| | 0 | 84 | | catch (Exception e) |
| | | 85 | | { |
| | | 86 | | // Log errors but continue processing other commands |
| | 0 | 87 | | _logger.LogError(e, "An unhandled exception occurred while processing the queue"); |
| | 0 | 88 | | } |
| | | 89 | | } |
| | 0 | 90 | | } |
| | | 91 | | } |