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
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user