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:
Claude committed 2026-10-13 17:33:28 +00:00
1 parent e2c987873b
commit 346d5ca075
38 files changed
+9308

No files matched your search

@@ -0,0 +1,315 @@
using Febe.Core.Abstractions;
using Febe.Core.Domain;
namespace Febe.Core.Engine;
/// <summary>What the «Con queste impostazioni» panel needs (spec §4.4, mockup 05).</summary>
public sealed record AccountPlanInput
{
/// <summary>The account with the settings being edited (not yet saved).</summary>
public required Account Account { get; init; }
/// <summary>All the other accounts, to compute the load on the daily budgets (the edited account is ignored here by id).</summary>
public IReadOnlyList<Account> OtherAccounts { get; init; } = [];
/// <summary>The effective caution profile (settings applied).</summary>
public required CautionProfile Profile { get; init; }
/// <summary>Posts of this account already in the library (for the backfill estimate).</summary>
public int ArchivedPosts { get; init; }
public EngineOptions Options { get; init; } = EngineOptions.Default;
}
/// <summary>A line of the panel: «Nuovi post» — «controllati ogni 3 ore circa, tra le 7:30 e le 23:30».</summary>
public sealed record PlanLine(string Title, string Text);
/// <summary>The consequences of an account's settings, with real numbers (spec §4.5).</summary>
public sealed record AccountPlanEstimate
{
public required IReadOnlyList<PlanLine> Lines { get; init; }
/// <summary>Warnings: requested accounts and frequencies exceed what the budgets allow (checks get sparser, not forced).</summary>
public required IReadOnlyList<string> Warnings { get; init; }
/// <summary>The engine contacts this account at all (not paused, not «Solo archivio», reachable).</summary>
public bool Contacted { get; init; }
/// <summary>Profile checks as wished by the frequency.</summary>
public TimeSpan? ProfileCheckWanted { get; init; }
/// <summary>Profile checks as they will really happen (sparser when the budget is short).</summary>
public TimeSpan? ProfileCheckEvery { get; init; }
/// <summary>Planned interval between story checks (null with stories off).</summary>
public TimeSpan? StoryInterval { get; init; }
public double? StoryChecksPerDay { get; init; }
/// <summary>Profile openings per day caused by this account (after thinning).</summary>
public double ProfileOpensPerDay { get; init; }
/// <summary>Profile openings per day asked by all the accounts together (before thinning).</summary>
public double TotalProfileOpensPerDay { get; init; }
/// <summary>Daily budget of profiles opened (full, without gradual start or halving).</summary>
public int DailyProfileBudget { get; init; }
/// <summary>Share of the daily profile budget taken by this account, 0–1.</summary>
public double ShareOfDailyBudget { get; init; }
/// <summary>All the accounts together ask more than the budget allows.</summary>
public bool OverBudget { get; init; }
public int? BackfillRemainingPosts { get; init; }
/// <summary>Days the backfill needs (null when the number of posts is not known yet).</summary>
public int? BackfillDays { get; init; }
}
/// <summary>
/// The «Con queste impostazioni» calculator (spec §4.4): a pure function the web layer can call at every change.
/// The numbers are estimates from medians; they say «circa».
/// </summary>
public static class AccountPlanCalculator
{
/// <summary>Mean of the next-check jitter (log-normal, median 1, σ 0.25, truncated to [0.6, 1.8]).</summary>
private const double MeanCheckJitter = 1.03;
/// <summary>Mean of the story jitter (median 0.75, σ 0.25, truncated to [0.45, 1]).</summary>
private const double MeanStoryJitter = 0.74;
public static AccountPlanEstimate Calculate(AccountPlanInput input)
{
ArgumentNullException.ThrowIfNull(input);
var account = input.Account;
var profile = input.Profile;
var options = input.Options;
var window = CautionProfileRules.WindowLength(profile.WindowStart, profile.WindowEnd);
var windowText = $"tra le {Clock(profile.WindowStart)} e le {Clock(profile.WindowEnd)}";
var lines = new List<PlanLine>();
var warnings = new List<string>();
var all = input.OtherAccounts.Where(a => a.Id == 0 || a.Id != account.Id).Append(account).ToList();
var contactable = all.Where(CheckPolicy.IsContactable).ToList();
var totalDemand = contactable.Sum(a => ProfileOpensPerDay(a, window, options));
var budget = profile.Budgets.TryGetValue(ActionKind.ProfileOpen, out var b) ? b.PerDay : 0;
var overBudget = budget > 0 && totalDemand > budget;
var thinning = overBudget ? totalDemand / budget : 1.0;
var contacted = CheckPolicy.IsContactable(account);
var own = contacted ? ProfileOpensPerDay(account, window, options) : 0;
TimeSpan? wanted = null;
TimeSpan? every = null;
TimeSpan? storyInterval = null;
double? storyChecks = null;
if (!contacted)
{
lines.Add(new PlanLine("Controlli", NotContactedText(account)));
}
else
{
// New posts.
if (CheckPolicy.WantsProfileChecks(account))
{
wanted = account.IsFollowed ? CheckPolicy.ProfileCheckInterval(account) : CheckPolicy.VisitInterval(account, window, options.MinimumStoryChecksPerDay);
every = TimeSpan.FromTicks((long)(wanted.Value.Ticks * MeanCheckJitter * thinning));
var text = account.IsFollowed
? $"scoperti dal giro dei profili che segui, di norma entro {Minutes(profile.PauseMin)}–{Minutes(profile.PauseMax)} minuti dalla pubblicazione, {windowText}. Il profilo si riapre solo per riconciliare, {ItalianText.Every(Round(every.Value))} circa."
: $"controllati {ItalianText.Every(Round(every.Value))} circa, {windowText}.";
lines.Add(new PlanLine("Nuovi post", text));
}
else
{
lines.Add(new PlanLine("Nuovi post", "non scaricati con queste impostazioni."));
}
// Stories.
if (CheckPolicy.WantsStories(account))
{
storyInterval = CheckPolicy.StoryInterval(account, window, options.MinimumStoryChecksPerDay);
storyChecks = Math.Max(options.MinimumStoryChecksPerDay, 1 + (window / (storyInterval.Value * MeanStoryJitter)));
var how = account.IsFollowed && options.SweepCoversFollowedStories
? "a ogni giro dei profili che segui e"
: string.Empty;
lines.Add(new PlanLine(
"Storie",
$"controllate {how} almeno {ItalianText.Number(options.MinimumStoryChecksPerDay)} volte al giorno; fra due controlli passano al massimo {ItalianText.Duration(storyInterval.Value)} circa. Restano 24 ore, quindi nessuna dovrebbe scadere prima di essere vista."
.Replace(" ", " ", StringComparison.Ordinal)));
}
else
{
lines.Add(new PlanLine("Storie", "spente."));
}
}
// History.
var (backfillText, remaining, days) = Backfill(input, all);
lines.Add(new PlanLine("Storico", backfillText));
// Weight on the daily budget.
var ownAfter = own / thinning;
var share = budget > 0 ? ownAfter / budget : 0;
lines.Add(new PlanLine(
"Carico",
contacted
? $"circa {ItalianText.Decimal(ownAfter, ownAfter < 10 ? 1 : 0)} aperture del profilo al giorno, su {ItalianText.Number(budget)} disponibili ogni giorno per tutti gli account."
: "nessuno."));
if (overBudget)
{
warnings.Add(
$"Con {ItalianText.Count(contactable.Count, "account", "account")} e queste frequenze servirebbero circa {ItalianText.Number((long)Math.Round(totalDemand))} aperture di profili al giorno, "
+ $"ma il tetto è {ItalianText.Number(budget)}: i controlli si diradano (circa {ItalianText.Decimal(thinning, 1)} volte più radi), non si forzano.");
}
var sessionsPerDay = SessionsPerDay(profile, window);
var homeBudget = profile.Budgets.TryGetValue(ActionKind.Home, out var home) ? home.PerDay : 0;
if (contactable.Any(a => a.IsFollowed) && homeBudget > 0 && sessionsPerDay * options.SweepProbability > homeBudget)
{
warnings.Add($"Il tetto della home ({ItalianText.Number(homeBudget)} al giorno) è più basso del numero di sessioni: alcuni giri dei seguiti salteranno e i nuovi post arriveranno più tardi.");
}
if (profile.GradualStart && profile.RampUpDays > 0)
{
warnings.Add($"Con l'avvio graduale, nei primi {ItalianText.Count(profile.RampUpDays, "giorno", "giorni")} dopo il collegamento i tetti partono dalla metà: tutto è più lento.");
}
return new AccountPlanEstimate
{
Lines = lines,
Warnings = warnings,
Contacted = contacted,
ProfileCheckWanted = wanted,
ProfileCheckEvery = every,
StoryInterval = storyInterval,
StoryChecksPerDay = storyChecks,
ProfileOpensPerDay = ownAfter,
TotalProfileOpensPerDay = totalDemand,
DailyProfileBudget = budget,
ShareOfDailyBudget = share,
OverBudget = overBudget,
BackfillRemainingPosts = remaining,
BackfillDays = days,
};
}
/// <summary>Profile openings per day an account asks for (visits, reconciliations, tagged tab).</summary>
public static double ProfileOpensPerDay(Account account, TimeSpan window, EngineOptions? options = null)
{
ArgumentNullException.ThrowIfNull(account);
options ??= EngineOptions.Default;
if (!CheckPolicy.IsContactable(account))
{
return 0;
}
double visits;
if (CheckPolicy.WantsProfileChecks(account))
{
var interval = account.IsFollowed ? CheckPolicy.ProfileCheckInterval(account) : CheckPolicy.VisitInterval(account, window, options.MinimumStoryChecksPerDay);
visits = ChecksPerDay(interval * MeanCheckJitter, window);
}
else if (!account.IsFollowed && CheckPolicy.WantsStories(account))
{
visits = ChecksPerDay(CheckPolicy.StoryInterval(account, window, options.MinimumStoryChecksPerDay) * MeanStoryJitter, window);
}
else
{
visits = 0;
}
return (account.ContentTypes & ContentTypes.Tagged) != 0 ? visits * 2 : visits;
}
/// <summary>Checks a day at an interval, counting the morning catch-up after the night.</summary>
public static double ChecksPerDay(TimeSpan interval, TimeSpan window)
{
if (interval <= TimeSpan.Zero)
{
return 0;
}
if (interval >= TimeSpan.FromHours(24))
{
return 24 / interval.TotalHours;
}
return 1 + (window / interval);
}
/// <summary>Sessions a day with median session length and median pause.</summary>
public static double SessionsPerDay(CautionProfile profile, TimeSpan window)
{
ArgumentNullException.ThrowIfNull(profile);
var session = Math.Sqrt(profile.SessionMin.TotalMinutes * profile.SessionMax.TotalMinutes);
var pause = Math.Sqrt(profile.PauseMin.TotalMinutes * profile.PauseMax.TotalMinutes);
return window.TotalMinutes / (session + pause);
}
private static (string Text, int? Remaining, int? Days) Backfill(AccountPlanInput input, List<Account> all)
{
var account = input.Account;
var profile = input.Profile;
if (account.BackfillCompletedAt is { } done && account.State != AccountState.Backfilling)
{
return ($"completato il {ItalianText.Day(DateOnly.FromDateTime(done.UtcDateTime))}.", 0, 0);
}
if (account.Limits.Depth == HistoryDepth.FromDate && account.Limits.FromDate is { } from)
{
return ($"dipende da quanti post ci sono dopo il {ItalianText.Day(DateOnly.FromDateTime(from.UtcDateTime))}: lo saprò strada facendo.", null, null);
}
if (account.State is not (AccountState.Backfilling or AccountState.UpToDate) || !CheckPolicy.WantsProfileChecks(account))
{
return ("nessuno storico da scaricare con queste impostazioni.", null, null);
}
int? target = account.Limits.Depth == HistoryDepth.LastPosts
? account.Limits.LastPosts is { } last ? Math.Min(last, account.PostCount ?? last) : account.PostCount
: account.PostCount;
if (target is null)
{
return ("il numero dei post non è ancora noto: lo saprò dopo il primo controllo del profilo.", null, null);
}
var remaining = Math.Max(0, target.Value - input.ArchivedPosts);
if (remaining == 0)
{
return ("tutto già in libreria.", 0, 0);
}
var sharing = Math.Max(1, all.Count(a => a.State == AccountState.Backfilling && a.BackfillCompletedAt is null && CheckPolicy.IsContactable(a)));
var pagesPerDay = profile.Budgets.TryGetValue(ActionKind.BackfillPage, out var pages) ? pages.PerDay : 0;
var byBudget = pagesPerDay * input.Options.PostsPerBackfillPage / (double)sharing;
var perDay = Math.Min(Math.Min(account.Limits.BackfillPostsPerDay, profile.BackfillPostsPerAccountPerDay), byBudget);
if (perDay <= 0)
{
return ("fermo: il limite di storico al giorno è zero.", remaining, null);
}
var days = (int)Math.Ceiling(remaining / perDay);
var text = $"mancano {ItalianText.Count(remaining, "post", "post")}, servono circa {ItalianText.Count(days, "giorno", "giorni")} ({ItalianText.Number((long)Math.Floor(perDay))} post al giorno"
+ (sharing > 1 ? $", a turno con altri {ItalianText.Number(sharing - 1)} account" : string.Empty) + ").";
return (text, remaining, days);
}
private static string NotContactedText(Account account) => account.State switch
{
AccountState.ArchiveOnly => "«Solo archivio»: Febe non contatta questo account.",
AccountState.Paused => "in pausa: Febe non controlla questo account finché non lo riattivi.",
AccountState.Unreachable => "non raggiungibile: Febe non lo contatta finché non lo verifichi.",
_ => "Febe non contatta questo account.",
};
private static string Clock(TimeOnly time) => time.Hour.ToString(System.Globalization.CultureInfo.InvariantCulture) + ":" + time.Minute.ToString("00", System.Globalization.CultureInfo.InvariantCulture);
private static string Minutes(TimeSpan span) => ItalianText.Number((long)Math.Round(span.TotalMinutes));
/// <summary>Rounds an interval for display: to 5 minutes under 2 hours, to half an hour above.</summary>
private static TimeSpan Round(TimeSpan interval) => interval < TimeSpan.FromHours(2)
? TimeSpan.FromMinutes(Math.Max(5, Math.Round(interval.TotalMinutes / 5) * 5))
: TimeSpan.FromMinutes(Math.Round(interval.TotalMinutes / 30) * 30);
}
+138
View File
@@ -0,0 +1,138 @@
using Febe.Core.Abstractions;
using Febe.Core.Domain;
namespace Febe.Core.Engine;
/// <summary>Which reduction of the budgets is in force (spec §7.2 avvio graduale, §7.6 tetti dimezzati).</summary>
public enum BudgetReduction
{
None,
/// <summary>Gradual start: from half to full over the profile's ramp days.</summary>
GradualStart,
/// <summary>Halved for 48 hours after a throttle stop.</summary>
HalvedAfterThrottle,
}
/// <summary>The budgets in force at an instant, after the strongest reduction.</summary>
/// <param name="Budgets">Hourly and daily budget per category (data excluded).</param>
/// <param name="DataPerDayBytes">Daily download budget.</param>
/// <param name="BackfillPostsPerAccountPerDay">The profile's per-account backfill limit, reduced as the budgets.</param>
/// <param name="Factor">Multiplier applied to the profile's values (1 = full).</param>
/// <param name="Reduction">The reduction that determined <paramref name="Factor"/>.</param>
/// <param name="Until">When the reduction ends (end of the ramp or of the 48 hours), if any.</param>
public sealed record EffectiveBudgets(
IReadOnlyDictionary<ActionKind, Budget> Budgets,
long DataPerDayBytes,
int BackfillPostsPerAccountPerDay,
double Factor,
BudgetReduction Reduction,
DateTimeOffset? Until)
{
/// <summary>Daily limit of a category (bytes for data).</summary>
public long DailyLimit(ActionKind kind) => kind == ActionKind.DataDownload ? DataPerDayBytes : Budgets[kind].PerDay;
/// <summary>Hourly limit of a category; null for data, which only has a daily budget.</summary>
public long? HourlyLimit(ActionKind kind) => kind == ActionKind.DataDownload ? null : Budgets[kind].PerHour;
}
/// <summary>
/// Effective budgets (spec §7.4): when several reductions apply together (gradual start, halved budgets after a
/// throttle) the strongest wins, never their product.
/// </summary>
public static class BudgetLimits
{
/// <summary>Gradual start factor: 0.5 at <paramref name="rampStart"/>, rising linearly to 1 after the profile's ramp days.</summary>
public static double GradualStartFactor(CautionProfile profile, DateTimeOffset? rampStart, DateTimeOffset now)
{
ArgumentNullException.ThrowIfNull(profile);
if (!profile.GradualStart || rampStart is not { } start || profile.RampUpDays <= 0)
{
return 1;
}
var elapsed = (now - start).TotalDays;
if (elapsed < 0)
{
return 0.5;
}
return elapsed >= profile.RampUpDays ? 1 : 0.5 + (0.5 * elapsed / profile.RampUpDays);
}
/// <summary>0.5 while the 48 hours after a throttle stop last, otherwise 1.</summary>
public static double ThrottleFactor(DateTimeOffset? halvedUntil, DateTimeOffset now) =>
halvedUntil is { } until && now < until ? 0.5 : 1;
public static EffectiveBudgets Compute(CautionProfile profile, DateTimeOffset? rampStart, DateTimeOffset? halvedUntil, DateTimeOffset now)
{
ArgumentNullException.ThrowIfNull(profile);
var ramp = GradualStartFactor(profile, rampStart, now);
var throttle = ThrottleFactor(halvedUntil, now);
// The strongest reduction wins, never the product (spec §7.4).
var factor = Math.Min(ramp, throttle);
var reduction = factor >= 1 ? BudgetReduction.None
: throttle <= ramp ? BudgetReduction.HalvedAfterThrottle
: BudgetReduction.GradualStart;
DateTimeOffset? until = reduction switch
{
BudgetReduction.HalvedAfterThrottle => halvedUntil,
BudgetReduction.GradualStart => rampStart?.AddDays(profile.RampUpDays),
_ => null,
};
var budgets = new Dictionary<ActionKind, Budget>();
foreach (var (kind, budget) in profile.Budgets)
{
budgets[kind] = new Budget(Scale(budget.PerHour, factor), Scale(budget.PerDay, factor));
}
foreach (var kind in Enum.GetValues<ActionKind>())
{
if (kind != ActionKind.DataDownload && !budgets.ContainsKey(kind))
{
budgets[kind] = new Budget(0, 0);
}
}
return new EffectiveBudgets(
budgets,
ScaleBytes(profile.DataPerDayBytes, factor),
Scale(profile.BackfillPostsPerAccountPerDay, factor),
factor,
reduction,
until);
}
/// <summary>A budget times the factor, rounded down, never below 1 when the full budget is positive.</summary>
public static int Scale(int value, double factor) =>
value <= 0 ? 0 : Math.Max(1, (int)Math.Floor((value * factor) + 1e-9));
public static long ScaleBytes(long value, double factor) =>
value <= 0 ? 0 : Math.Max(1, (long)Math.Floor((value * factor) + 1e-6));
}
/// <summary>Use of one budget category, for the interface (spec §7.4, §7.9).</summary>
/// <param name="Kind">Category.</param>
/// <param name="UsedToday">Actions (bytes for data) of the current local day.</param>
/// <param name="LimitToday">Daily limit in force.</param>
/// <param name="UsedLastHour">Actions in the rolling last 60 minutes (null for data).</param>
/// <param name="LimitPerHour">Hourly limit in force (null for data).</param>
public sealed record BudgetStatus(ActionKind Kind, long UsedToday, long LimitToday, long? UsedLastHour, long? LimitPerHour)
{
/// <summary>Amber threshold of the interface (spec §7.4).</summary>
public const double AmberThreshold = 0.8;
public double DailyRatio => LimitToday <= 0 ? 1 : (double)UsedToday / LimitToday;
public double HourlyRatio => LimitPerHour is not > 0 ? 0 : (double)(UsedLastHour ?? 0) / LimitPerHour.Value;
/// <summary>At or above 80% of the daily or of the hourly budget.</summary>
public bool IsAmber => DailyRatio >= AmberThreshold || HourlyRatio >= AmberThreshold;
public bool DailyReached => UsedToday >= LimitToday;
public bool HourlyReached => LimitPerHour is { } limit && (UsedLastHour ?? 0) >= limit;
}
+192
View File
@@ -0,0 +1,192 @@
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Pacing;
namespace Febe.Core.Engine;
/// <summary>
/// Frequencies of spec §7.3 and the rules that say which accounts the engine may contact. A frequency expresses a
/// wish; the Governor decides what is possible.
/// </summary>
public static class CheckPolicy
{
/// <summary>Content types that need a visit of the profile page (posts, highlights, tagged posts, profile picture).</summary>
public const ContentTypes ProfileContent = ContentTypes.PostPhotos | ContentTypes.PostVideos | ContentTypes.Highlights
| ContentTypes.Tagged | ContentTypes.ProfilePicture;
/// <summary>
/// The engine contacts an account only when it is up to date or backfilling. «Solo archivio», «In pausa» (also
/// after the single download of «Tieni aggiornato» off) and «Non raggiungibile» are never contacted on the
/// engine's initiative.
/// </summary>
public static bool IsContactable(Account account)
{
ArgumentNullException.ThrowIfNull(account);
return account.State is AccountState.UpToDate or AccountState.Backfilling;
}
/// <summary>
/// Whether a «Controlla ora» of Alberto may contact the account: never «Solo archivio» and never a private profile
/// he does not follow (rule 6); paused and other unreachable accounts may be checked on request.
/// </summary>
public static bool AllowsManualCheck(Account account)
{
ArgumentNullException.ThrowIfNull(account);
return account.State switch
{
AccountState.ArchiveOnly => false,
AccountState.Unreachable => account.UnreachableReason is not UnreachableReason.PrivateNotFollowed,
_ => true,
};
}
public static bool WantsProfileChecks(Account account) => (account.ContentTypes & ProfileContent) != 0;
public static bool WantsStories(Account account) => (account.ContentTypes & ContentTypes.Stories) != 0;
/// <summary>
/// Interval between profile checks. Not followed: ~12 h / ~3 h / ~75 min (Su misura: the hours chosen). Followed: the
/// sweep discovers new posts, the profile check is only a reconciliation every 24 / 12 / 6 hours (Su misura: four
/// times the chosen interval, between 6 and 24 hours).
/// </summary>
public static TimeSpan ProfileCheckInterval(Account account)
{
ArgumentNullException.ThrowIfNull(account);
if (account.IsFollowed)
{
return account.Frequency switch
{
Frequency.Low => TimeSpan.FromHours(24),
Frequency.High => TimeSpan.FromHours(6),
Frequency.Custom when account.CustomPostInterval is { } custom =>
TimeSpan.FromTicks(Math.Clamp(custom.Ticks * 4, TimeSpan.FromHours(6).Ticks, TimeSpan.FromHours(24).Ticks)),
_ => TimeSpan.FromHours(12),
};
}
return account.Frequency switch
{
Frequency.Low => TimeSpan.FromHours(12),
Frequency.High => TimeSpan.FromMinutes(75),
Frequency.Custom when account.CustomPostInterval is { } custom && custom > TimeSpan.Zero => custom,
_ => TimeSpan.FromHours(3),
};
}
/// <summary>Maximum interval between two story checks: 8 / 6 / 3 hours (Su misura: the chosen one).</summary>
public static TimeSpan StoryMaxInterval(Account account)
{
ArgumentNullException.ThrowIfNull(account);
return account.Frequency switch
{
Frequency.Low => TimeSpan.FromHours(8),
Frequency.High => TimeSpan.FromHours(3),
Frequency.Custom when account.CustomStoryInterval is { } custom && custom > TimeSpan.Zero => custom,
_ => TimeSpan.FromHours(6),
};
}
/// <summary>
/// Story interval actually planned: the frequency's maximum, but never more than a third of the active window, so
/// that every account gets at least three story checks a day inside it (spec §7.3).
/// </summary>
public static TimeSpan StoryInterval(Account account, TimeSpan windowLength, int checksPerDay = 3)
{
var max = StoryMaxInterval(account);
if (windowLength <= TimeSpan.Zero || checksPerDay <= 0)
{
return max;
}
var cap = TimeSpan.FromTicks(windowLength.Ticks / checksPerDay);
return max < cap ? max : cap;
}
/// <summary>
/// Interval between visits of a profile that is not followed: its stories can be seen only from the profile, so a
/// visit serves both the profile check and the story check and comes at the shorter of the two intervals.
/// </summary>
public static TimeSpan VisitInterval(Account account, TimeSpan windowLength, int checksPerDay = 3)
{
var profile = ProfileCheckInterval(account);
if (account.IsFollowed || !WantsStories(account))
{
return profile;
}
var stories = StoryInterval(account, windowLength, checksPerDay);
return WantsProfileChecks(account) && profile < stories ? profile : stories;
}
/// <summary>Frequency weight of spec §7.2: High 3, Normal 2, Low 1 (Su misura from its interval).</summary>
public static double FrequencyWeight(Account account)
{
ArgumentNullException.ThrowIfNull(account);
return account.Frequency switch
{
Frequency.High => 3,
Frequency.Low => 1,
Frequency.Custom => ProfileCheckInterval(account with { IsFollowed = false }) switch
{
var i when i <= TimeSpan.FromHours(2) => 3,
var i when i <= TimeSpan.FromHours(6) => 2,
_ => 1,
},
_ => 2,
};
}
/// <summary>Weight of an account in the random order: frequency weight × (1 + delay ÷ interval), the ratio limited to 3.</summary>
public static double SelectionWeight(Account account, TimeSpan delay, TimeSpan interval)
{
var ratio = interval <= TimeSpan.Zero ? 0 : Math.Clamp(delay / interval, 0, 3);
return FrequencyWeight(account) * (1 + ratio);
}
/// <summary>The next check: interval × log-normal (median 1, σ 0.25, [0.6, 1.8]) (spec §7.2).</summary>
public static TimeSpan NextCheckDelay(IRandomSource random, TimeSpan interval) => random.JitteredInterval(interval);
/// <summary>
/// The next story check. «Intervallo massimo» is a maximum, so the jitter is drawn below it: interval × log-normal
/// with median 0.75, σ 0.25, truncated to [0.45, 1].
/// </summary>
public static TimeSpan NextStoryCheckDelay(IRandomSource random, TimeSpan maxInterval) =>
TimeSpan.FromTicks((long)(maxInterval.Ticks * random.TruncatedLogNormal(0.75, 0.25, 0.45, 1.0)));
/// <summary>
/// A random order of items by weight, never the same (Efraimidis–Spirakis: key = u^(1/w), highest first).
/// </summary>
public static IReadOnlyList<T> WeightedOrder<T>(IRandomSource random, IEnumerable<(T Item, double Weight)> items)
{
ArgumentNullException.ThrowIfNull(random);
return [.. items
.Select(i => (i.Item, Key: Math.Pow(1.0 - random.NextDouble(), 1.0 / Math.Max(i.Weight, 1e-6))))
.OrderByDescending(i => i.Key)
.Select(i => i.Item)];
}
/// <summary>Budget category a recipe needs first (to skip it when that budget is exhausted).</summary>
public static ActionKind CategoryOf(RecipeKind kind) => kind switch
{
RecipeKind.FollowingSweep => ActionKind.Home,
RecipeKind.AccountStories or RecipeKind.Highlight => ActionKind.StoryView,
RecipeKind.Backfill => ActionKind.BackfillPage,
RecipeKind.SinglePost => ActionKind.SinglePost,
RecipeKind.FollowingList => ActionKind.FollowingListPage,
_ => ActionKind.ProfileOpen,
};
public static RecipeKind RecipeOf(EngineTaskKind kind) => kind switch
{
EngineTaskKind.FollowingSweep => RecipeKind.FollowingSweep,
EngineTaskKind.AccountStories => RecipeKind.AccountStories,
EngineTaskKind.ProfileCheck => RecipeKind.ProfileCheck,
EngineTaskKind.Backfill => RecipeKind.Backfill,
EngineTaskKind.HighlightCheck => RecipeKind.Highlight,
EngineTaskKind.TaggedCheck => RecipeKind.Tagged,
EngineTaskKind.ReelsCheck => RecipeKind.Reels,
EngineTaskKind.SinglePost => RecipeKind.SinglePost,
EngineTaskKind.FollowingList => RecipeKind.FollowingList,
_ => throw new ArgumentOutOfRangeException(nameof(kind), kind, null),
};
}
+409
View File
@@ -0,0 +1,409 @@
using System.Globalization;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Storage;
namespace Febe.Core.Engine;
/// <summary>
/// The circuit breaker («interruttore», spec §7.6).
/// <list type="bullet">
/// <item>Throttle: closes the session at once; stops 1 hour the first time, 6 hours the second within 24 hours,
/// 24 hours the third; then halved budgets for 48 hours. Reopens by itself.</item>
/// <item>Challenge and disconnection: stop everything and never restart alone; only <see cref="ResumeAsync"/>
/// (Alberto's «Riprendi», after fixing things in the browser) reopens, and the resume starts the gradual start.</item>
/// </list>
/// Every stop is an <c>incident</c> row and a line of the Activity timeline; the state is restored from the database
/// at start-up. <see cref="Report"/> is synchronous (signals arrive from capture threads): the state changes at once
/// and the rows are written in order in the background (<see cref="FlushAsync"/> waits for them).
/// </summary>
public sealed class CircuitBreaker : ICircuitBreaker
{
/// <summary>Fixed stop durations (spec §7.6: not editable in version 1).</summary>
public static readonly IReadOnlyList<TimeSpan> ThrottleStops = [TimeSpan.FromHours(1), TimeSpan.FromHours(6), TimeSpan.FromHours(24)];
public static readonly TimeSpan HalvedPeriod = TimeSpan.FromHours(48);
public static readonly TimeSpan EscalationWindow = TimeSpan.FromHours(24);
public static readonly TimeSpan ProposalWindow = TimeSpan.FromDays(7);
public const int ProposalThreshold = 3;
private readonly IFebeStorage _storage;
private readonly IClock _clock;
private readonly EngineRuntime _runtime;
private readonly EngineEvents? _events;
private readonly Lock _gate = new();
private readonly List<DateTimeOffset> _recentThrottles = [];
private readonly List<long> _openIncidents = [];
private BreakerState _state = BreakerState.Normal;
private Task _tail = Task.CompletedTask;
private CircuitBreaker(IFebeStorage storage, IClock clock, EngineRuntime runtime, EngineEvents? events)
{
_storage = storage;
_clock = clock;
_runtime = runtime;
_events = events;
}
/// <summary>Raised after every change of state (outside the internal lock). The engine closes the session on it.</summary>
public event EventHandler<BreakerState>? StateChanged;
/// <summary>Current state; a throttle stop that has expired turns into Closed here.</summary>
public BreakerState State
{
get
{
BreakerState state;
bool changed;
lock (_gate)
{
changed = ExpireLocked(_clock.Now);
state = _state;
}
if (changed)
{
StateChanged?.Invoke(this, state);
}
return state;
}
}
/// <summary>Restores the state from the incidents table (open stops, recent throttles, halved budgets).</summary>
public static async Task<CircuitBreaker> LoadAsync(
IFebeStorage storage,
IClock clock,
EngineRuntime runtime,
EngineEvents? events = null,
CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(storage);
ArgumentNullException.ThrowIfNull(clock);
ArgumentNullException.ThrowIfNull(runtime);
var breaker = new CircuitBreaker(storage, clock, runtime, events);
var now = clock.Now;
var recent = await storage.Incidents.ListAsync(now - ProposalWindow - EscalationWindow, now.AddSeconds(1), ct).ConfigureAwait(false);
DateTimeOffset? halvedUntil = null;
foreach (var incident in recent.Where(i => i.Level == SignalLevel.Throttle))
{
breaker._recentThrottles.Add(incident.At);
if (incident.StoppedUntil is { } until && until + HalvedPeriod > now && (halvedUntil is null || until + HalvedPeriod > halvedUntil))
{
halvedUntil = until + HalvedPeriod;
}
}
var state = new BreakerState(BreakerStatus.Closed, null, null, halvedUntil);
foreach (var incident in await storage.Incidents.ListOpenAsync(ct).ConfigureAwait(false))
{
var signal = new Signal(incident.Level, incident.Signal, incident.Url, incident.At);
switch (incident.Level)
{
case SignalLevel.Challenge:
state = state with { Status = BreakerStatus.Challenge, Until = null, LastSignal = signal };
breaker._openIncidents.Add(incident.Id);
break;
case SignalLevel.Disconnect:
state = state with { Status = BreakerStatus.Disconnected, Until = null, LastSignal = signal };
breaker._openIncidents.Add(incident.Id);
break;
case SignalLevel.Throttle when incident.StoppedUntil is { } until && until > now:
if (state.Status == BreakerStatus.Closed)
{
state = state with { Status = BreakerStatus.Throttled, Until = until, LastSignal = signal };
}
breaker._openIncidents.Add(incident.Id);
break;
default:
// An expired throttle left open by a previous process: resolved at its planned end.
await storage.Incidents.ResolveAsync(incident.Id, incident.StoppedUntil ?? now, ct).ConfigureAwait(false);
break;
}
}
breaker._state = state;
return breaker;
}
public void Report(Signal signal) => _ = ReportAsync(signal);
/// <summary>Same as <see cref="Report"/>, returning when the incident and the event are stored.</summary>
public Task ReportAsync(Signal signal, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(signal);
BreakerState state;
Task persisted;
lock (_gate)
{
var now = _clock.Now;
ExpireLocked(now);
var sessionId = _runtime.CurrentSession?.SessionId;
switch (signal.Level)
{
case SignalLevel.Throttle:
if (_state.Status != BreakerStatus.Closed)
{
// Already stopped: a late signal of the same stop does not escalate it.
return _tail;
}
_recentThrottles.RemoveAll(t => t < now - ProposalWindow);
var within24Hours = _recentThrottles.Count(t => t > now - EscalationWindow);
var stop = ThrottleStops[Math.Min(within24Hours, ThrottleStops.Count - 1)];
_recentThrottles.Add(now);
var until = now + stop;
_state = new BreakerState(BreakerStatus.Throttled, until, signal, until + HalvedPeriod);
var withinWeek = _recentThrottles.Count(t => t > now - ProposalWindow);
persisted = EnqueueLocked(c => PersistThrottleAsync(signal, now, until, stop, sessionId, withinWeek, c));
break;
case SignalLevel.Challenge:
case SignalLevel.Disconnect:
var status = signal.Level == SignalLevel.Challenge ? BreakerStatus.Challenge : BreakerStatus.Disconnected;
if (_state.Status == status)
{
return _tail;
}
var wasThrottled = _state.Status == BreakerStatus.Throttled;
_state = new BreakerState(status, null, signal, _state.HalvedBudgetsUntil);
persisted = EnqueueLocked(c => PersistManualStopAsync(signal, now, wasThrottled, sessionId, c));
break;
default:
throw new ArgumentOutOfRangeException(nameof(signal), signal.Level, null);
}
state = _state;
}
StateChanged?.Invoke(this, state);
return persisted;
}
/// <summary>
/// «Riprendi» after a verification or a disconnection, once Alberto fixed things in the browser. Resolves the open
/// incidents and restarts the gradual start. False when the breaker is not in such a stop (a throttle stop has a
/// fixed duration and cannot be shortened).
/// </summary>
public async Task<bool> ResumeAsync(CancellationToken ct = default)
{
BreakerState state;
Task persisted;
lock (_gate)
{
var now = _clock.Now;
if (_state.Status is not (BreakerStatus.Challenge or BreakerStatus.Disconnected))
{
return false;
}
var previous = _state.Status;
_state = _state with { Status = BreakerStatus.Closed, Until = null };
_runtime.RampStart = now;
persisted = EnqueueLocked(c => PersistResumeAsync(previous, now, c));
state = _state;
}
await persisted.WaitAsync(ct).ConfigureAwait(false);
StateChanged?.Invoke(this, state);
return true;
}
/// <summary>Waits until every incident and event reported so far is stored.</summary>
public Task FlushAsync()
{
lock (_gate)
{
return _tail;
}
}
private bool ExpireLocked(DateTimeOffset now)
{
if (_state.Status != BreakerStatus.Throttled || _state.Until is not { } until || now < until)
{
return false;
}
_state = _state with { Status = BreakerStatus.Closed, Until = null };
var halvedUntil = _state.HalvedBudgetsUntil;
EnqueueLocked(ct => PersistThrottleEndAsync(until, halvedUntil, ct));
return true;
}
private Task EnqueueLocked(Func<CancellationToken, Task> work)
{
// Rows are written strictly in order: an incident is opened before it is resolved.
_tail = _tail.ContinueWith(_ => work(CancellationToken.None), CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default).Unwrap();
return _tail;
}
private async Task PersistThrottleAsync(Signal signal, DateTimeOffset now, DateTimeOffset until, TimeSpan stop, long? sessionId, int withinWeek, CancellationToken ct)
{
var incident = await _storage.Incidents.OpenAsync(
new Incident
{
At = signal.At,
Level = SignalLevel.Throttle,
Signal = signal.Code,
Url = signal.Url,
StoppedUntil = until,
SessionId = sessionId,
},
ct).ConfigureAwait(false);
lock (_gate)
{
_openIncidents.Add(incident.Id);
}
if (_events is null)
{
return;
}
var zone = _clock.LocalZone;
await _events.WriteAsync(
EventSeverity.Warning,
EngineEventCodes.ThrottleStop,
$"Instagram ha chiesto di rallentare (segnale {signal.Code}). Ho chiuso la sessione e mi fermo per {ItalianText.Duration(stop)}, "
+ $"fino {ItalianText.AtDay(until, now, zone)}. Poi i tetti restano dimezzati per 48 ore.",
sessionId: sessionId,
ct: ct).ConfigureAwait(false);
if (withinWeek >= ProposalThreshold)
{
var profile = _runtime.Profile.Kind;
var proposal = profile is CautionProfileKind.Prudent
? "Tre rallentamenti in sette giorni anche con il profilo «Prudente»: conviene ridurre gli account seguiti o abbassare le loro frequenze."
: $"Tre rallentamenti in sette giorni con il profilo «{ItalianText.Profile(profile)}»: conviene passare al profilo «{ItalianText.Profile(MorePrudent(profile))}» o ridurre gli account seguiti.";
await _events.WriteAsync(EventSeverity.Warning, EngineEventCodes.ProposeMorePrudence, proposal, ct: ct).ConfigureAwait(false);
}
}
private async Task PersistManualStopAsync(Signal signal, DateTimeOffset now, bool wasThrottled, long? sessionId, CancellationToken ct)
{
if (wasThrottled)
{
await ResolveOpenAsync(now, ct).ConfigureAwait(false);
}
var incident = await _storage.Incidents.OpenAsync(
new Incident
{
At = signal.At,
Level = signal.Level,
Signal = signal.Code,
Url = signal.Url,
SessionId = sessionId,
},
ct).ConfigureAwait(false);
lock (_gate)
{
_openIncidents.Add(incident.Id);
}
if (_events is null)
{
return;
}
var at = ItalianText.At(now, _clock.LocalZone);
var message = signal.Level == SignalLevel.Challenge
? $"Instagram chiede una verifica (segnale {signal.Code}). Ho fermato tutto {at} e non riparto da solo: apri il browser, completa la verifica a mano, poi premi «Riprendi»."
: $"La sessione di Instagram non c'è più (segnale {signal.Code}). Ho fermato tutto {at} e non provo a rientrare: apri il browser, accedi a mano, poi premi «Riprendi».";
await _events.WriteAsync(
EventSeverity.Error,
signal.Level == SignalLevel.Challenge ? EngineEventCodes.ChallengeStop : EngineEventCodes.DisconnectStop,
message,
sessionId: sessionId,
ct: ct).ConfigureAwait(false);
}
private async Task PersistThrottleEndAsync(DateTimeOffset until, DateTimeOffset? halvedUntil, CancellationToken ct)
{
await ResolveOpenAsync(until, ct).ConfigureAwait(false);
if (_events is null)
{
return;
}
var tail = halvedUntil is { } h
? $" Riprendo con i tetti dimezzati fino {ItalianText.AtDay(h, until, _clock.LocalZone)}."
: " Riprendo con i tetti normali.";
await _events.WriteAsync(EventSeverity.Info, EngineEventCodes.ThrottleEnd, "Fine del fermo per rallentamento." + tail, ct: ct).ConfigureAwait(false);
}
private async Task PersistResumeAsync(BreakerStatus previous, DateTimeOffset now, CancellationToken ct)
{
await ResolveOpenAsync(now, ct).ConfigureAwait(false);
await _storage.Settings.SetAsync(
EngineSettingKeys.RampStart,
now.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture),
ct).ConfigureAwait(false);
if (_events is null)
{
return;
}
var profile = _runtime.Profile;
var what = previous == BreakerStatus.Challenge ? "Ripresa dopo la verifica." : "Ripresa dopo il nuovo accesso.";
var ramp = profile.GradualStart && profile.RampUpDays > 0
? $" I tetti ripartono dalla metà e tornano pieni in {ItalianText.Count(profile.RampUpDays, "giorno", "giorni")}."
: string.Empty;
await _events.WriteAsync(EventSeverity.Success, EngineEventCodes.Resumed, what + ramp, ct: ct).ConfigureAwait(false);
}
private async Task ResolveOpenAsync(DateTimeOffset at, CancellationToken ct)
{
long[] open;
lock (_gate)
{
open = [.. _openIncidents];
_openIncidents.Clear();
}
foreach (var id in open)
{
await _storage.Incidents.ResolveAsync(id, at, ct).ConfigureAwait(false);
}
}
private static CautionProfileKind MorePrudent(CautionProfileKind kind) => kind switch
{
CautionProfileKind.Fast => CautionProfileKind.Balanced,
_ => CautionProfileKind.Prudent,
};
}
/// <summary>Stable codes of the engine's timeline events.</summary>
public static class EngineEventCodes
{
public const string ThrottleStop = "fermo-rallentamento";
public const string ThrottleEnd = "fine-fermo";
public const string ChallengeStop = "verifica-richiesta";
public const string DisconnectStop = "disconnessione";
public const string Resumed = "ripresa";
public const string ProposeMorePrudence = "proposta-prudenza";
public const string Paused = "pausa";
public const string Unpaused = "fine-pausa";
public const string BudgetReached = "tetto-raggiunto";
public const string SessionEnded = "sessione";
public const string BackfillCompleted = "storico-completato";
public const string BackfillWaiting = "storico-in-attesa";
public const string RecipeSuspended = "ricetta-sospesa";
public const string RecipeResumed = "ricetta-riattivata";
public const string FormatUnrecognized = "formato-non-riconosciuto";
public const string TargetNotFound = "bersaglio-non-trovato";
public const string AccountUnreachable = "account-non-raggiungibile";
public const string AccountPaused = "account-in-pausa";
public const string ManualCheck = "controlla-ora";
public const string RecipeFailed = "ricetta-fallita";
public const string SettingsChanged = "impostazioni-motore";
/// <summary>Prefix of the per-recipe lines («Appena fatto»): "ricetta." + recipe kind.</summary>
public const string RecipePrefix = "ricetta.";
}
+183
View File
@@ -0,0 +1,183 @@
using System.Globalization;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Pacing;
using Febe.Core.Storage;
namespace Febe.Core.Engine;
/// <summary>
/// The active window of one day (spec §7.2): the engine works only inside it. A window belongs to the local day it
/// starts on and may end after midnight (e.g. 06:30–00:30).
/// </summary>
public sealed record ActiveWindow(DateOnly Day, DateTimeOffset Start, DateTimeOffset End)
{
public TimeSpan Length => End - Start;
public bool Contains(DateTimeOffset instant) => instant >= Start && instant < End;
}
/// <summary>
/// Plans the active window of every day: the profile's start and end, each shifted every day by a random amount within
/// ± the profile's jitter (a normal draw with σ = jitter/2 truncated to ± jitter, never uniform), only on active
/// weekdays. The shifts of a day are derived from a seed drawn once from the engine's random source and persisted, so
/// they are deterministic per day and a restart never redraws them.
/// </summary>
public sealed class DayPlanner
{
private const double ShiftSigma = 0.5;
private static readonly TimeSpan MinimumLength = TimeSpan.FromMinutes(30);
private readonly ISettingsStore _settings;
private readonly IRandomSource _random;
private readonly Func<CautionProfile> _profile;
private readonly SemaphoreSlim _seedGate = new(1, 1);
private ulong? _seed;
public DayPlanner(ISettingsStore settings, IRandomSource random, Func<CautionProfile> profile, TimeZoneInfo zone)
{
_settings = settings ?? throw new ArgumentNullException(nameof(settings));
_random = random ?? throw new ArgumentNullException(nameof(random));
_profile = profile ?? throw new ArgumentNullException(nameof(profile));
Zone = zone ?? throw new ArgumentNullException(nameof(zone));
}
public TimeZoneInfo Zone { get; }
/// <summary>The window of a local day, or null when the weekday is not active.</summary>
public async Task<ActiveWindow?> GetWindowAsync(DateOnly day, CancellationToken ct = default)
{
var profile = _profile();
if (!profile.ActiveDays.Contains(day.DayOfWeek))
{
return null;
}
var seed = await GetSeedAsync(ct).ConfigureAwait(false);
return Compute(day, profile, seed, Zone);
}
/// <summary>The window containing <paramref name="instant"/> (today's, or yesterday's when it crosses midnight); null at night.</summary>
public async Task<ActiveWindow?> GetWindowAtAsync(DateTimeOffset instant, CancellationToken ct = default)
{
var today = LocalCalendar.Today(instant, Zone);
foreach (var day in new[] { today.AddDays(-1), today })
{
var window = await GetWindowAsync(day, ct).ConfigureAwait(false);
if (window is not null && window.Contains(instant))
{
return window;
}
}
return null;
}
/// <summary>The window containing <paramref name="instant"/>, or the next one to start; null only without active days.</summary>
public async Task<ActiveWindow?> GetNextWindowAsync(DateTimeOffset instant, CancellationToken ct = default)
{
var today = LocalCalendar.Today(instant, Zone);
for (var offset = -1; offset <= 8; offset++)
{
var window = await GetWindowAsync(today.AddDays(offset), ct).ConfigureAwait(false);
if (window is not null && window.End > instant)
{
return window;
}
}
return null;
}
/// <summary>The window of a day from a seed: pure, used by the planner and by tests.</summary>
public static ActiveWindow Compute(DateOnly day, CautionProfile profile, ulong seed, TimeZoneInfo zone)
{
ArgumentNullException.ThrowIfNull(profile);
var (startShift, endShift) = Shifts(seed, day);
var endDay = profile.WindowEnd > profile.WindowStart ? day : day.AddDays(1);
var baseStart = LocalCalendar.FromLocal(day.ToDateTime(profile.WindowStart), zone);
var baseEnd = LocalCalendar.FromLocal(endDay.ToDateTime(profile.WindowEnd), zone);
var start = baseStart + (profile.WindowJitter * startShift);
var end = baseEnd + (profile.WindowJitter * endShift);
if (end - start < MinimumLength)
{
end = start + MinimumLength;
}
// Whole seconds: easier to read and to compare with stored times (milliseconds).
return new ActiveWindow(day, TruncateToSecond(start), TruncateToSecond(end));
}
/// <summary>Daily shifts of start and end as fractions of the jitter, in [-1, 1].</summary>
internal static (double Start, double End) Shifts(ulong seed, DateOnly day)
{
var random = new SplitMixRandom(seed ^ ((ulong)day.DayNumber * 0x9E3779B97F4A7C15UL));
return (TruncatedNormal(random), TruncatedNormal(random));
}
private static double TruncatedNormal(IRandomSource random)
{
for (var attempt = 0; attempt < 64; attempt++)
{
var value = random.Normal(0, ShiftSigma);
if (value is >= -1 and <= 1)
{
return value;
}
}
return 0;
}
private static DateTimeOffset TruncateToSecond(DateTimeOffset value) =>
new(value.Ticks - (value.Ticks % TimeSpan.TicksPerSecond), value.Offset);
private async Task<ulong> GetSeedAsync(CancellationToken ct)
{
if (_seed is { } known)
{
return known;
}
await _seedGate.WaitAsync(ct).ConfigureAwait(false);
try
{
if (_seed is { } again)
{
return again;
}
var text = await _settings.GetAsync(EngineSettingKeys.WindowSeed, ct).ConfigureAwait(false);
if (!ulong.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var seed))
{
var high = (ulong)(_random.NextDouble() * uint.MaxValue);
var low = (ulong)(_random.NextDouble() * uint.MaxValue);
seed = (high << 32) | low;
await _settings.SetAsync(EngineSettingKeys.WindowSeed, seed.ToString(CultureInfo.InvariantCulture), ct).ConfigureAwait(false);
}
_seed = seed;
return seed;
}
finally
{
_seedGate.Release();
}
}
}
/// <summary>SplitMix64: a tiny deterministic generator for values derived from a stored seed.</summary>
internal sealed class SplitMixRandom(ulong seed) : IRandomSource
{
private ulong _state = seed;
public double NextDouble() => (Next() >> 11) * (1.0 / (1UL << 53));
private ulong Next()
{
var z = _state += 0x9E3779B97F4A7C15UL;
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9UL;
z = (z ^ (z >> 27)) * 0x94D049BB133111EBUL;
return z ^ (z >> 31);
}
}
+122
View File
@@ -0,0 +1,122 @@
using System.Runtime.CompilerServices;
using System.Threading.Channels;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Storage;
namespace Febe.Core.Engine;
/// <summary>What changed in the engine, for the interface (the web layer turns these into server-sent events).</summary>
public enum EngineNotificationKind
{
/// <summary>A line was added to the Activity timeline (<see cref="EngineNotification.Event"/>).</summary>
Event,
/// <summary>The mode of the engine changed (session started or ended, pause, stop, resume...): refresh the snapshot.</summary>
StateChanged,
/// <summary>A recipe started or ended inside a session: refresh the current activity and the budgets.</summary>
ActivityChanged,
}
/// <summary>A notification of the engine. Never contains captions, bodies, cookies or signed addresses.</summary>
public sealed record EngineNotification(EngineNotificationKind Kind, DateTimeOffset At, EventRecord? Event = null);
/// <summary>
/// Writes the readable timeline (spec §8.3 <c>event</c>) and publishes engine notifications to any number of
/// subscribers. Slow subscribers lose the oldest notifications, never block the engine.
/// </summary>
public sealed class EngineEvents
{
private const int SubscriberCapacity = 256;
private readonly IEventStore _store;
private readonly IClock _clock;
private readonly Lock _gate = new();
private readonly List<Channel<EngineNotification>> _subscribers = [];
public EngineEvents(IEventStore store, IClock clock)
{
_store = store ?? throw new ArgumentNullException(nameof(store));
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
}
/// <summary>Raised synchronously for every notification (after the event is stored).</summary>
public event EventHandler<EngineNotification>? Notified;
/// <summary>Stores an event of the timeline and publishes it.</summary>
public async Task<EventRecord> WriteAsync(
EventSeverity severity,
string code,
string message,
long? accountId = null,
long? sessionId = null,
CancellationToken ct = default)
{
var record = await _store.AppendAsync(
new EventRecord
{
At = _clock.Now,
Severity = severity,
Code = code,
Message = message,
AccountId = accountId,
SessionId = sessionId,
},
ct).ConfigureAwait(false);
Publish(new EngineNotification(EngineNotificationKind.Event, record.At, record));
return record;
}
/// <summary>Publishes a notification that is not a timeline line.</summary>
public void Publish(EngineNotificationKind kind) => Publish(new EngineNotification(kind, _clock.Now));
/// <summary>Notifications from now on, until <paramref name="ct"/> is cancelled.</summary>
public async IAsyncEnumerable<EngineNotification> SubscribeAsync([EnumeratorCancellation] CancellationToken ct = default)
{
var channel = Channel.CreateBounded<EngineNotification>(new BoundedChannelOptions(SubscriberCapacity)
{
FullMode = BoundedChannelFullMode.DropOldest,
SingleReader = true,
SingleWriter = false,
});
lock (_gate)
{
_subscribers.Add(channel);
}
try
{
while (await channel.Reader.WaitToReadAsync(ct).ConfigureAwait(false))
{
while (channel.Reader.TryRead(out var notification))
{
yield return notification;
}
}
}
finally
{
lock (_gate)
{
_subscribers.Remove(channel);
}
}
}
private void Publish(EngineNotification notification)
{
Channel<EngineNotification>[] subscribers;
lock (_gate)
{
subscribers = [.. _subscribers];
}
foreach (var subscriber in subscribers)
{
subscriber.Writer.TryWrite(notification);
}
Notified?.Invoke(this, notification);
}
}
+828
View File
@@ -0,0 +1,828 @@
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Pacing;
using Febe.Core.Storage;
namespace Febe.Core.Engine;
/// <summary>Outcome of «Controlla ora» (spec §7.8).</summary>
public enum CheckNowStatus
{
/// <summary>Put on top of the queue.</summary>
Queued,
/// <summary>Outside the active window: Alberto must confirm with <see cref="CheckNowResult.ConfirmationToken"/>.</summary>
NeedsConfirmation,
/// <summary>Not possible now (budget exhausted, engine stopped, account not contactable); the message says why.</summary>
Refused,
}
/// <summary>Answer to «Controlla ora»: an Italian message for the interface and, when needed, a confirmation token.</summary>
public sealed record CheckNowResult(CheckNowStatus Status, string Message, string? ConfirmationToken = null, DateTimeOffset? ExpectedAround = null);
/// <summary>Answer to «Riprendi».</summary>
public sealed record ResumeResult(bool Resumed, string Message);
/// <summary>
/// The engine (spec §7): a background loop that plans the day, opens sessions inside the active window, composes them
/// and rests between them. It only uses <see cref="IClock"/> for time and <see cref="IRandomSource"/> for chance, so the
/// same code runs under the virtual clock of the simulation.
/// </summary>
/// <remarks>
/// Commands from the interface (pause, resume, «Controlla ora», settings) are thread-safe and wake the loop.
/// While Alberto uses the browser, during a pause and during a stop of the breaker the engine opens nothing.
/// </remarks>
public sealed class EngineHost : IAsyncDisposable
{
private static readonly TimeSpan LongWait = TimeSpan.FromHours(6);
private readonly EngineServices _s;
private readonly IRecipeRunner _runner;
private readonly RecipeHealth _health;
private readonly RecentActions _recent = new();
private readonly SessionComposer _composer;
private readonly Lock _gate = new();
private readonly Dictionary<string, (long AccountId, DateTimeOffset Expires)> _confirmations = new(StringComparer.Ordinal);
private readonly Dictionary<long, DateTimeOffset> _outsideWindowAllowed = [];
private CancellationTokenSource _wake = new();
private CancellationTokenSource? _sessionCts;
private CancellationTokenSource? _loopCts;
private Task? _loop;
private bool _initialized;
private bool _manualWaiting;
private DateTimeOffset? _plannedAfterStop;
public EngineHost(EngineServices services, IRecipeRunner runner)
{
_s = services ?? throw new ArgumentNullException(nameof(services));
_runner = runner ?? throw new ArgumentNullException(nameof(runner));
_health = new RecipeHealth(services.Storage.Settings, services.Options.ConsecutiveFailuresToSuspend);
_composer = new SessionComposer(services, runner, _health, _recent, ManualDone);
Monitor = new EngineMonitor(services, this);
_s.Breaker.StateChanged += OnBreakerChanged;
}
public EngineServices Services => _s;
/// <summary>What the interface shows of the engine (Attività, sidebar, account settings panel).</summary>
public IEngineMonitor Monitor { get; }
/// <summary>Recipes suspended after repeated unrecognized formats, with when.</summary>
public IReadOnlyDictionary<RecipeKind, DateTimeOffset> SuspendedRecipes => _health.Suspended;
internal IReadOnlyList<RecentAction> RecentActions(int limit) => _recent.Snapshot(limit);
/// <summary>Starts the background loop.</summary>
public Task StartAsync(CancellationToken ct = default)
{
lock (_gate)
{
if (_loop is not null)
{
return Task.CompletedTask;
}
_loopCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
var token = _loopCts.Token;
_loop = Task.Run(() => RunAsync(token), CancellationToken.None);
}
return Task.CompletedTask;
}
/// <summary>Stops the loop; a session in progress ends as interrupted and the browser goes to rest.</summary>
public async Task StopAsync()
{
Task? loop;
lock (_gate)
{
loop = _loop;
_loopCts?.Cancel();
}
if (loop is not null)
{
try
{
await loop.ConfigureAwait(false);
}
catch (OperationCanceledException)
{
}
}
lock (_gate)
{
_loop = null;
_loopCts?.Dispose();
_loopCts = null;
}
}
public async ValueTask DisposeAsync()
{
_s.Breaker.StateChanged -= OnBreakerChanged;
await StopAsync().ConfigureAwait(false);
_wake.Dispose();
}
/// <summary>
/// The loop of the engine, until <paramref name="ct"/> is cancelled. <see cref="StartAsync"/> runs it in the
/// background; the simulation awaits it directly under the virtual clock.
/// </summary>
public async Task RunAsync(CancellationToken ct)
{
_s.Runtime.IsRunning = true;
try
{
await InitializeAsync(ct).ConfigureAwait(false);
while (true)
{
ct.ThrowIfCancellationRequested();
CancellationToken wake;
lock (_gate)
{
wake = _wake.Token;
}
var wait = await StepAsync(ct).ConfigureAwait(false);
if (wait is { } delay && delay > TimeSpan.Zero)
{
await WaitAsync(delay, wake, ct).ConfigureAwait(false);
}
}
}
finally
{
_s.Runtime.IsRunning = false;
_s.Events.Publish(EngineNotificationKind.StateChanged);
}
}
/// <summary>«Metti in pausa»: stops the engine until «Riprendi»; a session in progress ends now.</summary>
public async Task PauseAsync(CancellationToken ct = default)
{
if (_s.Runtime.IsPaused)
{
return;
}
_s.Runtime.IsPaused = true;
await _s.Storage.Settings.SetBoolAsync(EngineSettingKeys.Paused, true, ct).ConfigureAwait(false);
CancelSession();
Wake();
await _s.Events.WriteAsync(EventSeverity.Info, EngineEventCodes.Paused, "Messo in pausa da te: Febe non apre nulla finché non premi «Riprendi».", ct: ct).ConfigureAwait(false);
_s.Events.Publish(EngineNotificationKind.StateChanged);
}
/// <summary>
/// «Riprendi»: ends a pause and, after a verification or a disconnection that Alberto fixed in the browser, reopens
/// the breaker (with the gradual start). A throttle stop has a fixed length and is not shortened.
/// </summary>
public async Task<ResumeResult> ResumeAsync(CancellationToken ct = default)
{
var messages = new List<string>();
var resumed = false;
var breaker = _s.Breaker.State;
if (breaker.Status is BreakerStatus.Challenge or BreakerStatus.Disconnected)
{
resumed |= await _s.Breaker.ResumeAsync(ct).ConfigureAwait(false);
messages.Add(_s.Runtime.Profile.GradualStart ? "Ripreso dopo il fermo: i tetti ripartono dalla metà." : "Ripreso dopo il fermo.");
}
if (_s.Runtime.IsPaused)
{
_s.Runtime.IsPaused = false;
await _s.Storage.Settings.SetBoolAsync(EngineSettingKeys.Paused, false, ct).ConfigureAwait(false);
await _s.Events.WriteAsync(EventSeverity.Info, EngineEventCodes.Unpaused, "Ripreso dopo la pausa.", ct: ct).ConfigureAwait(false);
messages.Add("Ripreso dopo la pausa.");
resumed = true;
}
breaker = _s.Breaker.State;
if (breaker.Status == BreakerStatus.Throttled && breaker.Until is { } until)
{
messages.Add($"Il fermo per rallentamento dura fino {ItalianText.AtDay(until, _s.Clock.Now, _s.Clock.LocalZone)} e non si accorcia.");
}
else if (resumed)
{
// The first session after «Riprendi» comes 2–10 minutes later, as after a start.
var restart = _s.Clock.Now + _s.Random.Between(_s.Options.StartupDelayMin, _s.Options.StartupDelayMax);
if (_s.Runtime.NextSessionAt is not { } planned || planned < restart)
{
_s.Runtime.NextSessionAt = restart;
}
}
Wake();
_s.Events.Publish(EngineNotificationKind.StateChanged);
return new ResumeResult(resumed, messages.Count == 0 ? "Febe stava già lavorando." : string.Join(" ", messages));
}
/// <summary>
/// «Controlla ora» (spec §7.8): puts the check of an account on top of the queue. It still goes through the
/// Governor: with an exhausted budget Febe says so and does not do it. Outside the active window the first call
/// returns <see cref="CheckNowStatus.NeedsConfirmation"/> with a token; calling again with the token allows that
/// single check.
/// </summary>
public async Task<CheckNowResult> CheckNowAsync(long accountId, string? confirmationToken = null, CancellationToken ct = default)
{
var now = _s.Clock.Now;
var zone = _s.Clock.LocalZone;
var account = await _s.Storage.Accounts.GetAsync(accountId, ct).ConfigureAwait(false);
if (account is null)
{
return new CheckNowResult(CheckNowStatus.Refused, "Questo account non c'è più nell'elenco di Febe.");
}
var handle = ItalianText.Handle(account.Username);
if (!CheckPolicy.AllowsManualCheck(account))
{
return new CheckNowResult(
CheckNowStatus.Refused,
account.State == AccountState.ArchiveOnly
? $"{handle} è «Solo archivio»: Febe non lo contatta."
: $"{handle} è privato e non lo segui: Febe non lo apre.");
}
var breaker = _s.Breaker.State;
if (!breaker.AllowsSiteActions)
{
return new CheckNowResult(CheckNowStatus.Refused, Governor.BreakerMessage(breaker, now, zone));
}
if (_s.Runtime.IsPaused)
{
return new CheckNowResult(CheckNowStatus.Refused, "Febe è in pausa: premi «Riprendi» prima di chiedere un controllo.");
}
var kind = CheckPolicy.WantsProfileChecks(account) ? EngineTaskKind.ProfileCheck : EngineTaskKind.AccountStories;
var category = kind == EngineTaskKind.ProfileCheck ? ActionKind.ProfileOpen : ActionKind.StoryView;
var budget = await _s.Governor.EvaluateBudgetAsync(category, accountId, ct).ConfigureAwait(false);
if (!budget.Granted && budget.Reason != DenialReason.AccountNotContactable)
{
return new CheckNowResult(CheckNowStatus.Refused, (budget.Message ?? "Tetto raggiunto.") + " Il controllo non parte.");
}
var window = await _s.Planner.GetWindowAtAsync(now, ct).ConfigureAwait(false);
var floor = PauseFloor();
if (window is null)
{
bool confirmed;
lock (_gate)
{
PruneLocked(now);
confirmed = confirmationToken is not null
&& _confirmations.TryGetValue(confirmationToken, out var pending)
&& pending.AccountId == accountId;
if (confirmed)
{
_confirmations.Remove(confirmationToken!);
_outsideWindowAllowed[accountId] = now + TimeSpan.FromHours(1);
}
}
if (!confirmed)
{
var token = Guid.NewGuid().ToString("N");
lock (_gate)
{
_confirmations[token] = (accountId, now + _s.Options.ManualConfirmationLifetime);
}
var next = await _s.Planner.GetNextWindowAsync(now, ct).ConfigureAwait(false);
var resumes = next is null ? string.Empty : $" Di solito riprende {ItalianText.Around(next.Start, now, zone)}.";
return new CheckNowResult(
CheckNowStatus.NeedsConfirmation,
$"Sei fuori dalla fascia oraria, quando Febe non apre nulla da solo.{resumes} Confermi un solo controllo di {handle} adesso?",
token);
}
await EnqueueManualAsync(kind, accountId, now, ct).ConfigureAwait(false);
var expected = floor is { } f && f > now ? f : now;
await _s.Events.WriteAsync(
EventSeverity.Info,
EngineEventCodes.ManualCheck,
$"Controllo di {handle} fuori fascia, confermato da te: parte {(expected > now ? ItalianText.Around(expected, now, zone) : "adesso")}.",
accountId,
ct: ct).ConfigureAwait(false);
Wake();
return new CheckNowResult(CheckNowStatus.Queued, $"Controllo di {handle} confermato: è l'unico che Febe fa fuori fascia.", null, expected);
}
await EnqueueManualAsync(kind, accountId, now, ct).ConfigureAwait(false);
Wake();
if (_s.Runtime.CurrentSession is not null)
{
return new CheckNowResult(CheckNowStatus.Queued, $"Controllo di {handle} in cima alla coda: parte in questa sessione.", null, now);
}
// The next session comes as soon as the pause floor allows (spec §7.2: the floor always holds).
var start = floor is { } minimum && minimum > now ? minimum : now;
await _s.Events.WriteAsync(
EventSeverity.Info,
EngineEventCodes.ManualCheck,
$"Controllo di {handle} chiesto da te: in cima alla coda.",
accountId,
ct: ct).ConfigureAwait(false);
return new CheckNowResult(
CheckNowStatus.Queued,
start > now
? $"Controllo di {handle} in cima alla coda: parte {ItalianText.Around(start, now, zone)}, dopo la pausa minima fra due sessioni."
: $"Controllo di {handle} in cima alla coda: parte adesso.",
null,
start);
}
/// <summary>«Leggi l'elenco dei seguiti» (spec §4.2): read at human pace inside the budgets, possibly over several sessions.</summary>
public async Task RequestFollowingListAsync(CancellationToken ct = default)
{
var now = _s.Clock.Now;
Volatile.Write(ref _manualWaiting, true);
await _s.Storage.Tasks.EnqueueAsync(
new EngineTask
{
Kind = EngineTaskKind.FollowingList,
DueAt = now,
Priority = _s.Options.ManualPriority,
IsManual = true,
CreatedAt = now,
},
ct).ConfigureAwait(false);
Wake();
_s.Events.Publish(EngineNotificationKind.StateChanged);
}
/// <summary>Accounts were added, removed or changed: the queue is brought in step before the next session.</summary>
public async Task NotifyAccountsChangedAsync(CancellationToken ct = default)
{
await _composer.SyncQueueAsync(ct).ConfigureAwait(false);
Wake();
_s.Events.Publish(EngineNotificationKind.StateChanged);
}
/// <summary>Alberto started or finished using the browser: when he starts, the session in progress ends at once.</summary>
public void NotifyUserDrivingChanged()
{
if (_s.Runtime.UserIsDriving)
{
CancelSession();
}
Wake();
_s.Events.Publish(EngineNotificationKind.StateChanged);
}
/// <summary>Reactivates a recipe suspended after repeated unrecognized formats (after the reader was updated).</summary>
public async Task<bool> ResumeRecipeAsync(RecipeKind kind, CancellationToken ct = default)
{
var resumed = await _health.ResumeAsync(kind, ct).ConfigureAwait(false);
if (resumed)
{
await _s.Events.WriteAsync(
EventSeverity.Info,
EngineEventCodes.RecipeResumed,
$"«{ItalianText.Capitalize(SessionComposer.RecipeName(kind))}» riattivato.",
ct: ct).ConfigureAwait(false);
Wake();
}
return resumed;
}
/// <summary>Stores and applies new engine settings, then replans.</summary>
public async Task ApplySettingsAsync(EngineSettings settings, CancellationToken ct = default)
{
await _s.ApplySettingsAsync(settings, ct).ConfigureAwait(false);
Wake();
}
private async Task InitializeAsync(CancellationToken ct)
{
if (_initialized)
{
return;
}
var now = _s.Clock.Now;
var store = _s.Storage;
await _health.LoadAsync(ct).ConfigureAwait(false);
// A session left open by a process that ended abruptly closes at its last action.
var lastAction = await store.ActionLog.GetLastActionAtAsync(null, ct).ConfigureAwait(false);
var last = await store.Sessions.GetLastAsync(ct).ConfigureAwait(false);
if (last is { EndedAt: null })
{
var end = lastAction is { } a && a > last.StartedAt && a <= now ? a : last.StartedAt;
await store.Sessions.CloseInterruptedAsync(end, ct).ConfigureAwait(false);
last = await store.Sessions.GetLastAsync(ct).ConfigureAwait(false);
}
await store.Tasks.RequeueRunningAsync(ct).ConfigureAwait(false);
// A restart never brings the next session earlier than a program that stayed on would have.
var lastEnd = Max(last?.EndedAt, lastAction);
_s.Runtime.LastSessionEnd = lastEnd;
var persisted = await store.Settings.GetInt64Async(EngineSettingKeys.NextSession, ct).ConfigureAwait(false);
var next = now + _s.Random.Between(_s.Options.StartupDelayMin, _s.Options.StartupDelayMax);
if (persisted is { } ms && DateTimeOffset.FromUnixTimeMilliseconds(ms) > next)
{
next = DateTimeOffset.FromUnixTimeMilliseconds(ms);
}
if (PauseFloor() is { } floor && floor > next)
{
next = floor;
}
_s.Runtime.NextSessionAt = next;
_s.Runtime.StartedAt = now;
_s.Runtime.HadSessionSinceStart = false;
await store.Settings.SetInt64Async(EngineSettingKeys.NextSession, next.ToUnixTimeMilliseconds(), ct).ConfigureAwait(false);
await _composer.SyncQueueAsync(ct).ConfigureAwait(false);
_initialized = true;
_s.Events.Publish(EngineNotificationKind.StateChanged);
}
/// <summary>One turn of the loop: runs a session when one is due, otherwise says how long to wait.</summary>
private async Task<TimeSpan?> StepAsync(CancellationToken ct)
{
var now = _s.Clock.Now;
var runtime = _s.Runtime;
if (runtime.IsPaused)
{
return LongWait;
}
var breaker = _s.Breaker.State;
if (!breaker.AllowsSiteActions)
{
if (breaker.Status == BreakerStatus.Throttled && breaker.Until is { } until)
{
// After the stop the engine does not restart on the dot: a few minutes later, as after a start.
if (_plannedAfterStop != until)
{
_plannedAfterStop = until;
var restart = until + _s.Random.Between(_s.Options.StartupDelayMin, _s.Options.StartupDelayMax);
if (runtime.NextSessionAt is not { } planned || planned < restart)
{
runtime.NextSessionAt = restart;
}
}
return until - now;
}
return LongWait;
}
if (runtime.UserIsDriving || runtime.IsConnected == false)
{
// Alberto at the browser, or no Instagram session yet: look again in a while.
return _s.Options.UserDrivingPoll;
}
var floor = PauseFloor();
var window = await _s.Planner.GetWindowAtAsync(now, ct).ConfigureAwait(false);
if (window is null)
{
// Night: nothing on the engine's initiative. The only exception is a «Controlla ora» Alberto confirmed.
var manual = await FindConfirmedManualAsync(now, ct).ConfigureAwait(false);
if (manual is not null)
{
if (floor is { } f && f > now)
{
return f - now;
}
await RunSessionAsync(null, manual, ct).ConfigureAwait(false);
return null;
}
var next = await _s.Planner.GetNextWindowAsync(now, ct).ConfigureAwait(false);
if (next is null)
{
return LongWait;
}
var target = runtime.NextSessionAt is { } planned && planned > next.Start ? planned : next.Start;
if (floor is { } minimum && minimum > target)
{
target = minimum;
}
runtime.NextSessionAt = target;
return target - now;
}
var start = runtime.NextSessionAt ?? now;
if (start > now && Volatile.Read(ref _manualWaiting))
{
// «Controlla ora»: the next session comes as soon as the pause floor allows.
start = now;
}
if (floor is { } pauseFloor && pauseFloor > start)
{
start = pauseFloor;
}
if (start > now)
{
runtime.NextSessionAt = start;
return (start < window.End ? start : window.End) - now;
}
if (window.End - now < _s.Options.MinimumSessionRoom)
{
return window.End - now;
}
await RunSessionAsync(window, null, ct).ConfigureAwait(false);
return null;
}
private async Task RunSessionAsync(ActiveWindow? window, EngineTask? outsideWindowTask, CancellationToken ct)
{
var s = _s;
var profile = s.Runtime.Profile;
var start = s.Clock.Now;
var mood = s.Random.SessionMood();
var plannedEnd = start + s.Random.Between(profile.SessionMin, profile.SessionMax);
if (window is not null && plannedEnd > window.End)
{
plannedEnd = window.End;
}
var record = await s.Storage.Sessions.StartAsync(start, ct).ConfigureAwait(false);
var context = new SessionContext(record.Id, mood, start, plannedEnd, outsideWindowTask?.AccountId);
using var sessionCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
lock (_gate)
{
_sessionCts = sessionCts;
}
s.Runtime.CurrentSession = context;
s.Runtime.HadSessionSinceStart = true;
Volatile.Write(ref _manualWaiting, false);
s.Runtime.NextSessionAt = null;
s.Events.Publish(EngineNotificationKind.StateChanged);
var outcome = SessionOutcome.Completed;
var interrupted = false;
try
{
// A stop that arrived while the session was opening ends it before anything is done.
if (!s.Breaker.State.AllowsSiteActions || s.Runtime.IsPaused || s.Runtime.UserIsDriving)
{
sessionCts.Cancel();
}
var summary = await _composer.RunAsync(context, outsideWindowTask, sessionCts.Token).ConfigureAwait(false);
if (summary.StoppedEarly || !s.Breaker.State.AllowsSiteActions || s.Runtime.IsPaused || s.Runtime.UserIsDriving)
{
outcome = StopOutcome();
}
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
outcome = StopOutcome();
}
catch (OperationCanceledException)
{
outcome = SessionOutcome.Interrupted;
interrupted = true;
throw;
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
outcome = SessionOutcome.Failed;
await s.Events.WriteAsync(
EventSeverity.Error,
EngineEventCodes.RecipeFailed,
$"La sessione si è chiusa per un errore imprevisto ({ex.GetType().Name}). Riprendo alla prossima.",
sessionId: record.Id,
ct: CancellationToken.None).ConfigureAwait(false);
}
finally
{
lock (_gate)
{
_sessionCts = null;
}
s.Runtime.CurrentSession = null;
s.Runtime.Activity = null;
await EndSessionAsync(record, context, outcome, outsideWindowTask, interrupted).ConfigureAwait(false);
}
}
private async Task EndSessionAsync(SessionRecord record, SessionContext context, SessionOutcome outcome, EngineTask? outsideWindowTask, bool interrupted)
{
var s = _s;
var ct = CancellationToken.None;
// Rest on the empty page, except when the page must stay as it is (verification, disconnection) or Alberto is
// using the browser (spec §6.1, §7.6).
var breaker = s.Breaker.State;
var keepPage = breaker.Status is BreakerStatus.Challenge or BreakerStatus.Disconnected || s.Runtime.UserIsDriving;
if (!keepPage)
{
try
{
await _runner.RestAsync(ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
await s.Events.WriteAsync(
EventSeverity.Warning,
EngineEventCodes.RecipeFailed,
$"Non sono riuscito a portare il browser sulla pagina vuota ({ex.GetType().Name}).",
sessionId: record.Id,
ct: ct).ConfigureAwait(false);
}
}
var end = s.Clock.Now;
var summaryText = $"{ItalianText.Count(context.ActionCount, "azione", "azioni")}, {ItalianText.Count(context.NewEntries, "contenuto nuovo", "contenuti nuovi")}";
var writes = new List<Task> { s.Storage.Sessions.EndAsync(record.Id, end, outcome, context.ActionCount, summaryText, ct) };
s.Runtime.LastSessionEnd = end;
if (outsideWindowTask?.AccountId is { } manualAccount)
{
ManualDone(manualAccount);
}
if (interrupted)
{
await Task.WhenAll(writes).ConfigureAwait(false);
return;
}
var pause = s.Random.Between(s.Runtime.Profile.PauseMin, s.Runtime.Profile.PauseMax);
var next = end + pause;
s.Runtime.NextSessionAt = next;
writes.Add(s.Storage.Settings.SetInt64Async(EngineSettingKeys.NextSession, next.ToUnixTimeMilliseconds(), ct));
if ((await s.Storage.Accounts.ListAsync(ct).ConfigureAwait(false)).Any(a => a.IsFollowed && CheckPolicy.IsContactable(a)))
{
writes.Add(_composer.EnsureSweepTaskAsync(next, ct));
}
var length = ItalianText.Duration(end - record.StartedAt);
var tail = outcome switch
{
SessionOutcome.Throttled => " Chiusa per un rallentamento chiesto da Instagram.",
SessionOutcome.Stopped => " Chiusa prima del previsto.",
SessionOutcome.Failed => " Chiusa per un errore.",
_ => string.Empty,
};
writes.Add(s.Events.WriteAsync(
outcome == SessionOutcome.Completed ? EventSeverity.Info : EventSeverity.Warning,
EngineEventCodes.SessionEnded,
$"Sessione di {length}: {summaryText}.{tail}",
sessionId: record.Id,
ct: ct));
await Task.WhenAll(writes).ConfigureAwait(false);
s.Events.Publish(EngineNotificationKind.StateChanged);
}
private SessionOutcome StopOutcome() =>
_s.Breaker.State.Status == BreakerStatus.Throttled ? SessionOutcome.Throttled : SessionOutcome.Stopped;
private DateTimeOffset? PauseFloor() =>
_s.Runtime.LastSessionEnd is { } end ? end + _s.Runtime.Profile.PauseMin : null;
private async Task<EngineTask?> FindConfirmedManualAsync(DateTimeOffset now, CancellationToken ct)
{
Dictionary<long, DateTimeOffset> allowed;
lock (_gate)
{
PruneLocked(now);
if (_outsideWindowAllowed.Count == 0)
{
return null;
}
allowed = new Dictionary<long, DateTimeOffset>(_outsideWindowAllowed);
}
var due = await _s.Storage.Tasks.PeekDueAsync(now, 100, ct).ConfigureAwait(false);
return due.FirstOrDefault(t => t.IsManual && t.AccountId is { } id && allowed.ContainsKey(id));
}
private void ManualDone(long accountId)
{
lock (_gate)
{
_outsideWindowAllowed.Remove(accountId);
}
}
private void PruneLocked(DateTimeOffset now)
{
foreach (var token in _confirmations.Where(c => c.Value.Expires <= now).Select(c => c.Key).ToList())
{
_confirmations.Remove(token);
}
foreach (var account in _outsideWindowAllowed.Where(c => c.Value <= now).Select(c => c.Key).ToList())
{
_outsideWindowAllowed.Remove(account);
}
}
private async Task EnqueueManualAsync(EngineTaskKind kind, long accountId, DateTimeOffset now, CancellationToken ct)
{
Volatile.Write(ref _manualWaiting, true);
await _s.Storage.Tasks.EnqueueAsync(
new EngineTask
{
Kind = kind,
AccountId = accountId,
DueAt = now,
Priority = _s.Options.ManualPriority,
IsManual = true,
CreatedAt = now,
},
ct).ConfigureAwait(false);
}
private void OnBreakerChanged(object? sender, BreakerState state)
{
// Signals arrive on capture threads: the engine is never run inline on them (it may need the browser to answer).
// The composer also checks the breaker before every recipe, so the session stops at once either way.
CancellationTokenSource? session = null;
if (!state.AllowsSiteActions)
{
lock (_gate)
{
session = _sessionCts;
}
}
_ = Task.Run(() =>
{
Cancel(session);
Wake();
_s.Events.Publish(EngineNotificationKind.StateChanged);
});
}
private void CancelSession()
{
CancellationTokenSource? session;
lock (_gate)
{
session = _sessionCts;
}
Cancel(session);
}
private static void Cancel(CancellationTokenSource? session)
{
try
{
session?.Cancel();
}
catch (ObjectDisposedException)
{
}
}
/// <summary>Wakes the loop if it is waiting; the wait it was in is cancelled synchronously.</summary>
private void Wake()
{
CancellationTokenSource old;
lock (_gate)
{
old = _wake;
_wake = new CancellationTokenSource();
}
// The old source is not disposed: the loop may still hold its (now cancelled) token.
old.Cancel();
}
private async Task WaitAsync(TimeSpan delay, CancellationToken wake, CancellationToken ct)
{
if (wake.IsCancellationRequested)
{
return;
}
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, wake);
try
{
await _s.Clock.Delay(delay, linked.Token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
// Woken by a command: look again.
}
}
private static DateTimeOffset? Max(DateTimeOffset? a, DateTimeOffset? b) =>
a is null ? b : b is null ? a : a > b ? a : b;
}
+71
View File
@@ -0,0 +1,71 @@
namespace Febe.Core.Engine;
/// <summary>
/// Tuning of the engine that is not part of a caution profile. Values marked «ipotesi» depend on how Instagram
/// behaves and must be confirmed in M0 (spec §6.6, rule 10): they are configuration, not facts.
/// </summary>
public sealed record EngineOptions
{
public static EngineOptions Default { get; } = new();
/// <summary>
/// Ipotesi da confermare in M0 (H3): posts loaded by one page of history. Used only to estimate how many pages
/// the per-account daily backfill limit allows and how many days a backfill needs; the Governor counts real posts.
/// </summary>
public int PostsPerBackfillPage { get; init; } = 12;
/// <summary>
/// Ipotesi da confermare in M0 (H2): the stories bar read by the Giro dei seguiti tells which followed profiles
/// have active stories, so a completed sweep counts as a story check of every followed account it did not flag.
/// With false, followed accounts get explicit story checks at their interval.
/// </summary>
public bool SweepCoversFollowedStories { get; init; } = true;
/// <summary>«Lo storico non corre più veloce dei download» (spec §6.3): backfill of an account waits above this many pending files.</summary>
public int BackfillMaxPendingDownloads { get; init; } = 60;
/// <summary>Minimum distance between two counted actions at the «naturale» gesture pace (spec §7.2); scaled by the pace.</summary>
public TimeSpan MinimumSpacing { get; init; } = TimeSpan.FromSeconds(4);
/// <summary>The first session starts 2–10 minutes after the program (spec §7.2).</summary>
public TimeSpan StartupDelayMin { get; init; } = TimeSpan.FromMinutes(2);
public TimeSpan StartupDelayMax { get; init; } = TimeSpan.FromMinutes(10);
/// <summary>«Una sessione comincia di norma con il Giro dei seguiti»: probability of opening with the sweep.</summary>
public double SweepProbability { get; init; } = 0.9;
/// <summary>«Circa una su tre si limita al giro e alle storie».</summary>
public double LightSessionProbability { get; init; } = 1.0 / 3.0;
/// <summary>«Qualche pagina di storico» per session: drawn in this range (log-normal), then limited by the account's daily maximum.</summary>
public int BackfillPagesMin { get; init; } = 3;
public int BackfillPagesMax { get; init; } = 12;
/// <summary>Wait between two recipes of a session («fra un account e l'altro da 1 a 4 s»), times mood and pace.</summary>
public TimeSpan BetweenRecipesMin { get; init; } = TimeSpan.FromSeconds(1);
public TimeSpan BetweenRecipesMax { get; init; } = TimeSpan.FromSeconds(4);
/// <summary>Consecutive «formato non riconosciuto» (or «bersaglio non trovato») outcomes that suspend a recipe (spec §6.4).</summary>
public int ConsecutiveFailuresToSuspend { get; init; } = 3;
/// <summary>How long a «Controlla ora» confirmation token stays valid outside the active window (spec §7.8).</summary>
public TimeSpan ManualConfirmationLifetime { get; init; } = TimeSpan.FromMinutes(10);
/// <summary>How often the idle engine looks again whether Alberto has finished using the browser.</summary>
public TimeSpan UserDrivingPoll { get; init; } = TimeSpan.FromSeconds(30);
/// <summary>A session does not start when less than this remains of the active window.</summary>
public TimeSpan MinimumSessionRoom { get; init; } = TimeSpan.FromMinutes(1);
/// <summary>With «Storie» on, every account gets at least this many story checks per day inside the window (spec §7.3).</summary>
public int MinimumStoryChecksPerDay { get; init; } = 3;
/// <summary>Priority of «Controlla ora» and of other commands of Alberto in the queue.</summary>
public int ManualPriority { get; init; } = 100;
/// <summary>Priority of story checks flagged by the stories bar.</summary>
public int FlaggedStoriesPriority { get; init; } = 10;
}
+170
View File
@@ -0,0 +1,170 @@
using Febe.Core.Abstractions;
using Febe.Core.Domain;
namespace Febe.Core.Engine;
/// <summary>
/// Live state shared by the engine host, the Governor, the circuit breaker and the monitor. Everything that must
/// survive a restart is persisted by its owner; this object only mirrors it in memory. Thread-safe.
/// </summary>
public sealed class EngineRuntime
{
private readonly Lock _gate = new();
private readonly Func<bool> _userIsDriving;
private readonly Func<bool>? _isConnected;
private CautionProfile _profile = CautionProfile.Prudent;
private DateTimeOffset? _rampStart;
private SessionContext? _session;
private string? _activity;
private DateTimeOffset? _nextSessionAt;
private DateTimeOffset? _lastSessionEnd;
private bool _paused;
private bool _running;
/// <param name="userIsDriving">True while Alberto uses the browser (<see cref="IBrowserHost.UserIsDriving"/>).</param>
/// <param name="isConnected">Whether the Instagram session exists in the browser; null when unknown.</param>
public EngineRuntime(Func<bool>? userIsDriving = null, Func<bool>? isConnected = null)
{
_userIsDriving = userIsDriving ?? (() => false);
_isConnected = isConnected;
}
/// <summary>The effective caution profile (settings applied).</summary>
public CautionProfile Profile
{
get { lock (_gate) { return _profile; } }
set { lock (_gate) { _profile = value ?? throw new ArgumentNullException(nameof(value)); } }
}
/// <summary>Start of the gradual start: first connection or last resolved verification/disconnection.</summary>
public DateTimeOffset? RampStart
{
get { lock (_gate) { return _rampStart; } }
set { lock (_gate) { _rampStart = value; } }
}
/// <summary>«Metti in pausa» is active.</summary>
public bool IsPaused
{
get { lock (_gate) { return _paused; } }
set { lock (_gate) { _paused = value; } }
}
/// <summary>True while Alberto uses the browser: the engine does not act.</summary>
public bool UserIsDriving => _userIsDriving();
/// <summary>Whether the browser holds an Instagram session; null when the host does not say.</summary>
public bool? IsConnected => _isConnected?.Invoke();
/// <summary>The session in progress, if any. The Governor refuses every site action without one.</summary>
public SessionContext? CurrentSession
{
get { lock (_gate) { return _session; } }
set { lock (_gate) { _session = value; } }
}
/// <summary>What the engine is doing now, in Italian («Sto guardando le storie di @marta.demo»).</summary>
public string? Activity
{
get { lock (_gate) { return _activity; } }
set { lock (_gate) { _activity = value; } }
}
/// <summary>Planned start of the next session (indicative: «verso le»).</summary>
public DateTimeOffset? NextSessionAt
{
get { lock (_gate) { return _nextSessionAt; } }
set { lock (_gate) { _nextSessionAt = value; } }
}
/// <summary>End of the last session (the pause floor counts from here).</summary>
public DateTimeOffset? LastSessionEnd
{
get { lock (_gate) { return _lastSessionEnd; } }
set { lock (_gate) { _lastSessionEnd = value; } }
}
/// <summary>The background loop of the engine is running.</summary>
public bool IsRunning
{
get { lock (_gate) { return _running; } }
set { lock (_gate) { _running = value; } }
}
/// <summary>When the loop started (the first session comes 2–10 minutes later).</summary>
public DateTimeOffset? StartedAt
{
get { lock (_gate) { return _startedAt; } }
set { lock (_gate) { _startedAt = value; } }
}
/// <summary>A session has started since the loop started.</summary>
public bool HadSessionSinceStart
{
get { lock (_gate) { return _hadSession; } }
set { lock (_gate) { _hadSession = value; } }
}
private DateTimeOffset? _startedAt;
private bool _hadSession;
}
/// <summary>The session in progress (spec §7.2), handed to every recipe.</summary>
public sealed class SessionContext : ISessionContext
{
private int _actions;
private int _newEntries;
private long _manualAccountId = -1;
public SessionContext(long sessionId, double mood, DateTimeOffset startedAt, DateTimeOffset plannedEnd, long? outsideWindowAccountId = null)
{
SessionId = sessionId;
Mood = mood;
StartedAt = startedAt;
PlannedEnd = plannedEnd;
OutsideWindowAccountId = outsideWindowAccountId;
if (outsideWindowAccountId is { } id)
{
_manualAccountId = id;
}
}
/// <summary>
/// The account of the «Controlla ora» being run, if any: a paused or unreachable account (not private and
/// unfollowed, not «Solo archivio») may be checked on Alberto's request.
/// </summary>
public long? ManualAccountId
{
get
{
var value = Interlocked.Read(ref _manualAccountId);
return value < 0 ? null : value;
}
internal set => Interlocked.Exchange(ref _manualAccountId, value ?? OutsideWindowAccountId ?? -1);
}
public long SessionId { get; }
public double Mood { get; }
public DateTimeOffset StartedAt { get; }
public DateTimeOffset PlannedEnd { get; }
/// <summary>
/// Set only for a «Controlla ora» confirmed by Alberto outside the active window (spec §7.8): the Governor allows
/// actions on this account only, and only during this session.
/// </summary>
public long? OutsideWindowAccountId { get; }
/// <summary>Counted actions granted in this session.</summary>
public int ActionCount => Volatile.Read(ref _actions);
/// <summary>New entries reported by the recipes of this session.</summary>
public int NewEntries => Volatile.Read(ref _newEntries);
internal void CountAction() => Interlocked.Increment(ref _actions);
internal void AddNewEntries(int count) => Interlocked.Add(ref _newEntries, count);
}
+148
View File
@@ -0,0 +1,148 @@
using System.Globalization;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Storage;
namespace Febe.Core.Engine;
/// <summary>
/// The parts of the engine that recipes and the interface need before the engine host exists: runtime state,
/// timeline, day planner, circuit breaker and Governor. Built in two steps because the real recipe runner needs the
/// Governor and the breaker, and the host needs the recipe runner:
/// <code>
/// var services = await EngineServices.CreateAsync(storage, clock, random);
/// var runner = new SomeRecipeRunner(services.Governor, services.Breaker, ...);
/// await using var engine = new EngineHost(services, runner);
/// await engine.StartAsync(ct);
/// </code>
/// </summary>
public sealed class EngineServices
{
private EngineServices(
IFebeStorage storage,
IClock clock,
IRandomSource random,
EngineOptions options,
EngineRuntime runtime,
EngineEvents events,
DayPlanner planner,
CircuitBreaker breaker,
Governor governor,
EngineSettings settings)
{
Storage = storage;
Clock = clock;
Random = random;
Options = options;
Runtime = runtime;
Events = events;
Planner = planner;
Breaker = breaker;
Governor = governor;
Settings = settings;
}
public IFebeStorage Storage { get; }
public IClock Clock { get; }
public IRandomSource Random { get; }
public EngineOptions Options { get; }
public EngineRuntime Runtime { get; }
public EngineEvents Events { get; }
public DayPlanner Planner { get; }
public CircuitBreaker Breaker { get; }
/// <summary>The Governor: <see cref="IGovernor"/> for recipes, <see cref="IDataBudget"/> for the download queue.</summary>
public Governor Governor { get; }
/// <summary>Current engine and caution settings.</summary>
public EngineSettings Settings { get; private set; }
/// <summary>
/// Loads settings, pause flag, gradual-start origin and breaker state from the database. When the gradual start has
/// no origin yet (first run after the first connection) it starts now.
/// </summary>
/// <param name="storage">The database.</param>
/// <param name="clock">Time source (virtual in tests and simulation).</param>
/// <param name="random">Random source (seeded in tests and simulation).</param>
/// <param name="options">Tuning; <see cref="EngineOptions.Default"/> when null.</param>
/// <param name="userIsDriving">True while Alberto uses the browser.</param>
/// <param name="isConnected">Whether the browser holds an Instagram session; null when unknown.</param>
/// <param name="ct">Cancellation.</param>
public static async Task<EngineServices> CreateAsync(
IFebeStorage storage,
IClock clock,
IRandomSource random,
EngineOptions? options = null,
Func<bool>? userIsDriving = null,
Func<bool>? isConnected = null,
CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(storage);
ArgumentNullException.ThrowIfNull(clock);
ArgumentNullException.ThrowIfNull(random);
options ??= EngineOptions.Default;
var runtime = new EngineRuntime(userIsDriving, isConnected);
var settings = await EngineSettingsStore.LoadAsync(storage.Settings, ct).ConfigureAwait(false);
runtime.Profile = settings.EffectiveProfile;
runtime.IsPaused = await storage.Settings.GetBoolAsync(EngineSettingKeys.Paused, false, ct).ConfigureAwait(false);
var rampStart = await storage.Settings.GetInt64Async(EngineSettingKeys.RampStart, ct).ConfigureAwait(false);
if (rampStart is null)
{
rampStart = clock.Now.ToUnixTimeMilliseconds();
await storage.Settings.SetInt64Async(EngineSettingKeys.RampStart, rampStart, ct).ConfigureAwait(false);
}
runtime.RampStart = DateTimeOffset.FromUnixTimeMilliseconds(rampStart.Value);
var events = new EngineEvents(storage.Events, clock);
var planner = new DayPlanner(storage.Settings, random, () => runtime.Profile, clock.LocalZone);
// Draws (or loads) the seed of the daily windows now, so that later readers never consume randomness.
await planner.GetNextWindowAsync(clock.Now, ct).ConfigureAwait(false);
var breaker = await CircuitBreaker.LoadAsync(storage, clock, runtime, events, ct).ConfigureAwait(false);
var governor = new Governor(storage, breaker, runtime, planner, clock, options, events);
return new EngineServices(storage, clock, random, options, runtime, events, planner, breaker, governor, settings);
}
/// <summary>
/// Validates and stores new engine settings (mockup 07) and applies them at once. Throws
/// <see cref="ArgumentException"/> with Italian messages when a value is outside the limits of spec §7.5.
/// </summary>
public async Task ApplySettingsAsync(EngineSettings settings, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(settings);
await EngineSettingsStore.SaveAsync(Storage.Settings, settings, ct).ConfigureAwait(false);
Settings = settings;
Runtime.Profile = settings.EffectiveProfile;
await Events.WriteAsync(
EventSeverity.Info,
EngineEventCodes.SettingsChanged,
$"Impostazioni del motore cambiate: profilo «{ItalianText.Profile(settings.ProfileKind)}».",
ct: ct).ConfigureAwait(false);
Events.Publish(EngineNotificationKind.StateChanged);
}
/// <summary>
/// The first connection to Instagram (spec §7.2): the gradual start begins now. Later connections do not restart it;
/// the resume after a verification or a disconnection does, through <see cref="CircuitBreaker.ResumeAsync"/>.
/// </summary>
public async Task NotifyFirstConnectionAsync(CancellationToken ct = default)
{
var now = Clock.Now;
Runtime.RampStart = now;
await Storage.Settings.SetAsync(
EngineSettingKeys.RampStart,
now.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture),
ct).ConfigureAwait(false);
}
}
+379
View File
@@ -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);
}
+410
View File
@@ -0,0 +1,410 @@
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Pacing;
using Febe.Core.Storage;
namespace Febe.Core.Engine;
/// <summary>
/// The Governor (spec §7.4): the single point through which every engine action toward the site passes (rule 7).
/// For every request it checks, in order: breaker state, pause and Alberto using the browser, active window, session
/// in progress, hourly (rolling 60 minutes) and daily (local calendar day) budget of the category, minimum spacing from
/// the previous counted action, the account's own limits. Counts come from <c>action_log</c>, never from memory, so a
/// restart resets nothing. Granted actions are recorded there with session and account.
/// </summary>
/// <remarks>
/// <para>The minimum spacing is a pace, not a refusal: <see cref="RequestAsync"/> waits for it (on <see cref="IClock"/>)
/// and then grants; <see cref="EvaluateAsync"/> reports it as <see cref="DenialReason.MinimumSpacing"/>.</para>
/// <para>CDN downloads are not site actions: <see cref="ActionKind.DataDownload"/> only checks the daily byte budget, also
/// during a stop (spec §7.6: queued downloads may complete), and bytes are recorded with <see cref="RecordAsync"/>.</para>
/// </remarks>
public sealed class Governor : IGovernor, IDataBudget
{
private static readonly TimeSpan Hour = TimeSpan.FromMinutes(60);
private readonly IFebeStorage _storage;
private readonly ICircuitBreaker _breaker;
private readonly EngineRuntime _runtime;
private readonly DayPlanner _planner;
private readonly IClock _clock;
private readonly EngineOptions _options;
private readonly EngineEvents? _events;
private readonly SemaphoreSlim _gate = new(1, 1);
private readonly Lock _noticeGate = new();
private readonly HashSet<(ActionKind, DateOnly)> _dailyNoticesSent = [];
public Governor(
IFebeStorage storage,
ICircuitBreaker breaker,
EngineRuntime runtime,
DayPlanner planner,
IClock clock,
EngineOptions? options = null,
EngineEvents? events = null)
{
_storage = storage ?? throw new ArgumentNullException(nameof(storage));
_breaker = breaker ?? throw new ArgumentNullException(nameof(breaker));
_runtime = runtime ?? throw new ArgumentNullException(nameof(runtime));
_planner = planner ?? throw new ArgumentNullException(nameof(planner));
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
_options = options ?? EngineOptions.Default;
_events = events;
}
/// <summary>Raised for every refusal of <see cref="RequestAsync"/> (the monitor shows the last one).</summary>
public event EventHandler<Permit>? Denied;
/// <summary>Raised for every granted site action.</summary>
public event EventHandler<Permit>? Granted;
/// <summary>Minimum distance between two counted actions at the current gesture pace.</summary>
public TimeSpan MinimumSpacing => _options.MinimumSpacing * GesturePaceFactors.For(_runtime.Profile.Pace);
/// <summary>Budgets in force at <paramref name="now"/>: profile, gradual start and halved budgets, strongest reduction.</summary>
public EffectiveBudgets GetEffectiveBudgets(DateTimeOffset now) =>
BudgetLimits.Compute(_runtime.Profile, _runtime.RampStart, _breaker.State.HalvedBudgetsUntil, now);
public async Task<Permit> RequestAsync(ActionKind kind, long? accountId, CancellationToken ct)
{
if (kind == ActionKind.DataDownload)
{
return await EvaluateDataAsync(accountId, ct).ConfigureAwait(false);
}
await _gate.WaitAsync(ct).ConfigureAwait(false);
try
{
while (true)
{
var now = _clock.Now;
var permit = await EvaluateCoreAsync(kind, accountId, now, ct).ConfigureAwait(false);
if (permit.Reason == DenialReason.MinimumSpacing && permit.RetryAfter is { } retry)
{
// Spacing is a pace: wait for it, then look again (the state may have changed meanwhile).
await _clock.Delay(retry - now, ct).ConfigureAwait(false);
continue;
}
if (!permit.Granted)
{
Denied?.Invoke(this, permit);
await NoticeDailyBudgetAsync(permit, now, ct).ConfigureAwait(false);
return permit;
}
var session = _runtime.CurrentSession;
await _storage.ActionLog.AppendAsync(
new ActionLogRecord { At = now, Category = kind, AccountId = accountId, SessionId = session?.SessionId },
ct).ConfigureAwait(false);
session?.CountAction();
Granted?.Invoke(this, permit);
return permit;
}
}
finally
{
_gate.Release();
}
}
/// <summary>
/// What <see cref="RequestAsync"/> would answer now, without recording or waiting (spacing is reported as a
/// refusal with its retry time). The scheduler uses it to skip work whose budget is exhausted.
/// </summary>
public Task<Permit> EvaluateAsync(ActionKind kind, long? accountId, CancellationToken ct = default) =>
kind == ActionKind.DataDownload
? EvaluateDataAsync(accountId, ct)
: EvaluateCoreAsync(kind, accountId, _clock.Now, ct);
/// <summary>Budget checks only (no breaker, window, session or spacing): «is there room today for this?».</summary>
public async Task<Permit> EvaluateBudgetAsync(ActionKind kind, long? accountId, CancellationToken ct = default)
{
if (kind == ActionKind.DataDownload)
{
return await EvaluateDataAsync(accountId, ct).ConfigureAwait(false);
}
var now = _clock.Now;
return await CheckBudgetsAsync(kind, accountId, now, GetEffectiveBudgets(now), ct).ConfigureAwait(false)
?? Permit.Grant(kind, accountId);
}
/// <summary>
/// How many more actions of a category the budgets allow right now (the smaller of the hourly and daily rest).
/// For recipes that need room for several actions, e.g. «the budget must allow at least ten stories» (spec §6.3).
/// </summary>
public async Task<long> RemainingAsync(ActionKind kind, CancellationToken ct = default)
{
if (kind == ActionKind.DataDownload)
{
return await RemainingTodayAsync(ct).ConfigureAwait(false);
}
var now = _clock.Now;
var budget = GetEffectiveBudgets(now).Budgets[kind];
var (dayStart, dayEnd) = LocalCalendar.DayBounds(now, _clock.LocalZone);
var tick = TimeSpan.FromMilliseconds(1);
var today = await _storage.ActionLog.SumAsync(kind, dayStart, dayEnd, ct: ct).ConfigureAwait(false);
var lastHour = await _storage.ActionLog.SumAsync(kind, now - Hour + tick, now + tick, ct: ct).ConfigureAwait(false);
return Math.Max(0, Math.Min(budget.PerDay - today, budget.PerHour - lastHour));
}
/// <summary>Use of every category with the limits in force (spec §7.4, §7.9).</summary>
public async Task<IReadOnlyList<BudgetStatus>> GetBudgetStatusAsync(CancellationToken ct = default)
{
var now = _clock.Now;
var budgets = GetEffectiveBudgets(now);
var usage = await _storage.ActionLog.GetUsageAsync(now, _clock.LocalZone, ct).ConfigureAwait(false);
return [.. Enum.GetValues<ActionKind>().Select(kind =>
{
var used = usage.TryGetValue(kind, out var u) ? u : default;
return kind == ActionKind.DataDownload
? new BudgetStatus(kind, used.Today, budgets.DataPerDayBytes, null, null)
: new BudgetStatus(kind, used.Today, budgets.Budgets[kind].PerDay, used.LastHour, budgets.Budgets[kind].PerHour);
})];
}
public async Task<long> RemainingTodayAsync(CancellationToken ct)
{
var now = _clock.Now;
var (start, end) = LocalCalendar.DayBounds(now, _clock.LocalZone);
var used = await _storage.ActionLog.SumAsync(ActionKind.DataDownload, start, end, ct: ct).ConfigureAwait(false);
return Math.Max(0, GetEffectiveBudgets(now).DataPerDayBytes - used);
}
public async Task RecordAsync(long bytes, long? accountId, CancellationToken ct)
{
ArgumentOutOfRangeException.ThrowIfNegative(bytes);
if (bytes == 0)
{
return;
}
await _storage.ActionLog.AppendAsync(
new ActionLogRecord
{
At = _clock.Now,
Category = ActionKind.DataDownload,
AccountId = accountId,
SessionId = _runtime.CurrentSession?.SessionId,
Amount = bytes,
},
ct).ConfigureAwait(false);
}
private async Task<Permit> EvaluateDataAsync(long? accountId, CancellationToken ct)
{
var remaining = await RemainingTodayAsync(ct).ConfigureAwait(false);
if (remaining > 0)
{
return Permit.Grant(ActionKind.DataDownload, accountId);
}
var now = _clock.Now;
var limit = GetEffectiveBudgets(now).DataPerDayBytes;
return Permit.Deny(
ActionKind.DataDownload,
accountId,
DenialReason.DailyBudgetReached,
$"Raggiunto il tetto giornaliero dei dati scaricati ({ItalianText.Bytes(limit)}): gli scaricamenti riprendono domani.",
LocalCalendar.DayBounds(now, _clock.LocalZone).End);
}
private async Task<Permit> EvaluateCoreAsync(ActionKind kind, long? accountId, DateTimeOffset now, CancellationToken ct)
{
var zone = _clock.LocalZone;
// 1. Breaker.
var breaker = _breaker.State;
if (!breaker.AllowsSiteActions)
{
return Permit.Deny(kind, accountId, DenialReason.BreakerOpen, BreakerMessage(breaker, now, zone), breaker.Until);
}
// Pause and Alberto at the browser: the engine does not act.
if (_runtime.IsPaused)
{
return Permit.Deny(kind, accountId, DenialReason.Paused, "Febe è in pausa: premi «Riprendi» per ripartire.");
}
if (_runtime.UserIsDriving)
{
return Permit.Deny(kind, accountId, DenialReason.UserIsDriving, "Stai usando il browser di Febe: il motore aspetta che tu abbia finito.");
}
// 2. Active window; the only exception is a «Controlla ora» confirmed outside it, for that account only.
var session = _runtime.CurrentSession;
var manualOutside = session?.OutsideWindowAccountId is { } manualAccount && accountId == manualAccount;
if (!manualOutside)
{
var window = await _planner.GetWindowAtAsync(now, ct).ConfigureAwait(false);
if (window is null)
{
var next = await _planner.GetNextWindowAsync(now, ct).ConfigureAwait(false);
var when = next is null ? "nei giorni attivi" : ItalianText.Around(next.Start, now, zone);
return Permit.Deny(kind, accountId, DenialReason.OutsideActiveWindow, $"Fuori dalla fascia oraria: Febe riprende {when}.", next?.Start);
}
}
// 3. Session in progress.
if (session is null)
{
return Permit.Deny(kind, accountId, DenialReason.NoSession, "Nessuna sessione in corso: le azioni verso il sito partono solo dentro una sessione.");
}
// 4. Budgets of the category, then 5. spacing, then 6. the account's own limits.
var budgets = GetEffectiveBudgets(now);
var denial = await CheckCategoryBudgetsAsync(kind, accountId, now, budgets, ct).ConfigureAwait(false);
if (denial is not null)
{
return denial;
}
var last = await _storage.ActionLog.GetLastActionAtAsync(null, ct).ConfigureAwait(false);
var spacing = MinimumSpacing;
if (last is { } previous && now - previous < spacing)
{
return Permit.Deny(
kind,
accountId,
DenialReason.MinimumSpacing,
$"Troppo vicino all'azione precedente: fra due azioni passano almeno {ItalianText.Decimal(spacing.TotalSeconds, 1)} secondi.",
previous + spacing);
}
return await CheckAccountAsync(kind, accountId, now, budgets, session, ct).ConfigureAwait(false)
?? Permit.Grant(kind, accountId);
}
private async Task<Permit?> CheckBudgetsAsync(ActionKind kind, long? accountId, DateTimeOffset now, EffectiveBudgets budgets, CancellationToken ct) =>
await CheckCategoryBudgetsAsync(kind, accountId, now, budgets, ct).ConfigureAwait(false)
?? await CheckAccountAsync(kind, accountId, now, budgets, _runtime.CurrentSession, ct).ConfigureAwait(false);
private async Task<Permit?> CheckCategoryBudgetsAsync(ActionKind kind, long? accountId, DateTimeOffset now, EffectiveBudgets budgets, CancellationToken ct)
{
var zone = _clock.LocalZone;
var budget = budgets.Budgets[kind];
var (dayStart, dayEnd) = LocalCalendar.DayBounds(now, zone);
var today = await _storage.ActionLog.SumAsync(kind, dayStart, dayEnd, ct: ct).ConfigureAwait(false);
var tick = TimeSpan.FromMilliseconds(1);
// Rolling window (now − 60 min, now], in the milliseconds of the database.
var lastHour = await _storage.ActionLog.SumAsync(kind, now - Hour + tick, now + tick, ct: ct).ConfigureAwait(false);
var used = new BudgetUsage(lastHour, today);
if (used.Today + 1 > budget.PerDay)
{
var tomorrow = LocalCalendar.DayBounds(now, zone).End;
var next = await _planner.GetNextWindowAsync(tomorrow, ct).ConfigureAwait(false);
var retry = next is null || next.Start < tomorrow ? tomorrow : next.Start;
return Permit.Deny(
kind,
accountId,
DenialReason.DailyBudgetReached,
$"Raggiunto il tetto giornaliero delle {ItalianText.Category(kind)} ({ItalianText.Number(budget.PerDay)} al giorno): la categoria riprende domani.",
retry);
}
if (used.LastHour + 1 > budget.PerHour)
{
var retry = await HourlyRetryAsync(kind, now, budget.PerHour, ct).ConfigureAwait(false);
return Permit.Deny(
kind,
accountId,
DenialReason.HourlyBudgetReached,
$"Raggiunto il tetto orario delle {ItalianText.Category(kind)} ({ItalianText.Number(budget.PerHour)} all'ora): la categoria riprende {ItalianText.Around(retry, now, zone)}.",
retry);
}
return null;
}
private async Task<Permit?> CheckAccountAsync(
ActionKind kind,
long? accountId,
DateTimeOffset now,
EffectiveBudgets budgets,
SessionContext? session,
CancellationToken ct)
{
if (accountId is not { } id)
{
return null;
}
var account = await _storage.Accounts.GetAsync(id, ct).ConfigureAwait(false);
if (account is null)
{
return Permit.Deny(kind, accountId, DenialReason.AccountNotContactable, "Questo account non c'è più nell'elenco di Febe.");
}
var manual = session?.ManualAccountId == id;
if (!CheckPolicy.IsContactable(account) && !(manual && CheckPolicy.AllowsManualCheck(account)))
{
return Permit.Deny(kind, accountId, DenialReason.AccountNotContactable, NotContactableMessage(account));
}
if (kind == ActionKind.BackfillPage)
{
var zone = _clock.LocalZone;
var limit = Math.Min(account.Limits.BackfillPostsPerDay, budgets.BackfillPostsPerAccountPerDay);
var (dayStart, dayEnd) = LocalCalendar.DayBounds(now, zone);
var today = await _storage.Entries.CountDiscoveredAsync(id, EntryKind.Post, dayStart, dayEnd, ct).ConfigureAwait(false);
if (today >= limit)
{
return Permit.Deny(
kind,
accountId,
DenialReason.AccountLimitReached,
$"Raggiunto il limite di storico di {ItalianText.Handle(account.Username)} per oggi ({ItalianText.Number(limit)} post): riprende domani.",
dayEnd);
}
}
return null;
}
/// <summary>When the oldest action that keeps the rolling hour full leaves the window.</summary>
private async Task<DateTimeOffset> HourlyRetryAsync(ActionKind kind, DateTimeOffset now, int perHour, CancellationToken ct)
{
var recent = await _storage.ActionLog.ListAsync(now - Hour, now.AddMilliseconds(1), ct).ConfigureAwait(false);
var times = recent.Where(r => r.Category == kind && r.At > now - Hour).Select(r => r.At).OrderBy(t => t).ToList();
var excess = times.Count - perHour;
return excess >= 0 && excess < times.Count ? times[excess] + Hour : now + TimeSpan.FromMinutes(1);
}
private async Task NoticeDailyBudgetAsync(Permit permit, DateTimeOffset now, CancellationToken ct)
{
if (_events is null || permit.Reason != DenialReason.DailyBudgetReached)
{
return;
}
var day = LocalCalendar.Today(now, _clock.LocalZone);
lock (_noticeGate)
{
if (!_dailyNoticesSent.Add((permit.Kind, day)))
{
return;
}
}
await _events.WriteAsync(EventSeverity.Info, EngineEventCodes.BudgetReached, permit.Message ?? string.Empty, ct: ct).ConfigureAwait(false);
}
internal static string BreakerMessage(BreakerState state, DateTimeOffset now, TimeZoneInfo zone) => state.Status switch
{
BreakerStatus.Throttled when state.Until is { } until =>
$"Instagram ha chiesto di rallentare: Febe è fermo fino {ItalianText.AtDay(until, now, zone)}.",
BreakerStatus.Challenge => "Instagram chiede una verifica: Febe è fermo finché non la completi nel browser e premi «Riprendi».",
BreakerStatus.Disconnected => "La sessione di Instagram è chiusa: Febe è fermo finché non accedi di nuovo nel browser e premi «Riprendi».",
_ => "Febe è fermo.",
};
private static string NotContactableMessage(Account account) => account.State switch
{
AccountState.ArchiveOnly => $"{ItalianText.Handle(account.Username)} è «Solo archivio»: Febe non lo contatta.",
AccountState.Paused => $"{ItalianText.Handle(account.Username)} è in pausa: Febe non lo controlla.",
AccountState.Unreachable => $"{ItalianText.Handle(account.Username)} non è raggiungibile: Febe non lo contatta.",
_ => $"Febe non contatta {ItalianText.Handle(account.Username)}.",
};
}
+237
View File
@@ -0,0 +1,237 @@
using System.Globalization;
using System.Text;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
namespace Febe.Core.Engine;
/// <summary>
/// Italian wording used by the engine for events, denials and the monitor (spec §10.4): dot for thousands, comma for
/// decimals, «verso le» for future engine times. Independent of the process culture, so it reads the same in Docker
/// (invariant globalization) and on Windows.
/// </summary>
public static class ItalianText
{
private static readonly string[] Months =
[
"gennaio", "febbraio", "marzo", "aprile", "maggio", "giugno",
"luglio", "agosto", "settembre", "ottobre", "novembre", "dicembre",
];
private static readonly string[] Weekdays = ["domenica", "lunedì", "martedì", "mercoledì", "giovedì", "venerdì", "sabato"];
/// <summary>Whole number with dots for thousands: 7.682.</summary>
public static string Number(long value)
{
var digits = Math.Abs(value).ToString(CultureInfo.InvariantCulture);
var builder = new StringBuilder();
if (value < 0)
{
builder.Append('-');
}
for (var i = 0; i < digits.Length; i++)
{
if (i > 0 && (digits.Length - i) % 3 == 0)
{
builder.Append('.');
}
builder.Append(digits[i]);
}
return builder.ToString();
}
/// <summary>Decimal number with a comma: 1,3. Trailing zeros of the decimals are kept only when asked.</summary>
public static string Decimal(double value, int decimals = 1, bool keepZeros = false)
{
var rounded = Math.Round(value, decimals, MidpointRounding.AwayFromZero);
var whole = (long)Math.Truncate(rounded);
var fraction = Math.Abs(rounded - whole);
var text = Number(whole);
if (whole == 0 && rounded < 0)
{
text = "-0";
}
if (decimals <= 0)
{
return text;
}
var fractionDigits = ((long)Math.Round(fraction * Math.Pow(10, decimals))).ToString(CultureInfo.InvariantCulture).PadLeft(decimals, '0');
if (!keepZeros)
{
fractionDigits = fractionDigits.TrimEnd('0');
}
return fractionDigits.Length == 0 ? text : text + "," + fractionDigits;
}
/// <summary>Byte amount: «850 MB», «1,3 GB».</summary>
public static string Bytes(long bytes)
{
const double KB = 1024;
const double MB = KB * 1024;
const double GB = MB * 1024;
return bytes switch
{
>= (long)GB => Decimal(bytes / GB, 1) + " GB",
>= (long)MB => Decimal(bytes / MB, bytes >= 100 * MB ? 0 : 1) + " MB",
>= (long)KB => Decimal(bytes / KB, 0) + " kB",
_ => Number(bytes) + " byte",
};
}
/// <summary>Local clock time without a leading zero on the hour: «7:42», «15:30».</summary>
public static string Clock(DateTimeOffset instant, TimeZoneInfo zone)
{
var local = LocalCalendar.ToLocal(instant, zone);
return local.Hour.ToString(CultureInfo.InvariantCulture) + ":" + local.Minute.ToString("00", CultureInfo.InvariantCulture);
}
/// <summary>«alle 17:32», «all'1:05».</summary>
public static string At(DateTimeOffset instant, TimeZoneInfo zone) =>
(LocalCalendar.ToLocal(instant, zone).Hour == 1 ? "all'" : "alle ") + Clock(instant, zone);
/// <summary>«dalle 16:32», «dall'1:05».</summary>
public static string Since(DateTimeOffset instant, TimeZoneInfo zone) =>
(LocalCalendar.ToLocal(instant, zone).Hour == 1 ? "dall'" : "dalle ") + Clock(instant, zone);
/// <summary>
/// A future engine time, always indicative (spec §7.9): «verso le 15:30», «domani verso le 7:42»,
/// «giovedì verso le 7:42», «il 21 ottobre verso le 7:42».
/// </summary>
public static string Around(DateTimeOffset instant, DateTimeOffset now, TimeZoneInfo zone)
{
var hour = LocalCalendar.ToLocal(instant, zone).Hour;
var time = (hour == 1 ? "verso l'" : "verso le ") + Clock(instant, zone);
var prefix = DayPrefix(instant, now, zone);
return prefix.Length == 0 ? time : prefix + " " + time;
}
/// <summary>«alle 17:32», «domani alle 7:42»: a fixed future time (e.g. the end of a throttle stop).</summary>
public static string AtDay(DateTimeOffset instant, DateTimeOffset now, TimeZoneInfo zone)
{
var prefix = DayPrefix(instant, now, zone);
var at = At(instant, zone);
return prefix.Length == 0 ? at : prefix + " " + at;
}
/// <summary>«13 ottobre».</summary>
public static string Day(DateOnly day) => day.Day.ToString(CultureInfo.InvariantCulture) + " " + Months[day.Month - 1];
/// <summary>«lunedì 13 ottobre».</summary>
public static string DayWithWeekday(DateOnly day) => Weekdays[(int)day.DayOfWeek] + " " + Day(day);
/// <summary>A duration in words: «45 minuti», «1 ora e 20 minuti», «2 giorni e 3 ore», «30 secondi».</summary>
public static string Duration(TimeSpan span)
{
if (span < TimeSpan.Zero)
{
span = TimeSpan.Zero;
}
if (span < TimeSpan.FromMinutes(1))
{
var seconds = (long)Math.Round(span.TotalSeconds);
return seconds == 1 ? "1 secondo" : Number(seconds) + " secondi";
}
if (span < TimeSpan.FromHours(1))
{
return Minutes((long)Math.Round(span.TotalMinutes));
}
if (span < TimeSpan.FromDays(2))
{
var totalMinutes = (long)Math.Round(span.TotalMinutes);
var hours = totalMinutes / 60;
var minutes = totalMinutes % 60;
var text = hours == 1 ? "1 ora" : Number(hours) + " ore";
return minutes == 0 ? text : text + " e " + Minutes(minutes);
}
var totalHours = (long)Math.Round(span.TotalHours);
var days = totalHours / 24;
var restHours = totalHours % 24;
var dayText = days == 1 ? "1 giorno" : Number(days) + " giorni";
return restHours == 0 ? dayText : dayText + " e " + (restHours == 1 ? "1 ora" : Number(restHours) + " ore");
}
/// <summary>An interval of a check («ogni 3 ore», «ogni 75 minuti», «ogni giorno»).</summary>
public static string Every(TimeSpan interval)
{
if (interval >= TimeSpan.FromHours(23.5) && interval <= TimeSpan.FromHours(24.5))
{
return "ogni giorno";
}
if (interval < TimeSpan.FromHours(2) && interval.TotalMinutes % 60 != 0)
{
return "ogni " + Minutes((long)Math.Round(interval.TotalMinutes));
}
var hours = interval.TotalHours;
if (Math.Abs(hours - Math.Round(hours)) < 0.05)
{
var whole = (long)Math.Round(hours);
return whole == 1 ? "ogni ora" : "ogni " + Number(whole) + " ore";
}
return "ogni " + Decimal(hours, 1) + " ore";
}
/// <summary>Italian name of a budget category, as in the table of spec §7.5.</summary>
public static string Category(ActionKind kind) => kind switch
{
ActionKind.Home => "aperture della home",
ActionKind.ProfileOpen => "profili aperti",
ActionKind.StoryView => "storie viste",
ActionKind.BackfillPage => "pagine di storico",
ActionKind.SinglePost => "post singoli",
ActionKind.FollowingListPage => "pagine dell'elenco dei seguiti",
ActionKind.DataDownload => "dati scaricati",
_ => kind.ToString(),
};
/// <summary>Category name with a capital initial, for labels: «Profili aperti».</summary>
public static string CategoryLabel(ActionKind kind) => Capitalize(Category(kind));
/// <summary>Italian name of a caution profile: «Prudente».</summary>
public static string Profile(CautionProfileKind kind) => kind switch
{
CautionProfileKind.Prudent => "Prudente",
CautionProfileKind.Balanced => "Equilibrato",
CautionProfileKind.Fast => "Rapido",
CautionProfileKind.Custom => "Su misura",
_ => kind.ToString(),
};
/// <summary>«@marta.demo».</summary>
public static string Handle(string? username) => string.IsNullOrWhiteSpace(username) ? "un account" : "@" + username.TrimStart('@');
/// <summary>Count with its noun: «1 storia nuova», «3 storie nuove».</summary>
public static string Count(long count, string singular, string plural) =>
count == 1 ? "1 " + singular : Number(count) + " " + plural;
public static string Capitalize(string text) =>
string.IsNullOrEmpty(text) ? text : char.ToUpperInvariant(text[0]) + text[1..];
private static string Minutes(long minutes) => minutes == 1 ? "1 minuto" : Number(minutes) + " minuti";
private static string DayPrefix(DateTimeOffset instant, DateTimeOffset now, TimeZoneInfo zone)
{
var day = LocalCalendar.Today(instant, zone);
var today = LocalCalendar.Today(now, zone);
var difference = day.DayNumber - today.DayNumber;
return difference switch
{
<= 0 => string.Empty,
1 => "domani",
< 7 => Weekdays[(int)day.DayOfWeek],
_ => "il " + Day(day),
};
}
}
+536
View File
@@ -0,0 +1,536 @@
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Storage;
namespace Febe.Core.Engine;
/// <summary>
/// Builds the snapshot of the engine for the interface. Reads only: it never draws from the engine's random source,
/// so watching the engine does not change what it does. Future times are indicative and written «verso le».
/// </summary>
public sealed class EngineMonitor : IEngineMonitor
{
private static readonly ActionKind[] Main = [ActionKind.ProfileOpen, ActionKind.StoryView, ActionKind.BackfillPage, ActionKind.DataDownload];
private readonly EngineServices _s;
private readonly EngineHost _host;
internal EngineMonitor(EngineServices services, EngineHost host)
{
_s = services;
_host = host;
}
public IAsyncEnumerable<EngineNotification> SubscribeAsync(CancellationToken ct = default) => _s.Events.SubscribeAsync(ct);
public async Task<EngineSnapshot> GetSnapshotAsync(CancellationToken ct = default)
{
var now = _s.Clock.Now;
var zone = _s.Clock.LocalZone;
var runtime = _s.Runtime;
var breaker = _s.Breaker.State;
var profile = runtime.Profile;
var window = await _s.Planner.GetWindowAtAsync(now, ct).ConfigureAwait(false);
var nextWindow = window ?? await _s.Planner.GetNextWindowAsync(now, ct).ConfigureAwait(false);
var session = runtime.CurrentSession;
var mode = ModeOf(runtime, breaker, session, window);
var resumes = ResumesAround(mode, runtime, breaker, nextWindow, now);
var (headline, details, sidebar) = Texts(mode, runtime, breaker, session, resumes, now, zone);
var budgets = _s.Governor.GetEffectiveBudgets(now);
var statuses = await _s.Governor.GetBudgetStatusAsync(ct).ConfigureAwait(false);
var views = statuses.Select(b => View(b, breaker, now, zone)).ToList();
var accounts = (await _s.Storage.Accounts.ListAsync(ct).ConfigureAwait(false)).ToDictionary(a => a.Id);
return new EngineSnapshot
{
At = now,
Mode = mode,
Headline = headline,
Details = details,
SidebarLine = sidebar,
ResumesAround = resumes,
Banner = Banner(breaker, now, zone),
Profile = profile.Kind,
ProfileLine = $"Profilo «{ItalianText.Profile(profile.Kind)}»",
ReductionNote = ReductionNote(budgets, now, zone),
Today = await StripAsync(now, zone, session, runtime, profile, accounts, ct).ConfigureAwait(false),
MainBudgets = [.. Main.Select(k => views.First(v => v.Kind == k))],
AllBudgets = views,
ProfilesOpenedToday = views.First(v => v.Kind == ActionKind.ProfileOpen),
Queue = await QueueAsync(now, zone, mode, session, runtime, accounts, ct).ConfigureAwait(false),
RecentActions = await RecentAsync(now, zone, ct).ConfigureAwait(false),
SuspendedRecipes = [.. _host.SuspendedRecipes.Select(r => new SuspendedRecipeView(r.Key, ItalianText.Capitalize(SessionComposer.RecipeName(r.Key)), r.Value))],
Breaker = breaker,
};
}
private static EngineMode ModeOf(EngineRuntime runtime, BreakerState breaker, SessionContext? session, ActiveWindow? window)
{
if (breaker.Status == BreakerStatus.Challenge)
{
return EngineMode.StoppedForVerification;
}
if (breaker.Status == BreakerStatus.Disconnected)
{
return EngineMode.Disconnected;
}
if (runtime.IsConnected == false)
{
return EngineMode.NotConnected;
}
if (breaker.Status == BreakerStatus.Throttled)
{
return EngineMode.Throttled;
}
if (runtime.IsPaused)
{
return EngineMode.Paused;
}
if (runtime.UserIsDriving)
{
return EngineMode.UserDriving;
}
if (!runtime.IsRunning)
{
return EngineMode.Off;
}
if (session is not null)
{
return EngineMode.InSession;
}
if (window is null)
{
return EngineMode.OutsideWindow;
}
return runtime.HadSessionSinceStart ? EngineMode.Resting : EngineMode.Starting;
}
private static DateTimeOffset? ResumesAround(EngineMode mode, EngineRuntime runtime, BreakerState breaker, ActiveWindow? nextWindow, DateTimeOffset now)
{
switch (mode)
{
case EngineMode.Throttled:
return breaker.Until;
case EngineMode.Resting or EngineMode.Starting or EngineMode.OutsideWindow:
var next = runtime.NextSessionAt;
if (mode == EngineMode.OutsideWindow && nextWindow is not null && (next is null || next < nextWindow.Start))
{
next = nextWindow.Start;
}
return next is { } n && n < now ? now : next;
default:
return null;
}
}
private static (string Headline, IReadOnlyList<string> Details, string Sidebar) Texts(
EngineMode mode,
EngineRuntime runtime,
BreakerState breaker,
SessionContext? session,
DateTimeOffset? resumes,
DateTimeOffset now,
TimeZoneInfo zone)
{
var around = resumes is { } r ? ItalianText.Around(r, now, zone) : null;
switch (mode)
{
case EngineMode.InSession when session is not null:
{
var activity = runtime.Activity ?? "Sto per iniziare il prossimo passo";
var left = session.PlannedEnd - now;
var timing = left > TimeSpan.FromMinutes(1)
? $"Iniziata {ItalianText.At(session.StartedAt, zone)}, ancora {ItalianText.Duration(left)} circa."
: $"Iniziata {ItalianText.At(session.StartedAt, zone)}, sta per finire.";
if (session.OutsideWindowAccountId is not null)
{
timing += " Controllo fuori fascia confermato da te.";
}
var sidebar = runtime.Activity is { } a && a.StartsWith("Sto ", StringComparison.Ordinal) ? ItalianText.Capitalize(a[4..]) : "In sessione";
return ("In sessione", [activity, timing], sidebar);
}
case EngineMode.Resting:
return ("In ascolto", [$"Riprende {around ?? "a breve"}.", "Fra una sessione e l'altra il browser resta sulla pagina vuota."], $"Riprende {around ?? "a breve"}");
case EngineMode.Starting:
return ("In avvio", [$"Prima sessione {around ?? "a breve"}."], $"Prima sessione {around ?? "a breve"}");
case EngineMode.OutsideWindow:
return ("Fuori fascia", ["Fuori dalla fascia oraria Febe non apre nulla da solo.", $"Riprende {around ?? "nei giorni attivi"}."], $"Riprende {around ?? "nei giorni attivi"}");
case EngineMode.Paused:
return ("In pausa", ["Messo in pausa da te.", "Premi «Riprendi» per ripartire."], "In pausa");
case EngineMode.Throttled:
{
var until = breaker.Until is { } u ? ItalianText.Around(u, now, zone) : "più tardi";
return ("Fermo per rallentamento", [$"Instagram ha chiesto di rallentare: riprende {until}.", "Poi i tetti restano dimezzati per 48 ore."], $"Riprende {until}");
}
case EngineMode.StoppedForVerification:
{
var since = breaker.LastSignal is { } s ? $"Fermo {ItalianText.Since(s.At, zone)}. " : string.Empty;
return ("Fermo", ["In attesa che tu completi la verifica", since + "Nessun nuovo tentativo finché non premi «Riprendi»."], "Serve il tuo intervento");
}
case EngineMode.Disconnected:
return ("Scollegato", ["La sessione di Instagram non c'è più.", "Apri il browser, accedi di nuovo, poi premi «Riprendi». Febe non prova a rientrare da solo."], "Accedi di nuovo");
case EngineMode.NotConnected:
return ("Non collegato", ["Il browser di Febe non ha una sessione di Instagram.", "Collegalo dalla pagina Collegamento."], "Non collegato");
case EngineMode.UserDriving:
return ("Stai usando il browser", ["Il motore resta fermo finché non hai finito."], "Stai usando il browser");
default:
return ("Motore spento", ["Il motore non è in funzione."], "Motore spento");
}
}
private static StopBanner? Banner(BreakerState breaker, DateTimeOffset now, TimeZoneInfo zone)
{
var at = breaker.LastSignal is { } s ? ItalianText.At(s.At, zone) : null;
return breaker.Status switch
{
BreakerStatus.Challenge => new StopBanner(
BannerLevel.Error,
"Instagram chiede una verifica",
$"Ho fermato tutto{(at is null ? string.Empty : " " + at)} e non riparto da solo. Apri il browser, completa la verifica a mano, poi premi «Riprendi».",
true),
BreakerStatus.Disconnected => new StopBanner(
BannerLevel.Error,
"Instagram ha chiuso la sessione",
$"Ho fermato tutto{(at is null ? string.Empty : " " + at)} e non provo a rientrare. Apri il browser, accedi a mano, poi premi «Riprendi».",
true),
BreakerStatus.Throttled when breaker.Until is { } until => new StopBanner(
BannerLevel.Warning,
"Instagram ha chiesto di rallentare",
$"Ho chiuso la sessione e mi fermo fino {ItalianText.AtDay(until, now, zone)}; poi riparto da solo con i tetti dimezzati per 48 ore.",
false),
_ => null,
};
}
private static string? ReductionNote(EffectiveBudgets budgets, DateTimeOffset now, TimeZoneInfo zone) => budgets.Reduction switch
{
BudgetReduction.GradualStart =>
$"Avvio graduale: tetti al {ItalianText.Number((long)Math.Round(budgets.Factor * 100))}%"
+ (budgets.Until is { } u ? $", pieni {ItalianText.Around(u, now, zone)}" : string.Empty) + ".",
BudgetReduction.HalvedAfterThrottle =>
"Tetti dimezzati dopo un rallentamento" + (budgets.Until is { } h ? $" fino {ItalianText.AtDay(h, now, zone)}" : string.Empty) + ".",
_ => null,
};
internal static BudgetView View(BudgetStatus status, BreakerState breaker, DateTimeOffset now, TimeZoneInfo zone)
{
var data = status.Kind == ActionKind.DataDownload;
var usedText = data ? ItalianText.Bytes(status.UsedToday) : ItalianText.Number(status.UsedToday);
var limitText = "di " + (data ? ItalianText.Bytes(status.LimitToday) : ItalianText.Number(status.LimitToday));
string note;
if (!breaker.AllowsSiteActions && !data)
{
note = breaker.LastSignal is { } s ? "Fermo " + ItalianText.Since(s.At, zone) : "Fermo";
}
else if (status.DailyReached)
{
note = "Tetto di oggi raggiunto: riprende domani";
}
else if (status.HourlyReached)
{
note = "Tetto orario raggiunto: riprende entro un'ora";
}
else if (status.DailyRatio >= BudgetStatus.AmberThreshold)
{
note = "Quasi al limite per oggi";
}
else if (status.HourlyRatio >= BudgetStatus.AmberThreshold)
{
note = "Quasi al limite di quest'ora";
}
else if (data)
{
note = "Restano " + ItalianText.Bytes(Math.Max(0, status.LimitToday - status.UsedToday));
}
else
{
note = $"In questa ora {ItalianText.Number(status.UsedLastHour ?? 0)} di {ItalianText.Number(status.LimitPerHour ?? 0)}";
}
return new BudgetView(
status.Kind,
ItalianText.CategoryLabel(status.Kind),
status.UsedToday,
status.LimitToday,
status.UsedLastHour,
status.LimitPerHour,
status.IsAmber,
Math.Clamp(status.DailyRatio, 0, 1),
usedText,
limitText,
note);
}
private async Task<DayStrip> StripAsync(
DateTimeOffset now,
TimeZoneInfo zone,
SessionContext? current,
EngineRuntime runtime,
CautionProfile profile,
Dictionary<long, Account> accounts,
CancellationToken ct)
{
var day = LocalCalendar.Today(now, zone);
var (dayStart, dayEnd) = LocalCalendar.DayBounds(day, zone);
var spans = new List<StripSpan>();
// Night and inactive hours: everything of the day outside the windows of yesterday and today.
var windows = new List<ActiveWindow>();
foreach (var d in new[] { day.AddDays(-1), day })
{
if (await _s.Planner.GetWindowAsync(d, ct).ConfigureAwait(false) is { } w && w.End > dayStart && w.Start < dayEnd)
{
windows.Add(w);
}
}
var cursor = dayStart;
foreach (var w in windows.OrderBy(w => w.Start))
{
var start = w.Start < dayStart ? dayStart : w.Start;
if (start > cursor)
{
spans.Add(new StripSpan(StripSpanKind.OutsideWindow, cursor, start, false, "Fuori fascia"));
}
cursor = w.End > cursor ? w.End : cursor;
}
if (cursor < dayEnd)
{
spans.Add(new StripSpan(StripSpanKind.OutsideWindow, cursor, dayEnd, false, "Fuori fascia"));
}
// Sessions of the day and the rests between them.
var sessions = await _s.Storage.Sessions.ListAsync(dayStart, dayEnd, ct).ConfigureAwait(false);
DateTimeOffset? previousEnd = null;
var activeMinutes = 0.0;
foreach (var session in sessions)
{
var end = session.EndedAt ?? now;
var inProgress = session.EndedAt is null && current?.SessionId == session.Id;
if (previousEnd is { } rest && session.StartedAt > rest)
{
spans.Add(new StripSpan(StripSpanKind.Rest, rest, session.StartedAt, false, "Pausa"));
}
spans.Add(new StripSpan(
inProgress ? StripSpanKind.CurrentSession : StripSpanKind.Session,
session.StartedAt,
end,
false,
(inProgress ? "Sessione in corso dalle " : "Sessione dalle ") + ItalianText.Clock(session.StartedAt, zone)
+ (inProgress ? string.Empty : " alle " + ItalianText.Clock(end, zone))));
activeMinutes += ((end < dayEnd ? end : dayEnd) - (session.StartedAt > dayStart ? session.StartedAt : dayStart)).TotalMinutes;
previousEnd = end;
}
if (current is null && previousEnd is { } lastEnd && lastEnd < now && windows.Any(w => w.Contains(now)))
{
spans.Add(new StripSpan(StripSpanKind.Rest, lastEnd, now, false, "Pausa"));
}
// Stops.
var throttles = 0;
foreach (var incident in await _s.Storage.Incidents.ListAsync(dayStart - TimeSpan.FromDays(2), dayEnd, ct).ConfigureAwait(false))
{
var end = incident.ResolvedAt ?? (incident.Level == SignalLevel.Throttle ? incident.StoppedUntil ?? now : now);
if (end <= dayStart || incident.At >= dayEnd)
{
continue;
}
if (incident.Level == SignalLevel.Throttle)
{
if (incident.At >= dayStart)
{
throttles++;
}
spans.Add(new StripSpan(StripSpanKind.Throttle, incident.At, end, incident.ResolvedAt is null, "Fermo per rallentamento"));
}
else
{
spans.Add(new StripSpan(
StripSpanKind.Stop,
incident.At,
incident.ResolvedAt ?? now,
false,
incident.Level == SignalLevel.Challenge ? "Fermo per una verifica" : "Fermo per disconnessione"));
}
}
// Planned sessions, indicative: median length and median pause from the next planned start.
if (current is null && runtime.NextSessionAt is { } next && _s.Breaker.State.AllowsSiteActions && !runtime.IsPaused)
{
var sessionLength = TimeSpan.FromTicks((long)Math.Sqrt((double)profile.SessionMin.Ticks * profile.SessionMax.Ticks));
var pause = TimeSpan.FromTicks((long)Math.Sqrt((double)profile.PauseMin.Ticks * profile.PauseMax.Ticks));
var start = next < now ? now : next;
for (var i = 0; i < 40 && start < dayEnd; i++)
{
var window = windows.FirstOrDefault(w => w.Contains(start));
if (window is null)
{
break;
}
var end = start + sessionLength;
spans.Add(new StripSpan(StripSpanKind.PlannedSession, start, end < window.End ? end : window.End, true, "Prossima sessione " + ItalianText.Around(start, now, zone)));
start = end + pause;
}
}
var newEntries = 0L;
foreach (var account in accounts.Values)
{
foreach (var kind in new[] { EntryKind.Post, EntryKind.Story, EntryKind.Highlight, EntryKind.Tagged })
{
newEntries += await _s.Storage.Entries.CountDiscoveredAsync(account.Id, kind, dayStart, dayEnd, ct).ConfigureAwait(false);
}
}
var summary = string.Join(", ", new[]
{
ItalianText.Count(sessions.Count, "sessione", "sessioni"),
ItalianText.Count((long)Math.Round(activeMinutes), "minuto di attività", "minuti di attività"),
ItalianText.Count(newEntries, "contenuto nuovo", "contenuti nuovi"),
throttles == 0 ? "nessun rallentamento" : ItalianText.Count(throttles, "rallentamento", "rallentamenti"),
});
return new DayStrip(day, dayStart, dayEnd, now, summary, [.. spans.OrderBy(s => s.Start).ThenBy(s => s.Kind)]);
}
private async Task<IReadOnlyList<QueueItem>> QueueAsync(
DateTimeOffset now,
TimeZoneInfo zone,
EngineMode mode,
SessionContext? session,
EngineRuntime runtime,
Dictionary<long, Account> accounts,
CancellationToken ct)
{
var suspended = mode is EngineMode.Paused or EngineMode.Throttled or EngineMode.StoppedForVerification or EngineMode.Disconnected
or EngineMode.NotConnected or EngineMode.Off;
var tasks = await _s.Storage.Tasks.ListPendingAsync(200, ct).ConfigureAwait(false);
var items = new List<QueueItem>();
foreach (var task in tasks
.OrderByDescending(t => t.IsManual)
.ThenBy(t => t.DueAt)
.ThenByDescending(t => t.Priority)
.Take(20))
{
Account? account = null;
if (task.AccountId is { } id)
{
accounts.TryGetValue(id, out account);
}
var (title, detail) = Describe(task, account);
DateTimeOffset? around = null;
string when;
if (suspended)
{
when = "Sospeso";
}
else if (session is not null && task.DueAt <= now)
{
around = now;
when = "In questa sessione";
}
else
{
var t = task.DueAt;
var next = runtime.NextSessionAt ?? now;
if (t < next)
{
t = next;
}
if (t < now)
{
t = now;
}
if (await _s.Planner.GetWindowAtAsync(t, ct).ConfigureAwait(false) is null
&& await _s.Planner.GetNextWindowAsync(t, ct).ConfigureAwait(false) is { } w)
{
t = w.Start;
}
around = t;
when = ItalianText.Around(t, now, zone);
}
items.Add(new QueueItem(task.Id, task.Kind, task.AccountId, title, detail, around, when, task.IsManual, suspended));
}
return items;
}
private static (string Title, string Detail) Describe(EngineTask task, Account? account)
{
var who = ItalianText.Handle(account?.Username);
return task.Kind switch
{
EngineTaskKind.FollowingSweep => ("Giro dei profili che segui", "Home e barra delle storie"),
EngineTaskKind.FollowingList => ("Elenco dei profili che segui", "Lettura chiesta da te"),
EngineTaskKind.ProfileCheck when task.IsManual => (who, "Controllo chiesto da te"),
EngineTaskKind.ProfileCheck when account is { IsFollowed: true } => (who, "Riconciliazione del profilo"),
EngineTaskKind.ProfileCheck when account is not null && CheckPolicy.WantsStories(account) => (who, "Nuovi post e storie"),
EngineTaskKind.ProfileCheck => (who, "Nuovi post"),
EngineTaskKind.AccountStories when task.IsManual => (who, "Storie, chieste da te"),
EngineTaskKind.AccountStories when task.Priority > 0 => (who, "Storie segnalate dalla barra"),
EngineTaskKind.AccountStories => (who, "Storie"),
EngineTaskKind.Backfill when account?.PostCount is { } count => (who, "Storico, " + ItalianText.Count(count, "post sul profilo", "post sul profilo")),
EngineTaskKind.Backfill => (who, "Storico"),
EngineTaskKind.HighlightCheck => (who, "Storie in evidenza"),
EngineTaskKind.TaggedCheck => (who, "Post in cui è taggato"),
EngineTaskKind.ReelsCheck => (who, "Reel"),
EngineTaskKind.SinglePost => (who, "Post singolo"),
_ => (who, task.Kind.ToString()),
};
}
private async Task<IReadOnlyList<RecentActionView>> RecentAsync(DateTimeOffset now, TimeZoneInfo zone, CancellationToken ct)
{
var views = new List<RecentActionView>();
if (_s.Runtime.CurrentSession is not null && _s.Runtime.Activity is { } activity)
{
views.Add(new RecentActionView(now, ItalianText.Clock(now, zone), activity.StartsWith("Sto ", StringComparison.Ordinal) ? ItalianText.Capitalize(activity[4..]) : activity, string.Empty, "In corso", true));
}
var recent = _host.RecentActions(10);
if (recent.Count > 0)
{
views.AddRange(recent.Select(r => new RecentActionView(r.At, ItalianText.Clock(r.At, zone), r.Title, r.Detail, r.Badge, false)));
return views;
}
// Just started: the latest lines of the timeline.
var events = await _s.Storage.Events.ListAsync(new EventQuery { Limit = 200 }, ct).ConfigureAwait(false);
foreach (var e in events.Where(e => e.Code.StartsWith(EngineEventCodes.RecipePrefix, StringComparison.Ordinal)).Take(10))
{
var split = e.Message.IndexOf(": ", StringComparison.Ordinal);
var title = split > 0 ? e.Message[..split] : e.Message;
var detail = split > 0 ? e.Message[(split + 2)..] : string.Empty;
views.Add(new RecentActionView(e.At, ItalianText.Clock(e.At, zone), title, detail, null, false));
}
return views;
}
}
+193
View File
@@ -0,0 +1,193 @@
using Febe.Core.Abstractions;
using Febe.Core.Domain;
namespace Febe.Core.Engine;
/// <summary>What the interface shows of the engine (spec §7.9, mockups 06 and 11, sidebar of §10.2).</summary>
public interface IEngineMonitor
{
/// <summary>The state of the engine now: mode, texts, strip of the day, budgets, queue, latest actions.</summary>
Task<EngineSnapshot> GetSnapshotAsync(CancellationToken ct = default);
/// <summary>Notifications from now on (timeline lines and state changes); the web layer turns them into server-sent events.</summary>
IAsyncEnumerable<EngineNotification> SubscribeAsync(CancellationToken ct = default);
}
/// <summary>Mode of the engine, in order of precedence.</summary>
public enum EngineMode
{
/// <summary>The loop is not running.</summary>
Off,
/// <summary>Just started: the first session comes 2–10 minutes after the program.</summary>
Starting,
InSession,
/// <summary>Between two sessions, inside the active window («In ascolto»).</summary>
Resting,
/// <summary>Outside the active window (night or inactive day).</summary>
OutsideWindow,
/// <summary>«Metti in pausa».</summary>
Paused,
/// <summary>Timed stop after a throttle.</summary>
Throttled,
/// <summary>Stopped for a verification: needs Alberto and «Riprendi».</summary>
StoppedForVerification,
/// <summary>The Instagram session is gone: needs a new login and «Riprendi».</summary>
Disconnected,
/// <summary>The browser has no Instagram session yet.</summary>
NotConnected,
/// <summary>Alberto is using the browser.</summary>
UserDriving,
}
/// <summary>Severity of the strip at the top of every page.</summary>
public enum BannerLevel
{
Warning,
Error,
}
/// <summary>The strip at the top of every page while Febe is stopped and needs Alberto (mockup 11).</summary>
/// <param name="Level">Error for verification and disconnection, warning for a throttle stop.</param>
/// <param name="Title">«Instagram chiede una verifica».</param>
/// <param name="Message">What happened, what Febe did, what Alberto must do.</param>
/// <param name="NeedsResume">«Riprendi» is needed (after Alberto used the browser).</param>
public sealed record StopBanner(BannerLevel Level, string Title, string Message, bool NeedsResume);
public enum StripSpanKind
{
/// <summary>Outside the active window: night (hatched).</summary>
OutsideWindow,
/// <summary>A past session.</summary>
Session,
/// <summary>The session in progress.</summary>
CurrentSession,
/// <summary>A planned session, indicative («Prossime, orario indicativo»).</summary>
PlannedSession,
/// <summary>Rest between sessions («Pausa»).</summary>
Rest,
/// <summary>Throttle stop.</summary>
Throttle,
/// <summary>Stop for a verification or a disconnection.</summary>
Stop,
}
/// <summary>A stretch of the strip of the day.</summary>
public sealed record StripSpan(StripSpanKind Kind, DateTimeOffset Start, DateTimeOffset End, bool Indicative, string Label);
/// <summary>The strip of the day: a 24-hour bar with sessions as irregular strokes (spec §10.1).</summary>
/// <param name="Day">Local day.</param>
/// <param name="Start">Local midnight.</param>
/// <param name="End">Next local midnight.</param>
/// <param name="Now">Instant of the snapshot (the marker).</param>
/// <param name="Summary">«9 sessioni, 80 minuti di attività, 41 contenuti nuovi, nessun rallentamento».</param>
/// <param name="Spans">Stretches in time order (spans of different kinds may overlap: stops over sessions).</param>
public sealed record DayStrip(DateOnly Day, DateTimeOffset Start, DateTimeOffset End, DateTimeOffset Now, string Summary, IReadOnlyList<StripSpan> Spans);
/// <summary>One budget as the interface shows it (spec §7.4: amber from 80%).</summary>
/// <param name="Kind">Category.</param>
/// <param name="Label">«Profili aperti».</param>
/// <param name="UsedToday">Today (bytes for data).</param>
/// <param name="LimitToday">Daily limit in force.</param>
/// <param name="UsedLastHour">Rolling last hour (null for data).</param>
/// <param name="LimitPerHour">Hourly limit in force (null for data).</param>
/// <param name="Amber">At or above 80% of the daily or hourly budget.</param>
/// <param name="Ratio">Daily use between 0 and 1 (for the bar).</param>
/// <param name="UsedText">«38», «1,3 GB».</param>
/// <param name="LimitText">«di 100», «di 4 GB».</param>
/// <param name="Note">«In questa ora 3 di 12», «Quasi al limite per oggi», «Fermo dalle 16:32».</param>
public sealed record BudgetView(
ActionKind Kind,
string Label,
long UsedToday,
long LimitToday,
long? UsedLastHour,
long? LimitPerHour,
bool Amber,
double Ratio,
string UsedText,
string LimitText,
string Note);
/// <summary>A task of the queue with its indicative time.</summary>
/// <param name="TaskId">Task key.</param>
/// <param name="Kind">What it is.</param>
/// <param name="AccountId">Account, when it has one.</param>
/// <param name="Title">«@luca.viaggi.demo» or «Giro dei profili che segui».</param>
/// <param name="Detail">«Nuovi post», «Storico, altri 120 post».</param>
/// <param name="Around">Indicative time; null when suspended.</param>
/// <param name="When">«verso le 14:32», «In questa sessione», «Sospeso».</param>
/// <param name="IsManual">Asked by Alberto.</param>
/// <param name="Suspended">The engine is stopped or paused.</param>
public sealed record QueueItem(long TaskId, EngineTaskKind Kind, long? AccountId, string Title, string Detail, DateTimeOffset? Around, string When, bool IsManual, bool Suspended);
/// <summary>A line of «Appena fatto».</summary>
public sealed record RecentActionView(DateTimeOffset At, string Time, string Title, string Detail, string? Badge, bool InProgress);
/// <summary>A recipe suspended after repeated unrecognized formats.</summary>
public sealed record SuspendedRecipeView(RecipeKind Recipe, string Name, DateTimeOffset Since);
/// <summary>Everything the Activity page, the sidebar and the stop strip need, at one instant.</summary>
public sealed record EngineSnapshot
{
public required DateTimeOffset At { get; init; }
public required EngineMode Mode { get; init; }
/// <summary>«In sessione», «In ascolto», «Fermo».</summary>
public required string Headline { get; init; }
/// <summary>Lines under the headline: «Sto guardando le storie di @marta.demo», «Iniziata alle 15:31, ancora 3 minuti circa».</summary>
public required IReadOnlyList<string> Details { get; init; }
/// <summary>One short line for the sidebar: «Storie di @marta.demo», «Riprende verso le 15:30».</summary>
public required string SidebarLine { get; init; }
/// <summary>Indicative restart time when not working.</summary>
public DateTimeOffset? ResumesAround { get; init; }
/// <summary>The red (or amber) strip at the top of every page; null when the engine does not need Alberto.</summary>
public StopBanner? Banner { get; init; }
public required CautionProfileKind Profile { get; init; }
/// <summary>«Profilo «Prudente»» with the reduction in force, if any.</summary>
public required string ProfileLine { get; init; }
/// <summary>«Avvio graduale: tetti al 64%» or «Tetti dimezzati fino a giovedì alle 17:32»; null without reductions.</summary>
public string? ReductionNote { get; init; }
public required DayStrip Today { get; init; }
/// <summary>The four main budgets: profiles opened, stories viewed, history pages, data downloaded.</summary>
public required IReadOnlyList<BudgetView> MainBudgets { get; init; }
/// <summary>«Tutti i tetti».</summary>
public required IReadOnlyList<BudgetView> AllBudgets { get; init; }
/// <summary>«Profili aperti oggi» meter of the sidebar.</summary>
public required BudgetView ProfilesOpenedToday { get; init; }
public required IReadOnlyList<QueueItem> Queue { get; init; }
public required IReadOnlyList<RecentActionView> RecentActions { get; init; }
public required IReadOnlyList<SuspendedRecipeView> SuspendedRecipes { get; init; }
public required BreakerState Breaker { get; init; }
}
+60
View File
@@ -0,0 +1,60 @@
namespace Febe.Core.Engine;
/// <summary>One recipe run, as shown in «Appena fatto» (mockup 06).</summary>
/// <param name="At">When it ended.</param>
/// <param name="Recipe">Recipe.</param>
/// <param name="AccountId">Account, when the recipe has one.</param>
/// <param name="Title">«@marta.demo» or «Giro dei profili che segui».</param>
/// <param name="Detail">«2 storie nuove», «Nessuna novità».</param>
/// <param name="Status">How it ended.</param>
/// <param name="NewEntries">New entries found.</param>
public sealed record RecentAction(
DateTimeOffset At,
RecipeKind Recipe,
long? AccountId,
string Title,
string Detail,
RecipeStatus Status,
int NewEntries)
{
/// <summary>Short label of the outcome for a badge («Scaricato», «Rimandato»...); null when nothing to say.</summary>
public string? Badge => Status switch
{
RecipeStatus.Completed => NewEntries > 0 ? "Scaricato" : null,
RecipeStatus.Denied => "Rimandato",
RecipeStatus.StoppedBySignal => "Tutto fermo",
RecipeStatus.TargetNotFound => "Da controllare",
RecipeStatus.UnrecognizedFormat => "Formato nuovo",
RecipeStatus.AccountUnreachable => "Non raggiungibile",
RecipeStatus.Cancelled => "Interrotto",
RecipeStatus.Failed => "Errore",
_ => null,
};
}
/// <summary>The last recipe runs, newest first, in memory (the timeline keeps the full history).</summary>
internal sealed class RecentActions(int capacity = 50)
{
private readonly Lock _gate = new();
private readonly LinkedList<RecentAction> _items = new();
public void Add(RecentAction action)
{
lock (_gate)
{
_items.AddFirst(action);
while (_items.Count > capacity)
{
_items.RemoveLast();
}
}
}
public IReadOnlyList<RecentAction> Snapshot(int limit)
{
lock (_gate)
{
return [.. _items.Take(limit)];
}
}
}
+149
View File
@@ -0,0 +1,149 @@
using System.Globalization;
using Febe.Core.Storage;
namespace Febe.Core.Engine;
/// <summary>
/// Consecutive failures per recipe and suspended recipes (spec §6.4: after three «formato non riconosciuto» in a row
/// the recipe is suspended and the interface says so). Persisted in the settings table.
/// </summary>
internal sealed class RecipeHealth
{
private readonly ISettingsStore _settings;
private readonly int _threshold;
private readonly Lock _gate = new();
private readonly Dictionary<RecipeKind, int> _failures = [];
private readonly Dictionary<RecipeKind, DateTimeOffset> _suspended = [];
public RecipeHealth(ISettingsStore settings, int threshold)
{
_settings = settings;
_threshold = Math.Max(1, threshold);
}
public async Task LoadAsync(CancellationToken ct)
{
var failures = await _settings.GetAsync(EngineSettingKeys.RecipeFailures, ct).ConfigureAwait(false);
var suspended = await _settings.GetAsync(EngineSettingKeys.SuspendedRecipes, ct).ConfigureAwait(false);
lock (_gate)
{
_failures.Clear();
_suspended.Clear();
foreach (var (kind, value) in Parse(failures))
{
_failures[kind] = (int)value;
}
foreach (var (kind, value) in Parse(suspended))
{
_suspended[kind] = DateTimeOffset.FromUnixTimeMilliseconds(value);
}
}
}
public IReadOnlyDictionary<RecipeKind, DateTimeOffset> Suspended
{
get
{
lock (_gate)
{
return new Dictionary<RecipeKind, DateTimeOffset>(_suspended);
}
}
}
public bool IsSuspended(RecipeKind kind)
{
lock (_gate)
{
return _suspended.ContainsKey(kind);
}
}
public int Failures(RecipeKind kind)
{
lock (_gate)
{
return _failures.GetValueOrDefault(kind);
}
}
/// <summary>Counts a failure; true when this one suspends the recipe.</summary>
public async Task<bool> RecordFailureAsync(RecipeKind kind, DateTimeOffset now, CancellationToken ct)
{
bool suspendedNow;
lock (_gate)
{
var count = _failures.GetValueOrDefault(kind) + 1;
_failures[kind] = count;
suspendedNow = count >= _threshold && _suspended.TryAdd(kind, now);
}
await SaveAsync(ct).ConfigureAwait(false);
return suspendedNow;
}
public async Task RecordSuccessAsync(RecipeKind kind, CancellationToken ct)
{
lock (_gate)
{
if (!_failures.Remove(kind))
{
return;
}
}
await SaveAsync(ct).ConfigureAwait(false);
}
/// <summary>Alberto updated the reader and reactivated the recipe.</summary>
public async Task<bool> ResumeAsync(RecipeKind kind, CancellationToken ct)
{
bool removed;
lock (_gate)
{
removed = _suspended.Remove(kind);
_failures.Remove(kind);
}
await SaveAsync(ct).ConfigureAwait(false);
return removed;
}
private Task SaveAsync(CancellationToken ct)
{
string failures;
string suspended;
lock (_gate)
{
failures = string.Join(';', _failures.OrderBy(f => f.Key).Select(f => f.Key + "=" + f.Value.ToString(CultureInfo.InvariantCulture)));
suspended = string.Join(';', _suspended.OrderBy(s => s.Key).Select(s => s.Key + "=" + s.Value.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture)));
}
return _settings.SetManyAsync(
new Dictionary<string, string?>
{
[EngineSettingKeys.RecipeFailures] = failures.Length == 0 ? null : failures,
[EngineSettingKeys.SuspendedRecipes] = suspended.Length == 0 ? null : suspended,
},
ct);
}
private static IEnumerable<(RecipeKind Kind, long Value)> Parse(string? text)
{
if (string.IsNullOrWhiteSpace(text))
{
yield break;
}
foreach (var part in text.Split(';', StringSplitOptions.RemoveEmptyEntries))
{
var pair = part.Split('=', 2);
if (pair.Length == 2 && Enum.TryParse<RecipeKind>(pair[0], out var kind)
&& long.TryParse(pair[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out var value))
{
yield return (kind, value);
}
}
}
}
File diff suppressed because it is too large. Load diff