Raccolta (M0/M2): sito di prova completo, lettori per forma, ricette su browser vero, coda degli scaricamenti, sonda con ripulitura e verifica; documenti delle ipotesi e delle prove dal vivo

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
Claude committed 2026-10-13 17:32:35 +00:00
1 parent e2c987873b
commit 4fc5a6c0d4
74 files changed
+12689 -13

No files matched your search

@@ -0,0 +1,187 @@
using Febe.Core.Abstractions;
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>
/// 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.</summary>
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++;
}
/// <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);
var load = await Env.Driver.OpenAsync(path, Ct).ConfigureAwait(false);
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);
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)))
{
_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)
{
UnknownShapes.AddRange(unknown);
throw Stop(RecipeStatus.UnrecognizedFormat, "La risposta del sito ha una forma che i lettori non riconoscono.");
}
_signals.ObserveEmptyPage(where);
ThrowIfSignal();
return false;
}
private void OnSignal(object? sender, Signal signal) => Interlocked.CompareExchange(ref _signal, signal, null);
}