Files
Flypaper/src/Flypaper.Storage/Dashboard/DashboardQueries.cs
T

143 lines
5.8 KiB
C#

using Flypaper.Core.Models;
using Flypaper.Storage.Entities;
using Microsoft.EntityFrameworkCore;
namespace Flypaper.Storage.Dashboard;
public sealed class DashboardQueries(IDbContextFactory<FlypaperDbContext> dbContextFactory, TimeProvider timeProvider)
{
private const int TopCount = 10;
public async Task<DashboardData> GetAsync(CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
var events = db.TrapEvents.AsNoTracking();
var catches = events.Where(e => e.Outcome != TrapOutcome.Rejected);
var since = timeProvider.GetUtcNow().UtcDateTime.AddHours(-24);
var countries = await catches
.Where(e => e.CountryCode != null)
.GroupBy(e => e.CountryCode!)
.Select(g => new { g.Key, Count = g.Count(), DurationMs = g.Sum(e => e.DurationMs), Name = g.Max(e => e.Country) })
.OrderByDescending(x => x.Count)
.ThenByDescending(x => x.DurationMs)
.ToListAsync(ct);
var providers = await catches
.Where(e => e.Asn != null)
.GroupBy(e => e.Asn!.Value)
.Select(g => new { g.Key, Count = g.Count(), DurationMs = g.Sum(e => e.DurationMs), Name = g.Max(e => e.Provider) })
.OrderByDescending(x => x.Count)
.ThenByDescending(x => x.DurationMs)
.Take(TopCount)
.ToListAsync(ct);
return new DashboardData(
await catches.CountAsync(ct),
await catches.CountAsync(e => e.StartedAt >= since, ct),
await events.CountAsync(e => e.Outcome == TrapOutcome.Rejected, ct),
await events.CountAsync(e => e.Outcome == TrapOutcome.Rejected && e.StartedAt >= since, ct),
await events.Select(e => e.RemoteIp).Distinct().CountAsync(ct),
await events.Where(e => e.StartedAt >= since).Select(e => e.RemoteIp).Distinct().CountAsync(ct),
TimeSpan.FromMilliseconds(await catches.SumAsync(e => e.DurationMs, ct)),
await TopAsync(catches.GroupBy(e => e.RemoteIp), ct),
await TopAsync(catches.Where(e => e.Target != null).GroupBy(e => e.Target!), ct),
await TopAsync(catches.GroupBy(e => e.Strategy), ct),
countries
.Take(TopCount)
.Select(x => new TopEntry(x.Key, x.Count, TimeSpan.FromMilliseconds(x.DurationMs), x.Name))
.ToList(),
providers
.Select(x => new TopEntry($"AS{x.Key}", x.Count, TimeSpan.FromMilliseconds(x.DurationMs), x.Name))
.ToList(),
countries.ToDictionary(x => x.Key, x => x.Count, StringComparer.OrdinalIgnoreCase));
}
public async Task<RecentCatches> GetRecentAsync(RecentFilter filter, CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
var events = Apply(db.TrapEvents.AsNoTracking(), filter);
var countries = await db.TrapEvents
.Where(e => e.CountryCode != null)
.GroupBy(e => e.CountryCode!)
.Select(g => new CountryOption(g.Key, g.Max(e => e.Country)))
.ToListAsync(ct);
return new RecentCatches(
await events.OrderByDescending(e => e.StartedAt).ThenByDescending(e => e.Id)
.Take(Math.Clamp(filter.Limit, 1, RecentFilter.MaxLimit))
.ToListAsync(ct),
await events.CountAsync(ct),
countries);
}
private IQueryable<TrapEventEntity> Apply(IQueryable<TrapEventEntity> events, RecentFilter filter)
{
if (filter.Window is { } window)
{
var since = timeProvider.GetUtcNow().UtcDateTime - window;
events = events.Where(e => e.StartedAt >= since);
}
if (filter.Outcome is { } outcome)
{
events = events.Where(e => e.Outcome == outcome);
}
if (filter.CountryCode is { } country)
{
events = events.Where(e => e.CountryCode == country);
}
if (filter.Asn is { } asn)
{
events = events.Where(e => e.Asn == asn);
}
if (filter.Ip is { } ip)
{
events = events.Where(e => e.RemoteIp == ip);
}
if (filter.Target is { } target)
{
events = events.Where(e => e.Target == target);
}
if (filter.Strategy is { } strategy)
{
events = events.Where(e => e.Strategy == strategy);
}
if (!string.IsNullOrWhiteSpace(filter.Search))
{
var pattern = $"%{filter.Search.Trim().Replace("\\", "\\\\").Replace("%", "\\%").Replace("_", "\\_")}%";
var strategyNames = filter.SearchStrategies ?? [];
events = events.Where(e =>
EF.Functions.Like(e.RemoteIp, pattern, "\\")
|| strategyNames.Any(name => e.Strategy == name || EF.Functions.Like(e.Strategy, name + " %", "\\"))
|| EF.Functions.Like(e.Provider!, pattern, "\\")
|| EF.Functions.Like(e.Target!, pattern, "\\")
|| EF.Functions.Like(e.Strategy, pattern, "\\")
|| EF.Functions.Like(e.ClientInfo!, pattern, "\\"));
}
return events;
}
private static async Task<IReadOnlyList<TopEntry>> TopAsync(
IQueryable<IGrouping<string, TrapEventEntity>> groups,
CancellationToken ct)
{
var rows = await groups
.Select(g => new { g.Key, Count = g.Count(), DurationMs = g.Sum(e => e.DurationMs) })
.OrderByDescending(x => x.Count)
.ThenByDescending(x => x.DurationMs)
.Take(TopCount)
.ToListAsync(ct);
return rows.Select(x => new TopEntry(x.Key, x.Count, TimeSpan.FromMilliseconds(x.DurationMs))).ToList();
}
}