using System.Collections.Concurrent; using Flypaper.Core.Abstractions; using Flypaper.Core.Models; namespace Flypaper.Core.Runtime; public sealed class ActiveTrapRegistry(TimeProvider timeProvider) : IActiveTraps { private readonly ConcurrentDictionary _entries = new(); public IActiveTrapHandle Begin(TrapContext context, string strategy) { var entry = new Entry(this, context, strategy, timeProvider.GetUtcNow()); _entries[context.Session.Id] = entry; return entry; } public IReadOnlyList Snapshot() => _entries.Values.Select(entry => entry.ToActiveTrap()).OrderBy(trap => trap.StartedAt).ToList(); private sealed class Entry(ActiveTrapRegistry owner, TrapContext context, string strategy, DateTimeOffset startedAt) : IActiveTrapHandle { private Func? _bytesSent; public void Attach(Func bytesSent) => _bytesSent = bytesSent; public ActiveTrap ToActiveTrap() => new( context.Session.Id, context.Session.RemoteIp, context.Target, context.ClientInfo, strategy, startedAt, _bytesSent?.Invoke() ?? 0); public void Dispose() => owner._entries.TryRemove(context.Session.Id, out _); } }