using System.Globalization;
using System.Text.Json;
using System.Text.Json.Nodes;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Storage;
namespace Febe.Core.Engine;
/// Setting keys of the engine (spec §8.3 setting). Values are invariant-culture text.
public static class EngineSettingKeys
{
/// Caution profile kind: Prudent, Balanced, Fast or Custom.
public const string Profile = "motore.profilo";
/// Values of the «Su misura» profile, as compact JSON.
public const string CustomProfile = "motore.profilo-su-misura";
/// «Ritmo dei gesti»: Slow, Natural, Brisk.
public const string Pace = "motore.ritmo-gesti";
/// «Avvio graduale» on or off.
public const string GradualStart = "motore.avvio-graduale";
/// Active weekdays as digits 0 (Sunday) … 6 (Saturday), e.g. "0123456".
public const string ActiveDays = "motore.giorni-attivi";
/// «Metti in pausa»: true while the engine is paused by Alberto.
public const string Paused = "motore.in-pausa";
/// Start of the gradual start (first connection, last resolved verification), Unix milliseconds.
public const string RampStart = "motore.avvio-graduale-dal";
/// Planned start of the next session, Unix milliseconds: a restart never brings it earlier.
public const string NextSession = "motore.prossima-sessione";
/// Seed of the daily shifts of the active window: a restart does not redraw them.
public const string WindowSeed = "motore.fascia-seme";
/// Recipes suspended after repeated unrecognized formats: "Kind=ms;Kind=ms".
public const string SuspendedRecipes = "motore.ricette-sospese";
/// Consecutive failures per recipe: "Kind=n;Kind=n".
public const string RecipeFailures = "motore.ricette-errori-consecutivi";
/// Last completed Giro dei seguiti, Unix milliseconds (it read the stories bar of every followed account).
public const string LastSweep = "motore.ultimo-giro";
///
/// Fingerprint of the collection configuration the suspensions and failure counts refer to (reader vocabulary and
/// target map of the site, as loaded): when it changes they are cleared once.
///
public const string CollectionConfiguration = "motore.configurazione-raccolta";
}
///
/// Engine and caution settings chosen by Alberto (mockup 07): profile, «Su misura» values, gesture pace, gradual
/// start, active days.
///
public sealed record EngineSettings
{
public static readonly IReadOnlySet AllDays = new HashSet(Enum.GetValues());
public CautionProfileKind ProfileKind { get; init; } = CautionProfileKind.Prudent;
/// Values of the «Su misura» profile; used when is Custom.
public CautionProfile? Custom { get; init; }
public GesturePace Pace { get; init; } = GesturePace.Natural;
public bool GradualStart { get; init; } = true;
public IReadOnlySet ActiveDays { get; init; } = AllDays;
/// The profile the engine applies: preset or custom values, with pace, gradual start and active days.
public CautionProfile EffectiveProfile
{
get
{
var basis = ProfileKind == CautionProfileKind.Custom
? (Custom ?? CautionProfile.Prudent) with { Kind = CautionProfileKind.Custom }
: CautionProfile.For(ProfileKind);
return basis with { Pace = Pace, GradualStart = GradualStart, ActiveDays = ActiveDays };
}
}
/// A modified value turns the profile into «Su misura» (spec §7.5).
public EngineSettings WithCustomValues(CautionProfile values) =>
this with { ProfileKind = CautionProfileKind.Custom, Custom = values with { Kind = CautionProfileKind.Custom } };
}
/// Reads and writes in the settings table.
public static class EngineSettingsStore
{
public static async Task LoadAsync(ISettingsStore store, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(store);
var all = await store.GetAllAsync(ct).ConfigureAwait(false);
var settings = new EngineSettings();
if (all.TryGetValue(EngineSettingKeys.Profile, out var kindText) && Enum.TryParse(kindText, out var kind))
{
settings = settings with { ProfileKind = kind };
}
if (all.TryGetValue(EngineSettingKeys.CustomProfile, out var customText))
{
settings = settings with { Custom = CautionProfileCodec.TryDecode(customText) };
}
if (all.TryGetValue(EngineSettingKeys.Pace, out var paceText) && Enum.TryParse(paceText, out var pace))
{
settings = settings with { Pace = pace };
}
if (all.TryGetValue(EngineSettingKeys.GradualStart, out var gradualText) && bool.TryParse(gradualText, out var gradual))
{
settings = settings with { GradualStart = gradual };
}
if (all.TryGetValue(EngineSettingKeys.ActiveDays, out var daysText))
{
var days = ParseDays(daysText);
if (days.Count > 0)
{
settings = settings with { ActiveDays = days };
}
}
if (settings.ProfileKind == CautionProfileKind.Custom && settings.Custom is null)
{
settings = settings with { ProfileKind = CautionProfileKind.Prudent };
}
return settings;
}
/// Validates and stores the settings. Throws with Italian messages when a value is outside the limits of spec §7.5.
public static async Task SaveAsync(ISettingsStore store, EngineSettings settings, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(store);
ArgumentNullException.ThrowIfNull(settings);
var errors = CautionProfileRules.Validate(settings.EffectiveProfile);
if (settings.ActiveDays.Count == 0)
{
errors = [.. errors, "Serve almeno un giorno attivo."];
}
if (errors.Count > 0)
{
throw new ArgumentException(string.Join(" ", errors), nameof(settings));
}
await store.SetManyAsync(
new Dictionary
{
[EngineSettingKeys.Profile] = settings.ProfileKind.ToString(),
[EngineSettingKeys.CustomProfile] = settings.Custom is null ? null : CautionProfileCodec.Encode(settings.Custom),
[EngineSettingKeys.Pace] = settings.Pace.ToString(),
[EngineSettingKeys.GradualStart] = settings.GradualStart ? "true" : "false",
[EngineSettingKeys.ActiveDays] = FormatDays(settings.ActiveDays),
},
ct).ConfigureAwait(false);
}
internal static string FormatDays(IReadOnlySet days) =>
string.Concat(days.OrderBy(d => (int)d).Select(d => ((int)d).ToString(CultureInfo.InvariantCulture)));
internal static HashSet ParseDays(string text)
{
var days = new HashSet();
foreach (var c in text)
{
if (c is >= '0' and <= '6')
{
days.Add((DayOfWeek)(c - '0'));
}
}
return days;
}
}
/// Limits of what the interface accepts for a profile (spec §7.5).
public static class CautionProfileRules
{
/// Largest daily jitter of the window that makes sense.
public static readonly TimeSpan MaxJitter = TimeSpan.FromHours(2);
public const int MaxRampUpDays = 30;
/// Length of the active window before the daily shift (crossing midnight when the end is not after the start).
public static TimeSpan WindowLength(TimeOnly start, TimeOnly end)
{
var length = end.ToTimeSpan() - start.ToTimeSpan();
return length <= TimeSpan.Zero ? length + TimeSpan.FromDays(1) : length;
}
/// Italian messages for every value outside the limits; empty when the profile is acceptable.
public static IReadOnlyList Validate(CautionProfile profile)
{
ArgumentNullException.ThrowIfNull(profile);
var errors = new List();
if (profile.PauseMin < CautionProfile.Limits.MinPause)
{
errors.Add("La pausa minima non può scendere sotto i 5 minuti.");
}
if (profile.PauseMax < profile.PauseMin)
{
errors.Add("La pausa massima deve essere almeno pari alla minima.");
}
if (profile.SessionMin < TimeSpan.FromMinutes(1))
{
errors.Add("Una sessione dura almeno 1 minuto.");
}
if (profile.SessionMax > CautionProfile.Limits.MaxSession)
{
errors.Add("Una sessione non può durare più di 30 minuti.");
}
if (profile.SessionMax < profile.SessionMin)
{
errors.Add("La durata massima di una sessione deve essere almeno pari alla minima.");
}
var window = WindowLength(profile.WindowStart, profile.WindowEnd);
if (window > CautionProfile.Limits.MaxWindow)
{
errors.Add("La fascia oraria non può superare le 20 ore.");
}
if (profile.WindowJitter < TimeSpan.Zero || profile.WindowJitter > MaxJitter)
{
errors.Add("Lo spostamento giornaliero della fascia va da 0 a 2 ore.");
}
foreach (var kind in Enum.GetValues())
{
if (kind == ActionKind.DataDownload)
{
continue;
}
if (!profile.Budgets.TryGetValue(kind, out var budget))
{
errors.Add($"Manca il tetto delle {ItalianText.Category(kind)}.");
continue;
}
var max = CautionProfile.Limits.MaxBudget(kind);
if (budget.PerHour < 0 || budget.PerDay < 0)
{
errors.Add($"Il tetto delle {ItalianText.Category(kind)} non può essere negativo.");
}
else if (budget.PerHour > max.PerHour || budget.PerDay > max.PerDay)
{
errors.Add(
$"Il tetto delle {ItalianText.Category(kind)} non può superare il doppio di «Rapido» ({ItalianText.Number(max.PerHour)} all'ora, {ItalianText.Number(max.PerDay)} al giorno).");
}
}
if (profile.DataPerDayBytes < 0 || profile.DataPerDayBytes > CautionProfile.Limits.MaxDataPerDayBytes)
{
errors.Add($"I dati scaricati al giorno non possono superare il doppio di «Rapido» ({ItalianText.Bytes(CautionProfile.Limits.MaxDataPerDayBytes)}).");
}
var maxBackfill = CautionProfile.Fast.BackfillPostsPerAccountPerDay * 2;
if (profile.BackfillPostsPerAccountPerDay < 0 || profile.BackfillPostsPerAccountPerDay > maxBackfill)
{
errors.Add($"Lo storico per account al giorno non può superare il doppio di «Rapido» ({ItalianText.Number(maxBackfill)} post).");
}
if (profile.RampUpDays < 0 || profile.RampUpDays > MaxRampUpDays)
{
errors.Add("L'avvio graduale dura da 0 a 30 giorni.");
}
if (profile.ActiveDays.Count == 0)
{
errors.Add("Serve almeno un giorno attivo.");
}
return errors;
}
}
///
/// Compact JSON of a «Su misura» profile. Written with (no reflection serializer), so it keeps
/// working in a trimmed single-file build.
///
public static class CautionProfileCodec
{
public static string Encode(CautionProfile profile)
{
ArgumentNullException.ThrowIfNull(profile);
var budgets = new JsonObject();
foreach (var (kind, budget) in profile.Budgets.OrderBy(b => b.Key))
{
budgets[kind.ToString()] = new JsonArray(budget.PerHour, budget.PerDay);
}
var json = new JsonObject
{
["windowStart"] = profile.WindowStart.ToString("HH:mm", CultureInfo.InvariantCulture),
["windowEnd"] = profile.WindowEnd.ToString("HH:mm", CultureInfo.InvariantCulture),
["jitterMin"] = profile.WindowJitter.TotalMinutes,
["sessionMinMin"] = profile.SessionMin.TotalMinutes,
["sessionMaxMin"] = profile.SessionMax.TotalMinutes,
["pauseMinMin"] = profile.PauseMin.TotalMinutes,
["pauseMaxMin"] = profile.PauseMax.TotalMinutes,
["budgets"] = budgets,
["dataPerDayBytes"] = profile.DataPerDayBytes,
["backfillPerAccount"] = profile.BackfillPostsPerAccountPerDay,
["rampUpDays"] = profile.RampUpDays,
};
return json.ToJsonString();
}
/// Null when the text is not a valid profile (it then falls back to «Prudente»).
public static CautionProfile? TryDecode(string? text)
{
if (string.IsNullOrWhiteSpace(text))
{
return null;
}
try
{
if (JsonNode.Parse(text) is not JsonObject json)
{
return null;
}
var budgets = new Dictionary();
if (json["budgets"] is JsonObject budgetNode)
{
foreach (var (key, value) in budgetNode)
{
if (Enum.TryParse(key, out var kind) && value is JsonArray { Count: 2 } pair)
{
budgets[kind] = new Budget(pair[0]!.GetValue(), pair[1]!.GetValue());
}
}
}
foreach (var kind in Enum.GetValues())
{
if (kind != ActionKind.DataDownload && !budgets.ContainsKey(kind))
{
budgets[kind] = CautionProfile.Prudent.Budgets[kind];
}
}
if (json["windowStart"] is not JsonValue start || json["windowEnd"] is not JsonValue end)
{
return null;
}
return new CautionProfile
{
Kind = CautionProfileKind.Custom,
WindowStart = TimeOnly.ParseExact(start.GetValue(), "HH:mm", CultureInfo.InvariantCulture),
WindowEnd = TimeOnly.ParseExact(end.GetValue(), "HH:mm", CultureInfo.InvariantCulture),
WindowJitter = TimeSpan.FromMinutes(Number(json, "jitterMin")),
SessionMin = TimeSpan.FromMinutes(Number(json, "sessionMinMin")),
SessionMax = TimeSpan.FromMinutes(Number(json, "sessionMaxMin")),
PauseMin = TimeSpan.FromMinutes(Number(json, "pauseMinMin")),
PauseMax = TimeSpan.FromMinutes(Number(json, "pauseMaxMin")),
Budgets = budgets,
DataPerDayBytes = (long)Number(json, "dataPerDayBytes"),
BackfillPostsPerAccountPerDay = (int)Number(json, "backfillPerAccount"),
RampUpDays = (int)Number(json, "rampUpDays"),
};
}
catch (Exception ex) when (ex is JsonException or FormatException or InvalidOperationException or KeyNotFoundException)
{
return null;
}
}
private static double Number(JsonObject json, string key) =>
json[key] is JsonValue value ? value.GetValue() : throw new KeyNotFoundException(key);
}