Path: redb-identity/tests/redb.Identity.Tests/Webhooks/TestWebhookReceiver.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/TestWebhookReceiver.cs
----
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace redb.Identity.Tests.Webhooks;
///
/// A bare HTTP endpoint for webhook tests: records every request (delivery headers and body) and
/// answers with the status the test chose, after the delay the test chose; a negative delay means it
/// never answers (a black hole).
///
internal sealed class TestWebhookReceiver : IAsyncDisposable
{
private readonly TcpListener _listener = new(IPAddress.Loopback, 0);
private readonly CancellationTokenSource _stop = new();
private readonly Stopwatch _clock = Stopwatch.StartNew();
private readonly Func _answer;
private int _count;
public sealed record Arrival(string DeliveryId, int Attempt, string EventType, string Body, TimeSpan At);
public ConcurrentQueue Arrivals { get; } = new();
public int Port { get; }
public string Url => $"http://127.0.0.1:{Port}/hook";
public TimeSpan Now => _clock.Elapsed;
/// For the n-th request (1-based): the status and the delay before answering.
public TestWebhookReceiver(Func answer)
{
_answer = answer;
_listener.Start();
Port = ((IPEndPoint)_listener.LocalEndpoint).Port;
_ = AcceptAsync();
}
public static TestWebhookReceiver Answering(int status) => new(_ => (status, TimeSpan.Zero));
private async Task AcceptAsync()
{
try
{
while (!_stop.IsCancellationRequested)
{
var client = await _listener.AcceptTcpClientAsync(_stop.Token);
_ = ServeAsync(client);
}
}
catch (Exception e) when (e is OperationCanceledException or ObjectDisposedException or SocketException) { }
}
private async Task ServeAsync(TcpClient client)
{
using (client)
{
try
{
var stream = client.GetStream();
var buffer = new byte[64 * 1024];
var read = 0;
string text;
int headEnd;
do
{
var n = await stream.ReadAsync(buffer.AsMemory(read), _stop.Token);
if (n == 0) return;
read += n;
text = Encoding.UTF8.GetString(buffer, 0, read);
headEnd = text.IndexOf("\r\n\r\n", StringComparison.Ordinal);
} while (headEnd < 0 && read < buffer.Length);
var head = text[..headEnd];
var length = int.TryParse(Header(head, "Content-Length"), out var l) ? l : 0;
while (Encoding.UTF8.GetByteCount(text) - (headEnd + 4) < length && read < buffer.Length)
{
var n = await stream.ReadAsync(buffer.AsMemory(read), _stop.Token);
if (n == 0) break;
read += n;
text = Encoding.UTF8.GetString(buffer, 0, read);
}
Arrivals.Enqueue(new Arrival(
Header(head, "X-RedbIdentity-Delivery") ?? "",
int.TryParse(Header(head, "X-RedbIdentity-Attempt"), out var attempt) ? attempt : 0,
Header(head, "X-RedbIdentity-EventType") ?? "",
text[(headEnd + 4)..],
_clock.Elapsed));
var (status, delay) = _answer(Interlocked.Increment(ref _count));
if (delay < TimeSpan.Zero)
{
await Task.Delay(Timeout.Infinite, _stop.Token);
return;
}
if (delay > TimeSpan.Zero) await Task.Delay(delay, _stop.Token);
var answer = Encoding.ASCII.GetBytes($"HTTP/1.1 {status} X\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
await stream.WriteAsync(answer, _stop.Token);
}
catch (Exception e) when (e is OperationCanceledException or IOException or SocketException) { }
}
}
private static string? Header(string head, string name)
{
foreach (var line in head.Split("\r\n"))
{
if (line.StartsWith(name + ":", StringComparison.OrdinalIgnoreCase))
return line[(name.Length + 1)..].Trim();
}
return null;
}
public ValueTask DisposeAsync()
{
_stop.Cancel();
_listener.Stop();
return ValueTask.CompletedTask;
}
}