using Microsoft.Extensions.Options; namespace Flypaper.Core; public sealed class TrapRunner( IConnectionGovernor governor, IEnumerable strategies, ITrapEventSink sink, IOptions options, TimeProvider timeProvider) { public async Task RunAsync( TrapContext context, Func> openChannel, CancellationToken ct) { var session = context.Session; var strategy = strategies.FirstOrDefault(s => s.Supports(session.Protocol)); if (strategy is null || !governor.TryAcquire(session, out var lease)) { Publish(context, strategy?.Name ?? "none", 0, TrapOutcome.Rejected); return TrapOutcome.Rejected; } using var _ = lease; using var hold = new CancellationTokenSource(options.Value.MaxHoldDuration, timeProvider); using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, hold.Token); CountingTrapChannel? channel = null; var outcome = TrapOutcome.Completed; try { channel = new CountingTrapChannel(await openChannel(linked.Token)); await strategy.RunAsync(channel, linked.Token); } catch (OperationCanceledException) when (linked.IsCancellationRequested) { outcome = hold.IsCancellationRequested && !ct.IsCancellationRequested ? TrapOutcome.Timeout : TrapOutcome.ClientAborted; } catch (IOException) { outcome = TrapOutcome.ClientAborted; } Publish(context, strategy.Name, channel?.BytesSent ?? 0, outcome); return outcome; } private void Publish(TrapContext context, string strategy, long bytesSent, TrapOutcome outcome) { var session = context.Session; sink.Publish(new TrapEvent( session.Id, session.Protocol, session.RemoteIp, strategy, session.StartedAt, timeProvider.GetUtcNow(), bytesSent, outcome, context.Target, context.ClientInfo)); } }