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:
19 files changed
+1122
-92
No files matched your search
@@ -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()
|
||||
|
||||
@@ -365,6 +365,9 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
ConfigFolder = Data!.Root,
|
||||
Pace = services.Settings.Pace,
|
||||
UserIsDriving = () => browser.UserIsDriving,
|
||||
|
||||
// Rule 7: the pages Alberto opens (login, verification) are his, not the engine's, while no session runs.
|
||||
UserOwnsPage = () => browser.UserIsDriving && services.Runtime.CurrentSession is null,
|
||||
Log = Log.ForBrowser(),
|
||||
},
|
||||
ct).ConfigureAwait(false);
|
||||
|
||||
@@ -42,6 +42,18 @@ public sealed class UserDrivingGate
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>How many leases are open (an owner can tell whether someone besides it still holds one).</summary>
|
||||
public int Leases
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _leases;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Raised when <see cref="IsDriving"/> changes; the argument is the new value.</summary>
|
||||
public event EventHandler<bool>? Changed;
|
||||
|
||||
|
||||
@@ -77,6 +77,12 @@ public sealed record CollectionPipelineOptions
|
||||
/// <summary>True while Alberto uses the browser: gestures are not performed.</summary>
|
||||
public Func<bool>? UserIsDriving { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// True while the page is Alberto's (he uses the browser and no engine session runs): what he opens is not a stop
|
||||
/// signal (<see cref="SignalDetector.UserOwnsPage"/>). Null: always the engine's.
|
||||
/// </summary>
|
||||
public Func<bool>? UserOwnsPage { get; init; }
|
||||
|
||||
public IBrowserLog? Log { get; init; }
|
||||
}
|
||||
|
||||
@@ -131,7 +137,7 @@ public sealed class CollectionPipeline : IAsyncDisposable
|
||||
var rules = rulesFile is not null && File.Exists(rulesFile) ? SignalRules.Load(rulesFile) : SignalRules.LoadEmbedded(site.SignalsFile);
|
||||
|
||||
var tap = new ResponseTap(options.Cdp, site.Hosts, options.Clock, options.Log);
|
||||
var signals = new SignalDetector(rules, options.Breaker, options.Clock);
|
||||
var signals = new SignalDetector(rules, options.Breaker, options.Clock) { UserOwnsPage = options.UserOwnsPage };
|
||||
var capture = new CaptureCollector(new ShapeReader(vocabulary), options.Clock);
|
||||
var driver = new BrowserPageDriver(options.Cdp, targets, site.Hosts, options.Clock, options.Random, new BrowserDriverOptions
|
||||
{
|
||||
|
||||
@@ -31,6 +31,15 @@ public sealed class SignalDetector : IResponseObserver, IResponseConsumer, IStop
|
||||
|
||||
public TimeSpan DedupeWindow { get; }
|
||||
|
||||
/// <summary>
|
||||
/// True while the page is Alberto's, not the engine's: he holds the «driving» lease and no session runs. The
|
||||
/// addresses he opens then — the login page of «Accedi a Instagram», a verification he completes by hand — are not
|
||||
/// engine actions (rule 7 of §2) nor the page «going back to the login» of §7.6, so path rules (navigations and
|
||||
/// main documents) are not signals. Status and text rules, and the cookie check of the recipes, still are.
|
||||
/// Null: the page is always the engine's.
|
||||
/// </summary>
|
||||
public Func<bool>? UserOwnsPage { get; init; }
|
||||
|
||||
/// <summary>Raised after a signal has been reported to the breaker.</summary>
|
||||
public event EventHandler<Signal>? SignalRaised;
|
||||
|
||||
@@ -49,6 +58,7 @@ public sealed class SignalDetector : IResponseObserver, IResponseConsumer, IStop
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(response);
|
||||
var scope = response.IsMainFrameDocument ? SignalScope.Document : SignalScope.Subresource;
|
||||
var paths = !UserIsOnPage();
|
||||
foreach (var rule in _rules.Rules)
|
||||
{
|
||||
if (!rule.HostKinds.Contains(response.HostKind) || (rule.Scope & scope) == 0)
|
||||
@@ -57,7 +67,7 @@ public sealed class SignalDetector : IResponseObserver, IResponseConsumer, IStop
|
||||
}
|
||||
|
||||
if ((rule.Statuses.Count > 0 && rule.Statuses.Contains(response.Status))
|
||||
|| (rule.Path is not null && SafeIsMatch(rule.Path, response.Path)))
|
||||
|| (paths && rule.Path is not null && SafeIsMatch(rule.Path, response.Path)))
|
||||
{
|
||||
return Raise(rule.Level, rule.Code, response.Url);
|
||||
}
|
||||
@@ -66,10 +76,15 @@ public sealed class SignalDetector : IResponseObserver, IResponseConsumer, IStop
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Path rules on a main-frame navigation.</summary>
|
||||
/// <summary>Path rules on a main-frame navigation (none while the page is Alberto's: <see cref="UserOwnsPage"/>).</summary>
|
||||
public Signal? ObserveNavigation(NavigationDescriptor navigation)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(navigation);
|
||||
if (UserIsOnPage())
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
foreach (var rule in _rules.Rules)
|
||||
{
|
||||
if (rule.Path is null || (rule.Scope & SignalScope.Navigation) == 0 || !rule.HostKinds.Contains(navigation.HostKind))
|
||||
@@ -144,6 +159,8 @@ public sealed class SignalDetector : IResponseObserver, IResponseConsumer, IStop
|
||||
public Signal? ObserveSessionCookie(bool present) =>
|
||||
present ? null : Raise(SignalLevel.Disconnect, SignalRules.SessionCookieMissingCode, null);
|
||||
|
||||
private bool UserIsOnPage() => UserOwnsPage?.Invoke() == true;
|
||||
|
||||
private Signal? Raise(SignalLevel level, string code, string? url)
|
||||
{
|
||||
var now = _clock.Now;
|
||||
|
||||
@@ -44,6 +44,19 @@ public static class CheckPolicy
|
||||
|
||||
public static bool WantsStories(Account account) => (account.ContentTypes & ContentTypes.Stories) != 0;
|
||||
|
||||
public static bool WantsHighlights(Account account) => (account.ContentTypes & ContentTypes.Highlights) != 0;
|
||||
|
||||
/// <summary>
|
||||
/// Interval between two looks at the same highlight collection («Raccolta in evidenza»): eight story intervals of
|
||||
/// the frequency, between one and seven days (High 1 day, Normal 2, Low a little less than 3). Collections change far
|
||||
/// less often than stories, and mostly with stories already saved (H9); a new collection is looked at at once.
|
||||
/// </summary>
|
||||
public static TimeSpan HighlightInterval(Account account)
|
||||
{
|
||||
var ticks = StoryMaxInterval(account).Ticks * 8;
|
||||
return TimeSpan.FromTicks(Math.Clamp(ticks, TimeSpan.FromDays(1).Ticks, TimeSpan.FromDays(7).Ticks));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Interval between profile checks. Not followed: ~12 h / ~3 h / ~75 min (Su misura: the hours chosen). Followed: the
|
||||
/// sweep discovers new posts, the profile check is only a reconciliation every 24 / 12 / 6 hours (Su misura: four
|
||||
|
||||
@@ -51,6 +51,7 @@ public sealed class EngineHost : IAsyncDisposable
|
||||
private Task? _loop;
|
||||
private bool _initialized;
|
||||
private bool _manualWaiting;
|
||||
private int _restAfterDriving;
|
||||
private DateTimeOffset? _plannedAfterStop;
|
||||
|
||||
public EngineHost(EngineServices services, IRecipeRunner runner)
|
||||
@@ -363,11 +364,15 @@ public sealed class EngineHost : IAsyncDisposable
|
||||
_s.Events.Publish(EngineNotificationKind.StateChanged);
|
||||
}
|
||||
|
||||
/// <summary>Alberto started or finished using the browser: when he starts, the session in progress ends at once.</summary>
|
||||
/// <summary>
|
||||
/// Alberto started or finished using the browser: when he starts, the session in progress ends at once (leaving the
|
||||
/// page to him); when he lets go, the loop puts the page back to rest.
|
||||
/// </summary>
|
||||
public void NotifyUserDrivingChanged()
|
||||
{
|
||||
if (_s.Runtime.UserIsDriving)
|
||||
{
|
||||
Volatile.Write(ref _restAfterDriving, 1);
|
||||
CancelSession();
|
||||
}
|
||||
|
||||
@@ -451,6 +456,15 @@ public sealed class EngineHost : IAsyncDisposable
|
||||
{
|
||||
var now = _s.Clock.Now;
|
||||
var runtime = _s.Runtime;
|
||||
if (runtime.UserIsDriving)
|
||||
{
|
||||
Volatile.Write(ref _restAfterDriving, 1);
|
||||
}
|
||||
else if (Interlocked.Exchange(ref _restAfterDriving, 0) == 1)
|
||||
{
|
||||
await RestAfterDrivingAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (runtime.IsPaused)
|
||||
{
|
||||
return LongWait;
|
||||
@@ -630,6 +644,8 @@ public sealed class EngineHost : IAsyncDisposable
|
||||
var keepPage = breaker.Status is BreakerStatus.Challenge or BreakerStatus.Disconnected || s.Runtime.UserIsDriving;
|
||||
if (!keepPage)
|
||||
{
|
||||
// This rest also serves a driving period that ended during the session.
|
||||
Interlocked.Exchange(ref _restAfterDriving, 0);
|
||||
try
|
||||
{
|
||||
await _runner.RestAsync(ct).ConfigureAwait(false);
|
||||
@@ -687,6 +703,36 @@ public sealed class EngineHost : IAsyncDisposable
|
||||
s.Events.Publish(EngineNotificationKind.StateChanged);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Alberto let go of the browser and no session runs: the page goes back to rest (spec §6.1), so that nothing he or a
|
||||
/// cancelled session left open stays on the site — a story viewer moves on by itself to other accounts (§6.3).
|
||||
/// After a verification or a disconnection the page stays as it is until «Riprendi» (§7.6).
|
||||
/// </summary>
|
||||
private async Task RestAfterDrivingAsync(CancellationToken ct)
|
||||
{
|
||||
if (_s.Breaker.State.Status is BreakerStatus.Challenge or BreakerStatus.Disconnected)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await _runner.RestAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
await _s.Events.WriteAsync(
|
||||
EventSeverity.Warning,
|
||||
EngineEventCodes.RecipeFailed,
|
||||
$"Non sono riuscito a portare il browser sulla pagina vuota ({ex.GetType().Name}).",
|
||||
ct: CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private SessionOutcome StopOutcome() =>
|
||||
_s.Breaker.State.Status == BreakerStatus.Throttled ? SessionOutcome.Throttled : SessionOutcome.Stopped;
|
||||
|
||||
|
||||
@@ -7,9 +7,10 @@ namespace Febe.Core.Engine;
|
||||
|
||||
/// <summary>
|
||||
/// Composes and runs one session (spec §7.2, §7.3): commands of Alberto first, then usually the Giro dei seguiti,
|
||||
/// the flagged and due stories, the expired profile checks, finally a few pages of history on one account. About one
|
||||
/// session in three stops after the sweep and the stories. Accounts are taken in a random order weighted by frequency
|
||||
/// and delay. Planned work lives in the persisted task queue; this class keeps it in step with the accounts.
|
||||
/// the flagged and due stories, the expired profile checks and highlight collections, finally a few pages of history on
|
||||
/// one account. About one session in three stops after the sweep and the stories. Accounts are taken in a random order
|
||||
/// weighted by frequency and delay. Planned work lives in the persisted task queue; this class keeps it in step with
|
||||
/// the accounts.
|
||||
/// </summary>
|
||||
internal sealed class SessionComposer
|
||||
{
|
||||
@@ -22,6 +23,12 @@ internal sealed class SessionComposer
|
||||
private readonly Action<long> _manualDone;
|
||||
private readonly Lock _noticeGate = new();
|
||||
private readonly HashSet<(string Code, long? Account, DateOnly Day)> _notices = [];
|
||||
|
||||
// The interface calls SyncQueueAsync while a session may be running. A recipe's task is Running in the database
|
||||
// between its start and its bookkeeping, and then has its successor: under this gate the queue is looked at only
|
||||
// when every task is pending, in flight (_inFlight) or already replaced by its successor, never in between.
|
||||
private readonly SemaphoreSlim _queueGate = new(1, 1);
|
||||
private EngineTask? _inFlight;
|
||||
private DateTimeOffset? _lastSweepAt;
|
||||
private bool _lastSweepLoaded;
|
||||
|
||||
@@ -114,7 +121,7 @@ internal sealed class SessionComposer
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Expired profile checks and other planned work.
|
||||
// 4. Expired profile checks, highlight collections and other planned work.
|
||||
if (!light && !Over(state, ct))
|
||||
{
|
||||
var now = Clock.Now;
|
||||
@@ -146,11 +153,25 @@ internal sealed class SessionComposer
|
||||
|
||||
/// <summary>
|
||||
/// Keeps the queue in step with the accounts: a profile check and a story check (as the account wants them) for
|
||||
/// every contactable account, a backfill task for every account «Storico in corso», a Giro dei seguiti when someone
|
||||
/// is followed; pending planned tasks of accounts that may not be contacted are cancelled. Commands of Alberto
|
||||
/// are left alone.
|
||||
/// every contactable account, a look at each highlight collection on its profile, a backfill task for every account
|
||||
/// «Storico in corso», a Giro dei seguiti when someone is followed; pending planned tasks of accounts that may not be
|
||||
/// contacted are cancelled. Commands of Alberto are left alone, and so is the task of the recipe in progress: its
|
||||
/// own bookkeeping plans the next one.
|
||||
/// </summary>
|
||||
public async Task<Dictionary<long, Account>> SyncQueueAsync(CancellationToken ct)
|
||||
{
|
||||
await _queueGate.WaitAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
return await SyncQueueLockedAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_queueGate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<Dictionary<long, Account>> SyncQueueLockedAsync(CancellationToken ct)
|
||||
{
|
||||
var now = Clock.Now;
|
||||
var accounts = (await Store.Accounts.ListAsync(ct).ConfigureAwait(false)).ToDictionary(a => a.Id);
|
||||
@@ -161,14 +182,14 @@ internal sealed class SessionComposer
|
||||
{
|
||||
var tasks = byAccount[account.Id].Where(t => !t.IsManual).ToList();
|
||||
var wanted = WantedKinds(account);
|
||||
foreach (var task in tasks.Where(t => !wanted.ContainsKey(t.Kind) && !(t.Kind == EngineTaskKind.AccountStories && t.Priority >= Options.FlaggedStoriesPriority && CheckPolicy.IsContactable(account))))
|
||||
foreach (var task in tasks.Where(t => t.Kind != EngineTaskKind.HighlightCheck && !wanted.ContainsKey(t.Kind) && !(t.Kind == EngineTaskKind.AccountStories && t.Priority >= Options.FlaggedStoriesPriority && CheckPolicy.IsContactable(account))))
|
||||
{
|
||||
await Store.Tasks.CancelAsync(task.Id, now, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
foreach (var (kind, dueAt) in wanted)
|
||||
{
|
||||
if (tasks.Any(t => t.Kind == kind))
|
||||
if (tasks.Any(t => t.Kind == kind) || InFlight(account.Id, kind, null))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
@@ -177,6 +198,8 @@ internal sealed class SessionComposer
|
||||
new EngineTask { Kind = kind, AccountId = account.Id, DueAt = dueAt ?? now, CreatedAt = now },
|
||||
ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await SyncHighlightsAsync(account, tasks, now, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var anyFollowed = accounts.Values.Any(a => a.IsFollowed && CheckPolicy.IsContactable(a));
|
||||
@@ -196,6 +219,52 @@ internal sealed class SessionComposer
|
||||
return accounts;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// «Raccolta in evidenza» (spec §6.3) for an account that wants «Storie in evidenza»: one task per collection the
|
||||
/// profile check found (payload: its Instagram identifier), due at once for a collection never looked at, then
|
||||
/// after <see cref="CheckPolicy.HighlightInterval"/>. Tasks of collections that left the profile, or of accounts
|
||||
/// that no longer want them or may not be contacted, are cancelled.
|
||||
/// </summary>
|
||||
private async Task SyncHighlightsAsync(Account account, List<EngineTask> tasks, DateTimeOffset now, CancellationToken ct)
|
||||
{
|
||||
var planned = tasks.Where(t => t.Kind == EngineTaskKind.HighlightCheck).ToList();
|
||||
var collections = new Dictionary<string, Highlight>(StringComparer.Ordinal);
|
||||
if (CheckPolicy.IsContactable(account) && CheckPolicy.WantsHighlights(account))
|
||||
{
|
||||
foreach (var highlight in await Store.Highlights.ListAsync(account.Id, includeRemoved: false, ct).ConfigureAwait(false))
|
||||
{
|
||||
if (highlight.InstagramId is { Length: > 0 } id)
|
||||
{
|
||||
collections.TryAdd(id, highlight);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var task in planned.Where(t => t.Payload is null || !collections.ContainsKey(t.Payload)))
|
||||
{
|
||||
await Store.Tasks.CancelAsync(task.Id, now, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
foreach (var (id, highlight) in collections)
|
||||
{
|
||||
if (planned.Any(t => t.Payload == id) || InFlight(account.Id, EngineTaskKind.HighlightCheck, id))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var due = highlight.LastCheckedAt is { } last
|
||||
? last + CheckPolicy.NextCheckDelay(_s.Random, CheckPolicy.HighlightInterval(account))
|
||||
: now;
|
||||
await Store.Tasks.EnqueueAsync(
|
||||
new EngineTask { Kind = EngineTaskKind.HighlightCheck, AccountId = account.Id, Payload = id, DueAt = due, CreatedAt = now },
|
||||
ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Whether the recipe in progress runs a task of this kind (and payload) for the account. Under the queue gate.</summary>
|
||||
private bool InFlight(long accountId, EngineTaskKind kind, string? payload) =>
|
||||
_inFlight is { } task && task.AccountId == accountId && task.Kind == kind && (payload is null || task.Payload == payload);
|
||||
|
||||
/// <summary>The Giro dei seguiti shown in the queue at the next session.</summary>
|
||||
public Task EnsureSweepTaskAsync(DateTimeOffset dueAt, CancellationToken ct) =>
|
||||
Store.Tasks.EnqueueAsync(
|
||||
@@ -359,6 +428,13 @@ internal sealed class SessionComposer
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// One highlight collection per account and session, and none on a profile already opened in this session:
|
||||
// the others wait for the next session instead of reopening the same profile again and again.
|
||||
if (task.Kind == EngineTaskKind.HighlightCheck && (state.Visited.Contains(id) || !state.HighlightAccounts.Add(id)))
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
switch (task.Kind)
|
||||
@@ -610,7 +686,7 @@ internal sealed class SessionComposer
|
||||
return null;
|
||||
}
|
||||
|
||||
if (task is not null && !await Store.Tasks.TryStartAsync(task.Id, Clock.Now, ct).ConfigureAwait(false))
|
||||
if (task is not null && !await StartTaskAsync(task, ct).ConfigureAwait(false))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
@@ -627,7 +703,16 @@ internal sealed class SessionComposer
|
||||
{
|
||||
if (task is not null)
|
||||
{
|
||||
await RequeueAsync(task, "Interrotta", Clock.Now).ConfigureAwait(false);
|
||||
await _queueGate.WaitAsync(CancellationToken.None).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await RequeueAsync(task, "Interrotta", Clock.Now).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_inFlight = null;
|
||||
_queueGate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
throw;
|
||||
@@ -643,11 +728,41 @@ internal sealed class SessionComposer
|
||||
}
|
||||
|
||||
context.AddNewEntries(outcome.NewEntries);
|
||||
await ApplyOutcomeAsync(task, request, account, outcome, state).ConfigureAwait(false);
|
||||
await _queueGate.WaitAsync(CancellationToken.None).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await ApplyOutcomeAsync(task, request, account, outcome, state).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_inFlight = null;
|
||||
_queueGate.Release();
|
||||
}
|
||||
|
||||
_s.Events.Publish(EngineNotificationKind.ActivityChanged);
|
||||
return outcome;
|
||||
}
|
||||
|
||||
/// <summary>Pending → Running, recorded as the task in flight under the queue gate. False when it was not pending.</summary>
|
||||
private async Task<bool> StartTaskAsync(EngineTask task, CancellationToken ct)
|
||||
{
|
||||
await _queueGate.WaitAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
if (!await Store.Tasks.TryStartAsync(task.Id, Clock.Now, ct).ConfigureAwait(false))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
_inFlight = task;
|
||||
return true;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_queueGate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ApplyOutcomeAsync(EngineTask? task, RecipeRequest request, Account? account, RecipeOutcome outcome, SessionState state)
|
||||
{
|
||||
// Bookkeeping always completes, even when the session has just been cancelled. Independent writes are queued
|
||||
@@ -1022,6 +1137,9 @@ internal sealed class SessionComposer
|
||||
/// <summary>Commands of Alberto already taken up in this session.</summary>
|
||||
public HashSet<long> ManualDone { get; } = [];
|
||||
|
||||
/// <summary>Accounts whose highlight collection was taken up in this session (one per account and session).</summary>
|
||||
public HashSet<long> HighlightAccounts { get; } = [];
|
||||
|
||||
public bool Stop { get; set; }
|
||||
|
||||
public int Recipes { get; set; }
|
||||
|
||||
@@ -13,6 +13,11 @@ namespace Febe.Core.Simulation;
|
||||
/// <para>Delays are rounded up to whole milliseconds, the resolution of the database, so stored and computed times compare exactly.</para>
|
||||
/// <para>With <see cref="AutoAdvance"/> a delay moves time forward at once: handy for one component under test, without a driver.</para>
|
||||
/// <para>Each actor must wait on at most one delay at a time, otherwise the driver could advance before the second is registered.</para>
|
||||
/// <para>
|
||||
/// A delay may be cancelled from any thread, also one that is not an actor (the engine cancels a session from the thread
|
||||
/// pool when a signal arrives). The cancelled actor runs again, so the driver decides whether to fire the next timer or
|
||||
/// to finish under the same lock in which it looks again at how many actors still wait.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed class VirtualClock : IClock
|
||||
{
|
||||
@@ -120,17 +125,9 @@ public sealed class VirtualClock : IClock
|
||||
/// <summary>Moves time to <paramref name="target"/>, firing in order the timers that fall due on the way.</summary>
|
||||
public void AdvanceTo(DateTimeOffset target)
|
||||
{
|
||||
while (TryFireNext(target))
|
||||
while (FireNextOrFinish(target, running: 0) != Step.Finished)
|
||||
{
|
||||
}
|
||||
|
||||
lock (_gate)
|
||||
{
|
||||
if (target > _now)
|
||||
{
|
||||
_now = target;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -152,16 +149,9 @@ public sealed class VirtualClock : IClock
|
||||
await failed.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (!TryFireNext(target))
|
||||
var running = Actors - actors.Count(a => a.IsCompleted);
|
||||
if (FireNextOrFinish(target, running) == Step.Finished)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (target > _now)
|
||||
{
|
||||
_now = target;
|
||||
}
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -198,11 +188,22 @@ public sealed class VirtualClock : IClock
|
||||
}
|
||||
}
|
||||
|
||||
private bool TryFireNext(DateTimeOffset limit)
|
||||
/// <summary>
|
||||
/// One step of the driver, atomic with a fresh look at the waiting actors: fires the earliest live timer due by
|
||||
/// <paramref name="limit"/>; when there is none, moves time to <paramref name="limit"/> and says the run is finished.
|
||||
/// With <paramref name="running"/> actors expected to wait, fewer pending timers mean that an actor's timer was
|
||||
/// cancelled from another thread after the quiescence check: that actor runs again and nothing moves.
|
||||
/// </summary>
|
||||
private Step FireNextOrFinish(DateTimeOffset limit, int running)
|
||||
{
|
||||
PendingDelay? fired = null;
|
||||
lock (_gate)
|
||||
{
|
||||
if (running > 0 && _active < running)
|
||||
{
|
||||
return Step.NotQuiescent;
|
||||
}
|
||||
|
||||
while (_timers.TryPeek(out var next, out _))
|
||||
{
|
||||
if (next.Done)
|
||||
@@ -228,16 +229,21 @@ public sealed class VirtualClock : IClock
|
||||
FiredTimers++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (fired is null)
|
||||
{
|
||||
return false;
|
||||
if (fired is null)
|
||||
{
|
||||
if (limit > _now)
|
||||
{
|
||||
_now = limit;
|
||||
}
|
||||
|
||||
return Step.Finished;
|
||||
}
|
||||
}
|
||||
|
||||
fired.Registration.Dispose();
|
||||
fired.Completion.TrySetResult();
|
||||
return true;
|
||||
return Step.Fired;
|
||||
}
|
||||
|
||||
private void Cancel(PendingDelay delay, CancellationToken ct)
|
||||
@@ -259,6 +265,18 @@ public sealed class VirtualClock : IClock
|
||||
delay.Completion.TrySetCanceled(ct);
|
||||
}
|
||||
|
||||
private enum Step
|
||||
{
|
||||
/// <summary>A timer fired: an actor runs.</summary>
|
||||
Fired,
|
||||
|
||||
/// <summary>An actor runs again (its timer was cancelled from outside): wait until it waits.</summary>
|
||||
NotQuiescent,
|
||||
|
||||
/// <summary>Nothing left before the limit: time is at the limit.</summary>
|
||||
Finished,
|
||||
}
|
||||
|
||||
private sealed class PendingDelay
|
||||
{
|
||||
public DateTimeOffset Due { get; set; }
|
||||
|
||||
@@ -13,11 +13,14 @@ namespace Febe.Server;
|
||||
/// <summary>
|
||||
/// The remote view over the real Chromium (spec §4.1, §11, PROTOCOLLO.md): a <see cref="RemoteViewSession"/> per open
|
||||
/// view, which holds the «Alberto is driving» lease while it is open, so the engine is still. One view at a time: a
|
||||
/// view opened in another tab replaces the older one. Keys go to the browser and nowhere else.
|
||||
/// view opened in another tab replaces the older one, also when two open at the same moment (opening is serialized, so
|
||||
/// the older view is always ended — and its screencast stopped — before the newer one starts). Keys go to the browser
|
||||
/// and nowhere else.
|
||||
/// </summary>
|
||||
internal sealed class BrowserRemoteViewHost(ChromiumBrowser browser, BrowserUseTracker tracker, IClock clock, FebeLog log) : IRemoteViewHost
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
private readonly SemaphoreSlim _opening = new(1, 1);
|
||||
private BrowserRemoteViewConnection? _current;
|
||||
private bool _shuttingDown;
|
||||
|
||||
@@ -30,41 +33,70 @@ internal sealed class BrowserRemoteViewHost(ChromiumBrowser browser, BrowserUseT
|
||||
: "Il browser di Febe si sta avviando: riprova fra qualche secondo.");
|
||||
}
|
||||
|
||||
BrowserRemoteViewConnection? previous;
|
||||
lock (_gate)
|
||||
// From the look at the current view to the new one in its place, one opening at a time: two views opened at once
|
||||
// would both start and the later assignment would orphan the other (still holding its lease, and stopping the
|
||||
// shared screencast when it closes).
|
||||
await _opening.WaitAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
if (_shuttingDown)
|
||||
BrowserRemoteViewConnection? previous;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_shuttingDown)
|
||||
{
|
||||
throw new RemoteViewUnavailableException("Febe si sta fermando.");
|
||||
}
|
||||
|
||||
previous = _current;
|
||||
_current = null;
|
||||
}
|
||||
|
||||
if (previous is not null)
|
||||
{
|
||||
await previous.EndAsync(RemoteViewEnd.Replaced).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var connection = new BrowserRemoteViewConnection(this, browser, tracker, clock);
|
||||
try
|
||||
{
|
||||
await connection.StartAsync(browser.BrowserOptions.WindowWidth, browser.BrowserOptions.WindowHeight, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Whatever went wrong (the page gone away, an unexpected frame tree), nothing of the view stays behind:
|
||||
// no lease, no screencast, no subscription.
|
||||
await connection.DisposeAsync().ConfigureAwait(false);
|
||||
if (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException)
|
||||
{
|
||||
throw new RemoteViewUnavailableException("Il browser di Febe non risponde: riprova fra qualche secondo.", ex);
|
||||
}
|
||||
|
||||
throw;
|
||||
}
|
||||
|
||||
bool stopping;
|
||||
lock (_gate)
|
||||
{
|
||||
stopping = _shuttingDown;
|
||||
if (!stopping)
|
||||
{
|
||||
_current = connection;
|
||||
}
|
||||
}
|
||||
|
||||
if (stopping)
|
||||
{
|
||||
await connection.EndAsync(RemoteViewEnd.ShuttingDown).ConfigureAwait(false);
|
||||
throw new RemoteViewUnavailableException("Febe si sta fermando.");
|
||||
}
|
||||
|
||||
previous = _current;
|
||||
_current = null;
|
||||
log.Info("vista", "Vista remota aperta: il motore resta fermo finché è aperta.");
|
||||
return connection;
|
||||
}
|
||||
|
||||
if (previous is not null)
|
||||
finally
|
||||
{
|
||||
await previous.EndAsync(RemoteViewEnd.Replaced).ConfigureAwait(false);
|
||||
_opening.Release();
|
||||
}
|
||||
|
||||
var connection = new BrowserRemoteViewConnection(this, browser, tracker, clock);
|
||||
try
|
||||
{
|
||||
await connection.StartAsync(browser.BrowserOptions.WindowWidth, browser.BrowserOptions.WindowHeight, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException)
|
||||
{
|
||||
await connection.DisposeAsync().ConfigureAwait(false);
|
||||
throw new RemoteViewUnavailableException("Il browser di Febe non risponde: riprova fra qualche secondo.", ex);
|
||||
}
|
||||
|
||||
lock (_gate)
|
||||
{
|
||||
_current = connection;
|
||||
}
|
||||
|
||||
log.Info("vista", "Vista remota aperta: il motore resta fermo finché è aperta.");
|
||||
return connection;
|
||||
}
|
||||
|
||||
/// <summary>Febe is stopping: the open view is closed with a reason the page can show.</summary>
|
||||
|
||||
@@ -28,6 +28,15 @@ public static class RemoteViewSocket
|
||||
/// <summary>Close code when the browser stopped or is restarting.</summary>
|
||||
public const int CloseBrowserStopped = 4002;
|
||||
|
||||
/// <summary>How often the server pings the page.</summary>
|
||||
public static readonly TimeSpan KeepAliveInterval = TimeSpan.FromSeconds(20);
|
||||
|
||||
/// <summary>
|
||||
/// How long a ping may stay unanswered: a page that vanished without closing (laptop lid, lost Wi-Fi) is dropped
|
||||
/// then, and with it the «Alberto is driving» lease of its view, instead of when TCP gives up many minutes later.
|
||||
/// </summary>
|
||||
public static readonly TimeSpan KeepAliveTimeout = TimeSpan.FromSeconds(30);
|
||||
|
||||
public static void Map(IEndpointRouteBuilder endpoints)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(endpoints);
|
||||
@@ -69,15 +78,21 @@ public static class RemoteViewSocket
|
||||
|
||||
await using (connection.ConfigureAwait(false))
|
||||
{
|
||||
using var socket = await context.WebSockets.AcceptWebSocketAsync(new WebSocketAcceptContext
|
||||
{
|
||||
KeepAliveInterval = TimeSpan.FromSeconds(20),
|
||||
DangerousEnableCompression = false,
|
||||
}).ConfigureAwait(false);
|
||||
using var socket = await context.WebSockets.AcceptWebSocketAsync(AcceptContext()).ConfigureAwait(false);
|
||||
await RunAsync(socket, connection, context.RequestAborted).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pings with a timeout: with an interval alone ASP.NET Core sends unsolicited pongs and never notices a dead page.
|
||||
/// </summary>
|
||||
internal static WebSocketAcceptContext AcceptContext() => new()
|
||||
{
|
||||
KeepAliveInterval = KeepAliveInterval,
|
||||
KeepAliveTimeout = KeepAliveTimeout,
|
||||
DangerousEnableCompression = false,
|
||||
};
|
||||
|
||||
/// <summary>Pumps one view until either side closes it.</summary>
|
||||
internal static async Task RunAsync(WebSocket socket, IRemoteViewConnection connection, CancellationToken aborted)
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user