using System.Diagnostics; using Febe.Browser.Cdp; using Febe.Browser.Diagnostics; using Febe.Core.Abstractions; using Febe.Core.Security; namespace Febe.Browser.Hosting; /// /// 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. /// /// /// /// Supervised: if Chromium exits it is restarted with backoff and reconnects by itself /// (subscriptions survive; see ). /// The DevTools port must listen on loopback only, or the start is aborted. /// Stopping sends SIGINT first (not SIGTERM: see ), 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. /// /// 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); private readonly SemaphoreSlim _restartLock = 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; private int _restarting; public ChromiumProcessHost(ChromiumLaunchOptions? launch = null, IClock? clock = null, IBrowserLog? log = null) { _launch = launch ?? new ChromiumLaunchOptions(); _clock = clock ?? new SystemClock(); _log = log ?? NullBrowserLog.Instance; } /// The page session. Stable across restarts; commands fail with while the browser is down. public ICdpSession Cdp => _session; /// Raised when the connection was replaced after a restart. public ICdpConnectionEvents Connection => _session; /// Leases taken while Alberto uses the browser (remote view, connection page). 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? StateChanged; /// True while a page connection is attached (commands can be sent). public bool IsAttached => _session.IsAttached; public async Task StartAsync(BrowserOptions options, CancellationToken ct) { ArgumentNullException.ThrowIfNull(options); if (_supervisor is not null) { throw new InvalidOperationException("Il browser è già avviato."); } await StartCoreAsync(options, ct).ConfigureAwait(false); } /// /// Stops the browser (SIGINT, so the profile is written to disk), runs — «Scollega» /// deletes the profile there — and starts it again with the same options. stays the same object: /// subscriptions survive and is raised once the new browser is /// connected. /// public async Task RestartAsync(Action? whileStopped, CancellationToken ct) { var options = _options ?? throw new InvalidOperationException("Il browser non è mai partito."); if (Volatile.Read(ref _stopping) == 1) { throw new InvalidOperationException("Il browser si sta fermando."); } await _restartLock.WaitAsync(ct).ConfigureAwait(false); Interlocked.Exchange(ref _restarting, 1); try { if (_supervisor is { } current) { await DropClientAsync().ConfigureAwait(false); await current.StopAsync(StopGrace).ConfigureAwait(false); _supervisor = null; _log.Info("Chromium è fermo per un nuovo avvio."); } whileStopped?.Invoke(); await StartCoreAsync(options, ct).ConfigureAwait(false); } finally { Interlocked.Exchange(ref _restarting, 0); _restartLock.Release(); } } private async Task StartCoreAsync(BrowserOptions options, CancellationToken ct) { 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."); } /// Windows only: the Docker browser is seen through the remote view. public Task ShowToUserAsync() => Task.CompletedTask; public Task HideFromUserAsync() => Task.CompletedTask; /// Puts the browser at rest on the blank page (spec §6.1). public Task RestAsync(CancellationToken ct = default) => _session.RestAsync(ct); /// Whether the session cookie exists. Never reads its value. public Task HasSessionCookieAsync(CancellationToken ct = default) => SessionCookieProbe.HasSessionCookieAsync(_session, _launch.SessionCookie, ct); /// Kills the browser as if it had crashed (tests and «riavvia il browser»). The supervisor restarts it. public void KillForRestart() => _supervisor?.KillCurrent(); public async Task StopAsync() { if (Interlocked.Exchange(ref _stopping, 1) == 1) { return; } await _lifetime.CancelAsync().ConfigureAwait(false); // A restart in progress («Scollega») finishes first, so that no browser is left running behind the stop. await _restartLock.WaitAsync().ConfigureAwait(false); try { await DropClientAsync().ConfigureAwait(false); if (_supervisor is { } supervisor) { await supervisor.StopAsync(StopGrace).ConfigureAwait(false); } } finally { _restartLock.Release(); } _log.Info("Chromium è fermo."); } /// Same as . A stopped host cannot be started again: create a new one. public ValueTask DisposeAsync() => new(StopAsync()); /// /// The start of Chromium (or Edge): its arguments, the display, the variables of , /// and never Febe's secrets (), whatever the parent or the options hold. /// internal ProcessStartInfo BuildStartInfo(string executable, IReadOnlyList 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.WithoutSecrets(); } private async Task WaitReadyAndConnectAsync(Process process, CancellationToken ct) { // First of all, as close to the start as possible: the processes the browser opens afterwards follow it. _launch.ProcessStarted?.Invoke(process); 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, deadline, () => process.HasExited ? $"Chromium si è chiuso all'avvio (codice {process.ExitCode}). {_supervisor?.StderrTail()}".TrimEnd() : null, ct).ConfigureAwait(false); } /// /// Connects to the first page target. The first tab may appear a while after the port opens on a loaded machine: /// the wait shares the start deadline, and ends at once when says the process is no longer the /// one to connect to (it exited, or the supervisor replaced it): nobody waits on the connect lock for a dead browser. /// private async Task ConnectAsync(int port, DateTimeOffset deadline, Func gone, CancellationToken ct) { await _connectLock.WaitAsync(ct).ConfigureAwait(false); try { CdpTarget? page; while ((page = await TryFindPageAsync(port, ct).ConfigureAwait(false)) is null) { if (gone() is { } reason) { throw new InvalidOperationException(reason); } if (_clock.Now >= deadline) { throw new InvalidOperationException("Chromium non ha nessuna scheda aperta."); } await _clock.Delay(TimeSpan.FromMilliseconds(100), ct).ConfigureAwait(false); } 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(); } } /// The page target, or null when there is none yet or the endpoint did not answer this time. private static async Task TryFindPageAsync(int port, CancellationToken ct) { try { return await CdpTargetDiscovery.FindPageAsync(port, ct).ConfigureAwait(false); } catch (HttpRequestException) { return null; } catch (TaskCanceledException) when (!ct.IsCancellationRequested) { return null; // a slow answer of /json/list, not a missing one } } private void OnClientDisconnected(object? sender, Exception? reason) { if (Volatile.Read(ref _stopping) == 1 || Volatile.Read(ref _restarting) == 1 || !ReferenceEquals(sender, Volatile.Read(ref _client))) { return; } _session.Detach(); _ = Task.Run(ReconnectAfterDropAsync); } /// /// 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. /// 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; } // The process that dropped the connection: if it exits or the supervisor restarts it, stop at once and leave // the connect lock to the restart, which connects by itself. var processId = supervisor.ProcessId; string? Gone() => supervisor.State != SupervisedState.Running || supervisor.ProcessId != processId ? "Chromium è stato riavviato o si è chiuso durante il ricollegamento." : null; var deadline = _clock.Now + _launch.StartupTimeout; for (var attempt = 0; attempt < 3 && Gone() is null; attempt++) { try { await ConnectAsync(_options.DebugPort, deadline, Gone, 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); } } if (Gone() is not null) { return; } _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); } } }