Files

321 lines
16 KiB
C#

using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Tests.Engine.Support;
namespace Febe.Tests.Engine;
[TestClass]
public sealed class GovernorTests
{
[TestMethod]
public async Task GrantsInsideTheWindowDuringASessionAndRecordsTheAction()
{
await using var bed = await EngineTestBed.CreateAsync();
var account = await bed.AddAccountAsync("marta.demo", followed: false);
var session = await bed.BeginSessionAsync();
var permit = await bed.Governor.RequestAsync(ActionKind.ProfileOpen, account.Id, CancellationToken.None);
Assert.IsTrue(permit.Granted, permit.Message);
var logged = await bed.Db.ActionLog.ListAsync(bed.Clock.Now.AddMinutes(-1), bed.Clock.Now.AddMinutes(1));
Assert.HasCount(1, logged);
Assert.AreEqual(ActionKind.ProfileOpen, logged[0].Category);
Assert.AreEqual(account.Id, logged[0].AccountId);
Assert.AreEqual(session.SessionId, logged[0].SessionId);
Assert.AreEqual(1, session.ActionCount);
}
[TestMethod]
public async Task RefusesWithoutASession()
{
await using var bed = await EngineTestBed.CreateAsync();
var permit = await bed.Governor.RequestAsync(ActionKind.Home, null, CancellationToken.None);
Assert.IsFalse(permit.Granted);
Assert.AreEqual(DenialReason.NoSession, permit.Reason);
Assert.IsFalse(string.IsNullOrWhiteSpace(permit.Message));
Assert.HasCount(0, await bed.Db.ActionLog.ListAsync(bed.Clock.Now.AddDays(-1), bed.Clock.Now.AddDays(1)));
}
[TestMethod]
public async Task RefusesOutsideTheWindowWithTheNextWindowAsRetryTime()
{
await using var bed = await EngineTestBed.CreateAsync(EngineTestBed.Local(2026, 10, 14, 3, 0));
await bed.BeginSessionAsync();
var permit = await bed.Governor.RequestAsync(ActionKind.Home, null, CancellationToken.None);
Assert.AreEqual(DenialReason.OutsideActiveWindow, permit.Reason);
Assert.IsNotNull(permit.RetryAfter);
var window = await bed.Services.Planner.GetWindowAsync(new DateOnly(2026, 10, 14));
Assert.AreEqual(window!.Start, permit.RetryAfter);
StringAssert.Contains(permit.Message!, "verso le");
}
[TestMethod]
public async Task TheBreakerIsCheckedFirst()
{
await using var bed = await EngineTestBed.CreateAsync(EngineTestBed.Local(2026, 10, 14, 3, 0));
await bed.Breaker.ReportAsync(new Signal(SignalLevel.Challenge, "challenge-url", "https://sito.prova/challenge", bed.Clock.Now));
// Outside the window and without a session too: the breaker comes first.
var permit = await bed.Governor.RequestAsync(ActionKind.Home, null, CancellationToken.None);
Assert.AreEqual(DenialReason.BreakerOpen, permit.Reason);
StringAssert.Contains(permit.Message!, "verifica");
}
[TestMethod]
public async Task PauseAndAlbertoAtTheBrowserRefuse()
{
var driving = false;
await using var bed = await EngineTestBed.CreateAsync(userIsDriving: () => driving);
await bed.BeginSessionAsync();
bed.Runtime.IsPaused = true;
Assert.AreEqual(DenialReason.Paused, (await bed.Governor.RequestAsync(ActionKind.Home, null, CancellationToken.None)).Reason);
bed.Runtime.IsPaused = false;
driving = true;
Assert.AreEqual(DenialReason.UserIsDriving, (await bed.Governor.RequestAsync(ActionKind.Home, null, CancellationToken.None)).Reason);
driving = false;
Assert.IsTrue((await bed.Governor.RequestAsync(ActionKind.Home, null, CancellationToken.None)).Granted);
}
[TestMethod]
public async Task TheHourlyBudgetIsARolling60MinuteWindow()
{
await using var bed = await EngineTestBed.CreateAsync();
bed.Clock.AutoAdvance = true;
await bed.BeginSessionAsync();
var first = bed.Clock.Now;
// «Prudente»: 4 home pages per hour.
for (var i = 0; i < 4; i++)
{
Assert.IsTrue((await bed.Governor.RequestAsync(ActionKind.Home, null, CancellationToken.None)).Granted);
}
var denied = await bed.Governor.RequestAsync(ActionKind.Home, null, CancellationToken.None);
Assert.AreEqual(DenialReason.HourlyBudgetReached, denied.Reason);
Assert.AreEqual(first + TimeSpan.FromHours(1), denied.RetryAfter);
StringAssert.Contains(denied.Message!, "tetto orario");
// Other categories go on.
Assert.IsTrue((await bed.Governor.RequestAsync(ActionKind.StoryView, null, CancellationToken.None)).Granted);
bed.Clock.AdvanceTo(first + TimeSpan.FromHours(1));
Assert.IsTrue((await bed.Governor.RequestAsync(ActionKind.Home, null, CancellationToken.None)).Granted);
}
[TestMethod]
public async Task TheDailyBudgetUsesTheLocalCalendarDayAndComesFromTheDatabase()
{
await using var bed = await EngineTestBed.CreateAsync();
var account = await bed.AddAccountAsync("luca.demo", followed: false);
var morning = EngineTestBed.Local(2026, 10, 14, 8, 0);
for (var i = 0; i < 100; i++)
{
await bed.Db.ActionLog.AppendAsync(new ActionLogRecord { At = morning.AddSeconds(i * 20), Category = ActionKind.ProfileOpen, AccountId = account.Id });
}
// Yesterday's actions do not count today.
await bed.Db.ActionLog.AppendAsync(new ActionLogRecord { At = morning.AddDays(-1), Category = ActionKind.StoryView });
await bed.BeginSessionAsync();
var denied = await bed.Governor.RequestAsync(ActionKind.ProfileOpen, account.Id, CancellationToken.None);
Assert.AreEqual(DenialReason.DailyBudgetReached, denied.Reason);
Assert.IsTrue(denied.RetryAfter >= EngineTestBed.Local(2026, 10, 15, 0, 0));
StringAssert.Contains(denied.Message!, "domani");
var events = await bed.Db.Events.ListAsync(new Febe.Core.Storage.EventQuery());
Assert.IsTrue(events.Any(e => e.Code == EngineEventCodes.BudgetReached));
}
[TestMethod]
[DataRow(GesturePace.Natural, 4000)]
[DataRow(GesturePace.Brisk, 3000)]
[DataRow(GesturePace.Slow, 5400)]
public async Task TheMinimumSpacingIsWaitedAndScaledByThePace(GesturePace pace, int spacingMs)
{
await using var bed = await EngineTestBed.CreateAsync(settings: new EngineSettings { GradualStart = false, Pace = pace });
bed.Clock.AutoAdvance = true;
await bed.BeginSessionAsync();
Assert.IsTrue((await bed.Governor.RequestAsync(ActionKind.StoryView, null, CancellationToken.None)).Granted);
var evaluation = await bed.Governor.EvaluateAsync(ActionKind.StoryView, null);
Assert.AreEqual(DenialReason.MinimumSpacing, evaluation.Reason);
Assert.IsTrue((await bed.Governor.RequestAsync(ActionKind.StoryView, null, CancellationToken.None)).Granted);
var log = await bed.Db.ActionLog.ListAsync(bed.Clock.Now.AddHours(-1), bed.Clock.Now.AddSeconds(1));
Assert.HasCount(2, log);
Assert.AreEqual(TimeSpan.FromMilliseconds(spacingMs), log[1].At - log[0].At);
}
[TestMethod]
public async Task TheAccountBackfillLimitCountsPostsDiscoveredToday()
{
await using var bed = await EngineTestBed.CreateAsync();
var account = await bed.AddAccountAsync("storico.demo", followed: true, state: AccountState.Backfilling, backfillPerDay: 24);
for (var i = 0; i < 24; i++)
{
await bed.Db.Entries.AddAsync(
new Entry { AccountId = account.Id, Kind = EntryKind.Post, InstagramId = "p" + i, PublishedAt = bed.Clock.Now.AddDays(-100 - i), DiscoveredAt = bed.Clock.Now.AddMinutes(-30) },
[new Media { Position = 1, Kind = MediaKind.Photo }]);
}
await bed.BeginSessionAsync();
var denied = await bed.Governor.RequestAsync(ActionKind.BackfillPage, account.Id, CancellationToken.None);
Assert.AreEqual(DenialReason.AccountLimitReached, denied.Reason);
StringAssert.Contains(denied.Message!, "@storico.demo");
// Other categories of the same account are not limited by the backfill limit.
Assert.IsTrue((await bed.Governor.RequestAsync(ActionKind.ProfileOpen, account.Id, CancellationToken.None)).Granted);
}
[TestMethod]
public async Task AccountsThatMustNotBeContactedAreRefused()
{
await using var bed = await EngineTestBed.CreateAsync();
var archive = await bed.AddAccountAsync("archivio.demo", followed: false, state: AccountState.ArchiveOnly);
var paused = await bed.AddAccountAsync("pausa.demo", followed: false, state: AccountState.Paused);
var session = await bed.BeginSessionAsync();
Assert.AreEqual(DenialReason.AccountNotContactable, (await bed.Governor.RequestAsync(ActionKind.ProfileOpen, archive.Id, CancellationToken.None)).Reason);
Assert.AreEqual(DenialReason.AccountNotContactable, (await bed.Governor.RequestAsync(ActionKind.ProfileOpen, paused.Id, CancellationToken.None)).Reason);
// «Controlla ora» on a paused account is allowed; on an archive-only one never.
session.ManualAccountId = paused.Id;
Assert.IsTrue((await bed.Governor.RequestAsync(ActionKind.ProfileOpen, paused.Id, CancellationToken.None)).Granted);
session.ManualAccountId = archive.Id;
bed.Clock.Advance(TimeSpan.FromSeconds(10));
Assert.AreEqual(DenialReason.AccountNotContactable, (await bed.Governor.RequestAsync(ActionKind.ProfileOpen, archive.Id, CancellationToken.None)).Reason);
}
[TestMethod]
public async Task AConfirmedManualCheckOutsideTheWindowAllowsOnlyThatAccount()
{
await using var bed = await EngineTestBed.CreateAsync(EngineTestBed.Local(2026, 10, 14, 2, 0));
var asked = await bed.AddAccountAsync("chiesto.demo", followed: false);
var other = await bed.AddAccountAsync("altro.demo", followed: false);
await bed.BeginSessionAsync(outsideWindowAccountId: asked.Id);
Assert.IsTrue((await bed.Governor.RequestAsync(ActionKind.ProfileOpen, asked.Id, CancellationToken.None)).Granted);
bed.Clock.Advance(TimeSpan.FromSeconds(10));
Assert.AreEqual(DenialReason.OutsideActiveWindow, (await bed.Governor.RequestAsync(ActionKind.ProfileOpen, other.Id, CancellationToken.None)).Reason);
Assert.AreEqual(DenialReason.OutsideActiveWindow, (await bed.Governor.RequestAsync(ActionKind.Home, null, CancellationToken.None)).Reason);
}
[TestMethod]
public void TheGradualStartGoesFromHalfToFullLinearly()
{
var profile = CautionProfile.Prudent;
var start = EngineTestBed.Noon;
Assert.AreEqual(0.5, BudgetLimits.GradualStartFactor(profile, start, start), 1e-9);
Assert.AreEqual(0.75, BudgetLimits.GradualStartFactor(profile, start, start.AddDays(3.5)), 1e-9);
Assert.AreEqual(1.0, BudgetLimits.GradualStartFactor(profile, start, start.AddDays(7)), 1e-9);
Assert.AreEqual(1.0, BudgetLimits.GradualStartFactor(profile with { GradualStart = false }, start, start), 1e-9);
var budgets = BudgetLimits.Compute(profile, start, null, start);
Assert.AreEqual(BudgetReduction.GradualStart, budgets.Reduction);
Assert.AreEqual(new Budget(6, 50), budgets.Budgets[ActionKind.ProfileOpen]);
Assert.AreEqual(2L * 1024 * 1024 * 1024, budgets.DataPerDayBytes);
Assert.AreEqual(150, budgets.BackfillPostsPerAccountPerDay);
}
[TestMethod]
public void TheStrongestReductionWinsNeverTheProduct()
{
var profile = CautionProfile.Prudent;
var start = EngineTestBed.Noon;
var now = start.AddDays(2);
var halvedUntil = now.AddHours(10);
var both = BudgetLimits.Compute(profile, start, halvedUntil, now);
Assert.AreEqual(0.5, both.Factor, 1e-9, "Halved (0.5) is stronger than the ramp at day 2 (0.64): 0.5, not 0.32.");
Assert.AreEqual(BudgetReduction.HalvedAfterThrottle, both.Reduction);
Assert.AreEqual(new Budget(6, 50), both.Budgets[ActionKind.ProfileOpen]);
var rampOnly = BudgetLimits.Compute(profile, start, halvedUntil, halvedUntil);
Assert.AreEqual(0.5 + (0.5 * (2 + (10.0 / 24)) / 7), rampOnly.Factor, 1e-9);
Assert.AreEqual(BudgetReduction.GradualStart, rampOnly.Reduction);
var none = BudgetLimits.Compute(profile, start, halvedUntil, start.AddDays(8));
Assert.AreEqual(1, none.Factor);
Assert.AreEqual(BudgetReduction.None, none.Reduction);
}
[TestMethod]
public async Task HalvedBudgetsApplyAfterAThrottle()
{
await using var bed = await EngineTestBed.CreateAsync();
await bed.Breaker.ReportAsync(new Signal(SignalLevel.Throttle, "http-429", null, bed.Clock.Now));
bed.Clock.Advance(TimeSpan.FromHours(1));
var budgets = bed.Governor.GetEffectiveBudgets(bed.Clock.Now);
Assert.AreEqual(BudgetReduction.HalvedAfterThrottle, budgets.Reduction);
Assert.AreEqual(new Budget(2, 15), budgets.Budgets[ActionKind.Home]);
bed.Clock.Advance(TimeSpan.FromHours(48));
Assert.AreEqual(BudgetReduction.None, bed.Governor.GetEffectiveBudgets(bed.Clock.Now).Reduction);
}
[TestMethod]
public async Task TheDataBudgetIsDailyInBytesAndWorksDuringAStop()
{
await using var bed = await EngineTestBed.CreateAsync();
var full = 4L * 1024 * 1024 * 1024;
Assert.AreEqual(full, await bed.Governor.RemainingTodayAsync(CancellationToken.None));
// After a throttle the data budget is halved too.
await bed.Breaker.ReportAsync(new Signal(SignalLevel.Throttle, "http-429", null, bed.Clock.Now));
Assert.AreEqual(full / 2, await bed.Governor.RemainingTodayAsync(CancellationToken.None));
await bed.Governor.RecordAsync((full / 2) - 1000, null, CancellationToken.None);
Assert.AreEqual(1000L, await bed.Governor.RemainingTodayAsync(CancellationToken.None));
// Queued downloads may complete during a stop: the data budget does not look at the breaker.
Assert.IsTrue((await bed.Governor.RequestAsync(ActionKind.DataDownload, null, CancellationToken.None)).Granted);
await bed.Governor.RecordAsync(1000, null, CancellationToken.None);
var denied = await bed.Governor.RequestAsync(ActionKind.DataDownload, null, CancellationToken.None);
Assert.AreEqual(DenialReason.DailyBudgetReached, denied.Reason);
Assert.AreEqual(0L, await bed.Governor.RemainingTodayAsync(CancellationToken.None));
bed.Clock.AdvanceTo(EngineTestBed.Local(2026, 10, 15, 0, 0));
Assert.IsTrue(await bed.Governor.RemainingTodayAsync(CancellationToken.None) > 0);
}
[TestMethod]
public async Task RemainingSaysHowMuchRoomIsLeft()
{
await using var bed = await EngineTestBed.CreateAsync();
bed.Clock.AutoAdvance = true;
await bed.BeginSessionAsync();
Assert.AreEqual(50L, await bed.Governor.RemainingAsync(ActionKind.StoryView));
for (var i = 0; i < 45; i++)
{
await bed.Governor.RequestAsync(ActionKind.StoryView, null, CancellationToken.None);
}
Assert.AreEqual(5L, await bed.Governor.RemainingAsync(ActionKind.StoryView), "Not room for ten stories in this hour.");
}
[TestMethod]
public async Task BudgetsTurnAmberFrom80Percent()
{
await using var bed = await EngineTestBed.CreateAsync();
bed.Clock.AutoAdvance = true;
await bed.BeginSessionAsync();
for (var i = 0; i < 3; i++)
{
await bed.Governor.RequestAsync(ActionKind.Home, null, CancellationToken.None);
}
var statuses = await bed.Governor.GetBudgetStatusAsync();
var home = statuses.Single(s => s.Kind == ActionKind.Home);
Assert.AreEqual(3L, home.UsedLastHour);
Assert.IsFalse(home.IsAmber, "3 of 4 is 75%.");
await bed.Governor.RequestAsync(ActionKind.Home, null, CancellationToken.None);
home = (await bed.Governor.GetBudgetStatusAsync()).Single(s => s.Kind == ActionKind.Home);
Assert.IsTrue(home.IsAmber);
Assert.IsTrue(home.HourlyReached);
Assert.IsFalse(statuses.Single(s => s.Kind == ActionKind.StoryView).IsAmber);
}
}