Refactor DEXJob to ProfileJob across the codebase

Renamed namespaces, classes, and commands from `DEXJob` to `ProfileJob` to align with the new "Profiles" context. Updated pipeline behaviors (`CheckQueryExecutionBehavior`, `MainQueryExecutionBehavior`, `ReCRequestExecutionBehavior`) to handle `TriggeringProfileJobCommand`.

Refactored unit tests to reflect the new naming convention, including mock setups and assertions. Updated `DtoExtensions` to return `TriggeringProfileJobBatchCommand`. Adjusted queries and dependency injection to use the new `Profiles` namespace.

Performed general refactoring to replace all references to "DEXJob" with "ProfileJob" in method names, variables, and documentation for consistency and clarity.
This commit is contained in:
2026-08-03 11:36:45 +02:00
parent a698f8daae
commit 1110728741
12 changed files with 56 additions and 56 deletions

View File

@@ -0,0 +1,116 @@
using ECMJobRunner.Application.Common.Constants;
using ECMJobRunner.Application.Common.Dtos;
using ECMJobRunner.Application.Common.Exceptions;
using ECMJobRunner.Application.Common.Interfaces;
using ECMJobRunner.Application.Common.Options;
using ECMJobRunner.Application.Profiles.Commands;
using MediatR;
using Microsoft.Extensions.Options;
using System;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace ECMJobRunner.Application.Profiles.Commands.Behaviors
{
/// <summary>
/// Pipeline behavior that executes the check SQL query for DEX jobs
/// Runs after MainQueryExecutionBehavior and validates query results
/// </summary>
/// <typeparam name="TRequest">The request type</typeparam>
/// <typeparam name="TResponse">The response type</typeparam>
public class CheckQueryExecutionBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
where TRequest : notnull
{
private readonly ISQLExecutor _executor;
private readonly DexJobOptions _options;
/// <summary>
/// Initializes a new instance of CheckQueryExecutionBehavior
/// </summary>
/// <param name="executor">SQL executor for query execution</param>
/// <param name="options">DEX job configuration options</param>
public CheckQueryExecutionBehavior(ISQLExecutor executor, IOptions<DexJobOptions> options)
{
_executor = executor;
_options = options.Value;
}
/// <summary>
/// Handles the pipeline behavior
/// Executes check query if request is TriggeringDEXJobCommand
/// </summary>
#if NET48
public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
#else
public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
#endif
{
if (request is TriggeringProfileJobCommand command)
{
await ExecuteCheckQueryAsync(command, cancellationToken);
}
return await next();
}
private async Task ExecuteCheckQueryAsync(TriggeringProfileJobCommand command, CancellationToken cancel)
{
if (!string.IsNullOrWhiteSpace(command.Job.SqlCheckQuery))
{
var sqlCheckQuery = Regex.Replace(
command.Job.SqlCheckQuery!,
_options.Placeholders.BatchId.Pattern,
command.BatchId,
_options.Placeholders.BatchId.RegexOptions);
try
{
var result = await _executor.ExecuteQueryAsync<CheckQueryResult>(sqlCheckQuery, cancel);
if (_options.Error.CheckQuery.OnUnexpectedResult == ErrorAction.Stop)
{
if (result is null)
throw new JobSqlException(
jobName: "Triggering DEX",
processName: "Check Query",
batchId: command.BatchId,
reason: "Check Query returned nothing.",
query: sqlCheckQuery,
innerException: null);
else if (result.ReturnValue <= 0)
throw new JobSqlException(
jobName: "Triggering DEX",
processName: "Check Query",
batchId: command.BatchId,
reason: $"The query unexpectedly returned the value {result.ReturnValue}. The expected value was any value greater than 0.",
query: sqlCheckQuery,
innerException: null);
}
}
catch (Exception ex)
{
if (_options.Error.CheckQuery.OnExecution == ErrorAction.Stop)
throw new JobSqlException(
jobName: "Triggering DEX",
processName: "Check Query",
batchId: command.BatchId,
reason: null,
query: sqlCheckQuery,
innerException: ex
);
}
}
else if (_options.Error.CheckQuery.IfNullOrWhiteSpace == ErrorAction.Stop)
{
throw new JobSqlException(
jobName:"Triggering DEX",
processName:"Check Query",
batchId:command.BatchId,
reason: "SQL Check Query is null or empty",
query: null,
innerException: null
);
}
}
}
}

View File

@@ -0,0 +1,113 @@
using ECMJobRunner.Application.Common.Constants;
using ECMJobRunner.Application.Common.Dtos;
using ECMJobRunner.Application.Common.Exceptions;
using ECMJobRunner.Application.Common.Interfaces;
using ECMJobRunner.Application.Common.Options;
using ECMJobRunner.Application.Profiles.Commands;
using MediatR;
using Microsoft.Extensions.Options;
using System;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace ECMJobRunner.Application.Profiles.Commands.Behaviors
{
/// <summary>
/// Pipeline behavior that executes the main SQL query for DEX jobs
/// Runs before the command handler and validates query results
/// </summary>
/// <typeparam name="TRequest">The request type</typeparam>
/// <typeparam name="TResponse">The response type</typeparam>
public class MainQueryExecutionBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
where TRequest : notnull
{
private readonly ISQLExecutor _executor;
private readonly DexJobOptions _options;
/// <summary>
/// Initializes a new instance of MainQueryExecutionBehavior
/// </summary>
/// <param name="executor">SQL executor for query execution</param>
/// <param name="options">DEX job configuration options</param>
public MainQueryExecutionBehavior(ISQLExecutor executor, IOptions<DexJobOptions> options)
{
_executor = executor;
_options = options.Value;
}
/// <summary>
/// Handles the pipeline behavior
/// Executes main query if request is TriggeringDEXJobCommand
/// </summary>
#if NET48
public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
#else
public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
#endif
{
if (request is TriggeringProfileJobCommand command)
{
await ExecuteMainQueryAsync(command, cancellationToken);
}
return await next();
}
private async Task ExecuteMainQueryAsync(TriggeringProfileJobCommand command, CancellationToken cancel)
{
if (!string.IsNullOrWhiteSpace(command.Job.SqlMainQuery))
{
var sqlMainQuery = Regex.Replace(
command.Job.SqlMainQuery!,
_options.Placeholders.BatchId.Pattern,
command.BatchId,
_options.Placeholders.BatchId.RegexOptions);
try
{
var result = await _executor.ExecuteQueryAsync<MainQueryResult>(sqlMainQuery, cancel);
if (_options.Error.MainQuery.OnUnexpectedResult == ErrorAction.Stop)
{
if (result is null)
throw new JobSqlException(
jobName: "Triggering DEX",
processName: "Main Query",
batchId: command.BatchId,
reason: "Main Query returned nothing.",
query: sqlMainQuery,
innerException: null);
else if (result.ReturnValue is not null)
throw new JobSqlException(
jobName: "Triggering DEX",
processName: "Main Query",
batchId: command.BatchId,
reason: $"The query unexpectedly returned the value {result.ReturnValue}. The expected value was null.",
query: sqlMainQuery, innerException: null);
}
}
catch (Exception ex)
{
if (_options.Error.MainQuery.OnExecution == ErrorAction.Stop)
throw new JobSqlException(
jobName: "Triggering DEX",
processName: "Main Query",
batchId: command.BatchId,
reason: null,
query: sqlMainQuery,
innerException: ex);
}
}
else if (_options.Error.MainQuery.IfNullOrWhiteSpace == ErrorAction.Stop)
{
throw new JobSqlException(
jobName: "Triggering DEX",
processName: "Main Query",
batchId: command.BatchId,
reason: "SQL Check Query is null or empty",
query: null,
innerException: null);
}
}
}
}

View File

@@ -0,0 +1,81 @@
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.Options;
using ReC.Client;
using ReC.Client.Api;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ECMJobRunner.Application.Profiles.Commands.Behaviors
{
/// <summary>
/// Pipeline behavior that sends ReC HTTP request for DEX jobs
/// Runs after CheckQueryExecutionBehavior and invokes ReC API
/// </summary>
/// <typeparam name="TRequest">The request type</typeparam>
/// <typeparam name="TResponse">The response type</typeparam>
public class ReCRequestExecutionBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
where TRequest : notnull
{
private readonly ReCClient _reCClient;
private readonly DexJobOptions _options;
/// <summary>
/// Initializes a new instance of ReCRequestExecutionBehavior
/// </summary>
/// <param name="reCClient">ReC client for HTTP requests</param>
/// <param name="options">DEX job configuration options</param>
public ReCRequestExecutionBehavior(ReCClient reCClient, IOptions<DexJobOptions> options)
{
_reCClient = reCClient;
_options = options.Value;
}
/// <summary>
/// Handles the pipeline behavior
/// Sends ReC request if request is TriggeringDEXJobCommand
/// </summary>
#if NET48
public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
#else
public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> 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
{
await _reCClient.RecActions.InvokeAsync(command.Job.ProfileId, new InvokeReferences()
{
BatchId = command.BatchId,
}, cancel);
}
catch (Exception ex)
{
if (_options.Error.ReCRequest.OnSending == ErrorAction.Stop)
{
throw new JobHttpException(
jobName: "Triggering DEX",
processName: "ReC Http Request",
batchId: command.BatchId,
reason: null,
clientLibrary: "ReC.Client",
clientMethod: "RecActions.InvokeAsync",
innerException: ex);
}
}
}
}
}

View File

@@ -0,0 +1,92 @@
using ECMJobRunner.Application.Common.Exceptions;
using ECMJobRunner.Application.Common.Interfaces;
using ECMJobRunner.Domain.Interfaces;
using MediatR;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ECMJobRunner.Application.Profiles.Commands
{
/// <summary>
/// Command to trigger DEX job batch for a profile
/// Executes all SQL jobs associated with a profile ID
/// </summary>
public class TriggeringProfileJobBatchCommand : IRequest<Unit>
{
/// <summary>
/// Profile ID to trigger all associated SQL jobs
/// </summary>
public long ProfileId { get; set; }
}
/// <summary>
/// Handler for TriggeringDEXJobBatchCommand
/// Retrieves all SQL jobs for a profile and executes them sequentially
/// Validates that the profile is active before execution
/// </summary>
public class TriggeringDEXJobBatchCommandHandler(ICfgProfileRepository profileRepo, IProfileSqlJobRepository jobRepo, ISender sender)
: IRequestHandler<TriggeringProfileJobBatchCommand, Unit>
{
/// <summary>
/// Handles the TriggeringDEXJobBatchCommand
/// Creates a unique batch ID and triggers individual job commands
/// </summary>
/// <param name="request">The command containing the profile ID</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>Unit value indicating completion</returns>
/// <exception cref="InactiveProfileException">Thrown when the profile is not active</exception>
public async Task<Unit> Handle(TriggeringProfileJobBatchCommand request, CancellationToken cancellationToken)
{
var batchId = CreateBatchId();
// Retrieve the profile to check if it's active
var profile = await profileRepo.GetByIdAsync(request.ProfileId, cancellationToken);
// Check if profile exists and is active
if (profile == null)
{
throw new InvalidOperationException($"Profile with ID {request.ProfileId} not found.");
}
if (!profile.Active)
{
throw new InactiveProfileException(profile.Id, profile.ProfileName, batchId);
}
// Retrieve all jobs for the profile
var jobs = await jobRepo.FindAsync(j => j.ProfileId == request.ProfileId, cancellationToken);
foreach (var job in jobs)
{
await sender.Send(new TriggeringProfileJobCommand
{
Job = job,
BatchId = batchId
}, cancellationToken);
}
return Unit.Value;
}
/// <summary>
/// Creates a unique batch ID based on current timestamp
/// </summary>
/// <returns>20-character timestamp string (yyyyMMddHHmmssfffffff truncated to 20 chars)</returns>
public static string CreateBatchId()
{
// Format: "yyyy" : Year (4 digits)
// "MM" : Month (2 digits)
// "dd" : Day (2 digits)
// "HH" : Hour (24-hour format, 2 digits)
// "mm" : Minute (2 digits)
// "ss" : Second (2 digits)
// "fffffff": Fractions of a second / 100-nanoseconds (7 digits)
string fullBatchId = DateTime.Now.ToString("yyyyMMddHHmmssfffffff");
// Limit to 20 characters as per specification
return fullBatchId.Substring(0, 20);
}
}
}

View File

@@ -0,0 +1,51 @@
using ECMJobRunner.Domain.Entities;
using MediatR;
using System.Threading;
using System.Threading.Tasks;
namespace ECMJobRunner.Application.Profiles.Commands
{
/// <summary>
/// Command to trigger a single DEX job execution
/// Execution logic is handled by pipeline behaviors:
/// 1. MainQueryExecutionBehavior - executes main SQL query
/// 2. CheckQueryExecutionBehavior - validates with check SQL query
/// 3. ReCRequestExecutionBehavior - invokes ReC HTTP request
/// </summary>
public class TriggeringProfileJobCommand : IRequest<Unit>
{
/// <summary>
/// The SQL job to execute
/// </summary>
public ProfileSqlJob Job { get; set; } = null!;
/// <summary>
/// Unique batch identifier for this execution
/// </summary>
public string BatchId { get; set; } = null!;
}
/// <summary>
/// Handler for TriggeringDEXJobCommand
/// All execution logic is delegated to pipeline behaviors
/// This handler simply returns completion after behaviors execute
/// </summary>
public class TriggeringDEXJobCommandHandler : IRequestHandler<TriggeringProfileJobCommand, Unit>
{
/// <summary>
/// Handles the TriggeringDEXJobCommand
/// Returns immediately as behaviors perform all work
/// </summary>
/// <param name="request">The command containing job and batch ID</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>Unit value indicating completion</returns>
public Task<Unit> Handle(TriggeringProfileJobCommand request, CancellationToken cancellationToken)
{
// All execution logic is handled by pipeline behaviors:
// - MainQueryExecutionBehavior
// - CheckQueryExecutionBehavior
// - ReCRequestExecutionBehavior
return Task.FromResult(Unit.Value);
}
}
}

View File

@@ -0,0 +1,124 @@
using AutoMapper;
using ECMJobRunner.Application.Common.Dtos;
using ECMJobRunner.Domain.Interfaces;
using MediatR;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace ECMJobRunner.Application.Profiles.Queries
{
/// <summary>
/// Query to retrieve profiles with flexible filtering options
/// All query options are nullable - when no filters are specified, returns all profiles
/// </summary>
public class GetProfileQuery : IRequest<List<CfgProfileDto>>
{
/// <summary>
/// Profile ID to retrieve (optional)
/// When specified, returns only the profile with this ID
/// </summary>
public long? Id { get; set; }
/// <summary>
/// Filter by active status (optional)
/// When null, returns both active and inactive profiles
/// When true, returns only active profiles
/// When false, returns only inactive profiles
/// </summary>
public bool? Active { get; set; }
/// <summary>
/// Filter by profile type (optional)
/// When specified, returns only profiles with this type
/// Type: 0 = ADSync; 1 = GraphQL; 2 = SQL-Job; 3 = SQL and REST-Job
/// </summary>
public byte? TypeId { get; set; }
/// <summary>
/// Filter by profile name (optional)
/// When specified, returns profiles with matching name (case-insensitive contains)
/// </summary>
public string? ProfileName { get; set; }
/// <summary>
/// Include associated SQL jobs in the result (optional)
/// Default: true
/// </summary>
public bool IncludeSqlJobs { get; set; } = true;
}
/// <summary>
/// Handler for GetProfileQuery
/// Retrieves profiles with optional filtering and uses AutoMapper for DTO mapping
/// </summary>
public class GetProfileQueryHandler : IRequestHandler<GetProfileQuery, List<CfgProfileDto>>
{
private readonly ICfgProfileRepository _profileRepository;
private readonly IMapper _mapper;
public GetProfileQueryHandler(ICfgProfileRepository profileRepository, IMapper mapper)
{
_profileRepository = profileRepository;
_mapper = mapper;
}
public async Task<List<CfgProfileDto>> Handle(GetProfileQuery request, CancellationToken cancellationToken)
{
IEnumerable<Domain.Entities.CfgProfile> profiles;
// If ID is specified, get single profile by ID
if (request.Id.HasValue)
{
var profile = request.IncludeSqlJobs
? await _profileRepository.GetByIdWithSqlJobsAsync(request.Id.Value, cancellationToken)
: await _profileRepository.GetByIdAsync(request.Id.Value, cancellationToken);
profiles = profile != null ? new[] { profile } : [];
}
// Otherwise, get profiles with filters
else
{
// Get all profiles with SQL jobs if requested
if (request.IncludeSqlJobs)
{
// If Active filter is specified and true, use optimized method
if (request.Active.HasValue && request.Active.Value)
{
profiles = await _profileRepository.GetAllActiveWithSqlJobsAsync(cancellationToken);
}
else
{
// Generic query with filters
profiles = await _profileRepository.FindAsync(p => true, cancellationToken);
}
}
else
{
profiles = await _profileRepository.GetAllAsync(cancellationToken);
}
// Apply filters
if (request.Active.HasValue)
{
profiles = profiles.Where(p => p.Active == request.Active.Value);
}
if (request.TypeId.HasValue)
{
profiles = profiles.Where(p => p.TypeId == request.TypeId.Value);
}
if (!string.IsNullOrWhiteSpace(request.ProfileName))
{
var searchName = request.ProfileName.ToLowerInvariant();
profiles = profiles.Where(p => p.ProfileName.ToLowerInvariant().Contains(searchName));
}
}
// Use AutoMapper to map entities to DTOs
return _mapper.Map<List<CfgProfileDto>>(profiles.ToList());
}
}
}