Files
Febe/tests/Febe.Tests/Engine/Support/EngineTestBed.cs
T

173 lines
6.2 KiB
C#

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();
}
}