using MediatR; using Microsoft.Extensions.Logging; using ReC.Application.RecActions.Queries; namespace ReC.Application.RecActions.Commands; public record InvokeBatchRecActionsCommand : ReadRecActionQueryBase, IRequest; public static class InvokeBatchRecActionsCommandExtensions { public static Task InvokeBatchRecAction(this ISender sender, int profileId) => sender.Send(new InvokeBatchRecActionsCommand { ProfileId = profileId }); } public class InvokeRecActionsCommandHandler(ISender sender, IHttpClientFactory clientFactory, ILogger? logger = null) : IRequestHandler { public async Task Handle(InvokeBatchRecActionsCommand request, CancellationToken cancel) { var actions = await sender.Send(request.ToReadQuery(), cancel); var http = clientFactory.CreateClient(); using var semaphore = new SemaphoreSlim(5); var tasks = actions.Select(async action => { await semaphore.WaitAsync(cancel); try { await sender.Send(action.ToInvokeCommand(), cancel); } catch(Exception ex) { logger?.LogError( ex, "Error invoking Rec action. ProfileId: {ProfileId}, Id: {Id}", action.ProfileId, action.Id ); } finally { semaphore.Release(); } }); await Task.WhenAll(tasks); } }