using System.Text.Json; using System.Text.Json.Serialization; using System.Text.RegularExpressions; using Febe.Core.Abstractions; namespace Febe.Core.Collection; /// Where a path rule looks. [Flags] public enum SignalScope { None = 0, /// Main-frame navigations (the address the page moved to). Navigation = 1, /// Main-frame document responses (page loads, redirects included). Document = 2, /// Every other response (data requests, files). Subresource = 4, Any = Navigation | Document | Subresource, } /// One rule of segnali.json: exactly one matcher among status, path and text. public sealed record SignalRule { public required string Code { get; init; } public required SignalLevel Level { get; init; } /// HTTP status codes that trigger the rule. public IReadOnlySet Statuses { get; init; } = new HashSet(); /// Regular expression on the address path (no query string). public Regex? Path { get; init; } /// Regular expression on the string values of short JSON responses. public Regex? Text { get; init; } /// Text rules only look at responses whose strings total at most this many characters. public int MaxTextChars { get; init; } = SignalRules.DefaultMaxTextChars; public IReadOnlySet HostKinds { get; init; } = new HashSet { HostKind.Site, HostKind.Cdn }; public SignalScope Scope { get; init; } = SignalScope.Any; /// Hypothesis of spec §6.6 the rule depends on (e.g. «H8»), when it is not yet confirmed. public string? Hypothesis { get; init; } } /// Threshold of the «repeated empty pages» throttle signal. public sealed record EmptyPagesRule(string Code, SignalLevel Level, int Consecutive); /// /// The stop-signal rules (spec §7.6), loaded from segnali.json so they can change without recompiling. /// public sealed class SignalRules { public const int DefaultMaxTextChars = 4000; /// Code of the built-in rule «the session cookie is gone» (spec §7.6, Disconnessione). public const string SessionCookieMissingCode = "session-cookie-missing"; private static readonly TimeSpan RegexTimeout = TimeSpan.FromMilliseconds(250); public SignalRules(IReadOnlyList rules, EmptyPagesRule? emptyPages, string? source = null) { Rules = rules; EmptyPages = emptyPages; Source = source; } public IReadOnlyList Rules { get; } public EmptyPagesRule? EmptyPages { get; } /// Where the rules came from (file path or embedded resource name), for messages. public string? Source { get; } /// The shipped Instagram rules (embedded copy of config/segnali.json). public static SignalRules LoadDefault() => LoadEmbedded("segnali.json"); /// The rules of the local test site (embedded copy of config/segnali.prova.json). public static SignalRules LoadTestSite() => LoadEmbedded("segnali.prova.json"); /// Loads when it exists, otherwise the shipped default rules. 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(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); } /// Parses a level name, in English (code) or Italian (interface) form. 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.Site, HostKind.Cdn } : new HashSet { 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(), 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? Rules { get; set; } public EmptyPagesDto? EmptyPages { get; set; } } internal sealed class SignalRuleDto { public string? Code { get; set; } public string? Level { get; set; } public List? Status { get; set; } public string? Path { get; set; } public string? Text { get; set; } public int? MaxTextChars { get; set; } public List? HostKinds { get; set; } public List? 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;