using ECMJobRunner.Application.Common.Constants; using ECMJobRunner.Application.Common.Exceptions; using ECMJobRunner.Application.Common.Options; using ECMJobRunner.Application.Profiles.Commands; using MediatR; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using ReC.Client; using ReC.Client.Api; using System; using System.Threading; using System.Threading.Tasks; namespace ECMJobRunner.Application.Profiles.Commands.Behaviors { /// /// Pipeline behavior that sends ReC HTTP request for DEX jobs /// Runs after CheckQueryExecutionBehavior and invokes ReC API /// /// The request type /// The response type /// /// Initializes a new instance of ReCRequestExecutionBehavior /// /// ReC client for HTTP requests /// DEX job configuration options public class ReCRequestExecutionBehavior(ReCClient ReCClient, IOptions options, ILogger> Logger) : IPipelineBehavior where TRequest : notnull { private readonly DexJobOptions Options = options.Value; /// /// Handles the pipeline behavior /// Sends ReC request if request is TriggeringDEXJobCommand /// #if NET48 public async Task Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate next) #else public async Task Handle(TRequest request, RequestHandlerDelegate next, CancellationToken cancellationToken) #endif { if (request is TriggeringProfileJobCommand command) { await SendReCRequestAsync(command, cancellationToken); } return await next(); } private async Task SendReCRequestAsync(TriggeringProfileJobCommand command, CancellationToken cancel) { try { command.RecActionResult = await ReCClient.RecActions.InvokeAsync(command.Job.ProfileId, new InvokeReferences() { BatchId = command.BatchId, }, cancel); Logger.LogInformation( "ReC request completed successfully. Profile ID: {ProfileId} | Job name: {JobName} | Batch ID: {BatchId} | Total action count: {TotalActionCount} | Action exception count: {ActionExceptionCount}", command.Job.ProfileId, command.Job.Name, command.BatchId, command.RecActionResult?.TotalActionCount ?? 0, command.RecActionResult?.ActionExceptionCount ?? 0); } catch (Exception ex) { if (Options.Error.ReCRequest.OnSending == ErrorAction.Stop) { throw new JobHttpException( profileId: command.Job.ProfileId, jobName: "Triggering DEX", processName: "ReC Http Request", batchId: command.BatchId, reason: null, clientLibrary: "ReC.Client", clientMethod: "RecActions.InvokeAsync", innerException: ex); } } } } }