M3 Motore: Governatore con tetti da action_log, interruttore con fermi 1/6/24 ore e ripresa manuale, fascia giornaliera spostata a caso e salvata, sessioni con pause log-normali e pavimento, composizione delle sessioni sulla coda persistente, «Controlla ora» con conferma fuori fascia, cruscotto per l'interfaccia e calcolatore «Con queste impostazioni», simulazione con orologio virtuale e comando --simula; prove del motore e dell'interruttore
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
38 files changed
+9308
No files matched your search
@@ -0,0 +1,71 @@
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.Tests.Engine.Support;
|
||||
|
||||
/// <summary>
|
||||
/// Independent check of the budgets from <c>action_log</c>: at every action, the rolling hour and the local day so far
|
||||
/// must stay within the profile's full limits (reductions only make them lower).
|
||||
/// </summary>
|
||||
internal static class BudgetAudit
|
||||
{
|
||||
private static readonly TimeSpan Hour = TimeSpan.FromMinutes(60);
|
||||
|
||||
public static async Task<IReadOnlyList<string>> OverrunsAsync(IFebeStorage storage, CautionProfile profile, TimeZoneInfo zone, DateTimeOffset from, DateTimeOffset to)
|
||||
{
|
||||
var actions = await storage.ActionLog.ListAsync(from, to);
|
||||
var problems = new List<string>();
|
||||
foreach (var kind in Enum.GetValues<ActionKind>())
|
||||
{
|
||||
var list = actions.Where(a => a.Category == kind).OrderBy(a => a.At).ThenBy(a => a.Id).ToList();
|
||||
var first = 0;
|
||||
long hour = 0;
|
||||
long day = 0;
|
||||
DateOnly? current = null;
|
||||
foreach (var action in list)
|
||||
{
|
||||
hour += action.Amount;
|
||||
while (list[first].At <= action.At - Hour)
|
||||
{
|
||||
hour -= list[first].Amount;
|
||||
first++;
|
||||
}
|
||||
|
||||
var today = LocalCalendar.Today(action.At, zone);
|
||||
if (today != current)
|
||||
{
|
||||
current = today;
|
||||
day = 0;
|
||||
}
|
||||
|
||||
day += action.Amount;
|
||||
var over = kind == ActionKind.DataDownload
|
||||
? day > profile.DataPerDayBytes
|
||||
: hour > profile.Budgets[kind].PerHour || day > profile.Budgets[kind].PerDay;
|
||||
if (over)
|
||||
{
|
||||
problems.Add($"{kind} at {action.At:O}: hour {hour}, day {day}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return problems;
|
||||
}
|
||||
|
||||
/// <summary>Actions (data excluded) that fall outside the active window of their day.</summary>
|
||||
public static async Task<IReadOnlyList<ActionLogRecord>> OutsideWindowAsync(IFebeStorage storage, DayPlanner planner, DateTimeOffset from, DateTimeOffset to)
|
||||
{
|
||||
var outside = new List<ActionLogRecord>();
|
||||
foreach (var action in (await storage.ActionLog.ListAsync(from, to)).Where(a => a.Category != ActionKind.DataDownload))
|
||||
{
|
||||
if (await planner.GetWindowAtAsync(action.At) is null)
|
||||
{
|
||||
outside.Add(action);
|
||||
}
|
||||
}
|
||||
|
||||
return outside;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Simulation;
|
||||
using Febe.Data;
|
||||
using Febe.Tests.Support;
|
||||
|
||||
namespace Febe.Tests.Engine.Support;
|
||||
|
||||
/// <summary>
|
||||
/// A temporary database, a virtual clock in Rome's zone and the engine services on top, with a fixed seed.
|
||||
/// <see cref="ReopenAsync"/> builds new engine objects on the same database, as a restart of the program does.
|
||||
/// </summary>
|
||||
internal sealed class EngineTestBed : IAsyncDisposable
|
||||
{
|
||||
private readonly TempFolder _folder;
|
||||
private EngineHost? _host;
|
||||
private CancellationTokenSource? _loopCts;
|
||||
private Task? _loop;
|
||||
|
||||
private EngineTestBed(TempFolder folder, FebeDatabase db, VirtualClock clock, EngineServices services, EngineOptions options, int seed)
|
||||
{
|
||||
_folder = folder;
|
||||
Db = db;
|
||||
Clock = clock;
|
||||
Services = services;
|
||||
Options = options;
|
||||
Seed = seed;
|
||||
}
|
||||
|
||||
public static TimeZoneInfo Zone => SimulationZones.Rome;
|
||||
|
||||
/// <summary>Wednesday 14 October 2026 at 12:00 in Rome: inside every profile's window whatever the daily shift.</summary>
|
||||
public static DateTimeOffset Noon { get; } = Local(2026, 10, 14, 12, 0);
|
||||
|
||||
public FebeDatabase Db { get; }
|
||||
|
||||
public VirtualClock Clock { get; }
|
||||
|
||||
public EngineServices Services { get; private set; }
|
||||
|
||||
public EngineOptions Options { get; }
|
||||
|
||||
public int Seed { get; }
|
||||
|
||||
public Governor Governor => Services.Governor;
|
||||
|
||||
public CircuitBreaker Breaker => Services.Breaker;
|
||||
|
||||
public EngineRuntime Runtime => Services.Runtime;
|
||||
|
||||
public static DateTimeOffset Local(int year, int month, int day, int hour, int minute) =>
|
||||
LocalCalendar.FromLocal(new DateTime(year, month, day, hour, minute, 0), Zone);
|
||||
|
||||
/// <summary>A bed with the given profile; the gradual start is off unless asked, so budgets are the profile's.</summary>
|
||||
public static async Task<EngineTestBed> CreateAsync(
|
||||
DateTimeOffset? start = null,
|
||||
CautionProfileKind profile = CautionProfileKind.Prudent,
|
||||
bool gradualStart = false,
|
||||
int seed = 7,
|
||||
EngineOptions? options = null,
|
||||
EngineSettings? settings = null,
|
||||
Func<bool>? userIsDriving = null,
|
||||
Func<bool>? isConnected = null)
|
||||
{
|
||||
var folder = new TempFolder("motore");
|
||||
var db = await FebeDatabase.OpenAsync(folder.Combine("dati"));
|
||||
var clock = new VirtualClock(start ?? Noon, Zone);
|
||||
settings ??= new EngineSettings { ProfileKind = profile, GradualStart = gradualStart };
|
||||
await EngineSettingsStore.SaveAsync(db.Settings, settings);
|
||||
options ??= EngineOptions.Default;
|
||||
var services = await EngineServices.CreateAsync(db, clock, new SeededRandom(seed), options, userIsDriving, isConnected);
|
||||
return new EngineTestBed(folder, db, clock, services, options, seed);
|
||||
}
|
||||
|
||||
/// <summary>New engine objects on the same database (a restart), with a different random stream.</summary>
|
||||
public async Task<EngineServices> ReopenAsync(int seed, Func<bool>? userIsDriving = null)
|
||||
{
|
||||
await StopAsync();
|
||||
Services = await EngineServices.CreateAsync(Db, Clock, new SeededRandom(seed), Options, userIsDriving);
|
||||
return Services;
|
||||
}
|
||||
|
||||
public async Task<Account> AddAccountAsync(
|
||||
string username,
|
||||
bool followed,
|
||||
Frequency frequency = Frequency.Normal,
|
||||
AccountState state = AccountState.UpToDate,
|
||||
ContentTypes? types = null,
|
||||
int? postCount = null,
|
||||
int? backfillPerDay = null)
|
||||
{
|
||||
var account = Account.Create(username, StartingPoint.EverythingAndKeepUpdated, Clock.Now, Zone, Runtime.Profile) with
|
||||
{
|
||||
InstagramId = "77" + ((uint)username.GetHashCode(StringComparison.Ordinal)).ToString(System.Globalization.CultureInfo.InvariantCulture),
|
||||
IsFollowed = followed,
|
||||
Frequency = frequency,
|
||||
State = state,
|
||||
BackfillCompletedAt = state == AccountState.Backfilling ? null : Clock.Now,
|
||||
PostCount = postCount,
|
||||
};
|
||||
if (types is { } t)
|
||||
{
|
||||
account = account with { ContentTypes = t };
|
||||
}
|
||||
|
||||
if (backfillPerDay is { } perDay)
|
||||
{
|
||||
account = account with { Limits = account.Limits with { BackfillPostsPerDay = perDay } };
|
||||
}
|
||||
|
||||
return await Db.Accounts.AddAsync(account);
|
||||
}
|
||||
|
||||
/// <summary>A session as the engine opens it, for testing the Governor alone.</summary>
|
||||
public async Task<SessionContext> BeginSessionAsync(long? outsideWindowAccountId = null)
|
||||
{
|
||||
var record = await Db.Sessions.StartAsync(Clock.Now);
|
||||
var session = new SessionContext(record.Id, 1, Clock.Now, Clock.Now + TimeSpan.FromMinutes(10), outsideWindowAccountId);
|
||||
Runtime.CurrentSession = session;
|
||||
return session;
|
||||
}
|
||||
|
||||
/// <summary>Starts the engine loop on the virtual clock (no time passes until <see cref="RunUntilAsync"/>).</summary>
|
||||
public EngineHost Start(IRecipeRunner runner)
|
||||
{
|
||||
_host = new EngineHost(Services, runner);
|
||||
_loopCts = new CancellationTokenSource();
|
||||
_loop = _host.RunAsync(_loopCts.Token);
|
||||
return _host;
|
||||
}
|
||||
|
||||
public EngineHost Host => _host ?? throw new InvalidOperationException("Engine not started.");
|
||||
|
||||
/// <summary>Advances virtual time to <paramref name="target"/>, letting the engine run.</summary>
|
||||
public Task RunUntilAsync(DateTimeOffset target) =>
|
||||
_loop is null ? Task.Run(() => Clock.AdvanceTo(target)) : Clock.RunUntilAsync(target, CancellationToken.None, _loop);
|
||||
|
||||
public Task RunForAsync(TimeSpan span) => RunUntilAsync(Clock.Now + span);
|
||||
|
||||
/// <summary>Stops the loop as a shutdown would (a session in progress ends interrupted).</summary>
|
||||
public async Task StopAsync()
|
||||
{
|
||||
if (_loop is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await _loopCts!.CancelAsync();
|
||||
try
|
||||
{
|
||||
await _loop;
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
|
||||
await _host!.DisposeAsync();
|
||||
_loopCts.Dispose();
|
||||
_loop = null;
|
||||
_loopCts = null;
|
||||
_host = null;
|
||||
await Breaker.FlushAsync();
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await StopAsync();
|
||||
await Db.DisposeAsync();
|
||||
_folder.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Engine;
|
||||
|
||||
namespace Febe.Tests.Engine.Support;
|
||||
|
||||
/// <summary>A recipe run seen by <see cref="ScriptedRunner"/>.</summary>
|
||||
internal sealed record RunRecord(DateTimeOffset At, RecipeRequest Request, long SessionId, RecipeStatus Status);
|
||||
|
||||
/// <summary>
|
||||
/// A recipe runner for engine tests: asks the Governor for one counted action like the real recipes (stories:
|
||||
/// none, as if no story was active), spends a little virtual time and completes, unless <see cref="Script"/> says
|
||||
/// otherwise. Records every run.
|
||||
/// </summary>
|
||||
internal sealed class ScriptedRunner(IGovernor governor, IClock clock) : IRecipeRunner
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
private readonly List<RunRecord> _runs = [];
|
||||
|
||||
/// <summary>Forced outcome for a request (null: default behaviour). Runs before the Governor is asked.</summary>
|
||||
public Func<RecipeRequest, RecipeOutcome?>? Script { get; set; }
|
||||
|
||||
/// <summary>Called after the counted action was granted (e.g. to report a signal).</summary>
|
||||
public Action<RecipeRequest>? AfterGrant { get; set; }
|
||||
|
||||
/// <summary>Accounts the stories bar flags in every sweep.</summary>
|
||||
public IReadOnlyList<long> FlaggedStories { get; set; } = [];
|
||||
|
||||
public int Rests { get; private set; }
|
||||
|
||||
public IReadOnlyList<RunRecord> Runs
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return [.. _runs];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<RecipeOutcome> RunAsync(RecipeRequest request, ISessionContext session, CancellationToken ct)
|
||||
{
|
||||
RecipeOutcome outcome;
|
||||
try
|
||||
{
|
||||
outcome = Script?.Invoke(request) ?? await DefaultAsync(request, ct);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_runs.Add(new RunRecord(clock.Now, request, session.SessionId, RecipeStatus.Cancelled));
|
||||
}
|
||||
|
||||
throw;
|
||||
}
|
||||
|
||||
lock (_gate)
|
||||
{
|
||||
_runs.Add(new RunRecord(clock.Now, request, session.SessionId, outcome.Status));
|
||||
}
|
||||
|
||||
return outcome;
|
||||
}
|
||||
|
||||
public Task RestAsync(CancellationToken ct)
|
||||
{
|
||||
Rests++;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private async Task<RecipeOutcome> DefaultAsync(RecipeRequest request, CancellationToken ct)
|
||||
{
|
||||
if (request.Kind == RecipeKind.AccountStories)
|
||||
{
|
||||
await clock.Delay(TimeSpan.FromSeconds(2), ct);
|
||||
return new RecipeOutcome(RecipeStatus.Completed, 0, 0);
|
||||
}
|
||||
|
||||
var kind = CheckPolicy.CategoryOf(request.Kind);
|
||||
var pages = request.Kind == RecipeKind.Backfill ? Math.Max(1, request.MaxPages ?? 1) : 1;
|
||||
var counted = 0;
|
||||
for (var i = 0; i < pages; i++)
|
||||
{
|
||||
var permit = await governor.RequestAsync(kind, request.AccountId, ct);
|
||||
if (!permit.Granted)
|
||||
{
|
||||
return new RecipeOutcome(counted > 0 ? RecipeStatus.Completed : RecipeStatus.Denied, counted, 0);
|
||||
}
|
||||
|
||||
counted++;
|
||||
AfterGrant?.Invoke(request);
|
||||
await clock.Delay(TimeSpan.FromSeconds(5), ct);
|
||||
}
|
||||
|
||||
return new RecipeOutcome(RecipeStatus.Completed, counted, 0)
|
||||
{
|
||||
AccountsWithStories = request.Kind == RecipeKind.FollowingSweep ? FlaggedStories : [],
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user