Refactor to support batch action invocation
Replaced `InvokeRecAction` with `InvokeBatchRecAction` in `ActionController` to transition from single-action to batch-action invocation. Removed `InvokeRecActionCommand.cs`, which previously handled individual action invocations. Introduced `InvokeBatchRecActionsCommand.cs` to handle batch processing with similar concurrency control logic using a semaphore. This redesign improves scalability and aligns with updated business requirements while maintaining compatibility with the existing application structure.
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
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<InvokeRecActionsCommandHandler>? logger = null) : IRequestHandler<InvokeBatchRecActionsCommand>
|
||||
{
|
||||
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
|
||||
{
|
||||
if (action.RestType is null)
|
||||
{
|
||||
logger?.LogWarning(
|
||||
"Rec action could not be invoked because the RestType value is null. ProfileId: {ProfileId}, ActionId: {ActionId}",
|
||||
action.ProfileId,
|
||||
action.ActionId
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
var method = new HttpMethod(action.RestType.ToUpper());
|
||||
var msg = new HttpRequestMessage(method, action.EndpointUri);
|
||||
|
||||
var response = await http.SendAsync(msg, cancel);
|
||||
var body = await response.Content.ReadAsStringAsync(cancel);
|
||||
var headers = response.Headers.ToDictionary();
|
||||
}
|
||||
catch(Exception ex)
|
||||
{
|
||||
logger?.LogError(
|
||||
ex,
|
||||
"Error invoking Rec action. ProfileId: {ProfileId}, ActionId: {ActionId}",
|
||||
action.ProfileId,
|
||||
action.ActionId
|
||||
);
|
||||
}
|
||||
finally
|
||||
{
|
||||
semaphore.Release();
|
||||
}
|
||||
});
|
||||
|
||||
await Task.WhenAll(tasks);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user