(MaxBatchSize);
+ while (await sink.Reader.WaitToReadAsync(stoppingToken))
+ {
+ while (batch.Count < MaxBatchSize && sink.Reader.TryRead(out var trapEvent))
+ {
+ batch.Add(trapEvent);
+ }
+
+ try
+ {
+ await using var db = await dbContextFactory.CreateDbContextAsync(stoppingToken);
+ db.TrapEvents.AddRange(batch.Select(TrapEventEntity.From));
+ await db.SaveChangesAsync(stoppingToken);
+ }
+ catch (Exception ex) when (ex is not OperationCanceledException)
+ {
+ logger.LogError(ex, "Failed to persist {Count} trap events", batch.Count);
+ }
+
+ batch.Clear();
+ }
+ }
+}
diff --git a/src/Flypaper.Web/Components/App.razor b/src/Flypaper.Web/Components/App.razor
new file mode 100644
index 0000000..ce1943c
--- /dev/null
+++ b/src/Flypaper.Web/Components/App.razor
@@ -0,0 +1,20 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Flypaper.Web/Components/Layout/MainLayout.razor b/src/Flypaper.Web/Components/Layout/MainLayout.razor
new file mode 100644
index 0000000..e1a9a75
--- /dev/null
+++ b/src/Flypaper.Web/Components/Layout/MainLayout.razor
@@ -0,0 +1,3 @@
+@inherits LayoutComponentBase
+
+@Body
diff --git a/src/Flypaper.Web/Components/Layout/MainLayout.razor.css b/src/Flypaper.Web/Components/Layout/MainLayout.razor.css
new file mode 100644
index 0000000..60cec92
--- /dev/null
+++ b/src/Flypaper.Web/Components/Layout/MainLayout.razor.css
@@ -0,0 +1,20 @@
+#blazor-error-ui {
+ color-scheme: light only;
+ background: lightyellow;
+ bottom: 0;
+ box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.2);
+ box-sizing: border-box;
+ display: none;
+ left: 0;
+ padding: 0.6rem 1.25rem 0.7rem 1.25rem;
+ position: fixed;
+ width: 100%;
+ z-index: 1000;
+}
+
+ #blazor-error-ui .dismiss {
+ cursor: pointer;
+ position: absolute;
+ right: 0.75rem;
+ top: 0.5rem;
+ }
diff --git a/src/Flypaper.Web/Components/Pages/Error.razor b/src/Flypaper.Web/Components/Pages/Error.razor
new file mode 100644
index 0000000..576cc2d
--- /dev/null
+++ b/src/Flypaper.Web/Components/Pages/Error.razor
@@ -0,0 +1,36 @@
+@page "/Error"
+@using System.Diagnostics
+
+Error
+
+Error.
+An error occurred while processing your request.
+
+@if (ShowRequestId)
+{
+
+ Request ID: @RequestId
+
+}
+
+Development Mode
+
+ Swapping to Development environment will display more detailed information about the error that occurred.
+
+
+ The Development environment shouldn't be enabled for deployed applications.
+ It can result in displaying sensitive information from exceptions to end users.
+ For local debugging, enable the Development environment by setting the ASPNETCORE_ENVIRONMENT environment variable to Development
+ and restarting the app.
+
+
+@code{
+ [CascadingParameter]
+ private HttpContext? HttpContext { get; set; }
+
+ private string? RequestId { get; set; }
+ private bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
+
+ protected override void OnInitialized() =>
+ RequestId = Activity.Current?.Id ?? HttpContext?.TraceIdentifier;
+}
diff --git a/src/Flypaper.Web/Components/Pages/Home.razor b/src/Flypaper.Web/Components/Pages/Home.razor
new file mode 100644
index 0000000..2bbee2a
--- /dev/null
+++ b/src/Flypaper.Web/Components/Pages/Home.razor
@@ -0,0 +1,7 @@
+@page "/"
+
+Flypaper
+
+Flypaper
+
+Dashboard folgt.
diff --git a/src/Flypaper.Web/Components/Pages/NotFound.razor b/src/Flypaper.Web/Components/Pages/NotFound.razor
new file mode 100644
index 0000000..917ada1
--- /dev/null
+++ b/src/Flypaper.Web/Components/Pages/NotFound.razor
@@ -0,0 +1,5 @@
+@page "/not-found"
+@layout MainLayout
+
+Not Found
+Sorry, the content you are looking for does not exist.
\ No newline at end of file
diff --git a/src/Flypaper.Web/Components/Routes.razor b/src/Flypaper.Web/Components/Routes.razor
new file mode 100644
index 0000000..105855d
--- /dev/null
+++ b/src/Flypaper.Web/Components/Routes.razor
@@ -0,0 +1,6 @@
+
+
+
+
+
+
diff --git a/src/Flypaper.Web/Components/_Imports.razor b/src/Flypaper.Web/Components/_Imports.razor
new file mode 100644
index 0000000..3a3a828
--- /dev/null
+++ b/src/Flypaper.Web/Components/_Imports.razor
@@ -0,0 +1,11 @@
+@using System.Net.Http
+@using System.Net.Http.Json
+@using Microsoft.AspNetCore.Components.Forms
+@using Microsoft.AspNetCore.Components.Routing
+@using Microsoft.AspNetCore.Components.Web
+@using static Microsoft.AspNetCore.Components.Web.RenderMode
+@using Microsoft.AspNetCore.Components.Web.Virtualization
+@using Microsoft.JSInterop
+@using Flypaper.Web
+@using Flypaper.Web.Components
+@using Flypaper.Web.Components.Layout
diff --git a/src/Flypaper.Web/Flypaper.Web.csproj b/src/Flypaper.Web/Flypaper.Web.csproj
new file mode 100644
index 0000000..680b0db
--- /dev/null
+++ b/src/Flypaper.Web/Flypaper.Web.csproj
@@ -0,0 +1,12 @@
+
+
+
+ true
+
+
+
+
+
+
+
+
diff --git a/src/Flypaper.Web/Program.cs b/src/Flypaper.Web/Program.cs
new file mode 100644
index 0000000..c7c4189
--- /dev/null
+++ b/src/Flypaper.Web/Program.cs
@@ -0,0 +1,30 @@
+using Flypaper.Core;
+using Flypaper.Http;
+using Flypaper.Storage;
+using Flypaper.Web.Components;
+
+var builder = WebApplication.CreateBuilder(args);
+
+builder.WebHost.ConfigureKestrel(options => options.AddServerHeader = false);
+
+builder.Services.AddRazorComponents();
+builder.Services.AddFlypaperCore(builder.Configuration);
+builder.Services.AddFlypaperHttp(builder.Configuration);
+builder.Services.AddFlypaperStorage(builder.Configuration.GetConnectionString("Flypaper") ?? "Data Source=flypaper.db");
+
+var app = builder.Build();
+
+app.UseFlypaper();
+
+if (!app.Environment.IsDevelopment())
+{
+ app.UseExceptionHandler("/Error", createScopeForErrors: true);
+}
+app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true);
+
+app.UseAntiforgery();
+
+app.MapStaticAssets();
+app.MapRazorComponents();
+
+app.Run();
diff --git a/src/Flypaper.Web/Properties/launchSettings.json b/src/Flypaper.Web/Properties/launchSettings.json
new file mode 100644
index 0000000..6ddff38
--- /dev/null
+++ b/src/Flypaper.Web/Properties/launchSettings.json
@@ -0,0 +1,23 @@
+{
+ "$schema": "https://json.schemastore.org/launchsettings.json",
+ "profiles": {
+ "http": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": true,
+ "applicationUrl": "http://localhost:5248",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ },
+ "https": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": true,
+ "applicationUrl": "https://localhost:7142;http://localhost:5248",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ }
+ }
+ }
diff --git a/src/Flypaper.Web/appsettings.Development.json b/src/Flypaper.Web/appsettings.Development.json
new file mode 100644
index 0000000..5d3801e
--- /dev/null
+++ b/src/Flypaper.Web/appsettings.Development.json
@@ -0,0 +1,16 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning"
+ }
+ },
+ "Flypaper": {
+ "Drip": {
+ "Interval": "00:00:01"
+ },
+ "Http": {
+ "KnownHosts": [ "localhost" ]
+ }
+ }
+}
diff --git a/src/Flypaper.Web/appsettings.json b/src/Flypaper.Web/appsettings.json
new file mode 100644
index 0000000..2bb83b4
--- /dev/null
+++ b/src/Flypaper.Web/appsettings.json
@@ -0,0 +1,40 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning"
+ }
+ },
+ "AllowedHosts": "*",
+ "ConnectionStrings": {
+ "Flypaper": "Data Source=flypaper.db"
+ },
+ "Flypaper": {
+ "MaxConnections": 1000,
+ "MaxConnectionsPerIp": 10,
+ "MaxHoldDuration": "01:00:00",
+ "Drip": {
+ "Interval": "00:00:10"
+ },
+ "Http": {
+ "KnownHosts": [],
+ "TrustedProxies": [],
+ "TrapPaths": [
+ "/.env",
+ "/.env.*",
+ "/.git/*",
+ "/.aws/*",
+ "/.DS_Store",
+ "/wp-login.php",
+ "/wp-admin/*",
+ "/xmlrpc.php",
+ "/phpmyadmin/*",
+ "/vendor/phpunit/*",
+ "/server-status",
+ "/actuator/*",
+ "/cgi-bin/*",
+ "/boaform/*"
+ ]
+ }
+ }
+}
diff --git a/src/Flypaper.Web/wwwroot/app.css b/src/Flypaper.Web/wwwroot/app.css
new file mode 100644
index 0000000..5388357
--- /dev/null
+++ b/src/Flypaper.Web/wwwroot/app.css
@@ -0,0 +1,38 @@
+h1:focus {
+ outline: none;
+}
+
+.valid.modified:not([type=checkbox]) {
+ outline: 1px solid #26b050;
+}
+
+.invalid {
+ outline: 1px solid #e50000;
+}
+
+.validation-message {
+ color: #e50000;
+}
+
+.blazor-error-boundary {
+ background: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTYiIGhlaWdodD0iNDkiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIG92ZXJmbG93PSJoaWRkZW4iPjxkZWZzPjxjbGlwUGF0aCBpZD0iY2xpcDAiPjxyZWN0IHg9IjIzNSIgeT0iNTEiIHdpZHRoPSI1NiIgaGVpZ2h0PSI0OSIvPjwvY2xpcFBhdGg+PC9kZWZzPjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMCkiIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0yMzUgLTUxKSI+PHBhdGggZD0iTTI2My41MDYgNTFDMjY0LjcxNyA1MSAyNjUuODEzIDUxLjQ4MzcgMjY2LjYwNiA1Mi4yNjU4TDI2Ny4wNTIgNTIuNzk4NyAyNjcuNTM5IDUzLjYyODMgMjkwLjE4NSA5Mi4xODMxIDI5MC41NDUgOTIuNzk1IDI5MC42NTYgOTIuOTk2QzI5MC44NzcgOTMuNTEzIDI5MSA5NC4wODE1IDI5MSA5NC42NzgyIDI5MSA5Ny4wNjUxIDI4OS4wMzggOTkgMjg2LjYxNyA5OUwyNDAuMzgzIDk5QzIzNy45NjMgOTkgMjM2IDk3LjA2NTEgMjM2IDk0LjY3ODIgMjM2IDk0LjM3OTkgMjM2LjAzMSA5NC4wODg2IDIzNi4wODkgOTMuODA3MkwyMzYuMzM4IDkzLjAxNjIgMjM2Ljg1OCA5Mi4xMzE0IDI1OS40NzMgNTMuNjI5NCAyNTkuOTYxIDUyLjc5ODUgMjYwLjQwNyA1Mi4yNjU4QzI2MS4yIDUxLjQ4MzcgMjYyLjI5NiA1MSAyNjMuNTA2IDUxWk0yNjMuNTg2IDY2LjAxODNDMjYwLjczNyA2Ni4wMTgzIDI1OS4zMTMgNjcuMTI0NSAyNTkuMzEzIDY5LjMzNyAyNTkuMzEzIDY5LjYxMDIgMjU5LjMzMiA2OS44NjA4IDI1OS4zNzEgNzAuMDg4N0wyNjEuNzk1IDg0LjAxNjEgMjY1LjM4IDg0LjAxNjEgMjY3LjgyMSA2OS43NDc1QzI2Ny44NiA2OS43MzA5IDI2Ny44NzkgNjkuNTg3NyAyNjcuODc5IDY5LjMxNzkgMjY3Ljg3OSA2Ny4xMTgyIDI2Ni40NDggNjYuMDE4MyAyNjMuNTg2IDY2LjAxODNaTTI2My41NzYgODYuMDU0N0MyNjEuMDQ5IDg2LjA1NDcgMjU5Ljc4NiA4Ny4zMDA1IDI1OS43ODYgODkuNzkyMSAyNTkuNzg2IDkyLjI4MzcgMjYxLjA0OSA5My41Mjk1IDI2My41NzYgOTMuNTI5NSAyNjYuMTE2IDkzLjUyOTUgMjY3LjM4NyA5Mi4yODM3IDI2Ny4zODcgODkuNzkyMSAyNjcuMzg3IDg3LjMwMDUgMjY2LjExNiA4Ni4wNTQ3IDI2My41NzYgODYuMDU0N1oiIGZpbGw9IiNGRkU1MDAiIGZpbGwtcnVsZT0iZXZlbm9kZCIvPjwvZz48L3N2Zz4=) no-repeat 1rem/1.8rem, #b32121;
+ padding: 1rem 1rem 1rem 3.7rem;
+ color: white;
+}
+
+ .blazor-error-boundary::after {
+ content: "An error has occurred."
+ }
+
+.darker-border-checkbox.form-check-input {
+ border-color: #929292;
+}
+
+.form-floating > .form-control-plaintext::placeholder, .form-floating > .form-control::placeholder {
+ color: var(--bs-secondary-color);
+ text-align: end;
+}
+
+.form-floating > .form-control-plaintext:focus::placeholder, .form-floating > .form-control:focus::placeholder {
+ text-align: start;
+}
\ No newline at end of file
diff --git a/test/Flypaper.Tests/ConnectionGovernorTests.cs b/test/Flypaper.Tests/ConnectionGovernorTests.cs
new file mode 100644
index 0000000..8a035d3
--- /dev/null
+++ b/test/Flypaper.Tests/ConnectionGovernorTests.cs
@@ -0,0 +1,76 @@
+using System.Net;
+using Flypaper.Core;
+using Microsoft.Extensions.Options;
+using Shouldly;
+
+namespace Flypaper.Tests;
+
+public sealed class ConnectionGovernorTests
+{
+ private static readonly IPAddress IpA = IPAddress.Parse("203.0.113.1");
+ private static readonly IPAddress IpB = IPAddress.Parse("203.0.113.2");
+
+ [Fact]
+ public void Rejects_when_per_ip_limit_reached()
+ {
+ var governor = CreateGovernor(maxConnections: 10, maxPerIp: 2);
+
+ governor.TryAcquire(Session(IpA), out _).ShouldBeTrue();
+ governor.TryAcquire(Session(IpA), out _).ShouldBeTrue();
+ governor.TryAcquire(Session(IpA), out var lease).ShouldBeFalse();
+ lease.ShouldBeNull();
+
+ governor.TryAcquire(Session(IpB), out _).ShouldBeTrue();
+ }
+
+ [Fact]
+ public void Rejects_when_total_limit_reached()
+ {
+ var governor = CreateGovernor(maxConnections: 2, maxPerIp: 10);
+
+ governor.TryAcquire(Session(IpA), out _).ShouldBeTrue();
+ governor.TryAcquire(Session(IpB), out _).ShouldBeTrue();
+ governor.TryAcquire(Session(IPAddress.Parse("203.0.113.3")), out _).ShouldBeFalse();
+ }
+
+ [Fact]
+ public void Disposing_lease_frees_slot()
+ {
+ var governor = CreateGovernor(maxConnections: 1, maxPerIp: 1);
+
+ governor.TryAcquire(Session(IpA), out var lease).ShouldBeTrue();
+ governor.TryAcquire(Session(IpA), out _).ShouldBeFalse();
+
+ lease.Dispose();
+
+ governor.ActiveConnections.ShouldBe(0);
+ governor.TryAcquire(Session(IpA), out _).ShouldBeTrue();
+ }
+
+ [Fact]
+ public void Disposing_lease_twice_releases_once()
+ {
+ var governor = CreateGovernor(maxConnections: 10, maxPerIp: 10);
+ governor.TryAcquire(Session(IpA), out var first).ShouldBeTrue();
+ governor.TryAcquire(Session(IpA), out _).ShouldBeTrue();
+
+ first.Dispose();
+ first.Dispose();
+
+ governor.ActiveConnections.ShouldBe(1);
+ }
+
+ [Fact]
+ public void Treats_ipv4_mapped_ipv6_as_same_ip()
+ {
+ var governor = CreateGovernor(maxConnections: 10, maxPerIp: 1);
+
+ governor.TryAcquire(Session(IpA), out _).ShouldBeTrue();
+ governor.TryAcquire(Session(IpA.MapToIPv6()), out _).ShouldBeFalse();
+ }
+
+ private static ConnectionGovernor CreateGovernor(int maxConnections, int maxPerIp) =>
+ new(Options.Create(new FlypaperOptions { MaxConnections = maxConnections, MaxConnectionsPerIp = maxPerIp }));
+
+ private static TrapSession Session(IPAddress ip) => new(Guid.NewGuid(), TrapProtocol.Http, ip, DateTimeOffset.UtcNow);
+}
diff --git a/test/Flypaper.Tests/DripStrategyTests.cs b/test/Flypaper.Tests/DripStrategyTests.cs
new file mode 100644
index 0000000..ffa4209
--- /dev/null
+++ b/test/Flypaper.Tests/DripStrategyTests.cs
@@ -0,0 +1,43 @@
+using Flypaper.Core;
+using Flypaper.Core.Strategies;
+using Microsoft.Extensions.Options;
+using Shouldly;
+
+namespace Flypaper.Tests;
+
+public sealed class DripStrategyTests
+{
+ [Fact]
+ public async Task Drips_single_bytes_until_cancelled()
+ {
+ var strategy = CreateStrategy(TimeSpan.FromMilliseconds(20));
+ var channel = new FakeTrapChannel();
+ using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(300));
+
+ await Should.ThrowAsync(() => strategy.RunAsync(channel, cts.Token));
+
+ channel.Writes.Count.ShouldBeInRange(3, 20);
+ channel.Writes.ShouldAllBe(write => write.Length == 1);
+ }
+
+ [Fact]
+ public async Task Writes_first_byte_immediately()
+ {
+ var strategy = CreateStrategy(TimeSpan.FromMinutes(1));
+ var channel = new FakeTrapChannel();
+ using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(100));
+
+ await Should.ThrowAsync(() => strategy.RunAsync(channel, cts.Token));
+
+ channel.Writes.Count.ShouldBe(1);
+ }
+
+ [Theory]
+ [InlineData(TrapProtocol.Http, true)]
+ [InlineData(TrapProtocol.Ssh, false)]
+ public void Supports_only_http(TrapProtocol protocol, bool expected) =>
+ CreateStrategy(TimeSpan.FromSeconds(1)).Supports(protocol).ShouldBe(expected);
+
+ private static DripStrategy CreateStrategy(TimeSpan interval) =>
+ new(Options.Create(new DripOptions { Interval = interval }), TimeProvider.System);
+}
diff --git a/test/Flypaper.Tests/FakeTrapChannel.cs b/test/Flypaper.Tests/FakeTrapChannel.cs
new file mode 100644
index 0000000..7d50060
--- /dev/null
+++ b/test/Flypaper.Tests/FakeTrapChannel.cs
@@ -0,0 +1,19 @@
+using System.Collections.Concurrent;
+using System.Net;
+using Flypaper.Core;
+
+namespace Flypaper.Tests;
+
+internal sealed class FakeTrapChannel : ITrapChannel
+{
+ public TrapSession Session { get; } = new(Guid.NewGuid(), TrapProtocol.Http, IPAddress.Loopback, DateTimeOffset.UtcNow);
+
+ public ConcurrentQueue Writes { get; } = new();
+
+ public ValueTask WriteAsync(ReadOnlyMemory data, CancellationToken ct)
+ {
+ ct.ThrowIfCancellationRequested();
+ Writes.Enqueue(data.ToArray());
+ return ValueTask.CompletedTask;
+ }
+}
diff --git a/test/Flypaper.Tests/Flypaper.Tests.csproj b/test/Flypaper.Tests/Flypaper.Tests.csproj
new file mode 100644
index 0000000..06e2909
--- /dev/null
+++ b/test/Flypaper.Tests/Flypaper.Tests.csproj
@@ -0,0 +1,25 @@
+
+
+
+ false
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/test/Flypaper.Tests/TrapMatcherTests.cs b/test/Flypaper.Tests/TrapMatcherTests.cs
new file mode 100644
index 0000000..bb873d1
--- /dev/null
+++ b/test/Flypaper.Tests/TrapMatcherTests.cs
@@ -0,0 +1,41 @@
+using Flypaper.Http;
+using Microsoft.Extensions.Options;
+using Shouldly;
+
+namespace Flypaper.Tests;
+
+public sealed class TrapMatcherTests
+{
+ private readonly TrapMatcher _matcher = new(Options.Create(new HttpTrapOptions
+ {
+ KnownHosts = ["example.com", "*.example.org"],
+ TrapPaths = ["/.env", "/.git/*", "/wp-login.php"]
+ }));
+
+ [Theory]
+ [InlineData("example.com", "/")]
+ [InlineData("EXAMPLE.com", "/index.html")]
+ [InlineData("app.example.org", "/api/items")]
+ [InlineData("example.com", "/.envelope")]
+ [InlineData("example.com", "/.git")]
+ public void Lets_normal_requests_pass(string host, string path) =>
+ _matcher.Match(host, path).ShouldBe(TrapMatch.None);
+
+ [Theory]
+ [InlineData("example.com", "/.env")]
+ [InlineData("example.com", "/.ENV")]
+ [InlineData("example.com", "/.env/")]
+ [InlineData("example.com", "/.git/config")]
+ [InlineData("app.example.org", "/wp-login.php")]
+ public void Traps_configured_paths(string host, string path) =>
+ _matcher.Match(host, path).ShouldBe(TrapMatch.TrapPath);
+
+ [Theory]
+ [InlineData("unknown.net", "/")]
+ [InlineData("203.0.113.7", "/")]
+ [InlineData("example.org", "/")]
+ [InlineData("", "/")]
+ [InlineData(null, "/")]
+ public void Traps_unknown_hosts(string? host, string path) =>
+ _matcher.Match(host, path).ShouldBe(TrapMatch.UnknownHost);
+}
diff --git a/test/Flypaper.Tests/TrapRunnerTests.cs b/test/Flypaper.Tests/TrapRunnerTests.cs
new file mode 100644
index 0000000..97230e1
--- /dev/null
+++ b/test/Flypaper.Tests/TrapRunnerTests.cs
@@ -0,0 +1,88 @@
+using System.Net;
+using Flypaper.Core;
+using Flypaper.Core.Strategies;
+using Microsoft.Extensions.Options;
+using NSubstitute;
+using Shouldly;
+
+namespace Flypaper.Tests;
+
+public sealed class TrapRunnerTests
+{
+ private readonly IConnectionGovernor _governor = Substitute.For();
+ private readonly ITrapEventSink _sink = Substitute.For();
+ private readonly FakeTrapChannel _channel = new();
+
+ [Fact]
+ public async Task Rejects_without_opening_channel_when_governor_is_full()
+ {
+ _governor.TryAcquire(Arg.Any(), out Arg.Any()).Returns(false);
+ var opened = false;
+
+ var outcome = await CreateRunner(TimeSpan.FromSeconds(1)).RunAsync(
+ Context(),
+ _ =>
+ {
+ opened = true;
+ return ValueTask.FromResult(_channel);
+ },
+ CancellationToken.None);
+
+ outcome.ShouldBe(TrapOutcome.Rejected);
+ opened.ShouldBeFalse();
+ _sink.Received(1).Publish(Arg.Is(e => e.Outcome == TrapOutcome.Rejected && e.BytesSent == 0));
+ }
+
+ [Fact]
+ public async Task Times_out_after_max_hold_duration_and_releases_lease()
+ {
+ var lease = AllowAcquire();
+
+ var outcome = await CreateRunner(TimeSpan.FromMilliseconds(200)).RunAsync(Context(), Open, CancellationToken.None);
+
+ outcome.ShouldBe(TrapOutcome.Timeout);
+ lease.Received(1).Dispose();
+ _sink.Received(1).Publish(Arg.Is(e =>
+ e.Outcome == TrapOutcome.Timeout && e.BytesSent == _channel.Writes.Count && e.BytesSent > 0));
+ }
+
+ [Fact]
+ public async Task Reports_client_abort_when_caller_cancels()
+ {
+ AllowAcquire();
+ using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(100));
+
+ var outcome = await CreateRunner(TimeSpan.FromMinutes(1)).RunAsync(Context(), Open, cts.Token);
+
+ outcome.ShouldBe(TrapOutcome.ClientAborted);
+ _sink.Received(1).Publish(Arg.Is(e => e.Outcome == TrapOutcome.ClientAborted && e.Strategy == "drip"));
+ }
+
+ private IDisposable AllowAcquire()
+ {
+ var lease = Substitute.For();
+ _governor.TryAcquire(Arg.Any(), out Arg.Any())
+ .Returns(call =>
+ {
+ call[1] = lease;
+ return true;
+ });
+ return lease;
+ }
+
+ private ValueTask Open(CancellationToken ct) => ValueTask.FromResult(_channel);
+
+ private TrapRunner CreateRunner(TimeSpan maxHoldDuration)
+ {
+ var drip = new DripStrategy(Options.Create(new DripOptions { Interval = TimeSpan.FromMilliseconds(20) }), TimeProvider.System);
+ return new TrapRunner(
+ _governor,
+ [drip],
+ _sink,
+ Options.Create(new FlypaperOptions { MaxHoldDuration = maxHoldDuration }),
+ TimeProvider.System);
+ }
+
+ private static TrapContext Context() =>
+ new(new TrapSession(Guid.NewGuid(), TrapProtocol.Http, IPAddress.Parse("203.0.113.9"), DateTimeOffset.UtcNow), "GET /.env");
+}