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; /// /// A temporary database, a virtual clock in Rome's zone and the engine services on top, with a fixed seed. /// builds new engine objects on the same database, as a restart of the program does. /// 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; /// Wednesday 14 October 2026 at 12:00 in Rome: inside every profile's window whatever the daily shift. 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); /// A bed with the given profile; the gradual start is off unless asked, so budgets are the profile's. public static async Task CreateAsync( DateTimeOffset? start = null, CautionProfileKind profile = CautionProfileKind.Prudent, bool gradualStart = false, int seed = 7, EngineOptions? options = null, EngineSettings? settings = null, Func? userIsDriving = null, Func? 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); } /// New engine objects on the same database (a restart), with a different random stream. public async Task ReopenAsync(int seed, Func? userIsDriving = null) { await StopAsync(); Services = await EngineServices.CreateAsync(Db, Clock, new SeededRandom(seed), Options, userIsDriving); return Services; } public async Task 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); } /// A session as the engine opens it, for testing the Governor alone. public async Task 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; } /// Starts the engine loop on the virtual clock (no time passes until ). public EngineHost Start(IRecipeRunner runner) { _host = new EngineHost(Services, runner); _loopCts = new CancellationTokenSource(); _loop = _host.RunAsync(_loopCts.Token); return _host; } /// /// Like , with run on the host before its loop, as the composition /// does at start-up (). /// public async Task StartAsync(IRecipeRunner runner, Func beforeLoop) { _host = new EngineHost(Services, runner); await beforeLoop(_host); _loopCts = new CancellationTokenSource(); _loop = _host.RunAsync(_loopCts.Token); return _host; } public EngineHost Host => _host ?? throw new InvalidOperationException("Engine not started."); /// Advances virtual time to , letting the engine run. 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); /// Stops the loop as a shutdown would (a session in progress ends interrupted). 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(); } }