78 lines
2.4 KiB
C#
78 lines
2.4 KiB
C#
using System.Text.RegularExpressions;
|
|
using Flypaper.Storage.Entities;
|
|
|
|
namespace Flypaper.Storage.Explanations;
|
|
|
|
public sealed record Explanation(ExplanationRuleEntity? Target, ExplanationRuleEntity? Client, ExplanationRuleEntity? Outcome)
|
|
{
|
|
public bool HasTarget => Target is not null;
|
|
}
|
|
|
|
public sealed class RuleSet
|
|
{
|
|
public static readonly RuleSet Empty = new([]);
|
|
|
|
private readonly IReadOnlyDictionary<ExplanationKind, IReadOnlyList<(ExplanationRuleEntity Rule, Regex Regex)>> _byKind;
|
|
|
|
public RuleSet(IEnumerable<ExplanationRuleEntity> rules)
|
|
{
|
|
var compiled = new Dictionary<ExplanationKind, List<(ExplanationRuleEntity, Regex)>>();
|
|
foreach (var rule in rules.OrderByDescending(r => r.Priority).ThenBy(r => r.Id))
|
|
{
|
|
Regex regex;
|
|
try
|
|
{
|
|
regex = ExplanationValidator.Compile(rule.Pattern);
|
|
}
|
|
catch (Exception exception) when (exception is ArgumentException or NotSupportedException)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
if (!compiled.TryGetValue(rule.Kind, out var list))
|
|
{
|
|
compiled[rule.Kind] = list = [];
|
|
}
|
|
|
|
list.Add((rule, regex));
|
|
}
|
|
|
|
_byKind = compiled.ToDictionary(p => p.Key, p => (IReadOnlyList<(ExplanationRuleEntity, Regex)>)p.Value);
|
|
}
|
|
|
|
public ExplanationRuleEntity? Winner(ExplanationKind kind, string value) => Matching(kind, value).FirstOrDefault();
|
|
|
|
public IEnumerable<ExplanationRuleEntity> Matching(ExplanationKind kind, string value)
|
|
{
|
|
if (!_byKind.TryGetValue(kind, out var rules))
|
|
{
|
|
yield break;
|
|
}
|
|
|
|
foreach (var (rule, regex) in rules)
|
|
{
|
|
if (IsMatch(regex, value))
|
|
{
|
|
yield return rule;
|
|
}
|
|
}
|
|
}
|
|
|
|
public Explanation Explain(TrapEventEntity trapEvent) => new(
|
|
trapEvent.Target is null ? null : Winner(ExplanationKind.Target, ExplanationText.Value(ExplanationKind.Target, trapEvent)),
|
|
Winner(ExplanationKind.ClientInfo, ExplanationText.Value(ExplanationKind.ClientInfo, trapEvent)),
|
|
Winner(ExplanationKind.Outcome, ExplanationText.Value(ExplanationKind.Outcome, trapEvent)));
|
|
|
|
private static bool IsMatch(Regex regex, string value)
|
|
{
|
|
try
|
|
{
|
|
return regex.IsMatch(value);
|
|
}
|
|
catch (RegexMatchTimeoutException)
|
|
{
|
|
return false;
|
|
}
|
|
}
|
|
}
|