Integrazione 0.1.1: unione di correzione/vista-remota-navigazione
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> # Conflicts: # docs/decisioni.md
This commit is contained in:
commit
058c0e8a4d
10 files changed
+586
-28
No files matched your search
@@ -262,3 +262,6 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
|
||||
| 2026-10-20 | «Storico completato» lo scrive solo il motore (`SessionComposer.FinishBackfillAsync`: @nome, post in libreria, che cosa succede ora); la ricetta Storico non scrive più una riga sua. Il motore chiude lo storico ogni volta che il cammino è arrivato in fondo (`BackfillFinished`), anche se poi la corsa finisce con un segnale o un'interruzione | Due righe nella cronologia e in «Avvisi» per lo stesso storico (@marta.prova, 14:31): la corta della ricetta e quella del motore. La notifica era già una sola e col testo del motore, perché la riga della ricetta (`CollectionWriter.EventAsync`) non passa da `EngineEvents` e `AlertService` non la vede. Con un segnale subito dopo l'ultima pagina l'account restava «Storico in corso» per sempre |
|
||||
| 2026-10-20 | Anche lo storico completato dal controllo del profilo (profilo tutto nella prima pagina) lo chiude il motore, con la sua riga (`BackfillFinished` del controllo, solo per un account «Storico in corso»). A inizio sessione il motore chiude gli account rimasti «Storico in corso» con lo storico già completato; la fase dello Storico rilegge gli account invece di usare quelli di inizio sessione | Con due account «Storico in corso» quello piccolo restava così per sempre, senza riga né avviso: dalla sessione dopo non era più candidato dello Storico. Rileggere gli account evita una seconda riga quando lo Storico della stessa sessione sceglierebbe proprio quello appena chiuso |
|
||||
| 2026-10-20 | Quando chiude uno storico, il motore toglie subito dalla coda il suo «Storico» e, se l'account resta in pausa, gli altri compiti pianificati; non rimette in coda la corsa dello Storico arrivata in fondo e poi fermata da un segnale | La Coda mostrava fino alla sessione dopo (dopo una verifica, fino a «Riprendi») uno Storico da fare per un account già «Aggiornato» o «In pausa». I comandi di Alberto restano |
|
||||
| 2026-10-20 | Vista remota: `Page.startScreencast` si manda di nuovo solo se Chromium risponde -32000 «Not attached to an active page», con pause da 100 a 500 ms e per al più 5 s di orologio vero (`ScreencastSession.InactivePageBudget`); collegamento chiuso, nessuna risposta o qualunque altro rifiuto danno subito «Il browser di Febe non risponde». Nessun comando CDP nuovo | Issue #3. Dal `ReadyToCommitNavigation` di una navigazione con un nuovo RenderFrameHost fino al suo commit, DevTools punta già al documento nuovo non ancora attivo e i comandi di pagina gestiti dal browser falliscono così (`page_handler.cc`, `AssureTopLevelActiveFrame`); con RenderDocument, attivo in Chromium, vale per ogni navigazione, anche verso la pagina di riposo. Ci cadevano la vista aperta insieme alla pagina di accesso, dopo un riposo del motore o durante una sessione |
|
||||
| 2026-10-20 | Sostituzione di una vista remota: `BrowserRemoteViewHost.OpenAsync` tiene un permesso «Alberto usa il browser» di passaggio dalla fine della vista vecchia all'avvio della nuova; l'ospite della vista usa `IFebeBrowser` invece di `ChromiumBrowser` | Fra le due viste i permessi scendevano a zero: il motore si svegliava e riportava la pagina a riposo proprio mentre la vista nuova avviava i fotogrammi (il fallimento della CI, issue #3), e avrebbe potuto cominciare una sessione. L'interfaccia permette di provarlo senza browser |
|
||||
| 2026-10-20 | Prova con Chromium vero del ritentativo della vista remota (`RemoteViewDuringNavigationTests`): una pagina del sito locale delle prove (`/occupata`) tiene occupato il renderer per 2 s, così la navigazione verso un'altra pagina dello stesso sito resta fra «ready to commit» e il commit e `Page.startScreencast` ci cade apposta; se in nessun giro Chromium rifiuta il primo avvio, la prova risulta inconcludente e non superata | Revisione dell'issue #3: TwoViews… prova solo il permesso di passaggio, e una vista aperta dall'ospite dopo l'inizio di una navigazione non incontra il rifiuto (`Page.getFrameTree` risponde solo dopo il commit). Con Chrome 155 sulla macchina di sviluppo, in un esperimento a parte con lo stesso codice di Febe, il rifiuto è arrivato in 18 giri su 18 e la vista si è aperta al sesto tentativo; con il testo atteso cambiato la stessa sequenza fallisce. Verso about:blank da una pagina del sito il commit avviene in un altro renderer: quel caso non serve allo scopo |
|
||||
@@ -92,11 +92,31 @@ public sealed class CdpCommandNotAllowedException(string method, string message)
|
||||
public sealed class CdpCommandException(string method, int code, string browserMessage)
|
||||
: Exception($"Il comando CDP «{method}» è fallito: {browserMessage} (codice {code}).")
|
||||
{
|
||||
/// <summary>Chromium's generic «server error» code.</summary>
|
||||
public const int ServerErrorCode = -32000;
|
||||
|
||||
/// <summary>
|
||||
/// What Chromium answers to a browser-side page command (<c>Page.startScreencast</c>, <c>Page.captureScreenshot</c>)
|
||||
/// while the page's current document is not «active»: from <c>ReadyToCommitNavigation</c> of a navigation that uses
|
||||
/// a new RenderFrameHost until that navigation commits, DevTools already points at the new, still uncommitted frame
|
||||
/// (content/browser/devtools/protocol/page_handler.cc, <c>AssureTopLevelActiveFrame</c>;
|
||||
/// render_frame_devtools_agent_host.cc, <c>ReadyToCommitNavigation</c>). A new RenderFrameHost comes with a process
|
||||
/// swap, a cross-site or back-forward-cache swap and, with RenderDocument (on by default in current Chromium), with
|
||||
/// every navigation of the page to a new document — the rest page included.
|
||||
/// </summary>
|
||||
public const string InactivePageMessage = "Not attached to an active page";
|
||||
|
||||
public string Method { get; } = method;
|
||||
|
||||
public int Code { get; } = code;
|
||||
|
||||
public string BrowserMessage { get; } = browserMessage;
|
||||
|
||||
/// <summary>
|
||||
/// The page is between two documents (see <see cref="InactivePageMessage"/>): the same command a moment later finds
|
||||
/// the new document committed. A browser that is gone answers differently (closed connection, no answer).
|
||||
/// </summary>
|
||||
public bool IsInactivePage => Code == ServerErrorCode && string.Equals(BrowserMessage, InactivePageMessage, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>The connection to the browser is closed (browser exited, crashed or is restarting).</summary>
|
||||
|
||||
@@ -64,12 +64,16 @@ public sealed class RemoteViewSession : IAsyncDisposable
|
||||
private IDisposable? _lease;
|
||||
private int _buttons;
|
||||
|
||||
public RemoteViewSession(ICdpSession cdp, UserDrivingGate gate, IBrowserLog? log = null)
|
||||
/// <param name="cdp">The page session.</param>
|
||||
/// <param name="gate">Where the «Alberto is driving» lease is taken.</param>
|
||||
/// <param name="log">Where opening and closing are noted (never keys).</param>
|
||||
/// <param name="clock">Wall-clock time for the screencast's start attempts; null: the system clock.</param>
|
||||
public RemoteViewSession(ICdpSession cdp, UserDrivingGate gate, IBrowserLog? log = null, IClock? clock = null)
|
||||
{
|
||||
_cdp = cdp ?? throw new ArgumentNullException(nameof(cdp));
|
||||
_gate = gate ?? throw new ArgumentNullException(nameof(gate));
|
||||
_log = log ?? NullBrowserLog.Instance;
|
||||
Screencast = new ScreencastSession(cdp, _log);
|
||||
Screencast = new ScreencastSession(cdp, _log, clock);
|
||||
}
|
||||
|
||||
public ScreencastSession Screencast { get; }
|
||||
|
||||
@@ -39,10 +39,22 @@ public sealed record ScreencastFrame(
|
||||
/// <c>Page.screencastFrameAck</c>, stopped with <c>Page.stopScreencast</c>. Frames are delivered through
|
||||
/// <see cref="ReadFramesAsync"/> (only the latest ones are kept when the reader is slow) and <see cref="FrameReceived"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A view opened while the page changes document (the rest page after a session, the login page opened together with
|
||||
/// the view) can meet the moment in which Chromium refuses the start with «Not attached to an active page»: the start
|
||||
/// is sent again, a few times, for at most <see cref="InactivePageBudget"/>. Any other failure is reported at once.
|
||||
/// </remarks>
|
||||
public sealed class ScreencastSession : IAsyncDisposable
|
||||
{
|
||||
/// <summary>How long a start refused because the page is between two documents is tried again.</summary>
|
||||
public static readonly TimeSpan InactivePageBudget = TimeSpan.FromSeconds(5);
|
||||
|
||||
private static readonly TimeSpan FirstPause = TimeSpan.FromMilliseconds(100);
|
||||
private static readonly TimeSpan LongestPause = TimeSpan.FromMilliseconds(500);
|
||||
|
||||
private readonly ICdpSession _cdp;
|
||||
private readonly IBrowserLog _log;
|
||||
private readonly IClock _clock;
|
||||
private readonly Channel<ScreencastFrame> _frames = Channel.CreateBounded<ScreencastFrame>(
|
||||
new BoundedChannelOptions(2) { FullMode = BoundedChannelFullMode.DropOldest, SingleReader = true });
|
||||
|
||||
@@ -54,10 +66,14 @@ public sealed class ScreencastSession : IAsyncDisposable
|
||||
private int _stopped;
|
||||
private long _framesReceived;
|
||||
|
||||
public ScreencastSession(ICdpSession cdp, IBrowserLog? log = null)
|
||||
/// <param name="cdp">The page session.</param>
|
||||
/// <param name="log">Where the start and stop are noted (never parameters or frames).</param>
|
||||
/// <param name="clock">Wall-clock time for the pauses between start attempts; null: the system clock.</param>
|
||||
public ScreencastSession(ICdpSession cdp, IBrowserLog? log = null, IClock? clock = null)
|
||||
{
|
||||
_cdp = cdp ?? throw new ArgumentNullException(nameof(cdp));
|
||||
_log = log ?? NullBrowserLog.Instance;
|
||||
_clock = clock ?? new SystemClock();
|
||||
}
|
||||
|
||||
/// <summary>Raised on the browser event thread for every frame: handlers must be quick.</summary>
|
||||
@@ -144,20 +160,47 @@ public sealed class ScreencastSession : IAsyncDisposable
|
||||
_lifetime.Dispose();
|
||||
}
|
||||
|
||||
private Task SendStartAsync(CancellationToken ct)
|
||||
private async Task SendStartAsync(CancellationToken ct)
|
||||
{
|
||||
var o = _options ?? new ScreencastOptions();
|
||||
return _cdp.SendAsync(
|
||||
"Page.startScreencast",
|
||||
new JsonObject
|
||||
var deadline = _clock.Now + InactivePageBudget;
|
||||
var pause = FirstPause;
|
||||
for (var attempt = 1; ; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
["format"] = "jpeg",
|
||||
["quality"] = Math.Clamp(o.Quality, 0, 100),
|
||||
["maxWidth"] = o.MaxWidth,
|
||||
["maxHeight"] = o.MaxHeight,
|
||||
["everyNthFrame"] = Math.Max(1, o.EveryNthFrame),
|
||||
},
|
||||
ct);
|
||||
await _cdp.SendAsync(
|
||||
"Page.startScreencast",
|
||||
new JsonObject
|
||||
{
|
||||
["format"] = "jpeg",
|
||||
["quality"] = Math.Clamp(o.Quality, 0, 100),
|
||||
["maxWidth"] = o.MaxWidth,
|
||||
["maxHeight"] = o.MaxHeight,
|
||||
["everyNthFrame"] = Math.Max(1, o.EveryNthFrame),
|
||||
},
|
||||
ct).ConfigureAwait(false);
|
||||
if (attempt > 1)
|
||||
{
|
||||
_log.Debug($"Vista remota: fotogrammi avviati al tentativo {attempt.ToString(System.Globalization.CultureInfo.InvariantCulture)}, dopo un cambio di pagina.");
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
catch (CdpCommandException ex) when (ex.IsInactivePage && _clock.Now + pause <= deadline)
|
||||
{
|
||||
// A navigation is committing in a new frame of the page: nothing is started on the browser side, the
|
||||
// same start a moment later finds the new document. Past the budget the error goes up as it is.
|
||||
}
|
||||
|
||||
await _clock.Delay(pause, ct).ConfigureAwait(false);
|
||||
if (Volatile.Read(ref _stopped) == 1)
|
||||
{
|
||||
return; // stopped meanwhile (a restart's start in the background): nothing left to start
|
||||
}
|
||||
|
||||
pause = pause * 2 < LongestPause ? pause * 2 : LongestPause;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnReconnected(object? sender, EventArgs e) =>
|
||||
|
||||
@@ -17,18 +17,40 @@ namespace Febe.Server;
|
||||
/// 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
|
||||
internal sealed class BrowserRemoteViewHost : IRemoteViewHost
|
||||
{
|
||||
private readonly IFebeBrowser _browser;
|
||||
private readonly BrowserUseTracker _tracker;
|
||||
private readonly IClock _clock;
|
||||
private readonly IClock _browserClock;
|
||||
private readonly FebeLog _log;
|
||||
private readonly Lock _gate = new();
|
||||
private readonly SemaphoreSlim _opening = new(1, 1);
|
||||
private BrowserRemoteViewConnection? _current;
|
||||
private bool _shuttingDown;
|
||||
|
||||
/// <param name="browser">The browser shown.</param>
|
||||
/// <param name="tracker">Notes when Alberto last used the browser.</param>
|
||||
/// <param name="clock">The composition's clock (the time of that note).</param>
|
||||
/// <param name="log">Febe's log.</param>
|
||||
/// <param name="browserClock">
|
||||
/// Time for the waits on the browser itself; null: the wall clock, because the browser commits a navigation in real
|
||||
/// time whatever clock the engine runs on (the tests compress it).
|
||||
/// </param>
|
||||
public BrowserRemoteViewHost(IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, FebeLog log, IClock? browserClock = null)
|
||||
{
|
||||
_browser = browser ?? throw new ArgumentNullException(nameof(browser));
|
||||
_tracker = tracker ?? throw new ArgumentNullException(nameof(tracker));
|
||||
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
||||
_log = log ?? throw new ArgumentNullException(nameof(log));
|
||||
_browserClock = browserClock ?? new SystemClock(clock.LocalZone);
|
||||
}
|
||||
|
||||
public async Task<IRemoteViewConnection> OpenAsync(CancellationToken ct)
|
||||
{
|
||||
if (!browser.IsAvailable)
|
||||
if (!_browser.IsAvailable)
|
||||
{
|
||||
throw new RemoteViewUnavailableException(browser.LastError is { } error
|
||||
throw new RemoteViewUnavailableException(_browser.LastError is { } error
|
||||
? "Il browser di Febe non è in funzione: " + error
|
||||
: "Il browser di Febe si sta avviando: riprova fra qualche secondo.");
|
||||
}
|
||||
@@ -37,6 +59,7 @@ internal sealed class BrowserRemoteViewHost(ChromiumBrowser browser, BrowserUseT
|
||||
// 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);
|
||||
IDisposable? handover = null;
|
||||
try
|
||||
{
|
||||
BrowserRemoteViewConnection? previous;
|
||||
@@ -53,13 +76,17 @@ internal sealed class BrowserRemoteViewHost(ChromiumBrowser browser, BrowserUseT
|
||||
|
||||
if (previous is not null)
|
||||
{
|
||||
// Alberto is still at the browser while one view takes the place of the other: without this lease the
|
||||
// engine would see nobody driving for a moment and put the page back to rest (a navigation under the new
|
||||
// view's start) or even begin a session.
|
||||
handover = _browser.UserDriving.Begin();
|
||||
await previous.EndAsync(RemoteViewEnd.Replaced).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var connection = new BrowserRemoteViewConnection(this, browser, tracker, clock);
|
||||
var connection = new BrowserRemoteViewConnection(this, _browser, _tracker, _clock, _browserClock);
|
||||
try
|
||||
{
|
||||
await connection.StartAsync(browser.BrowserOptions.WindowWidth, browser.BrowserOptions.WindowHeight, ct).ConfigureAwait(false);
|
||||
await connection.StartAsync(_browser.WindowWidth, _browser.WindowHeight, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -90,11 +117,13 @@ internal sealed class BrowserRemoteViewHost(ChromiumBrowser browser, BrowserUseT
|
||||
throw new RemoteViewUnavailableException("Febe si sta fermando.");
|
||||
}
|
||||
|
||||
log.Info("vista", "Vista remota aperta: il motore resta fermo finché è aperta.");
|
||||
_log.Info("vista", "Vista remota aperta: il motore resta fermo finché è aperta.");
|
||||
return connection;
|
||||
}
|
||||
finally
|
||||
{
|
||||
// The new view holds its own lease by now; if it did not start, nobody is at the browser any more.
|
||||
handover?.Dispose();
|
||||
_opening.Release();
|
||||
}
|
||||
}
|
||||
@@ -126,7 +155,7 @@ internal sealed class BrowserRemoteViewHost(ChromiumBrowser browser, BrowserUseT
|
||||
}
|
||||
}
|
||||
|
||||
log.Info("vista", "Vista remota chiusa.");
|
||||
_log.Info("vista", "Vista remota chiusa.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,7 +163,7 @@ internal sealed class BrowserRemoteViewHost(ChromiumBrowser browser, BrowserUseT
|
||||
internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
|
||||
{
|
||||
private readonly BrowserRemoteViewHost _owner;
|
||||
private readonly ChromiumBrowser _browser;
|
||||
private readonly IFebeBrowser _browser;
|
||||
private readonly BrowserUseTracker _tracker;
|
||||
private readonly IClock _clock;
|
||||
private readonly RemoteViewSession _session;
|
||||
@@ -155,18 +184,18 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
|
||||
private int _disposed;
|
||||
private bool _used;
|
||||
|
||||
public BrowserRemoteViewConnection(BrowserRemoteViewHost owner, ChromiumBrowser browser, BrowserUseTracker tracker, IClock clock)
|
||||
public BrowserRemoteViewConnection(BrowserRemoteViewHost owner, IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, IClock browserClock)
|
||||
{
|
||||
_owner = owner;
|
||||
_browser = browser;
|
||||
_tracker = tracker;
|
||||
_clock = clock;
|
||||
_session = new RemoteViewSession(browser.Host.Cdp, browser.Host.UserDriving);
|
||||
_session = new RemoteViewSession(browser.Cdp, browser.UserDriving, clock: browserClock);
|
||||
}
|
||||
|
||||
public RemoteViewEnd? Ended { get; private set; }
|
||||
|
||||
private ICdpSession Cdp => _browser.Host.Cdp;
|
||||
private ICdpSession Cdp => _browser.Cdp;
|
||||
|
||||
public async Task StartAsync(int width, int height, CancellationToken ct)
|
||||
{
|
||||
|
||||
@@ -53,7 +53,7 @@ internal sealed class DockerPlatform(ServerOptions options) : IFebePlatform
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(services);
|
||||
ArgumentNullException.ThrowIfNull(app);
|
||||
RemoteView = new BrowserRemoteViewHost((ChromiumBrowser)app.Browser!, app.Tracker, app.Clock, app.Log);
|
||||
RemoteView = new BrowserRemoteViewHost(app.Browser!, app.Tracker, app.Clock, app.Log);
|
||||
services.AddSingleton<IRemoteViewHost>(RemoteView);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics;
|
||||
using Febe.Browser.Cdp;
|
||||
using Febe.Browser.Diagnostics;
|
||||
using Febe.Browser.RemoteView;
|
||||
using Febe.Tests.Browser.TestSupport;
|
||||
|
||||
namespace Febe.Tests.Browser;
|
||||
|
||||
/// <summary>
|
||||
/// The remote view started while the page is between two documents (Gitea issue #3), on a real Chromium on Xvfb and the
|
||||
/// local test site. From <c>ReadyToCommitNavigation</c> of a navigation in a new RenderFrameHost until its commit,
|
||||
/// DevTools points at the new, not yet active document and Chromium refuses <c>Page.startScreencast</c> with -32000
|
||||
/// «Not attached to an active page». That moment lasts milliseconds in real use; here a page keeps its renderer busy, so
|
||||
/// a navigation away from it to a page of the same site waits to commit for over a second and the start lands in it on
|
||||
/// purpose. The view must open once the new document has committed and show its frames. If Chromium ever answers that
|
||||
/// moment with another text or code, the start fails here, on the CI, and not in Alberto's hands.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Seen with Chrome 155 on the development machine (a standalone CDP experiment, same pages): the start was refused in
|
||||
/// every round to a page of the same site and went through once the new document had committed. A navigation to
|
||||
/// about:blank from a site page commits in another renderer, which is not busy, so it is not used here. And a view opened
|
||||
/// through the host after a navigation has begun does not meet the refusal at all: its <c>Page.getFrameTree</c> is answered
|
||||
/// only once that navigation has committed (see ServerEndToEndTests.AViewOpenedWhileThePageIsNavigating…).
|
||||
/// </remarks>
|
||||
[TestClass]
|
||||
[DoNotParallelize]
|
||||
public sealed class RemoteViewDuringNavigationTests
|
||||
{
|
||||
public TestContext TestContext { get; set; } = null!;
|
||||
|
||||
[TestInitialize]
|
||||
public void RequireBrowser()
|
||||
{
|
||||
if (RealBrowser.UnavailableReason() is { } reason)
|
||||
{
|
||||
Assert.Inconclusive(reason);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(180_000, CooperativeCancellation = true)]
|
||||
public async Task AViewStartedBeforeTheNewDocumentCommitsOpensOnceItHasCommitted()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var browser = await RealBrowser.StartAsync();
|
||||
var cdp = browser.Cdp;
|
||||
|
||||
const int rounds = 6;
|
||||
var refusedRounds = 0;
|
||||
for (var round = 0; round < rounds; round++)
|
||||
{
|
||||
// Page.navigate answers once the new document is ready to commit; the busy page commits a moment later and its
|
||||
// script holds the renderer from 0.1 s after that, for 2 s.
|
||||
var busy = await cdp.NavigateAsync(browser.Site.Url("/occupata"), ct);
|
||||
Assert.IsTrue(busy.Succeeded, busy.ErrorText);
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(500), ct);
|
||||
|
||||
// The login page of the site, as «Accedi a Instagram» opens it: ready to commit at once, committed only when
|
||||
// the busy script lets go.
|
||||
var navigation = cdp.NavigateAsync(browser.Site.Url($"/accesso?giro={round}"), ct);
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(150), ct);
|
||||
|
||||
var notes = new ConcurrentQueue<string>();
|
||||
var log = new DelegateBrowserLog((level, message, _) =>
|
||||
{
|
||||
if (level == BrowserLogLevel.Debug)
|
||||
{
|
||||
notes.Enqueue(message);
|
||||
}
|
||||
});
|
||||
var view = new RemoteViewSession(cdp, browser.Host.UserDriving, log);
|
||||
try
|
||||
{
|
||||
var watch = Stopwatch.StartNew();
|
||||
await view.StartAsync(new ScreencastOptions(Quality: 60, MaxWidth: 1280, MaxHeight: 900), ct);
|
||||
watch.Stop();
|
||||
var navigated = await navigation;
|
||||
Assert.IsTrue(navigated.Succeeded, $"Round {round}: {navigated.ErrorText}");
|
||||
Assert.IsTrue(browser.Host.UserIsDriving, $"Round {round}: the open view holds the browser.");
|
||||
|
||||
// Only the attempt number is in the note (ScreencastSession): «… al tentativo N, dopo un cambio di pagina.»
|
||||
var retry = notes.FirstOrDefault(n => n.Contains("tentativo", StringComparison.Ordinal));
|
||||
if (retry is not null)
|
||||
{
|
||||
refusedRounds++;
|
||||
}
|
||||
|
||||
TestContext.WriteLine($"Giro {round}: vista aperta in {watch.ElapsedMilliseconds} ms; {retry ?? "fotogrammi avviati al primo tentativo."}");
|
||||
|
||||
// The frames of the new document: an animated page repaints all the time.
|
||||
var animated = await cdp.NavigateAsync(browser.Site.Url("/animata"), ct);
|
||||
Assert.IsTrue(animated.Succeeded, animated.ErrorText);
|
||||
Assert.IsTrue(await JpegArrivesAsync(view.Screencast, ct), $"Round {round}: frames after the view opened.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
await view.DisposeAsync();
|
||||
}
|
||||
|
||||
Assert.IsFalse(browser.Host.UserIsDriving, $"Round {round}: the closed view released the browser.");
|
||||
}
|
||||
|
||||
TestContext.WriteLine($"Giri in cui Chromium ha rifiutato il primo avvio con «{CdpCommandException.InactivePageMessage}»: {refusedRounds} su {rounds}.");
|
||||
if (refusedRounds == 0)
|
||||
{
|
||||
// Every view opened: the product is fine, but the start never met the refusal, so the retry was not exercised.
|
||||
Assert.Inconclusive("La vista si è aperta in ogni giro, ma Chromium non ha mai rifiutato il primo avvio: la prova non ha raggiunto il momento fra «ready to commit» e il commit (pagina /occupata, versione di Chromium) e il ritentativo non è stato messo alla prova.");
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<bool> JpegArrivesAsync(ScreencastSession screencast, CancellationToken ct)
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(15));
|
||||
try
|
||||
{
|
||||
await foreach (var frame in screencast.ReadFramesAsync(timeout.Token))
|
||||
{
|
||||
return frame.Jpeg is [0xFF, 0xD8, ..];
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -202,6 +202,10 @@ public sealed class LocalTestSite : IDisposable
|
||||
"/spa" => "<p>Applicazione</p><script>addEventListener('load', () => setTimeout(() => history.pushState({}, '', '/verifica/interna?x=1'), 300));</script>",
|
||||
"/verifica" => "<h1>Verifica</h1>",
|
||||
"/accesso" => "<h1>Accesso</h1>",
|
||||
|
||||
// Keeps its renderer busy for 2 s, from 0.1 s after it has committed: a navigation away from it to a page of the
|
||||
// same site (same renderer) reaches «ready to commit» at once but commits only when the script lets go.
|
||||
"/occupata" => "<p>Occupata</p><script>setTimeout(() => { const end = performance.now() + 2000; while (performance.now() < end) { } }, 100);</script>",
|
||||
_ => "<p>Pagina di prova</p>",
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
using System.Diagnostics;
|
||||
using System.Text.Json.Nodes;
|
||||
using Febe.App;
|
||||
using Febe.Browser.Cdp;
|
||||
using Febe.Browser.Hosting;
|
||||
using Febe.Browser.RemoteView;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Server;
|
||||
using Febe.Tests.Browser.TestSupport;
|
||||
using Febe.Web.Connection;
|
||||
using Febe.Web.Engine;
|
||||
|
||||
namespace Febe.Tests.Server;
|
||||
|
||||
/// <summary>
|
||||
/// Opening the remote view while the page changes document (Gitea issue #3), without a browser. From
|
||||
/// <c>ReadyToCommitNavigation</c> of a navigation in a new RenderFrameHost until it commits, Chromium answers
|
||||
/// <c>Page.startScreencast</c> with -32000 «Not attached to an active page»: the view must open once the new document is
|
||||
/// there, a page that never gets there must still end in «non risponde» within a few seconds, and a browser that is gone
|
||||
/// must say so at once.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class RemoteViewStartTests
|
||||
{
|
||||
public TestContext TestContext { get; set; } = null!;
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(30_000, CooperativeCancellation = true)]
|
||||
public async Task AViewOpenedWhileThePageChangesDocumentOpensOnceTheNewDocumentIsThere()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = new Bed(attempt => attempt == 1 ? InactivePage() : null);
|
||||
|
||||
var view = await bed.Host.OpenAsync(ct);
|
||||
|
||||
Assert.IsNull(view.Ended, "the view is open");
|
||||
Assert.AreEqual(2, bed.Starts, "the start refused while the page changed document was sent again");
|
||||
Assert.AreEqual(1, bed.Browser.UserDriving.Leases, "the open view holds the browser");
|
||||
Assert.IsLessThan(TimeSpan.FromSeconds(1), bed.Elapsed, "a short pause, not the whole budget");
|
||||
|
||||
// Frames flow to the view: meta first, then the JPEG.
|
||||
bed.Cdp.Raise("Page.screencastFrame", Frame());
|
||||
var outputs = await ReadUntilFrameAsync(view, ct);
|
||||
Assert.IsInstanceOfType<RemoteViewMeta>(outputs[0]);
|
||||
Assert.IsInstanceOfType<RemoteViewFrame>(outputs[^1]);
|
||||
|
||||
await view.DisposeAsync();
|
||||
Assert.AreEqual(0, bed.Browser.UserDriving.Leases, "no view, no lease");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(30_000, CooperativeCancellation = true)]
|
||||
public async Task APageThatStaysBetweenTwoDocumentsStillEndsInNonRispondeWithinTheBudget()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = new Bed(_ => InactivePage());
|
||||
var watch = Stopwatch.StartNew();
|
||||
|
||||
var error = await Assert.ThrowsExactlyAsync<RemoteViewUnavailableException>(() => bed.Host.OpenAsync(ct));
|
||||
|
||||
StringAssert.Contains(error.Message, "non risponde");
|
||||
Assert.IsTrue(error.InnerException is CdpCommandException { IsInactivePage: true }, "the browser's answer stays the cause");
|
||||
Assert.IsLessThanOrEqualTo(ScreencastSession.InactivePageBudget, bed.Elapsed, "never longer than the budget");
|
||||
Assert.IsGreaterThan(TimeSpan.FromSeconds(4), bed.Elapsed, "tried for the whole budget");
|
||||
Assert.IsInRange(5, 15, bed.Starts, "a few attempts, spaced out");
|
||||
Assert.IsLessThan(TimeSpan.FromSeconds(10), watch.Elapsed, "the pauses are the clock's, not a hang");
|
||||
Assert.AreEqual(0, bed.Browser.UserDriving.Leases, "nothing of the view stays behind");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(30_000, CooperativeCancellation = true)]
|
||||
public async Task ABrowserThatIsGoneIsNotTriedAgain()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = new Bed(_ => new CdpDisconnectedException("Il collegamento con il browser si è chiuso."));
|
||||
|
||||
var error = await Assert.ThrowsExactlyAsync<RemoteViewUnavailableException>(() => bed.Host.OpenAsync(ct));
|
||||
|
||||
StringAssert.Contains(error.Message, "non risponde");
|
||||
Assert.AreEqual(1, bed.Starts);
|
||||
Assert.AreEqual(TimeSpan.Zero, bed.Elapsed, "no pause at all");
|
||||
Assert.AreEqual(0, bed.Browser.UserDriving.Leases);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(30_000, CooperativeCancellation = true)]
|
||||
public async Task AnotherRefusalOfTheBrowserIsNotTriedAgain()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = new Bed(_ => new CdpCommandException("Page.startScreencast", CdpCommandException.ServerErrorCode, "Not attached to a page"));
|
||||
|
||||
await Assert.ThrowsExactlyAsync<RemoteViewUnavailableException>(() => bed.Host.OpenAsync(ct));
|
||||
|
||||
Assert.AreEqual(1, bed.Starts, "only «Not attached to an active page» is the moment of a navigation");
|
||||
Assert.AreEqual(TimeSpan.Zero, bed.Elapsed);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(30_000, CooperativeCancellation = true)]
|
||||
public async Task ReplacingAViewKeepsAlbertoAtTheBrowserThroughout()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = new Bed(_ => null);
|
||||
var gate = bed.Browser.UserDriving;
|
||||
var older = await bed.Host.OpenAsync(ct);
|
||||
var released = 0;
|
||||
void OnChanged(object? sender, bool driving)
|
||||
{
|
||||
if (!driving)
|
||||
{
|
||||
Interlocked.Increment(ref released);
|
||||
}
|
||||
}
|
||||
|
||||
gate.Changed += OnChanged;
|
||||
try
|
||||
{
|
||||
var newer = await bed.Host.OpenAsync(ct);
|
||||
|
||||
Assert.AreEqual(RemoteViewEnd.Replaced, older.Ended);
|
||||
Assert.IsNull(newer.Ended);
|
||||
Assert.AreEqual(0, released, "the engine never sees nobody at the browser between the two views (it would rest the page under the new one)");
|
||||
Assert.AreEqual(1, gate.Leases);
|
||||
|
||||
await newer.DisposeAsync();
|
||||
Assert.AreEqual(1, released, "closing the last view lets the engine go on");
|
||||
Assert.AreEqual(0, gate.Leases);
|
||||
}
|
||||
finally
|
||||
{
|
||||
gate.Changed -= OnChanged;
|
||||
}
|
||||
}
|
||||
|
||||
private static CdpCommandException InactivePage() =>
|
||||
new("Page.startScreencast", CdpCommandException.ServerErrorCode, CdpCommandException.InactivePageMessage);
|
||||
|
||||
private static JsonObject Frame() => new()
|
||||
{
|
||||
["sessionId"] = 1,
|
||||
["data"] = Convert.ToBase64String([0xFF, 0xD8, 0xFF, 0xD9]),
|
||||
["metadata"] = new JsonObject { ["deviceWidth"] = Bed.Width, ["deviceHeight"] = Bed.Height, ["pageScaleFactor"] = 1 },
|
||||
};
|
||||
|
||||
private static async Task<List<RemoteViewOutput>> ReadUntilFrameAsync(IRemoteViewConnection view, CancellationToken ct)
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(10));
|
||||
var outputs = new List<RemoteViewOutput>();
|
||||
await foreach (var output in view.ReadAsync(timeout.Token))
|
||||
{
|
||||
outputs.Add(output);
|
||||
if (output is RemoteViewFrame)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return outputs;
|
||||
}
|
||||
|
||||
/// <summary>The host over a fake page whose answer to each <c>Page.startScreencast</c> is chosen by the test.</summary>
|
||||
private sealed class Bed : IAsyncDisposable
|
||||
{
|
||||
public const int Width = 1280;
|
||||
public const int Height = 900;
|
||||
|
||||
private readonly FebeLog _log;
|
||||
private readonly DateTimeOffset _start;
|
||||
private int _starts;
|
||||
|
||||
/// <param name="startFailure">For the n-th start (from 1), the exception the browser answers with; null: started.</param>
|
||||
public Bed(Func<int, Exception?> startFailure)
|
||||
{
|
||||
Clock = new VirtualClock();
|
||||
_start = Clock.Now;
|
||||
Cdp = new FakeCdpSession(Clock)
|
||||
{
|
||||
Responder = (method, _) =>
|
||||
{
|
||||
switch (method)
|
||||
{
|
||||
case "Page.getFrameTree":
|
||||
return new JsonObject { ["frameTree"] = new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = "about:blank" } } };
|
||||
case "Page.startScreencast":
|
||||
if (startFailure(Interlocked.Increment(ref _starts)) is { } failure)
|
||||
{
|
||||
throw failure;
|
||||
}
|
||||
|
||||
return null;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
},
|
||||
};
|
||||
Browser = new PageBrowser(Cdp);
|
||||
_log = new FebeLog(null, null, Clock);
|
||||
Host = new BrowserRemoteViewHost(Browser, new BrowserUseTracker(), Clock, _log, browserClock: Clock);
|
||||
}
|
||||
|
||||
public VirtualClock Clock { get; }
|
||||
|
||||
public FakeCdpSession Cdp { get; }
|
||||
|
||||
public PageBrowser Browser { get; }
|
||||
|
||||
public BrowserRemoteViewHost Host { get; }
|
||||
|
||||
public int Starts => Volatile.Read(ref _starts);
|
||||
|
||||
/// <summary>Time spent in the host's pauses (the virtual clock moves only there).</summary>
|
||||
public TimeSpan Elapsed => Clock.Now - _start;
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await Host.ShutdownAsync();
|
||||
_log.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A running browser on one page, as the remote view host sees it.</summary>
|
||||
private sealed class PageBrowser(ICdpSession cdp) : IFebeBrowser
|
||||
{
|
||||
public ICdpSession Cdp { get; } = cdp;
|
||||
|
||||
public UserDrivingGate UserDriving { get; } = new();
|
||||
|
||||
public bool UserIsDriving => UserDriving.IsDriving;
|
||||
|
||||
public bool IsAvailable => true;
|
||||
|
||||
public string? LastError => null;
|
||||
|
||||
public string ProfileDirectory => "browser";
|
||||
|
||||
public int WindowWidth => Bed.Width;
|
||||
|
||||
public int WindowHeight => Bed.Height;
|
||||
|
||||
public Task RunAsync(CancellationToken ct) => Task.CompletedTask;
|
||||
|
||||
public Task<NavigationResult> RestAsync(CancellationToken ct) => Cdp.RestAsync(ct);
|
||||
|
||||
public Task ShowToUserAsync(CancellationToken ct) => Task.CompletedTask;
|
||||
|
||||
public Task HideFromUserAsync(CancellationToken ct) => Task.CompletedTask;
|
||||
|
||||
public Task RestartWithEmptyProfileAsync(CancellationToken ct) => Task.CompletedTask;
|
||||
|
||||
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -252,20 +252,44 @@ public sealed partial class ServerEndToEndTests
|
||||
await server.Running.WaitAsync(TimeSpan.FromSeconds(60), ct);
|
||||
var host = server.RemoteView!;
|
||||
var gate = server.Browser!.UserDriving;
|
||||
var released = 0;
|
||||
void OnChanged(object? sender, bool driving)
|
||||
{
|
||||
if (!driving)
|
||||
{
|
||||
Interlocked.Increment(ref released);
|
||||
}
|
||||
}
|
||||
|
||||
for (var round = 0; round < 5; round++)
|
||||
{
|
||||
// From the rest page: where the browser starts, and where the engine puts it once nobody is at the browser.
|
||||
// Page.getFrameTree is answered by the page itself, which DevTools holds back while a navigation is pending:
|
||||
// «about:blank» here means the engine's rest has committed.
|
||||
await ServerTestBed.WaitUntilAsync(
|
||||
async () => await Febe.Browser.Cdp.CdpPageExtensions.GetMainFrameUrlAsync(server.Browser.Cdp, ct) == "about:blank",
|
||||
TimeSpan.FromSeconds(20),
|
||||
"la pagina di riposo");
|
||||
|
||||
// Two tabs restored together, or the phone and the PC at once: the newest wins, the other is ended.
|
||||
var views = await Task.WhenAll(Task.Run(() => host.OpenAsync(ct), ct), Task.Run(() => host.OpenAsync(ct), ct));
|
||||
// Two tabs restored together, or the phone and the PC at once: the newest wins, the other is ended — and the
|
||||
// engine never sees nobody at the browser in between (it would put the page to rest under the newer view).
|
||||
Volatile.Write(ref released, 0);
|
||||
gate.Changed += OnChanged;
|
||||
IRemoteViewConnection[] views;
|
||||
try
|
||||
{
|
||||
views = await Task.WhenAll(Task.Run(() => host.OpenAsync(ct), ct), Task.Run(() => host.OpenAsync(ct), ct));
|
||||
}
|
||||
finally
|
||||
{
|
||||
gate.Changed -= OnChanged;
|
||||
}
|
||||
|
||||
var open = views.Where(v => v.Ended is null).ToList();
|
||||
Assert.HasCount(1, open, $"Round {round}: one view stays open.");
|
||||
Assert.AreEqual(RemoteViewEnd.Replaced, views.Single(v => v.Ended is not null).Ended);
|
||||
Assert.AreEqual(1, gate.Leases, $"Round {round}: only the open view holds the browser.");
|
||||
Assert.AreEqual(0, Volatile.Read(ref released), $"Round {round}: the browser was never left without a driver while one view replaced the other.");
|
||||
|
||||
// The page of the replaced view closes its socket: the open view still gets its frames.
|
||||
await views.Single(v => v.Ended is not null).DisposeAsync();
|
||||
@@ -277,6 +301,55 @@ public sealed partial class ServerEndToEndTests
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(180_000, CooperativeCancellation = true)]
|
||||
public async Task AViewOpenedWhileThePageIsNavigatingOpensAndShowsItsFrames()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ServerTestBed.StartAsync();
|
||||
var server = bed.Server;
|
||||
await server.Running.WaitAsync(TimeSpan.FromSeconds(60), ct);
|
||||
var host = server.RemoteView!;
|
||||
var browser = server.Browser!;
|
||||
|
||||
for (var round = 0; round < 6; round++)
|
||||
{
|
||||
// From the rest page, as in TwoViews…: the previous round ends on a site page, so «about:blank» here means the
|
||||
// engine's rest after the last view has committed and nothing else navigates.
|
||||
await ServerTestBed.WaitUntilAsync(
|
||||
async () => await Febe.Browser.Cdp.CdpPageExtensions.GetMainFrameUrlAsync(browser.Cdp, ct) == "about:blank",
|
||||
TimeSpan.FromSeconds(20),
|
||||
"la pagina di riposo");
|
||||
|
||||
// Even rounds: «Accedi a Instagram» on the Collegamento page navigates to the login page while the same page
|
||||
// opens the view. Odd rounds: the rest page, as the engine puts it after a session or after the last view.
|
||||
// A guard of these pairs, not of the retry: with the navigation already sent, the view's first look at the
|
||||
// page (Page.getFrameTree) is answered only once it has committed, so the start comes after the commit (seen
|
||||
// with Chrome 155). RemoteViewDuringNavigationTests makes the start meet the refusal on purpose.
|
||||
var navigation = round % 2 == 0
|
||||
? Febe.Browser.Cdp.CdpPageExtensions.NavigateAsync(browser.Cdp, $"{bed.Site.SiteUrl}/?vista={round}", ct)
|
||||
: browser.RestAsync(ct);
|
||||
var view = await host.OpenAsync(ct);
|
||||
try
|
||||
{
|
||||
var navigated = await navigation;
|
||||
Assert.IsTrue(navigated.Succeeded, $"Round {round}: {navigated.ErrorText}");
|
||||
Assert.IsNull(view.Ended, $"Round {round}: the view is open.");
|
||||
Assert.AreEqual(1, browser.UserDriving.Leases, $"Round {round}: only the view holds the browser.");
|
||||
|
||||
// A new page paints: its frames reach the view.
|
||||
await Febe.Browser.Cdp.CdpPageExtensions.NavigateAsync(browser.Cdp, $"{bed.Site.SiteUrl}/?giro={round}", ct);
|
||||
Assert.IsTrue(await FrameArrivesAsync(view, ct), $"Round {round}: frames of the page.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
await view.DisposeAsync();
|
||||
}
|
||||
|
||||
Assert.AreEqual(0, browser.UserDriving.Leases, $"Round {round}: no view, no lease.");
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<bool> FrameArrivesAsync(IRemoteViewConnection view, CancellationToken ct)
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
|
||||
Reference in new issue
Block a user