Compare commits

...

16 Commits

Author SHA1 Message Date
khwezi ab3d8e6e9a Merge pull request 'Refactored GetNotificationsAsync() date handling' (#29) from emailjobs into master
Reviewed-on: #29
2026-05-17 13:14:01 +02:00
Khwezi Mngoma 97bde73777 Refactored GetNotificationsAsync() date handling
continuous-integration/drone/pr Build is passing
2026-05-17 13:12:58 +02:00
khwezi db4c348288 Merge pull request 'Fixed email sending logic' (#28) from emailjobs into master
Reviewed-on: #28
2026-05-16 00:29:01 +02:00
Khwezi Mngoma a65e926a53 Fixed email sending logic
continuous-integration/drone/pr Build is passing
2026-05-16 00:28:31 +02:00
khwezi 6683234642 Merge pull request 'Refactored batch drop logic' (#27) from emailjobs into master
Reviewed-on: #27
2026-05-16 00:05:51 +02:00
Khwezi Mngoma 1471d9e597 Refactored batch drop logic
continuous-integration/drone/pr Build is passing
2026-05-16 00:04:58 +02:00
khwezi 6ddbb9479a Merge pull request 'Added an empty constructor to ProcessEmailNotificationEvent' (#26) from emailjobs into master
Reviewed-on: #26
2026-05-15 23:53:09 +02:00
Khwezi Mngoma e978aa17f8 Added an empty constructor to ProcessEmailNotificationEvent
continuous-integration/drone/pr Build is passing
2026-05-15 23:52:38 +02:00
khwezi 6c7349a0f8 Merge pull request 'Added additional logging and traces' (#25) from emailjobs into master
Reviewed-on: #25
2026-05-15 23:21:52 +02:00
Khwezi Mngoma a31f75c5ef Added additional logging and traces
continuous-integration/drone/pr Build is passing
2026-05-15 23:21:31 +02:00
khwezi e97fd6cd3f Merge pull request 'Added debug logging' (#24) from emailjobs into master
Reviewed-on: #24
2026-05-15 23:09:21 +02:00
Khwezi Mngoma 7f4246ac63 Added debug logging
continuous-integration/drone/pr Build is passing
2026-05-15 23:08:15 +02:00
khwezi 184c7c252a Merge pull request 'Set misfireThreshold to 2min and eased Cluster node checkin limit' (#23) from emailjobs into master
Reviewed-on: #23
2026-05-15 22:29:08 +02:00
Khwezi Mngoma dfc62c8fe1 Set misfireThreshold to 2min and eased Cluster node checkin limit
continuous-integration/drone/pr Build is passing
2026-05-15 22:28:18 +02:00
khwezi bfe8c458d6 Merge pull request 'Optimised quartz' (#22) from emailjobs into master
Reviewed-on: #22
2026-05-15 09:52:06 +02:00
Khwezi Mngoma 0f91f102e5 Optimised quartz
continuous-integration/drone/pr Build is passing
2026-05-15 09:51:26 +02:00
8 changed files with 75 additions and 18 deletions
@@ -1,4 +1,6 @@
using LiteCharms.Features.Shop.Notifications; using LiteCharms.Features.Models;
using LiteCharms.Features.Shop.Notifications;
using LiteCharms.Features.Shop.Notifications.Events;
namespace LiteCharms.Features.Tests; namespace LiteCharms.Features.Tests;
@@ -32,4 +34,31 @@ public class NotificationsFeatureTests(CommonFixture fixture, ITestOutputHelper
foreach (var error in createResult.Errors) output.WriteLine(error.Message); foreach (var error in createResult.Errors) output.WriteLine(error.Message);
} }
[Fact]
public async Task GetNotifications_ShouldReturn_AllNotifications()
{
DateRange range = new()
{
From = DateOnly.FromDateTime(new DateTime(2026, 05, 01, 0, 0, 0, DateTimeKind.Utc)),
To = DateOnly.FromDateTime(DateTime.UtcNow),
MaxRecords = 10
};
var getResult = await notificationService.GetNotificationsAsync(range);
Assert.True(getResult.IsSuccess);
foreach (var error in getResult.Errors) output.WriteLine(error.Message);
}
[Fact]
public async Task ProcessEmailNotificationsEvent_ShouldSucceed()
{
var notification = ProcessEmailNotificationsEvent.Create();
await fixture.Mediator.Publish(notification);
Assert.True(true);
}
} }
+3 -2
View File
@@ -35,8 +35,9 @@ public class EmailService(IOptions<SmtpSettings> options) : IDisposable
var bodyBuilder = new BodyBuilder(); var bodyBuilder = new BodyBuilder();
foreach (var attachment in message.Body?.Attachments!) if (message.Body!.Properties.HasAttachments)
bodyBuilder.Attachments.Add(attachment.Name!, attachment.FileStream!, cancellationToken); foreach (var attachment in message.Body?.Attachments!)
bodyBuilder.Attachments.Add(attachment.Name!, attachment.FileStream!, cancellationToken);
if (!message.Body.Properties.IsHtml) bodyBuilder.TextBody = message.Body.Message; if (!message.Body.Properties.IsHtml) bodyBuilder.TextBody = message.Body.Message;
if (message.Body.Properties.IsHtml) bodyBuilder.HtmlBody = message.Body.Message; if (message.Body.Properties.IsHtml) bodyBuilder.HtmlBody = message.Body.Message;
+8 -4
View File
@@ -34,7 +34,7 @@ public static class Quartz
storage.UseClustering(cluster => storage.UseClustering(cluster =>
{ {
cluster.CheckinInterval = TimeSpan.FromSeconds(30); cluster.CheckinInterval = TimeSpan.FromSeconds(30);
cluster.CheckinMisfireThreshold = TimeSpan.FromSeconds(2); cluster.CheckinMisfireThreshold = TimeSpan.FromSeconds(90);
}); });
}); });
}); });
@@ -48,6 +48,8 @@ public static class Quartz
services.ConfigureCommon(); services.ConfigureCommon();
services.AddQuartzHostedService(options => options.WaitForJobsToComplete = true);
services.AddQuartz(config => services.AddQuartz(config =>
{ {
config.SchedulerName = schedulerName; config.SchedulerName = schedulerName;
@@ -60,6 +62,8 @@ public static class Quartz
config.UseDefaultThreadPool(options => options.MaxConcurrency = 1); config.UseDefaultThreadPool(options => options.MaxConcurrency = 1);
config.UseTimeZoneConverter(); config.UseTimeZoneConverter();
config.SetProperty("quartz.jobStore.misfireThreshold", TimeSpan.FromMinutes(2).TotalMilliseconds.ToString());
config.UsePersistentStore(storage => config.UsePersistentStore(storage =>
{ {
storage.PerformSchemaValidation = false; storage.PerformSchemaValidation = false;
@@ -72,7 +76,7 @@ public static class Quartz
storage.UseClustering(cluster => storage.UseClustering(cluster =>
{ {
cluster.CheckinInterval = TimeSpan.FromSeconds(30); cluster.CheckinInterval = TimeSpan.FromSeconds(30);
cluster.CheckinMisfireThreshold = TimeSpan.FromSeconds(2); cluster.CheckinMisfireThreshold = TimeSpan.FromSeconds(90);
}); });
}); });
}); });
@@ -86,14 +90,14 @@ public static class Quartz
{ {
options.Scheduling.IgnoreDuplicates = true; options.Scheduling.IgnoreDuplicates = true;
options.Scheduling.OverWriteExistingData = true; options.Scheduling.OverWriteExistingData = true;
options["quartz.plugin.jobHistory.type"] = "Quartz.Plugin.History.LoggingJobHistoryPlugin, Quartz.Plugins"; options["quartz.plugin.jobHistory.type"] = "Quartz.Plugin.History.LoggingJobHistoryPlugin, Quartz.Plugins";
options["quartz.plugin.triggerHistory.type"] = "Quartz.Plugin.History.LoggingTriggerHistoryPlugin, Quartz.Plugins"; options["quartz.plugin.triggerHistory.type"] = "Quartz.Plugin.History.LoggingTriggerHistoryPlugin, Quartz.Plugins";
}); });
services.AddTransient<RetryJobListener>(); services.AddTransient<RetryJobListener>();
services.AddTransient<IJobOrchestrator, JobOrchestrator>(); services.AddTransient<IJobOrchestrator, JobOrchestrator>();
services.AddQuartzHostedService(options => options.WaitForJobsToComplete = true);
return services; return services;
} }
} }
@@ -50,9 +50,9 @@ public class JobOrchestrator(ISchedulerFactory schedulerFactory) : IJobOrchestra
var trigger = global::Quartz.TriggerBuilder.Create() var trigger = global::Quartz.TriggerBuilder.Create()
.WithIdentity(triggerKey) .WithIdentity(triggerKey)
.WithDescription($"Scheduled via Main Job at {now:g} UTC") .WithDescription($"Scheduled via Main Job at {now:g}")
.WithCronSchedule(cronExpression, cron => cron .WithCronSchedule(cronExpression, cron => cron
.WithMisfireHandlingInstructionFireAndProceed()) .WithMisfireHandlingInstructionIgnoreMisfires())
.StartAt(now) .StartAt(now)
.Build(); .Build();
+14 -2
View File
@@ -10,16 +10,28 @@ public class MediatorJob<TNotification>(IMediator mediator) : IJob where TNotifi
{ {
var data = context.MergedJobDataMap["Payload"] as string; var data = context.MergedJobDataMap["Payload"] as string;
if (string.IsNullOrWhiteSpace(data)) return; if (string.IsNullOrWhiteSpace(data))
{
Trace.WriteLine("Job Payload missing, job ended");
return;
}
var notification = JsonSerializer.Deserialize<TNotification>(data); var notification = JsonSerializer.Deserialize<TNotification>(data);
if (notification is null) return; if (notification is null)
{
Trace.WriteLine("Notification could not be JSon converted from data string, job ended");
return;
}
using var activity = MediatorTelemetry.Source.StartActivity($"Quartz: {typeof(TNotification).Name}"); using var activity = MediatorTelemetry.Source.StartActivity($"Quartz: {typeof(TNotification).Name}");
activity?.SetTag("event.correlation_id", notification.CorrelationId); activity?.SetTag("event.correlation_id", notification.CorrelationId);
await mediator.Publish(notification, context.CancellationToken); await mediator.Publish(notification, context.CancellationToken);
Trace.WriteLine("Job published");
} }
} }
@@ -1,4 +1,5 @@
using LiteCharms.Features.Email; using k8s.KubeConfigModels;
using LiteCharms.Features.Email;
using LiteCharms.Features.Shop.Notifications.Models; using LiteCharms.Features.Shop.Notifications.Models;
using LiteCharms.Features.Shop.Postgres; using LiteCharms.Features.Shop.Postgres;
@@ -15,17 +16,20 @@ public class ProcessEmailNotificationsEventHandler(IDbContextFactory<ShopDbConte
{ {
using var context = await contextFactory.CreateDbContextAsync(cancellationToken); using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if (emailService.Status != EmailStatuses.Connected)
await emailService.ConnectAsync(cancellationToken);
var notifications = await context.Notifications var notifications = await context.Notifications
.OrderByDescending(o => o.CreatedAt) .OrderByDescending(o => o.CreatedAt)
.ThenBy(o => o.Priority) .ThenBy(o => o.Priority)
.Where(n => n.CorrelationIdType == CorrelationIdTypes.Email) .Where(n => n.Platform == NotificationPlatforms.Email &&
.Where(n => n.Direction == NotificationDirection.Outgoing) n.Direction == NotificationDirection.Outgoing && n.Processed == false)
.Take(message.MaxRecords) .Take(message.MaxRecords)
.ToListAsync(cancellationToken); .ToListAsync(cancellationToken);
foreach (var notification in notifications) foreach (var notification in notifications)
{ {
if (dropBatch || cancellationToken.IsCancellationRequested) break; if (dropBatch) break;
var sendResult = await SendEmailAsync(notification,emailService, cancellationToken); var sendResult = await SendEmailAsync(notification,emailService, cancellationToken);
@@ -46,12 +50,16 @@ public class ProcessEmailNotificationsEventHandler(IDbContextFactory<ShopDbConte
notification.UpdatedAt = DateTime.UtcNow; notification.UpdatedAt = DateTime.UtcNow;
} }
await context.SaveChangesAsync(cancellationToken); await context.SaveChangesAsync(cancellationToken);
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, ex.Message); logger.LogError(ex, ex.Message);
} }
finally
{
await emailService.DisconnectAsync(cancellationToken);
}
} }
private async Task<Result> SendEmailAsync(Notification notification, EmailService service, CancellationToken cancellationToken = default) private async Task<Result> SendEmailAsync(Notification notification, EmailService service, CancellationToken cancellationToken = default)
@@ -8,6 +8,8 @@ public class ProcessEmailNotificationsEvent : EventBase, IEvent
public int MaxRecords { get; set; } public int MaxRecords { get; set; }
public ProcessEmailNotificationsEvent() { MaxRecords = 1000; }
private ProcessEmailNotificationsEvent(int maxRecords = 1000) => MaxRecords = maxRecords; private ProcessEmailNotificationsEvent(int maxRecords = 1000) => MaxRecords = maxRecords;
public static ProcessEmailNotificationsEvent Create(int maxRecords = 1000) => new(maxRecords); public static ProcessEmailNotificationsEvent Create(int maxRecords = 1000) => new(maxRecords);
@@ -63,8 +63,8 @@ public class NotificationService(IDbContextFactory<ShopDbContext> contextFactory
{ {
try try
{ {
var fromDate = range.From.ToDateTime(TimeOnly.MinValue); var fromDate = range.From.ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc);
var toDate = range.To.ToDateTime(TimeOnly.MaxValue); var toDate = range.To.ToDateTime(TimeOnly.MaxValue, DateTimeKind.Utc);
using var context = await contextFactory.CreateDbContextAsync(cancellationToken); using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
@@ -96,6 +96,7 @@ public class NotificationService(IDbContextFactory<ShopDbContext> contextFactory
return Result.Fail(new Error($"Notification with id {request.NotificationId} not found.")); return Result.Fail(new Error($"Notification with id {request.NotificationId} not found."));
notification.Processed = request.Processed; notification.Processed = request.Processed;
notification.UpdatedAt = DateTime.UtcNow;
if (request.HasError) if (request.HasError)
{ {