168 lines
7.1 KiB
C#
168 lines
7.1 KiB
C#
using Flypaper.Core.Models;
|
|
using Flypaper.Storage.Entities;
|
|
using Flypaper.Storage.Explanations;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace Flypaper.Storage.Dashboard;
|
|
|
|
public sealed class DashboardQueries(IDbContextFactory<FlypaperDbContext> dbContextFactory, TimeProvider timeProvider, ExplanationRuleStore explanations)
|
|
{
|
|
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 catches.Select(e => new StrategySample(e.Strategy, e.DurationMs)).ToListAsync(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);
|
|
|
|
var ordered = events.OrderByDescending(e => e.StartedAt).ThenByDescending(e => e.Id);
|
|
var take = Math.Clamp(filter.Limit, 1, RecentFilter.MaxLimit);
|
|
|
|
if (filter.Unexplained)
|
|
{
|
|
var rules = await explanations.GetRuleSetAsync(ct);
|
|
var candidates = await ordered.Where(e => e.Target != null).Select(e => new { e.Id, e.Target }).ToListAsync(ct);
|
|
var ids = candidates
|
|
.Where(c => rules.Winner(ExplanationKind.Target, ExplanationText.Path(c.Target)!) is null)
|
|
.Select(c => c.Id)
|
|
.ToList();
|
|
var page = ids.Take(take).ToList();
|
|
var items = (await db.TrapEvents.AsNoTracking().Where(e => page.Contains(e.Id)).ToListAsync(ct))
|
|
.OrderByDescending(e => e.StartedAt).ThenByDescending(e => e.Id).ToList();
|
|
return new RecentCatches(items, ids.Count, countries);
|
|
}
|
|
|
|
return new RecentCatches(await ordered.Take(take).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)
|
|
{
|
|
var bases = strategy.Bases;
|
|
events = events.Where(e => bases.Any(name => e.Strategy == name || EF.Functions.Like(e.Strategy, name + " %", "\\")));
|
|
foreach (var flag in strategy.With)
|
|
{
|
|
var pattern = $"% {flag} %";
|
|
events = events.Where(e => EF.Functions.Like(" " + e.Strategy + " ", pattern, "\\"));
|
|
}
|
|
|
|
foreach (var flag in strategy.Without)
|
|
{
|
|
var pattern = $"% {flag} %";
|
|
events = events.Where(e => !EF.Functions.Like(" " + e.Strategy + " ", pattern, "\\"));
|
|
}
|
|
}
|
|
|
|
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();
|
|
}
|
|
}
|