Path: redb-identity/tests/redb.Identity.Tests/Webhooks/OutboxOperationsTests.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/OutboxOperationsTests.cs
----
using System.Net;
using System.Net.Http.Headers;
using System.Text.Json;
using AwesomeAssertions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using redb.Core;
using redb.Core.Query;
using redb.Identity.Contracts.Events;
using redb.Identity.Contracts.Routes;
using redb.Identity.Core.Configuration;
using redb.Identity.Core.Events;
using redb.Identity.Core.Health;
using redb.Identity.Core.Routes;
using redb.Identity.Core.Routes.Processors;
using redb.Identity.Tests.Infrastructure;
using Xunit;
namespace redb.Identity.Tests.Webhooks;
///
/// Running the outbox: the cleanup deletes finished rows past their retention and never a pending one;
/// the management API lists deliveries and sends a failed one again; the backlog drives the health rule;
/// the event wire taps run on their own bounded pool.
///
[Collection("ProductionHttp")]
public sealed class OutboxOperationsTests
{
private readonly ProductionHttpFixture _fx;
public OutboxOperationsTests(ProductionHttpFixture fx) => _fx = fx;
[Fact]
public async Task Cleanup_DeletesFinishedRowsPastTheirRetention_AndNeverAPendingOne()
{
var marker = "cleanup-" + Guid.NewGuid().ToString("N")[..10];
var pending = await InsertAsync(marker + "-pending", null);
var delivered = await InsertAsync(marker + "-delivered", "delivered");
var failed = await InsertAsync(marker + "-failed", "failed");
var cancelled = await InsertAsync(marker + "-cancelled", "cancelled");
// Retention longer than the rows' age: nothing goes.
await CleanupAllAsync(TimeSpan.FromHours(1), TimeSpan.FromHours(1));
(await StatusesAsync(marker)).Should().HaveCount(4);
// Delivered rows expire first: the failed and cancelled ones are kept for their longer retention.
await Task.Delay(1100);
await CleanupAllAsync(TimeSpan.Zero, TimeSpan.FromHours(1));
(await StatusesAsync(marker)).Keys.Should().BeEquivalentTo([pending, failed, cancelled]);
// Past every retention: only the pending row is left, though it is the oldest of them.
await CleanupAllAsync(TimeSpan.Zero, TimeSpan.Zero);
var left = await StatusesAsync(marker);
left.Keys.Should().Equal(pending);
left[pending].Should().Be("pending");
delivered.Should().NotBe(pending);
}
[Fact]
public async Task AFailedDelivery_IsListed_AndSentAgainThroughTheManagementApi()
{
await _fx.DeliverOutboxAsync();
var marker = "redeliver-" + Guid.NewGuid().ToString("N")[..10];
var id = await InsertAsync(marker, "failed");
using (var list = await SendAsync(HttpMethod.Get, "/api/v1/identity/webhooks/deliveries?kind=audit&status=failed&count=200"))
{
var body = await list.Content.ReadAsStringAsync();
list.StatusCode.Should().Be(HttpStatusCode.OK, body);
var items = JsonDocument.Parse(body).RootElement.GetProperty("items").EnumerateArray().ToList();
items.Should().Contain(i => i.GetProperty("id").GetInt64() == id);
var item = items.Single(i => i.GetProperty("id").GetInt64() == id);
item.GetProperty("destination").GetString().Should().Be("test-capture");
item.TryGetProperty("payload", out _).Should().BeFalse("the list does not carry the event");
}
using (var again = await SendAsync(HttpMethod.Post, $"/api/v1/identity/webhooks/deliveries/{id}/redeliver"))
again.StatusCode.Should().Be(HttpStatusCode.OK, await again.Content.ReadAsStringAsync());
(await StatusesAsync(marker))[id].Should().Be("pending");
(await WaitForRedeliveredEventsAsync(id, 1)).Should().Be(1, "the operator's act is audited");
await _fx.DeliverOutboxAsync();
(await StatusesAsync(marker))[id].Should().Be("delivered");
_fx.AuditTargetMessages.Should().Contain(m => m.Body.Contains(marker));
// Delivered now: not sent again. An unknown id: not found. Neither refusal is audited.
using (var twice = await SendAsync(HttpMethod.Post, $"/api/v1/identity/webhooks/deliveries/{id}/redeliver"))
twice.StatusCode.Should().Be(HttpStatusCode.Conflict);
using (var unknown = await SendAsync(HttpMethod.Post, "/api/v1/identity/webhooks/deliveries/987654321012/redeliver"))
unknown.StatusCode.Should().Be(HttpStatusCode.NotFound);
(await WaitForRedeliveredEventsAsync(id, 2, TimeSpan.FromMilliseconds(500))).Should().Be(1);
(await WaitForRedeliveredEventsAsync(987654321012, 1, TimeSpan.FromMilliseconds(100))).Should().Be(0);
}
///
/// The audit rows of for one outbox row; the
/// event goes through a wire tap, so this waits until are there or the time is up.
///
private async Task WaitForRedeliveredEventsAsync(long outboxId, int atLeast, TimeSpan? within = null)
{
var deadline = DateTime.UtcNow + (within ?? TimeSpan.FromSeconds(10));
while (true)
{
var count = await _fx.UseRedbAsync(redb => redb.Context.ExecuteScalarAsync(
"SELECT COUNT(*) FROM identity_audit_log WHERE event_type = @p0 AND details LIKE @p1",
IdentityAuditEventIds.WebhookDeliveryRedelivered, $"%:{outboxId}}}%"));
if (count >= atLeast || DateTime.UtcNow > deadline) return count;
await Task.Delay(50);
}
}
[Fact]
public async Task TheBacklog_CountsPendingRows_AndTheHealthRuleDegradesPastTheLimit()
{
var marker = "backlog-" + Guid.NewGuid().ToString("N")[..10];
await InsertAsync(marker, null);
var backlog = new DeliveryBacklog(_fx.ServiceProvider.GetRequiredService(), TimeProvider.System,
NullLogger.Instance);
var stats = await backlog.GetAsync(CancellationToken.None);
stats.Should().NotBeNull();
stats!.Pending.Should().BeGreaterThan(0);
stats.OldestSeconds.Should().BeGreaterThanOrEqualTo(0);
IdentityHealthContributor.BacklogWithin(stats, TimeSpan.FromDays(3650)).Should().BeTrue();
IdentityHealthContributor.BacklogWithin(new OutboxStats { Pending = 3, OldestSeconds = 301 }, TimeSpan.FromMinutes(5))
.Should().BeFalse("the oldest pending row is past the limit");
IdentityHealthContributor.BacklogWithin(new OutboxStats { Pending = 0, OldestSeconds = 0 }, TimeSpan.Zero)
.Should().BeTrue("nothing waits");
IdentityHealthContributor.BacklogWithin(null, TimeSpan.Zero).Should().BeTrue("the database probe reports a table it cannot read");
await _fx.DeliverOutboxAsync(); // the row goes to the fixture's target
}
[Fact]
public void TheEventWireTaps_RunOnTheirOwnBoundedPool()
{
var profile = _fx.Context.GetThreadPoolProfile(IdentityCoreRouteBuilder.EventTapPool);
profile.MaxConcurrency.Should().Be(new IdentityAuditOptions().TapConcurrency);
}
///
/// Cleanup runs until one deletes nothing: the shared test database holds the finished rows of every
/// earlier test, and one run stops after a bounded number of batches.
///
private async Task CleanupAllAsync(TimeSpan delivered, TimeSpan failed)
{
var cleanup = new OutboxCleanupProcessor(_fx.ServiceProvider,
new DeliveryOptions { DeliveredRetention = delivered, FailedRetention = failed, CleanupBatchSize = 500 },
NullLogger.Instance);
for (var run = 0; run < 100 && await cleanup.RunAsync() > 0; run++) { }
}
/// An audit-target row of the fixture's target; finished rows get the status and finish at their creation.
private Task InsertAsync(string marker, string? finishedAs)
=> _fx.UseRedbAsync(async redb =>
{
var dialect = _fx.ServiceProvider.GetRequiredService();
var evt = new IdentityEvent { EventType = "GroupCreated", Details = new Dictionary { ["Marker"] = marker } };
await new IdentityEventStore(redb, dialect).InsertOutboxAsync(
[new OutboxEntry(Guid.NewGuid(), Guid.Parse(evt.EventId), AuditTargetEnqueueProcessor.Kind, "test-capture",
evt.EventType, AuditTargetMessage.Payload(evt))]);
var id = (await redb.Context.QueryAsync(
"SELECT id FROM identity_delivery_outbox WHERE payload LIKE @p0", "%" + marker + "%")).Single().Id;
if (finishedAs is not null)
await redb.Context.ExecuteAsync(
"UPDATE identity_delivery_outbox SET status = @p1, finished_at = created_at WHERE id = @p0", id, finishedAs);
return id;
});
private Task> StatusesAsync(string marker)
=> _fx.UseRedbAsync(async redb => (await redb.Context.QueryAsync(
"SELECT id, status FROM identity_delivery_outbox WHERE payload LIKE @p0 ORDER BY id", "%" + marker + "%"))
.ToDictionary(r => r.Id, r => r.Status));
private Task SendAsync(HttpMethod method, string path)
{
var request = new HttpRequestMessage(method, path);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken);
return _fx.Http.SendAsync(request);
}
private sealed class IdRow
{
[System.Text.Json.Serialization.JsonPropertyName("id")] public long Id { get; set; }
}
private sealed class StatusRow
{
[System.Text.Json.Serialization.JsonPropertyName("id")] public long Id { get; set; }
[System.Text.Json.Serialization.JsonPropertyName("status")] public string Status { get; set; } = "";
}
}