using System.Globalization; using Febe.Browser.Session; using Febe.Core.Abstractions; using Febe.Core.Collection.Requests; namespace Febe.App; /// How a copy of the browser's session ended (counts and names only). public enum SessionCopyStatus { /// Copied and written to the saved session. Saved, /// Copied; it counts at once, but the disk refused it (tried again with the next write). SavedInMemoryOnly, /// Not copied: says why. Refused, /// Copied, then thrown away: meanwhile the page was no longer Alberto's (rule 7). Discarded, /// /// Copied but not saved: a value the requests need was missing, the saved copy has them all, and Alberto chose /// «Tieni la copia completa» (). The saved session stays as it was. /// KeptComplete, } /// What a copy did, for the message of «Ho finito» and the tests. Never a value. /// How it ended. /// Why nothing was copied (with ). /// Cookies copied. /// Values of the page it did not find that a configured operation sends. /// doc_id of configured operations it did not find. public sealed record SessionCopyOutcome(SessionCopyStatus Status, CaptureRefusal? Refusal, int Cookies, int MissingValues, int MissingDocIds) { /// True when the copy now is the saved session. public bool Saved => Status is SessionCopyStatus.Saved or SessionCopyStatus.SavedInMemoryOnly; } /// /// 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. /// /// Whether a saved session is there and can be read. /// When the browser's session was copied; null without a session or when not known. /// How many cookies it holds. /// Values of the page it holds, of . /// Values of the page the copy reads. /// Names of the values of the page it lacks. /// doc_id it holds, of . /// doc_id the copy reads. /// Operations whose doc_id it lacks. /// How many of the missing values and doc_id a configured operation sends. public sealed record SavedSessionReport( SavedSessionState State, DateTimeOffset? CopiedAt, int Cookies, int ValuesPresent, int ValuesExpected, IReadOnlyList MissingValues, int DocIdsPresent, int DocIdsExpected, IReadOnlyList MissingDocIds, int NeededMissing) { /// True when a readable session is there and nothing a configured operation sends is missing. public bool Complete => State == SavedSessionState.Present && NeededMissing == 0; } /// /// 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. /// public interface ISessionCopier { /// /// Copies the session the page holds now. The caller holds the page (Alberto's lease, the page turn). /// /// Asked after reading, before saving: false throws the copy away (the page stopped being Alberto's). /// Cancels the copy; nothing is saved then. Task CopyAsync(Func mayKeep, CancellationToken ct); /// Whether a saved session is there and can be read (cheap: «Collegato» and the engine ask it often). SavedSessionState SavedState { get; } /// The saved session now, in counts and names (the Collegamento page, «Collegato»). SavedSessionReport Report(); } /// /// The copy over the browser's page () into a , bounded by /// . Logs one line with counts and names, never a value (rule 10). /// public sealed class BrowserSessionCopier : ISessionCopier { private readonly ICdpSession _cdp; private readonly SessionCapturePlan _plan; private readonly ISavedSiteSession _store; private readonly IClock _clock; private readonly Action _log; /// The page of Febe's browser. /// What to read (from the catalog of the site). /// The saved session the copy replaces. /// The composition's clock (when the copy was made). /// Receives the Italian log line (counts and names only). public BrowserSessionCopier(ICdpSession cdp, SessionCapturePlan plan, ISavedSiteSession store, IClock clock, Action 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)); } /// /// What an incomplete copy does, asked at every copy (the setting of the Collegamento page, /// ); by default it replaces the saved session, as before. /// public Func> IncompleteCopy { get; init; } = _ => Task.FromResult(IncompleteCopyChoice.Replace); /// /// 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). /// public TimeSpan Timeout { get; set; } = TimeSpan.FromSeconds(10); public async Task CopyAsync(Func 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(); 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(); 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); } /// «manca app_id», «mancano hsi, rev» (with : «manca anche …»), for the log: names only. private static string Missing(IReadOnlyList names, bool also = false) => (names.Count == 1 ? "manca " : "mancano ") + (also ? "anche " : string.Empty) + string.Join(", ", names); /// Why a copy was refused, in Italian. 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", }; /// /// 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). /// private async Task 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; } } /// True when holds every value and doc_id a configured operation sends. 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; } }