fix(outbox): persist a delivery outcome on its own token, not the shutdown token (NTF-1, WP4 task 4.5)

This commit is contained in:
Joseph Doherty
2026-12-03 09:54:37 -05:00
parent f02fe9d696
commit 5f7b850af2
3 changed files with 85 additions and 5 deletions
@@ -116,6 +116,69 @@ public class NotificationOutboxActorDispatchTests : TestKit
.Returns(new[] { config });
}
/// <summary>
/// Adapter whose send completes only when the test releases it, ignoring the cancellation
/// token — the shape of a relay that has already accepted the message when shutdown lands.
/// </summary>
private sealed class GatedAdapter : INotificationDeliveryAdapter
{
public readonly TaskCompletionSource Entered = new(TaskCreationOptions.RunContinuationsAsynchronously);
public readonly TaskCompletionSource Release = new(TaskCreationOptions.RunContinuationsAsynchronously);
/// <inheritdoc />
public NotificationType Type => NotificationType.Email;
/// <inheritdoc />
public async Task<DeliveryOutcome> DeliverAsync(
Notification notification, CancellationToken cancellationToken = default)
{
Entered.TrySetResult();
await Release.Task;
return DeliveryOutcome.Success("ops@example.com");
}
}
/// <summary>
/// NTF-1 regression: the singleton is stopped (handover) while a send is in flight; the relay
/// has already accepted it. The Delivered write must still land — on a token the shutdown did
/// not cancel — or the next active node re-sends the email/SMS.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task ShutdownMidDelivery_StillPersistsTheDeliveredOutcome()
{
SetupSmtpRetryPolicy(maxRetries: 5, retryDelay: TimeSpan.FromMinutes(1));
var notification = MakeNotification();
_outboxRepository.GetDueAsync(Arg.Any<DateTimeOffset>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(new[] { notification });
// A real EF ExecuteUpdateAsync throws on a cancelled token; model that.
var persisted = new TaskCompletionSource<NotificationStatus>(TaskCreationOptions.RunContinuationsAsynchronously);
_outboxRepository.UpdateAsync(Arg.Any<Notification>(), Arg.Any<CancellationToken>())
.Returns(ci =>
{
((CancellationToken)ci[1]).ThrowIfCancellationRequested();
persisted.TrySetResult(((Notification)ci[0]).Status);
return Task.FromResult(true);
});
var adapter = new GatedAdapter();
var actor = CreateActor([adapter]);
Watch(actor);
actor.Tell(InternalMessages.DispatchTick.Instance);
await adapter.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5));
// Handover: PostStop cancels the shutdown token while the send is in flight.
Sys.Stop(actor);
ExpectTerminated(actor);
adapter.Release.TrySetResult();
var status = await persisted.Task.WaitAsync(TimeSpan.FromSeconds(5));
Assert.Equal(NotificationStatus.Delivered, status);
}
/// <summary>Verifies that a dispatch tick claims due notifications and invokes the adapter.</summary>
[Fact]
public void DispatchTick_ClaimsDueNotifications_AndInvokesAdapter()