La fine della guida da sola, dopo la copia, guarda di nuovo nello stesso passo in cui rilascia il permesso: se la vista remota, la finestra o un nuovo «Accedi» / «Usa il browser» sono tornati durante la copia, il permesso resta. Prima finiva comunque, e alla chiusura successiva il motore riprendeva subito, senza attesa e senza copia. Un «Ho finito» che prova davvero a copiare, o che chiude lui il permesso, e la chiusura della finestra che rinuncia dimenticano la copia di un abbandono precedente: un secondo «Ho finito» non dice più «era già stata copiata» dopo una copia appena rifiutata. Il registro non incolpa il browser quando il tempo della finestra finisce in attesa della pagina tenuta dalla ricerca dei profili; la riga di avvio del motore segue IsReadyToCollect e dice quando aspetta la copia; il riquadro «Se una copia nuova è incompleta» non mostra né accetta una scelta finché il server non dice quella salvata, non si fa cambiare da una risposta tardiva e torna alla scelta precedente se il salvataggio fallisce; singolare italiano nei messaggi («manca 1 valore che serve»). La guida e PROTOCOLLO.md dicono che in Docker copia solo «Ho finito»: lasciare la pagina vale «Annulla». Nuova riga in decisioni.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
304 lines
15 KiB
C#
304 lines
15 KiB
C#
using System.Globalization;
|
|
using Febe.Browser.Session;
|
|
using Febe.Core.Abstractions;
|
|
using Febe.Core.Collection.Requests;
|
|
|
|
namespace Febe.App;
|
|
|
|
/// <summary>How a copy of the browser's session ended (counts and names only).</summary>
|
|
public enum SessionCopyStatus
|
|
{
|
|
/// <summary>Copied and written to the saved session.</summary>
|
|
Saved,
|
|
|
|
/// <summary>Copied; it counts at once, but the disk refused it (tried again with the next write).</summary>
|
|
SavedInMemoryOnly,
|
|
|
|
/// <summary>Not copied: <see cref="SessionCopyOutcome.Refusal"/> says why.</summary>
|
|
Refused,
|
|
|
|
/// <summary>Copied, then thrown away: meanwhile the page was no longer Alberto's (rule 7).</summary>
|
|
Discarded,
|
|
|
|
/// <summary>
|
|
/// Copied but not saved: a value the requests need was missing, the saved copy has them all, and Alberto chose
|
|
/// «Tieni la copia completa» (<see cref="IncompleteCopyChoice.KeepComplete"/>). The saved session stays as it was.
|
|
/// </summary>
|
|
KeptComplete,
|
|
}
|
|
|
|
/// <summary>What a copy did, for the message of «Ho finito» and the tests. Never a value.</summary>
|
|
/// <param name="Status">How it ended.</param>
|
|
/// <param name="Refusal">Why nothing was copied (with <see cref="SessionCopyStatus.Refused"/>).</param>
|
|
/// <param name="Cookies">Cookies copied.</param>
|
|
/// <param name="MissingValues">Values of the page it did not find that a configured operation sends.</param>
|
|
/// <param name="MissingDocIds">doc_id of configured operations it did not find.</param>
|
|
public sealed record SessionCopyOutcome(SessionCopyStatus Status, CaptureRefusal? Refusal, int Cookies, int MissingValues, int MissingDocIds)
|
|
{
|
|
/// <summary>True when the copy now is the saved session.</summary>
|
|
public bool Saved => Status is SessionCopyStatus.Saved or SessionCopyStatus.SavedInMemoryOnly;
|
|
}
|
|
|
|
/// <summary>
|
|
/// The saved session as the Collegamento page shows it (issue #36, S4b, answer 10): its state, when it was copied, how
|
|
/// many values of the page and doc_id it holds and the names of those it lacks. Counts and names only, never a value.
|
|
/// </summary>
|
|
/// <param name="State">Whether a saved session is there and can be read.</param>
|
|
/// <param name="CopiedAt">When the browser's session was copied; null without a session or when not known.</param>
|
|
/// <param name="Cookies">How many cookies it holds.</param>
|
|
/// <param name="ValuesPresent">Values of the page it holds, of <paramref name="ValuesExpected"/>.</param>
|
|
/// <param name="ValuesExpected">Values of the page the copy reads.</param>
|
|
/// <param name="MissingValues">Names of the values of the page it lacks.</param>
|
|
/// <param name="DocIdsPresent">doc_id it holds, of <paramref name="DocIdsExpected"/>.</param>
|
|
/// <param name="DocIdsExpected">doc_id the copy reads.</param>
|
|
/// <param name="MissingDocIds">Operations whose doc_id it lacks.</param>
|
|
/// <param name="NeededMissing">How many of the missing values and doc_id a configured operation sends.</param>
|
|
public sealed record SavedSessionReport(
|
|
SavedSessionState State,
|
|
DateTimeOffset? CopiedAt,
|
|
int Cookies,
|
|
int ValuesPresent,
|
|
int ValuesExpected,
|
|
IReadOnlyList<string> MissingValues,
|
|
int DocIdsPresent,
|
|
int DocIdsExpected,
|
|
IReadOnlyList<string> MissingDocIds,
|
|
int NeededMissing)
|
|
{
|
|
/// <summary>True when a readable session is there and nothing a configured operation sends is missing.</summary>
|
|
public bool Complete => State == SavedSessionState.Present && NeededMissing == 0;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Copies the session of Febe's browser into the saved session (issue #36, S4, spec §6.0): at «Ho finito», after the
|
|
/// automatic login of the test site, and (S4b) when Alberto closes the browser window on Windows or his driving lease
|
|
/// ends by itself. A new copy replaces the saved one (§6.0 «un nuovo accesso ricopia tutto e sostituisce»), also when
|
|
/// some value of the page is missing — unless Alberto chose «Tieni la copia completa» and the saved one is complete.
|
|
/// The requests that send a missing value do not leave and stop the engine as a disconnection until a new copy has it
|
|
/// (never a way back to the pages). A refused copy leaves the saved session as it is.
|
|
/// </summary>
|
|
public interface ISessionCopier
|
|
{
|
|
/// <summary>
|
|
/// Copies the session the page holds now. The caller holds the page (Alberto's lease, the page turn).
|
|
/// </summary>
|
|
/// <param name="mayKeep">Asked after reading, before saving: false throws the copy away (the page stopped being Alberto's).</param>
|
|
/// <param name="ct">Cancels the copy; nothing is saved then.</param>
|
|
Task<SessionCopyOutcome> CopyAsync(Func<bool> mayKeep, CancellationToken ct);
|
|
|
|
/// <summary>Whether a saved session is there and can be read (cheap: «Collegato» and the engine ask it often).</summary>
|
|
SavedSessionState SavedState { get; }
|
|
|
|
/// <summary>The saved session now, in counts and names (the Collegamento page, «Collegato»).</summary>
|
|
SavedSessionReport Report();
|
|
}
|
|
|
|
/// <summary>
|
|
/// The copy over the browser's page (<see cref="SessionCapture"/>) into a <see cref="ISavedSiteSession"/>, bounded by
|
|
/// <see cref="Timeout"/>. Logs one line with counts and names, never a value (rule 10).
|
|
/// </summary>
|
|
public sealed class BrowserSessionCopier : ISessionCopier
|
|
{
|
|
private readonly ICdpSession _cdp;
|
|
private readonly SessionCapturePlan _plan;
|
|
private readonly ISavedSiteSession _store;
|
|
private readonly IClock _clock;
|
|
private readonly Action<string> _log;
|
|
|
|
/// <param name="cdp">The page of Febe's browser.</param>
|
|
/// <param name="plan">What to read (from the catalog of the site).</param>
|
|
/// <param name="store">The saved session the copy replaces.</param>
|
|
/// <param name="clock">The composition's clock (when the copy was made).</param>
|
|
/// <param name="log">Receives the Italian log line (counts and names only).</param>
|
|
public BrowserSessionCopier(ICdpSession cdp, SessionCapturePlan plan, ISavedSiteSession store, IClock clock, Action<string> log)
|
|
{
|
|
_cdp = cdp ?? throw new ArgumentNullException(nameof(cdp));
|
|
_plan = plan ?? throw new ArgumentNullException(nameof(plan));
|
|
_store = store ?? throw new ArgumentNullException(nameof(store));
|
|
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
|
_log = log ?? throw new ArgumentNullException(nameof(log));
|
|
}
|
|
|
|
/// <summary>
|
|
/// What an incomplete copy does, asked at every copy (the setting of the Collegamento page,
|
|
/// <see cref="SessionCopySettings"/>); by default it replaces the saved session, as before.
|
|
/// </summary>
|
|
public Func<CancellationToken, Task<IncompleteCopyChoice>> IncompleteCopy { get; init; } = _ => Task.FromResult(IncompleteCopyChoice.Replace);
|
|
|
|
/// <summary>
|
|
/// How long the reading may last before it counts as a browser error: «Ho finito» holds the commands of the
|
|
/// connection meanwhile, so a browser that hangs must not hold them for ever (real time).
|
|
/// </summary>
|
|
public TimeSpan Timeout { get; set; } = TimeSpan.FromSeconds(10);
|
|
|
|
public async Task<SessionCopyOutcome> CopyAsync(Func<bool> mayKeep, CancellationToken ct)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(mayKeep);
|
|
SessionCaptureResult result;
|
|
using (var limit = CancellationTokenSource.CreateLinkedTokenSource(ct))
|
|
{
|
|
limit.CancelAfter(Timeout);
|
|
try
|
|
{
|
|
result = await SessionCapture.CaptureAsync(_cdp, _plan, _clock, limit.Token).ConfigureAwait(false);
|
|
}
|
|
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
|
|
{
|
|
_log("Sessione non copiata: il browser non ha risposto in tempo.");
|
|
return new SessionCopyOutcome(SessionCopyStatus.Refused, CaptureRefusal.BrowserError, 0, 0, 0);
|
|
}
|
|
}
|
|
|
|
if (result.Values is not { } values)
|
|
{
|
|
var refusal = result.Refusal ?? CaptureRefusal.BrowserError;
|
|
_log($"Sessione non copiata: {Reason(refusal)}. La sessione salvata resta com'era.");
|
|
return new SessionCopyOutcome(SessionCopyStatus.Refused, refusal, 0, 0, 0);
|
|
}
|
|
|
|
var counts = string.Create(
|
|
CultureInfo.InvariantCulture,
|
|
$"{result.Cookies} cookie ({result.DroppedCookies} scartati), {result.ExpectedValues - result.MissingValues.Count} valori della pagina su {result.ExpectedValues}, {result.ExpectedDocIds - result.MissingDocIds.Count} doc_id su {result.ExpectedDocIds}");
|
|
// Missing counts only what a configured operation sends: that request will not leave (a disconnection, §6.0).
|
|
var neededValues = result.MissingValues.Where(_plan.NeededValues.Contains).ToList();
|
|
var neededDocIds = result.MissingDocIds.Where(_plan.NeededDocIds.Contains).ToList();
|
|
var needed = neededValues.Concat(neededDocIds).ToList();
|
|
var unused = result.MissingValues.Concat(result.MissingDocIds).Except(needed, StringComparer.Ordinal).ToList();
|
|
|
|
// An incomplete copy replaces the saved one (§6.0: an older copy could keep another login's cookies), unless
|
|
// Alberto chose to keep a complete one (answer 9 of 18 November 2026) and the saved one is complete. The choice
|
|
// is read before the last look at whose page it is, so that nothing awaited comes between that look and the write.
|
|
var keepComplete = needed.Count > 0 && IsComplete(_store.Read()) && await KeepsCompleteAsync().ConfigureAwait(false);
|
|
|
|
if (!mayKeep())
|
|
{
|
|
_log($"Sessione letta ma non salvata: nel frattempo il browser è tornato al motore ({counts}).");
|
|
return new SessionCopyOutcome(SessionCopyStatus.Discarded, null, result.Cookies, result.MissingValues.Count, result.MissingDocIds.Count);
|
|
}
|
|
|
|
if (keepComplete)
|
|
{
|
|
_log($"Sessione letta ma non salvata: {Missing(needed)}, che {(needed.Count == 1 ? "serve" : "servono")} alle operazioni configurate; come scelto, resta la copia completa salvata prima ({counts}).");
|
|
return new SessionCopyOutcome(SessionCopyStatus.KeptComplete, null, result.Cookies, neededValues.Count, neededDocIds.Count);
|
|
}
|
|
|
|
// Not cancelled from here: the copy was made, and a half-written replacement is never left.
|
|
var onDisk = await _store.ReplaceAsync(values, CancellationToken.None).ConfigureAwait(false);
|
|
_log($"Sessione copiata: {counts}"
|
|
+ (needed.Count == 0 ? string.Empty : "; " + Missing(needed) + ", che " + (needed.Count == 1 ? "serve" : "servono") + " alle operazioni configurate")
|
|
+ (unused.Count == 0 ? string.Empty : "; " + Missing(unused, also: true) + ", che nessuna operazione configurata usa")
|
|
+ (onDisk ? string.Empty : "; non ancora scritta su disco")
|
|
+ ".");
|
|
return new SessionCopyOutcome(
|
|
onDisk ? SessionCopyStatus.Saved : SessionCopyStatus.SavedInMemoryOnly,
|
|
null,
|
|
result.Cookies,
|
|
neededValues.Count,
|
|
neededDocIds.Count);
|
|
}
|
|
|
|
public SavedSessionState SavedState => _store.State;
|
|
|
|
public SavedSessionReport Report()
|
|
{
|
|
var state = _store.State;
|
|
var values = state == SavedSessionState.Present ? _store.Read() : null;
|
|
if (values is null)
|
|
{
|
|
var none = state == SavedSessionState.Present ? SavedSessionState.None : state;
|
|
return new SavedSessionReport(none, null, 0, 0, _plan.Values.Count, [], 0, _plan.DocIds.Count, [], 0);
|
|
}
|
|
|
|
var missingValues = new List<string>();
|
|
var needed = 0;
|
|
foreach (var read in _plan.Values)
|
|
{
|
|
if (!values.Fields.ContainsKey(read.Field))
|
|
{
|
|
missingValues.Add(read.Field);
|
|
needed += _plan.NeededValues.Contains(read.Field) ? 1 : 0;
|
|
}
|
|
}
|
|
|
|
var missingDocIds = new List<string>();
|
|
foreach (var read in _plan.DocIds)
|
|
{
|
|
if (!values.DocIds.ContainsKey(read.Field))
|
|
{
|
|
missingDocIds.Add(read.Field);
|
|
needed += _plan.NeededDocIds.Contains(read.Field) ? 1 : 0;
|
|
}
|
|
}
|
|
|
|
return new SavedSessionReport(
|
|
SavedSessionState.Present,
|
|
values.CopiedAt,
|
|
values.Cookies.Count,
|
|
_plan.Values.Count - missingValues.Count,
|
|
_plan.Values.Count,
|
|
missingValues,
|
|
_plan.DocIds.Count - missingDocIds.Count,
|
|
_plan.DocIds.Count,
|
|
missingDocIds,
|
|
needed);
|
|
}
|
|
|
|
/// <summary>«manca app_id», «mancano hsi, rev» (with <paramref name="also"/>: «manca anche …»), for the log: names only.</summary>
|
|
private static string Missing(IReadOnlyList<string> names, bool also = false) =>
|
|
(names.Count == 1 ? "manca " : "mancano ") + (also ? "anche " : string.Empty) + string.Join(", ", names);
|
|
|
|
/// <summary>Why a copy was refused, in Italian.</summary>
|
|
public static string Reason(CaptureRefusal refusal) => refusal switch
|
|
{
|
|
CaptureRefusal.NotOnSite => "il browser non era su una pagina del sito",
|
|
CaptureRefusal.CheckpointPage => "il browser era sulla pagina di accesso o di verifica",
|
|
CaptureRefusal.NoUserAgent => "il browser non ha dato il suo user agent",
|
|
_ => "il browser non ha risposto",
|
|
};
|
|
|
|
/// <summary>
|
|
/// Whether Alberto chose «Tieni la copia completa». A choice that cannot be read (the database busy or failing) is
|
|
/// the default, «Sostituisci comunque»: the copy goes on, and «Ho finito» never fails because of the setting. The log
|
|
/// gets the kind of error only (rule 10).
|
|
/// </summary>
|
|
private async Task<bool> KeepsCompleteAsync()
|
|
{
|
|
try
|
|
{
|
|
return await IncompleteCopy(CancellationToken.None).ConfigureAwait(false) == IncompleteCopyChoice.KeepComplete;
|
|
}
|
|
catch (Exception ex) when (ex is not OutOfMemoryException)
|
|
{
|
|
_log($"Scelta per la copia incompleta non letta ({ex.GetType().Name}): vale la predefinita, la copia sostituisce quella salvata.");
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/// <summary>True when <paramref name="saved"/> holds every value and doc_id a configured operation sends.</summary>
|
|
private bool IsComplete(SiteSessionValues? saved)
|
|
{
|
|
if (saved is null)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
foreach (var field in _plan.NeededValues)
|
|
{
|
|
if (!saved.Fields.ContainsKey(field))
|
|
{
|
|
return false;
|
|
}
|
|
}
|
|
|
|
foreach (var operation in _plan.NeededDocIds)
|
|
{
|
|
if (!saved.DocIds.ContainsKey(operation))
|
|
{
|
|
return false;
|
|
}
|
|
}
|
|
|
|
return true;
|
|
}
|
|
}
|