Le prove cadevano a ogni carico della CI, ogni volta prove diverse. Dietro alcune c'erano difetti veri: FebeDatabase lasciava i file aperti dopo DisposeAsync (comandi SQLite non chiusi, pool di lettura chiuso dopo lo scrittore), e il WAL spariva durante lo spostamento della cartella Dati; la scheda dell'account senza statistiche leggeva i file di tutta la libreria; l'arresto di FebeApp non aspettava i lavori aggiunti da un avvio in corso. Chromium ha 120 s per avviarsi e aprire la prima scheda, e il ricollegamento smette appena il processo cambia. Nelle prove i limiti di tempo diventano protezioni contro un blocco: attese per condizione con un aiuto comune, limiti per classe nella prova di scala con il tempo migliore, porta 0 e stderr di Chromium nel browser delle prove, e la prova di «Scollega» di WebView2 controlla che il processo esca davvero. Provato su Windows con tutti i core occupati. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
195 lines
8.0 KiB
C#
195 lines
8.0 KiB
C#
using System.Globalization;
|
|
using Febe.Core.Abstractions;
|
|
|
|
namespace Febe.Browser.Hosting;
|
|
|
|
/// <summary>Where the session cookie is looked for (existence only, never the value).</summary>
|
|
/// <param name="CookieName">Cookie name. Instagram's is «sessionid» (public knowledge; hypothesis H10, to confirm in M0).</param>
|
|
/// <param name="SiteUrl">Address whose cookies are listed.</param>
|
|
public sealed record SessionCookieOptions(string CookieName, string SiteUrl)
|
|
{
|
|
public static SessionCookieOptions Instagram { get; } = new("sessionid", "https://www.instagram.com/");
|
|
}
|
|
|
|
/// <summary>Chromium-specific launch settings, on top of <see cref="BrowserOptions"/>.</summary>
|
|
public sealed record ChromiumLaunchOptions
|
|
{
|
|
/// <summary>
|
|
/// Adds <c>--no-sandbox</c>. Only as the documented compromise of S5 (spec §11), never by default:
|
|
/// as root Chromium refuses to start without it; as a normal user with user namespaces it is not needed.
|
|
/// </summary>
|
|
public bool NoSandbox { get; init; }
|
|
|
|
/// <summary>Extra arguments, checked by <see cref="ChromiumCommandLine.EnsureAllowed"/>.</summary>
|
|
public IReadOnlyList<string> ExtraArguments { get; init; } = [];
|
|
|
|
/// <summary>Environment overrides for the browser process (e.g. LANG, TZ in tests). A null value removes the variable.</summary>
|
|
public IReadOnlyDictionary<string, string?> Environment { get; init; } = new Dictionary<string, string?>();
|
|
|
|
/// <summary>Start page: always the rest page.</summary>
|
|
public string StartUrl { get; init; } = "about:blank";
|
|
|
|
/// <summary>
|
|
/// How long a Chromium that is alive may take to open its debugging port and its first tab. A crash fails the start
|
|
/// at once; this only bounds a browser that hangs, so it is generous for a loaded machine (docs/decisioni.md, #46).
|
|
/// </summary>
|
|
public TimeSpan StartupTimeout { get; init; } = TimeSpan.FromSeconds(120);
|
|
|
|
|
|
public RestartPolicy Restart { get; init; } = RestartPolicy.Default;
|
|
|
|
public SessionCookieOptions SessionCookie { get; init; } = SessionCookieOptions.Instagram;
|
|
|
|
/// <summary>
|
|
/// On a new profile, writes preferences that turn off password saving and autofill (spec §6.1, §11).
|
|
/// The Docker image also ships a policy file for the same purpose.
|
|
/// </summary>
|
|
public bool SeedProfilePreferences { get; init; } = true;
|
|
|
|
/// <summary>
|
|
/// Called with every browser process right after it starts (also after a restart), before it is ready. Windows: Edge
|
|
/// is tied to the life of Febe.exe, so that it never outlives a crash of Febe holding the profile and the debugging
|
|
/// port. Null: nothing.
|
|
/// </summary>
|
|
public Action<System.Diagnostics.Process>? ProcessStarted { get; init; }
|
|
}
|
|
|
|
/// <summary>
|
|
/// Builds Chromium's command line (spec §6.1, §11): a normal windowed browser with a fixed debugging port on
|
|
/// 127.0.0.1. Never headless, never automation mode, never user agent, language or proxy overrides:
|
|
/// language comes from LANG and the time zone from TZ.
|
|
/// </summary>
|
|
public static class ChromiumCommandLine
|
|
{
|
|
/// <summary>Arguments refused in <see cref="ChromiumLaunchOptions.ExtraArguments"/>, by prefix.</summary>
|
|
public static IReadOnlyList<string> ForbiddenPrefixes { get; } =
|
|
[
|
|
"--headless",
|
|
"--enable-automation",
|
|
"--remote-debugging-pipe",
|
|
"--remote-debugging-port",
|
|
"--remote-debugging-address",
|
|
"--remote-allow-origins",
|
|
"--user-agent",
|
|
"--lang",
|
|
"--accept-lang",
|
|
"--proxy-server",
|
|
"--proxy-pac-url",
|
|
"--proxy-auto-detect",
|
|
"--proxy-bypass-list",
|
|
"--no-proxy-server",
|
|
"--host-resolver-rules",
|
|
"--disable-blink-features",
|
|
"--enable-blink-features",
|
|
"--blink-settings",
|
|
"--disable-web-security",
|
|
"--load-extension",
|
|
"--disable-extensions-except",
|
|
"--user-data-dir",
|
|
"--window-size",
|
|
"--use-mobile-user-agent",
|
|
"--force-device-scale-factor",
|
|
"--auto-open-devtools-for-tabs",
|
|
"--no-sandbox",
|
|
];
|
|
|
|
public static IReadOnlyList<string> Build(BrowserOptions options, ChromiumLaunchOptions launch)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(options);
|
|
ArgumentNullException.ThrowIfNull(launch);
|
|
if (options.DebugPort is < 1024 or > 65535)
|
|
{
|
|
throw new ArgumentOutOfRangeException(nameof(options), options.DebugPort, "La porta di debug deve essere fissa, fra 1024 e 65535: mai 0 (specifica §6.1).");
|
|
}
|
|
|
|
if (options.WindowWidth < 400 || options.WindowHeight < 300)
|
|
{
|
|
throw new ArgumentOutOfRangeException(nameof(options), "La finestra del browser è troppo piccola.");
|
|
}
|
|
|
|
ArgumentException.ThrowIfNullOrWhiteSpace(options.ProfileDirectory);
|
|
|
|
var inv = CultureInfo.InvariantCulture;
|
|
var args = new List<string>
|
|
{
|
|
$"--remote-debugging-port={options.DebugPort.ToString(inv)}",
|
|
$"--user-data-dir={Path.GetFullPath(options.ProfileDirectory)}",
|
|
"--no-first-run",
|
|
"--no-default-browser-check",
|
|
$"--window-size={options.WindowWidth.ToString(inv)},{options.WindowHeight.ToString(inv)}",
|
|
"--window-position=0,0",
|
|
"--password-store=basic",
|
|
"--disable-dev-shm-usage",
|
|
};
|
|
|
|
if (launch.NoSandbox)
|
|
{
|
|
args.Add("--no-sandbox");
|
|
}
|
|
|
|
foreach (var extra in launch.ExtraArguments)
|
|
{
|
|
EnsureAllowed(extra);
|
|
args.Add(extra);
|
|
}
|
|
|
|
// The start page goes last, as a plain argument.
|
|
args.Add(string.IsNullOrWhiteSpace(launch.StartUrl) ? "about:blank" : launch.StartUrl);
|
|
return args;
|
|
}
|
|
|
|
/// <summary>Refuses arguments that change what the browser declares, put it in automation mode or are set by Febe itself.</summary>
|
|
public static void EnsureAllowed(string argument)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(argument);
|
|
var trimmed = argument.Trim();
|
|
if (!trimmed.StartsWith("--", StringComparison.Ordinal))
|
|
{
|
|
throw new ArgumentException("Gli argomenti aggiuntivi di Chromium devono essere opzioni «--nome».", nameof(argument));
|
|
}
|
|
|
|
foreach (var prefix in ForbiddenPrefixes)
|
|
{
|
|
if (trimmed.Equals(prefix, StringComparison.OrdinalIgnoreCase)
|
|
|| trimmed.StartsWith(prefix + "=", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
throw new ArgumentException($"L'opzione «{prefix}» di Chromium è vietata o la imposta già Febe (specifica §2, regola 2; §6.1; §11).", nameof(argument));
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Finds Chromium: explicit path, then the FEBE_CHROMIUM variable, then PATH and the usual places
|
|
/// (Debian's «chromium» first; Edge on Windows as the S2 fallback).
|
|
/// </summary>
|
|
public static string? FindExecutable(string? explicitPath = null)
|
|
{
|
|
if (!string.IsNullOrWhiteSpace(explicitPath))
|
|
{
|
|
return File.Exists(explicitPath) ? explicitPath : null;
|
|
}
|
|
|
|
var fromEnv = System.Environment.GetEnvironmentVariable("FEBE_CHROMIUM");
|
|
if (!string.IsNullOrWhiteSpace(fromEnv) && File.Exists(fromEnv))
|
|
{
|
|
return fromEnv;
|
|
}
|
|
|
|
if (OperatingSystem.IsWindows())
|
|
{
|
|
var programFilesX86 = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFilesX86);
|
|
var programFiles = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFiles);
|
|
return ExecutableSearch.Find(
|
|
["msedge", "chrome"],
|
|
[
|
|
Path.Combine(programFilesX86, "Microsoft", "Edge", "Application", "msedge.exe"),
|
|
Path.Combine(programFiles, "Microsoft", "Edge", "Application", "msedge.exe"),
|
|
]);
|
|
}
|
|
|
|
return ExecutableSearch.Find(
|
|
["chromium", "chromium-browser", "google-chrome-stable", "google-chrome"],
|
|
["/usr/bin/chromium", "/usr/lib/chromium/chromium"]);
|
|
}
|
|
}
|