76 lines
2.8 KiB
C#
76 lines
2.8 KiB
C#
using MassTransit;
|
|
using Newtonsoft.Json;
|
|
using Quartz;
|
|
|
|
namespace FictionArchive.Service.SchedulerService.Models.JobTemplates;
|
|
|
|
public class EventJobTemplate : IJob
|
|
{
|
|
private readonly IPublishEndpoint _publishEndpoint;
|
|
private readonly ISendEndpointProvider _sendEndpointProvider;
|
|
private readonly ILogger<EventJobTemplate> _logger;
|
|
|
|
public const string EventTypeParameter = "MessageType";
|
|
public const string EventDataParameter = "MessageData";
|
|
public const string IsCommandParameter = "IsCommand";
|
|
public const string DestinationQueueParameter = "DestinationQueue";
|
|
|
|
public EventJobTemplate(
|
|
IPublishEndpoint publishEndpoint,
|
|
ISendEndpointProvider sendEndpointProvider,
|
|
ILogger<EventJobTemplate> logger)
|
|
{
|
|
_publishEndpoint = publishEndpoint;
|
|
_sendEndpointProvider = sendEndpointProvider;
|
|
_logger = logger;
|
|
}
|
|
|
|
public async Task Execute(IJobExecutionContext context)
|
|
{
|
|
try
|
|
{
|
|
var messageData = context.MergedJobDataMap.GetString(EventDataParameter);
|
|
var messageTypeName = context.MergedJobDataMap.GetString(EventTypeParameter);
|
|
var isCommand = context.MergedJobDataMap.GetBoolean(IsCommandParameter);
|
|
|
|
var messageType = Type.GetType(messageTypeName!);
|
|
if (messageType == null)
|
|
{
|
|
_logger.LogError("Could not resolve message type: {MessageType}", messageTypeName);
|
|
return;
|
|
}
|
|
|
|
var message = JsonConvert.DeserializeObject(messageData!, messageType);
|
|
if (message == null)
|
|
{
|
|
_logger.LogError("Could not deserialize message data for type: {MessageType}", messageTypeName);
|
|
return;
|
|
}
|
|
|
|
if (isCommand)
|
|
{
|
|
var destinationQueue = context.MergedJobDataMap.GetString(DestinationQueueParameter);
|
|
if (string.IsNullOrEmpty(destinationQueue))
|
|
{
|
|
_logger.LogError("Destination queue not specified for command message");
|
|
return;
|
|
}
|
|
|
|
var endpoint = await _sendEndpointProvider.GetSendEndpoint(new Uri($"queue:{destinationQueue}"));
|
|
await endpoint.Send(message, messageType);
|
|
_logger.LogInformation("Sent command {MessageType} to queue {Queue}", messageTypeName, destinationQueue);
|
|
}
|
|
else
|
|
{
|
|
await _publishEndpoint.Publish(message, messageType);
|
|
_logger.LogInformation("Published event {MessageType}", messageTypeName);
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, "An error occurred while running an event job.");
|
|
throw; // Re-throw to let Quartz handle retries
|
|
}
|
|
}
|
|
}
|