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:
Claude committed 2026-10-13 15:51:02 +00:00
1 parent c803bd98b5
commit 925141bb37
44 files changed
+8396

No files matched your search

+204
View File
@@ -0,0 +1,204 @@
using System.Diagnostics;
using System.Globalization;
using Febe.Browser.Diagnostics;
using Febe.Core.Abstractions;
namespace Febe.Browser.Hosting;
/// <summary>
/// The virtual display of the Docker version (spec §6.1, §11): Chromium runs as a normal windowed browser on it.
/// Supervised: restarted with backoff if it exits; Chromium, which loses its display, is restarted by its own host.
/// </summary>
public sealed class XvfbProcess : IAsyncDisposable
{
private readonly SupervisedProcess _supervisor;
private readonly int _displayNumber;
/// <param name="display">Display name, e.g. «:99».</param>
/// <param name="width">Screen width: at least the browser window width.</param>
/// <param name="height">Screen height: at least the browser window height.</param>
/// <param name="executable">Xvfb executable; null searches PATH.</param>
public XvfbProcess(
string display = ":99",
int width = 1280,
int height = 900,
string? executable = null,
IClock? clock = null,
IBrowserLog? log = null,
RestartPolicy? restart = null)
{
_displayNumber = ParseDisplay(display);
Display = display;
Width = width;
Height = height;
var exe = executable ?? FindExecutable() ?? throw new FileNotFoundException("Xvfb non è installato.");
var effectiveClock = clock ?? new SystemClock();
_supervisor = new SupervisedProcess(
"Xvfb",
() => BuildStartInfo(exe),
(process, ct) => WaitForSocketAsync(process, effectiveClock, ct),
effectiveClock,
log,
restart);
}
public string Display { get; }
public int Width { get; }
public int Height { get; }
public SupervisedState State => _supervisor.State;
public int? ProcessId => _supervisor.ProcessId;
/// <summary>Path of the X socket that appears when the display is ready.</summary>
public string SocketPath => $"/tmp/.X11-unix/X{_displayNumber.ToString(CultureInfo.InvariantCulture)}";
public event EventHandler? Restarted
{
add => _supervisor.Restarted += value;
remove => _supervisor.Restarted -= value;
}
public Task StartAsync(CancellationToken ct)
{
if (!OperatingSystem.IsLinux())
{
throw new PlatformNotSupportedException("Xvfb serve solo su Linux (Docker).");
}
if (IsLockHeldByLiveProcess())
{
throw new InvalidOperationException($"Il display {Display} è già in uso da un altro processo.");
}
return _supervisor.StartAsync(ct);
}
public Task StopAsync() => _supervisor.StopAsync(TimeSpan.FromSeconds(3));
public ValueTask DisposeAsync() => _supervisor.DisposeAsync();
/// <summary>Finds Xvfb in PATH or in the usual places.</summary>
public static string? FindExecutable() => ExecutableSearch.Find(["Xvfb"], ["/usr/bin/Xvfb", "/usr/local/bin/Xvfb"]);
/// <summary>First display number in [<paramref name="from"/>, <paramref name="to"/>] with neither socket nor lock file.</summary>
public static string? FindFreeDisplay(int from = 90, int to = 199)
{
for (var n = from; n <= to; n++)
{
var id = n.ToString(CultureInfo.InvariantCulture);
if (!File.Exists($"/tmp/.X11-unix/X{id}") && !File.Exists($"/tmp/.X{id}-lock"))
{
return $":{id}";
}
}
return null;
}
private ProcessStartInfo BuildStartInfo(string exe)
{
var info = new ProcessStartInfo(exe);
info.ArgumentList.Add(Display);
info.ArgumentList.Add("-screen");
info.ArgumentList.Add("0");
info.ArgumentList.Add(string.Create(CultureInfo.InvariantCulture, $"{Width}x{Height}x24"));
info.ArgumentList.Add("-nolisten");
info.ArgumentList.Add("tcp");
info.ArgumentList.Add("-noreset");
return info;
}
private async Task WaitForSocketAsync(Process process, IClock clock, CancellationToken ct)
{
var deadline = clock.Now + TimeSpan.FromSeconds(10);
while (!File.Exists(SocketPath) || LockOwner() != process.Id)
{
if (process.HasExited)
{
throw new InvalidOperationException($"Xvfb si è chiuso all'avvio (codice {process.ExitCode}). {_supervisor.StderrTail()}");
}
if (clock.Now >= deadline)
{
throw new TimeoutException($"Il display {Display} non è pronto dopo 10 secondi.");
}
await clock.Delay(TimeSpan.FromMilliseconds(50), ct).ConfigureAwait(false);
}
}
/// <summary>Process id written in the X lock file, or null.</summary>
private int? LockOwner()
{
var lockFile = $"/tmp/.X{_displayNumber.ToString(CultureInfo.InvariantCulture)}-lock";
try
{
return File.Exists(lockFile) && int.TryParse(File.ReadAllText(lockFile).Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out var pid)
? pid
: null;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
return null;
}
}
private bool IsLockHeldByLiveProcess()
{
if (LockOwner() is not { } pid)
{
return false;
}
try
{
using var holder = Process.GetProcessById(pid);
return !holder.HasExited;
}
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException)
{
return false;
}
}
private static int ParseDisplay(string display)
{
if (string.IsNullOrEmpty(display) || display[0] != ':'
|| !int.TryParse(display.AsSpan(1).ToString().Split('.')[0], NumberStyles.None, CultureInfo.InvariantCulture, out var number))
{
throw new ArgumentException($"Display «{display}» non valido: si scrive come «:99».", nameof(display));
}
return number;
}
}
/// <summary>Looks for executables in PATH and in a few known places.</summary>
internal static class ExecutableSearch
{
public static string? Find(IEnumerable<string> names, IEnumerable<string> knownPaths)
{
var path = Environment.GetEnvironmentVariable("PATH") ?? string.Empty;
foreach (var name in names)
{
foreach (var dir in path.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries))
{
var candidate = Path.Combine(dir, name);
if (File.Exists(candidate))
{
return candidate;
}
if (OperatingSystem.IsWindows() && File.Exists(candidate + ".exe"))
{
return candidate + ".exe";
}
}
}
return knownPaths.FirstOrDefault(File.Exists);
}
}