Files
Febe/src/Febe.Core/Collection/Recipes/RecipeRun.cs
T
Alby96andClaude Opus 5.5 badd1681a0
verifica / controlli (push) Successful in 18s
verifica / prove (push) Successful in 13m5s
verifica / installatore (push) Successful in 4m11s
verifica / immagine (push) Successful in 14m4s
Rapporto di diagnostica della raccolta (#39)
Dopo una prova dal vivo andata male, Alberto deve poter mandare un solo file che
spieghi perché, senza che nessuno veda dati di altre persone. Attività ha ora il
pulsante «Diagnostica», che scarica il rapporto delle sessioni degli ultimi 14 giorni:
pagine aperte e forma degli indirizzi, risposte per tipo, stato e dimensione con ciò
che i lettori ne hanno fatto, struttura stretta delle forme sconosciute, ricette,
segnali, permessi negati, file in coda e scaricati, e il motivo di ogni arresto.

Nel rapporto entrano solo valori da elenchi chiusi, numeri, orari e forme: mai nomi,
indirizzi completi, codici, cursori, cookie o pezzi di risposte. Le forme degli
indirizzi e la regola delle chiavi-dato passano dalla sonda a Core, e la sonda le
richiama. Il registratore non lancia mai eccezioni verso la raccolta e tiene i file in
Dati/diagnostica per 14 giorni.

Prova che il rapporto non contiene valori, con controlli di mutazione; tre giri di
revisione avversaria (25 difetti confermati, tutti corretti).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 14:41:34 +01:00

208 lines
8.2 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.</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);
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;
}
/// <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);
}