using System.Net;
using System.Net.Sockets;
using Microsoft.AspNetCore.Http;
namespace OpenWaf.Tests.Integration;
///
/// The application behind the edge. It is deliberately dumb: it answers a
/// configured status per path and counts what it was asked. The whole point of
/// the feature is the edge reacting to what the upstream answered, so the test
/// needs to control that answer and observe whether the edge noticed.
///
internal sealed class FakeUpstream : IAsyncDisposable
{
private readonly HttpListener _listener = new();
private readonly CancellationTokenSource _cts = new();
public string Address { get; }
public int RequestCount;
public List Paths = [];
/// What this upstream answers for a path.
public Func StatusFor { get; set; } = _ => StatusCodes.Status404NotFound;
public static FakeUpstream Start()
{
var port = FreePort();
var upstream = new FakeUpstream($"http://127.0.0.1:{port}/");
upstream._listener.Start();
_ = upstream.LoopAsync();
return upstream;
}
private FakeUpstream(string address)
{
Address = address;
_listener.Prefixes.Add(address);
}
private async Task LoopAsync()
{
try
{
while (!_cts.IsCancellationRequested)
{
var context = await _listener.GetContextAsync();
var path = context.Request.Url?.AbsolutePath ?? "/";
Interlocked.Increment(ref RequestCount);
lock (Paths) Paths.Add(path);
context.Response.StatusCode = StatusFor(path);
context.Response.OutputStream.Close();
}
}
catch
{
// Listener closed at teardown — the expected way out.
}
}
private static int FreePort()
{
var probe = new TcpListener(IPAddress.Loopback, 0);
probe.Start();
var port = ((IPEndPoint)probe.LocalEndpoint).Port;
probe.Stop();
return port;
}
public async ValueTask DisposeAsync()
{
_cts.Cancel();
_listener.Close();
await Task.CompletedTask;
}
}