Sessione salvata: copia alla chiusura della finestra e alla fine della guida, «Serve «Ho finito»», scelta per la copia incompleta e stato in Collegamento (#36, S4b)

Risposte 1, 5, 6, 9 e 10 di Alberto a S4. I valori __spin_r, __spin_b e __spin_t si copiano dalla pagina come gli altri (su Instagram da SiteData, ipotesi H23, operazioni ancora non configurate; nel sito di prova dal modulo GiroProva). La sessione si copia anche quando si chiude la finestra del browser su Windows e quando il permesso di guida finisce, sempre prima che la pagina torni al motore e con le garanzie di «Ho finito». Con «richieste» «Collegato» vuole una sessione salvata leggibile, altrimenti lo stato è «Serve «Ho finito»» e il motore aspetta. Nuova impostazione sessione.copia-incompleta (sostituisci, predefinita, o tieni-completa) e riquadro della sessione salvata nella pagina Collegamento, con soli conteggi e nomi.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-18 11:41:35 +01:00
1 parent 9958745e53
commit 883ea4683c
41 files changed
+1349 -101

No files matched your search

+246 -2
View File
@@ -4,6 +4,7 @@ using Febe.Browser.Hosting;
using Febe.Browser.Session;
using Febe.Core.Abstractions;
using Febe.Core.Collection;
using Febe.Core.Collection.Requests;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Storage;
@@ -40,6 +41,14 @@ namespace Febe.App;
/// (spec §7.6): reported to the breaker as the recipes would, so that it is an incident with its alert and only
/// «Riprendi» restarts the engine. Not when Alberto himself is at the browser, nor after his «Scollega».
/// </para>
/// <para>
/// With a saved session (issue #36, S4b) the session is copied at «Ho finito», and also when Alberto lets go of the
/// browser without it: the window «Browser di Febe» closed on Windows (<see cref="CopyOnWindowClosedAsync"/>) and the
/// lease of «Accedi» / «Usa il browser» ending by itself. Always before the page goes back to the engine, with the
/// same guarantees as «Ho finito» (the driving gate held, the page's turn), and only from a page of the site that is
/// not a login or verification page. «Collegato» then also needs a readable saved session: without one the state is
/// <see cref="ConnectionState.SessionCopyMissing"/> («Serve «Ho finito»») and the engine waits.
/// </para>
/// </remarks>
public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposable
{
@@ -74,6 +83,7 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
private bool? _connected;
private bool? _disconnectedByUser;
private DateTimeOffset _checkedAt = DateTimeOffset.MinValue;
private DateTimeOffset _lastCopyAt = DateTimeOffset.MinValue;
/// <param name="browser">The browser of Febe.</param>
/// <param name="storage">The database (first connection, «Scollega»).</param>
@@ -119,6 +129,24 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
}
}
/// <summary>
/// True when the composition keeps a saved session (raccolta «richieste») and there is no readable one: the cookie
/// alone is not «Collegato», the copy of «Ho finito» is missing (issue #36, S4b, answer 6).
/// </summary>
public bool SessionCopyMissing => _copier is not null && _copier.SavedState != SavedSessionState.Present;
/// <summary>
/// Whether the engine may collect (<see cref="EngineRuntime.IsConnected"/>): the session cookie is in the browser
/// and, with a saved session, a readable copy of it is there too.
/// </summary>
public bool IsReadyToCollect => IsConnected == true && !SessionCopyMissing;
/// <summary>
/// How long a copy when Alberto closes the browser window waits, at most, for the commands of the connection and for
/// the copy itself (real time); then it gives up and the window gives the page back. Tests shorten it.
/// </summary>
public TimeSpan LetGoWait { get; set; } = TimeSpan.FromSeconds(30);
/// <summary>
/// Where the browser goes when Alberto takes it from the rest page or presses «Pagina iniziale» (issue #52): the
/// site's home when the session is there, the login page when it is not (or not known yet) and after a disconnection
@@ -161,6 +189,11 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
var state = breaker is BreakerStatus.Challenge or BreakerStatus.Disconnected
? ConnectionState.VerificationRequired
: await CheckAsync(force: false, mayReport: true, ct).ConfigureAwait(false) == true ? ConnectionState.Connected : ConnectionState.NotConnected;
var saved = _copier?.Report();
if (state == ConnectionState.Connected && saved is not null && saved.State != SavedSessionState.Present)
{
state = ConnectionState.SessionCopyMissing;
}
Account? mine = null;
if (state != ConnectionState.NotConnected)
@@ -168,7 +201,47 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
mine = await _storage.Accounts.GetMineAsync(ct).ConfigureAwait(false);
}
return new ConnectionStatus(state, mine?.Username, mine?.DisplayName, driving, await CurrentUrlAsync(ct).ConfigureAwait(false));
return new ConnectionStatus(state, mine?.Username, mine?.DisplayName, driving, await CurrentUrlAsync(ct).ConfigureAwait(false), ToStatus(saved));
}
/// <summary>
/// The window «Browser di Febe» was closed by Alberto without «Ho finito» (Windows, issue #36, S4b, answer 5): the
/// session is copied while the page is still his. The caller (the window) holds the driving gate until this returns,
/// so the page goes back to the engine only afterwards. Gives up after <see cref="LetGoWait"/>. Never throws for the
/// browser; logs counts only.
/// </summary>
public async Task CopyOnWindowClosedAsync(CancellationToken ct)
{
const string What = "Finestra del browser chiusa";
if (_copier is null || !_browser.IsAvailable)
{
return;
}
using var limit = CancellationTokenSource.CreateLinkedTokenSource(ct);
limit.CancelAfter(LetGoWait);
try
{
await _commands.WaitAsync(limit.Token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (limit.IsCancellationRequested)
{
_log.Info("collegamento", $"{What}: sessione non copiata, un altro comando del collegamento era ancora in corso.");
return;
}
catch (ObjectDisposedException)
{
return; // Febe is stopping
}
try
{
await CopyOnLetGoAsync(What, () => _browser.UserIsDriving, limit.Token).ConfigureAwait(false);
}
finally
{
ReleaseCommands();
}
}
public async Task BeginUserDrivingAsync(bool openLogin, CancellationToken ct)
@@ -653,7 +726,18 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
lastSign = _lastDrivingSign;
}
if (_clock.Now - lastSign >= grace && ReleaseLease(lease))
if (_clock.Now - lastSign < grace)
{
continue;
}
// Before the page goes back to the engine: the copy of the session (S4b, answer 5).
if (!await CopyBeforeLeaseEndsAsync(lease, lastSign, poll, ct).ConfigureAwait(false))
{
continue;
}
if (ReleaseLease(lease))
{
_log.Info("collegamento", $"Nessuna vista del browser aperta da {ItalianText.Duration(grace)} senza «Ho finito» né «Annulla»: il motore può riprendere.");
return;
@@ -666,6 +750,163 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
}
}
/// <summary>
/// The copy when the lease of «Accedi» / «Usa il browser» is about to end by itself (S4b, answer 5), while it still
/// holds. Not when a copy was already made since the last sign that Alberto used the browser (the window closed a
/// moment before): the window's own hold lasts a moment after its copy, so a sign within one look
/// (<paramref name="poll"/>) of the copy is that hold, not Alberto. False when the lease must not end now: a sign of
/// driving came while the copy waited for its turn.
/// </summary>
private async Task<bool> CopyBeforeLeaseEndsAsync(IDisposable lease, DateTimeOffset lastSign, TimeSpan poll, CancellationToken ct)
{
if (_copier is null)
{
return true;
}
lock (_gate)
{
if (_lastCopyAt != DateTimeOffset.MinValue && _lastCopyAt >= lastSign - poll)
{
return true;
}
}
// Cancelled when «Ho finito», «Annulla» or «Scollega» end the lease meanwhile: then they decide.
await _commands.WaitAsync(ct).ConfigureAwait(false);
try
{
bool StillAlbertos()
{
lock (_gate)
{
return ReferenceEquals(_lease, lease);
}
}
if (!StillAlbertos())
{
return true;
}
if (_browser.UserDriving.Leases > 1)
{
// The remote view or the window came back while this waited: the lease goes on.
lock (_gate)
{
_lastDrivingSign = _clock.Now;
}
return false;
}
await CopyOnLetGoAsync("Fine della guida del browser", StillAlbertos, ct).ConfigureAwait(false);
return true;
}
finally
{
ReleaseCommands();
}
}
/// <summary>
/// The copy when Alberto lets go of the browser without «Ho finito»: only while the page is still his, only when the
/// browser holds the session, with the driving gate held and the page's turn, like «Ho finito». The copier refuses a
/// page off the site or a login or verification page. One log line with the outcome (counts only).
/// </summary>
private async Task CopyOnLetGoAsync(string what, Func<bool> stillAlbertos, CancellationToken ct)
{
try
{
if (!_browser.UserIsDriving)
{
_log.Info("collegamento", $"{what}: sessione non copiata, il browser era già tornato al motore.");
return;
}
if (await CheckAsync(force: true, mayReport: false, ct).ConfigureAwait(false) != true)
{
_log.Info("collegamento", $"{what}: nessuna sessione nel browser, niente da copiare.");
return;
}
var hold = _browser.UserDriving.Begin();
try
{
using var turn = await TakePageAsync(ct).ConfigureAwait(false);
if (_engine is not null && turn is null)
{
_log.Info("collegamento", $"{what}: sessione non copiata, la pagina era occupata dalla ricerca dei profili.");
return;
}
var outcome = await _copier!.CopyAsync(stillAlbertos, ct).ConfigureAwait(false);
lock (_gate)
{
_lastCopyAt = _clock.Now;
}
_log.Info("collegamento", $"{what}: {LetGoSummary(outcome)}.");
}
finally
{
hold.Dispose();
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
_log.Info("collegamento", $"{what}: sessione non copiata, il browser non ha risposto in tempo.");
}
}
/// <summary>What a copy without «Ho finito» did, for the log (counts only).</summary>
internal static string LetGoSummary(SessionCopyOutcome copy)
{
ArgumentNullException.ThrowIfNull(copy);
var missing = copy.MissingValues + copy.MissingDocIds;
var clause = missing == 0 ? string.Empty : string.Create(CultureInfo.InvariantCulture, $", ma mancano {missing} valori che servono alle richieste");
return copy.Status switch
{
SessionCopyStatus.Saved => "sessione copiata" + clause,
SessionCopyStatus.SavedInMemoryOnly => "sessione copiata, non ancora scritta su disco" + clause,
SessionCopyStatus.KeptComplete => string.Create(CultureInfo.InvariantCulture, $"copia incompleta ({missing} valori mancanti), resta quella completa salvata prima"),
SessionCopyStatus.Discarded => "sessione letta ma non salvata, il browser era tornato al motore",
_ => $"sessione non copiata, {BrowserSessionCopier.Reason(copy.Refusal ?? CaptureRefusal.BrowserError)}; la sessione salvata resta com'era",
};
}
/// <summary>The saved session for the interface, in counts and names; null without a saved session in this start.</summary>
private static SavedSessionStatus? ToStatus(SavedSessionReport? report) => report is null
? null
: new SavedSessionStatus(
report.State switch
{
SavedSessionState.Present => SavedSessionStatus.Present,
SavedSessionState.Unreadable => SavedSessionStatus.Unreadable,
_ => SavedSessionStatus.None,
},
report.CopiedAt,
report.Cookies,
report.ValuesPresent,
report.ValuesExpected,
report.MissingValues,
report.DocIdsPresent,
report.DocIdsExpected,
report.MissingDocIds,
report.NeededMissing);
private void ReleaseCommands()
{
try
{
_commands.Release();
}
catch (ObjectDisposedException)
{
// Febe stopped while the copy ran.
}
}
/// <summary>The first connection ever starts the gradual start (spec §7.2). True when it was the first.</summary>
private async Task<bool> MarkConnectedAsync(CancellationToken ct)
{
@@ -801,6 +1042,9 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
"Sessione copiata per le richieste di Febe, ma non ancora scritta su disco: Febe riprova alla prossima scrittura." + missingClause,
SessionCopyStatus.Discarded =>
"La sessione per le richieste non è stata copiata: nel frattempo il browser era tornato al motore. Rifai l'accesso dalla pagina Collegamento e premi «Ho finito» sulla tua pagina iniziale.",
SessionCopyStatus.KeptComplete => string.Create(
CultureInfo.InvariantCulture,
$"Alla pagina mancavano {missing} valori che servono alle richieste: come hai scelto nella pagina Collegamento («Tieni la copia completa»), Febe tiene la copia completa salvata prima e non usa quella nuova. Se nel frattempo hai rifatto l'accesso o cambiato account, scegli «Sostituisci comunque». {Again}"),
_ when copy.Refusal is CaptureRefusal.NotOnSite or CaptureRefusal.CheckpointPage =>
$"La sessione per le richieste non è stata copiata: {BrowserSessionCopier.Reason(copy.Refusal.Value)}. La sessione salvata resta com'era. {Again}",
_ =>
+20 -5
View File
@@ -261,7 +261,16 @@ public sealed class FebeApp : IAsyncDisposable
// Browser, connection, engine. The engine loop starts only once the browser is up.
// «Pagina iniziale» (issue #52) is the connection's, which exists only after the browser: looked up when pressed.
var context = new FebePlatformContext(o, data, Database, Clock, Log, Tracker, ct => Connection?.OpenStartPageAsync(ct) ?? Task.CompletedTask);
// The copy when Alberto closes the browser window (S4b) is the connection's too, looked up when it happens.
var context = new FebePlatformContext(
o,
data,
Database,
Clock,
Log,
Tracker,
ct => Connection?.OpenStartPageAsync(ct) ?? Task.CompletedTask,
ct => Connection?.CopyOnWindowClosedAsync(ct) ?? Task.CompletedTask);
var browser = await _platform.CreateBrowserAsync(context, ct).ConfigureAwait(false);
Browser = browser;
PrepareSavedSession(context, browser);
@@ -286,8 +295,9 @@ public sealed class FebeApp : IAsyncDisposable
random,
engineOptions,
userIsDriving: () => browser.UserIsDriving,
isConnected: () => connection.IsConnected == true,
ct: ct).ConfigureAwait(false);
isConnected: () => connection.IsReadyToCollect,
ct: ct,
sessionCopyMissing: () => connection.IsConnected == true && connection.SessionCopyMissing).ConfigureAwait(false);
// The diagnostic report (issue #39): one recorder for the engine, the pipeline and the interface. What the
// capture sees goes to the session in progress, if any.
var diagnostics = new CollectionDiagnostics(Clock, () => services.Runtime.CurrentSession?.SessionId, new DiagnosticLog(data.Diagnostics, Clock));
@@ -576,10 +586,15 @@ public sealed class FebeApp : IAsyncDisposable
var protector = _platform.CreateSessionProtector(context);
var saved = new FileSiteSession(context.Data.SessionFile, protector, message => Log.Info("sessione", message));
var rules = LoadSignalRules(context.Data);
_copier = new BrowserSessionCopier(browser.Cdp, SessionCapturePlan.For(o.Site, catalog, rules), saved, Clock, message => Log.Info("sessione", message));
var settings = context.Storage.Settings;
_copier = new BrowserSessionCopier(browser.Cdp, SessionCapturePlan.For(o.Site, catalog, rules), saved, Clock, message => Log.Info("sessione", message))
{
// What an incomplete copy does (S4b): read at every copy, so a change on the Collegamento page holds at once.
IncompleteCopy = async token => (await SessionCopySettings.LoadAsync(settings, token).ConfigureAwait(false)).IncompleteCopy,
};
_requestCatalog = catalog;
SavedSession = saved;
Log.Info("raccolta", $"Raccolta «richieste»: {catalog.Configured.Count().ToString(CultureInfo.InvariantCulture)} operazioni configurate in {Path.GetFileName(catalog.Source)}; la sessione si copia a «Ho finito».");
Log.Info("raccolta", $"Raccolta «richieste»: {catalog.Configured.Count().ToString(CultureInfo.InvariantCulture)} operazioni configurate in {Path.GetFileName(catalog.Source)}; la sessione si copia a «Ho finito», alla chiusura della finestra del browser e alla fine della guida.");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or CryptographicException or PlatformNotSupportedException)
{
+6 -1
View File
@@ -72,7 +72,12 @@ public interface IFebePlatform
/// the login page otherwise, once the engine's session ended and with the page's turn
/// (<c>BrowserConnectionService.OpenStartPageAsync</c>). Null: the button does nothing.
/// </param>
public sealed record FebePlatformContext(FebeAppOptions Options, DataFolderLayout Data, IFebeStorage Storage, IClock Clock, FebeLog Log, BrowserUseTracker Tracker, Func<CancellationToken, Task>? OpenStartPage = null);
/// <param name="CopyOnWindowClosed">
/// What closing the browser window does before the page goes back to the engine (issue #36, S4b): the connection copies
/// the session into the saved session, when there is one (<c>BrowserConnectionService.CopyOnWindowClosedAsync</c>). The
/// window holds the driving gate until the task ends. Null: nothing.
/// </param>
public sealed record FebePlatformContext(FebeAppOptions Options, DataFolderLayout Data, IFebeStorage Storage, IClock Clock, FebeLog Log, BrowserUseTracker Tracker, Func<CancellationToken, Task>? OpenStartPage = null, Func<CancellationToken, Task>? CopyOnWindowClosed = null);
/// <summary>Options of the shared composition, filled by each shell from its own configuration.</summary>
public sealed record FebeAppOptions
+140 -9
View File
@@ -19,6 +19,12 @@ public enum SessionCopyStatus
/// <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>
@@ -34,11 +40,42 @@ public sealed record SessionCopyOutcome(SessionCopyStatus Status, CaptureRefusal
}
/// <summary>
/// Copies the session of Febe's browser into the saved session (issue #36, S4, spec §6.0): at «Ho finito», and after the
/// automatic login of the test site. 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: the requests that send it then 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.
/// 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
{
@@ -48,6 +85,12 @@ public interface ISessionCopier
/// <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>
@@ -76,6 +119,12 @@ public sealed class BrowserSessionCopier : ISessionCopier
_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).
@@ -116,15 +165,24 @@ public sealed class BrowserSessionCopier : ISessionCopier
return new SessionCopyOutcome(SessionCopyStatus.Discarded, null, result.Cookies, result.MissingValues.Count, result.MissingDocIds.Count);
}
// Not cancelled from here: the copy was made, and a half-written replacement is never left. It replaces the
// saved session also when a value is missing (§6.0): keeping an older copy could keep another login's cookies.
var onDisk = await _store.ReplaceAsync(values, CancellationToken.None).ConfigureAwait(false);
// 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.
if (needed.Count > 0
&& IsComplete(_store.Read())
&& await IncompleteCopy(CancellationToken.None).ConfigureAwait(false) == IncompleteCopyChoice.KeepComplete)
{
_log($"Sessione letta ma non salvata: mancano {string.Join(", ", needed)}, che 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 : "; mancano " + string.Join(", ", needed) + ", che servono alle operazioni configurate")
+ (unused.Count == 0 ? string.Empty : "; mancano anche " + string.Join(", ", unused) + ", che nessuna operazione configurata usa")
@@ -138,6 +196,52 @@ public sealed class BrowserSessionCopier : ISessionCopier
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>Why a copy was refused, in Italian.</summary>
public static string Reason(CaptureRefusal refusal) => refusal switch
{
@@ -146,4 +250,31 @@ public sealed class BrowserSessionCopier : ISessionCopier
CaptureRefusal.NoUserAgent => "il browser non ha dato il suo user agent",
_ => "il browser non ha risposto",
};
/// <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;
}
}