Path: redb-identity/tests/redb.Identity.Tests/Webhooks/WebhookOutboxTests.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/tests/redb.Identity.Tests/Webhooks/WebhookOutboxTests.cs
----
using System.Diagnostics;
using System.Diagnostics.Metrics;
using AwesomeAssertions;
using Microsoft.Extensions.DependencyInjection;
using redb.Core.Query;
using redb.Identity.Core.Configuration;
using redb.Identity.Core.Events;
using redb.Identity.Core.Metrics;
using redb.Identity.Tests.Infrastructure;
using Xunit;
namespace redb.Identity.Tests.Webhooks;
///
/// Webhook delivery through the outbox: at least once with a stable delivery id, nothing sent to a
/// subscription that went away, leases decided by the database clock, a hanging subscriber that does
/// not starve the others, no work for an event nobody wants, and the audit row first.
///
[Collection("ProductionHttp")]
public class WebhookOutboxTests
{
private readonly ProductionHttpFixture _fx;
private readonly WebhookTestSupport _w;
public WebhookOutboxTests(ProductionHttpFixture fx)
{
_fx = fx;
_w = new WebhookTestSupport(fx);
}
[Fact]
public async Task ARetriedDelivery_KeepsItsDeliveryId_AndEndsDelivered()
{
// The first request fails, the second succeeds.
await using var receiver = new TestWebhookReceiver(n => (n == 1 ? 500 : 200, TimeSpan.Zero));
var sub = await _w.SubscribeAsync(receiver.Url, maxAttempts: 3, retryBackoffMs: 50);
try
{
await _w.RaiseAsync();
(await _w.WaitForRowsAsync(sub, 1)).Should().HaveCount(1);
var worker = _w.Worker();
await WebhookTestSupport.RunUntilAsync(worker, () => receiver.Arrivals.Count >= 2, TimeSpan.FromSeconds(10));
await worker.DrainAsync();
var arrivals = receiver.Arrivals.ToArray();
arrivals.Should().HaveCount(2);
arrivals.Select(a => a.DeliveryId).Distinct().Should().ContainSingle("a retry is the same delivery");
arrivals.Select(a => a.Attempt).Should().Equal(1, 2);
arrivals[0].Body.Should().Contain("\"eventId\"", "the body is the event, whose id a receiver can deduplicate by");
var rows = await _w.RowsAsync(sub);
rows.Should().ContainSingle();
rows[0].Status.Should().Be("delivered");
rows[0].Attempts.Should().Be(2);
}
finally { await _w.UnsubscribeAsync(sub); }
}
[Fact]
public async Task ASubscriptionDeletedBeforeDelivery_IsNotSent_AndTheRowIsCancelled()
{
await using var receiver = TestWebhookReceiver.Answering(200);
var sub = await _w.SubscribeAsync(receiver.Url);
await _w.RaiseAsync();
(await _w.WaitForRowsAsync(sub, 1)).Should().HaveCount(1);
await _w.UnsubscribeAsync(sub);
var worker = _w.Worker();
await WebhookTestSupport.RunUntilAsync(worker, () => false, TimeSpan.FromMilliseconds(600));
await worker.DrainAsync();
receiver.Arrivals.Should().BeEmpty();
(await _w.RowsAsync(sub)).Single().Status.Should().Be("cancelled");
}
[Fact]
public async Task ASubscriptionDisabledBeforeDelivery_IsNotSent_AndTheRowIsCancelled()
{
await using var receiver = TestWebhookReceiver.Answering(200);
var sub = await _w.SubscribeAsync(receiver.Url);
try
{
await _w.RaiseAsync();
(await _w.WaitForRowsAsync(sub, 1)).Should().HaveCount(1);
await _w.DisableAsync(sub);
var worker = _w.Worker();
await WebhookTestSupport.RunUntilAsync(worker, () => false, TimeSpan.FromMilliseconds(600));
await worker.DrainAsync();
receiver.Arrivals.Should().BeEmpty();
(await _w.RowsAsync(sub)).Single().Status.Should().Be("cancelled");
}
finally { await _w.UnsubscribeAsync(sub); }
}
[Fact]
public async Task ARowLeasedByAnotherNode_IsNotTaken_EvenByANodeWhoseClockIsAnHourAhead()
{
await using var receiver = TestWebhookReceiver.Answering(200);
var sub = await _w.SubscribeAsync(receiver.Url);
try
{
await _w.RaiseAsync();
var row = (await _w.WaitForRowsAsync(sub, 1)).Single();
// Node A takes the lease, by the database clock.
var claimed = await _fx.UseRedbAsync(redb =>
new IdentityEventStore(redb, _fx.ServiceProvider.GetRequiredService())
.TryClaimAsync(row.Id, row.Attempts, 60, "node-A"));
claimed.Should().BeTrue();
// Node B believes it is an hour later; the lease is still A's.
var nodeB = _w.Worker(time: new ShiftedTime(TimeSpan.FromHours(1)), node: "node-B");
await WebhookTestSupport.RunUntilAsync(nodeB, () => false, TimeSpan.FromMilliseconds(600));
await nodeB.DrainAsync();
receiver.Arrivals.Should().BeEmpty();
var after = (await _w.RowsAsync(sub)).Single();
after.Status.Should().Be("pending");
after.LeasedBy.Should().Be("node-A");
}
finally { await _w.UnsubscribeAsync(sub); }
}
[Fact]
public async Task AClaimFromARowReadBeforeAnotherAttempt_IsRefused()
{
var (staleClaim, freshClaim) = await _fx.UseRedbAsync(async redb =>
{
// A kind no worker sends, so only this test touches the row.
var store = new IdentityEventStore(redb, _fx.ServiceProvider.GetRequiredService());
await store.InsertOutboxAsync([new OutboxEntry(Guid.NewGuid(), Guid.NewGuid(), "test-stale-claim", "d1", "x", "{}")]);
var read = (await store.DueAsync(10_000)).Single(r => r.Kind == "test-stale-claim");
try
{
// Node B claims the row and makes attempt 1; the retry is due at once.
(await store.TryClaimAsync(read.Id, read.Attempts, 30, "node-B")).Should().BeTrue();
await store.ScheduleRetryAsync(read.Id, "node-B", 0, "HTTP 500");
await Task.Delay(50);
// Node A read the row before that attempt.
var stale = await store.TryClaimAsync(read.Id, read.Attempts, 30, "node-A");
var fresh = await store.TryClaimAsync(read.Id, read.Attempts + 1, 30, "node-A");
return (stale, fresh);
}
finally
{
await redb.Context.ExecuteAsync("DELETE FROM identity_delivery_outbox WHERE id = @p0", read.Id);
}
});
staleClaim.Should().BeFalse("the row was read before attempt 1, so its attempt count is stale");
freshClaim.Should().BeTrue("a pass that reads the row again claims it");
}
[Fact]
public async Task AFailingSubscriber_GetsAttempts1To3_FromTwoNodes_AndTheRowFailsAtMaxAttempts()
{
await using var receiver = TestWebhookReceiver.Answering(500);
var sub = await _w.SubscribeAsync(receiver.Url, maxAttempts: 3, retryBackoffMs: 20);
try
{
await _w.RaiseAsync();
(await _w.WaitForRowsAsync(sub, 1)).Should().HaveCount(1);
// Two nodes poll as fast as they can, so passes read rows that the other node is about to retry.
var nodes = new[] { _w.Worker(node: "node-A"), _w.Worker(node: "node-B") };
var deadline = DateTime.UtcNow.AddSeconds(15);
await Task.WhenAll(nodes.Select(async node =>
{
while (DateTime.UtcNow < deadline && (await _w.RowsAsync(sub)).Single().Status == "pending")
await node.RunOnceAsync();
}));
foreach (var node in nodes) await node.DrainAsync();
receiver.Arrivals.Select(a => a.Attempt).Should().Equal(1, 2, 3);
var row = (await _w.RowsAsync(sub)).Single();
row.Status.Should().Be("failed");
row.Attempts.Should().Be(3);
}
finally { await _w.UnsubscribeAsync(sub); }
}
[Fact]
public async Task TwoNodesRacingForOneRow_SendItOnce()
{
// An own host with several nodes and no cluster policy runs the delivery timer on every node;
// the lease alone must keep one row from being sent twice.
await using var receiver = new TestWebhookReceiver(_ => (200, TimeSpan.FromMilliseconds(300)));
var sub = await _w.SubscribeAsync(receiver.Url);
try
{
await _w.RaiseAsync();
(await _w.WaitForRowsAsync(sub, 1)).Should().HaveCount(1);
var nodes = Enumerable.Range(0, 4).Select(i => _w.Worker(node: $"racer-{i}")).ToArray();
await Task.WhenAll(nodes.Select(n => n.RunOnceAsync()));
await Task.WhenAll(nodes.Select(n => n.DrainAsync()));
receiver.Arrivals.Should().ContainSingle("four nodes picked the same row; only the one holding the lease sends it");
(await _w.RowsAsync(sub)).Single().Status.Should().Be("delivered");
}
finally { await _w.UnsubscribeAsync(sub); }
}
[Fact]
public async Task ASubscriberThatHangs_DoesNotHoldBackAHealthyOne()
{
await using var blackHole = new TestWebhookReceiver(_ => (200, TimeSpan.FromMilliseconds(-1)));
await using var healthy = TestWebhookReceiver.Answering(200);
var hanging = await _w.SubscribeAsync(blackHole.Url, timeoutMs: 8000, maxAttempts: 1);
var good = await _w.SubscribeAsync(healthy.Url);
try
{
const int events = 6;
for (var i = 0; i < events; i++) await _w.RaiseAsync();
(await _w.WaitForRowsAsync(good, events)).Should().HaveCount(events);
(await _w.WaitForRowsAsync(hanging, events)).Should().HaveCount(events);
var worker = _w.Worker(new DeliveryOptions { MaxParallel = 4, MaxParallelPerDestination = 2, BatchSize = 50 });
var clock = Stopwatch.StartNew();
await WebhookTestSupport.RunUntilAsync(worker, () => healthy.Arrivals.Count >= events, TimeSpan.FromSeconds(6));
var healthyDone = clock.Elapsed;
healthy.Arrivals.Should().HaveCount(events);
healthyDone.Should().BeLessThan(TimeSpan.FromSeconds(3),
"the hanging subscriber holds two slots for 8 s; the healthy one must not wait for them");
blackHole.Arrivals.Count.Should().BeLessThanOrEqualTo(2, "one destination never holds more than its own slots");
}
finally
{
await _w.UnsubscribeAsync(hanging);
await _w.UnsubscribeAsync(good);
}
}
[Fact]
public async Task AnEventNobodySubscribedTo_WritesNoOutboxRow_AndReadsTheSubscriptionsOnce()
{
var cache = _fx.ServiceProvider.GetRequiredService();
var before = await _fx.UseRedbAsync(redb => redb.Context.ExecuteScalarAsync("SELECT COUNT(*) FROM identity_delivery_outbox WHERE kind = 'webhook'"));
cache.Invalidate();
var loads = cache.Loads;
for (var i = 0; i < 5; i++) await _w.RaiseAsync();
await Task.Delay(500); // the events route runs on a wire tap
var after = await _fx.UseRedbAsync(redb => redb.Context.ExecuteScalarAsync("SELECT COUNT(*) FROM identity_delivery_outbox WHERE kind = 'webhook'"));
after.Should().Be(before, "no subscription, no webhook row (the audit target of the fixture has its own)");
(cache.Loads - loads).Should().Be(1, "five events, one read of the subscriptions");
}
[Fact]
public async Task WhenTheOutboxCannotBeWritten_TheAuditRowIsStillWritten_AndTheLossIsCounted()
{
var failures = new List();
using var listener = new MeterListener();
listener.InstrumentPublished = (instrument, l) =>
{
if (instrument.Meter.Name == IdentityMetrics.MeterName && instrument.Name == "identity.delivery.enqueue_failures")
l.EnableMeasurementEvents(instrument);
};
listener.SetMeasurementEventCallback((_, _, tags, _) =>
{
foreach (var tag in tags) if (tag.Key == "event_type") lock (failures) failures.Add(tag.Value?.ToString());
});
listener.Start();
await using var receiver = TestWebhookReceiver.Answering(200);
var sub = await _w.SubscribeAsync(receiver.Url);
await RenameOutboxAsync("identity_delivery_outbox", "identity_delivery_outbox_away");
try
{
var groupId = await _w.RaiseAsync();
long audited = 0;
var deadline = DateTime.UtcNow.AddSeconds(10);
while (audited == 0 && DateTime.UtcNow < deadline)
{
audited = await _fx.UseRedbAsync(redb => redb.Context.ExecuteScalarAsync(
"SELECT COUNT(*) FROM identity_audit_log WHERE event_type = @p0 AND details LIKE @p1",
WebhookTestSupport.EventType, $"%{groupId}%"));
if (audited == 0) await Task.Delay(50);
}
audited.Should().Be(1, "the local trail comes first");
deadline = DateTime.UtcNow.AddSeconds(5);
while (DateTime.UtcNow < deadline)
{
lock (failures) if (failures.Contains(WebhookTestSupport.EventType)) break;
await Task.Delay(50);
}
lock (failures) failures.Should().Contain(WebhookTestSupport.EventType);
}
finally
{
await RenameOutboxAsync("identity_delivery_outbox_away", "identity_delivery_outbox");
await _w.UnsubscribeAsync(sub);
}
}
private Task RenameOutboxAsync(string from, string to)
=> _fx.UseRedbAsync(redb => redb.Context.ExecuteAsync(
TestRedbSetup.SelectedProvider == TestRedbSetup.Provider.MsSql
? $"EXEC sp_rename 'dbo.{from}', '{to}'"
: $"ALTER TABLE {from} RENAME TO {to}"));
private sealed class ShiftedTime(TimeSpan shift) : TimeProvider
{
public override DateTimeOffset GetUtcNow() => base.GetUtcNow() + shift;
}
}