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:
@@ -111,6 +111,8 @@ The site→central handoff is **at-least-once**. Central ingests an inbound noti
|
||||
|
||||
Delivery has no row-level claim or lease: dispatchers read due rows and persist delivery status after sending. An interrupted delivery can therefore be sent again after failover. During a dual-active partition permitted by the auto-down policy, both central singletons can repeatedly select overlapping batches and deliver duplicate notifications across multiple sweeps; exposure is not limited to one notification or one handover. The `NotificationId` deduplication above protects ingestion, not external Email/SMS delivery. This remains an accepted at-least-once delivery limitation; there is no dispatcher fencing or exactly-once guarantee.
|
||||
|
||||
A **graceful** handover no longer widens that window (NTF-1, 2026-12): the actor's shutdown token is passed to the channel adapter (so CoordinatedShutdown cuts an in-flight send short) but **not** to the write that records the adapter's outcome. Once the adapter has returned — for a success, after the relay accepted the message — the status write runs on its own token bounded by a 30 s timeout, and the audit rows are emitted the same way. Previously that write was cancelled with the shutdown token, the row stayed `Pending`/`Retrying` with no record of the send, and the new active node's first sweep sent the email or SMS again.
|
||||
|
||||
## Dispatcher
|
||||
|
||||
The dispatcher loop runs on a fixed interval. On each tick the `NotificationOutboxActor`:
|
||||
|
||||
@@ -683,7 +683,7 @@ public class NotificationOutboxActor : ReceiveActor, IWithTimers
|
||||
notification.Status = NotificationStatus.Parked;
|
||||
notification.LastError = missingAdapterError;
|
||||
notification.LastAttemptAt = parkedAt;
|
||||
await WarnIfVanishedAsync(outboxRepository, notification, cancellationToken);
|
||||
await WarnIfVanishedAsync(outboxRepository, notification);
|
||||
await EmitAttemptAuditAsync(
|
||||
notification,
|
||||
parkedAt,
|
||||
@@ -741,7 +741,12 @@ public class NotificationOutboxActor : ReceiveActor, IWithTimers
|
||||
break;
|
||||
}
|
||||
|
||||
await WarnIfVanishedAsync(outboxRepository, notification, cancellationToken);
|
||||
// NTF-1: from here on the shutdown token is NOT used. The adapter has returned an
|
||||
// outcome — for a Success the email/SMS has already been accepted by the relay — so
|
||||
// the write that records it must land even when a singleton handover cancelled the
|
||||
// token mid-delivery. With the shutdown token the write threw, the row stayed
|
||||
// Pending/Retrying with no record of the send, and the new active node re-sent it.
|
||||
await WarnIfVanishedAsync(outboxRepository, notification);
|
||||
|
||||
// Emit the per-attempt Attempted row exactly once regardless of the
|
||||
// outcome (B2). The error message comes from the outcome, not from
|
||||
@@ -767,6 +772,14 @@ public class NotificationOutboxActor : ReceiveActor, IWithTimers
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Upper bound on the write that records a delivery outcome (NTF-1). That write runs on
|
||||
/// its own token rather than the actor's shutdown token, so a handover cannot cancel the
|
||||
/// record of a send that already happened; this keeps a wedged database from pinning a
|
||||
/// stopping actor's delivery task forever. Settable for tests.
|
||||
/// </summary>
|
||||
internal static TimeSpan OutcomePersistTimeout { get; set; } = TimeSpan.FromSeconds(30);
|
||||
|
||||
/// <summary>
|
||||
/// Persists the dispatcher's delivery-state write and logs when the row has
|
||||
/// VANISHED underneath it — <see cref="INotificationOutboxRepository.UpdateAsync"/>
|
||||
@@ -783,10 +796,12 @@ public class NotificationOutboxActor : ReceiveActor, IWithTimers
|
||||
/// </remarks>
|
||||
private async Task WarnIfVanishedAsync(
|
||||
INotificationOutboxRepository repository,
|
||||
Notification notification,
|
||||
CancellationToken cancellationToken)
|
||||
Notification notification)
|
||||
{
|
||||
var persisted = await repository.UpdateAsync(notification, cancellationToken);
|
||||
// Deliberately NOT the actor's shutdown token (NTF-1): this records an outcome the
|
||||
// channel already produced, so it is bounded by its own timeout instead.
|
||||
using var persistCts = new CancellationTokenSource(OutcomePersistTimeout);
|
||||
var persisted = await repository.UpdateAsync(notification, persistCts.Token);
|
||||
if (!persisted)
|
||||
{
|
||||
_logger.LogWarning(
|
||||
|
||||
+63
@@ -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()
|
||||
|
||||
Reference in New Issue
Block a user