M3 Motore: Governatore con tetti da action_log, interruttore con fermi 1/6/24 ore e ripresa manuale, fascia giornaliera spostata a caso e salvata, sessioni con pause log-normali e pavimento, composizione delle sessioni sulla coda persistente, «Controlla ora» con conferma fuori fascia, cruscotto per l'interfaccia e calcolatore «Con queste impostazioni», simulazione con orologio virtuale e comando --simula; prove del motore e dell'interruttore
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
38 files changed
+9308
No files matched your search
@@ -0,0 +1,379 @@
|
||||
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;
|
||||
|
||||
/// <summary>Setting keys of the engine (spec §8.3 <c>setting</c>). Values are invariant-culture text.</summary>
|
||||
public static class EngineSettingKeys
|
||||
{
|
||||
/// <summary>Caution profile kind: Prudent, Balanced, Fast or Custom.</summary>
|
||||
public const string Profile = "motore.profilo";
|
||||
|
||||
/// <summary>Values of the «Su misura» profile, as compact JSON.</summary>
|
||||
public const string CustomProfile = "motore.profilo-su-misura";
|
||||
|
||||
/// <summary>«Ritmo dei gesti»: Slow, Natural, Brisk.</summary>
|
||||
public const string Pace = "motore.ritmo-gesti";
|
||||
|
||||
/// <summary>«Avvio graduale» on or off.</summary>
|
||||
public const string GradualStart = "motore.avvio-graduale";
|
||||
|
||||
/// <summary>Active weekdays as digits 0 (Sunday) … 6 (Saturday), e.g. "0123456".</summary>
|
||||
public const string ActiveDays = "motore.giorni-attivi";
|
||||
|
||||
/// <summary>«Metti in pausa»: true while the engine is paused by Alberto.</summary>
|
||||
public const string Paused = "motore.in-pausa";
|
||||
|
||||
/// <summary>Start of the gradual start (first connection, last resolved verification), Unix milliseconds.</summary>
|
||||
public const string RampStart = "motore.avvio-graduale-dal";
|
||||
|
||||
/// <summary>Planned start of the next session, Unix milliseconds: a restart never brings it earlier.</summary>
|
||||
public const string NextSession = "motore.prossima-sessione";
|
||||
|
||||
/// <summary>Seed of the daily shifts of the active window: a restart does not redraw them.</summary>
|
||||
public const string WindowSeed = "motore.fascia-seme";
|
||||
|
||||
/// <summary>Recipes suspended after repeated unrecognized formats: "Kind=ms;Kind=ms".</summary>
|
||||
public const string SuspendedRecipes = "motore.ricette-sospese";
|
||||
|
||||
/// <summary>Consecutive failures per recipe: "Kind=n;Kind=n".</summary>
|
||||
public const string RecipeFailures = "motore.ricette-errori-consecutivi";
|
||||
|
||||
/// <summary>Last completed Giro dei seguiti, Unix milliseconds (it read the stories bar of every followed account).</summary>
|
||||
public const string LastSweep = "motore.ultimo-giro";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Engine and caution settings chosen by Alberto (mockup 07): profile, «Su misura» values, gesture pace, gradual
|
||||
/// start, active days.
|
||||
/// </summary>
|
||||
public sealed record EngineSettings
|
||||
{
|
||||
public static readonly IReadOnlySet<DayOfWeek> AllDays = new HashSet<DayOfWeek>(Enum.GetValues<DayOfWeek>());
|
||||
|
||||
public CautionProfileKind ProfileKind { get; init; } = CautionProfileKind.Prudent;
|
||||
|
||||
/// <summary>Values of the «Su misura» profile; used when <see cref="ProfileKind"/> is Custom.</summary>
|
||||
public CautionProfile? Custom { get; init; }
|
||||
|
||||
public GesturePace Pace { get; init; } = GesturePace.Natural;
|
||||
|
||||
public bool GradualStart { get; init; } = true;
|
||||
|
||||
public IReadOnlySet<DayOfWeek> ActiveDays { get; init; } = AllDays;
|
||||
|
||||
/// <summary>The profile the engine applies: preset or custom values, with pace, gradual start and active days.</summary>
|
||||
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 };
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A modified value turns the profile into «Su misura» (spec §7.5).</summary>
|
||||
public EngineSettings WithCustomValues(CautionProfile values) =>
|
||||
this with { ProfileKind = CautionProfileKind.Custom, Custom = values with { Kind = CautionProfileKind.Custom } };
|
||||
}
|
||||
|
||||
/// <summary>Reads and writes <see cref="EngineSettings"/> in the settings table.</summary>
|
||||
public static class EngineSettingsStore
|
||||
{
|
||||
public static async Task<EngineSettings> 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<CautionProfileKind>(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<GesturePace>(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;
|
||||
}
|
||||
|
||||
/// <summary>Validates and stores the settings. Throws <see cref="ArgumentException"/> with Italian messages when a value is outside the limits of spec §7.5.</summary>
|
||||
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<string, string?>
|
||||
{
|
||||
[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<DayOfWeek> days) =>
|
||||
string.Concat(days.OrderBy(d => (int)d).Select(d => ((int)d).ToString(CultureInfo.InvariantCulture)));
|
||||
|
||||
internal static HashSet<DayOfWeek> ParseDays(string text)
|
||||
{
|
||||
var days = new HashSet<DayOfWeek>();
|
||||
foreach (var c in text)
|
||||
{
|
||||
if (c is >= '0' and <= '6')
|
||||
{
|
||||
days.Add((DayOfWeek)(c - '0'));
|
||||
}
|
||||
}
|
||||
|
||||
return days;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Limits of what the interface accepts for a profile (spec §7.5).</summary>
|
||||
public static class CautionProfileRules
|
||||
{
|
||||
/// <summary>Largest daily jitter of the window that makes sense.</summary>
|
||||
public static readonly TimeSpan MaxJitter = TimeSpan.FromHours(2);
|
||||
|
||||
public const int MaxRampUpDays = 30;
|
||||
|
||||
/// <summary>Length of the active window before the daily shift (crossing midnight when the end is not after the start).</summary>
|
||||
public static TimeSpan WindowLength(TimeOnly start, TimeOnly end)
|
||||
{
|
||||
var length = end.ToTimeSpan() - start.ToTimeSpan();
|
||||
return length <= TimeSpan.Zero ? length + TimeSpan.FromDays(1) : length;
|
||||
}
|
||||
|
||||
/// <summary>Italian messages for every value outside the limits; empty when the profile is acceptable.</summary>
|
||||
public static IReadOnlyList<string> Validate(CautionProfile profile)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(profile);
|
||||
var errors = new List<string>();
|
||||
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<ActionKind>())
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Compact JSON of a «Su misura» profile. Written with <see cref="JsonNode"/> (no reflection serializer), so it keeps
|
||||
/// working in a trimmed single-file build.
|
||||
/// </summary>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>Null when the text is not a valid profile (it then falls back to «Prudente»).</summary>
|
||||
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<ActionKind, Budget>();
|
||||
if (json["budgets"] is JsonObject budgetNode)
|
||||
{
|
||||
foreach (var (key, value) in budgetNode)
|
||||
{
|
||||
if (Enum.TryParse<ActionKind>(key, out var kind) && value is JsonArray { Count: 2 } pair)
|
||||
{
|
||||
budgets[kind] = new Budget(pair[0]!.GetValue<int>(), pair[1]!.GetValue<int>());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var kind in Enum.GetValues<ActionKind>())
|
||||
{
|
||||
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<string>(), "HH:mm", CultureInfo.InvariantCulture),
|
||||
WindowEnd = TimeOnly.ParseExact(end.GetValue<string>(), "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<double>() : throw new KeyNotFoundException(key);
|
||||
}
|
||||
Reference in new issue
Block a user