Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
299 lines
12 KiB
C#
299 lines
12 KiB
C#
using System.Globalization;
|
||
using Febe.Browser.Cdp;
|
||
using Febe.Browser.Hosting;
|
||
using Febe.Core.Abstractions;
|
||
|
||
namespace Febe.App;
|
||
|
||
/// <summary>How a Chromium-family browser is started and looked after (spec §6.1, §11; S2 fallback on Windows).</summary>
|
||
public sealed record ChromiumBrowserSettings
|
||
{
|
||
/// <summary>The profile folder given to the browser (<c>--user-data-dir</c>): it holds the Instagram session.</summary>
|
||
public required string ProfileDirectory { get; init; }
|
||
|
||
/// <summary>
|
||
/// The folder «Scollega» deletes while the browser is stopped. Null: <see cref="ProfileDirectory"/>. On Windows the
|
||
/// Edge profile is a subfolder of <c>Dati\browser</c>, and «Scollega» deletes the whole <c>Dati\browser</c>.
|
||
/// </summary>
|
||
public string? ProfileFolderToDelete { get; init; }
|
||
|
||
/// <summary>Folder created before the start (Docker: the HOME of the browser process). Null: none.</summary>
|
||
public string? HomeDirectory { get; init; }
|
||
|
||
/// <summary>Size of the browser window, always the same (spec §6.1).</summary>
|
||
public int WindowWidth { get; init; } = 1280;
|
||
|
||
public int WindowHeight { get; init; } = 900;
|
||
|
||
/// <summary>The fixed DevTools port, on 127.0.0.1 only (spec §6.1).</summary>
|
||
public int DebugPort { get; init; } = 9222;
|
||
|
||
/// <summary>The executable; null: <see cref="ChromiumCommandLine.FindExecutable"/>.</summary>
|
||
public string? ExecutablePath { get; init; }
|
||
|
||
/// <summary>The Xvfb display (Docker, «:99»). Null: no virtual display, the browser opens a normal window.</summary>
|
||
public string? Display { get; init; }
|
||
|
||
/// <summary>Arguments, environment, cookie of the session, restart policy.</summary>
|
||
public ChromiumLaunchOptions Launch { get; init; } = new();
|
||
|
||
/// <summary>Added to the «browser ready» log line (Docker: «, senza sandbox (FEBE_SENZA_SANDBOX)»).</summary>
|
||
public string? ReadyRemark { get; init; }
|
||
|
||
/// <summary>Added to a start error that mentions the sandbox (Docker: where the seccomp profile is explained).</summary>
|
||
public string? SandboxAdvice { get; init; }
|
||
}
|
||
|
||
/// <summary>
|
||
/// A Chromium-family browser started and supervised by Febe itself, never by a shell script (spec §5, §6.1, §11): the
|
||
/// distribution's Chromium on Xvfb in Docker, or Edge on Windows as the last fallback of S2. A start that fails
|
||
/// (browser missing, sandbox refused, port taken) is retried with a growing wait; once running, the supervisors of
|
||
/// <see cref="XvfbProcess"/> and <see cref="ChromiumProcessHost"/> restart what crashes.
|
||
/// </summary>
|
||
public sealed class ChromiumBrowser : IFebeBrowser
|
||
{
|
||
private static readonly TimeSpan[] Retry = [TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(30), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(5)];
|
||
|
||
private readonly ChromiumBrowserSettings _settings;
|
||
private readonly IClock _clock;
|
||
private readonly FebeLog _log;
|
||
private readonly TaskCompletionSource _ready = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
private XvfbProcess? _xvfb;
|
||
private volatile bool _started;
|
||
private volatile string? _lastError;
|
||
|
||
public ChromiumBrowser(ChromiumBrowserSettings settings, IClock clock, FebeLog log)
|
||
{
|
||
_settings = settings ?? throw new ArgumentNullException(nameof(settings));
|
||
ArgumentNullException.ThrowIfNull(clock);
|
||
_log = log ?? throw new ArgumentNullException(nameof(log));
|
||
|
||
// Processes start, time out and restart in wall-clock time, whatever clock the engine runs on.
|
||
_clock = new SystemClock(clock.LocalZone);
|
||
ProfileDirectory = Path.GetFullPath(settings.ProfileDirectory);
|
||
HomeDirectory = settings.HomeDirectory is { } home ? Path.GetFullPath(home) : null;
|
||
Host = new ChromiumProcessHost(settings.Launch, _clock, log.ForBrowser());
|
||
BrowserOptions = new BrowserOptions(
|
||
ProfileDirectory,
|
||
settings.WindowWidth,
|
||
settings.WindowHeight,
|
||
settings.DebugPort,
|
||
settings.ExecutablePath,
|
||
settings.Display);
|
||
}
|
||
|
||
/// <summary>The browser: stable for the whole life of the composition (a «Scollega» restarts it in place).</summary>
|
||
public ChromiumProcessHost Host { get; }
|
||
|
||
public BrowserOptions BrowserOptions { get; }
|
||
|
||
public ICdpSession Cdp => Host.Cdp;
|
||
|
||
public UserDrivingGate UserDriving => Host.UserDriving;
|
||
|
||
public string ProfileDirectory { get; }
|
||
|
||
/// <summary>HOME of the browser process (certificate database, font cache); null when not set.</summary>
|
||
public string? HomeDirectory { get; }
|
||
|
||
public int WindowWidth => BrowserOptions.WindowWidth;
|
||
|
||
public int WindowHeight => BrowserOptions.WindowHeight;
|
||
|
||
/// <summary>True when the browser runs on a virtual display (Docker).</summary>
|
||
public bool UsesXvfb => _settings.Display is not null;
|
||
|
||
/// <summary>True when the browser runs and a page connection is attached.</summary>
|
||
public bool IsAvailable => _started && Host.IsAttached;
|
||
|
||
/// <summary>Completes when the browser started the first time.</summary>
|
||
public Task Ready => _ready.Task;
|
||
|
||
public string? LastError => _lastError;
|
||
|
||
public bool UserIsDriving => Host.UserIsDriving;
|
||
|
||
public async Task RunAsync(CancellationToken ct)
|
||
{
|
||
for (var attempt = 0; !ct.IsCancellationRequested; attempt++)
|
||
{
|
||
try
|
||
{
|
||
await StartOnceAsync(ct).ConfigureAwait(false);
|
||
_started = true;
|
||
_lastError = null;
|
||
_ready.TrySetResult();
|
||
_log.Info("browser", $"Browser pronto: finestra {WindowWidth.ToString(CultureInfo.InvariantCulture)}×{WindowHeight.ToString(CultureInfo.InvariantCulture)}, porta di debug {_settings.DebugPort.ToString(CultureInfo.InvariantCulture)} solo su 127.0.0.1{_settings.ReadyRemark}.");
|
||
return;
|
||
}
|
||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||
{
|
||
return;
|
||
}
|
||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||
{
|
||
_lastError = Explain(ex);
|
||
var wait = Retry[Math.Min(attempt, Retry.Length - 1)];
|
||
_log.Error("browser", $"Il browser non parte: {_lastError} Nuovo tentativo fra {wait.TotalSeconds.ToString("0", CultureInfo.InvariantCulture)} s.");
|
||
|
||
// A failed start leaves nothing running in the host (it can be started again); Xvfb, if it started, stays.
|
||
try
|
||
{
|
||
await _clock.Delay(wait, ct).ConfigureAwait(false);
|
||
}
|
||
catch (OperationCanceledException)
|
||
{
|
||
return;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
public Task<NavigationResult> RestAsync(CancellationToken ct) => Host.RestAsync(ct);
|
||
|
||
/// <summary>Nothing: in Docker the remote view shows the browser (on Windows, <c>EdgeBrowser</c> moves the window).</summary>
|
||
public Task ShowToUserAsync(CancellationToken ct) => Task.CompletedTask;
|
||
|
||
/// <summary>Nothing: on Xvfb the window is never in anyone's view.</summary>
|
||
public Task HideFromUserAsync(CancellationToken ct) => Task.CompletedTask;
|
||
|
||
/// <summary>
|
||
/// «Scollega» (spec §4.1): stops the browser (SIGINT on Linux, so it closes cleanly), deletes the profile folder with
|
||
/// the Instagram session, and starts the browser again with an empty profile.
|
||
/// </summary>
|
||
public async Task RestartWithEmptyProfileAsync(CancellationToken ct)
|
||
{
|
||
if (!_started)
|
||
{
|
||
DeleteProfile();
|
||
return;
|
||
}
|
||
|
||
await Host.RestartAsync(DeleteProfile, ct).ConfigureAwait(false);
|
||
_log.Info("browser", "Profilo del browser cancellato; il browser è ripartito vuoto.");
|
||
}
|
||
|
||
public async ValueTask DisposeAsync()
|
||
{
|
||
await StopProcessesAsync().ConfigureAwait(false);
|
||
}
|
||
|
||
private async Task StartOnceAsync(CancellationToken ct)
|
||
{
|
||
if (HomeDirectory is { } home)
|
||
{
|
||
Directory.CreateDirectory(home);
|
||
}
|
||
|
||
if (_settings.Display is { } display && _xvfb is null)
|
||
{
|
||
RemoveStaleDisplayLock(display);
|
||
var xvfb = new XvfbProcess(display, WindowWidth, WindowHeight, clock: _clock, log: _log.ForBrowser());
|
||
await xvfb.StartAsync(ct).ConfigureAwait(false);
|
||
_xvfb = xvfb;
|
||
}
|
||
|
||
RemoveStaleProfileLocks(ProfileDirectory);
|
||
await Host.StartAsync(BrowserOptions, ct).ConfigureAwait(false);
|
||
}
|
||
|
||
private async Task StopProcessesAsync()
|
||
{
|
||
try
|
||
{
|
||
await Host.StopAsync().ConfigureAwait(false);
|
||
}
|
||
catch (Exception ex) when (ex is InvalidOperationException or IOException)
|
||
{
|
||
}
|
||
|
||
if (_xvfb is { } xvfb)
|
||
{
|
||
_xvfb = null;
|
||
await xvfb.DisposeAsync().ConfigureAwait(false);
|
||
}
|
||
}
|
||
|
||
private void DeleteProfile()
|
||
{
|
||
var folder = _settings.ProfileFolderToDelete is { } root ? Path.GetFullPath(root) : ProfileDirectory;
|
||
if (Directory.Exists(folder))
|
||
{
|
||
Directory.Delete(folder, recursive: true);
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// Chromium's «profile in use on another computer» lock: after the container is recreated the host name changes and
|
||
/// Chromium would refuse the profile with a dialog nobody sees. Only Febe starts this browser, and it is not running
|
||
/// now, so the lock files are stale by definition.
|
||
/// </summary>
|
||
internal static void RemoveStaleProfileLocks(string profileDirectory)
|
||
{
|
||
foreach (var name in new[] { "SingletonLock", "SingletonSocket", "SingletonCookie" })
|
||
{
|
||
var path = Path.Combine(profileDirectory, name);
|
||
try
|
||
{
|
||
if (File.Exists(path) || new FileInfo(path).LinkTarget is not null)
|
||
{
|
||
File.Delete(path);
|
||
}
|
||
}
|
||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||
{
|
||
}
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// A display lock left by an Xvfb of an earlier run of the same container (restart after a crash): its process
|
||
/// number may now belong to another process, so a lock whose owner is not an Xvfb is removed.
|
||
/// </summary>
|
||
internal static void RemoveStaleDisplayLock(string display)
|
||
{
|
||
if (!OperatingSystem.IsLinux() || !int.TryParse(display.AsSpan(1), NumberStyles.None, CultureInfo.InvariantCulture, out var number))
|
||
{
|
||
return;
|
||
}
|
||
|
||
var id = number.ToString(CultureInfo.InvariantCulture);
|
||
var lockFile = $"/tmp/.X{id}-lock";
|
||
try
|
||
{
|
||
if (!File.Exists(lockFile))
|
||
{
|
||
return;
|
||
}
|
||
|
||
var owner = int.TryParse(File.ReadAllText(lockFile).Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out var pid) ? pid : 0;
|
||
var comm = owner > 0 && File.Exists($"/proc/{owner.ToString(CultureInfo.InvariantCulture)}/comm")
|
||
? File.ReadAllText($"/proc/{owner.ToString(CultureInfo.InvariantCulture)}/comm").Trim()
|
||
: string.Empty;
|
||
if (comm.Equals("Xvfb", StringComparison.Ordinal))
|
||
{
|
||
return;
|
||
}
|
||
|
||
File.Delete(lockFile);
|
||
var socket = $"/tmp/.X11-unix/X{id}";
|
||
if (File.Exists(socket))
|
||
{
|
||
File.Delete(socket);
|
||
}
|
||
}
|
||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||
{
|
||
}
|
||
}
|
||
|
||
private string Explain(Exception ex) => ex switch
|
||
{
|
||
FileNotFoundException => ex.Message,
|
||
PlatformNotSupportedException => ex.Message,
|
||
TimeoutException => ex.Message,
|
||
InvalidOperationException when ex.Message.Contains("sandbox", StringComparison.OrdinalIgnoreCase) => ex.Message + _settings.SandboxAdvice,
|
||
_ => $"{ex.GetType().Name}: {ex.Message}",
|
||
};
|
||
}
|