using Febe.Core.Abstractions; using Febe.Core.Engine; namespace Febe.Tests.Engine.Support; /// A recipe run seen by . internal sealed record RunRecord(DateTimeOffset At, RecipeRequest Request, long SessionId, RecipeStatus Status); /// /// 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 says /// otherwise. Records every run. /// internal sealed class ScriptedRunner(IGovernor governor, IClock clock) : IRecipeRunner { private readonly Lock _gate = new(); private readonly List _runs = []; /// Forced outcome for a request (null: default behaviour). Runs before the Governor is asked. public Func? Script { get; set; } /// Called after the counted action was granted (e.g. to report a signal). public Action? AfterGrant { get; set; } /// /// Awaited when a recipe starts, while its task is running (e.g. what the real recipe writes, or a command of /// Alberto arriving meanwhile). /// public Func? Before { get; set; } /// Accounts the stories bar flags in every sweep. public IReadOnlyList FlaggedStories { get; set; } = []; public int Rests { get; private set; } public IReadOnlyList Runs { get { lock (_gate) { return [.. _runs]; } } } public async Task RunAsync(RecipeRequest request, ISessionContext session, CancellationToken ct) { RecipeOutcome outcome; try { if (Before is { } before) { await before(request); } 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 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 : [], }; } }