using Febe.Core.Abstractions; using Febe.Core.Collection.Diagnostics; using Febe.Core.Collection.Readers; using Febe.Core.Domain; using Febe.Core.Engine; namespace Febe.Core.Collection.Recipes; /// Stops a recipe where it is, with a status and an Italian message (internal control flow). internal sealed class RecipeStopException(RecipeStatus status, string message) : Exception(message) { public RecipeStatus Status { get; } = status; /// For a failure on an unexpected error: the type name of that exception (diagnostic report, never the message). public string? ErrorType { get; init; } } /// /// The state of one recipe run: counted actions, new entries, the first stop signal seen, and the helpers every /// recipe uses (ask the Governor, open a page, click a target, wait for data). Any of them stops the run with a /// when something says to stop. /// internal sealed class RecipeRun : IDisposable { private readonly RecipeRunner _runner; private readonly IStopSignals _signals; private Signal? _signal; public RecipeRun(RecipeRunner runner, RecipeRequest request, ISessionContext session, CancellationToken ct) { _runner = runner; Request = request; Session = session; Ct = ct; _signals = runner.Env.Signals; _signals.SignalRaised += OnSignal; } public RecipeRequest Request { get; } public ISessionContext Session { get; } public CancellationToken Ct { get; } public int Actions { get; set; } public int NewEntries { get; set; } public HashSet AccountsWithStories { get; } = []; public HashSet AccountsWithNewPosts { get; } = []; public bool Finished { get; set; } /// The first stop signal raised since the run started. public Signal? Signal => Volatile.Read(ref _signal); /// Key structures of unrecognized responses seen in the run. public List UnknownShapes { get; } = []; private RecipeEnvironment Env => _runner.Env; public void Dispose() => _signals.SignalRaised -= OnSignal; public static RecipeStopException Stop(RecipeStatus status, string message) => new(status, message); /// Stops the run when a signal was raised or the breaker is open. public void ThrowIfSignal() { if (Signal is { } signal) { throw Stop(RecipeStatus.StoppedBySignal, RecipeRunner.Describe(signal)); } if (Env.Breaker is { } breaker && !breaker.State.AllowsSiteActions) { throw Stop(RecipeStatus.StoppedBySignal, breaker.State.LastSignal is { } last ? RecipeRunner.Describe(last) : "L'interruttore è aperto: la ricetta si ferma."); } } /// Asks the Governor for a counted action; stops in order when refused or when the session is over. public async Task PermitAsync(ActionKind kind, long? accountId) { ThrowIfSignal(); if (Env.Clock.Now > Session.PlannedEnd) { throw Stop(RecipeStatus.Denied, "La sessione è finita: la ricetta riprenderà alla prossima."); } var permit = await Env.Governor.RequestAsync(kind, accountId, Ct).ConfigureAwait(false); if (!permit.Granted) { throw Stop(RecipeStatus.Denied, permit.Message ?? $"Il Governatore non ha concesso l'azione ({permit.Reason})."); } Actions++; } /// Opens a page of the site map and waits after the load like a person (§7.7). public async Task OpenAsync(string page, IReadOnlyDictionary? values = null) { var path = Env.SiteMap.BuildPath(page, values); PageLoad load; try { load = await Env.Driver.OpenAsync(path, Ct).ConfigureAwait(false); } catch { Env.Diagnostics?.PageOpened(Session.SessionId, page, ok: false); throw; } // The page NAME of the site map, never the path: it holds the user name or the code. Env.Diagnostics?.PageOpened(Session.SessionId, page, load.Succeeded); ThrowIfSignal(); if (!load.Succeeded) { throw Stop(RecipeStatus.Failed, $"La pagina non si è caricata ({load.Error ?? "errore sconosciuto"})."); } await EnsureOnSiteAsync().ConfigureAwait(false); await Env.Driver.WaitAfterLoadAsync(Ct).ConfigureAwait(false); ThrowIfSignal(); return load; } /// Clicks a target of the map; stops and reports when it cannot be found (never coordinates). public async Task ClickAsync(string target, IReadOnlyDictionary? parameters = null) { ThrowIfSignal(); var result = await Env.Driver.ClickAsync(target, parameters, Ct).ConfigureAwait(false); Env.Diagnostics?.TargetClicked(Session.SessionId, target, result.Status); if (!result.Found) { ThrowIfSignal(); throw Stop(RecipeStatus.TargetNotFound, result.Message); } ThrowIfSignal(); await EnsureOnSiteAsync().ConfigureAwait(false); } /// Read-only lookup of a target. public Task FindAsync(string target, IReadOnlyDictionary? parameters = null) => Env.Driver.FindAsync(target, parameters, Ct); /// The page must still be on the site: links outside it are never followed (spec §6.1). public async Task EnsureOnSiteAsync() { if (!await Env.Driver.IsOnSiteAsync(Ct).ConfigureAwait(false)) { ThrowIfSignal(); throw Stop(RecipeStatus.Failed, "La pagina ha portato fuori dal sito: la ricetta si ferma e non segue collegamenti esterni."); } } /// Waits for reads after that satisfy , or for a stop signal. public async Task> WaitForDataAsync(long mark, Func expected, TimeSpan? timeout = null) { var reads = await Env.Capture.WaitAsync( mark, r => Signal is not null || r.Any(x => x.Result.Shape == ReadShape.Recognized && expected(x.Result)), timeout ?? Env.Options.DataTimeout, Env.Options.Poll, Ct).ConfigureAwait(false); ThrowIfSignal(); return reads; } /// Waits until no data response is on its way any more. public async Task SettleAsync() { await Env.Capture.SettleAsync(Env.Options.SettleQuiet, Env.Options.DataTimeout, Env.Options.Poll, Ct).ConfigureAwait(false); ThrowIfSignal(); } /// /// Judges the reads of a step that expected : recognized data resets the empty-page /// counter; only unknown shapes stop the run with ; nothing at all is /// an empty page (three in a row raise a throttle signal). Returns true when the expected data arrived. /// public bool Judge(IReadOnlyList reads, Func expected, string? where) { if (reads.Any(r => r.Result.Shape == ReadShape.Recognized && expected(r.Result))) { Env.Diagnostics?.StepJudged(Session.SessionId, CollectionDiagnostics.VerdictRecognized); _signals.ObserveNonEmptyPage(); return true; } var unknown = reads.Where(r => r.Result.Shape == ReadShape.Unrecognized && r.Result.KeyStructure is not null).Select(r => r.Result.KeyStructure!).Distinct().ToList(); if (unknown.Count > 0) { Env.Diagnostics?.StepJudged(Session.SessionId, CollectionDiagnostics.VerdictUnknown); UnknownShapes.AddRange(unknown); throw Stop(RecipeStatus.UnrecognizedFormat, "La risposta del sito ha una forma che i lettori non riconoscono."); } Env.Diagnostics?.StepJudged(Session.SessionId, CollectionDiagnostics.VerdictEmpty); _signals.ObserveEmptyPage(where); ThrowIfSignal(); return false; } private void OnSignal(object? sender, Signal signal) => Interlocked.CompareExchange(ref _signal, signal, null); }