Unione di funzione/codec-immagini in funzione/decoder-h264 (catena della 0.3.0)
Porta nel decodificatore H.264 le regole senza componenti esterni, la sessione S4b e i codec di immagini di casa (C1), così la richiesta di unione di questo ramo contiene già tutta la catena. Conflitti risolti tenendo le due parti: in decisioni.md tutte le righe, prima quelle della catena e poi quelle del decodificatore; in docker.md, processo.md e Sviluppo.md né ffmpeg (uscito con questo ramo) né SkiaSharp (uscito con C1), con l'eccezione «da fare» delle prove di conformità; nelle prove di Febe.Tests entrambe le cartelle di file copiati e, nelle prove delle miniature, sia i video sia le immagini di riferimento. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
8bcc86e496
279 files changed
+25617
-816
No files matched your search
@@ -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,16 @@ 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"/>), the page
|
||||
/// of the browser left in Docker (<see cref="LeavePageAsync"/>, <see cref="RemoteViewClosed"/>: after
|
||||
/// <see cref="PageLeaveGrace"/> without a view open again, answer of 25 November 2026) and the lease of «Accedi» /
|
||||
/// «Usa il browser» ending by itself. «Annulla» never copies. 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
|
||||
{
|
||||
@@ -55,6 +66,9 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
|
||||
/// <summary>How often the cookie is looked at in the background (outside sessions it is the only way to notice).</summary>
|
||||
public static readonly TimeSpan BackgroundCheck = TimeSpan.FromSeconds(30);
|
||||
|
||||
/// <summary>How the log names leaving the page of the browser in Docker (answer of 25 November 2026).</summary>
|
||||
private const string PageLeftText = "Pagina del browser lasciata";
|
||||
|
||||
private readonly IFebeBrowser _browser;
|
||||
private readonly IFebeStorage _storage;
|
||||
private readonly BrowserUseTracker _tracker;
|
||||
@@ -74,6 +88,9 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
|
||||
private bool? _connected;
|
||||
private bool? _disconnectedByUser;
|
||||
private DateTimeOffset _checkedAt = DateTimeOffset.MinValue;
|
||||
private DateTimeOffset _lastCopyAt = DateTimeOffset.MinValue;
|
||||
private SessionCopyOutcome? _letGoCopy;
|
||||
private DateTimeOffset? _leftAt;
|
||||
|
||||
/// <param name="browser">The browser of Febe.</param>
|
||||
/// <param name="storage">The database (first connection, «Scollega»).</param>
|
||||
@@ -119,6 +136,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
|
||||
@@ -140,6 +175,14 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
|
||||
/// </summary>
|
||||
public TimeSpan DrivingGrace { get; set; } = TimeSpan.FromMinutes(2);
|
||||
|
||||
/// <summary>
|
||||
/// How long after Alberto left the page of the browser in Docker (<see cref="LeavePageAsync"/>, or its remote view
|
||||
/// closed by the page: <see cref="RemoteViewClosed"/>) no view may open again before Febe takes it as letting go of
|
||||
/// the browser (answer of 25 November 2026, proposal of 5 seconds): a reload of the page opens its view again well
|
||||
/// before. Read at every look; tests shorten it.
|
||||
/// </summary>
|
||||
public TimeSpan PageLeaveGrace { get; set; } = TimeSpan.FromSeconds(5);
|
||||
|
||||
/// <summary>
|
||||
/// How long Alberto's page waits for its turn while a step of the profile search holds it (real time). Read at every
|
||||
/// wait; tests shorten it.
|
||||
@@ -161,6 +204,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 +216,55 @@ 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», or left minimised too long (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, and says which of the two happened.
|
||||
/// </summary>
|
||||
public async Task CopyOnWindowClosedAsync(BrowserWindowLetGo how, CancellationToken ct)
|
||||
{
|
||||
var what = how == BrowserWindowLetGo.MinimizedTooLong ? "Finestra del browser ridotta a icona troppo a lungo" : "Finestra del browser chiusa";
|
||||
if (_copier is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!_browser.IsAvailable)
|
||||
{
|
||||
// A letting go that copies nothing: a late «Ho finito» must not report a copy of an earlier one.
|
||||
ForgetLetGoCopy();
|
||||
return;
|
||||
}
|
||||
|
||||
using var limit = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
limit.CancelAfter(LetGoWait);
|
||||
try
|
||||
{
|
||||
await _commands.WaitAsync(limit.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (limit.IsCancellationRequested)
|
||||
{
|
||||
ForgetLetGoCopy();
|
||||
_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)
|
||||
@@ -181,6 +277,8 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
|
||||
{
|
||||
if (_lease is null)
|
||||
{
|
||||
// A new use of the browser: what an earlier one copied when it let go is no longer this one's.
|
||||
_letGoCopy = null;
|
||||
_lease = _browser.UserDriving.Begin();
|
||||
var watch = new CancellationTokenSource();
|
||||
_leaseWatch = watch;
|
||||
@@ -189,6 +287,9 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
|
||||
}
|
||||
|
||||
_lastDrivingSign = _clock.Now;
|
||||
|
||||
// Alberto is back (a reload of the page left a moment ago): not a letting go.
|
||||
_leftAt = null;
|
||||
}
|
||||
|
||||
_tracker.MarkUsed(_clock.Now);
|
||||
@@ -313,6 +414,52 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Docker (answer of 25 November 2026): the page of the browser was left without «Ho finito» or «Annulla». Nothing
|
||||
/// happens at once — a reload opens the page, «Usa il browser» and the view again within a moment. The watch of the
|
||||
/// lease lets go of the browser once, for <see cref="PageLeaveGrace"/> after this and after the last view closed, no
|
||||
/// view is open and no «Accedi» / «Usa il browser» came: the copy of the session as when the window is closed on
|
||||
/// Windows, then the lease ends and the page goes back to the engine (which puts it to rest).
|
||||
/// </summary>
|
||||
public Task LeavePageAsync(CancellationToken ct)
|
||||
{
|
||||
if (NoteLeft())
|
||||
{
|
||||
_log.Info("collegamento", $"Pagina del browser lasciata senza «Ho finito» né «Annulla»: se entro {ItalianText.Duration(PageLeaveGrace)} non torni al browser, Febe copia la sessione e il motore può riprendere.");
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Docker: a remote view was closed by its page (the page left, the tab closed, the link lost; not another view taking
|
||||
/// its place, nor Febe stopping). While the lease of «Accedi» / «Usa il browser» holds it counts as leaving the page
|
||||
/// (<see cref="LeavePageAsync"/>): the last view closed, the moment starts again from now.
|
||||
/// </summary>
|
||||
public void RemoteViewClosed()
|
||||
{
|
||||
// The browser gone: its view closed with it, Alberto did not leave (the page opens it again once it is back).
|
||||
if (_browser.IsAvailable)
|
||||
{
|
||||
NoteLeft();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Notes that Alberto may have left the browser; false without the lease of «Accedi» / «Usa il browser».</summary>
|
||||
private bool NoteLeft()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_lease is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
_leftAt = _clock.Now;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<FinishResult> FinishAsync(CancellationToken ct)
|
||||
{
|
||||
await _commands.WaitAsync(ct).ConfigureAwait(false);
|
||||
@@ -320,7 +467,7 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
|
||||
{
|
||||
if (!_browser.IsAvailable)
|
||||
{
|
||||
ReleaseLease();
|
||||
EndUseWithHoFinito();
|
||||
return new FinishResult(false, "Il browser di Febe non è in funzione in questo momento, quindi Febe non può controllare il collegamento. Riprova fra qualche minuto; se il problema resta, guarda il registro.");
|
||||
}
|
||||
|
||||
@@ -330,10 +477,10 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
|
||||
var first = connected && await MarkConnectedAsync(ct).ConfigureAwait(false);
|
||||
|
||||
// The copy for the site client (S4): while the page still holds the session and is still Alberto's.
|
||||
var copy = connected && _copier is not null ? await CopySessionAsync(ct).ConfigureAwait(false) : null;
|
||||
var copy = connected && _copier is not null ? await CopySessionAsync(ct).ConfigureAwait(false) : default;
|
||||
await RestIfAlbertosAsync().ConfigureAwait(false);
|
||||
await HideQuietlyAsync().ConfigureAwait(false);
|
||||
ReleaseLease();
|
||||
EndUseWithHoFinito();
|
||||
|
||||
var stopped = _engine?.Services.Breaker.State.Status is BreakerStatus.Challenge or BreakerStatus.Disconnected;
|
||||
string message;
|
||||
@@ -354,9 +501,9 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
|
||||
message = "Collegato a Instagram. Febe riprende da solo alla prossima sessione.";
|
||||
}
|
||||
|
||||
if (copy is not null)
|
||||
if (copy.Outcome is { } outcome)
|
||||
{
|
||||
message += " " + CopyMessage(copy);
|
||||
message += " " + CopyMessage(outcome, copy.Earlier);
|
||||
}
|
||||
|
||||
_log.Info("collegamento", connected ? "«Ho finito»: sessione presente nel browser." : "«Ho finito»: sessione assente nel browser.");
|
||||
@@ -634,9 +781,12 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
|
||||
while (true)
|
||||
{
|
||||
var grace = DrivingGrace;
|
||||
var poll = TimeSpan.FromTicks(Math.Clamp(grace.Ticks / 8, TimeSpan.FromMilliseconds(20).Ticks, TimeSpan.FromSeconds(5).Ticks));
|
||||
var leaveGrace = PageLeaveGrace;
|
||||
var shortest = leaveGrace < grace ? leaveGrace : grace;
|
||||
var poll = TimeSpan.FromTicks(Math.Clamp(shortest.Ticks / 8, TimeSpan.FromMilliseconds(20).Ticks, TimeSpan.FromSeconds(5).Ticks));
|
||||
await _clock.Delay(poll, ct).ConfigureAwait(false);
|
||||
DateTimeOffset lastSign;
|
||||
DateTimeOffset? leftAt;
|
||||
lock (_gate)
|
||||
{
|
||||
if (!ReferenceEquals(_lease, lease))
|
||||
@@ -651,11 +801,34 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
|
||||
}
|
||||
|
||||
lastSign = _lastDrivingSign;
|
||||
leftAt = _leftAt;
|
||||
}
|
||||
|
||||
if (_clock.Now - lastSign >= grace && ReleaseLease(lease))
|
||||
// Docker: the page of the browser left, or its last view closed by the page, and for a moment nothing came
|
||||
// back (answer of 25 November 2026). Otherwise the long wait of a lease nobody uses.
|
||||
var now = _clock.Now;
|
||||
var left = leftAt is { } at && now - (at > lastSign ? at : lastSign) >= leaveGrace;
|
||||
if (!left && now - lastSign < grace)
|
||||
{
|
||||
_log.Info("collegamento", $"Nessuna vista del browser aperta da {ItalianText.Duration(grace)} senza «Ho finito» né «Annulla»: il motore può riprendere.");
|
||||
continue;
|
||||
}
|
||||
|
||||
// Before the page goes back to the engine: the copy of the session (S4b, answer 5; leaving the page in
|
||||
// Docker, answer of 25 November 2026).
|
||||
var what = left ? PageLeftText : "Fine della guida del browser";
|
||||
if (!await CopyBeforeLeaseEndsAsync(lease, lastSign, poll, what, ct).ConfigureAwait(false))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// The copy may have lasted long (the page's turn, the browser, the database): the remote view, the window
|
||||
// or «Accedi» / «Usa il browser» may have come back meanwhile. Looked at again in the same step that ends
|
||||
// the lease, so that nothing slips in between.
|
||||
if (ReleaseIdleLease(lease, lastSign))
|
||||
{
|
||||
_log.Info("collegamento", left
|
||||
? $"{PageLeftText}: nessuna vista del browser riaperta, il motore può riprendere."
|
||||
: $"Nessuna vista del browser aperta da {ItalianText.Duration(grace)} senza «Ho finito» né «Annulla»: il motore può riprendere.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -664,6 +837,205 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
|
||||
{
|
||||
// The lease ended with a command of Alberto.
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
// Whatever failed, the lease must not hold the engine still for ever (rule 10: the kind of error only).
|
||||
_log.Warn("collegamento", $"Controllo della fine della guida del browser interrotto da un errore ({ex.GetType().Name}): il motore può riprendere.");
|
||||
ReleaseLease(lease);
|
||||
}
|
||||
}
|
||||
|
||||
/// <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, string what, 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.
|
||||
try
|
||||
{
|
||||
await _commands.WaitAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (ObjectDisposedException)
|
||||
{
|
||||
return true; // Febe is stopping
|
||||
}
|
||||
|
||||
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(what, 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;
|
||||
}
|
||||
|
||||
// The last time this use of the browser let go decides what a late «Ho finito» says: a copy that does not
|
||||
// happen now (no session, the page busy, refused, an error) forgets one made at an earlier letting go.
|
||||
ForgetLetGoCopy();
|
||||
|
||||
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
|
||||
{
|
||||
const string PageBusy = "sessione non copiata, la pagina era occupata dalla ricerca dei profili";
|
||||
PageTurn? taken;
|
||||
try
|
||||
{
|
||||
taken = await TakePageAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
// The time of the letting go ran out while a step of the search held the page: not the browser's fault.
|
||||
_log.Info("collegamento", $"{what}: {PageBusy}.");
|
||||
return;
|
||||
}
|
||||
|
||||
using var turn = taken;
|
||||
if (_engine is not null && turn is null)
|
||||
{
|
||||
_log.Info("collegamento", $"{what}: {PageBusy}.");
|
||||
return;
|
||||
}
|
||||
|
||||
var outcome = await _copier!.CopyAsync(stillAlbertos, ct).ConfigureAwait(false);
|
||||
lock (_gate)
|
||||
{
|
||||
_lastCopyAt = _clock.Now;
|
||||
if (outcome.Status is SessionCopyStatus.Saved or SessionCopyStatus.SavedInMemoryOnly or SessionCopyStatus.KeptComplete)
|
||||
{
|
||||
// A late «Ho finito» of this use says that the session was already copied (S4b).
|
||||
_letGoCopy = outcome;
|
||||
}
|
||||
}
|
||||
|
||||
_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.");
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
// The database, the disk, Febe stopping: never the lease held for ever because of it. The kind of error only
|
||||
// (rule 10): the page and the saved session hold what the session holds.
|
||||
_log.Warn("collegamento", $"{what}: copia della sessione non riuscita per un errore ({ex.GetType().Name}).");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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 : ", ma " + MissingNeeded(missing, past: false);
|
||||
return copy.Status switch
|
||||
{
|
||||
SessionCopyStatus.Saved => "sessione copiata" + clause,
|
||||
SessionCopyStatus.SavedInMemoryOnly => "sessione copiata, non ancora scritta su disco" + clause,
|
||||
SessionCopyStatus.KeptComplete => $"copia incompleta ({ItalianText.Count(missing, "valore mancante", "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>
|
||||
@@ -736,22 +1108,35 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
|
||||
/// The copy at «Ho finito» (issue #36, S4, §6.0): only while Alberto's own lease («Accedi», «Usa il browser») still
|
||||
/// holds — after it ended the page is the engine's, and nothing is read from it (rule 7). A hold of the driving gate
|
||||
/// keeps the lease from ending by itself meanwhile, and the page turn keeps a step of the profile search off the
|
||||
/// page; a lease that ended all the same before the copy is saved throws the copy away.
|
||||
/// page; a lease that ended all the same before the copy is saved throws the copy away. A late «Ho finito», after
|
||||
/// this use of the browser already copied when it let go (S4b), reads nothing and reports that earlier copy
|
||||
/// (<c>Earlier</c>), as long as the saved session is still there.
|
||||
/// </summary>
|
||||
private async Task<SessionCopyOutcome> CopySessionAsync(CancellationToken ct)
|
||||
private async Task<(SessionCopyOutcome? Outcome, bool Earlier)> CopySessionAsync(CancellationToken ct)
|
||||
{
|
||||
IDisposable? lease;
|
||||
SessionCopyOutcome? earlier;
|
||||
lock (_gate)
|
||||
{
|
||||
lease = _lease;
|
||||
earlier = _letGoCopy;
|
||||
}
|
||||
|
||||
if (lease is null || !_browser.UserIsDriving)
|
||||
{
|
||||
if (earlier is not null && _copier!.SavedState == SavedSessionState.Present)
|
||||
{
|
||||
_log.Info("collegamento", "«Ho finito»: sessione non copiata di nuovo, era già stata copiata quando il browser è tornato al motore.");
|
||||
return (earlier, true);
|
||||
}
|
||||
|
||||
_log.Info("collegamento", "«Ho finito»: sessione non copiata, il browser era già tornato al motore.");
|
||||
return new SessionCopyOutcome(SessionCopyStatus.Discarded, null, 0, 0, 0);
|
||||
return (new SessionCopyOutcome(SessionCopyStatus.Discarded, null, 0, 0, 0), false);
|
||||
}
|
||||
|
||||
// «Ho finito» copies again: from now on its own outcome is what a later «Ho finito» refers to, not an earlier copy
|
||||
// made when the browser was let go (that copy may be of another login).
|
||||
ForgetLetGoCopy();
|
||||
var hold = _browser.UserDriving.Begin();
|
||||
try
|
||||
{
|
||||
@@ -759,7 +1144,7 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
|
||||
if (_engine is not null && turn is null)
|
||||
{
|
||||
_log.Info("collegamento", "«Ho finito»: sessione non copiata, la pagina era occupata dalla ricerca dei profili.");
|
||||
return new SessionCopyOutcome(SessionCopyStatus.Refused, CaptureRefusal.BrowserError, 0, 0, 0);
|
||||
return (new SessionCopyOutcome(SessionCopyStatus.Refused, CaptureRefusal.BrowserError, 0, 0, 0), false);
|
||||
}
|
||||
|
||||
bool StillAlbertos()
|
||||
@@ -770,7 +1155,7 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
|
||||
}
|
||||
}
|
||||
|
||||
return await _copier!.CopyAsync(StillAlbertos, ct).ConfigureAwait(false);
|
||||
return (await _copier!.CopyAsync(StillAlbertos, ct).ConfigureAwait(false), false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -782,25 +1167,34 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
|
||||
/// The clause of the «Ho finito» message about the copy, in Italian (counts only). It says what the code does: a
|
||||
/// value a configured operation needs and the page did not give stops that request as a disconnection (§6.0), never
|
||||
/// a way back to the browser; and after a refusal a new «Ho finito» needs the browser opened again, because
|
||||
/// «Ho finito» always ends the lease.
|
||||
/// «Ho finito» always ends the lease. With <paramref name="earlier"/> the copy is the one made a moment before, when
|
||||
/// the browser went back to the engine without «Ho finito» (S4b): the message says so, and never asks for a new login
|
||||
/// when that copy is complete.
|
||||
/// </summary>
|
||||
internal static string CopyMessage(SessionCopyOutcome copy)
|
||||
internal static string CopyMessage(SessionCopyOutcome copy, bool earlier = false)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(copy);
|
||||
const string Before = "La sessione per le richieste era già stata copiata quando il browser è tornato al motore";
|
||||
const string Again = "Riapri il browser dalla pagina Collegamento («Usa il browser» o «Pagina iniziale») e premi di nuovo «Ho finito» sulla tua pagina iniziale.";
|
||||
var missing = copy.MissingValues + copy.MissingDocIds;
|
||||
var needed = MissingNeeded(missing, past: true);
|
||||
var missingClause = missing == 0
|
||||
? string.Empty
|
||||
: string.Create(
|
||||
CultureInfo.InvariantCulture,
|
||||
$" Alla pagina però mancavano {missing} valori che servono alle richieste: la copia ha comunque sostituito quella salvata prima, e le richieste che li usano non partono. Alla prima Febe si ferma come disconnessione e chiede un nuovo accesso. {Again}");
|
||||
: $" Alla pagina però {needed}: la copia ha comunque sostituito quella salvata prima, e le richieste che {(missing == 1 ? "lo" : "li")} usano non partono. Alla prima Febe si ferma come disconnessione e chiede un nuovo accesso. {Again}";
|
||||
return copy.Status switch
|
||||
{
|
||||
SessionCopyStatus.Saved when earlier => Before + "." + (missing == 0 ? " Non serve rifare l'accesso." : missingClause),
|
||||
SessionCopyStatus.SavedInMemoryOnly when earlier =>
|
||||
Before + ", ma non ancora scritta su disco: Febe riprova alla prossima scrittura." + (missing == 0 ? " Non serve rifare l'accesso." : missingClause),
|
||||
SessionCopyStatus.KeptComplete when earlier =>
|
||||
$"Quando il browser è tornato al motore alla pagina {needed}: come hai scelto nella pagina Collegamento («Tieni la copia completa»), Febe tiene la copia completa salvata prima. Se nel frattempo hai rifatto l'accesso o cambiato account, scegli «Sostituisci comunque». {Again}",
|
||||
SessionCopyStatus.Saved => "Sessione copiata per le richieste di Febe." + missingClause,
|
||||
SessionCopyStatus.SavedInMemoryOnly =>
|
||||
"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 =>
|
||||
$"Alla pagina {needed}: 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}",
|
||||
_ =>
|
||||
@@ -808,6 +1202,17 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// «mancano 3 valori che servono alle richieste», «manca 1 valore che serve alle richieste» (<paramref name="past"/>:
|
||||
/// «mancava», «mancavano»): the count with the Italian singular.
|
||||
/// </summary>
|
||||
internal static string MissingNeeded(int missing, bool past)
|
||||
{
|
||||
var one = missing == 1;
|
||||
var verb = past ? (one ? "mancava" : "mancavano") : (one ? "manca" : "mancano");
|
||||
return $"{verb} {ItalianText.Count(missing, "valore", "valori")} che {(one ? "serve" : "servono")} alle richieste";
|
||||
}
|
||||
|
||||
/// <summary>«Scollega» deletes the saved session (memory first, then the file); returns the error of the disk, if any.</summary>
|
||||
private async Task<Exception?> ForgetSavedSessionAsync()
|
||||
{
|
||||
@@ -938,6 +1343,27 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Forgets the copy made when this use of the browser was let go (S4b): it no longer answers a late «Ho finito».</summary>
|
||||
private void ForgetLetGoCopy()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_letGoCopy = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// «Ho finito» ends the lease. When it ends one, that use of the browser is over: a further «Ho finito» (a double
|
||||
/// click, a second tab) must not report a copy made when that use was let go earlier.
|
||||
/// </summary>
|
||||
private void EndUseWithHoFinito()
|
||||
{
|
||||
if (ReleaseLease())
|
||||
{
|
||||
ForgetLetGoCopy();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Ends the lease (only <paramref name="expected"/>, when given). True when a lease ended.</summary>
|
||||
private bool ReleaseLease(IDisposable? expected = null)
|
||||
{
|
||||
@@ -950,12 +1376,56 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
|
||||
return false;
|
||||
}
|
||||
|
||||
lease = _lease;
|
||||
watch = _leaseWatch;
|
||||
_lease = null;
|
||||
_leaseWatch = null;
|
||||
(lease, watch) = TakeLeaseLocked();
|
||||
}
|
||||
|
||||
return EndLease(lease, watch);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ends <paramref name="expected"/> by itself only if, in the same look, it is still the only lease of the browser and
|
||||
/// no sign that Alberto uses the browser came after <paramref name="lastSign"/>: another lease (the remote view, the
|
||||
/// window, a hold of the connection) is a sign now. True when the lease ended.
|
||||
/// </summary>
|
||||
private bool ReleaseIdleLease(IDisposable expected, DateTimeOffset lastSign)
|
||||
{
|
||||
IDisposable? lease;
|
||||
CancellationTokenSource? watch;
|
||||
lock (_gate)
|
||||
{
|
||||
if (!ReferenceEquals(_lease, expected))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (_browser.UserDriving.Leases > 1)
|
||||
{
|
||||
_lastDrivingSign = _clock.Now;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (_lastDrivingSign > lastSign)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
(lease, watch) = TakeLeaseLocked();
|
||||
}
|
||||
|
||||
return EndLease(lease, watch);
|
||||
}
|
||||
|
||||
private (IDisposable? Lease, CancellationTokenSource? Watch) TakeLeaseLocked()
|
||||
{
|
||||
var taken = (_lease, _leaseWatch);
|
||||
_lease = null;
|
||||
_leaseWatch = null;
|
||||
_leftAt = null;
|
||||
return taken;
|
||||
}
|
||||
|
||||
private static bool EndLease(IDisposable? lease, CancellationTokenSource? watch)
|
||||
{
|
||||
if (watch is not null)
|
||||
{
|
||||
watch.Cancel();
|
||||
|
||||
+39
-8
@@ -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,
|
||||
(how, ct) => Connection?.CopyOnWindowClosedAsync(how, 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));
|
||||
@@ -500,9 +510,7 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
|
||||
InBackground(() => Connection.RunAsync(ct));
|
||||
await engine.StartAsync(ct).ConfigureAwait(false);
|
||||
Log.Info("motore", Connection.IsConnected == true
|
||||
? "Motore avviato: il browser è collegato."
|
||||
: "Motore avviato: aspetta il collegamento (pagina Collegamento, «Accedi a Instagram»).");
|
||||
Log.Info("motore", StartedMessage(Connection));
|
||||
_running.TrySetResult();
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
@@ -576,10 +584,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)
|
||||
{
|
||||
@@ -665,6 +678,24 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The start-up line of the engine, with what it waits for: the same state as the engine's own gate
|
||||
/// (<see cref="BrowserConnectionService.IsReadyToCollect"/>), so that the log never says «collegato» while the monitor
|
||||
/// says «Serve «Ho finito»».
|
||||
/// </summary>
|
||||
internal static string StartedMessage(BrowserConnectionService connection)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(connection);
|
||||
if (connection.IsReadyToCollect)
|
||||
{
|
||||
return "Motore avviato: il browser è collegato.";
|
||||
}
|
||||
|
||||
return connection.IsConnected == true && connection.SessionCopyMissing
|
||||
? "Motore avviato: il browser è collegato, ma aspetta la copia della sessione per le richieste (pagina Collegamento, «Ho finito»)."
|
||||
: "Motore avviato: aspetta il collegamento (pagina Collegamento, «Accedi a Instagram»).";
|
||||
}
|
||||
|
||||
/// <summary>The site's home page as the browser writes it (with its final slash), for «Pagina iniziale».</summary>
|
||||
private static string HomeUrl(string baseUrl) =>
|
||||
Uri.TryCreate(baseUrl, UriKind.Absolute, out var home) ? home.AbsoluteUri : baseUrl;
|
||||
|
||||
@@ -72,7 +72,23 @@ 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 (or leaving it minimised too long) 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<BrowserWindowLetGo, CancellationToken, Task>? CopyOnWindowClosed = null);
|
||||
|
||||
/// <summary>How Alberto let go of the window «Browser di Febe» without «Ho finito» (Windows): the log says which.</summary>
|
||||
public enum BrowserWindowLetGo
|
||||
{
|
||||
/// <summary>He closed it.</summary>
|
||||
Closed,
|
||||
|
||||
/// <summary>He left it minimised longer than its limit: it went out of view as if closed.</summary>
|
||||
MinimizedTooLong,
|
||||
}
|
||||
|
||||
/// <summary>Options of the shared composition, filled by each shell from its own configuration.</summary>
|
||||
public sealed record FebeAppOptions
|
||||
|
||||
+169
-15
@@ -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).
|
||||
@@ -110,24 +159,34 @@ public sealed class BrowserSessionCopier : ISessionCopier
|
||||
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);
|
||||
}
|
||||
|
||||
// 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);
|
||||
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);
|
||||
}
|
||||
|
||||
// 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();
|
||||
// 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")
|
||||
+ (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(
|
||||
@@ -138,6 +197,56 @@ 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>«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
|
||||
{
|
||||
@@ -146,4 +255,49 @@ public sealed class BrowserSessionCopier : ISessionCopier
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user