using System.Net; using Flypaper.Core; using Flypaper.Core.Abstractions; using Flypaper.Core.Models; using Flypaper.Core.Runtime; using Flypaper.Core.Strategies; using Flypaper.Tests.Fakes; using Microsoft.Extensions.Logging.Abstractions; using NSubstitute; using Shouldly; namespace Flypaper.Tests.Core; 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(TestOptions.Monitor(new DripOptions { Interval = TimeSpan.FromMilliseconds(20) }), TimeProvider.System); return new TrapRunner( _governor, [drip], _sink, TestOptions.Monitor(new FlypaperOptions { MaxHoldDuration = maxHoldDuration }), TimeProvider.System, NullLogger.Instance); } private static TrapContext Context() => new(new TrapSession(Guid.NewGuid(), TrapProtocol.Http, IPAddress.Parse("203.0.113.9"), DateTimeOffset.UtcNow), "GET /.env"); }