Files
Heimdall/tests/Heimdall.IntegrationTests/Notifications/NotificationDeliveryOutboxTests.cs
T

220 lines
10 KiB
C#
Raw Normal View History

using System.Reflection;
using Hangfire;
using Hangfire.States;
using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using Heimdall.Domain.Enums;
using Heimdall.Infrastructure.Data;
using Heimdall.Infrastructure.Jobs;
using Heimdall.Infrastructure.Services;
using Heimdall.IntegrationTests.Controllers;
using Heimdall.IntegrationTests.Factories;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using Shouldly;
namespace Heimdall.IntegrationTests.Notifications;
public sealed class NotificationDeliveryOutboxTests(PostgreSqlContainerFixture postgres) : PostgresTestBase(postgres)
{
[Fact]
public async Task ProcessAsync_EmailSuccess_MarksDeliveryDeliveredAndClearsLease()
{
var (_, deliveryId) = await CreateDeliveryAsync(NotificationChannel.Email, "<door@example.test>", "<door>");
var email = new RecordingEmailService();
await ProcessDeliveryAsync(deliveryId, email: email);
var delivery = await GetDeliveryAsync(deliveryId);
delivery.Status.ShouldBe(NotificationDeliveryStatus.Delivered);
delivery.Attempts.ShouldBe(1);
delivery.DeliveredAt.ShouldNotBeNull();
delivery.LeaseExpiresAt.ShouldBeNull();
delivery.NextAttemptAt.ShouldBeNull();
delivery.LastErrorType.ShouldBeNull();
email.Recipient.ShouldBe("<door@example.test>");
email.Subject.ShouldBe("<door>");
email.Body!.ShouldContain("&lt;door&gt;");
}
[Fact]
public async Task ProcessAsync_NtfyFailure_SchedulesRetryAndStoresOnlyErrorType()
{
var (_, deliveryId) = await CreateDeliveryAsync(NotificationChannel.Ntfy, "security-topic", "Motion");
var ntfy = new RecordingNtfyService
{
OnSend = (_, _, _, _, _, _) => Task.FromException(new InvalidOperationException("private provider response"))
};
await ProcessDeliveryAsync(deliveryId, ntfy: ntfy);
var delivery = await GetDeliveryAsync(deliveryId);
delivery.Status.ShouldBe(NotificationDeliveryStatus.Pending);
delivery.Attempts.ShouldBe(1);
delivery.NextAttemptAt.ShouldNotBeNull();
delivery.NextAttemptAt!.Value.ShouldBeGreaterThan(DateTime.UtcNow);
delivery.LeaseExpiresAt.ShouldBeNull();
delivery.LastErrorType.ShouldBe(nameof(InvalidOperationException));
delivery.LastErrorType!.ShouldNotContain("private provider response");
ntfy.SendCount.ShouldBe(1);
}
[Fact]
public async Task ProcessAsync_FutureDeliveryAndActiveLease_DoNotCallProvider()
{
var (_, futureId) = await CreateDeliveryAsync(NotificationChannel.Email, "future@example.test", "Future");
var (_, leasedId) = await CreateDeliveryAsync(NotificationChannel.Email, "leased@example.test", "Leased");
await UpdateDeliveryAsync(futureId, update => update
.SetProperty(d => d.NextAttemptAt, (DateTime?)DateTime.UtcNow.AddMinutes(10)));
await UpdateDeliveryAsync(leasedId, update => update
.SetProperty(d => d.Status, NotificationDeliveryStatus.Processing)
.SetProperty(d => d.Attempts, 1)
.SetProperty(d => d.LeaseExpiresAt, (DateTime?)DateTime.UtcNow.AddMinutes(5)));
var email = new RecordingEmailService();
await ProcessDeliveryAsync(futureId, email: email);
await ProcessDeliveryAsync(leasedId, email: email);
email.SendCount.ShouldBe(0);
var future = await GetDeliveryAsync(futureId);
future.Status.ShouldBe(NotificationDeliveryStatus.Pending);
future.Attempts.ShouldBe(0);
var leased = await GetDeliveryAsync(leasedId);
leased.Status.ShouldBe(NotificationDeliveryStatus.Processing);
leased.Attempts.ShouldBe(1);
}
[Fact]
public async Task ProcessAsync_ExpiredLease_ReclaimsAndCompletesDelivery()
{
var (_, deliveryId) = await CreateDeliveryAsync(NotificationChannel.Email, "retry@example.test", "Retry");
await UpdateDeliveryAsync(deliveryId, update => update
.SetProperty(d => d.Status, NotificationDeliveryStatus.Processing)
.SetProperty(d => d.Attempts, 1)
.SetProperty(d => d.LeaseExpiresAt, (DateTime?)DateTime.UtcNow.AddMinutes(-1)));
var email = new RecordingEmailService();
await ProcessDeliveryAsync(deliveryId, email: email);
var delivery = await GetDeliveryAsync(deliveryId);
delivery.Status.ShouldBe(NotificationDeliveryStatus.Delivered);
delivery.Attempts.ShouldBe(2);
delivery.LeaseExpiresAt.ShouldBeNull();
email.SendCount.ShouldBe(1);
}
[Fact]
public async Task Dispatcher_EnqueuesOnlyDueOrExpiredDeliveriesOnChannelQueues()
{
var (_, dueEmailId) = await CreateDeliveryAsync(NotificationChannel.Email, "due@example.test", "Due");
var (_, dueNtfyId) = await CreateDeliveryAsync(NotificationChannel.Ntfy, "due-topic", "Due");
var (_, futureId) = await CreateDeliveryAsync(NotificationChannel.Email, "future@example.test", "Future");
var (_, activeLeaseId) = await CreateDeliveryAsync(NotificationChannel.Ntfy, "active-topic", "Active");
var (_, expiredLeaseId) = await CreateDeliveryAsync(NotificationChannel.Email, "expired@example.test", "Expired");
await UpdateDeliveryAsync(futureId, update => update
.SetProperty(d => d.NextAttemptAt, (DateTime?)DateTime.UtcNow.AddMinutes(10)));
await UpdateDeliveryAsync(activeLeaseId, update => update
.SetProperty(d => d.Status, NotificationDeliveryStatus.Processing)
.SetProperty(d => d.LeaseExpiresAt, (DateTime?)DateTime.UtcNow.AddMinutes(5)));
await UpdateDeliveryAsync(expiredLeaseId, update => update
.SetProperty(d => d.Status, NotificationDeliveryStatus.Processing)
.SetProperty(d => d.LeaseExpiresAt, (DateTime?)DateTime.UtcNow.AddMinutes(-1)));
var backgroundJobs = Substitute.For<IBackgroundJobClient>();
backgroundJobs.Create(Arg.Any<Job>(), Arg.Any<IState>()).Returns("job-id");
await using var scope = Factory.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await new NotificationDeliveryDispatcherJob(db, backgroundJobs).ExecuteAsync(CancellationToken.None);
var scheduled = backgroundJobs.ReceivedCalls()
.Where(call => call.GetMethodInfo().Name == nameof(IBackgroundJobClient.Create))
.Select(call => call.GetArguments())
.Select(args => (Job)args[0]!)
.ToArray();
scheduled.Length.ShouldBe(3);
scheduled.Select(job => (Guid)job.Args[0]!).ShouldBe([dueEmailId, dueNtfyId, expiredLeaseId]);
var queues = backgroundJobs.ReceivedCalls()
.Where(call => call.GetMethodInfo().Name == nameof(IBackgroundJobClient.Create))
.Select(call => (EnqueuedState)call.GetArguments()[1]!)
.Select(state => state.Queue)
.ToArray();
queues.ShouldBe(["email", "ntfy", "email"]);
}
private async Task<(Guid NotificationId, Guid DeliveryId)> CreateDeliveryAsync(
NotificationChannel channel, string recipient, string title)
{
await using var scope = Factory.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var notification = new Notification(Guid.NewGuid(), title, "A test event", NotificationType.Info);
var delivery = new NotificationDelivery(notification.Id, channel, recipient, "https://ntfy.example.test", 4);
db.Notifications.Add(notification);
db.NotificationDeliveries.Add(delivery);
await db.SaveChangesAsync();
return (notification.Id, delivery.Id);
}
private async Task UpdateDeliveryAsync(Guid deliveryId,
System.Linq.Expressions.Expression<Func<SetPropertyCalls<NotificationDelivery>,
SetPropertyCalls<NotificationDelivery>>> update)
{
await using var scope = Factory.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await db.NotificationDeliveries.Where(d => d.Id == deliveryId).ExecuteUpdateAsync(update);
}
private async Task ProcessDeliveryAsync(Guid deliveryId,
RecordingEmailService? email = null, RecordingNtfyService? ntfy = null)
{
await using var scope = Factory.Services.CreateAsyncScope();
var context = scope.ServiceProvider.GetRequiredService<Heimdall.Application.Common.IApplicationDbContext>();
var processor = new NotificationDeliveryProcessor(context, email ?? new RecordingEmailService(),
ntfy ?? new RecordingNtfyService(), NullLogger<NotificationDeliveryProcessor>.Instance);
await processor.ProcessAsync(deliveryId, CancellationToken.None);
}
private async Task<NotificationDelivery> GetDeliveryAsync(Guid deliveryId)
{
await using var scope = Factory.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
return await db.NotificationDeliveries.AsNoTracking().SingleAsync(d => d.Id == deliveryId);
}
private sealed class RecordingEmailService : IEmailService
{
public int SendCount { get; private set; }
public string? Recipient { get; private set; }
public string? Subject { get; private set; }
public string? Body { get; private set; }
public Task SendEmailAsync(string recipient, string subject, string bodyHtml, CancellationToken ct = default)
{
SendCount++;
Recipient = recipient;
Subject = subject;
Body = bodyHtml;
return Task.CompletedTask;
}
}
private sealed class RecordingNtfyService : INtfyService
{
public int SendCount { get; private set; }
public Func<string, string, string, int, string?, CancellationToken, Task>? OnSend { get; init; }
public Task SendNotificationAsync(string topic, string title, string message, int priority = 3,
string? baseUrl = null, CancellationToken ct = default)
{
SendCount++;
return OnSend?.Invoke(topic, title, message, priority, baseUrl, ct) ?? Task.CompletedTask;
}
public Task<bool> SendTestAsync(string topic, string title, string message, string? baseUrl = null,
CancellationToken ct = default) => Task.FromResult(true);
}
}