Strato browser (M0/M2): client CDP con elenco dei comandi ammessi, ChromiumProcessHost e Xvfb sorvegliati, gesti umani, mappa dei bersagli, cattura delle risposte, segnali di arresto, scaricamento dal browser, vista remota, distribuzioni del ritmo; prove unitarie e d'insieme con Chromium su Xvfb; esito locale di S5 e S6
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
44 files changed
+8396
No files matched your search
@@ -0,0 +1,307 @@
|
||||
using System.Diagnostics;
|
||||
using Febe.Browser.Cdp;
|
||||
using Febe.Browser.Diagnostics;
|
||||
using Febe.Core.Abstractions;
|
||||
|
||||
namespace Febe.Browser.Hosting;
|
||||
|
||||
/// <summary>
|
||||
/// The browser host of the Docker version (spec §5, §6.1, §11): the distribution's Chromium, started as a normal
|
||||
/// windowed browser on a display (Xvfb), driven through its fixed DevTools port on 127.0.0.1.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <list type="bullet">
|
||||
/// <item>Supervised: if Chromium exits it is restarted with backoff and <see cref="Cdp"/> reconnects by itself
|
||||
/// (subscriptions survive; see <see cref="ICdpConnectionEvents.Reconnected"/>).</item>
|
||||
/// <item>The DevTools port must listen on loopback only, or the start is aborted.</item>
|
||||
/// <item>Stopping sends SIGINT first (not SIGTERM: see <see cref="ProcessSignals.SigInt"/>), so the profile and the
|
||||
/// session are written to disk; the process tree is killed only if it does not exit within the grace period.</item>
|
||||
/// </list>
|
||||
/// </remarks>
|
||||
public sealed class ChromiumProcessHost : IBrowserHost
|
||||
{
|
||||
private static readonly TimeSpan StopGrace = TimeSpan.FromSeconds(10);
|
||||
|
||||
private readonly ChromiumLaunchOptions _launch;
|
||||
private readonly IClock _clock;
|
||||
private readonly IBrowserLog _log;
|
||||
private readonly ReconnectingCdpSession _session = new();
|
||||
private readonly SemaphoreSlim _connectLock = new(1, 1);
|
||||
// Not disposed on purpose: background reconnection may still read its token; it holds no timer or handle.
|
||||
private readonly CancellationTokenSource _lifetime = new();
|
||||
private SupervisedProcess? _supervisor;
|
||||
private CdpClient? _client;
|
||||
private BrowserOptions? _options;
|
||||
private int _stopping;
|
||||
|
||||
public ChromiumProcessHost(ChromiumLaunchOptions? launch = null, IClock? clock = null, IBrowserLog? log = null)
|
||||
{
|
||||
_launch = launch ?? new ChromiumLaunchOptions();
|
||||
_clock = clock ?? new SystemClock();
|
||||
_log = log ?? NullBrowserLog.Instance;
|
||||
}
|
||||
|
||||
/// <summary>The page session. Stable across restarts; commands fail with <see cref="BrowserUnavailableException"/> while the browser is down.</summary>
|
||||
public ICdpSession Cdp => _session;
|
||||
|
||||
/// <summary>Raised when the connection was replaced after a restart.</summary>
|
||||
public ICdpConnectionEvents Connection => _session;
|
||||
|
||||
/// <summary>Leases taken while Alberto uses the browser (remote view, connection page).</summary>
|
||||
public UserDrivingGate UserDriving { get; } = new();
|
||||
|
||||
public bool UserIsDriving => UserDriving.IsDriving;
|
||||
|
||||
public BrowserOptions? Options => _options;
|
||||
|
||||
public SupervisedState State => _supervisor?.State ?? SupervisedState.Stopped;
|
||||
|
||||
public int? ProcessId => _supervisor?.ProcessId;
|
||||
|
||||
public int Restarts => _supervisor?.Restarts ?? 0;
|
||||
|
||||
public event EventHandler<SupervisedState>? StateChanged;
|
||||
|
||||
public async Task StartAsync(BrowserOptions options, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
if (_supervisor is not null)
|
||||
{
|
||||
throw new InvalidOperationException("Il browser è già avviato.");
|
||||
}
|
||||
|
||||
var executable = ChromiumCommandLine.FindExecutable(options.ExecutablePath)
|
||||
?? throw new FileNotFoundException("Chromium non è installato o non si trova (si può indicare con FEBE_CHROMIUM).");
|
||||
var arguments = ChromiumCommandLine.Build(options, _launch);
|
||||
if (LoopbackPortCheck.IsInUse(options.DebugPort))
|
||||
{
|
||||
throw new InvalidOperationException($"La porta di debug {options.DebugPort} è già occupata da un altro programma.");
|
||||
}
|
||||
|
||||
ChromiumProfile.Prepare(options.ProfileDirectory, _launch.SeedProfilePreferences);
|
||||
_options = options;
|
||||
|
||||
var supervisor = new SupervisedProcess(
|
||||
"Chromium",
|
||||
() => BuildStartInfo(executable, arguments, options),
|
||||
WaitReadyAndConnectAsync,
|
||||
_clock,
|
||||
_log,
|
||||
_launch.Restart,
|
||||
// Measured locally: on SIGTERM Chromium exits in ~35 ms and usually loses cookies set in the last 30 s;
|
||||
// on SIGINT it takes ~100 ms and writes them. The session must survive a restart (S3).
|
||||
ProcessSignals.SigInt);
|
||||
supervisor.ExitedUnexpectedly += (_, _) => _ = DropClientAsync();
|
||||
supervisor.StateChanged += (_, state) => StateChanged?.Invoke(this, state);
|
||||
_supervisor = supervisor;
|
||||
|
||||
try
|
||||
{
|
||||
await supervisor.StartAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
_supervisor = null;
|
||||
throw;
|
||||
}
|
||||
|
||||
_log.Info("Chromium è in funzione.");
|
||||
}
|
||||
|
||||
/// <summary>Windows only: the Docker browser is seen through the remote view.</summary>
|
||||
public Task ShowToUserAsync() => Task.CompletedTask;
|
||||
|
||||
public Task HideFromUserAsync() => Task.CompletedTask;
|
||||
|
||||
/// <summary>Puts the browser at rest on the blank page (spec §6.1).</summary>
|
||||
public Task<NavigationResult> RestAsync(CancellationToken ct = default) => _session.RestAsync(ct);
|
||||
|
||||
/// <summary>Whether the session cookie exists. Never reads its value.</summary>
|
||||
public Task<bool> HasSessionCookieAsync(CancellationToken ct = default) =>
|
||||
SessionCookieProbe.HasSessionCookieAsync(_session, _launch.SessionCookie, ct);
|
||||
|
||||
/// <summary>Kills the browser as if it had crashed (tests and «riavvia il browser»). The supervisor restarts it.</summary>
|
||||
public void KillForRestart() => _supervisor?.KillCurrent();
|
||||
|
||||
public async Task StopAsync()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _stopping, 1) == 1)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await _lifetime.CancelAsync().ConfigureAwait(false);
|
||||
await DropClientAsync().ConfigureAwait(false);
|
||||
if (_supervisor is { } supervisor)
|
||||
{
|
||||
await supervisor.StopAsync(StopGrace).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
_log.Info("Chromium è fermo.");
|
||||
}
|
||||
|
||||
/// <summary>Same as <see cref="StopAsync"/>. A stopped host cannot be started again: create a new one.</summary>
|
||||
public ValueTask DisposeAsync() => new(StopAsync());
|
||||
|
||||
private ProcessStartInfo BuildStartInfo(string executable, IReadOnlyList<string> arguments, BrowserOptions options)
|
||||
{
|
||||
var info = new ProcessStartInfo(executable);
|
||||
foreach (var argument in arguments)
|
||||
{
|
||||
info.ArgumentList.Add(argument);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(options.Display))
|
||||
{
|
||||
info.Environment["DISPLAY"] = options.Display;
|
||||
}
|
||||
|
||||
foreach (var (name, value) in _launch.Environment)
|
||||
{
|
||||
if (value is null)
|
||||
{
|
||||
info.Environment.Remove(name);
|
||||
}
|
||||
else
|
||||
{
|
||||
info.Environment[name] = value;
|
||||
}
|
||||
}
|
||||
|
||||
return info;
|
||||
}
|
||||
|
||||
private async Task WaitReadyAndConnectAsync(Process process, CancellationToken ct)
|
||||
{
|
||||
var options = _options ?? throw new InvalidOperationException("Opzioni mancanti.");
|
||||
var port = options.DebugPort;
|
||||
var deadline = _clock.Now + _launch.StartupTimeout;
|
||||
while (!await CdpTargetDiscovery.IsAvailableAsync(port, ct).ConfigureAwait(false))
|
||||
{
|
||||
if (process.HasExited)
|
||||
{
|
||||
throw new InvalidOperationException($"Chromium si è chiuso all'avvio (codice {process.ExitCode}). {_supervisor?.StderrTail()}".TrimEnd());
|
||||
}
|
||||
|
||||
if (_clock.Now >= deadline)
|
||||
{
|
||||
throw new TimeoutException($"Chromium non ha aperto la porta di debug entro {_launch.StartupTimeout.TotalSeconds:0} s.");
|
||||
}
|
||||
|
||||
await _clock.Delay(TimeSpan.FromMilliseconds(100), ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (!LoopbackPortCheck.IsLoopbackOnly(port, out var listeners))
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"La porta di debug {port} non è limitata a 127.0.0.1 ({listeners.Count} punti di ascolto): avvio annullato (specifica §6.1).");
|
||||
}
|
||||
|
||||
await ConnectAsync(port, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task ConnectAsync(int port, CancellationToken ct)
|
||||
{
|
||||
await _connectLock.WaitAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
CdpTarget? page = null;
|
||||
for (var attempt = 0; attempt < 50 && page is null; attempt++)
|
||||
{
|
||||
page = await CdpTargetDiscovery.FindPageAsync(port, ct).ConfigureAwait(false);
|
||||
if (page is null)
|
||||
{
|
||||
await _clock.Delay(TimeSpan.FromMilliseconds(100), ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (page is null)
|
||||
{
|
||||
throw new InvalidOperationException("Chromium non ha nessuna scheda aperta.");
|
||||
}
|
||||
|
||||
var client = await CdpClient.ConnectAsync(page.WebSocketDebuggerUrl, _log, null, ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await client.SendAsync("Page.enable", null, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
await client.DisposeAsync().ConfigureAwait(false);
|
||||
throw;
|
||||
}
|
||||
|
||||
client.Disconnected += OnClientDisconnected;
|
||||
var previous = Interlocked.Exchange(ref _client, client);
|
||||
_session.Attach(client);
|
||||
if (previous is not null)
|
||||
{
|
||||
previous.Disconnected -= OnClientDisconnected;
|
||||
await previous.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_connectLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private void OnClientDisconnected(object? sender, Exception? reason)
|
||||
{
|
||||
if (Volatile.Read(ref _stopping) == 1 || !ReferenceEquals(sender, Volatile.Read(ref _client)))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_session.Detach();
|
||||
_ = Task.Run(ReconnectAfterDropAsync);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The page connection dropped. If the process is gone the supervisor restarts it (and reconnects);
|
||||
/// if it is alive, reconnect to its page, or restart it when that fails.
|
||||
/// </summary>
|
||||
private async Task ReconnectAfterDropAsync()
|
||||
{
|
||||
var ct = _lifetime.Token;
|
||||
try
|
||||
{
|
||||
await _clock.Delay(TimeSpan.FromMilliseconds(500), ct).ConfigureAwait(false);
|
||||
if (_supervisor is not { } supervisor || supervisor.State != SupervisedState.Running || supervisor.ProcessId is null || _options is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
for (var attempt = 0; attempt < 3; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
await ConnectAsync(_options.DebugPort, ct).ConfigureAwait(false);
|
||||
_log.Info("Collegamento con Chromium ripristinato.");
|
||||
return;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
await _clock.Delay(TimeSpan.FromSeconds(1), ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
_log.Warn("Collegamento con Chromium perso: riavvio del browser.");
|
||||
supervisor.KillCurrent();
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private async Task DropClientAsync()
|
||||
{
|
||||
_session.Detach();
|
||||
var client = Interlocked.Exchange(ref _client, null);
|
||||
if (client is not null)
|
||||
{
|
||||
client.Disconnected -= OnClientDisconnected;
|
||||
await client.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user