Path: redb-identity/tests/redb.Identity.Tests/Webhooks/WebhookTestSupport.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/WebhookTestSupport.cs
----
using System.Net.Http.Headers;
using System.Net.Http.Json;
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.Core.Configuration;
using redb.Identity.Core.Events;
using redb.Identity.Core.Routes.Processors;
using redb.Identity.Tests.Infrastructure;
namespace redb.Identity.Tests.Webhooks;
/// What the webhook tests share: subscriptions over the API, an event to raise, the outbox.
internal sealed class WebhookTestSupport
{
private readonly ProductionHttpFixture _fx;
public WebhookTestSupport(ProductionHttpFixture fx) => _fx = fx;
/// The event the tests raise: creating a group emits it.
public const string EventType = "GroupCreated";
public WebhookDeliveryWorker Worker(DeliveryOptions? options = null, TimeProvider? time = null, string? node = null)
=> new(_fx.ServiceProvider, _fx.Context, options ?? new DeliveryOptions(), time ?? TimeProvider.System,
NullLogger.Instance, node, _fx.AuditTargets);
public async Task SubscribeAsync(string url, int timeoutMs = 2000, int maxAttempts = 3, int retryBackoffMs = 50,
string filter = EventType)
{
// Every event of every earlier test left an audit-target row, and due rows are read oldest first: a
// worker built by the test would work through that backlog before reaching its own rows. Cleared
// here, before the test has rows of its own.
await _fx.DeliverOutboxAsync();
using var response = await SendAsync(HttpMethod.Post, "/api/v1/identity/webhooks", new
{
url,
displayName = "test-" + Guid.NewGuid().ToString("N")[..8],
eventTypeFilter = filter,
timeoutMs,
maxAttempts,
retryBackoffMs,
});
var body = await response.Content.ReadAsStringAsync();
((int)response.StatusCode).Should().BeInRange(200, 299, body);
return long.Parse(JsonDocument.Parse(body).RootElement.GetProperty("id").ToString());
}
public async Task UnsubscribeAsync(long id)
{
using var _ = await SendAsync(HttpMethod.Delete, $"/api/v1/identity/webhooks/{id}", null);
}
public async Task DisableAsync(long id)
{
using var response = await SendAsync(HttpMethod.Put, $"/api/v1/identity/webhooks/{id}", new { enabled = false });
((int)response.StatusCode).Should().BeInRange(200, 299, await response.Content.ReadAsStringAsync());
}
/// Raises one event of ; returns the new group's id.
public async Task RaiseAsync()
{
using var response = await SendAsync(HttpMethod.Post, "/api/v1/identity/groups",
new { name = "webhook-event-" + Guid.NewGuid().ToString("N")[..12] });
var body = await response.Content.ReadAsStringAsync();
((int)response.StatusCode).Should().BeInRange(200, 299, body);
return JsonDocument.Parse(body).RootElement.GetProperty("id").ToString();
}
///
/// The events route runs on a wire tap, after the request answered: wait until the subscription has
/// outbox rows.
///
public async Task> WaitForRowsAsync(long subscriptionId, int count)
{
var deadline = DateTime.UtcNow.AddSeconds(10);
while (true)
{
var rows = await RowsAsync(subscriptionId);
if (rows.Count >= count || DateTime.UtcNow > deadline) return rows;
await Task.Delay(50);
}
}
public Task> RowsAsync(long subscriptionId)
=> _fx.UseRedbAsync(async redb =>
{
var rows = await redb.Context.QueryAsync(
"SELECT id, status, attempts, leased_by FROM identity_delivery_outbox WHERE kind = 'webhook' AND destination = @p0 ORDER BY id",
subscriptionId.ToString());
return rows.Select(r => (r.Id, r.Status, r.Attempts, r.LeasedBy)).ToList();
});
/// Runs worker passes until holds or the time is up.
public static async Task RunUntilAsync(WebhookDeliveryWorker worker, Func done, TimeSpan within)
{
var deadline = DateTime.UtcNow + within;
while (!done() && DateTime.UtcNow < deadline)
{
await worker.RunOnceAsync();
await Task.Delay(50);
}
}
private Task SendAsync(HttpMethod method, string path, object? body)
{
var request = new HttpRequestMessage(method, path);
if (body is not null) request.Content = JsonContent.Create(body);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken);
return _fx.Http.SendAsync(request);
}
private sealed class Row
{
[System.Text.Json.Serialization.JsonPropertyName("id")] public long Id { get; set; }
[System.Text.Json.Serialization.JsonPropertyName("status")] public string Status { get; set; } = "";
[System.Text.Json.Serialization.JsonPropertyName("attempts")] public int Attempts { get; set; }
[System.Text.Json.Serialization.JsonPropertyName("leased_by")] public string? LeasedBy { get; set; }
}
}