using Flypaper.Storage.Entities; using Microsoft.EntityFrameworkCore; namespace Flypaper.Storage.Explanations; public enum UnexplainedGrouping { Path, Pattern } public sealed record ObservedValue(string Value, int Catches, DateTime FirstSeen, DateTime LastSeen, string? ExampleTarget, string? ExampleUserAgent); public sealed record UnexplainedGroup(string Key, int Catches, IReadOnlyList ExamplePaths, string? ExampleUserAgent, DateTime FirstSeen, DateTime LastSeen); public sealed record UnexplainedResult(int Catches, int DistinctPaths, IReadOnlyList Groups, int GroupsOmitted); public sealed record RuleTakeover(ExplanationRuleEntity Rule, int Catches, IReadOnlyList Examples); public sealed record RuleTestResult( int Catches, int DistinctValues, IReadOnlyList<(string Value, int Catches)> Examples, int NewlyExplained, IReadOnlyList TakesOver, int Lost, IReadOnlyList LostExamples); public sealed class ExplanationQueries(IDbContextFactory dbContextFactory, ExplanationRuleStore store) { public const int ExampleCount = 10; public const int MaxGroups = 500; public async Task> GetValuesAsync(ExplanationKind kind, DateTime? since, CancellationToken ct = default) { await using var db = await dbContextFactory.CreateDbContextAsync(ct); var events = db.TrapEvents.AsNoTracking(); if (since is { } start) { events = events.Where(e => e.StartedAt >= start); } IEnumerable values; switch (kind) { case ExplanationKind.Target: var targets = await events.Where(e => e.Target != null).GroupBy(e => e.Target!) .Select(g => new { g.Key, Count = g.Count(), First = g.Min(e => e.StartedAt), Last = g.Max(e => e.StartedAt), Agent = g.Max(e => e.ClientInfo) }) .ToListAsync(ct); values = targets.Select(t => new ObservedValue(ExplanationText.Path(t.Key)!, t.Count, t.First, t.Last, t.Key, t.Agent)); break; case ExplanationKind.ClientInfo: var agents = await events.GroupBy(e => e.ClientInfo ?? "") .Select(g => new { g.Key, Count = g.Count(), First = g.Min(e => e.StartedAt), Last = g.Max(e => e.StartedAt), Target = g.Max(e => e.Target) }) .ToListAsync(ct); values = agents.Select(a => new ObservedValue(a.Key, a.Count, a.First, a.Last, a.Target, a.Key.Length == 0 ? null : a.Key)); break; default: var outcomes = await events.GroupBy(e => new { e.Outcome, Seconds = e.DurationMs / 1000 }) .Select(g => new { g.Key.Outcome, g.Key.Seconds, Count = g.Count(), First = g.Min(e => e.StartedAt), Last = g.Max(e => e.StartedAt), Target = g.Max(e => e.Target), Agent = g.Max(e => e.ClientInfo) }) .ToListAsync(ct); values = outcomes.Select(o => new ObservedValue(ExplanationText.Outcome(o.Outcome, o.Seconds * 1000), o.Count, o.First, o.Last, o.Target, o.Agent)); break; } return values .GroupBy(v => v.Value) .Select(g => new ObservedValue( g.Key, g.Sum(v => v.Catches), g.Min(v => v.FirstSeen), g.Max(v => v.LastSeen), g.OrderByDescending(v => v.Catches).First().ExampleTarget, g.Select(v => v.ExampleUserAgent).FirstOrDefault(a => a is not null))) .ToList(); } public async Task FindUnexplainedAsync(DateTime? since, UnexplainedGrouping grouping, int limit, CancellationToken ct = default) { var rules = await store.GetRuleSetAsync(ct); var unexplained = (await GetValuesAsync(ExplanationKind.Target, since, ct)) .Where(v => rules.Winner(ExplanationKind.Target, v.Value) is null) .ToList(); var groups = unexplained .GroupBy(v => grouping == UnexplainedGrouping.Path ? v.Value : ExplanationText.PathShape(v.Value)) .Select(g => new UnexplainedGroup( g.Key, g.Sum(v => v.Catches), g.OrderByDescending(v => v.Catches).Take(3).Select(v => v.Value).ToList(), g.OrderByDescending(v => v.Catches).Select(v => v.ExampleUserAgent).FirstOrDefault(a => a is not null), g.Min(v => v.FirstSeen), g.Max(v => v.LastSeen))) .OrderByDescending(g => g.Catches) .ThenBy(g => g.Key, StringComparer.Ordinal) .ToList(); var take = Math.Clamp(limit, 1, MaxGroups); return new UnexplainedResult(unexplained.Sum(v => v.Catches), unexplained.Count, groups.Take(take).ToList(), Math.Max(0, groups.Count - take)); } public async Task TestAsync(ExplanationKind kind, string pattern, int priority, int? replacesRuleId, DateTime? since, CancellationToken ct = default) { var validPattern = ExplanationValidator.Pattern(pattern); ExplanationValidator.Priority(priority); var existing = (await store.ListAsync(ct)).Where(r => r.Enabled).ToList(); var candidateId = replacesRuleId ?? int.MaxValue; var candidate = new ExplanationRuleEntity { Id = candidateId, Kind = kind, Pattern = validPattern, Text = "-", Priority = priority, CreatedBy = "test" }; var before = new RuleSet(existing); var after = new RuleSet(existing.Where(r => r.Id != replacesRuleId).Append(candidate)); var candidateOnly = new RuleSet([candidate]); var byId = existing.ToDictionary(r => r.Id); var matched = new List(); var newly = 0; var lost = 0; var lostExamples = new List(); var takeovers = new Dictionary Examples)>(); foreach (var value in (await GetValuesAsync(kind, since, ct)).OrderByDescending(v => v.Catches)) { var wasWinner = before.Winner(kind, value.Value); var nowWinner = after.Winner(kind, value.Value); var hit = candidateOnly.Winner(kind, value.Value) is not null; if (hit) { matched.Add(value); } if (nowWinner?.Id == candidateId) { if (wasWinner is null) { newly += value.Catches; } else if (wasWinner.Id != candidateId) { var (catches, examples) = takeovers.GetValueOrDefault(wasWinner.Id, (0, [])); if (examples.Count < ExampleCount) { examples.Add(value.Value); } takeovers[wasWinner.Id] = (catches + value.Catches, examples); } } else if (wasWinner?.Id == candidateId && nowWinner is null) { lost += value.Catches; if (lostExamples.Count < ExampleCount) { lostExamples.Add(value.Value); } } } return new RuleTestResult( matched.Sum(v => v.Catches), matched.Count, matched.Take(ExampleCount).Select(v => (v.Value, v.Catches)).ToList(), newly, takeovers.OrderByDescending(t => t.Value.Catches).Select(t => new RuleTakeover(byId[t.Key], t.Value.Catches, t.Value.Examples)).ToList(), lost, lostExamples); } public async Task> CountHitsAsync(CancellationToken ct = default) { var rules = await store.ListAsync(ct); var hits = rules.ToDictionary(r => r.Id, _ => 0); foreach (var group in rules.GroupBy(r => r.Kind)) { var set = new RuleSet(group); foreach (var value in await GetValuesAsync(group.Key, null, ct)) { foreach (var rule in set.Matching(group.Key, value.Value)) { hits[rule.Id] += value.Catches; } } } return hits; } }