Files
Febe/src/Febe.Core/Collection/Recipes/RecipeRun.cs
T
Alby96andClaude Opus 5.5 9941a2fa1f
verifica / controlli (push) Successful in 20s
verifica / prove (push) Failing after 19m40s
verifica / installatore (push) Skipped
verifica / immagine (push) Skipped
Ricerca dei profili con suggerimenti e foto (#37)
«Aggiungi account» ha una sola casella: mentre Alberto scrive compaiono
subito i suggerimenti locali, poi i profili di Instagram con la foto, come
chiesto in #37. Il browser di Febe scrive nella casella «Cerca» di Instagram
con tasti veri da una mappa chiusa (mai Invio, Tab o Esc), controlla prima
il fuoco, legge la risposta della pagina e non clicca mai un risultato.

La ricerca ha una categoria propria nel Governatore, con tetti larghi che
non consumano quelli della raccolta, e si dà il turno con il motore
sull'unica pagina; a fine sessione la pagina torna comunque al riposo. Le
foto passano dal CDN con un permesso ciascuna e restano solo in memoria.

Le risposte di Alberto del 15 novembre (controllo del fuoco, turni, evento
requestWillBeSent, niente foto dei seguiti per ora) sono in §6.1 e in
docs/decisioni.md. Su Instagram vero la ricerca parte quando i bersagli
search-open e search-box saranno raccolti dal vivo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 16:30:03 +01:00

219 lines
8.9 KiB
C#

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;
/// <summary>Stops a recipe where it is, with a status and an Italian message (internal control flow).</summary>
internal sealed class RecipeStopException(RecipeStatus status, string message) : Exception(message)
{
public RecipeStatus Status { get; } = status;
/// <summary>For a failure on an unexpected error: the type name of that exception (diagnostic report, never the message).</summary>
public string? ErrorType { get; init; }
}
/// <summary>
/// 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
/// <see cref="RecipeStopException"/> when something says to stop.
/// </summary>
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<long> AccountsWithStories { get; } = [];
public HashSet<long> AccountsWithNewPosts { get; } = [];
public bool Finished { get; set; }
/// <summary>The first stop signal raised since the run started.</summary>
public Signal? Signal => Volatile.Read(ref _signal);
/// <summary>Key structures of unrecognized responses seen in the run.</summary>
public List<string> UnknownShapes { get; } = [];
private RecipeEnvironment Env => _runner.Env;
public void Dispose() => _signals.SignalRaised -= OnSignal;
public static RecipeStopException Stop(RecipeStatus status, string message) => new(status, message);
/// <summary>Stops the run when a signal was raised or the breaker is open.</summary>
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.");
}
}
/// <summary>
/// Asks the Governor for a counted action; stops in order when refused or when the session is over. With
/// <paramref name="opensPage"/> (the next step opens a page), this is a turn point of the page (issue #37): when the
/// profile search waits, it gets the page for one step first, and the checks run again after it.
/// </summary>
public async Task PermitAsync(ActionKind kind, long? accountId, bool opensPage = false)
{
ThrowIfSignal();
if (opensPage && Env.PageTurns is { } turns && turns.EngineTurn is { } turn && await turns.YieldAsync(turn, Ct).ConfigureAwait(false))
{
// The page may have changed meanwhile: what follows opens a page anyway, but the state is looked at again.
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++;
}
/// <summary>Opens a page of the site map and waits after the load like a person (§7.7).</summary>
public async Task<PageLoad> OpenAsync(string page, IReadOnlyDictionary<string, string>? values = null)
{
var path = Env.SiteMap.BuildPath(page, values);
PageLoad load;
try
{
load = await Env.Driver.OpenAsync(path, Ct).ConfigureAwait(false);
Env.PageTurns?.NoteOpened(PageUser.Engine);
}
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;
}
/// <summary>Clicks a target of the map; stops and reports when it cannot be found (never coordinates).</summary>
public async Task ClickAsync(string target, IReadOnlyDictionary<string, string>? 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);
}
/// <summary>Read-only lookup of a target.</summary>
public Task<TargetCheck> FindAsync(string target, IReadOnlyDictionary<string, string>? parameters = null) =>
Env.Driver.FindAsync(target, parameters, Ct);
/// <summary>The page must still be on the site: links outside it are never followed (spec §6.1).</summary>
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.");
}
}
/// <summary>Waits for reads after <paramref name="mark"/> that satisfy <paramref name="expected"/>, or for a stop signal.</summary>
public async Task<IReadOnlyList<CapturedRead>> WaitForDataAsync(long mark, Func<ReadResult, bool> 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;
}
/// <summary>Waits until no data response is on its way any more.</summary>
public async Task SettleAsync()
{
await Env.Capture.SettleAsync(Env.Options.SettleQuiet, Env.Options.DataTimeout, Env.Options.Poll, Ct).ConfigureAwait(false);
ThrowIfSignal();
}
/// <summary>
/// Judges the reads of a step that expected <paramref name="expected"/>: recognized data resets the empty-page
/// counter; only unknown shapes stop the run with <see cref="RecipeStatus.UnrecognizedFormat"/>; nothing at all is
/// an empty page (three in a row raise a throttle signal). Returns true when the expected data arrived.
/// </summary>
public bool Judge(IReadOnlyList<CapturedRead> reads, Func<ReadResult, bool> 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);
}