Collegamento e motore: correzioni regole-1, regole-2, regole-6, websec-1, websec-5, websec-6, engine-1, engine-2, sched-1

Pagine aperte da Alberto non sono segnali (regole-1); cookie perso fuori sessione = disconnessione (regole-2); pagina a riposo quando Alberto lascia il browser (regole-6); la lease di «Accedi»/«Usa il browser» finisce da sola dopo 2 minuti senza vista remota né finestra (websec-1); ping con scadenza sulla vista remota (websec-5); aperture della vista remota serializzate (websec-6); orologio virtuale senza fine anticipata (engine-1); la sincronizzazione della coda non duplica il compito in corso (engine-2); raccolte in evidenza programmate (sched-1).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
Claude committed 2026-10-14 00:21:13 +00:00
1 parent 78c92eb2a4
commit aff81dfac9
19 files changed
+1122 -92

No files matched your search

+182 -14
View File
@@ -2,6 +2,7 @@ using System.Globalization;
using Febe.Browser.Cdp;
using Febe.Browser.Hosting;
using Febe.Core.Abstractions;
using Febe.Core.Collection;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Storage;
@@ -20,11 +21,27 @@ namespace Febe.App;
/// «Ho finito» and «Annulla» put it back out of view, «Scollega» closes it before deleting the profile. In Docker
/// showing and hiding do nothing (the remote view shows the browser).
/// </summary>
/// <remarks>
/// <para>
/// The lease taken by «Accedi a Instagram» and «Usa il browser» ends with «Ho finito», «Annulla» or «Scollega», and also
/// by itself when for <see cref="DrivingGrace"/> it is the only sign that Alberto uses the browser — no remote view open
/// in Docker, the window «Browser di Febe» out of view on Windows: he went away without either button, and the engine
/// must not stay still for ever.
/// </para>
/// <para>
/// A session cookie that disappears outside a session (or is missing at start-up after a connection) is a disconnection
/// (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>
/// </remarks>
public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposable
{
/// <summary>Setting written at the first connection ever (Unix ms): the gradual start begins only once.</summary>
public const string FirstConnectionKey = "collegamento.primo";
/// <summary>Setting set by «Scollega» and removed by the next connection: until then a missing session is expected.</summary>
public const string DisconnectedByUserKey = "collegamento.scollegato";
/// <summary>A cookie check younger than this is reused by the status (the sidebar asks often).</summary>
public static readonly TimeSpan CookieCacheLifetime = TimeSpan.FromSeconds(3);
@@ -42,7 +59,10 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
private readonly Lock _gate = new();
private EngineHost? _engine;
private IDisposable? _lease;
private CancellationTokenSource? _leaseWatch;
private DateTimeOffset _lastDrivingSign;
private bool? _connected;
private bool? _disconnectedByUser;
private DateTimeOffset _checkedAt = DateTimeOffset.MinValue;
public BrowserConnectionService(IFebeBrowser browser, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, FebeLog log, string loginUrl, SessionCookieOptions cookie)
@@ -78,6 +98,12 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
/// </summary>
public event EventHandler<bool>? ConnectionChanged;
/// <summary>
/// How long the lease of «Accedi a Instagram» / «Usa il browser» outlives every other lease of the browser (remote
/// view, window in front) before it ends by itself. Read at every look; tests shorten it.
/// </summary>
public TimeSpan DrivingGrace { get; set; } = TimeSpan.FromMinutes(2);
/// <summary>The engine, once it exists (it is built after the browser).</summary>
public void AttachEngine(EngineHost engine) => _engine = engine ?? throw new ArgumentNullException(nameof(engine));
@@ -92,7 +118,7 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
var breaker = _engine?.Services.Breaker.State.Status;
var state = breaker is BreakerStatus.Challenge or BreakerStatus.Disconnected
? ConnectionState.VerificationRequired
: await CheckAsync(force: false, ct).ConfigureAwait(false) == true ? ConnectionState.Connected : ConnectionState.NotConnected;
: await CheckAsync(force: false, mayReport: true, ct).ConfigureAwait(false) == true ? ConnectionState.Connected : ConnectionState.NotConnected;
Account? mine = null;
if (state != ConnectionState.NotConnected)
@@ -111,7 +137,16 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
{
lock (_gate)
{
_lease ??= _browser.UserDriving.Begin();
if (_lease is null)
{
_lease = _browser.UserDriving.Begin();
var watch = new CancellationTokenSource();
_leaseWatch = watch;
var lease = _lease;
_ = Task.Run(() => WatchLeaseAsync(lease, watch.Token), CancellationToken.None);
}
_lastDrivingSign = _clock.Now;
}
_tracker.MarkUsed(_clock.Now);
@@ -149,10 +184,11 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
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.");
}
var connected = await CheckAsync(force: true, ct).ConfigureAwait(false) == true;
// Alberto has just been at the browser: a session he did not complete is said here, not reported as a stop.
var connected = await CheckAsync(force: true, mayReport: false, ct).ConfigureAwait(false) == true;
_tracker.MarkUsed(_clock.Now);
var first = connected && await MarkConnectedAsync(ct).ConfigureAwait(false);
await RestQuietlyAsync().ConfigureAwait(false);
await RestIfAlbertosAsync().ConfigureAwait(false);
await HideQuietlyAsync().ConfigureAwait(false);
ReleaseLease();
@@ -191,7 +227,7 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
{
if (_browser.IsAvailable)
{
await RestQuietlyAsync().ConfigureAwait(false);
await RestIfAlbertosAsync().ConfigureAwait(false);
await HideQuietlyAsync().ConfigureAwait(false);
}
@@ -210,6 +246,8 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
var hold = _browser.UserDriving.Begin();
try
{
// From now on a missing session is Alberto's choice, not a disconnection to report (until he connects again).
await RememberUserDisconnectAsync().ConfigureAwait(false);
var engine = _engine;
if (engine is not null)
{
@@ -264,7 +302,8 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
/// <summary>
/// Looks at the cookie now (outside the cache) and records the change. Used at start-up, by the background loop
/// and after the test site's automatic login.
/// and after the test site's automatic login. A session that went away (or is missing at start-up after a
/// connection) while Alberto is not at the browser is reported to the breaker as a disconnection (spec §7.6).
/// </summary>
public async Task<bool?> RefreshAsync(CancellationToken ct)
{
@@ -273,7 +312,7 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
return IsConnected;
}
var connected = await CheckAsync(force: true, ct).ConfigureAwait(false);
var connected = await CheckAsync(force: true, mayReport: true, ct).ConfigureAwait(false);
if (connected == true)
{
await MarkConnectedAsync(ct).ConfigureAwait(false);
@@ -313,7 +352,7 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
return ValueTask.CompletedTask;
}
private async Task<bool?> CheckAsync(bool force, CancellationToken ct)
private async Task<bool?> CheckAsync(bool force, bool mayReport, CancellationToken ct)
{
lock (_gate)
{
@@ -333,21 +372,31 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
return IsConnected;
}
SetConnected(has);
var previous = SetConnected(has);
if (has)
{
await ForgetUserDisconnectAsync(ct).ConfigureAwait(false);
}
else if (mayReport && previous != false && !_browser.UserIsDriving)
{
await ReportLostSessionAsync(previous, ct).ConfigureAwait(false);
}
return has;
}
private void SetConnected(bool connected)
/// <summary>Records the state of the cookie; returns the one before (null before the first check).</summary>
private bool? SetConnected(bool connected)
{
bool changed;
bool? previous;
lock (_gate)
{
changed = _connected != connected;
previous = _connected;
_connected = connected;
_checkedAt = _clock.Now;
}
if (changed)
if (previous != connected)
{
_log.Info("collegamento", connected ? "Sessione presente nel browser: collegato." : "Nessuna sessione nel browser: non collegato.");
@@ -355,6 +404,102 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
_engine?.NotifyUserDrivingChanged();
ConnectionChanged?.Invoke(this, connected);
}
return previous;
}
/// <summary>
/// The session cookie is gone while Alberto is not at the browser (spec §7.6 «il cookie di sessione non c'è più»):
/// the same disconnection the recipes report, so the breaker writes the incident, the alert goes out and only
/// «Riprendi» (with the gradual start) restarts the engine. Not after «Scollega», and at start-up only when the
/// profile had been connected.
/// </summary>
private async Task ReportLostSessionAsync(bool? previous, CancellationToken ct)
{
if (_engine is not { } engine || await IsDisconnectedByUserAsync(ct).ConfigureAwait(false))
{
return;
}
if (previous is null && await _storage.Settings.GetInt64Async(FirstConnectionKey, ct).ConfigureAwait(false) is null)
{
return; // never connected: nothing was lost
}
engine.Services.Breaker.Report(new Signal(SignalLevel.Disconnect, SignalRules.SessionCookieMissingCode, null, _clock.Now));
_log.Warn("collegamento", "La sessione di Instagram non c'è più nel browser: Febe si ferma finché non accedi di nuovo e premi «Riprendi».");
}
private async Task<bool> IsDisconnectedByUserAsync(CancellationToken ct)
{
if (_disconnectedByUser is { } known)
{
return known;
}
var stored = await _storage.Settings.GetBoolAsync(DisconnectedByUserKey, false, ct).ConfigureAwait(false);
_disconnectedByUser = stored;
return stored;
}
private async Task RememberUserDisconnectAsync()
{
_disconnectedByUser = true;
await _storage.Settings.SetBoolAsync(DisconnectedByUserKey, true, CancellationToken.None).ConfigureAwait(false);
}
/// <summary>A session is in the browser again: from now on its loss is a disconnection.</summary>
private async Task ForgetUserDisconnectAsync(CancellationToken ct)
{
if (await IsDisconnectedByUserAsync(ct).ConfigureAwait(false))
{
_disconnectedByUser = false;
await _storage.Settings.SetAsync(DisconnectedByUserKey, null, ct).ConfigureAwait(false);
}
}
/// <summary>
/// The «driving» lease of this service ends by itself once it has been the only lease of the browser for
/// <see cref="DrivingGrace"/>: the remote view closed (Docker) or the window went out of view (Windows), and
/// neither «Ho finito» nor «Annulla» came. The page is not touched here (the engine puts it to rest).
/// </summary>
private async Task WatchLeaseAsync(IDisposable lease, CancellationToken ct)
{
try
{
while (true)
{
var grace = DrivingGrace;
var poll = TimeSpan.FromTicks(Math.Clamp(grace.Ticks / 8, TimeSpan.FromMilliseconds(20).Ticks, TimeSpan.FromSeconds(5).Ticks));
await _clock.Delay(poll, ct).ConfigureAwait(false);
DateTimeOffset lastSign;
lock (_gate)
{
if (!ReferenceEquals(_lease, lease))
{
return;
}
// Besides this lease: the remote view, the browser window in front, «Scollega» in progress.
if (_browser.UserDriving.Leases > 1)
{
_lastDrivingSign = _clock.Now;
}
lastSign = _lastDrivingSign;
}
if (_clock.Now - lastSign >= grace && ReleaseLease(lease))
{
_log.Info("collegamento", $"Nessuna vista del browser aperta da {ItalianText.Duration(grace)} senza «Ho finito» né «Annulla»: il motore può riprendere.");
return;
}
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
// The lease ended with a command of Alberto.
}
}
/// <summary>The first connection ever starts the gradual start (spec §7.2). True when it was the first.</summary>
@@ -408,6 +553,13 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
}
}
/// <summary>
/// Puts the page to rest while it is Alberto's (a lease holds the engine still). Once every lease ended — this
/// service's ended by itself after <see cref="DrivingGrace"/> — the page is the engine's again: a late «Ho finito» or
/// «Annulla» must not navigate under a session (the engine rested the page when the driving ended).
/// </summary>
private Task RestIfAlbertosAsync() => _browser.UserIsDriving ? RestQuietlyAsync() : Task.CompletedTask;
private async Task RestQuietlyAsync()
{
try
@@ -444,16 +596,32 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
}
}
private void ReleaseLease()
/// <summary>Ends the lease (only <paramref name="expected"/>, when given). True when a lease ended.</summary>
private bool ReleaseLease(IDisposable? expected = null)
{
IDisposable? lease;
CancellationTokenSource? watch;
lock (_gate)
{
if (expected is not null && !ReferenceEquals(_lease, expected))
{
return false;
}
lease = _lease;
watch = _leaseWatch;
_lease = null;
_leaseWatch = null;
}
if (watch is not null)
{
watch.Cancel();
watch.Dispose();
}
lease?.Dispose();
return lease is not null;
}
private void EnsureBrowser()