using System.Globalization; using Flypaper.Core.Models; using Flypaper.Core.Strategies; using Flypaper.Storage.Entities; using Microsoft.EntityFrameworkCore; namespace Flypaper.Storage.Queries; public sealed class CatchQueries(IDbContextFactory dbContextFactory) { public const int MaxLimit = 500; public async Task GetStatsAsync(DateTime? since, CancellationToken ct = default) { await using var db = await dbContextFactory.CreateDbContextAsync(ct); var events = InPeriod(db, since); var catches = events.Where(e => e.Outcome != TrapOutcome.Rejected); var count = await catches.CountAsync(ct); var totalMs = count == 0 ? 0 : await catches.SumAsync(e => e.DurationMs, ct); var longest = await catches.OrderByDescending(e => e.DurationMs).ThenByDescending(e => e.Id).FirstOrDefaultAsync(ct); return new CatchStats( count, await events.CountAsync(e => e.Outcome == TrapOutcome.Rejected, ct), await events.Select(e => e.RemoteIp).Distinct().CountAsync(ct), totalMs / 1000d, count == 0 ? 0 : totalMs / 1000d / count, longest is null ? null : ToRecord(longest)); } public async Task> ListAsync(CatchFilter filter, CancellationToken ct = default) { await using var db = await dbContextFactory.CreateDbContextAsync(ct); var events = InPeriod(db, filter.Since); if (filter.Until is { } until) { events = events.Where(e => e.StartedAt < until); } if (!string.IsNullOrWhiteSpace(filter.Country)) { var country = filter.Country.Trim().ToUpperInvariant(); events = events.Where(e => e.CountryCode == country); } if (!string.IsNullOrWhiteSpace(filter.Provider)) { events = ByProvider(events, filter.Provider.Trim()); } if (!string.IsNullOrWhiteSpace(filter.Ip)) { var ip = filter.Ip.Trim(); events = events.Where(e => e.RemoteIp == ip); } if (!string.IsNullOrWhiteSpace(filter.TargetContains)) { var text = filter.TargetContains.Trim().ToLowerInvariant(); events = events.Where(e => e.Target != null && e.Target.ToLower().Contains(text)); } if (!string.IsNullOrWhiteSpace(filter.Marker)) { var marker = filter.Marker.Trim(); var prefix = $"{marker[..8]}-{marker[8..]}%"; events = events.Where(e => EF.Functions.Like(e.SessionId.ToString(), prefix)); } var rows = await events.OrderByDescending(e => e.StartedAt).ThenByDescending(e => e.Id).Take(Clamp(filter.Limit)).ToListAsync(ct); return rows.Select(ToRecord).ToList(); } public async Task> LongestAsync(DateTime? since, int limit, CancellationToken ct = default) { await using var db = await dbContextFactory.CreateDbContextAsync(ct); var rows = await InPeriod(db, since) .Where(e => e.Outcome != TrapOutcome.Rejected) .OrderByDescending(e => e.DurationMs) .ThenByDescending(e => e.Id) .Take(Clamp(limit)) .ToListAsync(ct); return rows.Select(ToRecord).ToList(); } public async Task> TopAsync(TopDimension dimension, DateTime? since, int limit, CancellationToken ct = default) { await using var db = await dbContextFactory.CreateDbContextAsync(ct); var catches = InPeriod(db, since).Where(e => e.Outcome != TrapOutcome.Rejected); var take = Clamp(limit); IQueryable rows = dimension switch { TopDimension.Ips => catches.GroupBy(e => e.RemoteIp) .Select(g => new TopRow { Key = g.Key, Label = g.Max(e => e.CountryCode), Count = g.Count(), DurationMs = g.Sum(e => e.DurationMs) }), TopDimension.Countries => catches.Where(e => e.CountryCode != null).GroupBy(e => e.CountryCode!) .Select(g => new TopRow { Key = g.Key, Label = g.Max(e => e.Country), Count = g.Count(), DurationMs = g.Sum(e => e.DurationMs) }), TopDimension.Providers => catches.Where(e => e.Asn != null).GroupBy(e => e.Asn!.Value) .Select(g => new TopRow { Key = "AS" + g.Key.ToString(), Label = g.Max(e => e.Provider), Count = g.Count(), DurationMs = g.Sum(e => e.DurationMs) }), TopDimension.Targets => catches.Where(e => e.Target != null).GroupBy(e => e.Target!) .Select(g => new TopRow { Key = g.Key, Count = g.Count(), DurationMs = g.Sum(e => e.DurationMs) }), TopDimension.Strategies => catches.GroupBy(e => e.Strategy) .Select(g => new TopRow { Key = g.Key, Count = g.Count(), DurationMs = g.Sum(e => e.DurationMs) }), TopDimension.UserAgents => catches.Where(e => e.ClientInfo != null).GroupBy(e => e.ClientInfo!) .Select(g => new TopRow { Key = g.Key, Count = g.Count(), DurationMs = g.Sum(e => e.DurationMs) }), _ => throw new ArgumentOutOfRangeException(nameof(dimension)) }; var top = await rows .OrderByDescending(x => x.Count) .ThenByDescending(x => x.DurationMs) .Take(take) .ToListAsync(ct); return top.Select(x => new TopItem(x.Key, x.Label, x.Count, x.DurationMs / 1000d)).ToList(); } public async Task<(bool Found, TrapRequestEntity? Request)> GetRequestAsync(long catchId, CancellationToken ct = default) { await using var db = await dbContextFactory.CreateDbContextAsync(ct); if (!await db.TrapEvents.AnyAsync(e => e.Id == catchId, ct)) { return (false, null); } return (true, await db.TrapRequests.AsNoTracking().FirstOrDefaultAsync(r => r.TrapEventId == catchId, ct)); } public async Task LookupIpAsync(string ip, CancellationToken ct = default) { await using var db = await dbContextFactory.CreateDbContextAsync(ct); var events = db.TrapEvents.AsNoTracking().Where(e => e.RemoteIp == ip); var total = await events.CountAsync(ct); if (total == 0) { return null; } var catches = events.Where(e => e.Outcome != TrapOutcome.Rejected); var origin = await events.Where(e => e.CountryCode != null || e.Asn != null).OrderByDescending(e => e.Id).FirstOrDefaultAsync(ct); var recent = await events.OrderByDescending(e => e.StartedAt).ThenByDescending(e => e.Id).Take(MaxLimit).ToListAsync(ct); return new IpProfile( ip, origin?.CountryCode, origin?.Country, origin?.City, origin?.Asn, origin?.Provider, await catches.CountAsync(ct), await events.CountAsync(e => e.Outcome == TrapOutcome.Rejected, ct), await catches.SumAsync(e => e.DurationMs, ct) / 1000d, await events.SumAsync(e => e.BytesSent, ct), await events.MinAsync(e => e.StartedAt, ct), await events.MaxAsync(e => e.EndedAt, ct), recent.Select(ToRecord).ToList(), Math.Max(0, total - recent.Count)); } private static IQueryable InPeriod(FlypaperDbContext db, DateTime? since) { var events = db.TrapEvents.AsNoTracking(); return since is { } start ? events.Where(e => e.StartedAt >= start) : events; } private static IQueryable ByProvider(IQueryable events, string provider) { var number = provider.StartsWith("AS", StringComparison.OrdinalIgnoreCase) ? provider[2..] : provider; if (long.TryParse(number, NumberStyles.None, CultureInfo.InvariantCulture, out var asn)) { return events.Where(e => e.Asn == asn); } var text = provider.ToLowerInvariant(); return events.Where(e => e.Provider != null && e.Provider.ToLower().Contains(text)); } private static int Clamp(int limit) => Math.Clamp(limit, 1, MaxLimit); private static CatchRecord ToRecord(TrapEventEntity e) => new( e.Id, e.StartedAt, e.EndedAt, e.DurationMs / 1000d, e.BytesSent, e.Outcome, e.Strategy, e.RemoteIp, e.CountryCode, e.Country, e.City, e.Asn, e.Provider, e.Target, e.ClientInfo, SignpostLinks.MarkerOf(e.SessionId)); private sealed class TopRow { public required string Key { get; init; } public string? Label { get; init; } public int Count { get; init; } public long DurationMs { get; init; } } }