From 71e869a01112f0f56cb480125966e068139553e7 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sat, 24 Oct 2026 22:27:53 +0200 Subject: [PATCH 1/3] feat(notifications): persist external deliveries in outbox --- .../Common/IApplicationDbContext.cs | 1 + .../Entities/NotificationDelivery.cs | 36 ++++++ .../Enums/NotificationDeliveryStatus.cs | 9 ++ .../BackgroundJobs/DependencyInjection.cs | 2 + .../BackgroundJobs/JobSetup.cs | 5 + .../Data/AppDbContext.cs | 1 + .../NotificationDeliveryConfiguration.cs | 31 +++++ .../DependencyInjection.cs | 1 + .../Jobs/NotificationDeliveryDispatcherJob.cs | 36 ++++++ .../Jobs/NotificationDeliveryJob.cs | 11 ++ ...024030000_AddNotificationDeliveryOutbox.cs | 60 ++++++++++ .../Migrations/AppDbContextModelSnapshot.cs | 78 +++++++++++++ .../Services/EmailService.cs | 5 +- .../Services/NotificationDeliveryProcessor.cs | 108 ++++++++++++++++++ .../Services/NotificationService.cs | 82 ++++++++----- todo.md | 2 +- 16 files changed, 438 insertions(+), 30 deletions(-) create mode 100644 src/Heimdall.Domain/Entities/NotificationDelivery.cs create mode 100644 src/Heimdall.Domain/Enums/NotificationDeliveryStatus.cs create mode 100644 src/Heimdall.Infrastructure/Data/Configurations/NotificationDeliveryConfiguration.cs create mode 100644 src/Heimdall.Infrastructure/Jobs/NotificationDeliveryDispatcherJob.cs create mode 100644 src/Heimdall.Infrastructure/Jobs/NotificationDeliveryJob.cs create mode 100644 src/Heimdall.Infrastructure/Migrations/20261024030000_AddNotificationDeliveryOutbox.cs create mode 100644 src/Heimdall.Infrastructure/Services/NotificationDeliveryProcessor.cs diff --git a/src/Heimdall.Application/Common/IApplicationDbContext.cs b/src/Heimdall.Application/Common/IApplicationDbContext.cs index 9e3f679..01f4146 100644 --- a/src/Heimdall.Application/Common/IApplicationDbContext.cs +++ b/src/Heimdall.Application/Common/IApplicationDbContext.cs @@ -24,6 +24,7 @@ public interface IApplicationDbContext // Notification entities DbSet Notifications { get; } + DbSet NotificationDeliveries { get; } DbSet NotificationTemplates { get; } DbSet UserNotificationConfigs { get; } DbSet Groups { get; } diff --git a/src/Heimdall.Domain/Entities/NotificationDelivery.cs b/src/Heimdall.Domain/Entities/NotificationDelivery.cs new file mode 100644 index 0000000..535f208 --- /dev/null +++ b/src/Heimdall.Domain/Entities/NotificationDelivery.cs @@ -0,0 +1,36 @@ +using Heimdall.Domain.Enums; +using Heimdall.Domain.Primitives; + +namespace Heimdall.Domain.Entities; + +/// Durable external delivery request for one notification channel. +public sealed class NotificationDelivery : Entity, IAuditableEntity +{ + public Guid NotificationId { get; private set; } + public NotificationChannel Channel { get; private set; } + public string Recipient { get; private set; } = string.Empty; + public string? ServiceUrl { get; private set; } + public int Priority { get; private set; } + public NotificationDeliveryStatus Status { get; private set; } = NotificationDeliveryStatus.Pending; + public int Attempts { get; private set; } + public DateTime? NextAttemptAt { get; private set; } + public DateTime? LeaseExpiresAt { get; private set; } + public DateTime? DeliveredAt { get; private set; } + public string? LastErrorType { get; private set; } + public DateTime CreatedAt { get; set; } + public DateTime UpdatedAt { get; set; } + + private NotificationDelivery() { } + + public NotificationDelivery(Guid notificationId, NotificationChannel channel, string recipient, + string? serviceUrl = null, int priority = 3) + : base(Guid.NewGuid()) + { + NotificationId = notificationId; + Channel = channel; + Recipient = recipient; + ServiceUrl = serviceUrl; + Priority = priority; + NextAttemptAt = DateTime.UtcNow; + } +} diff --git a/src/Heimdall.Domain/Enums/NotificationDeliveryStatus.cs b/src/Heimdall.Domain/Enums/NotificationDeliveryStatus.cs new file mode 100644 index 0000000..b693ef8 --- /dev/null +++ b/src/Heimdall.Domain/Enums/NotificationDeliveryStatus.cs @@ -0,0 +1,9 @@ +namespace Heimdall.Domain.Enums; + +public enum NotificationDeliveryStatus +{ + Pending = 0, + Processing = 1, + Delivered = 2, + Failed = 3 +} diff --git a/src/Heimdall.Infrastructure/BackgroundJobs/DependencyInjection.cs b/src/Heimdall.Infrastructure/BackgroundJobs/DependencyInjection.cs index f29cda2..ccbb721 100644 --- a/src/Heimdall.Infrastructure/BackgroundJobs/DependencyInjection.cs +++ b/src/Heimdall.Infrastructure/BackgroundJobs/DependencyInjection.cs @@ -37,6 +37,8 @@ public static class DependencyInjection services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); + services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); diff --git a/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs b/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs index 880db28..aae1f8e 100644 --- a/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs +++ b/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs @@ -80,6 +80,11 @@ public static class JobSetup job => job.ExecuteTimeoutSweepAsync(CancellationToken.None), "* * * * *"); // Every minute + manager.AddOrUpdate( + "notification-delivery-dispatch", + job => job.ExecuteAsync(CancellationToken.None), + "* * * * *"); // Recover due outbox deliveries every minute. + manager.AddOrUpdate( "partition-manager", job => job.ExecuteAsync(CancellationToken.None), diff --git a/src/Heimdall.Infrastructure/Data/AppDbContext.cs b/src/Heimdall.Infrastructure/Data/AppDbContext.cs index 91b2ef6..78f4c02 100644 --- a/src/Heimdall.Infrastructure/Data/AppDbContext.cs +++ b/src/Heimdall.Infrastructure/Data/AppDbContext.cs @@ -54,6 +54,7 @@ public class AppDbContext : IdentityDbContext, IApplicat // Notification entities public DbSet Notifications => Set(); + public DbSet NotificationDeliveries => Set(); public DbSet NotificationTemplates => Set(); public DbSet UserNotificationConfigs => Set(); diff --git a/src/Heimdall.Infrastructure/Data/Configurations/NotificationDeliveryConfiguration.cs b/src/Heimdall.Infrastructure/Data/Configurations/NotificationDeliveryConfiguration.cs new file mode 100644 index 0000000..47997b4 --- /dev/null +++ b/src/Heimdall.Infrastructure/Data/Configurations/NotificationDeliveryConfiguration.cs @@ -0,0 +1,31 @@ +using Heimdall.Domain.Entities; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Heimdall.Infrastructure.Data.Configurations; + +public sealed class NotificationDeliveryConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("notification_deliveries"); + builder.HasKey(d => d.Id); + builder.Property(d => d.Channel).HasConversion().HasMaxLength(20).IsRequired(); + builder.Property(d => d.Recipient).HasMaxLength(320).IsRequired(); + builder.Property(d => d.ServiceUrl).HasMaxLength(2048); + builder.Property(d => d.Status).HasConversion().HasMaxLength(20).IsRequired(); + builder.Property(d => d.LastErrorType).HasMaxLength(200); + builder.Property(d => d.CreatedAt).HasDefaultValueSql("NOW()"); + builder.Property(d => d.UpdatedAt).HasDefaultValueSql("NOW()"); + + builder.HasIndex(d => new { d.NotificationId, d.Channel }) + .IsUnique() + .HasDatabaseName("ux_notification_deliveries_notification_channel"); + builder.HasIndex(d => new { d.Status, d.NextAttemptAt, d.LeaseExpiresAt }) + .HasDatabaseName("ix_notification_deliveries_dispatch"); + builder.HasOne() + .WithMany() + .HasForeignKey(d => d.NotificationId) + .OnDelete(DeleteBehavior.Cascade); + } +} diff --git a/src/Heimdall.Infrastructure/DependencyInjection.cs b/src/Heimdall.Infrastructure/DependencyInjection.cs index 7338496..b6ba1fa 100644 --- a/src/Heimdall.Infrastructure/DependencyInjection.cs +++ b/src/Heimdall.Infrastructure/DependencyInjection.cs @@ -175,6 +175,7 @@ public static class DependencyInjection // Notification services services.AddScoped(); + services.AddScoped(); services.AddSingleton(); services.AddScoped(); services.AddScoped(); diff --git a/src/Heimdall.Infrastructure/Jobs/NotificationDeliveryDispatcherJob.cs b/src/Heimdall.Infrastructure/Jobs/NotificationDeliveryDispatcherJob.cs new file mode 100644 index 0000000..8c1f06f --- /dev/null +++ b/src/Heimdall.Infrastructure/Jobs/NotificationDeliveryDispatcherJob.cs @@ -0,0 +1,36 @@ +using Hangfire; +using Hangfire.Common; +using Hangfire.States; +using Heimdall.Application.Common; +using Heimdall.Domain.Enums; +using Microsoft.EntityFrameworkCore; + +namespace Heimdall.Infrastructure.Jobs; + +/// Re-enqueues due outbox rows so a process interruption after commit cannot lose delivery. +public sealed class NotificationDeliveryDispatcherJob( + IApplicationDbContext context, + IBackgroundJobClient backgroundJobs) +{ + public async Task ExecuteAsync(CancellationToken ct) + { + var now = DateTime.UtcNow; + var ids = await context.NotificationDeliveries.AsNoTracking() + .Where(d => (d.Status == NotificationDeliveryStatus.Pending && + (d.NextAttemptAt == null || d.NextAttemptAt <= now)) || + (d.Status == NotificationDeliveryStatus.Processing && d.LeaseExpiresAt <= now)) + .OrderBy(d => d.CreatedAt) + .Select(d => new { d.Id, d.Channel }) + .Take(100) + .ToListAsync(ct) + .ConfigureAwait(false); + + foreach (var delivery in ids) + { + var job = Job.FromExpression(service => + service.ExecuteAsync(delivery.Id, CancellationToken.None)); + var queue = delivery.Channel == NotificationChannel.Email ? "email" : "ntfy"; + backgroundJobs.Create(job, new EnqueuedState(queue)); + } + } +} diff --git a/src/Heimdall.Infrastructure/Jobs/NotificationDeliveryJob.cs b/src/Heimdall.Infrastructure/Jobs/NotificationDeliveryJob.cs new file mode 100644 index 0000000..bd455dd --- /dev/null +++ b/src/Heimdall.Infrastructure/Jobs/NotificationDeliveryJob.cs @@ -0,0 +1,11 @@ +using Hangfire; +using Heimdall.Infrastructure.Services; + +namespace Heimdall.Infrastructure.Jobs; + +public sealed class NotificationDeliveryJob(NotificationDeliveryProcessor processor) +{ + [AutomaticRetry(Attempts = 3, OnAttemptsExceeded = AttemptsExceededAction.Fail)] + public Task ExecuteAsync(Guid deliveryId, CancellationToken ct = default) => + processor.ProcessAsync(deliveryId, ct); +} diff --git a/src/Heimdall.Infrastructure/Migrations/20261024030000_AddNotificationDeliveryOutbox.cs b/src/Heimdall.Infrastructure/Migrations/20261024030000_AddNotificationDeliveryOutbox.cs new file mode 100644 index 0000000..4479d79 --- /dev/null +++ b/src/Heimdall.Infrastructure/Migrations/20261024030000_AddNotificationDeliveryOutbox.cs @@ -0,0 +1,60 @@ +using System; +using Heimdall.Infrastructure.Data; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Heimdall.Infrastructure.Migrations; + +[DbContext(typeof(AppDbContext))] +[Migration("20261024030000_AddNotificationDeliveryOutbox")] +public partial class AddNotificationDeliveryOutbox : Migration +{ + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "notification_deliveries", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + NotificationId = table.Column(type: "uuid", nullable: false), + Channel = table.Column(type: "character varying(20)", maxLength: 20, nullable: false), + Recipient = table.Column(type: "character varying(320)", maxLength: 320, nullable: false), + ServiceUrl = table.Column(type: "character varying(2048)", maxLength: 2048, nullable: true), + Priority = table.Column(type: "integer", nullable: false), + Status = table.Column(type: "character varying(20)", maxLength: 20, nullable: false), + Attempts = table.Column(type: "integer", nullable: false), + NextAttemptAt = table.Column(type: "timestamp with time zone", nullable: true), + LeaseExpiresAt = table.Column(type: "timestamp with time zone", nullable: true), + DeliveredAt = table.Column(type: "timestamp with time zone", nullable: true), + LastErrorType = table.Column(type: "character varying(200)", maxLength: 200, nullable: true), + CreatedAt = table.Column(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()"), + UpdatedAt = table.Column(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()") + }, + constraints: table => + { + table.PrimaryKey("PK_notification_deliveries", x => x.Id); + table.ForeignKey( + name: "FK_notification_deliveries_notifications_NotificationId", + column: x => x.NotificationId, + principalTable: "notifications", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "ux_notification_deliveries_notification_channel", + table: "notification_deliveries", + columns: new[] { "NotificationId", "Channel" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "ix_notification_deliveries_dispatch", + table: "notification_deliveries", + columns: new[] { "Status", "NextAttemptAt", "LeaseExpiresAt" }); + } + + protected override void Down(MigrationBuilder migrationBuilder) => + migrationBuilder.DropTable(name: "notification_deliveries"); +} diff --git a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs index 59b66c1..310b763 100644 --- a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs +++ b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs @@ -1579,6 +1579,75 @@ namespace Heimdall.Infrastructure.Migrations b.ToTable("notifications", (string)null); }); + modelBuilder.Entity("Heimdall.Domain.Entities.NotificationDelivery", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Attempts") + .HasColumnType("integer"); + + b.Property("Channel") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeliveredAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastErrorType") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("LeaseExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("NextAttemptAt") + .HasColumnType("timestamp with time zone"); + + b.Property("NotificationId") + .HasColumnType("uuid"); + + b.Property("Priority") + .HasColumnType("integer"); + + b.Property("Recipient") + .IsRequired() + .HasMaxLength(320) + .HasColumnType("character varying(320)"); + + b.Property("ServiceUrl") + .HasMaxLength(2048) + .HasColumnType("character varying(2048)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("Status", "NextAttemptAt", "LeaseExpiresAt") + .HasDatabaseName("ix_notification_deliveries_dispatch"); + + b.HasIndex("NotificationId", "Channel") + .IsUnique() + .HasDatabaseName("ux_notification_deliveries_notification_channel"); + + b.ToTable("notification_deliveries", (string)null); + }); + modelBuilder.Entity("Heimdall.Domain.Entities.NotificationTemplate", b => { b.Property("Id") @@ -2292,6 +2361,15 @@ namespace Heimdall.Infrastructure.Migrations b.ToTable("user_tokens", (string)null); }); + modelBuilder.Entity("Heimdall.Domain.Entities.NotificationDelivery", b => + { + b.HasOne("Heimdall.Domain.Entities.Notification", null) + .WithMany() + .HasForeignKey("NotificationId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b => { b.HasOne("Heimdall.Domain.Entities.Site", "Site") diff --git a/src/Heimdall.Infrastructure/Services/EmailService.cs b/src/Heimdall.Infrastructure/Services/EmailService.cs index 139cc27..f48c8ba 100644 --- a/src/Heimdall.Infrastructure/Services/EmailService.cs +++ b/src/Heimdall.Infrastructure/Services/EmailService.cs @@ -29,8 +29,7 @@ public class EmailService : IEmailService if (string.IsNullOrEmpty(smtpHost)) { - _logger.LogWarning("Email not sent: SMTP not configured (set Email:SmtpHost). To={To}, Subject={Subject}", recipient, subject); - return; + throw new InvalidOperationException("SMTP is not configured; email delivery cannot be completed."); } try @@ -60,7 +59,7 @@ public class EmailService : IEmailService } catch (OperationCanceledException) { - _logger.LogDebug("Email cancelled for {To}: {Subject}", recipient, subject); + throw; } catch (Exception ex) { diff --git a/src/Heimdall.Infrastructure/Services/NotificationDeliveryProcessor.cs b/src/Heimdall.Infrastructure/Services/NotificationDeliveryProcessor.cs new file mode 100644 index 0000000..774c68d --- /dev/null +++ b/src/Heimdall.Infrastructure/Services/NotificationDeliveryProcessor.cs @@ -0,0 +1,108 @@ +using System.Text.Encodings.Web; +using Heimdall.Application.Common; +using Heimdall.Application.Services; +using Heimdall.Domain.Entities; +using Heimdall.Domain.Enums; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; + +namespace Heimdall.Infrastructure.Services; + +/// Claims and sends one durable external notification delivery. +public sealed class NotificationDeliveryProcessor( + IApplicationDbContext context, + IEmailService emailService, + INtfyService ntfyService, + ILogger logger) +{ + private static readonly TimeSpan LeaseDuration = TimeSpan.FromMinutes(5); + + public async Task ProcessAsync(Guid deliveryId, CancellationToken ct) + { + var now = DateTime.UtcNow; + var leaseExpiresAt = now.Add(LeaseDuration); + var claimed = await context.NotificationDeliveries + .Where(d => d.Id == deliveryId && + ((d.Status == NotificationDeliveryStatus.Pending && + (d.NextAttemptAt == null || d.NextAttemptAt <= now)) || + (d.Status == NotificationDeliveryStatus.Processing && d.LeaseExpiresAt <= now))) + .ExecuteUpdateAsync(update => update + .SetProperty(d => d.Status, NotificationDeliveryStatus.Processing) + .SetProperty(d => d.Attempts, d => d.Attempts + 1) + .SetProperty(d => d.LeaseExpiresAt, leaseExpiresAt) + .SetProperty(d => d.UpdatedAt, now), ct) + .ConfigureAwait(false); + + if (claimed == 0) return; + + var delivery = await context.NotificationDeliveries.AsNoTracking() + .FirstOrDefaultAsync(d => d.Id == deliveryId, ct).ConfigureAwait(false); + if (delivery is null) return; + + var notification = await context.Notifications.AsNoTracking() + .FirstOrDefaultAsync(n => n.Id == delivery.NotificationId, ct).ConfigureAwait(false); + if (notification is null) + { + await MarkFailedAsync(deliveryId, "NotificationMissing", now, ct).ConfigureAwait(false); + return; + } + + try + { + switch (delivery.Channel) + { + case NotificationChannel.Email: + var body = $"

{HtmlEncoder.Default.Encode(notification.Title)}

{HtmlEncoder.Default.Encode(notification.Message)}

"; + await emailService.SendEmailAsync(delivery.Recipient, notification.Title, body, ct).ConfigureAwait(false); + break; + case NotificationChannel.Ntfy: + await ntfyService.SendNotificationAsync(delivery.Recipient, notification.Title, + notification.Message, delivery.Priority, delivery.ServiceUrl, ct).ConfigureAwait(false); + break; + default: + await MarkFailedAsync(deliveryId, "UnsupportedChannel", now, ct).ConfigureAwait(false); + return; + } + + var deliveredAt = DateTime.UtcNow; + await context.NotificationDeliveries.Where(d => d.Id == deliveryId && d.Status == NotificationDeliveryStatus.Processing) + .ExecuteUpdateAsync(update => update + .SetProperty(d => d.Status, NotificationDeliveryStatus.Delivered) + .SetProperty(d => d.DeliveredAt, deliveredAt) + .SetProperty(d => d.LeaseExpiresAt, (DateTime?)null) + .SetProperty(d => d.NextAttemptAt, (DateTime?)null) + .SetProperty(d => d.LastErrorType, (string?)null) + .SetProperty(d => d.UpdatedAt, deliveredAt), ct) + .ConfigureAwait(false); + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + // The lease makes an interrupted delivery eligible for recovery after process loss. + throw; + } + catch (Exception ex) + { + var failedAt = DateTime.UtcNow; + // Keep retrying transient provider failures; the row remains a durable pending delivery. + var retryAt = failedAt.AddMinutes(Math.Min(60, Math.Pow(2, delivery.Attempts - 1))); + await context.NotificationDeliveries.Where(d => d.Id == deliveryId && d.Status == NotificationDeliveryStatus.Processing) + .ExecuteUpdateAsync(update => update + .SetProperty(d => d.Status, NotificationDeliveryStatus.Pending) + .SetProperty(d => d.NextAttemptAt, retryAt) + .SetProperty(d => d.LeaseExpiresAt, (DateTime?)null) + .SetProperty(d => d.LastErrorType, ex.GetType().Name) + .SetProperty(d => d.UpdatedAt, failedAt), ct) + .ConfigureAwait(false); + logger.LogWarning("Notification delivery {DeliveryId} failed with {ErrorType} on attempt {Attempt}", + deliveryId, ex.GetType().Name, delivery.Attempts); + } + } + + private Task MarkFailedAsync(Guid deliveryId, string errorType, DateTime now, CancellationToken ct) => + context.NotificationDeliveries.Where(d => d.Id == deliveryId) + .ExecuteUpdateAsync(update => update + .SetProperty(d => d.Status, NotificationDeliveryStatus.Failed) + .SetProperty(d => d.LeaseExpiresAt, (DateTime?)null) + .SetProperty(d => d.LastErrorType, errorType) + .SetProperty(d => d.UpdatedAt, now), ct); +} diff --git a/src/Heimdall.Infrastructure/Services/NotificationService.cs b/src/Heimdall.Infrastructure/Services/NotificationService.cs index 632a4bb..7c6a6df 100644 --- a/src/Heimdall.Infrastructure/Services/NotificationService.cs +++ b/src/Heimdall.Infrastructure/Services/NotificationService.cs @@ -89,18 +89,30 @@ public class NotificationService : INotificationService } } + var notificationCreated = false; + var deliveries = new List(); if (notification is null) { notification = new Notification( userId, title, message, type, eventType, cameraId, siteId, snapshotUrl, link, notificationId); + // Persist the notification and its external delivery intent in the same EF transaction. + // The recurring dispatcher recovers rows if enqueueing below is interrupted. + if (_backgroundJobs is not null) + deliveries = await BuildExternalDeliveriesAsync(notification, userId, ct).ConfigureAwait(false); + _context.Notifications.Add(notification); + if (deliveries.Count > 0) + _context.NotificationDeliveries.AddRange(deliveries); try { await _context.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false); + notificationCreated = true; } catch (DbUpdateException) when (notificationId.HasValue) { + if (deliveries.Count > 0) + _context.NotificationDeliveries.RemoveRange(deliveries); notification = await _context.Notifications.AsNoTracking() .FirstOrDefaultAsync(n => n.Id == notificationId.Value, ct).ConfigureAwait(false); if (notification is null) throw; @@ -112,8 +124,24 @@ public class NotificationService : INotificationService // Broadcast in-app await _broadcast.NotifyNewNotification(dto, ct).ConfigureAwait(false); - // Send via email/ntfy if user has config - await DispatchToExternalChannelsAsync(notification, userId, ct).ConfigureAwait(false); + if (_backgroundJobs is not null) + { + if (notificationCreated) + { + foreach (var delivery in deliveries) + { + var job = Job.FromExpression(service => + service.ExecuteAsync(delivery.Id, CancellationToken.None)); + var queue = delivery.Channel == NotificationChannel.Email ? "email" : "ntfy"; + _backgroundJobs.Create(job, new EnqueuedState(queue)); + } + } + } + else + { + // Preserve synchronous delivery when Hangfire is not configured. + await DispatchToExternalChannelsAsync(notification, userId, ct).ConfigureAwait(false); + } return ServiceResult.Success(dto); } @@ -141,43 +169,45 @@ public class NotificationService : INotificationService if (config.EmailEnabled && !string.IsNullOrEmpty(config.EmailAddress)) { var htmlBody = $"

{HtmlEncoder.Default.Encode(notification.Title)}

{HtmlEncoder.Default.Encode(notification.Message)}

"; - if (_backgroundJobs is null) - { - await _emailService.SendEmailAsync(config.EmailAddress, notification.Title, htmlBody, ct).ConfigureAwait(false); - } - else - { - var job = Job.FromExpression(service => - service.SendEmailAsync(config.EmailAddress, notification.Title, htmlBody, CancellationToken.None)); - _backgroundJobs.Create(job, new EnqueuedState("email")); - } + await _emailService.SendEmailAsync(config.EmailAddress, notification.Title, htmlBody, ct).ConfigureAwait(false); } if (config.NtfyEnabled) { var topic = await ResolveNtfyTopicAsync(notification, userId, ct); - if (_backgroundJobs is null) - { - await _ntfyService.SendNotificationAsync( - topic, notification.Title, notification.Message, priority, config.NtfyUrl, ct).ConfigureAwait(false); - } - else - { - var ntfyUrl = config.NtfyUrl; - var job = Job.FromExpression(service => - service.SendNtfyAsync(topic, notification.Title, notification.Message, priority, ntfyUrl, CancellationToken.None)); - _backgroundJobs.Create(job, new EnqueuedState("ntfy")); - } + await _ntfyService.SendNotificationAsync( + topic, notification.Title, notification.Message, priority, config.NtfyUrl, ct).ConfigureAwait(false); } } catch (Exception ex) { _logger.LogError(ex, "Failed to dispatch external notification for user {UserId}", userId); - if (_backgroundJobs is not null) - throw; } } + private async Task> BuildExternalDeliveriesAsync( + Notification notification, Guid userId, CancellationToken ct) + { + var deliveries = new List(); + var config = await _context.UserNotificationConfigs + .FirstOrDefaultAsync(c => c.UserId == userId, ct).ConfigureAwait(false); + if (config is null || !config.IsEventTypeSubscribed(notification.EventType)) + return deliveries; + + var priority = EventTypePriorityMap.GetPriority(notification.EventType); + if (config.EmailEnabled && !string.IsNullOrEmpty(config.EmailAddress)) + deliveries.Add(new NotificationDelivery(notification.Id, NotificationChannel.Email, config.EmailAddress)); + + if (config.NtfyEnabled) + { + var topic = await ResolveNtfyTopicAsync(notification, userId, ct).ConfigureAwait(false); + deliveries.Add(new NotificationDelivery(notification.Id, NotificationChannel.Ntfy, + topic, config.NtfyUrl, priority)); + } + + return deliveries; + } + /// /// Résout le topic ntfy cible d'une notification (ticket #105) : /// topic configuré par l'utilisateur (NtfyTopic) > topic du site > défaut heimdall_{userId}. diff --git a/todo.md b/todo.md index a98e70c..1416f44 100644 --- a/todo.md +++ b/todo.md @@ -21,7 +21,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **PIPE-09** Valider sur caméra réelle capture automatique/manuelle, corrélation, miniatures, lecture autorisée, reprise d'upload et absence de références cassées. - [ ] **PIPE-01/02** La PR #61 implémente une première verticale PostgreSQL : dispatch vers l'agent assigné, claim atomique, tentative protégée, capture/analyse `ObjectDetection` CPU et résultat JSON persisté. Les PR #66 et #67 couvrent et valident avec PostgreSQL deux agents, réaffectation après échec, timeout par le sweep Hangfire, rejet des résultats tardifs et persistance du résultat courant. Restent les validations sur deux agents déployés et les autres types d'analyse. -- [ ] **PIPE-10 / FEAT-05** La PR de correction ntfy fait remonter les erreurs réseau/HTTP pour activer les retries Hangfire. Restent l’outbox transactionnelle serveur, état de livraison, déduplication/limitation par destinataire/canal, coupure/reprise sans perte ni doublon, SMTP/ntfy réels et échappement HTML. +- [ ] **PIPE-10 / FEAT-05** La PR #74 fait remonter les erreurs ntfy; cette PR ajoute une outbox SQL atomique avec état, leases, reprise périodique et unicité par notification/canal. Restent la validation CI et les essais SMTP/ntfy réels. La livraison reste au moins une fois : une panne après acceptation fournisseur mais avant l’acquittement SQL peut produire un doublon; aucune garantie exactement une fois n’est possible avec ces interfaces. - [ ] **OPS-02** Les PR #62 et #63 protègent les références de caméras supprimées logiquement, enregistrent l'inventaire des destinations avant upload et font parcourir ces destinations par le nettoyage final. Restent les objets recording tant que FEAT-02 n'a pas de producteur, les lignes historiques sans provenance (ne pas deviner), le test des anciens stockages inaccessibles et la vérification du changement de provider. - [ ] **OPS-05 / AGENT-06** Installer clés de signature CI et clés publiques indépendantes de Central côté Agent ; tester release réelle, digest/signature, mise à jour native et Docker, arrêt propre et rollback. - [ ] **AGENT-08** Valider reconnexion, remplacement atomique de configuration caméra et ACK persisté sur Agent déployé. -- 2.54.1 From f93b2459114173ff8568ddb860442ce8e76e9867 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sat, 24 Oct 2026 22:28:15 +0200 Subject: [PATCH 2/3] docs(audit): reference notification outbox pull request --- todo.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/todo.md b/todo.md index 1416f44..97728b4 100644 --- a/todo.md +++ b/todo.md @@ -21,7 +21,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **PIPE-09** Valider sur caméra réelle capture automatique/manuelle, corrélation, miniatures, lecture autorisée, reprise d'upload et absence de références cassées. - [ ] **PIPE-01/02** La PR #61 implémente une première verticale PostgreSQL : dispatch vers l'agent assigné, claim atomique, tentative protégée, capture/analyse `ObjectDetection` CPU et résultat JSON persisté. Les PR #66 et #67 couvrent et valident avec PostgreSQL deux agents, réaffectation après échec, timeout par le sweep Hangfire, rejet des résultats tardifs et persistance du résultat courant. Restent les validations sur deux agents déployés et les autres types d'analyse. -- [ ] **PIPE-10 / FEAT-05** La PR #74 fait remonter les erreurs ntfy; cette PR ajoute une outbox SQL atomique avec état, leases, reprise périodique et unicité par notification/canal. Restent la validation CI et les essais SMTP/ntfy réels. La livraison reste au moins une fois : une panne après acceptation fournisseur mais avant l’acquittement SQL peut produire un doublon; aucune garantie exactement une fois n’est possible avec ces interfaces. +- [ ] **PIPE-10 / FEAT-05** La PR #74 fait remonter les erreurs ntfy; la PR #76 ajoute une outbox SQL atomique avec état, leases, reprise périodique et unicité par notification/canal. Restent la validation CI et les essais SMTP/ntfy réels. La livraison reste au moins une fois : une panne après acceptation fournisseur mais avant l’acquittement SQL peut produire un doublon; aucune garantie exactement une fois n’est possible avec ces interfaces. - [ ] **OPS-02** Les PR #62 et #63 protègent les références de caméras supprimées logiquement, enregistrent l'inventaire des destinations avant upload et font parcourir ces destinations par le nettoyage final. Restent les objets recording tant que FEAT-02 n'a pas de producteur, les lignes historiques sans provenance (ne pas deviner), le test des anciens stockages inaccessibles et la vérification du changement de provider. - [ ] **OPS-05 / AGENT-06** Installer clés de signature CI et clés publiques indépendantes de Central côté Agent ; tester release réelle, digest/signature, mise à jour native et Docker, arrêt propre et rollback. - [ ] **AGENT-08** Valider reconnexion, remplacement atomique de configuration caméra et ACK persisté sur Agent déployé. -- 2.54.1 From 59f07820946a6fc5b37a4db4801b09634cd8a5bc Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sat, 24 Oct 2026 22:29:05 +0200 Subject: [PATCH 3/3] fix(notifications): type delivery lease update explicitly --- .../Services/NotificationDeliveryProcessor.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Heimdall.Infrastructure/Services/NotificationDeliveryProcessor.cs b/src/Heimdall.Infrastructure/Services/NotificationDeliveryProcessor.cs index 774c68d..7f2bec1 100644 --- a/src/Heimdall.Infrastructure/Services/NotificationDeliveryProcessor.cs +++ b/src/Heimdall.Infrastructure/Services/NotificationDeliveryProcessor.cs @@ -29,7 +29,7 @@ public sealed class NotificationDeliveryProcessor( .ExecuteUpdateAsync(update => update .SetProperty(d => d.Status, NotificationDeliveryStatus.Processing) .SetProperty(d => d.Attempts, d => d.Attempts + 1) - .SetProperty(d => d.LeaseExpiresAt, leaseExpiresAt) + .SetProperty(d => d.LeaseExpiresAt, (DateTime?)leaseExpiresAt) .SetProperty(d => d.UpdatedAt, now), ct) .ConfigureAwait(false); -- 2.54.1