Files
Febe/src/Febe.Core/Collection/SignalRules.cs
T

272 lines
10 KiB
C#

using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using Febe.Core.Abstractions;
namespace Febe.Core.Collection;
/// <summary>Where a path rule looks.</summary>
[Flags]
public enum SignalScope
{
None = 0,
/// <summary>Main-frame navigations (the address the page moved to).</summary>
Navigation = 1,
/// <summary>Main-frame document responses (page loads, redirects included).</summary>
Document = 2,
/// <summary>Every other response (data requests, files).</summary>
Subresource = 4,
Any = Navigation | Document | Subresource,
}
/// <summary>One rule of <c>segnali.json</c>: exactly one matcher among status, path and text.</summary>
public sealed record SignalRule
{
public required string Code { get; init; }
public required SignalLevel Level { get; init; }
/// <summary>HTTP status codes that trigger the rule.</summary>
public IReadOnlySet<int> Statuses { get; init; } = new HashSet<int>();
/// <summary>Regular expression on the address path (no query string).</summary>
public Regex? Path { get; init; }
/// <summary>Regular expression on the string values of short JSON responses.</summary>
public Regex? Text { get; init; }
/// <summary>Text rules only look at responses whose strings total at most this many characters.</summary>
public int MaxTextChars { get; init; } = SignalRules.DefaultMaxTextChars;
public IReadOnlySet<HostKind> HostKinds { get; init; } = new HashSet<HostKind> { HostKind.Site, HostKind.Cdn };
public SignalScope Scope { get; init; } = SignalScope.Any;
/// <summary>Hypothesis of spec §6.6 the rule depends on (e.g. «H8»), when it is not yet confirmed.</summary>
public string? Hypothesis { get; init; }
}
/// <summary>Threshold of the «repeated empty pages» throttle signal.</summary>
public sealed record EmptyPagesRule(string Code, SignalLevel Level, int Consecutive);
/// <summary>
/// The stop-signal rules (spec §7.6), loaded from <c>segnali.json</c> so they can change without recompiling.
/// </summary>
public sealed class SignalRules
{
public const int DefaultMaxTextChars = 4000;
/// <summary>Code of the built-in rule «the session cookie is gone» (spec §7.6, Disconnessione).</summary>
public const string SessionCookieMissingCode = "session-cookie-missing";
private static readonly TimeSpan RegexTimeout = TimeSpan.FromMilliseconds(250);
public SignalRules(IReadOnlyList<SignalRule> rules, EmptyPagesRule? emptyPages, string? source = null)
{
Rules = rules;
EmptyPages = emptyPages;
Source = source;
}
public IReadOnlyList<SignalRule> Rules { get; }
public EmptyPagesRule? EmptyPages { get; }
/// <summary>Where the rules came from (file path or embedded resource name), for messages.</summary>
public string? Source { get; }
/// <summary>The shipped Instagram rules (embedded copy of <c>config/segnali.json</c>).</summary>
public static SignalRules LoadDefault() => LoadEmbedded("segnali.json");
/// <summary>The rules of the local test site (embedded copy of <c>config/segnali.prova.json</c>).</summary>
public static SignalRules LoadTestSite() => LoadEmbedded("segnali.prova.json");
/// <summary>Loads <paramref name="path"/> when it exists, otherwise the shipped default rules.</summary>
public static SignalRules LoadOrDefault(string? path) =>
!string.IsNullOrEmpty(path) && File.Exists(path) ? Load(path) : LoadDefault();
public static SignalRules Load(string path) => Parse(File.ReadAllText(path), path);
public static SignalRules LoadEmbedded(string fileName)
{
var resource = $"Febe.Core.Config.{fileName}";
using var stream = typeof(SignalRules).Assembly.GetManifestResourceStream(resource)
?? throw new FileNotFoundException($"Risorsa incorporata mancante: {resource}");
using var reader = new StreamReader(stream);
return Parse(reader.ReadToEnd(), fileName);
}
public static SignalRules Parse(string json, string? source = null)
{
var name = source ?? "segnali.json";
SignalRulesFile? file;
try
{
file = JsonSerializer.Deserialize(json, SignalRulesJsonContext.Default.SignalRulesFile);
}
catch (JsonException ex)
{
throw new InvalidDataException($"{name}: il file non è un JSON valido (riga {ex.LineNumber + 1}).", ex);
}
if (file?.Rules is null)
{
throw new InvalidDataException($"{name}: manca l'elenco «rules».");
}
var rules = new List<SignalRule>(file.Rules.Count);
for (var i = 0; i < file.Rules.Count; i++)
{
rules.Add(ToRule(file.Rules[i], $"{name}, regola {i + 1}"));
}
// The same code may appear in several rules (e.g. two challenge paths): that is allowed.
EmptyPagesRule? empty = null;
if (file.EmptyPages is { } e)
{
if (e.Consecutive < 2)
{
throw new InvalidDataException($"{name}: «emptyPages.consecutive» deve essere almeno 2.");
}
empty = new EmptyPagesRule(RequireCode(e.Code, $"{name}, emptyPages"), ParseLevel(e.Level, $"{name}, emptyPages"), e.Consecutive);
}
return new SignalRules(rules, empty, source);
}
/// <summary>Parses a level name, in English (code) or Italian (interface) form.</summary>
public static SignalLevel ParseLevel(string? value, string where) => value?.Trim().ToLowerInvariant() switch
{
"throttle" or "rallentamento" => SignalLevel.Throttle,
"challenge" or "verifica" => SignalLevel.Challenge,
"disconnect" or "disconnessione" => SignalLevel.Disconnect,
_ => throw new InvalidDataException($"{where}: livello «{value}» sconosciuto (ammessi: throttle, challenge, disconnect)."),
};
private static SignalRule ToRule(SignalRuleDto dto, string where)
{
var code = RequireCode(dto.Code, where);
var level = ParseLevel(dto.Level, where);
var matchers = (dto.Status is { Count: > 0 } ? 1 : 0) + (string.IsNullOrEmpty(dto.Path) ? 0 : 1) + (string.IsNullOrEmpty(dto.Text) ? 0 : 1);
if (matchers != 1)
{
throw new InvalidDataException($"{where}: serve esattamente uno fra «status», «path» e «text».");
}
var hostKinds = dto.HostKinds is { Count: > 0 }
? dto.HostKinds.Select(k => ParseHostKind(k, where)).ToHashSet()
: (dto.Text is null ? new HashSet<HostKind> { HostKind.Site, HostKind.Cdn } : new HashSet<HostKind> { HostKind.Site });
var scope = dto.On is { Count: > 0 }
? dto.On.Aggregate(SignalScope.None, (acc, s) => acc | ParseScope(s, where))
: (string.IsNullOrEmpty(dto.Path) ? SignalScope.Any : SignalScope.Navigation | SignalScope.Document);
return new SignalRule
{
Code = code,
Level = level,
Statuses = dto.Status is { Count: > 0 } ? dto.Status.ToHashSet() : new HashSet<int>(),
Path = CompileRegex(dto.Path, where),
Text = CompileRegex(dto.Text, where),
MaxTextChars = dto.MaxTextChars is > 0 ? dto.MaxTextChars.Value : DefaultMaxTextChars,
HostKinds = hostKinds,
Scope = scope,
Hypothesis = string.IsNullOrWhiteSpace(dto.Hypothesis) ? null : dto.Hypothesis.Trim(),
};
}
private static string RequireCode(string? code, string where) =>
string.IsNullOrWhiteSpace(code) ? throw new InvalidDataException($"{where}: manca «code».") : code.Trim();
private static Regex? CompileRegex(string? pattern, string where)
{
if (string.IsNullOrEmpty(pattern))
{
return null;
}
try
{
return new Regex(pattern, RegexOptions.CultureInvariant | RegexOptions.IgnoreCase, RegexTimeout);
}
catch (ArgumentException ex)
{
throw new InvalidDataException($"{where}: espressione «{pattern}» non valida.", ex);
}
}
private static HostKind ParseHostKind(string value, string where) => value.Trim().ToLowerInvariant() switch
{
"site" or "sito" => HostKind.Site,
"cdn" => HostKind.Cdn,
"other" or "altro" => HostKind.Other,
_ => throw new InvalidDataException($"{where}: tipo di host «{value}» sconosciuto (ammessi: site, cdn, other)."),
};
private static SignalScope ParseScope(string value, string where) => value.Trim().ToLowerInvariant() switch
{
"navigation" => SignalScope.Navigation,
"document" => SignalScope.Document,
"subresource" => SignalScope.Subresource,
"any" => SignalScope.Any,
_ => throw new InvalidDataException($"{where}: ambito «{value}» sconosciuto (ammessi: navigation, document, subresource, any)."),
};
}
internal sealed class SignalRulesFile
{
public string? Note { get; set; }
public List<SignalRuleDto>? Rules { get; set; }
public EmptyPagesDto? EmptyPages { get; set; }
}
internal sealed class SignalRuleDto
{
public string? Code { get; set; }
public string? Level { get; set; }
public List<int>? Status { get; set; }
public string? Path { get; set; }
public string? Text { get; set; }
public int? MaxTextChars { get; set; }
public List<string>? HostKinds { get; set; }
public List<string>? On { get; set; }
public string? Hypothesis { get; set; }
public string? Note { get; set; }
}
internal sealed class EmptyPagesDto
{
public string? Code { get; set; }
public string? Level { get; set; }
public int Consecutive { get; set; }
public string? Note { get; set; }
}
[JsonSourceGenerationOptions(
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
ReadCommentHandling = JsonCommentHandling.Skip,
AllowTrailingCommas = true,
UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow)]
[JsonSerializable(typeof(SignalRulesFile))]
internal sealed partial class SignalRulesJsonContext : JsonSerializerContext;